Beispiel #1
0
 def isVehicleInAOI(matrix):
     ownPos = Math.Matrix(BigWorld.camera().invViewMatrix).translation
     entryPos = Math.Matrix(matrix).translation
     return (ownPos.x - entryPos.x)**2 + (ownPos.z -
                                          entryPos.z)**2 < AOI_ESTIMATE**2
 def getVehicleSpaceMatrix(vehicle):
     toVehSpace = Math.Matrix(vehicle.mover.matrix)
     toVehSpace.invert()
     return toVehSpace
Beispiel #3
0
 def __init__(self, modelName='helpers/models/position_gizmo.model'):
     self.model = BigWorld.Model(modelName)
     BigWorld.player().addModel(self.model)
     self.motor = BigWorld.Servo(Math.Matrix())
     self.model.addMotor(self.motor)
def fromHangarVehicleToWorldCoords(hangarVehicleCoords):
    compoundModel = g_currentVehicle.hangarSpace.space.getVehicleEntity().appearance.compoundModel
    modelMatrix = Math.Matrix(compoundModel.matrix)
    return modelMatrix.applyPoint(hangarVehicleCoords)
Beispiel #5
0
def testPoint(pos, color):
    matrix = Math.Matrix()
    matrix.translation = pos
    BigWorld.addPoint('Test', matrix, color, True)
Beispiel #6
0
 def __getAlignedToPointPosition(self, rotationMat):
     dirVector = Math.Vector3(0, 0, self.__rotationRadius)
     camMat = Math.Matrix(self.__cam.invViewProvider.a)
     point = camMat.applyPoint(dirVector)
     return point + rotationMat.applyVector(-dirVector)
Beispiel #7
0
    def __init__(self):
        userPrefs = Settings.g_instance.userPrefs
        if not userPrefs.has_key(Settings.KEY_REPLAY_PREFERENCES):
            userPrefs.write(Settings.KEY_REPLAY_PREFERENCES, '')
        self.__settings = userPrefs[Settings.KEY_REPLAY_PREFERENCES]
        self.__fileName = None
        self.__replayCtrl = BigWorld.WGReplayController()
        self.__replayCtrl.replayFinishedCallback = self.onReplayFinished
        self.__replayCtrl.controlModeChangedCallback = self.onControlModeChanged
        self.__replayCtrl.ammoButtonPressedCallback = self.__onAmmoButtonPressed
        self.__replayCtrl.playerVehicleIDChangedCallback = self.onPlayerVehicleIDChanged
        self.__replayCtrl.clientVersionDiffersCallback = self.onClientVersionDiffers
        self.__replayCtrl.battleChatMessageCallback = self.onBattleChatMessage
        self.__replayCtrl.lockTargetCallback = self.onLockTarget
        self.__replayCtrl.cruiseModeCallback = self.onSetCruiseMode
        self.__replayCtrl.equipmentIdCallback = self.onSetEquipmentId
        self.__replayCtrl.warpFinishedCallback = self.__onTimeWarpFinished
        self.__replayCtrl.sniperModeCallback = self.onSniperModeChanged
        self.__isAutoRecordingEnabled = False
        self.__quitAfterStop = False
        self.__isPlayingPlayList = False
        self.__playList = []
        self.__isFinished = False
        self.__isMenuShowed = False
        self.__updateGunOnTimeWarp = False
        self.__isBattleSimulation = False
        battleSimulationSection = userPrefs[_BATTLE_SIMULATION_KEY_PATH]
        if battleSimulationSection is not None:
            self.__isBattleSimulation = battleSimulationSection.asBool
        self.__playerDatabaseID = 0
        self.__serverSettings = dict()
        if isPlayerAccount():
            self.__playerDatabaseID = BigWorld.player().databaseID
        self.__playbackSpeedModifiers = (0.0, 0.0625, 0.125, 0.25, 0.5, 1.0,
                                         2.0, 4.0, 8.0, 16.0)
        self.__playbackSpeedModifiersStr = ('0', '1/16', '1/8', '1/4', '1/2',
                                            '1', '2', '4', '8', '16')
        self.__playbackSpeedIdx = self.__playbackSpeedModifiers.index(1.0)
        self.__savedPlaybackSpeedIdx = self.__playbackSpeedIdx
        self.__gunWasLockedBeforePause = False
        self.__wasVideoBeforeRewind = False
        self.__videoCameraMatrix = Math.Matrix()
        self.__replayDir = './replays'
        self.__replayCtrl.clientVersion = BigWorld.wg_getProductVersion()
        self.__enableTimeWarp = False
        self.__isChatPlaybackEnabled = True
        self.__warpTime = -1.0
        self.__equipmentId = None
        self.__rewind = False
        self.replayTimeout = 0
        self.__arenaPeriod = -1
        self.enableAutoRecordingBattles(True)
        self.onCommandReceived = Event.Event()
        self.onAmmoSettingChanged = Event.Event()
        self.onStopped = Event.Event()
        if constants.IS_DEVELOPMENT:
            try:
                import development.replay_override
            except:
                pass

        return
