Esempio n. 1
0
    def show(self, id1, pos1, id2, pos2, time_gap):
        ac.setBackgroundTexture(self.positionLabel1,
                                FC.LEADERBOARD_POSITION_LABEL[pos1 + 1])
        ac.setBackgroundTexture(self.positionLabel2,
                                FC.LEADERBOARD_POSITION_LABEL[pos2 + 1])
        ac.setText(self.gapLabel, time_to_string(time_gap))

        ac.setVisible(self.rolexLabel, 1)
        ac.setVisible(self.speedometerIconLabel, 1)
        ac.setVisible(self.backgroundTexture, 1)
        ac.setVisible(self.extendedBackgroundTexture, 1)
        ac.setVisible(self.positionLabel1, 1)
        ac.setVisible(self.positionLabel2, 1)
        ac.setVisible(self.nameLabel1, 1)
        ac.setVisible(self.nameLabel2, 1)
        ac.setVisible(self.carLabel1, 1)
        ac.setVisible(self.carLabel2, 1)
        ac.setVisible(self.gapsIconLabelL, 1)
        ac.setVisible(self.gapsIconLabelR, 1)
        ac.setVisible(self.gapLabel, 1)
        ac.setVisible(self.secondsLabel, 1)

        if self.id1 != id1 and self.id2 != id2:
            name1 = ac.getDriverName(id1)
            ac.setText(self.nameLabel1, name1.split()[-1].upper())
            if FC.TEAM_COLORS:
                try:
                    ac.setBackgroundTexture(self.teamLabel1,
                                            FC.TEAM_COLORS[name1])
                    ac.setBackgroundTexture(self.carLabel1, FC.CARS[name1])
                    ac.setVisible(self.teamLabel1, 1)
                    ac.setVisible(self.carLabel1, 1)
                except KeyError:
                    ac.log("%s:Name Missing in teams.txt" % (FC.APP_NAME))

        if self.id2 != id2:
            name2 = ac.getDriverName(id2)
            ac.setText(self.nameLabel2, name2.split()[-1].upper())
            if FC.TEAM_COLORS:
                try:
                    ac.setBackgroundTexture(self.teamLabel2,
                                            FC.TEAM_COLORS[name2])
                    ac.setBackgroundTexture(self.carLabel2, FC.CARS[name2])
                    ac.setVisible(self.teamLabel2, 1)
                    ac.setVisible(self.carLabel2, 1)
                except KeyError:
                    ac.log("%s:Name Missing in teams.txt" % (FC.APP_NAME))

        self.id1 = id1
        self.id2 = id2
        self.visible = True
Esempio n. 2
0
def getDriverInformation(detectionArea):
    global labelStorage, appPosX, appPosY, spinner_y_offset, fov_setting
    triangle = Triangle(detectionArea[0], detectionArea[1], detectionArea[2])
    setLabel = 0
    for x in range(ac.getCarsCount()):
        posX, posZ, posY = ac.getCarState(x, acsys.CS.WorldPosition)
        if triangle.isInside((posX, posY)) and x != 0:
            vect_x = posX - detectionArea[0][0]
            vect_y = posY - detectionArea[0][1]
            distance = math.sqrt(math.pow(vect_x, 2) + math.pow(vect_y, 2))
            newPosition = getRenderPosition(x, detectionArea, (posX, posY))
            ac.setText(labelStorage[setLabel], ac.getDriverName(x))
            fov_angle = ac.getValue(fov_setting)
            xPos = (((newPosition * windowSizeX) / fov_angle) - appPosX)
            yOffset = ac.getValue(spinner_y_offset)
            yPos = (((windowSizeY / 2) - 20) - appPosY) + int(yOffset)
            fontSize = (10 *
                        (1 /
                         (distance / 100))) * (ac.getValue(scale_factor) / 10)
            ac.setPosition(labelStorage[setLabel], xPos, yPos)
            ac.setFontSize(labelStorage[setLabel], fontSize)
            setLabel += 1

    for z in range(ac.getCarsCount() - setLabel):
        ac.setText(labelStorage[setLabel + z], "")
Esempio n. 3
0
def updateSharedMemory():
    global sharedMem
    sharedmem = sharedMem.getsharedmem()
    sharedmem.numVehicles = ac.getCarsCount()
    sharedmem.focusVehicle = ac.getFocusedCar()

    #now we'll build the slots, so we later know every single (possible) car
    carIds = range(0, ac.getCarsCount(), 1)
    for carId in carIds:
        #first we'll check wether there is a car for this id; as soon it returns -1
        #it's over
        if str(ac.getCarName(carId)) == '-1':
            break
        else:
            sharedmem.vehicleInfo[carId].carId = carId
            sharedmem.vehicleInfo[carId].driverName = ac.getDriverName(carId).encode('utf-8')
            sharedmem.vehicleInfo[carId].carModel = ac.getCarName(carId).encode('utf-8')
            sharedmem.vehicleInfo[carId].speedMS = ac.getCarState(carId, acsys.CS.SpeedMS)
            sharedmem.vehicleInfo[carId].bestLapMS = ac.getCarState(carId, acsys.CS.BestLap)
            sharedmem.vehicleInfo[carId].lapCount = ac.getCarState(carId, acsys.CS.LapCount)
            sharedmem.vehicleInfo[carId].currentLapInvalid = ac.getCarState(carId, acsys.CS.LapInvalidated)
            sharedmem.vehicleInfo[carId].currentLapTimeMS = ac.getCarState(carId, acsys.CS.LapTime)
            sharedmem.vehicleInfo[carId].lastLapTimeMS = ac.getCarState(carId, acsys.CS.LastLap)
            sharedmem.vehicleInfo[carId].worldPosition = ac.getCarState(carId, acsys.CS.WorldPosition)
            sharedmem.vehicleInfo[carId].isCarInPitline = ac.isCarInPitline(carId)
            sharedmem.vehicleInfo[carId].isCarInPit = ac.isCarInPit(carId)
            sharedmem.vehicleInfo[carId].carLeaderboardPosition = ac.getCarLeaderboardPosition(carId)
            sharedmem.vehicleInfo[carId].carRealTimeLeaderboardPosition = ac.getCarRealTimeLeaderboardPosition(carId)
            sharedmem.vehicleInfo[carId].spLineLength=  ac.getCarState(carId, acsys.CS.NormalizedSplinePosition) 
            sharedmem.vehicleInfo[carId].isConnected = ac.isConnected(carId)
Esempio n. 4
0
    def checkForNewDriver(self):
        acname = ac.getDriverName(self.id)
        if acname == self.name:
            return False

        self.name = acname
        return True
Esempio n. 5
0
def acMain(ac_version):
    global DRIVER, TRACK, CAR, WINDOW, LAP_LABELS, LAP_VALID_INDICATOR

    DRIVER = ac.getDriverName(DRIVER_ID_SELF)
    TRACK = '%s-%s' % (ac.getTrackName(DRIVER_ID_SELF),
                       ac.getTrackConfiguration(DRIVER_ID_SELF))
    CAR = ac.getCarName(DRIVER_ID_SELF)

    ac.console('Initialize %s: driver %s on %s in %s' %
               (NAME, DRIVER, TRACK, CAR))

    WINDOW = ac.newApp(NAME)
    ac.setSize(WINDOW, *SIZE)
    ac.setTitle(NAME)

    if ac.addOnAppActivatedListener(WINDOW, onActivate) == -1:
        ac.console('Failed to add listener activate')
    if ac.addOnAppDismissedListener(WINDOW, onDeactivate) == -1:
        ac.console('Failed to add listener deactivate')

    i = 0
    while i < LAP_COUNT:
        label = ac.addLabel(WINDOW, 'Waiting for lap time...')
        LAP_LABELS.append(label)
        i += 1
    LAP_VALID_INDICATOR = ac.addLabel(WINDOW, 'Clean')
    refreshLapDisplay()

    return NAME
Esempio n. 6
0
def announceStart():
    if SERVERS and any(ac.getServerName().startswith(x) for x in SERVERS):
        driver_name = ac.getDriverName(0)
        digest = hashlib.md5(
            open("apps/python/%s/%s.py" % (APP_NAME, APP_NAME),
                 'rb').read()).hexdigest()
        ac.sendChatMessage(APP_NAME + " %s : %s --> %s" %
                           (VERSION, driver_name, digest))
Esempio n. 7
0
    def update_data(self, deltaT):
        '''
        Called by acUpdate, updates internal data
        '''
        self.best_lap = ac.getCarState(0, acsys.CS.BestLap)

        # Update cars
        for i in range(30):
            try:
                car = self.cars[i]
            except IndexError:
                name = ac.getDriverName(i)
                if name == -1:
                    # No such car
                    break
                car = Car(name)
                self.cars.append(car)

            # The name can change if in no-booking mode
            car.name = ac.getDriverName(i)

            car.spline_pos = ac.getCarState(i,
                                            acsys.CS.NormalizedSplinePosition)
            car.lap = ac.getCarState(i, acsys.CS.LapCount)
            # There is currently no way to know if another car is in the pit using the API
            # so we consider cars going slower than 20kph and close to start/finish line to
            # be in the pits
            car.in_pits = ac.getCarState(i, acsys.CS.SpeedKMH) < 20 and \
                (car.spline_pos < 0.1 or car.spline_pos > 0.9)

            if i == 0:
                self.player = car
            else:
                car.relative_position = car.spline_pos - self.player.spline_pos
                if car.relative_position > 0.5:
                    car.relative_position -= 1
                if car.relative_position < -0.5:
                    car.relative_position += 1
                car.delta = car.relative_position * self.best_lap

        # Update the cars' race position:
        for i, car in enumerate(
                sorted(self.cars, key=lambda car:
                       (-car.lap, -car.spline_pos))):
            car.position = i + 1
Esempio n. 8
0
 def onStartup(self, ac_version):
     self.steam_id = steamID()
     self.ac_version = ac_version
     driver = ac.getDriverName(0)
     car = ac.getCarName(0)
     track = ac.getTrackName(0)
     track_config = ac.getTrackConfiguration(0)
     self.session = Session(ac_version, driver, car, track, track_config)
     self.latestPos = getCoords()
     self.latestUpdate = datetime.datetime.now()
Esempio n. 9
0
    def update_data(self, deltaT):
        '''
        Called by acUpdate, updates internal data
        '''
        self.best_lap = ac.getCarState(0, acsys.CS.BestLap)

        # Update cars
        for i in range(30):
            try:
                car = self.cars[i]
            except IndexError:
                name = ac.getDriverName(i)
                if name == -1:
                    # No such car
                    break
                car = Car(name)
                self.cars.append(car)

            # The name can change if in no-booking mode
            car.name = ac.getDriverName(i)

            car.spline_pos = ac.getCarState(i, acsys.CS.NormalizedSplinePosition)
            car.lap = ac.getCarState(i, acsys.CS.LapCount)
            # There is currently no way to know if another car is in the pit using the API
            # so we consider cars going slower than 20kph and close to start/finish line to
            # be in the pits
            car.in_pits = ac.getCarState(i, acsys.CS.SpeedKMH) < 20 and \
                (car.spline_pos < 0.1 or car.spline_pos > 0.9)

            if i == 0:
                self.player = car
            else:
                car.relative_position = car.spline_pos - self.player.spline_pos
                if car.relative_position > 0.5:
                    car.relative_position -= 1
                if car.relative_position < -0.5:
                    car.relative_position += 1
                car.delta = car.relative_position * self.best_lap

        # Update the cars' race position:
        for i, car in enumerate(sorted(self.cars, key=lambda car: (-car.lap, -car.spline_pos))):
            car.position = i + 1
 def updateCarList(self):
     # Обновляет список машин/пилотов (прежде всего всё-таки пилотов).
     # Игроки могут меняться в ходе сессии. Если игрок вышел, его "забываем"
     # Нового игрока добавляем в список, обнулив пройденную дистанцию
     # postLogMessage('slot count: ' + str(self.slotCount))
     for carId in range(0, self.MAX_CARS):
         # postLogMessage('updateCarList: slot ' + str(carId))
         if self.carList[carId] is None:  # если машины не было
             # проверяем её существование в игре, если есть - добавляем
             driverName = str(
                 ac.getDriverName(carId)
             )  # эта странная штука возвращает либо строку, либо число -1
             # TODO возможное изменение в API: -1 невозможен для индексов, меньших кол-ва слотов на сервере
             if driverName != "-1" and len(driverName) > 0:
                 self.carList[carId] = CarInfo(carId)
         else:  # машина (была) занята, проверим, занята ли она сейчас и кем
             driverName = str(ac.getDriverName(carId))
             if str(driverName) == "-1":  # ушёл
                 self.carList[carId] = None
             elif driverName != self.carList[carId].driverName:  # сменился
                 self.carList[carId] = CarInfo(carId)
Esempio n. 11
0
    def prepare(self):
        self.track = ac.getTrackName(0)

        #now we'll build the slots, so we later know every single (possible) car
        carIds = range(0, ac.getCarsCount(), 1)
        for carId in carIds:
            #first we'll check wether there is a car for this id; as soon it returns -1
            #it's over
            carModel = str(ac.getCarName(carId))
            if carModel == '-1':
                break
            else:
                maxSlotId = carId
                driverName = ac.getDriverName(carId)
                self.cars.append(helipicapewcar.HeliPicaPewCar(carId, driverName, carModel))
