Exemple #1
0
 def __cameraUpdate(self, allowModeChange = True):
     curTime = BigWorld.time()
     deltaTime = curTime - self.__prevTime
     self.__prevTime = curTime
     if not self.__autoUpdateDxDyDz.x == self.__autoUpdateDxDyDz.y == self.__autoUpdateDxDyDz.z == 0.0:
         self.__rotateAndZoom(self.__autoUpdateDxDyDz.x, self.__autoUpdateDxDyDz.y, self.__autoUpdateDxDyDz.z)
     self.__aimingSystem.update(deltaTime)
     localTransform, impulseTransform = self.__updateOscillators(deltaTime)
     aimMatrix = cameras.getAimMatrix(*self.__defaultAimOffset)
     camMat = Matrix(aimMatrix)
     rodMat = mathUtils.createTranslationMatrix(-self.__dynamicCfg['pivotShift'])
     antiRodMat = mathUtils.createTranslationMatrix(self.__dynamicCfg['pivotShift'])
     camMat.postMultiply(rodMat)
     camMat.postMultiply(localTransform)
     camMat.postMultiply(antiRodMat)
     camMat.postMultiply(self.__aimingSystem.matrix)
     camMat.invert()
     self.__cam.set(camMat)
     replayCtrl = BattleReplay.g_replayCtrl
     if replayCtrl.isPlaying and replayCtrl.isControllingCamera:
         aimOffset = replayCtrl.getAimClipPosition()
         binocularsOffset = aimOffset
     else:
         aimOffset = self.__calcAimOffset(impulseTransform)
         binocularsOffset = self.__calcAimOffset()
         if replayCtrl.isRecording:
             replayCtrl.setAimClipPosition(aimOffset)
     self.__aim.offset(aimOffset)
     self.__binoculars.setMaskCenter(binocularsOffset.x, binocularsOffset.y)
     player = BigWorld.player()
     if allowModeChange and (self.__isPositionUnderwater(self.__aimingSystem.matrix.translation) or player.isGunLocked):
         self.__onChangeControlMode(False)
         return -1
     return 0.0
 def __cameraUpdate(self):
     curTime = BigWorld.time()
     deltaTime = curTime - self.__prevTime
     self.__prevTime = curTime
     if not self.__autoUpdateDxDyDz.x == self.__autoUpdateDxDyDz.y == self.__autoUpdateDxDyDz.z == 0.0:
         self.__rotateAndZoom(self.__autoUpdateDxDyDz.x, self.__autoUpdateDxDyDz.y, self.__autoUpdateDxDyDz.z)
     self.__aimingSystem.update(deltaTime)
     localTransform, impulseTransform = self.__updateOscillators(deltaTime)
     ownVehicle = BigWorld.entity(BigWorld.player().playerVehicleID)
     if ownVehicle is not None and ownVehicle.isStarted and ownVehicle.appearance.isUnderwater:
         self.__onChangeControlMode()
         return 0.0
     else:
         aimMatrix = cameras.getAimMatrix(*self.__defaultAimOffset)
         camMat = Matrix(aimMatrix)
         rodMat = mathUtils.createTranslationMatrix(-self.__dynamicCfg['pivotShift'])
         antiRodMat = mathUtils.createTranslationMatrix(self.__dynamicCfg['pivotShift'])
         camMat.postMultiply(rodMat)
         camMat.postMultiply(localTransform)
         camMat.postMultiply(antiRodMat)
         camMat.postMultiply(self.__aimingSystem.matrix)
         camMat.invert()
         self.__cam.set(camMat)
         replayCtrl = BattleReplay.g_replayCtrl
         if replayCtrl.isPlaying and replayCtrl.isControllingCamera:
             aimOffset = replayCtrl.getAimClipPosition()
             binocularsOffset = aimOffset
         else:
             aimOffset = self.__calcAimOffset(impulseTransform)
             binocularsOffset = self.__calcAimOffset()
             if replayCtrl.isRecording:
                 replayCtrl.setAimClipPosition(aimOffset)
         self.__aim.offset((aimOffset.x, aimOffset.y))
         self.__binoculars.setMaskCenter(binocularsOffset.x, binocularsOffset.y)
         return 0.0
def prepareCompoundAssembler(vehicleDesc,
                             modelsSetParams,
                             spaceID,
                             isTurretDetached=False):
    if constants.IS_DEVELOPMENT and modelsSetParams.state not in VehicleDamageState.MODEL_STATE_NAMES:
        raise SoftException(
            'Invalid modelStateName %s, must be in %s' %
            (modelsSetParams.state, VehicleDamageState.MODEL_STATE_NAMES))
    if spaceID is None:
        spaceID = BigWorld.player().spaceID
    partModels = getPartModelsFromDesc(vehicleDesc, modelsSetParams)
    chassis, hull, turret, gun = partModels
    assembler = BigWorld.CompoundAssembler()
    assembler.addRootPart(chassis, TankPartNames.CHASSIS)
    assembler.emplacePart(hull, 'V', TankPartNames.HULL)
    turretJointName = vehicleDesc.hull.turretHardPoints[0]
    assembler.addNodeAlias(turretJointName, TankNodeNames.TURRET_JOINT)
    if not isTurretDetached:
        assembler.addPart(turret, turretJointName, TankPartNames.TURRET)
        assembler.addPart(gun, TankNodeNames.GUN_JOINT, TankPartNames.GUN)
    cornerPoint = vehicleDesc.chassis.topRightCarryingPoint
    assembler.addNode(
        TankNodeNames.TRACK_LEFT_MID, TankPartNames.CHASSIS,
        mathUtils.createTranslationMatrix((-cornerPoint[0], 0, 0)))
    assembler.addNode(
        TankNodeNames.TRACK_RIGHT_MID, TankPartNames.CHASSIS,
        mathUtils.createTranslationMatrix((cornerPoint[0], 0, 0)))
    assembler.addNode(TankNodeNames.CHASSIS_MID_TRAIL, TankPartNames.CHASSIS)
    assembler.name = vehicleDesc.name
    assembler.spaceID = spaceID
    return assembler