Beispiel #8
0
 def update(self, matrix, time):
     self.__animMat.keyframes = ((0.0, Math.Matrix(self.__animMat)), (time, matrix))
     self.__animMat.time = 0.0
Beispiel #9
0
 def lockSoundMatrix(self):
     if self.__manualSound is not None:
         provider = self.__manualSound.matrixProvider
         self.__manualSound.matrixProvider = Math.Matrix(provider)
     return
 def overridePose(self, pos, rot):
     transform = Math.Matrix()
     transform.setRotateYPR(rot)
     transform.translation = self._cam._checkSpaceBounds(
         BigWorld.camera().position, pos)
     self._cam.setViewMatrix(transform)
Beispiel #11
0
 def __init__(self, avatar):
     m = Math.Matrix()
     m.setIdentity()
     self.__animMat = Math.MatrixAnimation()
     self.__animMat.keyframes = ((0.0, m),)
Beispiel #12
0
def setupSplineTracks(fashion, vDesc, chassisModel, prereqs):
    splineDesc = vDesc.chassis.splineDesc
    resultTracks = None
    if splineDesc is not None:
        leftSpline = None
        rightSpline = None
        segmentModelLeft = segmentModelRight = segment2ModelLeft = segment2ModelRight = None
        modelName = splineDesc.segmentModelLeft
        try:
            segmentModelLeft = prereqs[modelName]
        except Exception:
            debug_utils.LOG_ERROR("can't load track segment model <%s>" %
                                  modelName)

        modelName = splineDesc.segmentModelRight
        try:
            segmentModelRight = prereqs[modelName]
        except Exception:
            debug_utils.LOG_ERROR("can't load track segment model <%s>" %
                                  modelName)

        modelName = splineDesc.segment2ModelLeft
        if modelName is not None:
            try:
                segment2ModelLeft = prereqs[modelName]
            except Exception:
                debug_utils.LOG_ERROR("can't load track segment 2 model <%s>" %
                                      modelName)

        modelName = splineDesc.segment2ModelRight
        if modelName is not None:
            try:
                segment2ModelRight = prereqs[modelName]
            except Exception:
                debug_utils.LOG_ERROR("can't load track segment 2 model <%s>" %
                                      modelName)

        if segmentModelLeft is not None and segmentModelRight is not None:
            identityMatrix = Math.Matrix()
            identityMatrix.setIdentity()
            if splineDesc.leftDesc is not None:
                leftSpline = BigWorld.wg_createSplineTrack(
                    fashion, chassisModel, splineDesc.leftDesc,
                    splineDesc.segmentLength, segmentModelLeft,
                    splineDesc.segmentOffset, segment2ModelLeft,
                    splineDesc.segment2Offset, _ROOT_NODE_NAME,
                    splineDesc.atlasUTiles, splineDesc.atlasVTiles)
                if leftSpline is not None:
                    chassisModel.root.attach(leftSpline, identityMatrix, True)
            if splineDesc.rightDesc is not None:
                rightSpline = BigWorld.wg_createSplineTrack(
                    fashion, chassisModel, splineDesc.rightDesc,
                    splineDesc.segmentLength, segmentModelRight,
                    splineDesc.segmentOffset, segment2ModelRight,
                    splineDesc.segment2Offset, _ROOT_NODE_NAME,
                    splineDesc.atlasUTiles, splineDesc.atlasVTiles)
                if rightSpline is not None:
                    chassisModel.root.attach(rightSpline, identityMatrix, True)
            fashion.setSplineTrack(leftSpline, rightSpline)
        resultTracks = SplineTracks(leftSpline, rightSpline)
    return resultTracks
Beispiel #13
0
def makePositionMatrix(position):
    matrix = Math.Matrix()
    matrix.setTranslate(position)
    return matrix
Beispiel #14
0
 def isVehicleInAOI(matrix):
     ownPos = Math.Matrix(BigWorld.camera().invViewMatrix).translation
     entryPos = Math.Matrix(matrix).translation
     return bool(
         abs(ownPos.x - entryPos.x) < AOI_ESTIMATE
         and abs(ownPos.z - entryPos.z) < AOI_ESTIMATE)
Beispiel #15
0
def makePositionMP(position):
    provider = Math.WGReplayAwaredSmoothTranslationOnlyMP()
    matrix = Math.Matrix()
    matrix.setTranslate(position)
    provider.source = matrix
    return provider