Esempio n. 12
0
 def update_name(self, id):
     if id == ac.getFocusedCar():
         ac.setVisible(self.highlightLabel, 1)
     else:
         ac.setVisible(self.highlightLabel, 0)
     if self.driverId == id: return  # no need to update
     self.driverId = id
     self.driverName = ac.getDriverName(id)
     displayName = self.driverName.split()[-1][:3].upper()
     ac.setText(self.nameLabel, displayName)
     try:
         ac.setBackgroundTexture(self.teamLabel,
                                 FC.TEAM_COLORS[self.driverName])
     except KeyError:
         ac.log("%s:Name Missing in teams.txt %s" %
                (FC.APP_NAME, self.driverName))
Esempio n. 13
0
def updateSharedMemory():
    global sharedMem
    sharedmem = sharedMem.getsharedmem()
    sharedmem.numVehicles = ac.getCarsCount()
    sharedmem.focusVehicle = ac.getFocusedCar()
    #now we'll build the slots, so we later know every single (possible) car
    carIds = range(0, ac.getCarsCount(), 1)
    for carId in carIds:
        #first we'll check wether there is a car for this id; as soon it returns -1
        #it's over
        if str(ac.getCarName(carId)) == '-1':
            break
        else:
            sharedmem.vehicleInfo[carId].carId = carId
            sharedmem.vehicleInfo[carId].driverName = ac.getDriverName(
                carId).encode('utf-8')
            sharedmem.vehicleInfo[carId].carModel = ac.getCarName(
                carId).encode('utf-8')
            sharedmem.vehicleInfo[carId].speedMS = ac.getCarState(
                carId, acsys.CS.SpeedMS)
            sharedmem.vehicleInfo[carId].bestLapMS = ac.getCarState(
                carId, acsys.CS.BestLap)
            sharedmem.vehicleInfo[carId].lapCount = ac.getCarState(
                carId, acsys.CS.LapCount)
            sharedmem.vehicleInfo[carId].currentLapInvalid = ac.getCarState(
                carId, acsys.CS.LapInvalidated)
            sharedmem.vehicleInfo[carId].currentLapTimeMS = ac.getCarState(
                carId, acsys.CS.LapTime)
            sharedmem.vehicleInfo[carId].lastLapTimeMS = ac.getCarState(
                carId, acsys.CS.LastLap)
            sharedmem.vehicleInfo[carId].worldPosition = ac.getCarState(
                carId, acsys.CS.WorldPosition)
            sharedmem.vehicleInfo[carId].isCarInPitline = ac.isCarInPitline(
                carId)
            sharedmem.vehicleInfo[carId].isCarInPit = ac.isCarInPit(carId)
            sharedmem.vehicleInfo[
                carId].carLeaderboardPosition = ac.getCarLeaderboardPosition(
                    carId)
            sharedmem.vehicleInfo[
                carId].carRealTimeLeaderboardPosition = ac.getCarRealTimeLeaderboardPosition(
                    carId)
            sharedmem.vehicleInfo[carId].spLineLength = ac.getCarState(
                carId, acsys.CS.NormalizedSplinePosition)
            sharedmem.vehicleInfo[carId].isConnected = ac.isConnected(carId)
            sharedmem.vehicleInfo[carId].finishStatus = ac.getCarState(
                carId, acsys.CS.RaceFinished)
Esempio n. 14
0
def SendCurrentScore():
    global highscore, storeDriftScore
    if highscore < storeDriftScore:
        highscore = storeDriftScore
    data = {
        "name": ac.getDriverName(0),
        "track": ac.getTrackName(0) + "-" + ac.getTrackConfiguration(0),
        "mode": "drift",
        "score": str(storeDriftScore),
        "car": ac.getCarName(0)
    }
    t = threading.Thread(target=SendScore, args=(data, ))
    #t.daemon = True
    t.start()
    resetDriftScoring()
    #ac.console("current score sent: "+str(storeDriftScore))
    return
Esempio n. 15
0
 def startLogging(self):
     if self.outputFile != None:
         return
     
     ac.console('Start')
     tmpFile = open('D:\logger_' + datetime.now().strftime('%Y%m%d_%H%M') + '.log', mode = 'w')
     tmpFile.write('Course : {}\n'.format(ac.getTrackName(self.carId)))
     tmpFile.write('Layout : {}\n'.format(ac.getTrackConfiguration(self.carId)))
     tmpFile.write('Car Id : {}\n'.format(self.carId))
     tmpFile.write('Driver : {}\n'.format(ac.getDriverName(self.carId)))
     tmpFile.write('Driver : {}\n'.format(ac.getCarName(self.carId)))
     tmpFile.write('\n')
     
     tmpFile.write('\t'.join(['lapCount', 'lapTime', 'distance', 'speed', 'throttle', \
                              'brake', 'gear', 'RPM', 'steer', 'x', 'y', 'z\n']))
     
     self.outputFile = tmpFile
Esempio n. 16
0
def SendLapScore():
    global lastLapCumulativeScore, cumulativescore, driftScoreAtStartLine
    currentDrift = round(ac.getCarState(0, acsys.CS.InstantDrift))
    lapscore = cumulativescore - lastLapCumulativeScore + currentDrift - driftScoreAtStartLine
    # + currentDrift - driftScoreAtStartLine
    driftScoreAtStartLine = currentDrift
    lastLapCumulativeScore = cumulativescore
    data = {
        "name": ac.getDriverName(0),
        "track": ac.getTrackName(0) + "-" + ac.getTrackConfiguration(0),
        "mode": "OneLapDrifting",
        "car": ac.getCarName(0),
        "score": str(lapscore),
        "laptime": str(ac.getCarState(0, acsys.CS.LastLap))
    }
    t = threading.Thread(target=SendScore, args=(data, ))
    t.start()
    #SendScore(data);
    return
Esempio n. 17
0
def SendSessionData():
    #send cumulatice score
    global cumulativescore, server_connection_ok, sessionDataSent
    if sessionDataSent > 0:
        return
    sessionDataSent = sessionDataSent + 1
    if server_connection_ok == 0:
        return

    session = info.graphics.session
    session_string = "other"
    laps = ac.getCarState(0, acsys.CS.LapCount)
    if laps < 1:
        laps = 1
    if session == 0:
        session_string = "practise"
    if session == 1:
        session_string = "qualify"
    if session == 2:
        session_string = "race"
    data = {
        "name":
        ac.getDriverName(0),
        "track":
        ac.getTrackName(0) + "-" + ac.getTrackConfiguration(0),
        "mode":
        session_string,
        "car":
        ac.getCarName(0),
        "score":
        str(cumulativescore),
        "laps":
        str(laps),
        "bestlap":
        str(info.graphics.iBestTime),
        "average_score_per_lap":
        str(cumulativescore / laps),
        "score_per_km":
        str(cumulativescore / (info.graphics.distanceTraveled / 1000))
    }
    SendScore(data)
    return
Esempio n. 18
0
def build_driver_list():
    """Builds list of cars that drove through joker"""
    global driver_list, polygon

    # Get number of cars
    car_amount = ac.getCarsCount()

    # Iterate through cars
    for i in range(0, car_amount):
        driver_name = ac.getDriverName(i)
        if driver_name not in driver_list:
            inpitbox = ac.isCarInPit(i)
            isconnected = ac.isConnected(i)
            if not inpitbox and isconnected:
                crds = ac.getCarState(i, acsys.CS.WorldPosition)
                inside_joker = inside_polygon(crds[0], crds[2], polygon)
                if inside_joker:
                    driver_list.append(driver_name)
                    lap = ac.getCarState(i, acsys.CS.LapCount)
                    send_chat_message(driver_name, lap)
Esempio n. 19
0
File: acdelta.py Progetto: Nrde/ACTV
 def save_delta(self):
     reference_lap = list(self.referenceLap)
     reference_lap_time = self.referenceLapTime.value
     if len(reference_lap) > 0:
         try:
             times = []
             for l in reference_lap:
                 times.append((l.sector, l.time))
             data_file = {
                 'lap': reference_lap_time,
                 'times': times,
                 'track': ac.getTrackName(0),
                 'config': ac.getTrackConfiguration(0),
                 'car': ac.getCarName(0),
                 'user': ac.getDriverName(0)
             }
             file = self.get_delta_file_path()
             with gzip.open(file, 'wt') as outfile:
                 json.dump(data_file, outfile)
         except:
             Log.w("Error tower")
Esempio n. 20
0
def updateCyclists(data: OtherCyclistData):
    otherCyclists[data.Name] = data
    otherCyclistsList = sorted(otherCyclists.values(), key=lambda c : c.Distance)

    # center the list around self
    targetSelfIndex = int(otherCyclistsMaxCount/2)
    currentSelfIndex = 0
    for i in range(len(otherCyclistsList)):
        if otherCyclistsList[i].Name == ac.getDriverName(0):
            currentSelfIndex = i
            break
    
    renderList = otherCyclistsList
    if targetSelfIndex - currentSelfIndex > 0: # need to move data to the right (pad with None)
        renderList = [None] * (targetSelfIndex - currentSelfIndex) + otherCyclistsList
    elif targetSelfIndex - currentSelfIndex < 0: # need to move data to the left (=truncate)
        renderList = otherCyclistsList[currentSelfIndex-targetSelfIndex:]

    if len(renderList) < otherCyclistsMaxCount+1:
        renderList = renderList + [None] * (otherCyclistsMaxCount+1 - len(renderList))

    otherCyclistsUI.update(renderList)
 def __init__(self, carId):
     self.carId = carId  # ID - номер машины в списке
     self.driverName = ac.getDriverName(carId)  # имя игрока
     self.carName = getCarName(ac.getCarName(carId))  # машина
     # TODO: брать название машины из конфигов: например, вместо ks_bmw_m235i_racing будет BMW M235i Racing
     self.lapsCompleted = 0  # завершено кругов
     self.lastLap = ac.getCarState(
         self.carId,
         acsys.CS.LastLap)  # время последнего пройденного круга в мс
     self.bestLap = ac.getCarState(
         self.carId, acsys.CS.BestLap)  # время лучшего круга сессии в мс
     self.qualifiedTime = 0  # время, поставленное в квалификации (сохраняется для сортировки пилотов на старте)
     self.totalTime = 0  # суммарное время кругов (время гонки, в остальных сессиях не имеет смысла)
     self.totalDistance = 0  # суммарная дистанция (для сортировки в гонке)
     self.isInPitlane = ac.isCarInPitlane(carId)  # машина на пит-лейне
     self.isInPit = ac.isCarInPit(carId)  # машина в боксах
     self.lapPostTime = 0  # момент времени (по session_time), когда было поставлено время в практике/квалификации
     self.connected = False
     self.leaderboardPosition = 0
     self.realTimeLeaderboardPosition = 0
     self.isTimedRace = 0  # гонка ограничена временем, а не кругами
     self.hasExtraLap = 0  # дополнительный круг в гонке по времени
     self.isFinished = 0  # гонщик завершил сессию
Esempio n. 22
0
 def saveDelta(self):
     # ac.log(str(time.time())+" saveDelta start:")
     referenceLap = list(self.referenceLap)
     # referenceLap=self.referenceLap
     referenceLapTime = self.referenceLapTime.value
     if len(referenceLap) > 0:
         try:
             times = []
             for l in referenceLap:
                 times.append((l.sector, l.time))
             data_file = {
                 "lap": referenceLapTime,
                 "times": times,
                 "track": ac.getTrackName(0),
                 "config": ac.getTrackConfiguration(0),
                 "car": ac.getCarName(0),
                 "user": ac.getDriverName(0),
             }
             file = self.getDeltaFilePath()
             with gzip.open(file, "wt") as outfile:
                 json.dump(data_file, outfile)
         except:
             Log.w("Error tower")