Exemple #4
0
 def __init__(self, vehicleEffect, cameraEffect, centerPosition):
     self.__vehicleTM = Math.WGTranslationOnlyMP()
     self.__vehicleDirMatrix = BigWorld.DiffDirProvider(self.__vehicleTM, mathUtils.createTranslationMatrix(centerPosition))
     self.__cameraTM = Math.WGTranslationOnlyMP()
     self.__cameraDirMatrix = BigWorld.DiffDirProvider(self.__cameraTM, mathUtils.createTranslationMatrix(centerPosition))
     self.__vehicleFakeModel = BigWorld.Model('')
     self.__vehicleFakeModel.addMotor(BigWorld.Servo(self.__vehicleDirMatrix))
     self.__cameraFakeModel = BigWorld.Model('')
     self.__cameraFakeModel.addMotor(BigWorld.Servo(self.__cameraDirMatrix))
     self.__vehicleEffects = vehicleEffect
     self.__vehicleEffectsPlayer = None
     self.__cameraEffects = cameraEffect
     self.__cameraEffectsPlayer = None
     return
Exemple #5
0
def getGunMatrixProvider(vehicleTypeDescriptor, turretMatrixProvider,
                         gunPitchMatrixProvider):
    gunOffset = vehicleTypeDescriptor.turret['gunPosition']
    return MatrixProviders.product(
        gunPitchMatrixProvider,
        MatrixProviders.product(mathUtils.createTranslationMatrix(gunOffset),
                                turretMatrixProvider))
Exemple #6
0
 def set(self, start, end):
     self.start = start
     self.end = end
     direction = end - start
     m = mathUtils.createSRTMatrix((self.__thickness, self.__thickness, direction.length), (direction.yaw, direction.pitch, 0), start + direction / 2)
     m.preMultiply(mathUtils.createTranslationMatrix(Vector3(-0.5, -0.5, -0.5)))
     self.motor.signal = m
def launch(spaceName):
    global g_offlineModeEnabled
    global g_spaceID
    global g_videoCamera
    print 'Entering offline space', spaceName
    BigWorld.clearAllSpaces()
    BigWorld.worldDrawEnabled(False)
    _displayGUI(spaceName)
    g_spaceID = BigWorld.createSpace()
    BigWorld.addSpaceGeometryMapping(g_spaceID, None, spaceName)
    BigWorld.setCursor(GUI.mcursor())
    GUI.mcursor().visible = False
    GUI.mcursor().clipped = True
    g_offlineModeEnabled = True
    BigWorld.callback(1.0, _offlineLoadCheck)
    rootSection = ResMgr.openSection(AvatarInputHandler._INPUT_HANDLER_CFG)
    videoSection = rootSection['videoMode']
    videoCameraSection = videoSection['camera']
    g_videoCamera = VideoCamera(videoCameraSection)
    g_videoCamera.enable(camMatrix=mathUtils.createTranslationMatrix((0.0, 0.0, 0.0)))
    BigWorld.camera().spaceID = g_spaceID
    import game
    game.handleKeyEvent = handleKeyEvent
    game.handleMouseEvent = handleMouseEvent
    BigWorld.player = lambda : g_fakeAvatar
    return
Exemple #8
0
 def set(self, start, end):
     self.start = start
     self.end = end
     direction = end - start
     m = mathUtils.createSRTMatrix((self.__thickness, self.__thickness, direction.length), (direction.yaw, direction.pitch, 0), start + direction / 2)
     m.preMultiply(mathUtils.createTranslationMatrix(Vector3(-0.5, -0.5, -0.5)))
     self.motor.signal = m
 def selectPlacement(self, placement):
     if self.__vehicle is None:
         return
     else:
         self.__placement = placement
         self.__lookAtProvider = None
         if placement == _VehicleBounder.SELECT_CHASSIS:
             self.matrix = self.__vehicle.matrix
         elif placement == _VehicleBounder.SELECT_TURRET:
             self.matrix = AimingSystems.getTurretMatrixProvider(
                 self.__vehicle.typeDescriptor, self.__vehicle.matrix,
                 self.__vehicle.appearance.turretMatrix)
         elif placement == _VehicleBounder.SELECT_GUN:
             turretMatrixProv = AimingSystems.getTurretMatrixProvider(
                 self.__vehicle.typeDescriptor, self.__vehicle.matrix,
                 self.__vehicle.appearance.turretMatrix)
             self.matrix = AimingSystems.getGunMatrixProvider(
                 self.__vehicle.typeDescriptor, turretMatrixProv,
                 self.__vehicle.appearance.gunMatrix)
         elif placement == _VehicleBounder.SELECT_LOOK_AT:
             self.matrix = mathUtils.createIdentityMatrix()
             self.__lookAtProvider = mathUtils.MatrixProviders.product(
                 mathUtils.createTranslationMatrix(self.__boundLocalPos),
                 self.__vehicle.matrix)
         return
Exemple #10
0
 def selectPlacement(self, placement):
     if self.__vehicle is None:
         return
     else:
         self.__placement = placement
         self.__lookAtProvider = None
         if placement == _VehicleBounder.SELECT_CHASSIS:
             self.matrix = self.__vehicle.matrix
         elif placement == _VehicleBounder.SELECT_TURRET:
             self.matrix = AimingSystems.getTurretMatrixProvider(
                 self.__vehicle.typeDescriptor, self.__vehicle.matrix, self.__vehicle.appearance.turretMatrix
             )
         elif placement == _VehicleBounder.SELECT_GUN:
             turretMatrixProv = AimingSystems.getTurretMatrixProvider(
                 self.__vehicle.typeDescriptor, self.__vehicle.matrix, self.__vehicle.appearance.turretMatrix
             )
             self.matrix = AimingSystems.getGunMatrixProvider(
                 self.__vehicle.typeDescriptor, turretMatrixProv, self.__vehicle.appearance.gunMatrix
             )
         elif placement == _VehicleBounder.SELECT_LOOK_AT:
             self.matrix = mathUtils.createIdentityMatrix()
             self.__lookAtProvider = mathUtils.MatrixProviders.product(
                 mathUtils.createTranslationMatrix(self.__boundLocalPos), self.__vehicle.matrix
             )
         return