Beispiel #16
0
 def setToVehicleDirection(self):
     matrix = Math.Matrix(self.getTargetMProv())
     self.setYawPitch(matrix.yaw, matrix.pitch)
Beispiel #17
0
def convertToLastSpottedVehicleMP(matrix):
    converted = Math.WGReplayAwaredSmoothTranslationOnlyMP()
    converted.source = Math.Matrix(matrix.source)
    return converted
Beispiel #18
0
 def __cameraUpdate(self):
     if not (self.__autoUpdateDxDyDz.x == 0.0 and self.__autoUpdateDxDyDz.y
             == 0.0 and self.__autoUpdateDxDyDz.z == 0.0):
         self.__update(self.__autoUpdateDxDyDz.x, self.__autoUpdateDxDyDz.y,
                       self.__autoUpdateDxDyDz.z)
     player = BigWorld.player()
     vehicle = player.getVehicleAttached()
     inertDt = deltaTime = self.measureDeltaTime()
     replayCtrl = BattleReplay.g_replayCtrl
     if replayCtrl.isPlaying:
         repSpeed = replayCtrl.playbackSpeed
         if repSpeed == 0.0:
             inertDt = 0.01
             deltaTime = 0.0
         else:
             inertDt = deltaTime = deltaTime / repSpeed
     self.__aimingSystem.update(deltaTime)
     virginShotPoint = self.__aimingSystem.getThirdPersonShotPoint()
     delta = self.__inputInertia.positionDelta
     sign = delta.dot(Vector3(0, 0, 1))
     self.__inputInertia.update(inertDt)
     delta = (delta - self.__inputInertia.positionDelta).length
     if delta != 0.0:
         self.__cam.setScrollDelta(math.copysign(delta, sign))
     FovExtended.instance().setFovByMultiplier(
         self.__inputInertia.fovZoomMultiplier)
     unshakenPos = self.__inputInertia.calcWorldPos(
         self.__aimingSystem.matrix)
     vehMatrix = Math.Matrix(self.__aimingSystem.vehicleMProv)
     vehiclePos = vehMatrix.translation
     fromVehicleToUnshakedPos = unshakenPos - vehiclePos
     deviationBasis = mathUtils.createRotationMatrix(
         Vector3(self.__aimingSystem.yaw, 0, 0))
     impulseDeviation, movementDeviation, oscillationsZoomMultiplier = self.__updateOscillators(
         deltaTime)
     relCamPosMatrix = mathUtils.createTranslationMatrix(impulseDeviation +
                                                         movementDeviation)
     relCamPosMatrix.postMultiply(deviationBasis)
     relCamPosMatrix.translation += fromVehicleToUnshakedPos
     upRotMat = mathUtils.createRotationMatrix(
         Vector3(
             0, 0, -impulseDeviation.x *
             self.__dynamicCfg['sideImpulseToRollRatio'] -
             self.__noiseOscillator.deviation.z))
     upRotMat.postMultiply(relCamPosMatrix)
     self.__cam.up = upRotMat.applyVector(Vector3(0, 1, 0))
     relTranslation = relCamPosMatrix.translation
     shotPoint = self.__calcFocalPoint(virginShotPoint, deltaTime)
     vehToShotPoint = shotPoint - vehiclePos
     self.__setCameraAimPoint(vehToShotPoint)
     self.__setCameraPosition(relTranslation)
     replayCtrl = BattleReplay.g_replayCtrl
     if replayCtrl.isPlaying and replayCtrl.isControllingCamera:
         aimOffset = replayCtrl.getAimClipPosition()
         if not BigWorld.player().isForcedGuiControlMode() and GUI.mcursor(
         ).inFocus:
             GUI.mcursor().position = aimOffset
     else:
         aimOffset = self.__calcAimOffset(oscillationsZoomMultiplier)
         if replayCtrl.isRecording:
             replayCtrl.setAimClipPosition(aimOffset)
     self.__cam.aimPointClipCoords = aimOffset
     self.__aimOffset = aimOffset
     if self.__shiftKeySensor is not None:
         self.__shiftKeySensor.update(1.0)
         if self.__shiftKeySensor.currentVelocity.lengthSquared > 0.0:
             self.shiftCamPos(self.__shiftKeySensor.currentVelocity)
             self.__shiftKeySensor.currentVelocity = Math.Vector3()
     return 0.0
Beispiel #19
0
 def __applyScale(self, transformComponent, radius):
     scaleMatrix = Math.Matrix()
     scaleMatrix.setScale(Math.Vector3(radius, 1.0, radius))
     matrix = transformComponent.transform
     matrix.preMultiply(scaleMatrix)
     transformComponent.transform = matrix