Esempio n. 23
0
def acUpdate(deltaT):
    global timer0, timer1
    global tyreLabels, tyrePressureLabels
    global drsLabel, ersLabel, ersModeLabel, ersRecoveryLabel, fuelLabel, drsPenaltyLabel, drsPenaltyBackgroundLabel
    global carValue, trackConfigValue, trackValue

    global currentLapValue, lapValue, previousLapValue, carWasInPit

    global totalDrivers, trackLength, driversList, totalPenalty, soundPlaying, drsAvailableZones, currentDrsZone, drsPenaltyAwardedInZone, lastTime

    global tyreCompoundShort, tyreCompoundCleaned, previousTyreCompoundValue, minimumOptimalTemperature, maximumOptimalTemperature, idealPressureFront, idealPressureRear
    global tyreTemperatureValue, tyreTemperatureValueI, tyreTemperatureValueM, tyreTemperatureValueO, tyrePressureValue, tyreCompoundValue
    global temperatureTransitionRange, tyrePracticalTemperatureValue
    global fuelAmountValue, fuelStartValue, relevantLapsNumber, fuelSpentValue, fuelPerLapValue

    global compounds, modCompounds

    timer0 += deltaT
    timer1 += deltaT

    # Once per second
    if timer0 > 1:
        timer0 = 0

        # =================================================================================================================
        #                                    GET A BUNCH OF INFO
        # =================================================================================================================
        tyreCompoundValue = info.graphics.tyreCompound
        tyreTemperatureValue = info.physics.tyreCoreTemperature
        tyreTemperatureValueI = info.physics.tyreTempI
        tyreTemperatureValueM = info.physics.tyreTempM
        tyreTemperatureValueO = info.physics.tyreTempO
        tyrePressureValue = info.physics.wheelsPressure

        fuelAmountValue = info.physics.fuel

        if ac.isCarInPitline(0):
            carWasInPit = 1

        # =================================================================================================================
        #                                   SET IDEAL TYRE PRESSURES AND TEMPERATURES
        # =================================================================================================================
        if previousTyreCompoundValue != tyreCompoundValue:
            previousTyreCompoundValue = tyreCompoundValue
            tyreCompoundShort = tyreCompoundValue[tyreCompoundValue.find("(") +
                                                  1:tyreCompoundValue.find(")"
                                                                           )]
            tyreCompoundCleaned = re.sub(
                '\_+$', '', re.sub(r'[^\w]+', '_', tyreCompoundValue)).lower()

            if compounds.has_section(carValue + "_" + tyreCompoundCleaned):
                try:
                    idealPressureFront = int(
                        compounds.get(carValue + "_" + tyreCompoundCleaned,
                                      "IDEAL_PRESSURE_F"))
                    idealPressureRear = int(
                        compounds.get(carValue + "_" + tyreCompoundCleaned,
                                      "IDEAL_PRESSURE_R"))
                    minimumOptimalTemperature = int(
                        compounds.get(carValue + "_" + tyreCompoundCleaned,
                                      "MIN_OPTIMAL_TEMP"))
                    maximumOptimalTemperature = int(
                        compounds.get(carValue + "_" + tyreCompoundCleaned,
                                      "MAX_OPTIMAL_TEMP"))
                except:
                    ac.console("Error loading tyre data.")
            elif modCompounds.has_section(carValue + "_" +
                                          tyreCompoundCleaned):
                try:
                    idealPressureFront = int(
                        modCompounds.get(carValue + "_" + tyreCompoundCleaned,
                                         "IDEAL_PRESSURE_F"))
                    idealPressureRear = int(
                        modCompounds.get(carValue + "_" + tyreCompoundCleaned,
                                         "IDEAL_PRESSURE_R"))
                    minimumOptimalTemperature = int(
                        float(
                            modCompounds.get(
                                carValue + "_" + tyreCompoundCleaned,
                                "MIN_OPTIMAL_TEMP")))
                    maximumOptimalTemperature = int(
                        float(
                            modCompounds.get(
                                carValue + "_" + tyreCompoundCleaned,
                                "MAX_OPTIMAL_TEMP")))
                    # ac.console("Tyres: {}, {}psi/{}psi, {}°C-{}°C".format(tyreCompoundValue, idealPressureFront, idealPressureRear, minimumOptimalTemperature, maximumOptimalTemperature))
                except:
                    ac.console("Error loading mod tyre data.")
            else:
                ac.console(
                    "Tyres: {}, no data found".format(tyreCompoundValue))

    # 10 times per second
    if timer1 > 0.1:
        timer1 = 0

        currentLapValue = info.graphics.iCurrentTime
        lapValue = ac.getCarState(0, acsys.CS.LapCount)
        lapProgressValue = ac.getCarState(0, acsys.CS.NormalizedSplinePosition)

        # =================================================================================================================
        #                                                  DRS
        # =================================================================================================================
        drsAvailableValue = ac.getCarState(0, acsys.CS.DrsAvailable)
        drsEnabledValue = ac.getCarState(0, acsys.CS.DrsEnabled)

        # =================================================================================================================
        #                                        DRS SIMPLE (not races)
        # =================================================================================================================

        if info.graphics.session != 2 and ac.getCarName(0) in DRS_ALLOWED_CARS:
            if drsEnabledValue:
                set_drs_good()
            elif drsAvailableValue:
                set_drs_available()

                if not soundPlaying and SOUND_ON:  # use this variable to control drs beep at begining of drs
                    sound_player.play(audio)
                    sound_player.stop()
                    soundPlaying = True
            else:
                soundPlaying = False
                ac.setVisible(drsLabel, 0)

        # =================================================================================================================
        #                                          DRS DATA COLLECTION
        # =================================================================================================================

        if info.graphics.session == 2 and ac.getCarName(0) in DRS_ALLOWED_CARS:

            crossedDetectionZone = -1
            crossedEndZone = -1
            crossedStartZone = -1
            curTime = time.time()
            for i in range(totalDrivers):
                spline = ac.getCarState(i, acsys.CS.NormalizedSplinePosition)
                for zid, zone in enumerate(drsZones):
                    if driver_crossed_zone(driversList[i].last_pos,
                                           zone['detection'], spline):
                        driversList[i].drs_detection_times[zid] = curTime
                        if i == 0:  # current driver
                            crossedDetectionZone = zid  # mark zone crossed by driver (not possible to cross multiple zone)
                    if i == 0 and driver_crossed_zone(driversList[i].last_pos,
                                                      zone['end'], spline):
                        crossedEndZone = zid
                    if i == 0 and driver_crossed_zone(driversList[i].last_pos,
                                                      zone['start'], spline):
                        crossedStartZone = zid
                driversList[i].last_pos = spline

        # =================================================================================================================
        #                                          DRS ALLOWANCE MANAGEMENT
        # =================================================================================================================

        # Race Restart
            if info.graphics.completedLaps == 0 and info.graphics.iCurrentTime == 0:
                totalPenalty = 0  # reset penalty
                set_drs_penalty(0)

            # DRS DETECTION Zone crossed
            if crossedDetectionZone != -1:
                if info.graphics.completedLaps + 1 >= DRS_STARTS_ON_LAP:  # if this is a valid lap
                    ac.log("Checking Detection Zone: " +
                           str(crossedDetectionZone) + " on lap: " +
                           str(info.graphics.completedLaps))
                    # check if there is any driver within DRS_GAP
                    if any(driversList[0].
                           drs_detection_times[crossedDetectionZone] -
                           driver.drs_detection_times[crossedDetectionZone] <=
                           DRS_GAP and driversList[0].
                           drs_detection_times[crossedDetectionZone] - driver.
                           drs_detection_times[crossedDetectionZone] >= 0
                           for driver in driversList[1:]):
                        set_drs_possible()
                        drsAvailableZones[crossedDetectionZone] = True

            # DRS END Zone crossed
            if crossedEndZone != -1:
                drsAvailableZones[crossedEndZone] = False
                currentDrsZone = -1
                drsPenaltyAwardedInZone = False
                # if next zone allows for drs already -- for cases where 1 DRS detection is used in 2 zones
                if drsAvailableZones[(crossedEndZone + 1) %
                                     len(drsAvailableZones)]:
                    set_drs_possible()
                set_drs_hidden()

            # DRS START Zone crossed
            if crossedStartZone != -1:
                currentDrsZone = crossedStartZone

            # IN DRS ZONE
            if drsAvailableValue:
                if drsAvailableZones[currentDrsZone]:
                    if drsEnabledValue:
                        set_drs_good()
                    else:
                        set_drs_available()
                        if totalPenalty > 0: totalPenalty -= curTime - lastTime
                        set_drs_penalty(totalPenalty)
                else:
                    if drsEnabledValue:
                        set_drs_bad()
                        if not drsPenaltyAwardedInZone:
                            drsPenaltyAwardedInZone = True
                            announcePenalty(
                                ac.getDriverName(0),
                                info.graphics.completedLaps + 1,
                                "Illegal DRS use, Zone %d" % (currentDrsZone))
                        # Add penalty amount
                        if abs(curTime - lastTime) < 1:
                            totalPenalty += curTime - lastTime
                        set_drs_penalty(totalPenalty)
                    else:
                        set_drs_hidden()

            # end of drs update save current values into lasts
            lastTime = curTime

        # =================================================================================================================
        #                                              ERS LABEL
        # =================================================================================================================

        ersRecoveryLevel = info.physics.ersRecoveryLevel
        ersMode = info.physics.ersPowerLevel
        ac.setText(ersModeLabel, "🗲{}".format(ersMode))
        ac.setText(ersRecoveryLabel, "↺{}".format(ersRecoveryLevel))
        ac.setFontColor(ersModeLabel, *ERS_COLORS[ersMode])
        ac.setFontColor(ersLabel, *ERS_COLORS[ersMode])
        ac.setFontColor(ersRecoveryLabel, *ERS_COLORS[ersMode])

        # =================================================================================================================
        #                                              FUEL LABEL
        # =================================================================================================================

        if fuelPerLapValue:
            ac.setText(
                fuelLabel,
                "💧 {:.1f} Laps".format(fuelAmountValue / fuelPerLapValue))

        # =================================================================================================================
        #                                          TYRE TEMPERATURES
        # =================================================================================================================

        for i in range(4):
            tyrePracticalTemperatureValue[i] = 0.25 * (
                (tyreTemperatureValueI[i] + tyreTemperatureValueM[i] +
                 tyreTemperatureValueO[i]) /
                3) + 0.75 * tyreTemperatureValue[i]

        for i, label in enumerate(tyreLabels):
            # ac.setText(label, "{:.0f}".format(tyrePracticalTemperatureValue[i]))
            if minimumOptimalTemperature and maximumOptimalTemperature:
                if int(round(tyrePracticalTemperatureValue[i])
                       ) >= minimumOptimalTemperature and int(
                           round(tyrePracticalTemperatureValue[i])
                       ) <= maximumOptimalTemperature:
                    ac.setBackgroundColor(label, 0.17, 1, 0)
                elif int(round(tyrePracticalTemperatureValue[i])
                         ) < minimumOptimalTemperature:
                    idealTemperatureDifference = min(
                        temperatureTransitionRange, minimumOptimalTemperature -
                        tyrePracticalTemperatureValue[i]
                    ) / temperatureTransitionRange
                    ac.setBackgroundColor(
                        label, max(0,
                                   0.17 - idealTemperatureDifference / 5.88),
                        max(0.51, 1 - idealTemperatureDifference / 1.96),
                        min(1, 0 + idealTemperatureDifference))
                elif int(round(tyrePracticalTemperatureValue[i])
                         ) > maximumOptimalTemperature:
                    idealTemperatureDifference = min(
                        temperatureTransitionRange,
                        tyrePracticalTemperatureValue[i] -
                        maximumOptimalTemperature) / temperatureTransitionRange
                    ac.setBackgroundColor(
                        label, min(1,
                                   0.17 + idealTemperatureDifference / 0.83),
                        max(0.17, 1 - idealTemperatureDifference / 0.83), 0)
            else:
                ac.setBackgroundOpacity(label, 0)
            ac.setBackgroundOpacity(
                label, 1
            )  # background colors start to hyde for some reason so this is needed

        for i, label in enumerate(tyrePressureLabels):
            if idealPressureFront and idealPressureRear:
                if i < 2:  # front
                    ac.setText(
                        label, "{:+.1f}".format(tyrePressureValue[i] -
                                                idealPressureFront))
                else:  # rear
                    ac.setText(
                        label, "{:+.1f}".format(tyrePressureValue[i] -
                                                idealPressureRear))
            else:
                ac.setText(label, "{:.0f}".format(tyrePressureValue[i]))

    # =================================================================================================================
    #                                     CALCULATE AT LAP ENDING OR LAP START
    # =================================================================================================================

    #Display/calculate on lap start
    if currentLapValue > 500 and currentLapValue < 1000:
        carWasInPit = 0
        fuelStartValue = fuelAmountValue

    #Display/calculate on lap finish
    if previousLapValue < lapValue:
        # announce any penalty at the end of a lap
        if totalPenalty > 0:
            announceTotalPenalty(ac.getDriverName(0),
                                 info.graphics.completedLaps + 1)
        previousLapValue = lapValue

        #Fuel per lap
        if fuelAmountValue < fuelStartValue and not carWasInPit:
            relevantLapsNumber += 1
            fuelSpentValue += fuelStartValue - fuelAmountValue
            fuelPerLapValue = fuelSpentValue / relevantLapsNumber