Exemple #11
0
def launch(spaceName):
    global g_offlineModeEnabled
    global g_spaceID
    global g_videoCamera
    print 'Entering offline space', spaceName
    BigWorld.clearAllSpaces()
    BigWorld.worldDrawEnabled(False)
    _displayGUI(spaceName)
    g_spaceID = BigWorld.createSpace()
    BigWorld.addSpaceGeometryMapping(g_spaceID, None, spaceName)
    BigWorld.setCursor(GUI.mcursor())
    GUI.mcursor().visible = False
    GUI.mcursor().clipped = True
    g_offlineModeEnabled = True
    BigWorld.callback(1.0, _offlineLoadCheck)
    rootSection = ResMgr.openSection(AvatarInputHandler._INPUT_HANDLER_CFG)
    videoSection = rootSection['videoMode']
    videoCameraSection = videoSection['camera']
    g_videoCamera = VideoCamera(videoCameraSection)
    g_videoCamera.enable(camMatrix=mathUtils.createTranslationMatrix((0.0, 0.0,
                                                                      0.0)))
    BigWorld.camera().spaceID = g_spaceID
    import game
    game.handleKeyEvent = handleKeyEvent
    game.handleMouseEvent = handleMouseEvent
    BigWorld.player = lambda: g_fakeAvatar
 def __cameraUpdate(self, allowModeChange=True):
     curTime = BigWorld.time()
     deltaTime = curTime - self.__prevTime
     self.__prevTime = curTime
     if not self.__autoUpdateDxDyDz.x == self.__autoUpdateDxDyDz.y == self.__autoUpdateDxDyDz.z == 0.0:
         self.__rotateAndZoom(self.__autoUpdateDxDyDz.x,
                              self.__autoUpdateDxDyDz.y,
                              self.__autoUpdateDxDyDz.z)
     self.__aimingSystem.update(deltaTime)
     localTransform, impulseTransform = self.__updateOscillators(deltaTime)
     zoom = self.__aimingSystem.overrideZoom(self.__zoom)
     aimMatrix = cameras.getAimMatrix(self.__defaultAimOffset.x,
                                      self.__defaultAimOffset.y)
     camMat = Matrix(aimMatrix)
     rodMat = mathUtils.createTranslationMatrix(
         -self.__dynamicCfg['pivotShift'])
     antiRodMat = mathUtils.createTranslationMatrix(
         self.__dynamicCfg['pivotShift'])
     camMat.postMultiply(rodMat)
     camMat.postMultiply(localTransform)
     camMat.postMultiply(antiRodMat)
     camMat.postMultiply(self.__aimingSystem.matrix)
     camMat.invert()
     self.__cam.set(camMat)
     if zoom != self.__zoom:
         self.__zoom = zoom
         self.__applyZoom(self.__zoom)
     replayCtrl = BattleReplay.g_replayCtrl
     if replayCtrl.isPlaying and replayCtrl.isControllingCamera:
         aimOffset = replayCtrl.getAimClipPosition()
         binocularsOffset = aimOffset
         if not BigWorld.player().isForcedGuiControlMode() and GUI.mcursor(
         ).inFocus:
             GUI.mcursor().position = aimOffset
     else:
         aimOffset = self.__calcAimOffset(impulseTransform)
         binocularsOffset = self.__calcAimOffset()
         if replayCtrl.isRecording:
             replayCtrl.setAimClipPosition(aimOffset)
     self.__aimOffset = aimOffset
     self.__binoculars.setMaskCenter(binocularsOffset.x, binocularsOffset.y)
     player = BigWorld.player()
     if allowModeChange and (self.__isPositionUnderwater(
             self.__aimingSystem.matrix.translation) or player.isGunLocked
                             and not player.isObserverFPV):
         self.__onChangeControlMode(False)
         return -1
Exemple #13
0
 def __updateOscillator(self, deltaTime):
     if StrategicCamera.isCameraDynamic():
         self.__positionOscillator.update(deltaTime)
         self.__positionNoiseOscillator.update(deltaTime)
     else:
         self.__positionOscillator.reset()
         self.__positionNoiseOscillator.reset()
     self.__cam.target.a = mathUtils.createTranslationMatrix(self.__positionOscillator.deviation + self.__positionNoiseOscillator.deviation)
Exemple #14
0
 def __createCube(self, position, size):
     modelName = self.CUBE_MODEL
     model, motor = self.__getModel(modelName)
     m = mathUtils.createSRTMatrix(size, (0, 0, 0), position)
     m.preMultiply(
         mathUtils.createTranslationMatrix(Vector3(0.0, -0.5, 0.0)))
     motor.signal = m
     return (modelName, model, motor)
Exemple #15
0
 def __updateOscillator(self, deltaTime):
     if ArtyCamera.isCameraDynamic():
         self.__positionOscillator.update(deltaTime)
         self.__positionNoiseOscillator.update(deltaTime)
     else:
         self.__positionOscillator.reset()
         self.__positionNoiseOscillator.reset()
     self.__cam.target.a = mathUtils.createTranslationMatrix(self.__positionOscillator.deviation + self.__positionNoiseOscillator.deviation)
Exemple #16
0
def getTurretMatrixProvider(vehicleTypeDescriptor, vehicleMatrixProvider,
                            turretYawMatrixProvider):
    turretOffset = vehicleTypeDescriptor.chassis[
        'hullPosition'] + vehicleTypeDescriptor.hull['turretPositions'][0]
    return MatrixProviders.product(
        turretYawMatrixProvider,
        MatrixProviders.product(
            mathUtils.createTranslationMatrix(turretOffset),
            vehicleMatrixProvider))
Exemple #17
0
def assembleCompoundModel2(models, position, vehicleDesc):
    worldMatrix = mathUtils.createTranslationMatrix(position)
    chassisFashion = BigWorld.WGVehicleFashion()
    VehicleAppearance.setupTracksFashion(chassisFashion, vehicleDesc)
    fashions.append(chassisFashion)
    gunFashion = BigWorld.WGGunRecoil('G')
    fashions.append(gunFashion)
    assembler = prepareCompoundAssembler(vehicleDesc, ModelStates.UNDAMAGED, BigWorld.camera().spaceID if BigWorld.player().spaceID == 0 else BigWorld.player().spaceID)
    BigWorld.loadResourceListBG((assembler,), functools.partial(setupTank, chassisFashion, gunFashion, vehicleDesc, worldMatrix))