Beispiel #20
0
 def __addPointEntry(self, symbol, sectorBase):
     matrix = Math.Matrix()
     matrix.setTranslate(sectorBase.position)
     return self._addEntryEx(sectorBase.baseID, symbol, _EPIC_TEAM_POINTS, matrix, True)
def fromWorldCoordsToHangarVehicle(worldCoords):
    compoundModel = g_currentVehicle.hangarSpace.space.getVehicleEntity().appearance.compoundModel
    modelMat = Math.Matrix(compoundModel.matrix)
    modelMat.invert()
    return modelMat.applyPoint(worldCoords)
Beispiel #22
0
 def __addRPEntry(self, symbol, pos):
     position = (pos.x, 0, pos.y)
     matrix = Math.Matrix()
     matrix.setTranslate(position)
     return self._addEntry(symbol, _EPIC_TEAM_POINTS, matrix=matrix, active=True)
Beispiel #23
0
    def readCurrentSettings(self, quiet=True):
        super(ConfigInterface, self).readCurrentSettings(quiet)
        self.settings = loadJson(self.ID, 'settings', self.settings,
                                 self.configPath)
        self.modelsData['models'].clear()
        self.modelsData['selected'] = selectedData = loadJson(
            self.ID, 'remodsCache', self.modelsData['selected'],
            self.configPath)
        remodTanks = set()
        for root, _, fNames in os.walk(self.configPath + 'remods/'):
            for fName in fnmatch.filter(fNames, '*.json'):
                sName = fName.split('.')[0]
                confDict = loadJson(self.ID, sName, {}, root, encrypted=True)
                if not confDict:
                    print self.ID + ': error while reading', fName + '.'
                    continue
                settingsDict = self.settings.setdefault(
                    sName, {team: confDict[team]
                            for team in self.teams})
                self.modelsData['models'][
                    sName] = pRecord = self.modelDescriptor
                pRecord['name'] = sName
                pRecord['message'] = confDict.get('message', '')
                settingsDict['whitelist'] = pRecord[
                    'whitelist'] = whitelist = remDups(
                        x.strip() for x in settingsDict.get(
                            'whitelist', confDict['whitelist']) if x.strip())
                for xmlName in whitelist:
                    remodTanks.add(xmlName)
                    for team in selectedData:
                        if xmlName not in selectedData[
                                team] or selectedData[team][xmlName] is None:
                            if settingsDict[team]:
                                selectedData[team][xmlName] = sName
                            else:
                                selectedData[team][xmlName] = None
                if self.data['isDebug']:
                    if not whitelist:
                        print self.ID + ': empty whitelist for', sName + '.'
                    else:
                        print self.ID + ': whitelist for', sName + ':', whitelist
                for key, data in pRecord.iteritems():
                    if key in ('name', 'message', 'whitelist'):
                        continue
                    if key == 'common':
                        confSubDict = confDict
                    else:
                        confSubDict = confDict.get(key)
                    if not confSubDict:
                        continue
                    if 'undamaged' in data:
                        data['undamaged'] = confSubDict['undamaged']
                    if 'AODecals' in data and 'AODecals' in confSubDict and 'hullPosition' in confSubDict:
                        data['AODecals'] = []
                        for subList in confSubDict['AODecals']:
                            m = Math.Matrix()
                            for strNum, row in enumerate(subList):
                                for colNum, elemNum in enumerate(row):
                                    m.setElement(strNum, colNum, elemNum)
                            data['AODecals'].append(m)
                        data['hullPosition'] = confSubDict['hullPosition']
                    if 'camouflage' in data and 'exclusionMask' in confSubDict.get(
                            'camouflage', {}):
                        data['camouflage']['exclusionMask'] = confSubDict[
                            'camouflage']['exclusionMask']
                        if 'tiling' in confSubDict['camouflage']:
                            data['camouflage']['tiling'] = confSubDict[
                                'camouflage']['tiling']
                    elif key == 'common' and self.data['isDebug']:
                        print self.ID + ': default camomask not found for', sName
                    if 'emblemSlots' in data:
                        data['emblemSlots'] = slots = []
                        for subDict in confSubDict.get('emblemSlots', []):
                            if subDict['type'] not in AES:
                                print g_config.ID + ': not supported emblem slot type:', subDict[
                                    'type'] + ', expected:', AES
                                continue
                            descr = EmblemSlot(
                                Math.Vector3(tuple(subDict['rayStart'])),
                                Math.Vector3(tuple(subDict['rayEnd'])),
                                Math.Vector3(tuple(subDict['rayUp'])),
                                subDict['size'],
                                subDict.get('hideIfDamaged',
                                            False), subDict['type'],
                                subDict.get('isMirrored', False),
                                subDict.get('isUVProportional', True),
                                subDict.get('emblemId', None),
                                subDict.get(
                                    'slotId',
                                    c11n_constants.customizationSlotIds[key][
                                        subDict['type']][0]),
                                subDict.get('applyToFabric', True))
                            slots.append(descr)
                    if 'exhaust' in data and 'exhaust' in confSubDict:
                        if 'nodes' in confSubDict['exhaust']:
                            data['exhaust']['nodes'] = confSubDict['exhaust'][
                                'nodes']
                        if 'pixie' in confSubDict['exhaust']:
                            data['exhaust']['pixie'] = confSubDict['exhaust'][
                                'pixie']
                    if key == 'chassis':
                        for k in chassis_params + ('chassisLodDistance', ):
                            data[k] = confSubDict[k]
                    for k in ('soundID', 'drivenJoints'):
                        if k in data and k in confSubDict:
                            data[k] = confSubDict[k]
                if self.data['isDebug']:
                    print self.ID + ': config for', sName, 'loaded.'

        for sName in self.settings.keys():
            if sName not in self.modelsData['models']:
                del self.settings[sName]

        if not self.modelsData['models']:
            if not quiet:
                print self.ID + ': no configs found, model module standing down.'
        for team in self.teams:
            for xmlName in selectedData[team].keys():
                if xmlName not in remodTanks:
                    del selectedData[team][xmlName]
                    continue
                if selectedData[team][xmlName] is None or (
                        selectedData[team][xmlName]
                        and selectedData[team][xmlName]
                        not in self.modelsData['models']):
                    selectedData[team][xmlName] = next(
                        (sName for sName in sorted(self.modelsData['models'])
                         if xmlName in self.settings[sName]['whitelist']
                         and self.settings[sName][team]), None) or ''
        loadJson(self.ID,
                 'remodsCache',
                 selectedData,
                 self.configPath,
                 True,
                 quiet=quiet)
        loadJson(self.ID,
                 'settings',
                 self.settings,
                 self.configPath,
                 True,
                 quiet=quiet)