Esempio n. 24
0
    def show(self, id, pos, starting_position, tyres, pit_stops):
        ac.setBackgroundTexture(self.positionLabel,
                                FC.LEADERBOARD_POSITION_LABEL[pos + 1])

        ac.setVisible(self.positionLabel, 1)
        ac.setVisible(self.rolexLabel, 1)
        ac.setVisible(self.backgroundTexture, 1)
        ac.setVisible(self.nameLabel, 1)

        if self.extended:
            places = starting_position - (pos + 1)
            if places == 0:
                ac.setFontColor(self.placesLabel, 0.86, 0.86, 0.86, 1)
                ac.setVisible(self.placesIconLabel, 0)
                ac.setPosition(self.placesLabel, 175, 85)
            elif places > 0:
                ac.setFontColor(self.placesLabel, 0.3, .85, .28, 1)  # green
                ac.setBackgroundTexture(self.placesIconLabel,
                                        FC.POSITION_GAINED)
                ac.setPosition(self.placesLabel, 190, 85)
                ac.setVisible(self.placesIconLabel, 1)
            elif places < 0:
                ac.setFontColor(self.placesLabel, 0.97, .25, .25, 1)  # red
                ac.setBackgroundTexture(self.placesIconLabel, FC.POSITION_LOST)
                ac.setPosition(self.placesLabel, 190, 85)
                ac.setVisible(self.placesIconLabel, 1)
            ac.setText(self.placesLabel, str(abs(places)))

        if self.id != id:
            name = ac.getDriverName(id)
            sName = name.split()
            ac.setText(self.nameLabel, "%s %s" % (sName[0], sName[-1].upper()))

            if FC.TEAM_COLORS:
                try:
                    ac.setBackgroundTexture(self.teamLabel,
                                            FC.TEAM_COLORS[name])
                    ac.setText(self.teamNameLabel, FC.TEAM_NAME[name])
                    ac.setBackgroundTexture(self.numberLabel,
                                            FC.NUMBER_TAGS[name])
                    ac.setVisible(self.teamLabel, 1)
                    ac.setVisible(self.teamNameLabel, 1)
                    ac.setVisible(self.numberLabel, 1)
                except KeyError:
                    ac.log("%s:Name Missing in teams.txt %s" %
                           (FC.APP_NAME, name))

        if self.extended != DriverWidget.extended or self.id != id:
            self.extended = DriverWidget.extended
            if self.extended:
                ac.setText(self.pitStopLabel, str(pit_stops))
                u = str(starting_position)[-1]
                if u == "1": subscript = "st"
                if u == "2": subscript = "nd"
                if u == "3": subscript = "rd"
                else: subscript = "th"
                ac.setText(self.startedLabel,
                           str(starting_position) + subscript)
                ac.setBackgroundTexture(self.tyreLabel,
                                        FC.TYRE_DIR + tyres + ".png")
                ac.setBackgroundTexture(self.backgroundTexture,
                                        FC.DRIVER_WIDGET_BACKGROUND_ALTERNATE)
                ac.setVisible(self.extendedBackgroundTexture, 1)
                ac.setVisible(self.startedLabel, 1)
                ac.setVisible(self.startedTextLabel, 1)
                ac.setVisible(self.placesLabel, 1)
                ac.setVisible(self.placesTextLabel, 1)
                ac.setVisible(self.tyreTextLabel, 1)
                ac.setVisible(self.tyreLabel, 1)
                ac.setVisible(self.pitStopTextLabel, 1)
                ac.setVisible(self.pitStopLabel, 1)
            else:
                ac.setBackgroundTexture(self.backgroundTexture,
                                        FC.DRIVER_WIDGET_BACKGROUND)
                ac.setVisible(self.extendedBackgroundTexture, 0)
                ac.setVisible(self.startedLabel, 0)
                ac.setVisible(self.startedTextLabel, 0)
                ac.setVisible(self.placesLabel, 0)
                ac.setVisible(self.placesTextLabel, 0)
                ac.setVisible(self.placesIconLabel, 0)
                ac.setVisible(self.tyreTextLabel, 0)
                ac.setVisible(self.tyreLabel, 0)
                ac.setVisible(self.pitStopTextLabel, 0)
                ac.setVisible(self.pitStopLabel, 0)
        self.id = id
        self.visible = True
Esempio n. 25
0
    def __init__(self, leaderboardWindow, row):
        # SET SOME VARIABLES
        self.row = row
        px, py = LeaderboardRow.X_BASE, LeaderboardRow.Y_BASE + LeaderboardRow.ROW_HEIGHT * self.row  # position of the names
        self.px = px
        self.py = py
        self.positionLabelId = 0  # 0 white, 1 red, 2 green - to prevent loading the labels all the time
        self.out = False
        self.pit = False

        self.highlightLabel = ac.addLabel(leaderboardWindow, "")
        ac.setPosition(self.highlightLabel, px - 5, py - 6)
        ac.setSize(self.highlightLabel, 258, LeaderboardRow.ROW_HEIGHT + 1)
        ac.setBackgroundTexture(self.highlightLabel,
                                FC.LEADERBOARD_PLAYER_HIGHLIGHT)
        ac.setVisible(self.highlightLabel, 0)

        # CREATE LABELS
        self.positionLabel = ac.addLabel(leaderboardWindow, "")
        ac.setPosition(self.positionLabel, px - 4, py - 7)
        ac.setSize(self.positionLabel, 38, 38)
        ac.setBackgroundTexture(self.positionLabel,
                                FC.LEADERBOARD_POSITION_LABEL[self.row + 1])

        self.driverName = ac.getDriverName(row)
        self.driverId = -1
        self.nameLabel = ac.addLabel(leaderboardWindow,
                                     self.driverName[:3].upper())
        ac.setPosition(self.nameLabel, px + 65, py + 4)
        ac.setFontSize(self.nameLabel, 18)
        ac.setCustomFont(self.nameLabel, FC.FONT_NAME, 0, 1)
        ac.setFontColor(self.nameLabel, 0.86, 0.86, 0.86, 1)
        ac.setFontAlignment(self.nameLabel, "left")

        self.teamLabel = ac.addLabel(leaderboardWindow, "")
        ac.setPosition(self.teamLabel, px + 47, py + 2)
        ac.setSize(self.teamLabel, 5, 18)
        if FC.TEAM_COLORS:
            try:
                ac.setBackgroundTexture(self.teamLabel,
                                        FC.TEAM_COLORS[self.driverName])
            except KeyError:
                ac.log("%s:Name Missing in teams.txt %s" %
                       (FC.APP_NAME, self.driverName))

        self.infoLabel = ac.addLabel(leaderboardWindow, "Interval")
        ac.setPosition(self.infoLabel, 250, py + 4)
        ac.setFontSize(self.infoLabel, 18)
        ac.setCustomFont(self.infoLabel, FC.FONT_NAME, 0, 1)
        ac.setFontColor(self.infoLabel, 0.86, 0.86, 0.86, 1)
        ac.setFontAlignment(self.infoLabel, "right")

        self.positionChangeLabel = ac.addLabel(leaderboardWindow, "")
        ac.setPosition(self.positionChangeLabel, 205, py + 4)
        ac.setSize(self.positionChangeLabel, 18, 18)
        ac.setVisible(self.positionChangeLabel, 0)

        self.fastestLapLabel = ac.addLabel(leaderboardWindow, "")
        ac.setPosition(self.fastestLapLabel, px - 41, py - 6)
        ac.setSize(self.fastestLapLabel, 37, 37)
        ac.setBackgroundTexture(self.fastestLapLabel,
                                FC.LEADERBOARD_FASTEST_LAP)
        ac.setVisible(self.fastestLapLabel, 0)

        self.focus_button = ac.addButton(leaderboardWindow, "")
        ac.setPosition(self.focus_button, px, py - 7)
        ac.setSize(self.focus_button, 140, 38)
        self.on_click_focus_func = functools.partial(self.on_click_focus,
                                                     row=self)
        ac.addOnClickedListener(self.focus_button, self.on_click_focus_func)
        ac.setBackgroundOpacity(self.focus_button, 0)
        ac.drawBorder(self.focus_button, 0)