Exemple #18
0
def assembleCompoundModel2(models, position, vehicleDesc):
    worldMatrix = mathUtils.createTranslationMatrix(position)
    chassisFashion = BigWorld.WGVehicleFashion()
    VehicleAppearance.setupTracksFashion(chassisFashion, vehicleDesc)
    fashions.append(chassisFashion)
    gunFashion = BigWorld.WGGunRecoil('G')
    fashions.append(gunFashion)
    assembler = prepareCompoundAssembler(vehicleDesc, ModelStates.UNDAMAGED, BigWorld.camera().spaceID if BigWorld.player().spaceID == 0 else BigWorld.player().spaceID)
    BigWorld.loadResourceListBG((assembler,), functools.partial(setupTank, chassisFashion, gunFashion, vehicleDesc, worldMatrix))
 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)
     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.idealMatrix if self.__adCfg['enable'] else 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
     self.__setCameraPosition(relTranslation)
     shotPoint = self.__calcFocalPoint(virginShotPoint, deltaTime)
     vehToShotPoint = shotPoint - vehiclePos
     self.__setCameraAimPoint(vehToShotPoint)
     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
 def __init__(self, beginExplosionPos, endExplosionPos, areaWidth, velocity):
     CallbackDelayer.__init__(self)
     self.model = BigWorld.Model('helpers/models/unit_cube.model')
     BigWorld.addModel(self.model)
     self.model.position = beginExplosionPos
     linearHomer = BigWorld.LinearHomer()
     self.model.addMotor(linearHomer)
     linearHomer.align = mathUtils.createSRTMatrix((areaWidth, 5, 1), (0.0, 0, 0), Vector3(0, 0, 0))
     linearHomer.acceleration = 0
     linearHomer.velocity = velocity
     linearHomer.target = mathUtils.createTranslationMatrix(endExplosionPos)
     linearHomer.proximityCallback = self.__onDeath
 def __init__(self, beginExplosionPos, endExplosionPos, areaWidth, velocity):
     CallbackDelayer.__init__(self)
     self.model = BigWorld.Model("helpers/models/unit_cube.model")
     BigWorld.addModel(self.model)
     self.model.position = beginExplosionPos
     linearHomer = BigWorld.LinearHomer()
     self.model.addMotor(linearHomer)
     linearHomer.align = mathUtils.createSRTMatrix((areaWidth, 5, 1), (0.0, 0, 0), Vector3(0, 0, 0))
     linearHomer.acceleration = 0
     linearHomer.velocity = velocity
     linearHomer.target = mathUtils.createTranslationMatrix(endExplosionPos)
     linearHomer.proximityCallback = self.__onDeath
Exemple #22
0
 def __createDirectedLine(self, pointA, pointB, width):
     modelName = self.CUBE_MODEL
     model, motor = self.__getModel(modelName)
     direction = pointB - pointA
     scale = (width, width, direction.length)
     rotation = (direction.yaw, direction.pitch, 0)
     translation = pointA + direction * 0.5
     m = mathUtils.createSRTMatrix(scale, rotation, translation)
     m.preMultiply(
         mathUtils.createTranslationMatrix(Vector3(0.0, -0.5, 0.0)))
     motor.signal = m
     return (modelName, model, motor)
Exemple #23
0
def computeTransform(confDict):
    matDict = {
        'preRotate': mathUtils.createIdentityMatrix(),
        'postRotate': mathUtils.createIdentityMatrix(),
        'vect': mathUtils.createIdentityMatrix()
    }
    if any(
            isinstance(confDict[confKey][0], tuple)
            for confKey in matDict.keys()):
        for confKey in matDict.keys():
            if isinstance(confDict[confKey][0], tuple):
                keyframes = []
                for keyframe in confDict[confKey]:
                    timeStamp, value = keyframe
                    if 'vect' in confKey:
                        Mat = mathUtils.createTranslationMatrix(value)
                    else:
                        Mat = mathUtils.createRotationMatrix(value)
                    keyframes.append((timeStamp, Mat))
                MatAn = Math.MatrixAnimation()
                MatAn.keyframes = keyframes
                MatAn.time = 0.0
                MatAn.loop = True
            elif 'vect' in confKey:
                MatAn = mathUtils.createTranslationMatrix(confDict[confKey])
            else:
                MatAn = mathUtils.createRotationMatrix(confDict[confKey])
            matDict[confKey] = MatAn

        matProd = mathUtils.MatrixProviders.product(matDict['vect'],
                                                    matDict['postRotate'])
        LightMat = mathUtils.MatrixProviders.product(matDict['preRotate'],
                                                     matProd)
    else:
        preRotate = mathUtils.createRotationMatrix(confDict['preRotate'])
        postRotate = mathUtils.createRotationMatrix(confDict['postRotate'])
        LightMat = mathUtils.createTranslationMatrix(confDict['vect'])
        LightMat.postMultiply(postRotate)
        LightMat.preMultiply(preRotate)
    return LightMat
Exemple #24
0
 def setup(self, position, direction, size, visualPath, color, marker):
     self.__fakeModel = model = BigWorld.player().newFakeModel()
     model.position = position
     model.yaw = direction.yaw
     BigWorld.addModel(model)
     rootNode = model.node('')
     self.__terrainSelectedArea = area = BigWorld.PyTerrainSelectedArea()
     area.setup(visualPath, size, OVER_TERRAIN_HEIGHT, color)
     rootNode.attach(area)
     markerTranslation = mathUtils.MatrixProviders.product(rootNode, mathUtils.createTranslationMatrix(Math.Vector3(0.0, MARKER_HEIGHT, 0.0)))
     self.__nextPosition = position
     self.__speed = Math.Vector3(0.0, 0.0, 0.0)
     self.__time = 0.0
Exemple #25
0
 def __create3DText(self, position, text, color, textSize):
     if self.reuse3DTexts:
         model, motor, component = self.reuse3DTexts.pop()
     else:
         attachment = GUI.Attachment()
         component = GUI.Text(text)
         attachment.component = component
         attachment.faceCamera = True
         motor = BigWorld.Servo(mathUtils.createTranslationMatrix(position))
         model = BigWorld.Model('')
         model.addMotor(motor)
         BigWorld.addModel(model, self.spaceID)
         model.root.attach(attachment)
         component.visible = True
         component.multiline = True
         component.explicitSize = True
         component.filterType = 'LINEAR'
         component.verticalAnchor = 'BOTTOM'
     component.text = text
     component.size = (0, textSize)
     component.colour = color
     motor.signal = mathUtils.createTranslationMatrix(position)
     return (model, motor, component)