Beispiel #24
0
 def __addRPEntry(self, symbol, position):
     matrix = Math.Matrix()
     matrix.setTranslate(position)
     entryID = self._addEntry(symbol, _EPIC_ICONS, matrix=matrix, active=True)
     return entryID
Beispiel #25
0
def lightsCreate(vehicleID, callPlace=''):
    try:
        vehicle = BigWorld.player().arena.vehicles[vehicleID]
        vEntity = BigWorld.entity(vehicleID)
        if vEntity is None:
            return
        vDesc = vEntity.typeDescriptor
        if vehicleID == BigWorld.player().playerVehicleID:
            print 'LampLights: Create at %s' % callPlace
        constNodesList = [
            TankNodeNames.TRACK_LEFT_UP_FRONT,
            TankNodeNames.TRACK_LEFT_UP_REAR,
            TankNodeNames.TRACK_RIGHT_UP_FRONT,
            TankNodeNames.TRACK_RIGHT_UP_REAR
        ]
        compoundModel = vEntity.appearance.compoundModel
        nodeListML, nodeListNL = findWheelNodes(vehicleID, 'L')
        nodeListMR, nodeListNR = findWheelNodes(vehicleID, 'R')
        fakesDict[vehicleID] = fakeDict = {}
        fakeMotorsDict[vehicleID] = fakeMotorDict = {}

        sourcesDict = {TankPartNames.CHASSIS: None, TankPartNames.HULL: None}
        for tankPartName in sourcesDict.keys():
            curSource = getattr(vDesc, tankPartName).models.undamaged
            modelSec = ResMgr.openSection(curSource)
            if modelSec is None:
                print 'LampLights: file not found:', curSource
            sourceSecStr = modelSec['nodefullVisual'].asString
            sourceSec = ResMgr.openSection(sourceSecStr + '.visual')
            if sourceSec is None:
                sourceSec = ResMgr.openSection(sourceSecStr +
                                               '.visual_processed')
            if sourceSec is None:
                print 'LampLights: visual not found for', curSource
                print callPlace
            else:
                sourcesDict[tankPartName] = sourceSec
        HullMat = math_utils.createIdentityMatrix()
        deHullMat = math_utils.createIdentityMatrix()
        if sourcesDict[TankPartNames.CHASSIS] is not None:
            deHullMat = nodeWatcher(sourcesDict[TankPartNames.CHASSIS], 'V')
            deHullMat.invert()
        for tankPartName in (TankPartNames.CHASSIS, TankPartNames.HULL):
            fakeDict[tankPartName] = BigWorld.Model('objects/fake_model.model')
            fakeDict[tankPartName +
                     'Root'] = BigWorld.Model('objects/fake_model.model')
            compoundModel.node(TankPartNames.HULL).attach(
                fakeDict[tankPartName + 'Root'],
                HullMat if 'hull' in tankPartName else deHullMat)
            if fakeMotorDict.get(tankPartName) not in tuple(
                    fakeDict[tankPartName].motors):
                fakeMotorDict[tankPartName] = BigWorld.Servo(
                    fakeDict[tankPartName + 'Root'].matrix)
                fakeDict[tankPartName].addMotor(fakeMotorDict[tankPartName])
            if fakeDict[tankPartName] not in tuple(BigWorld.models()):
                BigWorld.addModel(fakeDict[tankPartName])
        for idx, node in enumerate(nodeListNL):
            fakeDict[node] = BigWorld.Model('objects/fake_model.model')
            fakeDict[TankPartNames.CHASSIS].node('', nodeListML[idx]).attach(
                fakeDict[node])

        for idx, node in enumerate(nodeListNR):
            fakeDict[node] = BigWorld.Model('objects/fake_model.model')
            fakeDict[TankPartNames.CHASSIS].node('', nodeListMR[idx]).attach(
                fakeDict[node])

        for node in constNodesList:
            fakeDict[node] = BigWorld.Model('objects/fake_model.model')
            restoreMat = math_utils.createIdentityMatrix()
            transMat = None
            isChassis = False
            if sourcesDict[TankPartNames.HULL] is not None:
                transMat = nodeWatcher(sourcesDict[TankPartNames.HULL], node)
            if transMat is None and sourcesDict[
                    TankPartNames.CHASSIS] is not None:
                transMat = nodeWatcher(sourcesDict[TankPartNames.CHASSIS],
                                       node)
                if transMat is None:
                    transMat = nodeWatcher(sourcesDict[TankPartNames.CHASSIS],
                                           node.replace('Up', ''))
                isChassis = True
            if transMat is None and isChassis:  # wheeled
                placed = node.split('_')[-1]
                place, side = placed[:1], placed[1:]
                template = 'HP_Wheel_%s_0%s_%s' % (place, '%s', side)
                edge = None
                if side == 'Front':
                    edge = nodeWatcher(sourcesDict[TankPartNames.CHASSIS],
                                       template % 1)
                else:
                    for idx in xrange(1, 10):
                        found = nodeWatcher(sourcesDict[TankPartNames.CHASSIS],
                                            template % idx)
                        if found is None:
                            break
                        edge = found
                if edge is not None:
                    wheels = nodeListML if place == 'L' else nodeListMR
                    sign = 1 if side == 'Front' else -1
                    center = max(wheels, key=lambda x: x.translation.z * sign)
                    rotator = Math.Matrix()
                    rotator.setRotateX(-sign * 3.1415 * 3 / 4)
                    transMat = Math.Matrix()
                    transMat.setTranslate(
                        center.applyPoint(
                            rotator.applyPoint(edge.translation -
                                               center.translation)))
            if transMat is None:
                print _config.ID + ': restore Matrix not found for node', node, 'in', vDesc.hull.models.undamaged
                print callPlace
            else:
                restoreMat.setTranslate(transMat.translation)
            fakeDict[TankPartNames.HULL if not isChassis else TankPartNames.
                     CHASSIS].node('', restoreMat).attach(fakeDict[node])

        fakeDict[TankPartNames.GUN +
                 'Root'] = BigWorld.Model('objects/fake_model.model')
        compoundModel.node(TankPartNames.GUN).attach(
            fakeDict[TankPartNames.GUN + 'Root'])
        fakeDict[TankPartNames.GUN] = BigWorld.Model(
            'objects/fake_model.model')
        if fakeMotorDict.get(TankPartNames.GUN) not in tuple(
                fakeDict[TankPartNames.GUN].motors):
            fakeMotorDict[TankPartNames.GUN] = BigWorld.Servo(
                fakeDict[TankPartNames.GUN + 'Root'].matrix)
            fakeDict[TankPartNames.GUN].addMotor(
                fakeMotorDict[TankPartNames.GUN])
        if fakeDict[TankPartNames.GUN] not in tuple(BigWorld.models()):
            BigWorld.addModel(fakeDict[TankPartNames.GUN])
        fakeDict[TankPartNames.TURRET] = BigWorld.Model(
            'objects/fake_model.model')
        fakeDict[TankPartNames.TURRET +
                 'Root'] = BigWorld.Model('objects/fake_model.model')
        fakeDict[TankPartNames.TURRET +
                 'RootRoot'] = BigWorld.Model('objects/fake_model.model')
        hull_bbox_min, hull_bbox_max, _ = vDesc.hull.hitTester.bbox
        turret_pos_on_hull = vDesc.hull.turretPositions[0]
        turret_bbox_max = vDesc.turret.hitTester.bbox[1]
        gun_pos_on_turret = vDesc.turret.gunPosition
        gun_pos_on_hull = gun_pos_on_turret + turret_pos_on_hull
        gun_bbox_max = vDesc.gun.hitTester.bbox[1]
        if hull_bbox_max.y >= turret_pos_on_hull.y + turret_bbox_max.y:
            observer_pos = Math.Vector3(0, hull_bbox_max.y, 0)
            node = TankPartNames.HULL
        elif gun_pos_on_turret.y + gun_bbox_max.y >= turret_bbox_max.y:
            observer_pos = Math.Vector3(0, gun_bbox_max.y, 0)
            node = TankPartNames.GUN
        else:
            observer_pos = Math.Vector3(0, turret_bbox_max.y, 0)
            node = TankPartNames.TURRET
        mat = Math.Matrix()
        mat.setTranslate(observer_pos)
        compoundModel.node(node).attach(fakeDict[TankPartNames.TURRET +
                                                 'RootRoot'])
        if fakeMotorDict.get(TankPartNames.TURRET + 'Root') not in tuple(
                fakeDict[TankPartNames.TURRET + 'Root'].motors):
            fakeMotorDict[TankPartNames.TURRET + 'Root'] = BigWorld.Servo(
                fakeDict[TankPartNames.TURRET + 'RootRoot'].matrix)
            fakeDict[TankPartNames.TURRET + 'Root'].addMotor(
                fakeMotorDict[TankPartNames.TURRET + 'Root'])
        if fakeDict[TankPartNames.TURRET + 'Root'] not in tuple(
                BigWorld.models()):
            BigWorld.addModel(fakeDict[TankPartNames.TURRET + 'Root'])
        fakeDict[TankPartNames.TURRET + 'Root'].node('', mat).attach(
            fakeDict[TankPartNames.TURRET])

        hullLocalCenterY = (hull_bbox_min.y + hull_bbox_max.y) / 2.0
        hullLocalCenterZ = (hull_bbox_min.z + hull_bbox_max.z) / 2.0
        nodes = {
            'hullLocalPt1':
            Math.Vector3(0.0, hullLocalCenterY, hull_bbox_max.z),
            'hullLocalPt2':
            Math.Vector3(0.0, hullLocalCenterY, hull_bbox_min.z),
            'hullLocalPt3':
            Math.Vector3(hull_bbox_max.x, gun_pos_on_hull.y, hullLocalCenterZ),
            'hullLocalPt4':
            Math.Vector3(hull_bbox_min.x, gun_pos_on_hull.y, hullLocalCenterZ),
            'hullGunLocal':
            gun_pos_on_hull
        }
        for node in nodes:
            fakeDict[node] = BigWorld.Model('objects/fake_model.model')
            fakeDict[TankPartNames.HULL].node(
                '', math_utils.createTranslationMatrix(nodes[node])).attach(
                    fakeDict[node])

        lightDBDict.setdefault(vehicleID, {})
        for configDict in _config.configsDict.values():
            for name in sorted(configDict.keys()):
                try:
                    if name in ('enable', 'meta', 'attachToPlayer',
                                'attachToAlly', 'attachToEnemy'):
                        continue
                    confDict = configDict[name]
                    needToAttach = \
                        confDict['attachToPlayer'] and vehicleID == BigWorld.player().playerVehicleID or \
                        confDict['attachToEnemy'] and vehicle['team'] != BigWorld.player().team or \
                        confDict['attachToAlly'] and vehicleID != BigWorld.player().playerVehicleID and \
                        vehicle['team'] == BigWorld.player().team
                    if not needToAttach:
                        continue
                    nodeL = []
                    if '.' in name:
                        nodeL.append(confDict['place'])
                    elif confDict['place'] == 'leftFront':
                        nodeL.append(TankNodeNames.TRACK_LEFT_UP_FRONT)
                    elif confDict['place'] == 'rightFront':
                        nodeL.append(TankNodeNames.TRACK_RIGHT_UP_FRONT)
                    elif confDict['place'] == 'leftRear':
                        nodeL.append(TankNodeNames.TRACK_LEFT_UP_REAR)
                    elif confDict['place'] == 'rightRear':
                        nodeL.append(TankNodeNames.TRACK_RIGHT_UP_REAR)
                    elif confDict['place'] == 'hull':
                        nodeL.append(TankPartNames.HULL)
                    elif confDict['place'] == 'turret':
                        nodeL.append(TankPartNames.TURRET)
                    elif confDict['place'] == 'spot':
                        nodeL.extend([TankPartNames.TURRET, TankPartNames.GUN])
                        nodeL.extend(
                            ['hullLocalPt%s' % num for num in xrange(1, 5)])
                        nodeL.append('hullGunLocal')
                    elif 'wheels' in confDict['place']:
                        if 'left' in confDict['place']:
                            nodeL.extend(nodeListNL)
                        else:
                            nodeL.extend(nodeListNR)

                    nameTree = name.split('.')[:-1]
                    namesList = []
                    for curKey in lightDBDict[vehicleID].keys():
                        curTree = curKey.split('.')
                        if len(curTree) != len(nameTree) or any(
                                upperName not in curTree[depth]
                                for depth, upperName in enumerate(nameTree)):
                            continue
                        namesList.append(curKey + '.' + name.split('.')[-1])
                    if not namesList:
                        namesList = [name]
                    for fullName in namesList:
                        for node in nodeL:
                            curName = fullName + ':' + node
                            if 'model' not in confDict['type']:
                                if confDict['type'] == 'spotLight':
                                    LightSource = BigWorld.PySpotLight()
                                    LightSource.coneAngle = confDict['ca']
                                else:
                                    LightSource = BigWorld.PyOmniLight()
                                    if confDict['type'] != 'omniLight':
                                        LOG_ERROR(
                                            'Unknown type of %s: %s. Set to omniLight'
                                            % (name, confDict['type']))
                                LightSource.innerRadius = confDict[
                                    'innerRadius']
                                LightSource.outerRadius = confDict[
                                    'outerRadius']
                                LightSource.castShadows = confDict['cs']
                                LightSource.multiplier = confDict['bright']
                                if isinstance(confDict['colour'][0], tuple):
                                    if confDict['type'] != 'spotLight':
                                        FrontLightShader = Math.Vector4Animation(
                                        )
                                        FrontLightShader.duration = confDict[
                                            'dur']
                                        FrontLightShader.keyframes = confDict[
                                            'colour']
                                        LightSource.colorAnimator = FrontLightShader
                                    else:
                                        LightSource.colour = confDict[
                                            'colour'][0][1]
                                else:
                                    LightSource.colour = confDict['colour']
                            else:
                                LightSource = BigWorld.Model(confDict['path'])
                            if '.' not in name:
                                if node in fakeDict:
                                    fakeNode = fakeDict[node].node(
                                        '', computeTransform(confDict))
                            else:
                                if curName not in fakeDict:
                                    fakeDict[curName] = BigWorld.Model(
                                        'objects/fake_model.model')
                                    lightDBDict[vehicleID][curName.rsplit(
                                        '.', 1)[0]].node(node).attach(
                                            fakeDict[curName])
                                fakeNode = fakeDict[curName].node(
                                    '', computeTransform(confDict))
                            if 'model' not in confDict['type']:
                                # noinspection PyUnboundLocalVariable
                                LightSource.source = fakeNode
                            elif not LightSource.attached:
                                fakeNode.attach(LightSource)
                            lightVisible(
                                LightSource, _config.isLampsVisible
                                and name in _config.modes['constant'])
                            lightDBDict[vehicleID][curName] = LightSource

                except StandardError:
                    traceback.print_exc()
                    print name
                    print callPlace
                    print vDesc.name

    except StandardError:
        traceback.print_exc()
        print callPlace