def acUpdate(deltaT):
    # TIMERS
    global timer0, timer1, timer2

    # VARIABLES
    global totalDrivers
    global drivers
    global fastest_lap

    global race_started, replay_started, quali_started

    global qualify_session_time

    global replay_file
    global replay_data

    # Widgets
    global leaderboardWindow, driverWidget, driverComparisonWidget

    # LABELS
    global leaderboard
    global lapCountTimerLabel, leaderboardBaseLabel, leaderboardInfoBackgroundLabel, leaderboardBackgroundLabel
    global flagLabel

    # ============================
    # UPDATE TIMERS
    timer0 += deltaT
    timer1 += deltaT
    timer2 += deltaT
    # ============================

    # ================================================================
    #                            RACES
    # ================================================================
    if info.graphics.session == 2:

        # 10 times per second
        if timer2 > 0.1:
            timer2 = 0

            # =============================
            # SAVE SPLIT TIMES
            for d in drivers:
                if ac.isConnected(d.id) == 0: continue
                current_split = d.get_split_id(ac.getCarState(d.id, acsys.CS.NormalizedSplinePosition))
                if d.current_split != current_split: # save split time at each split of the track
                    d.split_times[current_split-1] = time.time()
                    d.current_split = current_split

        # 3 times per second
        if timer1 > 0.3:
            # CHECK RACE RESTART
            if race_started and info.graphics.completedLaps == 0 and info.graphics.iCurrentTime == 0:
                race_started = False

            # CHECK RACE START
            if not race_started and info.graphics.iCurrentTime > 0:
                # RESET THINGS
                fastest_lap = MAX_LAP_TIME
                LeaderboardRow.FASTEST_LAP_ID = -1
                for row in leaderboard: # clean the fastest lap marker
                    row.mark_fastest_lap()
                # in case we are coming from a qualify
                ac.setFontColor(lapCountTimerLabel, 0.86, 0.86, 0.86, 1)
                ac.setBackgroundTexture(leaderboardBaseLabel, FC.LEADERBOARD_BASE_RACE)
                ac.setVisible(lapCountTimerLabel, 1)

                race_started = True
                quali_started = False
                for d in drivers:
                    d.starting_position = ac.getCarLeaderboardPosition(d.id)
                    d.tyre = ac.getCarTyreCompound(d.id)
                    d.pits = 0
                replay_file = setup_replay_file(drivers, info.graphics.numberOfLaps) # save starting info on the drivers

            # ============================
            # POSITION UPDATE
            for i in range(totalDrivers):
                pos = ac.getCarRealTimeLeaderboardPosition(i)
                connected = ac.isConnected(i)
                if connected == 0: # mark unconnected drivers
                    leaderboard[pos].mark_out()
                    drivers[i].out = True
                else:
                    leaderboard[pos].mark_in()
                    drivers[i].out = False
                leaderboard[pos].update_name(i)

                # OVERTAKE
                if pos != drivers[i].position: # there was an overtake
                    drivers[i].timer = FC.OVERTAKE_POSITION_LABEL_TIMER # set timer
                    if pos < drivers[i].position:
                        leaderboard[pos].mark_green_position()
                    elif pos > drivers[i].position:
                        leaderboard[pos].mark_red_position()
                elif drivers[i].timer <= 0:
                    leaderboard[pos].mark_white_position()
                else:
                    drivers[i].timer -= timer1
                drivers[i].position = pos
                # END OVERTAKE

            # ============================
            # FASTEST LAP BANNER TIMER
            if fastest_lap_banner.timer > 0:
                fastest_lap_banner.timer -= timer1
                fastest_lap_banner.hide()

            # ============================
            # FLAGS
            if info.graphics.flag == 1:
                ac.setBackgroundTexture(flagLabel, FC.BLUE_FLAG)
                ac.setVisible(flagLabel, 1)
            elif info.graphics.flag == 2:
                ac.setBackgroundTexture(flagLabel, FC.YELLOW_FLAG)
                ac.setVisible(flagLabel, 1)
            elif info.graphics.flag == 5:
                ac.setBackgroundTexture(flagLabel, FC.CHECKERED_FLAG)
                ac.setVisible(flagLabel, 1)
            elif info.graphics.flag == 0:
                ac.setVisible(flagLabel, 0)

            timer1 = 0

        # Once per second
        if timer0 > 1:
            timer0 = 0
            ac.setBackgroundOpacity(leaderboardWindow, 0)
            ac.setBackgroundOpacity(driverWidget.window, 0)
            ac.setBackgroundOpacity(driverComparisonWidget.window, 0)
            ac.setBackgroundOpacity(fastest_lap_banner.window, 0)

            # ============================
            # SERVER LAP
            for i in range(totalDrivers):
                drivers[i].current_lap = ac.getCarState(i, acsys.CS.LapCount)
            lc = max((drivers[i].current_lap for i in range(totalDrivers))) + 1
            if lc >= info.graphics.numberOfLaps:
                ac.setVisible(lapCountTimerLabel, 0)
                ac.setBackgroundTexture(leaderboardBaseLabel, FC.LEADERBOARD_FINAL_LAP)
            else:
                ac.setText(lapCountTimerLabel, "%d / %d" % (lc, info.graphics.numberOfLaps))

            # ===========================
            # CALCULATE TIME DIFERENCES
            dPosition = sorted(drivers, key=lambda x: x.position)
            if LeaderboardRow.update_type == INFO_TYPE.GAPS:
                for i in range(1, len(dPosition)):
                    driver_ahead, driver = dPosition[i-1], dPosition[i]
                    timeDiff = driver.split_times[driver.current_split - 1] - driver_ahead.split_times[driver.current_split - 1]
                    if timeDiff < 0: continue # ignore these times, happens on overtakes
                    if driver.position > totalDrivers: continue # might try to update before it is possible
                    driver.timeDiff = timeDiff
                    if timeDiff > 60:
                        leaderboard[driver.position].update_time("+1 MIN")
                    else:
                        leaderboard[driver.position].update_time("+" + time_to_string(timeDiff*1000))
                leaderboard[0].update_time("Interval") # Force it
            elif LeaderboardRow.update_type == INFO_TYPE.POSITIONS:
                for d in dPosition:
                    posDiff = d.starting_position - d.position - 1
                    leaderboard[d.position].update_positions(posDiff)

            # ============================
            # MARK FASTEST LAP
            if lc > FC.FASTEST_LAP_STARTING_LAP:
                for d in drivers:
                    lap = ac.getCarState(d.id, acsys.CS.BestLap)
                    if lap != 0 and lap < fastest_lap:
                        fastest_lap = lap
                        fastest_lap_banner.show(lap, ac.getDriverName(d.id))
                        LeaderboardRow.FASTEST_LAP_ID = d.id
                        if replay_file:
                            write_fastest_lap(replay_file, info.graphics.completedLaps, info.graphics.iCurrentTime, d, fastest_lap)
                for row in leaderboard:
                    row.mark_fastest_lap()

            # ============================
            # PITS MARKER
            for row in leaderboard:
                if ac.isCarInPitline(row.driverId) == 1:
                    row.mark_enter_pits()
                    drivers[row.driverId].tyre = ac.getCarTyreCompound(row.driverId) # maybe will change tyre
                else:
                    row.mark_left_pits()
                if time.time() - drivers[row.driverId].pit_time > 20 and ac.isCarInPit(row.driverId):
                    drivers[row.driverId].pits += 1
                    drivers[row.driverId].pit_time = time.time()

            # ============================
            # CHANGE CAR FOCUS AND DRIVER WIDGET
            if race_started:
                id = ac.getFocusedCar()
                if drivers[id].position <= totalDrivers: # in case it wasnt updated yet
                    driverWidget.show(id, drivers[id].position, drivers[id].starting_position, drivers[id].tyre, drivers[id].pits)
                    if drivers[id].position == 0:
                        driverComparisonWidget.hide()
                    else:
                        for d in drivers: # find driver ahead
                            if d.position == drivers[id].position - 1:
                                driverComparisonWidget.show(d.id, d.position, id, drivers[id].position, drivers[id].timeDiff*1000)
                                break
            else:
                driverWidget.hide()
                driverComparisonWidget.hide()

            # ========================================================
            # SAVE DRIVER STATUS IN A FILE TO LOAD ON REPLAY
            if replay_file:
                write_driver_info(replay_file, info.graphics.completedLaps, info.graphics.iCurrentTime, drivers)
            # ========================================================


    # ================================================================
    #                        QUALIFY / PRACTICE
    # ================================================================
    elif info.graphics.session == 1 or (info.graphics.session == 0 and info.graphics.status != 1):

        # 3 times per second
        if timer1 > 0.3:
            # =============================================
            # QUALIFY RESTART
            if quali_started and qualify_session_time - info.graphics.sessionTimeLeft < 1:
                quali_started = False

            # =============================================
            # QUALIFY START
            if not quali_started:
                ac.setBackgroundTexture(leaderboardBaseLabel, FC.LEADERBOARD_BASE_QUALI)
                if (info.graphics.session == 0 and info.graphics.status != 0):
                    ac.setBackgroundTexture(leaderboardBaseLabel, FC.LEADERBOARD_BASE_PRACTICE)
                ac.setFontColor(lapCountTimerLabel, 0.86, 0.86, 0.86, 1)
                qualify_session_time = info.graphics.sessionTimeLeft
                fastest_lap = MAX_LAP_TIME
                LeaderboardRow.FASTEST_LAP_ID = -1
                quali_started = True
                race_started = False

            # =============================================
            # SAVE BEST LAPS FOR EACH DRIVER
            for i in range(totalDrivers):
                lap = ac.getCarState(i, acsys.CS.BestLap)
                if lap != 0:
                    drivers[i].best_lap = lap
                if lap != 0 and lap < fastest_lap:
                    fastest_lap = lap
                    fastest_lap_banner.show(lap, ac.getDriverName(i))

                # MARK IN/OUT DRIVERS
                connected = ac.isConnected(i)
                if connected == 0: # mark unconnected drivers
                    drivers[i].out = True
                else:
                    drivers[i].out = False
                
            # =============================================
            # MANAGE LEADERBOARD

            # Sorting: sort drivers by this order 1. in or out drivers, 2. best lap, 3. driver id
            dPosition = sorted(drivers, key=lambda d: (d.out, d.best_lap, d.id))

            for i in range(totalDrivers):
                if dPosition[i].out:
                    leaderboard[i].mark_out()
                else:
                    leaderboard[i].mark_in()

                leaderboard[i].update_name(dPosition[i].id)
                if dPosition[i].best_lap == MAX_LAP_TIME:
                    leaderboard[i].update_time("NO TIME")
                elif i == 0:
                    leaderboard[i].update_time(time_to_string(dPosition[i].best_lap))
                else:
                    timeDiff = dPosition[i].best_lap - dPosition[0].best_lap
                    if timeDiff > 60000:
                        leaderboard[i].update_time("+1 MIN")
                    else:
                        leaderboard[i].update_time("+" + time_to_string(timeDiff))

                # OVERTAKES
                if i != dPosition[i].position: # there was an overtake on this driver
                    dPosition[i].timer = FC.OVERTAKE_POSITION_LABEL_TIMER
                    if i < dPosition[i].position:
                        leaderboard[i].mark_green_position()
                    elif i > dPosition[i].position:
                        leaderboard[i].mark_red_position()
                elif dPosition[i].timer <= 0:
                    leaderboard[i].mark_white_position()
                else:
                    dPosition[i].timer -= timer1
                dPosition[i].position = i
                # END OVERTAKE

            # ============================
            # FASTEST LAP BANNER TIMER
            if fastest_lap_banner.timer > 0:
                fastest_lap_banner.timer -= timer1
                fastest_lap_banner.hide()

            timer1 = 0

        # Once per second
        if timer0 > 1:
            timer0 = 0
            ac.setBackgroundOpacity(leaderboardWindow, 0)
            ac.setBackgroundOpacity(driverWidget.window, 0)
            ac.setBackgroundOpacity(driverComparisonWidget.window, 0)
            ac.setBackgroundOpacity(fastest_lap_banner.window, 0)

            if quali_started:
                if info.graphics.sessionTimeLeft < 0:
                    ac.setText(lapCountTimerLabel, "0:00")
                else:
                    timeText = time_to_string(info.graphics.sessionTimeLeft)[:-4]
                    ac.setText(lapCountTimerLabel, "0:00"[:-len(timeText)] + timeText)
                if info.graphics.sessionTimeLeft < qualify_session_time / 5:
                    ac.setFontColor(lapCountTimerLabel, 1,0,0,1)

            driverWidget.hide()
            driverComparisonWidget.hide()


    # ================================================================
    #                            REPLAYS
    # ================================================================
    elif info.graphics.status == 1:

        # three times per second
        if timer1 > 0.3:
            if not replay_started:
                if info.graphics.iCurrentTime > 0:
                    replay_data = load_replay_file(drivers)
                    replay_started = True

            # ============================
            # FASTEST LAP BANNER TIMER
            if fastest_lap_banner.timer > 0:
                fastest_lap_banner.timer -= timer1
                fastest_lap_banner.hide()

            # ============================
            # GET DATA FOR THIS UPDATE
            if replay_data:
                new_positions = lookup_data(info.graphics.completedLaps, info.graphics.iCurrentTime, replay_data, drivers)

                # ============================
                # POSITION UPDATE
                for i in range(totalDrivers):
                    pos = new_positions[i]
                    if drivers[i].out: # mark unconnected drivers
                        leaderboard[pos].mark_out()
                    else:
                        leaderboard[pos].mark_in()
                    leaderboard[pos].update_name(i)

                    # OVERTAKE
                    if pos != drivers[i].position: # there was an overtake
                        drivers[i].timer = FC.OVERTAKE_POSITION_LABEL_TIMER # set timer
                        if pos < drivers[i].position:
                            leaderboard[pos].mark_green_position()
                        elif pos > drivers[i].position:
                            leaderboard[pos].mark_red_position()
                    elif drivers[i].timer <= 0:
                        leaderboard[pos].mark_white_position()
                    else:
                        drivers[i].timer -= timer1
                    drivers[i].position = pos
                    # END OVERTAKE

            timer1 = 0

        # Once per second
        if timer0 > 1:
            timer0 = 0
            ac.setBackgroundOpacity(leaderboardWindow, 0)
            ac.setBackgroundOpacity(driverWidget.window, 0)
            ac.setBackgroundOpacity(driverComparisonWidget.window, 0)
            ac.setBackgroundOpacity(fastest_lap_banner.window, 0)

            # ============================
            # GET FASTEST LAP UPDATE
            if replay_data:
                fl_data = lookup_fastest_lap(info.graphics.completedLaps, info.graphics.iCurrentTime, replay_data)
                if fl_data:
                    display_time = FC.FASTEST_LAP_DISPLAY_TIME - (info.graphics.iCurrentTime - fl_data[0]) / 1000
                    fastest_lap_banner.show(fl_data[2], ac.getDriverName(fl_data[1]), timer=display_time) # display only for the time left

            # ============================
            # SERVER LAP
            if replay_data:
                lc = max((drivers[i].current_lap for i in range(totalDrivers))) + 1
                if lc >= replay_data['nLaps']:
                    ac.setVisible(lapCountTimerLabel, 0)
                    ac.setBackgroundTexture(leaderboardBaseLabel, FC.LEADERBOARD_FINAL_LAP)
                else:
                    ac.setText(lapCountTimerLabel, "%d / %d" % (lc, replay_data['nLaps']))
                    ac.setVisible(lapCountTimerLabel, 1)
                    ac.setBackgroundTexture(leaderboardBaseLabel, FC.LEADERBOARD_BASE_RACE)

            # ============================
            # PITS MARKER
            for row in leaderboard:
                if ac.isCarInPitline(row.driverId) == 1:
                    row.mark_enter_pits()
                else:
                    row.mark_left_pits()

            # ============================
            # DRIVER WIDGET UPDATE
            if replay_started:
                id = ac.getFocusedCar()
                if drivers[id].position <= totalDrivers: # in case it wasnt updated yet
                    driverWidget.show(id, drivers[id].position, drivers[id].starting_position, drivers[id].tyre, drivers[id].pits)
                    if drivers[id].position == 0:
                        driverComparisonWidget.hide()
                    else:
                        for d in drivers: # find driver ahead
                            if d.position == drivers[id].position - 1:
                                driverComparisonWidget.show(d.id, d.position, id, drivers[id].position, drivers[id].timeDiff*1000)
                                break
            else:
                driverWidget.hide()
                driverComparisonWidget.hide()

            # ============================
            # UPDATE TIMES
            if replay_data:
                for row in leaderboard:
                    if LeaderboardRow.update_type == INFO_TYPE.GAPS:
                        row.update_time("+" + time_to_string(drivers[row.driverId].timeDiff*1000))
                        if row.row == 0:
                            row.update_time("Interval") # Force it
                    elif LeaderboardRow.update_type == INFO_TYPE.POSITIONS:
                        posDiff = drivers[row.driverId].starting_position - drivers[row.driverId].position - 1
                        row.update_positions(posDiff)