def prepareCompoundAssembler(vehicleDesc, modelStateName, spaceID, isTurretDetached = False):
    if constants.IS_DEVELOPMENT and modelStateName not in VehicleDamageState.MODEL_STATE_NAMES:
        raise Exception('Invalid modelStateName %s, must be in %s' % (modelStateName, VehicleDamageState.MODEL_STATE_NAMES))
    if spaceID is None:
        spaceID = BigWorld.player().spaceID
    partModels = getPartModelsFromDesc(vehicleDesc, modelStateName)
    chassis, hull, turret, gun = partModels
    assembler = BigWorld.CompoundAssembler()
    skeleton = getSkeleton(vehicleDesc, modelStateName)
    assembler.addRootPart(chassis, TankPartNames.CHASSIS, skeleton.chassis, mathUtils.createIdentityMatrix())
    assembler.emplacePart(hull, 'V', TankPartNames.HULL, skeleton.hull)
    turretJointName = vehicleDesc.hull['turretHardPoints'][0]
    assembler.renameNode(turretJointName, TankNodeNames.TURRET_JOINT)
    if not isTurretDetached:
        assembler.addPart(turret, TankNodeNames.TURRET_JOINT, TankPartNames.TURRET, skeleton.turret, mathUtils.createIdentityMatrix())
        assembler.addPart(gun, TankNodeNames.GUN_JOINT, TankPartNames.GUN, skeleton.gun, mathUtils.createIdentityMatrix())
    cornerPoint = vehicleDesc.chassis['topRightCarryingPoint']
    assembler.addDummyNode(TankPartNames.CHASSIS, TankNodeNames.TRACK_LEFT_MID, mathUtils.createTranslationMatrix((-cornerPoint[0], 0, 0)))
    assembler.addDummyNode(TankPartNames.CHASSIS, TankNodeNames.TRACK_RIGHT_MID, mathUtils.createTranslationMatrix((cornerPoint[0], 0, 0)))
    assembler.addDummyNode(TankPartNames.CHASSIS, TankNodeNames.CHASSIS_MID_TRAIL)
    assembler.assemblerName = vehicleDesc.name
    assembler.spaceID = spaceID
    return assembler
def prepareCompoundAssembler(vehicleDesc,
                             modelStateName,
                             spaceID,
                             isTurretDetached=False):
    if constants.IS_DEVELOPMENT and modelStateName not in VehicleDamageState.MODEL_STATE_NAMES:
        raise Exception('Invalid modelStateName %s, must be in %s' %
                        (modelStateName, VehicleDamageState.MODEL_STATE_NAMES))
    if spaceID is None:
        spaceID = BigWorld.player().spaceID
    partModels = getPartModelsFromDesc(vehicleDesc, modelStateName)
    chassis, hull, turret, gun = partModels
    assembler = BigWorld.CompoundAssembler()
    skeleton = getSkeleton(vehicleDesc, modelStateName)
    assembler.addRootPart(chassis, TankPartNames.CHASSIS, skeleton.chassis,
                          mathUtils.createIdentityMatrix())
    assembler.emplacePart(hull, 'V', TankPartNames.HULL, skeleton.hull)
    turretJointName = vehicleDesc.hull['turretHardPoints'][0]
    assembler.renameNode(turretJointName, TankNodeNames.TURRET_JOINT)
    if not isTurretDetached:
        assembler.addPart(turret, TankNodeNames.TURRET_JOINT,
                          TankPartNames.TURRET, skeleton.turret,
                          mathUtils.createIdentityMatrix())
        assembler.addPart(gun, TankNodeNames.GUN_JOINT, TankPartNames.GUN,
                          skeleton.gun, mathUtils.createIdentityMatrix())
    cornerPoint = vehicleDesc.chassis['topRightCarryingPoint']
    assembler.addDummyNode(
        TankPartNames.CHASSIS, TankNodeNames.TRACK_LEFT_MID,
        mathUtils.createTranslationMatrix((-cornerPoint[0], 0, 0)))
    assembler.addDummyNode(
        TankPartNames.CHASSIS, TankNodeNames.TRACK_RIGHT_MID,
        mathUtils.createTranslationMatrix((cornerPoint[0], 0, 0)))
    assembler.addDummyNode(TankPartNames.CHASSIS,
                           TankNodeNames.CHASSIS_MID_TRAIL)
    assembler.assemblerName = vehicleDesc.name
    assembler.spaceID = spaceID
    return assembler