Beispiel #26
0
 def __addProtectionZoneEntry(self, symbol, position):
     matrix = Math.Matrix()
     matrix.setTranslate(position)
     entryID = self._addEntry(symbol, _EPIC_PROTECTION_ZONE, matrix=matrix, active=True)
     self._parentObj.setEntryParameters(entryID, doClip=False, scaleType=MINIMAP_SCALE_TYPES.REAL_SCALE)
     return entryID
 def __init__(self, templateTree):
     self.input = {}
     self.templateTree = templateTree
     for id, node in self.templateTree.nodeList.items():
         self.input[id] = Math.Matrix()
         self.input[id].set(node.localMatrix)
Beispiel #28
0
def makeVehicleEntityMPCopy(vehicle):
    provider = Math.WGTranslationOnlyMP()
    provider.source = Math.Matrix(vehicle.matrix)
    return provider
Beispiel #29
0
 def isPointInsideBox(self, point):
     if not isinstance(point, Math.Vector3):
         raise TypeError('point argument must be Vector3, not {!s}'.format(
             type(point).__name__))
     return self.boundingBox._isPointInsideBox(
         Math.Matrix(self.invBounds).applyPoint(point))
Beispiel #30
0
 def __updateNodePosition(self, node, vehiclePos, waterHeight):
     if waterHeight is not None:
         toCenterShift = vehiclePos.y - (Math.Matrix(node).translation.y - node.local.translation.y)
         node.local.translation = Math.Vector3(0, waterHeight + toCenterShift, 0)
     else:
         node.local.translation = Math.Vector3(0, 0, 0)