Esempio n. 27
0
    def on_update(self, sim_info, standings, game_data):
        session_time_left = game_data.sessionTimeLeft
        sim_info_status = game_data.status
        self.standings = standings
        if self.is_multiplayer:
            self.numCars = 0
        for i in range(self.cars_count):
            if ac.isConnected(i) > 0:
                if self.is_multiplayer:
                    self.numCars += 1
                self.drivers_lap_count[i].setValue(
                    ac.getCarState(i, acsys.CS.LapCount))
                if self.last_lap_start[i] == -1 and session_time_left != 0:
                    self.last_lap_start[i] = session_time_left
                if self.drivers_lap_count[i].hasChanged(
                ) and session_time_left != 0:
                    self.last_lap_start[i] = session_time_left
                    # if PB save delta
                    if ac.getCarState(i, acsys.CS.LastLap) <= ac.getCarState(
                            i, acsys.CS.BestLap):
                        self.reference_lap_time_others[i] = list(
                            self.current_lap_others[i])
                        if len(self.reference_lap_time_others[i]
                               ) > 2000:  # 2laps in
                            how_much = math.floor(
                                len(self.reference_lap_time_others[i]) / 1000)
                            del self.reference_lap_time_others[i][0:math.floor(
                                len(self.reference_lap_time_others[i]) /
                                how_much)]
                    # reset
                    self.current_lap_others[i] = []
                # Deltas
                self.spline_others[i].setValue(
                    round(ac.getCarState(i, acsys.CS.NormalizedSplinePosition),
                          3))
                if self.is_touristenfahrten and self.spline_others[
                        i].value == 0.953:
                    self.last_lap_start[i] = session_time_left
                    self.current_lap_others[i] = []
                if ac.isCarInPit(i) or ac.isCarInPitline(i):
                    self.current_lap_others[i] = []
                if self.spline_others[i].hasChanged(
                ) and session_time_left != 0:
                    self.current_lap_others[i].append(
                        raceGaps(self.spline_others[i].value,
                                 self.last_lap_start[i] - session_time_left))

        if not self.deltaLoaded and Configuration.save_delta:
            thread_load = threading.Thread(target=self.load_delta)
            thread_load.daemon = True
            thread_load.start()
        if self.__class__.resetPressed:
            self.referenceLapTime.setValue(0)
            self.referenceLap = []
            self.lastLapTime.setValue(0)
            self.spline.setValue(0)
            self.__class__.resetPressed = False
        if self.__class__.importPressed:
            self.referenceLap = self.reference_lap_time_others[
                self.currentVehicle.value]
            self.referenceLapTime.setValue(
                ac.getCarState(self.currentVehicle.value, acsys.CS.BestLap))
            '''
            self.lastLapTime.setValue(0)
            self.spline.setValue(0)
            '''
            self.__class__.importPressed = False
        self.session.setValue(game_data.session)
        self.manage_window(game_data)
        self.animate()
        self.currentVehicle.setValue(game_data.focusedCar)
        self.current_car_class.setValue(
            self.get_class_id(self.currentVehicle.value))
        if self.currentVehicle.hasChanged(
        ) or self.current_car_class.hasChanged():
            # number, curtime...
            if Configuration.names == 1:
                self.lbl_name_text.setText(
                    self.format_name_tlc2(
                        ac.getDriverName(self.currentVehicle.value)))
            else:
                self.lbl_name_text.setText(
                    self.format_name_tlc(
                        ac.getDriverName(self.currentVehicle.value)))
            self.lbl_number_text.setText(self.get_driver_number())
            #car_name=ac.getCarName(self.currentVehicle.value)
            self.lbl_number_bg.set(background=Colors.color_for_car_class(
                self.current_car_class.value),
                                   init=True)
            self.lbl_number_text.set(color=Colors.txt_color_for_car_class(
                self.current_car_class.value),
                                     init=True)
            self.performance_display = 0
        completed_laps = ac.getCarState(self.currentVehicle.value,
                                        acsys.CS.LapCount)
        self.lbl_laps_completed_text.setText(str(completed_laps))
        self.lbl_laps_completed_text_shadow.setText(str(completed_laps))
        if completed_laps > 1:
            self.lbl_laps_text.setText("LAPS")
            self.lbl_laps_text_shadow.setText("LAPS")
        else:
            self.lbl_laps_text.setText("LAP")
            self.lbl_laps_text_shadow.setText("LAP")

        if sim_info_status == 2:  # LIVE
            if session_time_left == 0 or game_data.beforeRaceStart:
                self.reset_data()
                self.reset_others()
                if not Configuration.save_delta:
                    self.referenceLapTime.setValue(0)
                    self.referenceLap = []
                    self.lastLapTime.setValue(0)
                    self.spline.setValue(0)
            elif self.currentVehicle.value == 0 and bool(
                    ac.isCarInPitline(0)) or bool(ac.isCarInPit(0)):
                self.reset_data()
            self.spline.setValue(
                round(
                    ac.getCarState(self.currentVehicle.value,
                                   acsys.CS.NormalizedSplinePosition), 3))
            #Current lap time
            if self.currentVehicle.value != 0 and self.last_lap_start[
                    self.currentVehicle.
                    value] != -1 and session_time_left != 0:
                self.lbl_current_time_text.setText(
                    self.time_splitting_full(
                        self.last_lap_start[self.currentVehicle.value] -
                        session_time_left))
            else:
                self.lbl_current_time_text.setText(
                    self.time_splitting_full(
                        ac.getCarState(self.currentVehicle.value,
                                       acsys.CS.LapTime)))
            if self.currentVehicle.value == 0 and not self.lastLapIsValid:
                self.lbl_current_time_text.set(color=Colors.red(),
                                               animated=True)
            else:
                self.lbl_current_time_text.set(color=Colors.white(),
                                               animated=True)

            if self.currentVehicle.value == 0 and self.lastLapIsValid and sim_info.physics.numberOfTyresOut >= 4:
                self.lastLapIsValid = False

            if self.spline.hasChanged():
                if self.currentVehicle.value == 0:
                    self.laptime.setValue(
                        round(
                            ac.getCarState(self.currentVehicle.value,
                                           acsys.CS.LapTime), 3))
                    self.lastLapTime.setValue(
                        ac.getCarState(self.currentVehicle.value,
                                       acsys.CS.LastLap))
                    gap = self.get_performance_gap(self.spline.value,
                                                   self.laptime.value)
                    if gap != False:
                        self.performance.setValue(gap)
                    if self.lastLapTime.value > 0:
                        self.lbl_last_time_text.setText(
                            self.time_splitting(self.lastLapTime.value, "yes"))
                    else:
                        self.lbl_last_time_text.setText("--:--.---")
                    # new lap
                    if self.lastLapTime.hasChanged():
                        if (
                                self.referenceLapTime.value == 0
                                or self.lastLapTime.value <
                                self.referenceLapTime.value
                        ) and self.lastLapIsValid and self.lastLapTime.value > 0 and self.lapCount < ac.getCarState(
                                0, acsys.CS.LapCount):
                            #if self.lastLapTime.value > 0:
                            #    self.lbl_last_time_text.setText(self.time_splitting(self.lastLapTime.value, "yes"))
                            #else:
                            #    self.lbl_last_time_text.setText("--:--.---")
                            self.referenceLapTime.setValue(
                                self.lastLapTime.value)
                            self.referenceLap = list(self.currentLap)
                            if len(self.referenceLap) > 2000:  # 2laps in
                                ac.console("too many laps in reference----")
                                ac.log("too many laps in reference----")
                                how_much = math.floor(
                                    len(self.referenceLap) / 1000)
                                del self.referenceLap[0:math.floor(
                                    len(self.referenceLap) / how_much)]
                            if self.currentVehicle.value == 0 and Configuration.save_delta and len(
                                    self.referenceLap) > 20:
                                thread_save = threading.Thread(
                                    target=self.save_delta)
                                thread_save.daemon = True
                                thread_save.start()

                        self.currentLap = []
                        self.lapCount = ac.getCarState(
                            self.currentVehicle.value, acsys.CS.LapCount)
                        self.lastLapIsValid = True

                    self.currentLap.append(
                        raceGaps(self.spline.value, self.laptime.value))

                    self.best_lap_time = self.referenceLapTime.value
                    self.performance_display = self.performance.value
                else:
                    gap = self.get_performance_gap(
                        self.spline.value,
                        self.last_lap_start[self.currentVehicle.value] -
                        session_time_left)
                    if gap != False:
                        self.performance_display = gap
                    #else:
                    #    self.performance_display = ac.getCarState(self.currentVehicle.value, acsys.CS.PerformanceMeter)
                    self.best_lap_time = ac.getCarState(
                        self.currentVehicle.value, acsys.CS.BestLap)
                    last_lap = ac.getCarState(self.currentVehicle.value,
                                              acsys.CS.LastLap)
                    if last_lap > 0:
                        self.lbl_last_time_text.setText(
                            self.time_splitting(last_lap, "yes"))
                    else:
                        self.lbl_last_time_text.setText("--:--.---")

            #update rate
            self.TimeLeftUpdate.setValue(int(session_time_left / 500))
            if self.TimeLeftUpdate.hasChanged():
                # update graphics

                # position
                if self.session.value != 2:
                    pos = self.get_standings_position(
                        self.currentVehicle.value)
                else:
                    pos = self.get_race_standings_position(
                        self.currentVehicle.value)
                if pos > self.numCars:
                    pos = self.numCars

                if Colors.multiCarsClasses:
                    # Position in class
                    pos_class = self.get_race_standings_position_in_class(
                        self.currentVehicle.value)
                    self.lbl_position_text.setText(str(pos_class[0]))
                    self.lbl_position_text_shadow.setText(str(pos_class[0]))
                    self.lbl_position_total_text.setText("/{0}".format(
                        pos_class[1]))
                    self.lbl_position_total_text_shadow.setText("/{0}".format(
                        pos_class[1]))
                    # Position in overall
                    self.lbl_position_text_multi.setText(str(pos)).show()
                    self.lbl_position_text_multi_shadow.setText(
                        str(pos)).show()
                    self.lbl_position_total_text_multi.setText("/{0}".format(
                        self.numCars)).show()
                    self.lbl_position_total_text_multi_shadow.setText(
                        "/{0}".format(self.numCars)).show()
                else:
                    # Position in overall
                    self.lbl_position_text.setText(str(pos))
                    self.lbl_position_text_shadow.setText(str(pos))
                    self.lbl_position_total_text.setText("/{0}".format(
                        self.numCars))
                    self.lbl_position_total_text_shadow.setText("/{0}".format(
                        self.numCars))
                    self.lbl_position_text_multi.hide()
                    self.lbl_position_text_multi_shadow.hide()
                    self.lbl_position_total_text_multi.hide()
                    self.lbl_position_total_text_multi_shadow.hide()

                # flags
                flag = game_data.flag
                if flag == 1:
                    # AC_BLUE_FLAG Flag
                    self.lbl_flag.set(background=Colors.blue_flag()).show()
                elif flag == 2:
                    # AC_YELLOW_FLAG Flag
                    self.lbl_flag.set(background=Colors.
                                      timer_border_yellow_flag_bg()).show()
                    self.last_yellow_flag_end = session_time_left
                elif flag == 3 or flag == 6:
                    # AC_BLACK_FLAG,AC_PENALTY_FLAG
                    self.lbl_flag.set(background=Colors.black()).show()
                elif flag == 4:
                    # AC_WHITE_FLAG
                    self.lbl_flag.set(background=Colors.white(bg=True)).show()
                elif ac.getCarState(self.currentVehicle.value,
                                    acsys.CS.RaceFinished) == 1:  #flag == 5
                    # AC_CHECKERED_FLAG
                    self.lbl_flag.set(background=Colors.flag_finish()).show()
                elif self.last_yellow_flag_end != False and self.last_yellow_flag_end - 4000 <= session_time_left:
                    # Green flag
                    self.lbl_flag.set(
                        background=Colors.timer_border_bg()).show()
                else:
                    self.lbl_flag.hide()

                if self.best_lap_time > 0:
                    self.lbl_best_time_text.setText(
                        self.time_splitting(self.best_lap_time, "yes"))
                else:
                    self.lbl_best_time_text.setText("--:--.---")
                if self.best_lap_time > 0:  # and self.currentVehicle.value == 0
                    time_prefix = "+"
                    color = Colors.delta_neutral()
                    if self.performance_display >= 10:
                        time_prefix = "+"
                        color = Colors.delta_positive()
                    elif self.performance_display <= -10:
                        time_prefix = "-"
                        color = Colors.delta_negative()
                    self.lbl_delta_bg.set(background=color, animated=True)
                    txt_delta = time_prefix + self.time_splitting_delta(
                        abs(self.performance_display))
                    self.lbl_delta_text.set(
                        font_size=self.font_size +
                        self.rowHeight.value * 3 / 38 -
                        ((len(txt_delta) - 5) * self.rowHeight.value * 4 / 38),
                        animated=True).setText(txt_delta)
                    if self.performance_display < self.best_lap_time:
                        self.lbl_prediction_time_text.setText(
                            self.time_splitting(
                                self.best_lap_time + self.performance_display,
                                "yes"))
                    else:
                        self.lbl_prediction_time_text.setText("--:--.---")
                else:
                    self.lbl_delta_bg.set(background=Colors.delta_neutral(),
                                          animated=True)
                    self.lbl_delta_text.set(font_size=self.font_size +
                                            self.rowHeight.value * 4 / 38,
                                            animated=True).setText("-.--")
                    self.lbl_prediction_time_text.setText("--:--.---")
Esempio n. 28
0
 def getDriverString(self):
     return str(self.carId) + ' : ' + ac.getDriverName(self.carId)
Esempio n. 29
0
def updateSharedMemory():
    global sharedMem
    global packetID

    sharedmem = sharedMem.getsharedmem()
    sharedmem.packetID = -1
    sharedmem.numVehicles = ac.getCarsCount()
    sharedmem.focusVehicle = ac.getFocusedCar()

    carIds = range(0, ac.getCarsCount(), 1)

    for carId in carIds:
        if str(ac.getCarName(carId)) == '-1':
            break
        else:
            sharedmem.vehicleInfo[carId].carId = carId
            sharedmem.vehicleInfo[carId].driverName = ac.getDriverName(
                carId).encode('utf-8')
            sharedmem.vehicleInfo[carId].carModel = ac.getCarName(
                carId).encode('utf-8')
            sharedmem.vehicleInfo[carId].speedMS = ac.getCarState(
                carId, acsys.CS.SpeedMS)
            sharedmem.vehicleInfo[carId].bestLapMS = ac.getCarState(
                carId, acsys.CS.BestLap)
            sharedmem.vehicleInfo[carId].lapCount = ac.getCarState(
                carId, acsys.CS.LapCount)
            sharedmem.vehicleInfo[carId].currentLapInvalid = ac.getCarState(
                carId, acsys.CS.LapInvalidated)
            sharedmem.vehicleInfo[carId].currentLapTimeMS = ac.getCarState(
                carId, acsys.CS.LapTime)
            sharedmem.vehicleInfo[carId].lastLapTimeMS = ac.getCarState(
                carId, acsys.CS.LastLap)
            sharedmem.vehicleInfo[carId].worldPosition = ac.getCarState(
                carId, acsys.CS.WorldPosition)
            sharedmem.vehicleInfo[carId].isCarInPitline = ac.isCarInPitline(
                carId)
            sharedmem.vehicleInfo[carId].isCarInPit = ac.isCarInPit(carId)
            sharedmem.vehicleInfo[
                carId].carLeaderboardPosition = ac.getCarLeaderboardPosition(
                    carId)
            sharedmem.vehicleInfo[
                carId].carRealTimeLeaderboardPosition = ac.getCarRealTimeLeaderboardPosition(
                    carId)
            sharedmem.vehicleInfo[carId].splinePosition = ac.getCarState(
                carId, acsys.CS.NormalizedSplinePosition)
            sharedmem.vehicleInfo[carId].isConnected = ac.isConnected(carId)

            if libInit == 1 and carId == 0:
                sharedmem.vehicleInfo[carId].suspensionDamage[
                    0] = funcGetSuspensionDamage(carId, 0)
                sharedmem.vehicleInfo[carId].suspensionDamage[
                    1] = funcGetSuspensionDamage(carId, 1)
                sharedmem.vehicleInfo[carId].suspensionDamage[
                    2] = funcGetSuspensionDamage(carId, 2)
                sharedmem.vehicleInfo[carId].suspensionDamage[
                    3] = funcGetSuspensionDamage(carId, 3)
                sharedmem.vehicleInfo[
                    carId].engineLifeLeft = funcGetEngineLifeLeft(carId)
                sharedmem.vehicleInfo[carId].tyreInflation[
                    0] = funcGetTyreInflation(carId, 0)
                sharedmem.vehicleInfo[carId].tyreInflation[
                    1] = funcGetTyreInflation(carId, 1)
                sharedmem.vehicleInfo[carId].tyreInflation[
                    2] = funcGetTyreInflation(carId, 2)
                sharedmem.vehicleInfo[carId].tyreInflation[
                    3] = funcGetTyreInflation(carId, 3)

    packetID = packetID + 1
    sharedmem.packetID = packetID