Exemple #28
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)
     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()
     self.__inputInertia.update(inertDt)
     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
     self.__setCameraPosition(relTranslation)
     shotPoint = self.__calcFocalPoint(virginShotPoint, deltaTime)
     vehToShotPoint = shotPoint - vehiclePos
     self.__setCameraAimPoint(vehToShotPoint)
     replayCtrl = BattleReplay.g_replayCtrl
     if replayCtrl.isPlaying and replayCtrl.isControllingCamera:
         aimOffset = replayCtrl.getAimClipPosition()
     else:
         aimOffset = self.__calcAimOffset(oscillationsZoomMultiplier)
         if replayCtrl.isRecording:
             replayCtrl.setAimClipPosition(aimOffset)
     self.__cam.aimPointClipCoords = aimOffset
     self.__aim.offset(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
Exemple #29
0
def setupTank(chassisFashion, gunFashion, vehicleDesc, worldMatrix, resources):
    print resources
    tank = resources[vehicleDesc.name]
    tank.matrix = worldMatrix
    tanks.append(tank)
    effect = Pixie.create('particles/Tank/exhaust/large_gas_gear.xml')
    tank.node('HP_gunFire').attach(effect)
    tank.node('HP_gunFire').attach(
        BigWorld.Model('helpers/models/position_gizmo.model'))
    tank.node('HP_Track_Exhaus_1').attach(
        BigWorld.Model('helpers/models/unit_cube.model'))
    m = mathUtils.createTranslationMatrix(Vector3(0, 10, 5))
    fakeMatrixes.append(m)
    tank.node('gun').attach(effect.clone(), m)
    BigWorld.addModel(tank)
    recoilDescr = vehicleDesc.gun['recoil']
    recoil = BigWorld.RecoilAnimator(recoilDescr['backoffTime'],
                                     recoilDescr['returnTime'],
                                     recoilDescr['amplitude'],
                                     recoilDescr['lodDist'])
    recoil.basisMatrix = tank.node('G').localMatrix
    recoil = assemblerModule.createGunAnimator(vehicleDesc,
                                               tank.node('G').localMatrix)
    recoil.lodSetting = 10
    tank.node('G', recoil)
    gunFashion.gunLocalMatrix = recoil
    recoil.lodLink = DataLinks.createFloatLink(chassisFashion, 'lastLod')
    swingingAnimator = assemblerModule.createSwingingAnimator(
        vehicleDesc,
        tank.node('hull').localMatrix, worldMatrix)
    chassisFashion.setupSwinging(swingingAnimator, 'hull')
    swingingAnimator.lodLink = DataLinks.createFloatLink(
        chassisFashion, 'lastLod')
    tank.setupFashions([chassisFashion, None, None, gunFashion])
    fashions.append(swingingAnimator)
    tank.node('hull', swingingAnimator)
    animMatrix = Math.MatrixAnimation()
    keys = []
    for x in xrange(100):
        angle = math.pi * 0.5 * (1 if x & 1 else -1)
        keys.append((x * 3, mathUtils.createRotationMatrix((angle, 0, 0))))

    animMatrix.keyframes = tuple(keys)
    tank.node('turret', animMatrix)
    return
Exemple #30
0
 def __getRemoteAim(self, allowModeChange=True):
     player = BigWorld.player()
     vehicle = player.getVehicleAttached()
     pos = Math.Vector3(vehicle.position)
     pos += player.remoteCameraSniper.camMatrixTranslation
     camMat = mathUtils.createTranslationMatrix(-pos)
     dir = player.remoteCameraSniper.camMatrixRotation
     getVector3 = getattr(player.filter, 'getVector3', None)
     if getVector3 is not None:
         time = BigWorld.serverTime()
         dirFiltered = getVector3(AVATAR_SUBFILTERS.CAMERA_SNIPER_ROTATION,
                                  time)
         dir = dirFiltered
     else:
         LOG_WARNING(
             "SniperCamera.__getRemoteAim, the filter doesn't have getVector3 method!"
         )
     camMat.postMultiply(mathUtils.createRotationMatrix(dir))
     return camMat
Exemple #31
0
def setupTank(chassisFashion, gunFashion, vehicleDesc, worldMatrix, resources):
    print resources
    tank = resources[vehicleDesc.name]
    tank.matrix = worldMatrix
    tanks.append(tank)
    effect = Pixie.create('particles/Tank/exhaust/large_gas_gear.xml')
    tank.node('HP_gunFire').attach(effect)
    tank.node('HP_gunFire').attach(BigWorld.Model('helpers/models/position_gizmo.model'))
    tank.node('HP_Track_Exhaus_1').attach(BigWorld.Model('helpers/models/unit_cube.model'))
    m = mathUtils.createTranslationMatrix(Vector3(0, 10, 5))
    fakeMatrixes.append(m)
    tank.node('gun').attach(effect.clone(), m)
    BigWorld.addModel(tank)
    recoilDescr = vehicleDesc.gun['recoil']
    recoil = BigWorld.RecoilAnimator(recoilDescr['backoffTime'], recoilDescr['returnTime'], recoilDescr['amplitude'], recoilDescr['lodDist'])
    recoil.basisMatrix = tank.node('G').localMatrix
    recoil = assemblerModule.createGunAnimator(vehicleDesc, tank.node('G').localMatrix)
    recoil.lodSetting = 10
    tank.node('G', recoil)
    gunFashion.gunLocalMatrix = recoil
    recoil.lodLink = DataLinks.createFloatLink(chassisFashion, 'lastLod')
    swingingAnimator = assemblerModule.createSwingingAnimator(vehicleDesc, tank.node('hull').localMatrix, worldMatrix)
    chassisFashion.setupSwinging(swingingAnimator, 'hull')
    swingingAnimator.lodLink = DataLinks.createFloatLink(chassisFashion, 'lastLod')
    tank.setupFashions([chassisFashion,
     None,
     None,
     gunFashion])
    fashions.append(swingingAnimator)
    tank.node('hull', swingingAnimator)
    animMatrix = Math.MatrixAnimation()
    keys = []
    for x in xrange(100):
        angle = math.pi * 0.5 * (1 if x & 1 else -1)
        keys.append((x * 3, mathUtils.createRotationMatrix((angle, 0, 0))))

    animMatrix.keyframes = tuple(keys)
    tank.node('turret', animMatrix)
    return
Exemple #32
0
    def __onFarPosUpdated(self):
        entries = self.__entries
        arena = BigWorld.player().arena
        vehicles = arena.vehicles
        for id, pos in arena.positions.iteritems():
            entry = entries.get(id)
            if entry is not None:
                location = entry['location']
                if location == VehicleLocation.FAR:
                    entry['matrix'] = mathUtils.createTranslationMatrix(pos)
                elif location == VehicleLocation.AOI_TO_FAR:
                    self.__delEntry(id)
                    self.__addEntry(id, VehicleLocation.FAR, False)
            elif vehicles[id]['isAlive']:
                self.__addEntry(id, VehicleLocation.FAR, True)

        for id in set(entries).difference(set(arena.positions)):
            location = entries[id]['location']
            if location == VehicleLocation.FAR:
                self.__delEntry(id)
            elif location == VehicleLocation.AOI_TO_FAR:
                self.__delEntry(id)
 def notifyViewPointChanged(self, avatar, staticPosition = None):
     if staticPosition is not None:
         self.__setTarget(mathUtils.createTranslationMatrix(staticPosition))
     return
 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.idealMatrix if self.
         __adCfg['enable'] else 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
     if self.__isRemoteCamera and vehicle is not None:
         relTranslation = player.remoteCameraArcade.relTranslation
         vehToShotPoint = player.remoteCameraArcade.shotPoint
         getVector3 = getattr(player.filter, 'getVector3', None)
         if getVector3 is not None:
             time = BigWorld.serverTime()
             relTranslation = getVector3(
                 AVATAR_SUBFILTERS.CAMERA_ARCADE_REL_TRANSLATION, time)
             vehToShotPoint = getVector3(
                 AVATAR_SUBFILTERS.CAMERA_ARCADE_SHOT_POINT, time)
         else:
             LOG_WARNING(
                 "ArcadeCamera.__cameraUpdate, the filter doesn't have getVector3 method!"
             )
     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 vehicle is not None and not player.isObserver():
         vehicle.setArcadeCameraDataForObservers(vehToShotPoint,
                                                 relTranslation)
     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
Exemple #35
0
def getTurretMatrixProvider(vehicleTypeDescriptor, vehicleMatrixProvider, turretYawMatrixProvider):
    turretOffset = vehicleTypeDescriptor.chassis['hullPosition'] + vehicleTypeDescriptor.hull['turretPositions'][0]
    return MatrixProviders.product(turretYawMatrixProvider, MatrixProviders.product(mathUtils.createTranslationMatrix(turretOffset), vehicleMatrixProvider))
Exemple #36
0
def getGunMatrixProvider(vehicleTypeDescriptor, turretMatrixProvider, gunPitchMatrixProvider):
    gunOffset = vehicleTypeDescriptor.turret['gunPosition']
    return MatrixProviders.product(gunPitchMatrixProvider, MatrixProviders.product(mathUtils.createTranslationMatrix(gunOffset), turretMatrixProvider))
Exemple #37
0
def createCrosshairMatrix(offsetFromNearPlane):
    nearPlane = BigWorld.projection().nearPlane
    return mathUtils.createTranslationMatrix(Vector3(0, 0, nearPlane + offsetFromNearPlane))
 def notifyViewPointChanged(self, avatar, staticPosition=None):
     if staticPosition is not None:
         self.__setTarget(mathUtils.createTranslationMatrix(staticPosition))
     return
Exemple #39
0
def new_setupModel(base, self, buildIdx):
    base(self, buildIdx)
    if not g_config.data['enabled']:
        return
    vEntityId = self._VehicleAppearance__vEntityId
    vEntity = BigWorld.entity(vEntityId)
    vDesc = self._VehicleAppearance__vDesc
    compoundModel = vEntity.model
    self.collisionLoaded = True
    self.modifiedModelsDesc = dict([(partName, {'model': None, 'matrix': None}) for partName in TankPartNames.ALL])
    self.modifiedModelsDesc.update([(
        '%s%d' % ((TankPartNames.ADDITIONAL_TURRET if idx % 2 == 0 else TankPartNames.ADDITIONAL_GUN), (idx + 2)/2),
        {'model': None, 'matrix': None})
        for idx in xrange(len(vDesc.turrets[1:]) * 2)])
    failList = []
    for partName in self.modifiedModelsDesc.keys():
        modelName = ''
        try:
            if 'additional' not in partName:
                modelName = getattr(vDesc, partName).hitTester.bspModelName
            else:
                _, addPartName, idxStr = partName.split('_')
                modelName = getattr(vDesc.turrets[int(idxStr)], addPartName).hitTester.bspModelName
            self.modifiedModelsDesc[partName]['model'] = model = BigWorld.Model(modelName)
            model.visible = False
        except StandardError:
            self.collisionLoaded = False
            failList.append(modelName if modelName else partName)
    if failList:
        print 'RemodEnabler: collision load failed: models not found'
        print failList
    if not self.collisionLoaded:
        return
    if any((g_config.data['collisionEnabled'], g_config.data['collisionComparisonEnabled'])):
        # Getting offset matrices
        hullOffset = mathUtils.createTranslationMatrix(vDesc.chassis.hullPosition)
        self.modifiedModelsDesc[TankPartNames.CHASSIS]['matrix'] = fullChassisMP = mathUtils.createIdentityMatrix()
        hullMP = mathUtils.MatrixProviders.product(mathUtils.createIdentityMatrix(), hullOffset)
        self.modifiedModelsDesc[TankPartNames.HULL]['matrix'] = fullHullMP = mathUtils.MatrixProviders.product(
            hullMP, fullChassisMP)
        for idx, turretPosition in enumerate(vDesc.hull.turretPositions):
            turretOffset = mathUtils.createTranslationMatrix(vDesc.hull.turretPositions[idx])
            gunOffset = mathUtils.createTranslationMatrix(vDesc.turrets[idx].turret.gunPosition)
        # Getting local transform matrices
            turretMP = mathUtils.MatrixProviders.product(mathUtils.createIdentityMatrix(), turretOffset)
            gunMP = mathUtils.MatrixProviders.product(mathUtils.createIdentityMatrix(), gunOffset)
            # turretMP = mathUtils.MatrixProviders.product(vEntity.appearance.turretMatrix, turretOffset)
            # gunMP = mathUtils.MatrixProviders.product(vEntity.appearance.gunMatrix, gunOffset)
        # Getting full transform matrices relative to vehicle coordinate system
            self.modifiedModelsDesc[TankPartNames.TURRET if not idx else '%s%d' % (TankPartNames.ADDITIONAL_TURRET, idx)][
                'matrix'] = fullTurretMP = mathUtils.MatrixProviders.product(turretMP, fullHullMP)
            self.modifiedModelsDesc[TankPartNames.GUN if not idx else '%s%d' % (TankPartNames.ADDITIONAL_GUN, idx)][
                'matrix'] = mathUtils.MatrixProviders.product(gunMP, fullTurretMP)
        for moduleName, moduleDict in self.modifiedModelsDesc.items():
            motor = BigWorld.Servo(mathUtils.MatrixProviders.product(moduleDict['matrix'], vEntity.matrix))
            moduleDict['model'].addMotor(motor)
            if moduleDict['model'] not in tuple(vEntity.models):
                try:
                    vEntity.addModel(moduleDict['model'])
                except StandardError:
                    pass
            moduleDict['model'].visible = True
        addCollisionGUI(self)
    if g_config.data['collisionEnabled']:
        for moduleName in TankPartNames.ALL:
            if compoundModel.node(moduleName) is not None:
                scaleMat = Math.Matrix()
                scaleMat.setScale((0.001, 0.001, 0.001))
                compoundModel.node(moduleName, scaleMat)
            else:
                print 'RemodEnabler: model rescale for %s failed' % moduleName
Exemple #40
0
 def __cameraUpdate(self, allowModeChange=True):
     curTime = BigWorld.time()
     deltaTime = curTime - self.__prevTime
     self.__prevTime = curTime
     if not self.__autoUpdateDxDyDz.x == self.__autoUpdateDxDyDz.y == self.__autoUpdateDxDyDz.z == 0.0:
         self.__rotateAndZoom(self.__autoUpdateDxDyDz.x,
                              self.__autoUpdateDxDyDz.y,
                              self.__autoUpdateDxDyDz.z)
     self.__aimingSystem.update(deltaTime)
     localTransform, impulseTransform = self.__updateOscillators(deltaTime)
     player = BigWorld.player()
     vehicle = player.getVehicleAttached()
     zoom = self.__zoom
     if self.__isRemoteCamera and vehicle is not None:
         camMat = self.__getRemoteAim(allowModeChange)
         if camMat is None:
             return 0.0
         zoom = float(player.remoteCameraSniper.zoom)
     else:
         aimMatrix = cameras.getAimMatrix(self.__defaultAimOffset.x,
                                          self.__defaultAimOffset.y)
         camMat = Matrix(aimMatrix)
         rodMat = mathUtils.createTranslationMatrix(
             -self.__dynamicCfg['pivotShift'])
         antiRodMat = mathUtils.createTranslationMatrix(
             self.__dynamicCfg['pivotShift'])
         camMat.postMultiply(rodMat)
         camMat.postMultiply(localTransform)
         camMat.postMultiply(antiRodMat)
         camMat.postMultiply(self.__aimingSystem.matrix)
         camMat.invert()
     if not player.isObserver() and vehicle is not None:
         relTranslation = self.__cam.position - vehicle.position
         rot = Math.Vector3(camMat.yaw, camMat.pitch, camMat.roll)
         vehicle.setSniperCameraDataForObservers(relTranslation, rot, zoom)
     self.__cam.set(camMat)
     if zoom != self.__zoom:
         self.__zoom = zoom
         self.__applyZoom(self.__zoom)
     replayCtrl = BattleReplay.g_replayCtrl
     if replayCtrl.isPlaying and replayCtrl.isControllingCamera:
         aimOffset = replayCtrl.getAimClipPosition()
         binocularsOffset = aimOffset
         if not BigWorld.player().isForcedGuiControlMode() and GUI.mcursor(
         ).inFocus:
             GUI.mcursor().position = aimOffset
     else:
         aimOffset = self.__calcAimOffset(impulseTransform)
         binocularsOffset = self.__calcAimOffset()
         if replayCtrl.isRecording:
             replayCtrl.setAimClipPosition(aimOffset)
     self.__aimOffset = aimOffset
     self.__binoculars.setMaskCenter(binocularsOffset.x, binocularsOffset.y)
     if not self.__isRemoteCamera and allowModeChange and (
             self.__isPositionUnderwater(
                 self.__aimingSystem.matrix.translation)
             or player.isGunLocked):
         self.__onChangeControlMode(False)
         return -1
     else:
         return 0.0
Exemple #41
0
def new_setupModel(base, self, buildIdx):
    base(self, buildIdx)
    if not g_config.data['enabled']:
        return
    if g_config.collisionMode:
        vEntity = self._HangarVehicleAppearance__vEntity
        vDesc = self._HangarVehicleAppearance__vDesc
        compoundModel = vEntity.model
        self.collisionLoaded = True
        self.modifiedModelsDesc = {}
        failList = []
        for partName in TankPartNames.ALL:
            modelName = ''
            try:
                modelName = getattr(vDesc, partName).hitTester.bspModelName
                model = BigWorld.Model(modelName)
                model.visible = False
                self.modifiedModelsDesc[partName] = {
                    'model': model,
                    'matrix': None
                }
            except StandardError:
                self.collisionLoaded = False
                failList.append(modelName if modelName else partName)
        if failList:
            print g_config.ID + ': collision load failed: models not found', failList
        if not self.collisionLoaded:
            return
        # Getting offset matrices
        hullOffset = mathUtils.createTranslationMatrix(
            vDesc.chassis.hullPosition)
        self.modifiedModelsDesc[TankPartNames.CHASSIS][
            'matrix'] = fullChassisMP = mathUtils.createIdentityMatrix()
        hullMP = mathUtils.MatrixProviders.product(
            mathUtils.createIdentityMatrix(), hullOffset)
        self.modifiedModelsDesc[TankPartNames.HULL][
            'matrix'] = fullHullMP = mathUtils.MatrixProviders.product(
                hullMP, fullChassisMP)
        for idx in xrange(len(vDesc.hull.turretPositions)):
            if idx:
                print g_config.ID + ': WARNING: multiple turrets are present!', vDesc.name
                break
            turretOffset = mathUtils.createTranslationMatrix(
                vDesc.hull.turretPositions[idx])
            gunOffset = mathUtils.createTranslationMatrix(
                vDesc.turret.gunPosition)
            # Getting local transform matrices
            turretMP = mathUtils.MatrixProviders.product(
                mathUtils.createIdentityMatrix(), turretOffset)
            gunMP = mathUtils.MatrixProviders.product(
                mathUtils.createIdentityMatrix(), gunOffset)
            # turretMP = mathUtils.MatrixProviders.product(vEntity.appearance.turretMatrix, turretOffset)
            # gunMP = mathUtils.MatrixProviders.product(vEntity.appearance.gunMatrix, gunOffset)
            # Getting full transform matrices relative to vehicle coordinate system
            self.modifiedModelsDesc[TankPartNames.TURRET][
                'matrix'] = fullTurretMP = mathUtils.MatrixProviders.product(
                    turretMP, fullHullMP)
            self.modifiedModelsDesc[TankPartNames.GUN][
                'matrix'] = mathUtils.MatrixProviders.product(
                    gunMP, fullTurretMP)
        for moduleDict in self.modifiedModelsDesc.itervalues():
            motor = BigWorld.Servo(
                mathUtils.MatrixProviders.product(moduleDict['matrix'],
                                                  vEntity.matrix))
            moduleDict['model'].addMotor(motor)
            if moduleDict['model'] not in tuple(vEntity.models):
                try:
                    vEntity.addModel(moduleDict['model'])
                except StandardError:
                    pass
            moduleDict['model'].visible = True
        addCollisionGUI(self)
    if g_config.collisionMode == 1:
        for moduleName in TankPartNames.ALL:
            # noinspection PyUnboundLocalVariable
            if compoundModel.node(moduleName) is not None:
                scaleMat = Math.Matrix()
                scaleMat.setScale((0.001, 0.001, 0.001))
                compoundModel.node(moduleName, scaleMat)
            else:
                print g_config.ID + ': model rescale for', moduleName, 'failed'
Exemple #42
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 = mathUtils.createIdentityMatrix()
        deHullMat = mathUtils.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 = mathUtils.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:
                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(
                '', mathUtils.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']:
                                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
def createCrosshairMatrix(offsetFromNearPlane):
    nearPlane = BigWorld.projection().nearPlane
    return mathUtils.createTranslationMatrix(
        Vector3(0, 0, nearPlane + offsetFromNearPlane))