Esempio n. 30
0
# is car in the pit lane
current_inpit = 0

# was car in the pit lane on the current lap
current_lap_inpit = 0

# current lap number
lapnumber = ac.getCarState(0, acsys.CS.LapCount)

# last lap time
last_lap = 0

# current date and file name
now = datetime.date.today()
driver_name = ac.getDriverName(0)
track_name = ac.getTrackName(0)
car = ac.getCarName(0)

# file name
file_name = time.strftime(
    '%Y%m%d%H%M%S',
    time.localtime()) + "_" + driver_name + "_" + track_name + ".csv"

# get lap time on this lap
get_laptime = 0

# initiate empty lists
time_list = []
lap_list = []
pit_list = []
Esempio n. 31
0
def getGeneralDataForCar(carNumber):
    res = dict()
    res['driverName'] = ac.getDriverName(carNumber)
    res['carName'] = ac.getCarName(carNumber)
    return res
Esempio n. 32
0
clap_top_speed = 0
llap_top_speed = 0
tspeed_session = 0
l_tspeed_session = 0
l_tspeed_llap = 0
l_tspeed_clap = 0
l_q = 0
l_fuel = 0
l_session_type = 0
session_type = 0  # 0 = practice, 1 = quali, 2 = race, updates each graphic step
session = [
    'Practice', 'Qualify', 'Race', 'Hotlap', 'Time Attack', 'Drift', 'Drag'
]

#Session ID
drivername = ac.getDriverName(0)  #info.static.playerName
drivername = drivername.replace(" ", "")
trackname = ac.getTrackName(0)  #info.static.track
carname = ac.getCarName(0)  #info.static.carModel
currenttime = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
sessionid = "{a}_{b}_{c}_{d}".format(a=drivername,
                                     b=currenttime,
                                     c=trackname,
                                     d=carname)

#Output file name and directory definition
try:
    sessionstarttime = datetime.datetime.now().strftime(' %b, %d, %Y %H %M %S')
    targetdir = os.path.dirname(__file__) + '/TESTS/'
    targetname = "{d}Session from {t}.txt".format(d=targetdir,
                                                  t=sessionstarttime)
Esempio n. 33
0
File: nChat.py Progetto: nuggs/nChat
import acsys
import math
import random

appWindow = 0
inputWindow = 0
textInput = 0
messages = []
lines = []
updateTrans = 1001
currentTrans = 0
updateText = 3001
currentText = 0
maxLines = 6
title = None
driver = ac.getDriverName(0).strip()

def acMain(ac_version):
    global textInput, appWindow, inputWindow, messages, lines, maxLines
    appWindow = ac.newApp('nChat')
    inputWindow = ac.newApp('nInput')

    ac.setSize(appWindow, 500, 100)
    ac.drawBorder(appWindow, 0)
    ac.setTitle(appWindow, '')
    ac.setIconPosition(appWindow, -9000, 0)
    ac.setBackgroundOpacity(appWindow, 0)

    ac.setSize(inputWindow, 435, 62)
    ac.drawBorder(inputWindow, 0)
    ac.setTitle(inputWindow, '')
Esempio n. 34
0
 def name(self):
     return ac.getDriverName(self._player)
Esempio n. 35
0
File: acinfo.py Progetto: prunn/ACTV
 def onUpdate(self, sim_info, fl):
     self.session.setValue(sim_info.graphics.session)
     self.manageWindow()
     self.animate()
     if self.carsCount==0:
         self.carsCount = ac.getCarsCount()
     sessionTimeLeft=sim_info.graphics.sessionTimeLeft
     sim_info_status=sim_info.graphics.status
     self.currentVehicule.setValue(ac.getFocusedCar())        
     backupLaptime=0
     backupLastLapInPits=0
     if len(self.lapTimesArray) < self.carsCount:
         for x in range(self.carsCount):
             c = ac.getCarState(x,acsys.CS.LapCount)
             self.driversLap.append(Value(c))
             self.lapTimesArray.append(lapTimeStart(c,sessionTimeLeft,0)) 
     else:
         for x in range(self.carsCount):
             c = ac.getCarState(x,acsys.CS.LapCount)
             self.driversLap[x].setValue(c)
             if self.driversLap[x].hasChanged():
                 self.lapTimesArray[x].lap=self.driversLap[x].value
                 self.lapTimesArray[x].time=sessionTimeLeft
             if bool(ac.isCarInPitline(x)) or bool(ac.isCarInPit(x)):
                 self.lapTimesArray[x].lastpit=c
             if x == self.currentVehicule.value:
                 backupLaptime=self.lapTimesArray[x].time-sessionTimeLeft
                 self.lastLapStart = self.lapTimesArray[x].time
                 backupLastLapInPits = self.lapTimesArray[x].lastpit
     
                         
     currentVehiculeChanged=self.currentVehicule.hasChanged()
                 
     if currentVehiculeChanged or (self.fastestLapBorderActive and sessionTimeLeft < self.visible_end-2000):
         self.fastestLapBorderActive = False
         car = ac.getCarName(self.currentVehicule.value)        
         self.lbl_border.setBgColor(Colors.colorFromCar(car))           
         
     if sim_info_status == 2:
         #LIVE
         strOffset = "  "
         #self.nameOffset=14
         if self.session.value != 2 :
             #NOT RACE
             #qtime 
             self.fastestLap.setValue(fl)         
             bestlap = ac.getCarState(self.currentVehicule.value,acsys.CS.BestLap)
             isInPit = (bool(ac.isCarInPitline(self.currentVehicule.value)) or bool(ac.isCarInPit(self.currentVehicule.value)))
             LapCount = ac.getCarState(self.currentVehicule.value,acsys.CS.LapCount)
             if self.lastLap != LapCount:
                 self.lastLap = LapCount
                 self.firstLapStarted=False
                 if self.currentVehicule.value==0:
                     self.lastLapStart = sessionTimeLeft
             curLapTime = ac.getCarState(self.currentVehicule.value, acsys.CS.LapTime)
             if curLapTime == 0 and backupLaptime > 0 and self.minLapCount > 0:
                 curLapTime = backupLaptime
             if curLapTime > 0:
                 self.firstLapStarted=True
             #if self.minLapCount == 0 and self.firstLapStarted and ((self.lastLapTime > curLapTime and curLapTime < 1000) or self.lastLapStart==10000):
             #    self.lastLapStart = sessionTimeLeft                  
             self.lastLapTime = curLapTime
                               
             if isInPit :
                 self.lastLapInPit = LapCount
                 self.lastTimeInPit = sessionTimeLeft
             if self.currentVehicule.value==0 and sim_info.physics.numberOfTyresOut >= 4 and self.lapCanBeInvalidated:
                 self.lastLapInvalidated = LapCount
             if isInPit and self.minLapCount == 0:
                 self.lastLapInvalidated = -1
             if self.sectorCount < 0:
                 self.sectorCount = sim_info.static.sectorCount    
             
             if self.fastestLap.value > 0:
                 for x in range(self.carsCount): 
                     c = ac.getCarState(x,acsys.CS.BestLap)
                     if self.fastestLap2.value == 0 or (c > 0 and c < self.fastestLap2.value):               
                         self.fastestLap2.setValue(c)
                         self.fastestLapSectors = ac.getLastSplits(x)
             else:
                 self.fastestLapSectors = [0,0,0,0,0,0]
                         
             #lapInvalidated = bool(ac.getCarState(0, acsys.CS.LapInvalidated))
             lapInvalidated = bool(self.lastLapInvalidated==LapCount)
             if currentVehiculeChanged or self.lbl_driver_name_text.value=="":
                 self.lbl_driver_name_text.setValue(self.format_name(ac.getDriverName(self.currentVehicule.value)))
             #sector_delay = 5000
             # live or info      
             #ac.console("("+str(self.lastLapInPit)+" < "+str(LapCount)+" or "+str(self.minLapCount)+"==0) and not "+str(lapInvalidated)+" and ("+str(self.lastTimeInPit)+"==0 or "+str(self.lastTimeInPit)+" > "+str(self.lastLapStart)+")")            
             if ((self.lastLapStart < 0 and self.minLapCount > 0) or (self.minLapCount == 0 and lapInvalidated)) and self.session.value != 0:                    
                 self.lbl_driver_name_visible.setValue(0)
                 self.lbl_timing_visible.setValue(0)  
                 self.lbl_split.hideText()  
                 self.info_position.hide()
                 self.info_position_lead.hide()          
             elif (self.lastLapInPit < LapCount or self.minLapCount==0) and not lapInvalidated and (self.lastTimeInPit==0 or self.lastTimeInPit > self.lastLapStart or self.minLapCount==0) :
                 
                 if self.currentVehicule.value == 0:
                     sector = sim_info.graphics.currentSectorIndex
                 else:
                     sector = self.getSector()
                 
                 self.lbl_driver_name_visible.setValue(1)
                 self.lbl_timing_visible.setValue(1)  
                 
                 #lapTime = ac.getCarState(self.currentVehicule.value, acsys.CS.LapTime)
                 if self.currentVehicule.value == 0:
                     lastLap = sim_info.graphics.iLastTime
                 else: 
                     lastLap=0                       
                     lastSplits = ac.getLastSplits(self.currentVehicule.value)
                     for c in lastSplits:
                         lastLap+=c
                     if lastLap==0:
                         lastLap=ac.getCarState(self.currentVehicule.value, acsys.CS.LastLap)
                         
                 
                 traite=False
                 cur_splits = ac.getCurrentSplits(self.currentVehicule.value)
                 timeSplit=0
                 fastestSplit=0
                 i=0
                 showSplit=False
                 for c in cur_splits: 
                     if c > 0:
                         timeSplit+=c 
                         fastestSplit+=self.fastestLapSectors[i]
                         i+=1
                 fastestSplit_fin=fastestSplit
                 if i < self.sectorCount:
                     fastestSplit_fin+=self.fastestLapSectors[i]
                      
                 #Situation
                 for s in range(0,self.sectorCount):                    
                     if self.fastestLap.value > 0 and curLapTime > fastestSplit_fin - self.sector_delay:
                         #LAST_SECONDS_OF_SECTOR_X, sector == s and
                         self.info_position.hide() 
                         self.nameOffset=self.rowHeight*14/36 #14
                         if self.sectorCount-1 == sector:
                             #LAST_SECONDS_OF_SECTOR_LAP,
                             self.lbl_split.setText(self.time_splitting(self.fastestLap.value,"yes")).setColor(Colors.white()).showText()
                             self.info_position_lead.show() 
                             
                             showSplit=True
                         elif fastestSplit_fin > 0:
                             self.lbl_split.setText(self.time_splitting(fastestSplit_fin,"yes")).setColor(Colors.white()).showText()
                             self.info_position_lead.show() 
                             showSplit=True
                         break
                     if sector == s + 1 and s + 1 <= self.sectorCount and curLapTime - timeSplit <= self.sector_delay and fastestSplit > 0 :
                         #SECTOR_X_FINISHED_BEGIN_SECTOR_Y    
                         self.nameOffset=self.rowHeight*14/36 #14            
                         self.lbl_timing_text.setValue(strOffset + self.time_splitting(timeSplit,"yes")) 
                         if fastestSplit < timeSplit:
                             self.lbl_split.setText("+"+self.time_splitting(timeSplit-fastestSplit,"yes")).setColor(Colors.yellow()).showText()
                         else:
                             self.lbl_split.setText("-"+self.time_splitting(fastestSplit-timeSplit,"yes")).setColor(Colors.green()).showText()
                         self.info_position_lead.show() 
                         self.info_position.hide()
                         traite=True
                         break
                 
                 if not traite:
                     if self.sectorCount-1 == sector and self.fastestLap.value > 0 and curLapTime > self.fastestLap.value - self.sector_delay:
                         #LAST_SECONDS_OF_SECTOR_LAP,
                         self.nameOffset=self.rowHeight*14/36 #14
                         self.lbl_timing_text.setValue(strOffset + self.time_splitting(curLapTime)) 
                         self.info_position.hide()
                         #self.lbl_split.setText(self.time_splitting(self.fastestLap,"yes") + strOffset).setVisible(1)
                     elif self.lastLapInvalidated!=LapCount-1 and ((self.lastLapInPit!=LapCount-1 and sector == 0) or (self.minLapCount==0)) and curLapTime <= self.sector_delay and lastLap > 0:
                         #LAP_FINISHED_BEGIN_NEW_LAP,                       
                         pos = ac.getCarLeaderboardPosition(self.currentVehicule.value)
                         if pos == -1:
                             pos = self.getStandingsPosition(self.currentVehicule.value)                                
             
                         if pos > 1:
                             self.info_position.setColor(Colors.white()).setBgColor(Colors.grey(bg = True)).setBgOpacity(0.8)
                         else:
                             self.info_position.setColor(Colors.white()).setBgColor(Colors.red(bg = True)).setBgOpacity(0.8)
                         self.info_position.setText(str(pos))
                         self.info_position.show()
                         
                         self.nameOffset=self.rowHeight*49/36 #49
                         self.lbl_timing_text.setValue(strOffset + self.time_splitting(lastLap,"yes")) 
                         if self.fastestLap.value < lastLap:
                             self.lbl_split.setText("+"+self.time_splitting(lastLap-self.fastestLap.value,"yes")).setColor(Colors.yellow()).showText()
                         else:                            
                             self.lbl_split.setText("-"+self.time_splitting(self.getBestLap()-lastLap,"yes")).setColor(Colors.green()).showText()
                         self.info_position_lead.show() 
                         
                     else:
                         #OTHER
                         self.nameOffset=self.rowHeight*14/36 #14
                         self.lbl_timing_text.setValue(strOffset + self.time_splitting(curLapTime))  
                         self.info_position.hide()
                         if not showSplit:
                             self.lbl_split.hideText()
                             self.info_position_lead.hide()
                 self.fastestLap.changed=False
             else :                    
                 self.info_position_lead.hide()                     
                 normalizedSplinePosition = ac.getCarState(self.currentVehicule.value,acsys.CS.NormalizedSplinePosition)
                 if normalizedSplinePosition <= 0.001:
                     normalizedSplinePosition=1
                 if sessionTimeLeft > 0 and self.minLapCount==1 and normalizedSplinePosition > 0.95 and not isInPit :          
                     self.lbl_driver_name_visible.setValue(1)
                     self.nameOffset=self.rowHeight*14/36 #14
                     self.lbl_timing_visible.setValue(1)  
                     self.lbl_split.hideText()  
                     self.info_position.hide()
                     self.lbl_timing_text.setValue(strOffset + "0.0") 
                     
                 elif lapInvalidated and self.lastLapInPit < LapCount and self.minLapCount > 0 :
                     self.lbl_driver_name_visible.setValue(0)
                     self.lbl_timing_visible.setValue(0)  
                     self.lbl_split.hideText()  
                     self.info_position.hide()  
                 elif bestlap > 0 :             
                     self.lbl_driver_name_visible.setValue(1)
                     self.lbl_timing_visible.setValue(1)  
                      
                     if self.fastestLap.value < bestlap:
                         self.lbl_split.setText("+"+self.time_splitting(bestlap-self.fastestLap.value,"yes")).setColor(Colors.yellow()).showText()                           
                     else:                            
                         self.lbl_split.hideText()
                     
                     self.lbl_timing_text.setValue(strOffset + self.time_splitting(bestlap,"yes")) 
                                         
                     self.nameOffset=self.rowHeight*49/36 #49
                     #pos = sim_info.graphics.position
                     pos = ac.getCarLeaderboardPosition(self.currentVehicule.value)
                     if pos == -1:
                         pos = self.getStandingsPosition(self.currentVehicule.value) 
                     if pos > 1:
                         self.info_position.setColor(Colors.white()).setBgColor(Colors.grey(bg = True)).setBgOpacity(1)
                     else:
                         self.info_position.setColor(Colors.white()).setBgColor(Colors.red(bg = True)).setBgOpacity(1)
                     self.info_position.setText(str(pos)).show()   
                     self.lbl_position_text.setValue(str(pos))                
                         
                 elif isInPit :     
                     self.lbl_driver_name_visible.setValue(0)
                     self.lbl_timing_visible.setValue(0)  
                     self.lbl_split.hideText()  
                     self.info_position.hide()
                 else :
                     self.nameOffset=self.rowHeight*14/36 #14
                     self.lbl_driver_name_visible.setValue(1)
                     self.lbl_timing_visible.setValue(1)
                     if self.currentVehicule.value==0:
                         self.lbl_timing_text.setValue(strOffset + self.format_tire(sim_info.graphics.tyreCompound))
                     else:
                         self.lbl_timing_text.setValue(strOffset + "Out Lap")
                     self.lbl_split.hideText()
                     self.info_position.hide() 
                  
             if curLapTime <= self.sector_delay and ac.getCarState(self.currentVehicule.value, acsys.CS.LastLap) > 0 and backupLastLapInPits + 1 < ac.getCarState(x,acsys.CS.LapCount) and sessionTimeLeft < 0:
                 self.nameOffset=self.rowHeight*49/36 #49
                 self.lbl_driver_name_visible.setValue(1)
                 self.lbl_timing_visible.setValue(1)
                 self.lbl_split.showText()
                 self.info_position.show() 
                 #time vis
             self.visibilityQualif()
                 
         else:
             ################ Race ################
             self.info_position_lead.hide() 
             self.lbl_split.hideText()
             #fastest lap
             completed=0
             for x in range(self.carsCount): 
                 c = ac.getCarState(x,acsys.CS.LapCount)
                 if c > completed:
                     completed=c
             if completed <=1:
                 self.race_fastest_lap.setValue(0)
             else:
                 for i in range(self.carsCount): 
                     bl=ac.getCarState(i,acsys.CS.BestLap)
                     l = ac.getCarState(i,acsys.CS.LapCount)
                     if bl > 0 and l > self.minLapCount and (self.race_fastest_lap.value == 0 or bl < self.race_fastest_lap.value):
                         self.race_fastest_lap.setValue(bl)
                         self.race_fastest_lap_driver.setValue(i)
                     
             if self.race_fastest_lap.hasChanged() and self.race_fastest_lap.value > 0:
                 self.fastestLapBorderActive = True
                 car = ac.getCarName(self.race_fastest_lap_driver.value)        
                 self.lbl_border.setBgColor(Colors.colorFromCar(car))            
                 self.visible_end = sessionTimeLeft - 8000
                 self.lbl_driver_name_visible.setValue(1)
                 self.lbl_driver_name_text.setValue(self.format_name(ac.getDriverName(self.race_fastest_lap_driver.value)))
                 self.nameOffset=self.rowHeight*14/36 #14
                 self.lbl_timing_text.setValue(strOffset + "Fastest Lap")
                 self.lbl_timing_visible.setValue(1)
                 self.info_position.hide() 
                 self.lbl_fastest_split.setText(self.time_splitting(self.race_fastest_lap.value,"yes")).showText()
                 
             elif currentVehiculeChanged:  
                 #driver info                  
                 self.visible_end = sessionTimeLeft - 8000
                 self.lbl_driver_name_visible.setValue(1)
                 self.lbl_driver_name_text.setValue(self.format_name(ac.getDriverName(self.currentVehicule.value)))
                 self.nameOffset=self.rowHeight*49/36 #49
                 #pos = ac.getCarLeaderboardPosition(self.currentVehicule.value)
                 pos = ac.getCarRealTimeLeaderboardPosition(self.currentVehicule.value) + 1
                 if pos > 1:
                     self.info_position.setColor(Colors.white()).setBgColor(Colors.grey(bg = True)).setBgOpacity(1)
                 else:
                     self.info_position.setColor(Colors.white()).setBgColor(Colors.red(bg = True)).setBgOpacity(1)
                 self.info_position.setText(str(pos)).show() 
                 self.lbl_timing_visible.setValue(0)
                 self.lbl_fastest_split.hideText()
             elif self.visible_end == 0 or sessionTimeLeft < self.visible_end or sessionTimeLeft > 1800000:
                 self.lbl_driver_name_visible.setValue(0)
                 self.info_position.hide()
                 self.lbl_timing_visible.setValue(0)
                 self.lbl_fastest_split.hideText()
                 
             self.visibilityRace()
                 
     elif sim_info_status == 1 and self.session.value != 2:
         #Replay Qualif
         strOffset = "  "
         showSplit=False
         LapCount = ac.getCarState(self.currentVehicule.value,acsys.CS.LapCount)
         curLapTime = ac.getCarState(self.currentVehicule.value, acsys.CS.LapTime)
         isInPit = (bool(ac.isCarInPitline(self.currentVehicule.value)) or bool(ac.isCarInPit(self.currentVehicule.value)))
         if currentVehiculeChanged or self.lbl_driver_name_text.value=="":
             self.lbl_driver_name_text.setValue(self.format_name(ac.getDriverName(self.currentVehicule.value)))
         if isInPit:
             self.lbl_driver_name_visible.setValue(0)
             self.lbl_timing_visible.setValue(0)  
             self.lbl_split.hideText()  
             self.info_position.hide()
         elif curLapTime <= self.sector_delay and LapCount > 1:
             #show last lap
             self.lbl_driver_name_visible.setValue(1)
             self.lbl_timing_visible.setValue(1)
             if self.currentVehicule.value == 0:
                 lastLap = sim_info.graphics.iLastTime
             else: 
                 lastLap=0                       
                 lastSplits = ac.getLastSplits(self.currentVehicule.value)
                 for c in lastSplits:
                     lastLap+=c
                 if lastLap==0:
                     lastLap=ac.getCarState(self.currentVehicule.value, acsys.CS.LastLap)
             pos = ac.getCarLeaderboardPosition(self.currentVehicule.value)
             if pos == -1:
                 pos = self.getStandingsPosition(self.currentVehicule.value)                                
 
             if pos > 1:
                 self.info_position.setColor(Colors.white()).setBgColor(Colors.grey(bg = True)).setBgOpacity(0.8)
             else:
                 self.info_position.setColor(Colors.white()).setBgColor(Colors.red(bg = True)).setBgOpacity(0.8)
             self.info_position.setText(str(pos))
             self.info_position.show()
             self.nameOffset=self.rowHeight*49/36 #49
             self.lbl_timing_text.setValue(strOffset + self.time_splitting(lastLap,"yes")) 
             if self.fastestLap.value < lastLap:
                 self.lbl_split.setText("+"+self.time_splitting(lastLap-self.fastestLap.value,"yes")).setColor(Colors.yellow()).showText()
             else:                            
                 self.lbl_split.setText("-"+self.time_splitting(self.fastestLap.old-lastLap,"yes")).setColor(Colors.green()).showText()
             self.info_position_lead.show()
             self.fastestLap.changed=False
         elif LapCount > self.minLapCount:
             #showTiming
             self.lbl_driver_name_visible.setValue(1)
             self.lbl_timing_visible.setValue(1)
             self.info_position_lead.hide() 
             self.nameOffset=self.rowHeight*14/36 #14
             self.lbl_timing_text.setValue(strOffset + self.time_splitting(curLapTime))  
             self.info_position.hide()
             if not showSplit:
                 self.lbl_split.hideText()
                 self.info_position_lead.hide()
         else:
             #showTireInfo
             self.info_position_lead.hide() 
             self.nameOffset=self.rowHeight*14/36 #14
             self.lbl_driver_name_visible.setValue(1)
             self.lbl_timing_visible.setValue(1)
             if self.currentVehicule.value==0:
                 self.lbl_timing_text.setValue(strOffset + self.format_tire(sim_info.graphics.tyreCompound))
             else:
                 self.lbl_timing_text.setValue(strOffset + "Out Lap")
             self.lbl_split.hideText()
             self.info_position.hide()            
         
         self.visibilityQualif()
             
             
         
     elif sim_info_status == 1 and self.session.value == 2:
         #Replay Race
         todo=1
         '''
         if currentVehiculeChanged:
             self.visible_end = sessionTimeLeft - 8000
             self.lbl_driver_name_visible.setValue(1)
             self.lbl_driver_name_text.setValue(self.format_name(ac.getDriverName(self.currentVehicule.value)))
             self.nameOffset=self.rowHeight*49/36 #49
             pos = ac.getCarRealTimeLeaderboardPosition(self.currentVehicule.value) + 1
             if pos > 1:
                 self.info_position.setColor(Colors.white()).setBgColor(Colors.grey(bg = True)).setBgOpacity(1)
             else:
                 self.info_position.setColor(Colors.white()).setBgColor(Colors.red(bg = True)).setBgOpacity(1)
             self.info_position.setText(str(pos)).show() 
             self.lbl_timing_visible.setValue(0)
             self.lbl_fastest_split.hideText()
             
             if self.lbl_driver_name_visible.hasChanged():         
                 if self.lbl_driver_name_visible.value == 0:
                     self.lbl_driver_name.hide()
                     self.lbl_border.hide()
                 else:
                     self.lbl_driver_name.show()
                     self.lbl_border.show()
                 
             if self.lbl_timing_visible.hasChanged():         
                 if self.lbl_timing_visible.value == 0:
                     self.lbl_timing.hide()
                 else:
                     self.lbl_timing.show()
                     
             if self.lbl_driver_name_text.hasChanged():
                 self.lbl_driver_name.setText(self.lbl_driver_name_text.value)  
             if self.lbl_timing_text.hasChanged():
                 self.lbl_timing.setText(self.lbl_timing_text.value,hidden=bool(self.lbl_timing_height < 30)) 
         '''
     else:
         #REPLAY
         self.resetVisibility()