Welcome to mirror list, hosted at ThFree Co, Russian Federation.

git.blender.org/blender.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorDalai Felinto <dfelinto@gmail.com>2018-04-16 15:07:42 +0300
committerDalai Felinto <dfelinto@gmail.com>2018-04-17 18:51:28 +0300
commit159806140fd33e6ddab951c0f6f180cfbf927d38 (patch)
treeda076be3baa4d987fb5935e220a3d901c926e0e7 /source/gameengine
parent28b996a9d2090efdd74115a653629ef9d7d871f7 (diff)
Removing Blender Game Engine from Blender 2.8
Folders removed entirely: * //extern/recastnavigation * //intern/decklink * //intern/moto * //source/blender/editors/space_logic * //source/blenderplayer * //source/gameengine This includes DNA data and any reference to the BGE code in Blender itself. We are bumping the subversion. Pending tasks: * Tile/clamp code in image editor draw code. * Viewport drawing code (so much of this will go away because of BI removal that we can wait until then to remove this.
Diffstat (limited to 'source/gameengine')
-rw-r--r--source/gameengine/BlenderRoutines/BL_KetsjiEmbedStart.cpp683
-rw-r--r--source/gameengine/BlenderRoutines/BL_System.cpp102
-rw-r--r--source/gameengine/BlenderRoutines/BL_System.h70
-rw-r--r--source/gameengine/BlenderRoutines/CMakeLists.txt78
-rw-r--r--source/gameengine/BlenderRoutines/KX_BlenderCanvas.cpp352
-rw-r--r--source/gameengine/BlenderRoutines/KX_BlenderCanvas.h222
-rw-r--r--source/gameengine/BlenderRoutines/KX_BlenderInputDevice.cpp33
-rw-r--r--source/gameengine/BlenderRoutines/KX_BlenderInputDevice.h80
-rw-r--r--source/gameengine/BlenderRoutines/KX_BlenderKeyboardDevice.cpp169
-rw-r--r--source/gameengine/BlenderRoutines/KX_BlenderKeyboardDevice.h62
-rw-r--r--source/gameengine/BlenderRoutines/KX_BlenderMouseDevice.cpp192
-rw-r--r--source/gameengine/BlenderRoutines/KX_BlenderMouseDevice.h58
-rw-r--r--source/gameengine/BlenderRoutines/KX_BlenderSystem.cpp59
-rw-r--r--source/gameengine/BlenderRoutines/KX_BlenderSystem.h56
-rw-r--r--source/gameengine/CMakeLists.txt57
-rw-r--r--source/gameengine/Converter/BL_ActionActuator.cpp664
-rw-r--r--source/gameengine/Converter/BL_ActionActuator.h158
-rw-r--r--source/gameengine/Converter/BL_ArmatureActuator.cpp271
-rw-r--r--source/gameengine/Converter/BL_ArmatureActuator.h96
-rw-r--r--source/gameengine/Converter/BL_ArmatureChannel.cpp469
-rw-r--r--source/gameengine/Converter/BL_ArmatureChannel.h101
-rw-r--r--source/gameengine/Converter/BL_ArmatureConstraint.cpp456
-rw-r--r--source/gameengine/Converter/BL_ArmatureConstraint.h125
-rw-r--r--source/gameengine/Converter/BL_ArmatureObject.cpp691
-rw-r--r--source/gameengine/Converter/BL_ArmatureObject.h145
-rw-r--r--source/gameengine/Converter/BL_BlenderDataConversion.cpp2473
-rw-r--r--source/gameengine/Converter/BL_BlenderDataConversion.h56
-rw-r--r--source/gameengine/Converter/BL_DeformableGameObject.cpp116
-rw-r--r--source/gameengine/Converter/BL_DeformableGameObject.h107
-rw-r--r--source/gameengine/Converter/BL_MeshDeformer.cpp239
-rw-r--r--source/gameengine/Converter/BL_MeshDeformer.h98
-rw-r--r--source/gameengine/Converter/BL_ModifierDeformer.cpp227
-rw-r--r--source/gameengine/Converter/BL_ModifierDeformer.h115
-rw-r--r--source/gameengine/Converter/BL_ShapeActionActuator.cpp563
-rw-r--r--source/gameengine/Converter/BL_ShapeActionActuator.h144
-rw-r--r--source/gameengine/Converter/BL_ShapeDeformer.cpp237
-rw-r--r--source/gameengine/Converter/BL_ShapeDeformer.h86
-rw-r--r--source/gameengine/Converter/BL_SkinDeformer.cpp384
-rw-r--r--source/gameengine/Converter/BL_SkinDeformer.h125
-rw-r--r--source/gameengine/Converter/CMakeLists.txt123
-rw-r--r--source/gameengine/Converter/KX_BlenderScalarInterpolator.cpp81
-rw-r--r--source/gameengine/Converter/KX_BlenderScalarInterpolator.h76
-rw-r--r--source/gameengine/Converter/KX_BlenderSceneConverter.cpp1477
-rw-r--r--source/gameengine/Converter/KX_BlenderSceneConverter.h232
-rw-r--r--source/gameengine/Converter/KX_ConvertActuators.cpp1146
-rw-r--r--source/gameengine/Converter/KX_ConvertActuators.h45
-rw-r--r--source/gameengine/Converter/KX_ConvertControllers.cpp250
-rw-r--r--source/gameengine/Converter/KX_ConvertControllers.h47
-rw-r--r--source/gameengine/Converter/KX_ConvertProperties.cpp243
-rw-r--r--source/gameengine/Converter/KX_ConvertProperties.h41
-rw-r--r--source/gameengine/Converter/KX_ConvertSensors.cpp663
-rw-r--r--source/gameengine/Converter/KX_ConvertSensors.h45
-rw-r--r--source/gameengine/Converter/KX_LibLoadStatus.cpp255
-rw-r--r--source/gameengine/Converter/KX_LibLoadStatus.h93
-rw-r--r--source/gameengine/Converter/KX_SoftBodyDeformer.cpp121
-rw-r--r--source/gameengine/Converter/KX_SoftBodyDeformer.h102
-rw-r--r--source/gameengine/Expressions/CMakeLists.txt91
-rw-r--r--source/gameengine/Expressions/EXP_BoolValue.h65
-rw-r--r--source/gameengine/Expressions/EXP_ConstExpr.h54
-rw-r--r--source/gameengine/Expressions/EXP_EmptyValue.h49
-rw-r--r--source/gameengine/Expressions/EXP_ErrorValue.h47
-rw-r--r--source/gameengine/Expressions/EXP_Expression.h149
-rw-r--r--source/gameengine/Expressions/EXP_FloatValue.h58
-rw-r--r--source/gameengine/Expressions/EXP_HashedPtr.h59
-rw-r--r--source/gameengine/Expressions/EXP_IdentifierExpr.h59
-rw-r--r--source/gameengine/Expressions/EXP_IfExpr.h54
-rw-r--r--source/gameengine/Expressions/EXP_InputParser.h118
-rw-r--r--source/gameengine/Expressions/EXP_IntValue.h73
-rw-r--r--source/gameengine/Expressions/EXP_ListValue.h92
-rw-r--r--source/gameengine/Expressions/EXP_ListWrapper.h109
-rw-r--r--source/gameengine/Expressions/EXP_Operator1Expr.h59
-rw-r--r--source/gameengine/Expressions/EXP_Operator2Expr.h66
-rw-r--r--source/gameengine/Expressions/EXP_PyObjectPlus.h648
-rw-r--r--source/gameengine/Expressions/EXP_Python.h82
-rw-r--r--source/gameengine/Expressions/EXP_PythonCallBack.h40
-rw-r--r--source/gameengine/Expressions/EXP_StringValue.h61
-rw-r--r--source/gameengine/Expressions/EXP_Value.h432
-rw-r--r--source/gameengine/Expressions/EXP_VectorValue.h94
-rw-r--r--source/gameengine/Expressions/EXP_VoidValue.h81
-rw-r--r--source/gameengine/Expressions/intern/BoolValue.cpp216
-rw-r--r--source/gameengine/Expressions/intern/ConstExpr.cpp131
-rw-r--r--source/gameengine/Expressions/intern/EmptyValue.cpp133
-rw-r--r--source/gameengine/Expressions/intern/ErrorValue.cpp131
-rw-r--r--source/gameengine/Expressions/intern/Expression.cpp77
-rw-r--r--source/gameengine/Expressions/intern/FloatValue.cpp329
-rw-r--r--source/gameengine/Expressions/intern/HashedPtr.cpp57
-rw-r--r--source/gameengine/Expressions/intern/IdentifierExpr.cpp103
-rw-r--r--source/gameengine/Expressions/intern/IfExpr.cpp144
-rw-r--r--source/gameengine/Expressions/intern/InputParser.cpp669
-rw-r--r--source/gameengine/Expressions/intern/IntValue.cpp344
-rw-r--r--source/gameengine/Expressions/intern/ListValue.cpp702
-rw-r--r--source/gameengine/Expressions/intern/ListWrapper.cpp424
-rw-r--r--source/gameengine/Expressions/intern/Operator1Expr.cpp151
-rw-r--r--source/gameengine/Expressions/intern/Operator2Expr.cpp276
-rw-r--r--source/gameengine/Expressions/intern/PyObjectPlus.cpp1226
-rw-r--r--source/gameengine/Expressions/intern/PythonCallBack.cpp119
-rw-r--r--source/gameengine/Expressions/intern/StringValue.cpp147
-rw-r--r--source/gameengine/Expressions/intern/Value.cpp672
-rw-r--r--source/gameengine/Expressions/intern/VectorValue.cpp225
-rw-r--r--source/gameengine/GameLogic/CMakeLists.txt147
-rw-r--r--source/gameengine/GameLogic/Joystick/SCA_Joystick.cpp382
-rw-r--r--source/gameengine/GameLogic/Joystick/SCA_Joystick.h214
-rw-r--r--source/gameengine/GameLogic/Joystick/SCA_JoystickDefines.h56
-rw-r--r--source/gameengine/GameLogic/Joystick/SCA_JoystickEvents.cpp137
-rw-r--r--source/gameengine/GameLogic/Joystick/SCA_JoystickPrivate.h52
-rw-r--r--source/gameengine/GameLogic/SCA_2DFilterActuator.cpp153
-rw-r--r--source/gameengine/GameLogic/SCA_2DFilterActuator.h71
-rw-r--r--source/gameengine/GameLogic/SCA_ANDController.cpp131
-rw-r--r--source/gameengine/GameLogic/SCA_ANDController.h51
-rw-r--r--source/gameengine/GameLogic/SCA_ActuatorEventManager.cpp68
-rw-r--r--source/gameengine/GameLogic/SCA_ActuatorEventManager.h56
-rw-r--r--source/gameengine/GameLogic/SCA_ActuatorSensor.cpp171
-rw-r--r--source/gameengine/GameLogic/SCA_ActuatorSensor.h70
-rw-r--r--source/gameengine/GameLogic/SCA_AlwaysEventManager.cpp59
-rw-r--r--source/gameengine/GameLogic/SCA_AlwaysEventManager.h50
-rw-r--r--source/gameengine/GameLogic/SCA_AlwaysSensor.cpp139
-rw-r--r--source/gameengine/GameLogic/SCA_AlwaysSensor.h53
-rw-r--r--source/gameengine/GameLogic/SCA_BasicEventManager.cpp61
-rw-r--r--source/gameengine/GameLogic/SCA_BasicEventManager.h57
-rw-r--r--source/gameengine/GameLogic/SCA_DelaySensor.cpp170
-rw-r--r--source/gameengine/GameLogic/SCA_DelaySensor.h66
-rw-r--r--source/gameengine/GameLogic/SCA_EventManager.cpp83
-rw-r--r--source/gameengine/GameLogic/SCA_EventManager.h91
-rw-r--r--source/gameengine/GameLogic/SCA_ExpressionController.cpp159
-rw-r--r--source/gameengine/GameLogic/SCA_ExpressionController.h66
-rw-r--r--source/gameengine/GameLogic/SCA_IActuator.cpp140
-rw-r--r--source/gameengine/GameLogic/SCA_IActuator.h168
-rw-r--r--source/gameengine/GameLogic/SCA_IController.cpp298
-rw-r--r--source/gameengine/GameLogic/SCA_IController.h112
-rw-r--r--source/gameengine/GameLogic/SCA_IInputDevice.cpp139
-rw-r--r--source/gameengine/GameLogic/SCA_IInputDevice.h334
-rw-r--r--source/gameengine/GameLogic/SCA_ILogicBrick.cpp271
-rw-r--r--source/gameengine/GameLogic/SCA_ILogicBrick.h167
-rw-r--r--source/gameengine/GameLogic/SCA_IObject.cpp349
-rw-r--r--source/gameengine/GameLogic/SCA_IObject.h229
-rw-r--r--source/gameengine/GameLogic/SCA_IScene.cpp145
-rw-r--r--source/gameengine/GameLogic/SCA_IScene.h87
-rw-r--r--source/gameengine/GameLogic/SCA_ISensor.cpp471
-rw-r--r--source/gameengine/GameLogic/SCA_ISensor.h220
-rw-r--r--source/gameengine/GameLogic/SCA_JoystickManager.cpp92
-rw-r--r--source/gameengine/GameLogic/SCA_JoystickManager.h59
-rw-r--r--source/gameengine/GameLogic/SCA_JoystickSensor.cpp428
-rw-r--r--source/gameengine/GameLogic/SCA_JoystickSensor.h168
-rw-r--r--source/gameengine/GameLogic/SCA_KeyboardManager.cpp80
-rw-r--r--source/gameengine/GameLogic/SCA_KeyboardManager.h66
-rw-r--r--source/gameengine/GameLogic/SCA_KeyboardSensor.cpp668
-rw-r--r--source/gameengine/GameLogic/SCA_KeyboardSensor.h141
-rw-r--r--source/gameengine/GameLogic/SCA_LogicManager.cpp342
-rw-r--r--source/gameengine/GameLogic/SCA_LogicManager.h154
-rw-r--r--source/gameengine/GameLogic/SCA_MouseManager.cpp112
-rw-r--r--source/gameengine/GameLogic/SCA_MouseManager.h75
-rw-r--r--source/gameengine/GameLogic/SCA_MouseSensor.cpp317
-rw-r--r--source/gameengine/GameLogic/SCA_MouseSensor.h120
-rw-r--r--source/gameengine/GameLogic/SCA_NANDController.cpp133
-rw-r--r--source/gameengine/GameLogic/SCA_NANDController.h52
-rw-r--r--source/gameengine/GameLogic/SCA_NORController.cpp133
-rw-r--r--source/gameengine/GameLogic/SCA_NORController.h48
-rw-r--r--source/gameengine/GameLogic/SCA_ORController.cpp129
-rw-r--r--source/gameengine/GameLogic/SCA_ORController.h49
-rw-r--r--source/gameengine/GameLogic/SCA_PropertyActuator.cpp293
-rw-r--r--source/gameengine/GameLogic/SCA_PropertyActuator.h90
-rw-r--r--source/gameengine/GameLogic/SCA_PropertyEventManager.cpp57
-rw-r--r--source/gameengine/GameLogic/SCA_PropertyEventManager.h55
-rw-r--r--source/gameengine/GameLogic/SCA_PropertySensor.cpp332
-rw-r--r--source/gameengine/GameLogic/SCA_PropertySensor.h98
-rw-r--r--source/gameengine/GameLogic/SCA_PythonController.cpp539
-rw-r--r--source/gameengine/GameLogic/SCA_PythonController.h118
-rw-r--r--source/gameengine/GameLogic/SCA_PythonJoystick.cpp188
-rw-r--r--source/gameengine/GameLogic/SCA_PythonJoystick.h56
-rw-r--r--source/gameengine/GameLogic/SCA_PythonKeyboard.cpp153
-rw-r--r--source/gameengine/GameLogic/SCA_PythonKeyboard.h50
-rw-r--r--source/gameengine/GameLogic/SCA_PythonMouse.cpp206
-rw-r--r--source/gameengine/GameLogic/SCA_PythonMouse.h59
-rw-r--r--source/gameengine/GameLogic/SCA_RandomActuator.cpp543
-rw-r--r--source/gameengine/GameLogic/SCA_RandomActuator.h120
-rw-r--r--source/gameengine/GameLogic/SCA_RandomEventManager.cpp58
-rw-r--r--source/gameengine/GameLogic/SCA_RandomEventManager.h54
-rw-r--r--source/gameengine/GameLogic/SCA_RandomNumberGenerator.cpp133
-rw-r--r--source/gameengine/GameLogic/SCA_RandomNumberGenerator.h85
-rw-r--r--source/gameengine/GameLogic/SCA_RandomSensor.cpp187
-rw-r--r--source/gameengine/GameLogic/SCA_RandomSensor.h71
-rw-r--r--source/gameengine/GameLogic/SCA_TimeEventManager.cpp120
-rw-r--r--source/gameengine/GameLogic/SCA_TimeEventManager.h62
-rw-r--r--source/gameengine/GameLogic/SCA_XNORController.cpp137
-rw-r--r--source/gameengine/GameLogic/SCA_XNORController.h53
-rw-r--r--source/gameengine/GameLogic/SCA_XORController.cpp136
-rw-r--r--source/gameengine/GameLogic/SCA_XORController.h48
-rw-r--r--source/gameengine/GamePlayer/CMakeLists.txt27
-rw-r--r--source/gameengine/GamePlayer/common/CMakeLists.txt75
-rw-r--r--source/gameengine/GamePlayer/common/GPC_Canvas.cpp168
-rw-r--r--source/gameengine/GamePlayer/common/GPC_Canvas.h147
-rw-r--r--source/gameengine/GamePlayer/common/GPC_KeyboardDevice.cpp128
-rw-r--r--source/gameengine/GamePlayer/common/GPC_KeyboardDevice.h90
-rw-r--r--source/gameengine/GamePlayer/common/GPC_MouseDevice.cpp214
-rw-r--r--source/gameengine/GamePlayer/common/GPC_MouseDevice.h103
-rw-r--r--source/gameengine/GamePlayer/ghost/CMakeLists.txt112
-rw-r--r--source/gameengine/GamePlayer/ghost/GPG_Application.cpp998
-rw-r--r--source/gameengine/GamePlayer/ghost/GPG_Application.h181
-rw-r--r--source/gameengine/GamePlayer/ghost/GPG_Canvas.cpp177
-rw-r--r--source/gameengine/GamePlayer/ghost/GPG_Canvas.h76
-rw-r--r--source/gameengine/GamePlayer/ghost/GPG_KeyboardDevice.cpp165
-rw-r--r--source/gameengine/GamePlayer/ghost/GPG_KeyboardDevice.h56
-rw-r--r--source/gameengine/GamePlayer/ghost/GPG_System.cpp53
-rw-r--r--source/gameengine/GamePlayer/ghost/GPG_System.h54
-rw-r--r--source/gameengine/GamePlayer/ghost/GPG_ghost.cpp1228
-rw-r--r--source/gameengine/Ketsji/BL_Action.cpp534
-rw-r--r--source/gameengine/Ketsji/BL_Action.h151
-rw-r--r--source/gameengine/Ketsji/BL_ActionManager.cpp164
-rw-r--r--source/gameengine/Ketsji/BL_ActionManager.h132
-rw-r--r--source/gameengine/Ketsji/BL_BlenderShader.cpp188
-rw-r--r--source/gameengine/Ketsji/BL_BlenderShader.h96
-rw-r--r--source/gameengine/Ketsji/BL_Material.cpp123
-rw-r--r--source/gameengine/Ketsji/BL_Material.h182
-rw-r--r--source/gameengine/Ketsji/BL_Shader.cpp1478
-rw-r--r--source/gameengine/Ketsji/BL_Shader.h241
-rw-r--r--source/gameengine/Ketsji/BL_Texture.cpp759
-rw-r--r--source/gameengine/Ketsji/BL_Texture.h82
-rw-r--r--source/gameengine/Ketsji/CMakeLists.txt265
-rw-r--r--source/gameengine/Ketsji/KXNetwork/CMakeLists.txt56
-rw-r--r--source/gameengine/Ketsji/KXNetwork/KX_NetworkEventManager.cpp77
-rw-r--r--source/gameengine/Ketsji/KXNetwork/KX_NetworkEventManager.h55
-rw-r--r--source/gameengine/Ketsji/KXNetwork/KX_NetworkMessageActuator.cpp139
-rw-r--r--source/gameengine/Ketsji/KXNetwork/KX_NetworkMessageActuator.h72
-rw-r--r--source/gameengine/Ketsji/KXNetwork/KX_NetworkMessageSensor.cpp224
-rw-r--r--source/gameengine/Ketsji/KXNetwork/KX_NetworkMessageSensor.h90
-rw-r--r--source/gameengine/Ketsji/KXNetwork/KX_NetworkObjectActuator.cpp31
-rw-r--r--source/gameengine/Ketsji/KXNetwork/KX_NetworkObjectActuator.h32
-rw-r--r--source/gameengine/Ketsji/KXNetwork/KX_NetworkObjectSensor.cpp32
-rw-r--r--source/gameengine/Ketsji/KXNetwork/KX_NetworkObjectSensor.h32
-rw-r--r--source/gameengine/Ketsji/KX_ArmatureSensor.cpp208
-rw-r--r--source/gameengine/Ketsji/KX_ArmatureSensor.h90
-rw-r--r--source/gameengine/Ketsji/KX_BlenderMaterial.cpp1334
-rw-r--r--source/gameengine/Ketsji/KX_BlenderMaterial.h200
-rw-r--r--source/gameengine/Ketsji/KX_Camera.cpp1166
-rw-r--r--source/gameengine/Ketsji/KX_Camera.h334
-rw-r--r--source/gameengine/Ketsji/KX_CameraActuator.cpp428
-rw-r--r--source/gameengine/Ketsji/KX_CameraActuator.h138
-rw-r--r--source/gameengine/Ketsji/KX_CameraIpoSGController.cpp126
-rw-r--r--source/gameengine/Ketsji/KX_CameraIpoSGController.h97
-rw-r--r--source/gameengine/Ketsji/KX_CharacterWrapper.cpp167
-rw-r--r--source/gameengine/Ketsji/KX_CharacterWrapper.h40
-rw-r--r--source/gameengine/Ketsji/KX_ClientObjectInfo.h84
-rw-r--r--source/gameengine/Ketsji/KX_ConstraintActuator.cpp629
-rw-r--r--source/gameengine/Ketsji/KX_ConstraintActuator.h152
-rw-r--r--source/gameengine/Ketsji/KX_ConstraintWrapper.cpp133
-rw-r--r--source/gameengine/Ketsji/KX_ConstraintWrapper.h61
-rw-r--r--source/gameengine/Ketsji/KX_Dome.cpp2051
-rw-r--r--source/gameengine/Ketsji/KX_Dome.h197
-rw-r--r--source/gameengine/Ketsji/KX_EmptyObject.cpp37
-rw-r--r--source/gameengine/Ketsji/KX_EmptyObject.h50
-rw-r--r--source/gameengine/Ketsji/KX_FontObject.cpp300
-rw-r--r--source/gameengine/Ketsji/KX_FontObject.h81
-rw-r--r--source/gameengine/Ketsji/KX_GameActuator.cpp267
-rw-r--r--source/gameengine/Ketsji/KX_GameActuator.h91
-rw-r--r--source/gameengine/Ketsji/KX_GameObject.cpp4203
-rw-r--r--source/gameengine/Ketsji/KX_GameObject.h1142
-rw-r--r--source/gameengine/Ketsji/KX_IInterpolator.h56
-rw-r--r--source/gameengine/Ketsji/KX_IPOTransform.h87
-rw-r--r--source/gameengine/Ketsji/KX_IPO_SGController.cpp373
-rw-r--r--source/gameengine/Ketsji/KX_IPO_SGController.h124
-rw-r--r--source/gameengine/Ketsji/KX_IScalarInterpolator.h52
-rw-r--r--source/gameengine/Ketsji/KX_ISceneConverter.h103
-rw-r--r--source/gameengine/Ketsji/KX_ISystem.h63
-rw-r--r--source/gameengine/Ketsji/KX_IpoConvert.cpp441
-rw-r--r--source/gameengine/Ketsji/KX_IpoConvert.h69
-rw-r--r--source/gameengine/Ketsji/KX_KetsjiEngine.cpp2081
-rw-r--r--source/gameengine/Ketsji/KX_KetsjiEngine.h553
-rw-r--r--source/gameengine/Ketsji/KX_Light.cpp479
-rw-r--r--source/gameengine/Ketsji/KX_Light.h100
-rw-r--r--source/gameengine/Ketsji/KX_LightIpoSGController.cpp122
-rw-r--r--source/gameengine/Ketsji/KX_LightIpoSGController.h105
-rw-r--r--source/gameengine/Ketsji/KX_MaterialIpoController.cpp105
-rw-r--r--source/gameengine/Ketsji/KX_MaterialIpoController.h65
-rw-r--r--source/gameengine/Ketsji/KX_MeshProxy.cpp464
-rw-r--r--source/gameengine/Ketsji/KX_MeshProxy.h85
-rw-r--r--source/gameengine/Ketsji/KX_MotionState.cpp106
-rw-r--r--source/gameengine/Ketsji/KX_MotionState.h65
-rw-r--r--source/gameengine/Ketsji/KX_MouseActuator.cpp539
-rw-r--r--source/gameengine/Ketsji/KX_MouseActuator.h132
-rw-r--r--source/gameengine/Ketsji/KX_MouseFocusSensor.cpp520
-rw-r--r--source/gameengine/Ketsji/KX_MouseFocusSensor.h208
-rw-r--r--source/gameengine/Ketsji/KX_NavMeshObject.cpp747
-rw-r--r--source/gameengine/Ketsji/KX_NavMeshObject.h80
-rw-r--r--source/gameengine/Ketsji/KX_NearSensor.cpp292
-rw-r--r--source/gameengine/Ketsji/KX_NearSensor.h107
-rw-r--r--source/gameengine/Ketsji/KX_ObColorIpoSGController.cpp110
-rw-r--r--source/gameengine/Ketsji/KX_ObColorIpoSGController.h80
-rw-r--r--source/gameengine/Ketsji/KX_ObjectActuator.cpp709
-rw-r--r--source/gameengine/Ketsji/KX_ObjectActuator.h234
-rw-r--r--source/gameengine/Ketsji/KX_ObstacleSimulation.cpp832
-rw-r--r--source/gameengine/Ketsji/KX_ObstacleSimulation.h134
-rw-r--r--source/gameengine/Ketsji/KX_OrientationInterpolator.cpp56
-rw-r--r--source/gameengine/Ketsji/KX_OrientationInterpolator.h64
-rw-r--r--source/gameengine/Ketsji/KX_ParentActuator.cpp205
-rw-r--r--source/gameengine/Ketsji/KX_ParentActuator.h91
-rw-r--r--source/gameengine/Ketsji/KX_PhysicsEngineEnums.h42
-rw-r--r--source/gameengine/Ketsji/KX_PolyProxy.cpp266
-rw-r--r--source/gameengine/Ketsji/KX_PolyProxy.h85
-rw-r--r--source/gameengine/Ketsji/KX_PositionInterpolator.cpp42
-rw-r--r--source/gameengine/Ketsji/KX_PositionInterpolator.h64
-rw-r--r--source/gameengine/Ketsji/KX_PyConstraintBinding.cpp750
-rw-r--r--source/gameengine/Ketsji/KX_PyConstraintBinding.h45
-rw-r--r--source/gameengine/Ketsji/KX_PyMath.cpp215
-rw-r--r--source/gameengine/Ketsji/KX_PyMath.h281
-rw-r--r--source/gameengine/Ketsji/KX_PythonInit.cpp2953
-rw-r--r--source/gameengine/Ketsji/KX_PythonInit.h95
-rw-r--r--source/gameengine/Ketsji/KX_PythonInitTypes.cpp286
-rw-r--r--source/gameengine/Ketsji/KX_PythonInitTypes.h40
-rw-r--r--source/gameengine/Ketsji/KX_PythonMain.cpp71
-rw-r--r--source/gameengine/Ketsji/KX_PythonMain.h41
-rw-r--r--source/gameengine/Ketsji/KX_RadarSensor.cpp230
-rw-r--r--source/gameengine/Ketsji/KX_RadarSensor.h100
-rw-r--r--source/gameengine/Ketsji/KX_RayCast.cpp121
-rw-r--r--source/gameengine/Ketsji/KX_RayCast.h149
-rw-r--r--source/gameengine/Ketsji/KX_RayEventManager.cpp53
-rw-r--r--source/gameengine/Ketsji/KX_RayEventManager.h53
-rw-r--r--source/gameengine/Ketsji/KX_RaySensor.cpp383
-rw-r--r--source/gameengine/Ketsji/KX_RaySensor.h109
-rw-r--r--source/gameengine/Ketsji/KX_SCA_AddObjectActuator.cpp284
-rw-r--r--source/gameengine/Ketsji/KX_SCA_AddObjectActuator.h133
-rw-r--r--source/gameengine/Ketsji/KX_SCA_DynamicActuator.cpp160
-rw-r--r--source/gameengine/Ketsji/KX_SCA_DynamicActuator.h76
-rw-r--r--source/gameengine/Ketsji/KX_SCA_EndObjectActuator.cpp125
-rw-r--r--source/gameengine/Ketsji/KX_SCA_EndObjectActuator.h74
-rw-r--r--source/gameengine/Ketsji/KX_SCA_ReplaceMeshActuator.cpp182
-rw-r--r--source/gameengine/Ketsji/KX_SCA_ReplaceMeshActuator.h96
-rw-r--r--source/gameengine/Ketsji/KX_SG_BoneParentNodeRelationship.cpp155
-rw-r--r--source/gameengine/Ketsji/KX_SG_BoneParentNodeRelationship.h96
-rw-r--r--source/gameengine/Ketsji/KX_SG_NodeRelationships.cpp298
-rw-r--r--source/gameengine/Ketsji/KX_SG_NodeRelationships.h231
-rw-r--r--source/gameengine/Ketsji/KX_ScalarInterpolator.cpp39
-rw-r--r--source/gameengine/Ketsji/KX_ScalarInterpolator.h69
-rw-r--r--source/gameengine/Ketsji/KX_ScalingInterpolator.cpp42
-rw-r--r--source/gameengine/Ketsji/KX_ScalingInterpolator.h64
-rw-r--r--source/gameengine/Ketsji/KX_Scene.cpp2644
-rw-r--r--source/gameengine/Ketsji/KX_Scene.h697
-rw-r--r--source/gameengine/Ketsji/KX_SceneActuator.cpp292
-rw-r--r--source/gameengine/Ketsji/KX_SceneActuator.h109
-rw-r--r--source/gameengine/Ketsji/KX_SoundActuator.cpp571
-rw-r--r--source/gameengine/Ketsji/KX_SoundActuator.h127
-rw-r--r--source/gameengine/Ketsji/KX_StateActuator.cpp171
-rw-r--r--source/gameengine/Ketsji/KX_StateActuator.h97
-rw-r--r--source/gameengine/Ketsji/KX_SteeringActuator.cpp639
-rw-r--r--source/gameengine/Ketsji/KX_SteeringActuator.h123
-rw-r--r--source/gameengine/Ketsji/KX_TimeCategoryLogger.cpp141
-rw-r--r--source/gameengine/Ketsji/KX_TimeCategoryLogger.h136
-rw-r--r--source/gameengine/Ketsji/KX_TimeLogger.cpp117
-rw-r--r--source/gameengine/Ketsji/KX_TimeLogger.h114
-rw-r--r--source/gameengine/Ketsji/KX_TouchEventManager.cpp246
-rw-r--r--source/gameengine/Ketsji/KX_TouchEventManager.h109
-rw-r--r--source/gameengine/Ketsji/KX_TouchSensor.cpp362
-rw-r--r--source/gameengine/Ketsji/KX_TouchSensor.h138
-rw-r--r--source/gameengine/Ketsji/KX_TrackToActuator.cpp430
-rw-r--r--source/gameengine/Ketsji/KX_TrackToActuator.h98
-rw-r--r--source/gameengine/Ketsji/KX_VehicleWrapper.cpp380
-rw-r--r--source/gameengine/Ketsji/KX_VehicleWrapper.h61
-rw-r--r--source/gameengine/Ketsji/KX_VertexProxy.cpp595
-rw-r--r--source/gameengine/Ketsji/KX_VertexProxy.h112
-rw-r--r--source/gameengine/Ketsji/KX_VisibilityActuator.cpp127
-rw-r--r--source/gameengine/Ketsji/KX_VisibilityActuator.h75
-rw-r--r--source/gameengine/Ketsji/KX_WorldInfo.cpp494
-rw-r--r--source/gameengine/Ketsji/KX_WorldInfo.h105
-rw-r--r--source/gameengine/Ketsji/KX_WorldIpoController.cpp125
-rw-r--r--source/gameengine/Ketsji/KX_WorldIpoController.h117
-rw-r--r--source/gameengine/Network/CMakeLists.txt48
-rw-r--r--source/gameengine/Network/LoopBackNetwork/CMakeLists.txt43
-rw-r--r--source/gameengine/Network/LoopBackNetwork/NG_LoopBackNetworkDeviceInterface.cpp112
-rw-r--r--source/gameengine/Network/LoopBackNetwork/NG_LoopBackNetworkDeviceInterface.h63
-rw-r--r--source/gameengine/Network/NG_NetworkDeviceInterface.h82
-rw-r--r--source/gameengine/Network/NG_NetworkMessage.cpp55
-rw-r--r--source/gameengine/Network/NG_NetworkMessage.h138
-rw-r--r--source/gameengine/Network/NG_NetworkObject.cpp46
-rw-r--r--source/gameengine/Network/NG_NetworkObject.h55
-rw-r--r--source/gameengine/Network/NG_NetworkScene.cpp272
-rw-r--r--source/gameengine/Network/NG_NetworkScene.h118
-rw-r--r--source/gameengine/Physics/Bullet/CMakeLists.txt73
-rw-r--r--source/gameengine/Physics/Bullet/CcdGraphicController.cpp152
-rw-r--r--source/gameengine/Physics/Bullet/CcdGraphicController.h90
-rw-r--r--source/gameengine/Physics/Bullet/CcdPhysicsController.cpp2668
-rw-r--r--source/gameengine/Physics/Bullet/CcdPhysicsController.h832
-rw-r--r--source/gameengine/Physics/Bullet/CcdPhysicsEnvironment.cpp3795
-rw-r--r--source/gameengine/Physics/Bullet/CcdPhysicsEnvironment.h345
-rw-r--r--source/gameengine/Physics/Dummy/CMakeLists.txt41
-rw-r--r--source/gameengine/Physics/Dummy/DummyPhysicsEnvironment.cpp121
-rw-r--r--source/gameengine/Physics/Dummy/DummyPhysicsEnvironment.h134
-rw-r--r--source/gameengine/Physics/common/PHY_DynamicTypes.h91
-rw-r--r--source/gameengine/Physics/common/PHY_ICharacter.h39
-rw-r--r--source/gameengine/Physics/common/PHY_IController.h63
-rw-r--r--source/gameengine/Physics/common/PHY_IGraphicController.h60
-rw-r--r--source/gameengine/Physics/common/PHY_IMotionState.h68
-rw-r--r--source/gameengine/Physics/common/PHY_IPhysicsController.h154
-rw-r--r--source/gameengine/Physics/common/PHY_IPhysicsEnvironment.h226
-rw-r--r--source/gameengine/Physics/common/PHY_IVehicle.h69
-rw-r--r--source/gameengine/Physics/common/PHY_Pro.h68
-rw-r--r--source/gameengine/Rasterizer/CMakeLists.txt92
-rw-r--r--source/gameengine/Rasterizer/RAS_2DFilterManager.cpp562
-rw-r--r--source/gameengine/Rasterizer/RAS_2DFilterManager.h114
-rw-r--r--source/gameengine/Rasterizer/RAS_BucketManager.cpp380
-rw-r--r--source/gameengine/Rasterizer/RAS_BucketManager.h93
-rw-r--r--source/gameengine/Rasterizer/RAS_CameraData.h79
-rw-r--r--source/gameengine/Rasterizer/RAS_Deformer.h103
-rw-r--r--source/gameengine/Rasterizer/RAS_FramingManager.cpp425
-rw-r--r--source/gameengine/Rasterizer/RAS_FramingManager.h316
-rw-r--r--source/gameengine/Rasterizer/RAS_ICanvas.cpp128
-rw-r--r--source/gameengine/Rasterizer/RAS_ICanvas.h287
-rw-r--r--source/gameengine/Rasterizer/RAS_ILightObject.h95
-rw-r--r--source/gameengine/Rasterizer/RAS_IOffScreen.h84
-rw-r--r--source/gameengine/Rasterizer/RAS_IPolygonMaterial.cpp292
-rw-r--r--source/gameengine/Rasterizer/RAS_IPolygonMaterial.h206
-rw-r--r--source/gameengine/Rasterizer/RAS_IRasterizer.h506
-rw-r--r--source/gameengine/Rasterizer/RAS_ISync.h48
-rw-r--r--source/gameengine/Rasterizer/RAS_MaterialBucket.cpp679
-rw-r--r--source/gameengine/Rasterizer/RAS_MaterialBucket.h267
-rw-r--r--source/gameengine/Rasterizer/RAS_MeshObject.cpp573
-rw-r--r--source/gameengine/Rasterizer/RAS_MeshObject.h161
-rw-r--r--source/gameengine/Rasterizer/RAS_ObjectColor.h41
-rw-r--r--source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Blur2DFilter.h55
-rw-r--r--source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Dilation2DFilter.h55
-rw-r--r--source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Erosion2DFilter.h54
-rw-r--r--source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_GrayScale2DFilter.h45
-rw-r--r--source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Invert2DFilter.h45
-rw-r--r--source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Laplacian2DFilter.h57
-rw-r--r--source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Prewitt2DFilter.h62
-rw-r--r--source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Sepia2DFilter.h45
-rw-r--r--source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Sharpen2DFilter.h55
-rw-r--r--source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Sobel2DFilter.h61
-rw-r--r--source/gameengine/Rasterizer/RAS_OpenGLRasterizer/CMakeLists.txt72
-rw-r--r--source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_IStorage.h56
-rw-r--r--source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_ListRasterizer.cpp278
-rw-r--r--source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_ListRasterizer.h77
-rw-r--r--source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLLight.cpp300
-rw-r--r--source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLLight.h56
-rw-r--r--source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLOffScreen.cpp347
-rw-r--r--source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLOffScreen.h65
-rw-r--r--source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLRasterizer.cpp1694
-rw-r--r--source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLRasterizer.h343
-rw-r--r--source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLSync.cpp82
-rw-r--r--source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLSync.h50
-rw-r--r--source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_StorageVA.cpp260
-rw-r--r--source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_StorageVA.h77
-rw-r--r--source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_StorageVBO.cpp227
-rw-r--r--source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_StorageVBO.h100
-rw-r--r--source/gameengine/Rasterizer/RAS_Polygon.cpp123
-rw-r--r--source/gameengine/Rasterizer/RAS_Polygon.h101
-rw-r--r--source/gameengine/Rasterizer/RAS_Rect.h104
-rw-r--r--source/gameengine/Rasterizer/RAS_TexMatrix.h42
-rw-r--r--source/gameengine/Rasterizer/RAS_TexVert.cpp164
-rw-r--r--source/gameengine/Rasterizer/RAS_TexVert.h146
-rw-r--r--source/gameengine/Rasterizer/RAS_texmatrix.cpp131
-rw-r--r--source/gameengine/SceneGraph/CMakeLists.txt53
-rw-r--r--source/gameengine/SceneGraph/SG_BBox.cpp262
-rw-r--r--source/gameengine/SceneGraph/SG_BBox.h143
-rw-r--r--source/gameengine/SceneGraph/SG_Controller.cpp46
-rw-r--r--source/gameengine/SceneGraph/SG_Controller.h124
-rw-r--r--source/gameengine/SceneGraph/SG_DList.h251
-rw-r--r--source/gameengine/SceneGraph/SG_IObject.cpp111
-rw-r--r--source/gameengine/SceneGraph/SG_IObject.h374
-rw-r--r--source/gameengine/SceneGraph/SG_Node.cpp227
-rw-r--r--source/gameengine/SceneGraph/SG_Node.h278
-rw-r--r--source/gameengine/SceneGraph/SG_ParentRelation.h139
-rw-r--r--source/gameengine/SceneGraph/SG_QList.h164
-rw-r--r--source/gameengine/SceneGraph/SG_Spatial.cpp217
-rw-r--r--source/gameengine/SceneGraph/SG_Spatial.h294
-rw-r--r--source/gameengine/SceneGraph/SG_Tree.cpp422
-rw-r--r--source/gameengine/SceneGraph/SG_Tree.h163
-rw-r--r--source/gameengine/VideoTexture/BlendType.h86
-rw-r--r--source/gameengine/VideoTexture/CMakeLists.txt119
-rw-r--r--source/gameengine/VideoTexture/Common.h64
-rw-r--r--source/gameengine/VideoTexture/DeckLink.cpp813
-rw-r--r--source/gameengine/VideoTexture/DeckLink.h86
-rw-r--r--source/gameengine/VideoTexture/Exception.cpp241
-rw-r--r--source/gameengine/VideoTexture/Exception.h239
-rw-r--r--source/gameengine/VideoTexture/FilterBase.cpp160
-rw-r--r--source/gameengine/VideoTexture/FilterBase.h161
-rw-r--r--source/gameengine/VideoTexture/FilterBlueScreen.cpp190
-rw-r--r--source/gameengine/VideoTexture/FilterBlueScreen.h105
-rw-r--r--source/gameengine/VideoTexture/FilterColor.cpp354
-rw-r--r--source/gameengine/VideoTexture/FilterColor.h176
-rw-r--r--source/gameengine/VideoTexture/FilterNormal.cpp173
-rw-r--r--source/gameengine/VideoTexture/FilterNormal.h115
-rw-r--r--source/gameengine/VideoTexture/FilterSource.cpp176
-rw-r--r--source/gameengine/VideoTexture/FilterSource.h352
-rw-r--r--source/gameengine/VideoTexture/ImageBase.cpp834
-rw-r--r--source/gameengine/VideoTexture/ImageBase.h392
-rw-r--r--source/gameengine/VideoTexture/ImageBuff.cpp424
-rw-r--r--source/gameengine/VideoTexture/ImageBuff.h69
-rw-r--r--source/gameengine/VideoTexture/ImageMix.cpp216
-rw-r--r--source/gameengine/VideoTexture/ImageMix.h131
-rw-r--r--source/gameengine/VideoTexture/ImageRender.cpp946
-rw-r--r--source/gameengine/VideoTexture/ImageRender.h125
-rw-r--r--source/gameengine/VideoTexture/ImageViewport.cpp467
-rw-r--r--source/gameengine/VideoTexture/ImageViewport.h113
-rw-r--r--source/gameengine/VideoTexture/PyTypeList.cpp97
-rw-r--r--source/gameengine/VideoTexture/PyTypeList.h100
-rw-r--r--source/gameengine/VideoTexture/Texture.cpp533
-rw-r--r--source/gameengine/VideoTexture/Texture.h99
-rw-r--r--source/gameengine/VideoTexture/VideoBase.cpp254
-rw-r--r--source/gameengine/VideoTexture/VideoBase.h207
-rw-r--r--source/gameengine/VideoTexture/VideoDeckLink.cpp1228
-rw-r--r--source/gameengine/VideoTexture/VideoDeckLink.h256
-rw-r--r--source/gameengine/VideoTexture/VideoFFmpeg.cpp1392
-rw-r--r--source/gameengine/VideoTexture/VideoFFmpeg.h219
-rw-r--r--source/gameengine/VideoTexture/blendVideoTex.cpp266
503 files changed, 0 insertions, 126193 deletions
diff --git a/source/gameengine/BlenderRoutines/BL_KetsjiEmbedStart.cpp b/source/gameengine/BlenderRoutines/BL_KetsjiEmbedStart.cpp
deleted file mode 100644
index 4e8f0eba9b7..00000000000
--- a/source/gameengine/BlenderRoutines/BL_KetsjiEmbedStart.cpp
+++ /dev/null
@@ -1,683 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- * Blender's Ketsji startpoint
- */
-
-/** \file gameengine/BlenderRoutines/BL_KetsjiEmbedStart.cpp
- * \ingroup blroutines
- */
-
-
-#include <signal.h>
-#include <stdlib.h>
-#include <stdio.h>
-
-#ifdef _MSC_VER
- /* don't show stl-warnings */
-# pragma warning (disable:4786)
-#endif
-
-#include "GPU_glew.h"
-
-#include "KX_BlenderCanvas.h"
-#include "KX_BlenderKeyboardDevice.h"
-#include "KX_BlenderMouseDevice.h"
-#include "KX_BlenderSystem.h"
-#include "BL_Material.h"
-
-#include "KX_KetsjiEngine.h"
-#include "KX_BlenderSceneConverter.h"
-#include "KX_PythonInit.h"
-#include "KX_PyConstraintBinding.h"
-#include "KX_PythonMain.h"
-
-#include "RAS_OpenGLRasterizer.h"
-#include "RAS_ListRasterizer.h"
-
-#include "NG_LoopBackNetworkDeviceInterface.h"
-
-#include "BL_System.h"
-
-#include "GPU_extensions.h"
-#include "EXP_Value.h"
-
-
-extern "C" {
- #include "DNA_object_types.h"
- #include "DNA_view3d_types.h"
- #include "DNA_screen_types.h"
- #include "DNA_userdef_types.h"
- #include "DNA_scene_types.h"
- #include "DNA_windowmanager_types.h"
-
- #include "BKE_global.h"
- #include "BKE_report.h"
- #include "BKE_ipo.h"
- #include "BKE_main.h"
- #include "BKE_context.h"
- #include "BKE_sound.h"
-
- /* avoid c++ conflict with 'new' */
- #define new _new
- #include "BKE_screen.h"
- #undef new
-
- #include "MEM_guardedalloc.h"
-
- #include "BLI_blenlib.h"
- #include "BLO_readfile.h"
-
- #include "../../blender/windowmanager/WM_types.h"
- #include "../../blender/windowmanager/wm_window.h"
-
-/* avoid more includes (not used by BGE) */
-typedef void * wmUIHandlerFunc;
-typedef void * wmUIHandlerRemoveFunc;
-
- #include "../../blender/windowmanager/wm_event_system.h"
-}
-
-#ifdef WITH_AUDASPACE
-# include <AUD_Device.h>
-#endif
-
-static BlendFileData *load_game_data(const char *filename)
-{
- ReportList reports;
- BlendFileData *bfd;
-
- BKE_reports_init(&reports, RPT_STORE);
- bfd= BLO_read_from_file(filename, &reports, BLO_READ_SKIP_USERDEF);
-
- if (!bfd) {
- printf("Loading %s failed: ", filename);
- BKE_reports_print(&reports, RPT_ERROR);
- }
-
- BKE_reports_clear(&reports);
-
- return bfd;
-}
-
-static int BL_KetsjiNextFrame(KX_KetsjiEngine *ketsjiengine, bContext *C, wmWindow *win, Scene *scene, ARegion *ar,
- KX_BlenderKeyboardDevice* keyboarddevice, KX_BlenderMouseDevice* mousedevice, int draw_letterbox)
-{
- int exitrequested;
-
- // first check if we want to exit
- exitrequested = ketsjiengine->GetExitCode();
-
- // kick the engine
- bool render = ketsjiengine->NextFrame();
-
- if (render) {
- if (draw_letterbox) {
- // Clear screen to border color
- // We do this here since we set the canvas to be within the frames. This means the engine
- // itself is unaware of the extra space, so we clear the whole region for it.
- glClearColor(scene->gm.framing.col[0], scene->gm.framing.col[1], scene->gm.framing.col[2], 1.0f);
- glViewport(ar->winrct.xmin, ar->winrct.ymin,
- BLI_rcti_size_x(&ar->winrct), BLI_rcti_size_y(&ar->winrct));
- glClear(GL_COLOR_BUFFER_BIT);
- }
-
- // render the frame
- ketsjiengine->Render();
- }
-
- wm_window_process_events_nosleep();
-
- // test for the ESC key
- //XXX while (qtest())
- while (wmEvent *event= (wmEvent *)win->queue.first) {
- short val = 0;
- //unsigned short event = 0; //XXX extern_qread(&val);
- unsigned int unicode = event->utf8_buf[0] ? BLI_str_utf8_as_unicode(event->utf8_buf) : event->ascii;
-
- if (keyboarddevice->ConvertBlenderEvent(event->type, event->val, unicode))
- exitrequested = KX_EXIT_REQUEST_BLENDER_ESC;
-
- /* Coordinate conversion... where
- * should this really be?
- */
- if (event->type == MOUSEMOVE) {
- /* Note, not nice! XXX 2.5 event hack */
- val = event->x - ar->winrct.xmin;
- mousedevice->ConvertBlenderEvent(MOUSEX, val, 0);
-
- val = ar->winy - (event->y - ar->winrct.ymin) - 1;
- mousedevice->ConvertBlenderEvent(MOUSEY, val, 0);
- }
- else {
- mousedevice->ConvertBlenderEvent(event->type, event->val, 0);
- }
-
- BLI_remlink(&win->queue, event);
- wm_event_free(event);
- }
-
- if (win != CTX_wm_window(C)) {
- exitrequested= KX_EXIT_REQUEST_OUTSIDE; /* window closed while bge runs */
- }
- return exitrequested;
-}
-
-
-#ifdef WITH_PYTHON
-static struct BL_KetsjiNextFrameState {
- class KX_KetsjiEngine* ketsjiengine;
- struct bContext *C;
- struct wmWindow* win;
- struct Scene* scene;
- struct ARegion *ar;
- KX_BlenderKeyboardDevice* keyboarddevice;
- KX_BlenderMouseDevice* mousedevice;
- int draw_letterbox;
-} ketsjinextframestate;
-
-static int BL_KetsjiPyNextFrame(void *state0)
-{
- BL_KetsjiNextFrameState *state = (BL_KetsjiNextFrameState *) state0;
- return BL_KetsjiNextFrame(
- state->ketsjiengine,
- state->C,
- state->win,
- state->scene,
- state->ar,
- state->keyboarddevice,
- state->mousedevice,
- state->draw_letterbox);
-}
-#endif
-
-
-extern "C" void StartKetsjiShell(struct bContext *C, struct ARegion *ar, rcti *cam_frame, int always_use_expand_framing)
-{
- /* context values */
- struct wmWindowManager *wm= CTX_wm_manager(C);
- struct wmWindow *win= CTX_wm_window(C);
- struct Scene *startscene= CTX_data_scene(C);
- struct Main* maggie1= CTX_data_main(C);
-
-
- RAS_Rect area_rect;
- area_rect.SetLeft(cam_frame->xmin);
- area_rect.SetBottom(cam_frame->ymin);
- area_rect.SetRight(cam_frame->xmax);
- area_rect.SetTop(cam_frame->ymax);
-
- int exitrequested = KX_EXIT_REQUEST_NO_REQUEST;
- Main* blenderdata = maggie1;
-
- char* startscenename = startscene->id.name+2;
- char pathname[FILE_MAXDIR+FILE_MAXFILE], oldsce[FILE_MAXDIR+FILE_MAXFILE];
- STR_String exitstring = "";
- BlendFileData *bfd= NULL;
-
- BLI_strncpy(pathname, blenderdata->name, sizeof(pathname));
- BLI_strncpy(oldsce, G.main->name, sizeof(oldsce));
-#ifdef WITH_PYTHON
- resetGamePythonPath(); // need this so running a second time wont use an old blendfiles path
- setGamePythonPath(G.main->name);
-
- // Acquire Python's GIL (global interpreter lock)
- // so we can safely run Python code and API calls
- PyGILState_STATE gilstate = PyGILState_Ensure();
-
- PyObject *pyGlobalDict = PyDict_New(); /* python utility storage, spans blend file loading */
-#endif
-
- // Globals to be carried on over blender files
- GlobalSettings gs;
- gs.matmode= startscene->gm.matmode;
- gs.glslflag= startscene->gm.flag;
-
- do
- {
- View3D *v3d= CTX_wm_view3d(C);
- RegionView3D *rv3d= CTX_wm_region_view3d(C);
-
- // get some preferences
- SYS_SystemHandle syshandle = SYS_GetSystem();
- bool properties = (SYS_GetCommandLineInt(syshandle, "show_properties", 0) != 0);
- bool usefixed = (SYS_GetCommandLineInt(syshandle, "fixedtime", 0) != 0);
- bool profile = (SYS_GetCommandLineInt(syshandle, "show_profile", 0) != 0);
- bool frameRate = (SYS_GetCommandLineInt(syshandle, "show_framerate", 0) != 0);
- bool animation_record = (SYS_GetCommandLineInt(syshandle, "animation_record", 0) != 0);
- bool displaylists = false; // (SYS_GetCommandLineInt(syshandle, "displaylists", 0) != 0) && GPU_display_list_support();
-#ifdef WITH_PYTHON
- bool nodepwarnings = (SYS_GetCommandLineInt(syshandle, "ignore_deprecation_warnings", 0) != 0);
-#endif
- // bool novertexarrays = (SYS_GetCommandLineInt(syshandle, "novertexarrays", 0) != 0);
- bool mouse_state = (startscene->gm.flag & GAME_SHOW_MOUSE) != 0;
- bool restrictAnimFPS = (startscene->gm.flag & GAME_RESTRICT_ANIM_UPDATES) != 0;
-
- short drawtype = v3d->drawtype;
-
- /* we do not support material mode in game engine, force change to texture mode */
- if (drawtype == OB_MATERIAL) drawtype = OB_TEXTURE;
- if (animation_record) usefixed= false; /* override since you don't want to run full-speed for sim recording */
-
- // create the canvas and rasterizer
- RAS_ICanvas* canvas = new KX_BlenderCanvas(wm, win, area_rect, ar);
-
- // default mouse state set on render panel
- if (mouse_state)
- canvas->SetMouseState(RAS_ICanvas::MOUSE_NORMAL);
- else
- canvas->SetMouseState(RAS_ICanvas::MOUSE_INVISIBLE);
-
- // Setup vsync
- int previous_vsync = 0;
- canvas->GetSwapInterval(previous_vsync);
- if (startscene->gm.vsync == VSYNC_ADAPTIVE)
- canvas->SetSwapInterval(-1);
- else
- canvas->SetSwapInterval((startscene->gm.vsync == VSYNC_ON) ? 1 : 0);
-
- RAS_IRasterizer* rasterizer = NULL;
- RAS_STORAGE_TYPE raster_storage = RAS_AUTO_STORAGE;
-
- if (startscene->gm.raster_storage == RAS_STORE_VBO) {
- raster_storage = RAS_VBO;
- }
- else if (startscene->gm.raster_storage == RAS_STORE_VA) {
- raster_storage = RAS_VA;
- }
- //Don't use displaylists with VBOs
- //If auto starts using VBOs, make sure to check for that here
- if (displaylists && raster_storage != RAS_VBO)
- rasterizer = new RAS_ListRasterizer(canvas, true, raster_storage);
- else
- rasterizer = new RAS_OpenGLRasterizer(canvas, raster_storage);
-
- RAS_IRasterizer::MipmapOption mipmapval = rasterizer->GetMipmapping();
-
-
- // create the inputdevices
- KX_BlenderKeyboardDevice* keyboarddevice = new KX_BlenderKeyboardDevice();
- KX_BlenderMouseDevice* mousedevice = new KX_BlenderMouseDevice();
-
- // create a networkdevice
- NG_NetworkDeviceInterface* networkdevice = new
- NG_LoopBackNetworkDeviceInterface();
-
- //
- // create a ketsji/blendersystem (only needed for timing and stuff)
- KX_BlenderSystem* kxsystem = new KX_BlenderSystem();
-
- // create the ketsjiengine
- KX_KetsjiEngine* ketsjiengine = new KX_KetsjiEngine(kxsystem);
-
- // set the devices
- ketsjiengine->SetKeyboardDevice(keyboarddevice);
- ketsjiengine->SetMouseDevice(mousedevice);
- ketsjiengine->SetNetworkDevice(networkdevice);
- ketsjiengine->SetCanvas(canvas);
- ketsjiengine->SetRasterizer(rasterizer);
- ketsjiengine->SetUseFixedTime(usefixed);
- ketsjiengine->SetTimingDisplay(frameRate, profile, properties);
- ketsjiengine->SetRestrictAnimationFPS(restrictAnimFPS);
- ketsjiengine->SetRender(true);
- KX_KetsjiEngine::SetExitKey(ConvertKeyCode(startscene->gm.exitkey));
-
- //set the global settings (carried over if restart/load new files)
- ketsjiengine->SetGlobalSettings(&gs);
-
-#ifdef WITH_PYTHON
- CValue::SetDeprecationWarnings(nodepwarnings);
-#endif
-
- //lock frame and camera enabled - storing global values
- int tmp_lay= startscene->lay;
- Object *tmp_camera = startscene->camera;
-
- if (v3d->scenelock==0) {
- startscene->lay= v3d->lay;
- startscene->camera= v3d->camera;
- }
-
- // some blender stuff
- float camzoom = 1.0f;
- int draw_letterbox = 0;
-
- if (rv3d->persp==RV3D_CAMOB) {
- if (startscene->gm.framing.type == SCE_GAMEFRAMING_BARS) { /* Letterbox */
- draw_letterbox = 1;
- }
- else {
- camzoom = 1.0f / BKE_screen_view3d_zoom_to_fac(rv3d->camzoom);
- }
- }
-
- rasterizer->SetDrawingMode(drawtype);
- ketsjiengine->SetCameraZoom(camzoom);
- ketsjiengine->SetCameraOverrideZoom(2.0f);
-
- // if we got an exitcode 3 (KX_EXIT_REQUEST_START_OTHER_GAME) load a different file
- if (exitrequested == KX_EXIT_REQUEST_START_OTHER_GAME || exitrequested == KX_EXIT_REQUEST_RESTART_GAME)
- {
- exitrequested = KX_EXIT_REQUEST_NO_REQUEST;
- if (bfd) BLO_blendfiledata_free(bfd);
-
- char basedpath[FILE_MAX];
- // base the actuator filename with respect
- // to the original file working directory
-
- if (exitstring != "")
- BLI_strncpy(basedpath, exitstring.ReadPtr(), sizeof(basedpath));
-
- // load relative to the last loaded file, this used to be relative
- // to the first file but that makes no sense, relative paths in
- // blend files should be relative to that file, not some other file
- // that happened to be loaded first
- BLI_path_abs(basedpath, pathname);
- bfd = load_game_data(basedpath);
-
- // if it wasn't loaded, try it forced relative
- if (!bfd)
- {
- // just add "//" in front of it
- char temppath[FILE_MAX] = "//";
- BLI_strncpy(temppath + 2, basedpath, FILE_MAX - 2);
-
- BLI_path_abs(temppath, pathname);
- bfd = load_game_data(temppath);
- }
-
- // if we got a loaded blendfile, proceed
- if (bfd)
- {
- blenderdata = bfd->main;
- startscenename = bfd->curscene->id.name + 2;
-
- if (blenderdata) {
- BLI_strncpy(G.main->name, blenderdata->name, sizeof(G.main->name));
- BLI_strncpy(pathname, blenderdata->name, sizeof(pathname));
-#ifdef WITH_PYTHON
- setGamePythonPath(G.main->name);
-#endif
- }
- }
- // else forget it, we can't find it
- else
- {
- exitrequested = KX_EXIT_REQUEST_QUIT_GAME;
- }
- }
-
- Scene *scene= bfd ? bfd->curscene : (Scene *)BLI_findstring(&blenderdata->scene, startscenename, offsetof(ID, name) + 2);
-
- if (scene)
- {
- int startFrame = scene->r.cfra;
- ketsjiengine->SetAnimRecordMode(animation_record, startFrame);
-
- // Quad buffered needs a special window.
- if (scene->gm.stereoflag == STEREO_ENABLED) {
- if (scene->gm.stereomode != RAS_IRasterizer::RAS_STEREO_QUADBUFFERED)
- rasterizer->SetStereoMode((RAS_IRasterizer::StereoMode) scene->gm.stereomode);
-
- rasterizer->SetEyeSeparation(scene->gm.eyeseparation);
- }
-
- rasterizer->SetBackColor(scene->gm.framing.col);
- }
-
- if (exitrequested != KX_EXIT_REQUEST_QUIT_GAME)
- {
- if (rv3d->persp != RV3D_CAMOB)
- {
- ketsjiengine->EnableCameraOverride(startscenename);
- ketsjiengine->SetCameraOverrideUseOrtho((rv3d->persp == RV3D_ORTHO));
- ketsjiengine->SetCameraOverrideProjectionMatrix(MT_CmMatrix4x4(rv3d->winmat));
- ketsjiengine->SetCameraOverrideViewMatrix(MT_CmMatrix4x4(rv3d->viewmat));
- ketsjiengine->SetCameraOverrideClipping(v3d->near, v3d->far);
- ketsjiengine->SetCameraOverrideLens(v3d->lens);
- }
-
- // create a scene converter, create and convert the startingscene
- KX_ISceneConverter* sceneconverter = new KX_BlenderSceneConverter(blenderdata, ketsjiengine);
- ketsjiengine->SetSceneConverter(sceneconverter);
- if (always_use_expand_framing)
- sceneconverter->SetAlwaysUseExpandFraming(true);
-
- sceneconverter->SetMaterials(true);
-
- if (gs.matmode == GAME_MAT_GLSL)
- sceneconverter->SetGLSLMaterials(true);
- if (scene->gm.flag & GAME_NO_MATERIAL_CACHING)
- sceneconverter->SetCacheMaterials(false);
-
- KX_Scene* startscene = new KX_Scene(keyboarddevice,
- mousedevice,
- networkdevice,
- startscenename,
- scene,
- canvas);
-
-#ifdef WITH_PYTHON
- // some python things
- PyObject *gameLogic, *gameLogic_keys;
- setupGamePython(ketsjiengine, startscene, blenderdata, pyGlobalDict, &gameLogic, &gameLogic_keys, 0, NULL);
-#endif // WITH_PYTHON
-
- //initialize Dome Settings
- if (scene->gm.stereoflag == STEREO_DOME)
- ketsjiengine->InitDome(scene->gm.dome.res, scene->gm.dome.mode, scene->gm.dome.angle, scene->gm.dome.resbuf, scene->gm.dome.tilt, scene->gm.dome.warptext);
-
- // initialize 3D Audio Settings
- AUD_Device* device = BKE_sound_get_device();
- AUD_Device_setSpeedOfSound(device, scene->audio.speed_of_sound);
- AUD_Device_setDopplerFactor(device, scene->audio.doppler_factor);
- AUD_Device_setDistanceModel(device, AUD_DistanceModel(scene->audio.distance_model));
-
- // from see blender.c:
- // FIXME: this version patching should really be part of the file-reading code,
- // but we still get too many unrelated data-corruption crashes otherwise...
- if (blenderdata->versionfile < 250)
- do_versions_ipos_to_animato(blenderdata);
-
- if (sceneconverter)
- {
- // convert and add scene
- sceneconverter->ConvertScene(
- startscene,
- rasterizer,
- canvas);
- ketsjiengine->AddScene(startscene);
-
- // init the rasterizer
- rasterizer->Init();
-
- // start the engine
- ketsjiengine->StartEngine(true);
-
-
- // Set the animation playback rate for ipo's and actions
- // the framerate below should patch with FPS macro defined in blendef.h
- // Could be in StartEngine set the framerate, we need the scene to do this
- ketsjiengine->SetAnimFrameRate(FPS);
-
-#ifdef WITH_PYTHON
- char *python_main = NULL;
- pynextframestate.state = NULL;
- pynextframestate.func = NULL;
- python_main = KX_GetPythonMain(scene);
-
- // the mainloop
- printf("\nBlender Game Engine Started\n");
- if (python_main) {
- char *python_code = KX_GetPythonCode(blenderdata, python_main);
- if (python_code) {
- // Set python environement variable.
- KX_SetActiveScene(startscene);
- PHY_SetActiveEnvironment(startscene->GetPhysicsEnvironment());
-
- ketsjinextframestate.ketsjiengine = ketsjiengine;
- ketsjinextframestate.C = C;
- ketsjinextframestate.win = win;
- ketsjinextframestate.scene = scene;
- ketsjinextframestate.ar = ar;
- ketsjinextframestate.keyboarddevice = keyboarddevice;
- ketsjinextframestate.mousedevice = mousedevice;
- ketsjinextframestate.draw_letterbox = draw_letterbox;
-
- pynextframestate.state = &ketsjinextframestate;
- pynextframestate.func = &BL_KetsjiPyNextFrame;
- printf("Yielding control to Python script '%s'...\n", python_main);
- PyRun_SimpleString(python_code);
- printf("Exit Python script '%s'\n", python_main);
- MEM_freeN(python_code);
- }
- }
- else
-#endif /* WITH_PYTHON */
- {
- while (!exitrequested)
- {
- exitrequested = BL_KetsjiNextFrame(ketsjiengine, C, win, scene, ar, keyboarddevice, mousedevice, draw_letterbox);
- }
- }
- printf("Blender Game Engine Finished\n");
- exitstring = ketsjiengine->GetExitString();
-#ifdef WITH_PYTHON
- if (python_main) MEM_freeN(python_main);
-#endif /* WITH_PYTHON */
-
- gs = *(ketsjiengine->GetGlobalSettings());
-
- // when exiting the mainloop
-#ifdef WITH_PYTHON
- // Clears the dictionary by hand:
- // This prevents, extra references to global variables
- // inside the GameLogic dictionary when the python interpreter is finalized.
- // which allows the scene to safely delete them :)
- // see: (space.c)->start_game
-
- //PyDict_Clear(PyModule_GetDict(gameLogic));
-
- // Keep original items, means python plugins will autocomplete members
- PyObject *gameLogic_keys_new = PyDict_Keys(PyModule_GetDict(gameLogic));
- const Py_ssize_t numitems= PyList_GET_SIZE(gameLogic_keys_new);
- Py_ssize_t listIndex;
- for (listIndex=0; listIndex < numitems; listIndex++) {
- PyObject *item = PyList_GET_ITEM(gameLogic_keys_new, listIndex);
- if (!PySequence_Contains(gameLogic_keys, item)) {
- PyDict_DelItem( PyModule_GetDict(gameLogic), item);
- }
- }
- Py_DECREF(gameLogic_keys_new);
- gameLogic_keys_new = NULL;
-#endif
- ketsjiengine->StopEngine();
-#ifdef WITH_PYTHON
- exitGamePythonScripting();
-#endif
- networkdevice->Disconnect();
- }
- if (sceneconverter)
- {
- delete sceneconverter;
- sceneconverter = NULL;
- }
-
-#ifdef WITH_PYTHON
- Py_DECREF(gameLogic_keys);
- gameLogic_keys = NULL;
-#endif
- }
- //lock frame and camera enabled - restoring global values
- if (v3d->scenelock==0) {
- startscene->lay= tmp_lay;
- startscene->camera= tmp_camera;
- }
-
- if (exitrequested != KX_EXIT_REQUEST_OUTSIDE)
- {
- // set the cursor back to normal
- canvas->SetMouseState(RAS_ICanvas::MOUSE_NORMAL);
-
- // set mipmap setting back to its original value
- rasterizer->SetMipmapping(mipmapval);
- }
-
- // clean up some stuff
- if (ketsjiengine)
- {
- delete ketsjiengine;
- ketsjiengine = NULL;
- }
- if (kxsystem)
- {
- delete kxsystem;
- kxsystem = NULL;
- }
- if (networkdevice)
- {
- delete networkdevice;
- networkdevice = NULL;
- }
- if (keyboarddevice)
- {
- delete keyboarddevice;
- keyboarddevice = NULL;
- }
- if (mousedevice)
- {
- delete mousedevice;
- mousedevice = NULL;
- }
- if (rasterizer)
- {
- delete rasterizer;
- rasterizer = NULL;
- }
- if (canvas)
- {
- canvas->SetSwapInterval(previous_vsync); // Set the swap interval back
- delete canvas;
- canvas = NULL;
- }
-
- // stop all remaining playing sounds
- AUD_Device_stopAll(BKE_sound_get_device());
-
- } while (exitrequested == KX_EXIT_REQUEST_RESTART_GAME || exitrequested == KX_EXIT_REQUEST_START_OTHER_GAME);
-
- if (bfd) BLO_blendfiledata_free(bfd);
-
- BLI_strncpy(G.main->name, oldsce, sizeof(G.main->name));
-
-#ifdef WITH_PYTHON
- PyDict_Clear(pyGlobalDict);
- Py_DECREF(pyGlobalDict);
-
- // Release Python's GIL
- PyGILState_Release(gilstate);
-#endif
-
-}
diff --git a/source/gameengine/BlenderRoutines/BL_System.cpp b/source/gameengine/BlenderRoutines/BL_System.cpp
deleted file mode 100644
index 251182a07aa..00000000000
--- a/source/gameengine/BlenderRoutines/BL_System.cpp
+++ /dev/null
@@ -1,102 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- * Interface to the commandline arguments
- */
-
-/** \file gameengine/BlenderRoutines/BL_System.cpp
- * \ingroup blroutines
- */
-
-#include "CTR_Map.h"
-#include "STR_HashedString.h"
-#include "BL_System.h"
-
-struct SingletonSystem {
- CTR_Map<STR_HashedString,int> int_params;
- CTR_Map<STR_HashedString,float> float_params;
- CTR_Map<STR_HashedString,STR_String> string_params;
-};
-
-static SingletonSystem *_system_instance = NULL;
-
-SYS_SystemHandle SYS_GetSystem()
-{
- if (!_system_instance)
- _system_instance = new SingletonSystem();
-
- return (SYS_SystemHandle)_system_instance;
-}
-
-void SYS_DeleteSystem(SYS_SystemHandle sys)
-{
- if (_system_instance) {
- delete _system_instance;
- _system_instance = NULL;
- }
-}
-
-int SYS_GetCommandLineInt(SYS_SystemHandle sys, const char *paramname, int defaultvalue)
-{
- int *result = ((SingletonSystem *)sys)->int_params[paramname];
- if (result)
- return *result;
-
- return defaultvalue;
-}
-
-float SYS_GetCommandLineFloat(SYS_SystemHandle sys, const char *paramname, float defaultvalue)
-{
- float *result = ((SingletonSystem *)sys)->float_params[paramname];
- if (result)
- return *result;
-
- return defaultvalue;
-}
-
-const char *SYS_GetCommandLineString(SYS_SystemHandle sys, const char *paramname, const char *defaultvalue)
-{
- STR_String *result = ((SingletonSystem *)sys)->string_params[paramname];
- if (result)
- return *result;
-
- return defaultvalue;
-}
-
-void SYS_WriteCommandLineInt(SYS_SystemHandle sys, const char *paramname, int value)
-{
- ((SingletonSystem *)sys)->int_params.insert(paramname, value);
-}
-
-void SYS_WriteCommandLineFloat(SYS_SystemHandle sys, const char *paramname, float value)
-{
- ((SingletonSystem *)sys)->float_params.insert(paramname, value);
-}
-
-void SYS_WriteCommandLineString(SYS_SystemHandle sys, const char *paramname, const char *value)
-{
- ((SingletonSystem *)sys)->string_params.insert(paramname, value);
-}
-
diff --git a/source/gameengine/BlenderRoutines/BL_System.h b/source/gameengine/BlenderRoutines/BL_System.h
deleted file mode 100644
index b9f51393f44..00000000000
--- a/source/gameengine/BlenderRoutines/BL_System.h
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- * System specific information / access.
- * Interface to the commandline arguments
- */
-
-/** \file gameengine/BlenderRoutines/BL_System.h
- * \ingroup blroutines
- */
-
-#ifndef __BL_SYSTEM_H__
-#define __BL_SYSTEM_H__
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/* Game Engine command line parameters */
-
-typedef void* SYS_SystemHandle;
-
-extern SYS_SystemHandle SYS_GetSystem(void);
-extern void SYS_DeleteSystem(SYS_SystemHandle sys);
-
-extern int SYS_GetCommandLineInt(SYS_SystemHandle sys, const char *paramname, int defaultvalue);
-extern float SYS_GetCommandLineFloat(SYS_SystemHandle sys, const char *paramname, float defaultvalue);
-extern const char *SYS_GetCommandLineString(SYS_SystemHandle sys, const char *paramname, const char *defaultvalue);
-
-extern void SYS_WriteCommandLineInt(SYS_SystemHandle sys, const char *paramname, int value);
-extern void SYS_WriteCommandLineFloat(SYS_SystemHandle sys, const char *paramname, float value);
-extern void SYS_WriteCommandLineString(SYS_SystemHandle sys, const char *paramname, const char *value);
-
-/* Start game engine */
-
-struct bContext;
-struct ARegion;
-struct rcti;
-
-extern void StartKetsjiShell(struct bContext *C, struct ARegion *ar,
- struct rcti *cam_frame, int always_use_expand_framing);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* __BL_SYSTEM_H__ */
-
diff --git a/source/gameengine/BlenderRoutines/CMakeLists.txt b/source/gameengine/BlenderRoutines/CMakeLists.txt
deleted file mode 100644
index 42293050753..00000000000
--- a/source/gameengine/BlenderRoutines/CMakeLists.txt
+++ /dev/null
@@ -1,78 +0,0 @@
-
-set(INC
- .
- ../Converter
- ../Expressions
- ../GameLogic
- ../Ketsji
- ../Network
- ../Network/LoopBackNetwork
- ../Physics/Bullet
- ../Physics/common
- ../Rasterizer
- ../Rasterizer/RAS_OpenGLRasterizer
- ../SceneGraph
- ../../blender
- ../../blender/blenfont
- ../../blender/blenkernel
- ../../blender/blenlib
- ../../blender/blenloader
- ../../blender/editors/include
- ../../blender/gpu
- ../../blender/imbuf
- ../../blender/makesdna
- ../../blender/makesrna
- ../../blender/windowmanager
- ../../../intern/container
- ../../../intern/glew-mx
- ../../../intern/guardedalloc
- ../../../intern/string
-)
-
-set(INC_SYS
- ../../../intern/moto/include
- ${PTHREADS_INCLUDE_DIRS}
- ${GLEW_INCLUDE_PATH}
- ${BOOST_INCLUDE_DIR}
-)
-
-set(SRC
- BL_KetsjiEmbedStart.cpp
- BL_System.cpp
- KX_BlenderCanvas.cpp
- KX_BlenderInputDevice.cpp
- KX_BlenderKeyboardDevice.cpp
- KX_BlenderMouseDevice.cpp
- KX_BlenderSystem.cpp
-
- BL_System.h
- KX_BlenderCanvas.h
- KX_BlenderInputDevice.h
- KX_BlenderKeyboardDevice.h
- KX_BlenderMouseDevice.h
- KX_BlenderSystem.h
-)
-
-add_definitions(${GL_DEFINITIONS})
-
-if(WITH_AUDASPACE)
- add_definitions(-DWITH_AUDASPACE)
-
- list(APPEND INC_SYS
- ${AUDASPACE_C_INCLUDE_DIRS}
- )
-endif()
-
-if(WITH_CODEC_FFMPEG)
- add_definitions(-DWITH_FFMPEG)
-endif()
-
-if(WITH_BULLET)
- list(APPEND INC_SYS
- ${BULLET_INCLUDE_DIRS}
- )
- add_definitions(-DWITH_BULLET)
-endif()
-
-
-blender_add_lib(ge_blen_routines "${SRC}" "${INC}" "${INC_SYS}")
diff --git a/source/gameengine/BlenderRoutines/KX_BlenderCanvas.cpp b/source/gameengine/BlenderRoutines/KX_BlenderCanvas.cpp
deleted file mode 100644
index 6fdc823ba1a..00000000000
--- a/source/gameengine/BlenderRoutines/KX_BlenderCanvas.cpp
+++ /dev/null
@@ -1,352 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/BlenderRoutines/KX_BlenderCanvas.cpp
- * \ingroup blroutines
- */
-
-#include "GPU_glew.h"
-
-#include "MEM_guardedalloc.h"
-
-#include "KX_BlenderCanvas.h"
-
-#include "DNA_screen_types.h"
-#include "DNA_scene_types.h"
-#include "DNA_windowmanager_types.h"
-
-#include "BKE_image.h"
-
-#include <assert.h>
-#include <iostream>
-
-extern "C" {
-#include "WM_api.h"
-#include "wm_cursors.h"
-#include "wm_window.h"
-}
-
-KX_BlenderCanvas::KX_BlenderCanvas(wmWindowManager *wm, wmWindow *win, RAS_Rect &rect, struct ARegion *ar) :
-m_wm(wm),
-m_win(win),
-m_frame_rect(rect)
-{
- // initialize area so that it's available for game logic on frame 1 (ImageViewport)
- m_area_rect = rect;
- // area boundaries needed for mouse coordinates in Letterbox framing mode
- m_area_left = ar->winrct.xmin;
- m_area_top = ar->winrct.ymax;
- m_frame = 1;
-
- glGetIntegerv(GL_VIEWPORT, (GLint *)m_viewport);
-}
-
-KX_BlenderCanvas::~KX_BlenderCanvas()
-{
-}
-
-void KX_BlenderCanvas::Init()
-{
- glDepthFunc(GL_LEQUAL);
-}
-
-
-void KX_BlenderCanvas::SwapBuffers()
-{
- wm_window_swap_buffers(m_win);
-}
-
-void KX_BlenderCanvas::SetSwapInterval(int interval)
-{
- wm_window_set_swap_interval(m_win, interval);
-}
-
-bool KX_BlenderCanvas::GetSwapInterval(int &intervalOut)
-{
- return wm_window_get_swap_interval(m_win, &intervalOut);
-}
-
-void KX_BlenderCanvas::GetDisplayDimensions(int &width, int &height)
-{
- wm_get_screensize(&width, &height);
-}
-
-void KX_BlenderCanvas::ResizeWindow(int width, int height)
-{
- // Not implemented for the embedded player
-}
-
-void KX_BlenderCanvas::SetFullScreen(bool enable)
-{
- // Not implemented for the embedded player
-}
-
-bool KX_BlenderCanvas::GetFullScreen()
-{
- // Not implemented for the embedded player
- return false;
-}
-
-bool KX_BlenderCanvas::BeginDraw()
-{
- // in case of multi-window we need to ensure we are drawing to the correct
- // window always, because it may change in window event handling
- wm_window_make_drawable(m_wm, m_win);
- return true;
-}
-
-
-void KX_BlenderCanvas::EndDraw()
-{
- // nothing needs to be done here
-}
-
-void KX_BlenderCanvas::BeginFrame()
-{
- glEnable(GL_DEPTH_TEST);
- glDepthFunc(GL_LEQUAL);
-}
-
-
-void KX_BlenderCanvas::EndFrame()
-{
- glDisable(GL_FOG);
-}
-
-
-
-void KX_BlenderCanvas::ClearColor(float r,float g,float b,float a)
-{
- glClearColor(r,g,b,a);
-}
-
-
-
-void KX_BlenderCanvas::ClearBuffer(int type)
-{
- int ogltype = 0;
-
- if (type & RAS_ICanvas::COLOR_BUFFER )
- ogltype |= GL_COLOR_BUFFER_BIT;
-
- if (type & RAS_ICanvas::DEPTH_BUFFER )
- ogltype |= GL_DEPTH_BUFFER_BIT;
- glClear(ogltype);
-}
-
-int KX_BlenderCanvas::GetWidth(
-) const {
- return m_frame_rect.GetWidth();
-}
-
-int KX_BlenderCanvas::GetHeight(
-) const {
- return m_frame_rect.GetHeight();
-}
-
-int KX_BlenderCanvas::GetMouseX(int x)
-{
- int left = GetWindowArea().GetLeft();
- return x - (left - m_area_left);
-}
-
-int KX_BlenderCanvas::GetMouseY(int y)
-{
- int top = GetWindowArea().GetTop();
- return y - (m_area_top - top);
-}
-
-float KX_BlenderCanvas::GetMouseNormalizedX(int x)
-{
- int can_x = GetMouseX(x);
- return float(can_x)/this->GetWidth();
-}
-
-float KX_BlenderCanvas::GetMouseNormalizedY(int y)
-{
- int can_y = GetMouseY(y);
- return float(can_y)/this->GetHeight();
-}
-
-RAS_Rect &
-KX_BlenderCanvas::
-GetWindowArea(
-) {
- return m_area_rect;
-}
-
- void
-KX_BlenderCanvas::
-SetViewPort(
- int x1, int y1,
- int x2, int y2
-) {
- /* x1 and y1 are the min pixel coordinate (e.g. 0)
- * x2 and y2 are the max pixel coordinate
- * the width,height is calculated including both pixels
- * therefore: max - min + 1
- */
- int vp_width = (x2 - x1) + 1;
- int vp_height = (y2 - y1) + 1;
- int minx = m_frame_rect.GetLeft();
- int miny = m_frame_rect.GetBottom();
-
- m_area_rect.SetLeft(minx + x1);
- m_area_rect.SetBottom(miny + y1);
- m_area_rect.SetRight(minx + x2);
- m_area_rect.SetTop(miny + y2);
-
- m_viewport[0] = minx+x1;
- m_viewport[1] = miny+y1;
- m_viewport[2] = vp_width;
- m_viewport[3] = vp_height;
-
- glViewport(minx + x1, miny + y1, vp_width, vp_height);
- glScissor(minx + x1, miny + y1, vp_width, vp_height);
-}
-
- void
-KX_BlenderCanvas::
-UpdateViewPort(
- int x1, int y1,
- int x2, int y2
-) {
- m_viewport[0] = x1;
- m_viewport[1] = y1;
- m_viewport[2] = x2;
- m_viewport[3] = y2;
-}
-
- const int*
-KX_BlenderCanvas::
-GetViewPort() {
-#ifdef DEBUG
- // If we're in a debug build, we might as well make sure our values don't differ
- // from what the gpu thinks we have. This could lead to nasty, hard to find bugs.
- int viewport[4];
- glGetIntegerv(GL_VIEWPORT, viewport);
- assert(viewport[0] == m_viewport[0]);
- assert(viewport[1] == m_viewport[1]);
- assert(viewport[2] == m_viewport[2]);
- assert(viewport[3] == m_viewport[3]);
-#endif
-
- return m_viewport;
-}
-
-void KX_BlenderCanvas::SetMouseState(RAS_MouseState mousestate)
-{
- m_mousestate = mousestate;
-
- switch (mousestate)
- {
- case MOUSE_INVISIBLE:
- {
- WM_cursor_set(m_win, CURSOR_NONE);
- break;
- }
- case MOUSE_WAIT:
- {
- WM_cursor_set(m_win, CURSOR_WAIT);
- break;
- }
- case MOUSE_NORMAL:
- {
- WM_cursor_set(m_win, CURSOR_STD);
- break;
- }
- default:
- {
- }
- }
-}
-
-
-
-// (0,0) is top left, (width,height) is bottom right
-void KX_BlenderCanvas::SetMousePosition(int x,int y)
-{
- int winX = m_frame_rect.GetLeft();
- int winY = m_frame_rect.GetBottom();
- int winH = m_frame_rect.GetHeight();
-
- WM_cursor_warp(m_win, winX + x, winY + (winH-y));
-}
-
-
-/* get shot from frontbuffer sort of a copy from screendump.c */
-static unsigned int *screenshot(ScrArea *curarea, int *dumpsx, int *dumpsy)
-{
- int x=0, y=0;
- unsigned int *dumprect= NULL;
-
- x= curarea->totrct.xmin;
- y= curarea->totrct.ymin;
- *dumpsx= curarea->totrct.xmax-x;
- *dumpsy= curarea->totrct.ymax-y;
-
- if (*dumpsx && *dumpsy) {
-
- dumprect= (unsigned int *)MEM_mallocN(sizeof(int) * (*dumpsx) * (*dumpsy), "dumprect");
- glReadBuffer(GL_FRONT);
- glReadPixels(x, y, *dumpsx, *dumpsy, GL_RGBA, GL_UNSIGNED_BYTE, dumprect);
- glFinish();
- glReadBuffer(GL_BACK);
- }
-
- return dumprect;
-}
-
-void KX_BlenderCanvas::MakeScreenShot(const char *filename)
-{
- ScrArea area_dummy= {0};
- unsigned int *dumprect;
- int dumpsx, dumpsy;
-
- area_dummy.totrct.xmin = m_frame_rect.GetLeft();
- area_dummy.totrct.xmax = m_frame_rect.GetRight();
- area_dummy.totrct.ymin = m_frame_rect.GetBottom();
- area_dummy.totrct.ymax = m_frame_rect.GetTop();
-
- dumprect = screenshot(&area_dummy, &dumpsx, &dumpsy);
- if (!dumprect) {
- std::cerr << "KX_BlenderCanvas: Unable to take screenshot!" << std::endl;
- return;
- }
-
- /* initialize image file format data */
- Scene *scene = WM_window_get_active_scene(m_win);
- ImageFormatData *im_format = (ImageFormatData *)MEM_mallocN(sizeof(ImageFormatData), "im_format");
-
- if (scene)
- *im_format = scene->r.im_format;
- else
- BKE_imformat_defaults(im_format);
-
- /* save_screenshot() frees dumprect and im_format */
- save_screenshot(filename, dumpsx, dumpsy, dumprect, im_format);
-}
diff --git a/source/gameengine/BlenderRoutines/KX_BlenderCanvas.h b/source/gameengine/BlenderRoutines/KX_BlenderCanvas.h
deleted file mode 100644
index 6f408f86551..00000000000
--- a/source/gameengine/BlenderRoutines/KX_BlenderCanvas.h
+++ /dev/null
@@ -1,222 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file KX_BlenderCanvas.h
- * \ingroup blroutines
- */
-
-#ifndef __KX_BLENDERCANVAS_H__
-#define __KX_BLENDERCANVAS_H__
-
-#ifdef WIN32
-#include <windows.h>
-#endif
-
-#include "RAS_ICanvas.h"
-#include "RAS_Rect.h"
-
-#ifdef WITH_CXX_GUARDEDALLOC
-#include "MEM_guardedalloc.h"
-#endif
-
-struct ARegion;
-struct wmWindow;
-struct wmWindowManager;
-
-/**
- * 2D Blender device context abstraction.
- * The connection from 3d rendercontext to 2d Blender surface embedding.
- */
-
-class KX_BlenderCanvas : public RAS_ICanvas
-{
-private:
- /**
- * Rect that defines the area used for rendering,
- * relative to the context */
- RAS_Rect m_displayarea;
- int m_viewport[4];
-
-public:
- /* Construct a new canvas.
- *
- * \param area The Blender ARegion to run the game within.
- */
- KX_BlenderCanvas(struct wmWindowManager *wm, struct wmWindow* win, RAS_Rect &rect, struct ARegion* ar);
- ~KX_BlenderCanvas();
-
- void
- Init(
- );
-
- void
- SwapBuffers(
- );
-
- void
- SetSwapInterval(
- int interval
- );
-
- bool
- GetSwapInterval(
- int &intervalOut
- );
-
- void GetDisplayDimensions(int &width, int &height);
-
- void
- ResizeWindow(
- int width,
- int height
- );
-
- void
- SetFullScreen(
- bool enable
- );
-
- bool
- GetFullScreen();
-
- void
- BeginFrame(
- );
-
- void
- EndFrame(
- );
-
- void
- ClearColor(
- float r,
- float g,
- float b,
- float a
- );
-
- void
- ClearBuffer(
- int type
- );
-
- int
- GetWidth(
- ) const;
-
- int
- GetHeight(
- ) const;
-
- int
- GetMouseX(int x
- );
-
- int
- GetMouseY(int y
- );
-
- float
- GetMouseNormalizedX(int x
- );
-
- float
- GetMouseNormalizedY(int y
- );
-
- const
- RAS_Rect &
- GetDisplayArea(
- ) const {
- return m_displayarea;
- };
-
- void
- SetDisplayArea(RAS_Rect *rect
- ) {
- m_displayarea= *rect;
- };
-
- RAS_Rect &
- GetWindowArea(
- );
-
- void
- SetViewPort(
- int x1, int y1,
- int x2, int y2
- );
-
- void
- UpdateViewPort(
- int x1, int y1,
- int x2, int y2
- );
-
- const int*
- GetViewPort();
-
- void
- SetMouseState(
- RAS_MouseState mousestate
- );
-
- void
- SetMousePosition(
- int x,
- int y
- );
-
- void
- MakeScreenShot(
- const char* filename
- );
-
- bool
- BeginDraw(
- );
-
- void
- EndDraw(
- );
-
-private:
- /** Blender area the game engine is running within */
- struct wmWindowManager *m_wm;
- struct wmWindow* m_win;
- RAS_Rect m_frame_rect;
- RAS_Rect m_area_rect;
- int m_area_left;
- int m_area_top;
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:KX_BlenderCanvas")
-#endif
-};
-
-#endif /* __KX_BLENDERCANVAS_H__ */
diff --git a/source/gameengine/BlenderRoutines/KX_BlenderInputDevice.cpp b/source/gameengine/BlenderRoutines/KX_BlenderInputDevice.cpp
deleted file mode 100644
index 8d224051df4..00000000000
--- a/source/gameengine/BlenderRoutines/KX_BlenderInputDevice.cpp
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/BlenderRoutines/KX_BlenderInputDevice.cpp
- * \ingroup blroutines
- */
-
-#include "KX_BlenderInputDevice.h"
-
diff --git a/source/gameengine/BlenderRoutines/KX_BlenderInputDevice.h b/source/gameengine/BlenderRoutines/KX_BlenderInputDevice.h
deleted file mode 100644
index a936f328545..00000000000
--- a/source/gameengine/BlenderRoutines/KX_BlenderInputDevice.h
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file KX_BlenderInputDevice.h
- * \ingroup blroutines
- */
-
-#ifndef __KX_BLENDERINPUTDEVICE_H__
-#define __KX_BLENDERINPUTDEVICE_H__
-
-#ifdef _MSC_VER
-# pragma warning(disable:4786) // shut off 255 char limit debug template warning
-#endif
-
-#include <map>
-
-#include "wm_event_types.h"
-#include "WM_types.h"
-#include "SCA_IInputDevice.h"
-#include "BL_BlenderDataConversion.h"
-
-#ifdef WITH_CXX_GUARDEDALLOC
-#include "MEM_guardedalloc.h"
-#endif
-
-/**
- * Base Class for Blender specific inputdevices.
- * Blender specific inputdevices are used when the gameengine is running in embedded mode instead of standalone mode.
- */
-class BL_BlenderInputDevice : public SCA_IInputDevice
-{
-public:
- BL_BlenderInputDevice()
- {
- }
-
- virtual ~BL_BlenderInputDevice()
- {
-
- }
-
- KX_EnumInputs ToNative(unsigned short incode) {
- return ConvertKeyCode(incode);
- }
-
- virtual bool IsPressed(SCA_IInputDevice::KX_EnumInputs inputcode)=0;
- // virtual const SCA_InputEvent& GetEventValue(SCA_IInputDevice::KX_EnumInputs inputcode)=0;
- virtual bool ConvertBlenderEvent(unsigned short incode, short val, unsigned int unicode)=0;
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:BL_BlenderInputDevice")
-#endif
-};
-
-#endif /* __KX_BLENDERINPUTDEVICE_H__ */
diff --git a/source/gameengine/BlenderRoutines/KX_BlenderKeyboardDevice.cpp b/source/gameengine/BlenderRoutines/KX_BlenderKeyboardDevice.cpp
deleted file mode 100644
index ea78d2d389e..00000000000
--- a/source/gameengine/BlenderRoutines/KX_BlenderKeyboardDevice.cpp
+++ /dev/null
@@ -1,169 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/BlenderRoutines/KX_BlenderKeyboardDevice.cpp
- * \ingroup blroutines
- */
-
-
-#ifdef _MSC_VER
- /* annoying warnings about truncated STL debug info */
-# pragma warning (disable:4786)
-#endif
-
-#include "KX_BlenderKeyboardDevice.h"
-#include "KX_KetsjiEngine.h"
-
-KX_BlenderKeyboardDevice::KX_BlenderKeyboardDevice()
- : m_hookesc(false)
-{
-
-}
-KX_BlenderKeyboardDevice::~KX_BlenderKeyboardDevice()
-{
-
-}
-
-/**
- * IsPressed gives boolean information about keyboard status, true if pressed, false if not
- */
-
-bool KX_BlenderKeyboardDevice::IsPressed(SCA_IInputDevice::KX_EnumInputs inputcode)
-{
- const SCA_InputEvent & inevent = m_eventStatusTables[m_currentTable][inputcode];
- bool pressed = (inevent.m_status == SCA_InputEvent::KX_JUSTACTIVATED ||
- inevent.m_status == SCA_InputEvent::KX_ACTIVE);
- return pressed;
-}
-/*const SCA_InputEvent& KX_BlenderKeyboardDevice::GetEventValue(SCA_IInputDevice::KX_EnumInputs inputcode)
-{
- return m_eventStatusTables[m_currentTable][inputcode];
-}
-*/
-/**
- * NextFrame toggles currentTable with previousTable,
- * and copy relevant event information from previous to current
- * (pressed keys need to be remembered)
- */
-void KX_BlenderKeyboardDevice::NextFrame()
-{
- SCA_IInputDevice::NextFrame();
-
- // now convert justpressed keyevents into regular (active) keyevents
- int previousTable = 1-m_currentTable;
- for (int keyevent= KX_BEGINKEY; keyevent<= KX_ENDKEY;keyevent++)
- {
- SCA_InputEvent& oldevent = m_eventStatusTables[previousTable][keyevent];
- if (oldevent.m_status == SCA_InputEvent::KX_JUSTACTIVATED ||
- oldevent.m_status == SCA_InputEvent::KX_ACTIVE )
- {
- m_eventStatusTables[m_currentTable][keyevent] = oldevent;
- m_eventStatusTables[m_currentTable][keyevent].m_status = SCA_InputEvent::KX_ACTIVE;
- }
- }
-}
-
-/**
- * ConvertBlenderEvent translates blender keyboard events into ketsji kbd events
- * extra event information is stored, like ramp-mode (just released/pressed)
-*/
-bool KX_BlenderKeyboardDevice::ConvertBlenderEvent(unsigned short incode, short val, unsigned int unicode)
-{
- bool result = false;
-
- // convert event
- KX_EnumInputs kxevent = this->ToNative(incode);
-
- // only process it, if it's a key
- if (kxevent >= KX_BEGINKEY && kxevent <= KX_ENDKEY)
- {
- int previousTable = 1-m_currentTable;
-
- if (val == KM_PRESS || val == KM_DBL_CLICK)
- {
- if (kxevent == KX_KetsjiEngine::GetExitKey() && val != 0 && !m_hookesc)
- result = true;
- if (kxevent == KX_PAUSEKEY && val && (IsPressed(KX_LEFTCTRLKEY) || IsPressed(KX_RIGHTCTRLKEY)))
- result = true;
-
- // todo: convert val ??
- m_eventStatusTables[m_currentTable][kxevent].m_eventval = val ; //???
- m_eventStatusTables[m_currentTable][kxevent].m_unicode = unicode;
-
- switch (m_eventStatusTables[previousTable][kxevent].m_status)
- {
- case SCA_InputEvent::KX_JUSTACTIVATED:
- {
- m_eventStatusTables[m_currentTable][kxevent].m_status = SCA_InputEvent::KX_ACTIVE;
- break;
- }
- case SCA_InputEvent::KX_ACTIVE:
-
- {
- m_eventStatusTables[m_currentTable][kxevent].m_status = SCA_InputEvent::KX_ACTIVE;
- break;
- }
- case SCA_InputEvent::KX_NO_INPUTSTATUS:
- {
- m_eventStatusTables[m_currentTable][kxevent].m_status = SCA_InputEvent::KX_JUSTACTIVATED;
- break;
- }
- default:
- {
- m_eventStatusTables[m_currentTable][kxevent].m_status = SCA_InputEvent::KX_JUSTACTIVATED;
- }
- }
-
- } else if (val == KM_RELEASE)
- {
- // blender eventval == 0
- switch (m_eventStatusTables[previousTable][kxevent].m_status)
- {
- case SCA_InputEvent::KX_JUSTACTIVATED:
- {
- m_eventStatusTables[m_currentTable][kxevent].m_status = SCA_InputEvent::KX_JUSTRELEASED;
- break;
- }
- case SCA_InputEvent::KX_ACTIVE:
- {
- m_eventStatusTables[m_currentTable][kxevent].m_status = SCA_InputEvent::KX_JUSTRELEASED;
- break;
- }
- default:
- {
- m_eventStatusTables[m_currentTable][kxevent].m_status = SCA_InputEvent::KX_NO_INPUTSTATUS;
- }
- }
- }
- }
- return result;
-}
-
-void KX_BlenderKeyboardDevice::HookEscape()
-{
- m_hookesc = true;
-}
diff --git a/source/gameengine/BlenderRoutines/KX_BlenderKeyboardDevice.h b/source/gameengine/BlenderRoutines/KX_BlenderKeyboardDevice.h
deleted file mode 100644
index 10a5b00937d..00000000000
--- a/source/gameengine/BlenderRoutines/KX_BlenderKeyboardDevice.h
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file KX_BlenderKeyboardDevice.h
- * \ingroup blroutines
- */
-
-#ifndef __KX_BLENDERKEYBOARDDEVICE_H__
-#define __KX_BLENDERKEYBOARDDEVICE_H__
-
-#include "KX_BlenderInputDevice.h"
-
-#ifdef WITH_CXX_GUARDEDALLOC
-#include "MEM_guardedalloc.h"
-#endif
-
-class KX_BlenderKeyboardDevice : public BL_BlenderInputDevice
-{
- bool m_hookesc;
-public:
- KX_BlenderKeyboardDevice();
- virtual ~KX_BlenderKeyboardDevice();
-
- virtual bool IsPressed(SCA_IInputDevice::KX_EnumInputs inputcode);
-// virtual const SCA_InputEvent& GetEventValue(SCA_IInputDevice::KX_EnumInputs inputcode);
- virtual bool ConvertBlenderEvent(unsigned short incode, short val, unsigned int unicode);
- virtual void NextFrame();
- virtual void HookEscape();
-private:
- /* short m_exit_key; */ /* UNUSED */
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:KX_BlenderKeyboardDevice")
-#endif
-};
-
-#endif /* __KX_BLENDERKEYBOARDDEVICE_H__ */
diff --git a/source/gameengine/BlenderRoutines/KX_BlenderMouseDevice.cpp b/source/gameengine/BlenderRoutines/KX_BlenderMouseDevice.cpp
deleted file mode 100644
index 9df06e83b92..00000000000
--- a/source/gameengine/BlenderRoutines/KX_BlenderMouseDevice.cpp
+++ /dev/null
@@ -1,192 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/BlenderRoutines/KX_BlenderMouseDevice.cpp
- * \ingroup blroutines
- */
-
-#ifdef _MSC_VER
- /* annoying warnings about truncated STL debug info */
-# pragma warning (disable:4786)
-#endif
-
-#include "KX_BlenderMouseDevice.h"
-
-KX_BlenderMouseDevice::KX_BlenderMouseDevice()
-{
-
-}
-KX_BlenderMouseDevice::~KX_BlenderMouseDevice()
-{
-
-}
-
-/**
- * IsPressed gives boolean information about mouse status, true if pressed, false if not
- */
-
-bool KX_BlenderMouseDevice::IsPressed(SCA_IInputDevice::KX_EnumInputs inputcode)
-{
- const SCA_InputEvent & inevent = m_eventStatusTables[m_currentTable][inputcode];
- bool pressed = (inevent.m_status == SCA_InputEvent::KX_JUSTACTIVATED ||
- inevent.m_status == SCA_InputEvent::KX_ACTIVE);
- return pressed;
-}
-/*const SCA_InputEvent& KX_BlenderMouseDevice::GetEventValue(SCA_IInputDevice::KX_EnumInputs inputcode)
-{
- return m_eventStatusTables[m_currentTable][inputcode];
-}
-*/
-
-/**
- * NextFrame toggles currentTable with previousTable,
- * and copy relevant event information from previous to current
- * (pressed keys need to be remembered)
- */
-void KX_BlenderMouseDevice::NextFrame()
-{
- SCA_IInputDevice::NextFrame();
-
- // now convert justpressed keyevents into regular (active) keyevents
- int previousTable = 1-m_currentTable;
- for (int mouseevent= KX_BEGINMOUSE; mouseevent< KX_ENDMOUSEBUTTONS;mouseevent++)
- {
- SCA_InputEvent& oldevent = m_eventStatusTables[previousTable][mouseevent];
- if (oldevent.m_status == SCA_InputEvent::KX_JUSTACTIVATED ||
- oldevent.m_status == SCA_InputEvent::KX_ACTIVE )
- {
- m_eventStatusTables[m_currentTable][mouseevent] = oldevent;
- m_eventStatusTables[m_currentTable][mouseevent].m_status = SCA_InputEvent::KX_ACTIVE;
- }
- }
- for (int mousemove= KX_ENDMOUSEBUTTONS; mousemove< KX_ENDMOUSE;mousemove++)
- {
- SCA_InputEvent& oldevent = m_eventStatusTables[previousTable][mousemove];
- m_eventStatusTables[m_currentTable][mousemove] = oldevent;
- if (oldevent.m_status == SCA_InputEvent::KX_JUSTACTIVATED ||
- oldevent.m_status == SCA_InputEvent::KX_ACTIVE )
- {
-
- m_eventStatusTables[m_currentTable][mousemove].m_status = SCA_InputEvent::KX_JUSTRELEASED;
- } else
- {
- if (oldevent.m_status == SCA_InputEvent::KX_JUSTRELEASED)
- {
-
- m_eventStatusTables[m_currentTable][mousemove].m_status = SCA_InputEvent::KX_NO_INPUTSTATUS;
- }
- }
- }
-}
-
-
-/**
- * ConvertBlenderEvent translates blender mouse events into ketsji kbd events
- * extra event information is stored, like ramp-mode (just released/pressed)
- */
-bool KX_BlenderMouseDevice::ConvertBlenderEvent(unsigned short incode, short val, unsigned int unicode)
-{
- bool result = false;
-
- // convert event
- KX_EnumInputs kxevent = this->ToNative(incode);
- int previousTable = 1-m_currentTable;
-
- // only process it, if it's a key
- if (kxevent > KX_BEGINMOUSE && kxevent < KX_ENDMOUSEBUTTONS)
- {
- if (val == KM_PRESS || val == KM_DBL_CLICK)
- {
- m_eventStatusTables[m_currentTable][kxevent].m_eventval = val ; //???
-
- switch (m_eventStatusTables[previousTable][kxevent].m_status)
- {
-
- case SCA_InputEvent::KX_ACTIVE:
- case SCA_InputEvent::KX_JUSTACTIVATED:
- {
- m_eventStatusTables[m_currentTable][kxevent].m_status = SCA_InputEvent::KX_ACTIVE;
- break;
- }
- case SCA_InputEvent::KX_JUSTRELEASED:
- {
- m_eventStatusTables[m_currentTable][kxevent].m_status = SCA_InputEvent::KX_JUSTACTIVATED;
- break;
- }
- default:
- {
- m_eventStatusTables[m_currentTable][kxevent].m_status = SCA_InputEvent::KX_JUSTACTIVATED;
- }
- }
-
- } else if (val == KM_RELEASE)
- {
- // blender eventval == 0
- switch (m_eventStatusTables[previousTable][kxevent].m_status)
- {
- case SCA_InputEvent::KX_JUSTACTIVATED:
- case SCA_InputEvent::KX_ACTIVE:
- {
- m_eventStatusTables[m_currentTable][kxevent].m_status = SCA_InputEvent::KX_JUSTRELEASED;
- break;
- }
- default:
- {
- m_eventStatusTables[m_currentTable][kxevent].m_status = SCA_InputEvent::KX_NO_INPUTSTATUS;
- }
- }
- }
- }
-
- if (kxevent > KX_ENDMOUSEBUTTONS && kxevent < KX_ENDMOUSE)
- {
- m_eventStatusTables[m_currentTable][kxevent].m_eventval = val ; //remember mouse position
-
- switch (m_eventStatusTables[previousTable][kxevent].m_status)
- {
-
- case SCA_InputEvent::KX_ACTIVE:
- case SCA_InputEvent::KX_JUSTACTIVATED:
- {
- m_eventStatusTables[m_currentTable][kxevent].m_status = SCA_InputEvent::KX_ACTIVE;
- break;
- }
- case SCA_InputEvent::KX_JUSTRELEASED:
- {
- m_eventStatusTables[m_currentTable][kxevent].m_status = SCA_InputEvent::KX_ACTIVE;
- break;
- }
- default:
- {
- m_eventStatusTables[m_currentTable][kxevent].m_status = SCA_InputEvent::KX_JUSTACTIVATED;
- }
- }
- }
-
-
- return result;
-}
diff --git a/source/gameengine/BlenderRoutines/KX_BlenderMouseDevice.h b/source/gameengine/BlenderRoutines/KX_BlenderMouseDevice.h
deleted file mode 100644
index 04b78aff05c..00000000000
--- a/source/gameengine/BlenderRoutines/KX_BlenderMouseDevice.h
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file KX_BlenderMouseDevice.h
- * \ingroup blroutines
- */
-
-#ifndef __KX_BLENDERMOUSEDEVICE_H__
-#define __KX_BLENDERMOUSEDEVICE_H__
-
-#include "KX_BlenderInputDevice.h"
-
-#ifdef WITH_CXX_GUARDEDALLOC
-#include "MEM_guardedalloc.h"
-#endif
-
-class KX_BlenderMouseDevice : public BL_BlenderInputDevice
-{
-public:
- KX_BlenderMouseDevice();
- virtual ~KX_BlenderMouseDevice();
-
- virtual bool IsPressed(SCA_IInputDevice::KX_EnumInputs inputcode);
-// virtual const SCA_InputEvent& GetEventValue(SCA_IInputDevice::KX_EnumInputs inputcode);
- virtual bool ConvertBlenderEvent(unsigned short incode, short val, unsigned int unicode);
- virtual void NextFrame();
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:KX_BlenderMouseDevice")
-#endif
-};
-
-#endif /* __KX_BLENDERMOUSEDEVICE_H__ */
diff --git a/source/gameengine/BlenderRoutines/KX_BlenderSystem.cpp b/source/gameengine/BlenderRoutines/KX_BlenderSystem.cpp
deleted file mode 100644
index 0582e79d269..00000000000
--- a/source/gameengine/BlenderRoutines/KX_BlenderSystem.cpp
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/BlenderRoutines/KX_BlenderSystem.cpp
- * \ingroup blroutines
- */
-
-
-#include "KX_ISystem.h"
-
-#ifdef _MSC_VER
-# pragma warning (disable:4786)
-#endif
-
-#ifdef WIN32
-#include <windows.h>
-#endif
-
-#include <iostream>
-#include <stdio.h>
-#include "KX_BlenderInputDevice.h"
-#include "KX_BlenderSystem.h"
-
-#include "PIL_time.h"
-
-KX_BlenderSystem::KX_BlenderSystem()
-: KX_ISystem()
-{
- m_starttime = PIL_check_seconds_timer();
-}
-
-double KX_BlenderSystem::GetTimeInSeconds()
-{
- return PIL_check_seconds_timer() - m_starttime;
-}
diff --git a/source/gameengine/BlenderRoutines/KX_BlenderSystem.h b/source/gameengine/BlenderRoutines/KX_BlenderSystem.h
deleted file mode 100644
index 0867ef2421f..00000000000
--- a/source/gameengine/BlenderRoutines/KX_BlenderSystem.h
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file KX_BlenderSystem.h
- * \ingroup blroutines
- * \brief Blender System embedding. Needed when gameengine runs embedded within Blender.
- */
-
-#ifndef __KX_BLENDERSYSTEM_H__
-#define __KX_BLENDERSYSTEM_H__
-
-#include "KX_ISystem.h"
-
-#ifdef WITH_CXX_GUARDEDALLOC
-#include "MEM_guardedalloc.h"
-#endif
-
-class KX_BlenderSystem : public KX_ISystem
-{
- double m_starttime;
-
-public:
- KX_BlenderSystem();
- virtual ~KX_BlenderSystem() {}
- virtual double GetTimeInSeconds();
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:KX_BlenderSystem")
-#endif
-};
-
-#endif /* __KX_BLENDERSYSTEM_H__ */
diff --git a/source/gameengine/CMakeLists.txt b/source/gameengine/CMakeLists.txt
deleted file mode 100644
index 62523175f46..00000000000
--- a/source/gameengine/CMakeLists.txt
+++ /dev/null
@@ -1,57 +0,0 @@
-# ***** BEGIN GPL LICENSE BLOCK *****
-#
-# This program is free software; you can redistribute it and/or
-# modify it under the terms of the GNU General Public License
-# as published by the Free Software Foundation; either version 2
-# of the License, or (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software Foundation,
-# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
-#
-# The Original Code is Copyright (C) 2006, Blender Foundation
-# All rights reserved.
-#
-# The Original Code is: all of this file.
-#
-# Contributor(s): Jacques Beaurain.
-#
-# ***** END GPL LICENSE BLOCK *****
-
-remove_extra_strict_flags()
-
-# there are too many inter-includes so best define here
-if(WITH_PYTHON)
- blender_include_dirs_sys("${PYTHON_INCLUDE_DIRS}")
- add_definitions(-DWITH_PYTHON)
-endif()
-
-add_subdirectory(BlenderRoutines)
-add_subdirectory(Converter)
-add_subdirectory(Expressions)
-add_subdirectory(GameLogic)
-add_subdirectory(Ketsji)
-add_subdirectory(Ketsji/KXNetwork)
-add_subdirectory(Network)
-add_subdirectory(Network/LoopBackNetwork)
-add_subdirectory(Physics/Dummy)
-add_subdirectory(Rasterizer)
-add_subdirectory(Rasterizer/RAS_OpenGLRasterizer)
-add_subdirectory(SceneGraph)
-
-if(WITH_BULLET)
- add_subdirectory(Physics/Bullet)
-endif()
-
-if(WITH_PYTHON)
- add_subdirectory(VideoTexture)
-endif()
-
-if(WITH_PLAYER)
- add_subdirectory(GamePlayer)
-endif()
diff --git a/source/gameengine/Converter/BL_ActionActuator.cpp b/source/gameengine/Converter/BL_ActionActuator.cpp
deleted file mode 100644
index d28cdb84275..00000000000
--- a/source/gameengine/Converter/BL_ActionActuator.cpp
+++ /dev/null
@@ -1,664 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Converter/BL_ActionActuator.cpp
- * \ingroup bgeconv
- */
-
-
-#include "SCA_LogicManager.h"
-#include "BL_ActionActuator.h"
-#include "BL_ArmatureObject.h"
-#include "BL_SkinDeformer.h"
-#include "BL_Action.h"
-#include "BL_ActionManager.h"
-#include "KX_GameObject.h"
-#include "STR_HashedString.h"
-#include "MEM_guardedalloc.h"
-#include "DNA_nla_types.h"
-#include "DNA_action_types.h"
-#include "DNA_armature_types.h"
-#include "DNA_scene_types.h"
-#include "BLI_blenlib.h"
-#include "BLI_math.h"
-#include "BLI_utildefines.h"
-#include "MT_Matrix4x4.h"
-
-#include "BKE_action.h"
-#include "EXP_FloatValue.h"
-#include "EXP_PyObjectPlus.h"
-#include "KX_PyMath.h"
-
-extern "C" {
-#include "BKE_animsys.h"
-#include "BKE_action.h"
-#include "RNA_access.h"
-#include "RNA_define.h"
-}
-
-BL_ActionActuator::BL_ActionActuator(SCA_IObject *gameobj,
- const STR_String& propname,
- const STR_String& framepropname,
- float starttime,
- float endtime,
- struct bAction *action,
- short playtype,
- short blend_mode,
- short blendin,
- short priority,
- short layer,
- float layer_weight,
- short ipo_flags,
- short end_reset,
- float stride)
- : SCA_IActuator(gameobj, KX_ACT_ACTION),
-
- m_lastpos(0, 0, 0),
- m_blendframe(0),
- m_flag(0),
- m_startframe (starttime),
- m_endframe(endtime) ,
- m_starttime(0),
- m_localtime(starttime),
- m_lastUpdate(-1),
- m_blendin(blendin),
- m_blendstart(0),
- m_stridelength(stride),
- m_layer_weight(layer_weight),
- m_playtype(playtype),
- m_blendmode(blend_mode),
- m_priority(priority),
- m_layer(layer),
- m_ipo_flags(ipo_flags),
- m_action(action),
- m_propname(propname),
- m_framepropname(framepropname)
-{
- if (!end_reset)
- m_flag |= ACT_FLAG_CONTINUE;
-};
-
-BL_ActionActuator::~BL_ActionActuator()
-{
-}
-
-void BL_ActionActuator::ProcessReplica()
-{
- SCA_IActuator::ProcessReplica();
-
- m_localtime=m_startframe;
- m_lastUpdate=-1;
-
-}
-
-void BL_ActionActuator::SetBlendTime(float newtime)
-{
- m_blendframe = newtime;
-}
-
-void BL_ActionActuator::SetLocalTime(float curtime)
-{
- float dt = (curtime-m_starttime)*KX_KetsjiEngine::GetAnimFrameRate();
-
- if (m_endframe < m_startframe)
- dt = -dt;
-
- m_localtime = m_startframe + dt;
-
- // Handle wrap around
- if (m_localtime < min(m_startframe, m_endframe) || m_localtime > max(m_startframe, m_endframe))
- {
- switch (m_playtype) {
- case ACT_ACTION_PLAY:
- // Clamp
- m_localtime = m_endframe;
- break;
- case ACT_ACTION_LOOP_END:
- // Put the time back to the beginning
- m_localtime = m_startframe;
- m_starttime = curtime;
- break;
- case ACT_ACTION_PINGPONG:
- // Swap the start and end frames
- float temp = m_startframe;
- m_startframe = m_endframe;
- m_endframe = temp;
-
- m_starttime = curtime;
-
- m_flag ^= ACT_FLAG_REVERSE;
-
- break;
- }
- }
-}
-
-void BL_ActionActuator::ResetStartTime(float curtime)
-{
- float dt = m_localtime - m_startframe;
-
- m_starttime = curtime - dt / (KX_KetsjiEngine::GetAnimFrameRate());
- //SetLocalTime(curtime);
-}
-
-CValue* BL_ActionActuator::GetReplica()
-{
- BL_ActionActuator* replica = new BL_ActionActuator(*this);//m_float,GetName());
- replica->ProcessReplica();
- return replica;
-}
-
-bool BL_ActionActuator::Update(double curtime, bool frame)
-{
- bool bNegativeEvent = false;
- bool bPositiveEvent = false;
- bool bUseContinue = false;
- KX_GameObject *obj = (KX_GameObject*)GetParent();
- short playtype = BL_Action::ACT_MODE_PLAY;
- short blendmode = (m_blendmode == ACT_ACTION_ADD) ? BL_Action::ACT_BLEND_ADD : BL_Action::ACT_BLEND_BLEND;
- float start = m_startframe;
- float end = m_endframe;
-
- // If we don't have an action, we can't do anything
- if (!m_action)
- return false;
-
- // Convert our playtype to one that BL_Action likes
- switch (m_playtype) {
- case ACT_ACTION_LOOP_END:
- case ACT_ACTION_LOOP_STOP:
- playtype = BL_Action::ACT_MODE_LOOP;
- break;
-
- case ACT_ACTION_PINGPONG:
- // We handle ping pong ourselves to increase compabitility
- // with files made prior to animation changes from GSoC 2011.
- playtype = BL_Action::ACT_MODE_PLAY;
-
- if (m_flag & ACT_FLAG_REVERSE)
- {
- start = m_endframe;
- end = m_startframe;
- }
-
- break;
- case ACT_ACTION_FROM_PROP:
- CValue* prop = GetParent()->GetProperty(m_propname);
-
- // If we don't have a property, we can't do anything, so just bail
- if (!prop) return false;
-
- playtype = BL_Action::ACT_MODE_PLAY;
- start = end = prop->GetNumber();
-
- break;
- }
-
- if (m_flag & ACT_FLAG_CONTINUE)
- bUseContinue = true;
-
-
- // Handle events
- if (frame)
- {
- bNegativeEvent = m_negevent;
- bPositiveEvent = m_posevent;
- RemoveAllEvents();
- }
-
- // "Active" actions need to keep updating their current frame
- if (bUseContinue && (m_flag & ACT_FLAG_ACTIVE))
- m_localtime = obj->GetActionFrame(m_layer);
-
- if (m_flag & ACT_FLAG_ATTEMPT_PLAY)
- SetLocalTime(curtime);
- else
- ResetStartTime(curtime);
-
- // Handle a frame property if it's defined
- if ((m_flag & ACT_FLAG_ACTIVE) && m_framepropname[0] != 0)
- {
- CValue* oldprop = obj->GetProperty(m_framepropname);
- CValue* newval = new CFloatValue(obj->GetActionFrame(m_layer));
- if (oldprop)
- oldprop->SetValue(newval);
- else
- obj->SetProperty(m_framepropname, newval);
-
- newval->Release();
- }
-
- // Handle a finished animation
- if ((m_flag & ACT_FLAG_PLAY_END) && (m_flag & ACT_FLAG_ACTIVE) && obj->IsActionDone(m_layer))
- {
- m_flag &= ~ACT_FLAG_ACTIVE;
-
- if (m_playtype == ACT_ACTION_PINGPONG) {
- m_flag ^= ACT_FLAG_REVERSE;
- }
- else {
- m_flag &= ~ACT_FLAG_ATTEMPT_PLAY;
- return false;
- }
- }
-
- // If a different action is playing, we've been overruled and are no longer active
- if (obj->GetCurrentAction(m_layer) != m_action && !obj->IsActionDone(m_layer))
- m_flag &= ~ACT_FLAG_ACTIVE;
-
- if (bPositiveEvent || (m_flag & ACT_FLAG_ATTEMPT_PLAY && !(m_flag & ACT_FLAG_ACTIVE)))
- {
- if (bPositiveEvent && m_playtype == ACT_ACTION_PLAY)
- {
- if (obj->IsActionDone(m_layer))
- m_localtime = start;
- ResetStartTime(curtime);
- }
-
- if (obj->PlayAction(m_action->id.name+2, start, end, m_layer, m_priority, m_blendin, playtype, m_layer_weight, m_ipo_flags, 1.f, blendmode))
- {
- m_flag |= ACT_FLAG_ACTIVE;
- if (bUseContinue)
- obj->SetActionFrame(m_layer, m_localtime);
-
- if (m_playtype == ACT_ACTION_PLAY || m_playtype == ACT_ACTION_PINGPONG)
- m_flag |= ACT_FLAG_PLAY_END;
- else
- m_flag &= ~ACT_FLAG_PLAY_END;
- }
- m_flag |= ACT_FLAG_ATTEMPT_PLAY;
- }
- else if ((m_flag & ACT_FLAG_ACTIVE) && bNegativeEvent)
- {
- m_flag &= ~ACT_FLAG_ATTEMPT_PLAY;
- m_localtime = obj->GetActionFrame(m_layer);
- bAction *curr_action = obj->GetCurrentAction(m_layer);
- if (curr_action && curr_action != m_action)
- {
- // Someone changed the action on us, so we wont mess with it
- // Hopefully there wont be too many problems with two actuators using
- // the same action...
- m_flag &= ~ACT_FLAG_ACTIVE;
- return false;
- }
-
- switch (m_playtype) {
- case ACT_ACTION_FROM_PROP:
- case ACT_ACTION_LOOP_STOP:
- obj->StopAction(m_layer); // Stop the action after getting the frame
-
- // We're done
- m_flag &= ~ACT_FLAG_ACTIVE;
- return false;
- case ACT_ACTION_LOOP_END:
- // Convert into a play and let it finish
- obj->SetPlayMode(m_layer, BL_Action::ACT_MODE_PLAY);
-
- m_flag |= ACT_FLAG_PLAY_END;
- break;
-
- case ACT_ACTION_FLIPPER:
- // Convert into a play action and play back to the beginning
- float temp = end;
- end = start;
- start = curr_action ? obj->GetActionFrame(m_layer) : temp;
- obj->PlayAction(m_action->id.name+2, start, end, m_layer, m_priority, 0, BL_Action::ACT_MODE_PLAY, m_layer_weight, m_ipo_flags, 1.f, blendmode);
-
- m_flag |= ACT_FLAG_PLAY_END;
- break;
- }
- }
-
- return m_flag & ACT_FLAG_ACTIVE;
-}
-
-void BL_ActionActuator::DecLink()
-{
- SCA_IActuator::DecLink();
- /* In this case no controllers use this action actuator,
- and it should stop its action. */
- if (m_links == 0) {
- KX_GameObject *obj = (KX_GameObject *)GetParent();
- obj->StopAction(m_layer);
- }
-}
-
-#ifdef WITH_PYTHON
-
-/* ------------------------------------------------------------------------- */
-/* Python functions */
-/* ------------------------------------------------------------------------- */
-
-PyObject *BL_ActionActuator::PyGetChannel(PyObject *value)
-{
- PyErr_SetString(PyExc_NotImplementedError, "BL_ActionActuator.getChannel() no longer works, please use BL_ArmatureObject.channels instead");
- return NULL;
-#if 0 // XXX To be removed in a later version (first removed in 2.64)
- const char *string= _PyUnicode_AsString(value);
-
- if (GetParent()->GetGameObjectType() != SCA_IObject::OBJ_ARMATURE)
- {
- PyErr_SetString(PyExc_NotImplementedError, "actuator.getChannel(): Only armatures support channels");
- return NULL;
- }
-
- if (!string) {
- PyErr_SetString(PyExc_TypeError, "expected a single string");
- return NULL;
- }
-
- bPoseChannel *pchan;
-
- if (m_userpose==NULL && m_pose==NULL) {
- BL_ArmatureObject *obj = (BL_ArmatureObject*)GetParent();
- obj->GetPose(&m_pose); /* Get the underlying pose from the armature */
- }
-
- // BKE_pose_channel_find_name accounts for NULL pose, run on both in case one exists but
- // the channel doesnt
- if ( !(pchan=BKE_pose_channel_find_name(m_userpose, string)) &&
- !(pchan=BKE_pose_channel_find_name(m_pose, string)) )
- {
- PyErr_SetString(PyExc_ValueError, "channel doesnt exist");
- return NULL;
- }
-
- PyObject *ret = PyTuple_New(3);
-
- PyObject *list = PyList_New(3);
- PyList_SET_ITEM(list, 0, PyFloat_FromDouble(pchan->loc[0]));
- PyList_SET_ITEM(list, 1, PyFloat_FromDouble(pchan->loc[1]));
- PyList_SET_ITEM(list, 2, PyFloat_FromDouble(pchan->loc[2]));
- PyTuple_SET_ITEM(ret, 0, list);
-
- list = PyList_New(3);
- PyList_SET_ITEM(list, 0, PyFloat_FromDouble(pchan->size[0]));
- PyList_SET_ITEM(list, 1, PyFloat_FromDouble(pchan->size[1]));
- PyList_SET_ITEM(list, 2, PyFloat_FromDouble(pchan->size[2]));
- PyTuple_SET_ITEM(ret, 1, list);
-
- list = PyList_New(4);
- PyList_SET_ITEM(list, 0, PyFloat_FromDouble(pchan->quat[0]));
- PyList_SET_ITEM(list, 1, PyFloat_FromDouble(pchan->quat[1]));
- PyList_SET_ITEM(list, 2, PyFloat_FromDouble(pchan->quat[2]));
- PyList_SET_ITEM(list, 3, PyFloat_FromDouble(pchan->quat[3]));
- PyTuple_SET_ITEM(ret, 2, list);
-
- return ret;
-#if 0
- return Py_BuildValue("([fff][fff][ffff])",
- pchan->loc[0], pchan->loc[1], pchan->loc[2],
- pchan->size[0], pchan->size[1], pchan->size[2],
- pchan->quat[0], pchan->quat[1], pchan->quat[2], pchan->quat[3] );
-#endif
-#endif
-}
-
-/* setChannel */
-KX_PYMETHODDEF_DOC(BL_ActionActuator, setChannel,
-"setChannel(channel, matrix)\n"
-"\t - channel : A string specifying the name of the bone channel.\n"
-"\t - matrix : A 4x4 matrix specifying the overriding transformation\n"
-"\t as an offset from the bone's rest position.\n")
-{
- PyErr_SetString(PyExc_NotImplementedError, "BL_ActionActuator.setChannel() no longer works, please use BL_ArmatureObject.channels instead");
- return NULL;
-
-#if 0 // XXX To be removed in a later version (first removed in 2.64)
- BL_ArmatureObject *obj = (BL_ArmatureObject*)GetParent();
- char *string;
- PyObject *pymat= NULL;
- PyObject *pyloc= NULL, *pysize= NULL, *pyquat= NULL;
- bPoseChannel *pchan;
-
- if (GetParent()->GetGameObjectType() != SCA_IObject::OBJ_ARMATURE)
- {
- PyErr_SetString(PyExc_NotImplementedError, "actuator.setChannel(): Only armatures support channels");
- return NULL;
- }
-
- if (PyTuple_Size(args)==2) {
- if (!PyArg_ParseTuple(args,"sO:setChannel", &string, &pymat)) // matrix
- return NULL;
- }
- else if (PyTuple_Size(args)==4) {
- if (!PyArg_ParseTuple(args,"sOOO:setChannel", &string, &pyloc, &pysize, &pyquat)) // loc/size/quat
- return NULL;
- }
- else {
- PyErr_SetString(PyExc_ValueError, "Expected a string and a 4x4 matrix (2 args) or a string and loc/size/quat sequences (4 args)");
- return NULL;
- }
-
- if (pymat) {
- float matrix[4][4];
- MT_Matrix4x4 mat;
-
- if (!PyMatTo(pymat, mat))
- return NULL;
-
- mat.getValue((float*)matrix);
-
- BL_ArmatureObject *obj = (BL_ArmatureObject*)GetParent();
-
- if (!m_userpose) {
- if (!m_pose)
- obj->GetPose(&m_pose); /* Get the underlying pose from the armature */
- game_copy_pose(&m_userpose, m_pose, 0);
- }
- // pchan= BKE_pose_channel_verify(m_userpose, string); // adds the channel if its not there.
- pchan= BKE_pose_channel_find_name(m_userpose, string); // adds the channel if its not there.
-
- if (pchan) {
- copy_v3_v3(pchan->loc, matrix[3]);
- mat4_to_size(pchan->size, matrix);
- mat4_to_quat(pchan->quat, matrix);
- }
- }
- else {
- MT_Vector3 loc;
- MT_Vector3 size;
- MT_Quaternion quat;
-
- if (!PyVecTo(pyloc, loc) || !PyVecTo(pysize, size) || !PyQuatTo(pyquat, quat))
- return NULL;
-
- // same as above
- if (!m_userpose) {
- if (!m_pose)
- obj->GetPose(&m_pose); /* Get the underlying pose from the armature */
- game_copy_pose(&m_userpose, m_pose, 0);
- }
- // pchan= BKE_pose_channel_verify(m_userpose, string);
- pchan= BKE_pose_channel_find_name(m_userpose, string); // adds the channel if its not there.
-
- // for some reason loc.setValue(pchan->loc) fails
- if (pchan) {
- pchan->loc[0] = loc[0]; pchan->loc[1] = loc[1]; pchan->loc[2] = loc[2];
- pchan->size[0] = size[0]; pchan->size[1] = size[1]; pchan->size[2] = size[2];
- pchan->quat[0] = quat[3]; pchan->quat[1] = quat[0]; pchan->quat[2] = quat[1]; pchan->quat[3] = quat[2]; /* notice xyzw -> wxyz is intentional */
- }
- }
-
- if (pchan==NULL) {
- PyErr_SetString(PyExc_ValueError, "Channel could not be found, use the 'channelNames' attribute to get a list of valid channels");
- return NULL;
- }
-
- Py_RETURN_NONE;
-#endif
-}
-
-/* ------------------------------------------------------------------------- */
-/* Python Integration Hooks */
-/* ------------------------------------------------------------------------- */
-
-PyTypeObject BL_ActionActuator::Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "BL_ActionActuator",
- sizeof(PyObjectPlus_Proxy),
- 0,
- py_base_dealloc,
- 0,
- 0,
- 0,
- 0,
- py_base_repr,
- 0,0,0,0,0,0,0,0,0,
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
- 0,0,0,0,0,0,0,
- Methods,
- 0,
- 0,
- &SCA_IActuator::Type,
- 0,0,0,0,0,0,
- py_base_new
-};
-
-PyMethodDef BL_ActionActuator::Methods[] = {
- {"getChannel", (PyCFunction) BL_ActionActuator::sPyGetChannel, METH_O},
- KX_PYMETHODTABLE(BL_ActionActuator, setChannel),
- {NULL,NULL} //Sentinel
-};
-
-PyAttributeDef BL_ActionActuator::Attributes[] = {
- KX_PYATTRIBUTE_FLOAT_RW("frameStart", 0, MAXFRAMEF, BL_ActionActuator, m_startframe),
- KX_PYATTRIBUTE_FLOAT_RW("frameEnd", 0, MAXFRAMEF, BL_ActionActuator, m_endframe),
- KX_PYATTRIBUTE_FLOAT_RW("blendIn", 0, MAXFRAMEF, BL_ActionActuator, m_blendin),
- KX_PYATTRIBUTE_RW_FUNCTION("action", BL_ActionActuator, pyattr_get_action, pyattr_set_action),
- KX_PYATTRIBUTE_RO_FUNCTION("channelNames", BL_ActionActuator, pyattr_get_channel_names),
- KX_PYATTRIBUTE_SHORT_RW("priority", 0, 100, false, BL_ActionActuator, m_priority),
- KX_PYATTRIBUTE_SHORT_RW("layer", 0, MAX_ACTION_LAYERS-1, true, BL_ActionActuator, m_layer),
- KX_PYATTRIBUTE_FLOAT_RW("layerWeight", 0, 1.0, BL_ActionActuator, m_layer_weight),
- KX_PYATTRIBUTE_RW_FUNCTION("frame", BL_ActionActuator, pyattr_get_frame, pyattr_set_frame),
- KX_PYATTRIBUTE_STRING_RW("propName", 0, MAX_PROP_NAME, false, BL_ActionActuator, m_propname),
- KX_PYATTRIBUTE_STRING_RW("framePropName", 0, MAX_PROP_NAME, false, BL_ActionActuator, m_framepropname),
- KX_PYATTRIBUTE_RW_FUNCTION("useContinue", BL_ActionActuator, pyattr_get_use_continue, pyattr_set_use_continue),
- KX_PYATTRIBUTE_FLOAT_RW_CHECK("blendTime", 0, MAXFRAMEF, BL_ActionActuator, m_blendframe, CheckBlendTime),
- KX_PYATTRIBUTE_SHORT_RW_CHECK("mode",0,100,false,BL_ActionActuator,m_playtype,CheckType),
- { NULL } //Sentinel
-};
-
-PyObject *BL_ActionActuator::pyattr_get_action(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- BL_ActionActuator* self = static_cast<BL_ActionActuator*>(self_v);
- return PyUnicode_FromString(self->GetAction() ? self->GetAction()->id.name+2 : "");
-}
-
-int BL_ActionActuator::pyattr_set_action(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- BL_ActionActuator* self = static_cast<BL_ActionActuator*>(self_v);
-
- if (!PyUnicode_Check(value))
- {
- PyErr_SetString(PyExc_ValueError, "actuator.action = val: Action Actuator, expected the string name of the action");
- return PY_SET_ATTR_FAIL;
- }
-
- bAction *action= NULL;
- STR_String val = _PyUnicode_AsString(value);
-
- if (val != "")
- {
- action= (bAction*)self->GetLogicManager()->GetActionByName(val);
- if (!action)
- {
- PyErr_SetString(PyExc_ValueError, "actuator.action = val: Action Actuator, action not found!");
- return PY_SET_ATTR_FAIL;
- }
- }
-
- self->SetAction(action);
- return PY_SET_ATTR_SUCCESS;
-
-}
-
-PyObject *BL_ActionActuator::pyattr_get_channel_names(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- PyErr_SetString(PyExc_NotImplementedError, "BL_ActionActuator.channelNames no longer works, please use BL_ArmatureObject.channels instead");
- return NULL;
-
-#if 0 // XXX To be removed in a later version (first removed in 2.64)
- BL_ActionActuator* self = static_cast<BL_ActionActuator*>(self_v);
- PyObject *ret= PyList_New(0);
- PyObject *item;
-
- if (self->GetParent()->GetGameObjectType() != SCA_IObject::OBJ_ARMATURE)
- {
- PyErr_SetString(PyExc_NotImplementedError, "actuator.channelNames: Only armatures support channels");
- return NULL;
- }
-
- bPose *pose= ((BL_ArmatureObject*)self->GetParent())->GetOrigPose();
-
- if (pose) {
- bPoseChannel *pchan;
- for (pchan= (bPoseChannel *)pose->chanbase.first; pchan; pchan= (bPoseChannel *)pchan->next) {
- item= PyUnicode_FromString(pchan->name);
- PyList_Append(ret, item);
- Py_DECREF(item);
- }
- }
-
- return ret;
-#endif
-}
-
-PyObject *BL_ActionActuator::pyattr_get_use_continue(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- BL_ActionActuator* self = static_cast<BL_ActionActuator*>(self_v);
- return PyBool_FromLong(self->m_flag & ACT_FLAG_CONTINUE);
-}
-
-int BL_ActionActuator::pyattr_set_use_continue(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- BL_ActionActuator* self = static_cast<BL_ActionActuator*>(self_v);
-
- if (PyObject_IsTrue(value))
- self->m_flag |= ACT_FLAG_CONTINUE;
- else
- self->m_flag &= ~ACT_FLAG_CONTINUE;
-
- return PY_SET_ATTR_SUCCESS;
-}
-
-PyObject *BL_ActionActuator::pyattr_get_frame(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- BL_ActionActuator* self = static_cast<BL_ActionActuator*>(self_v);
- return PyFloat_FromDouble(((KX_GameObject*)self->m_gameobj)->GetActionFrame(self->m_layer));
-}
-
-int BL_ActionActuator::pyattr_set_frame(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- BL_ActionActuator* self = static_cast<BL_ActionActuator*>(self_v);
-
- ((KX_GameObject*)self->m_gameobj)->SetActionFrame(self->m_layer, PyFloat_AsDouble(value));
-
- return PY_SET_ATTR_SUCCESS;
-}
-
-#endif // WITH_PYTHON
diff --git a/source/gameengine/Converter/BL_ActionActuator.h b/source/gameengine/Converter/BL_ActionActuator.h
deleted file mode 100644
index a43cf0f0a7b..00000000000
--- a/source/gameengine/Converter/BL_ActionActuator.h
+++ /dev/null
@@ -1,158 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file BL_ActionActuator.h
- * \ingroup bgeconv
- */
-
-#ifndef __BL_ACTIONACTUATOR_H__
-#define __BL_ACTIONACTUATOR_H__
-
-#include "CTR_HashedPtr.h"
-#include "SCA_IActuator.h"
-#include "DNA_actuator_types.h"
-#include "MT_Point3.h"
-
-class BL_ActionActuator : public SCA_IActuator
-{
-public:
- Py_Header
- BL_ActionActuator(SCA_IObject* gameobj,
- const STR_String& propname,
- const STR_String& framepropname,
- float starttime,
- float endtime,
- struct bAction *action,
- short playtype,
- short blend_mode,
- short blendin,
- short priority,
- short layer,
- float layer_weight,
- short ipo_flags,
- short end_reset,
- float stride);
-
- virtual ~BL_ActionActuator();
- virtual bool Update(double curtime, bool frame);
- virtual CValue* GetReplica();
- virtual void ProcessReplica();
-
- void SetBlendTime(float newtime);
- void SetLocalTime(float curtime);
- void ResetStartTime(float curtime);
-
- bAction* GetAction() { return m_action; }
- void SetAction(bAction* act) { m_action= act; }
-
- virtual void DecLink();
-
-#ifdef WITH_PYTHON
-
- KX_PYMETHOD_O(BL_ActionActuator,GetChannel)
- KX_PYMETHOD_DOC(BL_ActionActuator,setChannel)
-
- static PyObject* pyattr_get_action(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_action(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static PyObject* pyattr_get_channel_names(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_use_continue(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_use_continue(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static PyObject* pyattr_get_frame(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_frame(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
-
- static int CheckBlendTime(void *self, const PyAttributeDef*)
- {
- BL_ActionActuator* act = reinterpret_cast<BL_ActionActuator*>(self);
-
- if (act->m_blendframe > act->m_blendin)
- act->m_blendframe = act->m_blendin;
-
- return 0;
- }
-
- static int CheckType(void *self, const PyAttributeDef*)
- {
- BL_ActionActuator* act = reinterpret_cast<BL_ActionActuator*>(self);
-
- switch (act->m_playtype) {
- case ACT_ACTION_PLAY:
- case ACT_ACTION_PINGPONG:
- case ACT_ACTION_FLIPPER:
- case ACT_ACTION_LOOP_STOP:
- case ACT_ACTION_LOOP_END:
- case ACT_ACTION_FROM_PROP:
- return 0;
- default:
- PyErr_SetString(PyExc_ValueError, "Action Actuator, invalid play type supplied");
- return 1;
- }
- }
-#endif /* WITH_PYTHON */
-
-protected:
- MT_Point3 m_lastpos;
- float m_blendframe;
- int m_flag;
- /** The frame this action starts */
- float m_startframe;
- /** The frame this action ends */
- float m_endframe;
- /** The time this action started */
- float m_starttime;
- /** The current time of the action */
- float m_localtime;
-
- float m_lastUpdate;
- float m_blendin;
- float m_blendstart;
- float m_stridelength;
- float m_layer_weight;
- short m_playtype;
- short m_blendmode;
- short m_priority;
- short m_layer;
- short m_ipo_flags;
- struct bAction *m_action;
- STR_String m_propname;
- STR_String m_framepropname;
-};
-
-// Not all of these values are used in BL_ActionActuator anymore,
-// but BL_ShapeActionActuator still uses them, so we keep them around
-// for now.
-enum {
- ACT_FLAG_REVERSE = 1<<0,
- ACT_FLAG_LOCKINPUT = 1<<1,
- ACT_FLAG_KEYUP = 1<<2,
- ACT_FLAG_ACTIVE = 1<<3,
- ACT_FLAG_CONTINUE = 1<<4,
- ACT_FLAG_PLAY_END = 1<<5,
- ACT_FLAG_ATTEMPT_PLAY = 1<<6,
-};
-
-#endif
-
diff --git a/source/gameengine/Converter/BL_ArmatureActuator.cpp b/source/gameengine/Converter/BL_ArmatureActuator.cpp
deleted file mode 100644
index 67cc7d2c291..00000000000
--- a/source/gameengine/Converter/BL_ArmatureActuator.cpp
+++ /dev/null
@@ -1,271 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Converter/BL_ArmatureActuator.cpp
- * \ingroup bgeconv
- */
-
-
-#include "DNA_action_types.h"
-#include "DNA_constraint_types.h"
-#include "DNA_actuator_types.h"
-#include "BKE_constraint.h"
-#include "BL_ArmatureActuator.h"
-#include "BL_ArmatureObject.h"
-#include "BLI_math.h"
-
-/**
- * This class is the conversion of the Pose channel constraint.
- * It makes a link between the pose constraint and the KX scene.
- * The main purpose is to give access to the constraint target
- * to link it to a game object.
- * It also allows to activate/deactivate constraints during the game.
- * Later it will also be possible to create constraint on the fly
- */
-
-BL_ArmatureActuator::BL_ArmatureActuator(SCA_IObject* obj,
- int type,
- const char *posechannel,
- const char *constraintname,
- KX_GameObject* targetobj,
- KX_GameObject* subtargetobj,
- float weight,
- float influence) :
- SCA_IActuator(obj, KX_ACT_ARMATURE),
- m_constraint(NULL),
- m_gametarget(targetobj),
- m_gamesubtarget(subtargetobj),
- m_posechannel(posechannel),
- m_constraintname(constraintname),
- m_weight(weight),
- m_influence(influence),
- m_type(type)
-{
- if (m_gametarget)
- m_gametarget->RegisterActuator(this);
- if (m_gamesubtarget)
- m_gamesubtarget->RegisterActuator(this);
- FindConstraint();
-}
-
-BL_ArmatureActuator::~BL_ArmatureActuator()
-{
- if (m_gametarget)
- m_gametarget->UnregisterActuator(this);
- if (m_gamesubtarget)
- m_gamesubtarget->UnregisterActuator(this);
-}
-
-void BL_ArmatureActuator::ProcessReplica()
-{
- // the replica is tracking the same object => register it (this may be changed in Relnk())
- if (m_gametarget)
- m_gametarget->RegisterActuator(this);
- if (m_gamesubtarget)
- m_gamesubtarget->UnregisterActuator(this);
- SCA_IActuator::ProcessReplica();
-}
-
-void BL_ArmatureActuator::ReParent(SCA_IObject* parent)
-{
- SCA_IActuator::ReParent(parent);
- // must remap the constraint
- FindConstraint();
-}
-
-bool BL_ArmatureActuator::UnlinkObject(SCA_IObject* clientobj)
-{
- bool res=false;
- if (clientobj == m_gametarget)
- {
- // this object is being deleted, we cannot continue to track it.
- m_gametarget = NULL;
- res = true;
- }
- if (clientobj == m_gamesubtarget)
- {
- // this object is being deleted, we cannot continue to track it.
- m_gamesubtarget = NULL;
- res = true;
- }
- return res;
-}
-
-void BL_ArmatureActuator::Relink(CTR_Map<CTR_HashedPtr, void*> *obj_map)
-{
- void **h_obj = (*obj_map)[m_gametarget];
- if (h_obj) {
- if (m_gametarget)
- m_gametarget->UnregisterActuator(this);
- m_gametarget = (KX_GameObject*)(*h_obj);
- m_gametarget->RegisterActuator(this);
- }
- h_obj = (*obj_map)[m_gamesubtarget];
- if (h_obj) {
- if (m_gamesubtarget)
- m_gamesubtarget->UnregisterActuator(this);
- m_gamesubtarget = (KX_GameObject*)(*h_obj);
- m_gamesubtarget->RegisterActuator(this);
- }
-}
-
-void BL_ArmatureActuator::FindConstraint()
-{
- m_constraint = NULL;
-
- if (m_gameobj->GetGameObjectType() == SCA_IObject::OBJ_ARMATURE) {
- BL_ArmatureObject* armobj = (BL_ArmatureObject*)m_gameobj;
- m_constraint = armobj->GetConstraint(m_posechannel, m_constraintname);
- }
-}
-
-bool BL_ArmatureActuator::Update(double curtime, bool frame)
-{
- // the only role of this actuator is to ensure that the armature pose will be evaluated
- bool result = false;
- bool bNegativeEvent = IsNegativeEvent();
- RemoveAllEvents();
-
- if (!bNegativeEvent) {
- BL_ArmatureObject *obj = (BL_ArmatureObject*)GetParent();
- switch (m_type) {
- case ACT_ARM_RUN:
- result = true;
- obj->UpdateTimestep(curtime);
- break;
- case ACT_ARM_ENABLE:
- if (m_constraint)
- m_constraint->ClrConstraintFlag(CONSTRAINT_OFF);
- break;
- case ACT_ARM_DISABLE:
- if (m_constraint)
- m_constraint->SetConstraintFlag(CONSTRAINT_OFF);
- break;
- case ACT_ARM_SETTARGET:
- if (m_constraint) {
- m_constraint->SetTarget(m_gametarget);
- m_constraint->SetSubtarget(m_gamesubtarget);
- }
- break;
- case ACT_ARM_SETWEIGHT:
- if (m_constraint)
- m_constraint->SetWeight(m_weight);
- break;
- case ACT_ARM_SETINFLUENCE:
- if (m_constraint)
- m_constraint->SetInfluence(m_influence);
- break;
- }
- }
- return result;
-}
-
-#ifdef WITH_PYTHON
-
-/* ------------------------------------------------------------------------- */
-/* Python Integration Hooks */
-/* ------------------------------------------------------------------------- */
-
-PyTypeObject BL_ArmatureActuator::Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "BL_ArmatureActuator",
- sizeof(PyObjectPlus_Proxy),
- 0,
- py_base_dealloc,
- 0,
- 0,
- 0,
- 0,
- py_base_repr,
- 0,0,0,0,0,0,0,0,0,
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
- 0,0,0,0,0,0,0,
- Methods,
- 0,
- 0,
- &SCA_IActuator::Type,
- 0,0,0,0,0,0,
- py_base_new
-};
-
-
-PyMethodDef BL_ArmatureActuator::Methods[] = {
- {NULL,NULL} //Sentinel
-};
-
-PyAttributeDef BL_ArmatureActuator::Attributes[] = {
- KX_PYATTRIBUTE_RO_FUNCTION("constraint", BL_ArmatureActuator, pyattr_get_constraint),
- KX_PYATTRIBUTE_RW_FUNCTION("target", BL_ArmatureActuator, pyattr_get_object, pyattr_set_object),
- KX_PYATTRIBUTE_RW_FUNCTION("subtarget", BL_ArmatureActuator, pyattr_get_object, pyattr_set_object),
- KX_PYATTRIBUTE_FLOAT_RW("weight",0.0f,1.0f,BL_ArmatureActuator,m_weight),
- KX_PYATTRIBUTE_FLOAT_RW("influence",0.0f,1.0f,BL_ArmatureActuator,m_influence),
- KX_PYATTRIBUTE_INT_RW("type",0,ACT_ARM_MAXTYPE,false,BL_ArmatureActuator,m_type),
- { NULL } //Sentinel
-};
-
-PyObject *BL_ArmatureActuator::pyattr_get_object(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef)
-{
- BL_ArmatureActuator* actuator = static_cast<BL_ArmatureActuator*>(self);
- KX_GameObject *target = (!strcmp(attrdef->m_name, "target")) ? actuator->m_gametarget : actuator->m_gamesubtarget;
- if (!target)
- Py_RETURN_NONE;
- else
- return target->GetProxy();
-}
-
-int BL_ArmatureActuator::pyattr_set_object(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- BL_ArmatureActuator* actuator = static_cast<BL_ArmatureActuator*>(self);
- KX_GameObject* &target = (!strcmp(attrdef->m_name, "target")) ? actuator->m_gametarget : actuator->m_gamesubtarget;
- KX_GameObject *gameobj;
-
- if (!ConvertPythonToGameObject(actuator->GetLogicManager(), value, &gameobj, true, "actuator.object = value: BL_ArmatureActuator"))
- return PY_SET_ATTR_FAIL; // ConvertPythonToGameObject sets the error
-
- if (target != NULL)
- target->UnregisterActuator(actuator);
-
- target = gameobj;
-
- if (target)
- target->RegisterActuator(actuator);
-
- return PY_SET_ATTR_SUCCESS;
-}
-
-PyObject *BL_ArmatureActuator::pyattr_get_constraint(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef)
-{
- BL_ArmatureActuator* actuator = static_cast<BL_ArmatureActuator*>(self);
- BL_ArmatureConstraint* constraint = actuator->m_constraint;
- if (!constraint)
- Py_RETURN_NONE;
- else
- return constraint->GetProxy();
-}
-
-#endif // WITH_PYTHON
-
diff --git a/source/gameengine/Converter/BL_ArmatureActuator.h b/source/gameengine/Converter/BL_ArmatureActuator.h
deleted file mode 100644
index ba02c5aa362..00000000000
--- a/source/gameengine/Converter/BL_ArmatureActuator.h
+++ /dev/null
@@ -1,96 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file BL_ArmatureActuator.h
- * \ingroup bgeconv
- */
-
-#ifndef __BL_ARMATUREACTUATOR_H__
-#define __BL_ARMATUREACTUATOR_H__
-
-#include "SCA_IActuator.h"
-#include "BL_ArmatureConstraint.h"
-
-/**
- * This class is the conversion of the Pose channel constraint.
- * It makes a link between the pose constraint and the KX scene.
- * The main purpose is to give access to the constraint target
- * to link it to a game object.
- * It also allows to activate/deactivate constraints during the game.
- * Later it will also be possible to create constraint on the fly
- */
-
-class BL_ArmatureActuator : public SCA_IActuator
-{
- Py_Header
-public:
- BL_ArmatureActuator(SCA_IObject* gameobj,
- int type,
- const char *posechannel,
- const char *constraintname,
- KX_GameObject* targetobj,
- KX_GameObject* subtargetobj,
- float weight,
- float influence);
-
- virtual ~BL_ArmatureActuator();
-
- virtual CValue* GetReplica() {
- BL_ArmatureActuator* replica = new BL_ArmatureActuator(*this);
- replica->ProcessReplica();
- return replica;
- };
- virtual void ProcessReplica();
- virtual bool UnlinkObject(SCA_IObject* clientobj);
- virtual void Relink(CTR_Map<CTR_HashedPtr, void*> *obj_map);
- virtual bool Update(double curtime, bool frame);
- virtual void ReParent(SCA_IObject* parent);
-
-#ifdef WITH_PYTHON
-
- /* These are used to get and set m_target */
- static PyObject *pyattr_get_constraint(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject *pyattr_get_object(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_object(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
-
-#endif /* WITH_PYTHON */
-
-private:
- // identify the constraint that this actuator controls
- void FindConstraint();
-
- BL_ArmatureConstraint* m_constraint;
- KX_GameObject* m_gametarget;
- KX_GameObject* m_gamesubtarget;
- STR_String m_posechannel;
- STR_String m_constraintname;
- float m_weight;
- float m_influence;
- int m_type;
-};
-
-#endif /* __BL_ARMATUREACTUATOR_H__ */
diff --git a/source/gameengine/Converter/BL_ArmatureChannel.cpp b/source/gameengine/Converter/BL_ArmatureChannel.cpp
deleted file mode 100644
index 2b8dfd8f8d1..00000000000
--- a/source/gameengine/Converter/BL_ArmatureChannel.cpp
+++ /dev/null
@@ -1,469 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Converter/BL_ArmatureChannel.cpp
- * \ingroup bgeconv
- */
-
-
-#include "DNA_armature_types.h"
-#include "BL_ArmatureChannel.h"
-#include "BL_ArmatureObject.h"
-#include "BL_ArmatureConstraint.h"
-#include "BLI_math.h"
-#include "BLI_string.h"
-#include <stddef.h>
-
-#ifdef WITH_PYTHON
-
-PyTypeObject BL_ArmatureChannel::Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "BL_ArmatureChannel",
- sizeof(PyObjectPlus_Proxy),
- 0,
- py_base_dealloc,
- 0,
- 0,
- 0,
- 0,
- py_base_repr,
- 0,0,0,0,0,0,0,0,0,
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
- 0,0,0,0,0,0,0,
- Methods,
- 0,
- 0,
- &CValue::Type,
- 0,0,0,0,0,0,
- py_base_new
-};
-
-PyObject *BL_ArmatureChannel::py_repr(void)
-{
- return PyUnicode_FromString(m_posechannel->name);
-}
-
-PyObject *BL_ArmatureChannel::GetProxy()
-{
- return GetProxyPlus_Ext(this, &Type, m_posechannel);
-}
-
-PyObject *BL_ArmatureChannel::NewProxy(bool py_owns)
-{
- return NewProxyPlus_Ext(this, &Type, m_posechannel, py_owns);
-}
-
-#endif // WITH_PYTHON
-
-BL_ArmatureChannel::BL_ArmatureChannel(
- BL_ArmatureObject *armature,
- bPoseChannel *posechannel)
- : PyObjectPlus(), m_posechannel(posechannel), m_armature(armature)
-{
-}
-
-BL_ArmatureChannel::~BL_ArmatureChannel()
-{
-}
-
-#ifdef WITH_PYTHON
-
-// PYTHON
-
-PyMethodDef BL_ArmatureChannel::Methods[] = {
- {NULL,NULL} //Sentinel
-};
-
-// order of definition of attributes, must match Attributes[] array
-#define BCA_BONE 0
-#define BCA_PARENT 1
-
-PyAttributeDef BL_ArmatureChannel::Attributes[] = {
- // Keep these attributes in order of BCA_ defines!!! used by py_attr_getattr and py_attr_setattr
- KX_PYATTRIBUTE_RO_FUNCTION("bone",BL_ArmatureChannel,py_attr_getattr),
- KX_PYATTRIBUTE_RO_FUNCTION("parent",BL_ArmatureChannel,py_attr_getattr),
-
- { NULL } //Sentinel
-};
-
-/* attributes directly taken from bPoseChannel */
-PyAttributeDef BL_ArmatureChannel::AttributesPtr[] = {
- KX_PYATTRIBUTE_CHAR_RO("name",bPoseChannel,name),
- KX_PYATTRIBUTE_FLAG_RO("has_ik",bPoseChannel,flag, POSE_CHAIN),
- KX_PYATTRIBUTE_FLAG_NEGATIVE_RO("ik_dof_x",bPoseChannel,ikflag, BONE_IK_NO_XDOF),
- KX_PYATTRIBUTE_FLAG_NEGATIVE_RO("ik_dof_y",bPoseChannel,ikflag, BONE_IK_NO_YDOF),
- KX_PYATTRIBUTE_FLAG_NEGATIVE_RO("ik_dof_z",bPoseChannel,ikflag, BONE_IK_NO_ZDOF),
- KX_PYATTRIBUTE_FLAG_RO("ik_limit_x",bPoseChannel,ikflag, BONE_IK_XLIMIT),
- KX_PYATTRIBUTE_FLAG_RO("ik_limit_y",bPoseChannel,ikflag, BONE_IK_YLIMIT),
- KX_PYATTRIBUTE_FLAG_RO("ik_limit_z",bPoseChannel,ikflag, BONE_IK_ZLIMIT),
- KX_PYATTRIBUTE_FLAG_RO("ik_rot_control",bPoseChannel,ikflag, BONE_IK_ROTCTL),
- KX_PYATTRIBUTE_FLAG_RO("ik_lin_control",bPoseChannel,ikflag, BONE_IK_LINCTL),
- KX_PYATTRIBUTE_FLOAT_VECTOR_RW("location",-FLT_MAX,FLT_MAX,bPoseChannel,loc,3),
- KX_PYATTRIBUTE_FLOAT_VECTOR_RW("scale",-FLT_MAX,FLT_MAX,bPoseChannel,size,3),
- KX_PYATTRIBUTE_FLOAT_VECTOR_RW("rotation_quaternion",-1.0f,1.0f,bPoseChannel,quat,4),
- KX_PYATTRIBUTE_FLOAT_VECTOR_RW("rotation_euler",-10.f,10.f,bPoseChannel,eul,3),
- KX_PYATTRIBUTE_SHORT_RW("rotation_mode",ROT_MODE_MIN,ROT_MODE_MAX,false,bPoseChannel,rotmode),
- KX_PYATTRIBUTE_FLOAT_MATRIX_RO("channel_matrix",bPoseChannel,chan_mat,4),
- KX_PYATTRIBUTE_FLOAT_MATRIX_RO("pose_matrix",bPoseChannel,pose_mat,4),
- KX_PYATTRIBUTE_FLOAT_VECTOR_RO("pose_head",bPoseChannel,pose_head,3),
- KX_PYATTRIBUTE_FLOAT_VECTOR_RO("pose_tail",bPoseChannel,pose_tail,3),
- KX_PYATTRIBUTE_FLOAT_RO("ik_min_x",bPoseChannel,limitmin[0]),
- KX_PYATTRIBUTE_FLOAT_RO("ik_max_x",bPoseChannel,limitmax[0]),
- KX_PYATTRIBUTE_FLOAT_RO("ik_min_y",bPoseChannel,limitmin[1]),
- KX_PYATTRIBUTE_FLOAT_RO("ik_max_y",bPoseChannel,limitmax[1]),
- KX_PYATTRIBUTE_FLOAT_RO("ik_min_z",bPoseChannel,limitmin[2]),
- KX_PYATTRIBUTE_FLOAT_RO("ik_max_z",bPoseChannel,limitmax[2]),
- KX_PYATTRIBUTE_FLOAT_RO("ik_stiffness_x",bPoseChannel,stiffness[0]),
- KX_PYATTRIBUTE_FLOAT_RO("ik_stiffness_y",bPoseChannel,stiffness[1]),
- KX_PYATTRIBUTE_FLOAT_RO("ik_stiffness_z",bPoseChannel,stiffness[2]),
- KX_PYATTRIBUTE_FLOAT_RO("ik_stretch",bPoseChannel,ikstretch),
- KX_PYATTRIBUTE_FLOAT_RW("ik_rot_weight",0,1.0f,bPoseChannel,ikrotweight),
- KX_PYATTRIBUTE_FLOAT_RW("ik_lin_weight",0,1.0f,bPoseChannel,iklinweight),
- KX_PYATTRIBUTE_RW_FUNCTION("joint_rotation",BL_ArmatureChannel,py_attr_get_joint_rotation,py_attr_set_joint_rotation),
- { NULL } //Sentinel
-};
-
-PyObject *BL_ArmatureChannel::py_attr_getattr(void *self_v, const struct KX_PYATTRIBUTE_DEF *attrdef)
-{
- BL_ArmatureChannel* self = static_cast<BL_ArmatureChannel*>(self_v);
- bPoseChannel* channel = self->m_posechannel;
- int attr_order = attrdef-Attributes;
-
- if (!channel) {
- PyErr_SetString(PyExc_AttributeError, "channel is NULL");
- return NULL;
- }
-
- switch (attr_order) {
- case BCA_BONE:
- // bones are standalone proxy
- return NewProxyPlus_Ext(NULL,&BL_ArmatureBone::Type,channel->bone,false);
- case BCA_PARENT:
- {
- BL_ArmatureChannel* parent = self->m_armature->GetChannel(channel->parent);
- if (parent)
- return parent->GetProxy();
- else
- Py_RETURN_NONE;
- }
- }
- PyErr_SetString(PyExc_AttributeError, "channel unknown attribute");
- return NULL;
-}
-
-int BL_ArmatureChannel::py_attr_setattr(void *self_v, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- BL_ArmatureChannel* self = static_cast<BL_ArmatureChannel*>(self_v);
- bPoseChannel* channel = self->m_posechannel;
- int attr_order = attrdef-Attributes;
-
-// int ival;
-// double dval;
-// char* sval;
-// KX_GameObject *oval;
-
- if (!channel) {
- PyErr_SetString(PyExc_AttributeError, "channel is NULL");
- return PY_SET_ATTR_FAIL;
- }
-
- switch (attr_order) {
- default:
- break;
- }
-
- PyErr_SetString(PyExc_AttributeError, "channel unknown attribute");
- return PY_SET_ATTR_FAIL;
-}
-
-PyObject *BL_ArmatureChannel::py_attr_get_joint_rotation(void *self_v, const struct KX_PYATTRIBUTE_DEF *attrdef)
-{
- bPoseChannel* pchan = static_cast<bPoseChannel*>(self_v);
- // decompose the pose matrix in euler rotation
- float rest_mat[3][3];
- float pose_mat[3][3];
- float joint_mat[3][3];
- float joints[3];
- float norm;
- double sa, ca;
- // get rotation in armature space
- copy_m3_m4(pose_mat, pchan->pose_mat);
- normalize_m3(pose_mat);
- if (pchan->parent) {
- // bone has a parent, compute the rest pose of the bone taking actual pose of parent
- mul_m3_m3m4(rest_mat, pchan->parent->pose_mat, pchan->bone->bone_mat);
- normalize_m3(rest_mat);
- } else {
- // otherwise, the bone matrix in armature space is the rest pose
- copy_m3_m4(rest_mat, pchan->bone->arm_mat);
- }
- // remove the rest pose to get the joint movement
- transpose_m3(rest_mat);
- mul_m3_m3m3(joint_mat, rest_mat, pose_mat);
- joints[0] = joints[1] = joints[2] = 0.f;
- // returns a 3 element list that gives corresponding joint
- int flag = 0;
- if (!(pchan->ikflag & BONE_IK_NO_XDOF))
- flag |= 1;
- if (!(pchan->ikflag & BONE_IK_NO_YDOF))
- flag |= 2;
- if (!(pchan->ikflag & BONE_IK_NO_ZDOF))
- flag |= 4;
- switch (flag) {
- case 0: // fixed joint
- break;
- case 1: // X only
- mat3_to_eulO( joints, EULER_ORDER_XYZ,joint_mat);
- joints[1] = joints[2] = 0.f;
- break;
- case 2: // Y only
- mat3_to_eulO( joints, EULER_ORDER_XYZ,joint_mat);
- joints[0] = joints[2] = 0.f;
- break;
- case 3: // X+Y
- mat3_to_eulO( joints, EULER_ORDER_ZYX,joint_mat);
- joints[2] = 0.f;
- break;
- case 4: // Z only
- mat3_to_eulO( joints, EULER_ORDER_XYZ,joint_mat);
- joints[0] = joints[1] = 0.f;
- break;
- case 5: // X+Z
- // decompose this as an equivalent rotation vector in X/Z plane
- joints[0] = joint_mat[1][2];
- joints[2] = -joint_mat[1][0];
- norm = normalize_v3(joints);
- if (norm < FLT_EPSILON) {
- norm = (joint_mat[1][1] < 0.0f) ? (float)M_PI : 0.0f;
- } else {
- norm = acos(joint_mat[1][1]);
- }
- mul_v3_fl(joints, norm);
- break;
- case 6: // Y+Z
- mat3_to_eulO( joints, EULER_ORDER_XYZ,joint_mat);
- joints[0] = 0.f;
- break;
- case 7: // X+Y+Z
- // equivalent axis
- joints[0] = (joint_mat[1][2]-joint_mat[2][1])*0.5f;
- joints[1] = (joint_mat[2][0]-joint_mat[0][2])*0.5f;
- joints[2] = (joint_mat[0][1]-joint_mat[1][0])*0.5f;
- sa = len_v3(joints);
- ca = (joint_mat[0][0]+joint_mat[1][1]+joint_mat[1][1]-1.0f)*0.5f;
- if (sa > (double)FLT_EPSILON) {
- norm = atan2(sa,ca)/sa;
- } else {
- if (ca < 0.0) {
- norm = M_PI;
- mul_v3_fl(joints,0.f);
- if (joint_mat[0][0] > 0.f) {
- joints[0] = 1.0f;
- } else if (joint_mat[1][1] > 0.f) {
- joints[1] = 1.0f;
- } else {
- joints[2] = 1.0f;
- }
- } else {
- norm = 0.0;
- }
- }
- mul_v3_fl(joints,norm);
- break;
- }
- return Vector_CreatePyObject(joints, 3, NULL);
-}
-
-int BL_ArmatureChannel::py_attr_set_joint_rotation(void *self_v, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- BL_ArmatureChannel* self = static_cast<BL_ArmatureChannel*>(self_v);
- bPoseChannel* pchan = self->m_posechannel;
- PyObject *item;
- float joints[3];
- float quat[4];
-
- if (!PySequence_Check(value) || PySequence_Size(value) != 3) {
- PyErr_SetString(PyExc_AttributeError, "expected a sequence of 3 floats");
- return PY_SET_ATTR_FAIL;
- }
- for (int i=0; i<3; i++) {
- item = PySequence_GetItem(value, i); /* new ref */
- joints[i] = PyFloat_AsDouble(item);
- Py_DECREF(item);
- if (joints[i] == -1.0f && PyErr_Occurred()) {
- PyErr_SetString(PyExc_AttributeError, "expected a sequence of 3 floats");
- return PY_SET_ATTR_FAIL;
- }
- }
-
- int flag = 0;
- if (!(pchan->ikflag & BONE_IK_NO_XDOF))
- flag |= 1;
- if (!(pchan->ikflag & BONE_IK_NO_YDOF))
- flag |= 2;
- if (!(pchan->ikflag & BONE_IK_NO_ZDOF))
- flag |= 4;
- unit_qt(quat);
- switch (flag) {
- case 0: // fixed joint
- break;
- case 1: // X only
- joints[1] = joints[2] = 0.f;
- eulO_to_quat( quat,joints, EULER_ORDER_XYZ);
- break;
- case 2: // Y only
- joints[0] = joints[2] = 0.f;
- eulO_to_quat( quat,joints, EULER_ORDER_XYZ);
- break;
- case 3: // X+Y
- joints[2] = 0.f;
- eulO_to_quat( quat,joints, EULER_ORDER_ZYX);
- break;
- case 4: // Z only
- joints[0] = joints[1] = 0.f;
- eulO_to_quat( quat,joints, EULER_ORDER_XYZ);
- break;
- case 5: // X+Z
- // X and Z are components of an equivalent rotation axis
- joints[1] = 0;
- axis_angle_to_quat( quat,joints, len_v3(joints));
- break;
- case 6: // Y+Z
- joints[0] = 0.f;
- eulO_to_quat( quat,joints, EULER_ORDER_XYZ);
- break;
- case 7: // X+Y+Z
- // equivalent axis
- axis_angle_to_quat( quat,joints, len_v3(joints));
- break;
- }
- if (pchan->rotmode > 0) {
- quat_to_eulO( joints, pchan->rotmode,quat);
- copy_v3_v3(pchan->eul, joints);
- } else
- copy_qt_qt(pchan->quat, quat);
- return PY_SET_ATTR_SUCCESS;
-}
-
-// *************************
-// BL_ArmatureBone
-//
-// Access to Bone structure
-PyTypeObject BL_ArmatureBone::Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "BL_ArmatureBone",
- sizeof(PyObjectPlus_Proxy),
- 0,
- py_base_dealloc,
- 0,
- 0,
- 0,
- 0,
- py_bone_repr,
- 0,0,0,0,0,0,0,0,0,
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
- 0,0,0,0,0,0,0,
- Methods,
- 0,
- 0,
- &CValue::Type,
- 0,0,0,0,0,0,
- py_base_new
-};
-
-// not used since this class is never instantiated
-PyObject *BL_ArmatureBone::GetProxy()
-{
- return NULL;
-}
-PyObject *BL_ArmatureBone::NewProxy(bool py_owns)
-{
- return NULL;
-}
-
-PyObject *BL_ArmatureBone::py_bone_repr(PyObject *self)
-{
- Bone* bone = static_cast<Bone*>BGE_PROXY_PTR(self);
- return PyUnicode_FromString(bone->name);
-}
-
-PyMethodDef BL_ArmatureBone::Methods[] = {
- {NULL,NULL} //Sentinel
-};
-
-/* no attributes on C++ class since it is never instantiated */
-PyAttributeDef BL_ArmatureBone::Attributes[] = {
- { NULL } //Sentinel
-};
-
-// attributes that work on proxy ptr (points to a Bone structure)
-PyAttributeDef BL_ArmatureBone::AttributesPtr[] = {
- KX_PYATTRIBUTE_CHAR_RO("name",Bone,name),
- KX_PYATTRIBUTE_FLAG_RO("connected",Bone,flag, BONE_CONNECTED),
- KX_PYATTRIBUTE_FLAG_RO("hinge",Bone,flag, BONE_HINGE),
- KX_PYATTRIBUTE_FLAG_NEGATIVE_RO("inherit_scale",Bone,flag, BONE_NO_SCALE),
- KX_PYATTRIBUTE_SHORT_RO("bbone_segments",Bone,segments),
- KX_PYATTRIBUTE_FLOAT_RO("roll",Bone,roll),
- KX_PYATTRIBUTE_FLOAT_VECTOR_RO("head",Bone,head,3),
- KX_PYATTRIBUTE_FLOAT_VECTOR_RO("tail",Bone,tail,3),
- KX_PYATTRIBUTE_FLOAT_RO("length",Bone,length),
- KX_PYATTRIBUTE_FLOAT_VECTOR_RO("arm_head",Bone,arm_head,3),
- KX_PYATTRIBUTE_FLOAT_VECTOR_RO("arm_tail",Bone,arm_tail,3),
- KX_PYATTRIBUTE_FLOAT_MATRIX_RO("arm_mat",Bone,arm_mat,4),
- KX_PYATTRIBUTE_FLOAT_MATRIX_RO("bone_mat",Bone,bone_mat,3),
- KX_PYATTRIBUTE_RO_FUNCTION("parent",BL_ArmatureBone,py_bone_get_parent),
- KX_PYATTRIBUTE_RO_FUNCTION("children",BL_ArmatureBone,py_bone_get_children),
- { NULL } //Sentinel
-};
-
-PyObject *BL_ArmatureBone::py_bone_get_parent(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef)
-{
- Bone* bone = reinterpret_cast<Bone*>(self);
- if (bone->parent) {
- // create a proxy unconnected to any GE object
- return NewProxyPlus_Ext(NULL,&Type,bone->parent,false);
- }
- Py_RETURN_NONE;
-}
-
-PyObject *BL_ArmatureBone::py_bone_get_children(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef)
-{
- Bone* bone = reinterpret_cast<Bone*>(self);
- Bone* child;
- int count = 0;
- for (child = (Bone *)bone->childbase.first; child; child = child->next)
- count++;
-
- PyObject *childrenlist = PyList_New(count);
-
- for (count = 0, child = (Bone *)bone->childbase.first; child; child = child->next, ++count)
- PyList_SET_ITEM(childrenlist,count,NewProxyPlus_Ext(NULL,&Type,child,false));
-
- return childrenlist;
-}
-
-#endif // WITH_PYTHON
diff --git a/source/gameengine/Converter/BL_ArmatureChannel.h b/source/gameengine/Converter/BL_ArmatureChannel.h
deleted file mode 100644
index a07097f8178..00000000000
--- a/source/gameengine/Converter/BL_ArmatureChannel.h
+++ /dev/null
@@ -1,101 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file BL_ArmatureChannel.h
- * \ingroup bgeconv
- */
-
-#ifndef __BL_ARMATURECHANNEL_H__
-#define __BL_ARMATURECHANNEL_H__
-
-#include "DNA_action_types.h"
-#include "CTR_HashedPtr.h"
-#include "CTR_Map.h"
-#include "EXP_PyObjectPlus.h"
-
-class SCA_IObject;
-class KX_GameObject;
-class BL_ArmatureObject;
-struct bConstraint;
-struct bPoseChannel;
-struct Object;
-struct bPose;
-
-class BL_ArmatureChannel : public PyObjectPlus
-{
- // use Py_HeaderPtr since we use generic pointer in proxy
- Py_HeaderPtr;
-
-private:
- friend class BL_ArmatureObject;
- struct bPoseChannel* m_posechannel;
- BL_ArmatureObject* m_armature;
-
-public:
- BL_ArmatureChannel(class BL_ArmatureObject *armature,
- struct bPoseChannel *posechannel);
- virtual ~BL_ArmatureChannel();
-
- inline const char *GetName()
- {
- return m_posechannel->name;
- }
-
-#ifdef WITH_PYTHON
- // Python access
- virtual PyObject *py_repr(void);
-
- static PyObject *py_attr_getattr(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef);
- static int py_attr_setattr(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static PyObject *py_attr_get_joint_rotation(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef);
- static int py_attr_set_joint_rotation(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
-#endif /* WITH_PYTHON */
-};
-
-/* this is a factory class to access bBone data field in the GE.
- * It's not supposed to be instantiated, we only need it for the Attributes and Method array.
- * The actual proxy object will be manually created using NewProxyPtr */
-class BL_ArmatureBone : public PyObjectPlus
-{
- // use Py_HeaderPtr since we use generic pointer in proxy
- Py_HeaderPtr;
-private:
- // make constructor private to make sure no one tries to instantiate this class
- BL_ArmatureBone() {}
- virtual ~BL_ArmatureBone() {}
-
-public:
-
-#ifdef WITH_PYTHON
- static PyObject *py_bone_repr(PyObject *self);
- static PyObject *py_bone_get_parent(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject *py_bone_get_children(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef);
-#endif
-
-};
-
-#endif /* __BL_ARMATURECHANNEL_H__ */
diff --git a/source/gameengine/Converter/BL_ArmatureConstraint.cpp b/source/gameengine/Converter/BL_ArmatureConstraint.cpp
deleted file mode 100644
index d0c7e061fb7..00000000000
--- a/source/gameengine/Converter/BL_ArmatureConstraint.cpp
+++ /dev/null
@@ -1,456 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Converter/BL_ArmatureConstraint.cpp
- * \ingroup bgeconv
- */
-
-
-#include "DNA_constraint_types.h"
-#include "DNA_action_types.h"
-#include "BL_ArmatureConstraint.h"
-#include "BL_ArmatureObject.h"
-#include "BLI_math.h"
-#include "BLI_string.h"
-#include "KX_PythonInit.h"
-
-#ifdef WITH_PYTHON
-
-PyTypeObject BL_ArmatureConstraint::Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "BL_ArmatureConstraint",
- sizeof(PyObjectPlus_Proxy),
- 0,
- py_base_dealloc,
- 0,
- 0,
- 0,
- 0,
- py_base_repr,
- 0,0,0,0,0,0,0,0,0,
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
- 0,0,0,0,0,0,0,
- Methods,
- 0,
- 0,
- &CValue::Type,
- 0,0,0,0,0,0,
- py_base_new
-};
-
-PyObject *BL_ArmatureConstraint::py_repr(void)
-{
- return PyUnicode_FromString(m_name);
-}
-
-#endif // WITH_PYTHON
-
-BL_ArmatureConstraint::BL_ArmatureConstraint(
- BL_ArmatureObject *armature,
- bPoseChannel *posechannel,
- bConstraint *constraint,
- KX_GameObject* target,
- KX_GameObject* subtarget)
- : PyObjectPlus(), m_constraint(constraint), m_posechannel(posechannel), m_armature(armature)
-{
- m_target = target;
- m_blendtarget = (target) ? target->GetBlenderObject() : NULL;
- m_subtarget = subtarget;
- m_blendsubtarget = (subtarget) ? subtarget->GetBlenderObject() : NULL;
- m_pose = m_subpose = NULL;
- if (m_blendtarget) {
- copy_m4_m4(m_blendmat, m_blendtarget->obmat);
- if (m_blendtarget->type == OB_ARMATURE)
- m_pose = m_blendtarget->pose;
- }
- if (m_blendsubtarget) {
- copy_m4_m4(m_blendsubmat, m_blendsubtarget->obmat);
- if (m_blendsubtarget->type == OB_ARMATURE)
- m_subpose = m_blendsubtarget->pose;
- }
- if (m_target)
- m_target->RegisterObject(m_armature);
- if (m_subtarget)
- m_subtarget->RegisterObject(m_armature);
- BLI_snprintf(m_name, sizeof(m_name), "%s:%s", m_posechannel->name, m_constraint->name);
-}
-
-BL_ArmatureConstraint::~BL_ArmatureConstraint()
-{
- if (m_target)
- m_target->UnregisterObject(m_armature);
- if (m_subtarget)
- m_subtarget->UnregisterObject(m_armature);
-}
-
-BL_ArmatureConstraint* BL_ArmatureConstraint::GetReplica() const
-{
- BL_ArmatureConstraint* replica = new BL_ArmatureConstraint(*this);
- replica->ProcessReplica();
- return replica;
-}
-
-void BL_ArmatureConstraint::ReParent(BL_ArmatureObject* armature)
-{
- m_armature = armature;
- if (m_target)
- m_target->RegisterObject(armature);
- if (m_subtarget)
- m_subtarget->RegisterObject(armature);
- // find the corresponding constraint in the new armature object
- if (m_constraint) {
- bPose* newpose = armature->GetOrigPose();
- char* constraint = m_constraint->name;
- char* posechannel = m_posechannel->name;
- bPoseChannel* pchan;
- bConstraint* pcon;
- m_constraint = NULL;
- m_posechannel = NULL;
- // and locate the constraint
- for (pchan = (bPoseChannel*)newpose->chanbase.first; pchan; pchan = (bPoseChannel*)pchan->next) {
- if (!strcmp(pchan->name, posechannel)) {
- // now locate the constraint
- for (pcon = (bConstraint *)pchan->constraints.first; pcon; pcon = (bConstraint *)pcon->next) {
- if (!strcmp(pcon->name, constraint)) {
- m_constraint = pcon;
- m_posechannel = pchan;
- break;
- }
- }
- break;
- }
- }
- }
-}
-
-void BL_ArmatureConstraint::Relink(CTR_Map<CTR_HashedPtr, void*> *obj_map)
-{
- void **h_obj = (*obj_map)[m_target];
- if (h_obj) {
- m_target->UnregisterObject(m_armature);
- m_target = (KX_GameObject*)(*h_obj);
- m_target->RegisterObject(m_armature);
- }
- h_obj = (*obj_map)[m_subtarget];
- if (h_obj) {
- m_subtarget->UnregisterObject(m_armature);
- m_subtarget = (KX_GameObject*)(*h_obj);
- m_subtarget->RegisterObject(m_armature);
- }
-}
-
-bool BL_ArmatureConstraint::UnlinkObject(SCA_IObject* clientobj)
-{
- bool res=false;
- if (clientobj == m_target) {
- m_target = NULL;
- res = true;
- }
- if (clientobj == m_subtarget) {
- m_subtarget = NULL;
- res = true;
- }
- return res;
-}
-
-void BL_ArmatureConstraint::UpdateTarget()
-{
- if (m_constraint && !(m_constraint->flag&CONSTRAINT_OFF) && (!m_blendtarget || m_target)) {
- if (m_blendtarget) {
- // external target, must be updated
- m_target->UpdateBlenderObjectMatrix(m_blendtarget);
- if (m_pose && m_target->GetGameObjectType() == SCA_IObject::OBJ_ARMATURE)
- // update the pose in case a bone is specified in the constraint target
- m_blendtarget->pose = ((BL_ArmatureObject*)m_target)->GetOrigPose();
- }
- if (m_blendsubtarget && m_subtarget) {
- m_subtarget->UpdateBlenderObjectMatrix(m_blendsubtarget);
- if (m_subpose && m_subtarget->GetGameObjectType() == SCA_IObject::OBJ_ARMATURE)
- m_blendsubtarget->pose = ((BL_ArmatureObject*)m_subtarget)->GetOrigPose();
- }
- }
-}
-
-void BL_ArmatureConstraint::RestoreTarget()
-{
- if (m_constraint && !(m_constraint->flag&CONSTRAINT_OFF) && (!m_blendtarget || m_target)) {
- if (m_blendtarget) {
- copy_m4_m4(m_blendtarget->obmat, m_blendmat);
- if (m_pose)
- m_blendtarget->pose = m_pose;
- }
- if (m_blendsubtarget && m_subtarget) {
- copy_m4_m4(m_blendsubtarget->obmat, m_blendsubmat);
- if (m_subpose)
- m_blendsubtarget->pose = m_subpose;
- }
- }
-}
-
-bool BL_ArmatureConstraint::Match(const char* posechannel, const char* constraint)
-{
- return (!strcmp(m_posechannel->name, posechannel) && !strcmp(m_constraint->name, constraint));
-}
-
-void BL_ArmatureConstraint::SetTarget(KX_GameObject* target)
-{
- if (m_blendtarget) {
- if (target != m_target) {
- m_target->UnregisterObject(m_armature);
- m_target = target;
- if (m_target)
- m_target->RegisterObject(m_armature);
- }
- }
-
-}
-
-void BL_ArmatureConstraint::SetSubtarget(KX_GameObject* subtarget)
-{
- if (m_blendsubtarget) {
- if (subtarget != m_subtarget) {
- m_subtarget->UnregisterObject(m_armature);
- m_subtarget = subtarget;
- if (m_subtarget)
- m_subtarget->RegisterObject(m_armature);
- }
- }
-
-}
-
-#ifdef WITH_PYTHON
-
-// PYTHON
-
-PyMethodDef BL_ArmatureConstraint::Methods[] = {
- {NULL,NULL} //Sentinel
-};
-
-// order of definition of attributes, must match Attributes[] array
-#define BCA_TYPE 0
-#define BCA_NAME 1
-#define BCA_ENFORCE 2
-#define BCA_HEADTAIL 3
-#define BCA_LINERROR 4
-#define BCA_ROTERROR 5
-#define BCA_TARGET 6
-#define BCA_SUBTARGET 7
-#define BCA_ACTIVE 8
-#define BCA_IKWEIGHT 9
-#define BCA_IKTYPE 10
-#define BCA_IKFLAG 11
-#define BCA_IKDIST 12
-#define BCA_IKMODE 13
-
-PyAttributeDef BL_ArmatureConstraint::Attributes[] = {
- // Keep these attributes in order of BCA_ defines!!! used by py_attr_getattr and py_attr_setattr
- KX_PYATTRIBUTE_RO_FUNCTION("type",BL_ArmatureConstraint,py_attr_getattr),
- KX_PYATTRIBUTE_RO_FUNCTION("name",BL_ArmatureConstraint,py_attr_getattr),
- KX_PYATTRIBUTE_RW_FUNCTION("enforce",BL_ArmatureConstraint,py_attr_getattr,py_attr_setattr),
- KX_PYATTRIBUTE_RW_FUNCTION("headtail",BL_ArmatureConstraint,py_attr_getattr,py_attr_setattr),
- KX_PYATTRIBUTE_RO_FUNCTION("lin_error",BL_ArmatureConstraint,py_attr_getattr),
- KX_PYATTRIBUTE_RO_FUNCTION("rot_error",BL_ArmatureConstraint,py_attr_getattr),
- KX_PYATTRIBUTE_RW_FUNCTION("target",BL_ArmatureConstraint,py_attr_getattr,py_attr_setattr),
- KX_PYATTRIBUTE_RW_FUNCTION("subtarget",BL_ArmatureConstraint,py_attr_getattr,py_attr_setattr),
- KX_PYATTRIBUTE_RW_FUNCTION("active",BL_ArmatureConstraint,py_attr_getattr,py_attr_setattr),
- KX_PYATTRIBUTE_RW_FUNCTION("ik_weight",BL_ArmatureConstraint,py_attr_getattr,py_attr_setattr),
- KX_PYATTRIBUTE_RO_FUNCTION("ik_type",BL_ArmatureConstraint,py_attr_getattr),
- KX_PYATTRIBUTE_RO_FUNCTION("ik_flag",BL_ArmatureConstraint,py_attr_getattr),
- KX_PYATTRIBUTE_RW_FUNCTION("ik_dist",BL_ArmatureConstraint,py_attr_getattr,py_attr_setattr),
- KX_PYATTRIBUTE_RW_FUNCTION("ik_mode",BL_ArmatureConstraint,py_attr_getattr,py_attr_setattr),
-
- { NULL } //Sentinel
-};
-
-
-PyObject *BL_ArmatureConstraint::py_attr_getattr(void *self_v, const struct KX_PYATTRIBUTE_DEF *attrdef)
-{
- BL_ArmatureConstraint* self = static_cast<BL_ArmatureConstraint*>(self_v);
- bConstraint* constraint = self->m_constraint;
- bKinematicConstraint* ikconstraint = (constraint && constraint->type == CONSTRAINT_TYPE_KINEMATIC) ? (bKinematicConstraint*)constraint->data : NULL;
- int attr_order = attrdef-Attributes;
-
- if (!constraint) {
- PyErr_SetString(PyExc_AttributeError, "constraint is NULL");
- return NULL;
- }
-
- switch (attr_order) {
- case BCA_TYPE:
- return PyLong_FromLong(constraint->type);
- case BCA_NAME:
- return PyUnicode_FromString(constraint->name);
- case BCA_ENFORCE:
- return PyFloat_FromDouble(constraint->enforce);
- case BCA_HEADTAIL:
- return PyFloat_FromDouble(constraint->headtail);
- case BCA_LINERROR:
- return PyFloat_FromDouble(constraint->lin_error);
- case BCA_ROTERROR:
- return PyFloat_FromDouble(constraint->rot_error);
- case BCA_TARGET:
- if (!self->m_target)
- Py_RETURN_NONE;
- else
- return self->m_target->GetProxy();
- case BCA_SUBTARGET:
- if (!self->m_subtarget)
- Py_RETURN_NONE;
- else
- return self->m_subtarget->GetProxy();
- case BCA_ACTIVE:
- return PyBool_FromLong((constraint->flag & CONSTRAINT_OFF) == 0);
- case BCA_IKWEIGHT:
- case BCA_IKTYPE:
- case BCA_IKFLAG:
- case BCA_IKDIST:
- case BCA_IKMODE:
- if (!ikconstraint) {
- PyErr_SetString(PyExc_AttributeError, "constraint is not of IK type");
- return NULL;
- }
- switch (attr_order) {
- case BCA_IKWEIGHT:
- return PyFloat_FromDouble(ikconstraint->weight);
- case BCA_IKTYPE:
- return PyLong_FromLong(ikconstraint->type);
- case BCA_IKFLAG:
- return PyLong_FromLong(ikconstraint->flag);
- case BCA_IKDIST:
- return PyFloat_FromDouble(ikconstraint->dist);
- case BCA_IKMODE:
- return PyLong_FromLong(ikconstraint->mode);
- }
- // should not come here
- break;
- }
- PyErr_SetString(PyExc_AttributeError, "constraint unknown attribute");
- return NULL;
-}
-
-int BL_ArmatureConstraint::py_attr_setattr(void *self_v, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- BL_ArmatureConstraint* self = static_cast<BL_ArmatureConstraint*>(self_v);
- bConstraint* constraint = self->m_constraint;
- bKinematicConstraint* ikconstraint = (constraint && constraint->type == CONSTRAINT_TYPE_KINEMATIC) ? (bKinematicConstraint*)constraint->data : NULL;
- int attr_order = attrdef-Attributes;
- int ival;
- double dval;
-// char* sval;
- SCA_LogicManager *logicmgr = KX_GetActiveScene()->GetLogicManager();
- KX_GameObject *oval;
-
- if (!constraint) {
- PyErr_SetString(PyExc_AttributeError, "constraint is NULL");
- return PY_SET_ATTR_FAIL;
- }
-
- switch (attr_order) {
- case BCA_ENFORCE:
- dval = PyFloat_AsDouble(value);
- if (dval < 0.0 || dval > 1.0) { /* also accounts for non float */
- PyErr_SetString(PyExc_AttributeError, "constraint.enforce = float: BL_ArmatureConstraint, expected a float between 0 and 1");
- return PY_SET_ATTR_FAIL;
- }
- constraint->enforce = dval;
- return PY_SET_ATTR_SUCCESS;
-
- case BCA_HEADTAIL:
- dval = PyFloat_AsDouble(value);
- if (dval < 0.0 || dval > 1.0) { /* also accounts for non float */
- PyErr_SetString(PyExc_AttributeError, "constraint.headtail = float: BL_ArmatureConstraint, expected a float between 0 and 1");
- return PY_SET_ATTR_FAIL;
- }
- constraint->headtail = dval;
- return PY_SET_ATTR_SUCCESS;
-
- case BCA_TARGET:
- if (!ConvertPythonToGameObject(logicmgr, value, &oval, true, "constraint.target = value: BL_ArmatureConstraint"))
- return PY_SET_ATTR_FAIL; // ConvertPythonToGameObject sets the error
- self->SetTarget(oval);
- return PY_SET_ATTR_SUCCESS;
-
- case BCA_SUBTARGET:
- if (!ConvertPythonToGameObject(logicmgr, value, &oval, true, "constraint.subtarget = value: BL_ArmatureConstraint"))
- return PY_SET_ATTR_FAIL; // ConvertPythonToGameObject sets the error
- self->SetSubtarget(oval);
- return PY_SET_ATTR_SUCCESS;
-
- case BCA_ACTIVE:
- ival = PyObject_IsTrue( value );
- if (ival == -1) {
- PyErr_SetString(PyExc_AttributeError, "constraint.active = bool: BL_ArmatureConstraint, expected True or False");
- return PY_SET_ATTR_FAIL;
- }
- self->m_constraint->flag = (self->m_constraint->flag & ~CONSTRAINT_OFF) | ((ival)?0:CONSTRAINT_OFF);
- return PY_SET_ATTR_SUCCESS;
-
- case BCA_IKWEIGHT:
- case BCA_IKDIST:
- case BCA_IKMODE:
- if (!ikconstraint) {
- PyErr_SetString(PyExc_AttributeError, "constraint is not of IK type");
- return PY_SET_ATTR_FAIL;
- }
- switch (attr_order) {
- case BCA_IKWEIGHT:
- dval = PyFloat_AsDouble(value);
- if (dval < 0.0 || dval > 1.0) { /* also accounts for non float */
- PyErr_SetString(PyExc_AttributeError, "constraint.weight = float: BL_ArmatureConstraint, expected a float between 0 and 1");
- return PY_SET_ATTR_FAIL;
- }
- ikconstraint->weight = dval;
- return PY_SET_ATTR_SUCCESS;
-
- case BCA_IKDIST:
- dval = PyFloat_AsDouble(value);
- if (dval < 0.0) { /* also accounts for non float */
- PyErr_SetString(PyExc_AttributeError, "constraint.ik_dist = float: BL_ArmatureConstraint, expected a positive float");
- return PY_SET_ATTR_FAIL;
- }
- ikconstraint->dist = dval;
- return PY_SET_ATTR_SUCCESS;
-
- case BCA_IKMODE:
- ival = PyLong_AsLong(value);
- if (ival < 0) {
- PyErr_SetString(PyExc_AttributeError, "constraint.ik_mode = integer: BL_ArmatureConstraint, expected a positive integer");
- return PY_SET_ATTR_FAIL;
- }
- ikconstraint->mode = ival;
- return PY_SET_ATTR_SUCCESS;
- }
- // should not come here
- break;
-
- }
-
- PyErr_SetString(PyExc_AttributeError, "constraint unknown attribute");
- return PY_SET_ATTR_FAIL;
-}
-
-#endif // WITH_PYTHON
diff --git a/source/gameengine/Converter/BL_ArmatureConstraint.h b/source/gameengine/Converter/BL_ArmatureConstraint.h
deleted file mode 100644
index 1d9f7f0d548..00000000000
--- a/source/gameengine/Converter/BL_ArmatureConstraint.h
+++ /dev/null
@@ -1,125 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file BL_ArmatureConstraint.h
- * \ingroup bgeconv
- */
-
-#ifndef __BL_ARMATURECONSTRAINT_H__
-#define __BL_ARMATURECONSTRAINT_H__
-
-#include "DNA_constraint_types.h"
-#include "CTR_HashedPtr.h"
-#include "CTR_Map.h"
-#include "EXP_PyObjectPlus.h"
-
-class SCA_IObject;
-class KX_GameObject;
-class BL_ArmatureObject;
-struct bConstraint;
-struct bPoseChannel;
-struct Object;
-struct bPose;
-
-/**
- * SG_DList : element of controlled constraint list
- * head = BL_ArmatureObject::m_controlledConstraints
- * SG_QList : not used
- */
-class BL_ArmatureConstraint : public PyObjectPlus
-{
- Py_Header
-
-private:
- struct bConstraint* m_constraint;
- struct bPoseChannel* m_posechannel;
- class BL_ArmatureObject* m_armature;
- char m_name[64];
- KX_GameObject* m_target;
- KX_GameObject* m_subtarget;
- struct Object* m_blendtarget;
- struct Object* m_blendsubtarget;
- float m_blendmat[4][4];
- float m_blendsubmat[4][4];
- struct bPose* m_pose;
- struct bPose* m_subpose;
-
-public:
- BL_ArmatureConstraint(class BL_ArmatureObject *armature,
- struct bPoseChannel *posechannel,
- struct bConstraint *constraint,
- KX_GameObject* target,
- KX_GameObject* subtarget);
- virtual ~BL_ArmatureConstraint();
-
- BL_ArmatureConstraint* GetReplica() const;
- void ReParent(BL_ArmatureObject* armature);
- void Relink(CTR_Map<CTR_HashedPtr, void*> *map);
- bool UnlinkObject(SCA_IObject* clientobj);
-
- void UpdateTarget();
- void RestoreTarget();
-
- bool Match(const char* posechannel, const char* constraint);
- const char* GetName() { return m_name; }
-
- void SetConstraintFlag(int flag)
- {
- if (m_constraint)
- m_constraint->flag |= flag;
- }
- void ClrConstraintFlag(int flag)
- {
- if (m_constraint)
- m_constraint->flag &= ~flag;
- }
- void SetWeight(float weight)
- {
- if (m_constraint && m_constraint->type == CONSTRAINT_TYPE_KINEMATIC && m_constraint->data) {
- bKinematicConstraint* con = (bKinematicConstraint*)m_constraint->data;
- con->weight = weight;
- }
- }
- void SetInfluence(float influence)
- {
- if (m_constraint)
- m_constraint->enforce = influence;
- }
- void SetTarget(KX_GameObject* target);
- void SetSubtarget(KX_GameObject* subtarget);
-
-#ifdef WITH_PYTHON
-
- // Python access
- virtual PyObject *py_repr(void);
-
- static PyObject *py_attr_getattr(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef);
- static int py_attr_setattr(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
-#endif /* WITH_PYTHON */
-};
-
-#endif /* __BL_ARMATURECONSTRAINT_H__ */
diff --git a/source/gameengine/Converter/BL_ArmatureObject.cpp b/source/gameengine/Converter/BL_ArmatureObject.cpp
deleted file mode 100644
index 049fd49cab9..00000000000
--- a/source/gameengine/Converter/BL_ArmatureObject.cpp
+++ /dev/null
@@ -1,691 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Converter/BL_ArmatureObject.cpp
- * \ingroup bgeconv
- */
-
-
-#include "BL_ArmatureObject.h"
-#include "BL_ActionActuator.h"
-#include "BL_Action.h"
-#include "KX_BlenderSceneConverter.h"
-#include "MEM_guardedalloc.h"
-#include "BLI_blenlib.h"
-#include "BLI_math.h"
-#include "BLI_utildefines.h"
-#include "BLI_ghash.h"
-#include "BIK_api.h"
-#include "BKE_action.h"
-#include "BKE_armature.h"
-#include "BKE_object.h"
-#include "BKE_library.h"
-#include "BKE_global.h"
-
-extern "C" {
-#include "BKE_animsys.h"
-}
-
-#include "BKE_constraint.h"
-#include "CTR_Map.h"
-#include "CTR_HashedPtr.h"
-#include "MEM_guardedalloc.h"
-#include "DNA_action_types.h"
-#include "DNA_armature_types.h"
-#include "DNA_object_types.h"
-#include "DNA_scene_types.h"
-#include "DNA_constraint_types.h"
-#include "RNA_access.h"
-#include "KX_PythonInit.h"
-#include "KX_KetsjiEngine.h"
-
-#include "EXP_ListWrapper.h"
-
-#include "MT_Matrix4x4.h"
-
-/**
- * Move here pose function for game engine so that we can mix with GE objects
- * Principle is as follow:
- * Use Blender structures so that BKE_pose_where_is can be used unchanged
- * Copy the constraint so that they can be enabled/disabled/added/removed at runtime
- * Don't copy the constraints for the pose used by the Action actuator, it does not need them.
- * Scan the constraint structures so that the KX equivalent of target objects are identified and
- * stored in separate list.
- * When it is about to evaluate the pose, set the KX object position in the obmat of the corresponding
- * Blender objects and restore after the evaluation.
- */
-static void game_copy_pose(bPose **dst, bPose *src, int copy_constraint)
-{
- bPose *out;
- bPoseChannel *pchan, *outpchan;
- GHash *ghash;
-
- /* the game engine copies the current armature pose and then swaps
- * the object pose pointer. this makes it possible to change poses
- * without affecting the original blender data. */
-
- if (!src) {
- *dst=NULL;
- return;
- }
- else if (*dst==src) {
- printf("game_copy_pose source and target are the same\n");
- *dst=NULL;
- return;
- }
-
- out= (bPose*)MEM_dupallocN(src);
- out->chanhash = NULL;
- out->agroups.first= out->agroups.last= NULL;
- out->ikdata = NULL;
- out->ikparam = MEM_dupallocN(src->ikparam);
- out->flag |= POSE_GAME_ENGINE;
- BLI_duplicatelist(&out->chanbase, &src->chanbase);
-
- /* remap pointers */
- ghash= BLI_ghash_new(BLI_ghashutil_ptrhash, BLI_ghashutil_ptrcmp, "game_copy_pose gh");
-
- pchan= (bPoseChannel *)src->chanbase.first;
- outpchan= (bPoseChannel *)out->chanbase.first;
- for (; pchan; pchan=pchan->next, outpchan=outpchan->next)
- BLI_ghash_insert(ghash, pchan, outpchan);
-
- for (pchan = (bPoseChannel *)out->chanbase.first; pchan; pchan = pchan->next) {
- pchan->parent= (bPoseChannel *)BLI_ghash_lookup(ghash, pchan->parent);
- pchan->child= (bPoseChannel *)BLI_ghash_lookup(ghash, pchan->child);
-
- if (copy_constraint) {
- ListBase listb;
- // copy all constraint for backward compatibility
- // BKE_constraints_copy NULLs listb, no need to make extern for this operation.
- BKE_constraints_copy(&listb, &pchan->constraints, false);
- pchan->constraints= listb;
- }
- else {
- BLI_listbase_clear(&pchan->constraints);
- }
-
- if (pchan->custom) {
- id_us_plus(&pchan->custom->id);
- }
-
- // fails to link, props are not used in the BGE yet.
-#if 0
- if (pchan->prop)
- pchan->prop= IDP_CopyProperty(pchan->prop);
-#endif
- pchan->prop = NULL;
- pchan->draw_data = NULL;
- }
-
- BLI_ghash_free(ghash, NULL, NULL);
- // set acceleration structure for channel lookup
- BKE_pose_channels_hash_make(out);
- *dst=out;
-}
-
-
-
-/* Only allowed for Poses with identical channels */
-static void game_blend_poses(bPose *dst, bPose *src, float srcweight, short mode)
-{
- bPoseChannel *dchan;
- const bPoseChannel *schan;
- bConstraint *dcon, *scon;
- float dstweight;
- int i;
-
- if (mode == BL_Action::ACT_BLEND_BLEND)
- {
- dstweight = 1.0f - srcweight;
- } else if (mode == BL_Action::ACT_BLEND_ADD)
- {
- dstweight = 1.0f;
- } else {
- dstweight = 1.0f;
- }
-
- schan= (bPoseChannel *)src->chanbase.first;
- for (dchan = (bPoseChannel *)dst->chanbase.first; dchan; dchan=(bPoseChannel *)dchan->next, schan= (bPoseChannel *)schan->next) {
- // always blend on all channels since we don't know which one has been set
- /* quat interpolation done separate */
- if (schan->rotmode == ROT_MODE_QUAT) {
- float dquat[4], squat[4];
-
- copy_qt_qt(dquat, dchan->quat);
- copy_qt_qt(squat, schan->quat);
- // Normalize quaternions so that interpolation/multiplication result is correct.
- normalize_qt(dquat);
- normalize_qt(squat);
-
- if (mode==BL_Action::ACT_BLEND_BLEND)
- interp_qt_qtqt(dchan->quat, dquat, squat, srcweight);
- else {
- mul_fac_qt_fl(squat, srcweight);
- mul_qt_qtqt(dchan->quat, dquat, squat);
- }
-
- normalize_qt(dchan->quat);
- }
-
- for (i=0; i<3; i++) {
- /* blending for loc and scale are pretty self-explanatory... */
- dchan->loc[i] = (dchan->loc[i]*dstweight) + (schan->loc[i]*srcweight);
- dchan->size[i] = 1.0f + ((dchan->size[i]-1.0f)*dstweight) + ((schan->size[i]-1.0f)*srcweight);
-
- /* euler-rotation interpolation done here instead... */
- // FIXME: are these results decent?
- if (schan->rotmode)
- dchan->eul[i] = (dchan->eul[i]*dstweight) + (schan->eul[i]*srcweight);
- }
- for (dcon= (bConstraint *)dchan->constraints.first, scon= (bConstraint *)schan->constraints.first;
- dcon && scon;
- dcon = dcon->next, scon = scon->next)
- {
- /* no 'add' option for constraint blending */
- dcon->enforce= dcon->enforce*(1.0f-srcweight) + scon->enforce*srcweight;
- }
- }
-
- /* this pose is now in src time */
- dst->ctime= src->ctime;
-}
-
-BL_ArmatureObject::BL_ArmatureObject(
- void* sgReplicationInfo,
- SG_Callbacks callbacks,
- Object *armature,
- Scene *scene,
- int vert_deform_type)
-
-: KX_GameObject(sgReplicationInfo,callbacks),
- m_controlledConstraints(),
- m_poseChannels(),
- m_scene(scene), // maybe remove later. needed for BKE_pose_where_is
- m_lastframe(0.0),
- m_timestep(0.040),
- m_vert_deform_type(vert_deform_type),
- m_constraintNumber(0),
- m_channelNumber(0),
- m_lastapplyframe(0.0)
-{
- m_origObjArma = armature; // Keep a copy of the original armature so we can fix drivers later
- m_objArma = BKE_object_copy(G.main, armature);
- m_objArma->data = BKE_armature_copy(G.main, (bArmature *)armature->data);
- // During object replication ob->data is increase, we decrease it now because we get a copy.
- id_us_min(&((bArmature *)m_origObjArma->data)->id);
- m_pose = m_objArma->pose;
- // need this to get iTaSC working ok in the BGE
- m_pose->flag |= POSE_GAME_ENGINE;
- memcpy(m_obmat, m_objArma->obmat, sizeof(m_obmat));
-
- // The side-effect of this method registers this object as "animatable" with the KX_Scene.
- GetActionManager();
-}
-
-BL_ArmatureObject::~BL_ArmatureObject()
-{
- BL_ArmatureConstraint* constraint;
- while ((constraint = m_controlledConstraints.Remove()) != NULL) {
- delete constraint;
- }
- BL_ArmatureChannel* channel;
- while ((channel = static_cast<BL_ArmatureChannel*>(m_poseChannels.Remove())) != NULL) {
- delete channel;
- }
-
- if (m_objArma) {
- BKE_libblock_free(G.main, m_objArma->data);
- BKE_libblock_free(G.main, m_objArma);
- }
-}
-
-
-void BL_ArmatureObject::LoadConstraints(KX_BlenderSceneConverter* converter)
-{
- // first delete any existing constraint (should not have any)
- while (!m_controlledConstraints.Empty()) {
- BL_ArmatureConstraint* constraint = m_controlledConstraints.Remove();
- delete constraint;
- }
- m_constraintNumber = 0;
-
- // list all the constraint and convert them to BL_ArmatureConstraint
- // get the persistent pose structure
- bPoseChannel* pchan;
- bConstraint* pcon;
- const bConstraintTypeInfo* cti;
- Object* blendtarget;
- KX_GameObject* gametarget;
- KX_GameObject* gamesubtarget;
-
- // and locate the constraint
- for (pchan = (bPoseChannel *)m_pose->chanbase.first; pchan; pchan = pchan->next) {
- for (pcon = (bConstraint *)pchan->constraints.first; pcon; pcon = pcon->next) {
- if (pcon->flag & CONSTRAINT_DISABLE)
- continue;
- // which constraint should we support?
- switch (pcon->type) {
- case CONSTRAINT_TYPE_TRACKTO:
- case CONSTRAINT_TYPE_DAMPTRACK:
- case CONSTRAINT_TYPE_KINEMATIC:
- case CONSTRAINT_TYPE_ROTLIKE:
- case CONSTRAINT_TYPE_LOCLIKE:
- case CONSTRAINT_TYPE_MINMAX:
- case CONSTRAINT_TYPE_SIZELIKE:
- case CONSTRAINT_TYPE_LOCKTRACK:
- case CONSTRAINT_TYPE_STRETCHTO:
- case CONSTRAINT_TYPE_CLAMPTO:
- case CONSTRAINT_TYPE_TRANSFORM:
- case CONSTRAINT_TYPE_DISTLIMIT:
- case CONSTRAINT_TYPE_TRANSLIKE:
- cti = BKE_constraint_typeinfo_get(pcon);
- gametarget = gamesubtarget = NULL;
- if (cti && cti->get_constraint_targets) {
- ListBase listb = { NULL, NULL };
- cti->get_constraint_targets(pcon, &listb);
- if (listb.first) {
- bConstraintTarget* target = (bConstraintTarget*)listb.first;
- if (target->tar && target->tar != m_objArma) {
- // only remember external objects, self target is handled automatically
- blendtarget = target->tar;
- gametarget = converter->FindGameObject(blendtarget);
- }
- if (target->next != NULL) {
- // secondary target
- target = target->next;
- if (target->tar && target->tar != m_objArma) {
- // only track external object
- blendtarget = target->tar;
- gamesubtarget = converter->FindGameObject(blendtarget);
- }
- }
- }
- if (cti->flush_constraint_targets)
- cti->flush_constraint_targets(pcon, &listb, 1);
- }
- BL_ArmatureConstraint* constraint = new BL_ArmatureConstraint(this, pchan, pcon, gametarget, gamesubtarget);
- m_controlledConstraints.AddBack(constraint);
- m_constraintNumber++;
- }
- }
- }
-
- // If we have constraints, make sure we get treated as an "animated" object
- if (m_constraintNumber > 0)
- GetActionManager();
-}
-
-BL_ArmatureConstraint* BL_ArmatureObject::GetConstraint(const char* posechannel, const char* constraintname)
-{
- SG_DList::iterator<BL_ArmatureConstraint> cit(m_controlledConstraints);
- for (cit.begin(); !cit.end(); ++cit) {
- BL_ArmatureConstraint* constraint = *cit;
- if (constraint->Match(posechannel, constraintname))
- return constraint;
- }
- return NULL;
-}
-
-BL_ArmatureConstraint* BL_ArmatureObject::GetConstraint(const char* posechannelconstraint)
-{
- // performance: use hash string instead of plain string compare
- SG_DList::iterator<BL_ArmatureConstraint> cit(m_controlledConstraints);
- for (cit.begin(); !cit.end(); ++cit) {
- BL_ArmatureConstraint* constraint = *cit;
- if (!strcmp(constraint->GetName(), posechannelconstraint))
- return constraint;
- }
- return NULL;
-}
-
-BL_ArmatureConstraint* BL_ArmatureObject::GetConstraint(int index)
-{
- SG_DList::iterator<BL_ArmatureConstraint> cit(m_controlledConstraints);
- for (cit.begin(); !cit.end() && index; ++cit, --index);
- return (cit.end()) ? NULL : *cit;
-}
-
-/* this function is called to populate the m_poseChannels list */
-void BL_ArmatureObject::LoadChannels()
-{
- if (m_poseChannels.Empty()) {
- bPoseChannel* pchan;
- BL_ArmatureChannel* proxy;
-
- m_channelNumber = 0;
- for (pchan = (bPoseChannel *)m_pose->chanbase.first; pchan; pchan=(bPoseChannel *)pchan->next) {
- proxy = new BL_ArmatureChannel(this, pchan);
- m_poseChannels.AddBack(proxy);
- m_channelNumber++;
- }
- }
-}
-
-BL_ArmatureChannel* BL_ArmatureObject::GetChannel(bPoseChannel* pchan)
-{
- LoadChannels();
- SG_DList::iterator<BL_ArmatureChannel> cit(m_poseChannels);
- for (cit.begin(); !cit.end(); ++cit)
- {
- BL_ArmatureChannel* channel = *cit;
- if (channel->m_posechannel == pchan)
- return channel;
- }
- return NULL;
-}
-
-BL_ArmatureChannel* BL_ArmatureObject::GetChannel(const char* str)
-{
- LoadChannels();
- SG_DList::iterator<BL_ArmatureChannel> cit(m_poseChannels);
- for (cit.begin(); !cit.end(); ++cit)
- {
- BL_ArmatureChannel* channel = *cit;
- if (!strcmp(channel->m_posechannel->name, str))
- return channel;
- }
- return NULL;
-}
-
-BL_ArmatureChannel* BL_ArmatureObject::GetChannel(int index)
-{
- LoadChannels();
- if (index < 0 || index >= m_channelNumber)
- return NULL;
- SG_DList::iterator<BL_ArmatureChannel> cit(m_poseChannels);
- for (cit.begin(); !cit.end() && index; ++cit, --index);
- return (cit.end()) ? NULL : *cit;
-}
-
-CValue* BL_ArmatureObject::GetReplica()
-{
- BL_ArmatureObject* replica = new BL_ArmatureObject(*this);
- replica->ProcessReplica();
- return replica;
-}
-
-void BL_ArmatureObject::ProcessReplica()
-{
- KX_GameObject::ProcessReplica();
-
- bArmature* tmp = (bArmature*)m_objArma->data;
- m_objArma = BKE_object_copy(G.main, m_objArma);
- m_objArma->data = BKE_armature_copy(G.main, tmp);
- m_pose = m_objArma->pose;
-}
-
-void BL_ArmatureObject::ReParentLogic()
-{
- SG_DList::iterator<BL_ArmatureConstraint> cit(m_controlledConstraints);
- for (cit.begin(); !cit.end(); ++cit) {
- (*cit)->ReParent(this);
- }
- KX_GameObject::ReParentLogic();
-}
-
-void BL_ArmatureObject::Relink(CTR_Map<CTR_HashedPtr, void*> *obj_map)
-{
- SG_DList::iterator<BL_ArmatureConstraint> cit(m_controlledConstraints);
- for (cit.begin(); !cit.end(); ++cit) {
- (*cit)->Relink(obj_map);
- }
- KX_GameObject::Relink(obj_map);
-}
-
-bool BL_ArmatureObject::UnlinkObject(SCA_IObject* clientobj)
-{
- // clientobj is being deleted, make sure we don't hold any reference to it
- bool res = false;
- SG_DList::iterator<BL_ArmatureConstraint> cit(m_controlledConstraints);
- for (cit.begin(); !cit.end(); ++cit) {
- res |= (*cit)->UnlinkObject(clientobj);
- }
- return res;
-}
-
-void BL_ArmatureObject::ApplyPose()
-{
- /* TODO: This doesn't work currently because of eval_ctx. */
-#if 0
- m_armpose = m_objArma->pose;
- m_objArma->pose = m_pose;
- // in the GE, we use ctime to store the timestep
- m_pose->ctime = (float)m_timestep;
- //m_scene->r.cfra++;
- if (m_lastapplyframe != m_lastframe) {
- // update the constraint if any, first put them all off so that only the active ones will be updated
- SG_DList::iterator<BL_ArmatureConstraint> cit(m_controlledConstraints);
- for (cit.begin(); !cit.end(); ++cit) {
- (*cit)->UpdateTarget();
- }
- // update ourself
- UpdateBlenderObjectMatrix(m_objArma);
- BKE_pose_where_is(m_scene, m_objArma); // XXX
- // restore ourself
- memcpy(m_objArma->obmat, m_obmat, sizeof(m_obmat));
- // restore active targets
- for (cit.begin(); !cit.end(); ++cit) {
- (*cit)->RestoreTarget();
- }
- m_lastapplyframe = m_lastframe;
- }
-#endif
-}
-
-void BL_ArmatureObject::RestorePose()
-{
- m_objArma->pose = m_armpose;
- m_armpose = NULL;
-}
-
-void BL_ArmatureObject::SetPose(bPose *pose)
-{
- extract_pose_from_pose(m_pose, pose);
- m_lastapplyframe = -1.0;
-}
-
-void BL_ArmatureObject::SetPoseByAction(bAction *action, float localtime)
-{
- Object *arm = GetArmatureObject();
-
- PointerRNA ptrrna;
- RNA_id_pointer_create(&arm->id, &ptrrna);
-
- animsys_evaluate_action(&ptrrna, action, NULL, localtime);
-}
-
-void BL_ArmatureObject::BlendInPose(bPose *blend_pose, float weight, short mode)
-{
- game_blend_poses(m_pose, blend_pose, weight, mode);
-}
-
-bool BL_ArmatureObject::UpdateTimestep(double curtime)
-{
- if (curtime != m_lastframe) {
- // compute the timestep for the underlying IK algorithm
- m_timestep = curtime-m_lastframe;
- m_lastframe= curtime;
- }
-
- return false;
-}
-
-void BL_ArmatureObject::GetPose(bPose **pose)
-{
- /* If the caller supplies a null pose, create a new one. */
- /* Otherwise, copy the armature's pose channels into the caller-supplied pose */
-
- if (!*pose) {
- /* probably not to good of an idea to
- * duplicate everything, but it clears up
- * a crash and memory leakage when
- * &BL_ActionActuator::m_pose is freed
- */
- game_copy_pose(pose, m_pose, 0);
- }
- else {
- if (*pose == m_pose)
- // no need to copy if the pointers are the same
- return;
-
- extract_pose_from_pose(*pose, m_pose);
- }
-}
-
-double BL_ArmatureObject::GetLastFrame()
-{
- return m_lastframe;
-}
-
-bool BL_ArmatureObject::GetBoneMatrix(Bone* bone, MT_Matrix4x4& matrix)
-{
- bPoseChannel *pchan;
-
- ApplyPose();
- pchan = BKE_pose_channel_find_name(m_objArma->pose, bone->name);
- if (pchan)
- matrix.setValue(&pchan->pose_mat[0][0]);
- RestorePose();
-
- return (pchan != NULL);
-}
-
-float BL_ArmatureObject::GetBoneLength(Bone* bone) const
-{
- return (float)(MT_Point3(bone->head) - MT_Point3(bone->tail)).length();
-}
-
-#ifdef WITH_PYTHON
-
-// PYTHON
-
-PyTypeObject BL_ArmatureObject::Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "BL_ArmatureObject",
- sizeof(PyObjectPlus_Proxy),
- 0,
- py_base_dealloc,
- 0,
- 0,
- 0,
- 0,
- py_base_repr,
- 0,
- &KX_GameObject::Sequence,
- &KX_GameObject::Mapping,
- 0,0,0,
- NULL,
- NULL,
- 0,
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
- 0,0,0,0,0,0,0,
- Methods,
- 0,
- 0,
- &KX_GameObject::Type,
- 0,0,0,0,0,0,
- py_base_new
-};
-
-PyMethodDef BL_ArmatureObject::Methods[] = {
- KX_PYMETHODTABLE_NOARGS(BL_ArmatureObject, update),
- {NULL,NULL} //Sentinel
-};
-
-PyAttributeDef BL_ArmatureObject::Attributes[] = {
-
- KX_PYATTRIBUTE_RO_FUNCTION("constraints", BL_ArmatureObject, pyattr_get_constraints),
- KX_PYATTRIBUTE_RO_FUNCTION("channels", BL_ArmatureObject, pyattr_get_channels),
- {NULL} //Sentinel
-};
-
-static int bl_armature_object_get_constraints_size_cb(void *self_v)
-{
- return ((BL_ArmatureObject *)self_v)->GetConstraintNumber();
-}
-
-static PyObject *bl_armature_object_get_constraints_item_cb(void *self_v, int index)
-{
- return ((BL_ArmatureObject *)self_v)->GetConstraint(index)->GetProxy();
-}
-
-static const char *bl_armature_object_get_constraints_item_name_cb(void *self_v, int index)
-{
- return ((BL_ArmatureObject *)self_v)->GetConstraint(index)->GetName();
-}
-
-PyObject *BL_ArmatureObject::pyattr_get_constraints(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- return (new CListWrapper(self_v,
- ((BL_ArmatureObject *)self_v)->GetProxy(),
- NULL,
- bl_armature_object_get_constraints_size_cb,
- bl_armature_object_get_constraints_item_cb,
- bl_armature_object_get_constraints_item_name_cb,
- NULL))->NewProxy(true);
-}
-
-static int bl_armature_object_get_channels_size_cb(void *self_v)
-{
- return ((BL_ArmatureObject *)self_v)->GetChannelNumber();
-}
-
-static PyObject *bl_armature_object_get_channels_item_cb(void *self_v, int index)
-{
- return ((BL_ArmatureObject *)self_v)->GetChannel(index)->GetProxy();
-}
-
-static const char *bl_armature_object_get_channels_item_name_cb(void *self_v, int index)
-{
- return ((BL_ArmatureObject *)self_v)->GetChannel(index)->GetName();
-}
-
-PyObject *BL_ArmatureObject::pyattr_get_channels(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- BL_ArmatureObject *self = static_cast<BL_ArmatureObject *>(self_v);
- self->LoadChannels(); // make sure we have the channels
- return (new CListWrapper(self_v,
- self->GetProxy(),
- NULL,
- bl_armature_object_get_channels_size_cb,
- bl_armature_object_get_channels_item_cb,
- bl_armature_object_get_channels_item_name_cb,
- NULL))->NewProxy(true);
-}
-
-KX_PYMETHODDEF_DOC_NOARGS(BL_ArmatureObject, update,
- "update()\n"
- "Make sure that the armature will be updated on next graphic frame.\n"
- "This is automatically done if a KX_ArmatureActuator with mode run is active\n"
- "or if an action is playing. This function is useful in other cases.\n")
-{
- UpdateTimestep(KX_GetActiveEngine()->GetFrameTime());
- Py_RETURN_NONE;
-}
-
-#endif // WITH_PYTHON
diff --git a/source/gameengine/Converter/BL_ArmatureObject.h b/source/gameengine/Converter/BL_ArmatureObject.h
deleted file mode 100644
index 691e73d6bde..00000000000
--- a/source/gameengine/Converter/BL_ArmatureObject.h
+++ /dev/null
@@ -1,145 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file BL_ArmatureObject.h
- * \ingroup bgeconv
- */
-
-#ifndef __BL_ARMATUREOBJECT_H__
-#define __BL_ARMATUREOBJECT_H__
-
-#include "KX_GameObject.h"
-#include "BL_ArmatureConstraint.h"
-#include "BL_ArmatureChannel.h"
-
-#include "SG_IObject.h"
-#include <vector>
-#include <algorithm>
-
-struct bArmature;
-struct Bone;
-struct bConstraint;
-class BL_ActionActuator;
-class BL_ArmatureActuator;
-class MT_Matrix4x4;
-struct Object;
-class KX_BlenderSceneConverter;
-
-class BL_ArmatureObject : public KX_GameObject
-{
- Py_Header
-public:
-
- double GetLastFrame ();
- virtual void ProcessReplica();
- virtual void ReParentLogic();
- virtual void Relink(CTR_Map<CTR_HashedPtr, void*> *obj_map);
- virtual bool UnlinkObject(SCA_IObject* clientobj);
-
- BL_ArmatureObject(
- void* sgReplicationInfo,
- SG_Callbacks callbacks,
- Object *armature,
- Scene *scene,
- int vert_deform_type
- );
- virtual ~BL_ArmatureObject();
-
- virtual CValue* GetReplica();
- void GetPose(struct bPose **pose);
- void SetPose (struct bPose *pose);
- struct bPose *GetOrigPose() {return m_pose;} // never edit this, only for accessing names
-
- void ApplyPose();
- void SetPoseByAction(struct bAction* action, float localtime);
- void BlendInPose(struct bPose *blend_pose, float weight, short mode);
- void RestorePose();
-
- bool UpdateTimestep(double curtime);
-
- struct bArmature *GetArmature() { return (bArmature*)m_objArma->data; }
- const struct bArmature * GetArmature() const { return (bArmature*)m_objArma->data; }
- const struct Scene * GetScene() const { return m_scene; }
-
- Object* GetArmatureObject() {return m_objArma;}
- Object* GetOrigArmatureObject() {return m_origObjArma;}
-
- int GetVertDeformType() {return m_vert_deform_type;}
-
- // for constraint python API
- void LoadConstraints(KX_BlenderSceneConverter* converter);
- size_t GetConstraintNumber() const { return m_constraintNumber; }
- BL_ArmatureConstraint* GetConstraint(const char* posechannel, const char* constraint);
- BL_ArmatureConstraint* GetConstraint(const char* posechannelconstraint);
- BL_ArmatureConstraint* GetConstraint(int index);
- // for pose channel python API
- void LoadChannels();
- size_t GetChannelNumber() const { return m_channelNumber; }
- BL_ArmatureChannel* GetChannel(bPoseChannel* channel);
- BL_ArmatureChannel* GetChannel(const char* channel);
- BL_ArmatureChannel* GetChannel(int index);
-
- /// Retrieve the pose matrix for the specified bone.
- /// Returns true on success.
- bool GetBoneMatrix(Bone* bone, MT_Matrix4x4& matrix);
-
- /// Returns the bone length. The end of the bone is in the local y direction.
- float GetBoneLength(Bone* bone) const;
-
- virtual int GetGameObjectType() { return OBJ_ARMATURE; }
-
-#ifdef WITH_PYTHON
-
- // PYTHON
- static PyObject *pyattr_get_constraints(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject *pyattr_get_channels(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- KX_PYMETHOD_DOC_NOARGS(BL_ArmatureObject, update);
-
-#endif /* WITH_PYTHON */
-
-protected:
- /* list element: BL_ArmatureConstraint. Use SG_DListHead to have automatic list replication */
- SG_DListHead<BL_ArmatureConstraint> m_controlledConstraints;
- /* list element: BL_ArmatureChannel. Use SG_DList to avoid list replication */
- SG_DList m_poseChannels;
- Object *m_objArma;
- Object *m_origObjArma;
- struct bPose *m_pose;
- struct bPose *m_armpose;
- struct Scene *m_scene; // need for BKE_pose_where_is
- double m_lastframe;
- double m_timestep; // delta since last pose evaluation.
- int m_vert_deform_type;
- size_t m_constraintNumber;
- size_t m_channelNumber;
- // store the original armature object matrix
- float m_obmat[4][4];
-
- double m_lastapplyframe;
-};
-
-#endif /* __BL_ARMATUREOBJECT_H__ */
diff --git a/source/gameengine/Converter/BL_BlenderDataConversion.cpp b/source/gameengine/Converter/BL_BlenderDataConversion.cpp
deleted file mode 100644
index 39f517e03e8..00000000000
--- a/source/gameengine/Converter/BL_BlenderDataConversion.cpp
+++ /dev/null
@@ -1,2473 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- * Convert blender data to ketsji
- */
-
-/** \file gameengine/Converter/BL_BlenderDataConversion.cpp
- * \ingroup bgeconv
- */
-
-#ifdef _MSC_VER
-# pragma warning (disable:4786)
-#endif
-
-/* Since threaded object update we've disabled in-place
- * curve evaluation (in cases when applying curve modifier
- * with target curve non-evaluated yet).
- *
- * This requires game engine to take care of DAG and object
- * evaluation (currently it's designed to export only objects
- * it able to render).
- *
- * This workaround will make sure that curve_cache for curves
- * is up-to-date.
- */
-
-/* TODO: Disabled for now, because of eval_ctx. */
-//#define THREADED_DAG_WORKAROUND
-
-#include <math.h>
-#include <vector>
-#include <algorithm>
-
-#include "BL_BlenderDataConversion.h"
-
-#include "MT_Transform.h"
-#include "MT_MinMax.h"
-
-#include "PHY_Pro.h"
-#include "PHY_IPhysicsEnvironment.h"
-
-#include "RAS_MeshObject.h"
-#include "RAS_IRasterizer.h"
-#include "RAS_ILightObject.h"
-
-#include "KX_ConvertActuators.h"
-#include "KX_ConvertControllers.h"
-#include "KX_ConvertSensors.h"
-#include "SCA_LogicManager.h"
-#include "SCA_TimeEventManager.h"
-
-#include "KX_ClientObjectInfo.h"
-#include "KX_Scene.h"
-#include "KX_GameObject.h"
-#include "KX_Light.h"
-#include "KX_Camera.h"
-#include "KX_EmptyObject.h"
-#include "KX_FontObject.h"
-
-#include "RAS_TexMatrix.h"
-#include "RAS_ICanvas.h"
-#include "RAS_Polygon.h"
-#include "RAS_TexVert.h"
-#include "RAS_BucketManager.h"
-#include "RAS_IPolygonMaterial.h"
-#include "BL_Material.h"
-#include "KX_BlenderMaterial.h"
-#include "BL_Texture.h"
-
-#include "BKE_main.h"
-#include "BKE_global.h"
-#include "BKE_object.h"
-#include "BL_ModifierDeformer.h"
-#include "BL_ShapeDeformer.h"
-#include "BL_SkinDeformer.h"
-#include "BL_MeshDeformer.h"
-#include "KX_SoftBodyDeformer.h"
-#include "BLI_utildefines.h"
-#include "BLI_listbase.h"
-
-#include "KX_WorldInfo.h"
-
-#include "KX_KetsjiEngine.h"
-#include "KX_BlenderSceneConverter.h"
-
-/* This little block needed for linking to Blender... */
-#ifdef WIN32
-#include "BLI_winstuff.h"
-#endif
-
-/* This list includes only data type definitions */
-#include "DNA_object_types.h"
-#include "DNA_material_types.h"
-#include "DNA_texture_types.h"
-#include "DNA_image_types.h"
-#include "DNA_lamp_types.h"
-#include "DNA_group_types.h"
-#include "DNA_scene_types.h"
-#include "DNA_camera_types.h"
-#include "DNA_property_types.h"
-#include "DNA_text_types.h"
-#include "DNA_sensor_types.h"
-#include "DNA_controller_types.h"
-#include "DNA_actuator_types.h"
-#include "DNA_mesh_types.h"
-#include "DNA_meshdata_types.h"
-#include "DNA_view3d_types.h"
-#include "DNA_world_types.h"
-#include "DNA_sound_types.h"
-#include "DNA_key_types.h"
-#include "DNA_armature_types.h"
-#include "DNA_action_types.h"
-#include "DNA_object_force_types.h"
-#include "DNA_constraint_types.h"
-
-#include "MEM_guardedalloc.h"
-
-#include "BKE_key.h"
-#include "BKE_mesh.h"
-
-#include "BLI_math.h"
-
-extern "C" {
-#include "BKE_scene.h"
-#include "BKE_customdata.h"
-#include "BKE_cdderivedmesh.h"
-#include "BKE_DerivedMesh.h"
-#include "BKE_group.h"
-#include "BKE_layer.h"
-#include "BKE_material.h" /* give_current_material */
-#include "BKE_image.h"
-#include "IMB_imbuf_types.h"
-#include "BKE_displist.h"
-
-extern Material defmaterial; /* material.c */
-}
-
-/* end of blender include block */
-
-#include "KX_BlenderInputDevice.h"
-#include "KX_ConvertProperties.h"
-
-#include "SG_Node.h"
-#include "SG_BBox.h"
-#include "SG_Tree.h"
-#include "KX_SG_NodeRelationships.h"
-#include "KX_SG_BoneParentNodeRelationship.h"
-
-#ifdef WITH_BULLET
-#include "CcdPhysicsEnvironment.h"
-#include "CcdGraphicController.h"
-#endif
-
-#include "KX_MotionState.h"
-
-#include "BL_ArmatureObject.h"
-#include "BL_DeformableGameObject.h"
-
-#include "KX_NavMeshObject.h"
-#include "KX_ObstacleSimulation.h"
-
-#include "BLI_threads.h"
-
-
-static bool default_light_mode = 0;
-
-static std::map<int, SCA_IInputDevice::KX_EnumInputs> create_translate_table()
-{
- std::map<int, SCA_IInputDevice::KX_EnumInputs> m;
-
- /* The reverse table. In order to not confuse ourselves, we */
- /* immediately convert all events that come in to KX codes. */
- m[LEFTMOUSE ] = SCA_IInputDevice::KX_LEFTMOUSE;
- m[MIDDLEMOUSE ] = SCA_IInputDevice::KX_MIDDLEMOUSE;
- m[RIGHTMOUSE ] = SCA_IInputDevice::KX_RIGHTMOUSE;
- m[WHEELUPMOUSE ] = SCA_IInputDevice::KX_WHEELUPMOUSE;
- m[WHEELDOWNMOUSE ] = SCA_IInputDevice::KX_WHEELDOWNMOUSE;
- m[MOUSEX ] = SCA_IInputDevice::KX_MOUSEX;
- m[MOUSEY ] = SCA_IInputDevice::KX_MOUSEY;
-
- // TIMERS
-
- m[TIMER0 ] = SCA_IInputDevice::KX_TIMER0;
- m[TIMER1 ] = SCA_IInputDevice::KX_TIMER1;
- m[TIMER2 ] = SCA_IInputDevice::KX_TIMER2;
-
- // SYSTEM
-
-#if 0
- /* **** XXX **** */
- m[KEYBD ] = SCA_IInputDevice::KX_KEYBD;
- m[RAWKEYBD ] = SCA_IInputDevice::KX_RAWKEYBD;
- m[REDRAW ] = SCA_IInputDevice::KX_REDRAW;
- m[INPUTCHANGE ] = SCA_IInputDevice::KX_INPUTCHANGE;
- m[QFULL ] = SCA_IInputDevice::KX_QFULL;
- m[WINFREEZE ] = SCA_IInputDevice::KX_WINFREEZE;
- m[WINTHAW ] = SCA_IInputDevice::KX_WINTHAW;
- m[WINCLOSE ] = SCA_IInputDevice::KX_WINCLOSE;
- m[WINQUIT ] = SCA_IInputDevice::KX_WINQUIT;
- m[Q_FIRSTTIME ] = SCA_IInputDevice::KX_Q_FIRSTTIME;
- /* **** XXX **** */
-#endif
-
- // standard keyboard
-
- m[AKEY ] = SCA_IInputDevice::KX_AKEY;
- m[BKEY ] = SCA_IInputDevice::KX_BKEY;
- m[CKEY ] = SCA_IInputDevice::KX_CKEY;
- m[DKEY ] = SCA_IInputDevice::KX_DKEY;
- m[EKEY ] = SCA_IInputDevice::KX_EKEY;
- m[FKEY ] = SCA_IInputDevice::KX_FKEY;
- m[GKEY ] = SCA_IInputDevice::KX_GKEY;
- m[HKEY ] = SCA_IInputDevice::KX_HKEY;
- m[IKEY ] = SCA_IInputDevice::KX_IKEY;
- m[JKEY ] = SCA_IInputDevice::KX_JKEY;
- m[KKEY ] = SCA_IInputDevice::KX_KKEY;
- m[LKEY ] = SCA_IInputDevice::KX_LKEY;
- m[MKEY ] = SCA_IInputDevice::KX_MKEY;
- m[NKEY ] = SCA_IInputDevice::KX_NKEY;
- m[OKEY ] = SCA_IInputDevice::KX_OKEY;
- m[PKEY ] = SCA_IInputDevice::KX_PKEY;
- m[QKEY ] = SCA_IInputDevice::KX_QKEY;
- m[RKEY ] = SCA_IInputDevice::KX_RKEY;
- m[SKEY ] = SCA_IInputDevice::KX_SKEY;
- m[TKEY ] = SCA_IInputDevice::KX_TKEY;
- m[UKEY ] = SCA_IInputDevice::KX_UKEY;
- m[VKEY ] = SCA_IInputDevice::KX_VKEY;
- m[WKEY ] = SCA_IInputDevice::KX_WKEY;
- m[XKEY ] = SCA_IInputDevice::KX_XKEY;
- m[YKEY ] = SCA_IInputDevice::KX_YKEY;
- m[ZKEY ] = SCA_IInputDevice::KX_ZKEY;
-
- m[ZEROKEY ] = SCA_IInputDevice::KX_ZEROKEY;
- m[ONEKEY ] = SCA_IInputDevice::KX_ONEKEY;
- m[TWOKEY ] = SCA_IInputDevice::KX_TWOKEY;
- m[THREEKEY ] = SCA_IInputDevice::KX_THREEKEY;
- m[FOURKEY ] = SCA_IInputDevice::KX_FOURKEY;
- m[FIVEKEY ] = SCA_IInputDevice::KX_FIVEKEY;
- m[SIXKEY ] = SCA_IInputDevice::KX_SIXKEY;
- m[SEVENKEY ] = SCA_IInputDevice::KX_SEVENKEY;
- m[EIGHTKEY ] = SCA_IInputDevice::KX_EIGHTKEY;
- m[NINEKEY ] = SCA_IInputDevice::KX_NINEKEY;
-
- m[CAPSLOCKKEY ] = SCA_IInputDevice::KX_CAPSLOCKKEY;
-
- m[LEFTCTRLKEY ] = SCA_IInputDevice::KX_LEFTCTRLKEY;
- m[LEFTALTKEY ] = SCA_IInputDevice::KX_LEFTALTKEY;
- m[RIGHTALTKEY ] = SCA_IInputDevice::KX_RIGHTALTKEY;
- m[RIGHTCTRLKEY ] = SCA_IInputDevice::KX_RIGHTCTRLKEY;
- m[RIGHTSHIFTKEY ] = SCA_IInputDevice::KX_RIGHTSHIFTKEY;
- m[LEFTSHIFTKEY ] = SCA_IInputDevice::KX_LEFTSHIFTKEY;
-
- m[ESCKEY ] = SCA_IInputDevice::KX_ESCKEY;
- m[TABKEY ] = SCA_IInputDevice::KX_TABKEY;
- m[RETKEY ] = SCA_IInputDevice::KX_RETKEY;
- m[SPACEKEY ] = SCA_IInputDevice::KX_SPACEKEY;
- m[LINEFEEDKEY ] = SCA_IInputDevice::KX_LINEFEEDKEY;
- m[BACKSPACEKEY ] = SCA_IInputDevice::KX_BACKSPACEKEY;
- m[DELKEY ] = SCA_IInputDevice::KX_DELKEY;
- m[SEMICOLONKEY ] = SCA_IInputDevice::KX_SEMICOLONKEY;
- m[PERIODKEY ] = SCA_IInputDevice::KX_PERIODKEY;
- m[COMMAKEY ] = SCA_IInputDevice::KX_COMMAKEY;
- m[QUOTEKEY ] = SCA_IInputDevice::KX_QUOTEKEY;
- m[ACCENTGRAVEKEY ] = SCA_IInputDevice::KX_ACCENTGRAVEKEY;
- m[MINUSKEY ] = SCA_IInputDevice::KX_MINUSKEY;
- m[PLUSKEY ] = SCA_IInputDevice::KX_PLUSKEY;
- m[SLASHKEY ] = SCA_IInputDevice::KX_SLASHKEY;
- m[BACKSLASHKEY ] = SCA_IInputDevice::KX_BACKSLASHKEY;
- m[EQUALKEY ] = SCA_IInputDevice::KX_EQUALKEY;
- m[LEFTBRACKETKEY ] = SCA_IInputDevice::KX_LEFTBRACKETKEY;
- m[RIGHTBRACKETKEY ] = SCA_IInputDevice::KX_RIGHTBRACKETKEY;
-
- m[LEFTARROWKEY ] = SCA_IInputDevice::KX_LEFTARROWKEY;
- m[DOWNARROWKEY ] = SCA_IInputDevice::KX_DOWNARROWKEY;
- m[RIGHTARROWKEY ] = SCA_IInputDevice::KX_RIGHTARROWKEY;
- m[UPARROWKEY ] = SCA_IInputDevice::KX_UPARROWKEY;
-
- m[PAD2 ] = SCA_IInputDevice::KX_PAD2;
- m[PAD4 ] = SCA_IInputDevice::KX_PAD4;
- m[PAD6 ] = SCA_IInputDevice::KX_PAD6;
- m[PAD8 ] = SCA_IInputDevice::KX_PAD8;
-
- m[PAD1 ] = SCA_IInputDevice::KX_PAD1;
- m[PAD3 ] = SCA_IInputDevice::KX_PAD3;
- m[PAD5 ] = SCA_IInputDevice::KX_PAD5;
- m[PAD7 ] = SCA_IInputDevice::KX_PAD7;
- m[PAD9 ] = SCA_IInputDevice::KX_PAD9;
-
- m[PADPERIOD ] = SCA_IInputDevice::KX_PADPERIOD;
- m[PADSLASHKEY ] = SCA_IInputDevice::KX_PADSLASHKEY;
- m[PADASTERKEY ] = SCA_IInputDevice::KX_PADASTERKEY;
-
- m[PAD0 ] = SCA_IInputDevice::KX_PAD0;
- m[PADMINUS ] = SCA_IInputDevice::KX_PADMINUS;
- m[PADENTER ] = SCA_IInputDevice::KX_PADENTER;
- m[PADPLUSKEY ] = SCA_IInputDevice::KX_PADPLUSKEY;
-
-
- m[F1KEY ] = SCA_IInputDevice::KX_F1KEY;
- m[F2KEY ] = SCA_IInputDevice::KX_F2KEY;
- m[F3KEY ] = SCA_IInputDevice::KX_F3KEY;
- m[F4KEY ] = SCA_IInputDevice::KX_F4KEY;
- m[F5KEY ] = SCA_IInputDevice::KX_F5KEY;
- m[F6KEY ] = SCA_IInputDevice::KX_F6KEY;
- m[F7KEY ] = SCA_IInputDevice::KX_F7KEY;
- m[F8KEY ] = SCA_IInputDevice::KX_F8KEY;
- m[F9KEY ] = SCA_IInputDevice::KX_F9KEY;
- m[F10KEY ] = SCA_IInputDevice::KX_F10KEY;
- m[F11KEY ] = SCA_IInputDevice::KX_F11KEY;
- m[F12KEY ] = SCA_IInputDevice::KX_F12KEY;
- m[F13KEY ] = SCA_IInputDevice::KX_F13KEY;
- m[F14KEY ] = SCA_IInputDevice::KX_F14KEY;
- m[F15KEY ] = SCA_IInputDevice::KX_F15KEY;
- m[F16KEY ] = SCA_IInputDevice::KX_F16KEY;
- m[F17KEY ] = SCA_IInputDevice::KX_F17KEY;
- m[F18KEY ] = SCA_IInputDevice::KX_F18KEY;
- m[F19KEY ] = SCA_IInputDevice::KX_F19KEY;
-
- m[OSKEY ] = SCA_IInputDevice::KX_OSKEY;
-
- m[PAUSEKEY ] = SCA_IInputDevice::KX_PAUSEKEY;
- m[INSERTKEY ] = SCA_IInputDevice::KX_INSERTKEY;
- m[HOMEKEY ] = SCA_IInputDevice::KX_HOMEKEY;
- m[PAGEUPKEY ] = SCA_IInputDevice::KX_PAGEUPKEY;
- m[PAGEDOWNKEY ] = SCA_IInputDevice::KX_PAGEDOWNKEY;
- m[ENDKEY ] = SCA_IInputDevice::KX_ENDKEY;
-
- return m;
-}
-
-static std::map<int, SCA_IInputDevice::KX_EnumInputs> gReverseKeyTranslateTable = create_translate_table();
-
-SCA_IInputDevice::KX_EnumInputs ConvertKeyCode(int key_code)
-{
- return gReverseKeyTranslateTable[key_code];
-}
-
-static unsigned int KX_rgbaint2uint_new(unsigned int icol)
-{
- union
- {
- unsigned int integer;
- unsigned char cp[4];
- } out_color, in_color;
-
- in_color.integer = icol;
- out_color.cp[0] = in_color.cp[3]; // red
- out_color.cp[1] = in_color.cp[2]; // green
- out_color.cp[2] = in_color.cp[1]; // blue
- out_color.cp[3] = in_color.cp[0]; // alpha
-
- return out_color.integer;
-}
-
-/* Now the real converting starts... */
-static unsigned int KX_Mcol2uint_new(MCol col)
-{
- /* color has to be converted without endian sensitivity. So no shifting! */
- union
- {
- MCol col;
- unsigned int integer;
- unsigned char cp[4];
- } out_color, in_color;
-
- in_color.col = col;
- out_color.cp[0] = in_color.cp[3]; // red
- out_color.cp[1] = in_color.cp[2]; // green
- out_color.cp[2] = in_color.cp[1]; // blue
- out_color.cp[3] = in_color.cp[0]; // alpha
-
- return out_color.integer;
-}
-
-static void SetDefaultLightMode(Scene* scene)
-{
- default_light_mode = false;
- Scene *sce_iter;
- Base *base;
-
- for (SETLOOPER(scene, sce_iter, base))
- {
- if (base->object->type == OB_LAMP)
- {
- default_light_mode = true;
- return;
- }
- }
-}
-
-
-static bool GetMaterialUseVColor(Material *ma, const bool glslmat)
-{
- if (ma) {
- /* glsl uses vertex colors, otherwise use material setting
- * defmaterial doesn't have VERTEXCOLP as default [#34505] */
- return (glslmat || ma == &defmaterial || (ma->mode & MA_VERTEXCOLP) != 0);
- }
- else {
- /* no material, use vertex colors */
- return true;
- }
-}
-
-// --
-static void GetRGB(
- const bool use_vcol,
- MFace* mface,
- MCol* mmcol,
- Material *mat,
- unsigned int c[4])
-{
- unsigned int color = 0xFFFFFFFFL;
- if (use_vcol == true) {
- if (mmcol) {
- c[0] = KX_Mcol2uint_new(mmcol[0]);
- c[1] = KX_Mcol2uint_new(mmcol[1]);
- c[2] = KX_Mcol2uint_new(mmcol[2]);
- if (mface->v4)
- c[3] = KX_Mcol2uint_new(mmcol[3]);
- }
- else { // backup white
- c[0] = KX_rgbaint2uint_new(color);
- c[1] = KX_rgbaint2uint_new(color);
- c[2] = KX_rgbaint2uint_new(color);
- if (mface->v4)
- c[3] = KX_rgbaint2uint_new( color );
- }
- }
- else {
- /* material rgba */
- if (mat) {
- union {
- unsigned char cp[4];
- unsigned int integer;
- } col_converter;
- col_converter.cp[3] = (unsigned char) (mat->r * 255.0f);
- col_converter.cp[2] = (unsigned char) (mat->g * 255.0f);
- col_converter.cp[1] = (unsigned char) (mat->b * 255.0f);
- col_converter.cp[0] = (unsigned char) (mat->alpha * 255.0f);
- color = col_converter.integer;
- }
- c[0] = KX_rgbaint2uint_new(color);
- c[1] = KX_rgbaint2uint_new(color);
- c[2] = KX_rgbaint2uint_new(color);
- if (mface->v4) {
- c[3] = KX_rgbaint2uint_new(color);
- }
- }
-
-#if 0 /* white, unused */
- {
- c[0] = KX_rgbaint2uint_new(color);
- c[1] = KX_rgbaint2uint_new(color);
- c[2] = KX_rgbaint2uint_new(color);
- if (mface->v4)
- c[3] = KX_rgbaint2uint_new(color);
- }
-#endif
-}
-
-typedef struct MTF_localLayer {
- MTFace *face;
- const char *name;
-} MTF_localLayer;
-
-static void GetUVs(BL_Material *material, MTF_localLayer *layers, MFace *mface, MTFace *tface, MT_Point2 uvs[4][MAXTEX])
-{
- int unit = 0;
- if (tface)
- {
-
- uvs[0][0].setValue(tface->uv[0]);
- uvs[1][0].setValue(tface->uv[1]);
- uvs[2][0].setValue(tface->uv[2]);
-
- if (mface->v4)
- uvs[3][0].setValue(tface->uv[3]);
- }
- else
- {
- uvs[0][0] = uvs[1][0] = uvs[2][0] = uvs[3][0] = MT_Point2(0.f, 0.f);
- }
-
- vector<STR_String> found_layers;
-
- for (int vind = 0; vind<MAXTEX; vind++)
- {
- BL_Mapping &map = material->mapping[vind];
-
- if (!(map.mapping & USEUV)) continue;
-
- if (std::find(found_layers.begin(), found_layers.end(), map.uvCoName) != found_layers.end())
- continue;
-
- //If no UVSet is specified, try grabbing one from the UV/Image editor
- if (map.uvCoName.IsEmpty() && tface)
- {
- uvs[0][unit].setValue(tface->uv[0]);
- uvs[1][unit].setValue(tface->uv[1]);
- uvs[2][unit].setValue(tface->uv[2]);
-
- if (mface->v4)
- uvs[3][unit].setValue(tface->uv[3]);
-
- ++unit;
- continue;
- }
-
-
- for (int lay=0; lay<MAX_MTFACE; lay++)
- {
- MTF_localLayer& layer = layers[lay];
- if (layer.face == 0) break;
-
- if (map.uvCoName.IsEmpty() || strcmp(map.uvCoName.ReadPtr(), layer.name)==0)
- {
- uvs[0][unit].setValue(layer.face->uv[0]);
- uvs[1][unit].setValue(layer.face->uv[1]);
- uvs[2][unit].setValue(layer.face->uv[2]);
-
- if (mface->v4)
- uvs[3][unit].setValue(layer.face->uv[3]);
- else
- uvs[3][unit].setValue(0.0f, 0.0f);
-
- ++unit;
- found_layers.push_back(map.uvCoName);
- break;
- }
- }
- }
-}
-
-// ------------------------------------
-static bool ConvertMaterial(
- BL_Material *material,
- Material *mat,
- MTFace *tface,
- const char *tfaceName,
- MFace *mface,
- MCol *mmcol,
- bool glslmat)
-{
- material->Initialize();
- int texalpha = 0;
- const bool validmat = (mat != NULL);
- const bool validface = (tface != NULL);
- const bool use_vcol = GetMaterialUseVColor(mat, glslmat);
-
- material->IdMode = DEFAULT_BLENDER;
- material->glslmat = (validmat) ? glslmat: false;
- material->materialindex = mface->mat_nr;
-
- // --------------------------------
- if (validmat) {
-
- // use lighting?
- material->ras_mode |= (mat->mode & MA_SHLESS) ? 0 : USE_LIGHT;
- material->ras_mode |= (mat->game.flag & GEMAT_BACKCULL) ? 0 : TWOSIDED;
-
- // cast shadows?
- material->ras_mode |= ((mat->mode2 & MA_CASTSHADOW) && (mat->mode & MA_SHADBUF)) ? CAST_SHADOW : 0;
-
- // only shadows?
- material->ras_mode |= (mat->mode & MA_ONLYCAST) ? ONLY_SHADOW : 0;
-
- MTex *mttmp = NULL;
- int valid_index = 0;
-
- /* In Multitexture use the face texture if and only if
- * it is set in the buttons
- * In GLSL is not working yet :/ 3.2011 */
-
- // foreach MTex
- for (int i = 0; i < MAXTEX; i++) {
- // use face tex
- if (i == 0) {
-#if 0
- Image *tmp = (Image *)(tface->tpage);
-#else
- /* weak but better then nothing */
- Image *tmp = mat ? mat->edit_image : NULL;
-#endif
-
- if (tmp) {
- material->img[i] = tmp;
- material->texname[i] = material->img[i]->id.name;
- material->flag[i] |= MIPMAP;
-
- material->flag[i] |= (mat->game.alpha_blend & GEMAT_ALPHA_SORT) ? USEALPHA : 0;
- material->flag[i] |= (mat->game.alpha_blend & GEMAT_ALPHA) ? USEALPHA : 0;
- material->flag[i] |= (mat->game.alpha_blend & GEMAT_ADD) ? CALCALPHA : 0;
-
- if (material->img[i]->flag & IMA_REFLECT) {
- material->mapping[i].mapping |= USEREFL;
- }
- else {
- mttmp = getMTexFromMaterial(mat, i);
- if (mttmp && (mttmp->texco & TEXCO_UV)) {
- /* string may be "" but thats detected as empty after */
- material->mapping[i].uvCoName = mttmp->uvname;
- }
- material->mapping[i].mapping |= USEUV;
- }
-
- valid_index++;
- }
- else {
- material->img[i] = 0;
- material->texname[i] = "";
- }
- continue;
- }
-
- mttmp = getMTexFromMaterial(mat, i);
- if (mttmp) {
- if (mttmp->tex) {
- if (mttmp->tex->type == TEX_IMAGE) {
- material->mtexname[i] = mttmp->tex->id.name;
- material->img[i] = mttmp->tex->ima;
- if (material->img[i]) {
-
- material->texname[i] = material->img[i]->id.name;
- material->flag[i] |= (mttmp->tex->imaflag &TEX_MIPMAP) ? MIPMAP : 0;
- if (material->img[i] && (material->img[i]->flag & IMA_IGNORE_ALPHA) == 0) {
- material->flag[i] |= USEALPHA;
- }
- if (mttmp->tex->imaflag & TEX_CALCALPHA) {
- material->flag[i] |= CALCALPHA;
- }
- else if (mttmp->tex->flag & TEX_NEGALPHA) {
- material->flag[i] |= USENEGALPHA;
- }
-
- material->color_blend[i] = mttmp->colfac;
- material->flag[i] |= (mttmp->mapto & MAP_ALPHA) ? TEXALPHA : 0;
- material->flag[i] |= (mttmp->texflag & MTEX_NEGATIVE) ? TEXNEG : 0;
-
- if (!glslmat && (material->flag[i] & TEXALPHA)) {
- texalpha = 1;
- }
- }
- }
- else if (mttmp->tex->type == TEX_ENVMAP) {
- if (mttmp->tex->env->stype == ENV_LOAD) {
- material->mtexname[i] = mttmp->tex->id.name;
- EnvMap *env = mttmp->tex->env;
- env->ima = mttmp->tex->ima;
- material->cubemap[i] = env;
-
- if (material->cubemap[i]) {
- if (!material->cubemap[i]->cube[0]) {
- BL_Texture::SplitEnvMap(material->cubemap[i]);
- }
-
- material->texname[i] = material->cubemap[i]->ima->id.name;
- material->mapping[i].mapping |= USEENV;
- }
- }
- }
-#if 0 /* this flag isn't used anymore */
- material->flag[i] |= (BKE_animdata_from_id(mat->id) != NULL) ? HASIPO : 0;
-#endif
- /// --------------------------------
- // mapping methods
- if (mat->septex & (1 << i)) {
- // If this texture slot isn't in use, set it to disabled to prevent multi-uv problems
- material->mapping[i].mapping = DISABLE;
- }
- else {
- material->mapping[i].mapping |= (mttmp->texco & TEXCO_REFL) ? USEREFL : 0;
-
- if (mttmp->texco & TEXCO_OBJECT) {
- material->mapping[i].mapping |= USEOBJ;
- if (mttmp->object) {
- material->mapping[i].objconame = mttmp->object->id.name;
- }
- }
- else if (mttmp->texco & TEXCO_REFL) {
- material->mapping[i].mapping |= USEREFL;
- }
- else if (mttmp->texco & (TEXCO_ORCO | TEXCO_GLOB)) {
- material->mapping[i].mapping |= USEORCO;
- }
- else if (mttmp->texco & TEXCO_UV) {
- /* string may be "" but thats detected as empty after */
- material->mapping[i].uvCoName = mttmp->uvname;
- material->mapping[i].mapping |= USEUV;
- }
- else if (mttmp->texco & TEXCO_NORM) {
- material->mapping[i].mapping |= USENORM;
- }
- else if (mttmp->texco & TEXCO_TANGENT) {
- material->mapping[i].mapping |= USETANG;
- }
- else {
- material->mapping[i].mapping |= DISABLE;
- }
-
- material->mapping[i].scale[0] = mttmp->size[0];
- material->mapping[i].scale[1] = mttmp->size[1];
- material->mapping[i].scale[2] = mttmp->size[2];
- material->mapping[i].offsets[0] = mttmp->ofs[0];
- material->mapping[i].offsets[1] = mttmp->ofs[1];
- material->mapping[i].offsets[2] = mttmp->ofs[2];
-
- material->mapping[i].projplane[0] = mttmp->projx;
- material->mapping[i].projplane[1] = mttmp->projy;
- material->mapping[i].projplane[2] = mttmp->projz;
- }
- /// --------------------------------
-
- switch (mttmp->blendtype) {
- case MTEX_BLEND:
- material->blend_mode[i] = BLEND_MIX;
- break;
- case MTEX_MUL:
- material->blend_mode[i] = BLEND_MUL;
- break;
- case MTEX_ADD:
- material->blend_mode[i] = BLEND_ADD;
- break;
- case MTEX_SUB:
- material->blend_mode[i] = BLEND_SUB;
- break;
- case MTEX_SCREEN:
- material->blend_mode[i] = BLEND_SCR;
- break;
- }
- valid_index++;
- }
- }
- }
-
- // above one tex the switches here
- // are not used
- switch (valid_index) {
- case 0:
- material->IdMode = DEFAULT_BLENDER;
- break;
- case 1:
- material->IdMode = ONETEX;
- break;
- default:
- material->IdMode = GREATERTHAN2;
- break;
- }
- material->SetUsers(mat->id.us);
-
- material->num_enabled = valid_index;
-
- material->speccolor[0] = mat->specr;
- material->speccolor[1] = mat->specg;
- material->speccolor[2] = mat->specb;
- material->hard = (float)mat->har / 4.0f;
- material->matcolor[0] = mat->r;
- material->matcolor[1] = mat->g;
- material->matcolor[2] = mat->b;
- material->matcolor[3] = mat->alpha;
- material->alpha = mat->alpha;
- material->emit = mat->emit;
- material->spec_f = mat->spec;
- material->ref = mat->ref;
- material->amb = mat->amb;
-
- material->ras_mode |= (mat->material_type == MA_TYPE_WIRE) ? WIRE : 0;
- }
- else { // No Material
- int valid = 0;
-
- // check for tface tex to fallback on
- if (validface) {
-#if 0
- material->img[0] = (Image *)(tface->tpage);
-#else
- material->img[0] = mat ? mat->edit_image : NULL;
-#endif
- // ------------------------
- if (material->img[0]) {
- material->texname[0] = material->img[0]->id.name;
- material->mapping[0].mapping |= ((material->img[0]->flag & IMA_REFLECT) != 0) ? USEREFL : 0;
-
- /* see if depth of the image is 32bits */
- if (BKE_image_has_alpha(material->img[0])) {
- material->flag[0] |= USEALPHA;
- material->alphablend = GEMAT_ALPHA;
- }
- else {
- material->alphablend = GEMAT_SOLID;
- }
- valid++;
- }
- }
- else {
- material->alphablend = GEMAT_SOLID;
- }
-
- material->SetUsers(-1);
- material->num_enabled = valid;
- material->IdMode = TEXFACE;
- material->speccolor[0] = 1.0f;
- material->speccolor[1] = 1.0f;
- material->speccolor[2] = 1.0f;
- material->hard = 35.0f;
- material->matcolor[0] = 0.5f;
- material->matcolor[1] = 0.5f;
- material->matcolor[2] = 0.5f;
- material->spec_f = 0.5f;
- material->ref = 0.8f;
-
- // No material - old default TexFace properties
- material->ras_mode |= USE_LIGHT;
- }
-
- /* No material, what to do? let's see what is in the UV and set the material accordingly
- * light and visible is always on */
- if (validface) {
- /* nop */
- }
- else {
- // nothing at all
- material->alphablend = GEMAT_SOLID;
- material->tile = 0;
- }
-
- if (validmat && validface) {
- material->alphablend = mat->game.alpha_blend;
- }
-
- // with ztransp enabled, enforce alpha blending mode
- if (validmat && (mat->mode & MA_TRANSP) && (mat->mode & MA_ZTRANSP) && (material->alphablend == GEMAT_SOLID)) {
- material->alphablend = GEMAT_ALPHA;
- }
-
- // always zsort alpha + add
- if ((ELEM(material->alphablend, GEMAT_ALPHA, GEMAT_ALPHA_SORT, GEMAT_ADD) || texalpha) && (material->alphablend != GEMAT_CLIP)) {
- material->ras_mode |= ALPHA;
- material->ras_mode |= (mat && (mat->game.alpha_blend & GEMAT_ALPHA_SORT)) ? ZSORT : 0;
- }
-
- // XXX The RGB values here were meant to be temporary storage for the conversion process,
- // but fonts now make use of them too, so we leave them in for now.
- unsigned int rgb[4];
- GetRGB(use_vcol, mface, mmcol, mat, rgb);
-
- // swap the material color, so MCol on bitmap font works
- if (validmat && (use_vcol == false) && (mat->game.flag & GEMAT_TEXT)) {
- material->rgb[0] = KX_rgbaint2uint_new(rgb[0]);
- material->rgb[1] = KX_rgbaint2uint_new(rgb[1]);
- material->rgb[2] = KX_rgbaint2uint_new(rgb[2]);
- material->rgb[3] = KX_rgbaint2uint_new(rgb[3]);
- }
-
- if (validmat) {
- material->matname =(mat->id.name);
- }
- material->material = mat;
- return true;
-}
-
-static RAS_MaterialBucket *material_from_mesh(Material *ma, MFace *mface, MTFace *tface, MCol *mcol, MTF_localLayer *layers, int lightlayer, unsigned int *rgb, MT_Point2 uvs[4][RAS_TexVert::MAX_UNIT], const char *tfaceName, KX_Scene* scene, KX_BlenderSceneConverter *converter)
-{
- RAS_IPolyMaterial* polymat = converter->FindCachedPolyMaterial(scene, ma);
- BL_Material* bl_mat = converter->FindCachedBlenderMaterial(scene, ma);
- KX_BlenderMaterial* kx_blmat = NULL;
-
- /* first is the BL_Material */
- if (!bl_mat)
- {
- bl_mat = new BL_Material();
-
- ConvertMaterial(bl_mat, ma, tface, tfaceName, mface, mcol,
- converter->GetGLSLMaterials());
-
- if (ma)
- converter->CacheBlenderMaterial(scene, ma, bl_mat);
- }
-
- const bool use_vcol = GetMaterialUseVColor(ma, bl_mat->glslmat);
- GetRGB(use_vcol, mface, mcol, ma, rgb);
-
- GetUVs(bl_mat, layers, mface, tface, uvs);
-
- /* then the KX_BlenderMaterial */
- if (polymat == NULL)
- {
- kx_blmat = new KX_BlenderMaterial();
-
- kx_blmat->Initialize(scene, bl_mat, (ma?&ma->game:NULL), lightlayer);
- polymat = static_cast<RAS_IPolyMaterial*>(kx_blmat);
- if (ma)
- converter->CachePolyMaterial(scene, ma, polymat);
- }
-
- // see if a bucket was reused or a new one was created
- // this way only one KX_BlenderMaterial object has to exist per bucket
- bool bucketCreated;
- RAS_MaterialBucket* bucket = scene->FindBucket(polymat, bucketCreated);
-
- // this is needed to free up memory afterwards.
- // the converter will also prevent duplicates from being registered,
- // so just register everything.
- converter->RegisterPolyMaterial(polymat);
- converter->RegisterBlenderMaterial(bl_mat);
-
- return bucket;
-}
-
-/* blenderobj can be NULL, make sure its checked for */
-RAS_MeshObject* BL_ConvertMesh(Mesh* mesh, Object* blenderobj, KX_Scene* scene, KX_BlenderSceneConverter *converter, bool libloading)
-{
- RAS_MeshObject *meshobj;
- int lightlayer = blenderobj ? blenderobj->lay:(1<<20)-1; // all layers if no object.
-
- // Without checking names, we get some reuse we don't want that can cause
- // problems with material LoDs.
- if (blenderobj && ((meshobj = converter->FindGameMesh(mesh/*, ob->lay*/)) != NULL)) {
- const char *bge_name = meshobj->GetName().ReadPtr();
- const char *blender_name = ((ID *)blenderobj->data)->name + 2;
- if (STREQ(bge_name, blender_name)) {
- return meshobj;
- }
- }
-
- // Get DerivedMesh data
- DerivedMesh *dm = CDDM_from_mesh(mesh);
- DM_ensure_tessface(dm);
-
- MVert *mvert = dm->getVertArray(dm);
- int totvert = dm->getNumVerts(dm);
-
- MFace *mface = dm->getTessFaceArray(dm);
- MTFace *tface = static_cast<MTFace*>(dm->getTessFaceDataArray(dm, CD_MTFACE));
- MCol *mcol = static_cast<MCol*>(dm->getTessFaceDataArray(dm, CD_MCOL));
- float (*tangent)[4] = NULL;
- int totface = dm->getNumTessFaces(dm);
- const char *tfaceName = "";
-
- /* needs to be rewritten for loopdata */
- if (tface) {
- if (CustomData_get_layer_index(&dm->faceData, CD_TANGENT) == -1) {
- bool generate_data = false;
- if (CustomData_get_layer_index(&dm->loopData, CD_TANGENT) == -1) {
- DM_calc_loop_tangents(dm, true, NULL, 0);
- generate_data = true;
- }
- DM_generate_tangent_tessface_data(dm, generate_data);
- }
- tangent = (float(*)[4])dm->getTessFaceDataArray(dm, CD_TANGENT);
- }
-
- meshobj = new RAS_MeshObject(mesh);
-
- // Extract avaiable layers
- MTF_localLayer *layers = new MTF_localLayer[MAX_MTFACE];
- for (int lay=0; lay<MAX_MTFACE; lay++) {
- layers[lay].face = 0;
- layers[lay].name = "";
- }
-
- int validLayers = 0;
- for (int i=0; i<dm->faceData.totlayer; i++)
- {
- if (dm->faceData.layers[i].type == CD_MTFACE)
- {
- if (validLayers >= MAX_MTFACE) {
- printf("%s: corrupted mesh %s - too many CD_MTFACE layers\n", __func__, mesh->id.name);
- break;
- }
-
- layers[validLayers].face = (MTFace*)(dm->faceData.layers[i].data);
- layers[validLayers].name = dm->faceData.layers[i].name;
- if (tface == layers[validLayers].face)
- tfaceName = layers[validLayers].name;
- validLayers++;
- }
- }
-
- meshobj->SetName(mesh->id.name + 2);
- meshobj->m_sharedvertex_map.resize(totvert);
-
- Material* ma = 0;
- MT_Point2 uvs[4][RAS_TexVert::MAX_UNIT];
- unsigned int rgb[4] = {0};
-
- MT_Point3 pt[4];
- MT_Vector3 no[4];
- MT_Vector4 tan[4];
-
- /* ugh, if there is a less annoying way to do this please use that.
- * since these are converted from floats to floats, theres no real
- * advantage to use MT_ types - campbell */
- for (unsigned int i = 0; i < 4; i++) {
- const float zero_vec[4] = {0.0f};
- pt[i].setValue(zero_vec);
- no[i].setValue(zero_vec);
- tan[i].setValue(zero_vec);
- }
-
- /* we need to manually initialize the uvs (MoTo doesn't do that) [#34550] */
- for (unsigned int i = 0; i < RAS_TexVert::MAX_UNIT; i++) {
- uvs[0][i] = uvs[1][i] = uvs[2][i] = uvs[3][i] = MT_Point2(0.f, 0.f);
- }
-
- for (int f=0;f<totface;f++,mface++)
- {
- /* get coordinates, normals and tangents */
- pt[0].setValue(mvert[mface->v1].co);
- pt[1].setValue(mvert[mface->v2].co);
- pt[2].setValue(mvert[mface->v3].co);
- if (mface->v4) pt[3].setValue(mvert[mface->v4].co);
-
- if (mface->flag & ME_SMOOTH) {
- float n0[3], n1[3], n2[3], n3[3];
-
- normal_short_to_float_v3(n0, mvert[mface->v1].no);
- normal_short_to_float_v3(n1, mvert[mface->v2].no);
- normal_short_to_float_v3(n2, mvert[mface->v3].no);
- no[0] = n0;
- no[1] = n1;
- no[2] = n2;
-
- if (mface->v4) {
- normal_short_to_float_v3(n3, mvert[mface->v4].no);
- no[3] = n3;
- }
- }
- else {
- float fno[3];
-
- if (mface->v4)
- normal_quad_v3(fno,mvert[mface->v1].co, mvert[mface->v2].co, mvert[mface->v3].co, mvert[mface->v4].co);
- else
- normal_tri_v3(fno,mvert[mface->v1].co, mvert[mface->v2].co, mvert[mface->v3].co);
-
- no[0] = no[1] = no[2] = no[3] = MT_Vector3(fno);
- }
-
- if (tangent) {
- tan[0] = tangent[f*4 + 0];
- tan[1] = tangent[f*4 + 1];
- tan[2] = tangent[f*4 + 2];
-
- if (mface->v4)
- tan[3] = tangent[f*4 + 3];
- }
- if (blenderobj)
- ma = give_current_material(blenderobj, mface->mat_nr+1);
- else
- ma = mesh->mat ? mesh->mat[mface->mat_nr]:NULL;
-
- // Check for blender material
- if (ma == NULL) {
- ma= &defmaterial;
- }
-
- {
-
- RAS_MaterialBucket* bucket = material_from_mesh(ma, mface, tface, mcol, layers, lightlayer, rgb, uvs, tfaceName, scene, converter);
-
- // set render flags
- bool visible = ((ma->game.flag & GEMAT_INVISIBLE)==0);
- bool twoside = ((ma->game.flag & GEMAT_BACKCULL)==0);
- bool collider = ((ma->game.flag & GEMAT_NOPHYSICS)==0);
-
- /* mark face as flat, so vertices are split */
- bool flat = (mface->flag & ME_SMOOTH) == 0;
-
- int nverts = (mface->v4)? 4: 3;
-
- RAS_Polygon *poly = meshobj->AddPolygon(bucket, nverts);
-
- poly->SetVisible(visible);
- poly->SetCollider(collider);
- poly->SetTwoside(twoside);
- //poly->SetEdgeCode(mface->edcode);
-
- meshobj->AddVertex(poly,0,pt[0],uvs[0],tan[0],rgb[0],no[0],flat,mface->v1);
- meshobj->AddVertex(poly,1,pt[1],uvs[1],tan[1],rgb[1],no[1],flat,mface->v2);
- meshobj->AddVertex(poly,2,pt[2],uvs[2],tan[2],rgb[2],no[2],flat,mface->v3);
-
- if (nverts==4)
- meshobj->AddVertex(poly,3,pt[3],uvs[3],tan[3],rgb[3],no[3],flat,mface->v4);
- }
-
- if (tface)
- tface++;
- if (mcol)
- mcol+=4;
-
- for (int lay=0; lay<MAX_MTFACE; lay++)
- {
- MTF_localLayer &layer = layers[lay];
- if (layer.face == 0) break;
-
- layer.face++;
- }
- }
- // keep meshobj->m_sharedvertex_map for reinstance phys mesh.
- // 2.49a and before it did: meshobj->m_sharedvertex_map.clear();
- // but this didnt save much ram. - Campbell
- meshobj->EndConversion();
-
- // pre calculate texture generation
- // However, we want to delay this if we're libloading so we can make sure we have the right scene.
- if (!libloading) {
- for (list<RAS_MeshMaterial>::iterator mit = meshobj->GetFirstMaterial();
- mit != meshobj->GetLastMaterial(); ++ mit) {
- mit->m_bucket->GetPolyMaterial()->OnConstruction();
- }
- }
-
- if (layers)
- delete []layers;
-
- dm->release(dm);
-
- converter->RegisterGameMesh(meshobj, mesh);
- return meshobj;
-}
-
-
-
-static PHY_MaterialProps *CreateMaterialFromBlenderObject(struct Object* blenderobject)
-{
- PHY_MaterialProps *materialProps = new PHY_MaterialProps;
-
- MT_assert(materialProps && "Create physics material properties failed");
-
- Material* blendermat = give_current_material(blenderobject, 1);
-
- if (blendermat)
- {
- MT_assert(0.0f <= blendermat->reflect && blendermat->reflect <= 1.0f);
-
- materialProps->m_restitution = blendermat->reflect;
- materialProps->m_friction = blendermat->friction;
- materialProps->m_fh_spring = blendermat->fh;
- materialProps->m_fh_damping = blendermat->xyfrict;
- materialProps->m_fh_distance = blendermat->fhdist;
- materialProps->m_fh_normal = (blendermat->dynamode & MA_FH_NOR) != 0;
- }
- else {
- //give some defaults
- materialProps->m_restitution = 0.f;
- materialProps->m_friction = 0.5;
- materialProps->m_fh_spring = 0.f;
- materialProps->m_fh_damping = 0.f;
- materialProps->m_fh_distance = 0.f;
- materialProps->m_fh_normal = false;
-
- }
-
- return materialProps;
-}
-
-static PHY_ShapeProps *CreateShapePropsFromBlenderObject(struct Object* blenderobject)
-{
- PHY_ShapeProps *shapeProps = new PHY_ShapeProps;
-
- MT_assert(shapeProps);
-
- shapeProps->m_mass = blenderobject->mass;
-
-// This needs to be fixed in blender. For now, we use:
-
-// in Blender, inertia stands for the size value which is equivalent to
-// the sphere radius
- shapeProps->m_inertia = blenderobject->formfactor;
-
- MT_assert(0.0f <= blenderobject->damping && blenderobject->damping <= 1.0f);
- MT_assert(0.0f <= blenderobject->rdamping && blenderobject->rdamping <= 1.0f);
-
- shapeProps->m_lin_drag = 1.0f - blenderobject->damping;
- shapeProps->m_ang_drag = 1.0f - blenderobject->rdamping;
-
- shapeProps->m_friction_scaling[0] = blenderobject->anisotropicFriction[0];
- shapeProps->m_friction_scaling[1] = blenderobject->anisotropicFriction[1];
- shapeProps->m_friction_scaling[2] = blenderobject->anisotropicFriction[2];
- shapeProps->m_do_anisotropic = ((blenderobject->gameflag & OB_ANISOTROPIC_FRICTION) != 0);
-
- shapeProps->m_do_fh = (blenderobject->gameflag & OB_DO_FH) != 0;
- shapeProps->m_do_rot_fh = (blenderobject->gameflag & OB_ROT_FH) != 0;
-
-// velocity clamping XXX
- shapeProps->m_clamp_vel_min = blenderobject->min_vel;
- shapeProps->m_clamp_vel_max = blenderobject->max_vel;
- shapeProps->m_clamp_angvel_min = blenderobject->min_angvel;
- shapeProps->m_clamp_angvel_max = blenderobject->max_angvel;
-
-// Character physics properties
- shapeProps->m_step_height = blenderobject->step_height;
- shapeProps->m_jump_speed = blenderobject->jump_speed;
- shapeProps->m_fall_speed = blenderobject->fall_speed;
- shapeProps->m_max_jumps = blenderobject->max_jumps;
-
- return shapeProps;
-}
-
-
-
-
-
-//////////////////////////////////////////////////////////
-
-
-
-static float my_boundbox_mesh(Mesh *me, float *loc, float *size)
-{
- MVert *mvert;
- BoundBox *bb;
- float min[3], max[3];
- float mloc[3], msize[3];
- float radius_sq=0.0f, vert_radius_sq, *co;
- int a;
-
- if (me->bb==0) {
- me->bb = BKE_boundbox_alloc_unit();
- }
- bb= me->bb;
-
- INIT_MINMAX(min, max);
-
- if (!loc) loc= mloc;
- if (!size) size= msize;
-
- mvert= me->mvert;
- for (a = 0; a<me->totvert; a++, mvert++) {
- co = mvert->co;
-
- /* bounds */
- minmax_v3v3_v3(min, max, co);
-
- /* radius */
-
- vert_radius_sq = len_squared_v3(co);
- if (vert_radius_sq > radius_sq)
- radius_sq = vert_radius_sq;
- }
-
- if (me->totvert) {
- loc[0] = (min[0] + max[0]) / 2.0f;
- loc[1] = (min[1] + max[1]) / 2.0f;
- loc[2] = (min[2] + max[2]) / 2.0f;
-
- size[0] = (max[0] - min[0]) / 2.0f;
- size[1] = (max[1] - min[1]) / 2.0f;
- size[2] = (max[2] - min[2]) / 2.0f;
- }
- else {
- loc[0] = loc[1] = loc[2] = 0.0f;
- size[0] = size[1] = size[2] = 0.0f;
- }
-
- bb->vec[0][0] = bb->vec[1][0] = bb->vec[2][0] = bb->vec[3][0] = loc[0]-size[0];
- bb->vec[4][0] = bb->vec[5][0] = bb->vec[6][0] = bb->vec[7][0] = loc[0]+size[0];
-
- bb->vec[0][1] = bb->vec[1][1] = bb->vec[4][1] = bb->vec[5][1] = loc[1]-size[1];
- bb->vec[2][1] = bb->vec[3][1] = bb->vec[6][1] = bb->vec[7][1] = loc[1]+size[1];
-
- bb->vec[0][2] = bb->vec[3][2] = bb->vec[4][2] = bb->vec[7][2] = loc[2]-size[2];
- bb->vec[1][2] = bb->vec[2][2] = bb->vec[5][2] = bb->vec[6][2] = loc[2]+size[2];
-
- return sqrtf_signed(radius_sq);
-}
-
-//////////////////////////////////////////////////////
-
-
-static void BL_CreateGraphicObjectNew(KX_GameObject* gameobj,
- const MT_Point3& localAabbMin,
- const MT_Point3& localAabbMax,
- KX_Scene* kxscene,
- bool isActive,
- e_PhysicsEngine physics_engine)
-{
- if (gameobj->GetMeshCount() > 0)
- {
- switch (physics_engine)
- {
-#ifdef WITH_BULLET
- case UseBullet:
- {
- CcdPhysicsEnvironment* env = (CcdPhysicsEnvironment*)kxscene->GetPhysicsEnvironment();
- assert(env);
- PHY_IMotionState* motionstate = new KX_MotionState(gameobj->GetSGNode());
- CcdGraphicController* ctrl = new CcdGraphicController(env, motionstate);
- gameobj->SetGraphicController(ctrl);
- ctrl->SetNewClientInfo(gameobj->getClientInfo());
- ctrl->SetLocalAabb(localAabbMin, localAabbMax);
- if (isActive) {
- // add first, this will create the proxy handle, only if the object is visible
- if (gameobj->GetVisible())
- env->AddCcdGraphicController(ctrl);
- // update the mesh if there is a deformer, this will also update the bounding box for modifiers
- RAS_Deformer* deformer = gameobj->GetDeformer();
- if (deformer)
- deformer->UpdateBuckets();
- }
- }
- break;
-#endif
- default:
- break;
- }
- }
-}
-
-static void BL_CreatePhysicsObjectNew(KX_GameObject* gameobj,
- struct Object* blenderobject,
- RAS_MeshObject* meshobj,
- KX_Scene* kxscene,
- int activeLayerBitInfo,
- KX_BlenderSceneConverter *converter,
- bool processCompoundChildren
- )
-
-{
- //SYS_SystemHandle syshandle = SYS_GetSystem(); /*unused*/
- //int userigidbody = SYS_GetCommandLineInt(syshandle,"norigidbody",0);
- //bool bRigidBody = (userigidbody == 0);
-
- // object has physics representation?
- if (!(blenderobject->gameflag & OB_COLLISION)) {
- // Respond to all collisions so that Near sensors work on No Collision
- // objects.
- gameobj->SetUserCollisionGroup(0xffff);
- gameobj->SetUserCollisionMask(0xffff);
- return;
- }
-
- gameobj->SetUserCollisionGroup(blenderobject->col_group);
- gameobj->SetUserCollisionMask(blenderobject->col_mask);
-
- // get Root Parent of blenderobject
- struct Object* parent= blenderobject->parent;
- while (parent && parent->parent) {
- parent= parent->parent;
- }
-
- bool isCompoundChild = false;
- bool hasCompoundChildren = !parent && (blenderobject->gameflag & OB_CHILD) && !(blenderobject->gameflag & OB_SOFT_BODY);
-
- /* When the parent is not OB_DYNAMIC and has no OB_COLLISION then it gets no bullet controller
- * and cant be apart of the parents compound shape, same goes for OB_SOFT_BODY */
- if (parent && (parent->gameflag & (OB_DYNAMIC | OB_COLLISION))) {
- if ((parent->gameflag & OB_CHILD)!=0 && (blenderobject->gameflag & OB_CHILD) && !(parent->gameflag & OB_SOFT_BODY)) {
- isCompoundChild = true;
- }
- }
- if (processCompoundChildren != isCompoundChild)
- return;
-
-
- PHY_ShapeProps* shapeprops =
- CreateShapePropsFromBlenderObject(blenderobject);
-
-
- PHY_MaterialProps* smmaterial =
- CreateMaterialFromBlenderObject(blenderobject);
-
- DerivedMesh* dm = NULL;
- if (gameobj->GetDeformer())
- dm = gameobj->GetDeformer()->GetPhysicsMesh();
-
- class PHY_IMotionState* motionstate = new KX_MotionState(gameobj->GetSGNode());
-
- kxscene->GetPhysicsEnvironment()->ConvertObject(gameobj, meshobj, dm, kxscene, shapeprops, smmaterial, motionstate, activeLayerBitInfo, isCompoundChild, hasCompoundChildren);
-
- bool isActor = (blenderobject->gameflag & OB_ACTOR)!=0;
- bool isSensor = (blenderobject->gameflag & OB_SENSOR) != 0;
- gameobj->getClientInfo()->m_type =
- (isSensor) ? ((isActor) ? KX_ClientObjectInfo::OBACTORSENSOR : KX_ClientObjectInfo::OBSENSOR) :
- (isActor) ? KX_ClientObjectInfo::ACTOR : KX_ClientObjectInfo::STATIC;
-
- // should we record animation for this object?
- if ((blenderobject->gameflag & OB_RECORD_ANIMATION) != 0)
- gameobj->SetRecordAnimation(true);
-
- delete shapeprops;
- delete smmaterial;
- if (dm) {
- dm->needsFree = 1;
- dm->release(dm);
- }
-}
-
-
-
-
-
-static KX_LightObject *gamelight_from_blamp(Object *ob, Lamp *la, unsigned int layerflag, KX_Scene *kxscene, RAS_IRasterizer *rasterizer, KX_BlenderSceneConverter *converter)
-{
- RAS_ILightObject *lightobj = rasterizer->CreateLight();
- KX_LightObject *gamelight;
-
- lightobj->m_att1 = la->att1;
- lightobj->m_att2 = (la->mode & LA_QUAD) ? la->att2 : 0.0f;
- lightobj->m_coeff_const = la->coeff_const;
- lightobj->m_coeff_lin = la->coeff_lin;
- lightobj->m_coeff_quad = la->coeff_quad;
- lightobj->m_color[0] = la->r;
- lightobj->m_color[1] = la->g;
- lightobj->m_color[2] = la->b;
- lightobj->m_distance = la->dist;
- lightobj->m_energy = la->energy;
- lightobj->m_shadowclipstart = la->clipsta;
- lightobj->m_shadowclipend = la->clipend;
- lightobj->m_shadowbias = la->bias;
- lightobj->m_shadowbleedbias = la->bleedbias;
- lightobj->m_shadowmaptype = la->shadowmap_type;
- lightobj->m_shadowfrustumsize = la->shadow_frustum_size;
- lightobj->m_shadowcolor[0] = la->shdwr;
- lightobj->m_shadowcolor[1] = la->shdwg;
- lightobj->m_shadowcolor[2] = la->shdwb;
- lightobj->m_layer = layerflag;
- lightobj->m_spotblend = la->spotblend;
- lightobj->m_spotsize = la->spotsize;
-
- lightobj->m_nodiffuse = (la->mode & LA_NO_DIFF) != 0;
- lightobj->m_nospecular = (la->mode & LA_NO_SPEC) != 0;
-
- bool glslmat = converter->GetGLSLMaterials();
-
- // in GLSL NEGATIVE LAMP is handled inside the lamp update function
- if (glslmat==0) {
- if (la->mode & LA_NEG)
- {
- lightobj->m_color[0] = -lightobj->m_color[0];
- lightobj->m_color[1] = -lightobj->m_color[1];
- lightobj->m_color[2] = -lightobj->m_color[2];
- }
- }
-
- if (la->type==LA_SUN) {
- lightobj->m_type = RAS_ILightObject::LIGHT_SUN;
- } else if (la->type==LA_SPOT) {
- lightobj->m_type = RAS_ILightObject::LIGHT_SPOT;
- } else {
- lightobj->m_type = RAS_ILightObject::LIGHT_NORMAL;
- }
-
- gamelight = new KX_LightObject(kxscene, KX_Scene::m_callbacks, rasterizer,
- lightobj, glslmat);
-
- return gamelight;
-}
-
-static KX_Camera *gamecamera_from_bcamera(Object *ob, KX_Scene *kxscene, KX_BlenderSceneConverter *converter)
-{
- Camera* ca = static_cast<Camera*>(ob->data);
- RAS_CameraData camdata(ca->lens, ca->ortho_scale, ca->sensor_x, ca->sensor_y, ca->sensor_fit, ca->shiftx, ca->shifty, ca->clipsta, ca->clipend, ca->type == CAM_PERSP, ca->YF_dofdist);
- KX_Camera *gamecamera;
-
- gamecamera= new KX_Camera(kxscene, KX_Scene::m_callbacks, camdata);
- gamecamera->SetName(ca->id.name + 2);
-
- return gamecamera;
-}
-
-static KX_GameObject *gameobject_from_blenderobject(
- Object *ob,
- KX_Scene *kxscene,
- RAS_IRasterizer *rendertools,
- KX_BlenderSceneConverter *converter,
- bool libloading)
-{
- KX_GameObject *gameobj = NULL;
- Scene *blenderscene = kxscene->GetBlenderScene();
-
- switch (ob->type) {
- case OB_LAMP:
- {
- KX_LightObject* gamelight = gamelight_from_blamp(ob, static_cast<Lamp*>(ob->data), ob->lay, kxscene, rendertools, converter);
- gameobj = gamelight;
-
- if (blenderscene->lay & ob->lay)
- {
- gamelight->AddRef();
- kxscene->GetLightList()->Add(gamelight);
- }
-
- break;
- }
-
- case OB_CAMERA:
- {
- KX_Camera* gamecamera = gamecamera_from_bcamera(ob, kxscene, converter);
- gameobj = gamecamera;
-
- //don't add a reference: the camera list in kxscene->m_cameras is not released at the end
- //gamecamera->AddRef();
- kxscene->AddCamera(gamecamera);
-
- break;
- }
-
- case OB_MESH:
- {
- Mesh* mesh = static_cast<Mesh*>(ob->data);
- float center[3], extents[3];
- float radius = my_boundbox_mesh((Mesh*) ob->data, center, extents);
- RAS_MeshObject* meshobj = BL_ConvertMesh(mesh,ob,kxscene,converter, libloading);
-
- // needed for python scripting
- kxscene->GetLogicManager()->RegisterMeshName(meshobj->GetName(),meshobj);
-
- if (ob->gameflag & OB_NAVMESH)
- {
- gameobj = new KX_NavMeshObject(kxscene,KX_Scene::m_callbacks);
- gameobj->AddMesh(meshobj);
- break;
- }
-
- gameobj = new BL_DeformableGameObject(ob,kxscene,KX_Scene::m_callbacks);
-
- // set transformation
- gameobj->AddMesh(meshobj);
-
- // gather levels of detail
- if (BLI_listbase_count_at_most(&ob->lodlevels, 2) > 1) {
- LodLevel *lod = ((LodLevel*)ob->lodlevels.first)->next;
- Mesh* lodmesh = mesh;
- Object* lodmatob = ob;
- gameobj->AddLodMesh(meshobj);
- for (; lod; lod = lod->next) {
- if (!lod->source || lod->source->type != OB_MESH) continue;
- if (lod->flags & OB_LOD_USE_MESH) {
- lodmesh = static_cast<Mesh*>(lod->source->data);
- }
- if (lod->flags & OB_LOD_USE_MAT) {
- lodmatob = lod->source;
- }
- gameobj->AddLodMesh(BL_ConvertMesh(lodmesh, lodmatob, kxscene, converter, libloading));
- }
- if (blenderscene->gm.lodflag & SCE_LOD_USE_HYST) {
- kxscene->SetLodHysteresis(true);
- kxscene->SetLodHysteresisValue(blenderscene->gm.scehysteresis);
- }
- }
-
- // for all objects: check whether they want to
- // respond to updates
- bool ignoreActivityCulling =
- ((ob->gameflag2 & OB_NEVER_DO_ACTIVITY_CULLING)!=0);
- gameobj->SetIgnoreActivityCulling(ignoreActivityCulling);
- gameobj->SetOccluder((ob->gameflag & OB_OCCLUDER) != 0, false);
-
- // we only want obcolor used if there is a material in the mesh
- // that requires it
- Material *mat= NULL;
- bool bUseObjectColor=false;
-
- for (int i=0;i<mesh->totcol;i++) {
- mat=mesh->mat[i];
- if (!mat) break;
- if ((mat->shade_flag & MA_OBCOLOR)) {
- bUseObjectColor = true;
- break;
- }
- }
- if (bUseObjectColor)
- gameobj->SetObjectColor(ob->col);
-
- // two options exists for deform: shape keys and armature
- // only support relative shape key
- bool bHasShapeKey = mesh->key != NULL && mesh->key->type==KEY_RELATIVE;
- bool bHasDvert = mesh->dvert != NULL && ob->defbase.first;
- bool bHasArmature = (BL_ModifierDeformer::HasArmatureDeformer(ob) && ob->parent && ob->parent->type == OB_ARMATURE && bHasDvert);
- bool bHasModifier = BL_ModifierDeformer::HasCompatibleDeformer(ob);
-#ifdef WITH_BULLET
- bool bHasSoftBody = (!ob->parent && (ob->gameflag & OB_SOFT_BODY));
-#endif
- if (bHasModifier) {
- BL_ModifierDeformer *dcont = new BL_ModifierDeformer((BL_DeformableGameObject *)gameobj,
- kxscene->GetBlenderScene(), ob, meshobj);
- ((BL_DeformableGameObject*)gameobj)->SetDeformer(dcont);
- } else if (bHasShapeKey) {
- // not that we can have shape keys without dvert!
- BL_ShapeDeformer *dcont = new BL_ShapeDeformer((BL_DeformableGameObject*)gameobj,
- ob, meshobj);
- ((BL_DeformableGameObject*)gameobj)->SetDeformer(dcont);
- } else if (bHasArmature) {
- BL_SkinDeformer *dcont = new BL_SkinDeformer((BL_DeformableGameObject*)gameobj,
- ob, meshobj);
- ((BL_DeformableGameObject*)gameobj)->SetDeformer(dcont);
- } else if (bHasDvert) {
- // this case correspond to a mesh that can potentially deform but not with the
- // object to which it is attached for the moment. A skin mesh was created in
- // BL_ConvertMesh() so must create a deformer too!
- BL_MeshDeformer *dcont = new BL_MeshDeformer((BL_DeformableGameObject*)gameobj,
- ob, meshobj);
- ((BL_DeformableGameObject*)gameobj)->SetDeformer(dcont);
-#ifdef WITH_BULLET
- } else if (bHasSoftBody) {
- KX_SoftBodyDeformer *dcont = new KX_SoftBodyDeformer(meshobj, (BL_DeformableGameObject*)gameobj);
- ((BL_DeformableGameObject*)gameobj)->SetDeformer(dcont);
-#endif
- }
-
- MT_Point3 min = MT_Point3(center) - MT_Vector3(extents);
- MT_Point3 max = MT_Point3(center) + MT_Vector3(extents);
- SG_BBox bbox = SG_BBox(min, max);
- gameobj->GetSGNode()->SetBBox(bbox);
- gameobj->GetSGNode()->SetRadius(radius);
-
- break;
- }
-
- case OB_ARMATURE:
- {
- bArmature *arm = (bArmature*)ob->data;
- gameobj = new BL_ArmatureObject(
- kxscene,
- KX_Scene::m_callbacks,
- ob,
- kxscene->GetBlenderScene(), // handle
- arm->gevertdeformer
- );
- /* Get the current pose from the armature object and apply it as the rest pose */
- break;
- }
-
- case OB_EMPTY:
- {
- gameobj = new KX_EmptyObject(kxscene,KX_Scene::m_callbacks);
- // set transformation
- break;
- }
-
- case OB_FONT:
- {
- bool do_color_management = BKE_scene_check_color_management_enabled(blenderscene);
- /* font objects have no bounding box */
- gameobj = new KX_FontObject(kxscene,KX_Scene::m_callbacks, rendertools, ob, do_color_management);
-
- /* add to the list only the visible fonts */
- if ((ob->lay & kxscene->GetBlenderScene()->lay) != 0)
- kxscene->AddFont(static_cast<KX_FontObject*>(gameobj));
- break;
- }
-
-#ifdef THREADED_DAG_WORKAROUND
- case OB_CURVE:
- {
- if (ob->curve_cache == NULL) {
- BKE_displist_make_curveTypes(blenderscene, ob, false);
- }
- }
-#endif
-
- }
- if (gameobj)
- {
- gameobj->SetLayer(ob->lay);
- gameobj->SetBlenderObject(ob);
- /* set the visibility state based on the objects render option in the outliner */
- if (ob->restrictflag & OB_RESTRICT_RENDER) gameobj->SetVisible(0, 0);
- }
- return gameobj;
-}
-
-struct parentChildLink {
- struct Object* m_blenderchild;
- SG_Node* m_gamechildnode;
-};
-
-#if 0
-static bPoseChannel *get_active_posechannel2(Object *ob)
-{
- bArmature *arm= (bArmature*)ob->data;
- bPoseChannel *pchan;
-
- /* find active */
- for (pchan= (bPoseChannel *)ob->pose->chanbase.first; pchan; pchan= pchan->next) {
- if (pchan->bone && (pchan->bone == arm->act_bone) && (pchan->bone->layer & arm->layer))
- return pchan;
- }
-
- return NULL;
-}
-#endif
-
-static ListBase *get_active_constraints2(Object *ob)
-{
- if (!ob)
- return NULL;
-
- // XXX - shouldnt we care about the pose data and not the mode???
-#if 0
- if (ob->mode & OB_MODE_POSE) {
- bPoseChannel *pchan;
-
- pchan = get_active_posechannel2(ob);
- if (pchan)
- return &pchan->constraints;
- }
- else
-#endif
- {
- return &ob->constraints;
- }
-
- return NULL;
-}
-
-static void UNUSED_FUNCTION(print_active_constraints2)(Object *ob) //not used, use to debug
-{
- bConstraint* curcon;
- ListBase* conlist = get_active_constraints2(ob);
-
- if (conlist) {
- for (curcon = (bConstraint *)conlist->first; curcon; curcon = (bConstraint *)curcon->next) {
- printf("%i\n",curcon->type);
- }
- }
-}
-
-// Copy base layer to object layer like in BKE_scene_set_background
-static void blenderSceneSetBackground(Scene *blenderscene)
-{
- Scene *it;
- Base *base;
-
- for (SETLOOPER(blenderscene, it, base)) {
- base->object->lay = base->lay;
- BKE_scene_object_base_flag_sync_from_base(base);
- }
-}
-
-static KX_GameObject* getGameOb(STR_String busc,CListValue* sumolist)
-{
-
- for (int j=0;j<sumolist->GetCount();j++)
- {
- KX_GameObject* gameobje = (KX_GameObject*) sumolist->GetValue(j);
- if (gameobje->GetName()==busc)
- return gameobje;
- }
-
- return 0;
-
-}
-
-static bool bl_isConstraintInList(KX_GameObject *gameobj, set<KX_GameObject*> convertedlist)
-{
- set<KX_GameObject*>::iterator gobit;
- for (gobit = convertedlist.begin(); gobit != convertedlist.end(); gobit++) {
- if ((*gobit)->GetName() == gameobj->GetName())
- return true;
- }
- return false;
-}
-
-/* helper for BL_ConvertBlenderObjects, avoids code duplication
- * note: all var names match args are passed from the caller */
-static void bl_ConvertBlenderObject_Single(
- KX_BlenderSceneConverter *converter,
- Object *blenderobject,
- vector<parentChildLink> &vec_parent_child,
- CListValue* logicbrick_conversionlist,
- CListValue* objectlist, CListValue* inactivelist, CListValue* sumolist,
- KX_Scene* kxscene, KX_GameObject* gameobj,
- SCA_LogicManager* logicmgr, SCA_TimeEventManager* timemgr,
- bool isInActiveLayer
- )
-{
- MT_Point3 pos(
- blenderobject->loc[0]+blenderobject->dloc[0],
- blenderobject->loc[1]+blenderobject->dloc[1],
- blenderobject->loc[2]+blenderobject->dloc[2]
- );
-
- MT_Matrix3x3 rotation;
- float rotmat[3][3];
- BKE_object_rot_to_mat3(blenderobject, rotmat, false);
- rotation.setValue3x3((float*)rotmat);
-
- MT_Vector3 scale(blenderobject->size);
-
- gameobj->NodeSetLocalPosition(pos);
- gameobj->NodeSetLocalOrientation(rotation);
- gameobj->NodeSetLocalScale(scale);
- gameobj->NodeUpdateGS(0);
-
- sumolist->Add(gameobj->AddRef());
-
- BL_ConvertProperties(blenderobject,gameobj,timemgr,kxscene,isInActiveLayer);
-
- gameobj->SetName(blenderobject->id.name + 2);
-
- // update children/parent hierarchy
- if (blenderobject->parent != 0)
- {
- // blender has an additional 'parentinverse' offset in each object
- SG_Callbacks callback(NULL,NULL,NULL,KX_Scene::KX_ScenegraphUpdateFunc,KX_Scene::KX_ScenegraphRescheduleFunc);
- SG_Node* parentinversenode = new SG_Node(NULL,kxscene,callback);
-
- // define a normal parent relationship for this node.
- KX_NormalParentRelation * parent_relation = KX_NormalParentRelation::New();
- parentinversenode->SetParentRelation(parent_relation);
-
- parentChildLink pclink;
- pclink.m_blenderchild = blenderobject;
- pclink.m_gamechildnode = parentinversenode;
- vec_parent_child.push_back(pclink);
-
- float* fl = (float*) blenderobject->parentinv;
- MT_Transform parinvtrans(fl);
- parentinversenode->SetLocalPosition(parinvtrans.getOrigin());
- // problem here: the parent inverse transform combines scaling and rotation
- // in the basis but the scenegraph needs separate rotation and scaling.
- // This is not important for OpenGL (it uses 4x4 matrix) but it is important
- // for the physic engine that needs a separate scaling
- //parentinversenode->SetLocalOrientation(parinvtrans.getBasis());
-
- // Extract the rotation and the scaling from the basis
- MT_Matrix3x3 ori(parinvtrans.getBasis());
- MT_Vector3 x(ori.getColumn(0));
- MT_Vector3 y(ori.getColumn(1));
- MT_Vector3 z(ori.getColumn(2));
- MT_Vector3 parscale(x.length(), y.length(), z.length());
- if (!MT_fuzzyZero(parscale[0]))
- x /= parscale[0];
- if (!MT_fuzzyZero(parscale[1]))
- y /= parscale[1];
- if (!MT_fuzzyZero(parscale[2]))
- z /= parscale[2];
- ori.setColumn(0, x);
- ori.setColumn(1, y);
- ori.setColumn(2, z);
- parentinversenode->SetLocalOrientation(ori);
- parentinversenode->SetLocalScale(parscale);
-
- parentinversenode->AddChild(gameobj->GetSGNode());
- }
-
- // needed for python scripting
- logicmgr->RegisterGameObjectName(gameobj->GetName(),gameobj);
-
- // needed for group duplication
- logicmgr->RegisterGameObj(blenderobject, gameobj);
- for (int i = 0; i < gameobj->GetMeshCount(); i++)
- logicmgr->RegisterGameMeshName(gameobj->GetMesh(i)->GetName(), blenderobject);
-
- converter->RegisterGameObject(gameobj, blenderobject);
- // this was put in rapidly, needs to be looked at more closely
- // only draw/use objects in active 'blender' layers
-
- logicbrick_conversionlist->Add(gameobj->AddRef());
-
- if (isInActiveLayer)
- {
- objectlist->Add(gameobj->AddRef());
- //tf.Add(gameobj->GetSGNode());
-
- gameobj->NodeUpdateGS(0);
- gameobj->AddMeshUser();
- }
- else
- {
- //we must store this object otherwise it will be deleted
- //at the end of this function if it is not a root object
- inactivelist->Add(gameobj->AddRef());
- }
-}
-
-
-// convert blender objects into ketsji gameobjects
-void BL_ConvertBlenderObjects(struct Main* maggie,
- KX_Scene* kxscene,
- KX_KetsjiEngine* ketsjiEngine,
- e_PhysicsEngine physics_engine,
- RAS_IRasterizer* rendertools,
- RAS_ICanvas* canvas,
- KX_BlenderSceneConverter* converter,
- bool alwaysUseExpandFraming,
- bool libloading
- )
-{
-
-#define BL_CONVERTBLENDEROBJECT_SINGLE \
- bl_ConvertBlenderObject_Single(converter, \
- blenderobject, \
- vec_parent_child, \
- logicbrick_conversionlist, \
- objectlist, inactivelist, sumolist, \
- kxscene, gameobj, \
- logicmgr, timemgr, \
- isInActiveLayer \
- )
-
-
-
- Scene *blenderscene = kxscene->GetBlenderScene();
- // for SETLOOPER
- Scene *sce_iter;
- Base *base;
-
- // Get the frame settings of the canvas.
- // Get the aspect ratio of the canvas as designed by the user.
-
- RAS_FrameSettings::RAS_FrameType frame_type;
- int aspect_width;
- int aspect_height;
- set<Group*> grouplist; // list of groups to be converted
- set<Object*> allblobj; // all objects converted
- set<Object*> groupobj; // objects from groups (never in active layer)
-
- // This is bad, but we use this to make sure the first time this is called
- // is not in a separate thread.
- BL_Texture::GetMaxUnits();
-
- /* We have to ensure that group definitions are only converted once
- * push all converted group members to this set.
- * This will happen when a group instance is made from a linked group instance
- * and both are on the active layer. */
- set<KX_GameObject*> convertedlist;
-
- if (alwaysUseExpandFraming) {
- frame_type = RAS_FrameSettings::e_frame_extend;
- aspect_width = canvas->GetWidth();
- aspect_height = canvas->GetHeight();
- } else {
- if (blenderscene->gm.framing.type == SCE_GAMEFRAMING_BARS) {
- frame_type = RAS_FrameSettings::e_frame_bars;
- } else if (blenderscene->gm.framing.type == SCE_GAMEFRAMING_EXTEND) {
- frame_type = RAS_FrameSettings::e_frame_extend;
- } else {
- frame_type = RAS_FrameSettings::e_frame_scale;
- }
-
- aspect_width = (int)(blenderscene->r.xsch * blenderscene->r.xasp);
- aspect_height = (int)(blenderscene->r.ysch * blenderscene->r.yasp);
- }
-
- RAS_FrameSettings frame_settings(
- frame_type,
- blenderscene->gm.framing.col[0],
- blenderscene->gm.framing.col[1],
- blenderscene->gm.framing.col[2],
- aspect_width,
- aspect_height
- );
- kxscene->SetFramingType(frame_settings);
-
- kxscene->SetGravity(MT_Vector3(0,0, -blenderscene->gm.gravity));
-
- /* set activity culling parameters */
- kxscene->SetActivityCulling( (blenderscene->gm.mode & WO_ACTIVITY_CULLING) != 0);
- kxscene->SetActivityCullingRadius(blenderscene->gm.activityBoxRadius);
- kxscene->SetDbvtCulling((blenderscene->gm.mode & WO_DBVT_CULLING) != 0);
-
- // no occlusion culling by default
- kxscene->SetDbvtOcclusionRes(0);
-
- int activeLayerBitInfo = blenderscene->lay;
-
- // list of all object converted, active and inactive
- CListValue* sumolist = new CListValue();
-
- vector<parentChildLink> vec_parent_child;
-
- CListValue* objectlist = kxscene->GetObjectList();
- CListValue* inactivelist = kxscene->GetInactiveList();
- CListValue* parentlist = kxscene->GetRootParentList();
-
- SCA_LogicManager* logicmgr = kxscene->GetLogicManager();
- SCA_TimeEventManager* timemgr = kxscene->GetTimeEventManager();
-
- CListValue* logicbrick_conversionlist = new CListValue();
-
- //SG_TreeFactory tf;
-
- // Convert actions to actionmap
- bAction *curAct;
- for (curAct = (bAction*)maggie->action.first; curAct; curAct=(bAction*)curAct->id.next)
- {
- logicmgr->RegisterActionName(curAct->id.name + 2, curAct);
- }
-
- SetDefaultLightMode(blenderscene);
-
- blenderSceneSetBackground(blenderscene);
-
- // Let's support scene set.
- // Beware of name conflict in linked data, it will not crash but will create confusion
- // in Python scripting and in certain actuators (replace mesh). Linked scene *should* have
- // no conflicting name for Object, Object data and Action.
- for (SETLOOPER(blenderscene, sce_iter, base))
- {
- Object* blenderobject = base->object;
- allblobj.insert(blenderobject);
-
- KX_GameObject* gameobj = gameobject_from_blenderobject(
- base->object,
- kxscene,
- rendertools,
- converter,
- libloading);
-
- bool isInActiveLayer = (blenderobject->lay & activeLayerBitInfo) !=0;
- if (gameobj)
- {
- /* macro calls object conversion funcs */
- BL_CONVERTBLENDEROBJECT_SINGLE;
-
- if (gameobj->IsDupliGroup()) {
- grouplist.insert(blenderobject->dup_group);
- }
-
- /* Note about memory leak issues:
- * When a CValue derived class is created, m_refcount is initialized to 1
- * so the class must be released after being used to make sure that it won't
- * hang in memory. If the object needs to be stored for a long time,
- * use AddRef() so that this Release() does not free the object.
- * Make sure that for any AddRef() there is a Release()!!!!
- * Do the same for any object derived from CValue, CExpression and NG_NetworkMessage
- */
- gameobj->Release();
- }
- }
-
- if (!grouplist.empty())
- {
- // now convert the group referenced by dupli group object
- // keep track of all groups already converted
- set<Group*> allgrouplist = grouplist;
- set<Group*> tempglist;
- // recurse
- while (!grouplist.empty())
- {
- set<Group*>::iterator git;
- tempglist.clear();
- tempglist.swap(grouplist);
- for (git=tempglist.begin(); git!=tempglist.end(); git++)
- {
- Group* group = *git;
- FOREACH_GROUP_OBJECT_BEGIN(group, blenderobject)
- {
- if (converter->FindGameObject(blenderobject) == NULL)
- {
- allblobj.insert(blenderobject);
- groupobj.insert(blenderobject);
- KX_GameObject* gameobj = gameobject_from_blenderobject(
- blenderobject,
- kxscene,
- rendertools,
- converter,
- libloading);
-
- bool isInActiveLayer = false;
- if (gameobj) {
- /* Insert object to the constraint game object list
- * so we can check later if there is a instance in the scene or
- * an instance and its actual group definition. */
- convertedlist.insert((KX_GameObject*)gameobj->AddRef());
-
- /* macro calls object conversion funcs */
- BL_CONVERTBLENDEROBJECT_SINGLE;
-
- if (gameobj->IsDupliGroup())
- {
- if (allgrouplist.insert(blenderobject->dup_group).second)
- {
- grouplist.insert(blenderobject->dup_group);
- }
- }
-
- /* see comment above re: mem leaks */
- gameobj->Release();
- }
- }
- }
- FOREACH_GROUP_OBJECT_END;
- }
- }
- }
-
- // non-camera objects not supported as camera currently
- if (blenderscene->camera && blenderscene->camera->type == OB_CAMERA) {
- KX_Camera *gamecamera= (KX_Camera*) converter->FindGameObject(blenderscene->camera);
-
- if (gamecamera)
- kxscene->SetActiveCamera(gamecamera);
- }
-
- // Set up armatures
- set<Object*>::iterator oit;
- for (oit=allblobj.begin(); oit!=allblobj.end(); oit++)
- {
- Object* blenderobj = *oit;
- if (blenderobj->type==OB_MESH) {
- Mesh *me = (Mesh*)blenderobj->data;
-
- if (me->dvert) {
- BL_DeformableGameObject *obj = (BL_DeformableGameObject*)converter->FindGameObject(blenderobj);
-
- if (obj && BL_ModifierDeformer::HasArmatureDeformer(blenderobj) && blenderobj->parent && blenderobj->parent->type==OB_ARMATURE) {
- KX_GameObject *par = converter->FindGameObject(blenderobj->parent);
- if (par && obj->GetDeformer())
- ((BL_SkinDeformer*)obj->GetDeformer())->SetArmature((BL_ArmatureObject*) par);
- }
- }
- }
- }
-
- // create hierarchy information
- int i;
- vector<parentChildLink>::iterator pcit;
-
- for (pcit = vec_parent_child.begin();!(pcit==vec_parent_child.end());++pcit)
- {
-
- struct Object* blenderchild = pcit->m_blenderchild;
- struct Object* blenderparent = blenderchild->parent;
- KX_GameObject* parentobj = converter->FindGameObject(blenderparent);
- KX_GameObject* childobj = converter->FindGameObject(blenderchild);
-
- assert(childobj);
-
- if (!parentobj || objectlist->SearchValue(childobj) != objectlist->SearchValue(parentobj))
- {
- // special case: the parent and child object are not in the same layer.
- // This weird situation is used in Apricot for test purposes.
- // Resolve it by not converting the child
- childobj->GetSGNode()->DisconnectFromParent();
- delete pcit->m_gamechildnode;
- // Now destroy the child object but also all its descendent that may already be linked
- // Remove the child reference in the local list!
- // Note: there may be descendents already if the children of the child were processed
- // by this loop before the child. In that case, we must remove the children also
- CListValue* childrenlist = childobj->GetChildrenRecursive();
- childrenlist->Add(childobj->AddRef());
- for ( i=0;i<childrenlist->GetCount();i++)
- {
- KX_GameObject* obj = static_cast<KX_GameObject*>(childrenlist->GetValue(i));
- if (sumolist->RemoveValue(obj))
- obj->Release();
- if (logicbrick_conversionlist->RemoveValue(obj))
- obj->Release();
- }
- childrenlist->Release();
-
- // now destroy recursively
- converter->UnregisterGameObject(childobj); // removing objects during conversion make sure this runs too
- kxscene->RemoveObject(childobj);
-
- continue;
- }
-
- switch (blenderchild->partype)
- {
- case PARVERT1:
- {
- // creat a new vertex parent relationship for this node.
- KX_VertexParentRelation * vertex_parent_relation = KX_VertexParentRelation::New();
- pcit->m_gamechildnode->SetParentRelation(vertex_parent_relation);
- break;
- }
- case PARSLOW:
- {
- // creat a new slow parent relationship for this node.
- KX_SlowParentRelation * slow_parent_relation = KX_SlowParentRelation::New(blenderchild->sf);
- pcit->m_gamechildnode->SetParentRelation(slow_parent_relation);
- break;
- }
- case PARBONE:
- {
- // parent this to a bone
- Bone *parent_bone = BKE_armature_find_bone_name(BKE_armature_from_object(blenderchild->parent),
- blenderchild->parsubstr);
-
- if (parent_bone) {
- KX_BoneParentRelation *bone_parent_relation = KX_BoneParentRelation::New(parent_bone);
- pcit->m_gamechildnode->SetParentRelation(bone_parent_relation);
- }
-
- break;
- }
- case PARSKEL: // skinned - ignore
- break;
- case PAROBJECT:
- case PARVERT3:
- default:
- // unhandled
- break;
- }
-
- parentobj-> GetSGNode()->AddChild(pcit->m_gamechildnode);
- }
- vec_parent_child.clear();
-
- // find 'root' parents (object that has not parents in SceneGraph)
- for (i=0;i<sumolist->GetCount();++i)
- {
- KX_GameObject* gameobj = (KX_GameObject*) sumolist->GetValue(i);
- if (gameobj->GetSGNode()->GetSGParent() == 0)
- {
- parentlist->Add(gameobj->AddRef());
- gameobj->NodeUpdateGS(0);
- }
- }
-
- // create graphic controller for culling
- if (kxscene->GetDbvtCulling())
- {
- bool occlusion = false;
- for (i=0; i<sumolist->GetCount();i++)
- {
- KX_GameObject* gameobj = (KX_GameObject*) sumolist->GetValue(i);
- if (gameobj->GetMeshCount() > 0)
- {
- MT_Point3 box[2];
- gameobj->GetSGNode()->BBox().getmm(box, MT_Transform::Identity());
- // box[0] is the min, box[1] is the max
- bool isactive = objectlist->SearchValue(gameobj);
- BL_CreateGraphicObjectNew(gameobj,box[0],box[1],kxscene,isactive,physics_engine);
- if (gameobj->GetOccluder())
- occlusion = true;
- }
- }
- if (occlusion)
- kxscene->SetDbvtOcclusionRes(blenderscene->gm.occlusionRes);
- }
- if (blenderscene->world)
- kxscene->GetPhysicsEnvironment()->SetNumTimeSubSteps(blenderscene->gm.physubstep);
-
- // now that the scenegraph is complete, let's instantiate the deformers.
- // We need that to create reusable derived mesh and physic shapes
- for (i=0;i<sumolist->GetCount();++i)
- {
- KX_GameObject* gameobj = (KX_GameObject*) sumolist->GetValue(i);
- if (gameobj->GetDeformer())
- gameobj->GetDeformer()->UpdateBuckets();
- }
-
- // Set up armature constraints and shapekey drivers
- for (i=0;i<sumolist->GetCount();++i)
- {
- KX_GameObject* gameobj = (KX_GameObject*) sumolist->GetValue(i);
- if (gameobj->GetGameObjectType() == SCA_IObject::OBJ_ARMATURE)
- {
- BL_ArmatureObject *armobj = (BL_ArmatureObject*)gameobj;
- armobj->LoadConstraints(converter);
-
- CListValue *children = armobj->GetChildren();
- for (int j=0; j<children->GetCount();++j)
- {
- BL_ShapeDeformer *deform = dynamic_cast<BL_ShapeDeformer*>(((KX_GameObject*)children->GetValue(j))->GetDeformer());
- if (deform)
- deform->LoadShapeDrivers(armobj);
- }
-
- children->Release();
- }
- }
-
- bool processCompoundChildren = false;
- // create physics information
- for (i=0;i<sumolist->GetCount();i++)
- {
- KX_GameObject* gameobj = (KX_GameObject*) sumolist->GetValue(i);
- struct Object* blenderobject = gameobj->GetBlenderObject();
- int nummeshes = gameobj->GetMeshCount();
- RAS_MeshObject* meshobj = 0;
- if (nummeshes > 0)
- {
- meshobj = gameobj->GetMesh(0);
- }
- int layerMask = (groupobj.find(blenderobject) == groupobj.end()) ? activeLayerBitInfo : 0;
- BL_CreatePhysicsObjectNew(gameobj,blenderobject,meshobj,kxscene,layerMask,converter,processCompoundChildren);
- }
-
- processCompoundChildren = true;
- // create physics information
- for (i=0;i<sumolist->GetCount();i++)
- {
- KX_GameObject* gameobj = (KX_GameObject*) sumolist->GetValue(i);
- struct Object* blenderobject = gameobj->GetBlenderObject();
- int nummeshes = gameobj->GetMeshCount();
- RAS_MeshObject* meshobj = 0;
- if (nummeshes > 0)
- {
- meshobj = gameobj->GetMesh(0);
- }
- int layerMask = (groupobj.find(blenderobject) == groupobj.end()) ? activeLayerBitInfo : 0;
- BL_CreatePhysicsObjectNew(gameobj,blenderobject,meshobj,kxscene,layerMask,converter,processCompoundChildren);
- }
-
- // create physics joints
- for (i=0;i<sumolist->GetCount();i++)
- {
- PHY_IPhysicsEnvironment *physEnv = kxscene->GetPhysicsEnvironment();
- KX_GameObject *gameobj = (KX_GameObject *)sumolist->GetValue(i);
- struct Object *blenderobject = gameobj->GetBlenderObject();
- ListBase *conlist = get_active_constraints2(blenderobject);
- bConstraint *curcon;
-
- if (!conlist)
- continue;
-
- for (curcon = (bConstraint *)conlist->first; curcon; curcon = (bConstraint *)curcon->next) {
- if (curcon->type != CONSTRAINT_TYPE_RIGIDBODYJOINT)
- continue;
-
- bRigidBodyJointConstraint *dat = (bRigidBodyJointConstraint *)curcon->data;
-
- /* Skip if no target or a child object is selected or constraints are deactivated */
- if (!dat->tar || dat->child || (curcon->flag & CONSTRAINT_OFF))
- continue;
-
- /* Store constraints of grouped and instanced objects for all layers */
- gameobj->AddConstraint(dat);
-
- /** if it's during libload we only add constraints in the object but
- * doesn't create it. Constraint will be replicated later in scene->MergeScene
- */
- if (libloading)
- continue;
-
- /* Skipped already converted constraints.
- * This will happen when a group instance is made from a linked group instance
- * and both are on the active layer. */
- if (bl_isConstraintInList(gameobj, convertedlist))
- continue;
-
- KX_GameObject *gotar = getGameOb(dat->tar->id.name + 2, sumolist);
-
- if (gotar && (gotar->GetLayer()&activeLayerBitInfo) && gotar->GetPhysicsController() &&
- (gameobj->GetLayer()&activeLayerBitInfo) && gameobj->GetPhysicsController())
- {
- physEnv->SetupObjectConstraints(gameobj, gotar, dat);
- }
- }
- }
-
- /* cleanup converted set of group objects */
- set<KX_GameObject*>::iterator gobit;
- for (gobit = convertedlist.begin(); gobit != convertedlist.end(); gobit++)
- (*gobit)->Release();
-
- convertedlist.clear();
- sumolist->Release();
-
- // convert world
- KX_WorldInfo* worldinfo = new KX_WorldInfo(blenderscene, blenderscene->world);
- converter->RegisterWorldInfo(worldinfo);
- kxscene->SetWorldInfo(worldinfo);
-
- //create object representations for obstacle simulation
- KX_ObstacleSimulation* obssimulation = kxscene->GetObstacleSimulation();
- if (obssimulation)
- {
- for ( i=0;i<objectlist->GetCount();i++)
- {
- KX_GameObject* gameobj = static_cast<KX_GameObject*>(objectlist->GetValue(i));
- struct Object* blenderobject = gameobj->GetBlenderObject();
- if (blenderobject->gameflag & OB_HASOBSTACLE)
- {
- obssimulation->AddObstacleForObj(gameobj);
- }
- }
- }
-
- //process navigation mesh objects
- for ( i=0; i<objectlist->GetCount();i++)
- {
- KX_GameObject* gameobj = static_cast<KX_GameObject*>(objectlist->GetValue(i));
- struct Object* blenderobject = gameobj->GetBlenderObject();
- if (blenderobject->type==OB_MESH && (blenderobject->gameflag & OB_NAVMESH))
- {
- KX_NavMeshObject* navmesh = static_cast<KX_NavMeshObject*>(gameobj);
- navmesh->SetVisible(0, true);
- navmesh->BuildNavMesh();
- if (obssimulation)
- obssimulation->AddObstaclesForNavMesh(navmesh);
- }
- }
- for ( i=0; i<inactivelist->GetCount();i++)
- {
- KX_GameObject* gameobj = static_cast<KX_GameObject*>(inactivelist->GetValue(i));
- struct Object* blenderobject = gameobj->GetBlenderObject();
- if (blenderobject->type==OB_MESH && (blenderobject->gameflag & OB_NAVMESH))
- {
- KX_NavMeshObject* navmesh = static_cast<KX_NavMeshObject*>(gameobj);
- navmesh->SetVisible(0, true);
- }
- }
-
- // convert logic bricks, sensors, controllers and actuators
- for (i=0;i<logicbrick_conversionlist->GetCount();i++)
- {
- KX_GameObject* gameobj = static_cast<KX_GameObject*>(logicbrick_conversionlist->GetValue(i));
- struct Object* blenderobj = gameobj->GetBlenderObject();
- int layerMask = (groupobj.find(blenderobj) == groupobj.end()) ? activeLayerBitInfo : 0;
- bool isInActiveLayer = (blenderobj->lay & layerMask)!=0;
- BL_ConvertActuators(maggie->name, blenderobj,gameobj,logicmgr,kxscene,ketsjiEngine,layerMask,isInActiveLayer,converter);
- }
- for ( i=0;i<logicbrick_conversionlist->GetCount();i++)
- {
- KX_GameObject* gameobj = static_cast<KX_GameObject*>(logicbrick_conversionlist->GetValue(i));
- struct Object* blenderobj = gameobj->GetBlenderObject();
- int layerMask = (groupobj.find(blenderobj) == groupobj.end()) ? activeLayerBitInfo : 0;
- bool isInActiveLayer = (blenderobj->lay & layerMask)!=0;
- BL_ConvertControllers(blenderobj,gameobj,logicmgr, layerMask,isInActiveLayer,converter, libloading);
- }
- for ( i=0;i<logicbrick_conversionlist->GetCount();i++)
- {
- KX_GameObject* gameobj = static_cast<KX_GameObject*>(logicbrick_conversionlist->GetValue(i));
- struct Object* blenderobj = gameobj->GetBlenderObject();
- int layerMask = (groupobj.find(blenderobj) == groupobj.end()) ? activeLayerBitInfo : 0;
- bool isInActiveLayer = (blenderobj->lay & layerMask)!=0;
- BL_ConvertSensors(blenderobj,gameobj,logicmgr,kxscene,ketsjiEngine,layerMask,isInActiveLayer,canvas,converter);
- // set the init state to all objects
- gameobj->SetInitState((blenderobj->init_state)?blenderobj->init_state:blenderobj->state);
- }
- // apply the initial state to controllers, only on the active objects as this registers the sensors
- for ( i=0;i<objectlist->GetCount();i++)
- {
- KX_GameObject* gameobj = static_cast<KX_GameObject*>(objectlist->GetValue(i));
- gameobj->ResetState();
- }
-
- logicbrick_conversionlist->Release();
-
- // Calculate the scene btree -
- // too slow - commented out.
- //kxscene->SetNodeTree(tf.MakeTree());
-
- // instantiate dupli group, we will loop trough the object
- // that are in active layers. Note that duplicating group
- // has the effect of adding objects at the end of objectlist.
- // Only loop through the first part of the list.
- int objcount = objectlist->GetCount();
- for (i=0;i<objcount;i++)
- {
- KX_GameObject* gameobj = (KX_GameObject*) objectlist->GetValue(i);
- if (gameobj->IsDupliGroup())
- {
- kxscene->DupliGroupRecurse(gameobj, 0);
- }
- }
-
- KX_Camera *activecam = kxscene->GetActiveCamera();
- MT_Scalar distance = (activecam)? activecam->GetCameraFar() - activecam->GetCameraNear(): 100.0f;
- RAS_BucketManager *bucketmanager = kxscene->GetBucketManager();
- bucketmanager->OptimizeBuckets(distance);
-}
-
diff --git a/source/gameengine/Converter/BL_BlenderDataConversion.h b/source/gameengine/Converter/BL_BlenderDataConversion.h
deleted file mode 100644
index 22210cc6035..00000000000
--- a/source/gameengine/Converter/BL_BlenderDataConversion.h
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file BL_BlenderDataConversion.h
- * \ingroup bgeconv
- */
-
-#ifndef __BL_BLENDERDATACONVERSION_H__
-#define __BL_BLENDERDATACONVERSION_H__
-
-#include "CTR_HashedPtr.h"
-#include "STR_String.h"
-#include "EXP_Python.h"
-#include "KX_PhysicsEngineEnums.h"
-#include "SCA_IInputDevice.h"
-
-class RAS_MeshObject* BL_ConvertMesh(struct Mesh* mesh,struct Object* lightobj,class KX_Scene* scene, class KX_BlenderSceneConverter *converter, bool libloading);
-
-void BL_ConvertBlenderObjects(struct Main* maggie,
- class KX_Scene* kxscene,
- class KX_KetsjiEngine* ketsjiEngine,
- e_PhysicsEngine physics_engine,
- class RAS_IRasterizer* rendertools,
- class RAS_ICanvas* canvas,
- class KX_BlenderSceneConverter* sceneconverter,
- bool alwaysUseExpandFraming,
- bool libloading=false
- );
-
-SCA_IInputDevice::KX_EnumInputs ConvertKeyCode(int key_code);
-
-#endif /* __BL_BLENDERDATACONVERSION_H__ */
diff --git a/source/gameengine/Converter/BL_DeformableGameObject.cpp b/source/gameengine/Converter/BL_DeformableGameObject.cpp
deleted file mode 100644
index 3a4a27a6722..00000000000
--- a/source/gameengine/Converter/BL_DeformableGameObject.cpp
+++ /dev/null
@@ -1,116 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Converter/BL_DeformableGameObject.cpp
- * \ingroup bgeconv
- */
-
-
-#include "BL_DeformableGameObject.h"
-#include "BL_ShapeDeformer.h"
-#include "BL_ShapeActionActuator.h"
-#include "RAS_MaterialBucket.h"
-
-
-BL_DeformableGameObject::~BL_DeformableGameObject()
-{
- if (m_pDeformer)
- delete m_pDeformer; // __NLA : Temporary until we decide where to put this
-}
-
-void BL_DeformableGameObject::ProcessReplica()
-{
- KX_GameObject::ProcessReplica();
-
- if (m_pDeformer)
- m_pDeformer= (BL_MeshDeformer*)m_pDeformer->GetReplica();
-}
-
-CValue* BL_DeformableGameObject::GetReplica()
-{
-
- BL_DeformableGameObject* replica = new BL_DeformableGameObject(*this);//m_float,GetName());
- replica->ProcessReplica();
- return replica;
-}
-
-bool BL_DeformableGameObject::SetActiveAction(BL_ShapeActionActuator *act, short priority, double curtime)
-{
- if (curtime != m_lastframe) {
- m_activePriority = 9999;
- m_lastframe= curtime;
- m_activeAct = NULL;
- }
-
- if (priority<=m_activePriority)
- {
- if (m_activeAct && (m_activeAct!=act))
- m_activeAct->SetBlendTime(0.0f); /* Reset the blend timer */
- m_activeAct = act;
- m_activePriority = priority;
- m_lastframe = curtime;
-
- return true;
- }
- else {
- act->SetBlendTime(0.0f);
- return false;
- }
-}
-
-bool BL_DeformableGameObject::GetShape(vector<float> &shape)
-{
- shape.clear();
- BL_ShapeDeformer* shape_deformer = dynamic_cast<BL_ShapeDeformer*>(m_pDeformer);
- if (shape_deformer)
- {
- // this check is normally superfluous: a shape deformer can only be created if the mesh
- // has relative keys
- Key* key = shape_deformer->GetKey();
- if (key && key->type==KEY_RELATIVE)
- {
- KeyBlock *kb;
- for (kb = (KeyBlock *)key->block.first; kb; kb = (KeyBlock *)kb->next)
- {
- shape.push_back(kb->curval);
- }
- }
- }
- return !shape.empty();
-}
-
-void BL_DeformableGameObject::SetDeformer(class RAS_Deformer* deformer)
-{
- m_pDeformer = deformer;
-
- SG_QList::iterator<RAS_MeshSlot> mit(m_meshSlots);
- for (mit.begin(); !mit.end(); ++mit)
- {
- (*mit)->SetDeformer(deformer);
- }
-}
-
diff --git a/source/gameengine/Converter/BL_DeformableGameObject.h b/source/gameengine/Converter/BL_DeformableGameObject.h
deleted file mode 100644
index 95e3b7c517d..00000000000
--- a/source/gameengine/Converter/BL_DeformableGameObject.h
+++ /dev/null
@@ -1,107 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file BL_DeformableGameObject.h
- * \ingroup bgeconv
- */
-
-#ifndef __BL_DEFORMABLEGAMEOBJECT_H__
-#define __BL_DEFORMABLEGAMEOBJECT_H__
-
-#ifdef _MSC_VER
-# pragma warning (disable:4786) // get rid of stupid stl-visual compiler debug warning
-#endif
-
-#include "DNA_mesh_types.h"
-#include "KX_GameObject.h"
-#include "BL_MeshDeformer.h"
-#include "KX_SoftBodyDeformer.h"
-#include <vector>
-
-class BL_ShapeActionActuator;
-struct Key;
-
-class BL_DeformableGameObject : public KX_GameObject
-{
-public:
- CValue* GetReplica();
-
- double GetLastFrame ()
- {
- return m_lastframe;
- }
- Object* GetBlendObject()
- {
- return m_blendobj;
- }
- virtual void Relink(CTR_Map<CTR_HashedPtr, void*>*map)
- {
- if (m_pDeformer)
- m_pDeformer->Relink (map);
- KX_GameObject::Relink(map);
- };
- void ProcessReplica();
-
- BL_DeformableGameObject(Object* blendobj, void* sgReplicationInfo, SG_Callbacks callbacks) :
- KX_GameObject(sgReplicationInfo,callbacks),
- m_pDeformer(NULL),
- m_activeAct(NULL),
- m_lastframe(0.0),
- m_blendobj(blendobj),
- m_activePriority(9999)
- {
- m_isDeformable = true;
- };
- virtual ~BL_DeformableGameObject();
- bool SetActiveAction(class BL_ShapeActionActuator *act, short priority, double curtime);
-
- bool GetShape(vector<float> &shape);
-
- virtual void SetDeformer(class RAS_Deformer* deformer);
- virtual class RAS_Deformer* GetDeformer()
- {
- return m_pDeformer;
- }
-
-public:
-
-protected:
-
- RAS_Deformer *m_pDeformer;
-
- class BL_ShapeActionActuator *m_activeAct;
- double m_lastframe;
- Object* m_blendobj;
- short m_activePriority;
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:BL_DeformableGameObject")
-#endif
-};
-
-#endif /* __BL_DEFORMABLEGAMEOBJECT_H__ */
diff --git a/source/gameengine/Converter/BL_MeshDeformer.cpp b/source/gameengine/Converter/BL_MeshDeformer.cpp
deleted file mode 100644
index 911ff245ab4..00000000000
--- a/source/gameengine/Converter/BL_MeshDeformer.cpp
+++ /dev/null
@@ -1,239 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- * Simple deformation controller that restores a mesh to its rest position
- */
-
-/** \file gameengine/Converter/BL_MeshDeformer.cpp
- * \ingroup bgeconv
- */
-
-#ifdef _MSC_VER
- /* This warning tells us about truncation of __long__ stl-generated names.
- * It can occasionally cause DevStudio to have internal compiler warnings. */
-# pragma warning( disable:4786 )
-#endif
-
-#include "RAS_IPolygonMaterial.h"
-#include "BL_DeformableGameObject.h"
-#include "BL_MeshDeformer.h"
-#include "RAS_MeshObject.h"
-#include "DNA_mesh_types.h"
-#include "DNA_meshdata_types.h"
-
-#include "CTR_Map.h"
-#include "STR_HashedString.h"
-#include "BLI_math.h"
-
-bool BL_MeshDeformer::Apply(RAS_IPolyMaterial*)
-{
- size_t i;
-
- // only apply once per frame if the mesh is actually modified
- if (m_pMeshObject->MeshModified() &&
- m_lastDeformUpdate != m_gameobj->GetLastFrame())
- {
- // For each material
- for (list<RAS_MeshMaterial>::iterator mit= m_pMeshObject->GetFirstMaterial();
- mit != m_pMeshObject->GetLastMaterial(); ++ mit) {
- if (!mit->m_slots[(void*)m_gameobj])
- continue;
-
- RAS_MeshSlot *slot = *mit->m_slots[(void*)m_gameobj];
- RAS_MeshSlot::iterator it;
-
- // for each array
- for (slot->begin(it); !slot->end(it); slot->next(it)) {
- // For each vertex
- for (i=it.startvertex; i<it.endvertex; i++) {
- RAS_TexVert& v = it.vertex[i];
- v.SetXYZ(m_bmesh->mvert[v.getOrigIndex()].co);
- }
- }
- }
-
- m_lastDeformUpdate = m_gameobj->GetLastFrame();
-
- return true;
- }
-
- return false;
-}
-
-BL_MeshDeformer::~BL_MeshDeformer()
-{
- if (m_transverts)
- delete [] m_transverts;
- if (m_transnors)
- delete [] m_transnors;
-}
-
-void BL_MeshDeformer::ProcessReplica()
-{
- m_transverts = NULL;
- m_transnors = NULL;
- m_tvtot = 0;
- m_bDynamic=false;
- m_lastDeformUpdate = -1;
-}
-
-void BL_MeshDeformer::Relink(CTR_Map<class CTR_HashedPtr, void*>*map)
-{
- void **h_obj = (*map)[m_gameobj];
-
- if (h_obj)
- m_gameobj = (BL_DeformableGameObject*)(*h_obj);
- else
- m_gameobj = NULL;
-}
-
-/**
- * \warning This function is expensive!
- */
-void BL_MeshDeformer::RecalcNormals()
-{
- /* We don't normalize for performance, not doing it for faces normals
- * gives area-weight normals which often look better anyway, and use
- * GL_NORMALIZE so we don't have to do per vertex normalization either
- * since the GPU can do it faster */
- list<RAS_MeshMaterial>::iterator mit;
- RAS_MeshSlot::iterator it;
- size_t i;
-
- /* set vertex normals to zero */
- memset(m_transnors, 0, sizeof(float)*3*m_bmesh->totvert);
-
- /* add face normals to vertices. */
- for (mit = m_pMeshObject->GetFirstMaterial();
- mit != m_pMeshObject->GetLastMaterial(); ++ mit) {
- if (!mit->m_slots[(void*)m_gameobj])
- continue;
-
- RAS_MeshSlot *slot = *mit->m_slots[(void*)m_gameobj];
-
- for (slot->begin(it); !slot->end(it); slot->next(it)) {
- int nvert = (int)it.array->m_type;
-
- for (i=0; i<it.totindex; i+=nvert) {
- RAS_TexVert& v1 = it.vertex[it.index[i]];
- RAS_TexVert& v2 = it.vertex[it.index[i+1]];
- RAS_TexVert& v3 = it.vertex[it.index[i+2]];
- RAS_TexVert *v4 = NULL;
-
- const float *co1 = m_transverts[v1.getOrigIndex()];
- const float *co2 = m_transverts[v2.getOrigIndex()];
- const float *co3 = m_transverts[v3.getOrigIndex()];
- const float *co4 = NULL;
-
- /* compute face normal */
- float fnor[3], n1[3], n2[3];
-
- if (nvert == 4) {
- v4 = &it.vertex[it.index[i+3]];
- co4 = m_transverts[v4->getOrigIndex()];
-
- n1[0] = co1[0] - co3[0];
- n1[1] = co1[1] - co3[1];
- n1[2] = co1[2] - co3[2];
-
- n2[0] = co2[0] - co4[0];
- n2[1] = co2[1] - co4[1];
- n2[2] = co2[2] - co4[2];
- }
- else {
- n1[0] = co1[0] - co2[0];
- n2[0] = co2[0] - co3[0];
- n1[1] = co1[1] - co2[1];
-
- n2[1] = co2[1] - co3[1];
- n1[2] = co1[2] - co2[2];
- n2[2] = co2[2] - co3[2];
- }
-
- fnor[0] = n1[1] * n2[2] - n1[2] * n2[1];
- fnor[1] = n1[2] * n2[0] - n1[0] * n2[2];
- fnor[2] = n1[0] * n2[1] - n1[1] * n2[0];
- normalize_v3(fnor);
-
- /* add to vertices for smooth normals */
- float *vn1 = m_transnors[v1.getOrigIndex()];
- float *vn2 = m_transnors[v2.getOrigIndex()];
- float *vn3 = m_transnors[v3.getOrigIndex()];
-
- vn1[0] += fnor[0]; vn1[1] += fnor[1]; vn1[2] += fnor[2];
- vn2[0] += fnor[0]; vn2[1] += fnor[1]; vn2[2] += fnor[2];
- vn3[0] += fnor[0]; vn3[1] += fnor[1]; vn3[2] += fnor[2];
-
- if (v4) {
- float *vn4 = m_transnors[v4->getOrigIndex()];
- vn4[0] += fnor[0]; vn4[1] += fnor[1]; vn4[2] += fnor[2];
- }
-
- /* in case of flat - just assign, the vertices are split */
- if (v1.getFlag() & RAS_TexVert::FLAT) {
- v1.SetNormal(fnor);
- v2.SetNormal(fnor);
- v3.SetNormal(fnor);
- if (v4)
- v4->SetNormal(fnor);
- }
- }
- }
- }
-
- /* assign smooth vertex normals */
- for (mit = m_pMeshObject->GetFirstMaterial();
- mit != m_pMeshObject->GetLastMaterial(); ++ mit) {
- if (!mit->m_slots[(void*)m_gameobj])
- continue;
-
- RAS_MeshSlot *slot = *mit->m_slots[(void*)m_gameobj];
-
- for (slot->begin(it); !slot->end(it); slot->next(it)) {
- for (i=it.startvertex; i<it.endvertex; i++) {
- RAS_TexVert& v = it.vertex[i];
-
- if (!(v.getFlag() & RAS_TexVert::FLAT))
- v.SetNormal(m_transnors[v.getOrigIndex()]); //.safe_normalized()
- }
- }
- }
-}
-
-void BL_MeshDeformer::VerifyStorage()
-{
- /* Ensure that we have the right number of verts assigned */
- if (m_tvtot!=m_bmesh->totvert) {
- if (m_transverts)
- delete [] m_transverts;
- if (m_transnors)
- delete [] m_transnors;
-
- m_transverts=new float[m_bmesh->totvert][3];
- m_transnors=new float[m_bmesh->totvert][3];
- m_tvtot = m_bmesh->totvert;
- }
-}
-
diff --git a/source/gameengine/Converter/BL_MeshDeformer.h b/source/gameengine/Converter/BL_MeshDeformer.h
deleted file mode 100644
index 6e84cdf03f8..00000000000
--- a/source/gameengine/Converter/BL_MeshDeformer.h
+++ /dev/null
@@ -1,98 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file BL_MeshDeformer.h
- * \ingroup bgeconv
- */
-
-#ifndef __BL_MESHDEFORMER_H__
-#define __BL_MESHDEFORMER_H__
-
-#include "RAS_Deformer.h"
-#include "DNA_object_types.h"
-#include "DNA_key_types.h"
-#include "MT_Point3.h"
-#include <stdlib.h>
-
-#ifdef _MSC_VER
-# pragma warning (disable:4786) /* get rid of stupid stl-visual compiler debug warning */
-#endif
-
-class BL_DeformableGameObject;
-
-class BL_MeshDeformer : public RAS_Deformer
-{
-public:
- void VerifyStorage();
- void RecalcNormals();
- virtual void Relink(CTR_Map<class CTR_HashedPtr, void*>*map);
- BL_MeshDeformer(BL_DeformableGameObject *gameobj,
- struct Object* obj,
- class RAS_MeshObject *meshobj ):
- m_pMeshObject(meshobj),
- m_bmesh((struct Mesh*)(obj->data)),
- m_transverts(0),
- m_transnors(0),
- m_objMesh(obj),
- m_tvtot(0),
- m_gameobj(gameobj),
- m_lastDeformUpdate(-1)
- {};
- virtual ~BL_MeshDeformer();
- virtual void SetSimulatedTime(double time) {}
- virtual bool Apply(class RAS_IPolyMaterial *mat);
- virtual bool Update(void) { return false; }
- virtual bool UpdateBuckets(void) { return false; }
- virtual RAS_Deformer* GetReplica() {return NULL;}
- virtual void ProcessReplica();
- struct Mesh* GetMesh() { return m_bmesh; }
- virtual class RAS_MeshObject* GetRasMesh() { return m_pMeshObject; }
- virtual float (* GetTransVerts(int *tot))[3] { *tot= m_tvtot; return m_transverts; }
- // virtual void InitDeform(double time) {}
-
-protected:
- class RAS_MeshObject* m_pMeshObject;
- struct Mesh* m_bmesh;
-
- // this is so m_transverts doesn't need to be converted
- // before deformation
- float (*m_transverts)[3];
- float (*m_transnors)[3];
- struct Object* m_objMesh;
- // --
- int m_tvtot;
- BL_DeformableGameObject* m_gameobj;
- double m_lastDeformUpdate;
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:BL_MeshDeformer")
-#endif
-};
-
-#endif
-
diff --git a/source/gameengine/Converter/BL_ModifierDeformer.cpp b/source/gameengine/Converter/BL_ModifierDeformer.cpp
deleted file mode 100644
index 3be2c1aff43..00000000000
--- a/source/gameengine/Converter/BL_ModifierDeformer.cpp
+++ /dev/null
@@ -1,227 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Converter/BL_ModifierDeformer.cpp
- * \ingroup bgeconv
- */
-
-#ifdef _MSC_VER
-# pragma warning (disable:4786)
-#endif
-
-#include "MEM_guardedalloc.h"
-#include "BL_ModifierDeformer.h"
-#include "CTR_Map.h"
-#include "STR_HashedString.h"
-#include "RAS_IPolygonMaterial.h"
-#include "RAS_MeshObject.h"
-#include "PHY_IGraphicController.h"
-
-#include "DNA_armature_types.h"
-#include "DNA_action_types.h"
-#include "DNA_key_types.h"
-#include "DNA_mesh_types.h"
-#include "DNA_meshdata_types.h"
-#include "DNA_curve_types.h"
-#include "DNA_modifier_types.h"
-#include "DNA_scene_types.h"
-#include "BLI_utildefines.h"
-#include "BKE_armature.h"
-#include "BKE_action.h"
-#include "BKE_key.h"
-#include "BKE_ipo.h"
-#include "MT_Point3.h"
-
-extern "C"{
- #include "BKE_customdata.h"
- #include "BKE_DerivedMesh.h"
- #include "BKE_lattice.h"
- #include "BKE_modifier.h"
-}
-
-#include "BLI_blenlib.h"
-#include "BLI_math.h"
-
-BL_ModifierDeformer::~BL_ModifierDeformer()
-{
- if (m_dm) {
- // deformedOnly is used as a user counter
- if (--m_dm->deformedOnly == 0) {
- m_dm->needsFree = 1;
- m_dm->release(m_dm);
- }
- }
-};
-
-RAS_Deformer *BL_ModifierDeformer::GetReplica()
-{
- BL_ModifierDeformer *result;
-
- result = new BL_ModifierDeformer(*this);
- result->ProcessReplica();
- return result;
-}
-
-void BL_ModifierDeformer::ProcessReplica()
-{
- /* Note! - This is not inherited from PyObjectPlus */
- BL_ShapeDeformer::ProcessReplica();
- if (m_dm)
- // by default try to reuse mesh, deformedOnly is used as a user count
- m_dm->deformedOnly++;
- // this will force an update and if the mesh cannot be reused, a new one will be created
- m_lastModifierUpdate = -1;
-}
-
-bool BL_ModifierDeformer::HasCompatibleDeformer(Object *ob)
-{
- if (!ob->modifiers.first)
- return false;
- // soft body cannot use mesh modifiers
- if ((ob->gameflag & OB_SOFT_BODY) != 0)
- return false;
- ModifierData* md;
- for (md = (ModifierData *)ob->modifiers.first; md; md = md->next) {
- if (modifier_dependsOnTime(md))
- continue;
- if (!(md->mode & eModifierMode_Realtime))
- continue;
- /* armature modifier are handled by SkinDeformer, not ModifierDeformer */
- if (md->type == eModifierType_Armature )
- continue;
- return true;
- }
- return false;
-}
-
-bool BL_ModifierDeformer::HasArmatureDeformer(Object *ob)
-{
- if (!ob->modifiers.first)
- return false;
-
- ModifierData* md = (ModifierData*)ob->modifiers.first;
- if (md->type == eModifierType_Armature )
- return true;
-
- return false;
-}
-
-// return a deformed mesh that supports mapping (with a valid CD_ORIGINDEX layer)
-struct DerivedMesh* BL_ModifierDeformer::GetPhysicsMesh()
-{
- /* TODO: This doesn't work currently because of eval_ctx. */
-#if 0
- /* we need to compute the deformed mesh taking into account the current
- * shape and skin deformers, we cannot just call mesh_create_derived_physics()
- * because that would use the m_transvers already deformed previously by BL_ModifierDeformer::Update(),
- * so restart from scratch by forcing a full update the shape/skin deformers
- * (will do nothing if there is no such deformer) */
- BL_ShapeDeformer::ForceUpdate();
- BL_ShapeDeformer::Update();
- // now apply the modifiers but without those that don't support mapping
- Object* blendobj = m_gameobj->GetBlendObject();
- /* hack: the modifiers require that the mesh is attached to the object
- * It may not be the case here because of replace mesh actuator */
- Mesh *oldmesh = (Mesh*)blendobj->data;
- blendobj->data = m_bmesh;
- DerivedMesh *dm = mesh_create_derived_physics(m_scene, blendobj, m_transverts, CD_MASK_MESH);
- /* restore object data */
- blendobj->data = oldmesh;
- /* m_transverts is correct here (takes into account deform only modifiers) */
- /* the derived mesh returned by this function must be released by the caller !!! */
- return dm;
-#endif
- return NULL;
-}
-
-bool BL_ModifierDeformer::Update(void)
-{
- /* TODO: This doesn't work currently because of eval_ctx. */
-#if 0
- bool bShapeUpdate = BL_ShapeDeformer::Update();
-
- if (bShapeUpdate || m_lastModifierUpdate != m_gameobj->GetLastFrame()) {
- // static derived mesh are not updated
- if (m_dm == NULL || m_bDynamic) {
- /* execute the modifiers */
- Object* blendobj = m_gameobj->GetBlendObject();
- /* hack: the modifiers require that the mesh is attached to the object
- * It may not be the case here because of replace mesh actuator */
- Mesh *oldmesh = (Mesh*)blendobj->data;
- blendobj->data = m_bmesh;
- /* execute the modifiers */
- DerivedMesh *dm = mesh_create_derived_no_virtual(m_scene, blendobj, m_transverts, CD_MASK_MESH);
- /* restore object data */
- blendobj->data = oldmesh;
- /* free the current derived mesh and replace, (dm should never be NULL) */
- if (m_dm != NULL) {
- // HACK! use deformedOnly as a user counter
- if (--m_dm->deformedOnly == 0) {
- m_dm->needsFree = 1;
- m_dm->release(m_dm);
- }
- }
- m_dm = dm;
- // get rid of temporary data
- m_dm->needsFree = 0;
- m_dm->release(m_dm);
- // HACK! use deformedOnly as a user counter
- m_dm->deformedOnly = 1;
- DM_update_materials(m_dm, blendobj);
- /* update the graphic controller */
- PHY_IGraphicController *ctrl = m_gameobj->GetGraphicController();
- if (ctrl) {
- float min[3], max[3];
- INIT_MINMAX(min, max);
- m_dm->getMinMax(m_dm, min, max);
- ctrl->SetLocalAabb(min, max);
- }
- }
- m_lastModifierUpdate=m_gameobj->GetLastFrame();
- bShapeUpdate = true;
-
- int nmat = m_pMeshObject->NumMaterials();
- for (int imat=0; imat<nmat; imat++) {
- RAS_MeshMaterial *mmat = m_pMeshObject->GetMeshMaterial(imat);
- RAS_MeshSlot **slot = mmat->m_slots[(void*)m_gameobj];
- if (!slot || !*slot)
- continue;
- (*slot)->m_pDerivedMesh = m_dm;
- }
- }
- return bShapeUpdate;
-#endif
- return false;
-}
-
-bool BL_ModifierDeformer::Apply(RAS_IPolyMaterial *mat)
-{
- if (!Update())
- return false;
-
- return true;
-}
diff --git a/source/gameengine/Converter/BL_ModifierDeformer.h b/source/gameengine/Converter/BL_ModifierDeformer.h
deleted file mode 100644
index 4efe4ca5bfc..00000000000
--- a/source/gameengine/Converter/BL_ModifierDeformer.h
+++ /dev/null
@@ -1,115 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file BL_ModifierDeformer.h
- * \ingroup bgeconv
- */
-
-#ifndef __BL_MODIFIERDEFORMER_H__
-#define __BL_MODIFIERDEFORMER_H__
-
-#ifdef _MSC_VER
-# pragma warning (disable:4786) /* get rid of stupid stl-visual compiler debug warning */
-#endif
-
-#include "BL_ShapeDeformer.h"
-#include "BL_DeformableGameObject.h"
-#include <vector>
-
-struct DerivedMesh;
-struct Object;
-
-class BL_ModifierDeformer : public BL_ShapeDeformer
-{
-public:
- static bool HasCompatibleDeformer(Object *ob);
- static bool HasArmatureDeformer(Object *ob);
-
-
- BL_ModifierDeformer(BL_DeformableGameObject *gameobj,
- Scene *scene,
- Object *bmeshobj,
- RAS_MeshObject *mesh)
- :
- BL_ShapeDeformer(gameobj,bmeshobj, mesh),
- m_lastModifierUpdate(-1),
- m_scene(scene),
- m_dm(NULL)
- {
- m_recalcNormal = false;
- }
-
- /* this second constructor is needed for making a mesh deformable on the fly. */
- BL_ModifierDeformer(BL_DeformableGameObject *gameobj,
- struct Scene *scene,
- struct Object *bmeshobj_old,
- struct Object *bmeshobj_new,
- class RAS_MeshObject *mesh,
- bool release_object,
- BL_ArmatureObject* arma = NULL)
- :
- BL_ShapeDeformer(gameobj, bmeshobj_old, bmeshobj_new, mesh, release_object, false, arma),
- m_lastModifierUpdate(-1),
- m_scene(scene),
- m_dm(NULL)
- {
- /* pass */
- }
-
- virtual void ProcessReplica();
- virtual RAS_Deformer *GetReplica();
- virtual ~BL_ModifierDeformer();
- virtual bool UseVertexArray()
- {
- return false;
- }
-
- bool Update (void);
- bool Apply(RAS_IPolyMaterial *mat);
- void ForceUpdate()
- {
- m_lastModifierUpdate = -1.0;
- };
- virtual struct DerivedMesh* GetFinalMesh()
- {
- return m_dm;
- }
- // The derived mesh returned by this function must be released!
- virtual struct DerivedMesh* GetPhysicsMesh();
-
-protected:
- double m_lastModifierUpdate;
- Scene *m_scene;
- DerivedMesh *m_dm;
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:BL_ModifierDeformer")
-#endif
-};
-
-#endif /* __BL_MODIFIERDEFORMER_H__ */
diff --git a/source/gameengine/Converter/BL_ShapeActionActuator.cpp b/source/gameengine/Converter/BL_ShapeActionActuator.cpp
deleted file mode 100644
index f21db419ebc..00000000000
--- a/source/gameengine/Converter/BL_ShapeActionActuator.cpp
+++ /dev/null
@@ -1,563 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Converter/BL_ShapeActionActuator.cpp
- * \ingroup bgeconv
- */
-
-
-#include <cmath>
-
-#include "SCA_LogicManager.h"
-#include "BL_ShapeActionActuator.h"
-#include "BL_ShapeDeformer.h"
-#include "KX_GameObject.h"
-#include "STR_HashedString.h"
-#include "DNA_nla_types.h"
-#include "DNA_action_types.h"
-#include "DNA_anim_types.h"
-#include "DNA_scene_types.h"
-#include "BKE_action.h"
-#include "DNA_armature_types.h"
-#include "MEM_guardedalloc.h"
-#include "BLI_blenlib.h"
-#include "BLI_math.h"
-#include "MT_Matrix4x4.h"
-
-#include "EXP_FloatValue.h"
-#include "EXP_PyObjectPlus.h"
-
-extern "C" {
- #include "BKE_animsys.h"
- #include "BKE_key.h"
- #include "RNA_access.h"
-}
-
-BL_ShapeActionActuator::BL_ShapeActionActuator(SCA_IObject* gameobj,
- const STR_String& propname,
- const STR_String& framepropname,
- float starttime,
- float endtime,
- struct bAction *action,
- short playtype,
- short blendin,
- short priority,
- float stride)
- : SCA_IActuator(gameobj, KX_ACT_SHAPEACTION),
-
- m_lastpos(0, 0, 0),
- m_blendframe(0),
- m_flag(0),
- m_startframe (starttime),
- m_endframe(endtime) ,
- m_starttime(0),
- m_localtime(starttime),
- m_lastUpdate(-1),
- m_blendin(blendin),
- m_blendstart(0),
- m_stridelength(stride),
- m_playtype(playtype),
- m_priority(priority),
- m_action(action),
- m_framepropname(framepropname),
- m_propname(propname)
-{
- m_idptr = new PointerRNA();
- BL_DeformableGameObject *obj = (BL_DeformableGameObject*)GetParent();
- BL_ShapeDeformer *shape_deformer = dynamic_cast<BL_ShapeDeformer*>(obj->GetDeformer());
- RNA_id_pointer_create(&shape_deformer->GetKey()->id, m_idptr);
-};
-
-BL_ShapeActionActuator::~BL_ShapeActionActuator()
-{
- if (m_idptr)
- delete m_idptr;
-}
-
-void BL_ShapeActionActuator::ProcessReplica()
-{
- SCA_IActuator::ProcessReplica();
- m_localtime=m_startframe;
- m_lastUpdate=-1;
-}
-
-void BL_ShapeActionActuator::SetBlendTime(float newtime)
-{
- m_blendframe = newtime;
-}
-
-CValue* BL_ShapeActionActuator::GetReplica()
-{
- BL_ShapeActionActuator* replica = new BL_ShapeActionActuator(*this);//m_float,GetName());
- replica->ProcessReplica();
- return replica;
-}
-
-bool BL_ShapeActionActuator::ClampLocalTime()
-{
- if (m_startframe < m_endframe) {
- if (m_localtime < m_startframe)
- {
- m_localtime = m_startframe;
- return true;
- }
- else if (m_localtime > m_endframe)
- {
- m_localtime = m_endframe;
- return true;
- }
- } else {
- if (m_localtime > m_startframe)
- {
- m_localtime = m_startframe;
- return true;
- }
- else if (m_localtime < m_endframe)
- {
- m_localtime = m_endframe;
- return true;
- }
- }
- return false;
-}
-
-void BL_ShapeActionActuator::SetStartTime(float curtime)
-{
- float direction = m_startframe < m_endframe ? 1.0 : -1.0;
-
- if (!(m_flag & ACT_FLAG_REVERSE))
- m_starttime = curtime - direction*(m_localtime - m_startframe)/KX_KetsjiEngine::GetAnimFrameRate();
- else
- m_starttime = curtime - direction*(m_endframe - m_localtime)/KX_KetsjiEngine::GetAnimFrameRate();
-}
-
-void BL_ShapeActionActuator::SetLocalTime(float curtime)
-{
- float delta_time = (curtime - m_starttime)*KX_KetsjiEngine::GetAnimFrameRate();
-
- if (m_endframe < m_startframe)
- delta_time = -delta_time;
-
- if (!(m_flag & ACT_FLAG_REVERSE))
- m_localtime = m_startframe + delta_time;
- else
- m_localtime = m_endframe - delta_time;
-}
-
-void BL_ShapeActionActuator::BlendShape(Key* key, float srcweight)
-{
- vector<float>::const_iterator it;
- float dstweight;
- KeyBlock *kb;
-
- dstweight = 1.0F - srcweight;
-
- for (it=m_blendshape.begin(), kb = (KeyBlock *)key->block.first;
- kb && it != m_blendshape.end();
- kb = (KeyBlock *)kb->next, it++)
- {
- kb->curval = kb->curval * dstweight + (*it) * srcweight;
- }
-}
-
-bool BL_ShapeActionActuator::Update(double curtime, bool frame)
-{
- bool bNegativeEvent = false;
- bool bPositiveEvent = false;
- bool keepgoing = true;
- bool wrap = false;
- bool apply=true;
- int priority;
- float newweight;
-
- curtime -= KX_KetsjiEngine::GetSuspendedDelta();
-
- // result = true if animation has to be continued, false if animation stops
- // maybe there are events for us in the queue !
- if (frame)
- {
- bNegativeEvent = m_negevent;
- bPositiveEvent = m_posevent;
- RemoveAllEvents();
-
- if (bPositiveEvent)
- m_flag |= ACT_FLAG_ACTIVE;
-
- if (bNegativeEvent)
- {
- if (!(m_flag & ACT_FLAG_ACTIVE))
- return false;
- m_flag &= ~ACT_FLAG_ACTIVE;
- }
- }
-
- /* This action can only be attached to a deform object */
- BL_DeformableGameObject *obj = (BL_DeformableGameObject*)GetParent();
- float length = m_endframe - m_startframe;
-
- priority = m_priority;
-
- /* Determine pre-incrementation behavior and set appropriate flags */
- switch (m_playtype) {
- case ACT_ACTION_MOTION:
- if (bNegativeEvent) {
- keepgoing=false;
- apply=false;
- };
- break;
- case ACT_ACTION_FROM_PROP:
- if (bNegativeEvent) {
- apply=false;
- keepgoing=false;
- }
- break;
- case ACT_ACTION_LOOP_END:
- if (bPositiveEvent) {
- if (!(m_flag & ACT_FLAG_LOCKINPUT)) {
- m_flag &= ~ACT_FLAG_KEYUP;
- m_flag &= ~ACT_FLAG_REVERSE;
- m_flag |= ACT_FLAG_LOCKINPUT;
- m_localtime = m_startframe;
- m_starttime = curtime;
- }
- }
- if (bNegativeEvent) {
- m_flag |= ACT_FLAG_KEYUP;
- }
- break;
- case ACT_ACTION_LOOP_STOP:
- if (bPositiveEvent) {
- if (!(m_flag & ACT_FLAG_LOCKINPUT)) {
- m_flag &= ~ACT_FLAG_REVERSE;
- m_flag &= ~ACT_FLAG_KEYUP;
- m_flag |= ACT_FLAG_LOCKINPUT;
- SetStartTime(curtime);
- }
- }
- if (bNegativeEvent) {
- m_flag |= ACT_FLAG_KEYUP;
- m_flag &= ~ACT_FLAG_LOCKINPUT;
- keepgoing=false;
- apply=false;
- }
- break;
- case ACT_ACTION_PINGPONG:
- if (bPositiveEvent) {
- if (!(m_flag & ACT_FLAG_LOCKINPUT)) {
- m_flag &= ~ACT_FLAG_KEYUP;
- m_localtime = m_starttime;
- m_starttime = curtime;
- m_flag |= ACT_FLAG_LOCKINPUT;
- }
- }
- break;
- case ACT_ACTION_FLIPPER:
- if (bPositiveEvent) {
- if (!(m_flag & ACT_FLAG_LOCKINPUT)) {
- m_flag &= ~ACT_FLAG_REVERSE;
- m_flag |= ACT_FLAG_LOCKINPUT;
- SetStartTime(curtime);
- }
- }
- else if (bNegativeEvent) {
- m_flag |= ACT_FLAG_REVERSE;
- m_flag &= ~ACT_FLAG_LOCKINPUT;
- SetStartTime(curtime);
- }
- break;
- case ACT_ACTION_PLAY:
- if (bPositiveEvent) {
- if (!(m_flag & ACT_FLAG_LOCKINPUT)) {
- m_flag &= ~ACT_FLAG_REVERSE;
- m_localtime = m_starttime;
- m_starttime = curtime;
- m_flag |= ACT_FLAG_LOCKINPUT;
- }
- }
- break;
- default:
- break;
- }
-
- /* Perform increment */
- if (keepgoing) {
- if (m_playtype == ACT_ACTION_MOTION) {
- MT_Point3 newpos;
- MT_Point3 deltapos;
-
- newpos = obj->NodeGetWorldPosition();
-
- /* Find displacement */
- deltapos = newpos-m_lastpos;
- m_localtime += (length/m_stridelength) * deltapos.length();
- m_lastpos = newpos;
- }
- else {
- SetLocalTime(curtime);
- }
- }
-
- /* Check if a wrapping response is needed */
- if (length) {
- if (m_localtime < m_startframe || m_localtime > m_endframe)
- {
- m_localtime = m_startframe + fmod(m_localtime, length);
- wrap = true;
- }
- }
- else
- m_localtime = m_startframe;
-
- /* Perform post-increment tasks */
- switch (m_playtype) {
- case ACT_ACTION_FROM_PROP:
- {
- CValue* propval = GetParent()->GetProperty(m_propname);
- if (propval)
- m_localtime = propval->GetNumber();
-
- if (bNegativeEvent) {
- keepgoing=false;
- }
- }
- break;
- case ACT_ACTION_MOTION:
- break;
- case ACT_ACTION_LOOP_STOP:
- break;
- case ACT_ACTION_PINGPONG:
- if (wrap) {
- if (!(m_flag & ACT_FLAG_REVERSE))
- m_localtime = m_endframe;
- else
- m_localtime = m_startframe;
-
- m_flag &= ~ACT_FLAG_LOCKINPUT;
- m_flag ^= ACT_FLAG_REVERSE; //flip direction
- keepgoing = false;
- }
- break;
- case ACT_ACTION_FLIPPER:
- if (wrap) {
- if (!(m_flag & ACT_FLAG_REVERSE)) {
- m_localtime=m_endframe;
- //keepgoing = false;
- }
- else {
- m_localtime=m_startframe;
- keepgoing = false;
- }
- }
- break;
- case ACT_ACTION_LOOP_END:
- if (wrap) {
- if (m_flag & ACT_FLAG_KEYUP) {
- keepgoing = false;
- m_localtime = m_endframe;
- m_flag &= ~ACT_FLAG_LOCKINPUT;
- }
- SetStartTime(curtime);
- }
- break;
- case ACT_ACTION_PLAY:
- if (wrap) {
- m_localtime = m_endframe;
- keepgoing = false;
- m_flag &= ~ACT_FLAG_LOCKINPUT;
- }
- break;
- default:
- keepgoing = false;
- break;
- }
-
- /* Set the property if its defined */
- if (m_framepropname[0] != '\0') {
- CValue* propowner = GetParent();
- CValue* oldprop = propowner->GetProperty(m_framepropname);
- CValue* newval = new CFloatValue(m_localtime);
- if (oldprop) {
- oldprop->SetValue(newval);
- } else {
- propowner->SetProperty(m_framepropname, newval);
- }
- newval->Release();
- }
-
- if (bNegativeEvent)
- m_blendframe=0.0f;
-
- /* Apply the pose if necessary*/
- if (apply) {
-
- /* Priority test */
- if (obj->SetActiveAction(this, priority, curtime)) {
- BL_ShapeDeformer *shape_deformer = dynamic_cast<BL_ShapeDeformer*>(obj->GetDeformer());
- Key *key = NULL;
-
- if (shape_deformer)
- key = shape_deformer->GetKey();
-
- if (!key) {
- // this could happen if the mesh was changed in the middle of an action
- // and the new mesh has no key, stop the action
- keepgoing = false;
- }
- else {
- ListBase tchanbase= {NULL, NULL};
-
- if (m_blendin && m_blendframe==0.0f) {
- // this is the start of the blending, remember the startup shape
- obj->GetShape(m_blendshape);
- m_blendstart = curtime;
- }
-
- KeyBlock *kb;
- // We go through and clear out the keyblocks so there isn't any interference
- // from other shape actions
- for (kb=(KeyBlock *)key->block.first; kb; kb=(KeyBlock *)kb->next)
- kb->curval = 0.f;
-
- animsys_evaluate_action(m_idptr, m_action, NULL, m_localtime);
-
- // XXX - in 2.5 theres no way to do this. possibly not that important to support - Campbell
- if (0) { // XXX !execute_ipochannels(&tchanbase)) {
- // no update, this is possible if action does not match the keys, stop the action
- keepgoing = false;
- }
- else {
- // the key have changed, apply blending if needed
- if (m_blendin && (m_blendframe<m_blendin)) {
- newweight = (m_blendframe/(float)m_blendin);
-
- BlendShape(key, 1.0f - newweight);
-
- /* Increment current blending percentage */
- m_blendframe = (curtime - m_blendstart)*KX_KetsjiEngine::GetAnimFrameRate();
- if (m_blendframe>m_blendin)
- m_blendframe = m_blendin;
- }
- m_lastUpdate = m_localtime;
- }
- BLI_freelistN(&tchanbase);
- }
- }
- else {
- m_blendframe = 0.0f;
- }
- }
-
- if (!keepgoing) {
- m_blendframe = 0.0f;
- }
- return keepgoing;
-};
-
-#ifdef WITH_PYTHON
-
-/* ------------------------------------------------------------------------- */
-/* Python functions */
-/* ------------------------------------------------------------------------- */
-
-/* Integration hooks ------------------------------------------------------- */
-
-PyTypeObject BL_ShapeActionActuator::Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "BL_ShapeActionActuator",
- sizeof(PyObjectPlus_Proxy),
- 0,
- py_base_dealloc,
- 0,
- 0,
- 0,
- 0,
- py_base_repr,
- 0,0,0,0,0,0,0,0,0,
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
- 0,0,0,0,0,0,0,
- Methods,
- 0,
- 0,
- &SCA_IActuator::Type,
- 0,0,0,0,0,0,
- py_base_new
-};
-
-
-PyMethodDef BL_ShapeActionActuator::Methods[] = {
- {NULL,NULL} //Sentinel
-};
-
-PyAttributeDef BL_ShapeActionActuator::Attributes[] = {
- KX_PYATTRIBUTE_FLOAT_RW("frameStart", 0, MAXFRAMEF, BL_ShapeActionActuator, m_startframe),
- KX_PYATTRIBUTE_FLOAT_RW("frameEnd", 0, MAXFRAMEF, BL_ShapeActionActuator, m_endframe),
- KX_PYATTRIBUTE_FLOAT_RW("blendIn", 0, MAXFRAMEF, BL_ShapeActionActuator, m_blendin),
- KX_PYATTRIBUTE_RW_FUNCTION("action", BL_ShapeActionActuator, pyattr_get_action, pyattr_set_action),
- KX_PYATTRIBUTE_SHORT_RW("priority", 0, 100, false, BL_ShapeActionActuator, m_priority),
- KX_PYATTRIBUTE_FLOAT_RW_CHECK("frame", 0, MAXFRAMEF, BL_ShapeActionActuator, m_localtime, CheckFrame),
- KX_PYATTRIBUTE_STRING_RW("propName", 0, MAX_PROP_NAME, false, BL_ShapeActionActuator, m_propname),
- KX_PYATTRIBUTE_STRING_RW("framePropName", 0, MAX_PROP_NAME, false, BL_ShapeActionActuator, m_framepropname),
- KX_PYATTRIBUTE_FLOAT_RW_CHECK("blendTime", 0, MAXFRAMEF, BL_ShapeActionActuator, m_blendframe, CheckBlendTime),
- KX_PYATTRIBUTE_SHORT_RW_CHECK("mode",0,100,false,BL_ShapeActionActuator,m_playtype,CheckType),
- { NULL } //Sentinel
-};
-
-PyObject *BL_ShapeActionActuator::pyattr_get_action(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- BL_ShapeActionActuator* self = static_cast<BL_ShapeActionActuator*>(self_v);
- return PyUnicode_FromString(self->GetAction() ? self->GetAction()->id.name+2 : "");
-}
-
-int BL_ShapeActionActuator::pyattr_set_action(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- BL_ShapeActionActuator* self = static_cast<BL_ShapeActionActuator*>(self_v);
- /* exact copy of BL_ActionActuator's function from here down */
- if (!PyUnicode_Check(value))
- {
- PyErr_SetString(PyExc_ValueError, "actuator.action = val: Shape Action Actuator, expected the string name of the action");
- return PY_SET_ATTR_FAIL;
- }
-
- bAction *action= NULL;
- STR_String val = _PyUnicode_AsString(value);
-
- if (val != "")
- {
- action= (bAction*)self->GetLogicManager()->GetActionByName(val);
- if (action==NULL)
- {
- PyErr_SetString(PyExc_ValueError, "actuator.action = val: Shape Action Actuator, action not found!");
- return PY_SET_ATTR_FAIL;
- }
- }
-
- self->SetAction(action);
- return PY_SET_ATTR_SUCCESS;
-
-}
-
-#endif // WITH_PYTHON
diff --git a/source/gameengine/Converter/BL_ShapeActionActuator.h b/source/gameengine/Converter/BL_ShapeActionActuator.h
deleted file mode 100644
index e96d0e0ebb4..00000000000
--- a/source/gameengine/Converter/BL_ShapeActionActuator.h
+++ /dev/null
@@ -1,144 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file BL_ShapeActionActuator.h
- * \ingroup bgeconv
- */
-
-#ifndef __BL_SHAPEACTIONACTUATOR_H__
-#define __BL_SHAPEACTIONACTUATOR_H__
-
-#include "CTR_HashedPtr.h"
-#include "SCA_IActuator.h"
-#include "BL_ActionActuator.h"
-#include "MT_Point3.h"
-#include <vector>
-
-struct Key;
-class BL_ShapeActionActuator : public SCA_IActuator
-{
-public:
- Py_Header
- BL_ShapeActionActuator(SCA_IObject* gameobj,
- const STR_String& propname,
- const STR_String& framepropname,
- float starttime,
- float endtime,
- struct bAction *action,
- short playtype,
- short blendin,
- short priority,
- float stride);
- virtual ~BL_ShapeActionActuator();
- virtual bool Update(double curtime, bool frame);
- virtual CValue* GetReplica();
- virtual void ProcessReplica();
-
- void SetBlendTime (float newtime);
- void BlendShape(struct Key* key, float weight);
-
- bAction* GetAction() { return m_action; }
- void SetAction(bAction* act) { m_action= act; }
-
-#ifdef WITH_PYTHON
-
- static PyObject* pyattr_get_action(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_action(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
-
- static int CheckBlendTime(void *self, const PyAttributeDef*)
- {
- BL_ShapeActionActuator* act = reinterpret_cast<BL_ShapeActionActuator*>(self);
-
- if (act->m_blendframe > act->m_blendin)
- act->m_blendframe = act->m_blendin;
-
- return 0;
- }
- static int CheckFrame(void *self, const PyAttributeDef*)
- {
- BL_ShapeActionActuator* act = reinterpret_cast<BL_ShapeActionActuator*>(self);
-
- if (act->m_localtime < act->m_startframe)
- act->m_localtime = act->m_startframe;
- else if (act->m_localtime > act->m_endframe)
- act->m_localtime = act->m_endframe;
-
- return 0;
- }
- static int CheckType(void *self, const PyAttributeDef*)
- {
- BL_ShapeActionActuator* act = reinterpret_cast<BL_ShapeActionActuator*>(self);
-
- switch (act->m_playtype) {
- case ACT_ACTION_PLAY:
- case ACT_ACTION_PINGPONG:
- case ACT_ACTION_FLIPPER:
- case ACT_ACTION_LOOP_STOP:
- case ACT_ACTION_LOOP_END:
- case ACT_ACTION_FROM_PROP:
- return 0;
- default:
- PyErr_SetString(PyExc_ValueError, "Shape Action Actuator, invalid play type supplied");
- return 1;
- }
-
- }
-
-#endif /* WITH_PYTHON */
-
-protected:
-
- void SetStartTime(float curtime);
- void SetLocalTime(float curtime);
- bool ClampLocalTime();
-
- MT_Point3 m_lastpos;
- float m_blendframe;
- int m_flag;
- /** The frame this action starts */
- float m_startframe;
- /** The frame this action ends */
- float m_endframe;
- /** The time this action started */
- float m_starttime;
- /** The current time of the action */
- float m_localtime;
-
- float m_lastUpdate;
- float m_blendin;
- float m_blendstart;
- float m_stridelength;
- short m_playtype;
- short m_priority;
- struct bAction *m_action;
- STR_String m_framepropname;
- STR_String m_propname;
- vector<float> m_blendshape;
- struct PointerRNA *m_idptr;
-};
-
-#endif /* __BL_SHAPEACTIONACTUATOR_H__ */
diff --git a/source/gameengine/Converter/BL_ShapeDeformer.cpp b/source/gameengine/Converter/BL_ShapeDeformer.cpp
deleted file mode 100644
index 94256a64d75..00000000000
--- a/source/gameengine/Converter/BL_ShapeDeformer.cpp
+++ /dev/null
@@ -1,237 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Converter/BL_ShapeDeformer.cpp
- * \ingroup bgeconv
- */
-
-#ifdef _MSC_VER
-# pragma warning (disable:4786)
-#endif
-
-#include "MEM_guardedalloc.h"
-#include "BL_ShapeDeformer.h"
-#include "CTR_Map.h"
-#include "STR_HashedString.h"
-#include "RAS_IPolygonMaterial.h"
-#include "RAS_MeshObject.h"
-
-#include "DNA_anim_types.h"
-#include "DNA_armature_types.h"
-#include "DNA_action_types.h"
-#include "DNA_key_types.h"
-#include "DNA_mesh_types.h"
-#include "DNA_meshdata_types.h"
-#include "BKE_armature.h"
-#include "BKE_action.h"
-#include "BKE_global.h"
-#include "BKE_main.h"
-#include "BKE_key.h"
-#include "BKE_fcurve.h"
-#include "BKE_ipo.h"
-#include "BKE_library.h"
-#include "MT_Point3.h"
-
-extern "C"{
- #include "BKE_lattice.h"
- #include "BKE_animsys.h"
-}
-
-#include "BLI_blenlib.h"
-#include "BLI_math.h"
-
-#define __NLA_DEFNORMALS
-//#undef __NLA_DEFNORMALS
-
-BL_ShapeDeformer::BL_ShapeDeformer(BL_DeformableGameObject *gameobj,
- Object *bmeshobj,
- RAS_MeshObject *mesh)
- :
- BL_SkinDeformer(gameobj,bmeshobj, mesh),
- m_useShapeDrivers(false),
- m_lastShapeUpdate(-1)
-{
- m_key = m_bmesh->key ? BKE_key_copy(G.main, m_bmesh->key) : NULL;
-};
-
-/* this second constructor is needed for making a mesh deformable on the fly. */
-BL_ShapeDeformer::BL_ShapeDeformer(BL_DeformableGameObject *gameobj,
- Object *bmeshobj_old,
- Object *bmeshobj_new,
- RAS_MeshObject *mesh,
- bool release_object,
- bool recalc_normal,
- BL_ArmatureObject* arma)
- :
- BL_SkinDeformer(gameobj, bmeshobj_old, bmeshobj_new, mesh, release_object, recalc_normal, arma),
- m_useShapeDrivers(false),
- m_lastShapeUpdate(-1)
-{
- m_key = m_bmesh->key ? BKE_key_copy(G.main, m_bmesh->key) : NULL;
-};
-
-BL_ShapeDeformer::~BL_ShapeDeformer()
-{
- if (m_key)
- {
- BKE_libblock_free(G.main, m_key);
- m_key = NULL;
- }
-};
-
-RAS_Deformer *BL_ShapeDeformer::GetReplica()
-{
- BL_ShapeDeformer *result;
-
- result = new BL_ShapeDeformer(*this);
- result->ProcessReplica();
- return result;
-}
-
-void BL_ShapeDeformer::ProcessReplica()
-{
- BL_SkinDeformer::ProcessReplica();
- m_lastShapeUpdate = -1;
-
- m_key = m_key ? BKE_key_copy(G.main, m_key) : NULL;
-}
-
-bool BL_ShapeDeformer::LoadShapeDrivers(KX_GameObject* parent)
-{
- // Only load shape drivers if we have a key
- if (GetKey() == NULL) {
- m_useShapeDrivers = false;
- return false;
- }
-
- // Fix drivers since BL_ArmatureObject makes copies
- if (parent->GetGameObjectType() == SCA_IObject::OBJ_ARMATURE && GetKey()->adt) {
- BL_ArmatureObject *arma = (BL_ArmatureObject*)parent;
- FCurve *fcu;
-
- for (fcu = (FCurve*)GetKey()->adt->drivers.first; fcu; fcu = (FCurve*)fcu->next) {
-
- DriverVar *dvar;
- for (dvar = (DriverVar*)fcu->driver->variables.first; dvar; dvar = (DriverVar*)dvar->next) {
- DRIVER_TARGETS_USED_LOOPER(dvar)
- {
- if (dtar->id) {
- if ((Object*)dtar->id == arma->GetOrigArmatureObject())
- dtar->id = (ID*)arma->GetArmatureObject();
- }
- }
- DRIVER_TARGETS_LOOPER_END
- }
- }
- }
-
- // This used to check if we had drivers from this armature,
- // now we just assume we want to use shape drivers
- // and let the animsys handle things.
- m_useShapeDrivers = true;
-
- return true;
-}
-
-bool BL_ShapeDeformer::ExecuteShapeDrivers(void)
-{
- if (m_useShapeDrivers && PoseUpdated()) {
- // We don't need an actual time, just use 0
- BKE_animsys_evaluate_animdata(NULL, &GetKey()->id, GetKey()->adt, 0.f, ADT_RECALC_DRIVERS);
-
- ForceUpdate();
- m_bDynamic = true;
- return true;
- }
- return false;
-}
-
-bool BL_ShapeDeformer::Update(void)
-{
- bool bShapeUpdate = false;
- bool bSkinUpdate = false;
-
- ExecuteShapeDrivers();
-
- /* See if the object shape has changed */
- if (m_lastShapeUpdate != m_gameobj->GetLastFrame()) {
- /* the key coefficient have been set already, we just need to blend the keys */
- Object* blendobj = m_gameobj->GetBlendObject();
-
- /* we will blend the key directly in m_transverts array: it is used by armature as the start position */
- /* m_key can be NULL in case of Modifier deformer */
- if (m_key) {
- WeightsArrayCache cache = {0, NULL};
- float **per_keyblock_weights;
-
- /* store verts locally */
- VerifyStorage();
-
- per_keyblock_weights = BKE_keyblock_get_per_block_weights(blendobj, m_key, &cache);
- BKE_key_evaluate_relative(0, m_bmesh->totvert, m_bmesh->totvert, (char *)(float *)m_transverts,
- m_key, NULL, per_keyblock_weights, 0); /* last arg is ignored */
- BKE_keyblock_free_per_block_weights(m_key, per_keyblock_weights, &cache);
-
- m_bDynamic = true;
- }
-
- // Don't release the weight array as in Blender, it will most likely be reusable on next frame
- // The weight array are ultimately deleted when the skin mesh is destroyed
-
- /* Update the current frame */
- m_lastShapeUpdate=m_gameobj->GetLastFrame();
-
- // As we have changed, the mesh, the skin deformer must update as well.
- // This will force the update
- BL_SkinDeformer::ForceUpdate();
- bShapeUpdate = true;
- }
- // check for armature deform
- bSkinUpdate = BL_SkinDeformer::UpdateInternal(bShapeUpdate && m_bDynamic);
-
- // non dynamic deformer = Modifer without armature and shape keys, no need to create storage
- if (!bSkinUpdate && bShapeUpdate && m_bDynamic) {
- // this means that there is no armature, we still need to
- // update the normal (was not done after shape key calculation)
-
-#ifdef __NLA_DEFNORMALS
- if (m_recalcNormal)
- RecalcNormals();
-#endif
-
- // We also need to handle transverts now (used to be in BL_SkinDeformer::Apply())
- UpdateTransverts();
- bSkinUpdate = true;
- }
-
- return bSkinUpdate;
-}
-
-Key *BL_ShapeDeformer::GetKey()
-{
- return m_key;
-}
diff --git a/source/gameengine/Converter/BL_ShapeDeformer.h b/source/gameengine/Converter/BL_ShapeDeformer.h
deleted file mode 100644
index f6746dd2302..00000000000
--- a/source/gameengine/Converter/BL_ShapeDeformer.h
+++ /dev/null
@@ -1,86 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file BL_ShapeDeformer.h
- * \ingroup bgeconv
- */
-
-#ifndef __BL_SHAPEDEFORMER_H__
-#define __BL_SHAPEDEFORMER_H__
-
-#ifdef _MSC_VER
-# pragma warning (disable:4786) /* get rid of stupid stl-visual compiler debug warning */
-#endif
-
-#include "BL_SkinDeformer.h"
-#include "BL_DeformableGameObject.h"
-#include <vector>
-
-class BL_ShapeDeformer : public BL_SkinDeformer
-{
-public:
- BL_ShapeDeformer(BL_DeformableGameObject *gameobj,
- Object *bmeshobj,
- RAS_MeshObject *mesh);
-
- /* this second constructor is needed for making a mesh deformable on the fly. */
- BL_ShapeDeformer(BL_DeformableGameObject *gameobj,
- struct Object *bmeshobj_old,
- struct Object *bmeshobj_new,
- class RAS_MeshObject *mesh,
- bool release_object,
- bool recalc_normal,
- BL_ArmatureObject* arma = NULL);
-
- virtual RAS_Deformer *GetReplica();
- virtual void ProcessReplica();
- virtual ~BL_ShapeDeformer();
-
- bool Update (void);
- bool LoadShapeDrivers(KX_GameObject* parent);
- bool ExecuteShapeDrivers(void);
-
- struct Key *GetKey();
-
- void ForceUpdate()
- {
- m_lastShapeUpdate = -1.0;
- };
-
-protected:
- bool m_useShapeDrivers;
- double m_lastShapeUpdate;
- struct Key* m_key;
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:BL_ShapeDeformer")
-#endif
-};
-
-#endif
-
diff --git a/source/gameengine/Converter/BL_SkinDeformer.cpp b/source/gameengine/Converter/BL_SkinDeformer.cpp
deleted file mode 100644
index 68da99f9fa5..00000000000
--- a/source/gameengine/Converter/BL_SkinDeformer.cpp
+++ /dev/null
@@ -1,384 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Converter/BL_SkinDeformer.cpp
- * \ingroup bgeconv
- */
-
-#ifdef _MSC_VER
-# pragma warning (disable:4786)
-#endif
-
-// Eigen3 stuff used for BGEDeformVerts
-#include <Eigen/Core>
-#include <Eigen/LU>
-
-#include "BL_SkinDeformer.h"
-#include "CTR_Map.h"
-#include "STR_HashedString.h"
-#include "RAS_IPolygonMaterial.h"
-#include "RAS_MeshObject.h"
-
-//#include "BL_ArmatureController.h"
-#include "DNA_armature_types.h"
-#include "DNA_action_types.h"
-#include "DNA_mesh_types.h"
-#include "DNA_meshdata_types.h"
-#include "DNA_modifier_types.h"
-#include "BLI_utildefines.h"
-#include "BKE_armature.h"
-#include "BKE_action.h"
-#include "MT_Point3.h"
-
-extern "C"{
- #include "BKE_lattice.h"
- #include "BKE_deform.h"
-}
-
-
-#include "BLI_blenlib.h"
-#include "BLI_math.h"
-
-#define __NLA_DEFNORMALS
-//#undef __NLA_DEFNORMALS
-
-static short get_deformflags(struct Object *bmeshobj)
-{
- short flags = ARM_DEF_VGROUP;
-
- ModifierData *md;
- for (md = (ModifierData *)bmeshobj->modifiers.first; md; md = md->next)
- {
- if (md->type == eModifierType_Armature)
- {
- flags |= ((ArmatureModifierData*)md)->deformflag;
- break;
- }
- }
-
- return flags;
-}
-
-BL_SkinDeformer::BL_SkinDeformer(BL_DeformableGameObject *gameobj,
- struct Object *bmeshobj,
- class RAS_MeshObject *mesh,
- BL_ArmatureObject* arma)
- : //
- BL_MeshDeformer(gameobj, bmeshobj, mesh),
- m_armobj(arma),
- m_lastArmaUpdate(-1),
- //m_defbase(&bmeshobj->defbase),
- m_releaseobject(false),
- m_poseApplied(false),
- m_recalcNormal(true),
- m_copyNormals(false),
- m_dfnrToPC(NULL)
-{
- copy_m4_m4(m_obmat, bmeshobj->obmat);
- m_deformflags = get_deformflags(bmeshobj);
-};
-
-BL_SkinDeformer::BL_SkinDeformer(
- BL_DeformableGameObject *gameobj,
- struct Object *bmeshobj_old, // Blender object that owns the new mesh
- struct Object *bmeshobj_new, // Blender object that owns the original mesh
- class RAS_MeshObject *mesh,
- bool release_object,
- bool recalc_normal,
- BL_ArmatureObject* arma) :
- BL_MeshDeformer(gameobj, bmeshobj_old, mesh),
- m_armobj(arma),
- m_lastArmaUpdate(-1),
- //m_defbase(&bmeshobj_old->defbase),
- m_releaseobject(release_object),
- m_recalcNormal(recalc_normal),
- m_copyNormals(false),
- m_dfnrToPC(NULL)
- {
- // this is needed to ensure correct deformation of mesh:
- // the deformation is done with Blender's armature_deform_verts() function
- // that takes an object as parameter and not a mesh. The object matrice is used
- // in the calculation, so we must use the matrix of the original object to
- // simulate a pure replacement of the mesh.
- copy_m4_m4(m_obmat, bmeshobj_new->obmat);
- m_deformflags = get_deformflags(bmeshobj_new);
- }
-
-BL_SkinDeformer::~BL_SkinDeformer()
-{
- if (m_releaseobject && m_armobj)
- m_armobj->Release();
- if (m_dfnrToPC)
- delete [] m_dfnrToPC;
-}
-
-void BL_SkinDeformer::Relink(CTR_Map<class CTR_HashedPtr, void*>*map)
-{
- if (m_armobj) {
- void **h_obj = (*map)[m_armobj];
-
- if (h_obj)
- m_armobj = (BL_ArmatureObject*)(*h_obj);
- else
- m_armobj=NULL;
- }
-
- BL_MeshDeformer::Relink(map);
-}
-
-bool BL_SkinDeformer::Apply(RAS_IPolyMaterial *mat)
-{
- // We do everything in UpdateInternal() now so we can thread it.
- // All that is left is telling the rasterizer if we've changed the mesh
- bool retval = !m_poseApplied;
- m_poseApplied = true;
- return retval;
-}
-
-RAS_Deformer *BL_SkinDeformer::GetReplica()
-{
- BL_SkinDeformer *result;
-
- result = new BL_SkinDeformer(*this);
- /* there is m_armobj that must be fixed but we cannot do it now, it will be done in Relink */
- result->ProcessReplica();
- return result;
-}
-
-void BL_SkinDeformer::ProcessReplica()
-{
- BL_MeshDeformer::ProcessReplica();
- m_lastArmaUpdate = -1;
- m_releaseobject = false;
- m_dfnrToPC = NULL;
-}
-
-void BL_SkinDeformer::BlenderDeformVerts()
-{
- float obmat[4][4]; // the original object matrix
- Object* par_arma = m_armobj->GetArmatureObject();
-
- // save matrix first
- copy_m4_m4(obmat, m_objMesh->obmat);
- // set reference matrix
- copy_m4_m4(m_objMesh->obmat, m_obmat);
-
- armature_deform_verts( par_arma, m_objMesh, NULL, m_transverts, NULL, m_bmesh->totvert, m_deformflags, NULL, NULL );
-
- // restore matrix
- copy_m4_m4(m_objMesh->obmat, obmat);
-
-#ifdef __NLA_DEFNORMALS
- if (m_recalcNormal)
- RecalcNormals();
-#endif
-}
-
-void BL_SkinDeformer::BGEDeformVerts()
-{
- Object *par_arma = m_armobj->GetArmatureObject();
- MDeformVert *dverts = m_bmesh->dvert;
- bDeformGroup *dg;
- int defbase_tot;
- Eigen::Matrix4f pre_mat, post_mat, chan_mat, norm_chan_mat;
-
- if (!dverts)
- return;
-
- defbase_tot = BLI_listbase_count(&m_objMesh->defbase);
-
- if (m_dfnrToPC == NULL)
- {
- m_dfnrToPC = new bPoseChannel*[defbase_tot];
- int i;
- for (i=0, dg=(bDeformGroup*)m_objMesh->defbase.first;
- dg;
- ++i, dg = dg->next)
- {
- m_dfnrToPC[i] = BKE_pose_channel_find_name(par_arma->pose, dg->name);
-
- if (m_dfnrToPC[i] && m_dfnrToPC[i]->bone->flag & BONE_NO_DEFORM)
- m_dfnrToPC[i] = NULL;
- }
- }
-
- post_mat = Eigen::Matrix4f::Map((float*)m_obmat).inverse() * Eigen::Matrix4f::Map((float*)m_armobj->GetArmatureObject()->obmat);
- pre_mat = post_mat.inverse();
-
- MDeformVert *dv= dverts;
- MDeformWeight *dw;
-
- for (int i=0; i<m_bmesh->totvert; ++i, dv++)
- {
- float contrib = 0.f, weight, max_weight=-1.f;
- bPoseChannel *pchan=NULL;
- Eigen::Map<Eigen::Vector3f> norm = Eigen::Vector3f::Map(m_transnors[i]);
- Eigen::Vector4f vec(0, 0, 0, 1);
- Eigen::Vector4f co(m_transverts[i][0],
- m_transverts[i][1],
- m_transverts[i][2],
- 1.f);
-
- if (!dv->totweight)
- continue;
-
- co = pre_mat * co;
-
- dw= dv->dw;
-
- for (unsigned int j= dv->totweight; j != 0; j--, dw++)
- {
- const int index = dw->def_nr;
-
- if (index < defbase_tot && (pchan=m_dfnrToPC[index]))
- {
- weight = dw->weight;
-
- if (weight)
- {
- chan_mat = Eigen::Matrix4f::Map((float*)pchan->chan_mat);
-
- // Update Vertex Position
- vec.noalias() += (chan_mat*co - co)*weight;
-
- // Save the most influential channel so we can use it to update the vertex normal
- if (weight > max_weight)
- {
- max_weight = weight;
- norm_chan_mat = chan_mat;
- }
-
- contrib += weight;
- }
- }
- }
-
- // Update Vertex Normal
- norm = norm_chan_mat.topLeftCorner<3, 3>()*norm;
-
- co.noalias() += vec/contrib;
- co[3] = 1.f; // Make sure we have a 1 for the w component!
-
- co = post_mat * co;
-
- m_transverts[i][0] = co[0];
- m_transverts[i][1] = co[1];
- m_transverts[i][2] = co[2];
- }
- m_copyNormals = true;
-}
-
-void BL_SkinDeformer::UpdateTransverts()
-{
- RAS_MeshSlot::iterator it;
- RAS_MeshMaterial *mmat;
- RAS_MeshSlot *slot;
- size_t i, nmat, imat;
-
- if (m_transverts) {
- // the vertex cache is unique to this deformer, no need to update it
- // if it wasn't updated! We must update all the materials at once
- // because we will not get here again for the other material
- nmat = m_pMeshObject->NumMaterials();
- for (imat=0; imat<nmat; imat++) {
- mmat = m_pMeshObject->GetMeshMaterial(imat);
- if (!mmat->m_slots[(void*)m_gameobj])
- continue;
-
- slot = *mmat->m_slots[(void*)m_gameobj];
-
- // for each array
- for (slot->begin(it); !slot->end(it); slot->next(it)) {
- // for each vertex
- // copy the untransformed data from the original mvert
- for (i=it.startvertex; i<it.endvertex; i++) {
- RAS_TexVert& v = it.vertex[i];
- v.SetXYZ(m_transverts[v.getOrigIndex()]);
- if (m_copyNormals)
- v.SetNormal(m_transnors[v.getOrigIndex()]);
- }
- }
- }
-
- if (m_copyNormals)
- m_copyNormals = false;
- }
-}
-
-bool BL_SkinDeformer::UpdateInternal(bool shape_applied)
-{
- /* See if the armature has been updated for this frame */
- if (PoseUpdated()) {
-
- if (!shape_applied) {
- /* store verts locally */
- VerifyStorage();
-
- /* duplicate */
- for (int v =0; v<m_bmesh->totvert; v++)
- {
- copy_v3_v3(m_transverts[v], m_bmesh->mvert[v].co);
- normal_short_to_float_v3(m_transnors[v], m_bmesh->mvert[v].no);
- }
- }
-
- m_armobj->ApplyPose();
-
- if (m_armobj->GetVertDeformType() == ARM_VDEF_BGE_CPU)
- BGEDeformVerts();
- else
- BlenderDeformVerts();
-
- /* Update the current frame */
- m_lastArmaUpdate=m_armobj->GetLastFrame();
-
- m_armobj->RestorePose();
- /* dynamic vertex, cannot use display list */
- m_bDynamic = true;
-
- UpdateTransverts();
-
- m_poseApplied = false;
-
- /* indicate that the m_transverts and normals are up to date */
- return true;
- }
-
- return false;
-}
-
-bool BL_SkinDeformer::Update(void)
-{
- return UpdateInternal(false);
-}
-
-/* XXX note: I propose to drop this function */
-void BL_SkinDeformer::SetArmature(BL_ArmatureObject *armobj)
-{
- // only used to set the object now
- m_armobj = armobj;
-}
diff --git a/source/gameengine/Converter/BL_SkinDeformer.h b/source/gameengine/Converter/BL_SkinDeformer.h
deleted file mode 100644
index 79043f60db8..00000000000
--- a/source/gameengine/Converter/BL_SkinDeformer.h
+++ /dev/null
@@ -1,125 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file BL_SkinDeformer.h
- * \ingroup bgeconv
- */
-
-#ifndef __BL_SKINDEFORMER_H__
-#define __BL_SKINDEFORMER_H__
-
-#ifdef _MSC_VER
-# pragma warning (disable:4786) /* get rid of stupid stl-visual compiler debug warning */
-#endif /* WIN32 */
-
-#include "CTR_HashedPtr.h"
-#include "BL_MeshDeformer.h"
-#include "BL_ArmatureObject.h"
-
-#include "DNA_mesh_types.h"
-#include "DNA_meshdata_types.h"
-#include "DNA_object_types.h"
-#include "BKE_armature.h"
-
-#include "RAS_Deformer.h"
-
-
-class BL_SkinDeformer : public BL_MeshDeformer
-{
-public:
-// void SetArmatureController (BL_ArmatureController *cont);
- virtual void Relink(CTR_Map<class CTR_HashedPtr, void*>*map);
- void SetArmature (class BL_ArmatureObject *armobj);
-
- BL_SkinDeformer(BL_DeformableGameObject *gameobj,
- struct Object *bmeshobj,
- class RAS_MeshObject *mesh,
- BL_ArmatureObject* arma = NULL);
-
- /* this second constructor is needed for making a mesh deformable on the fly. */
- BL_SkinDeformer(BL_DeformableGameObject *gameobj,
- struct Object *bmeshobj_old,
- struct Object *bmeshobj_new,
- class RAS_MeshObject *mesh,
- bool release_object,
- bool recalc_normal,
- BL_ArmatureObject* arma = NULL);
-
- virtual RAS_Deformer *GetReplica();
- virtual void ProcessReplica();
-
- virtual ~BL_SkinDeformer();
- bool Update (void);
- bool UpdateInternal (bool shape_applied);
- bool Apply (class RAS_IPolyMaterial *polymat);
- bool UpdateBuckets(void)
- {
- // update the deformer and all the mesh slots; Apply() does it well, so just call it.
- return Apply(NULL);
- }
- bool PoseUpdated(void)
- {
- if (m_armobj && m_lastArmaUpdate!=m_armobj->GetLastFrame()) {
- return true;
- }
- return false;
- }
-
- void ForceUpdate()
- {
- m_lastArmaUpdate = -1.0;
- };
- virtual bool ShareVertexArray()
- {
- return false;
- }
-
-protected:
- BL_ArmatureObject* m_armobj; // Our parent object
- float m_time;
- double m_lastArmaUpdate;
- //ListBase* m_defbase;
- float m_obmat[4][4]; // the reference matrix for skeleton deform
- bool m_releaseobject;
- bool m_poseApplied;
- bool m_recalcNormal;
- bool m_copyNormals; // dirty flag so we know if Apply() needs to copy normal information (used for BGEDeformVerts())
- struct bPoseChannel** m_dfnrToPC;
- short m_deformflags;
-
- void BlenderDeformVerts();
- void BGEDeformVerts();
-
- void UpdateTransverts();
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:BL_SkinDeformer")
-#endif
-};
-
-#endif /* __BL_SKINDEFORMER_H__ */
diff --git a/source/gameengine/Converter/CMakeLists.txt b/source/gameengine/Converter/CMakeLists.txt
deleted file mode 100644
index 7d6195e3c38..00000000000
--- a/source/gameengine/Converter/CMakeLists.txt
+++ /dev/null
@@ -1,123 +0,0 @@
-# ***** BEGIN GPL LICENSE BLOCK *****
-#
-# This program is free software; you can redistribute it and/or
-# modify it under the terms of the GNU General Public License
-# as published by the Free Software Foundation; either version 2
-# of the License, or (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software Foundation,
-# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
-#
-# The Original Code is Copyright (C) 2006, Blender Foundation
-# All rights reserved.
-#
-# The Original Code is: all of this file.
-#
-# Contributor(s): Jacques Beaurain.
-#
-# ***** END GPL LICENSE BLOCK *****
-
-set(INC
- .
- ../BlenderRoutines
- ../Expressions
- ../GameLogic
- ../Ketsji
- ../Ketsji/KXNetwork
- ../Network
- ../Network/LoopBackNetwork
- ../Physics/Bullet
- ../Physics/Dummy
- ../Physics/common
- ../Rasterizer
- ../Rasterizer/RAS_OpenGLRasterizer
- ../SceneGraph
- ../../blender
- ../../blender/blenkernel
- ../../blender/blenlib
- ../../blender/blenloader
- ../../blender/gpu
- ../../blender/ikplugin
- ../../blender/imbuf
- ../../blender/makesdna
- ../../blender/makesrna
- ../../blender/windowmanager
- ../../../intern/container
- ../../../intern/guardedalloc
- ../../../intern/string
-)
-
-set(INC_SYS
- ../../../intern/moto/include
- ../../../extern/recastnavigation/Detour/Include
- ${EIGEN3_INCLUDE_DIRS}
- ${PTHREADS_INCLUDE_DIRS}
- ${BOOST_INCLUDE_DIR}
-)
-
-set(SRC
- BL_ActionActuator.cpp
- BL_ArmatureActuator.cpp
- BL_ArmatureChannel.cpp
- BL_ArmatureConstraint.cpp
- BL_ArmatureObject.cpp
- BL_BlenderDataConversion.cpp
- BL_DeformableGameObject.cpp
- BL_MeshDeformer.cpp
- BL_ModifierDeformer.cpp
- BL_ShapeActionActuator.cpp
- BL_ShapeDeformer.cpp
- BL_SkinDeformer.cpp
- KX_BlenderScalarInterpolator.cpp
- KX_BlenderSceneConverter.cpp
- KX_ConvertActuators.cpp
- KX_ConvertControllers.cpp
- KX_ConvertProperties.cpp
- KX_ConvertSensors.cpp
- KX_LibLoadStatus.cpp
- KX_SoftBodyDeformer.cpp
-
- BL_ActionActuator.h
- BL_ArmatureActuator.h
- BL_ArmatureChannel.h
- BL_ArmatureConstraint.h
- BL_ArmatureObject.h
- BL_BlenderDataConversion.h
- BL_DeformableGameObject.h
- BL_MeshDeformer.h
- BL_ModifierDeformer.h
- BL_ShapeActionActuator.h
- BL_ShapeDeformer.h
- BL_SkinDeformer.h
- KX_BlenderScalarInterpolator.h
- KX_BlenderSceneConverter.h
- KX_ConvertActuators.h
- KX_ConvertControllers.h
- KX_ConvertProperties.h
- KX_ConvertSensors.h
- KX_LibLoadStatus.h
- KX_SoftBodyDeformer.h
-)
-
-if(WITH_BULLET)
- list(APPEND INC_SYS
- ${BULLET_INCLUDE_DIRS}
- )
- add_definitions(-DWITH_BULLET)
-endif()
-
-if(WITH_AUDASPACE)
- add_definitions(-DWITH_AUDASPACE)
-
- list(APPEND INC_SYS
- ${AUDASPACE_C_INCLUDE_DIRS}
- )
-endif()
-
-blender_add_lib(ge_converter "${SRC}" "${INC}" "${INC_SYS}")
diff --git a/source/gameengine/Converter/KX_BlenderScalarInterpolator.cpp b/source/gameengine/Converter/KX_BlenderScalarInterpolator.cpp
deleted file mode 100644
index 4d344cdf16a..00000000000
--- a/source/gameengine/Converter/KX_BlenderScalarInterpolator.cpp
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Converter/KX_BlenderScalarInterpolator.cpp
- * \ingroup bgeconv
- */
-
-
-#include "KX_BlenderScalarInterpolator.h"
-
-#include <cstring>
-
-extern "C" {
-#include "DNA_action_types.h"
-#include "DNA_anim_types.h"
-#include "BKE_fcurve.h"
-}
-
-float BL_ScalarInterpolator::GetValue(float currentTime) const
-{
- // XXX 2.4x IPO_GetFloatValue(m_blender_adt, m_channel, currentTime);
- return evaluate_fcurve(m_fcu, currentTime);
-}
-
-BL_InterpolatorList::BL_InterpolatorList(bAction *action)
-{
- if (action==NULL)
- return;
-
- for (FCurve *fcu = (FCurve *)action->curves.first; fcu; fcu = fcu->next) {
- if (fcu->rna_path) {
- BL_ScalarInterpolator *new_ipo = new BL_ScalarInterpolator(fcu);
- //assert(new_ipo);
- push_back(new_ipo);
- }
- }
-}
-
-BL_InterpolatorList::~BL_InterpolatorList()
-{
- BL_InterpolatorList::iterator i;
- for (i = begin(); !(i == end()); ++i) {
- delete *i;
- }
-}
-
-KX_IScalarInterpolator *BL_InterpolatorList::GetScalarInterpolator(const char *rna_path, int array_index)
-{
- for (BL_InterpolatorList::iterator i = begin(); (i != end()) ; i++ )
- {
- FCurve *fcu= (static_cast<BL_ScalarInterpolator *>(*i))->GetFCurve();
- if (array_index==fcu->array_index && strcmp(rna_path, fcu->rna_path)==0)
- return *i;
- }
- return NULL;
-}
-
diff --git a/source/gameengine/Converter/KX_BlenderScalarInterpolator.h b/source/gameengine/Converter/KX_BlenderScalarInterpolator.h
deleted file mode 100644
index d828910233f..00000000000
--- a/source/gameengine/Converter/KX_BlenderScalarInterpolator.h
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file KX_BlenderScalarInterpolator.h
- * \ingroup bgeconv
- */
-
-#ifndef __KX_BLENDERSCALARINTERPOLATOR_H__
-#define __KX_BLENDERSCALARINTERPOLATOR_H__
-
-#include <vector>
-
-#include "KX_IScalarInterpolator.h"
-
-typedef unsigned short BL_IpoChannel;
-
-class BL_ScalarInterpolator : public KX_IScalarInterpolator {
-public:
- BL_ScalarInterpolator() {} // required for use in STL list
- BL_ScalarInterpolator(struct FCurve* fcu) :
- m_fcu(fcu)
- {}
-
- virtual ~BL_ScalarInterpolator() {}
-
- virtual float GetValue(float currentTime) const;
- struct FCurve *GetFCurve() { return m_fcu; }
-
-private:
- struct FCurve *m_fcu;
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:BL_ScalarInterpolator")
-#endif
-};
-
-
-class BL_InterpolatorList : public std::vector<KX_IScalarInterpolator *> {
-public:
- BL_InterpolatorList(struct bAction *action);
- ~BL_InterpolatorList();
-
- KX_IScalarInterpolator *GetScalarInterpolator(const char *rna_path, int array_index);
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:BL_InterpolatorList")
-#endif
-};
-
-#endif /* __KX_BLENDERSCALARINTERPOLATOR_H__ */
diff --git a/source/gameengine/Converter/KX_BlenderSceneConverter.cpp b/source/gameengine/Converter/KX_BlenderSceneConverter.cpp
deleted file mode 100644
index 08b569fa4c2..00000000000
--- a/source/gameengine/Converter/KX_BlenderSceneConverter.cpp
+++ /dev/null
@@ -1,1477 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Converter/KX_BlenderSceneConverter.cpp
- * \ingroup bgeconv
- */
-
-#ifdef _MSC_VER
-# pragma warning (disable:4786) /* suppress stl-MSVC debug info warning */
-#endif
-
-#include "KX_Scene.h"
-#include "KX_GameObject.h"
-#include "KX_IpoConvert.h"
-#include "RAS_MeshObject.h"
-#include "KX_PhysicsEngineEnums.h"
-#include "PHY_IPhysicsEnvironment.h"
-#include "KX_KetsjiEngine.h"
-#include "KX_PythonInit.h" // So we can handle adding new text datablocks for Python to import
-#include "BL_Material.h"
-#include "BL_ActionActuator.h"
-#include "KX_BlenderMaterial.h"
-
-
-#include "BL_System.h"
-
-#include "DummyPhysicsEnvironment.h"
-
-
-#ifdef WITH_BULLET
-#include "CcdPhysicsEnvironment.h"
-#endif
-
-#include "KX_LibLoadStatus.h"
-#include "KX_BlenderScalarInterpolator.h"
-#include "BL_BlenderDataConversion.h"
-#include "KX_WorldInfo.h"
-
-/* This little block needed for linking to Blender... */
-#ifdef WIN32
-#include "BLI_winstuff.h"
-#endif
-
-/* This list includes only data type definitions */
-#include "DNA_scene_types.h"
-#include "DNA_world_types.h"
-#include "BKE_main.h"
-#include "BKE_fcurve.h"
-
-#include "BLI_math.h"
-
-extern "C"
-{
-#include "DNA_object_types.h"
-#include "DNA_curve_types.h"
-#include "DNA_mesh_types.h"
-#include "DNA_material_types.h"
-#include "BLI_blenlib.h"
-#include "MEM_guardedalloc.h"
-#include "BKE_global.h"
-#include "BKE_animsys.h"
-#include "BKE_library.h"
-#include "BKE_material.h" // BKE_material_copy
-#include "BKE_mesh.h" // BKE_mesh_copy
-#include "DNA_space_types.h"
-#include "DNA_anim_types.h"
-#include "DNA_action_types.h"
-#include "RNA_define.h"
-#include "../../blender/editors/include/ED_keyframing.h"
-}
-
-/* Only for dynamic loading and merging */
-#include "RAS_BucketManager.h" // XXX cant stay
-#include "KX_BlenderSceneConverter.h"
-#include "KX_MeshProxy.h"
-extern "C" {
- #include "PIL_time.h"
- #include "BKE_context.h"
- #include "BLO_readfile.h"
- #include "BKE_idcode.h"
- #include "BKE_report.h"
- #include "DNA_space_types.h"
- #include "DNA_windowmanager_types.h" /* report api */
- #include "../../blender/blenlib/BLI_linklist.h"
-}
-
-#include "BLI_task.h"
-
-// This is used to avoid including BLI_task.h in KX_BlenderSceneConverter.h
-typedef struct ThreadInfo {
- TaskPool *m_pool;
- ThreadMutex m_mutex;
-} ThreadInfo;
-
-KX_BlenderSceneConverter::KX_BlenderSceneConverter(
- Main *maggie,
- KX_KetsjiEngine *engine)
- :m_maggie(maggie),
- m_ketsjiEngine(engine),
- m_alwaysUseExpandFraming(false),
- m_usemat(false),
- m_useglslmat(false),
- m_use_mat_cache(true)
-{
- BKE_main_id_tag_all(maggie, LIB_TAG_DOIT, false); /* avoid re-tagging later on */
- m_newfilename = "";
- m_threadinfo = new ThreadInfo();
- m_threadinfo->m_pool = BLI_task_pool_create(engine->GetTaskScheduler(), NULL);
- BLI_mutex_init(&m_threadinfo->m_mutex);
-}
-
-KX_BlenderSceneConverter::~KX_BlenderSceneConverter()
-{
- // clears meshes, and hashmaps from blender to gameengine data
- // delete sumoshapes
-
- int numAdtLists = m_map_blender_to_gameAdtList.size();
- for (int i = 0; i < numAdtLists; i++) {
- BL_InterpolatorList *adtList = *m_map_blender_to_gameAdtList.at(i);
-
- delete (adtList);
- }
-
- vector<pair<KX_Scene *, KX_WorldInfo *> >::iterator itw = m_worldinfos.begin();
- while (itw != m_worldinfos.end()) {
- delete itw->second;
- itw++;
- }
- m_worldinfos.clear();
-
- vector<pair<KX_Scene *,RAS_IPolyMaterial *> >::iterator itp = m_polymaterials.begin();
- while (itp != m_polymaterials.end()) {
- delete itp->second;
- itp++;
- }
- m_polymaterials.clear();
-
- // delete after RAS_IPolyMaterial
- vector<pair<KX_Scene *,BL_Material *> >::iterator itmat = m_materials.begin();
- while (itmat != m_materials.end()) {
- delete itmat->second;
- itmat++;
- }
- m_materials.clear();
-
- vector<pair<KX_Scene *,RAS_MeshObject *> >::iterator itm = m_meshobjects.begin();
- while (itm != m_meshobjects.end()) {
- delete itm->second;
- itm++;
- }
- m_meshobjects.clear();
-
- /* free any data that was dynamically loaded */
- while (m_DynamicMaggie.size() != 0) {
- FreeBlendFile(m_DynamicMaggie[0]);
- }
-
- m_DynamicMaggie.clear();
-
- if (m_threadinfo) {
- /* Thread infos like mutex must be freed after FreeBlendFile function.
- Because it needs to lock the mutex, even if there's no active task when it's
- in the scene converter destructor. */
- BLI_task_pool_free(m_threadinfo->m_pool);
- BLI_mutex_end(&m_threadinfo->m_mutex);
- delete m_threadinfo;
- }
-}
-
-void KX_BlenderSceneConverter::SetNewFileName(const STR_String &filename)
-{
- m_newfilename = filename;
-}
-
-bool KX_BlenderSceneConverter::TryAndLoadNewFile()
-{
- bool result = false;
-
- return result;
-}
-
-Scene *KX_BlenderSceneConverter::GetBlenderSceneForName(const STR_String &name)
-{
- Scene *sce;
-
- /**
- * Find the specified scene by name, or NULL if nothing matches.
- */
- if ((sce = (Scene *)BLI_findstring(&m_maggie->scene, name.ReadPtr(), offsetof(ID, name) + 2)))
- return sce;
-
- for (vector<Main *>::iterator it=m_DynamicMaggie.begin(); !(it == m_DynamicMaggie.end()); it++) {
- Main *main = *it;
-
- if ((sce= (Scene *)BLI_findstring(&main->scene, name.ReadPtr(), offsetof(ID, name) + 2)))
- return sce;
- }
-
- return NULL;
-}
-
-void KX_BlenderSceneConverter::ConvertScene(KX_Scene *destinationscene, RAS_IRasterizer *rendertools,
- RAS_ICanvas *canvas, bool libloading)
-{
- //find out which physics engine
- Scene *blenderscene = destinationscene->GetBlenderScene();
-
- PHY_IPhysicsEnvironment *phy_env = NULL;
-
- e_PhysicsEngine physics_engine = UseBullet;
- // hook for registration function during conversion.
- m_currentScene = destinationscene;
- destinationscene->SetSceneConverter(this);
-
- // This doesn't really seem to do anything except cause potential issues
- // when doing threaded conversion, so it's disabled for now.
- // SG_SetActiveStage(SG_STAGE_CONVERTER);
-
- switch (blenderscene->gm.physicsEngine) {
-#ifdef WITH_BULLET
- case WOPHY_BULLET:
- {
- SYS_SystemHandle syshandle = SYS_GetSystem(); /*unused*/
- int visualizePhysics = SYS_GetCommandLineInt(syshandle, "show_physics", 0);
-
- phy_env = CcdPhysicsEnvironment::Create(blenderscene, visualizePhysics);
- physics_engine = UseBullet;
- break;
- }
-#endif
- default:
- case WOPHY_NONE:
- {
- // We should probably use some sort of factory here
- phy_env = new DummyPhysicsEnvironment();
- physics_engine = UseNone;
- break;
- }
- }
-
- destinationscene->SetPhysicsEnvironment(phy_env);
-
- BL_ConvertBlenderObjects(
- m_maggie,
- destinationscene,
- m_ketsjiEngine,
- physics_engine,
- rendertools,
- canvas,
- this,
- m_alwaysUseExpandFraming,
- libloading);
-
- //These lookup are not needed during game
- m_map_blender_to_gameactuator.clear();
- m_map_blender_to_gamecontroller.clear();
- m_map_blender_to_gameobject.clear();
-
- //Clearing this lookup table has the effect of disabling the cache of meshes
- //between scenes, even if they are shared in the blend file.
- //This cache mecanism is buggy so I leave it disable and the memory leak
- //that would result from this is fixed in RemoveScene()
- m_map_mesh_to_gamemesh.clear();
-}
-
-// This function removes all entities stored in the converter for that scene
-// It should be used instead of direct delete scene
-// Note that there was some provision for sharing entities (meshes...) between
-// scenes but that is now disabled so all scene will have their own copy
-// and we can delete them here. If the sharing is reactivated, change this code too..
-// (see KX_BlenderSceneConverter::ConvertScene)
-void KX_BlenderSceneConverter::RemoveScene(KX_Scene *scene)
-{
- int i, size;
- // delete the scene first as it will stop the use of entities
- delete scene;
- // delete the entities of this scene
- vector<pair<KX_Scene *, KX_WorldInfo *> >::iterator worldit;
- size = m_worldinfos.size();
- for (i = 0, worldit = m_worldinfos.begin(); i < size; ) {
- if (worldit->first == scene) {
- delete worldit->second;
- *worldit = m_worldinfos.back();
- m_worldinfos.pop_back();
- size--;
- }
- else {
- i++;
- worldit++;
- }
- }
-
- vector<pair<KX_Scene *, RAS_IPolyMaterial *> >::iterator polymit;
- size = m_polymaterials.size();
- for (i = 0, polymit = m_polymaterials.begin(); i < size; ) {
- if (polymit->first == scene) {
- m_polymat_cache[scene].erase(polymit->second->GetBlenderMaterial());
- delete polymit->second;
- *polymit = m_polymaterials.back();
- m_polymaterials.pop_back();
- size--;
- }
- else {
- i++;
- polymit++;
- }
- }
-
- m_polymat_cache.erase(scene);
-
- vector<pair<KX_Scene *, BL_Material *> >::iterator matit;
- size = m_materials.size();
- for (i = 0, matit = m_materials.begin(); i < size; ) {
- if (matit->first == scene) {
- m_mat_cache[scene].erase(matit->second->material);
- delete matit->second;
- *matit = m_materials.back();
- m_materials.pop_back();
- size--;
- }
- else {
- i++;
- matit++;
- }
- }
-
- m_mat_cache.erase(scene);
-
- vector<pair<KX_Scene *, RAS_MeshObject *> >::iterator meshit;
- size = m_meshobjects.size();
- for (i = 0, meshit = m_meshobjects.begin(); i < size; ) {
- if (meshit->first == scene) {
- delete meshit->second;
- *meshit = m_meshobjects.back();
- m_meshobjects.pop_back();
- size--;
- }
- else {
- i++;
- meshit++;
- }
- }
-}
-
-// use blender materials
-void KX_BlenderSceneConverter::SetMaterials(bool val)
-{
- m_usemat = val;
- m_useglslmat = false;
-}
-
-void KX_BlenderSceneConverter::SetGLSLMaterials(bool val)
-{
- m_usemat = val;
- m_useglslmat = val;
-}
-
-void KX_BlenderSceneConverter::SetCacheMaterials(bool val)
-{
- m_use_mat_cache = val;
-}
-
-bool KX_BlenderSceneConverter::GetMaterials()
-{
- return m_usemat;
-}
-
-bool KX_BlenderSceneConverter::GetGLSLMaterials()
-{
- return m_useglslmat;
-}
-
-bool KX_BlenderSceneConverter::GetCacheMaterials()
-{
- return m_use_mat_cache;
-}
-
-void KX_BlenderSceneConverter::RegisterBlenderMaterial(BL_Material *mat)
-{
- // First make sure we don't register the material twice
- vector<pair<KX_Scene *, BL_Material *> >::iterator it;
- for (it = m_materials.begin(); it != m_materials.end(); ++it)
- if (it->second == mat)
- return;
-
- m_materials.push_back(pair<KX_Scene *, BL_Material *> (m_currentScene, mat));
-}
-
-void KX_BlenderSceneConverter::SetAlwaysUseExpandFraming(bool to_what)
-{
- m_alwaysUseExpandFraming= to_what;
-}
-
-void KX_BlenderSceneConverter::RegisterGameObject(KX_GameObject *gameobject, Object *for_blenderobject)
-{
- /* only maintained while converting, freed during game runtime */
- m_map_blender_to_gameobject.insert(CHashedPtr(for_blenderobject), gameobject);
-}
-
-/* only need to run this during conversion since
- * m_map_blender_to_gameobject is freed after conversion */
-void KX_BlenderSceneConverter::UnregisterGameObject(KX_GameObject *gameobject)
-{
- Object *bobp = gameobject->GetBlenderObject();
- if (bobp) {
- CHashedPtr bptr(bobp);
- KX_GameObject **gobp = m_map_blender_to_gameobject[bptr];
- if (gobp && *gobp == gameobject) {
- // also maintain m_map_blender_to_gameobject if the gameobject
- // being removed is matching the blender object
- m_map_blender_to_gameobject.remove(bptr);
- }
- }
-}
-
-KX_GameObject *KX_BlenderSceneConverter::FindGameObject(Object *for_blenderobject)
-{
- KX_GameObject **obp = m_map_blender_to_gameobject[CHashedPtr(for_blenderobject)];
-
- return obp ? *obp : NULL;
-}
-
-void KX_BlenderSceneConverter::RegisterGameMesh(RAS_MeshObject *gamemesh, Mesh *for_blendermesh)
-{
- if (for_blendermesh) { /* dynamically loaded meshes we don't want to keep lookups for */
- m_map_mesh_to_gamemesh.insert(CHashedPtr(for_blendermesh),gamemesh);
- }
- m_meshobjects.push_back(pair<KX_Scene *, RAS_MeshObject *> (m_currentScene,gamemesh));
-}
-
-RAS_MeshObject *KX_BlenderSceneConverter::FindGameMesh(Mesh *for_blendermesh)
-{
- RAS_MeshObject **meshp = m_map_mesh_to_gamemesh[CHashedPtr(for_blendermesh)];
-
- if (meshp) {
- return *meshp;
- }
- else {
- return NULL;
- }
-}
-
-void KX_BlenderSceneConverter::RegisterPolyMaterial(RAS_IPolyMaterial *polymat)
-{
- // First make sure we don't register the material twice
- vector<pair<KX_Scene *, RAS_IPolyMaterial *> >::iterator it;
- for (it = m_polymaterials.begin(); it != m_polymaterials.end(); ++it)
- if (it->second == polymat)
- return;
- m_polymaterials.push_back(pair<KX_Scene *, RAS_IPolyMaterial *> (m_currentScene, polymat));
-}
-
-void KX_BlenderSceneConverter::CachePolyMaterial(KX_Scene *scene, Material *mat, RAS_IPolyMaterial *polymat)
-{
- if (m_use_mat_cache && mat)
- m_polymat_cache[scene][mat] = polymat;
-}
-
-RAS_IPolyMaterial *KX_BlenderSceneConverter::FindCachedPolyMaterial(KX_Scene *scene, Material *mat)
-{
- return (m_use_mat_cache) ? m_polymat_cache[scene][mat] : NULL;
-}
-
-void KX_BlenderSceneConverter::CacheBlenderMaterial(KX_Scene *scene, Material *mat, BL_Material *blmat)
-{
- if (m_use_mat_cache && mat)
- m_mat_cache[scene][mat] = blmat;
-}
-
-BL_Material *KX_BlenderSceneConverter::FindCachedBlenderMaterial(KX_Scene *scene, Material *mat)
-{
- return (m_use_mat_cache) ? m_mat_cache[scene][mat] : NULL;
-}
-
-void KX_BlenderSceneConverter::RegisterInterpolatorList(BL_InterpolatorList *actList, bAction *for_act)
-{
- m_map_blender_to_gameAdtList.insert(CHashedPtr(for_act), actList);
-}
-
-BL_InterpolatorList *KX_BlenderSceneConverter::FindInterpolatorList(bAction *for_act)
-{
- BL_InterpolatorList **listp = m_map_blender_to_gameAdtList[CHashedPtr(for_act)];
- return listp ? *listp : NULL;
-}
-
-void KX_BlenderSceneConverter::RegisterGameActuator(SCA_IActuator *act, bActuator *for_actuator)
-{
- m_map_blender_to_gameactuator.insert(CHashedPtr(for_actuator), act);
-}
-
-SCA_IActuator *KX_BlenderSceneConverter::FindGameActuator(bActuator *for_actuator)
-{
- SCA_IActuator **actp = m_map_blender_to_gameactuator[CHashedPtr(for_actuator)];
- return actp ? *actp : NULL;
-}
-
-void KX_BlenderSceneConverter::RegisterGameController(SCA_IController *cont, bController *for_controller)
-{
- m_map_blender_to_gamecontroller.insert(CHashedPtr(for_controller), cont);
-}
-
-SCA_IController *KX_BlenderSceneConverter::FindGameController(bController *for_controller)
-{
- SCA_IController **contp = m_map_blender_to_gamecontroller[CHashedPtr(for_controller)];
- return contp ? *contp : NULL;
-}
-
-void KX_BlenderSceneConverter::RegisterWorldInfo(KX_WorldInfo *worldinfo)
-{
- m_worldinfos.push_back(pair<KX_Scene *, KX_WorldInfo *> (m_currentScene, worldinfo));
-}
-
-void KX_BlenderSceneConverter::ResetPhysicsObjectsAnimationIpo(bool clearIpo)
-{
- //TODO this entire function is deprecated, written for 2.4x
- //the functionality should be rewritten, currently it does nothing
-
- KX_SceneList *scenes = m_ketsjiEngine->CurrentScenes();
- int numScenes = scenes->size();
- int i;
- for (i = 0; i < numScenes; i++) {
- KX_Scene *scene = scenes->at(i);
- CListValue *parentList = scene->GetRootParentList();
- int numObjects = parentList->GetCount();
- int g;
- for (g = 0; g < numObjects; g++) {
- KX_GameObject *gameObj = (KX_GameObject *)parentList->GetValue(g);
- if (gameObj->IsRecordAnimation()) {
- Object *blenderObject = gameObj->GetBlenderObject();
- if (blenderObject) {
-#if 0
- //erase existing ipo's
- Ipo* ipo = blenderObject->ipo;//findIpoForName(blenderObject->id.name+2);
- if (ipo) { //clear the curve data
- if (clearIpo) {//rcruiz
- IpoCurve *icu1;
-
- int numCurves = 0;
- for ( icu1 = (IpoCurve*)ipo->curve.first; icu1; ) {
-
- IpoCurve* tmpicu = icu1;
-
- /*int i;
- BezTriple *bezt;
- for ( bezt = tmpicu->bezt, i = 0; i < tmpicu->totvert; i++, bezt++) {
- printf("(%f,%f,%f),(%f,%f,%f),(%f,%f,%f)\n",bezt->vec[0][0],bezt->vec[0][1],bezt->vec[0][2],bezt->vec[1][0],bezt->vec[1][1],bezt->vec[1][2],bezt->vec[2][0],bezt->vec[2][1],bezt->vec[2][2]);
- }*/
-
- icu1 = icu1->next;
- numCurves++;
-
- BLI_remlink( &( blenderObject->ipo->curve ), tmpicu );
- if ( tmpicu->bezt )
- MEM_freeN( tmpicu->bezt );
- MEM_freeN( tmpicu );
- localDel_ipoCurve( tmpicu );
- }
- }
- }
- else {
- ipo = NULL; // XXX add_ipo(blenderObject->id.name+2, ID_OB);
- blenderObject->ipo = ipo;
- }
-#endif
- }
- }
- }
- }
-}
-
-void KX_BlenderSceneConverter::resetNoneDynamicObjectToIpo()
-{
- //TODO the functionality should be rewritten
-}
-
-// this generates ipo curves for position, rotation, allowing to use game physics in animation
-void KX_BlenderSceneConverter::WritePhysicsObjectToAnimationIpo(int frameNumber)
-{
- KX_SceneList *scenes = m_ketsjiEngine->CurrentScenes();
- int numScenes = scenes->size();
- int i;
- for (i = 0; i < numScenes; i++) {
- KX_Scene *scene = scenes->at(i);
- //PHY_IPhysicsEnvironment* physEnv = scene->GetPhysicsEnvironment();
- CListValue *parentList = scene->GetObjectList();
- int numObjects = parentList->GetCount();
- int g;
- for (g = 0; g < numObjects; g++) {
- KX_GameObject *gameObj = (KX_GameObject *)parentList->GetValue(g);
- Object *blenderObject = gameObj->GetBlenderObject();
- if (blenderObject && blenderObject->parent == NULL && gameObj->IsRecordAnimation()) {
- if (blenderObject->adt == NULL)
- BKE_animdata_add_id(&blenderObject->id);
-
- if (blenderObject->adt) {
- const MT_Point3 &position = gameObj->NodeGetWorldPosition();
- //const MT_Vector3& scale = gameObj->NodeGetWorldScaling();
- const MT_Matrix3x3 &orn = gameObj->NodeGetWorldOrientation();
-
- position.getValue(blenderObject->loc);
-
- float tmat[3][3];
- for (int r = 0; r < 3; r++)
- for (int c = 0; c < 3; c++)
- tmat[r][c] = (float)orn[c][r];
-
- mat3_to_compatible_eul(blenderObject->rot, blenderObject->rot, tmat);
-
- insert_keyframe(NULL, &blenderObject->id, NULL, NULL, "location", -1, (float)frameNumber, BEZT_KEYTYPE_JITTER, INSERTKEY_FAST);
- insert_keyframe(NULL, &blenderObject->id, NULL, NULL, "rotation_euler", -1, (float)frameNumber, BEZT_KEYTYPE_JITTER, INSERTKEY_FAST);
-
-#if 0
- const MT_Point3& position = gameObj->NodeGetWorldPosition();
- //const MT_Vector3& scale = gameObj->NodeGetWorldScaling();
- const MT_Matrix3x3& orn = gameObj->NodeGetWorldOrientation();
-
- float eulerAngles[3];
- float eulerAnglesOld[3] = {0.0f, 0.0f, 0.0f};
- float tmat[3][3];
-
- // XXX animato
- Ipo* ipo = blenderObject->ipo;
-
- //create the curves, if not existing, set linear if new
-
- IpoCurve *icu_lx = findIpoCurve((IpoCurve *)ipo->curve.first,"LocX");
- if (!icu_lx) {
- icu_lx = verify_ipocurve(&blenderObject->id, ipo->blocktype, NULL, NULL, NULL, OB_LOC_X, 1);
- if (icu_lx) icu_lx->ipo = IPO_LIN;
- }
- IpoCurve *icu_ly = findIpoCurve((IpoCurve *)ipo->curve.first,"LocY");
- if (!icu_ly) {
- icu_ly = verify_ipocurve(&blenderObject->id, ipo->blocktype, NULL, NULL, NULL, OB_LOC_Y, 1);
- if (icu_ly) icu_ly->ipo = IPO_LIN;
- }
- IpoCurve *icu_lz = findIpoCurve((IpoCurve *)ipo->curve.first,"LocZ");
- if (!icu_lz) {
- icu_lz = verify_ipocurve(&blenderObject->id, ipo->blocktype, NULL, NULL, NULL, OB_LOC_Z, 1);
- if (icu_lz) icu_lz->ipo = IPO_LIN;
- }
- IpoCurve *icu_rx = findIpoCurve((IpoCurve *)ipo->curve.first,"RotX");
- if (!icu_rx) {
- icu_rx = verify_ipocurve(&blenderObject->id, ipo->blocktype, NULL, NULL, NULL, OB_ROT_X, 1);
- if (icu_rx) icu_rx->ipo = IPO_LIN;
- }
- IpoCurve *icu_ry = findIpoCurve((IpoCurve *)ipo->curve.first,"RotY");
- if (!icu_ry) {
- icu_ry = verify_ipocurve(&blenderObject->id, ipo->blocktype, NULL, NULL, NULL, OB_ROT_Y, 1);
- if (icu_ry) icu_ry->ipo = IPO_LIN;
- }
- IpoCurve *icu_rz = findIpoCurve((IpoCurve *)ipo->curve.first,"RotZ");
- if (!icu_rz) {
- icu_rz = verify_ipocurve(&blenderObject->id, ipo->blocktype, NULL, NULL, NULL, OB_ROT_Z, 1);
- if (icu_rz) icu_rz->ipo = IPO_LIN;
- }
-
- if (icu_rx) eulerAnglesOld[0] = eval_icu( icu_rx, frameNumber - 1 ) / ((180 / 3.14159265f) / 10);
- if (icu_ry) eulerAnglesOld[1] = eval_icu( icu_ry, frameNumber - 1 ) / ((180 / 3.14159265f) / 10);
- if (icu_rz) eulerAnglesOld[2] = eval_icu( icu_rz, frameNumber - 1 ) / ((180 / 3.14159265f) / 10);
-
- // orn.getValue((float *)tmat); // uses the wrong ordering, cant use this
- for (int r = 0; r < 3; r++)
- for (int c = 0; c < 3; c++)
- tmat[r][c] = orn[c][r];
-
- // mat3_to_eul( eulerAngles,tmat); // better to use Mat3ToCompatibleEul
- mat3_to_compatible_eul( eulerAngles, eulerAnglesOld,tmat);
-
- //eval_icu
- for (int x = 0; x < 3; x++)
- eulerAngles[x] *= (float) ((180 / 3.14159265f) / 10.0);
-
- //fill the curves with data
- if (icu_lx) insert_vert_icu(icu_lx, frameNumber, position.x(), 1);
- if (icu_ly) insert_vert_icu(icu_ly, frameNumber, position.y(), 1);
- if (icu_lz) insert_vert_icu(icu_lz, frameNumber, position.z(), 1);
- if (icu_rx) insert_vert_icu(icu_rx, frameNumber, eulerAngles[0], 1);
- if (icu_ry) insert_vert_icu(icu_ry, frameNumber, eulerAngles[1], 1);
- if (icu_rz) insert_vert_icu(icu_rz, frameNumber, eulerAngles[2], 1);
-
- // Handles are corrected at the end, testhandles_ipocurve isn't needed yet
-#endif
- }
- }
- }
- }
-}
-
-void KX_BlenderSceneConverter::TestHandlesPhysicsObjectToAnimationIpo()
-{
- KX_SceneList *scenes = m_ketsjiEngine->CurrentScenes();
- int numScenes = scenes->size();
- int i;
- for (i = 0; i < numScenes; i++) {
- KX_Scene *scene = scenes->at(i);
- //PHY_IPhysicsEnvironment* physEnv = scene->GetPhysicsEnvironment();
- CListValue *parentList = scene->GetRootParentList();
- int numObjects = parentList->GetCount();
- int g;
- for (g = 0; g < numObjects; g++) {
- KX_GameObject *gameObj = (KX_GameObject *)parentList->GetValue(g);
- if (gameObj->IsRecordAnimation()) {
- Object *blenderObject = gameObj->GetBlenderObject();
- if (blenderObject && blenderObject->adt) {
- bAction *act = verify_adt_action(&blenderObject->id, false);
- FCurve *fcu;
-
- if (!act) {
- continue;
- }
-
- /* for now, not much choice but to run this on all curves... */
- for (fcu = (FCurve *)act->curves.first; fcu; fcu = fcu->next) {
- /* Note: calling `sort_time_fcurve()` here is not needed, since
- * all keys have been added in 'right' order. */
- calchandles_fcurve(fcu);
- }
-#if 0
- // XXX animato
- Ipo* ipo = blenderObject->ipo;
-
- //create the curves, if not existing
- //testhandles_ipocurve checks for NULL
- testhandles_ipocurve(findIpoCurve((IpoCurve *)ipo->curve.first,"LocX"));
- testhandles_ipocurve(findIpoCurve((IpoCurve *)ipo->curve.first,"LocY"));
- testhandles_ipocurve(findIpoCurve((IpoCurve *)ipo->curve.first,"LocZ"));
- testhandles_ipocurve(findIpoCurve((IpoCurve *)ipo->curve.first,"RotX"));
- testhandles_ipocurve(findIpoCurve((IpoCurve *)ipo->curve.first,"RotY"));
- testhandles_ipocurve(findIpoCurve((IpoCurve *)ipo->curve.first,"RotZ"));
-#endif
- }
- }
- }
- }
-}
-
-#ifdef WITH_PYTHON
-PyObject *KX_BlenderSceneConverter::GetPyNamespace()
-{
- return m_ketsjiEngine->GetPyNamespace();
-}
-#endif
-
-vector<Main *> &KX_BlenderSceneConverter::GetMainDynamic()
-{
- return m_DynamicMaggie;
-}
-
-Main *KX_BlenderSceneConverter::GetMainDynamicPath(const char *path)
-{
- for (vector<Main *>::iterator it = m_DynamicMaggie.begin(); !(it == m_DynamicMaggie.end()); it++)
- if (BLI_path_cmp((*it)->name, path) == 0)
- return *it;
-
- return NULL;
-}
-
-void KX_BlenderSceneConverter::MergeAsyncLoads()
-{
- vector<KX_Scene *> *merge_scenes;
-
- vector<KX_LibLoadStatus *>::iterator mit;
- vector<KX_Scene *>::iterator sit;
-
- BLI_mutex_lock(&m_threadinfo->m_mutex);
-
- for (mit = m_mergequeue.begin(); mit != m_mergequeue.end(); ++mit) {
- merge_scenes = (vector<KX_Scene *> *)(*mit)->GetData();
-
- for (sit=merge_scenes->begin(); sit!=merge_scenes->end(); ++sit) {
- (*mit)->GetMergeScene()->MergeScene(*sit);
- delete (*sit);
- }
-
- delete merge_scenes;
- (*mit)->SetData(NULL);
-
- (*mit)->Finish();
- }
-
- m_mergequeue.clear();
-
- BLI_mutex_unlock(&m_threadinfo->m_mutex);
-}
-
-void KX_BlenderSceneConverter::FinalizeAsyncLoads()
-{
- // Finish all loading libraries.
- if (m_threadinfo) {
- BLI_task_pool_work_and_wait(m_threadinfo->m_pool);
- }
- // Merge all libraries data in the current scene, to avoid memory leak of unmerged scenes.
- MergeAsyncLoads();
-}
-
-void KX_BlenderSceneConverter::AddScenesToMergeQueue(KX_LibLoadStatus *status)
-{
- BLI_mutex_lock(&m_threadinfo->m_mutex);
- m_mergequeue.push_back(status);
- BLI_mutex_unlock(&m_threadinfo->m_mutex);
-}
-
-static void async_convert(TaskPool *pool, void *ptr, int UNUSED(threadid))
-{
- KX_Scene *new_scene = NULL;
- KX_LibLoadStatus *status = (KX_LibLoadStatus *)ptr;
- vector<Scene *> *scenes = (vector<Scene *> *)status->GetData();
- vector<KX_Scene *> *merge_scenes = new vector<KX_Scene *>(); // Deleted in MergeAsyncLoads
-
- for (unsigned int i = 0; i < scenes->size(); ++i) {
- new_scene = status->GetEngine()->CreateScene((*scenes)[i], true);
-
- if (new_scene)
- merge_scenes->push_back(new_scene);
-
- status->AddProgress((1.0f / scenes->size()) * 0.9f); // We'll call conversion 90% and merging 10% for now
- }
-
- delete scenes;
- status->SetData(merge_scenes);
-
- status->GetConverter()->AddScenesToMergeQueue(status);
-}
-
-KX_LibLoadStatus *KX_BlenderSceneConverter::LinkBlendFileMemory(void *data, int length, const char *path, char *group, KX_Scene *scene_merge, char **err_str, short options)
-{
- BlendHandle *bpy_openlib = BLO_blendhandle_from_memory(data, length);
-
- // Error checking is done in LinkBlendFile
- return LinkBlendFile(bpy_openlib, path, group, scene_merge, err_str, options);
-}
-
-KX_LibLoadStatus *KX_BlenderSceneConverter::LinkBlendFilePath(const char *filepath, char *group, KX_Scene *scene_merge, char **err_str, short options)
-{
- BlendHandle *bpy_openlib = BLO_blendhandle_from_file(filepath, NULL);
-
- // Error checking is done in LinkBlendFile
- return LinkBlendFile(bpy_openlib, filepath, group, scene_merge, err_str, options);
-}
-
-static void load_datablocks(Main *main_tmp, BlendHandle *bpy_openlib, const char *path, int idcode)
-{
- LinkNode *names = NULL;
-
- int totnames_dummy;
- names = BLO_blendhandle_get_datablock_names(bpy_openlib, idcode, &totnames_dummy);
-
- int i = 0;
- LinkNode *n = names;
- while (n) {
- BLO_library_link_named_part(main_tmp, &bpy_openlib, idcode, (char *)n->link);
- n = (LinkNode *)n->next;
- i++;
- }
- BLI_linklist_free(names, free); /* free linklist *and* each node's data */
-}
-
-KX_LibLoadStatus *KX_BlenderSceneConverter::LinkBlendFile(BlendHandle *bpy_openlib, const char *path, char *group, KX_Scene *scene_merge, char **err_str, short options)
-{
- Main *main_newlib; /* stored as a dynamic 'main' until we free it */
- const int idcode = BKE_idcode_from_name(group);
- ReportList reports;
- static char err_local[255];
-
-// TIMEIT_START(bge_link_blend_file);
-
- KX_LibLoadStatus *status;
-
- /* only scene and mesh supported right now */
- if (idcode != ID_SCE && idcode != ID_ME && idcode != ID_AC) {
- snprintf(err_local, sizeof(err_local), "invalid ID type given \"%s\"\n", group);
- *err_str = err_local;
- BLO_blendhandle_close(bpy_openlib);
- return NULL;
- }
-
- if (GetMainDynamicPath(path)) {
- snprintf(err_local, sizeof(err_local), "blend file already open \"%s\"\n", path);
- *err_str = err_local;
- BLO_blendhandle_close(bpy_openlib);
- return NULL;
- }
-
- if (bpy_openlib == NULL) {
- snprintf(err_local, sizeof(err_local), "could not open blendfile \"%s\"\n", path);
- *err_str = err_local;
- return NULL;
- }
-
- main_newlib = BKE_main_new();
- BKE_reports_init(&reports, RPT_STORE);
-
- short flag = 0; /* don't need any special options */
- /* created only for linking, then freed */
- Main *main_tmp = BLO_library_link_begin(main_newlib, &bpy_openlib, (char *)path);
-
- load_datablocks(main_tmp, bpy_openlib, path, idcode);
-
- if (idcode == ID_SCE && options & LIB_LOAD_LOAD_SCRIPTS) {
- load_datablocks(main_tmp, bpy_openlib, path, ID_TXT);
- }
-
- /* now do another round of linking for Scenes so all actions are properly loaded */
- if (idcode == ID_SCE && options & LIB_LOAD_LOAD_ACTIONS) {
- load_datablocks(main_tmp, bpy_openlib, path, ID_AC);
- }
-
- BLO_library_link_end(main_tmp, &bpy_openlib, flag, NULL, NULL);
-
- BLO_blendhandle_close(bpy_openlib);
-
- BKE_reports_clear(&reports);
- /* done linking */
-
- /* needed for lookups*/
- GetMainDynamic().push_back(main_newlib);
- BLI_strncpy(main_newlib->name, path, sizeof(main_newlib->name));
-
-
- status = new KX_LibLoadStatus(this, m_ketsjiEngine, scene_merge, path);
-
- if (idcode == ID_ME) {
- /* Convert all new meshes into BGE meshes */
- ID *mesh;
-
- for (mesh = (ID *)main_newlib->mesh.first; mesh; mesh = (ID *)mesh->next ) {
- if (options & LIB_LOAD_VERBOSE)
- printf("MeshName: %s\n", mesh->name + 2);
- RAS_MeshObject *meshobj = BL_ConvertMesh((Mesh *)mesh, NULL, scene_merge, this, false); // For now only use the libloading option for scenes, which need to handle materials/shaders
- scene_merge->GetLogicManager()->RegisterMeshName(meshobj->GetName(), meshobj);
- }
- }
- else if (idcode == ID_AC) {
- /* Convert all actions */
- ID *action;
-
- for (action= (ID *)main_newlib->action.first; action; action = (ID *)action->next) {
- if (options & LIB_LOAD_VERBOSE)
- printf("ActionName: %s\n", action->name + 2);
- scene_merge->GetLogicManager()->RegisterActionName(action->name + 2, action);
- }
- }
- else if (idcode == ID_SCE) {
- /* Merge all new linked in scene into the existing one */
- ID *scene;
- // scenes gets deleted by the thread when it's done using it (look in async_convert())
- vector<Scene *> *scenes = (options & LIB_LOAD_ASYNC) ? new vector<Scene *>() : NULL;
-
- for (scene = (ID *)main_newlib->scene.first; scene; scene = (ID *)scene->next ) {
- if (options & LIB_LOAD_VERBOSE)
- printf("SceneName: %s\n", scene->name + 2);
-
- if (options & LIB_LOAD_ASYNC) {
- scenes->push_back((Scene *)scene);
- }
- else {
- /* merge into the base scene */
- KX_Scene* other = m_ketsjiEngine->CreateScene((Scene *)scene, true);
- scene_merge->MergeScene(other);
-
- // RemoveScene(other); // Don't run this, it frees the entire scene converter data, just delete the scene
- delete other;
- }
- }
-
- if (options & LIB_LOAD_ASYNC) {
- status->SetData(scenes);
- BLI_task_pool_push(m_threadinfo->m_pool, async_convert, (void *)status, false, TASK_PRIORITY_LOW);
- }
-
-#ifdef WITH_PYTHON
- /* Handle any text datablocks */
- if (options & LIB_LOAD_LOAD_SCRIPTS)
- addImportMain(main_newlib);
-#endif
-
- /* Now handle all the actions */
- if (options & LIB_LOAD_LOAD_ACTIONS) {
- ID *action;
-
- for (action = (ID *)main_newlib->action.first; action; action = (ID *)action->next) {
- if (options & LIB_LOAD_VERBOSE)
- printf("ActionName: %s\n", action->name + 2);
- scene_merge->GetLogicManager()->RegisterActionName(action->name + 2, action);
- }
- }
- }
-
- if (!(options & LIB_LOAD_ASYNC))
- status->Finish();
-
-// TIMEIT_END(bge_link_blend_file);
-
- m_status_map[main_newlib->name] = status;
- return status;
-}
-
-/* Note m_map_*** are all ok and don't need to be freed
- * most are temp and NewRemoveObject frees m_map_gameobject_to_blender */
-bool KX_BlenderSceneConverter::FreeBlendFile(Main *maggie)
-{
- int maggie_index = -1;
- int i = 0;
-
- if (maggie == NULL)
- return false;
-
- // If the given library is currently in loading, we do nothing.
- if (m_status_map.count(maggie->name)) {
- BLI_mutex_lock(&m_threadinfo->m_mutex);
- const bool finished = m_status_map[maggie->name]->IsFinished();
- BLI_mutex_unlock(&m_threadinfo->m_mutex);
-
- if (!finished) {
- printf("Library (%s) is currently being loaded asynchronously, and cannot be freed until this process is done\n", maggie->name);
- return false;
- }
- }
-
- /* tag all false except the one we remove */
- for (vector<Main *>::iterator it = m_DynamicMaggie.begin(); !(it == m_DynamicMaggie.end()); it++) {
- Main *main = *it;
- if (main != maggie) {
- BKE_main_id_tag_all(main, LIB_TAG_DOIT, false);
- }
- else {
- maggie_index = i;
- }
- i++;
- }
-
- /* should never happen but just to be safe */
- if (maggie_index == -1)
- return false;
-
- m_DynamicMaggie.erase(m_DynamicMaggie.begin() + maggie_index);
- BKE_main_id_tag_all(maggie, LIB_TAG_DOIT, true);
-
- /* free all tagged objects */
- KX_SceneList *scenes = m_ketsjiEngine->CurrentScenes();
- int numScenes = scenes->size();
-
- for (int scene_idx = 0; scene_idx < numScenes; scene_idx++) {
- KX_Scene *scene = scenes->at(scene_idx);
- if (IS_TAGGED(scene->GetBlenderScene())) {
- m_ketsjiEngine->RemoveScene(scene->GetName());
- m_mat_cache.erase(scene);
- m_polymat_cache.erase(scene);
- scene_idx--;
- numScenes--;
- }
- else {
- /* in case the mesh might be refered to later */
- {
- CTR_Map<STR_HashedString, void *> &mapStringToMeshes = scene->GetLogicManager()->GetMeshMap();
-
- for (int i = 0; i < mapStringToMeshes.size(); i++) {
- RAS_MeshObject *meshobj = (RAS_MeshObject *) *mapStringToMeshes.at(i);
- if (meshobj && IS_TAGGED(meshobj->GetMesh())) {
- STR_HashedString mn = meshobj->GetName();
- mapStringToMeshes.remove(mn);
- m_map_mesh_to_gamemesh.remove(CHashedPtr(meshobj->GetMesh()));
- i--;
- }
- }
- }
-
- /* Now unregister actions */
- {
- CTR_Map<STR_HashedString, void *> &mapStringToActions = scene->GetLogicManager()->GetActionMap();
-
- for (int i = 0; i < mapStringToActions.size(); i++) {
- ID *action = (ID*) *mapStringToActions.at(i);
-
- if (IS_TAGGED(action)) {
- STR_HashedString an = action->name + 2;
- mapStringToActions.remove(an);
- m_map_blender_to_gameAdtList.remove(CHashedPtr(action));
- i--;
- }
- }
- }
-
- //scene->FreeTagged(); /* removed tagged objects and meshes*/
- CListValue *obj_lists[] = {scene->GetObjectList(), scene->GetInactiveList(), NULL};
-
- for (int ob_ls_idx = 0; obj_lists[ob_ls_idx]; ob_ls_idx++) {
- CListValue *obs = obj_lists[ob_ls_idx];
- RAS_MeshObject *mesh;
-
- for (int ob_idx = 0; ob_idx < obs->GetCount(); ob_idx++) {
- KX_GameObject *gameobj = (KX_GameObject*)obs->GetValue(ob_idx);
- if (IS_TAGGED(gameobj->GetBlenderObject())) {
- int size_before = obs->GetCount();
-
- /* Eventually calls RemoveNodeDestructObject
- * frees m_map_gameobject_to_blender from UnregisterGameObject */
- scene->RemoveObject(gameobj);
-
- if (size_before != obs->GetCount())
- ob_idx--;
- else {
- printf("ERROR COULD NOT REMOVE \"%s\"\n", gameobj->GetName().ReadPtr());
- }
- }
- else {
- gameobj->RemoveTaggedActions();
- /* free the mesh, we could be referecing a linked one! */
- int mesh_index = gameobj->GetMeshCount();
- while (mesh_index--) {
- mesh = gameobj->GetMesh(mesh_index);
- if (IS_TAGGED(mesh->GetMesh())) {
- gameobj->RemoveMeshes(); /* XXX - slack, should only remove meshes that are library items but mostly objects only have 1 mesh */
- break;
- }
- else {
- /* also free the mesh if it's using a tagged material */
- int mat_index = mesh->NumMaterials();
- while (mat_index--) {
- if (IS_TAGGED(mesh->GetMeshMaterial(mat_index)->m_bucket->GetPolyMaterial()->GetBlenderMaterial())) {
- gameobj->RemoveMeshes(); /* XXX - slack, same as above */
- break;
- }
- }
- }
- }
-
- /* make sure action actuators are not referencing tagged actions */
- for (unsigned int act_idx = 0; act_idx < gameobj->GetActuators().size(); act_idx++) {
- if (gameobj->GetActuators()[act_idx]->IsType(SCA_IActuator::KX_ACT_ACTION)) {
- BL_ActionActuator *act = (BL_ActionActuator *)gameobj->GetActuators()[act_idx];
- if (IS_TAGGED(act->GetAction()))
- act->SetAction(NULL);
- }
- }
- }
- }
- }
- }
- }
-
- int size;
-
- // delete the entities of this scene
- /* TODO - */
-#if 0
- vector<pair<KX_Scene*,KX_WorldInfo*> >::iterator worldit;
- size = m_worldinfos.size();
- for (i=0, worldit=m_worldinfos.begin(); i<size; ) {
- if ((*worldit).second) {
- delete (*worldit).second;
- *worldit = m_worldinfos.back();
- m_worldinfos.pop_back();
- size--;
- } else {
- i++;
- worldit++;
- }
- }
-#endif
-
-
- /* Worlds don't reference original blender data so we need to make a set from them */
- typedef std::set<KX_WorldInfo *> KX_WorldInfoSet;
- KX_WorldInfoSet worldset;
- for (int scene_idx = 0; scene_idx < numScenes; scene_idx++) {
- KX_Scene *scene = scenes->at(scene_idx);
- if (scene->GetWorldInfo())
- worldset.insert(scene->GetWorldInfo());
- }
-
- vector<pair<KX_Scene *, KX_WorldInfo *> >::iterator worldit;
- size = m_worldinfos.size();
- for (i = 0, worldit = m_worldinfos.begin(); i < size;) {
- if (worldit->second && (worldset.count(worldit->second)) == 0) {
- delete worldit->second;
- *worldit = m_worldinfos.back();
- m_worldinfos.pop_back();
- size--;
- }
- else {
- i++;
- worldit++;
- }
- }
- worldset.clear();
- /* done freeing the worlds */
-
- vector<pair<KX_Scene *, RAS_IPolyMaterial *> >::iterator polymit;
- size = m_polymaterials.size();
-
- for (i = 0, polymit = m_polymaterials.begin(); i < size; ) {
- RAS_IPolyMaterial *mat = polymit->second;
- Material *bmat = NULL;
-
- KX_BlenderMaterial *bl_mat = static_cast<KX_BlenderMaterial *>(mat);
- bmat = bl_mat->GetBlenderMaterial();
-
- if (IS_TAGGED(bmat)) {
- /* only remove from bucket */
- polymit->first->GetBucketManager()->RemoveMaterial(mat);
- }
-
- i++;
- polymit++;
- }
-
- for (i = 0, polymit = m_polymaterials.begin(); i < size; ) {
- RAS_IPolyMaterial *mat = polymit->second;
- Material *bmat = NULL;
-
- KX_BlenderMaterial *bl_mat = static_cast<KX_BlenderMaterial*>(mat);
- bmat = bl_mat->GetBlenderMaterial();
-
- if (IS_TAGGED(bmat)) {
- // Remove the poly material coresponding to this Blender Material.
- m_polymat_cache[polymit->first].erase(bmat);
- delete polymit->second;
- *polymit = m_polymaterials.back();
- m_polymaterials.pop_back();
- size--;
- } else {
- i++;
- polymit++;
- }
- }
-
- vector<pair<KX_Scene *, BL_Material *> >::iterator matit;
- size = m_materials.size();
- for (i = 0, matit = m_materials.begin(); i < size; ) {
- BL_Material *mat = matit->second;
- if (IS_TAGGED(mat->material)) {
- // Remove the bl material coresponding to this Blender Material.
- m_mat_cache[matit->first].erase(mat->material);
- delete matit->second;
- *matit = m_materials.back();
- m_materials.pop_back();
- size--;
- }
- else {
- i++;
- matit++;
- }
- }
-
- vector<pair<KX_Scene *, RAS_MeshObject *> >::iterator meshit;
- RAS_BucketManager::BucketList::iterator bit;
- list<RAS_MeshSlot>::iterator msit;
- RAS_BucketManager::BucketList buckets;
-
- size = m_meshobjects.size();
- for (i = 0, meshit = m_meshobjects.begin(); i < size;) {
- RAS_MeshObject *me = meshit->second;
- if (IS_TAGGED(me->GetMesh())) {
- // Before deleting the mesh object, make sure the rasterizer is
- // no longer referencing it.
- buckets = meshit->first->GetBucketManager()->GetSolidBuckets();
- for (bit = buckets.begin(); bit != buckets.end(); bit++) {
- msit = (*bit)->msBegin();
-
- while (msit != (*bit)->msEnd()) {
- if (msit->m_mesh == meshit->second)
- (*bit)->RemoveMesh(&(*msit++));
- else
- msit++;
- }
- }
-
- // And now the alpha buckets
- buckets = meshit->first->GetBucketManager()->GetAlphaBuckets();
- for (bit = buckets.begin(); bit != buckets.end(); bit++) {
- msit = (*bit)->msBegin();
-
- while (msit != (*bit)->msEnd()) {
- if (msit->m_mesh == meshit->second)
- (*bit)->RemoveMesh(&(*msit++));
- else
- msit++;
- }
- }
-
- // Now it should be safe to delete
- delete meshit->second;
- *meshit = m_meshobjects.back();
- m_meshobjects.pop_back();
- size--;
- }
- else {
- i++;
- meshit++;
- }
- }
-
-#ifdef WITH_PYTHON
- /* make sure this maggie is removed from the import list if it's there
- * (this operation is safe if it isn't in the list) */
- removeImportMain(maggie);
-#endif
-
- delete m_status_map[maggie->name];
- m_status_map.erase(maggie->name);
-
- BKE_main_free(maggie);
-
- return true;
-}
-
-bool KX_BlenderSceneConverter::FreeBlendFile(const char *path)
-{
- return FreeBlendFile(GetMainDynamicPath(path));
-}
-
-bool KX_BlenderSceneConverter::MergeScene(KX_Scene *to, KX_Scene *from)
-{
- {
- vector<pair<KX_Scene *, KX_WorldInfo *> >::iterator itp = m_worldinfos.begin();
- while (itp != m_worldinfos.end()) {
- if (itp->first == from)
- itp->first = to;
- itp++;
- }
- }
-
- {
- vector<pair<KX_Scene *, RAS_IPolyMaterial *> >::iterator itp = m_polymaterials.begin();
- while (itp != m_polymaterials.end()) {
- if (itp->first == from) {
- itp->first = to;
-
- /* also switch internal data */
- RAS_IPolyMaterial *mat = itp->second;
- mat->Replace_IScene(to);
- }
- itp++;
- }
- }
-
- {
- vector<pair<KX_Scene *, RAS_MeshObject *> >::iterator itp = m_meshobjects.begin();
- while (itp != m_meshobjects.end()) {
- if (itp->first == from)
- itp->first = to;
- itp++;
- }
- }
-
- {
- vector<pair<KX_Scene *, BL_Material *> >::iterator itp = m_materials.begin();
- while (itp != m_materials.end()) {
- if (itp->first == from)
- itp->first = to;
- itp++;
- }
- }
-
- MaterialCache::iterator matcacheit = m_mat_cache.find(from);
- if (matcacheit != m_mat_cache.end()) {
- // Merge cached BL_Material map.
- m_mat_cache[to].insert(matcacheit->second.begin(), matcacheit->second.end());
- m_mat_cache.erase(matcacheit);
- }
-
- PolyMaterialCache::iterator polymatcacheit = m_polymat_cache.find(from);
- if (polymatcacheit != m_polymat_cache.end()) {
- // Merge cached RAS_IPolyMaterial map.
- m_polymat_cache[to].insert(polymatcacheit->second.begin(), polymatcacheit->second.end());
- m_polymat_cache.erase(polymatcacheit);
- }
-
- return true;
-}
-
-/* This function merges a mesh from the current scene into another main
- * it does not convert */
-RAS_MeshObject *KX_BlenderSceneConverter::ConvertMeshSpecial(KX_Scene *kx_scene, Main *maggie, const char *name)
-{
- /* Find a mesh in the current main */
- ID *me= static_cast<ID *>(BLI_findstring(&m_maggie->mesh, name, offsetof(ID, name) + 2));
- Main *from_maggie = m_maggie;
-
- if (me == NULL) {
- // The mesh wasn't in the current main, try any dynamic (i.e., LibLoaded) ones
- vector<Main *>::iterator it;
-
- for (it = GetMainDynamic().begin(); it != GetMainDynamic().end(); it++) {
- me = static_cast<ID *>(BLI_findstring(&(*it)->mesh, name, offsetof(ID, name) + 2));
- from_maggie = *it;
-
- if (me)
- break;
- }
- }
-
- if (me == NULL) {
- printf("Could not be found \"%s\"\n", name);
- return NULL;
- }
-
- /* Watch this!, if its used in the original scene can cause big troubles */
- if (me->us > 0) {
-#ifdef DEBUG
- printf("Mesh has a user \"%s\"\n", name);
-#endif
- me = (ID*)BKE_mesh_copy(from_maggie, (Mesh*)me);
- id_us_min(me);
- }
- BLI_remlink(&from_maggie->mesh, me); /* even if we made the copy it needs to be removed */
- BLI_addtail(&maggie->mesh, me);
-
- /* Must copy the materials this uses else we cant free them */
- {
- Mesh *mesh = (Mesh *)me;
-
- /* ensure all materials are tagged */
- for (int i = 0; i < mesh->totcol; i++) {
- if (mesh->mat[i])
- mesh->mat[i]->id.tag &= ~LIB_TAG_DOIT;
- }
-
- for (int i = 0; i < mesh->totcol; i++) {
- Material *mat_old = mesh->mat[i];
-
- /* if its tagged its a replaced material */
- if (mat_old && (mat_old->id.tag & LIB_TAG_DOIT) == 0) {
- Material *mat_old = mesh->mat[i];
- Material *mat_new = BKE_material_copy(from_maggie, mat_old);
-
- mat_new->id.tag |= LIB_TAG_DOIT;
- id_us_min(&mat_old->id);
-
- BLI_remlink(&from_maggie->mat, mat_new); // BKE_material_copy uses G.main, and there is no BKE_material_copy_ex
- BLI_addtail(&maggie->mat, mat_new);
-
- mesh->mat[i] = mat_new;
-
- /* the same material may be used twice */
- for (int j = i + 1; j < mesh->totcol; j++) {
- if (mesh->mat[j] == mat_old) {
- mesh->mat[j] = mat_new;
- id_us_plus(&mat_new->id);
- id_us_min(&mat_old->id);
- }
- }
- }
- }
- }
-
- m_currentScene = kx_scene; // This needs to be set in case we LibLoaded earlier
- RAS_MeshObject *meshobj = BL_ConvertMesh((Mesh *)me, NULL, kx_scene, this, false);
- kx_scene->GetLogicManager()->RegisterMeshName(meshobj->GetName(),meshobj);
- m_map_mesh_to_gamemesh.clear(); /* This is at runtime so no need to keep this, BL_ConvertMesh adds */
- return meshobj;
-}
diff --git a/source/gameengine/Converter/KX_BlenderSceneConverter.h b/source/gameengine/Converter/KX_BlenderSceneConverter.h
deleted file mode 100644
index 40c71a4d74b..00000000000
--- a/source/gameengine/Converter/KX_BlenderSceneConverter.h
+++ /dev/null
@@ -1,232 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file KX_BlenderSceneConverter.h
- * \ingroup bgeconv
- */
-
-#ifndef __KX_BLENDERSCENECONVERTER_H__
-#define __KX_BLENDERSCENECONVERTER_H__
-
-#include "EXP_HashedPtr.h"
-#include "CTR_Map.h"
-#include <stdio.h>
-
-#include "KX_ISceneConverter.h"
-#include "KX_IpoConvert.h"
-
-#include <map>
-
-using namespace std;
-
-class KX_WorldInfo;
-class SCA_IActuator;
-class SCA_IController;
-class RAS_MeshObject;
-class RAS_IPolyMaterial;
-class BL_InterpolatorList;
-class BL_Material;
-struct Main;
-struct Scene;
-struct ThreadInfo;
-struct Material;
-
-typedef map<KX_Scene*, map<Material*, BL_Material*> > MaterialCache;
-typedef map<KX_Scene*, map<Material*, RAS_IPolyMaterial*> > PolyMaterialCache;
-
-class KX_BlenderSceneConverter : public KX_ISceneConverter
-{
- // Use vector of pairs to allow removal of entities between scene switch
- vector<pair<KX_Scene*,KX_WorldInfo*> > m_worldinfos;
- vector<pair<KX_Scene*,RAS_IPolyMaterial*> > m_polymaterials;
- vector<pair<KX_Scene*,RAS_MeshObject*> > m_meshobjects;
- vector<pair<KX_Scene*,BL_Material *> > m_materials;
-
- vector<class KX_LibLoadStatus*> m_mergequeue;
- ThreadInfo *m_threadinfo;
-
- // Cached material conversions
- MaterialCache m_mat_cache;
- PolyMaterialCache m_polymat_cache;
-
- // Saved KX_LibLoadStatus objects
- map<char *, class KX_LibLoadStatus*> m_status_map;
-
- // Should also have a list of collision shapes.
- // For the time being this is held in KX_Scene::m_shapes
-
- CTR_Map<CHashedPtr,KX_GameObject*> m_map_blender_to_gameobject; /* cleared after conversion */
- CTR_Map<CHashedPtr,RAS_MeshObject*> m_map_mesh_to_gamemesh; /* cleared after conversion */
- CTR_Map<CHashedPtr,SCA_IActuator*> m_map_blender_to_gameactuator; /* cleared after conversion */
- CTR_Map<CHashedPtr,SCA_IController*>m_map_blender_to_gamecontroller; /* cleared after conversion */
-
- CTR_Map<CHashedPtr,BL_InterpolatorList*> m_map_blender_to_gameAdtList;
-
- Main* m_maggie;
- vector<struct Main*> m_DynamicMaggie;
-
- STR_String m_newfilename;
- class KX_KetsjiEngine* m_ketsjiEngine;
- class KX_Scene* m_currentScene; // Scene being converted
- bool m_alwaysUseExpandFraming;
- bool m_usemat;
- bool m_useglslmat;
- bool m_use_mat_cache;
-
-public:
- KX_BlenderSceneConverter(
- Main* maggie,
- class KX_KetsjiEngine* engine
- );
-
- virtual ~KX_BlenderSceneConverter();
-
- /* Scenename: name of the scene to be converted.
- * destinationscene: pass an empty scene, everything goes into this
- * dictobj: python dictionary (for pythoncontrollers)
- */
- virtual void ConvertScene(
- class KX_Scene* destinationscene,
- class RAS_IRasterizer* rendertools,
- class RAS_ICanvas* canvas,
- bool libloading=false
- );
- virtual void RemoveScene(class KX_Scene *scene);
-
- void SetNewFileName(const STR_String& filename);
- bool TryAndLoadNewFile();
-
- void SetAlwaysUseExpandFraming(bool to_what);
-
- void RegisterGameObject(KX_GameObject *gameobject, struct Object *for_blenderobject);
- void UnregisterGameObject(KX_GameObject *gameobject);
- KX_GameObject *FindGameObject(struct Object *for_blenderobject);
-
- void RegisterGameMesh(RAS_MeshObject *gamemesh, struct Mesh *for_blendermesh);
- RAS_MeshObject *FindGameMesh(struct Mesh *for_blendermesh/*, unsigned int onlayer*/);
-
- void RegisterPolyMaterial(RAS_IPolyMaterial *polymat);
- void CachePolyMaterial(KX_Scene *scene, Material *mat, RAS_IPolyMaterial *polymat);
- RAS_IPolyMaterial *FindCachedPolyMaterial(KX_Scene *scene, Material *mat);
-
- void RegisterBlenderMaterial(BL_Material *mat);
- void CacheBlenderMaterial(KX_Scene *scene, Material *mat, BL_Material *blmat);
- BL_Material *FindCachedBlenderMaterial(KX_Scene *scene, Material *mat);
-
- void RegisterInterpolatorList(BL_InterpolatorList *actList, struct bAction *for_act);
- BL_InterpolatorList *FindInterpolatorList(struct bAction *for_act);
-
- void RegisterGameActuator(SCA_IActuator *act, struct bActuator *for_actuator);
- SCA_IActuator *FindGameActuator(struct bActuator *for_actuator);
-
- void RegisterGameController(SCA_IController *cont, struct bController *for_controller);
- SCA_IController *FindGameController(struct bController *for_controller);
-
- void RegisterWorldInfo(KX_WorldInfo *worldinfo);
-
- virtual void ResetPhysicsObjectsAnimationIpo(bool clearIpo);
-
- ///this is for reseting the position,rotation and scale of the gameobjet that is not dynamic
- virtual void resetNoneDynamicObjectToIpo();
-
- ///this generates ipo curves for position, rotation, allowing to use game physics in animation
- virtual void WritePhysicsObjectToAnimationIpo(int frameNumber);
- virtual void TestHandlesPhysicsObjectToAnimationIpo();
-
- // use blender materials
- virtual void SetMaterials(bool val);
- virtual bool GetMaterials();
-
- // use blender glsl materials
- virtual void SetGLSLMaterials(bool val);
- virtual bool GetGLSLMaterials();
-
- // cache materials during conversion
- virtual void SetCacheMaterials(bool val);
- virtual bool GetCacheMaterials();
-
- struct Scene* GetBlenderSceneForName(const STR_String& name);
-
-// struct Main* GetMain() { return m_maggie; }
- struct Main* GetMainDynamicPath(const char *path);
- vector<struct Main*> &GetMainDynamic();
-
- class KX_LibLoadStatus *LinkBlendFileMemory(void *data, int length, const char *path, char *group, KX_Scene *scene_merge, char **err_str, short options);
- class KX_LibLoadStatus *LinkBlendFilePath(const char *path, char *group, KX_Scene *scene_merge, char **err_str, short options);
- class KX_LibLoadStatus *LinkBlendFile(struct BlendHandle *bpy_openlib, const char *path, char *group, KX_Scene *scene_merge, char **err_str, short options);
- bool MergeScene(KX_Scene *to, KX_Scene *from);
- RAS_MeshObject *ConvertMeshSpecial(KX_Scene* kx_scene, Main *maggie, const char *name);
- bool FreeBlendFile(struct Main *maggie);
- bool FreeBlendFile(const char *path);
-
- virtual void MergeAsyncLoads();
- virtual void FinalizeAsyncLoads();
- void AddScenesToMergeQueue(class KX_LibLoadStatus *status);
-
- void PrintStats() {
- printf("BGE STATS!\n");
-
- printf("\nAssets...\n");
- printf("\t m_worldinfos: %d\n", (int)m_worldinfos.size());
- printf("\t m_polymaterials: %d\n", (int)m_polymaterials.size());
- printf("\t m_meshobjects: %d\n", (int)m_meshobjects.size());
- printf("\t m_materials: %d\n", (int)m_materials.size());
-
- printf("\nMappings...\n");
- printf("\t m_map_blender_to_gameobject: %d\n", m_map_blender_to_gameobject.size());
- printf("\t m_map_mesh_to_gamemesh: %d\n", m_map_mesh_to_gamemesh.size());
- printf("\t m_map_blender_to_gameactuator: %d\n", m_map_blender_to_gameactuator.size());
- printf("\t m_map_blender_to_gamecontroller: %d\n", m_map_blender_to_gamecontroller.size());
- printf("\t m_map_blender_to_gameAdtList: %d\n", m_map_blender_to_gameAdtList.size());
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_printmemlist_pydict();
-#endif
-// /printf("\t m_ketsjiEngine->m_scenes: %d\n", m_ketsjiEngine->CurrentScenes()->size());
- }
-
- /* LibLoad Options */
- enum
- {
- LIB_LOAD_LOAD_ACTIONS = 1,
- LIB_LOAD_VERBOSE = 2,
- LIB_LOAD_LOAD_SCRIPTS = 4,
- LIB_LOAD_ASYNC = 8,
- };
-
-
-
-#ifdef WITH_PYTHON
- PyObject *GetPyNamespace();
-#endif
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:KX_BlenderSceneConverter")
-#endif
-};
-
-#endif /* __KX_BLENDERSCENECONVERTER_H__ */
diff --git a/source/gameengine/Converter/KX_ConvertActuators.cpp b/source/gameengine/Converter/KX_ConvertActuators.cpp
deleted file mode 100644
index d78ea4eed54..00000000000
--- a/source/gameengine/Converter/KX_ConvertActuators.cpp
+++ /dev/null
@@ -1,1146 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- * Convert Blender actuators for use in the GameEngine
- */
-
-/** \file gameengine/Converter/KX_ConvertActuators.cpp
- * \ingroup bgeconv
- */
-
-#ifdef _MSC_VER
-# pragma warning (disable:4786)
-#endif
-
-#include <math.h>
-
-#include "MEM_guardedalloc.h"
-
-#include "KX_BlenderSceneConverter.h"
-#include "KX_ConvertActuators.h"
-
-#ifdef WITH_AUDASPACE
-# include <AUD_Sound.h>
-#endif
-
-// Actuators
-//SCA logiclibrary native logicbricks
-#include "SCA_PropertyActuator.h"
-#include "SCA_LogicManager.h"
-#include "SCA_RandomActuator.h"
-#include "SCA_2DFilterActuator.h"
-
-// Ketsji specific logicbricks
-#include "KX_SceneActuator.h"
-#include "KX_SoundActuator.h"
-#include "KX_ObjectActuator.h"
-#include "KX_TrackToActuator.h"
-#include "KX_ConstraintActuator.h"
-#include "KX_CameraActuator.h"
-#include "KX_GameActuator.h"
-#include "KX_StateActuator.h"
-#include "KX_VisibilityActuator.h"
-#include "KX_SCA_AddObjectActuator.h"
-#include "KX_SCA_EndObjectActuator.h"
-#include "KX_SCA_ReplaceMeshActuator.h"
-#include "KX_ParentActuator.h"
-#include "KX_SCA_DynamicActuator.h"
-#include "KX_SteeringActuator.h"
-#include "KX_MouseActuator.h"
-
-#include "KX_Scene.h"
-#include "KX_KetsjiEngine.h"
-
-#include "EXP_IntValue.h"
-#include "KX_GameObject.h"
-
-/* This little block needed for linking to Blender... */
-#include "BKE_text.h"
-#include "BLI_blenlib.h"
-#include "BLI_math.h"
-#include "BLI_path_util.h"
-
-#include "KX_NetworkMessageActuator.h"
-
-#ifdef WIN32
-#include "BLI_winstuff.h"
-#endif
-
-#include "DNA_object_types.h"
-#include "DNA_sound_types.h"
-#include "DNA_scene_types.h"
-#include "DNA_actuator_types.h"
-#include "DNA_packedFile_types.h"
-#include "BL_ActionActuator.h"
-#include "BL_ShapeActionActuator.h"
-#include "BL_ArmatureActuator.h"
-#include "RNA_access.h"
-#include "BL_Action.h"
-/* end of blender include block */
-
-#include "BL_BlenderDataConversion.h"
-
-/**
- * KX_flt_trunc needed to round 'almost' zero values to zero, else velocities etc. are incorrectly set
- */
-
-BLI_INLINE float KX_flt_trunc(const float x)
-{
- return ( x < 0.0001f && x > -0.0001f ) ? 0.0f : x;
-}
-
-void BL_ConvertActuators(const char* maggiename,
- struct Object* blenderobject,
- KX_GameObject* gameobj,
- SCA_LogicManager* logicmgr,
- KX_Scene* scene,
- KX_KetsjiEngine* ketsjiEngine,
- int activeLayerBitInfo,
- bool isInActiveLayer,
- KX_BlenderSceneConverter* converter
- )
-{
-
- int uniqueint = 0;
- int actcount = 0;
- int executePriority = 0;
- bActuator* bact = (bActuator*) blenderobject->actuators.first;
- while (bact)
- {
- actcount++;
- bact = bact->next;
- }
- gameobj->ReserveActuator(actcount);
- bact = (bActuator*) blenderobject->actuators.first;
- while (bact)
- {
- STR_String uniquename = bact->name;
- STR_String& objectname = gameobj->GetName();
-
- SCA_IActuator* baseact = NULL;
- switch (bact->type)
- {
- case ACT_OBJECT:
- {
- bObjectActuator* obact = (bObjectActuator*) bact->data;
- KX_GameObject* obref = NULL;
- MT_Vector3 forcevec(KX_flt_trunc(obact->forceloc[0]),
- KX_flt_trunc(obact->forceloc[1]),
- KX_flt_trunc(obact->forceloc[2]));
- MT_Vector3 torquevec(obact->forcerot[0],
- obact->forcerot[1],
- obact->forcerot[2]);
- MT_Vector3 dlocvec(KX_flt_trunc(obact->dloc[0]),
- KX_flt_trunc(obact->dloc[1]),
- KX_flt_trunc(obact->dloc[2]));
- MT_Vector3 drotvec(KX_flt_trunc(obact->drot[0]),
- obact->drot[1],obact->drot[2]);
- MT_Vector3 linvelvec(KX_flt_trunc(obact->linearvelocity[0]),
- KX_flt_trunc(obact->linearvelocity[1]),
- KX_flt_trunc(obact->linearvelocity[2]));
- MT_Vector3 angvelvec(KX_flt_trunc(obact->angularvelocity[0]),
- KX_flt_trunc(obact->angularvelocity[1]),
- KX_flt_trunc(obact->angularvelocity[2]));
- short damping = obact->damping;
-
- /* Blender uses a bit vector internally for the local-flags. In */
- /* KX, we have four bools. The compiler should be smart enough */
- /* to do the right thing. We need to explicitly convert here! */
-
- KX_LocalFlags bitLocalFlag;
-
- bitLocalFlag.Force = bool((obact->flag & ACT_FORCE_LOCAL)!=0);
- bitLocalFlag.Torque = bool((obact->flag & ACT_TORQUE_LOCAL) !=0);//rlocal;
- bitLocalFlag.DLoc = bool((obact->flag & ACT_DLOC_LOCAL)!=0);
- bitLocalFlag.DRot = bool((obact->flag & ACT_DROT_LOCAL)!=0);
- bitLocalFlag.LinearVelocity = bool((obact->flag & ACT_LIN_VEL_LOCAL)!=0);
- bitLocalFlag.AngularVelocity = bool((obact->flag & ACT_ANG_VEL_LOCAL)!=0);
- bitLocalFlag.ServoControl = bool(obact->type == ACT_OBJECT_SERVO);
- bitLocalFlag.CharacterMotion = bool(obact->type == ACT_OBJECT_CHARACTER);
- bitLocalFlag.CharacterJump = bool((obact->flag & ACT_CHAR_JUMP)!=0);
- bitLocalFlag.AddOrSetLinV = bool((obact->flag & ACT_ADD_LIN_VEL)!=0);
- bitLocalFlag.AddOrSetCharLoc = bool((obact->flag & ACT_ADD_CHAR_LOC)!=0);
- if (obact->reference && bitLocalFlag.ServoControl)
- {
- obref = converter->FindGameObject(obact->reference);
- }
-
- KX_ObjectActuator* tmpbaseact = new KX_ObjectActuator(
- gameobj,
- obref,
- forcevec.getValue(),
- torquevec.getValue(),
- dlocvec.getValue(),
- drotvec.getValue(),
- linvelvec.getValue(),
- angvelvec.getValue(),
- damping,
- bitLocalFlag);
- baseact = tmpbaseact;
- break;
- }
- case ACT_ACTION:
- {
- bActionActuator* actact = (bActionActuator*) bact->data;
- STR_String propname = actact->name;
- STR_String propframe = actact->frameProp;
-
- short ipo_flags = 0;
-
- // Convert flags
- if (actact->flag & ACT_IPOFORCE) ipo_flags |= BL_Action::ACT_IPOFLAG_FORCE;
- if (actact->flag & ACT_IPOLOCAL) ipo_flags |= BL_Action::ACT_IPOFLAG_LOCAL;
- if (actact->flag & ACT_IPOADD) ipo_flags |= BL_Action::ACT_IPOFLAG_ADD;
- if (actact->flag & ACT_IPOCHILD) ipo_flags |= BL_Action::ACT_IPOFLAG_CHILD;
-
- BL_ActionActuator* tmpbaseact = new BL_ActionActuator(
- gameobj,
- propname,
- propframe,
- actact->sta,
- actact->end,
- actact->act,
- actact->type, // + 1, because Blender starts to count at zero,
- actact->blend_mode,
- actact->blendin,
- actact->priority,
- actact->layer,
- actact->layer_weight,
- ipo_flags,
- actact->end_reset,
- actact->stridelength
- // Ketsji at 1, because zero is reserved for "NoDef"
- );
- baseact= tmpbaseact;
- break;
- }
- case ACT_SHAPEACTION:
- {
- if (blenderobject->type==OB_MESH) {
- bActionActuator* actact = (bActionActuator*) bact->data;
- STR_String propname = actact->name;
- STR_String propframe = actact->frameProp;
-
- BL_ShapeActionActuator* tmpbaseact = new BL_ShapeActionActuator(
- gameobj,
- propname,
- propframe,
- actact->sta,
- actact->end,
- actact->act,
- actact->type, // + 1, because Blender starts to count at zero,
- actact->blendin,
- actact->priority,
- actact->stridelength);
- // Ketsji at 1, because zero is reserved for "NoDef"
- baseact= tmpbaseact;
- break;
- }
- else
- printf ("Discarded shape action actuator from non-mesh object [%s]\n", blenderobject->id.name+2);
- }
- case ACT_LAMP:
- {
- break;
- }
- case ACT_CAMERA:
- {
- bCameraActuator *camact = (bCameraActuator *) bact->data;
- if (camact->ob) {
- KX_GameObject *tmpgob = converter->FindGameObject(camact->ob);
-
- /* visifac, fac and axis are not copied from the struct... */
- /* that's some internal state... */
- KX_CameraActuator *tmpcamact = new KX_CameraActuator(
- gameobj,
- tmpgob,
- camact->height,
- camact->min,
- camact->max,
- camact->axis,
- camact->damping);
- baseact = tmpcamact;
- }
- break;
- }
- case ACT_MESSAGE:
- {
- bMessageActuator *msgAct = (bMessageActuator *) bact->data;
-
- /* Get the name of the properties that objects must own that
- * we're sending to, if present
- */
- STR_String toPropName = msgAct->toPropName;
-
- /* Get the Message Subject to send.
- */
- STR_String subject = msgAct->subject;
-
- /* Get the bodyType
- */
- int bodyType = msgAct->bodyType;
-
- /* Get the body (text message or property name whose value
- * we'll be sending, might be empty
- */
- const STR_String body = msgAct->body;
-
- KX_NetworkMessageActuator *tmpmsgact = new KX_NetworkMessageActuator(
- gameobj, // actuator controlling object
- scene->GetNetworkScene(), // needed for replication
- toPropName,
- subject,
- bodyType,
- body);
- baseact = tmpmsgact;
- break;
- }
- case ACT_MATERIAL:
- {
- break;
- }
- case ACT_SOUND:
- {
- bSoundActuator* soundact = (bSoundActuator*) bact->data;
- /* get type, and possibly a start and end frame */
- KX_SoundActuator::KX_SOUNDACT_TYPE
- soundActuatorType = KX_SoundActuator::KX_SOUNDACT_NODEF;
-
- switch (soundact->type) {
- case ACT_SND_PLAY_STOP_SOUND:
- soundActuatorType = KX_SoundActuator::KX_SOUNDACT_PLAYSTOP;
- break;
- case ACT_SND_PLAY_END_SOUND:
- soundActuatorType = KX_SoundActuator::KX_SOUNDACT_PLAYEND;
- break;
- case ACT_SND_LOOP_STOP_SOUND:
- soundActuatorType = KX_SoundActuator::KX_SOUNDACT_LOOPSTOP;
- break;
- case ACT_SND_LOOP_END_SOUND:
- soundActuatorType = KX_SoundActuator::KX_SOUNDACT_LOOPEND;
- break;
- case ACT_SND_LOOP_BIDIRECTIONAL_SOUND:
- soundActuatorType = KX_SoundActuator::KX_SOUNDACT_LOOPBIDIRECTIONAL;
- break;
- case ACT_SND_LOOP_BIDIRECTIONAL_STOP_SOUND:
- soundActuatorType = KX_SoundActuator::KX_SOUNDACT_LOOPBIDIRECTIONAL_STOP;
- break;
-
- default:
- /* This is an error!!! */
- soundActuatorType = KX_SoundActuator::KX_SOUNDACT_NODEF;
- }
-
- if (soundActuatorType != KX_SoundActuator::KX_SOUNDACT_NODEF)
- {
- bSound* sound = soundact->sound;
- bool is3d = soundact->flag & ACT_SND_3D_SOUND ? true : false;
- AUD_Sound* snd_sound = NULL;
- KX_3DSoundSettings settings;
- settings.cone_inner_angle = RAD2DEGF(soundact->sound3D.cone_inner_angle);
- settings.cone_outer_angle = RAD2DEGF(soundact->sound3D.cone_outer_angle);
- settings.cone_outer_gain = soundact->sound3D.cone_outer_gain;
- settings.max_distance = soundact->sound3D.max_distance;
- settings.max_gain = soundact->sound3D.max_gain;
- settings.min_gain = soundact->sound3D.min_gain;
- settings.reference_distance = soundact->sound3D.reference_distance;
- settings.rolloff_factor = soundact->sound3D.rolloff_factor;
-
- if (!sound)
- {
- std::cout << "WARNING: Sound actuator \"" << bact->name <<
- "\" from object \"" << blenderobject->id.name+2 <<
- "\" has no sound datablock." << std::endl;
- }
- else
- {
- snd_sound = sound->playback_handle;
-
- // if sound shall be 3D but isn't mono, we have to make it mono!
- if (is3d)
- {
- snd_sound = AUD_Sound_rechannel(snd_sound, AUD_CHANNELS_MONO);
- }
- }
- KX_SoundActuator* tmpsoundact =
- new KX_SoundActuator(gameobj,
- snd_sound,
- soundact->volume,
- (float)(expf((soundact->pitch / 12.0f) * (float)M_LN2)),
- is3d,
- settings,
- soundActuatorType);
-
- // if we made it mono, we have to free it
- if (sound && snd_sound && snd_sound != sound->playback_handle) {
- AUD_Sound_free(snd_sound);
- }
-
- tmpsoundact->SetName(bact->name);
- baseact = tmpsoundact;
- }
- break;
- }
- case ACT_PROPERTY:
- {
- bPropertyActuator* propact = (bPropertyActuator*) bact->data;
- SCA_IObject* destinationObj = NULL;
-
- /*
- * here the destinationobject is searched. problem with multiple scenes: other scenes
- * have not been converted yet, so the destobj will not be found, so the prop will
- * not be copied.
- * possible solutions:
- * - convert everything when possible and not realtime only when needed.
- * - let the object-with-property report itself to the act when converted
- */
- if (propact->ob)
- destinationObj = converter->FindGameObject(propact->ob);
-
- SCA_PropertyActuator* tmppropact = new SCA_PropertyActuator(
- gameobj,
- destinationObj,
- propact->name,
- propact->value,
- propact->type + 1); // + 1 because Ketsji Logic starts
- // with 0 for KX_ACT_PROP_NODEF
- baseact = tmppropact;
- break;
- }
- case ACT_EDIT_OBJECT:
- {
- bEditObjectActuator *editobact
- = (bEditObjectActuator *) bact->data;
- /* There are four different kinds of 'edit object' thingies */
- /* The alternative to this lengthy conversion is packing */
- /* several actuators in one, which is not very nice design.. */
- switch (editobact->type) {
- case ACT_EDOB_ADD_OBJECT:
- {
-
- // does the 'original' for replication exists, and
- // is it in a non-active layer ?
- SCA_IObject* originalval = NULL;
- if (editobact->ob)
- {
- if (editobact->ob->lay & activeLayerBitInfo)
- {
- fprintf(stderr, "Warning, object \"%s\" from AddObject actuator \"%s\" is not in a hidden layer.\n", objectname.Ptr(), uniquename.Ptr());
- }
- else {
- originalval = converter->FindGameObject(editobact->ob);
- }
- }
-
- KX_SCA_AddObjectActuator* tmpaddact = new KX_SCA_AddObjectActuator(
- gameobj,
- originalval,
- editobact->time,
- scene,
- editobact->linVelocity,
- (editobact->localflag & ACT_EDOB_LOCAL_LINV) != 0,
- editobact->angVelocity,
- (editobact->localflag & ACT_EDOB_LOCAL_ANGV) != 0);
-
- //editobact->ob to gameobj
- baseact = tmpaddact;
- }
- break;
- case ACT_EDOB_END_OBJECT:
- {
- KX_SCA_EndObjectActuator* tmpendact
- = new KX_SCA_EndObjectActuator(gameobj,scene);
- baseact = tmpendact;
- }
- break;
- case ACT_EDOB_REPLACE_MESH:
- {
- RAS_MeshObject *tmpmesh = converter->FindGameMesh(editobact->me);
-
- if (!tmpmesh) {
- std::cout << "Warning: object \"" << objectname <<
- "\" from ReplaceMesh actuator \"" << uniquename <<
- "\" uses a mesh not owned by an object in scene \"" <<
- scene->GetName() << "\"." << std::endl;
- }
-
- KX_SCA_ReplaceMeshActuator* tmpreplaceact = new KX_SCA_ReplaceMeshActuator(
- gameobj,
- tmpmesh,
- scene,
- (editobact->flag & ACT_EDOB_REPLACE_MESH_NOGFX) == 0,
- (editobact->flag & ACT_EDOB_REPLACE_MESH_PHYS) != 0);
-
- baseact = tmpreplaceact;
- }
- break;
- case ACT_EDOB_TRACK_TO:
- {
- SCA_IObject* originalval = NULL;
- if (editobact->ob)
- originalval = converter->FindGameObject(editobact->ob);
-
- KX_TrackToActuator* tmptrackact = new KX_TrackToActuator(
- gameobj,
- originalval,
- editobact->time,
- editobact->flag,
- editobact->trackflag,
- editobact->upflag);
- baseact = tmptrackact;
- break;
- }
- case ACT_EDOB_DYNAMICS:
- {
- KX_SCA_DynamicActuator* tmpdynact = new KX_SCA_DynamicActuator(
- gameobj,
- editobact->dyn_operation,
- editobact->mass);
- baseact = tmpdynact;
- }
- }
- break;
- }
- case ACT_CONSTRAINT:
- {
- float min = 0.0, max = 0.0;
- char *prop = NULL;
- KX_ConstraintActuator::KX_CONSTRAINTTYPE locrot = KX_ConstraintActuator::KX_ACT_CONSTRAINT_NODEF;
- bConstraintActuator *conact
- = (bConstraintActuator*) bact->data;
- /* convert settings... degrees in the ui become radians */
- /* internally */
- if (conact->type == ACT_CONST_TYPE_ORI) {
- min = conact->minloc[0];
- max = conact->maxloc[0];
- switch (conact->mode) {
- case ACT_CONST_DIRPX:
- locrot = KX_ConstraintActuator::KX_ACT_CONSTRAINT_ORIX;
- break;
- case ACT_CONST_DIRPY:
- locrot = KX_ConstraintActuator::KX_ACT_CONSTRAINT_ORIY;
- break;
- case ACT_CONST_DIRPZ:
- locrot = KX_ConstraintActuator::KX_ACT_CONSTRAINT_ORIZ;
- break;
- }
- } else if (conact->type == ACT_CONST_TYPE_DIST) {
- switch (conact->mode) {
- case ACT_CONST_DIRPX:
- locrot = KX_ConstraintActuator::KX_ACT_CONSTRAINT_DIRPX;
- min = conact->minloc[0];
- max = conact->maxloc[0];
- break;
- case ACT_CONST_DIRPY:
- locrot = KX_ConstraintActuator::KX_ACT_CONSTRAINT_DIRPY;
- min = conact->minloc[1];
- max = conact->maxloc[1];
- break;
- case ACT_CONST_DIRPZ:
- locrot = KX_ConstraintActuator::KX_ACT_CONSTRAINT_DIRPZ;
- min = conact->minloc[2];
- max = conact->maxloc[2];
- break;
- case ACT_CONST_DIRNX:
- locrot = KX_ConstraintActuator::KX_ACT_CONSTRAINT_DIRNX;
- min = conact->minloc[0];
- max = conact->maxloc[0];
- break;
- case ACT_CONST_DIRNY:
- locrot = KX_ConstraintActuator::KX_ACT_CONSTRAINT_DIRNY;
- min = conact->minloc[1];
- max = conact->maxloc[1];
- break;
- case ACT_CONST_DIRNZ:
- locrot = KX_ConstraintActuator::KX_ACT_CONSTRAINT_DIRNZ;
- min = conact->minloc[2];
- max = conact->maxloc[2];
- break;
- }
- prop = conact->matprop;
- } else if (conact->type == ACT_CONST_TYPE_FH) {
- switch (conact->mode) {
- case ACT_CONST_DIRPX:
- locrot = KX_ConstraintActuator::KX_ACT_CONSTRAINT_FHPX;
- min = conact->minloc[0];
- max = conact->maxloc[0];
- break;
- case ACT_CONST_DIRPY:
- locrot = KX_ConstraintActuator::KX_ACT_CONSTRAINT_FHPY;
- min = conact->minloc[1];
- max = conact->maxloc[1];
- break;
- case ACT_CONST_DIRPZ:
- locrot = KX_ConstraintActuator::KX_ACT_CONSTRAINT_FHPZ;
- min = conact->minloc[2];
- max = conact->maxloc[2];
- break;
- case ACT_CONST_DIRNX:
- locrot = KX_ConstraintActuator::KX_ACT_CONSTRAINT_FHNX;
- min = conact->minloc[0];
- max = conact->maxloc[0];
- break;
- case ACT_CONST_DIRNY:
- locrot = KX_ConstraintActuator::KX_ACT_CONSTRAINT_FHNY;
- min = conact->minloc[1];
- max = conact->maxloc[1];
- break;
- case ACT_CONST_DIRNZ:
- locrot = KX_ConstraintActuator::KX_ACT_CONSTRAINT_FHNZ;
- min = conact->minloc[2];
- max = conact->maxloc[2];
- break;
- }
- prop = conact->matprop;
- } else {
- switch (conact->flag) {
- case ACT_CONST_LOCX:
- locrot = KX_ConstraintActuator::KX_ACT_CONSTRAINT_LOCX;
- min = conact->minloc[0];
- max = conact->maxloc[0];
- break;
- case ACT_CONST_LOCY:
- locrot = KX_ConstraintActuator::KX_ACT_CONSTRAINT_LOCY;
- min = conact->minloc[1];
- max = conact->maxloc[1];
- break;
- case ACT_CONST_LOCZ:
- locrot = KX_ConstraintActuator::KX_ACT_CONSTRAINT_LOCZ;
- min = conact->minloc[2];
- max = conact->maxloc[2];
- break;
- case ACT_CONST_ROTX:
- locrot = KX_ConstraintActuator::KX_ACT_CONSTRAINT_ROTX;
- min = conact->minrot[0] * (float)MT_RADS_PER_DEG;
- max = conact->maxrot[0] * (float)MT_RADS_PER_DEG;
- break;
- case ACT_CONST_ROTY:
- locrot = KX_ConstraintActuator::KX_ACT_CONSTRAINT_ROTY;
- min = conact->minrot[1] * (float)MT_RADS_PER_DEG;
- max = conact->maxrot[1] * (float)MT_RADS_PER_DEG;
- break;
- case ACT_CONST_ROTZ:
- locrot = KX_ConstraintActuator::KX_ACT_CONSTRAINT_ROTZ;
- min = conact->minrot[2] * (float)MT_RADS_PER_DEG;
- max = conact->maxrot[2] * (float)MT_RADS_PER_DEG;
- break;
- default:
- ; /* error */
- }
- }
- KX_ConstraintActuator *tmpconact = new KX_ConstraintActuator(
- gameobj,
- conact->damp,
- conact->rotdamp,
- min,
- max,
- conact->maxrot,
- locrot,
- conact->time,
- conact->flag,
- prop);
- baseact = tmpconact;
- break;
- }
- case ACT_GROUP:
- {
- // deprecated
- }
- break;
- case ACT_SCENE:
- {
- bSceneActuator *sceneact = (bSceneActuator *) bact->data;
- STR_String nextSceneName("");
-
- KX_SceneActuator* tmpsceneact;
- int mode = KX_SceneActuator::KX_SCENE_NODEF;
- KX_Camera *cam = NULL;
- //KX_Scene* scene = NULL;
- switch (sceneact->type)
- {
- case ACT_SCENE_RESUME:
- case ACT_SCENE_SUSPEND:
- case ACT_SCENE_ADD_FRONT:
- case ACT_SCENE_ADD_BACK:
- case ACT_SCENE_REMOVE:
- case ACT_SCENE_SET:
- {
- switch (sceneact->type)
- {
- case ACT_SCENE_RESUME:
- mode = KX_SceneActuator::KX_SCENE_RESUME;
- break;
- case ACT_SCENE_SUSPEND:
- mode = KX_SceneActuator::KX_SCENE_SUSPEND;
- break;
- case ACT_SCENE_ADD_FRONT:
- mode = KX_SceneActuator::KX_SCENE_ADD_FRONT_SCENE;
- break;
- case ACT_SCENE_ADD_BACK:
- mode = KX_SceneActuator::KX_SCENE_ADD_BACK_SCENE;
- break;
- case ACT_SCENE_REMOVE:
- mode = KX_SceneActuator::KX_SCENE_REMOVE_SCENE;
- break;
- case ACT_SCENE_SET:
- default:
- mode = KX_SceneActuator::KX_SCENE_SET_SCENE;
- break;
- };
-
- if (sceneact->scene) {
- nextSceneName = sceneact->scene->id.name + 2;
- }
-
- break;
- }
- case ACT_SCENE_CAMERA:
- mode = KX_SceneActuator::KX_SCENE_SET_CAMERA;
- if (sceneact->camera)
- {
- KX_GameObject *tmp = converter->FindGameObject(sceneact->camera);
- if (tmp && tmp->GetGameObjectType() == SCA_IObject::OBJ_CAMERA)
- cam = (KX_Camera*)tmp;
- }
- break;
- case ACT_SCENE_RESTART:
- {
-
- mode = KX_SceneActuator::KX_SCENE_RESTART;
- break;
- }
- default:
- ; /* flag error */
- }
- tmpsceneact = new KX_SceneActuator(
- gameobj,
- mode,
- scene,
- ketsjiEngine,
- nextSceneName,
- cam);
- baseact = tmpsceneact;
- break;
- }
- case ACT_GAME:
- {
- bGameActuator *gameact = (bGameActuator *) bact->data;
- KX_GameActuator* tmpgameact;
- STR_String filename = maggiename;
- STR_String loadinganimationname = "";
- int mode = KX_GameActuator::KX_GAME_NODEF;
- switch (gameact->type)
- {
- case ACT_GAME_LOAD:
- {
- mode = KX_GameActuator::KX_GAME_LOAD;
- filename = gameact->filename;
- loadinganimationname = gameact->loadaniname;
- break;
- }
- case ACT_GAME_START:
- {
- mode = KX_GameActuator::KX_GAME_START;
- filename = gameact->filename;
- loadinganimationname = gameact->loadaniname;
- break;
- }
- case ACT_GAME_RESTART:
- {
- mode = KX_GameActuator::KX_GAME_RESTART;
- break;
- }
- case ACT_GAME_QUIT:
- {
- mode = KX_GameActuator::KX_GAME_QUIT;
- break;
- }
- case ACT_GAME_SAVECFG:
- {
- mode = KX_GameActuator::KX_GAME_SAVECFG;
- break;
- }
- case ACT_GAME_LOADCFG:
- {
- mode = KX_GameActuator::KX_GAME_LOADCFG;
- break;
- }
- case ACT_GAME_SCREENSHOT:
- {
- mode = KX_GameActuator::KX_GAME_SCREENSHOT;
- filename = gameact->filename;
- break;
- }
- default:
- ; /* flag error */
- }
- tmpgameact = new KX_GameActuator(
- gameobj,
- mode,
- filename,
- loadinganimationname,
- scene,
- ketsjiEngine);
- baseact = tmpgameact;
-
- break;
- }
- case ACT_RANDOM:
- {
- bRandomActuator *randAct
- = (bRandomActuator *) bact->data;
-
- unsigned long seedArg = randAct->seed;
- if (seedArg == 0)
- {
- seedArg = (int)(ketsjiEngine->GetRealTime()*100000.0);
- seedArg ^= (intptr_t)randAct;
- }
- SCA_RandomActuator::KX_RANDOMACT_MODE modeArg
- = SCA_RandomActuator::KX_RANDOMACT_NODEF;
- SCA_RandomActuator *tmprandomact;
- float paraArg1 = 0.0;
- float paraArg2 = 0.0;
-
- switch (randAct->distribution) {
- case ACT_RANDOM_BOOL_CONST:
- modeArg = SCA_RandomActuator::KX_RANDOMACT_BOOL_CONST;
- paraArg1 = (float) randAct->int_arg_1;
- break;
- case ACT_RANDOM_BOOL_UNIFORM:
- modeArg = SCA_RandomActuator::KX_RANDOMACT_BOOL_UNIFORM;
- break;
- case ACT_RANDOM_BOOL_BERNOUILLI:
- paraArg1 = randAct->float_arg_1;
- modeArg = SCA_RandomActuator::KX_RANDOMACT_BOOL_BERNOUILLI;
- break;
- case ACT_RANDOM_INT_CONST:
- modeArg = SCA_RandomActuator::KX_RANDOMACT_INT_CONST;
- paraArg1 = (float) randAct->int_arg_1;
- break;
- case ACT_RANDOM_INT_UNIFORM:
- paraArg1 = (float) randAct->int_arg_1;
- paraArg2 = (float) randAct->int_arg_2;
- modeArg = SCA_RandomActuator::KX_RANDOMACT_INT_UNIFORM;
- break;
- case ACT_RANDOM_INT_POISSON:
- paraArg1 = randAct->float_arg_1;
- modeArg = SCA_RandomActuator::KX_RANDOMACT_INT_POISSON;
- break;
- case ACT_RANDOM_FLOAT_CONST:
- paraArg1 = randAct->float_arg_1;
- modeArg = SCA_RandomActuator::KX_RANDOMACT_FLOAT_CONST;
- break;
- case ACT_RANDOM_FLOAT_UNIFORM:
- paraArg1 = randAct->float_arg_1;
- paraArg2 = randAct->float_arg_2;
- modeArg = SCA_RandomActuator::KX_RANDOMACT_FLOAT_UNIFORM;
- break;
- case ACT_RANDOM_FLOAT_NORMAL:
- paraArg1 = randAct->float_arg_1;
- paraArg2 = randAct->float_arg_2;
- modeArg = SCA_RandomActuator::KX_RANDOMACT_FLOAT_NORMAL;
- break;
- case ACT_RANDOM_FLOAT_NEGATIVE_EXPONENTIAL:
- paraArg1 = randAct->float_arg_1;
- modeArg = SCA_RandomActuator::KX_RANDOMACT_FLOAT_NEGATIVE_EXPONENTIAL;
- break;
- default:
- ; /* error */
- }
- tmprandomact = new SCA_RandomActuator(
- gameobj,
- seedArg,
- modeArg,
- paraArg1,
- paraArg2,
- randAct->propname);
- baseact = tmprandomact;
- }
- break;
-
- case ACT_VISIBILITY:
- {
- bVisibilityActuator *vis_act = (bVisibilityActuator *) bact->data;
- KX_VisibilityActuator * tmp_vis_act = NULL;
- bool v = ((vis_act->flag & ACT_VISIBILITY_INVISIBLE) != 0);
- bool o = ((vis_act->flag & ACT_VISIBILITY_OCCLUSION) != 0);
- bool recursive = ((vis_act->flag & ACT_VISIBILITY_RECURSIVE) != 0);
-
- tmp_vis_act = new KX_VisibilityActuator(gameobj, !v, o, recursive);
-
- baseact = tmp_vis_act;
- }
- break;
-
- case ACT_STATE:
- {
- bStateActuator *sta_act = (bStateActuator *) bact->data;
- KX_StateActuator * tmp_sta_act = NULL;
-
- tmp_sta_act =
- new KX_StateActuator(gameobj, sta_act->type, sta_act->mask);
-
- baseact = tmp_sta_act;
- }
- break;
-
- case ACT_2DFILTER:
- {
- bTwoDFilterActuator *_2dfilter = (bTwoDFilterActuator*) bact->data;
- SCA_2DFilterActuator *tmp = NULL;
-
- RAS_2DFilterManager::RAS_2DFILTER_MODE filtermode;
- switch (_2dfilter->type) {
- case ACT_2DFILTER_MOTIONBLUR:
- filtermode = RAS_2DFilterManager::RAS_2DFILTER_MOTIONBLUR;
- break;
- case ACT_2DFILTER_BLUR:
- filtermode = RAS_2DFilterManager::RAS_2DFILTER_BLUR;
- break;
- case ACT_2DFILTER_SHARPEN:
- filtermode = RAS_2DFilterManager::RAS_2DFILTER_SHARPEN;
- break;
- case ACT_2DFILTER_DILATION:
- filtermode = RAS_2DFilterManager::RAS_2DFILTER_DILATION;
- break;
- case ACT_2DFILTER_EROSION:
- filtermode = RAS_2DFilterManager::RAS_2DFILTER_EROSION;
- break;
- case ACT_2DFILTER_LAPLACIAN:
- filtermode = RAS_2DFilterManager::RAS_2DFILTER_LAPLACIAN;
- break;
- case ACT_2DFILTER_SOBEL:
- filtermode = RAS_2DFilterManager::RAS_2DFILTER_SOBEL;
- break;
- case ACT_2DFILTER_PREWITT:
- filtermode = RAS_2DFilterManager::RAS_2DFILTER_PREWITT;
- break;
- case ACT_2DFILTER_GRAYSCALE:
- filtermode = RAS_2DFilterManager::RAS_2DFILTER_GRAYSCALE;
- break;
- case ACT_2DFILTER_SEPIA:
- filtermode = RAS_2DFilterManager::RAS_2DFILTER_SEPIA;
- break;
- case ACT_2DFILTER_INVERT:
- filtermode = RAS_2DFilterManager::RAS_2DFILTER_INVERT;
- break;
- case ACT_2DFILTER_CUSTOMFILTER:
- filtermode = RAS_2DFilterManager::RAS_2DFILTER_CUSTOMFILTER;
- break;
- case ACT_2DFILTER_NOFILTER:
- filtermode = RAS_2DFilterManager::RAS_2DFILTER_NOFILTER;
- break;
- case ACT_2DFILTER_DISABLED:
- filtermode = RAS_2DFilterManager::RAS_2DFILTER_DISABLED;
- break;
- case ACT_2DFILTER_ENABLED:
- filtermode = RAS_2DFilterManager::RAS_2DFILTER_ENABLED;
- break;
- default:
- filtermode = RAS_2DFilterManager::RAS_2DFILTER_NOFILTER;
- break;
- }
-
- tmp = new SCA_2DFilterActuator(gameobj, filtermode, _2dfilter->flag,
- _2dfilter->float_arg, _2dfilter->int_arg,
- ketsjiEngine->GetRasterizer(), scene);
-
- if (_2dfilter->text)
- {
- char *buf;
- // this is some blender specific code
- buf = txt_to_buf(_2dfilter->text);
- if (buf)
- {
- tmp->SetShaderText(buf);
- MEM_freeN(buf);
- }
- }
-
- baseact = tmp;
-
- }
- break;
- case ACT_PARENT:
- {
- bParentActuator *parAct = (bParentActuator *) bact->data;
- int mode = KX_ParentActuator::KX_PARENT_NODEF;
- bool addToCompound = true;
- bool ghost = true;
- KX_GameObject *tmpgob = NULL;
-
- switch (parAct->type) {
- case ACT_PARENT_SET:
- mode = KX_ParentActuator::KX_PARENT_SET;
- tmpgob = converter->FindGameObject(parAct->ob);
- addToCompound = !(parAct->flag & ACT_PARENT_COMPOUND);
- ghost = !(parAct->flag & ACT_PARENT_GHOST);
- break;
- case ACT_PARENT_REMOVE:
- mode = KX_ParentActuator::KX_PARENT_REMOVE;
- tmpgob = NULL;
- break;
- }
-
- KX_ParentActuator *tmpparact
- = new KX_ParentActuator(gameobj,
- mode,
- addToCompound,
- ghost,
- tmpgob);
- baseact = tmpparact;
- break;
- }
-
- case ACT_ARMATURE:
- {
- bArmatureActuator* armAct = (bArmatureActuator*) bact->data;
- KX_GameObject *tmpgob = converter->FindGameObject(armAct->target);
- KX_GameObject *subgob = converter->FindGameObject(armAct->subtarget);
- BL_ArmatureActuator* tmparmact = new BL_ArmatureActuator(
- gameobj,
- armAct->type,
- armAct->posechannel,
- armAct->constraint,
- tmpgob,
- subgob,
- armAct->weight,
- armAct->influence);
- baseact = tmparmact;
- break;
- }
- case ACT_STEERING:
- {
- bSteeringActuator *stAct = (bSteeringActuator *) bact->data;
- KX_GameObject *navmeshob = NULL;
- if (stAct->navmesh)
- {
- PointerRNA settings_ptr;
- RNA_pointer_create((ID *)stAct->navmesh, &RNA_GameObjectSettings, stAct->navmesh, &settings_ptr);
- if (RNA_enum_get(&settings_ptr, "physics_type") == OB_BODY_TYPE_NAVMESH)
- navmeshob = converter->FindGameObject(stAct->navmesh);
- }
- KX_GameObject *targetob = converter->FindGameObject(stAct->target);
-
- int mode = KX_SteeringActuator::KX_STEERING_NODEF;
- switch (stAct->type) {
- case ACT_STEERING_SEEK:
- mode = KX_SteeringActuator::KX_STEERING_SEEK;
- break;
- case ACT_STEERING_FLEE:
- mode = KX_SteeringActuator::KX_STEERING_FLEE;
- break;
- case ACT_STEERING_PATHFOLLOWING:
- mode = KX_SteeringActuator::KX_STEERING_PATHFOLLOWING;
- break;
- }
-
- bool selfTerminated = (stAct->flag & ACT_STEERING_SELFTERMINATED) !=0;
- bool enableVisualization = (stAct->flag & ACT_STEERING_ENABLEVISUALIZATION) !=0;
- short facingMode = (stAct->flag & ACT_STEERING_AUTOMATICFACING) ? stAct->facingaxis : 0;
- bool normalup = (stAct->flag & ACT_STEERING_NORMALUP) !=0;
- bool lockzvel = (stAct->flag & ACT_STEERING_LOCKZVEL) !=0;
- KX_SteeringActuator *tmpstact
- = new KX_SteeringActuator(gameobj, mode, targetob, navmeshob,stAct->dist,
- stAct->velocity, stAct->acceleration, stAct->turnspeed,
- selfTerminated, stAct->updateTime,
- scene->GetObstacleSimulation(), facingMode, normalup, enableVisualization, lockzvel);
- baseact = tmpstact;
- break;
- }
- case ACT_MOUSE:
- {
- bMouseActuator* mouAct = (bMouseActuator*) bact->data;
- int mode = KX_MouseActuator::KX_ACT_MOUSE_NODEF;
-
- switch (mouAct->type) {
- case ACT_MOUSE_VISIBILITY:
- {
- mode = KX_MouseActuator::KX_ACT_MOUSE_VISIBILITY;
- break;
- }
- case ACT_MOUSE_LOOK:
- {
- mode = KX_MouseActuator::KX_ACT_MOUSE_LOOK;
- break;
- }
- }
-
- bool visible = (mouAct->flag & ACT_MOUSE_VISIBLE) != 0;
- bool use_axis[2] = {(mouAct->flag & ACT_MOUSE_USE_AXIS_X) != 0, (mouAct->flag & ACT_MOUSE_USE_AXIS_Y) != 0};
- bool reset[2] = {(mouAct->flag & ACT_MOUSE_RESET_X) != 0, (mouAct->flag & ACT_MOUSE_RESET_Y) != 0};
- bool local[2] = {(mouAct->flag & ACT_MOUSE_LOCAL_X) != 0, (mouAct->flag & ACT_MOUSE_LOCAL_Y) != 0};
-
- SCA_MouseManager* eventmgr = (SCA_MouseManager*) logicmgr->FindEventManager(SCA_EventManager::MOUSE_EVENTMGR);
- if (eventmgr) {
- KX_MouseActuator* tmpbaseact = new KX_MouseActuator(gameobj,
- ketsjiEngine,
- eventmgr,
- mode,
- visible,
- use_axis,
- mouAct->threshold,
- reset,
- mouAct->object_axis,
- local,
- mouAct->sensitivity,
- mouAct->limit_x,
- mouAct->limit_y);
- baseact = tmpbaseact;
- } else {
- //cout << "\n Couldn't find mouse event manager..."; - should throw an error here...
- }
- break;
- }
- default:
- ; /* generate some error */
- }
-
- if (baseact && !(bact->flag & ACT_DEACTIVATE))
- {
- baseact->SetExecutePriority(executePriority++);
- uniquename += "#ACT#";
- uniqueint++;
- CIntValue* uniqueval = new CIntValue(uniqueint);
- uniquename += uniqueval->GetText();
- uniqueval->Release();
- baseact->SetName(bact->name);
- baseact->SetLogicManager(logicmgr);
- //gameobj->SetProperty(uniquename,baseact);
- gameobj->AddActuator(baseact);
-
- converter->RegisterGameActuator(baseact, bact);
- // done with baseact, release it
- baseact->Release();
- }
- else if (baseact)
- baseact->Release();
-
- bact = bact->next;
- }
-}
-
-
diff --git a/source/gameengine/Converter/KX_ConvertActuators.h b/source/gameengine/Converter/KX_ConvertActuators.h
deleted file mode 100644
index 688b5db50ce..00000000000
--- a/source/gameengine/Converter/KX_ConvertActuators.h
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file KX_ConvertActuators.h
- * \ingroup bgeconv
- */
-
-#ifndef __KX_CONVERTACTUATORS_H__
-#define __KX_CONVERTACTUATORS_H__
-
-void BL_ConvertActuators(const char* maggiename,
- struct Object* blenderobject,
- class KX_GameObject* gameobj,
- class SCA_LogicManager* logicmgr,
- class KX_Scene* scene,
- class KX_KetsjiEngine* ketsjiEngine,
- int activeLayerBitInfo,
- bool isInActiveLayer,
- class KX_BlenderSceneConverter* converter);
-
-#endif /* __KX_CONVERTACTUATORS_H__ */
diff --git a/source/gameengine/Converter/KX_ConvertControllers.cpp b/source/gameengine/Converter/KX_ConvertControllers.cpp
deleted file mode 100644
index f55d81adb80..00000000000
--- a/source/gameengine/Converter/KX_ConvertControllers.cpp
+++ /dev/null
@@ -1,250 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Converter/KX_ConvertControllers.cpp
- * \ingroup bgeconv
- */
-
-
-#include "MEM_guardedalloc.h"
-
-#include "KX_BlenderSceneConverter.h"
-#include "KX_ConvertControllers.h"
-#include "EXP_Python.h"
-
-// Controller
-#include "SCA_ANDController.h"
-#include "SCA_ORController.h"
-#include "SCA_NANDController.h"
-#include "SCA_NORController.h"
-#include "SCA_XORController.h"
-#include "SCA_XNORController.h"
-#include "SCA_PythonController.h"
-#include "SCA_ExpressionController.h"
-
-#include "SCA_LogicManager.h"
-#include "KX_GameObject.h"
-#include "EXP_IntValue.h"
-
-/* This little block needed for linking to Blender... */
-#ifdef WIN32
-#include "BLI_winstuff.h"
-#endif
-
-#include "DNA_object_types.h"
-#include "DNA_controller_types.h"
-#include "DNA_text_types.h"
-
-#include "BKE_text.h"
-
-#include "BLI_blenlib.h"
-
-/* end of blender include block */
-
-
- static void
-LinkControllerToActuators(
- SCA_IController *game_controller,
- bController* bcontr,
- SCA_LogicManager* logicmgr,
- KX_BlenderSceneConverter* converter
-) {
- // Iterate through the actuators of the game blender
- // controller and find the corresponding ketsji actuator.
-
- game_controller->ReserveActuator(bcontr->totlinks);
- for (int i=0;i<bcontr->totlinks;i++)
- {
- bActuator* bact = (bActuator*) bcontr->links[i];
- SCA_IActuator *game_actuator = converter->FindGameActuator(bact);
- if (game_actuator) {
- logicmgr->RegisterToActuator(game_controller, game_actuator);
- }
- }
-}
-
-
-void BL_ConvertControllers(
- struct Object* blenderobject,
- class KX_GameObject* gameobj,
- SCA_LogicManager* logicmgr,
- int activeLayerBitInfo,
- bool isInActiveLayer,
- KX_BlenderSceneConverter* converter,
- bool libloading
-) {
- int uniqueint=0;
- int count = 0;
- int executePriority=0;
- bController* bcontr = (bController*)blenderobject->controllers.first;
- while (bcontr)
- {
- bcontr = bcontr->next;
- count++;
- }
- gameobj->ReserveController(count);
- bcontr = (bController*)blenderobject->controllers.first;
- while (bcontr)
- {
- SCA_IController* gamecontroller = NULL;
- switch (bcontr->type) {
- case CONT_LOGIC_AND:
- {
- gamecontroller = new SCA_ANDController(gameobj);
- break;
- }
- case CONT_LOGIC_OR:
- {
- gamecontroller = new SCA_ORController(gameobj);
- break;
- }
- case CONT_LOGIC_NAND:
- {
- gamecontroller = new SCA_NANDController(gameobj);
- break;
- }
- case CONT_LOGIC_NOR:
- {
- gamecontroller = new SCA_NORController(gameobj);
- break;
- }
- case CONT_LOGIC_XOR:
- {
- gamecontroller = new SCA_XORController(gameobj);
- break;
- }
- case CONT_LOGIC_XNOR:
- {
- gamecontroller = new SCA_XNORController(gameobj);
- break;
- }
- case CONT_EXPRESSION:
- {
- bExpressionCont* bexpcont = (bExpressionCont*) bcontr->data;
- STR_String expressiontext = STR_String(bexpcont->str);
- if (expressiontext.Length() > 0)
- {
- gamecontroller = new SCA_ExpressionController(gameobj,expressiontext);
- }
- break;
- }
- case CONT_PYTHON:
- {
- bPythonCont* pycont = (bPythonCont*) bcontr->data;
- SCA_PythonController* pyctrl = new SCA_PythonController(gameobj, pycont->mode);
- gamecontroller = pyctrl;
-#ifdef WITH_PYTHON
- // When libloading, this is delayed to KX_Scene::MergeScene_LogicBrick to avoid GIL issues
- if (!libloading)
- pyctrl->SetNamespace(converter->GetPyNamespace());
-
- if (pycont->mode==SCA_PythonController::SCA_PYEXEC_SCRIPT) {
- if (pycont->text)
- {
- char *buf;
- // this is some blender specific code
- buf= txt_to_buf(pycont->text);
- if (buf)
- {
- pyctrl->SetScriptText(STR_String(buf));
- pyctrl->SetScriptName(pycont->text->id.name+2);
- MEM_freeN(buf);
- }
-
- }
- }
- else {
- /* let the controller print any warnings here when importing */
- pyctrl->SetScriptText(STR_String(pycont->module));
- pyctrl->SetScriptName(pycont->module); /* will be something like module.func so using it as the name is OK */
-
- if (pycont->flag & CONT_PY_DEBUG) {
- printf("\nDebuging \"%s\", module for object %s\n\texpect worse performance.\n", pycont->module, blenderobject->id.name+2);
- pyctrl->SetDebug(true);
- }
- }
-#endif // WITH_PYTHON
-
- break;
- }
- default:
- {
-
- }
- }
-
- if (gamecontroller && !(bcontr->flag & CONT_DEACTIVATE))
- {
- LinkControllerToActuators(gamecontroller,bcontr,logicmgr,converter);
- gamecontroller->SetExecutePriority(executePriority++);
- gamecontroller->SetBookmark((bcontr->flag & CONT_PRIO) != 0);
- gamecontroller->SetState(bcontr->state_mask);
- STR_String uniquename = bcontr->name;
- uniquename += "#CONTR#";
- uniqueint++;
- CIntValue* uniqueval = new CIntValue(uniqueint);
- uniquename += uniqueval->GetText();
- uniqueval->Release();
- //unique name was never implemented for sensors and actuators, only for controllers
- //and it's producing difference in the keys for the lists: obj.controllers/sensors/actuators
- //at some point it should either be implemented globally (and saved as a separate var) or removed.
- //gamecontroller->SetName(uniquename);
- gamecontroller->SetName(bcontr->name);
- gamecontroller->SetLogicManager(logicmgr);
- gameobj->AddController(gamecontroller);
-
- converter->RegisterGameController(gamecontroller, bcontr);
-
-#ifdef WITH_PYTHON
- // When libloading, this is delayed to KX_Scene::MergeScene_LogicBrick to avoid GIL issues
- if (!libloading && bcontr->type==CONT_PYTHON) {
- SCA_PythonController *pyctrl= static_cast<SCA_PythonController*>(gamecontroller);
- /* not strictly needed but gives syntax errors early on and
- * gives more predictable performance for larger scripts */
- if (pyctrl->m_mode==SCA_PythonController::SCA_PYEXEC_SCRIPT)
- pyctrl->Compile();
- else {
- /* We cant do this because importing runs the script which could end up accessing
- * internal BGE functions, this is unstable while we're converting the scene.
- * This is a pity because its useful to see errors at startup but cant help it */
-
- // pyctrl->Import();
- }
- }
-
-#endif // WITH_PYTHON
-
- //done with gamecontroller
- gamecontroller->Release();
- }
- else if (gamecontroller)
- gamecontroller->Release();
-
- bcontr = bcontr->next;
- }
-
-}
diff --git a/source/gameengine/Converter/KX_ConvertControllers.h b/source/gameengine/Converter/KX_ConvertControllers.h
deleted file mode 100644
index 2f93d70a6f9..00000000000
--- a/source/gameengine/Converter/KX_ConvertControllers.h
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file KX_ConvertControllers.h
- * \ingroup bgeconv
- */
-
-#ifndef __KX_CONVERTCONTROLLERS_H__
-#define __KX_CONVERTCONTROLLERS_H__
-
-#include "EXP_Python.h"
-
-void BL_ConvertControllers(
- struct Object* blenderobject,
- class KX_GameObject* gameobj,
- class SCA_LogicManager* logicmgr,
- int activeLayerBitInfo,
- bool isInActiveLayer,
- class KX_BlenderSceneConverter* converter,
- bool libloading
-);
-
-#endif /* __KX_CONVERTCONTROLLERS_H__ */
diff --git a/source/gameengine/Converter/KX_ConvertProperties.cpp b/source/gameengine/Converter/KX_ConvertProperties.cpp
deleted file mode 100644
index 2cb61207fb5..00000000000
--- a/source/gameengine/Converter/KX_ConvertProperties.cpp
+++ /dev/null
@@ -1,243 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Converter/KX_ConvertProperties.cpp
- * \ingroup bgeconv
- */
-
-
-#include "KX_ConvertProperties.h"
-
-
-#include "DNA_object_types.h"
-#include "DNA_property_types.h"
-/* end of blender include block */
-
-
-#include "EXP_Value.h"
-#include "EXP_VectorValue.h"
-#include "EXP_BoolValue.h"
-#include "EXP_StringValue.h"
-#include "EXP_FloatValue.h"
-#include "KX_GameObject.h"
-#include "EXP_IntValue.h"
-#include "SCA_TimeEventManager.h"
-#include "SCA_IScene.h"
-
-#include "KX_FontObject.h"
-#include "DNA_curve_types.h"
-
-/* This little block needed for linking to Blender... */
-#ifdef WIN32
-#include "BLI_winstuff.h"
-#endif
-
-extern "C" {
- #include "BKE_property.h"
-}
-
-/* prototype */
-void BL_ConvertTextProperty(Object* object, KX_FontObject* fontobj,SCA_TimeEventManager* timemgr,SCA_IScene* scene, bool isInActiveLayer);
-
-void BL_ConvertProperties(Object* object,KX_GameObject* gameobj,SCA_TimeEventManager* timemgr,SCA_IScene* scene, bool isInActiveLayer)
-{
-
- bProperty* prop = (bProperty*)object->prop.first;
- CValue* propval;
- bool show_debug_info;
-
- while (prop) {
- propval = NULL;
- show_debug_info = bool (prop->flag & PROP_DEBUG);
-
- switch (prop->type) {
- case GPROP_BOOL:
- {
- propval = new CBoolValue((bool)(prop->data != 0));
- gameobj->SetProperty(prop->name,propval);
- //promp->poin= &prop->data;
- break;
- }
- case GPROP_INT:
- {
- propval = new CIntValue((int)prop->data);
- gameobj->SetProperty(prop->name,propval);
- break;
- }
- case GPROP_FLOAT:
- {
- //prop->poin= &prop->data;
- float floatprop = *((float*)&prop->data);
- propval = new CFloatValue(floatprop);
- gameobj->SetProperty(prop->name,propval);
- }
- break;
- case GPROP_STRING:
- {
- //prop->poin= callocN(MAX_PROPSTRING, "property string");
- propval = new CStringValue((char*)prop->poin,"");
- gameobj->SetProperty(prop->name,propval);
- break;
- }
- case GPROP_TIME:
- {
- float floatprop = *((float*)&prop->data);
-
- CValue* timeval = new CFloatValue(floatprop);
- // set a subproperty called 'timer' so that
- // we can register the replica of this property
- // at the time a game object is replicated (AddObjectActuator triggers this)
- CValue *bval = new CBoolValue(true);
- timeval->SetProperty("timer",bval);
- bval->Release();
- if (isInActiveLayer)
- {
- timemgr->AddTimeProperty(timeval);
- }
-
- propval = timeval;
- gameobj->SetProperty(prop->name,timeval);
-
- }
- default:
- {
- // todo make an assert etc.
- }
- }
-
- if (propval)
- {
- if (show_debug_info && isInActiveLayer)
- {
- scene->AddDebugProperty(gameobj,STR_String(prop->name));
- }
- // done with propval, release it
- propval->Release();
- }
-
-#ifdef WITH_PYTHON
- /* Warn if we double up on attributes, this isn't quite right since it wont find inherited attributes however there arnt many */
- for (PyAttributeDef *attrdef = KX_GameObject::Attributes; attrdef->m_name; attrdef++) {
- if (strcmp(prop->name, attrdef->m_name)==0) {
- printf("Warning! user defined property name \"%s\" is also a python attribute for object \"%s\"\n\tUse ob[\"%s\"] syntax to avoid conflict\n", prop->name, object->id.name+2, prop->name);
- break;
- }
- }
- for (PyMethodDef *methdef = KX_GameObject::Methods; methdef->ml_name; methdef++) {
- if (strcmp(prop->name, methdef->ml_name)==0) {
- printf("Warning! user defined property name \"%s\" is also a python method for object \"%s\"\n\tUse ob[\"%s\"] syntax to avoid conflict\n", prop->name, object->id.name+2, prop->name);
- break;
- }
- }
- /* end warning check */
-#endif // WITH_PYTHON
-
- prop = prop->next;
- }
- // check if state needs to be debugged
- if (object->scaflag & OB_DEBUGSTATE && isInActiveLayer)
- {
- // reserve name for object state
- scene->AddDebugProperty(gameobj,STR_String("__state__"));
- }
-
- /* Font Objects need to 'copy' the Font Object data body to ["Text"] */
- if (object->type == OB_FONT)
- {
- BL_ConvertTextProperty(object, (KX_FontObject *)gameobj, timemgr, scene, isInActiveLayer);
- }
-}
-
-void BL_ConvertTextProperty(Object* object, KX_FontObject* fontobj,SCA_TimeEventManager* timemgr,SCA_IScene* scene, bool isInActiveLayer)
-{
- CValue* tprop = fontobj->GetProperty("Text");
- if (!tprop) return;
- bProperty* prop = BKE_bproperty_object_get(object, "Text");
- if (!prop) return;
-
- Curve *curve = static_cast<Curve *>(object->data);
- STR_String str = curve->str;
- CValue* propval = NULL;
-
- switch (prop->type) {
- case GPROP_BOOL:
- {
- int value = atoi(str);
- propval = new CBoolValue((bool)(value != 0));
- tprop->SetValue(propval);
- break;
- }
- case GPROP_INT:
- {
- int value = atoi(str);
- propval = new CIntValue(value);
- tprop->SetValue(propval);
- break;
- }
- case GPROP_FLOAT:
- {
- float floatprop = (float)atof(str);
- propval = new CFloatValue(floatprop);
- tprop->SetValue(propval);
- break;
- }
- case GPROP_STRING:
- {
- propval = new CStringValue(str, "");
- tprop->SetValue(propval);
- break;
- }
- case GPROP_TIME:
- {
- float floatprop = (float)atof(str);
-
- CValue* timeval = new CFloatValue(floatprop);
- // set a subproperty called 'timer' so that
- // we can register the replica of this property
- // at the time a game object is replicated (AddObjectActuator triggers this)
- CValue *bval = new CBoolValue(true);
- timeval->SetProperty("timer",bval);
- bval->Release();
- if (isInActiveLayer)
- {
- timemgr->AddTimeProperty(timeval);
- }
-
- propval = timeval;
- tprop->SetValue(timeval);
- }
- default:
- {
- // todo make an assert etc.
- }
- }
-
- if (propval) {
- propval->Release();
- }
-}
-
diff --git a/source/gameengine/Converter/KX_ConvertProperties.h b/source/gameengine/Converter/KX_ConvertProperties.h
deleted file mode 100644
index 8f96cc21af6..00000000000
--- a/source/gameengine/Converter/KX_ConvertProperties.h
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file KX_ConvertProperties.h
- * \ingroup bgeconv
- */
-
-#ifndef __KX_CONVERTPROPERTIES_H__
-#define __KX_CONVERTPROPERTIES_H__
-
-void BL_ConvertProperties(struct Object* object,
- class KX_GameObject* gameobj,
- class SCA_TimeEventManager* timemgr,
- class SCA_IScene* scene,
- bool isInActiveLayer);
-
-#endif /* __KX_CONVERTPROPERTIES_H__ */
diff --git a/source/gameengine/Converter/KX_ConvertSensors.cpp b/source/gameengine/Converter/KX_ConvertSensors.cpp
deleted file mode 100644
index 5e897bb4a62..00000000000
--- a/source/gameengine/Converter/KX_ConvertSensors.cpp
+++ /dev/null
@@ -1,663 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Converter/KX_ConvertSensors.cpp
- * \ingroup bgeconv
- *
- * Conversion of Blender data blocks to KX sensor system
- */
-
-#include <stdio.h>
-
-#ifdef _MSC_VER
-# pragma warning (disable:4786)
-#endif
-
-#include "wm_event_types.h"
-#include "KX_BlenderSceneConverter.h"
-#include "KX_ConvertSensors.h"
-
-/* This little block needed for linking to Blender... */
-#ifdef _MSC_VER
-# include "BLI_winstuff.h"
-#endif
-
-#include "DNA_object_types.h"
-#include "DNA_material_types.h"
-#include "DNA_sensor_types.h"
-#include "DNA_controller_types.h"
-#include "DNA_actuator_types.h" /* for SENS_ALL_KEYS ? this define is
- * probably misplaced */
-/* end of blender include block */
-
-#include "RAS_IPolygonMaterial.h"
-// Sensors
-#include "KX_GameObject.h"
-#include "RAS_MeshObject.h"
-#include "SCA_KeyboardSensor.h"
-#include "SCA_MouseSensor.h"
-#include "SCA_AlwaysSensor.h"
-#include "KX_TouchSensor.h"
-#include "KX_NearSensor.h"
-#include "KX_RadarSensor.h"
-#include "KX_MouseFocusSensor.h"
-#include "KX_ArmatureSensor.h"
-#include "SCA_JoystickSensor.h"
-#include "KX_NetworkMessageSensor.h"
-#include "SCA_ActuatorSensor.h"
-#include "SCA_DelaySensor.h"
-
-
-#include "SCA_PropertySensor.h"
-#include "SCA_RandomSensor.h"
-#include "KX_RaySensor.h"
-#include "SCA_EventManager.h"
-#include "SCA_LogicManager.h"
-#include "KX_BlenderInputDevice.h"
-#include "KX_Scene.h"
-#include "EXP_IntValue.h"
-#include "KX_BlenderKeyboardDevice.h"
-#include "RAS_ICanvas.h"
-#include "PHY_IPhysicsEnvironment.h"
-
-#include "KX_KetsjiEngine.h"
-#include "BL_BlenderDataConversion.h"
-
-void BL_ConvertSensors(struct Object* blenderobject,
- class KX_GameObject* gameobj,
- SCA_LogicManager* logicmgr,
- KX_Scene* kxscene,
- KX_KetsjiEngine* kxengine,
- int activeLayerBitInfo,
- bool isInActiveLayer,
- RAS_ICanvas* canvas,
- KX_BlenderSceneConverter* converter
- )
-{
-
- int executePriority = 0;
- int uniqueint = 0;
- int count = 0;
- bSensor* sens = (bSensor*)blenderobject->sensors.first;
- bool pos_pulsemode = false;
- bool neg_pulsemode = false;
- int skipped_ticks = 0;
- bool invert = false;
- bool level = false;
- bool tap = false;
-
- while (sens)
- {
- sens = sens->next;
- count++;
- }
- gameobj->ReserveSensor(count);
- sens = (bSensor*)blenderobject->sensors.first;
-
- while (sens) {
- if (!(sens->flag & SENS_DEACTIVATE)) {
- SCA_ISensor* gamesensor=NULL;
- /* All sensors have a pulse toggle, skipped ticks parameter, and invert field. */
- /* These are extracted here, and set when the sensor is added to the */
- /* list. */
- pos_pulsemode = (sens->pulse & SENS_PULSE_REPEAT)!=0;
- neg_pulsemode = (sens->pulse & SENS_NEG_PULSE_MODE)!=0;
-
- skipped_ticks = sens->freq;
- invert = !(sens->invert == 0);
- level = !(sens->level == 0);
- tap = !(sens->tap == 0);
-
- switch (sens->type)
- {
- case SENS_ALWAYS:
- {
-
- SCA_EventManager* eventmgr = logicmgr->FindEventManager(SCA_EventManager::BASIC_EVENTMGR);
- if (eventmgr)
- {
- gamesensor = new SCA_AlwaysSensor(eventmgr, gameobj);
- }
-
- break;
- }
-
- case SENS_DELAY:
- {
- // we can reuse the Always event manager for the delay sensor
- SCA_EventManager* eventmgr = logicmgr->FindEventManager(SCA_EventManager::BASIC_EVENTMGR);
- if (eventmgr)
- {
- bDelaySensor* delaysensor = (bDelaySensor*)sens->data;
- gamesensor = new SCA_DelaySensor(eventmgr,
- gameobj,
- delaysensor->delay,
- delaysensor->duration,
- (delaysensor->flag & SENS_DELAY_REPEAT) != 0);
- }
- break;
- }
-
- case SENS_COLLISION:
- {
- SCA_EventManager* eventmgr = logicmgr->FindEventManager(SCA_EventManager::TOUCH_EVENTMGR);
- if (eventmgr)
- {
- // collision sensor can sense both materials and properties.
-
- bool bFindMaterial = false, bTouchPulse = false;
-
- bCollisionSensor* blendertouchsensor = (bCollisionSensor*)sens->data;
-
- bFindMaterial = (blendertouchsensor->mode & SENS_COLLISION_MATERIAL);
- bTouchPulse = (blendertouchsensor->mode & SENS_COLLISION_PULSE);
-
-
- const STR_String touchPropOrMatName = bFindMaterial ?
- blendertouchsensor->materialName : blendertouchsensor->name;
-
-
- if (gameobj->GetPhysicsController())
- {
- gamesensor = new KX_TouchSensor(eventmgr,
- gameobj,
- bFindMaterial,
- bTouchPulse,
- touchPropOrMatName);
- }
-
- }
-
- break;
- }
- case SENS_MESSAGE:
- {
- KX_NetworkEventManager* eventmgr = (KX_NetworkEventManager*)
- logicmgr->FindEventManager(SCA_EventManager::NETWORK_EVENTMGR);
- if (eventmgr) {
- bMessageSensor* msgSens = (bMessageSensor*) sens->data;
-
- /* Get our NetworkScene */
- NG_NetworkScene *NetworkScene = kxscene->GetNetworkScene();
- /* filter on the incoming subjects, might be empty */
- const STR_String subject = msgSens->subject;
-
- gamesensor = new KX_NetworkMessageSensor(
- eventmgr, // our eventmanager
- NetworkScene, // our NetworkScene
- gameobj, // the sensor controlling object
- subject); // subject to filter on
- }
- break;
- }
- case SENS_NEAR:
- {
-
- SCA_EventManager* eventmgr = logicmgr->FindEventManager(SCA_EventManager::TOUCH_EVENTMGR);
- if (eventmgr)
- {
- bNearSensor* blendernearsensor = (bNearSensor*)sens->data;
- const STR_String nearpropertyname = (char *)blendernearsensor->name;
-
- //DT_ShapeHandle shape = DT_Sphere(0.0);
-
- // this sumoObject is not deleted by a gameobj, so delete it ourself
- // later (memleaks)!
- float radius = blendernearsensor->dist;
- const MT_Vector3& wpos = gameobj->NodeGetWorldPosition();
- bool bFindMaterial = false;
- PHY_IPhysicsController* physCtrl = kxscene->GetPhysicsEnvironment()->CreateSphereController(radius,wpos);
-
- //will be done in KX_TouchEventManager::RegisterSensor()
- //if (isInActiveLayer)
- // kxscene->GetPhysicsEnvironment()->addSensor(physCtrl);
-
-
-
- gamesensor = new KX_NearSensor(eventmgr,gameobj,
- blendernearsensor->dist,
- blendernearsensor->resetdist,
- bFindMaterial,
- nearpropertyname,
- physCtrl);
-
- }
- break;
- }
-
-
- case SENS_KEYBOARD:
- {
- /* temporary input device, for converting the code for the keyboard sensor */
-
- bKeyboardSensor* blenderkeybdsensor = (bKeyboardSensor*)sens->data;
- SCA_KeyboardManager* eventmgr = (SCA_KeyboardManager*) logicmgr->FindEventManager(SCA_EventManager::KEYBOARD_EVENTMGR);
- if (eventmgr)
- {
- gamesensor = new SCA_KeyboardSensor(eventmgr,
- ConvertKeyCode(blenderkeybdsensor->key),
- ConvertKeyCode(blenderkeybdsensor->qual),
- ConvertKeyCode(blenderkeybdsensor->qual2),
- (blenderkeybdsensor->type == SENS_ALL_KEYS),
- blenderkeybdsensor->targetName,
- blenderkeybdsensor->toggleName,
- gameobj,
- KX_KetsjiEngine::GetExitKey()); // blenderkeybdsensor->pad);
-
- }
-
- break;
- }
- case SENS_MOUSE:
- {
- int keytype = SCA_MouseSensor::KX_MOUSESENSORMODE_NODEF;
- int trackfocus = 0;
- bMouseSensor *bmouse = (bMouseSensor *)sens->data;
-
- /* There are two main types of mouse sensors. If there is
- * no focus-related behavior requested, we can make do
- * with a basic sensor. This cuts down memory usage and
- * gives a slight performance gain. */
-
- SCA_MouseManager *eventmgr
- = (SCA_MouseManager*) logicmgr->FindEventManager(SCA_EventManager::MOUSE_EVENTMGR);
- if (eventmgr) {
-
- /* Determine key mode. There is at most one active mode. */
- switch (bmouse->type) {
- case BL_SENS_MOUSE_LEFT_BUTTON:
- keytype = SCA_MouseSensor::KX_MOUSESENSORMODE_LEFTBUTTON;
- break;
- case BL_SENS_MOUSE_MIDDLE_BUTTON:
- keytype = SCA_MouseSensor::KX_MOUSESENSORMODE_MIDDLEBUTTON;
- break;
- case BL_SENS_MOUSE_RIGHT_BUTTON:
- keytype = SCA_MouseSensor::KX_MOUSESENSORMODE_RIGHTBUTTON;
- break;
- case BL_SENS_MOUSE_WHEEL_UP:
- keytype = SCA_MouseSensor::KX_MOUSESENSORMODE_WHEELUP;
- break;
- case BL_SENS_MOUSE_WHEEL_DOWN:
- keytype = SCA_MouseSensor::KX_MOUSESENSORMODE_WHEELDOWN;
- break;
- case BL_SENS_MOUSE_MOVEMENT:
- keytype = SCA_MouseSensor::KX_MOUSESENSORMODE_MOVEMENT;
- break;
- case BL_SENS_MOUSE_MOUSEOVER:
- trackfocus = 1;
- break;
- case BL_SENS_MOUSE_MOUSEOVER_ANY:
- trackfocus = 2;
- break;
-
- default:
- ; /* error */
- }
-
- /* initial mouse position */
- int startx = canvas->GetWidth()/2;
- int starty = canvas->GetHeight()/2;
-
- if (!trackfocus) {
- /* plain, simple mouse sensor */
- gamesensor = new SCA_MouseSensor(eventmgr,
- startx,starty,
- keytype,
- gameobj);
- } else {
- /* give us a focus-aware sensor */
- bool bFindMaterial = (bmouse->mode & SENS_COLLISION_MATERIAL);
- bool bXRay = (bmouse->flag & SENS_RAY_XRAY);
- STR_String checkname = (bFindMaterial? bmouse->matname : bmouse->propname);
-
- gamesensor = new KX_MouseFocusSensor(eventmgr,
- startx,
- starty,
- keytype,
- trackfocus,
- (bmouse->flag & SENS_MOUSE_FOCUS_PULSE) ? true:false,
- checkname,
- bFindMaterial,
- bXRay,
- kxscene,
- kxengine,
- gameobj);
- }
- } else {
- // cout << "\n Could't find mouse event manager..."; - should throw an error here...
- }
- break;
- }
- case SENS_PROPERTY:
- {
- bPropertySensor* blenderpropsensor = (bPropertySensor*) sens->data;
- SCA_EventManager* eventmgr
- = logicmgr->FindEventManager(SCA_EventManager::BASIC_EVENTMGR);
- if (eventmgr)
- {
- STR_String propname=blenderpropsensor->name;
- STR_String propval=blenderpropsensor->value;
- STR_String propmaxval=blenderpropsensor->maxvalue;
-
- SCA_PropertySensor::KX_PROPSENSOR_TYPE
- propchecktype = SCA_PropertySensor::KX_PROPSENSOR_NODEF;
-
- /* Better do an explicit conversion here! (was implicit */
- /* before...) */
- switch (blenderpropsensor->type) {
- case SENS_PROP_EQUAL:
- propchecktype = SCA_PropertySensor::KX_PROPSENSOR_EQUAL;
- break;
- case SENS_PROP_NEQUAL:
- propchecktype = SCA_PropertySensor::KX_PROPSENSOR_NOTEQUAL;
- break;
- case SENS_PROP_INTERVAL:
- propchecktype = SCA_PropertySensor::KX_PROPSENSOR_INTERVAL;
- break;
- case SENS_PROP_CHANGED:
- propchecktype = SCA_PropertySensor::KX_PROPSENSOR_CHANGED;
- break;
- case SENS_PROP_EXPRESSION:
- propchecktype = SCA_PropertySensor::KX_PROPSENSOR_EXPRESSION;
- /* error */
- break;
- case SENS_PROP_LESSTHAN:
- propchecktype = SCA_PropertySensor::KX_PROPSENSOR_LESSTHAN;
- break;
- case SENS_PROP_GREATERTHAN:
- propchecktype = SCA_PropertySensor::KX_PROPSENSOR_GREATERTHAN;
- break;
- default:
- ; /* error */
- }
- gamesensor = new SCA_PropertySensor(eventmgr,gameobj,propname,propval,propmaxval,propchecktype);
- }
-
- break;
- }
- case SENS_ACTUATOR:
- {
- bActuatorSensor* blenderactsensor = (bActuatorSensor*) sens->data;
- // we will reuse the property event manager, there is nothing special with this sensor
- SCA_EventManager* eventmgr
- = logicmgr->FindEventManager(SCA_EventManager::ACTUATOR_EVENTMGR);
- if (eventmgr)
- {
- STR_String propname=blenderactsensor->name;
- gamesensor = new SCA_ActuatorSensor(eventmgr,gameobj,propname);
- }
- break;
- }
-
- case SENS_ARMATURE:
- {
- bArmatureSensor* blenderarmsensor = (bArmatureSensor*) sens->data;
- // we will reuse the property event manager, there is nothing special with this sensor
- SCA_EventManager* eventmgr
- = logicmgr->FindEventManager(SCA_EventManager::BASIC_EVENTMGR);
- if (eventmgr)
- {
- STR_String bonename=blenderarmsensor->posechannel;
- STR_String constraintname=blenderarmsensor->constraint;
- gamesensor = new KX_ArmatureSensor(eventmgr,gameobj,bonename,constraintname, blenderarmsensor->type, blenderarmsensor->value);
- }
- break;
- }
-
- case SENS_RADAR:
- {
-
- SCA_EventManager* eventmgr = logicmgr->FindEventManager(SCA_EventManager::TOUCH_EVENTMGR);
- if (eventmgr)
- {
- bRadarSensor* blenderradarsensor = (bRadarSensor*) sens->data;
- const STR_String radarpropertyname = blenderradarsensor->name;
-
- int radaraxis = blenderradarsensor->axis;
-
- MT_Scalar coneheight = blenderradarsensor->range;
-
- // janco: the angle was doubled, so should I divide the factor in 2
- // or the blenderradarsensor->angle?
- // nzc: the angle is the opening angle. We need to init with
- // the axis-hull angle,so /2.0.
- MT_Scalar factor = tan(blenderradarsensor->angle * 0.5f);
- //MT_Scalar coneradius = coneheight * (factor / 2);
- MT_Scalar coneradius = coneheight * factor;
-
-
- // this sumoObject is not deleted by a gameobj, so delete it ourself
- // later (memleaks)!
- MT_Scalar smallmargin = 0.0;
- MT_Scalar largemargin = 0.0;
-
- bool bFindMaterial = false;
- PHY_IPhysicsController* ctrl = kxscene->GetPhysicsEnvironment()->CreateConeController((float)coneradius, (float)coneheight);
-
- gamesensor = new KX_RadarSensor(
- eventmgr,
- gameobj,
- ctrl,
- coneradius,
- coneheight,
- radaraxis,
- smallmargin,
- largemargin,
- bFindMaterial,
- radarpropertyname);
-
- }
-
- break;
- }
- case SENS_RAY:
- {
- bRaySensor* blenderraysensor = (bRaySensor*) sens->data;
-
- //blenderradarsensor->angle;
- SCA_EventManager* eventmgr = logicmgr->FindEventManager(SCA_EventManager::BASIC_EVENTMGR);
- if (eventmgr)
- {
- bool bFindMaterial = (blenderraysensor->mode & SENS_COLLISION_MATERIAL);
- bool bXRay = (blenderraysensor->mode & SENS_RAY_XRAY);
-
- STR_String checkname = (bFindMaterial? blenderraysensor->matname : blenderraysensor->propname);
-
- // don't want to get rays of length 0.0 or so
- double distance = (blenderraysensor->range < 0.01f ? 0.01f : blenderraysensor->range);
- int axis = blenderraysensor->axisflag;
-
-
- gamesensor = new KX_RaySensor(eventmgr,
- gameobj,
- checkname,
- bFindMaterial,
- bXRay,
- distance,
- axis,
- kxscene);
-
- }
- break;
- }
-
- case SENS_RANDOM:
- {
- bRandomSensor* blenderrndsensor = (bRandomSensor*) sens->data;
- // some files didn't write randomsensor, avoid crash now for NULL ptr's
- if (blenderrndsensor)
- {
- SCA_EventManager* eventmgr = logicmgr->FindEventManager(SCA_EventManager::BASIC_EVENTMGR);
- if (eventmgr)
- {
- int randomSeed = blenderrndsensor->seed;
- if (randomSeed == 0)
- {
- randomSeed = (int)(kxengine->GetRealTime()*100000.0);
- randomSeed ^= (intptr_t)blenderrndsensor;
- }
- gamesensor = new SCA_RandomSensor(eventmgr, gameobj, randomSeed);
- }
- }
- break;
- }
- case SENS_JOYSTICK:
- {
- int joysticktype = SCA_JoystickSensor::KX_JOYSENSORMODE_NODEF;
-
- bJoystickSensor* bjoy = (bJoystickSensor*) sens->data;
-
- SCA_JoystickManager *eventmgr
- = (SCA_JoystickManager*) logicmgr->FindEventManager(SCA_EventManager::JOY_EVENTMGR);
- if (eventmgr)
- {
- int axis =0;
- int axisf =0;
- int button =0;
- int hat =0;
- int hatf =0;
- int prec =0;
-
- switch (bjoy->type) {
- case SENS_JOY_AXIS:
- axis = bjoy->axis;
- axisf = bjoy->axisf;
- prec = bjoy->precision;
- joysticktype = SCA_JoystickSensor::KX_JOYSENSORMODE_AXIS;
- break;
- case SENS_JOY_BUTTON:
- button = bjoy->button;
- joysticktype = SCA_JoystickSensor::KX_JOYSENSORMODE_BUTTON;
- break;
- case SENS_JOY_HAT:
- hat = bjoy->hat;
- hatf = bjoy->hatf;
- joysticktype = SCA_JoystickSensor::KX_JOYSENSORMODE_HAT;
- break;
- case SENS_JOY_AXIS_SINGLE:
- axis = bjoy->axis_single;
- prec = bjoy->precision;
- joysticktype = SCA_JoystickSensor::KX_JOYSENSORMODE_AXIS_SINGLE;
- break;
- default:
- printf("Error: bad case statement\n");
- break;
- }
- gamesensor = new SCA_JoystickSensor(
- eventmgr,
- gameobj,
- bjoy->joyindex,
- joysticktype,
- axis,axisf,
- prec,
- button,
- hat,hatf,
- (bjoy->flag & SENS_JOY_ANY_EVENT));
- }
- else
- {
- printf("Error there was a problem finding the event manager\n");
- }
-
- break;
- }
- default:
- {
- }
- }
-
- if (gamesensor)
- {
- gamesensor->SetExecutePriority(executePriority++);
- STR_String uniquename = sens->name;
- uniquename += "#SENS#";
- uniqueint++;
- CIntValue* uniqueval = new CIntValue(uniqueint);
- uniquename += uniqueval->GetText();
- uniqueval->Release();
-
- /* Conversion succeeded, so we can set the generic props here. */
- gamesensor->SetPulseMode(pos_pulsemode,
- neg_pulsemode,
- skipped_ticks);
- gamesensor->SetInvert(invert);
- gamesensor->SetLevel(level);
- gamesensor->SetTap(tap);
- gamesensor->SetName(sens->name);
- gamesensor->SetLogicManager(logicmgr);
-
- gameobj->AddSensor(gamesensor);
-
- // only register to manager if it's in an active layer
- // Make registration dynamic: only when sensor is activated
- //if (isInActiveLayer)
- // gamesensor->RegisterToManager();
-
- gamesensor->ReserveController(sens->totlinks);
- for (int i=0;i<sens->totlinks;i++)
- {
- bController* linkedcont = (bController*) sens->links[i];
- if (linkedcont) {
- // If the controller is deactived doesn't register it
- if (!(linkedcont->flag & CONT_DEACTIVATE)) {
- SCA_IController* gamecont = converter->FindGameController(linkedcont);
-
- if (gamecont) {
- logicmgr->RegisterToSensor(gamecont,gamesensor);
- }
- else {
- printf("Warning, sensor \"%s\" could not find its controller "
- "(link %d of %d) from object \"%s\"\n"
- "\tthere has been an error converting the blender controller for the game engine,"
- "logic may be incorrect\n", sens->name, i+1, sens->totlinks, blenderobject->id.name+2);
- }
- }
- }
- else {
- printf("Warning, sensor \"%s\" has lost a link to a controller "
- "(link %d of %d) from object \"%s\"\n"
- "\tpossible causes are partially appended objects or an error reading the file,"
- "logic may be incorrect\n", sens->name, i+1, sens->totlinks, blenderobject->id.name+2);
- }
- }
- // special case: Keyboard sensor with no link
- // this combination is usually used for key logging.
- if (sens->type == SENS_KEYBOARD && sens->totlinks == 0) {
- // Force the registration so that the sensor runs
- gamesensor->IncLink();
- }
-
- // done with gamesensor
- gamesensor->Release();
-
- }
- }
-
- sens=sens->next;
- }
-}
-
diff --git a/source/gameengine/Converter/KX_ConvertSensors.h b/source/gameengine/Converter/KX_ConvertSensors.h
deleted file mode 100644
index 56248721a37..00000000000
--- a/source/gameengine/Converter/KX_ConvertSensors.h
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file KX_ConvertSensors.h
- * \ingroup bgeconv
- */
-
-#ifndef __KX_CONVERTSENSORS_H__
-#define __KX_CONVERTSENSORS_H__
-
-void BL_ConvertSensors(struct Object* blenderobject,
- class KX_GameObject* gameobj,
- class SCA_LogicManager* logicmgr,
- class KX_Scene* kxscene,
- class KX_KetsjiEngine* kxengine,
- int activeLayerBitInfo,
- bool isInActiveLayer,
- class RAS_ICanvas* canvas,
- class KX_BlenderSceneConverter* converter);
-
-#endif /* __KX_CONVERTSENSORS_H__ */
diff --git a/source/gameengine/Converter/KX_LibLoadStatus.cpp b/source/gameengine/Converter/KX_LibLoadStatus.cpp
deleted file mode 100644
index 66fcd998269..00000000000
--- a/source/gameengine/Converter/KX_LibLoadStatus.cpp
+++ /dev/null
@@ -1,255 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * Contributor(s): Mitchell Stokes
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file KX_LibLoadStatus.cpp
- * \ingroup bgeconv
- */
-
-#include "KX_LibLoadStatus.h"
-#include "PIL_time.h"
-
-KX_LibLoadStatus::KX_LibLoadStatus(class KX_BlenderSceneConverter* kx_converter,
- class KX_KetsjiEngine* kx_engine,
- class KX_Scene* merge_scene,
- const char *path) :
- m_converter(kx_converter),
- m_engine(kx_engine),
- m_mergescene(merge_scene),
- m_data(NULL),
- m_libname(path),
- m_progress(0.0f),
- m_finished(false)
-#ifdef WITH_PYTHON
- ,
- m_finish_cb(NULL),
- m_progress_cb(NULL)
-#endif
-{
- m_endtime = m_starttime = PIL_check_seconds_timer();
-}
-
-void KX_LibLoadStatus::Finish()
-{
- m_finished = true;
- m_progress = 1.f;
- m_endtime = PIL_check_seconds_timer();
-
- RunFinishCallback();
- RunProgressCallback();
-}
-
-void KX_LibLoadStatus::RunFinishCallback()
-{
-#ifdef WITH_PYTHON
- if (m_finish_cb) {
- PyObject* args = Py_BuildValue("(O)", GetProxy());
-
- if (!PyObject_Call(m_finish_cb, args, NULL)) {
- PyErr_Print();
- PyErr_Clear();
- }
-
- Py_DECREF(args);
- }
-#endif
-}
-
-void KX_LibLoadStatus::RunProgressCallback()
-{
-// Progess callbacks are causing threading problems with Python, so they're disabled for now
-#if 0
-#ifdef WITH_PYTHON
- if (m_progress_cb) {
- //PyGILState_STATE gstate = PyGILState_Ensure();
- PyObject* args = Py_BuildValue("(O)", GetProxy());
-
- if (!PyObject_Call(m_progress_cb, args, NULL)) {
- PyErr_Print();
- PyErr_Clear();
- }
-
- Py_DECREF(args);
- //PyGILState_Release(gstate);
- }
-#endif
-#endif
-}
-
-class KX_BlenderSceneConverter *KX_LibLoadStatus::GetConverter()
-{
- return m_converter;
-}
-
-class KX_KetsjiEngine *KX_LibLoadStatus::GetEngine()
-{
- return m_engine;
-}
-
-class KX_Scene *KX_LibLoadStatus::GetMergeScene()
-{
- return m_mergescene;
-}
-
-void KX_LibLoadStatus::SetLibName(const char *name)
-{
- m_libname = name;
-}
-
-const char *KX_LibLoadStatus::GetLibName()
-{
- return m_libname;
-}
-
-void KX_LibLoadStatus::SetData(void *data)
-{
- m_data = data;
-}
-
-void *KX_LibLoadStatus::GetData()
-{
- return m_data;
-}
-
-void KX_LibLoadStatus::SetProgress(float progress)
-{
- m_progress = progress;
- RunProgressCallback();
-}
-
-float KX_LibLoadStatus::GetProgress()
-{
- return m_progress;
-}
-
-void KX_LibLoadStatus::AddProgress(float progress)
-{
- m_progress += progress;
- RunProgressCallback();
-}
-
-#ifdef WITH_PYTHON
-
-PyMethodDef KX_LibLoadStatus::Methods[] =
-{
- {NULL} //Sentinel
-};
-
-PyAttributeDef KX_LibLoadStatus::Attributes[] = {
- KX_PYATTRIBUTE_RW_FUNCTION("onFinish", KX_LibLoadStatus, pyattr_get_onfinish, pyattr_set_onfinish),
- // KX_PYATTRIBUTE_RW_FUNCTION("onProgress", KX_LibLoadStatus, pyattr_get_onprogress, pyattr_set_onprogress),
- KX_PYATTRIBUTE_FLOAT_RO("progress", KX_LibLoadStatus, m_progress),
- KX_PYATTRIBUTE_STRING_RO("libraryName", KX_LibLoadStatus, m_libname),
- KX_PYATTRIBUTE_RO_FUNCTION("timeTaken", KX_LibLoadStatus, pyattr_get_timetaken),
- KX_PYATTRIBUTE_BOOL_RO("finished", KX_LibLoadStatus, m_finished),
- { NULL } //Sentinel
-};
-
-PyTypeObject KX_LibLoadStatus::Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "KX_LibLoadStatus",
- sizeof(PyObjectPlus_Proxy),
- 0,
- py_base_dealloc,
- 0,
- 0,
- 0,
- 0,
- py_base_repr,
- 0,0,0,0,0,0,0,0,0,
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
- 0,0,0,0,0,0,0,
- Methods,
- 0,
- 0,
- &PyObjectPlus::Type,
- 0,0,0,0,0,0,
- py_base_new
-};
-
-
-PyObject* KX_LibLoadStatus::pyattr_get_onfinish(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_LibLoadStatus* self = static_cast<KX_LibLoadStatus*>(self_v);
-
- if (self->m_finish_cb) {
- Py_INCREF(self->m_finish_cb);
- return self->m_finish_cb;
- }
-
- Py_RETURN_NONE;
-}
-
-int KX_LibLoadStatus::pyattr_set_onfinish(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_LibLoadStatus* self = static_cast<KX_LibLoadStatus*>(self_v);
-
- if (!PyCallable_Check(value)) {
- PyErr_SetString(PyExc_TypeError, "KX_LibLoadStatus.onFinished requires a callable object");
- return PY_SET_ATTR_FAIL;
- }
-
- if (self->m_finish_cb)
- Py_DECREF(self->m_finish_cb);
-
- Py_INCREF(value);
- self->m_finish_cb = value;
-
- return PY_SET_ATTR_SUCCESS;
-}
-
-PyObject* KX_LibLoadStatus::pyattr_get_onprogress(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_LibLoadStatus* self = static_cast<KX_LibLoadStatus*>(self_v);
-
- if (self->m_progress_cb) {
- Py_INCREF(self->m_progress_cb);
- return self->m_progress_cb;
- }
-
- Py_RETURN_NONE;
-}
-
-int KX_LibLoadStatus::pyattr_set_onprogress(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_LibLoadStatus* self = static_cast<KX_LibLoadStatus*>(self_v);
-
- if (!PyCallable_Check(value)) {
- PyErr_SetString(PyExc_TypeError, "KX_LibLoadStatus.onProgress requires a callable object");
- return PY_SET_ATTR_FAIL;
- }
-
- if (self->m_progress_cb)
- Py_DECREF(self->m_progress_cb);
-
- Py_INCREF(value);
- self->m_progress_cb = value;
-
- return PY_SET_ATTR_SUCCESS;
-}
-
-PyObject* KX_LibLoadStatus::pyattr_get_timetaken(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_LibLoadStatus* self = static_cast<KX_LibLoadStatus*>(self_v);
-
- return PyFloat_FromDouble(self->m_endtime - self->m_starttime);
-}
-#endif // WITH_PYTHON
diff --git a/source/gameengine/Converter/KX_LibLoadStatus.h b/source/gameengine/Converter/KX_LibLoadStatus.h
deleted file mode 100644
index fd51bfddd85..00000000000
--- a/source/gameengine/Converter/KX_LibLoadStatus.h
+++ /dev/null
@@ -1,93 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * Contributor(s): Mitchell Stokes
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file KX_LibLoadStatus.h
- * \ingroup bgeconv
- */
-
-#ifndef __KX_LIBLOADSTATUS_H__
-#define __KX_LIBLOADSTATUS_H__
-
-#include "EXP_PyObjectPlus.h"
-
-class KX_LibLoadStatus : public PyObjectPlus
-{
- Py_Header
-private:
- class KX_BlenderSceneConverter* m_converter;
- class KX_KetsjiEngine* m_engine;
- class KX_Scene* m_mergescene;
- void* m_data;
- STR_String m_libname;
-
- float m_progress;
- double m_starttime;
- double m_endtime;
-
- // The current status of this libload, used by the scene converter.
- bool m_finished;
-
-#ifdef WITH_PYTHON
- PyObject* m_finish_cb;
- PyObject* m_progress_cb;
-#endif
-
-public:
- KX_LibLoadStatus(class KX_BlenderSceneConverter* kx_converter,
- class KX_KetsjiEngine* kx_engine,
- class KX_Scene* merge_scene,
- const char *path);
-
- void Finish(); // Called when the libload is done
- void RunFinishCallback();
- void RunProgressCallback();
-
- class KX_BlenderSceneConverter *GetConverter();
- class KX_KetsjiEngine *GetEngine();
- class KX_Scene *GetMergeScene();
-
- void SetLibName(const char *name);
- const char *GetLibName();
-
- void SetData(void *data);
- void *GetData();
-
- inline bool IsFinished() const
- {
- return m_finished;
- }
-
- void SetProgress(float progress);
- float GetProgress();
- void AddProgress(float progress);
-
-#ifdef WITH_PYTHON
- static PyObject* pyattr_get_onfinish(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_onfinish(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static PyObject* pyattr_get_onprogress(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_onprogress(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
-
- static PyObject* pyattr_get_timetaken(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
-#endif
-};
-
-#endif // __KX_LIBLOADSTATUS_H__
diff --git a/source/gameengine/Converter/KX_SoftBodyDeformer.cpp b/source/gameengine/Converter/KX_SoftBodyDeformer.cpp
deleted file mode 100644
index 877aebff556..00000000000
--- a/source/gameengine/Converter/KX_SoftBodyDeformer.cpp
+++ /dev/null
@@ -1,121 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Converter/KX_SoftBodyDeformer.cpp
- * \ingroup bgeconv
- */
-
-
-#ifdef _MSC_VER
-# pragma warning (disable:4786)
-#endif //WIN32
-
-#include "MT_assert.h"
-
-#include "KX_SoftBodyDeformer.h"
-#include "RAS_MeshObject.h"
-#include "CTR_Map.h"
-#include "CTR_HashedPtr.h"
-
-#ifdef WITH_BULLET
-
-#include "CcdPhysicsEnvironment.h"
-#include "CcdPhysicsController.h"
-#include "BulletSoftBody/btSoftBody.h"
-
-#include "btBulletDynamicsCommon.h"
-
-void KX_SoftBodyDeformer::Relink(CTR_Map<class CTR_HashedPtr, void*>*map)
-{
- void **h_obj = (*map)[m_gameobj];
-
- if (h_obj) {
- m_gameobj = (BL_DeformableGameObject*)(*h_obj);
- m_pMeshObject = m_gameobj->GetMesh(0);
- } else {
- m_gameobj = NULL;
- m_pMeshObject = NULL;
- }
-}
-
-bool KX_SoftBodyDeformer::Apply(class RAS_IPolyMaterial *polymat)
-{
- CcdPhysicsController* ctrl = (CcdPhysicsController*) m_gameobj->GetPhysicsController();
- if (!ctrl)
- return false;
-
- btSoftBody* softBody= ctrl->GetSoftBody();
- if (!softBody)
- return false;
-
- //printf("apply\n");
- RAS_MeshSlot::iterator it;
- RAS_MeshMaterial *mmat;
- RAS_MeshSlot *slot;
- size_t i;
-
- // update the vertex in m_transverts
- Update();
-
- // The vertex cache can only be updated for this deformer:
- // Duplicated objects with more than one ploymaterial (=multiple mesh slot per object)
- // share the same mesh (=the same cache). As the rendering is done per polymaterial
- // cycling through the objects, the entire mesh cache cannot be updated in one shot.
- mmat = m_pMeshObject->GetMeshMaterial(polymat);
- if (!mmat->m_slots[(void*)m_gameobj])
- return true;
-
- slot = *mmat->m_slots[(void*)m_gameobj];
-
- // for each array
- for (slot->begin(it); !slot->end(it); slot->next(it))
- {
- btSoftBody::tNodeArray& nodes(softBody->m_nodes);
-
- int index = 0;
- for (i=it.startvertex; i<it.endvertex; i++,index++) {
- RAS_TexVert& v = it.vertex[i];
- btAssert(v.getSoftBodyIndex() >= 0);
-
- MT_Point3 pt (
- nodes[v.getSoftBodyIndex()].m_x.getX(),
- nodes[v.getSoftBodyIndex()].m_x.getY(),
- nodes[v.getSoftBodyIndex()].m_x.getZ());
- v.SetXYZ(pt);
-
- MT_Vector3 normal (
- nodes[v.getSoftBodyIndex()].m_n.getX(),
- nodes[v.getSoftBodyIndex()].m_n.getY(),
- nodes[v.getSoftBodyIndex()].m_n.getZ());
- v.SetNormal(normal);
-
- }
- }
- return true;
-}
-
-#endif
diff --git a/source/gameengine/Converter/KX_SoftBodyDeformer.h b/source/gameengine/Converter/KX_SoftBodyDeformer.h
deleted file mode 100644
index d7bc088e1c0..00000000000
--- a/source/gameengine/Converter/KX_SoftBodyDeformer.h
+++ /dev/null
@@ -1,102 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file KX_SoftBodyDeformer.h
- * \ingroup bgeconv
- */
-
-#ifndef __KX_SOFTBODYDEFORMER_H__
-#define __KX_SOFTBODYDEFORMER_H__
-
-#ifdef _MSC_VER
-# pragma warning (disable:4786) /* get rid of stupid stl-visual compiler debug warning */
-#endif
-
-#include "RAS_Deformer.h"
-#include "BL_DeformableGameObject.h"
-#include <vector>
-
-
-class KX_SoftBodyDeformer : public RAS_Deformer
-{
- class RAS_MeshObject* m_pMeshObject;
- class BL_DeformableGameObject* m_gameobj;
-
-public:
- KX_SoftBodyDeformer(RAS_MeshObject* pMeshObject,BL_DeformableGameObject* gameobj)
- :m_pMeshObject(pMeshObject),
- m_gameobj(gameobj)
- {
- //printf("KX_SoftBodyDeformer\n");
- };
-
- virtual ~KX_SoftBodyDeformer()
- {
- //printf("~KX_SoftBodyDeformer\n");
- };
- virtual void Relink(CTR_Map<class CTR_HashedPtr, void*>*map);
- virtual bool Apply(class RAS_IPolyMaterial *polymat);
- virtual bool Update(void)
- {
- //printf("update\n");
- m_bDynamic = true;
- return true;//??
- }
- virtual bool UpdateBuckets(void)
- {
- // this is to update the mesh slots outside the rasterizer,
- // no need to do it for this deformer, it's done in any case in Apply()
- return false;
- }
-
- virtual RAS_Deformer *GetReplica()
- {
- KX_SoftBodyDeformer* deformer = new KX_SoftBodyDeformer(*this);
- deformer->ProcessReplica();
- return deformer;
- }
- virtual void ProcessReplica()
- {
- // we have two pointers to deal with but we cannot do it now, will be done in Relink
- m_bDynamic = false;
- }
- virtual bool SkipVertexTransform()
- {
- return true;
- }
-
-protected:
- //class RAS_MeshObject *m_pMesh;
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:BL_ShapeDeformer")
-#endif
-};
-
-
-#endif
-
diff --git a/source/gameengine/Expressions/CMakeLists.txt b/source/gameengine/Expressions/CMakeLists.txt
deleted file mode 100644
index 9c563a46ea2..00000000000
--- a/source/gameengine/Expressions/CMakeLists.txt
+++ /dev/null
@@ -1,91 +0,0 @@
-# ***** BEGIN GPL LICENSE BLOCK *****
-#
-# This program is free software; you can redistribute it and/or
-# modify it under the terms of the GNU General Public License
-# as published by the Free Software Foundation; either version 2
-# of the License, or (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software Foundation,
-# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
-#
-# The Original Code is Copyright (C) 2006, Blender Foundation
-# All rights reserved.
-#
-# The Original Code is: all of this file.
-#
-# Contributor(s): Jacques Beaurain.
-#
-# ***** END GPL LICENSE BLOCK *****
-
-set(INC
- .
- ../SceneGraph
- ../../blender/blenlib
- ../../../intern/guardedalloc
- ../../../intern/string
-)
-
-set(INC_SYS
- ../../../intern/moto/include
-)
-
-set(SRC
- intern/BoolValue.cpp
- intern/ConstExpr.cpp
- intern/EmptyValue.cpp
- intern/ErrorValue.cpp
- intern/Expression.cpp
- intern/FloatValue.cpp
- intern/IdentifierExpr.cpp
- intern/IfExpr.cpp
- intern/InputParser.cpp
- intern/IntValue.cpp
- intern/HashedPtr.cpp
- intern/ListValue.cpp
- intern/Operator1Expr.cpp
- intern/Operator2Expr.cpp
- intern/PyObjectPlus.cpp
- intern/StringValue.cpp
- intern/Value.cpp
- intern/VectorValue.cpp
- intern/ListWrapper.cpp
-
- EXP_BoolValue.h
- EXP_ConstExpr.h
- EXP_EmptyValue.h
- EXP_ErrorValue.h
- EXP_Expression.h
- EXP_FloatValue.h
- EXP_HashedPtr.h
- EXP_IdentifierExpr.h
- EXP_IfExpr.h
- EXP_InputParser.h
- EXP_IntValue.h
- EXP_ListValue.h
- EXP_Operator1Expr.h
- EXP_Operator2Expr.h
- EXP_PyObjectPlus.h
- EXP_Python.h
- EXP_StringValue.h
- EXP_Value.h
- EXP_VectorValue.h
- EXP_VoidValue.h
- EXP_ListWrapper.h
-
-)
-
-if(WITH_PYTHON)
- list(APPEND SRC
- intern/PythonCallBack.cpp
-
- EXP_PythonCallBack.h
- )
-endif()
-
-blender_add_lib(ge_logic_expressions "${SRC}" "${INC}" "${INC_SYS}")
diff --git a/source/gameengine/Expressions/EXP_BoolValue.h b/source/gameengine/Expressions/EXP_BoolValue.h
deleted file mode 100644
index 98ba1d75e52..00000000000
--- a/source/gameengine/Expressions/EXP_BoolValue.h
+++ /dev/null
@@ -1,65 +0,0 @@
-/*
- * BoolValue.h: interface for the CBoolValue class.
- * Copyright (c) 1996-2000 Erwin Coumans <coockie@acm.org>
- *
- * Permission to use, copy, modify, distribute and sell this software
- * and its documentation for any purpose is hereby granted without fee,
- * provided that the above copyright notice appear in all copies and
- * that both that copyright notice and this permission notice appear
- * in supporting documentation. Erwin Coumans makes no
- * representations about the suitability of this software for any
- * purpose. It is provided "as is" without express or implied warranty.
- *
- */
-
-/** \file EXP_BoolValue.h
- * \ingroup expressions
- */
-
-#ifndef __EXP_BOOLVALUE_H__
-#define __EXP_BOOLVALUE_H__
-
-#include "EXP_Value.h"
-
-/**
- * Smart Boolean Value class.
- * Is used by parser when an expression tree is build containing booleans.
- */
-
-class CBoolValue : public CPropValue
-{
-
- //PLUGIN_DECLARE_SERIAL(CBoolValue,CValue)
-
-public:
- static const STR_String sTrueString;
- static const STR_String sFalseString;
-
- CBoolValue();
- CBoolValue(bool inBool);
- CBoolValue(bool innie, const char *name, AllocationTYPE alloctype = CValue::HEAPVALUE);
-
- virtual const STR_String& GetText();
- virtual double GetNumber();
- virtual int GetValueType();
- bool GetBool();
- virtual void SetValue(CValue* newval);
-
- virtual CValue* Calc(VALUE_OPERATOR op, CValue *val);
- virtual CValue* CalcFinal(VALUE_DATA_TYPE dtype, VALUE_OPERATOR op, CValue *val);
-
- void Configure(CValue* menuvalue);
- virtual CValue* GetReplica();
-#ifdef WITH_PYTHON
- virtual PyObject* ConvertValueToPython();
-#endif
-
-private:
- bool m_bool;
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:CBoolValue")
-#endif
-};
-
-#endif /* __EXP_BOOLVALUE_H__ */
diff --git a/source/gameengine/Expressions/EXP_ConstExpr.h b/source/gameengine/Expressions/EXP_ConstExpr.h
deleted file mode 100644
index b4456dacdf3..00000000000
--- a/source/gameengine/Expressions/EXP_ConstExpr.h
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * ConstExpr.h: interface for the CConstExpr class.
- * Copyright (c) 1996-2000 Erwin Coumans <coockie@acm.org>
- *
- * Permission to use, copy, modify, distribute and sell this software
- * and its documentation for any purpose is hereby granted without fee,
- * provided that the above copyright notice appear in all copies and
- * that both that copyright notice and this permission notice appear
- * in supporting documentation. Erwin Coumans makes no
- * representations about the suitability of this software for any
- * purpose. It is provided "as is" without express or implied warranty.
- *
- */
-
-/** \file EXP_ConstExpr.h
- * \ingroup expressions
- */
-
-#ifndef __EXP_CONSTEXPR_H__
-#define __EXP_CONSTEXPR_H__
-
-#include "EXP_Expression.h"
-#include "EXP_Value.h" // Added by ClassView
-
-class CConstExpr : public CExpression
-{
- //PLUGIN_DECLARE_SERIAL_EXPRESSION (CConstExpr,CExpression)
-public:
- virtual bool MergeExpression(CExpression* otherexpr);
-
- void BroadcastOperators(VALUE_OPERATOR op);
-
- virtual unsigned char GetExpressionID();
- CExpression* CheckLink(std::vector<CBrokenLinkInfo*>& brokenlinks);
- //bool IsInside(float x,float y,float z,bool bBorderInclude=true);
- bool NeedsRecalculated();
- void ClearModified();
- virtual double GetNumber();
- virtual CValue* Calculate();
- CConstExpr(CValue* constval);
- CConstExpr();
- virtual ~CConstExpr();
-
-
-private:
- CValue* m_value;
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:CConstExpr")
-#endif
-};
-
-#endif /* __EXP_CONSTEXPR_H__ */
diff --git a/source/gameengine/Expressions/EXP_EmptyValue.h b/source/gameengine/Expressions/EXP_EmptyValue.h
deleted file mode 100644
index d23addb9f9f..00000000000
--- a/source/gameengine/Expressions/EXP_EmptyValue.h
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * EmptyValue.h: interface for the CEmptyValue class.
- * Copyright (c) 1996-2000 Erwin Coumans <coockie@acm.org>
- *
- * Permission to use, copy, modify, distribute and sell this software
- * and its documentation for any purpose is hereby granted without fee,
- * provided that the above copyright notice appear in all copies and
- * that both that copyright notice and this permission notice appear
- * in supporting documentation. Erwin Coumans makes no
- * representations about the suitability of this software for any
- * purpose. It is provided "as is" without express or implied warranty.
- *
- */
-
-/** \file EXP_EmptyValue.h
- * \ingroup expressions
- */
-
-#ifndef __EXP_EMPTYVALUE_H__
-#define __EXP_EMPTYVALUE_H__
-
-#include "EXP_Value.h"
-
-class CListValue;
-
-class CEmptyValue : public CPropValue
-{
- //PLUGIN_DECLARE_SERIAL (CEmptyValue,CValue)
-public:
- CEmptyValue();
- virtual ~CEmptyValue();
-
- virtual const STR_String & GetText();
- virtual double GetNumber();
- virtual int GetValueType();
- CListValue* GetPolySoup();
- virtual double* GetVector3(bool bGetTransformedVec=false);
- bool IsInside(CValue* testpoint,bool bBorderInclude=true);
- CValue * Calc(VALUE_OPERATOR op, CValue *val);
- CValue * CalcFinal(VALUE_DATA_TYPE dtype, VALUE_OPERATOR op, CValue *val);
- virtual CValue* GetReplica();
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:CEmptyValue")
-#endif
-};
-
-#endif /* __EXP_EMPTYVALUE_H__ */
diff --git a/source/gameengine/Expressions/EXP_ErrorValue.h b/source/gameengine/Expressions/EXP_ErrorValue.h
deleted file mode 100644
index a6f91ca200a..00000000000
--- a/source/gameengine/Expressions/EXP_ErrorValue.h
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * ErrorValue.h: interface for the CErrorValue class.
- * Copyright (c) 1996-2000 Erwin Coumans <coockie@acm.org>
- *
- * Permission to use, copy, modify, distribute and sell this software
- * and its documentation for any purpose is hereby granted without fee,
- * provided that the above copyright notice appear in all copies and
- * that both that copyright notice and this permission notice appear
- * in supporting documentation. Erwin Coumans makes no
- * representations about the suitability of this software for any
- * purpose. It is provided "as is" without express or implied warranty.
- *
- */
-
-/** \file EXP_ErrorValue.h
- * \ingroup expressions
- */
-
-#ifndef __EXP_ERRORVALUE_H__
-#define __EXP_ERRORVALUE_H__
-
-#include "EXP_Value.h"
-
-class CErrorValue : public CPropValue
-{
-
-public:
- virtual const STR_String & GetText();
- virtual double GetNumber();
- virtual int GetValueType();
- CErrorValue();
- CErrorValue(const char *errmsg);
- virtual ~CErrorValue();
- virtual CValue* Calc(VALUE_OPERATOR op, CValue* val);
- virtual CValue* CalcFinal(VALUE_DATA_TYPE dtype, VALUE_OPERATOR op, CValue *val);
- virtual CValue* GetReplica();
-
-private:
- STR_String m_strErrorText;
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:CErrorValue")
-#endif
-};
-
-#endif /* __EXP_ERRORVALUE_H__ */
diff --git a/source/gameengine/Expressions/EXP_Expression.h b/source/gameengine/Expressions/EXP_Expression.h
deleted file mode 100644
index 66a6e9476ff..00000000000
--- a/source/gameengine/Expressions/EXP_Expression.h
+++ /dev/null
@@ -1,149 +0,0 @@
-/*
- * Expression.h: interface for the CExpression class.
- * Copyright (c) 1996-2000 Erwin Coumans <coockie@acm.org>
- *
- * Permission to use, copy, modify, distribute and sell this software
- * and its documentation for any purpose is hereby granted without fee,
- * provided that the above copyright notice appear in all copies and
- * that both that copyright notice and this permission notice appear
- * in supporting documentation. Erwin Coumans makes no
- * representations about the suitability of this software for any
- * purpose. It is provided "as is" without express or implied warranty.
- *
- */
-
-/** \file EXP_Expression.h
- * \ingroup expressions
- */
-
-#ifndef __EXP_EXPRESSION_H__
-#define __EXP_EXPRESSION_H__
-
-#include "EXP_Value.h"
-
-//extern int gRefCountExpr; // only for debugging purposes (detect mem.leaks)
-
-
-#define PLUGIN_DECLARE_SERIAL_EXPRESSION(class_name, base_class_name) \
-public: \
- virtual base_class_name * Copy() { \
- return new class_name; \
- } \
- virtual bool EdSerialize(CompressorArchive& arch, \
- class CFactoryManager* facmgr, \
- bool bIsStoring); \
- virtual bool EdIdSerialize(CompressorArchive& arch, \
- class CFactoryManager* facmgr, \
- bool bIsStoring) \
- { \
- if (bIsStoring) \
- { \
- unsigned char exprID = GetExpressionID(); \
- arch << exprID; \
- } \
- return true; \
- } \
-
-
-
-class CExpression;
-
-
-// for undo/redo system the deletion in the expressiontree can be restored by replacing broken links 'inplace'
-class CBrokenLinkInfo
-{
- public:
- CBrokenLinkInfo(CExpression** pmemexpr,CExpression* expr)
- :m_pmemExpr(pmemexpr),
- m_pExpr(expr)
- {
- assertd(pmemexpr);
- m_bRestored=false;
- };
-
- virtual ~CBrokenLinkInfo();
- void RestoreLink();
- void BreakLink();
-
-
- // members vars
- private:
- CExpression** m_pmemExpr;
- CExpression* m_pExpr;
- bool m_bRestored;
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:CBrokenLinkInfo")
-#endif
-};
-
-
-
-
-
-
-
-
-class CExpression
-{
-public:
- enum {
- COPERATOR1EXPRESSIONID = 1,
- COPERATOR2EXPRESSIONID = 2,
- CCONSTEXPRESSIONID = 3,
- CIFEXPRESSIONID = 4,
- COPERATORVAREXPRESSIONID = 5,
- CIDENTIFIEREXPRESSIONID = 6
- };
-
-
-protected:
- virtual ~CExpression() = 0; //pure virtual
-public:
- virtual bool MergeExpression(CExpression* otherexpr) = 0;
- CExpression();
-
-
- virtual CValue* Calculate() = 0; //pure virtual
- virtual unsigned char GetExpressionID() = 0;
- //virtual bool IsInside(float x,float y,float z,bool bBorderInclude=true) = 0; //pure virtual
- virtual bool NeedsRecalculated() = 0; // another pure one
- virtual CExpression * CheckLink(std::vector<CBrokenLinkInfo*>& brokenlinks) =0; // another pure one
- virtual void ClearModified() = 0; // another pure one
- //virtual CExpression * Copy() =0;
- virtual void BroadcastOperators(VALUE_OPERATOR op) =0;
-
- virtual CExpression * AddRef() { // please leave multiline, for debugger !!!
-
-#ifdef DEBUG
- //gRefCountExpr++;
- assertd(m_refcount < 255);
-#endif
- m_refcount++;
- return this;
- };
- virtual CExpression* Release(CExpression* complicatedtrick=NULL) {
-#ifdef DEBUG
- //gRefCountExpr--;
-#endif
- if (--m_refcount < 1)
- {
- delete this;
- } //else
- // return this;
- return complicatedtrick;
- };
-
-
-protected:
-
- int m_refcount;
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:CExpression")
-#endif
-};
-
-#endif /* __EXP_EXPRESSION_H__ */
diff --git a/source/gameengine/Expressions/EXP_FloatValue.h b/source/gameengine/Expressions/EXP_FloatValue.h
deleted file mode 100644
index 3c16c57d16d..00000000000
--- a/source/gameengine/Expressions/EXP_FloatValue.h
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- * FloatValue.h: interface for the CFloatValue class.
- * Copyright (c) 1996-2000 Erwin Coumans <coockie@acm.org>
- *
- * Permission to use, copy, modify, distribute and sell this software
- * and its documentation for any purpose is hereby granted without fee,
- * provided that the above copyright notice appear in all copies and
- * that both that copyright notice and this permission notice appear
- * in supporting documentation. Erwin Coumans makes no
- * representations about the suitability of this software for any
- * purpose. It is provided "as is" without express or implied warranty.
- *
- */
-
-/** \file EXP_FloatValue.h
- * \ingroup expressions
- */
-
-#ifndef __EXP_FLOATVALUE_H__
-#define __EXP_FLOATVALUE_H__
-
-#include "EXP_Value.h"
-
-class CFloatValue : public CPropValue
-{
- //PLUGIN_DECLARE_SERIAL (CFloatValue,CValue)
-public:
- CFloatValue();
- CFloatValue(float fl);
- CFloatValue(float fl,const char *name,AllocationTYPE alloctype=CValue::HEAPVALUE);
-
- virtual const STR_String & GetText();
-
- void Configure(CValue* menuvalue);
- virtual double GetNumber();
- virtual int GetValueType();
- virtual void SetValue(CValue* newval);
- float GetFloat();
- void SetFloat(float fl);
- virtual ~CFloatValue();
- virtual CValue* GetReplica();
- virtual CValue* Calc(VALUE_OPERATOR op, CValue *val);
- virtual CValue* CalcFinal(VALUE_DATA_TYPE dtype, VALUE_OPERATOR op, CValue *val);
-#ifdef WITH_PYTHON
- virtual PyObject* ConvertValueToPython();
-#endif
-
-protected:
- float m_float;
- STR_String* m_pstrRep;
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:CFloatValue")
-#endif
-};
-
-#endif /* __EXP_FLOATVALUE_H__ */
diff --git a/source/gameengine/Expressions/EXP_HashedPtr.h b/source/gameengine/Expressions/EXP_HashedPtr.h
deleted file mode 100644
index 7c7c5f6e5ec..00000000000
--- a/source/gameengine/Expressions/EXP_HashedPtr.h
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file EXP_HashedPtr.h
- * \ingroup expressions
- */
-
-#ifndef __EXP_HASHEDPTR_H__
-#define __EXP_HASHEDPTR_H__
-
-#ifdef WITH_CXX_GUARDEDALLOC
-#include "MEM_guardedalloc.h"
-#endif
-
-class CHashedPtr
-{
- void* m_valptr;
-
-public:
- CHashedPtr(void* val);
-
- unsigned int hash() const;
-
- inline friend bool operator ==( const CHashedPtr & rhs,const CHashedPtr & lhs)
- {
- return rhs.m_valptr == lhs.m_valptr;
- }
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:CHashedPtr")
-#endif
-};
-
-#endif /* __EXP_HASHEDPTR_H__ */
diff --git a/source/gameengine/Expressions/EXP_IdentifierExpr.h b/source/gameengine/Expressions/EXP_IdentifierExpr.h
deleted file mode 100644
index 96ef3677cf3..00000000000
--- a/source/gameengine/Expressions/EXP_IdentifierExpr.h
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file EXP_IdentifierExpr.h
- * \ingroup expressions
- */
-
-#ifndef __EXP_IDENTIFIEREXPR_H__
-#define __EXP_IDENTIFIEREXPR_H__
-
-#include "EXP_Expression.h"
-
-class CIdentifierExpr : public CExpression
-{
- CValue* m_idContext;
- STR_String m_identifier;
-public:
- CIdentifierExpr(const STR_String& identifier,CValue* id_context);
- virtual ~CIdentifierExpr();
-
- virtual CValue* Calculate();
- virtual bool MergeExpression(CExpression* otherexpr);
- virtual unsigned char GetExpressionID();
- virtual bool NeedsRecalculated();
- virtual CExpression* CheckLink(std::vector<CBrokenLinkInfo*>& brokenlinks);
- virtual void ClearModified();
- virtual void BroadcastOperators(VALUE_OPERATOR op);
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:CIdentifierExpr")
-#endif
-};
-
-#endif /* __EXP_IDENTIFIEREXPR_H__ */
diff --git a/source/gameengine/Expressions/EXP_IfExpr.h b/source/gameengine/Expressions/EXP_IfExpr.h
deleted file mode 100644
index 43b4b8faf53..00000000000
--- a/source/gameengine/Expressions/EXP_IfExpr.h
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * IfExpr.h: interface for the CIfExpr class.
- * Copyright (c) 1996-2000 Erwin Coumans <coockie@acm.org>
- *
- * Permission to use, copy, modify, distribute and sell this software
- * and its documentation for any purpose is hereby granted without fee,
- * provided that the above copyright notice appear in all copies and
- * that both that copyright notice and this permission notice appear
- * in supporting documentation. Erwin Coumans makes no
- * representations about the suitability of this software for any
- * purpose. It is provided "as is" without express or implied warranty.
- *
- */
-
-/** \file EXP_IfExpr.h
- * \ingroup expressions
- */
-
-#ifndef __EXP_IFEXPR_H__
-#define __EXP_IFEXPR_H__
-
-#include "EXP_Expression.h"
-
-class CIfExpr : public CExpression
-{
- //PLUGIN_DECLARE_SERIAL_EXPRESSION (CIfExpr,CExpression)
-
-private:
- CExpression *m_guard, *m_e1, *m_e2;
-
-public:
- virtual bool MergeExpression(CExpression* otherexpr);
- CIfExpr(CExpression *guard, CExpression *e1, CExpression *e2);
- CIfExpr();
-
- virtual unsigned char GetExpressionID();
- virtual ~CIfExpr();
- virtual CValue* Calculate();
-
- virtual bool IsInside(float x,float y,float z,bool bBorderInclude=true);
- virtual bool NeedsRecalculated();
-
-
- virtual CExpression* CheckLink(std::vector<CBrokenLinkInfo*>& brokenlinks);
- virtual void ClearModified();
- virtual void BroadcastOperators(VALUE_OPERATOR op);
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:CIfExpr")
-#endif
-};
-
-#endif /* __EXP_IFEXPR_H__ */
diff --git a/source/gameengine/Expressions/EXP_InputParser.h b/source/gameengine/Expressions/EXP_InputParser.h
deleted file mode 100644
index 80471009a16..00000000000
--- a/source/gameengine/Expressions/EXP_InputParser.h
+++ /dev/null
@@ -1,118 +0,0 @@
-/*
- * Parser.h: interface for the CParser class.
- * Eindhoven University of Technology 1997
- * OOPS team (Serge vd Boom, Erwin Coumans, Tom Geelen, Wynke Stuylemeier)
- * Copyright (c) 1996-2000 Erwin Coumans <coockie@acm.org>
- *
- * Permission to use, copy, modify, distribute and sell this software
- * and its documentation for any purpose is hereby granted without fee,
- * provided that the above copyright notice appear in all copies and
- * that both that copyright notice and this permission notice appear
- * in supporting documentation. Erwin Coumans makes no
- * representations about the suitability of this software for any
- * purpose. It is provided "as is" without express or implied warranty.
- *
- */
-
-/** \file EXP_InputParser.h
- * \ingroup expressions
- */
-
-#ifndef __EXP_INPUTPARSER_H__
-#define __EXP_INPUTPARSER_H__
-
-class CParser;
-#include "EXP_Expression.h"
-
-
-class CParser
-{
-public:
- CParser();
- virtual ~CParser();
-
- float GetFloat(STR_String& txt);
- CValue* GetValue(STR_String& txt, bool bFallbackToText=false);
- CExpression* ProcessText(const char *intext);
- void SetContext(CValue* context);
-
-private:
- enum symbols {
- errorsym,
- lbracksym,
- rbracksym,
- cellsym,
- commasym,
- opsym,
- constsym,
- sumsym,
- ifsym,
- whocodedsym,
- eolsym,
- idsym
- }; // all kinds of symbols
-
- enum optype {
- OPmodulus,
- OPplus,
- OPminus,
- OPtimes,
- OPdivide,
- OPand,
- OPor,
- OPequal,
- OPunequal,
- OPgreater,
- OPless,
- OPgreaterequal,
- OPlessequal,
- OPnot
- }; // all kinds of operators
-
- enum consttype {
- booltype,
- inttype,
- floattype,
- stringtype
- }; // all kinds of constants
-
- int sym, // current symbol
- opkind, // kind of operator, if symbol is an operator
- constkind; // kind of operator, if symbol is a constant
-
- char ch; // current character
- int chcount; // index to character in input string
- CExpression *errmsg; // contains a errormessage, if scanner error
-
- STR_String text, // contains a copy of the original text
- const_as_string; // string representation of the symbol, if symbol is a constant
- bool boolvalue; // value of the boolean, if symbol is a constant of type boolean
- CValue* m_identifierContext;// context in which identifiers are looked up
-
-
- void ScanError(const char *str);
- CExpression* Error(const char *str);
- void NextCh();
- void TermChar(char c);
- void DigRep();
- void CharRep();
- void GrabString(int start);
- void GrabRealString(int start);
- void NextSym();
-#if 0 /* not used yet */
- int MakeInt();
-#endif
- const char *Symbol2Str(int s);
- void Term(int s);
- int Priority(int optor);
- CExpression *Ex(int i);
- CExpression *Expr();
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:CParser")
-#endif
-};
-
-#endif /* __EXP_INPUTPARSER_H__ */
-
diff --git a/source/gameengine/Expressions/EXP_IntValue.h b/source/gameengine/Expressions/EXP_IntValue.h
deleted file mode 100644
index a1cd96a888e..00000000000
--- a/source/gameengine/Expressions/EXP_IntValue.h
+++ /dev/null
@@ -1,73 +0,0 @@
-/*
- * IntValue.h: interface for the CIntValue class.
- * Copyright (c) 1996-2000 Erwin Coumans <coockie@acm.org>
- *
- * Permission to use, copy, modify, distribute and sell this software
- * and its documentation for any purpose is hereby granted without fee,
- * provided that the above copyright notice appear in all copies and
- * that both that copyright notice and this permission notice appear
- * in supporting documentation. Erwin Coumans makes no
- * representations about the suitability of this software for any
- * purpose. It is provided "as is" without express or implied warranty.
- *
- */
-
-/** \file EXP_IntValue.h
- * \ingroup expressions
- */
-
-#ifndef __EXP_INTVALUE_H__
-#define __EXP_INTVALUE_H__
-
-
-#include "EXP_Value.h"
-
-typedef long long cInt;
-
-class CIntValue : public CPropValue
-{
- //PLUGIN_DECLARE_SERIAL (CIntValue,CValue)
-
-public:
- virtual const STR_String& GetText();
- virtual double GetNumber();
- virtual int GetValueType();
-
- cInt GetInt();
- CIntValue();
- CIntValue(cInt innie);
- CIntValue(cInt innie,
- const char *name,
- AllocationTYPE alloctype=CValue::HEAPVALUE);
-
- virtual CValue* Calc(VALUE_OPERATOR op,
- CValue *val);
-
- virtual CValue* CalcFinal(VALUE_DATA_TYPE dtype,
- VALUE_OPERATOR op,
- CValue *val);
-
- virtual void SetValue(CValue* newval);
-
- void Configure(CValue* menuvalue);
- void AddConfigurationData(CValue* menuvalue);
- virtual CValue* GetReplica();
-
-#ifdef WITH_PYTHON
- virtual PyObject* ConvertValueToPython();
-#endif
-
-protected:
- virtual ~CIntValue();
-
-private:
- cInt m_int;
- STR_String* m_pstrRep;
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:CIntValue")
-#endif
-};
-
-#endif /* __EXP_INTVALUE_H__ */
diff --git a/source/gameengine/Expressions/EXP_ListValue.h b/source/gameengine/Expressions/EXP_ListValue.h
deleted file mode 100644
index f5421066f62..00000000000
--- a/source/gameengine/Expressions/EXP_ListValue.h
+++ /dev/null
@@ -1,92 +0,0 @@
-/*
- * ListValue.h: interface for the CListValue class.
- * Copyright (c) 1996-2000 Erwin Coumans <coockie@acm.org>
- *
- * Permission to use, copy, modify, distribute and sell this software
- * and its documentation for any purpose is hereby granted without fee,
- * provided that the above copyright notice appear in all copies and
- * that both that copyright notice and this permission notice appear
- * in supporting documentation. Erwin Coumans makes no
- * representations about the suitability of this software for any
- * purpose. It is provided "as is" without express or implied warranty.
- *
- */
-
-/** \file EXP_ListValue.h
- * \ingroup expressions
- */
-
-#ifndef __EXP_LISTVALUE_H__
-#define __EXP_LISTVALUE_H__
-
-#include "EXP_Value.h"
-
-class CListValue : public CPropValue
-{
- Py_Header
- //PLUGIN_DECLARE_SERIAL (CListValue,CValue)
-
-public:
- CListValue();
- virtual ~CListValue();
-
- void AddConfigurationData(CValue* menuvalue);
- void Configure(CValue* menuvalue);
- void Add(CValue* value);
-
- /** \attention not implemented yet :( */
- virtual CValue* Calc(VALUE_OPERATOR op,CValue *val);
- virtual CValue* CalcFinal(VALUE_DATA_TYPE dtype,
- VALUE_OPERATOR op,
- CValue* val);
- virtual double GetNumber();
- virtual int GetValueType();
- virtual CValue* GetReplica();
-
-public:
- void MergeList(CListValue* otherlist);
- bool RemoveValue(CValue* val);
- void SetReleaseOnDestruct(bool bReleaseContents);
- bool SearchValue(CValue* val);
-
- CValue* FindValue(const STR_String & name);
- CValue* FindValue(const char *name);
-
- void ReleaseAndRemoveAll();
- virtual void SetModified(bool bModified);
- virtual inline bool IsModified();
- void Remove(int i);
- void Resize(int num);
- void SetValue(int i,CValue* val);
- CValue* GetValue(int i) { assertd(i < m_pValueArray.size()); return m_pValueArray[i]; }
- int GetCount() { return m_pValueArray.size(); }
- virtual const STR_String & GetText();
-
- bool CheckEqual(CValue* first,CValue* second);
-
-#ifdef WITH_PYTHON
- virtual PyObject *py_repr(void) {
- PyObject *py_proxy= this->GetProxy();
- PyObject *py_list= PySequence_List(py_proxy);
- PyObject *py_string= PyObject_Repr(py_list);
- Py_DECREF(py_list);
- Py_DECREF(py_proxy);
- return py_string;
- }
-
- KX_PYMETHOD_O(CListValue,append);
- KX_PYMETHOD_NOARGS(CListValue,reverse);
- KX_PYMETHOD_O(CListValue,index);
- KX_PYMETHOD_O(CListValue,count);
- KX_PYMETHOD_VARARGS(CListValue,get);
- KX_PYMETHOD_O(CListValue,from_id);
-#endif
-
-private:
-
- std::vector<CValue*> m_pValueArray;
- bool m_bReleaseContents;
-};
-
-#endif /* __EXP_LISTVALUE_H__ */
-
diff --git a/source/gameengine/Expressions/EXP_ListWrapper.h b/source/gameengine/Expressions/EXP_ListWrapper.h
deleted file mode 100644
index e4c97691acb..00000000000
--- a/source/gameengine/Expressions/EXP_ListWrapper.h
+++ /dev/null
@@ -1,109 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * Contributor(s): Porteries Tristan.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file EXP_ListWrapper.h
- * \ingroup expressions
- */
-
-#ifdef WITH_PYTHON
-
-#ifndef __EXP_LISTWRAPPER_H__
-#define __EXP_LISTWRAPPER_H__
-
-#include "EXP_Value.h"
-
-class CListWrapper : public CValue
-{
- Py_Header
-private:
- /** The client instance passed as first argument of each callback.
- * We use a void * instead of a template to avoid to declare this class
- * for each use in KX_PythonInitTypes.
- */
- void *m_client;
-
- // The python object which owned this list.
- PyObject *m_base;
-
- /// Returns true if the list is still valid, else each call will raise an error.
- bool (*m_checkValid)(void *);
-
- /// Returns the list size.
- int (*m_getSize)(void *);
-
- /// Returns the list item for the giving index.
- PyObject *(*m_getItem)(void *, int);
-
- /// Returns name item for the giving index, used for python operator list["name"].
- const char *(*m_getItemName)(void *, int);
-
- /// Sets the nex item to the index place, return false when failed item conversion.
- bool (*m_setItem)(void *, int, PyObject *);
-
-public:
- CListWrapper(void *client,
- PyObject *base,
- bool (*checkValid)(void *),
- int (*getSize)(void *),
- PyObject *(*getItem)(void *, int),
- const char *(*getItemName)(void *, int),
- bool (*setItem)(void *, int, PyObject *));
- ~CListWrapper();
-
- /// \section Python Interface
- bool CheckValid();
- int GetSize();
- PyObject *GetItem(int index);
- const char *GetItemName(int index);
- bool SetItem(int index, PyObject *item);
- bool AllowSetItem();
- bool AllowGetItemByName();
-
- /// \section CValue Inherited Functions.
- virtual const STR_String &GetText();
- virtual void SetName(const char *name);
- virtual STR_String &GetName();
- virtual CValue *GetReplica();
- virtual CValue *Calc(VALUE_OPERATOR op, CValue *val);
- virtual CValue *CalcFinal(VALUE_DATA_TYPE dtype, VALUE_OPERATOR op, CValue *val);
- virtual double GetNumber();
- virtual int GetValueType();
- virtual PyObject *py_repr();
-
- // Python list operators.
- static PySequenceMethods py_as_sequence;
- // Python dictionnary operators.
- static PyMappingMethods py_as_mapping;
-
- static Py_ssize_t py_len(PyObject *self);
- static PyObject *py_get_item(PyObject *self, Py_ssize_t index);
- static int py_set_item(PyObject *self, Py_ssize_t index, PyObject *value);
- static PyObject *py_mapping_subscript(PyObject *self, PyObject *key);
- static int py_mapping_ass_subscript(PyObject *self, PyObject *key, PyObject *value);
- static int py_contains(PyObject *self, PyObject *key);
-
- KX_PYMETHOD_VARARGS(CListWrapper, Get);
-};
-
-#endif // __EXP_LISTWRAPPER_H__
-
-#endif // WITH_PYTHON
diff --git a/source/gameengine/Expressions/EXP_Operator1Expr.h b/source/gameengine/Expressions/EXP_Operator1Expr.h
deleted file mode 100644
index 9a05ce9c0c4..00000000000
--- a/source/gameengine/Expressions/EXP_Operator1Expr.h
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * Operator1Expr.h: interface for the COperator1Expr class.
- * Copyright (c) 1996-2000 Erwin Coumans <coockie@acm.org>
- *
- * Permission to use, copy, modify, distribute and sell this software
- * and its documentation for any purpose is hereby granted without fee,
- * provided that the above copyright notice appear in all copies and
- * that both that copyright notice and this permission notice appear
- * in supporting documentation. Erwin Coumans makes no
- * representations about the suitability of this software for any
- * purpose. It is provided "as is" without express or implied warranty.
- *
- */
-
-/** \file EXP_Operator1Expr.h
- * \ingroup expressions
- */
-
-#ifndef __EXP_OPERATOR1EXPR_H__
-#define __EXP_OPERATOR1EXPR_H__
-
-#include "EXP_Expression.h"
-
-class COperator1Expr : public CExpression
-{
- //PLUGIN_DECLARE_SERIAL_EXPRESSION (COperator1Expr,CExpression)
-
-
-
-public:
- virtual bool MergeExpression(CExpression* otherexpr);
- virtual void BroadcastOperators(VALUE_OPERATOR op);
-
- virtual unsigned char GetExpressionID() { return COPERATOR1EXPRESSIONID; }
- CExpression* CheckLink(std::vector<CBrokenLinkInfo*>& brokenlinks);
- //virtual bool IsInside(float x,float y,float z,bool bBorderInclude = true);
- virtual bool NeedsRecalculated();
- void ClearModified() {
- if (m_lhs)
- m_lhs->ClearModified();
- }
- virtual CValue* Calculate();
- COperator1Expr(VALUE_OPERATOR op, CExpression *lhs);
- COperator1Expr();
- virtual ~COperator1Expr();
-
-
-
-private:
- VALUE_OPERATOR m_op;
- CExpression * m_lhs;
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:")
-#endif
-};
-
-#endif /* __EXP_OPERATOR1EXPR_H__ */
diff --git a/source/gameengine/Expressions/EXP_Operator2Expr.h b/source/gameengine/Expressions/EXP_Operator2Expr.h
deleted file mode 100644
index cd7a492fde0..00000000000
--- a/source/gameengine/Expressions/EXP_Operator2Expr.h
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * Operator2Expr.h: interface for the COperator2Expr class.
- * Copyright (c) 1996-2000 Erwin Coumans <coockie@acm.org>
- *
- * Permission to use, copy, modify, distribute and sell this software
- * and its documentation for any purpose is hereby granted without fee,
- * provided that the above copyright notice appear in all copies and
- * that both that copyright notice and this permission notice appear
- * in supporting documentation. Erwin Coumans makes no
- * representations about the suitability of this software for any
- * purpose. It is provided "as is" without express or implied warranty.
- *
- */
-
-/** \file EXP_Operator2Expr.h
- * \ingroup expressions
- */
-
-#ifndef __EXP_OPERATOR2EXPR_H__
-#define __EXP_OPERATOR2EXPR_H__
-
-
-#include "EXP_Expression.h"
-#include "EXP_Value.h" // Added by ClassView
-
-class COperator2Expr : public CExpression
-{
- //PLUGIN_DECLARE_SERIAL_EXPRESSION (COperator2Expr,CExpression)
-
-public:
- virtual bool MergeExpression(CExpression* otherexpr);
- virtual unsigned char GetExpressionID() { return COPERATOR2EXPRESSIONID; }
- virtual void BroadcastOperators(VALUE_OPERATOR op);
- CExpression* CheckLink(std::vector<CBrokenLinkInfo*>& brokenlinks);
- //virtual bool IsInside(float x,float y,float z,bool bBorderInclude=true);
- //virtual bool IsLeftInside(float x,float y,float z,bool bBorderInclude);
- //virtual bool IsRightInside(float x,float y,float z,bool bBorderInclude);
- bool NeedsRecalculated();
- void ClearModified() {
- if (m_lhs)
- m_lhs->ClearModified();
- if (m_rhs)
- m_rhs->ClearModified();
- }
- virtual CValue* Calculate();
- COperator2Expr(VALUE_OPERATOR op, CExpression *lhs, CExpression *rhs);
- COperator2Expr();
- virtual ~COperator2Expr();
-
-
-protected:
- CExpression * m_rhs;
- CExpression * m_lhs;
- CValue* m_cached_calculate; // cached result
-
-private:
- VALUE_OPERATOR m_op;
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:COperator2Expr")
-#endif
-};
-
-#endif /* __EXP_OPERATOR2EXPR_H__ */
-
diff --git a/source/gameengine/Expressions/EXP_PyObjectPlus.h b/source/gameengine/Expressions/EXP_PyObjectPlus.h
deleted file mode 100644
index 32dc79cf6eb..00000000000
--- a/source/gameengine/Expressions/EXP_PyObjectPlus.h
+++ /dev/null
@@ -1,648 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file EXP_PyObjectPlus.h
- * \ingroup expressions
- */
-
-#ifndef __EXP_PYOBJECTPLUS_H__
-#define __EXP_PYOBJECTPLUS_H__
-
-/* for now keep weakrefs optional */
-#define USE_WEAKREFS
-
-
-#ifndef __cplusplus // c++ only
-#error Must be compiled with C++
-#endif
-
-#include "EXP_Python.h"
-#include "STR_String.h"
-#include "MT_Vector3.h"
-#include "SG_QList.h"
-#include <stddef.h>
-
-#ifdef WITH_PYTHON
-#ifdef USE_MATHUTILS
-extern "C" {
-#include "../../blender/python/mathutils/mathutils.h" /* so we can have mathutils callbacks */
-#include "../../blender/python/generic/py_capi_utils.h" /* for PyC_LineSpit only */
-}
-#endif
-
-#define MAX_PROP_NAME 64
-
-/* Use with ShowDeprecationWarning macro */
-typedef struct {
- bool warn_done;
- void *link;
-} WarnLink;
-
-#define ShowDeprecationWarning(old_way, new_way) \
-{ \
- static WarnLink wlink = {false, NULL}; \
- if ((PyObjectPlus::m_ignore_deprecation_warnings || wlink.warn_done)==0) \
- { \
- PyObjectPlus::ShowDeprecationWarning_func(old_way, new_way); \
- \
- WarnLink *wlink_last= PyObjectPlus::GetDeprecationWarningLinkLast(); \
- wlink.warn_done = true; \
- wlink.link = NULL; \
- \
- if (wlink_last) { \
- wlink_last->link= (void *)&(wlink); \
- PyObjectPlus::SetDeprecationWarningLinkLast(&(wlink)); \
- } \
- else { \
- PyObjectPlus::SetDeprecationWarningFirst(&(wlink)); \
- PyObjectPlus::SetDeprecationWarningLinkLast(&(wlink)); \
- } \
- } \
-} \
-
-
-
-typedef struct PyObjectPlus_Proxy {
- PyObject_HEAD /* required python macro */
- class PyObjectPlus *ref; // pointer to GE object, it holds a reference to this proxy
- void *ptr; // optional pointer to generic structure, the structure holds no reference to this proxy
- bool py_owns; // true if the object pointed by ref should be deleted when the proxy is deleted
- bool py_ref; // true if proxy is connected to a GE object (ref is used)
-#ifdef USE_WEAKREFS
- PyObject *in_weakreflist; // weak reference enabler
-#endif
-} PyObjectPlus_Proxy;
-
-#define BGE_PROXY_ERROR_MSG "Blender Game Engine data has been freed, cannot use this python variable"
-#define BGE_PROXY_REF(_self) (((PyObjectPlus_Proxy *)_self)->ref)
-#define BGE_PROXY_PTR(_self) (((PyObjectPlus_Proxy *)_self)->ptr)
-#define BGE_PROXY_PYOWNS(_self) (((PyObjectPlus_Proxy *)_self)->py_owns)
-#define BGE_PROXY_PYREF(_self) (((PyObjectPlus_Proxy *)_self)->py_ref)
-#ifdef USE_WEAKREFS
-# define BGE_PROXY_WKREF(_self) (((PyObjectPlus_Proxy *)_self)->in_weakreflist)
-#endif
-
-/* Note, sometimes we don't care what BGE type this is as long as its a proxy */
-#define BGE_PROXY_CHECK_TYPE(_type) ((_type)->tp_dealloc == PyObjectPlus::py_base_dealloc)
-
-/* Opposite of BGE_PROXY_REF */
-#define BGE_PROXY_FROM_REF(_self) (((PyObjectPlus *)_self)->GetProxy())
-/* Same as 'BGE_PROXY_REF' but doesn't incref. */
-#define BGE_PROXY_FROM_REF_BORROW(_self) _bge_proxy_from_ref_borrow((void *)_self)
-
-
-// This must be the first line of each
-// PyC++ class
-// AttributesPtr correspond to attributes of proxy generic pointer
-// each PyC++ class must be registered in KX_PythonInitTypes.cpp
-#define __Py_Header \
-public: \
- static PyTypeObject Type; \
- static PyMethodDef Methods[]; \
- static PyAttributeDef Attributes[]; \
- virtual PyTypeObject *GetType(void) { \
- return &Type; \
- } \
- virtual PyObject *GetProxy() { \
- return GetProxyPlus_Ext(this, &Type, NULL); \
- } \
- virtual PyObject *NewProxy(bool py_owns) { \
- return NewProxyPlus_Ext(this, &Type, NULL, py_owns); \
- } \
-
-// leave above line empty (macro)!
-// use this macro for class that use generic pointer in proxy
-// GetProxy() and NewProxy() must be defined to set the correct pointer in the proxy
-#define __Py_HeaderPtr \
-public: \
- static PyTypeObject Type; \
- static PyMethodDef Methods[]; \
- static PyAttributeDef Attributes[]; \
- static PyAttributeDef AttributesPtr[]; \
- virtual PyTypeObject *GetType(void) { \
- return &Type; \
- } \
- virtual PyObject *GetProxy(); \
- virtual PyObject *NewProxy(bool py_owns); \
-
-// leave above line empty (macro)!
-#ifdef WITH_CXX_GUARDEDALLOC
-#define Py_Header __Py_Header \
- void *operator new(size_t num_bytes) { \
- return MEM_mallocN(num_bytes, Type.tp_name); \
- } \
- void operator delete(void *mem) { \
- MEM_freeN(mem); \
- } \
-
-#else
-# define Py_Header __Py_Header
-#endif
-
-#ifdef WITH_CXX_GUARDEDALLOC
-#define Py_HeaderPtr __Py_HeaderPtr \
- void *operator new(size_t num_bytes) { \
- return MEM_mallocN(num_bytes, Type.tp_name); \
- } \
- void operator delete(void *mem) { \
- MEM_freeN(mem); \
- } \
-
-#else
-# define Py_HeaderPtr __Py_HeaderPtr
-#endif
-
-/*
- * nonzero values are an error for setattr
- * however because of the nested lookups we need to know if the errors
- * was because the attribute didnt exits of if there was some problem setting the value
- */
-
-#define PY_SET_ATTR_COERCE_FAIL 2
-#define PY_SET_ATTR_FAIL 1
-#define PY_SET_ATTR_MISSING -1
-#define PY_SET_ATTR_SUCCESS 0
-
-/**
- * These macros are helpful when embedding Python routines. The second
- * macro is one that also requires a documentation string
- */
-#define KX_PYMETHOD(class_name, method_name) \
- PyObject *Py##method_name(PyObject *args, PyObject *kwds); \
- static PyObject * \
- sPy##method_name(PyObject *self, PyObject *args, PyObject *kwds) { \
- if (BGE_PROXY_REF(self)==NULL) { \
- PyErr_SetString(PyExc_RuntimeError, \
- #class_name "." #method_name "() - " \
- BGE_PROXY_ERROR_MSG); \
- return NULL; \
- } \
- return((class_name*)BGE_PROXY_REF(self))->Py##method_name(args, kwds); \
- } \
-
-#define KX_PYMETHOD_VARARGS(class_name, method_name) \
- PyObject *Py##method_name(PyObject *args); \
- static PyObject* \
- sPy##method_name(PyObject *self, PyObject *args) { \
- if (BGE_PROXY_REF(self)==NULL) { \
- PyErr_SetString(PyExc_RuntimeError, \
- #class_name "." #method_name "() - " \
- BGE_PROXY_ERROR_MSG); return NULL; \
- } \
- return((class_name*)BGE_PROXY_REF(self))->Py##method_name(args); \
- } \
-
-#define KX_PYMETHOD_NOARGS(class_name, method_name) \
- PyObject *Py##method_name(); \
- static PyObject* \
- sPy##method_name(PyObject *self) { \
- if (BGE_PROXY_REF(self)==NULL) { \
- PyErr_SetString(PyExc_RuntimeError, \
- #class_name "." #method_name "() - " \
- BGE_PROXY_ERROR_MSG); return NULL; \
- } \
- return((class_name*)BGE_PROXY_REF(self))->Py##method_name(); \
- } \
-
-#define KX_PYMETHOD_O(class_name, method_name) \
- PyObject *Py##method_name(PyObject *value); \
- static PyObject* \
- sPy##method_name(PyObject *self, PyObject *value) { \
- if (BGE_PROXY_REF(self)==NULL) { \
- PyErr_SetString(PyExc_RuntimeError, \
- #class_name "." #method_name "(value) - " \
- BGE_PROXY_ERROR_MSG); return NULL; \
- } \
- return((class_name*)BGE_PROXY_REF(self))->Py##method_name(value); \
- } \
-
-#define KX_PYMETHOD_DOC(class_name, method_name) \
- PyObject *Py##method_name(PyObject *args, PyObject *kwds); \
- static PyObject* \
- sPy##method_name(PyObject *self, PyObject *args, PyObject *kwds) { \
- if (BGE_PROXY_REF(self)==NULL) { \
- PyErr_SetString(PyExc_RuntimeError, \
- #class_name "." #method_name "(...) - " \
- BGE_PROXY_ERROR_MSG); return NULL; \
- } \
- return((class_name*)BGE_PROXY_REF(self))->Py##method_name(args, kwds); \
- } \
- static const char method_name##_doc[]; \
-
-#define KX_PYMETHOD_DOC_VARARGS(class_name, method_name) \
- PyObject *Py##method_name(PyObject *args); \
- static PyObject* \
- sPy##method_name(PyObject *self, PyObject *args) { \
- if (BGE_PROXY_REF(self)==NULL) { \
- PyErr_SetString(PyExc_RuntimeError, \
- #class_name "." #method_name "(...) - " \
- BGE_PROXY_ERROR_MSG); \
- return NULL; \
- } \
- return((class_name*)BGE_PROXY_REF(self))->Py##method_name(args); \
- } \
- static const char method_name##_doc[]; \
-
-#define KX_PYMETHOD_DOC_O(class_name, method_name) \
- PyObject *Py##method_name(PyObject *value); \
- static PyObject * \
- sPy##method_name(PyObject *self, PyObject *value) { \
- if (BGE_PROXY_REF(self)==NULL) { \
- PyErr_SetString(PyExc_RuntimeError, \
- #class_name "." #method_name "(value) - " \
- BGE_PROXY_ERROR_MSG); \
- return NULL; \
- } \
- return ((class_name*)BGE_PROXY_REF(self))->Py##method_name(value); \
- } \
- static const char method_name##_doc[]; \
-
-#define KX_PYMETHOD_DOC_NOARGS(class_name, method_name) \
- PyObject *Py##method_name(); \
- static PyObject * \
- sPy##method_name(PyObject *self) { \
- if (BGE_PROXY_REF(self)==NULL) { \
- PyErr_SetString(PyExc_RuntimeError, \
- #class_name "." #method_name "() - " \
- BGE_PROXY_ERROR_MSG); \
- return NULL; \
- } \
- return ((class_name*)BGE_PROXY_REF(self))->Py##method_name(); \
- } \
- static const char method_name##_doc[]; \
-
-
-/* The line above should remain empty */
-/**
- * Method table macro (with doc)
- */
-#define KX_PYMETHODTABLE(class_name, method_name) \
- {#method_name, (PyCFunction) class_name::sPy##method_name, METH_VARARGS, (const char *)class_name::method_name##_doc}
-
-#define KX_PYMETHODTABLE_O(class_name, method_name) \
- {#method_name, (PyCFunction) class_name::sPy##method_name, METH_O, (const char *)class_name::method_name##_doc}
-
-#define KX_PYMETHODTABLE_NOARGS(class_name, method_name) \
- {#method_name, (PyCFunction) class_name::sPy##method_name, METH_NOARGS, (const char *)class_name::method_name##_doc}
-
-#define KX_PYMETHODTABLE_KEYWORDS(class_name, method_name) \
- {#method_name, (PyCFunction) class_name::sPy##method_name, METH_VARARGS|METH_KEYWORDS, (const char *)class_name::method_name##_doc}
-
-/**
- * Function implementation macro
- */
-#define KX_PYMETHODDEF_DOC(class_name, method_name, doc_string) \
-const char class_name::method_name##_doc[] = doc_string; \
-PyObject *class_name::Py##method_name(PyObject *args, PyObject *kwds)
-
-#define KX_PYMETHODDEF_DOC_VARARGS(class_name, method_name, doc_string) \
-const char class_name::method_name##_doc[] = doc_string; \
-PyObject *class_name::Py##method_name(PyObject *args)
-
-#define KX_PYMETHODDEF_DOC_O(class_name, method_name, doc_string) \
-const char class_name::method_name##_doc[] = doc_string; \
-PyObject *class_name::Py##method_name(PyObject *value)
-
-#define KX_PYMETHODDEF_DOC_NOARGS(class_name, method_name, doc_string) \
-const char class_name::method_name##_doc[] = doc_string; \
-PyObject *class_name::Py##method_name()
-
-/**
- * Attribute management
- */
-enum KX_PYATTRIBUTE_TYPE {
- KX_PYATTRIBUTE_TYPE_BOOL,
- KX_PYATTRIBUTE_TYPE_ENUM,
- KX_PYATTRIBUTE_TYPE_SHORT,
- KX_PYATTRIBUTE_TYPE_INT,
- KX_PYATTRIBUTE_TYPE_FLOAT,
- KX_PYATTRIBUTE_TYPE_STRING,
- KX_PYATTRIBUTE_TYPE_DUMMY,
- KX_PYATTRIBUTE_TYPE_FUNCTION,
- KX_PYATTRIBUTE_TYPE_VECTOR,
- KX_PYATTRIBUTE_TYPE_FLAG,
- KX_PYATTRIBUTE_TYPE_CHAR
-};
-
-enum KX_PYATTRIBUTE_ACCESS {
- KX_PYATTRIBUTE_RW,
- KX_PYATTRIBUTE_RO
-};
-
-struct KX_PYATTRIBUTE_DEF;
-typedef int (*KX_PYATTRIBUTE_CHECK_FUNCTION)(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef);
-typedef int (*KX_PYATTRIBUTE_SET_FUNCTION)(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
-typedef PyObject *(*KX_PYATTRIBUTE_GET_FUNCTION)(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef);
-
-typedef struct KX_PYATTRIBUTE_DEF {
- const char *m_name; // name of the python attribute
- KX_PYATTRIBUTE_TYPE m_type; // type of value
- KX_PYATTRIBUTE_ACCESS m_access; // read/write access or read-only
- int m_imin; // minimum value in case of integer attributes
- // (for string: minimum string length, for flag: mask value, for float: matrix row size)
- int m_imax; // maximum value in case of integer attributes
- // (for string: maximum string length, for flag: 1 if flag is negative, float: vector/matrix col size)
- float m_fmin; // minimum value in case of float attributes
- float m_fmax; // maximum value in case of float attributes
- bool m_clamp; // enforce min/max value by clamping
- bool m_usePtr; // the attribute uses the proxy generic pointer, set at runtime
- size_t m_offset; // position of field in structure
- size_t m_size; // size of field for runtime verification (enum only)
- size_t m_length; // length of array, 1=simple attribute
- KX_PYATTRIBUTE_CHECK_FUNCTION m_checkFunction; // static function to check the assignment, returns 0 if no error
- KX_PYATTRIBUTE_SET_FUNCTION m_setFunction; // static function to check the assignment, returns 0 if no error
- KX_PYATTRIBUTE_GET_FUNCTION m_getFunction; // static function to check the assignment, returns 0 if no error
-
- // The following pointers are just used to have compile time check for attribute type.
- // It would have been good to use a union but that would require C99 compatibility
- // to initialize specific union fields through designated initializers.
- struct {
- bool *m_boolPtr;
- short int *m_shortPtr;
- int *m_intPtr;
- float *m_floatPtr;
- STR_String *m_stringPtr;
- MT_Vector3 *m_vectorPtr;
- char *m_charPtr;
- } m_typeCheck;
-} PyAttributeDef;
-
-#define KX_PYATTRIBUTE_BOOL_RW(name, object, field) \
- { name, KX_PYATTRIBUTE_TYPE_BOOL, KX_PYATTRIBUTE_RW, 0, 1, 0.f, 0.f, false, false, offsetof(object, field), 0, 1, NULL, NULL, NULL, {&((object *)0)->field, NULL, NULL, NULL, NULL, NULL, NULL} }
-#define KX_PYATTRIBUTE_BOOL_RW_CHECK(name, object, field, function) \
- { name, KX_PYATTRIBUTE_TYPE_BOOL, KX_PYATTRIBUTE_RW, 0, 1, 0.f, 0.f, false, false, offsetof(object, field), 0, 1, &object::function, NULL, NULL, {&((object *)0)->field, NULL, NULL, NULL, NULL, NULL, NULL} }
-#define KX_PYATTRIBUTE_BOOL_RO(name, object, field) \
- { name, KX_PYATTRIBUTE_TYPE_BOOL, KX_PYATTRIBUTE_RO, 0, 1, 0.f, 0.f, false, false, offsetof(object, field), 0, 1, NULL, NULL, NULL, {&((object *)0)->field, NULL, NULL, NULL, NULL, NULL, NULL} }
-
-/* attribute points to a single bit of an integer field, attribute=true if bit is set */
-#define KX_PYATTRIBUTE_FLAG_RW(name, object, field, bit) \
- { name, KX_PYATTRIBUTE_TYPE_FLAG, KX_PYATTRIBUTE_RW, bit, 0, 0.f, 0.f, false, false, offsetof(object, field), sizeof(((object *)0)->field), 1, NULL, NULL, NULL, {NULL, NULL, NULL, NULL, NULL, NULL, NULL} }
-#define KX_PYATTRIBUTE_FLAG_RW_CHECK(name, object, field, bit, function) \
- { name, KX_PYATTRIBUTE_TYPE_FLAG, KX_PYATTRIBUTE_RW, bit, 0, 0.f, 0.f, false, false, offsetof(object, field), sizeof(((object *)0)->field), 1, &object::function, NULL, NULL, {NULL, NULL, NULL, NULL, NULL, NULL, NULL} }
-#define KX_PYATTRIBUTE_FLAG_RO(name, object, field, bit) \
- { name, KX_PYATTRIBUTE_TYPE_FLAG, KX_PYATTRIBUTE_RO, bit, 0, 0.f, 0.f, false, false, offsetof(object, field), sizeof(((object *)0)->field), 1, NULL, NULL, NULL, {NULL, NULL, NULL, NULL, NULL, NULL, NULL} }
-
-/* attribute points to a single bit of an integer field, attribute=true if bit is set*/
-#define KX_PYATTRIBUTE_FLAG_NEGATIVE_RW(name, object, field, bit) \
- { name, KX_PYATTRIBUTE_TYPE_FLAG, KX_PYATTRIBUTE_RW, bit, 1, 0.f, 0.f, false, false, offsetof(object, field), sizeof(((object *)0)->field), 1, NULL, NULL, NULL, {NULL, NULL, NULL, NULL, NULL, NULL, NULL} }
-#define KX_PYATTRIBUTE_FLAG_NEGATIVE_RW_CHECK(name, object, field, bit, function) \
- { name, KX_PYATTRIBUTE_TYPE_FLAG, KX_PYATTRIBUTE_RW, bit, 1, 0.f, 0.f, false, false, offsetof(object, field), sizeof(((object *)0)->field), 1, &object::function, NULL, NULL, {NULL, NULL, NULL, NULL, NULL, NULL, NULL} }
-#define KX_PYATTRIBUTE_FLAG_NEGATIVE_RO(name, object, field, bit) \
- { name, KX_PYATTRIBUTE_TYPE_FLAG, KX_PYATTRIBUTE_RO, bit, 1, 0.f, 0.f, false, false, offsetof(object, field), sizeof(((object *)0)->field), 1, NULL, NULL, NULL, {NULL, NULL, NULL, NULL, NULL, NULL, NULL} }
-
-// enum field cannot be mapped to pointer (because we would need a pointer for each enum)
-// use field size to verify mapping at runtime only, assuming enum size is equal to int size.
-#define KX_PYATTRIBUTE_ENUM_RW(name, min, max, clamp, object, field) \
- { name, KX_PYATTRIBUTE_TYPE_ENUM, KX_PYATTRIBUTE_RW, min, max, 0.f, 0.f, clamp, false, offsetof(object, field), sizeof(((object *)0)->field), 1, NULL, NULL, NULL, {NULL, NULL, NULL, NULL, NULL, NULL, NULL} }
-#define KX_PYATTRIBUTE_ENUM_RW_CHECK(name, min, max, clamp, object, field, function) \
- { name, KX_PYATTRIBUTE_TYPE_ENUM, KX_PYATTRIBUTE_RW, min, max, 0.f, 0.f, clamp, false, offsetof(object, field), sizeof(((object *)0)->field), 1, &object::function, NULL, NULL, {NULL, NULL, NULL, NULL, NULL, NULL, NULL} }
-#define KX_PYATTRIBUTE_ENUM_RO(name, object, field) \
- { name, KX_PYATTRIBUTE_TYPE_ENUM, KX_PYATTRIBUTE_RO, 0, 0, 0.f, 0.f, false, false, offsetof(object, field), sizeof(((object *)0)->field), 1, NULL, NULL, NULL, {NULL, NULL, NULL, NULL, NULL, NULL, NULL} }
-
-#define KX_PYATTRIBUTE_SHORT_RW(name, min, max, clamp, object, field) \
- { name, KX_PYATTRIBUTE_TYPE_SHORT, KX_PYATTRIBUTE_RW, min, max, 0.f, 0.f, clamp, false, offsetof(object, field), 0, 1, NULL, NULL, NULL, {NULL, &((object *)0)->field, NULL, NULL, NULL, NULL, NULL} }
-#define KX_PYATTRIBUTE_SHORT_RW_CHECK(name, min, max, clamp, object, field, function) \
- { name, KX_PYATTRIBUTE_TYPE_SHORT, KX_PYATTRIBUTE_RW, min, max, 0.f, 0.f, clamp, false, offsetof(object, field), 0, 1, &object::function, NULL, NULL, {NULL, &((object *)0)->field, NULL, NULL, NULL, NULL, NULL} }
-#define KX_PYATTRIBUTE_SHORT_RO(name, object, field) \
- { name, KX_PYATTRIBUTE_TYPE_SHORT, KX_PYATTRIBUTE_RO, 0, 0, 0.f, 0.f, false, false, offsetof(object, field), 0, 1, NULL, NULL, NULL, {NULL, &((object *)0)->field, NULL, NULL, NULL, NULL, NULL} }
-#define KX_PYATTRIBUTE_SHORT_ARRAY_RW(name, min, max, clamp, object, field, length) \
- { name, KX_PYATTRIBUTE_TYPE_SHORT, KX_PYATTRIBUTE_RW, min, max, 0.f, 0.f, clamp, false, offsetof(object, field), 0, length, NULL, NULL, NULL, {NULL, ((object *)0)->field, NULL, NULL, NULL, NULL, NULL} }
-#define KX_PYATTRIBUTE_SHORT_ARRAY_RW_CHECK(name, min, max, clamp, object, field, length, function) \
- { name, KX_PYATTRIBUTE_TYPE_SHORT, KX_PYATTRIBUTE_RW, min, max, 0.f, 0.f, clamp, false, offsetof(object, field), 0, length, &object::function, NULL, NULL, {NULL, ((object *)0)->field, NULL, NULL, NULL, NULL, NULL} }
-#define KX_PYATTRIBUTE_SHORT_ARRAY_RO(name, object, field, length) \
- { name, KX_PYATTRIBUTE_TYPE_SHORT, KX_PYATTRIBUTE_RO, 0, 0, 0.f, 0.f, false, false, offsetof(object, field), 0, length, NULL, NULL, NULL, {NULL, ((object *)0)->field, NULL, NULL, NULL, NULL, NULL} }
-// SHORT_LIST
-#define KX_PYATTRIBUTE_SHORT_LIST_RW(name, min, max, clamp, object, field, length) \
- { name, KX_PYATTRIBUTE_TYPE_SHORT, KX_PYATTRIBUTE_RW, min, max, 0.f, 0.f, clamp, false, offsetof(object, field), 0, length, NULL, NULL, NULL, {NULL, &((object *)0)->field, NULL, NULL, NULL, NULL, NULL} }
-#define KX_PYATTRIBUTE_SHORT_LIST_RW_CHECK(name, min, max, clamp, object, field, length, function) \
- { name, KX_PYATTRIBUTE_TYPE_SHORT, KX_PYATTRIBUTE_RW, min, max, 0.f, 0.f, clamp, false, offsetof(object, field), 0, length, &object::function, NULL, NULL, {NULL, &((object *)0)->field, NULL, NULL, NULL, NULL, NULL} }
-#define KX_PYATTRIBUTE_SHORT_LIST_RO(name, object, field, length) \
- { name, KX_PYATTRIBUTE_TYPE_SHORT, KX_PYATTRIBUTE_RO, 0, 0, 0.f, 0.f, false, false, offsetof(object, field), 0, length, NULL, NULL, NULL, {NULL, &((object *)0)->field, NULL, NULL, NULL, NULL, NULL} }
-
-#define KX_PYATTRIBUTE_INT_RW(name, min, max, clamp, object, field) \
- { name, KX_PYATTRIBUTE_TYPE_INT, KX_PYATTRIBUTE_RW, min, max, 0.f, 0.f, clamp, false, offsetof(object, field), 0, 1, NULL, NULL, NULL, {NULL, NULL, &((object *)0)->field, NULL, NULL, NULL, NULL} }
-#define KX_PYATTRIBUTE_INT_RW_CHECK(name, min, max, clamp, object, field, function) \
- { name, KX_PYATTRIBUTE_TYPE_INT, KX_PYATTRIBUTE_RW, min, max, 0.f, 0.f, clamp, false, offsetof(object, field), 0, 1, &object::function, NULL, NULL, {NULL, NULL, &((object *)0)->field, NULL, NULL, NULL, NULL} }
-#define KX_PYATTRIBUTE_INT_RO(name, object, field) \
- { name, KX_PYATTRIBUTE_TYPE_INT, KX_PYATTRIBUTE_RO, 0, 0, 0.f, 0.f, false, false, offsetof(object, field), 0, 1, NULL, NULL, NULL, {NULL, NULL, &((object *)0)->field, NULL, NULL, NULL, NULL} }
-#define KX_PYATTRIBUTE_INT_ARRAY_RW(name, min, max, clamp, object, field, length) \
- { name, KX_PYATTRIBUTE_TYPE_INT, KX_PYATTRIBUTE_RW, min, max, 0.f, 0.f, clamp, false, offsetof(object, field), 0, length, NULL, NULL, NULL, {NULL, NULL, ((object *)0)->field, NULL, NULL, NULL, NULL} }
-#define KX_PYATTRIBUTE_INT_ARRAY_RW_CHECK(name, min, max, clamp, object, field, length, function) \
- { name, KX_PYATTRIBUTE_TYPE_INT, KX_PYATTRIBUTE_RW, min, max, 0.f, 0.f, clamp, false, offsetof(object, field), 0, length, &object::function, NULL, NULL, {NULL, NULL, ((object *)0)->field, NULL, NULL, NULL, NULL} }
-#define KX_PYATTRIBUTE_INT_ARRAY_RO(name, object, field, length) \
- { name, KX_PYATTRIBUTE_TYPE_INT, KX_PYATTRIBUTE_RO, 0, 0, 0.f, 0.f, false, false, offsetof(object, field), 0, length, NULL, NULL, NULL, {NULL, NULL, ((object *)0)->field, NULL, NULL, NULL, NULL} }
-// INT_LIST
-#define KX_PYATTRIBUTE_INT_LIST_RW(name, min, max, clamp, object, field, length) \
- { name, KX_PYATTRIBUTE_TYPE_INT, KX_PYATTRIBUTE_RW, min, max, 0.f, 0.f, clamp, false, offsetof(object, field), 0, length, NULL, NULL, NULL, {NULL, NULL, &((object *)0)->field, NULL, NULL, NULL, NULL} }
-#define KX_PYATTRIBUTE_INT_LIST_RW_CHECK(name, min, max, clamp, object, field, length, function) \
- { name, KX_PYATTRIBUTE_TYPE_INT, KX_PYATTRIBUTE_RW, min, max, 0.f, 0.f, clamp, false, offsetof(object, field), 0, length, &object::function, NULL, NULL, {NULL, NULL, &((object *)0)->field, NULL, NULL, NULL, NULL} }
-#define KX_PYATTRIBUTE_INT_LIST_RO(name, object, field, length) \
- { name, KX_PYATTRIBUTE_TYPE_INT, KX_PYATTRIBUTE_RO, 0, 0, 0.f, 0.f, false, false, offsetof(object, field), 0, length, NULL, NULL, NULL, {NULL, NULL, &((object *)0)->field, NULL, NULL, NULL, NULL} }
-
-// always clamp for float
-#define KX_PYATTRIBUTE_FLOAT_RW(name, min, max, object, field) \
- { name, KX_PYATTRIBUTE_TYPE_FLOAT, KX_PYATTRIBUTE_RW, 0, 0, min, max, true, false, offsetof(object, field), 0, 1, NULL, NULL, NULL, {NULL, NULL, NULL, &((object *)0)->field, NULL, NULL, NULL} }
-#define KX_PYATTRIBUTE_FLOAT_RW_CHECK(name, min, max, object, field, function) \
- { name, KX_PYATTRIBUTE_TYPE_FLOAT, KX_PYATTRIBUTE_RW, 0, 0, min, max, true, false, offsetof(object, field), 0, 1, &object::function, NULL, NULL, {NULL, NULL, NULL, &((object *)0)->field, NULL, NULL, NULL} }
-#define KX_PYATTRIBUTE_FLOAT_RO(name, object, field) \
- { name, KX_PYATTRIBUTE_TYPE_FLOAT, KX_PYATTRIBUTE_RO, 0, 0, 0.f, 0.f, false, false, offsetof(object, field), 0, 1, NULL, NULL, NULL, {NULL, NULL, NULL, &((object *)0)->field, NULL, NULL, NULL} }
-// field must be float[n], returns a sequence
-#define KX_PYATTRIBUTE_FLOAT_ARRAY_RW(name, min, max, object, field, length) \
- { name, KX_PYATTRIBUTE_TYPE_FLOAT, KX_PYATTRIBUTE_RW, 0, 0, min, max, true, false, offsetof(object, field), 0, length, NULL, NULL, NULL, {NULL, NULL, NULL, ((object *)0)->field, NULL, NULL, NULL} }
-#define KX_PYATTRIBUTE_FLOAT_ARRAY_RW_CHECK(name, min, max, object, field, length, function) \
- { name, KX_PYATTRIBUTE_TYPE_FLOAT, KX_PYATTRIBUTE_RW, 0, 0, min, max, true, false, offsetof(object, field), 0, length, &object::function, NULL, NULL, {NULL, NULL, NULL, ((object *)0)->field, NULL, NULL, NULL} }
-#define KX_PYATTRIBUTE_FLOAT_ARRAY_RO(name, object, field, length) \
- { name, KX_PYATTRIBUTE_TYPE_FLOAT, KX_PYATTRIBUTE_RO, 0, 0, 0.f, 0.f, false, false, offsetof(object, field), 0, length, NULL, NULL, NULL, {NULL, NULL, NULL, ((object *)0)->field, NULL, NULL, NULL} }
-// field must be float[n], returns a vector
-#define KX_PYATTRIBUTE_FLOAT_VECTOR_RW(name, min, max, object, field, length) \
- { name, KX_PYATTRIBUTE_TYPE_FLOAT, KX_PYATTRIBUTE_RW, 0, length, min, max, true, false, offsetof(object, field), sizeof(((object *)0)->field), 1, NULL, NULL, NULL, {NULL, NULL, NULL, ((object *)0)->field, NULL, NULL, NULL} }
-#define KX_PYATTRIBUTE_FLOAT_VECTOR_RW_CHECK(name, min, max, object, field, length, function) \
- { name, KX_PYATTRIBUTE_TYPE_FLOAT, KX_PYATTRIBUTE_RW, 0, length, min, max, true, false, offsetof(object, field), sizeof(((object *)0)->field), 1, &object::function, NULL, NULL, {NULL, NULL, NULL, ((object *)0)->field, NULL, NULL, NULL} }
-#define KX_PYATTRIBUTE_FLOAT_VECTOR_RO(name, object, field, length) \
- { name, KX_PYATTRIBUTE_TYPE_FLOAT, KX_PYATTRIBUTE_RO, 0, length, 0.f, 0.f, false, false, offsetof(object, field), sizeof(((object *)0)->field), 1, NULL, NULL, NULL, {NULL, NULL, NULL, ((object *)0)->field, NULL, NULL, NULL} }
-// field must be float[n][n], returns a matrix
-#define KX_PYATTRIBUTE_FLOAT_MATRIX_RW(name, min, max, object, field, length) \
- { name, KX_PYATTRIBUTE_TYPE_FLOAT, KX_PYATTRIBUTE_RW, length, length, min, max, true, false, offsetof(object, field), sizeof(((object *)0)->field), 1, NULL, NULL, NULL, {NULL, NULL, NULL, ((object *)0)->field[0], NULL, NULL, NULL} }
-#define KX_PYATTRIBUTE_FLOAT_MATRIX_RW_CHECK(name, min, max, object, field, length, function) \
- { name, KX_PYATTRIBUTE_TYPE_FLOAT, KX_PYATTRIBUTE_RW, length, length, min, max, true, false, offsetof(object, field), sizeof(((object *)0)->field), 1, &object::function, NULL, NULL, {NULL, NULL, NULL, ((object *)0)->field[0], NULL, NULL, NULL} }
-#define KX_PYATTRIBUTE_FLOAT_MATRIX_RO(name, object, field, length) \
- { name, KX_PYATTRIBUTE_TYPE_FLOAT, KX_PYATTRIBUTE_RO, length, length, 0.f, 0.f, false, false, offsetof(object, field), sizeof(((object *)0)->field), 1, NULL, NULL, NULL, {NULL, NULL, NULL, ((object *)0)->field[0], NULL, NULL, NULL} }
-
-// only for STR_String member
-#define KX_PYATTRIBUTE_STRING_RW(name, min, max, clamp, object, field) \
- { name, KX_PYATTRIBUTE_TYPE_STRING, KX_PYATTRIBUTE_RW, min, max, 0.f, 0.f, clamp, false, offsetof(object, field), 0, 1, NULL, NULL, NULL, {NULL, NULL, NULL, NULL, &((object *)0)->field, NULL, NULL} }
-#define KX_PYATTRIBUTE_STRING_RW_CHECK(name, min, max, clamp, object, field, function) \
- { name, KX_PYATTRIBUTE_TYPE_STRING, KX_PYATTRIBUTE_RW, min, max, 0.f, 0.f, clamp, false, offsetof(object, field), 0, 1, &object::function, NULL, NULL, {NULL, NULL, NULL, NULL, &((object *)0)->field, NULL, NULL} }
-#define KX_PYATTRIBUTE_STRING_RO(name, object, field) \
- { name, KX_PYATTRIBUTE_TYPE_STRING, KX_PYATTRIBUTE_RO, 0, 0, 0.f, 0.f, false, false, offsetof(object, field), 0, 1 , NULL, NULL, NULL, {NULL, NULL, NULL, NULL, &((object *)0)->field, NULL, NULL} }
-
-// only for char [] array
-#define KX_PYATTRIBUTE_CHAR_RW(name, object, field) \
- { name, KX_PYATTRIBUTE_TYPE_CHAR, KX_PYATTRIBUTE_RW, 0, 0, 0.f, 0.f, true, false, offsetof(object, field), sizeof(((object *)0)->field), 1, NULL, NULL, NULL, {NULL, NULL, NULL, NULL, NULL, NULL, ((object *)0)->field} }
-#define KX_PYATTRIBUTE_CHAR_RW_CHECK(name, object, field, function) \
- { name, KX_PYATTRIBUTE_TYPE_CHAR, KX_PYATTRIBUTE_RW, 0, 0, 0.f, 0.f, true, false, offsetof(object, field), sizeof(((object *)0)->field), 1, &object::function, NULL, NULL, {NULL, NULL, NULL, NULL, NULL, NULL, ((object *)0)->field} }
-#define KX_PYATTRIBUTE_CHAR_RO(name, object, field) \
- { name, KX_PYATTRIBUTE_TYPE_CHAR, KX_PYATTRIBUTE_RO, 0, 0, 0.f, 0.f, false, false, offsetof(object, field), sizeof(((object *)0)->field), 1 , NULL, NULL, NULL, {NULL, NULL, NULL, NULL, NULL, NULL, ((object *)0)->field} }
-
-// for MT_Vector3 member
-#define KX_PYATTRIBUTE_VECTOR_RW(name, min, max, object, field) \
- { name, KX_PYATTRIBUTE_TYPE_VECTOR, KX_PYATTRIBUTE_RW, 0, 0, min, max, true, false, offsetof(object, field), 0, 1, NULL, NULL, NULL, {NULL, NULL, NULL, NULL, NULL, &((object *)0)->field, NULL} }
-#define KX_PYATTRIBUTE_VECTOR_RW_CHECK(name, min, max, clamp, object, field, function) \
- { name, KX_PYATTRIBUTE_TYPE_VECTOR, KX_PYATTRIBUTE_RW, 0, 0, min, max, true, false, offsetof(object, field), 0, 1, &object::function, NULL, NULL, {NULL, NULL, NULL, NULL, NULL, &((object *)0)->field, NULL} }
-#define KX_PYATTRIBUTE_VECTOR_RO(name, object, field) \
- { name, KX_PYATTRIBUTE_TYPE_VECTOR, KX_PYATTRIBUTE_RO, 0, 0, 0.f, 0.f, false, false, offsetof(object, field), 0, 1 , NULL, NULL, NULL, {NULL, NULL, NULL, NULL, NULL, &((object *)0)->field, NULL} }
-
-#define KX_PYATTRIBUTE_RW_FUNCTION(name, object, getfunction, setfunction) \
- { name, KX_PYATTRIBUTE_TYPE_FUNCTION, KX_PYATTRIBUTE_RW, 0, 0, 0.f, 0.f, false, false, 0, 0, 1, NULL, &object::setfunction, &object::getfunction, {NULL, NULL, NULL, NULL, NULL, NULL, NULL} }
-#define KX_PYATTRIBUTE_RO_FUNCTION(name, object, getfunction) \
- { name, KX_PYATTRIBUTE_TYPE_FUNCTION, KX_PYATTRIBUTE_RO, 0, 0, 0.f, 0.f, false, false, 0, 0, 1, NULL, NULL, &object::getfunction, {NULL, NULL, NULL, NULL, NULL, NULL, NULL} }
-#define KX_PYATTRIBUTE_ARRAY_RW_FUNCTION(name, object, length, getfunction, setfunction) \
- { name, KX_PYATTRIBUTE_TYPE_FUNCTION, KX_PYATTRIBUTE_RW, 0, 0, 0.f, 0, f, false, false, 0, 0, length, NULL, &object::setfunction, &object::getfunction, {NULL, NULL, NULL, NULL, NULL, NULL, NULL} }
-#define KX_PYATTRIBUTE_ARRAY_RO_FUNCTION(name, object, length, getfunction) \
- { name, KX_PYATTRIBUTE_TYPE_FUNCTION, KX_PYATTRIBUTE_RO, 0, 0, 0.f, 0, f, false, false, 0, 0, length, NULL, NULL, &object::getfunction, {NULL, NULL, NULL, NULL, NULL, NULL, NULL} }
-
-
-/*------------------------------
- * PyObjectPlus
- *------------------------------ */
-typedef PyTypeObject *PyParentObject; /* Define the PyParent Object */
-
-#else // WITH_PYTHON
-
-#ifdef WITH_CXX_GUARDEDALLOC
-#define Py_Header \
-public: \
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:PyObjectPlus") \
-
-
-#define Py_HeaderPtr \
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:PyObjectPlusPtr") \
-
-#else // WITH_CXX_GUARDEDALLOC
-
-#define Py_Header \
-public: \
-
-#define Py_HeaderPtr \
-public: \
-
-#endif /* WITH_CXX_GUARDEDALLOC */
-
-#endif
-
-
-// By making SG_QList the ultimate parent for PyObjectPlus objects, it
-// allows to put them in 2 different dynamic lists at the same time
-// The use of these links is interesting because they free of memory allocation
-// but it's very important not to mess up with them. If you decide that
-// the SG_QList or SG_DList component is used for something for a certain class,
-// they cannot can be used for anything else at a parent level!
-// What these lists are and what they are used for must be carefully documented
-// at the level where they are used.
-// DON'T MAKE ANY USE OF THESE LIST AT THIS LEVEL, they are already used
-// at SCA_IActuator, SCA_ISensor, SCA_IController level which rules out the
-// possibility to use them at SCA_ILogicBrick, CValue and PyObjectPlus level.
-class PyObjectPlus : public SG_QList
-{ // The PyObjectPlus abstract class
- Py_Header // Always start with Py_Header
-
-public:
- PyObjectPlus();
-
- virtual ~PyObjectPlus(); // destructor
-
-#ifdef WITH_PYTHON
- PyObject *m_proxy; /* actually a PyObjectPlus_Proxy */
-
- /* These static functions are referenced by ALL PyObjectPlus_Proxy types
- * they take the C++ reference from the PyObjectPlus_Proxy and call
- * its own virtual py_repr, py_base_dealloc, etc. functions.
- */
-
- static PyObject* py_base_new(PyTypeObject *type, PyObject *args, PyObject *kwds); /* allows subclassing */
- static void py_base_dealloc(PyObject *self);
- static PyObject* py_base_repr(PyObject *self);
-
- /* These are all virtual python methods that are defined in each class
- * Our own fake subclassing calls these on each class, then calls the parent */
- virtual PyObject* py_repr(void);
- /* subclass may overwrite this function to implement more sophisticated method of validating a proxy */
- virtual bool py_is_valid(void) { return true; }
-
- static PyObject* py_get_attrdef(PyObject *self_py, const PyAttributeDef *attrdef);
- static int py_set_attrdef(PyObject *self_py, PyObject *value, const PyAttributeDef *attrdef);
-
- /* Kindof dumb, always returns True, the false case is checked for, before this function gets accessed */
- static PyObject* pyattr_get_invalid(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
-
- static PyObject *GetProxyPlus_Ext(PyObjectPlus *self, PyTypeObject *tp, void *ptr);
- /* self=NULL => proxy to generic pointer detached from GE object
- * if py_owns is true, the memory pointed by ptr will be deleted automatically with MEM_freeN
- * self!=NULL=> proxy attached to GE object, ptr is optional and point to a struct from which attributes can be defined
- * if py_owns is true, the object will be deleted automatically, ptr will NOT be deleted
- * (assume object destructor takes care of it) */
- static PyObject *NewProxyPlus_Ext(PyObjectPlus *self, PyTypeObject *tp, void *ptr, bool py_owns);
-
- static WarnLink* GetDeprecationWarningLinkFirst(void);
- static WarnLink* GetDeprecationWarningLinkLast(void);
- static void SetDeprecationWarningFirst(WarnLink* wlink);
- static void SetDeprecationWarningLinkLast(WarnLink* wlink);
- static void NullDeprecationWarning();
-
- /** enable/disable display of deprecation warnings */
- static void SetDeprecationWarnings(bool ignoreDeprecationWarnings);
- /** Shows a deprecation warning */
- static void ShowDeprecationWarning_func(const char *method, const char *prop);
- static void ClearDeprecationWarning();
-
-#endif
-
- void InvalidateProxy();
-
- /**
- * Makes sure any internal data owned by this class is deep copied.
- */
- virtual void ProcessReplica();
-
- static bool m_ignore_deprecation_warnings;
-};
-
-#ifdef WITH_PYTHON
-PyObject *PyUnicode_From_STR_String(const STR_String& str);
-
-inline PyObject *_bge_proxy_from_ref_borrow(void *self_v)
-{
- PyObject *self_proxy = BGE_PROXY_FROM_REF(self_v);
- /* this is typically _very_ bad practice,
- * however we know the proxy is owned by 'self_v' */
- self_proxy->ob_refcnt--;
- return self_proxy;
-}
-
-#endif
-
-#endif /* __EXP_PYOBJECTPLUS_H__ */
diff --git a/source/gameengine/Expressions/EXP_Python.h b/source/gameengine/Expressions/EXP_Python.h
deleted file mode 100644
index f904151085e..00000000000
--- a/source/gameengine/Expressions/EXP_Python.h
+++ /dev/null
@@ -1,82 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file EXP_Python.h
- * \ingroup expressions
- */
-
-#ifndef __EXP_PYTHON_H__
-#define __EXP_PYTHON_H__
-
-//#define USE_DL_EXPORT
-
-/* python redefines, quiet the compiler */
-#ifdef _XOPEN_SOURCE
-#undef _XOPEN_SOURCE
-#endif
-
-#ifdef _POSIX_C_SOURCE
-#undef _POSIX_C_SOURCE
-#endif
-
-#ifdef WITH_PYTHON
-#include "Python.h"
-
-#define USE_MATHUTILS // Blender 2.5x api will use mathutils, for a while we might want to test without it
-
-#endif
-
-#ifdef __FreeBSD__
-#include <osreldate.h>
-#if __FreeBSD_version > 500039
-#undef isalnum
-#undef isalpha
-#undef iscntrl
-#undef isdigit
-#undef isgraph
-#undef islower
-#undef isprint
-#undef ispunct
-#undef isspace
-#undef isupper
-#undef isxdigit
-#undef tolower
-#undef toupper
-#endif
-#endif
-
-#ifdef __APPLE__
-#undef isalnum
-#undef isalpha
-#undef islower
-#undef isspace
-#undef isupper
-#undef tolower
-#undef toupper
-#endif
-
-#endif /* __EXP_PYTHON_H__ */
diff --git a/source/gameengine/Expressions/EXP_PythonCallBack.h b/source/gameengine/Expressions/EXP_PythonCallBack.h
deleted file mode 100644
index f0cbcac0c6f..00000000000
--- a/source/gameengine/Expressions/EXP_PythonCallBack.h
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * Contributor(s): Porteries Tristan.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file EXP_PythonCallBack.h
- * \ingroup expressions
- */
-
-#ifndef __EXP_PYTHON_CALLBACK_H__
-#define __EXP_PYTHON_CALLBACK_H__
-
-#include "EXP_Python.h"
-
-/** Execute each functions with at least one argument
- * \param functionlist The python list which contains callbacks.
- * \param arglist The first item in the tuple to execute callbacks (can be NULL for no arguments).
- * \param minargcount The minimum of quantity of arguments possible.
- * \param maxargcount The maximum of quantity of arguments possible.
- */
-void RunPythonCallBackList(PyObject *functionlist, PyObject **arglist, unsigned int minargcount, unsigned int maxargcount);
-
-#endif // __EXP_PYTHON_CALLBACK_H__
diff --git a/source/gameengine/Expressions/EXP_StringValue.h b/source/gameengine/Expressions/EXP_StringValue.h
deleted file mode 100644
index ca59ebf1f82..00000000000
--- a/source/gameengine/Expressions/EXP_StringValue.h
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * StringValue.h: interface for the CStringValue class.
- * Copyright (c) 1996-2000 Erwin Coumans <coockie@acm.org>
- *
- * Permission to use, copy, modify, distribute and sell this software
- * and its documentation for any purpose is hereby granted without fee,
- * provided that the above copyright notice appear in all copies and
- * that both that copyright notice and this permission notice appear
- * in supporting documentation. Erwin Coumans makes no
- * representations about the suitability of this software for any
- * purpose. It is provided "as is" without express or implied warranty.
- *
- */
-
-/** \file EXP_StringValue.h
- * \ingroup expressions
- */
-
-#ifndef __EXP_STRINGVALUE_H__
-#define __EXP_STRINGVALUE_H__
-
-#include "EXP_Value.h"
-
-class CStringValue : public CPropValue
-{
-
-
- //PLUGIN_DECLARE_SERIAL(CStringValue,CValue)
-public:
- /// Construction / destruction
- CStringValue();
- CStringValue(const char *txt, const char *name, AllocationTYPE alloctype = CValue::HEAPVALUE);
-
- virtual ~CStringValue() {}
- /// CValue implementation
- virtual bool IsEqual(const STR_String & other);
- virtual const STR_String & GetText();
- virtual double GetNumber();
- virtual int GetValueType();
-
- virtual CValue* Calc(VALUE_OPERATOR op, CValue *val);
- virtual CValue* CalcFinal(VALUE_DATA_TYPE dtype, VALUE_OPERATOR op, CValue *val);
- virtual void SetValue(CValue* newval) { m_strString = newval->GetText(); SetModified(true); }
- virtual CValue* GetReplica();
-#ifdef WITH_PYTHON
- virtual PyObject* ConvertValueToPython() {
- return PyUnicode_From_STR_String(m_strString);
- }
-#endif /* WITH_PYTHON */
-
-private:
- // data member
- STR_String m_strString;
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:CStringValue")
-#endif
-};
-
-#endif /* __EXP_STRINGVALUE_H__ */
diff --git a/source/gameengine/Expressions/EXP_Value.h b/source/gameengine/Expressions/EXP_Value.h
deleted file mode 100644
index 014fc59405f..00000000000
--- a/source/gameengine/Expressions/EXP_Value.h
+++ /dev/null
@@ -1,432 +0,0 @@
-/*
- * Value.h: interface for the CValue class.
- * Copyright (c) 1996-2000 Erwin Coumans <coockie@acm.org>
- *
- * Permission to use, copy, modify, distribute and sell this software
- * and its documentation for any purpose is hereby granted without fee,
- * provided that the above copyright notice appear in all copies and
- * that both that copyright notice and this permission notice appear
- * in supporting documentation. Erwin Coumans makes no
- * representations about the suitability of this software for any
- * purpose. It is provided "as is" without express or implied warranty.
- *
- */
-
-/** \file EXP_Value.h
- * \ingroup expressions
- */
-
-#ifndef __EXP_VALUE_H__
-#define __EXP_VALUE_H__
-
-#ifdef _MSC_VER
-# pragma warning (disable:4786)
-#endif
-
-#include <map> // array functionality for the propertylist
-#include "STR_String.h" // STR_String class
-
-using namespace std;
-
-#ifdef WITH_CXX_GUARDEDALLOC
-#include "MEM_guardedalloc.h"
-#endif
-
-#ifndef GEN_NO_ASSERT
-#undef assert
-#define assert(exp) ((void)NULL)
-#endif
-
-
-#ifndef GEN_NO_TRACE
-#undef trace
-#define trace(exp) ((void)NULL)
-#endif
-
-#ifndef GEN_NO_DEBUG
-#undef debug
-#define debug(exp) ((void)NULL)
-#endif
-
-#ifndef GEN_NO_ASSERTD
-#undef assertd
-#define assertd(exp) ((void)NULL)
-#endif
-
-enum VALUE_OPERATOR {
-
- VALUE_MOD_OPERATOR, // %
- VALUE_ADD_OPERATOR, // +
- VALUE_SUB_OPERATOR, // -
- VALUE_MUL_OPERATOR, // *
- VALUE_DIV_OPERATOR, // /
- VALUE_NEG_OPERATOR, // -
- VALUE_POS_OPERATOR, // +
- VALUE_AND_OPERATOR, // &&
- VALUE_OR_OPERATOR, // ||
- VALUE_EQL_OPERATOR, // ==
- VALUE_NEQ_OPERATOR, // !=
- VALUE_GRE_OPERATOR, // >
- VALUE_LES_OPERATOR, // <
- VALUE_GEQ_OPERATOR, // >=
- VALUE_LEQ_OPERATOR, // <=
- VALUE_NOT_OPERATOR, // !
- VALUE_NO_OPERATOR // no operation at all
-};
-
-enum VALUE_DATA_TYPE {
- VALUE_NO_TYPE, // abstract baseclass
- VALUE_INT_TYPE,
- VALUE_FLOAT_TYPE,
- VALUE_STRING_TYPE,
- VALUE_BOOL_TYPE,
- VALUE_ERROR_TYPE,
- VALUE_EMPTY_TYPE,
- VALUE_LIST_TYPE,
- VALUE_VOID_TYPE,
- VALUE_VECTOR_TYPE,
- VALUE_MAX_TYPE //only here to provide number of types
-};
-
-
-
-#ifdef DEBUG
-//extern int gRefCountValue; // debugonly variable to check if all CValue Refences are Dereferenced at programexit
-#endif
-
-struct HashableInt
-{
- HashableInt(int id) : mData(id) { }
-
- unsigned long Hash() const { return 0;} ////}gHash(&mData, sizeof(int));}
-
- bool operator==(HashableInt rhs) { return mData == rhs.mData; }
-
- int mData;
-};
-
-
-//
-// Bitfield that stores the flags for each CValue derived class
-//
-struct ValueFlags {
- ValueFlags() :
- Modified(true),
- Selected(false),
- Affected(false),
- ReleaseRequested(false),
- Error(false),
- RefCountDisabled(false),
- HasProperties(false),
- HasName(false),
- Visible(true),
- CustomFlag1(false),
- CustomFlag2(false)
- {
- }
-
- unsigned short Modified : 1;
- unsigned short Selected : 1;
- unsigned short Affected : 1;
- unsigned short ReleaseRequested : 1;
- unsigned short Error : 1;
- unsigned short RefCountDisabled : 1;
- unsigned short HasProperties : 1;
- unsigned short HasName : 1;
- unsigned short Visible : 1;
- unsigned short CustomFlag1 : 1;
- unsigned short CustomFlag2 : 1;
-
-
-};
-
-/**
- * Base Class for all Actions performed on CValue's. Can be extended for undo/redo system in future.
- */
-class CAction
-{
-public:
- CAction() {
- };
- virtual ~CAction() {
- };
- virtual void Execute() const =0;
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:CAction")
-#endif
-};
-
-
-#include "EXP_PyObjectPlus.h"
-#ifdef WITH_PYTHON
-#include "object.h"
-#endif
-
-/**
- * Baseclass CValue
- *
- * Together with CExpression, CValue and it's derived classes can be used to
- * parse expressions into a parsetree with error detecting/correcting capabilities
- * also expandable by a CFactory pluginsystem
- *
- * Base class for all editor functionality, flexible object type that allows
- * calculations and uses reference counting for memory management.
- *
- * Features:
- * - Reference Counting (AddRef() / Release())
- * - Calculations (Calc() / CalcFinal())
- * - Configuration (Configure())
- * - Serialization (EdSerialize() / EdIdSerialize() / EdPtrSerialize() and macro PLUGIN_DECLARE_SERIAL
- * - Property system (SetProperty() / GetProperty() / FindIdentifier())
- * - Replication (GetReplica())
- * - Flags (IsSelected() / IsModified() / SetSelected()...)
- *
- * - Some small editor-specific things added
- * - A helperclass CompressorArchive handles the serialization
- *
- */
-class CValue : public PyObjectPlus
-
-{
-Py_Header
-public:
- enum AllocationTYPE {
- STACKVALUE = 0,
- HEAPVALUE = 1
- };
-
- enum DrawTYPE {
- STARTFRAME = 0,
- ENDFRAME = 1,
- INTERFRAME = 2
- };
-
-
- // Construction / Destruction
- CValue();
-
-#ifdef WITH_PYTHON
- //static PyObject *PyMake(PyObject *, PyObject *);
- virtual PyObject *py_repr(void)
- {
- return PyUnicode_From_STR_String(GetText());
- }
-
- virtual PyObject *ConvertValueToPython() {
- return NULL;
- }
-
- virtual CValue *ConvertPythonToValue(PyObject *pyobj, const bool do_type_exception, const char *error_prefix);
-
- static PyObject *pyattr_get_name(void *self, const KX_PYATTRIBUTE_DEF *attrdef);
-
- virtual PyObject *ConvertKeysToPython( void );
-#endif /* WITH_PYTHON */
-
-
-
- // Expression Calculation
- virtual CValue* Calc(VALUE_OPERATOR op, CValue *val) = 0;
- virtual CValue* CalcFinal(VALUE_DATA_TYPE dtype, VALUE_OPERATOR op, CValue *val) = 0;
- virtual void SetOwnerExpression(class CExpression* expr);
-
-
-
- void Execute(const CAction& a)
- {
- a.Execute();
- };
-
- /// Reference Counting
- int GetRefCount()
- {
- return m_refcount;
- }
-
- // Add a reference to this value
- CValue *AddRef()
- {
- // Increase global reference count, used to see at the end of the program
- // if all CValue-derived classes have been dereferenced to 0
- //debug(gRefCountValue++);
-#ifdef DEBUG
- //gRefCountValue++;
-#endif
- m_refcount++;
- return this;
- }
-
- // Release a reference to this value (when reference count reaches 0, the value is removed from the heap)
- int Release()
- {
- // Decrease global reference count, used to see at the end of the program
- // if all CValue-derived classes have been dereferenced to 0
- //debug(gRefCountValue--);
-#ifdef DEBUG
- //gRefCountValue--;
-#endif
- // Decrease local reference count, if it reaches 0 the object should be freed
- if (--m_refcount > 0)
- {
- // Reference count normal, return new reference count
- return m_refcount;
- }
- else
- {
- // Reference count reached 0, delete ourselves and return 0
- // MT_assert(m_refcount==0, "Reference count reached sub-zero, object released too much");
-
- delete this;
- return 0;
- }
- }
-
-
- /// Property Management
- virtual void SetProperty(const STR_String& name,CValue* ioProperty); // Set property <ioProperty>, overwrites and releases a previous property with the same name if needed
- virtual void SetProperty(const char* name,CValue* ioProperty);
- virtual CValue* GetProperty(const char* inName); // Get pointer to a property with name <inName>, returns NULL if there is no property named <inName>
- virtual CValue* GetProperty(const STR_String & inName);
- const STR_String& GetPropertyText(const STR_String & inName); // Get text description of property with name <inName>, returns an empty string if there is no property named <inName>
- float GetPropertyNumber(const STR_String& inName,float defnumber);
- virtual bool RemoveProperty(const char *inName); // Remove the property named <inName>, returns true if the property was succesfully removed, false if property was not found or could not be removed
- virtual vector<STR_String> GetPropertyNames();
- virtual void ClearProperties(); // Clear all properties
-
- virtual void SetPropertiesModified(bool inModified); // Set all properties' modified flag to <inModified>
- virtual bool IsAnyPropertyModified(); // Check if any of the properties in this value have been modified
-
- virtual CValue* GetProperty(int inIndex); // Get property number <inIndex>
- virtual int GetPropertyCount(); // Get the amount of properties assiocated with this value
-
- virtual CValue* FindIdentifier(const STR_String& identifiername);
- /** Set the wireframe color of this value depending on the CSG
- * operator type <op>
- * \attention: not implemented */
- virtual void SetColorOperator(VALUE_OPERATOR op);
-
- virtual const STR_String & GetText() = 0;
- virtual double GetNumber() = 0;
- virtual int GetValueType(); // Get Prop value type
- double* ZeroVector() { return m_sZeroVec; }
- virtual double* GetVector3(bool bGetTransformedVec = false);
-
- virtual STR_String& GetName() = 0; // Retrieve the name of the value
- virtual void SetName(const char *name) = 0; // Set the name of the value
- /** Sets the value to this cvalue.
- * \attention this particular function should never be called. Why not abstract? */
- virtual void SetValue(CValue* newval);
- virtual CValue* GetReplica() =0;
- virtual void ProcessReplica();
- //virtual CValue* Copy() = 0;
-
- STR_String op2str(VALUE_OPERATOR op);
-
- // setting / getting flags
- inline void SetSelected(bool bSelected) { m_ValFlags.Selected = bSelected; }
- virtual void SetModified(bool bModified) { m_ValFlags.Modified = bModified; }
- virtual void SetAffected(bool bAffected=true) { m_ValFlags.Affected = bAffected; }
- inline void SetReleaseRequested(bool bReleaseRequested) { m_ValFlags.ReleaseRequested=bReleaseRequested; }
- inline void SetError(bool err) { m_ValFlags.Error=err; }
- inline void SetVisible (bool vis) { m_ValFlags.Visible=vis; }
-
- virtual bool IsModified() { return m_ValFlags.Modified; }
- inline bool IsError() { return m_ValFlags.Error; }
- virtual bool IsAffected() { return m_ValFlags.Affected || m_ValFlags.Modified; }
- virtual bool IsSelected() { return m_ValFlags.Selected; }
- inline bool IsReleaseRequested() { return m_ValFlags.ReleaseRequested; }
- virtual bool IsVisible() { return m_ValFlags.Visible;}
- virtual void SetCustomFlag1(bool bCustomFlag) { m_ValFlags.CustomFlag1 = bCustomFlag;}
- virtual bool IsCustomFlag1() { return m_ValFlags.CustomFlag1;}
-
- virtual void SetCustomFlag2(bool bCustomFlag) { m_ValFlags.CustomFlag2 = bCustomFlag;}
- virtual bool IsCustomFlag2() { return m_ValFlags.CustomFlag2;}
-
-protected:
- virtual void DisableRefCount(); // Disable reference counting for this value
- //virtual void AddDataToReplica(CValue* replica);
- virtual ~CValue();
-private:
- // Member variables
- std::map<STR_String,CValue*>* m_pNamedPropertyArray; // Properties for user/game etc
- ValueFlags m_ValFlags; // Frequently used flags in a bitfield (low memoryusage)
- int m_refcount; // Reference Counter
- static double m_sZeroVec[3];
-
-};
-
-
-
-//
-// Declare a CValue or CExpression or CWhatever to be serialized by the editor.
-//
-// This macro introduces the EdSerialize() function (which must be implemented by
-// the client) and the EdIdSerialize() function (which is implemented by this macro).
-//
-// The generated Copy() function returns a pointer to <root_base_class_name> type
-// of object. So, for *any* CValue-derived object this should be set to CValue,
-// for *any* CExpression-derived object this should be set to CExpression.
-//
-#define PLUGIN_DECLARE_SERIAL(class_name, root_base_class_name) \
-public: \
- virtual root_base_class_name *Copy() { \
- return new class_name; \
- } \
- virtual bool EdSerialize(CompressorArchive& arch, \
- class CFactoryManager* facmgr, \
- bool bIsStoring); \
- virtual bool EdIdSerialize(CompressorArchive& arch, \
- class CFactoryManager* facmgr, \
- bool bIsStoring) \
- { \
- if (bIsStoring) \
- arch.StoreString(#class_name); \
- return false; \
- } \
-
-
-////////////////////////////////////////////////////////////////////////////////
-////////////////////////////////////////////////////////////////////////////////
-////////////////////////////////////////////////////////////////////////////////
-
-// CPropValue is a CValue derived class, that implements the identification (String name)
-// SetName() / GetName(),
-// normal classes should derive from CPropValue, real lightweight classes straight from CValue
-
-
-class CPropValue : public CValue
-{
-public:
- CPropValue() :
- CValue(),
- m_strNewName()
-
- {
- }
-
- virtual ~CPropValue()
- {
- }
-
- virtual void SetName(const char *name) {
- m_strNewName = name;
- }
-
- virtual STR_String& GetName() {
- //STR_String namefromprop = GetPropertyText("Name");
- //if (namefromprop.Length() > 0)
- // return namefromprop;
- return m_strNewName;
- } // name of Value
-
-protected:
- STR_String m_strNewName; // Identification
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:CPropValue")
-#endif
-};
-
-#endif /* __EXP_VALUE_H__ */
diff --git a/source/gameengine/Expressions/EXP_VectorValue.h b/source/gameengine/Expressions/EXP_VectorValue.h
deleted file mode 100644
index d87d5097156..00000000000
--- a/source/gameengine/Expressions/EXP_VectorValue.h
+++ /dev/null
@@ -1,94 +0,0 @@
-/*
- * VectorValue.h: interface for the CVectorValue class.
- * Copyright (c) 1996-2000 Erwin Coumans <coockie@acm.org>
- *
- * Permission to use, copy, modify, distribute and sell this software
- * and its documentation for any purpose is hereby granted without fee,
- * provided that the above copyright notice appear in all copies and
- * that both that copyright notice and this permission notice appear
- * in supporting documentation. Erwin Coumans makes no
- * representations about the suitability of this software for any
- * purpose. It is provided "as is" without express or implied warranty.
- *
- */
-
-/** \file EXP_VectorValue.h
- * \ingroup expressions
- */
-
-#ifndef __EXP_VECTORVALUE_H__
-#define __EXP_VECTORVALUE_H__
-
-#include "EXP_Value.h"
-
-#define KX_X 0
-#define KX_Y 1
-#define KX_Z 2
-
-
-class CVectorValue : public CPropValue
-{
- //PLUGIN_DECLARE_SERIAL(CVectorValue,CValue)
-
-public:
- //void Transform(rcMatrix4x4 mat);
- virtual void SetValue(CValue* newval);
- void SetVector(double newvec[]);
- void Configure(CValue* menuvalue);
- virtual double* GetVector3(bool bGetTransformedVec=false);
- virtual double GetNumber();
- virtual int GetValueType();
-
- CValue* Calc(VALUE_OPERATOR op, CValue *val) {
- return val->CalcFinal(VALUE_VECTOR_TYPE, op, this);
- }
-
- CValue* CalcFinal(VALUE_DATA_TYPE dtype, VALUE_OPERATOR op, CValue *val);
-
-
- CVectorValue(double vec[3], const char *name,AllocationTYPE alloctype=CValue::HEAPVALUE);
- CVectorValue() {};
-
- CVectorValue(double vec[3], AllocationTYPE alloctype=CValue::HEAPVALUE);
- CVectorValue(float x,float y,float z, AllocationTYPE alloctype = CValue::HEAPVALUE);
- virtual ~CVectorValue();
- //virtual bool ExportT3D(File *txtfile,bool bNoName=false);
- void AddConfigurationData(CValue* menuvalue);
-
-
-
- virtual CValue* GetReplica();
- virtual const STR_String & GetText();
-
-#if 0
- void SnapPoint(float num,int snap)
- {
- if (num > 0) num += ((float)snap / 2);
- else num -= ((float)snap / 2);
- num = (long)(((long)(num / snap)) * snap);
- };
-
- void SnapPosition(const double snapvec[])
- {
-
- if (snapvec[KX_X] >= 1)
- SnapPoint(m_vec[KX_X],snapvec[KX_X]);
- if (snapvec[KX_Y] >= 1)
- SnapPoint(m_vec[KX_Y],snapvec[KX_Y]);
- if (snapvec[KX_Z] >= 1)
- SnapPoint(m_vec[KX_Z],snapvec[KX_Z]);
-
- }
-#endif
-
-protected:
- double m_vec[3];
- double m_transformedvec[3];
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:CVectorValue")
-#endif
-};
-
-#endif /* __EXP_VECTORVALUE_H__ */
diff --git a/source/gameengine/Expressions/EXP_VoidValue.h b/source/gameengine/Expressions/EXP_VoidValue.h
deleted file mode 100644
index 8b2c29488d7..00000000000
--- a/source/gameengine/Expressions/EXP_VoidValue.h
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * VoidValue.h: interface for the CVoidValue class.
- *
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file EXP_VoidValue.h
- * \ingroup expressions
- */
-
-#ifndef __EXP_VOIDVALUE_H__
-#define __EXP_VOIDVALUE_H__
-
-#include "EXP_Value.h"
-
-//
-// Void value, used to transport *any* type of data
-//
-class CVoidValue : public CPropValue
-{
- //PLUGIN_DECLARE_SERIAL (CVoidValue,CValue)
-
-public:
- /// Construction/destruction
- CVoidValue() : m_bDeleteOnDestruct(false), m_pAnything(NULL) { }
- CVoidValue(void *voidptr, bool bDeleteOnDestruct, AllocationTYPE alloctype) :
- m_bDeleteOnDestruct(bDeleteOnDestruct),
- m_pAnything(voidptr)
- {
- if (alloctype == STACKVALUE) {
- CValue::DisableRefCount();
- }
- }
- virtual ~CVoidValue(); /* Destruct void value, delete memory if we're owning it */
-
- /// Value -> String or number
- virtual const STR_String & GetText(); /* Get string description of void value (unimplemented) */
- virtual double GetNumber() { return -1; }
- virtual int GetValueType() { return VALUE_VOID_TYPE; }
-
- /// Value calculation
- virtual CValue* Calc(VALUE_OPERATOR op, CValue *val);
- virtual CValue* CalcFinal(VALUE_DATA_TYPE dtype, VALUE_OPERATOR op, CValue* val);
-
- /// Value replication
- virtual CValue* GetReplica();
-
- /// Data members
- bool m_bDeleteOnDestruct;
- void* m_pAnything;
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:CVoidValue")
-#endif
-};
-
-#endif /* __EXP_VOIDVALUE_H__ */
diff --git a/source/gameengine/Expressions/intern/BoolValue.cpp b/source/gameengine/Expressions/intern/BoolValue.cpp
deleted file mode 100644
index 1523a9212ba..00000000000
--- a/source/gameengine/Expressions/intern/BoolValue.cpp
+++ /dev/null
@@ -1,216 +0,0 @@
-/** \file gameengine/Expressions/BoolValue.cpp
- * \ingroup expressions
- */
-
-// BoolValue.cpp: implementation of the CBoolValue class.
-/*
- * Copyright (c) 1996-2000 Erwin Coumans <coockie@acm.org>
- *
- * Permission to use, copy, modify, distribute and sell this software
- * and its documentation for any purpose is hereby granted without fee,
- * provided that the above copyright notice appear in all copies and
- * that both that copyright notice and this permission notice appear
- * in supporting documentation. Erwin Coumans makes no
- * representations about the suitability of this software for any
- * purpose. It is provided "as is" without express or implied warranty.
- *
- */
-
-#include "EXP_BoolValue.h"
-#include "EXP_StringValue.h"
-#include "EXP_ErrorValue.h"
-#include "EXP_VoidValue.h"
-
-//////////////////////////////////////////////////////////////////////
-// Construction/Destruction
-//////////////////////////////////////////////////////////////////////
-
-const STR_String CBoolValue::sTrueString = "TRUE";
-const STR_String CBoolValue::sFalseString = "FALSE";
-
-CBoolValue::CBoolValue()
-/*
- * pre: false
- * effect: constructs a new CBoolValue
- */
-{
- trace("Bool constructor error");
-}
-
-
-
-CBoolValue::CBoolValue(bool inBool)
-: m_bool(inBool)
-{
-} // Constructs a new CBoolValue containing <inBool>
-
-
-
-CBoolValue::CBoolValue(bool innie,const char *name,AllocationTYPE alloctype)
-{
- m_bool = innie;
- SetName(name);
-
- if (alloctype == CValue::STACKVALUE)
- CValue::DisableRefCount();
-}
-
-
-
-void CBoolValue::SetValue(CValue* newval)
-{
- m_bool = (newval->GetNumber() != 0);
- SetModified(true);
-}
-
-
-
-CValue* CBoolValue::Calc(VALUE_OPERATOR op, CValue *val)
-/*
-pre:
-ret: a new object containing the result of applying operator op to this
-object and val
-*/
-{
- switch (op)
- {
- case VALUE_POS_OPERATOR:
- case VALUE_NEG_OPERATOR:
- {
- return new CErrorValue (op2str(op) + GetText());
- break;
- }
- case VALUE_NOT_OPERATOR:
- {
- return new CBoolValue (!m_bool);
- break;
- }
- default:
- {
- return val->CalcFinal(VALUE_BOOL_TYPE, op, this);
- break;
- }
- }
-}
-
-
-
-CValue* CBoolValue::CalcFinal(VALUE_DATA_TYPE dtype, VALUE_OPERATOR op, CValue *val)
-/*
-pre: the type of val is dtype
-ret: a new object containing the result of applying operator op to val and
-this object
-*/
-{
- CValue *ret;
-
- switch (dtype) {
- case VALUE_EMPTY_TYPE:
- case VALUE_BOOL_TYPE:
- {
- switch (op) {
- case VALUE_AND_OPERATOR:
- {
- ret = new CBoolValue (((CBoolValue *) val)->GetBool() && m_bool);
- break;
- }
- case VALUE_OR_OPERATOR:
- {
- ret = new CBoolValue (((CBoolValue *) val)->GetBool() || m_bool);
- break;
- }
- case VALUE_EQL_OPERATOR:
- {
- ret = new CBoolValue (((CBoolValue *) val)->GetBool() == m_bool);
- break;
- }
- case VALUE_NEQ_OPERATOR:
- {
- ret = new CBoolValue (((CBoolValue *) val)->GetBool() != m_bool);
- break;
- }
- case VALUE_NOT_OPERATOR:
- {
- return new CBoolValue (!m_bool);
- break;
- }
- default:
- {
- ret = new CErrorValue(val->GetText() + op2str(op) +
- "[operator not allowed on booleans]");
- break;
- }
- }
- break;
- }
- case VALUE_STRING_TYPE:
- {
- switch (op) {
- case VALUE_ADD_OPERATOR:
- {
- ret = new CStringValue(val->GetText() + GetText(),"");
- break;
- }
- default:
- {
- ret = new CErrorValue(val->GetText() + op2str(op) + "[Only + allowed on boolean and string]");
- break;
- }
- }
- break;
- }
- default:
- ret = new CErrorValue("[type mismatch]" + op2str(op) + GetText());
- }
-
- return ret;
-}
-
-
-
-bool CBoolValue::GetBool()
-/*
-pre:
-ret: the bool stored in the object
-*/
-{
- return m_bool;
-}
-
-
-
-double CBoolValue::GetNumber()
-{
- return (double)m_bool;
-}
-
-
-
-int CBoolValue::GetValueType()
-{
- return VALUE_BOOL_TYPE;
-}
-
-
-
-const STR_String& CBoolValue::GetText()
-{
- return m_bool ? sTrueString : sFalseString;
-}
-
-
-
-CValue* CBoolValue::GetReplica()
-{
- CBoolValue* replica = new CBoolValue(*this);
- replica->ProcessReplica();
-
- return replica;
-}
-
-#ifdef WITH_PYTHON
-PyObject *CBoolValue::ConvertValueToPython()
-{
- return PyBool_FromLong(m_bool != 0);
-}
-#endif // WITH_PYTHON
diff --git a/source/gameengine/Expressions/intern/ConstExpr.cpp b/source/gameengine/Expressions/intern/ConstExpr.cpp
deleted file mode 100644
index 597427ecfe5..00000000000
--- a/source/gameengine/Expressions/intern/ConstExpr.cpp
+++ /dev/null
@@ -1,131 +0,0 @@
-/** \file gameengine/Expressions/ConstExpr.cpp
- * \ingroup expressions
- */
-// ConstExpr.cpp: implementation of the CConstExpr class.
-
-/*
- * Copyright (c) 1996-2000 Erwin Coumans <coockie@acm.org>
- *
- * Permission to use, copy, modify, distribute and sell this software
- * and its documentation for any purpose is hereby granted without fee,
- * provided that the above copyright notice appear in all copies and
- * that both that copyright notice and this permission notice appear
- * in supporting documentation. Erwin Coumans makes no
- * representations about the suitability of this software for any
- * purpose. It is provided "as is" without express or implied warranty.
- *
- */
-
-#include "EXP_Value.h" // for precompiled header
-#include "EXP_ConstExpr.h"
-#include "EXP_VectorValue.h"
-
-//////////////////////////////////////////////////////////////////////
-// Construction/Destruction
-//////////////////////////////////////////////////////////////////////
-
-CConstExpr::CConstExpr()
-{
-}
-
-
-
-CConstExpr::CConstExpr(CValue* constval)
-/*
-pre:
-effect: constructs a CConstExpr cointing the value constval
-*/
-{
- m_value = constval;
-// m_bModified=true;
-}
-
-
-
-CConstExpr::~CConstExpr()
-/*
-pre:
-effect: deletes the object
-*/
-{
- if (m_value)
- m_value->Release();
-}
-
-
-
-unsigned char CConstExpr::GetExpressionID()
-{
- return CCONSTEXPRESSIONID;
-}
-
-
-
-CValue* CConstExpr::Calculate()
-/*
-pre:
-ret: a new object containing the value of the stored CValue
-*/
-{
- return m_value->AddRef();
-}
-
-
-
-void CConstExpr::ClearModified()
-{
- if (m_value)
- {
- m_value->SetModified(false);
- m_value->SetAffected(false);
- }
-}
-
-
-
-double CConstExpr::GetNumber()
-{
- return -1;
-}
-
-
-
-bool CConstExpr::NeedsRecalculated()
-{
- return m_value->IsAffected(); // IsAffected is m_bModified OR m_bAffected !!!
-}
-
-
-
-CExpression* CConstExpr::CheckLink(std::vector<CBrokenLinkInfo*>& brokenlinks)
-{
-// parent checks if child is still useful.
-// When for example it's value it's deleted flag set
-// then release Value, and return NULL in case of constexpression
-// else return this...
-
- assertd(m_value);
- if (m_value->IsReleaseRequested())
- {
- AddRef(); //numchanges++;
- return Release();
- }
- else
- return this;
-}
-
-
-
-void CConstExpr::BroadcastOperators(VALUE_OPERATOR op)
-{
- assertd(m_value);
- m_value->SetColorOperator(op);
-}
-
-
-
-bool CConstExpr::MergeExpression(CExpression *otherexpr)
-{
- assertd(false);
- return false;
-}
diff --git a/source/gameengine/Expressions/intern/EmptyValue.cpp b/source/gameengine/Expressions/intern/EmptyValue.cpp
deleted file mode 100644
index 9227626777d..00000000000
--- a/source/gameengine/Expressions/intern/EmptyValue.cpp
+++ /dev/null
@@ -1,133 +0,0 @@
-/** \file gameengine/Expressions/EmptyValue.cpp
- * \ingroup expressions
- */
-
-// EmptyValue.cpp: implementation of the CEmptyValue class.
-/*
- * Copyright (c) 1996-2000 Erwin Coumans <coockie@acm.org>
- *
- * Permission to use, copy, modify, distribute and sell this software
- * and its documentation for any purpose is hereby granted without fee,
- * provided that the above copyright notice appear in all copies and
- * that both that copyright notice and this permission notice appear
- * in supporting documentation. Erwin Coumans makes no
- * representations about the suitability of this software for any
- * purpose. It is provided "as is" without express or implied warranty.
- *
- */
-
-#include "EXP_EmptyValue.h"
-#include "EXP_IntValue.h"
-#include "EXP_FloatValue.h"
-#include "EXP_StringValue.h"
-#include "EXP_ErrorValue.h"
-#include "EXP_ListValue.h"
-#include "EXP_VoidValue.h"
-
-//////////////////////////////////////////////////////////////////////
-// Construction/Destruction
-//////////////////////////////////////////////////////////////////////
-
-CEmptyValue::CEmptyValue()
-/*
- * pre:
- * effect: constructs a new CEmptyValue
- */
-{
- SetModified(false);
-}
-
-
-
-CEmptyValue::~CEmptyValue()
-/*
- * pre:
- * effect: deletes the object
- */
-{
-
-}
-
-
-
-CValue *CEmptyValue::Calc(VALUE_OPERATOR op, CValue *val)
-/*
- * pre:
- * ret: a new object containing the result of applying operator op to this
- * object and val
- */
-{
- return val->CalcFinal(VALUE_EMPTY_TYPE, op, this);
-
-}
-
-
-
-CValue * CEmptyValue::CalcFinal(VALUE_DATA_TYPE dtype, VALUE_OPERATOR op, CValue *val)
-/*
- * pre: the type of val is dtype
- * ret: a new object containing the result of applying operator op to val and
- * this object
- */
-{
- return val->AddRef();
-}
-
-
-
-double CEmptyValue::GetNumber()
-{
- return 0;
-}
-
-
-
-int CEmptyValue::GetValueType()
-{
- return VALUE_EMPTY_TYPE;
-}
-
-
-
-CListValue* CEmptyValue::GetPolySoup()
-{
- CListValue* soup = new CListValue();
- //don't add any poly, while it's an empty value
- return soup;
-}
-
-
-
-bool CEmptyValue::IsInside(CValue* testpoint,bool bBorderInclude)
-{
- // empty space is solid, so always inside
- return true;
-}
-
-
-
-double* CEmptyValue::GetVector3(bool bGetTransformedVec)
-{
- assertd(false); // don't get vector from me
- return ZeroVector();
-}
-
-
-
-static STR_String emptyString = STR_String("");
-
-
-const STR_String & CEmptyValue::GetText()
-{
- return emptyString;
-}
-
-
-
-CValue* CEmptyValue::GetReplica()
-{
- CEmptyValue* replica = new CEmptyValue(*this);
- replica->ProcessReplica();
- return replica;
-}
-
diff --git a/source/gameengine/Expressions/intern/ErrorValue.cpp b/source/gameengine/Expressions/intern/ErrorValue.cpp
deleted file mode 100644
index c03ceb88073..00000000000
--- a/source/gameengine/Expressions/intern/ErrorValue.cpp
+++ /dev/null
@@ -1,131 +0,0 @@
-/** \file gameengine/Expressions/ErrorValue.cpp
- * \ingroup expressions
- */
-// ErrorValue.cpp: implementation of the CErrorValue class.
-/*
- * Copyright (c) 1996-2000 Erwin Coumans <coockie@acm.org>
- *
- * Permission to use, copy, modify, distribute and sell this software
- * and its documentation for any purpose is hereby granted without fee,
- * provided that the above copyright notice appear in all copies and
- * that both that copyright notice and this permission notice appear
- * in supporting documentation. Erwin Coumans makes no
- * representations about the suitability of this software for any
- * purpose. It is provided "as is" without express or implied warranty.
- *
- */
-
-#include "EXP_ErrorValue.h"
-
-//////////////////////////////////////////////////////////////////////
-// Construction/Destruction
-//////////////////////////////////////////////////////////////////////
-
-CErrorValue::CErrorValue()
-/*
-pre:
-effect: constructs a new CErrorValue containing errormessage "Error"
-*/
-{
- m_strErrorText = "Error";
- SetError(true);
-}
-
-
-
-CErrorValue::CErrorValue(const char *errmsg)
-/*
-pre:
-effect: constructs a new CErrorValue containing errormessage errmsg
-*/
-{
- m_strErrorText = "[";
- m_strErrorText += errmsg;
- m_strErrorText += "]";
- SetError(true);
-}
-
-
-
-CErrorValue::~CErrorValue()
-/*
-pre:
-effect: deletes the object
-*/
-{
-
-}
-
-
-
-CValue* CErrorValue::Calc(VALUE_OPERATOR op, CValue *val)
-/*
-pre:
-ret: a new object containing the result of applying operator op to this
- object and val
-*/
-{
- CValue* errorval;
-
- switch (op)
- {
- case VALUE_POS_OPERATOR:
- case VALUE_NEG_OPERATOR:
- case VALUE_NOT_OPERATOR:
- {
- errorval = new CErrorValue (op2str(op) + GetText());
- break;
- }
- default:
- {
- errorval = val->CalcFinal(VALUE_ERROR_TYPE, op, this);
- break;
- }
- }
-
- return errorval;
-}
-
-
-
-CValue* CErrorValue::CalcFinal(VALUE_DATA_TYPE dtype, VALUE_OPERATOR op, CValue *val)
-/*
-pre: the type of val is dtype
-ret: a new object containing the result of applying operator op to val and
- this object
-*/
-{
- return new CErrorValue (val->GetText() + op2str(op) + GetText());
-}
-
-
-
-double CErrorValue::GetNumber()
-{
- return -1;
-}
-
-
-
-int CErrorValue::GetValueType()
-{
- return VALUE_ERROR_TYPE;
-}
-
-
-
-const STR_String & CErrorValue::GetText()
-{
- return m_strErrorText;
-}
-
-
-
-CValue* CErrorValue::GetReplica()
-{
- // who would want a copy of an error ?
- trace ("Error: ErrorValue::GetReplica() not implemented yet");
- assertd(false);
-
- return NULL;
-}
diff --git a/source/gameengine/Expressions/intern/Expression.cpp b/source/gameengine/Expressions/intern/Expression.cpp
deleted file mode 100644
index 6a98a15aa12..00000000000
--- a/source/gameengine/Expressions/intern/Expression.cpp
+++ /dev/null
@@ -1,77 +0,0 @@
-/** \file gameengine/Expressions/Expression.cpp
- * \ingroup expressions
- */
-// Expression.cpp: implementation of the CExpression class.
-/*
- * Copyright (c) 1996-2000 Erwin Coumans <coockie@acm.org>
- *
- * Permission to use, copy, modify, distribute and sell this software
- * and its documentation for any purpose is hereby granted without fee,
- * provided that the above copyright notice appear in all copies and
- * that both that copyright notice and this permission notice appear
- * in supporting documentation. Erwin Coumans makes no
- * representations about the suitability of this software for any
- * purpose. It is provided "as is" without express or implied warranty.
- *
- */
-
-#include "EXP_Expression.h"
-#include "EXP_ErrorValue.h"
-
-//////////////////////////////////////////////////////////////////////
-// Construction/Destruction
-//////////////////////////////////////////////////////////////////////
-#ifdef DEBUG
-//int gRefCountExpr;
-#endif
-CExpression::CExpression()// : m_cached_calculate(NULL)
-{
- m_refcount = 1;
-#ifdef DEBUG
- //gRefCountExpr++;
-#endif
-}
-
-CExpression::~CExpression()
-{
- assert (m_refcount == 0);
-}
-
-
-
-// destuctor for CBrokenLinkInfo
-CBrokenLinkInfo::~CBrokenLinkInfo()
-{
- if (m_pExpr && !m_bRestored)
- m_pExpr->Release();
-}
-
-
-void CBrokenLinkInfo::RestoreLink()
-{
-
-
- assertd(m_pExpr);
-
- if (m_pExpr)
- {
- if (!m_bRestored) {
- m_bRestored=true;
-
- }
- if (*m_pmemExpr)
- {
- (*m_pmemExpr)->Release();
- }
- *m_pmemExpr = m_pExpr;
-
-// m_pExpr=NULL;
- }
-}
-
-void CBrokenLinkInfo::BreakLink()
-{
- m_bRestored=false;
- m_pExpr->AddRef();
-}
-
diff --git a/source/gameengine/Expressions/intern/FloatValue.cpp b/source/gameengine/Expressions/intern/FloatValue.cpp
deleted file mode 100644
index 0f86a429d81..00000000000
--- a/source/gameengine/Expressions/intern/FloatValue.cpp
+++ /dev/null
@@ -1,329 +0,0 @@
-/** \file gameengine/Expressions/FloatValue.cpp
- * \ingroup expressions
- */
-// FloatValue.cpp: implementation of the CFloatValue class.
-/*
- * Copyright (c) 1996-2000 Erwin Coumans <coockie@acm.org>
- *
- * Permission to use, copy, modify, distribute and sell this software
- * and its documentation for any purpose is hereby granted without fee,
- * provided that the above copyright notice appear in all copies and
- * that both that copyright notice and this permission notice appear
- * in supporting documentation. Erwin Coumans makes no
- * representations about the suitability of this software for any
- * purpose. It is provided "as is" without express or implied warranty.
- *
- */
-
-#include "EXP_FloatValue.h"
-#include "EXP_IntValue.h"
-#include "EXP_StringValue.h"
-#include "EXP_BoolValue.h"
-#include "EXP_ErrorValue.h"
-#include "EXP_VoidValue.h"
-
-//////////////////////////////////////////////////////////////////////
-// Construction/Destruction
-//////////////////////////////////////////////////////////////////////
-
-CFloatValue::CFloatValue()
-/*
-pre: false
-effect: constructs a new CFloatValue
-*/
-{
- m_pstrRep=NULL;
-}
-
-
-
-CFloatValue::CFloatValue(float fl)
-/*
-pre:
-effect: constructs a new CFloatValue containing value fl
-*/
-{
- m_float = fl;
- m_pstrRep=NULL;
-}
-
-
-
-CFloatValue::CFloatValue(float fl,const char *name,AllocationTYPE alloctype)
-/*
-pre:
-effect: constructs a new CFloatValue containing value fl
-*/
-{
-
- m_float = fl;
- SetName(name);
- if (alloctype==CValue::STACKVALUE)
- {
- CValue::DisableRefCount();
-
- }
- m_pstrRep=NULL;
-}
-
-
-
-CFloatValue::~CFloatValue()
-/*
-pre:
-effect: deletes the object
-*/
-{
- if (m_pstrRep)
- delete m_pstrRep;
-}
-
-
-
-CValue* CFloatValue::Calc(VALUE_OPERATOR op, CValue *val)
-/*
-pre:
-ret: a new object containing the result of applying operator op to this
- object and val
-*/
-{
- //return val->CalcFloat(op, this);
- switch (op)
- {
- case VALUE_POS_OPERATOR:
- return new CFloatValue (m_float);
- break;
- case VALUE_NEG_OPERATOR:
- return new CFloatValue (-m_float);
- break;
- case VALUE_NOT_OPERATOR:
- return new CBoolValue (m_float == 0.f);
- break;
- case VALUE_AND_OPERATOR:
- case VALUE_OR_OPERATOR:
- return new CErrorValue(val->GetText() + op2str(op) + "only allowed on booleans");
- break;
- default:
- return val->CalcFinal(VALUE_FLOAT_TYPE, op, this);
- break;
- }
-}
-
-
-
-CValue* CFloatValue::CalcFinal(VALUE_DATA_TYPE dtype, VALUE_OPERATOR op, CValue *val)
-/*
-pre: the type of val is dtype
-ret: a new object containing the result of applying operator op to val and
- this object
-*/
-{
- CValue *ret;
-
- switch (dtype) {
- case VALUE_INT_TYPE:
- {
- switch (op) {
- case VALUE_MOD_OPERATOR:
- ret = new CFloatValue(fmod(((CIntValue *) val)->GetInt(), m_float));
- break;
- case VALUE_ADD_OPERATOR:
- ret = new CFloatValue(((CIntValue *) val)->GetInt() + m_float);
- break;
- case VALUE_SUB_OPERATOR:
- ret = new CFloatValue(((CIntValue *) val)->GetInt() - m_float);
- break;
- case VALUE_MUL_OPERATOR:
- ret = new CFloatValue(((CIntValue *) val)->GetInt() * m_float);
- break;
- case VALUE_DIV_OPERATOR:
- if (m_float == 0)
- ret = new CErrorValue("Division by zero");
- else
- ret = new CFloatValue (((CIntValue *) val)->GetInt() / m_float);
- break;
- case VALUE_EQL_OPERATOR:
- ret = new CBoolValue(((CIntValue *) val)->GetInt() == m_float);
- break;
- case VALUE_NEQ_OPERATOR:
- ret = new CBoolValue(((CIntValue *) val)->GetInt() != m_float);
- break;
- case VALUE_GRE_OPERATOR:
- ret = new CBoolValue(((CIntValue *) val)->GetInt() > m_float);
- break;
- case VALUE_LES_OPERATOR:
- ret = new CBoolValue(((CIntValue *) val)->GetInt() < m_float);
- break;
- case VALUE_GEQ_OPERATOR:
- ret = new CBoolValue(((CIntValue *) val)->GetInt() >= m_float);
- break;
- case VALUE_LEQ_OPERATOR:
- ret = new CBoolValue(((CIntValue *) val)->GetInt() <= m_float);
- break;
- case VALUE_NOT_OPERATOR:
- ret = new CBoolValue(m_float == 0);
- break;
- default:
- ret = new CErrorValue("illegal operator. please send a bug report.");
- break;
- }
- break;
- }
- case VALUE_EMPTY_TYPE:
- case VALUE_FLOAT_TYPE:
- {
- switch (op) {
- case VALUE_MOD_OPERATOR:
- ret = new CFloatValue(fmod(((CFloatValue *) val)->GetFloat(), m_float));
- break;
- case VALUE_ADD_OPERATOR:
- ret = new CFloatValue(((CFloatValue *) val)->GetFloat() + m_float);
- break;
- case VALUE_SUB_OPERATOR:
- ret = new CFloatValue(((CFloatValue *) val)->GetFloat() - m_float);
- break;
- case VALUE_MUL_OPERATOR:
- ret = new CFloatValue(((CFloatValue *) val)->GetFloat() * m_float);
- break;
- case VALUE_DIV_OPERATOR:
- if (m_float == 0)
- ret = new CErrorValue("Division by zero");
- else
- ret = new CFloatValue (((CFloatValue *) val)->GetFloat() / m_float);
- break;
- case VALUE_EQL_OPERATOR:
- ret = new CBoolValue(((CFloatValue *) val)->GetFloat() == m_float);
- break;
- case VALUE_NEQ_OPERATOR:
- ret = new CBoolValue(((CFloatValue *) val)->GetFloat() != m_float);
- break;
- case VALUE_GRE_OPERATOR:
- ret = new CBoolValue(((CFloatValue *) val)->GetFloat() > m_float);
- break;
- case VALUE_LES_OPERATOR:
- ret = new CBoolValue(((CFloatValue *) val)->GetFloat() < m_float);
- break;
- case VALUE_GEQ_OPERATOR:
- ret = new CBoolValue(((CFloatValue *) val)->GetFloat() >= m_float);
- break;
- case VALUE_LEQ_OPERATOR:
- ret = new CBoolValue(((CFloatValue *) val)->GetFloat() <= m_float);
- break;
- case VALUE_NEG_OPERATOR:
- ret = new CFloatValue (-m_float);
- break;
- case VALUE_POS_OPERATOR:
- ret = new CFloatValue (m_float);
- break;
- case VALUE_NOT_OPERATOR:
- ret = new CBoolValue(m_float == 0);
- break;
- default:
- ret = new CErrorValue("illegal operator. please send a bug report.");
- break;
- }
- break;
- }
- case VALUE_STRING_TYPE:
- {
- switch (op) {
- case VALUE_ADD_OPERATOR:
- ret = new CStringValue(val->GetText() + GetText(),"");
- break;
- case VALUE_EQL_OPERATOR:
- case VALUE_NEQ_OPERATOR:
- case VALUE_GRE_OPERATOR:
- case VALUE_LES_OPERATOR:
- case VALUE_GEQ_OPERATOR:
- case VALUE_LEQ_OPERATOR:
- ret = new CErrorValue("[Cannot compare string with float]" + op2str(op) + GetText());
- break;
- default:
- ret = new CErrorValue("[operator not allowed on strings]" + op2str(op) + GetText());
- break;
- }
- break;
- }
- case VALUE_BOOL_TYPE:
- ret = new CErrorValue("[operator not valid on boolean and float]" + op2str(op) + GetText());
- break;
- case VALUE_ERROR_TYPE:
- ret = new CErrorValue(val->GetText() + op2str(op) + GetText());
- break;
- default:
- ret = new CErrorValue("illegal type. contact your dealer (if any)");
- break;
- }
- return ret;
-}
-
-
-
-void CFloatValue::SetFloat(float fl)
-{
- m_float = fl;
- SetModified(true);
-}
-
-
-
-float CFloatValue::GetFloat()
-/*
-pre:
-ret: the float stored in the object
-*/
-{
- return m_float;
-}
-
-
-
-double CFloatValue::GetNumber()
-{
- return m_float;
-}
-
-
-
-int CFloatValue::GetValueType()
-{
- return VALUE_FLOAT_TYPE;
-}
-
-
-
-void CFloatValue::SetValue(CValue* newval)
-{
- m_float = (float)newval->GetNumber();
- SetModified(true);
-}
-
-
-
-const STR_String & CFloatValue::GetText()
-{
- if (!m_pstrRep)
- m_pstrRep = new STR_String();
-
- m_pstrRep->Format("%f",m_float);
- return *m_pstrRep;
-}
-
-
-
-CValue* CFloatValue::GetReplica()
-{
- CFloatValue* replica = new CFloatValue(*this);
- replica->m_pstrRep = NULL; /* should be in CFloatValue::ProcessReplica() but its not defined, no matter */
- replica->ProcessReplica();
-
- return replica;
-}
-
-
-#ifdef WITH_PYTHON
-PyObject *CFloatValue::ConvertValueToPython()
-{
- return PyFloat_FromDouble(m_float);
-}
-#endif // WITH_PYTHON
diff --git a/source/gameengine/Expressions/intern/HashedPtr.cpp b/source/gameengine/Expressions/intern/HashedPtr.cpp
deleted file mode 100644
index 11d9482f993..00000000000
--- a/source/gameengine/Expressions/intern/HashedPtr.cpp
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Expressions/KX_HashedPtr.cpp
- * \ingroup expressions
- */
-
-
-#include "EXP_HashedPtr.h"
-
-
-CHashedPtr::CHashedPtr(void* val) : m_valptr(val)
-{
-}
-
-
-unsigned int CHashedPtr::hash() const
-{
-#if defined(_WIN64)
- unsigned __int64 key = (unsigned __int64)m_valptr;
-#else
- unsigned long key = (unsigned long)m_valptr;
-#endif
-
- key += ~(key << 16);
- key ^= (key >> 5);
- key += (key << 3);
- key ^= (key >> 13);
- key += ~(key << 9);
- key ^= (key >> 17);
-
- return (unsigned int)(key & 0xffffffff);
-}
diff --git a/source/gameengine/Expressions/intern/IdentifierExpr.cpp b/source/gameengine/Expressions/intern/IdentifierExpr.cpp
deleted file mode 100644
index 8fbbf41cd63..00000000000
--- a/source/gameengine/Expressions/intern/IdentifierExpr.cpp
+++ /dev/null
@@ -1,103 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Expressions/IdentifierExpr.cpp
- * \ingroup expressions
- */
-
-
-#include "EXP_IdentifierExpr.h"
-
-CIdentifierExpr::CIdentifierExpr(const STR_String& identifier,CValue* id_context)
-:m_identifier(identifier)
-{
- if (id_context)
- m_idContext = id_context->AddRef();
- else
- m_idContext=NULL;
-}
-
-
-CIdentifierExpr::~CIdentifierExpr()
-{
- if (m_idContext)
- m_idContext->Release();
-}
-
-
-
-CValue* CIdentifierExpr::Calculate()
-{
- CValue* result = NULL;
- if (m_idContext)
- result = m_idContext->FindIdentifier(m_identifier);
-
- return result;
-}
-
-
-
-bool CIdentifierExpr::MergeExpression(CExpression* otherexpr)
-{
- return false;
-}
-
-
-
-unsigned char CIdentifierExpr::GetExpressionID()
-{
- return CIDENTIFIEREXPRESSIONID;
-}
-
-
-
-bool CIdentifierExpr::NeedsRecalculated()
-{
- return true;
-}
-
-
-
-CExpression* CIdentifierExpr::CheckLink(std::vector<CBrokenLinkInfo*>& brokenlinks)
-{
- assertd(false); // not implemented yet
- return NULL;
-}
-
-
-
-void CIdentifierExpr::ClearModified()
-{
- assertd(false); // not implemented yet
-}
-
-
-
-void CIdentifierExpr::BroadcastOperators(VALUE_OPERATOR op)
-{
- assertd(false); // not implemented yet
-}
diff --git a/source/gameengine/Expressions/intern/IfExpr.cpp b/source/gameengine/Expressions/intern/IfExpr.cpp
deleted file mode 100644
index b4e2fe7315b..00000000000
--- a/source/gameengine/Expressions/intern/IfExpr.cpp
+++ /dev/null
@@ -1,144 +0,0 @@
-/** \file gameengine/Expressions/IfExpr.cpp
- * \ingroup expressions
- */
-// IfExpr.cpp: implementation of the CIfExpr class.
-/*
- * Copyright (c) 1996-2000 Erwin Coumans <coockie@acm.org>
- *
- * Permission to use, copy, modify, distribute and sell this software
- * and its documentation for any purpose is hereby granted without fee,
- * provided that the above copyright notice appear in all copies and
- * that both that copyright notice and this permission notice appear
- * in supporting documentation. Erwin Coumans makes no
- * representations about the suitability of this software for any
- * purpose. It is provided "as is" without express or implied warranty.
- *
- */
-
-#include "EXP_IfExpr.h"
-#include "EXP_EmptyValue.h"
-#include "EXP_ErrorValue.h"
-#include "EXP_BoolValue.h"
-
-//////////////////////////////////////////////////////////////////////
-// Construction/Destruction
-//////////////////////////////////////////////////////////////////////
-
-
-CIfExpr::CIfExpr()
-{
-}
-
-
-
-/*
- * pre:
- * effect: constructs an CifExpr-object corresponding to IF(guard, e1, e2)
- */
-CIfExpr::CIfExpr(CExpression *guard, CExpression *e1, CExpression *e2)
-{
- m_guard = guard;
- m_e1 = e1;
- m_e2 = e2;
-}
-
-
-
-/*
- * pre:
- * effect: dereferences the object
- */
-CIfExpr::~CIfExpr()
-{
- if (m_guard)
- m_guard->Release();
-
- if (m_e1)
- m_e1->Release();
-
- if (m_e2)
- m_e2->Release();
-}
-
-
-
-/**
- * pre:
- * ret: a new object containing the value of m_e1 if m_guard is a boolean true
- * a new object containing the value of m_e2 if m_guard is a boolean false
- * an new errorvalue if m_guard is not a boolean
- */
-CValue* CIfExpr::Calculate()
-{
- CValue *guardval;
- guardval = m_guard->Calculate();
- const STR_String& text = guardval->GetText();
- guardval->Release();
-
- if (&text == &CBoolValue::sTrueString)
- {
- return m_e1->Calculate();
- }
- else if (&text == &CBoolValue::sFalseString)
- {
- return m_e2->Calculate();
- }
- else
- {
- return new CErrorValue("Guard should be of boolean type");
- }
-}
-
-
-
-bool CIfExpr::MergeExpression(CExpression *otherexpr)
-{
- assertd(false);
- return false;
-}
-
-
-
-bool CIfExpr::IsInside(float x,float y,float z,bool bBorderInclude)
-{
- assertd(false);
- return false;
-}
-
-
-
-bool CIfExpr::NeedsRecalculated()
-{
- return (m_guard->NeedsRecalculated() ||
- m_e1->NeedsRecalculated() ||
- m_e2->NeedsRecalculated());
-}
-
-
-
-CExpression* CIfExpr::CheckLink(std::vector<CBrokenLinkInfo*>& brokenlinks)
-{
- assertd(false);
- return NULL;
-}
-
-
-
-void CIfExpr::ClearModified()
-{
- assertd(false);
-}
-
-
-
-void CIfExpr::BroadcastOperators(VALUE_OPERATOR op)
-{
- assertd(false);
-}
-
-
-
-unsigned char CIfExpr::GetExpressionID()
-{
- return CIFEXPRESSIONID;
-}
diff --git a/source/gameengine/Expressions/intern/InputParser.cpp b/source/gameengine/Expressions/intern/InputParser.cpp
deleted file mode 100644
index 583d8da63cb..00000000000
--- a/source/gameengine/Expressions/intern/InputParser.cpp
+++ /dev/null
@@ -1,669 +0,0 @@
-/** \file gameengine/Expressions/InputParser.cpp
- * \ingroup expressions
- */
-// Parser.cpp: implementation of the CParser class.
-/*
- * Copyright (c) 1996-2000 Erwin Coumans <coockie@acm.org>
- *
- * Permission to use, copy, modify, distribute and sell this software
- * and its documentation for any purpose is hereby granted without fee,
- * provided that the above copyright notice appear in all copies and
- * that both that copyright notice and this permission notice appear
- * in supporting documentation. Erwin Coumans makes no
- * representations about the suitability of this software for any
- * purpose. It is provided "as is" without express or implied warranty.
- *
- */
-
-#include <stdlib.h>
-
-#include "MT_assert.h"
-
-#include "EXP_Value.h"
-#include "EXP_InputParser.h"
-#include "EXP_ErrorValue.h"
-#include "EXP_IntValue.h"
-#include "EXP_StringValue.h"
-#include "EXP_FloatValue.h"
-#include "EXP_BoolValue.h"
-#include "EXP_EmptyValue.h"
-#include "EXP_ConstExpr.h"
-#include "EXP_Operator2Expr.h"
-#include "EXP_Operator1Expr.h"
-#include "EXP_IdentifierExpr.h"
-
-// this is disable at the moment, I expected a memleak from it, but the error-cleanup was the reason
-// well, looks we don't need it anyway, until maybe the Curved Surfaces are integrated into CSG
-// cool things like (IF(LOD==1,CCurvedValue,IF(LOD==2,CCurvedValue2)) etc...
-#include "EXP_IfExpr.h"
-
-#if defined(WIN32) || defined(WIN64)
-#define strcasecmp _stricmp
-
-#ifndef strtoll
-#define strtoll _strtoi64
-#endif
-
-#endif /* Def WIN32 or Def WIN64 */
-
-#define NUM_PRIORITY 6
-//////////////////////////////////////////////////////////////////////
-// Construction/Destruction
-//////////////////////////////////////////////////////////////////////
-
-CParser::CParser() : m_identifierContext(NULL)
-{
-}
-
-
-
-CParser::~CParser()
-{
- if (m_identifierContext)
- m_identifierContext->Release();
-}
-
-
-
-void CParser::ScanError(const char *str)
-{
- // sets the global variable errmsg to an errormessage with
- // contents str, appending if it already exists
- // AfxMessageBox("Parse Error:"+str,MB_ICONERROR);
- if (errmsg)
- errmsg = new COperator2Expr(VALUE_ADD_OPERATOR, errmsg, Error(str));
- else
- errmsg = Error(str);
-
- sym = errorsym;
-}
-
-
-
-CExpression* CParser::Error(const char *str)
-{
- // makes and returns a new CConstExpr filled with an CErrorValue
- // with string str
- // AfxMessageBox("Error:"+str,MB_ICONERROR);
- return new CConstExpr(new CErrorValue(str));
-}
-
-
-
-void CParser::NextCh()
-{
- // sets the global variable ch to the next character, if it exists
- // and increases the global variable chcount
- chcount++;
-
- if (chcount < text.Length())
- ch = text[chcount];
- else
- ch = 0x00;
-}
-
-
-
-void CParser::TermChar(char c)
-{
- // generates an error if the next char isn't the specified char c,
- // otherwise, skip the char
- if (ch == c)
- {
- NextCh();
- }
- else
- {
- STR_String str;
- str.Format("Warning: %c expected\ncontinuing without it", c);
- trace(str);
- }
-}
-
-
-
-void CParser::DigRep()
-{
- // changes the current character to the first character that
- // isn't a decimal
- while ((ch >= '0') && (ch <= '9'))
- NextCh();
-}
-
-
-
-void CParser::CharRep()
-{
- // changes the current character to the first character that
- // isn't an alphanumeric character
- while (((ch >= '0') && (ch <= '9'))
- || ((ch >= 'a') && (ch <= 'z'))
- || ((ch >= 'A') && (ch <= 'Z'))
- || (ch == '.') || (ch == '_'))
- NextCh();
-}
-
-
-
-void CParser::GrabString(int start)
-{
- // puts part of the input string into the global variable
- // const_as_string, from position start, to position chchount
- const_as_string = text.Mid(start, chcount-start);
-}
-
-
-
-void CParser::GrabRealString(int start)
-{
- // works like GrabString but converting \\n to \n
- // puts part of the input string into the global variable
- // const_as_string, from position start, to position chchount
-
- int i;
- char tmpch;
-
- const_as_string = STR_String();
- for (i=start;i<chcount;i++) {
- tmpch= text[i];
- if ((tmpch =='\\') && (text[i+1] == 'n')) {
- tmpch = '\n';
- i++;
- }
- const_as_string += tmpch;
- }
-}
-
-
-
-void CParser::NextSym()
-{
- // sets the global variable sym to the next symbol, and
- // if it is an operator
- // sets the global variable opkind to the kind of operator
- // if it is a constant
- // sets the global variable constkind to the kind of operator
- // if it is a reference to a cell
- // sets the global variable cellcoord to the kind of operator
-
- errmsg = NULL;
- while (ch == ' ' || ch == 0x9)
- NextCh();
-
- switch (ch) {
- case '(':
- sym = lbracksym; NextCh();
- break;
- case ')':
- sym = rbracksym; NextCh();
- break;
- case ',':
- sym = commasym; NextCh();
- break;
- case '%' :
- sym = opsym; opkind = OPmodulus; NextCh();
- break;
- case '+' :
- sym = opsym; opkind = OPplus; NextCh();
- break;
- case '-' :
- sym = opsym; opkind = OPminus; NextCh();
- break;
- case '*' :
- sym = opsym; opkind = OPtimes; NextCh();
- break;
- case '/' :
- sym = opsym; opkind = OPdivide; NextCh();
- break;
- case '&' :
- sym = opsym; opkind = OPand; NextCh(); TermChar('&');
- break;
- case '|' :
- sym = opsym; opkind = OPor; NextCh(); TermChar('|');
- break;
- case '=' :
- sym = opsym; opkind = OPequal; NextCh(); TermChar('=');
- break;
- case '!' :
- sym = opsym;
- NextCh();
- if (ch == '=')
- {
- opkind = OPunequal;
- NextCh();
- }
- else
- {
- opkind = OPnot;
- }
- break;
- case '>':
- sym = opsym;
- NextCh();
- if (ch == '=')
- {
- opkind = OPgreaterequal;
- NextCh();
- }
- else
- {
- opkind = OPgreater;
- }
- break;
- case '<':
- sym = opsym;
- NextCh();
- if (ch == '=') {
- opkind = OPlessequal;
- NextCh();
- } else {
- opkind = OPless;
- }
- break;
- case '\"' :
- {
- int start;
- sym = constsym;
- constkind = stringtype;
- NextCh();
- start = chcount;
- while ((ch != '\"') && (ch != 0x0))
- NextCh();
- GrabRealString(start);
- TermChar('\"'); // check for eol before '\"'
- break;
- }
- case 0x0: sym = eolsym; break;
- default:
- {
- int start;
- start = chcount;
- DigRep();
- if ((start != chcount) || (ch == '.')) { // number
- sym = constsym;
- if (ch == '.') {
- constkind = floattype;
- NextCh();
- DigRep();
- }
- else constkind = inttype;
- if ((ch == 'e') || (ch == 'E')) {
- int mark;
- constkind = floattype;
- NextCh();
- if ((ch == '+') || (ch == '-')) NextCh();
- mark = chcount;
- DigRep();
- if (mark == chcount) {
- ScanError("Number expected after 'E'");
- return;
- }
- }
- GrabString(start);
- } else if (((ch >= 'a') && (ch <= 'z'))
- || ((ch >= 'A') && (ch <= 'Z')))
- { // reserved word?
-
- start = chcount;
- CharRep();
- GrabString(start);
- if (!strcasecmp(const_as_string, "SUM")) {
- sym = sumsym;
- }
- else if (!strcasecmp(const_as_string, "NOT")) {
- sym = opsym;
- opkind = OPnot;
- }
- else if (!strcasecmp(const_as_string, "AND")) {
- sym = opsym; opkind = OPand;
- }
- else if (!strcasecmp(const_as_string, "OR")) {
- sym = opsym; opkind = OPor;
- }
- else if (!strcasecmp(const_as_string, "IF"))
- sym = ifsym;
- else if (!strcasecmp(const_as_string, "WHOMADE"))
- sym = whocodedsym;
- else if (!strcasecmp(const_as_string, "FALSE")) {
- sym = constsym; constkind = booltype; boolvalue = false;
- } else if (!strcasecmp(const_as_string, "TRUE")) {
- sym = constsym; constkind = booltype; boolvalue = true;
- } else {
- sym = idsym;
- //STR_String str;
- //str.Format("'%s' makes no sense here", (const char*)funstr);
- //ScanError(str);
- }
- } else { // unknown symbol
- STR_String str;
- str.Format("Unexpected character '%c'", ch);
- NextCh();
- ScanError(str);
- return;
- }
- }
- }
-}
-
-#if 0
-int CParser::MakeInt()
-{
- // returns the integer representation of the value in the global
- // variable const_as_string
- // pre: const_as_string contains only numercal chars
- return atoi(const_as_string);
-}
-#endif
-
-const char *CParser::Symbol2Str(int s)
-{
- // returns a string representation of of symbol s,
- // for use in Term when generating an error
- switch (s) {
- case errorsym: return "error";
- case lbracksym: return "(";
- case rbracksym: return ")";
- case commasym: return ",";
- case opsym: return "operator";
- case constsym: return "constant";
- case sumsym: return "SUM";
- case ifsym: return "IF";
- case whocodedsym: return "WHOMADE";
- case eolsym: return "end of line";
- case idsym: return "identifier";
- }
- return "unknown"; // should not happen
-}
-
-void CParser::Term(int s)
-{
- // generates an error if the next symbol isn't the specified symbol s
- // otherwise, skip the symbol
- if (s == sym) {
- NextSym();
- }
- else {
- STR_String msg;
- msg.Format("Warning: %s expected\ncontinuing without it", Symbol2Str(s));
-
-// AfxMessageBox(msg,MB_ICONERROR);
-
- trace(msg);
- }
-}
-
-int CParser::Priority(int optorkind)
-{
- // returns the priority of an operator
- // higher number means higher priority
- switch (optorkind) {
- case OPor: return 1;
- case OPand: return 2;
- case OPgreater:
- case OPless:
- case OPgreaterequal:
- case OPlessequal:
- case OPequal:
- case OPunequal: return 3;
- case OPplus:
- case OPminus: return 4;
- case OPmodulus:
- case OPtimes:
- case OPdivide: return 5;
- }
- MT_assert(false);
- return 0; // should not happen
-}
-
-CExpression *CParser::Ex(int i)
-{
- // parses an expression in the imput, starting at priority i, and
- // returns an CExpression, containing the parsed input
- CExpression *e1 = NULL, *e2 = NULL;
- int opkind2;
-
- if (i < NUM_PRIORITY) {
- e1 = Ex(i + 1);
- while ((sym == opsym) && (Priority(opkind) == i)) {
- opkind2 = opkind;
- NextSym();
- e2 = Ex(i + 1);
- switch (opkind2) {
- case OPmodulus: e1 = new COperator2Expr(VALUE_MOD_OPERATOR,e1, e2); break;
- case OPplus: e1 = new COperator2Expr(VALUE_ADD_OPERATOR,e1, e2); break;
- case OPminus: e1 = new COperator2Expr(VALUE_SUB_OPERATOR,e1, e2); break;
- case OPtimes: e1 = new COperator2Expr(VALUE_MUL_OPERATOR,e1, e2); break;
- case OPdivide: e1 = new COperator2Expr(VALUE_DIV_OPERATOR,e1, e2); break;
- case OPand: e1 = new COperator2Expr(VALUE_AND_OPERATOR,e1, e2); break;
- case OPor: e1 = new COperator2Expr(VALUE_OR_OPERATOR,e1, e2); break;
- case OPequal: e1 = new COperator2Expr(VALUE_EQL_OPERATOR,e1, e2); break;
- case OPunequal: e1 = new COperator2Expr(VALUE_NEQ_OPERATOR,e1, e2); break;
- case OPgreater: e1 = new COperator2Expr(VALUE_GRE_OPERATOR,e1, e2); break;
- case OPless: e1 = new COperator2Expr(VALUE_LES_OPERATOR,e1, e2); break;
- case OPgreaterequal: e1 = new COperator2Expr(VALUE_GEQ_OPERATOR,e1, e2); break;
- case OPlessequal: e1 = new COperator2Expr(VALUE_LEQ_OPERATOR,e1, e2); break;
- default: MT_assert(false); break; // should not happen
- }
- }
- } else if (i == NUM_PRIORITY) {
- if ((sym == opsym)
- && ( (opkind == OPminus) || (opkind == OPnot) || (opkind == OPplus) )
- )
- {
- NextSym();
- switch (opkind) {
- /* +1 is also a valid number! */
- case OPplus: e1 = new COperator1Expr(VALUE_POS_OPERATOR, Ex(NUM_PRIORITY)); break;
- case OPminus: e1 = new COperator1Expr(VALUE_NEG_OPERATOR, Ex(NUM_PRIORITY)); break;
- case OPnot: e1 = new COperator1Expr(VALUE_NOT_OPERATOR, Ex(NUM_PRIORITY)); break;
- default:
- {
- // should not happen
- e1 = Error("operator +, - or ! expected");
- }
- }
- }
- else {
- switch (sym) {
- case constsym:
- {
- switch (constkind) {
- case booltype:
- e1 = new CConstExpr(new CBoolValue(boolvalue));
- break;
- case inttype:
- {
- cInt temp;
- temp = strtoll(const_as_string, NULL, 10); /* atoi is for int only */
- e1 = new CConstExpr(new CIntValue(temp));
- break;
- }
- case floattype:
- {
- double temp;
- temp = atof(const_as_string);
- e1 = new CConstExpr(new CFloatValue(temp));
- break;
- }
- case stringtype:
- e1 = new CConstExpr(new CStringValue(const_as_string,""));
- break;
- default :
- MT_assert(false);
- break;
- }
- NextSym();
- break;
- }
- case lbracksym:
- NextSym();
- e1 = Ex(1);
- Term(rbracksym);
- break;
- case ifsym:
- {
- CExpression *e3;
- NextSym();
- Term(lbracksym);
- e1 = Ex(1);
- Term(commasym);
- e2 = Ex(1);
- if (sym == commasym) {
- NextSym();
- e3 = Ex(1);
- } else {
- e3 = new CConstExpr(new CEmptyValue());
- }
- Term(rbracksym);
- e1 = new CIfExpr(e1, e2, e3);
- break;
- }
- case idsym:
- {
- e1 = new CIdentifierExpr(const_as_string,m_identifierContext);
- NextSym();
-
- break;
- }
- case errorsym:
- {
- MT_assert(!e1);
- STR_String errtext="[no info]";
- if (errmsg)
- {
- CValue* errmsgval = errmsg->Calculate();
- errtext=errmsgval->GetText();
- errmsgval->Release();
-
- //e1 = Error(errmsg->Calculate()->GetText());//new CConstExpr(errmsg->Calculate());
-
- if ( !(errmsg->Release()) )
- {
- errmsg=NULL;
- } else {
- // does this happen ?
- MT_assert("does this happen");
- }
- }
- e1 = Error(errtext);
-
- break;
- }
- default:
- NextSym();
- //return Error("Expression expected");
- MT_assert(!e1);
- e1 = Error("Expression expected");
- }
- }
- }
- return e1;
-}
-
-CExpression *CParser::Expr()
-{
- // parses an expression in the imput, and
- // returns an CExpression, containing the parsed input
- return Ex(1);
-}
-
-CExpression* CParser::ProcessText
-(const char *intext) {
-
- // and parses the string in intext and returns it.
-
-
- CExpression* expr;
- text = intext;
-
-
- chcount = 0;
- if (text.Length() == 0) {
- return NULL;
- }
-
- ch = text[0];
- /* if (ch != '=') {
- * expr = new CConstExpr(new CStringValue(text));
- * *dependent = deplist;
- * return expr;
- * } else
- */
- // NextCh();
- NextSym();
- expr = Expr();
- if (sym != eolsym) {
- CExpression* oldexpr = expr;
- expr = new COperator2Expr(VALUE_ADD_OPERATOR,
- oldexpr, Error(STR_String("Extra characters after expression")));//new CConstExpr(new CErrorValue("Extra characters after expression")));
- }
- if (errmsg)
- errmsg->Release();
-
- return expr;
-}
-
-
-
-float CParser::GetFloat(STR_String& txt)
-{
- // returns parsed text into a float
- // empty string returns -1
-
-// AfxMessageBox("parsed string="+txt);
- CValue* val=NULL;
- float result=-1;
-// String tmpstr;
-
- CExpression* expr = ProcessText(txt);
- if (expr) {
- val = expr->Calculate();
- result=(float)val->GetNumber();
-
-
-
- val->Release();
- expr->Release();
- }
-// tmpstr.Format("parseresult=%g",result);
-// AfxMessageBox(tmpstr);
- return result;
-}
-
-CValue* CParser::GetValue(STR_String& txt, bool bFallbackToText)
-{
- // returns parsed text into a value,
- // empty string returns NULL value !
- // if bFallbackToText then unparsed stuff is put into text
-
- CValue* result=NULL;
- CExpression* expr = ProcessText(txt);
- if (expr) {
- result = expr->Calculate();
- expr->Release();
- }
- if (result)
- {
- // if the parsed stuff lead to an errorvalue, don't return errors, just NULL
- if (result->IsError()) {
- result->Release();
- result=NULL;
- if (bFallbackToText) {
- if (txt.Length()>0)
- {
- result = new CStringValue(txt,"");
- }
- }
- }
- }
- return result;
-}
-
-void CParser::SetContext(CValue* context)
-{
- if (m_identifierContext)
- {
- m_identifierContext->Release();
- }
- m_identifierContext = context;
-}
diff --git a/source/gameengine/Expressions/intern/IntValue.cpp b/source/gameengine/Expressions/intern/IntValue.cpp
deleted file mode 100644
index 7b2e841f13f..00000000000
--- a/source/gameengine/Expressions/intern/IntValue.cpp
+++ /dev/null
@@ -1,344 +0,0 @@
-/** \file gameengine/Expressions/IntValue.cpp
- * \ingroup expressions
- */
-// IntValue.cpp: implementation of the CIntValue class.
-/*
- * Copyright (c) 1996-2000 Erwin Coumans <coockie@acm.org>
- *
- * Permission to use, copy, modify, distribute and sell this software
- * and its documentation for any purpose is hereby granted without fee,
- * provided that the above copyright notice appear in all copies and
- * that both that copyright notice and this permission notice appear
- * in supporting documentation. Erwin Coumans makes no
- * representations about the suitability of this software for any
- * purpose. It is provided "as is" without express or implied warranty.
- *
- */
-
-#include <stdio.h>
-
-#include "EXP_IntValue.h"
-#include "EXP_ErrorValue.h"
-#include "EXP_FloatValue.h"
-#include "EXP_BoolValue.h"
-#include "EXP_StringValue.h"
-#include "EXP_VoidValue.h"
-
-//////////////////////////////////////////////////////////////////////
-// Construction/Destruction
-//////////////////////////////////////////////////////////////////////
-
-CIntValue::CIntValue()
-/*
-pre: false
-effect: constructs a new CIntValue
-*/
-{
-
-#ifdef DEBUG_
- m_textval = "Int illegal constructor";
-#endif
- m_pstrRep=NULL;
-}
-
-
-
-CIntValue::CIntValue(cInt innie)
-/*
-pre:
-effect: constructs a new CIntValue containing cInt innie
-*/
-{
- m_int = innie;
- m_pstrRep=NULL;
-}
-
-
-
-CIntValue::CIntValue(cInt innie,const char *name,AllocationTYPE alloctype)
-{
- m_int = innie;
- SetName(name);
-
- if (alloctype==CValue::STACKVALUE)
- {
- CValue::DisableRefCount();
- }
- m_pstrRep=NULL;
-
-}
-
-
-
-CIntValue::~CIntValue()
-/*
-pre:
-effect: deletes the object
-*/
-{
- if (m_pstrRep)
- delete m_pstrRep;
-}
-
-
-
-CValue* CIntValue::Calc(VALUE_OPERATOR op, CValue *val)
-/*
-pre:
-ret: a new object containing the result of applying operator op to this
-object and val
-*/
-{
- //return val->CalcInt(op, this);
- switch (op) {
- case VALUE_POS_OPERATOR:
- return new CIntValue (m_int);
- break;
- case VALUE_NEG_OPERATOR:
- return new CIntValue (-m_int);
- break;
- case VALUE_NOT_OPERATOR:
- return new CBoolValue (m_int == 0);
- break;
- case VALUE_AND_OPERATOR:
- case VALUE_OR_OPERATOR:
- return new CErrorValue(val->GetText() + op2str(op) + "only allowed on booleans");
- break;
- default:
- return val->CalcFinal(VALUE_INT_TYPE, op, this);
- break;
- }
-}
-
-/*
- * pre: the type of val is dtype
- * ret: a new object containing the result of applying operator op to val and
- * this object
- */
-CValue* CIntValue::CalcFinal(VALUE_DATA_TYPE dtype, VALUE_OPERATOR op, CValue *val)
-{
- CValue *ret;
-
- switch (dtype) {
- case VALUE_EMPTY_TYPE:
- case VALUE_INT_TYPE:
- {
- switch (op) {
- case VALUE_MOD_OPERATOR:
- ret = new CIntValue (((CIntValue *) val)->GetInt() % m_int);
- break;
- case VALUE_ADD_OPERATOR:
- ret = new CIntValue (((CIntValue *) val)->GetInt() + m_int);
- break;
- case VALUE_SUB_OPERATOR:
- ret = new CIntValue (((CIntValue *) val)->GetInt() - m_int);
- break;
- case VALUE_MUL_OPERATOR:
- ret = new CIntValue (((CIntValue *) val)->GetInt() * m_int);
- break;
- case VALUE_DIV_OPERATOR:
- if (m_int == 0) {
- if (val->GetNumber() == 0) {
- ret = new CErrorValue("Not a Number");
- }
- else {
- ret = new CErrorValue("Division by zero");
- }
- }
- else
- ret = new CIntValue (((CIntValue *) val)->GetInt() / m_int);
- break;
- case VALUE_EQL_OPERATOR:
- ret = new CBoolValue(((CIntValue *) val)->GetInt() == m_int);
- break;
- case VALUE_NEQ_OPERATOR:
- ret = new CBoolValue(((CIntValue *) val)->GetInt() != m_int);
- break;
- case VALUE_GRE_OPERATOR:
- ret = new CBoolValue(((CIntValue *) val)->GetInt() > m_int);
- break;
- case VALUE_LES_OPERATOR:
- ret = new CBoolValue(((CIntValue *) val)->GetInt() < m_int);
- break;
- case VALUE_GEQ_OPERATOR:
- ret = new CBoolValue(((CIntValue *) val)->GetInt() >= m_int);
- break;
- case VALUE_LEQ_OPERATOR:
- ret = new CBoolValue(((CIntValue *) val)->GetInt() <= m_int);
- break;
- case VALUE_NEG_OPERATOR:
- ret = new CIntValue (-m_int);
- break;
- case VALUE_POS_OPERATOR:
- ret = new CIntValue (m_int);
- break;
- case VALUE_NOT_OPERATOR:
- ret = new CBoolValue(m_int == 0);
- break;
- default:
- printf("Found op: %d\n", op);
- ret = new CErrorValue("illegal operator. please send a bug report.");
- break;
- }
- break;
- }
- case VALUE_FLOAT_TYPE:
- {
- switch (op) {
- case VALUE_MOD_OPERATOR:
- ret = new CFloatValue(fmod(((CFloatValue *) val)->GetFloat(), m_int));
- break;
- case VALUE_ADD_OPERATOR:
- ret = new CFloatValue (((CFloatValue *) val)->GetFloat() + m_int);
- break;
- case VALUE_SUB_OPERATOR:
- ret = new CFloatValue (((CFloatValue *) val)->GetFloat() - m_int);
- break;
- case VALUE_MUL_OPERATOR:
- ret = new CFloatValue (((CFloatValue *) val)->GetFloat() * m_int);
- break;
- case VALUE_DIV_OPERATOR:
- if (m_int == 0)
- ret = new CErrorValue("Division by zero");
- else
- ret = new CFloatValue (((CFloatValue *) val)->GetFloat() / m_int);
- break;
- case VALUE_EQL_OPERATOR:
- ret = new CBoolValue(((CFloatValue *) val)->GetFloat() == m_int);
- break;
- case VALUE_NEQ_OPERATOR:
- ret = new CBoolValue(((CFloatValue *) val)->GetFloat() != m_int);
- break;
- case VALUE_GRE_OPERATOR:
- ret = new CBoolValue(((CFloatValue *) val)->GetFloat() > m_int);
- break;
- case VALUE_LES_OPERATOR:
- ret = new CBoolValue(((CFloatValue *) val)->GetFloat() < m_int);
- break;
- case VALUE_GEQ_OPERATOR:
- ret = new CBoolValue(((CFloatValue *) val)->GetFloat() >= m_int);
- break;
- case VALUE_LEQ_OPERATOR:
- ret = new CBoolValue(((CFloatValue *) val)->GetFloat() <= m_int);
- break;
- case VALUE_NOT_OPERATOR:
- ret = new CBoolValue(m_int == 0);
- break;
- default:
- ret = new CErrorValue("illegal operator. please send a bug report.");
- break;
- }
- break;
- }
- case VALUE_STRING_TYPE:
- {
- switch (op) {
- case VALUE_ADD_OPERATOR:
- ret = new CStringValue(val->GetText() + GetText(),"");
- break;
- case VALUE_EQL_OPERATOR:
- case VALUE_NEQ_OPERATOR:
- case VALUE_GRE_OPERATOR:
- case VALUE_LES_OPERATOR:
- case VALUE_GEQ_OPERATOR:
- case VALUE_LEQ_OPERATOR:
- ret = new CErrorValue("[Cannot compare string with integer]" + op2str(op) + GetText());
- break;
- default:
- ret = new CErrorValue("[operator not allowed on strings]" + op2str(op) + GetText());
- break;
- }
- break;
- }
- case VALUE_BOOL_TYPE:
- ret = new CErrorValue("[operator not valid on boolean and integer]" + op2str(op) + GetText());
- break;
-#if 0
- case VALUE_EMPTY_TYPE:
- {
- switch (op) {
- case VALUE_ADD_OPERATOR:
- ret = new CIntValue (m_int);
- break;
- case VALUE_SUB_OPERATOR:
- ret = new CIntValue (-m_int);
- break;
- default:
- {
- ret = new CErrorValue(op2str(op) + GetText());
- }
- }
- break;
- }
-#endif
- case VALUE_ERROR_TYPE:
- ret = new CErrorValue(val->GetText() + op2str(op) + GetText());
- break;
- default:
- ret = new CErrorValue("illegal type. contact your dealer (if any)");
- break;
- }
- return ret;
-}
-
-
-/**
- * pre:
- * ret: the cInt stored in the object
- */
-cInt CIntValue::GetInt()
-{
- return m_int;
-}
-
-
-
-double CIntValue::GetNumber()
-{
- return (double) m_int;
-}
-
-
-
-int CIntValue::GetValueType()
-{
- return VALUE_INT_TYPE;
-}
-
-
-
-const STR_String & CIntValue::GetText()
-{
- if (!m_pstrRep)
- m_pstrRep=new STR_String();
- m_pstrRep->Format("%lld",m_int);
-
- return *m_pstrRep;
-}
-
-
-
-CValue* CIntValue::GetReplica()
-{
- CIntValue* replica = new CIntValue(*this);
- replica->ProcessReplica();
- replica->m_pstrRep = NULL;
-
- return replica;
-}
-
-
-
-void CIntValue::SetValue(CValue* newval)
-{
- m_int = (cInt)newval->GetNumber();
- SetModified(true);
-}
-
-
-#ifdef WITH_PYTHON
-PyObject *CIntValue::ConvertValueToPython()
-{
- return PyLong_FromLongLong(m_int);
-}
-#endif // WITH_PYTHON
diff --git a/source/gameengine/Expressions/intern/ListValue.cpp b/source/gameengine/Expressions/intern/ListValue.cpp
deleted file mode 100644
index 557ce7be300..00000000000
--- a/source/gameengine/Expressions/intern/ListValue.cpp
+++ /dev/null
@@ -1,702 +0,0 @@
-/** \file gameengine/Expressions/ListValue.cpp
- * \ingroup expressions
- */
-// ListValue.cpp: implementation of the CListValue class.
-//
-//////////////////////////////////////////////////////////////////////
-/*
- * Copyright (c) 1996-2000 Erwin Coumans <coockie@acm.org>
- *
- * Permission to use, copy, modify, distribute and sell this software
- * and its documentation for any purpose is hereby granted without fee,
- * provided that the above copyright notice appear in all copies and
- * that both that copyright notice and this permission notice appear
- * in supporting documentation. Erwin Coumans makes no
- * representations about the suitability of this software for any
- * purpose. It is provided "as is" without express or implied warranty.
- *
- */
-
-#include <stdio.h>
-
-#include "EXP_ListValue.h"
-#include "EXP_StringValue.h"
-#include "EXP_VoidValue.h"
-#include <algorithm>
-#include "EXP_BoolValue.h"
-
-#include "BLI_sys_types.h" /* for intptr_t support */
-
-
-//////////////////////////////////////////////////////////////////////
-// Construction/Destruction
-//////////////////////////////////////////////////////////////////////
-
-CListValue::CListValue()
-: CPropValue()
-{
- m_bReleaseContents=true;
-}
-
-
-
-CListValue::~CListValue()
-{
-
- if (m_bReleaseContents) {
- for (unsigned int i=0;i<m_pValueArray.size();i++) {
- m_pValueArray[i]->Release();
- }
- }
-}
-
-
-static STR_String gstrListRep=STR_String("List");
-
-const STR_String & CListValue::GetText()
-{
- gstrListRep = "[";
- STR_String commastr = "";
-
- for (int i=0;i<GetCount();i++)
- {
- gstrListRep += commastr;
- gstrListRep += GetValue(i)->GetText();
- commastr = ",";
- }
- gstrListRep += "]";
-
- return gstrListRep;
-}
-
-
-
-CValue* CListValue::GetReplica()
-{
- CListValue* replica = new CListValue(*this);
-
- replica->ProcessReplica();
-
- replica->m_bReleaseContents=true; // for copy, complete array is copied for now...
- // copy all values
- int numelements = m_pValueArray.size();
- unsigned int i=0;
- replica->m_pValueArray.resize(numelements);
- for (i=0;i<m_pValueArray.size();i++)
- replica->m_pValueArray[i] = m_pValueArray[i]->GetReplica();
-
-
- return replica;
-};
-
-
-
-void CListValue::SetValue(int i, CValue *val)
-{
- assertd(i < m_pValueArray.size());
- m_pValueArray[i]=val;
-}
-
-
-
-void CListValue::Resize(int num)
-{
- m_pValueArray.resize(num);
-}
-
-
-
-void CListValue::Remove(int i)
-{
- assertd(i<m_pValueArray.size());
- m_pValueArray.erase(m_pValueArray.begin()+i);
-}
-
-
-
-void CListValue::ReleaseAndRemoveAll()
-{
- for (unsigned int i=0;i<m_pValueArray.size();i++)
- m_pValueArray[i]->Release();
- m_pValueArray.clear();//.Clear();
-}
-
-
-
-CValue* CListValue::FindValue(const STR_String &name)
-{
- for (int i=0; i < GetCount(); i++)
- if (GetValue(i)->GetName() == name)
- return GetValue(i);
-
- return NULL;
-}
-
-CValue* CListValue::FindValue(const char *name)
-{
- for (int i=0; i < GetCount(); i++)
- if (GetValue(i)->GetName() == name)
- return GetValue(i);
-
- return NULL;
-}
-
-bool CListValue::SearchValue(CValue *val)
-{
- for (int i=0;i<GetCount();i++)
- if (val == GetValue(i))
- return true;
- return false;
-}
-
-
-
-void CListValue::SetReleaseOnDestruct(bool bReleaseContents)
-{
- m_bReleaseContents = bReleaseContents;
-}
-
-
-
-bool CListValue::RemoveValue(CValue *val)
-{
- bool result=false;
-
- for (int i=GetCount()-1;i>=0;i--)
- if (val == GetValue(i))
- {
- Remove(i);
- result=true;
- }
- return result;
-}
-
-
-
-void CListValue::MergeList(CListValue *otherlist)
-{
-
- int numelements = this->GetCount();
- int numotherelements = otherlist->GetCount();
-
-
- Resize(numelements+numotherelements);
-
- for (int i=0;i<numotherelements;i++)
- {
- SetValue(i+numelements,otherlist->GetValue(i)->AddRef());
- }
-}
-
-bool CListValue::CheckEqual(CValue* first,CValue* second)
-{
- bool result = false;
-
- CValue* eqval = ((CValue*)first)->Calc(VALUE_EQL_OPERATOR,(CValue*)second);
-
- if (eqval==NULL)
- return false;
- const STR_String& text = eqval->GetText();
- if (&text==&CBoolValue::sTrueString)
- {
- result = true;
- }
- eqval->Release();
- return result;
-
-}
-
-
-/* ---------------------------------------------------------------------
- * Some stuff taken from the header
- * --------------------------------------------------------------------- */
-CValue* CListValue::Calc(VALUE_OPERATOR op,CValue *val)
-{
- //assert(false); // todo: implement me!
- static int error_printed = 0;
- if (error_printed==0) {
- fprintf(stderr, "CValueList::Calc not yet implemented\n");
- error_printed = 1;
- }
- return NULL;
-}
-
-CValue* CListValue::CalcFinal(VALUE_DATA_TYPE dtype,
- VALUE_OPERATOR op,
- CValue* val)
-{
- //assert(false); // todo: implement me!
- static int error_printed = 0;
- if (error_printed==0) {
- fprintf(stderr, "CValueList::CalcFinal not yet implemented\n");
- error_printed = 1;
- }
- return NULL;
-}
-
-
-
-void CListValue::Add(CValue* value)
-{
- m_pValueArray.push_back(value);
-}
-
-
-
-double CListValue::GetNumber()
-{
- return -1;
-}
-
-
-
-int CListValue::GetValueType()
-{
- return VALUE_LIST_TYPE;
-}
-
-
-
-void CListValue::SetModified(bool bModified)
-{
- CValue::SetModified(bModified);
- int numels = GetCount();
-
- for (int i=0;i<numels;i++)
- GetValue(i)->SetModified(bModified);
-}
-
-
-
-bool CListValue::IsModified()
-{
- bool bmod = CValue::IsModified(); //normal own flag
- int numels = GetCount();
-
- for (int i=0;i<numels;i++)
- bmod = bmod || GetValue(i)->IsModified();
-
- return bmod;
-}
-
-#ifdef WITH_PYTHON
-
-/* --------------------------------------------------------------------- */
-/* Python interface ---------------------------------------------------- */
-/* --------------------------------------------------------------------- */
-
-static Py_ssize_t listvalue_bufferlen(PyObject *self)
-{
- CListValue *list= static_cast<CListValue *>(BGE_PROXY_REF(self));
- if (list==NULL)
- return 0;
-
- return (Py_ssize_t)list->GetCount();
-}
-
-static PyObject *listvalue_buffer_item(PyObject *self, Py_ssize_t index)
-{
- CListValue *list= static_cast<CListValue *>(BGE_PROXY_REF(self));
- CValue *cval;
-
- if (list==NULL) {
- PyErr_SetString(PyExc_SystemError, "val = CList[i], " BGE_PROXY_ERROR_MSG);
- return NULL;
- }
-
- int count = list->GetCount();
-
- if (index < 0)
- index = count+index;
-
- if (index < 0 || index >= count) {
- PyErr_SetString(PyExc_IndexError, "CList[i]: Python ListIndex out of range in CValueList");
- return NULL;
- }
-
- cval= list->GetValue(index);
-
- PyObject *pyobj = cval->ConvertValueToPython();
- if (pyobj)
- return pyobj;
- else
- return cval->GetProxy();
-}
-
-
-/* just slice it into a python list... */
-static PyObject *listvalue_buffer_slice(CListValue *list, Py_ssize_t start, Py_ssize_t stop)
-{
- PyObject *newlist;
- Py_ssize_t i, j;
-
- /* caller needs to validate negative index */
-#if 0
- Py_ssize_t len = list->GetCount();
-
- if (start > len) start = len;
- if (stop > len) stop = len;
-#endif
-
- newlist = PyList_New(stop - start);
- if (!newlist)
- return NULL;
-
- for (i = start, j = 0; i < stop; i++, j++) {
- PyObject *pyobj = list->GetValue(i)->ConvertValueToPython();
- if (!pyobj) {
- pyobj = list->GetValue(i)->GetProxy();
- }
- PyList_SET_ITEM(newlist, j, pyobj);
- }
- return newlist;
-}
-
-
-static PyObject *listvalue_mapping_subscript(PyObject *self, PyObject *key)
-{
- CListValue *list= static_cast<CListValue *>(BGE_PROXY_REF(self));
- if (list==NULL) {
- PyErr_SetString(PyExc_SystemError, "value = CList[i], " BGE_PROXY_ERROR_MSG);
- return NULL;
- }
-
- if (PyUnicode_Check(key)) {
- CValue *item = ((CListValue*) list)->FindValue(_PyUnicode_AsString(key));
- if (item) {
- PyObject *pyobj = item->ConvertValueToPython();
- if (pyobj)
- return pyobj;
- else
- return item->GetProxy();
- }
- }
- else if (PyIndex_Check(key)) {
- Py_ssize_t index = PyLong_AsSsize_t(key);
- return listvalue_buffer_item(self, index); /* wont add a ref */
- }
- else if (PySlice_Check(key)) {
- Py_ssize_t start, stop, step, slicelength;
-
- if (PySlice_GetIndicesEx(key, list->GetCount(), &start, &stop, &step, &slicelength) < 0)
- return NULL;
-
- if (slicelength <= 0) {
- return PyList_New(0);
- }
- else if (step == 1) {
- return listvalue_buffer_slice(list, start, stop);
- }
- else {
- PyErr_SetString(PyExc_TypeError, "CList[slice]: slice steps not supported");
- return NULL;
- }
- }
-
- PyErr_Format(PyExc_KeyError,
- "CList[key]: '%R' key not in list", key);
- return NULL;
-}
-
-/* clist + list, return a list that python owns */
-static PyObject *listvalue_buffer_concat(PyObject *self, PyObject *other)
-{
- CListValue *listval= static_cast<CListValue *>(BGE_PROXY_REF(self));
- Py_ssize_t i, numitems, numitems_orig;
-
- if (listval==NULL) {
- PyErr_SetString(PyExc_SystemError, "CList+other, " BGE_PROXY_ERROR_MSG);
- return NULL;
- }
-
- numitems_orig= listval->GetCount();
-
- // for now, we support CListValue concatenated with items
- // and CListValue concatenated to Python Lists
- // and CListValue concatenated with another CListValue
-
- /* Shallow copy, don't use listval->GetReplica(), it will screw up with KX_GameObjects */
- CListValue* listval_new = new CListValue();
-
- if (PyList_Check(other))
- {
- CValue* listitemval;
- bool error = false;
-
- numitems = PyList_GET_SIZE(other);
-
- /* copy the first part of the list */
- listval_new->Resize(numitems_orig + numitems);
- for (i=0;i<numitems_orig;i++)
- listval_new->SetValue(i, listval->GetValue(i)->AddRef());
-
- for (i=0;i<numitems;i++)
- {
- listitemval = listval->ConvertPythonToValue(PyList_GET_ITEM(other, i), true, "cList + pyList: CListValue, ");
-
- if (listitemval) {
- listval_new->SetValue(i+numitems_orig, listitemval);
- } else {
- error= true;
- break;
- }
- }
-
- if (error) {
- listval_new->Resize(numitems_orig+i); /* resize so we don't try release NULL pointers */
- listval_new->Release();
- return NULL; /* ConvertPythonToValue above sets the error */
- }
-
- }
- else if (PyObject_TypeCheck(other, &CListValue::Type)) {
- // add items from otherlist to this list
- CListValue* otherval = static_cast<CListValue *>(BGE_PROXY_REF(other));
- if (otherval==NULL) {
- listval_new->Release();
- PyErr_SetString(PyExc_SystemError, "CList+other, " BGE_PROXY_ERROR_MSG);
- return NULL;
- }
-
- numitems = otherval->GetCount();
-
- /* copy the first part of the list */
- listval_new->Resize(numitems_orig + numitems); /* resize so we don't try release NULL pointers */
- for (i=0;i<numitems_orig;i++)
- listval_new->SetValue(i, listval->GetValue(i)->AddRef());
-
- /* now copy the other part of the list */
- for (i=0;i<numitems;i++)
- listval_new->SetValue(i+numitems_orig, otherval->GetValue(i)->AddRef());
-
- }
- return listval_new->NewProxy(true); /* python owns this list */
-}
-
-static int listvalue_buffer_contains(PyObject *self_v, PyObject *value)
-{
- CListValue *self = static_cast<CListValue *>(BGE_PROXY_REF(self_v));
-
- if (self == NULL) {
- PyErr_SetString(PyExc_SystemError, "val in CList, " BGE_PROXY_ERROR_MSG);
- return -1;
- }
-
- if (PyUnicode_Check(value)) {
- if (self->FindValue((const char *)_PyUnicode_AsString(value))) {
- return 1;
- }
- }
- else if (PyObject_TypeCheck(value, &CValue::Type)) { /* not dict like at all but this worked before __contains__ was used */
- CValue *item= static_cast<CValue *>(BGE_PROXY_REF(value));
- for (int i=0; i < self->GetCount(); i++)
- if (self->GetValue(i) == item) // Com
- return 1;
-
- } // not using CheckEqual
-
- return 0;
-}
-
-
-static PySequenceMethods listvalue_as_sequence = {
- listvalue_bufferlen,//(inquiry)buffer_length, /*sq_length*/
- listvalue_buffer_concat, /*sq_concat*/
- NULL, /*sq_repeat*/
- listvalue_buffer_item, /*sq_item*/
-// TODO, slicing in py3
- NULL, // listvalue_buffer_slice, /*sq_slice*/
- NULL, /*sq_ass_item*/
- NULL, /*sq_ass_slice*/
- (objobjproc)listvalue_buffer_contains, /* sq_contains */
- (binaryfunc) NULL, /* sq_inplace_concat */
- (ssizeargfunc) NULL, /* sq_inplace_repeat */
-};
-
-
-
-/* Is this one used ? */
-static PyMappingMethods instance_as_mapping = {
- listvalue_bufferlen, /*mp_length*/
- listvalue_mapping_subscript, /*mp_subscript*/
- NULL /*mp_ass_subscript*/
-};
-
-
-
-PyTypeObject CListValue::Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "CListValue", /*tp_name*/
- sizeof(PyObjectPlus_Proxy), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- py_base_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- 0, /*tp_getattr*/
- 0, /*tp_setattr*/
- 0, /*tp_compare*/
- py_base_repr, /*tp_repr*/
- 0, /*tp_as_number*/
- &listvalue_as_sequence, /*tp_as_sequence*/
- &instance_as_mapping, /*tp_as_mapping*/
- 0, /*tp_hash*/
- 0, /*tp_call */
- 0,
- NULL,
- NULL,
- 0,
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
- 0,0,0,0,0,0,0,
- Methods,
- 0,
- 0,
- &CValue::Type,
- 0,0,0,0,0,0,
- py_base_new
-};
-
-PyMethodDef CListValue::Methods[] = {
- /* List style access */
- {"append", (PyCFunction)CListValue::sPyappend,METH_O},
- {"reverse", (PyCFunction)CListValue::sPyreverse,METH_NOARGS},
- {"index", (PyCFunction)CListValue::sPyindex,METH_O},
- {"count", (PyCFunction)CListValue::sPycount,METH_O},
-
- /* Dict style access */
- {"get", (PyCFunction)CListValue::sPyget,METH_VARARGS},
-
- /* Own cvalue funcs */
- {"from_id", (PyCFunction)CListValue::sPyfrom_id,METH_O},
-
- {NULL,NULL} //Sentinel
-};
-
-PyAttributeDef CListValue::Attributes[] = {
- { NULL } //Sentinel
-};
-
-PyObject *CListValue::Pyappend(PyObject *value)
-{
- CValue *objval = ConvertPythonToValue(value, true, "CList.append(i): CValueList, ");
-
- if (!objval) /* ConvertPythonToValue sets the error */
- return NULL;
-
- if (!BGE_PROXY_PYOWNS(m_proxy)) {
- PyErr_SetString(PyExc_TypeError,
- "CList.append(i): internal values can't be modified");
- return NULL;
- }
-
- Add(objval);
-
- Py_RETURN_NONE;
-}
-
-PyObject *CListValue::Pyreverse()
-{
- if (!BGE_PROXY_PYOWNS(m_proxy)) {
- PyErr_SetString(PyExc_TypeError,
- "CList.reverse(): internal values can't be modified");
- return NULL;
- }
-
- std::reverse(m_pValueArray.begin(),m_pValueArray.end());
- Py_RETURN_NONE;
-}
-
-PyObject *CListValue::Pyindex(PyObject *value)
-{
- PyObject *result = NULL;
-
- CValue *checkobj = ConvertPythonToValue(value, true, "val = cList[i]: CValueList, ");
- if (checkobj==NULL)
- return NULL; /* ConvertPythonToValue sets the error */
-
- int numelem = GetCount();
- for (int i=0;i<numelem;i++)
- {
- CValue* elem = GetValue(i);
- if (checkobj==elem || CheckEqual(checkobj,elem))
- {
- result = PyLong_FromLong(i);
- break;
- }
- }
- checkobj->Release();
-
- if (result==NULL) {
- PyErr_SetString(PyExc_ValueError, "CList.index(x): x not in CListValue");
- }
- return result;
-
-}
-
-
-
-PyObject *CListValue::Pycount(PyObject *value)
-{
- int numfound = 0;
-
- CValue *checkobj = ConvertPythonToValue(value, false, ""); /* error ignored */
-
- if (checkobj==NULL) { /* in this case just return that there are no items in the list */
- PyErr_Clear();
- return PyLong_FromLong(0);
- }
-
- int numelem = GetCount();
- for (int i=0;i<numelem;i++)
- {
- CValue* elem = GetValue(i);
- if (checkobj==elem || CheckEqual(checkobj,elem))
- {
- numfound ++;
- }
- }
- checkobj->Release();
-
- return PyLong_FromLong(numfound);
-}
-
-/* Matches python dict.get(key, [default]) */
-PyObject *CListValue::Pyget(PyObject *args)
-{
- char *key;
- PyObject *def = Py_None;
-
- if (!PyArg_ParseTuple(args, "s|O:get", &key, &def))
- return NULL;
-
- CValue *item = FindValue((const char *)key);
- if (item) {
- PyObject *pyobj = item->ConvertValueToPython();
- if (pyobj)
- return pyobj;
- else
- return item->GetProxy();
- }
- Py_INCREF(def);
- return def;
-}
-
-
-PyObject *CListValue::Pyfrom_id(PyObject *value)
-{
- uintptr_t id= (uintptr_t)PyLong_AsVoidPtr(value);
-
- if (PyErr_Occurred())
- return NULL;
-
- int numelem = GetCount();
- for (int i=0;i<numelem;i++)
- {
- if (reinterpret_cast<uintptr_t>(m_pValueArray[i]->m_proxy) == id)
- return GetValue(i)->GetProxy();
- }
- PyErr_SetString(PyExc_IndexError, "from_id(#): id not found in CValueList");
- return NULL;
-
-}
-
-#endif // WITH_PYTHON
diff --git a/source/gameengine/Expressions/intern/ListWrapper.cpp b/source/gameengine/Expressions/intern/ListWrapper.cpp
deleted file mode 100644
index db1518a4388..00000000000
--- a/source/gameengine/Expressions/intern/ListWrapper.cpp
+++ /dev/null
@@ -1,424 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * Contributor(s): Porteries Tristan.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file ListWrapper.cpp
- * \ingroup expressions
- */
-
-#ifdef WITH_PYTHON
-
-#include "EXP_ListWrapper.h"
-
-static STR_String pythonGeneratorList = "ListWrapper";
-
-CListWrapper::CListWrapper(void *client,
- PyObject *base,
- bool (*checkValid)(void *),
- int (*getSize)(void *),
- PyObject *(*getItem)(void *, int),
- const char *(*getItemName)(void *, int),
- bool (*setItem)(void *, int, PyObject *))
-:m_client(client),
-m_base(base),
-m_checkValid(checkValid),
-m_getSize(getSize),
-m_getItem(getItem),
-m_getItemName(getItemName),
-m_setItem(setItem)
-{
- // Incref to always have a existing pointer.
- Py_INCREF(m_base);
-}
-
-CListWrapper::~CListWrapper()
-{
- Py_DECREF(m_base);
-}
-
-bool CListWrapper::CheckValid()
-{
- if (m_base && !BGE_PROXY_REF(m_base)) {
- return false;
- }
- return m_checkValid ? (*m_checkValid)(m_client) : true;
-}
-
-int CListWrapper::GetSize()
-{
- return (*m_getSize)(m_client);
-}
-
-PyObject *CListWrapper::GetItem(int index)
-{
- return (*m_getItem)(m_client, index);
-}
-
-const char *CListWrapper::GetItemName(int index)
-{
- return (*m_getItemName)(m_client, index);
-}
-
-bool CListWrapper::SetItem(int index, PyObject *item)
-{
- return (*m_setItem)(m_client, index, item);
-}
-
-bool CListWrapper::AllowSetItem()
-{
- return m_setItem != NULL;
-}
-
-bool CListWrapper::AllowGetItemByName()
-{
- return m_getItemName != NULL;
-}
-
-// ================================================================
-
-const STR_String &CListWrapper::GetText()
-{
- return pythonGeneratorList;
-}
-
-void CListWrapper::SetName(const char *name)
-{
-}
-
-STR_String &CListWrapper::GetName()
-{
- return pythonGeneratorList;
-}
-
-CValue *CListWrapper::GetReplica()
-{
- return NULL;
-}
-
-CValue *CListWrapper::Calc(VALUE_OPERATOR op, CValue *val)
-{
- return NULL;
-}
-
-CValue *CListWrapper::CalcFinal(VALUE_DATA_TYPE dtype, VALUE_OPERATOR op, CValue *val)
-{
- return NULL;
-}
-
-double CListWrapper::GetNumber()
-{
- return -1;
-}
-
-int CListWrapper::GetValueType()
-{
- return -1;
-}
-
-// We convert all elements to python objects to make a proper repr string.
-PyObject *CListWrapper::py_repr()
-{
- if (!CheckValid()) {
- PyErr_SetString(PyExc_SystemError, "CListWrapper : repr, " BGE_PROXY_ERROR_MSG);
- return NULL;
- }
-
- PyObject *py_proxy = GetProxy();
- PyObject *py_list = PySequence_List(py_proxy);
- PyObject *py_string = PyObject_Repr(py_list);
- Py_DECREF(py_list);
- Py_DECREF(py_proxy);
- return py_string;
-}
-
-
-Py_ssize_t CListWrapper::py_len(PyObject *self)
-{
- CListWrapper *list = (CListWrapper *)BGE_PROXY_REF(self);
- // Invalid list.
- if (!list->CheckValid()) {
- PyErr_SetString(PyExc_SystemError, "len(CListWrapper), " BGE_PROXY_ERROR_MSG);
- return 0;
- }
-
- return (Py_ssize_t)list->GetSize();
-}
-
-PyObject *CListWrapper::py_get_item(PyObject *self, Py_ssize_t index)
-{
- CListWrapper *list = (CListWrapper *)BGE_PROXY_REF(self);
- // Invalid list.
- if (!list->CheckValid()) {
- PyErr_SetString(PyExc_SystemError, "val = CListWrapper[i], " BGE_PROXY_ERROR_MSG);
- return NULL;
- }
-
- int size = list->GetSize();
-
- if (index < 0) {
- index = size + index;
- }
- if (index < 0 || index >= size) {
- PyErr_SetString(PyExc_IndexError, "CListWrapper[i]: List index out of range in CListWrapper");
- return NULL;
- }
-
- PyObject *pyobj = list->GetItem(index);
-
- return pyobj;
-}
-
-int CListWrapper::py_set_item(PyObject *self, Py_ssize_t index, PyObject *value)
-{
- CListWrapper *list = (CListWrapper *)BGE_PROXY_REF(self);
- // Invalid list.
- if (!list->CheckValid()) {
- PyErr_SetString(PyExc_SystemError, "CListWrapper[i] = val, " BGE_PROXY_ERROR_MSG);
- return -1;
- }
-
- if (!list->AllowSetItem()) {
- PyErr_SetString(PyExc_TypeError, "CListWrapper's item type doesn't support assignment");
- return -1;
- }
-
- if (!value) {
- PyErr_SetString(PyExc_TypeError, "CListWrapper doesn't support item deletion");
- return -1;
- }
-
- int size = list->GetSize();
-
- if (index < 0) {
- index = size + index;
- }
- if (index < 0 || index >= size) {
- PyErr_SetString(PyExc_IndexError, "CListWrapper[i]: List index out of range in CListWrapper");
- return -1;
- }
-
- if (!list->SetItem(index, value)) {
- return -1;
- }
- return 0;
-}
-
-PyObject *CListWrapper::py_mapping_subscript(PyObject *self, PyObject *key)
-{
- CListWrapper *list = (CListWrapper *)BGE_PROXY_REF(self);
- // Invalid list.
- if (!list->CheckValid()) {
- PyErr_SetString(PyExc_SystemError, "val = CListWrapper[key], " BGE_PROXY_ERROR_MSG);
- return NULL;
- }
-
- if (PyIndex_Check(key)) {
- Py_ssize_t index = PyLong_AsSsize_t(key);
- return py_get_item(self, index);
- }
- else if (PyUnicode_Check(key)) {
- if (!list->AllowGetItemByName()) {
- PyErr_SetString(PyExc_SystemError, "CListWrapper's item type doesn't support access by key");
- return NULL;
- }
-
- const char *name = _PyUnicode_AsString(key);
- int size = list->GetSize();
-
- for (unsigned int i = 0; i < size; ++i) {
- if (strcmp(list->GetItemName(i), name) == 0) {
- return list->GetItem(i);
- }
- }
-
- PyErr_Format(PyExc_KeyError, "requested item \"%s\" does not exist", name);
- return NULL;
- }
-
- PyErr_Format(PyExc_KeyError, "CListWrapper[key]: '%R' key not in list", key);
- return NULL;
-}
-
-int CListWrapper::py_mapping_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
-{
- CListWrapper *list = (CListWrapper *)BGE_PROXY_REF(self);
- // Invalid list.
- if (!list->CheckValid()) {
- PyErr_SetString(PyExc_SystemError, "val = CListWrapper[key], " BGE_PROXY_ERROR_MSG);
- return -1;
- }
-
- if (!list->AllowSetItem()) {
- PyErr_SetString(PyExc_TypeError, "CListWrapper's item type doesn't support assignment");
- return -1;
- }
-
- if (PyIndex_Check(key)) {
- Py_ssize_t index = PyLong_AsSsize_t(key);
- return py_set_item(self, index, value);
- }
- else if (PyUnicode_Check(key)) {
- if (!list->AllowGetItemByName()) {
- PyErr_SetString(PyExc_SystemError, "CListWrapper's item type doesn't support access by key");
- return -1;
- }
-
- const char *name = _PyUnicode_AsString(key);
- int size = list->GetSize();
-
- for (unsigned int i = 0; i < size; ++i) {
- if (strcmp(list->GetItemName(i), name) == 0) {
- if (!list->SetItem(i, value)) {
- return -1;
- }
- return 0;
- }
- }
-
- PyErr_Format(PyExc_KeyError, "requested item \"%s\" does not exist", name);
- return -1;
- }
-
- PyErr_Format(PyExc_KeyError, "CListWrapper[key]: '%R' key not in list", key);
- return -1;
-}
-
-int CListWrapper::py_contains(PyObject *self, PyObject *key)
-{
- CListWrapper *list = (CListWrapper *)BGE_PROXY_REF(self);
- // Invalid list.
- if (!list->CheckValid()) {
- PyErr_SetString(PyExc_SystemError, "val = CListWrapper[i], " BGE_PROXY_ERROR_MSG);
- return -1;
- }
-
- if (!list->AllowGetItemByName()) {
- PyErr_SetString(PyExc_SystemError, "CListWrapper's item type doesn't support access by key");
- return -1;
- }
-
- if (!PyUnicode_Check(key)) {
- PyErr_SetString(PyExc_SystemError, "key in list, CListWrapper: key must be a string");
- return -1;
- }
-
- const char *name = _PyUnicode_AsString(key);
- int size = list->GetSize();
-
- for (unsigned int i = 0; i < size; ++i) {
- if (strcmp(list->GetItemName(i), name) == 0) {
- return 1;
- }
- }
-
- return 0;
-}
-
-PySequenceMethods CListWrapper::py_as_sequence = {
- py_len, // sq_length
- NULL, // sq_concat
- NULL, // sq_repeat
- py_get_item, // sq_item
- NULL, // sq_slice
- py_set_item, // sq_ass_item
- NULL, // sq_ass_slice
- (objobjproc)py_contains, // sq_contains
- (binaryfunc) NULL, // sq_inplace_concat
- (ssizeargfunc) NULL, // sq_inplace_repeat
-};
-
-PyMappingMethods CListWrapper::py_as_mapping = {
- py_len, // mp_length
- py_mapping_subscript, // mp_subscript
- py_mapping_ass_subscript // mp_ass_subscript
-};
-
-PyTypeObject CListWrapper::Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "CListWrapper", // tp_name
- sizeof(PyObjectPlus_Proxy), // tp_basicsize
- 0, // tp_itemsize
- py_base_dealloc, // tp_dealloc
- 0, // tp_print
- 0, // tp_getattr
- 0, // tp_setattr
- 0, // tp_compare
- py_base_repr, // tp_repr
- 0, // tp_as_number
- &py_as_sequence, // tp_as_sequence
- &py_as_mapping, // tp_as_mapping
- 0, // tp_hash
- 0, // tp_call
- 0,
- NULL,
- NULL,
- 0,
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
- 0,0,0,0,0,0,0,
- Methods,
- 0,
- 0,
- &CValue::Type,
- 0,0,0,0,0,0,
- py_base_new
-};
-
-PyMethodDef CListWrapper::Methods[] = {
- {"get", (PyCFunction)CListWrapper::sPyGet, METH_VARARGS},
- {NULL, NULL} //Sentinel
-};
-
-PyAttributeDef CListWrapper::Attributes[] = {
- {NULL} //Sentinel
-};
-
-/* Matches python dict.get(key, [default]) */
-PyObject *CListWrapper::PyGet(PyObject *args)
-{
- char *name;
- PyObject *def = Py_None;
-
- // Invalid list.
- if (!CheckValid()) {
- PyErr_SetString(PyExc_SystemError, "val = CListWrapper[i], " BGE_PROXY_ERROR_MSG);
- return NULL;
- }
-
- if (!AllowGetItemByName()) {
- PyErr_SetString(PyExc_SystemError, "CListWrapper's item type doesn't support access by key");
- return NULL;
- }
-
- if (!PyArg_ParseTuple(args, "s|O:get", &name, &def)) {
- return NULL;
- }
-
- for (unsigned int i = 0; i < GetSize(); ++i) {
- if (strcmp(GetItemName(i), name) == 0) {
- return GetItem(i);
- }
- }
-
- Py_INCREF(def);
- return def;
-}
-
-#endif // WITH_PYTHON
diff --git a/source/gameengine/Expressions/intern/Operator1Expr.cpp b/source/gameengine/Expressions/intern/Operator1Expr.cpp
deleted file mode 100644
index add0376f487..00000000000
--- a/source/gameengine/Expressions/intern/Operator1Expr.cpp
+++ /dev/null
@@ -1,151 +0,0 @@
-/** \file gameengine/Expressions/Operator1Expr.cpp
- * \ingroup expressions
- */
-// Operator1Expr.cpp: implementation of the COperator1Expr class.
-/*
- * Copyright (c) 1996-2000 Erwin Coumans <coockie@acm.org>
- *
- * Permission to use, copy, modify, distribute and sell this software
- * and its documentation for any purpose is hereby granted without fee,
- * provided that the above copyright notice appear in all copies and
- * that both that copyright notice and this permission notice appear
- * in supporting documentation. Erwin Coumans makes no
- * representations about the suitability of this software for any
- * purpose. It is provided "as is" without express or implied warranty.
- *
- */
-
-#include "EXP_Operator1Expr.h"
-#include "EXP_EmptyValue.h"
-
-//////////////////////////////////////////////////////////////////////
-// Construction/Destruction
-//////////////////////////////////////////////////////////////////////
-
-COperator1Expr::COperator1Expr()
-/*
-pre:
-effect: constucts an empty COperator1Expr
-*/
-{
- m_lhs = NULL;
-}
-
-COperator1Expr::COperator1Expr(VALUE_OPERATOR op, CExpression *lhs)
-/*
-pre:
-effect: constucts a COperator1Expr with op and lhs in it
-*/
-{
- m_lhs = lhs;
- m_op = op;
-}
-
-COperator1Expr::~COperator1Expr()
-/*
-pre:
-effect: deletes the object
-*/
-{
- if (m_lhs) m_lhs->Release();
-}
-
-CValue * COperator1Expr::Calculate()
-/*
-pre:
-ret: a new object containing the result of applying the operator m_op to the
- value of m_lhs
-*/
-{
- CValue *ret;
- CValue *temp = m_lhs->Calculate();
- CValue* empty = new CEmptyValue();
- ret = empty->Calc(m_op, temp);
- empty->Release();
- temp->Release();
-
- return ret;
-}
-
-/*
-bool COperator1Expr::IsInside(float x, float y, float z,bool bBorderInclude)
-{
-
- bool result = true;
- switch (m_op)
- {
-
- case VALUE_ADD_OPERATOR:
- {
-
- if (m_lhs)
- {
- result = result || m_lhs->IsInside(x,y,z,bBorderInclude);
- }
- break;
- }
- case VALUE_SUB_OPERATOR:
- {
- result = true;
- if (m_lhs)
- {
- result = result && (!m_lhs->IsInside(x,y,z,bBorderInclude));
- }
- break;
- }
- }
- return result;
-}
-
-*/
-bool COperator1Expr::NeedsRecalculated()
-{
- return m_lhs->NeedsRecalculated();
-}
-
-CExpression* COperator1Expr::CheckLink(std::vector<CBrokenLinkInfo*>& brokenlinks)
-{
-
- CExpression* newlhs = m_lhs->CheckLink(brokenlinks);
-
- if (newlhs)
- {
- if (newlhs==m_lhs) {
- // not changed
- } else {
- // changed
- //numchanges++;
- newlhs->AddRef();
-
- //m_lhs->Release();
- brokenlinks.push_back(new CBrokenLinkInfo(&m_lhs,m_lhs));
-
- m_lhs = newlhs;
- }
- return this;
- } else {
- //numchanges++;
- AddRef();
-
- return Release();
- }
-
-}
-
-void COperator1Expr::BroadcastOperators(VALUE_OPERATOR op)
-{
- if (m_lhs)
- m_lhs->BroadcastOperators(m_op);
-}
-
-
-
-
-bool COperator1Expr::MergeExpression(CExpression *otherexpr)
-{
- if (m_lhs)
- return m_lhs->MergeExpression(otherexpr);
-
- assertd(false); // should not get here, expression is not compatible for merge
- return false;
-}
diff --git a/source/gameengine/Expressions/intern/Operator2Expr.cpp b/source/gameengine/Expressions/intern/Operator2Expr.cpp
deleted file mode 100644
index 0a7f30b8cc8..00000000000
--- a/source/gameengine/Expressions/intern/Operator2Expr.cpp
+++ /dev/null
@@ -1,276 +0,0 @@
-/** \file gameengine/Expressions/Operator2Expr.cpp
- * \ingroup expressions
- */
-// Operator2Expr.cpp: implementation of the COperator2Expr class.
-/*
- * Copyright (c) 1996-2000 Erwin Coumans <coockie@acm.org>
- *
- * Permission to use, copy, modify, distribute and sell this software
- * and its documentation for any purpose is hereby granted without fee,
- * provided that the above copyright notice appear in all copies and
- * that both that copyright notice and this permission notice appear
- * in supporting documentation. Erwin Coumans makes no
- * representations about the suitability of this software for any
- * purpose. It is provided "as is" without express or implied warranty.
- *
- */
-// 31 dec 1998 - big update: try to use the cached data for updating, instead of
-// rebuilding completely it from left and right node. Modified flags and bounding boxes
-// have to do the trick
-// when expression is cached, there will be a call to UpdateCalc() instead of Calc()
-
-#include "EXP_Operator2Expr.h"
-#include "EXP_StringValue.h"
-#include "EXP_VoidValue.h"
-
-//////////////////////////////////////////////////////////////////////
-// Construction/Destruction
-//////////////////////////////////////////////////////////////////////
-
-COperator2Expr::COperator2Expr(VALUE_OPERATOR op, CExpression *lhs, CExpression *rhs)
-:
-m_rhs(rhs),
-m_lhs(lhs),
-m_cached_calculate(NULL),
-m_op(op)
-/*
-pre:
-effect: constucts a COperator2Expr with op, lhs and rhs in it
-*/
-{
-
-}
-
-COperator2Expr::COperator2Expr():
-m_rhs(NULL),
-m_lhs(NULL),
-m_cached_calculate(NULL)
-
-/*
-pre:
-effect: constucts an empty COperator2Expr
-*/
-{
-
-}
-
-COperator2Expr::~COperator2Expr()
-/*
-pre:
-effect: deletes the object
-*/
-{
- if (m_lhs)
- m_lhs->Release();
- if (m_rhs)
- m_rhs->Release();
- if (m_cached_calculate)
- m_cached_calculate->Release();
-
-}
-CValue* COperator2Expr::Calculate()
-/*
-pre:
-ret: a new object containing the result of applying operator m_op to m_lhs
-and m_rhs
-*/
-{
-
- bool leftmodified,rightmodified;
- leftmodified = m_lhs->NeedsRecalculated();
- rightmodified = m_rhs->NeedsRecalculated();
-
- // if no modifications on both left and right subtree, and result is already calculated
- // then just return cached result...
- if (!leftmodified && !rightmodified && (m_cached_calculate))
- {
- // not modified, just return m_cached_calculate
- } else {
- // if not yet calculated, or modified...
-
-
- if (m_cached_calculate) {
- m_cached_calculate->Release();
- m_cached_calculate=NULL;
- }
-
- CValue* ffleft = m_lhs->Calculate();
- CValue* ffright = m_rhs->Calculate();
-
- ffleft->SetOwnerExpression(this);//->m_pOwnerExpression=this;
- ffright->SetOwnerExpression(this);//->m_pOwnerExpression=this;
-
- m_cached_calculate = ffleft->Calc(m_op,ffright);
-
- //if (m_cached_calculate)
- // m_cached_calculate->Action(CValue::SETOWNEREXPR,&CVoidValue(this,false,CValue::STACKVALUE));
-
- ffleft->Release();
- ffright->Release();
- }
-
- return m_cached_calculate->AddRef();
-
-}
-
-#if 0
-bool COperator2Expr::IsInside(float x, float y, float z,bool bBorderInclude)
-{
- bool inside;
- inside = false;
-
- switch (m_op) {
- case VALUE_ADD_OPERATOR:
- {
- // inside = first || second; // optimized with early out if first is inside
- // todo: calculate smallest leaf first ! is much faster...
-
- bool second;//first ;//,second;
-
- //first = m_lhs->IsInside(x,y,z);
- second = m_rhs->IsInside(x,y,z,bBorderInclude);
- if (second)
- return true; //early out
-
- // second = m_rhs->IsInside(x,y,z);
-
- return m_lhs->IsInside(x,y,z,bBorderInclude);
-
- break;
- }
-
- case VALUE_SUB_OPERATOR:
- {
- //inside = first && !second; // optimized with early out
- // todo: same as with add_operator: calc smallest leaf first
-
- bool second;//first ;//,second;
- //first = m_lhs->IsInside(x,y,z);
- second = m_rhs->IsInside(x,y,z,bBorderInclude);
- if (second)
- return false;
-
- // second space get subtracted -> negate!
- //second = m_rhs->IsInside(x,y,z);
-
- return (m_lhs->IsInside(x,y,z,bBorderInclude));
-
-
- break;
- }
- default:
- {
- assert(false);
- // not yet implemented, only add or sub csg operations
- }
- }
-
- return inside;
-}
-
-bool COperator2Expr::IsRightInside(float x, float y, float z,bool bBorderInclude)
-{
- return m_rhs->IsInside(x,y,z,bBorderInclude);
-}
-
-bool COperator2Expr::IsLeftInside(float x, float y, float z,bool bBorderInclude)
-{
- return m_lhs->IsInside(x,y,z,bBorderInclude);
-}
-#endif
-
-bool COperator2Expr::NeedsRecalculated()
-{
- // added some lines, just for debugging purposes, it could be a one-liner :)
- //bool modleft
- //bool modright;
- assertd(m_lhs);
- assertd(m_rhs);
-
- //modright = m_rhs->NeedsRecalculated();
- if (m_rhs->NeedsRecalculated()) // early out
- return true;
- return m_lhs->NeedsRecalculated();
- //modleft = m_lhs->NeedsRecalculated();
- //return (modleft || modright);
-
-}
-
-
-
-CExpression* COperator2Expr::CheckLink(std::vector<CBrokenLinkInfo*>& brokenlinks)
-{
-// if both children are 'dead', return NULL
-// if only one child is alive, return that child
-// if both childresn are alive, return this
-
-
-// bool leftalive = true,rightalive=true;
- /* Does this mean the function will always bomb? */
- assertd(false);
- assert(m_lhs);
- assert(m_rhs);
-/*
- if (m_cached_calculate)
- m_cached_calculate->Action(CValue::REFRESH_CACHE);
-
- CExpression* newlhs = m_lhs->CheckLink(brokenlinks);
- CExpression* newrhs = m_rhs->CheckLink(brokenlinks);
-
- if (m_lhs != newlhs)
- {
- brokenlinks.push_back(new CBrokenLinkInfo(&m_lhs,m_lhs));
- }
-
- if (m_rhs != newrhs)
- {
- brokenlinks.push_back(new CBrokenLinkInfo(&m_rhs,m_rhs));
- }
-
-
-
- m_lhs = newlhs;
- m_rhs = newrhs;
-
- if (m_lhs && m_rhs) {
- return this;
- }
-
- AddRef();
- if (m_lhs)
- return Release(m_lhs->AddRef());
-
- if (m_rhs)
- return Release(m_rhs->AddRef());
-/
-
- */
- return Release();
-}
-
-
-bool COperator2Expr::MergeExpression(CExpression *otherexpr)
-{
- if (m_lhs)
- {
- if (m_lhs->GetExpressionID() == CExpression::CCONSTEXPRESSIONID)
- {
- // cross fingers ;) replace constexpr by new tree...
- m_lhs->Release();
- m_lhs = otherexpr->AddRef();
- return true;
- }
- }
-
- assertd(false);
- return false;
-}
-
-
-void COperator2Expr::BroadcastOperators(VALUE_OPERATOR op)
-{
- if (m_lhs)
- m_lhs->BroadcastOperators(m_op);
- if (m_rhs)
- m_rhs->BroadcastOperators(m_op);
-}
diff --git a/source/gameengine/Expressions/intern/PyObjectPlus.cpp b/source/gameengine/Expressions/intern/PyObjectPlus.cpp
deleted file mode 100644
index 1e4a59aeb5c..00000000000
--- a/source/gameengine/Expressions/intern/PyObjectPlus.cpp
+++ /dev/null
@@ -1,1226 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Expressions/PyObjectPlus.cpp
- * \ingroup expressions
- */
-
-
-/*------------------------------
- * PyObjectPlus cpp
- *
- * C++ library routines for Crawl 3.2
- *
- * Derived from work by
- * David Redish
- * graduate student
- * Computer Science Department
- * Carnegie Mellon University (CMU)
- * Center for the Neural Basis of Cognition (CNBC)
- * http://www.python.org/doc/PyCPP.html
- *
- * ----------------------------- */
-#include <stdlib.h>
-#include <stddef.h>
-
-#include "EXP_PyObjectPlus.h"
-#include "STR_String.h"
-#include "MT_Vector3.h"
-#include "MEM_guardedalloc.h"
-
-PyObjectPlus::~PyObjectPlus()
-{
-#ifdef WITH_PYTHON
- if (m_proxy) {
- BGE_PROXY_REF(m_proxy)= NULL;
- Py_DECREF(m_proxy); /* Remove own reference, python may still have 1 */
- }
-// assert(ob_refcnt==0);
-#endif
-}
-
-PyObjectPlus::PyObjectPlus() : SG_QList() // constructor
-{
-#ifdef WITH_PYTHON
- m_proxy= NULL;
-#endif
-};
-
-void PyObjectPlus::ProcessReplica()
-{
-#ifdef WITH_PYTHON
- /* Clear the proxy, will be created again if needed with GetProxy()
- * otherwise the PyObject will point to the wrong reference */
- m_proxy= NULL;
-#endif
-}
-
-/* Sometimes we might want to manually invalidate a BGE type even if
- * it hasn't been released by the BGE, say for example when an object
- * is removed from a scene, accessing it may cause problems.
- *
- * In this case the current proxy is made invalid, disowned,
- * and will raise an error on access. However if python can get access
- * to this class again it will make a new proxy and work as expected.
- */
-void PyObjectPlus::InvalidateProxy() // check typename of each parent
-{
-#ifdef WITH_PYTHON
- if (m_proxy) {
- BGE_PROXY_REF(m_proxy)=NULL;
- Py_DECREF(m_proxy);
- m_proxy= NULL;
- }
-#endif
-}
-
-
-#ifdef WITH_PYTHON
-
-/*------------------------------
- * PyObjectPlus Type -- Every class, even the abstract one should have a Type
- * ----------------------------- */
-
-
-PyTypeObject PyObjectPlus::Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "PyObjectPlus", /*tp_name*/
- sizeof(PyObjectPlus_Proxy), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- py_base_dealloc, /* tp_dealloc */
- 0, /* printfunc tp_print; */
- 0, /* getattrfunc tp_getattr; */
- 0, /* setattrfunc tp_setattr; */
- 0, /* tp_compare */ /* DEPRECATED in python 3.0! */
- py_base_repr, /* tp_repr */
- 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Method suites for standard classes */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* long tp_flags; */
- 0, 0, 0, 0,
- /* weak reference enabler */
-#ifdef USE_WEAKREFS
- offsetof(PyObjectPlus_Proxy, in_weakreflist), /* long tp_weaklistoffset; */
-#else
- 0,
-#endif
- 0, 0,
- Methods,
- 0,
- 0,
- NULL // no subtype
-};
-
-PyObject *PyObjectPlus::py_base_repr(PyObject *self) // This should be the entry in Type.
-{
- PyObjectPlus *self_plus= BGE_PROXY_REF(self);
- if (self_plus==NULL) {
- PyErr_SetString(PyExc_SystemError, BGE_PROXY_ERROR_MSG);
- return NULL;
- }
- return self_plus->py_repr();
-}
-
-
-PyObject *PyObjectPlus::py_base_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
-{
- PyTypeObject *base_type;
-
- /* one or more args is needed */
- if (!PyTuple_GET_SIZE(args)) {
- PyErr_SetString(PyExc_TypeError,
- "Expected at least one argument");
- return NULL;
- }
-
- PyObjectPlus_Proxy *base = (PyObjectPlus_Proxy *)PyTuple_GET_ITEM(args, 0);
-
- /**
- * the 'base' PyObject may be subclassed (multiple times even)
- * we need to find the first C++ defined class to check 'type'
- * is a subclass of the base arguments type.
- *
- * This way we can share one tp_new function for every PyObjectPlus
- *
- * eg.
- *
- * # CustomOb is called 'type' in this C code
- * \code{.py}
- * class CustomOb(GameTypes.KX_GameObject):
- * pass
- *
- * # this calls py_base_new(...), the type of 'CustomOb' is checked to be a subclass of the 'cont.owner' type
- * ob = CustomOb(cont.owner)
- * \endcode
- * */
- base_type= Py_TYPE(base);
- while (base_type && !BGE_PROXY_CHECK_TYPE(base_type))
- base_type= base_type->tp_base;
-
- if (base_type==NULL || !BGE_PROXY_CHECK_TYPE(base_type)) {
- PyErr_SetString(PyExc_TypeError, "can't subclass from a blender game type because the argument given is not a game class or subclass");
- return NULL;
- }
-
- /* use base_type rather than Py_TYPE(base) because we could already be subtyped */
- if (!PyType_IsSubtype(type, base_type)) {
- PyErr_Format(PyExc_TypeError, "can't subclass blender game type <%s> from <%s> because it is not a subclass", base_type->tp_name, type->tp_name);
- return NULL;
- }
-
- /* invalidate the existing base and return a new subclassed one,
- * this is a bit dodgy in that it also attaches its self to the existing object
- * which is not really 'correct' python OO but for our use its OK. */
-
- PyObjectPlus_Proxy *ret = (PyObjectPlus_Proxy *) type->tp_alloc(type, 0); /* starts with 1 ref, used for the return ref' */
- ret->ref= base->ref;
- ret->ptr= base->ptr;
- ret->py_owns= base->py_owns;
- ret->py_ref = base->py_ref;
-
- if (ret->py_ref) {
- base->ref= NULL; /* invalidate! disallow further access */
- base->ptr = NULL;
- if (ret->ref)
- ret->ref->m_proxy= NULL;
- /* 'base' may be freed after this func finished but not necessarily
- * there is no reference to the BGE data now so it will throw an error on access */
- Py_DECREF(base);
- if (ret->ref) {
- ret->ref->m_proxy= (PyObject *)ret; /* no need to add a ref because one is added when creating. */
- Py_INCREF(ret); /* we return a new ref but m_proxy holds a ref so we need to add one */
- }
- } else {
- // generic structures don't hold a reference to this proxy, so don't increment ref count
- if (ret->py_owns)
- // but if the proxy owns the structure, there can be only one owner
- base->ptr= NULL;
- }
-
- return (PyObject *)ret;
-}
-
-/**
- * \param self A PyObjectPlus_Proxy
- */
-void PyObjectPlus::py_base_dealloc(PyObject *self) // python wrapper
-{
-#ifdef USE_WEAKREFS
- if (BGE_PROXY_WKREF(self) != NULL)
- PyObject_ClearWeakRefs((PyObject *) self);
-#endif
-
- if (BGE_PROXY_PYREF(self)) {
- PyObjectPlus *self_plus= BGE_PROXY_REF(self);
- if (self_plus) {
- if (BGE_PROXY_PYOWNS(self)) { /* Does python own this?, then delete it */
- self_plus->m_proxy = NULL; /* Need this to stop ~PyObjectPlus from decrefing m_proxy otherwise its decref'd twice and py-debug crashes */
- delete self_plus;
- }
- BGE_PROXY_REF(self)= NULL; // not really needed
- }
- // the generic pointer is not deleted directly, only through self_plus
- BGE_PROXY_PTR(self)= NULL; // not really needed
- } else {
- void *ptr= BGE_PROXY_PTR(self);
- if (ptr) {
- if (BGE_PROXY_PYOWNS(self)) { /* Does python own this?, then delete it */
- // generic structure owned by python MUST be created though MEM_alloc
- MEM_freeN(ptr);
- }
- BGE_PROXY_PTR(self)= NULL; // not really needed
- }
- }
-#if 0
- /* is ok normally but not for subtyping, use tp_free instead. */
- PyObject_DEL( self );
-#else
- Py_TYPE(self)->tp_free(self);
-#endif
-};
-
-/*------------------------------
- * PyObjectPlus Methods -- Every class, even the abstract one should have a Methods
-------------------------------*/
-PyMethodDef PyObjectPlus::Methods[] = {
- {NULL, NULL} /* Sentinel */
-};
-
-#define BGE_PY_ATTR_INVALID (&(PyObjectPlus::Attributes[0]))
-PyAttributeDef PyObjectPlus::Attributes[] = {
- KX_PYATTRIBUTE_RO_FUNCTION("invalid", PyObjectPlus, pyattr_get_invalid),
- {NULL} //Sentinel
-};
-
-
-
-PyObject *PyObjectPlus::pyattr_get_invalid(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- return PyBool_FromLong(self_v ? 0:1);
-}
-
-/* note, this is called as a python 'getset, where the PyAttributeDef is the closure */
-PyObject *PyObjectPlus::py_get_attrdef(PyObject *self_py, const PyAttributeDef *attrdef)
-{
- PyObjectPlus *ref= (BGE_PROXY_REF(self_py));
- char* ptr = (attrdef->m_usePtr) ? (char*)BGE_PROXY_PTR(self_py) : (char*)ref;
- if (ptr == NULL || (BGE_PROXY_PYREF(self_py) && (ref==NULL || !ref->py_is_valid()))) {
- if (attrdef == BGE_PY_ATTR_INVALID)
- Py_RETURN_TRUE; // don't bother running the function
-
- PyErr_SetString(PyExc_SystemError, BGE_PROXY_ERROR_MSG);
- return NULL;
- }
-
- if (attrdef->m_type == KX_PYATTRIBUTE_TYPE_DUMMY)
- {
- // fake attribute, ignore
- return NULL;
- }
- if (attrdef->m_type == KX_PYATTRIBUTE_TYPE_FUNCTION)
- {
- // the attribute has no field correspondence, handover processing to function.
- if (attrdef->m_getFunction == NULL)
- return NULL;
- return (*attrdef->m_getFunction)(ptr, attrdef);
- }
- ptr += attrdef->m_offset;
- if (attrdef->m_length > 1)
- {
- PyObject *resultlist = PyList_New(attrdef->m_length);
- for (unsigned int i=0; i<attrdef->m_length; i++)
- {
- switch (attrdef->m_type) {
- case KX_PYATTRIBUTE_TYPE_BOOL:
- {
- bool *val = reinterpret_cast<bool*>(ptr);
- ptr += sizeof(bool);
- PyList_SET_ITEM(resultlist, i, PyBool_FromLong(*val));
- break;
- }
- case KX_PYATTRIBUTE_TYPE_SHORT:
- {
- short int *val = reinterpret_cast<short int*>(ptr);
- ptr += sizeof(short int);
- PyList_SET_ITEM(resultlist, i, PyLong_FromLong(*val));
- break;
- }
- case KX_PYATTRIBUTE_TYPE_ENUM:
- // enum are like int, just make sure the field size is the same
- if (sizeof(int) != attrdef->m_size)
- {
- Py_DECREF(resultlist);
- return NULL;
- }
- ATTR_FALLTHROUGH;
- case KX_PYATTRIBUTE_TYPE_INT:
- {
- int *val = reinterpret_cast<int*>(ptr);
- ptr += sizeof(int);
- PyList_SET_ITEM(resultlist, i, PyLong_FromLong(*val));
- break;
- }
- case KX_PYATTRIBUTE_TYPE_FLOAT:
- {
- float *val = reinterpret_cast<float*>(ptr);
- ptr += sizeof(float);
- PyList_SET_ITEM(resultlist, i, PyFloat_FromDouble(*val));
- break;
- }
- default:
- // no support for array of complex data
- Py_DECREF(resultlist);
- return NULL;
- }
- }
- return resultlist;
- }
- else
- {
- switch (attrdef->m_type) {
- case KX_PYATTRIBUTE_TYPE_FLAG:
- {
- bool bval;
- switch (attrdef->m_size) {
- case 1:
- {
- unsigned char *val = reinterpret_cast<unsigned char*>(ptr);
- bval = (*val & attrdef->m_imin);
- break;
- }
- case 2:
- {
- unsigned short *val = reinterpret_cast<unsigned short*>(ptr);
- bval = (*val & attrdef->m_imin);
- break;
- }
- case 4:
- {
- unsigned int *val = reinterpret_cast<unsigned int*>(ptr);
- bval = (*val & attrdef->m_imin);
- break;
- }
- default:
- return NULL;
- }
- if (attrdef->m_imax)
- bval = !bval;
- return PyBool_FromLong(bval);
- }
- case KX_PYATTRIBUTE_TYPE_BOOL:
- {
- bool *val = reinterpret_cast<bool*>(ptr);
- return PyBool_FromLong(*val);
- }
- case KX_PYATTRIBUTE_TYPE_SHORT:
- {
- short int *val = reinterpret_cast<short int*>(ptr);
- return PyLong_FromLong(*val);
- }
- case KX_PYATTRIBUTE_TYPE_ENUM:
- // enum are like int, just make sure the field size is the same
- if (sizeof(int) != attrdef->m_size)
- {
- return NULL;
- }
- ATTR_FALLTHROUGH;
- case KX_PYATTRIBUTE_TYPE_INT:
- {
- int *val = reinterpret_cast<int*>(ptr);
- return PyLong_FromLong(*val);
- }
- case KX_PYATTRIBUTE_TYPE_FLOAT:
- {
- float *val = reinterpret_cast<float*>(ptr);
- if (attrdef->m_imin == 0) {
- if (attrdef->m_imax == 0) {
- return PyFloat_FromDouble(*val);
- } else {
- // vector, verify size
- if (attrdef->m_size != attrdef->m_imax*sizeof(float))
- {
- return NULL;
- }
-#ifdef USE_MATHUTILS
- return Vector_CreatePyObject(val, attrdef->m_imax, NULL);
-#else
- PyObject *resultlist = PyList_New(attrdef->m_imax);
- for (unsigned int i=0; i<attrdef->m_imax; i++)
- {
- PyList_SET_ITEM(resultlist, i, PyFloat_FromDouble(val[i]));
- }
- return resultlist;
-#endif
- }
- } else {
- // matrix case
- if (attrdef->m_size != attrdef->m_imax*attrdef->m_imin*sizeof(float))
- {
- return NULL;
- }
-#ifdef USE_MATHUTILS
- return Matrix_CreatePyObject_wrap(val, attrdef->m_imin, attrdef->m_imax, NULL);
-#else
- PyObject *collist = PyList_New(attrdef->m_imin);
- for (unsigned int i=0; i<attrdef->m_imin; i++)
- {
- PyObject *col = PyList_New(attrdef->m_imax);
- for (unsigned int j=0; j<attrdef->m_imax; j++)
- {
- PyList_SET_ITEM(col, j, PyFloat_FromDouble(val[j]));
- }
- PyList_SET_ITEM(collist, i, col);
- val += attrdef->m_imax;
- }
- return collist;
-#endif
- }
- }
- case KX_PYATTRIBUTE_TYPE_VECTOR:
- {
- MT_Vector3 *val = reinterpret_cast<MT_Vector3*>(ptr);
-#ifdef USE_MATHUTILS
- float fval[3];
- val->getValue(fval);
- return Vector_CreatePyObject(fval, 3, NULL);
-#else
- PyObject *resultlist = PyList_New(3);
- for (unsigned int i=0; i<3; i++)
- {
- PyList_SET_ITEM(resultlist, i, PyFloat_FromDouble((*val)[i]));
- }
- return resultlist;
-#endif
- }
- case KX_PYATTRIBUTE_TYPE_STRING:
- {
- STR_String *val = reinterpret_cast<STR_String*>(ptr);
- return PyUnicode_From_STR_String(*val);
- }
- case KX_PYATTRIBUTE_TYPE_CHAR:
- {
- return PyUnicode_FromString(ptr);
- }
- default:
- return NULL;
- }
- }
-}
-
-
-static bool py_check_attr_float(float *var, PyObject *value, const PyAttributeDef *attrdef)
-{
- float val = PyFloat_AsDouble(value);
- if (val == -1.0f && PyErr_Occurred())
- {
- PyErr_Format(PyExc_TypeError, "expected float value for attribute \"%s\"", attrdef->m_name);
- return false;
- }
- if (attrdef->m_clamp)
- {
- if (val < attrdef->m_fmin)
- val = attrdef->m_fmin;
- else if (val > attrdef->m_fmax)
- val = attrdef->m_fmax;
- }
- else if (val < attrdef->m_fmin || val > attrdef->m_fmax)
- {
- PyErr_Format(PyExc_ValueError, "value out of range for attribute \"%s\"", attrdef->m_name);
- return false;
- }
- *var = (float)val;
- return true;
-}
-
-/* note, this is called as a python getset */
-int PyObjectPlus::py_set_attrdef(PyObject *self_py, PyObject *value, const PyAttributeDef *attrdef)
-{
- PyObjectPlus *ref= (BGE_PROXY_REF(self_py));
- char* ptr = (attrdef->m_usePtr) ? (char*)BGE_PROXY_PTR(self_py) : (char*)ref;
- if (ref==NULL || !ref->py_is_valid() || ptr==NULL) {
- PyErr_SetString(PyExc_SystemError, BGE_PROXY_ERROR_MSG);
- return PY_SET_ATTR_FAIL;
- }
-
- void *undoBuffer = NULL;
- void *sourceBuffer = NULL;
- size_t bufferSize = 0;
- PyObject *item = NULL; // to store object that must be dereferenced in case of error
- PyObject *list = NULL; // to store object that must be dereferenced in case of error
-
- ptr += attrdef->m_offset;
- if (attrdef->m_length > 1)
- {
- if (!PySequence_Check(value))
- {
- PyErr_Format(PyExc_TypeError, "expected a sequence for attribute \"%s\"", attrdef->m_name);
- return PY_SET_ATTR_FAIL;
- }
- if (PySequence_Size(value) != attrdef->m_length)
- {
- PyErr_Format(PyExc_TypeError, "incorrect number of elements in sequence for attribute \"%s\"", attrdef->m_name);
- return PY_SET_ATTR_FAIL;
- }
- switch (attrdef->m_type)
- {
- case KX_PYATTRIBUTE_TYPE_FUNCTION:
- if (attrdef->m_setFunction == NULL)
- {
- PyErr_Format(PyExc_AttributeError, "function attribute without function for attribute \"%s\", report to blender.org", attrdef->m_name);
- return PY_SET_ATTR_FAIL;
- }
- return (*attrdef->m_setFunction)(ref, attrdef, value);
- case KX_PYATTRIBUTE_TYPE_BOOL:
- bufferSize = sizeof(bool);
- break;
- case KX_PYATTRIBUTE_TYPE_SHORT:
- bufferSize = sizeof(short int);
- break;
- case KX_PYATTRIBUTE_TYPE_ENUM:
- case KX_PYATTRIBUTE_TYPE_INT:
- bufferSize = sizeof(int);
- break;
- case KX_PYATTRIBUTE_TYPE_FLOAT:
- bufferSize = sizeof(float);
- break;
- default:
- // should not happen
- PyErr_Format(PyExc_AttributeError, "Unsupported attribute type for attribute \"%s\", report to blender.org", attrdef->m_name);
- return PY_SET_ATTR_FAIL;
- }
- // let's implement a smart undo method
- bufferSize *= attrdef->m_length;
- undoBuffer = malloc(bufferSize);
- sourceBuffer = ptr;
- if (undoBuffer)
- {
- memcpy(undoBuffer, sourceBuffer, bufferSize);
- }
- for (int i=0; i<attrdef->m_length; i++)
- {
- item = PySequence_GetItem(value, i); /* new ref */
- switch (attrdef->m_type)
- {
- case KX_PYATTRIBUTE_TYPE_BOOL:
- {
- bool *var = reinterpret_cast<bool*>(ptr);
- ptr += sizeof(bool);
- if (PyLong_Check(item))
- {
- *var = (PyLong_AsLong(item) != 0);
- }
- else if (PyBool_Check(item))
- {
- *var = (item == Py_True);
- }
- else
- {
- PyErr_Format(PyExc_TypeError, "expected an integer or a bool for attribute \"%s\"", attrdef->m_name);
- goto UNDO_AND_ERROR;
- }
- break;
- }
- case KX_PYATTRIBUTE_TYPE_SHORT:
- {
- short int *var = reinterpret_cast<short int*>(ptr);
- ptr += sizeof(short int);
- if (PyLong_Check(item))
- {
- int val = PyLong_AsLong(item);
- if (attrdef->m_clamp)
- {
- if (val < attrdef->m_imin)
- val = attrdef->m_imin;
- else if (val > attrdef->m_imax)
- val = attrdef->m_imax;
- }
- else if (val < attrdef->m_imin || val > attrdef->m_imax)
- {
- PyErr_Format(PyExc_ValueError, "item value out of range for attribute \"%s\"", attrdef->m_name);
- goto UNDO_AND_ERROR;
- }
- *var = (short int)val;
- }
- else
- {
- PyErr_Format(PyExc_TypeError, "expected an integer for attribute \"%s\"", attrdef->m_name);
- goto UNDO_AND_ERROR;
- }
- break;
- }
- case KX_PYATTRIBUTE_TYPE_ENUM:
- // enum are equivalent to int, just make sure that the field size matches:
- if (sizeof(int) != attrdef->m_size)
- {
- PyErr_Format(PyExc_AttributeError, "Size check error for attribute, \"%s\", report to blender.org", attrdef->m_name);
- goto UNDO_AND_ERROR;
- }
- ATTR_FALLTHROUGH;
- case KX_PYATTRIBUTE_TYPE_INT:
- {
- int *var = reinterpret_cast<int*>(ptr);
- ptr += sizeof(int);
- if (PyLong_Check(item))
- {
- int val = PyLong_AsLong(item);
- if (attrdef->m_clamp)
- {
- if (val < attrdef->m_imin)
- val = attrdef->m_imin;
- else if (val > attrdef->m_imax)
- val = attrdef->m_imax;
- }
- else if (val < attrdef->m_imin || val > attrdef->m_imax)
- {
- PyErr_Format(PyExc_ValueError, "item value out of range for attribute \"%s\"", attrdef->m_name);
- goto UNDO_AND_ERROR;
- }
- *var = (int)val;
- }
- else
- {
- PyErr_Format(PyExc_TypeError, "expected an integer for attribute \"%s\"", attrdef->m_name);
- goto UNDO_AND_ERROR;
- }
- break;
- }
- case KX_PYATTRIBUTE_TYPE_FLOAT:
- {
- float *var = reinterpret_cast<float*>(ptr);
- ptr += sizeof(float);
- float val = PyFloat_AsDouble(item);
- if (val == -1.0f && PyErr_Occurred())
- {
- PyErr_Format(PyExc_TypeError, "expected a float for attribute \"%s\"", attrdef->m_name);
- goto UNDO_AND_ERROR;
- }
- else if (attrdef->m_clamp)
- {
- if (val < attrdef->m_fmin)
- val = attrdef->m_fmin;
- else if (val > attrdef->m_fmax)
- val = attrdef->m_fmax;
- }
- else if (val < attrdef->m_fmin || val > attrdef->m_fmax)
- {
- PyErr_Format(PyExc_ValueError, "item value out of range for attribute \"%s\"", attrdef->m_name);
- goto UNDO_AND_ERROR;
- }
- *var = (float)val;
- break;
- }
- default:
- // should not happen
- PyErr_Format(PyExc_AttributeError, "type check error for attribute \"%s\", report to blender.org", attrdef->m_name);
- goto UNDO_AND_ERROR;
- }
- // finished using item, release
- Py_DECREF(item);
- item = NULL;
- }
- // no error, call check function if any
- if (attrdef->m_checkFunction != NULL)
- {
- if ((*attrdef->m_checkFunction)(ref, attrdef) != 0)
- {
- // if the checing function didnt set an error then set a generic one here so we don't set an error with no exception
- if (PyErr_Occurred()==0)
- PyErr_Format(PyExc_AttributeError, "type check error for attribute \"%s\", reasion unknown", attrdef->m_name);
-
- // post check returned an error, restore values
- UNDO_AND_ERROR:
- if (undoBuffer)
- {
- memcpy(sourceBuffer, undoBuffer, bufferSize);
- free(undoBuffer);
- }
- if (item)
- Py_DECREF(item);
- return PY_SET_ATTR_FAIL;
- }
- }
- if (undoBuffer)
- free(undoBuffer);
- return PY_SET_ATTR_SUCCESS;
- }
- else // simple attribute value
- {
- if (attrdef->m_type == KX_PYATTRIBUTE_TYPE_FUNCTION)
- {
- if (attrdef->m_setFunction == NULL)
- {
- PyErr_Format(PyExc_AttributeError, "function attribute without function \"%s\", report to blender.org", attrdef->m_name);
- return PY_SET_ATTR_FAIL;
- }
- return (*attrdef->m_setFunction)(ref, attrdef, value);
- }
- if (attrdef->m_checkFunction != NULL || attrdef->m_type == KX_PYATTRIBUTE_TYPE_VECTOR)
- {
- // post check function is provided, prepare undo buffer
- sourceBuffer = ptr;
- switch (attrdef->m_type)
- {
- case KX_PYATTRIBUTE_TYPE_BOOL:
- bufferSize = sizeof(bool);
- break;
- case KX_PYATTRIBUTE_TYPE_SHORT:
- bufferSize = sizeof(short);
- break;
- case KX_PYATTRIBUTE_TYPE_ENUM:
- case KX_PYATTRIBUTE_TYPE_FLAG:
- case KX_PYATTRIBUTE_TYPE_CHAR:
- bufferSize = attrdef->m_size;
- break;
- case KX_PYATTRIBUTE_TYPE_INT:
- bufferSize = sizeof(int);
- break;
- case KX_PYATTRIBUTE_TYPE_FLOAT:
- bufferSize = sizeof(float);
- if (attrdef->m_imax)
- bufferSize *= attrdef->m_imax;
- if (attrdef->m_imin)
- bufferSize *= attrdef->m_imin;
- break;
- case KX_PYATTRIBUTE_TYPE_STRING:
- sourceBuffer = reinterpret_cast<STR_String*>(ptr)->Ptr();
- if (sourceBuffer)
- bufferSize = strlen(reinterpret_cast<char*>(sourceBuffer))+1;
- break;
- case KX_PYATTRIBUTE_TYPE_VECTOR:
- bufferSize = sizeof(MT_Vector3);
- break;
- default:
- PyErr_Format(PyExc_AttributeError, "unknown type for attribute \"%s\", report to blender.org", attrdef->m_name);
- return PY_SET_ATTR_FAIL;
- }
- if (bufferSize)
- {
- undoBuffer = malloc(bufferSize);
- if (undoBuffer)
- {
- memcpy(undoBuffer, sourceBuffer, bufferSize);
- }
- }
- }
-
- switch (attrdef->m_type)
- {
- case KX_PYATTRIBUTE_TYPE_BOOL:
- {
- bool *var = reinterpret_cast<bool*>(ptr);
- if (PyLong_Check(value))
- {
- *var = (PyLong_AsLong(value) != 0);
- }
- else if (PyBool_Check(value))
- {
- *var = (value == Py_True);
- }
- else
- {
- PyErr_Format(PyExc_TypeError, "expected an integer or a bool for attribute \"%s\"", attrdef->m_name);
- goto FREE_AND_ERROR;
- }
- break;
- }
- case KX_PYATTRIBUTE_TYPE_FLAG:
- {
- bool bval;
- if (PyLong_Check(value))
- {
- bval = (PyLong_AsLong(value) != 0);
- }
- else if (PyBool_Check(value))
- {
- bval = (value == Py_True);
- }
- else
- {
- PyErr_Format(PyExc_TypeError, "expected an integer or a bool for attribute \"%s\"", attrdef->m_name);
- goto FREE_AND_ERROR;
- }
- if (attrdef->m_imax)
- bval = !bval;
- switch (attrdef->m_size) {
- case 1:
- {
- unsigned char *val = reinterpret_cast<unsigned char*>(ptr);
- *val = (*val & ~attrdef->m_imin) | ((bval)?attrdef->m_imin:0);
- break;
- }
- case 2:
- {
- unsigned short *val = reinterpret_cast<unsigned short*>(ptr);
- *val = (*val & ~attrdef->m_imin) | ((bval)?attrdef->m_imin:0);
- break;
- }
- case 4:
- {
- unsigned int *val = reinterpret_cast<unsigned int*>(ptr);
- *val = (*val & ~attrdef->m_imin) | ((bval)?attrdef->m_imin:0);
- break;
- }
- default:
- PyErr_Format(PyExc_TypeError, "internal error: unsupported flag field \"%s\"", attrdef->m_name);
- goto FREE_AND_ERROR;
- }
- break;
- }
- case KX_PYATTRIBUTE_TYPE_SHORT:
- {
- short int *var = reinterpret_cast<short int*>(ptr);
- if (PyLong_Check(value))
- {
- int val = PyLong_AsLong(value);
- if (attrdef->m_clamp)
- {
- if (val < attrdef->m_imin)
- val = attrdef->m_imin;
- else if (val > attrdef->m_imax)
- val = attrdef->m_imax;
- }
- else if (val < attrdef->m_imin || val > attrdef->m_imax)
- {
- PyErr_Format(PyExc_ValueError, "value out of range for attribute \"%s\"", attrdef->m_name);
- goto FREE_AND_ERROR;
- }
- *var = (short int)val;
- }
- else
- {
- PyErr_Format(PyExc_TypeError, "expected an integer for attribute \"%s\"", attrdef->m_name);
- goto FREE_AND_ERROR;
- }
- break;
- }
- case KX_PYATTRIBUTE_TYPE_ENUM:
- // enum are equivalent to int, just make sure that the field size matches:
- if (sizeof(int) != attrdef->m_size)
- {
- PyErr_Format(PyExc_AttributeError, "attribute size check error for attribute \"%s\", report to blender.org", attrdef->m_name);
- goto FREE_AND_ERROR;
- }
- ATTR_FALLTHROUGH;
- case KX_PYATTRIBUTE_TYPE_INT:
- {
- int *var = reinterpret_cast<int*>(ptr);
- if (PyLong_Check(value))
- {
- int val = PyLong_AsLong(value);
- if (attrdef->m_clamp)
- {
- if (val < attrdef->m_imin)
- val = attrdef->m_imin;
- else if (val > attrdef->m_imax)
- val = attrdef->m_imax;
- }
- else if (val < attrdef->m_imin || val > attrdef->m_imax)
- {
- PyErr_Format(PyExc_ValueError, "value out of range for attribute \"%s\"", attrdef->m_name);
- goto FREE_AND_ERROR;
- }
- *var = (int)val;
- }
- else
- {
- PyErr_Format(PyExc_TypeError, "expected an integer for attribute \"%s\"", attrdef->m_name);
- goto FREE_AND_ERROR;
- }
- break;
- }
- case KX_PYATTRIBUTE_TYPE_FLOAT:
- {
- float *var = reinterpret_cast<float*>(ptr);
- if (attrdef->m_imin != 0)
- {
- if (attrdef->m_size != attrdef->m_imin*attrdef->m_imax*sizeof(float))
- {
- PyErr_Format(PyExc_TypeError, "internal error: incorrect field size for attribute \"%s\"", attrdef->m_name);
- goto FREE_AND_ERROR;
- }
- if (!PySequence_Check(value) || PySequence_Size(value) != attrdef->m_imin)
- {
- PyErr_Format(PyExc_TypeError, "expected a sequence of [%d][%d] floats for attribute \"%s\"", attrdef->m_imin, attrdef->m_imax, attrdef->m_name);
- goto FREE_AND_ERROR;
- }
- for (int i=0; i<attrdef->m_imin; i++)
- {
- PyObject *list = PySequence_GetItem(value, i); /* new ref */
- if (!PySequence_Check(list) || PySequence_Size(list) != attrdef->m_imax)
- {
- PyErr_Format(PyExc_TypeError, "expected a sequence of [%d][%d] floats for attribute \"%s\"", attrdef->m_imin, attrdef->m_imax, attrdef->m_name);
- goto RESTORE_AND_ERROR;
- }
- for (int j=0; j<attrdef->m_imax; j++)
- {
- item = PySequence_GetItem(list, j); /* new ref */
- if (!py_check_attr_float(var, item, attrdef))
- {
- PyErr_Format(PyExc_TypeError, "expected a sequence of [%d][%d] floats for attribute \"%s\"", attrdef->m_imin, attrdef->m_imax, attrdef->m_name);
- goto RESTORE_AND_ERROR;
- }
- Py_DECREF(item);
- item = NULL;
- ++var;
- }
- Py_DECREF(list);
- list = NULL;
- }
- }
- else if (attrdef->m_imax != 0)
- {
- if (attrdef->m_size != attrdef->m_imax*sizeof(float))
- {
- PyErr_Format(PyExc_TypeError, "internal error: incorrect field size for attribute \"%s\"", attrdef->m_name);
- goto FREE_AND_ERROR;
- }
- if (!PySequence_Check(value) || PySequence_Size(value) != attrdef->m_imax)
- {
- PyErr_Format(PyExc_TypeError, "expected a sequence of [%d] floats for attribute \"%s\"", attrdef->m_imax, attrdef->m_name);
- goto FREE_AND_ERROR;
- }
- for (int i=0; i<attrdef->m_imax; i++)
- {
- item = PySequence_GetItem(value, i); /* new ref */
- if (!py_check_attr_float(var, item, attrdef))
- {
- goto RESTORE_AND_ERROR;
- }
- Py_DECREF(item);
- item = NULL;
- ++var;
- }
- }
- else
- {
- if (!py_check_attr_float(var, value, attrdef))
- goto FREE_AND_ERROR;
- }
- break;
- }
- case KX_PYATTRIBUTE_TYPE_VECTOR:
- {
- if (!PySequence_Check(value) || PySequence_Size(value) != 3)
- {
- PyErr_Format(PyExc_TypeError, "expected a sequence of 3 floats for attribute \"%s\"", attrdef->m_name);
- goto FREE_AND_ERROR;
- }
- MT_Vector3 *var = reinterpret_cast<MT_Vector3*>(ptr);
- for (int i=0; i<3; i++)
- {
- item = PySequence_GetItem(value, i); /* new ref */
- float val = PyFloat_AsDouble(item);
- Py_DECREF(item);
- item = NULL;
- if (val == -1.0f && PyErr_Occurred())
- {
- PyErr_Format(PyExc_TypeError, "expected a sequence of 3 floats for attribute \"%s\"", attrdef->m_name);
- goto RESTORE_AND_ERROR;
- }
- else if (attrdef->m_clamp)
- {
- if (val < attrdef->m_fmin)
- val = attrdef->m_fmin;
- else if (val > attrdef->m_fmax)
- val = attrdef->m_fmax;
- }
- else if (val < attrdef->m_fmin || val > attrdef->m_fmax)
- {
- PyErr_Format(PyExc_ValueError, "value out of range for attribute \"%s\"", attrdef->m_name);
- goto RESTORE_AND_ERROR;
- }
- (*var)[i] = (MT_Scalar)val;
- }
- break;
- }
- case KX_PYATTRIBUTE_TYPE_CHAR:
- {
- if (PyUnicode_Check(value))
- {
- Py_ssize_t val_size;
- const char *val = _PyUnicode_AsStringAndSize(value, &val_size);
- strncpy(ptr, val, attrdef->m_size);
- ptr[attrdef->m_size-1] = 0;
- }
- else
- {
- PyErr_Format(PyExc_TypeError, "expected a string for attribute \"%s\"", attrdef->m_name);
- goto FREE_AND_ERROR;
- }
- break;
- }
- case KX_PYATTRIBUTE_TYPE_STRING:
- {
- STR_String *var = reinterpret_cast<STR_String*>(ptr);
- if (PyUnicode_Check(value))
- {
- Py_ssize_t val_len;
- const char *val = _PyUnicode_AsStringAndSize(value, &val_len); /* XXX, should be 'const' but we do a silly trick to have a shorter string */
- if (attrdef->m_clamp)
- {
- if (val_len < attrdef->m_imin)
- {
- // can't increase the length of the string
- PyErr_Format(PyExc_ValueError, "string length too short for attribute \"%s\"", attrdef->m_name);
- goto FREE_AND_ERROR;
- }
- else if (val_len > attrdef->m_imax)
- {
- // trim the string
- var->SetLength(attrdef->m_imax);
- memcpy(var->Ptr(), val, attrdef->m_imax - 1);
- break;
- }
- } else if (val_len < attrdef->m_imin || val_len > attrdef->m_imax)
- {
- PyErr_Format(PyExc_ValueError, "string length out of range for attribute \"%s\"", attrdef->m_name);
- goto FREE_AND_ERROR;
- }
- *var = val;
- }
- else
- {
- PyErr_Format(PyExc_TypeError, "expected a string for attribute \"%s\"", attrdef->m_name);
- goto FREE_AND_ERROR;
- }
- break;
- }
- default:
- // should not happen
- PyErr_Format(PyExc_AttributeError, "unknown type for attribute \"%s\", report to blender.org", attrdef->m_name);
- goto FREE_AND_ERROR;
- }
- }
- // check if post processing is needed
- if (attrdef->m_checkFunction != NULL)
- {
- if ((*attrdef->m_checkFunction)(ref, attrdef) != 0)
- {
- // restore value
- RESTORE_AND_ERROR:
- if (undoBuffer)
- {
- if (attrdef->m_type == KX_PYATTRIBUTE_TYPE_STRING)
- {
- // special case for STR_String: restore the string
- STR_String *var = reinterpret_cast<STR_String*>(ptr);
- *var = reinterpret_cast<char*>(undoBuffer);
- }
- else
- {
- // other field type have direct values
- memcpy(ptr, undoBuffer, bufferSize);
- }
- }
- FREE_AND_ERROR:
- if (undoBuffer)
- free(undoBuffer);
- if (list)
- Py_DECREF(list);
- if (item)
- Py_DECREF(item);
- return 1;
- }
- }
- if (undoBuffer)
- free(undoBuffer);
- return 0;
-}
-
-
-
-/*------------------------------
- * PyObjectPlus repr -- representations
-------------------------------*/
-PyObject *PyObjectPlus::py_repr(void)
-{
- PyErr_SetString(PyExc_SystemError, "Representation not overridden by object.");
- return NULL;
-}
-
-PyObject *PyObjectPlus::GetProxyPlus_Ext(PyObjectPlus *self, PyTypeObject *tp, void *ptr)
-{
- if (self->m_proxy==NULL)
- {
- self->m_proxy = reinterpret_cast<PyObject *>PyObject_NEW( PyObjectPlus_Proxy, tp);
- BGE_PROXY_PYOWNS(self->m_proxy) = false;
- BGE_PROXY_PYREF(self->m_proxy) = true;
-#ifdef USE_WEAKREFS
- BGE_PROXY_WKREF(self->m_proxy) = NULL;
-#endif
- }
- //PyObject_Print(self->m_proxy, stdout, 0);
- //printf("ref %d\n", self->m_proxy->ob_refcnt);
-
- BGE_PROXY_REF(self->m_proxy) = self; /* Its possible this was set to NULL, so set it back here */
- BGE_PROXY_PTR(self->m_proxy) = ptr;
- Py_INCREF(self->m_proxy); /* we own one, thos ones fore the return */
- return self->m_proxy;
-}
-
-PyObject *PyObjectPlus::NewProxyPlus_Ext(PyObjectPlus *self, PyTypeObject *tp, void *ptr, bool py_owns)
-{
- if (!self)
- {
- // in case of proxy without reference to game object
- PyObject *proxy = reinterpret_cast<PyObject *>PyObject_NEW( PyObjectPlus_Proxy, tp);
- BGE_PROXY_PYREF(proxy) = false;
- BGE_PROXY_PYOWNS(proxy) = py_owns;
- BGE_PROXY_REF(proxy) = NULL;
- BGE_PROXY_PTR(proxy) = ptr;
-#ifdef USE_WEAKREFS
- BGE_PROXY_WKREF(proxy) = NULL;
-#endif
- return proxy;
- }
- if (self->m_proxy)
- {
- if (py_owns)
- { /* Free */
- BGE_PROXY_REF(self->m_proxy) = NULL;
- Py_DECREF(self->m_proxy);
- self->m_proxy= NULL;
- }
- else {
- Py_INCREF(self->m_proxy);
- return self->m_proxy;
- }
-
- }
-
- GetProxyPlus_Ext(self, tp, ptr);
- if (py_owns) {
- BGE_PROXY_PYOWNS(self->m_proxy) = py_owns;
- Py_DECREF(self->m_proxy); /* could avoid thrashing here but for now its ok */
- }
- return self->m_proxy;
-}
-
-PyObject *PyUnicode_From_STR_String(const STR_String& str)
-{
- return PyUnicode_FromStringAndSize(str.ReadPtr(), str.Length());
-}
-
-///////////////////////////////////////////////////////////////////////////////////////////////
-///////////////////////////////////////////////////////////////////////////////////////////////
-/* deprecation warning management */
-
-bool PyObjectPlus::m_ignore_deprecation_warnings(false);
-void PyObjectPlus::SetDeprecationWarnings(bool ignoreDeprecationWarnings)
-{
- m_ignore_deprecation_warnings = ignoreDeprecationWarnings;
-}
-
-void PyObjectPlus::ShowDeprecationWarning_func(const char *old_way, const char *new_way)
-{
- printf("Method %s is deprecated, please use %s instead.\n", old_way, new_way);
- PyC_LineSpit();
-}
-
-void PyObjectPlus::ClearDeprecationWarning()
-{
- WarnLink *wlink_next;
- WarnLink *wlink = GetDeprecationWarningLinkFirst();
-
- while (wlink) {
- wlink->warn_done= false; /* no need to NULL the link, its cleared before adding to the list next time round */
- wlink_next= reinterpret_cast<WarnLink *>(wlink->link);
- wlink->link= NULL;
- wlink= wlink_next;
- }
- NullDeprecationWarning();
-}
-
-static WarnLink *m_base_wlink_first = NULL;
-static WarnLink *m_base_wlink_last = NULL;
-
-WarnLink* PyObjectPlus::GetDeprecationWarningLinkFirst(void) {return m_base_wlink_first;}
-WarnLink* PyObjectPlus::GetDeprecationWarningLinkLast(void) {return m_base_wlink_last;}
-void PyObjectPlus::SetDeprecationWarningFirst(WarnLink* wlink) {m_base_wlink_first= wlink;}
-void PyObjectPlus::SetDeprecationWarningLinkLast(WarnLink* wlink) {m_base_wlink_last= wlink;}
-void PyObjectPlus::NullDeprecationWarning() {m_base_wlink_first= m_base_wlink_last= NULL;}
-
-#endif // WITH_PYTHON
diff --git a/source/gameengine/Expressions/intern/PythonCallBack.cpp b/source/gameengine/Expressions/intern/PythonCallBack.cpp
deleted file mode 100644
index 3fb84569eca..00000000000
--- a/source/gameengine/Expressions/intern/PythonCallBack.cpp
+++ /dev/null
@@ -1,119 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * Contributor(s): Porteries Tristan.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Expressions/intern/PythonCallBack.cpp
- * \ingroup expressions
- */
-
-#include "EXP_PythonCallBack.h"
-#include <iostream>
-#include <stdarg.h>
-
-#include "BLI_alloca.h"
-
-/** Check if a python value is a function and have the correct number of arguments.
- * \param value The python value to check.
- * \param minargcount The minimum of arguments possible.
- * \param maxargcount The maximum of arguments possible.
- * \param r_argcount The number of argument of this function, this variable will be
- * changed in the function.
- */
-static PyObject *CheckPythonFunction(PyObject *value, unsigned int minargcount, unsigned int maxargcount, unsigned int &r_argcount)
-{
- if (PyMethod_Check(value)) {
- PyCodeObject *code = ((PyCodeObject *)PyFunction_GET_CODE(PyMethod_GET_FUNCTION(value)));
- // *args support
- r_argcount = (code->co_flags & CO_VARARGS) ? maxargcount : (code->co_argcount - 1);
- }
- else if (PyFunction_Check(value)) {
- PyCodeObject *code = ((PyCodeObject *)PyFunction_GET_CODE(value));
- // *args support
- r_argcount = (code->co_flags & CO_VARARGS) ? maxargcount : code->co_argcount;
- }
- else { // is not a methode or a function
- PyErr_Format(PyExc_TypeError, "items must be functions or methodes, not %s",
- Py_TYPE(value)->tp_name);
- return NULL;
- }
-
- if (r_argcount < minargcount || r_argcount > maxargcount) {
- // wrong number of arguments
- PyErr_Format(PyExc_TypeError, "methode or function (%s) has invalid number of arguments (%i) must be between %i and %i",
- Py_TYPE(value)->tp_name, r_argcount, minargcount, maxargcount);
- return NULL;
- }
-
- return value;
-}
-
-/** Create a python tuple to call a python function
- * \param argcount The lenght of the tuple.
- * \param arglist The fully list of python arguments [size >= argcount].
- */
-static PyObject *CreatePythonTuple(unsigned int argcount, PyObject **arglist)
-{
- PyObject *tuple = PyTuple_New(argcount);
-
- for (unsigned int i = 0; i < argcount; ++i) {
- PyObject *item = arglist[i];
- // increment reference and copy it in a new tuple
- Py_INCREF(item);
- PyTuple_SET_ITEM(tuple, i, item);
- }
-
- return tuple;
-}
-
-void RunPythonCallBackList(PyObject *functionlist, PyObject **arglist, unsigned int minargcount, unsigned int maxargcount)
-{
- unsigned int size = PyList_Size(functionlist);
- PyObject **argTuples = (PyObject **)BLI_array_alloca(argTuples, maxargcount - minargcount + 1);
- memset(argTuples, 0, sizeof(PyObject *) * (maxargcount - minargcount + 1));
-
- for (unsigned int i = 0; i < size; ++i) {
- unsigned int funcargcount = 0;
-
- PyObject *item = PyList_GET_ITEM(functionlist, i);
- PyObject *func = CheckPythonFunction(item, minargcount, maxargcount, funcargcount);
- if (!func) { // this item fails the check
- PyErr_Print();
- PyErr_Clear();
- continue;
- }
-
- // get correct argument tuple.
- PyObject *tuple = argTuples[funcargcount - minargcount];
- if (!tuple)
- argTuples[funcargcount - minargcount] = tuple = CreatePythonTuple(funcargcount, arglist);
-
- PyObject *ret = PyObject_Call(func, tuple, NULL);
- if (!ret) { // if ret is NULL this seems that the function doesn't work !
- PyErr_Print();
- PyErr_Clear();
- }
- else
- Py_DECREF(ret);
- }
-
- for (unsigned int i = 0; i <= (maxargcount - minargcount); ++i)
- Py_XDECREF(argTuples[i]);
-}
diff --git a/source/gameengine/Expressions/intern/StringValue.cpp b/source/gameengine/Expressions/intern/StringValue.cpp
deleted file mode 100644
index ddf61dc441c..00000000000
--- a/source/gameengine/Expressions/intern/StringValue.cpp
+++ /dev/null
@@ -1,147 +0,0 @@
-/** \file gameengine/Expressions/StringValue.cpp
- * \ingroup expressions
- */
-// StringValue.cpp: implementation of the CStringValue class.
-/*
- * Copyright (c) 1996-2000 Erwin Coumans <coockie@acm.org>
- *
- * Permission to use, copy, modify, distribute and sell this software
- * and its documentation for any purpose is hereby granted without fee,
- * provided that the above copyright notice appear in all copies and
- * that both that copyright notice and this permission notice appear
- * in supporting documentation. Erwin Coumans makes no
- * representations about the suitability of this software for any
- * purpose. It is provided "as is" without express or implied warranty.
- *
- */
-
-#include "EXP_StringValue.h"
-#include "EXP_BoolValue.h"
-#include "EXP_ErrorValue.h"
-#include "EXP_VoidValue.h"
-
-//////////////////////////////////////////////////////////////////////
-// Construction/Destruction
-//////////////////////////////////////////////////////////////////////
-
-/**
- * pre: false
- * effect: constructs a new CStringValue
- */
-CStringValue::CStringValue()
-{
- m_strString = "[Illegal String constructor call]";
-}
-
-/**
- * pre:
- * effect: constructs a new CStringValue containing text txt
- */
-CStringValue::CStringValue(const char *txt,const char *name,AllocationTYPE alloctype)
-{
- m_strString = txt;
- SetName(name);
-
- if (alloctype==CValue::STACKVALUE)
- {
- CValue::DisableRefCount();
-
- }
-
-
-}
-
-
-/**
- * pre:
- * ret: a new object containing the result of applying operator op to this
- * object and val
- */
-CValue* CStringValue::Calc(VALUE_OPERATOR op, CValue *val)
-{
- //return val->CalrcString(op, this);
- return val->CalcFinal(VALUE_STRING_TYPE, op, this);
-}
-
-/**
- * pre: the type of val is dtype
- * ret: a new object containing the result of applying operator op to val and
- * this object
- */
-CValue* CStringValue::CalcFinal(VALUE_DATA_TYPE dtype, VALUE_OPERATOR op, CValue *val)
-{
- CValue *ret;
-
- if (op == VALUE_ADD_OPERATOR) {
- if (dtype == VALUE_ERROR_TYPE)
- ret = new CErrorValue(val->GetText() + op2str(op) + GetText());
- else
- ret = new CStringValue(val->GetText() + GetText(),"");
- }
- else {
- if (dtype == VALUE_STRING_TYPE || dtype == VALUE_EMPTY_TYPE) {
- switch (op) {
- case VALUE_EQL_OPERATOR:
- ret = new CBoolValue(val->GetText() == GetText());
- break;
- case VALUE_NEQ_OPERATOR:
- ret = new CBoolValue(val->GetText() != GetText());
- break;
- case VALUE_GRE_OPERATOR:
- ret = new CBoolValue(val->GetText() > GetText());
- break;
- case VALUE_LES_OPERATOR:
- ret = new CBoolValue(val->GetText() < GetText());
- break;
- case VALUE_GEQ_OPERATOR:
- ret = new CBoolValue(val->GetText() >= GetText());
- break;
- case VALUE_LEQ_OPERATOR:
- ret = new CBoolValue(val->GetText() <= GetText());
- break;
- default:
- ret = new CErrorValue(val->GetText() + op2str(op) + "[operator not allowed on strings]");
- break;
- }
- }
- else {
- ret = new CErrorValue(val->GetText() + op2str(op) + "[operator not allowed on strings]");
- }
- }
- return ret;
-}
-
-
-
-double CStringValue::GetNumber()
-{
- return -1;
-}
-
-
-
-int CStringValue::GetValueType()
-{
- return VALUE_STRING_TYPE;
-}
-
-
-
-const STR_String & CStringValue::GetText()
-{
- return m_strString;
-}
-
-bool CStringValue::IsEqual(const STR_String & other)
-{
- return (m_strString == other);
-}
-
-CValue* CStringValue::GetReplica()
-{
- CStringValue* replica = new CStringValue(*this);
- replica->ProcessReplica();
- return replica;
-};
-
-
diff --git a/source/gameengine/Expressions/intern/Value.cpp b/source/gameengine/Expressions/intern/Value.cpp
deleted file mode 100644
index f8796a76e76..00000000000
--- a/source/gameengine/Expressions/intern/Value.cpp
+++ /dev/null
@@ -1,672 +0,0 @@
-/** \file gameengine/Expressions/Value.cpp
- * \ingroup expressions
- */
-// Value.cpp: implementation of the CValue class.
-// developed at Eindhoven University of Technology, 1997
-// by the OOPS team
-//////////////////////////////////////////////////////////////////////
-/*
- * Copyright (c) 1996-2000 Erwin Coumans <coockie@acm.org>
- *
- * Permission to use, copy, modify, distribute and sell this software
- * and its documentation for any purpose is hereby granted without fee,
- * provided that the above copyright notice appear in all copies and
- * that both that copyright notice and this permission notice appear
- * in supporting documentation. Erwin Coumans makes no
- * representations about the suitability of this software for any
- * purpose. It is provided "as is" without express or implied warranty.
- *
- */
-#include "EXP_Value.h"
-#include "EXP_BoolValue.h"
-#include "EXP_FloatValue.h"
-#include "EXP_IntValue.h"
-#include "EXP_VectorValue.h"
-#include "EXP_VoidValue.h"
-#include "EXP_StringValue.h"
-#include "EXP_ErrorValue.h"
-#include "EXP_ListValue.h"
-
-//////////////////////////////////////////////////////////////////////
-// Construction/Destruction
-//////////////////////////////////////////////////////////////////////
-
-double CValue::m_sZeroVec[3] = {0.0,0.0,0.0};
-
-#ifdef WITH_PYTHON
-
-PyTypeObject CValue::Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "CValue",
- sizeof(PyObjectPlus_Proxy),
- 0,
- py_base_dealloc,
- 0,
- 0,
- 0,
- 0,
- py_base_repr,
- 0,
- 0,0,0,0,0,
- NULL,
- NULL,
- 0,
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
- 0,0,0,0,0,0,0,
- Methods,
- 0,
- 0,
- &PyObjectPlus::Type,
- 0,0,0,0,0,0,
- py_base_new
-};
-
-PyMethodDef CValue::Methods[] = {
- {NULL,NULL} //Sentinel
-};
-#endif // WITH_PYTHON
-
-
-/*#define CVALUE_DEBUG*/
-#ifdef CVALUE_DEBUG
-int gRefCount;
-struct SmartCValueRef
-{
- CValue *m_ref;
- int m_count;
- SmartCValueRef(CValue *ref)
- {
- m_ref = ref;
- m_count = gRefCount++;
- }
-};
-
-#include <vector>
-
-std::vector<SmartCValueRef> gRefList;
-#endif
-
-#ifdef DEBUG
-//int gRefCountValue;
-#endif
-
-CValue::CValue()
- : PyObjectPlus(),
-
-m_pNamedPropertyArray(NULL),
-m_refcount(1)
-/*
-pre: false
-effect: constucts a CValue
-*/
-{
- //debug(gRefCountValue++) // debugging
-#ifdef DEBUG
- //gRefCountValue++;
-#ifdef CVALUE_DEBUG
- gRefList.push_back(SmartCValueRef(this));
-#endif
-#endif
-}
-
-
-
-CValue::~CValue()
-/*
-pre:
-effect: deletes the object
-*/
-{
- ClearProperties();
-
- assertd (m_refcount==0);
-#ifdef CVALUE_DEBUG
- std::vector<SmartCValueRef>::iterator it;
- for (it=gRefList.begin(); it!=gRefList.end(); it++)
- {
- if (it->m_ref == this)
- {
- *it = gRefList.back();
- gRefList.pop_back();
- break;
- }
- }
-#endif
-}
-
-
-/* UNUSED */
-#if 0
-#define VALUE_SUB(val1, val2) (val1)->Calc(VALUE_SUB_OPERATOR, val2)
-#define VALUE_MUL(val1, val2) (val1)->Calc(VALUE_MUL_OPERATOR, val2)
-#define VALUE_DIV(val1, val2) (val1)->Calc(VALUE_DIV_OPERATOR, val2)
-#define VALUE_NEG(val1) (val1)->Calc(VALUE_NEG_OPERATOR, val1)
-#define VALUE_POS(val1) (val1)->Calc(VALUE_POS_OPERATOR, val1)
-#endif
-
-STR_String CValue::op2str(VALUE_OPERATOR op)
-{
- //pre:
- //ret: the stringrepresentation of operator op
-
- STR_String opmsg;
- switch (op) {
- case VALUE_MOD_OPERATOR:
- opmsg = " % ";
- break;
- case VALUE_ADD_OPERATOR:
- opmsg = " + ";
- break;
- case VALUE_SUB_OPERATOR:
- opmsg = " - ";
- break;
- case VALUE_MUL_OPERATOR:
- opmsg = " * ";
- break;
- case VALUE_DIV_OPERATOR:
- opmsg = " / ";
- break;
- case VALUE_NEG_OPERATOR:
- opmsg = " -";
- break;
- case VALUE_POS_OPERATOR:
- opmsg = " +";
- break;
- case VALUE_AND_OPERATOR:
- opmsg = " & ";
- break;
- case VALUE_OR_OPERATOR:
- opmsg = " | ";
- break;
- case VALUE_EQL_OPERATOR:
- opmsg = " = ";
- break;
- case VALUE_NEQ_OPERATOR:
- opmsg = " != ";
- break;
- case VALUE_NOT_OPERATOR:
- opmsg = " !";
- break;
- default:
- opmsg="Error in Errorhandling routine.";
- // AfxMessageBox("Invalid operator");
- break;
- }
- return opmsg;
-}
-
-
-
-
-
-//---------------------------------------------------------------------------------------------------------------------
-// Property Management
-//---------------------------------------------------------------------------------------------------------------------
-
-
-
-//
-// Set property <ioProperty>, overwrites and releases a previous property with the same name if needed
-//
-void CValue::SetProperty(const STR_String & name,CValue* ioProperty)
-{
- if (ioProperty==NULL)
- { // Check if somebody is setting an empty property
- trace("Warning:trying to set empty property!");
- return;
- }
-
- if (m_pNamedPropertyArray)
- { // Try to replace property (if so -> exit as soon as we replaced it)
- CValue* oldval = (*m_pNamedPropertyArray)[name];
- if (oldval)
- oldval->Release();
- }
- else { // Make sure we have a property array
- m_pNamedPropertyArray = new std::map<STR_String,CValue *>;
- }
-
- // Add property at end of array
- (*m_pNamedPropertyArray)[name] = ioProperty->AddRef();//->Add(ioProperty);
-}
-
-void CValue::SetProperty(const char* name,CValue* ioProperty)
-{
- if (ioProperty==NULL)
- { // Check if somebody is setting an empty property
- trace("Warning:trying to set empty property!");
- return;
- }
-
- if (m_pNamedPropertyArray)
- { // Try to replace property (if so -> exit as soon as we replaced it)
- CValue* oldval = (*m_pNamedPropertyArray)[name];
- if (oldval)
- oldval->Release();
- }
- else { // Make sure we have a property array
- m_pNamedPropertyArray = new std::map<STR_String,CValue *>;
- }
-
- // Add property at end of array
- (*m_pNamedPropertyArray)[name] = ioProperty->AddRef();//->Add(ioProperty);
-}
-
-//
-// Get pointer to a property with name <inName>, returns NULL if there is no property named <inName>
-//
-CValue* CValue::GetProperty(const STR_String & inName)
-{
- if (m_pNamedPropertyArray) {
- std::map<STR_String,CValue*>::iterator it = m_pNamedPropertyArray->find(inName);
- if (it != m_pNamedPropertyArray->end())
- return (*it).second;
- }
- return NULL;
-}
-
-CValue* CValue::GetProperty(const char *inName)
-{
- if (m_pNamedPropertyArray) {
- std::map<STR_String,CValue*>::iterator it = m_pNamedPropertyArray->find(inName);
- if (it != m_pNamedPropertyArray->end())
- return (*it).second;
- }
- return NULL;
-}
-
-//
-// Get text description of property with name <inName>, returns an empty string if there is no property named <inName>
-//
-const STR_String& CValue::GetPropertyText(const STR_String & inName)
-{
- const static STR_String sEmpty("");
-
- CValue *property = GetProperty(inName);
- if (property)
- return property->GetText();
- else
- return sEmpty;
-}
-
-float CValue::GetPropertyNumber(const STR_String& inName,float defnumber)
-{
- CValue *property = GetProperty(inName);
- if (property)
- return property->GetNumber();
- else
- return defnumber;
-}
-
-
-
-//
-// Remove the property named <inName>, returns true if the property was succesfully removed, false if property was not found or could not be removed
-//
-bool CValue::RemoveProperty(const char *inName)
-{
- // Check if there are properties at all which can be removed
- if (m_pNamedPropertyArray)
- {
- std::map<STR_String,CValue*>::iterator it = m_pNamedPropertyArray->find(inName);
- if (it != m_pNamedPropertyArray->end())
- {
- ((*it).second)->Release();
- m_pNamedPropertyArray->erase(it);
- return true;
- }
- }
-
- return false;
-}
-
-//
-// Get Property Names
-//
-vector<STR_String> CValue::GetPropertyNames()
-{
- vector<STR_String> result;
- if (!m_pNamedPropertyArray) return result;
- result.reserve(m_pNamedPropertyArray->size());
-
- std::map<STR_String,CValue*>::iterator it;
- for (it= m_pNamedPropertyArray->begin(); (it != m_pNamedPropertyArray->end()); it++)
- {
- result.push_back((*it).first);
- }
- return result;
-}
-
-//
-// Clear all properties
-//
-void CValue::ClearProperties()
-{
- // Check if we have any properties
- if (m_pNamedPropertyArray == NULL)
- return;
-
- // Remove all properties
- std::map<STR_String,CValue*>::iterator it;
- for (it= m_pNamedPropertyArray->begin();(it != m_pNamedPropertyArray->end()); it++)
- {
- CValue* tmpval = (*it).second;
- //STR_String name = (*it).first;
- tmpval->Release();
- }
-
- // Delete property array
- delete m_pNamedPropertyArray;
- m_pNamedPropertyArray=NULL;
-}
-
-
-
-//
-// Set all properties' modified flag to <inModified>
-//
-void CValue::SetPropertiesModified(bool inModified)
-{
- if (!m_pNamedPropertyArray) return;
- std::map<STR_String,CValue*>::iterator it;
-
- for (it= m_pNamedPropertyArray->begin();(it != m_pNamedPropertyArray->end()); it++)
- ((*it).second)->SetModified(inModified);
-}
-
-
-
-//
-// Check if any of the properties in this value have been modified
-//
-bool CValue::IsAnyPropertyModified()
-{
- if (!m_pNamedPropertyArray) return false;
- std::map<STR_String,CValue*>::iterator it;
-
- for (it= m_pNamedPropertyArray->begin();(it != m_pNamedPropertyArray->end()); it++)
- if (((*it).second)->IsModified())
- return true;
-
- return false;
-}
-
-
-
-//
-// Get property number <inIndex>
-//
-CValue* CValue::GetProperty(int inIndex)
-{
-
- int count=0;
- CValue* result = NULL;
-
- if (m_pNamedPropertyArray)
- {
- std::map<STR_String,CValue*>::iterator it;
- for (it= m_pNamedPropertyArray->begin(); (it != m_pNamedPropertyArray->end()); it++)
- {
- if (count++ == inIndex)
- {
- result = (*it).second;
- break;
- }
- }
-
- }
- return result;
-}
-
-
-
-//
-// Get the amount of properties assiocated with this value
-//
-int CValue::GetPropertyCount()
-{
- if (m_pNamedPropertyArray)
- return m_pNamedPropertyArray->size();
- else
- return 0;
-}
-
-
-double* CValue::GetVector3(bool bGetTransformedVec)
-{
- assertd(false); // don't get vector from me
- return m_sZeroVec;//::sZero;
-}
-
-
-/*---------------------------------------------------------------------------------------------------------------------
- Reference Counting
----------------------------------------------------------------------------------------------------------------------*/
-
-
-
-//
-// Release a reference to this value (when reference count reaches 0, the value is removed from the heap)
-//
-
-
-
-//
-// Disable reference counting for this value
-//
-void CValue::DisableRefCount()
-{
- assertd(m_refcount == 1);
- m_refcount--;
-
- //debug(gRefCountValue--);
-#ifdef DEBUG
- //gRefCountValue--;
-#endif
- m_ValFlags.RefCountDisabled=true;
-}
-
-
-
-void CValue::ProcessReplica() /* was AddDataToReplica in 2.48 */
-{
- m_refcount = 1;
-
-#ifdef DEBUG
- //gRefCountValue++;
-#endif
- PyObjectPlus::ProcessReplica();
-
- m_ValFlags.RefCountDisabled = false;
-
- /* copy all props */
- if (m_pNamedPropertyArray)
- {
- std::map<STR_String,CValue*> *pOldArray = m_pNamedPropertyArray;
- m_pNamedPropertyArray=NULL;
- std::map<STR_String,CValue*>::iterator it;
- for (it= pOldArray->begin(); (it != pOldArray->end()); it++)
- {
- CValue *val = (*it).second->GetReplica();
- SetProperty((*it).first,val);
- val->Release();
- }
- }
-}
-
-
-
-int CValue::GetValueType()
-{
- return VALUE_NO_TYPE;
-}
-
-
-
-CValue* CValue::FindIdentifier(const STR_String& identifiername)
-{
-
- CValue* result = NULL;
-
- int pos = 0;
- // if a dot exists, explode the name into pieces to get the subcontext
- if ((pos=identifiername.Find('.'))>=0)
- {
- const STR_String rightstring = identifiername.Right(identifiername.Length() -1 - pos);
- const STR_String leftstring = identifiername.Left(pos);
- CValue* tempresult = GetProperty(leftstring);
- if (tempresult)
- {
- result=tempresult->FindIdentifier(rightstring);
- }
- } else
- {
- result = GetProperty(identifiername);
- if (result)
- return result->AddRef();
- }
- if (!result)
- {
- // warning here !!!
- result = new CErrorValue(identifiername+" not found");
- }
- return result;
-}
-
-#ifdef WITH_PYTHON
-
-PyAttributeDef CValue::Attributes[] = {
- KX_PYATTRIBUTE_RO_FUNCTION("name", CValue, pyattr_get_name),
- { NULL } //Sentinel
-};
-
-PyObject *CValue::pyattr_get_name(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- CValue * self = static_cast<CValue *> (self_v);
- return PyUnicode_From_STR_String(self->GetName());
-}
-
-/**
- * There are 2 reasons this could return NULL
- * - unsupported type.
- * - error converting (overflow).
- *
- * \param do_type_exception Use to skip raising an exception for unknown types.
- */
-CValue *CValue::ConvertPythonToValue(PyObject *pyobj, const bool do_type_exception, const char *error_prefix)
-{
-
- CValue *vallie;
- /* refcounting is broking here! - this crashes anyway, just store a python list for KX_GameObject */
-#if 0
- if (PyList_Check(pyobj))
- {
- CListValue* listval = new CListValue();
- bool error = false;
-
- Py_ssize_t i;
- Py_ssize_t numitems = PyList_GET_SIZE(pyobj);
- for (i=0;i<numitems;i++)
- {
- PyObject *listitem = PyList_GET_ITEM(pyobj,i); /* borrowed ref */
- CValue* listitemval = ConvertPythonToValue(listitem, error_prefix);
- if (listitemval)
- {
- listval->Add(listitemval);
- } else
- {
- error = true;
- }
- }
- if (!error)
- {
- // jippie! could be converted
- vallie = listval;
- } else
- {
- // list could not be converted... bad luck
- listval->Release();
- }
-
- } else
-#endif
- /* note: Boolean check should go before Int check [#34677] */
- if (PyBool_Check(pyobj))
- {
- vallie = new CBoolValue( (bool)PyLong_AsLongLong(pyobj) );
- } else
- if (PyFloat_Check(pyobj))
- {
- const double tval = PyFloat_AsDouble(pyobj);
- if (tval > (double)FLT_MAX || tval < (double)-FLT_MAX) {
- PyErr_Format(PyExc_OverflowError, "%soverflow converting from float, out of internal range", error_prefix);
- vallie = NULL;
- }
- else {
- vallie = new CFloatValue((float)tval);
- }
- } else
- if (PyLong_Check(pyobj))
- {
- vallie = new CIntValue( (cInt)PyLong_AsLongLong(pyobj) );
- } else
- if (PyUnicode_Check(pyobj))
- {
- vallie = new CStringValue(_PyUnicode_AsString(pyobj),"");
- } else
- if (PyObject_TypeCheck(pyobj, &CValue::Type)) /* Note, don't let these get assigned to GameObject props, must check elsewhere */
- {
- vallie = (static_cast<CValue *>(BGE_PROXY_REF(pyobj)))->AddRef();
- }
- else {
- if (do_type_exception) {
- /* return an error value from the caller */
- PyErr_Format(PyExc_TypeError, "%scould convert python value to a game engine property", error_prefix);
- }
- vallie = NULL;
- }
- return vallie;
-
-}
-
-PyObject *CValue::ConvertKeysToPython(void)
-{
- if (m_pNamedPropertyArray)
- {
- PyObject *pylist= PyList_New(m_pNamedPropertyArray->size());
- Py_ssize_t i= 0;
-
- std::map<STR_String,CValue*>::iterator it;
- for (it= m_pNamedPropertyArray->begin(); (it != m_pNamedPropertyArray->end()); it++)
- {
- PyList_SET_ITEM(pylist, i++, PyUnicode_From_STR_String((*it).first));
- }
-
- return pylist;
- }
- else {
- return PyList_New(0);
- }
-}
-
-#endif // WITH_PYTHON
-
-
-///////////////////////////////////////////////////////////////////////////////////////////////
-///////////////////////////////////////////////////////////////////////////////////////////////
-/* These implementations were moved out of the header */
-
-void CValue::SetOwnerExpression(class CExpression* expr)
-{
- /* intentionally empty */
-}
-
-void CValue::SetColorOperator(VALUE_OPERATOR op)
-{
- /* intentionally empty */
-}
-void CValue::SetValue(CValue* newval)
-{
- // no one should get here
- assertd(newval->GetNumber() == 10121969);
-}
diff --git a/source/gameengine/Expressions/intern/VectorValue.cpp b/source/gameengine/Expressions/intern/VectorValue.cpp
deleted file mode 100644
index a3d44116317..00000000000
--- a/source/gameengine/Expressions/intern/VectorValue.cpp
+++ /dev/null
@@ -1,225 +0,0 @@
-/** \file gameengine/Expressions/VectorValue.cpp
- * \ingroup expressions
- */
-// VectorValue.cpp: implementation of the CVectorValue class.
-/*
- * Copyright (c) 1996-2000 Erwin Coumans <coockie@acm.org>
- *
- * Permission to use, copy, modify, distribute and sell this software
- * and its documentation for any purpose is hereby granted without fee,
- * provided that the above copyright notice appear in all copies and
- * that both that copyright notice and this permission notice appear
- * in supporting documentation. Erwin Coumans makes no
- * representations about the suitability of this software for any
- * purpose. It is provided "as is" without express or implied warranty.
- *
- */
-
-#ifdef _MSC_VER
-# pragma warning (disable:4786)
-#endif
-
-#include "EXP_Value.h"
-#include "EXP_VectorValue.h"
-#include "EXP_ErrorValue.h"
-//#include "MatrixValue.h"
-#include "EXP_VoidValue.h"
-#include "EXP_StringValue.h"
-//#include "FactoryManager.h"
-
-
-
-//////////////////////////////////////////////////////////////////////
-// Construction/Destruction
-//////////////////////////////////////////////////////////////////////
-
-CVectorValue::CVectorValue(float x,float y,float z, AllocationTYPE alloctype)
-{
- SetCustomFlag1(false);//FancyOutput=false;
-
- if (alloctype == STACKVALUE)
- {
- CValue::DisableRefCount();
- };
-
- m_vec[KX_X] = m_transformedvec[KX_X] = x;
- m_vec[KX_Y] = m_transformedvec[KX_Y] = y;
- m_vec[KX_Z] = m_transformedvec[KX_Z] = z;
-
-}
-CVectorValue::CVectorValue(double vec[3], const char *name,AllocationTYPE alloctype)
-{
-
- SetCustomFlag1(false);//FancyOutput=false;
-
- m_vec[KX_X] = m_transformedvec[KX_X] = vec[KX_X];
- m_vec[KX_Y] = m_transformedvec[KX_Y] = vec[KX_Y];
- m_vec[KX_Z] = m_transformedvec[KX_Z] = vec[KX_Z];
-
- if (alloctype == STACKVALUE)
- {
- CValue::DisableRefCount();
-
- }
-
- SetName(name);
-}
-
-CVectorValue::CVectorValue(double vec[3], AllocationTYPE alloctype)
-{
-
- SetCustomFlag1(false);//FancyOutput=false;
-
- m_vec[KX_X] = m_transformedvec[KX_X] = vec[KX_X];
- m_vec[KX_Y] = m_transformedvec[KX_Y] = vec[KX_Y];
- m_vec[KX_Z] = m_transformedvec[KX_Z] = vec[KX_Z];
-
- if (alloctype == STACKVALUE)
- {
- CValue::DisableRefCount();
-
- }
-
-
-}
-CVectorValue::~CVectorValue()
-{
-
-}
-
-/**
- * pre: the type of val is dtype
- * ret: a new object containing the result of applying operator op to val and
- * this object
- */
-CValue* CVectorValue::CalcFinal(VALUE_DATA_TYPE dtype, VALUE_OPERATOR op, CValue *val)
-{
- CValue *ret = NULL;
-
- switch (op) {
- case VALUE_ADD_OPERATOR:
- {
- switch (dtype)
- {
- case VALUE_EMPTY_TYPE:
- case VALUE_VECTOR_TYPE:
- {
- ret = new CVectorValue(
- val->GetVector3()[KX_X] + GetVector3()[KX_X],
- val->GetVector3()[KX_Y] + GetVector3()[KX_Y],
- val->GetVector3()[KX_Z] + GetVector3()[KX_Z],
- CValue::HEAPVALUE);
- ret->SetName(GetName());
- break;
- }
-
- default:
- ret = new CErrorValue(val->GetText() + op2str(op) + GetText());
- }
- break;
- }
- case VALUE_MUL_OPERATOR:
- {
- switch (dtype)
- {
-
- case VALUE_EMPTY_TYPE:
- case VALUE_VECTOR_TYPE:
- {
- //MT_Vector3 supports 'scaling' by another vector, instead of using general transform, Gino?
- //ret = new CVectorValue(val->GetVector3().Scaled(GetVector3()),GetName());
- break;
- }
- case VALUE_FLOAT_TYPE:
- {
- ret = new CVectorValue(
- val->GetVector3()[KX_X] * GetVector3()[KX_X],
- val->GetVector3()[KX_Y] * GetVector3()[KX_Y],
- val->GetVector3()[KX_Z] * GetVector3()[KX_Z],
- CValue::HEAPVALUE);
- ret->SetName(GetName());
- break;
- }
-
- default:
- ret = new CErrorValue(val->GetText() + op2str(op) + GetText());
- }
- break;
-
- }
-
- default:
- ret = new CErrorValue(val->GetText() + op2str(op) + GetText());
- }
-
-
- return ret;
-}
-
-double CVectorValue::GetNumber()
-{
- return m_vec[KX_X];
-}
-
-
-
-int CVectorValue::GetValueType()
-{
- return VALUE_VECTOR_TYPE;
-}
-
-
-
-double* CVectorValue::GetVector3(bool bGetTransformedVec)
-{
- if (bGetTransformedVec)
- return m_transformedvec;
- // else
- return m_vec;
-}
-
-
-
-
-
-void CVectorValue::SetVector(double newvec[])
-{
- m_vec[KX_X] = m_transformedvec[KX_X] = newvec[KX_X];
- m_vec[KX_Y] = m_transformedvec[KX_Y] = newvec[KX_Y];
- m_vec[KX_Z] = m_transformedvec[KX_Z] = newvec[KX_Z];
-
- SetModified(true);
-}
-
-
-void CVectorValue::SetValue(CValue *newval)
-{
-
- double* newvec = ((CVectorValue*)newval)->GetVector3();
- m_vec[KX_X] = m_transformedvec[KX_X] = newvec[KX_X];
- m_vec[KX_Y] = m_transformedvec[KX_Y] = newvec[KX_Y];
- m_vec[KX_Z] = m_transformedvec[KX_Z] = newvec[KX_Z];
-
- SetModified(true);
-}
-
-static const STR_String gstrVectorStr=STR_String();
-const STR_String & CVectorValue::GetText()
-{
- assertd(false);
- return gstrVectorStr;
-}
-
-CValue* CVectorValue::GetReplica()
-{
- CVectorValue* replica = new CVectorValue(*this);
- replica->ProcessReplica();
- return replica;
-};
-
-#if 0
-void CVectorValue::Transform(rcMatrix4x4 mat)
-{
- m_transformedvec = mat*m_vec;
-}
-#endif
diff --git a/source/gameengine/GameLogic/CMakeLists.txt b/source/gameengine/GameLogic/CMakeLists.txt
deleted file mode 100644
index b9eec74f6f4..00000000000
--- a/source/gameengine/GameLogic/CMakeLists.txt
+++ /dev/null
@@ -1,147 +0,0 @@
-# ***** BEGIN GPL LICENSE BLOCK *****
-#
-# This program is free software; you can redistribute it and/or
-# modify it under the terms of the GNU General Public License
-# as published by the Free Software Foundation; either version 2
-# of the License, or (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software Foundation,
-# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
-#
-# The Original Code is Copyright (C) 2006, Blender Foundation
-# All rights reserved.
-#
-# The Original Code is: all of this file.
-#
-# Contributor(s): Jacques Beaurain.
-#
-# ***** END GPL LICENSE BLOCK *****
-
-set(INC
- .
- ../Expressions
- ../Rasterizer
- ../SceneGraph
- ../../blender/blenlib
- ../../../intern/container
- ../../../intern/string
- ../../../intern/ghost
-)
-
-set(INC_SYS
- ../../../intern/moto/include
-)
-
-set(SRC
- SCA_2DFilterActuator.cpp
- SCA_ANDController.cpp
- SCA_ActuatorEventManager.cpp
- SCA_ActuatorSensor.cpp
- SCA_AlwaysEventManager.cpp
- SCA_AlwaysSensor.cpp
- SCA_BasicEventManager.cpp
- SCA_DelaySensor.cpp
- SCA_EventManager.cpp
- SCA_ExpressionController.cpp
- SCA_IActuator.cpp
- SCA_IController.cpp
- SCA_IInputDevice.cpp
- SCA_ILogicBrick.cpp
- SCA_IObject.cpp
- SCA_IScene.cpp
- SCA_ISensor.cpp
- SCA_JoystickManager.cpp
- SCA_JoystickSensor.cpp
- SCA_KeyboardManager.cpp
- SCA_KeyboardSensor.cpp
- SCA_LogicManager.cpp
- SCA_MouseManager.cpp
- SCA_MouseSensor.cpp
- SCA_NANDController.cpp
- SCA_NORController.cpp
- SCA_ORController.cpp
- SCA_PropertyActuator.cpp
- SCA_PropertyEventManager.cpp
- SCA_PropertySensor.cpp
- SCA_PythonController.cpp
- SCA_PythonJoystick.cpp
- SCA_PythonKeyboard.cpp
- SCA_PythonMouse.cpp
- SCA_RandomActuator.cpp
- SCA_RandomEventManager.cpp
- SCA_RandomNumberGenerator.cpp
- SCA_RandomSensor.cpp
- SCA_TimeEventManager.cpp
- SCA_XNORController.cpp
- SCA_XORController.cpp
- Joystick/SCA_Joystick.cpp
- Joystick/SCA_JoystickEvents.cpp
-
- SCA_2DFilterActuator.h
- SCA_ANDController.h
- SCA_ActuatorEventManager.h
- SCA_ActuatorSensor.h
- SCA_AlwaysEventManager.h
- SCA_AlwaysSensor.h
- SCA_BasicEventManager.h
- SCA_DelaySensor.h
- SCA_EventManager.h
- SCA_ExpressionController.h
- SCA_IActuator.h
- SCA_IController.h
- SCA_IInputDevice.h
- SCA_ILogicBrick.h
- SCA_IObject.h
- SCA_IScene.h
- SCA_ISensor.h
- SCA_JoystickManager.h
- SCA_JoystickSensor.h
- SCA_KeyboardManager.h
- SCA_KeyboardSensor.h
- SCA_LogicManager.h
- SCA_MouseManager.h
- SCA_MouseSensor.h
- SCA_NANDController.h
- SCA_NORController.h
- SCA_ORController.h
- SCA_PropertyActuator.h
- SCA_PropertyEventManager.h
- SCA_PropertySensor.h
- SCA_PythonController.h
- SCA_PythonJoystick.h
- SCA_PythonKeyboard.h
- SCA_PythonMouse.h
- SCA_RandomActuator.h
- SCA_RandomEventManager.h
- SCA_RandomNumberGenerator.h
- SCA_RandomSensor.h
- SCA_TimeEventManager.h
- SCA_XNORController.h
- SCA_XORController.h
- Joystick/SCA_Joystick.h
- Joystick/SCA_JoystickDefines.h
- Joystick/SCA_JoystickPrivate.h
-)
-
-if(WITH_SDL)
- list(APPEND INC_SYS
- ${SDL_INCLUDE_DIR}
- )
-
- add_definitions(-DWITH_SDL)
-
- if(WITH_GHOST_SDL)
- add_definitions(-DWITH_GHOST_SDL)
- endif()
- if(WITH_SDL_DYNLOAD)
- add_definitions(-DWITH_SDL_DYNLOAD)
- endif()
-endif()
-
-blender_add_lib(ge_logic "${SRC}" "${INC}" "${INC_SYS}")
diff --git a/source/gameengine/GameLogic/Joystick/SCA_Joystick.cpp b/source/gameengine/GameLogic/Joystick/SCA_Joystick.cpp
deleted file mode 100644
index 9f532527a80..00000000000
--- a/source/gameengine/GameLogic/Joystick/SCA_Joystick.cpp
+++ /dev/null
@@ -1,382 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): snailrose.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/GameLogic/Joystick/SCA_Joystick.cpp
- * \ingroup gamelogic
- */
-
-#include <stdio.h>
-#include <stdlib.h>
-
-#include "SCA_Joystick.h"
-#include "SCA_JoystickPrivate.h"
-
-#include "BLI_path_util.h"
-
-#ifdef WITH_SDL
-# ifdef WITH_SDL_DYNLOAD
-# define SDL_CHECK(x) ((x) != (void *)0)
-# else
-# define SDL_CHECK(x) true
-# endif
-#endif
-
-SCA_Joystick::SCA_Joystick(short int index)
- :
- m_joyindex(index),
- m_prec(3200),
- m_axismax(-1),
- m_buttonmax(-1),
- m_hatmax(-1),
- m_isinit(0),
- m_istrig_axis(0),
- m_istrig_button(0),
- m_istrig_hat(0)
-{
- for (int i=0; i < JOYAXIS_MAX; i++)
- m_axis_array[i] = 0;
-
- for (int i=0; i < JOYHAT_MAX; i++)
- m_hat_array[i] = 0;
-
-#ifdef WITH_SDL
- m_private = new PrivateData();
-#endif
-}
-
-
-SCA_Joystick::~SCA_Joystick()
-
-{
-#ifdef WITH_SDL
- delete m_private;
-#endif
-}
-
-SCA_Joystick *SCA_Joystick::m_instance[JOYINDEX_MAX];
-int SCA_Joystick::m_joynum = 0;
-int SCA_Joystick::m_refCount = 0;
-
-SCA_Joystick *SCA_Joystick::GetInstance( short int joyindex )
-{
-#ifndef WITH_SDL
- return NULL;
-#else /* WITH_SDL */
- if (!SDL_CHECK(SDL_InitSubSystem)) {
- return NULL;
- }
- if (joyindex < 0 || joyindex >= JOYINDEX_MAX) {
- JOYSTICK_ECHO("Error-invalid joystick index: " << joyindex);
- return NULL;
- }
-
- if (m_refCount == 0)
- {
- int i;
-
- /* The video subsystem is required for joystick input to work. However,
- * when GHOST is running under SDL, video is initialized elsewhere. We
- * also need to set the videodriver to dummy, and do it here to avoid
- * interfering with addons that may use SDL too.
- *
- * We also init SDL once only. */
-# ifdef WITH_GHOST_SDL
- int success = (SDL_InitSubSystem(SDL_INIT_JOYSTICK) != -1 );
-# else
- /* set and restore environment variable */
- char *videodriver = getenv("SDL_VIDEODRIVER");
- BLI_setenv("SDL_VIDEODRIVER", "dummy");
-
-#if SDL_VERSION_ATLEAST(2, 0, 0)
- int success = (SDL_InitSubSystem(SDL_INIT_JOYSTICK) != -1 );
-#else
- int success = (SDL_InitSubSystem(SDL_INIT_JOYSTICK | SDL_INIT_VIDEO) != -1 );
-#endif
-
- BLI_setenv("SDL_VIDEODRIVER", videodriver);
-# endif
-
- if (!success) {
- JOYSTICK_ECHO("Error-Initializing-SDL: " << SDL_GetError());
- return NULL;
- }
-
- m_joynum = SDL_NumJoysticks();
-
- for (i = 0; i < m_joynum; i++) {
- m_instance[i] = new SCA_Joystick(i);
- m_instance[i]->CreateJoystickDevice();
- }
- m_refCount = 1;
- }
- else
- {
- m_refCount++;
- }
- return m_instance[joyindex];
-#endif /* WITH_SDL */
-}
-
-void SCA_Joystick::ReleaseInstance()
-{
- if (--m_refCount == 0)
- {
-#ifdef WITH_SDL
- if (!SDL_CHECK(SDL_QuitSubSystem)) {
- return;
- }
- for (int i = 0; i < m_joynum; i++) {
- if (m_instance[i]) {
- m_instance[i]->DestroyJoystickDevice();
- delete m_instance[i];
- }
- m_instance[i] = NULL;
- }
-
- /* The video subsystem is required for joystick input to work. However,
- * when GHOST is running under SDL, video is freed elsewhere.
- * Do this once only. */
-#if SDL_VERSION_ATLEAST(2, 0, 0)
- SDL_QuitSubSystem(SDL_INIT_JOYSTICK);
-#else
- SDL_QuitSubSystem(SDL_INIT_JOYSTICK | SDL_INIT_VIDEO);
-#endif
-#endif /* WITH_SDL */
- }
-}
-
-void SCA_Joystick::cSetPrecision(int val)
-{
- m_prec = val;
-}
-
-
-bool SCA_Joystick::aAxisPairIsPositive(int axis)
-{
- return (pAxisTest(axis) > m_prec) ? true:false;
-}
-
-bool SCA_Joystick::aAxisPairDirectionIsPositive(int axis, int dir)
-{
-
- int res;
-
- if (dir==JOYAXIS_UP || dir==JOYAXIS_DOWN)
- res = pGetAxis(axis, 1);
- else /* JOYAXIS_LEFT || JOYAXIS_RIGHT */
- res = pGetAxis(axis, 0);
-
- if (dir==JOYAXIS_DOWN || dir==JOYAXIS_RIGHT)
- return (res > m_prec) ? true : false;
- else /* JOYAXIS_UP || JOYAXIS_LEFT */
- return (res < -m_prec) ? true : false;
-}
-
-bool SCA_Joystick::aAxisIsPositive(int axis_single)
-{
- return abs(m_axis_array[axis_single]) > m_prec ? true:false;
-}
-
-bool SCA_Joystick::aAnyButtonPressIsPositive(void)
-{
-#ifdef WITH_SDL
- if (!SDL_CHECK(SDL_JoystickGetButton)) {
- return false;
- }
- /* this is needed for the "all events" option
- * so we know if there are no buttons pressed */
- for (int i=0; i<m_buttonmax; i++)
- if (SDL_JoystickGetButton(m_private->m_joystick, i))
- return true;
-#endif
- return false;
-}
-
-bool SCA_Joystick::aButtonPressIsPositive(int button)
-{
-#ifndef WITH_SDL
- return false;
-#else
- bool result;
- result = SDL_CHECK(SDL_JoystickGetButton) && SDL_JoystickGetButton(m_private->m_joystick, button);
- return result;
-#endif
-}
-
-
-bool SCA_Joystick::aButtonReleaseIsPositive(int button)
-{
-#ifndef WITH_SDL
- return false;
-#else
- bool result;
- result = !(SDL_CHECK(SDL_JoystickGetButton) && SDL_JoystickGetButton(m_private->m_joystick, button));
- return result;
-#endif
-}
-
-
-bool SCA_Joystick::aHatIsPositive(int hatnum, int dir)
-{
- return (GetHat(hatnum)==dir) ? true : false;
-}
-
-int SCA_Joystick::GetNumberOfAxes()
-{
- return m_axismax;
-}
-
-
-int SCA_Joystick::GetNumberOfButtons()
-{
- return m_buttonmax;
-}
-
-
-int SCA_Joystick::GetNumberOfHats()
-{
- return m_hatmax;
-}
-
-bool SCA_Joystick::CreateJoystickDevice(void)
-{
-#ifndef WITH_SDL
- m_isinit = true;
- m_axismax = m_buttonmax = m_hatmax = 0;
- return false;
-#else /* WITH_SDL */
- if (m_isinit == false && SDL_CHECK(SDL_JoystickOpen)) {
- if (m_joyindex>=m_joynum) {
- /* don't print a message, because this is done anyway */
- //JOYSTICK_ECHO("Joystick-Error: " << SDL_NumJoysticks() << " avaiable joystick(s)");
-
- /* Need this so python args can return empty lists */
- m_axismax = m_buttonmax = m_hatmax = 0;
- return false;
- }
-
- m_private->m_joystick = SDL_JoystickOpen(m_joyindex);
- SDL_JoystickEventState(SDL_ENABLE);
- m_isinit = true;
-
- JOYSTICK_ECHO("Joystick " << m_joyindex << " initialized");
-
- /* must run after being initialized */
- m_axismax = SDL_JoystickNumAxes(m_private->m_joystick);
- m_buttonmax = SDL_JoystickNumButtons(m_private->m_joystick);
- m_hatmax = SDL_JoystickNumHats(m_private->m_joystick);
-
- if (m_axismax > JOYAXIS_MAX) m_axismax = JOYAXIS_MAX; /* very unlikely */
- else if (m_axismax < 0) m_axismax = 0;
-
- if (m_hatmax > JOYHAT_MAX) m_hatmax = JOYHAT_MAX; /* very unlikely */
- else if (m_hatmax < 0) m_hatmax = 0;
-
- if (m_buttonmax < 0) m_buttonmax = 0;
-
- }
- return true;
-#endif /* WITH_SDL */
-}
-
-
-void SCA_Joystick::DestroyJoystickDevice(void)
-{
-#ifdef WITH_SDL
- if (m_isinit) {
-#if SDL_VERSION_ATLEAST(2, 0, 0)
- if (SDL_CHECK(SDL_JoystickGetAttached) && SDL_JoystickGetAttached(m_private->m_joystick))
-#else
- if (SDL_CHECK(SDL_JoystickOpened) && SDL_JoystickOpened(m_joyindex))
-#endif
- {
- JOYSTICK_ECHO("Closing-joystick " << m_joyindex);
- SDL_JoystickClose(m_private->m_joystick);
- }
- m_isinit = false;
- }
-#endif /* WITH_SDL */
-}
-
-int SCA_Joystick::Connected(void)
-{
-#ifdef WITH_SDL
- if (m_isinit &&
-#if SDL_VERSION_ATLEAST(2, 0, 0)
- SDL_CHECK(SDL_JoystickGetAttached) && SDL_JoystickGetAttached(m_private->m_joystick)
-#else
- SDL_CHECK(SDL_JoystickOpened) && SDL_JoystickOpened(m_joyindex)
-#endif
- )
- {
- return 1;
- }
-#endif
- return 0;
-}
-
-int SCA_Joystick::pGetAxis(int axisnum, int udlr)
-{
-#ifdef WITH_SDL
- return m_axis_array[(axisnum*2)+udlr];
-#endif
- return 0;
-}
-
-int SCA_Joystick::pAxisTest(int axisnum)
-{
-#ifdef WITH_SDL
- /* Use ints instead of shorts here to avoid problems when we get -32768.
- * When we take the negative of that later, we should get 32768, which is greater
- * than what a short can hold. In other words, abs(MIN_SHORT) > MAX_SHRT. */
- int i1 = m_axis_array[(axisnum * 2)];
- int i2 = m_axis_array[(axisnum * 2) + 1];
-
- /* long winded way to do:
- * return max_ff(absf(i1), absf(i2))
- * ...avoid abs from math.h */
- if (i1 < 0) i1 = -i1;
- if (i2 < 0) i2 = -i2;
- if (i1 <i2) return i2;
- else return i1;
-#else /* WITH_SDL */
- return 0;
-#endif /* WITH_SDL */
-}
-
-const char *SCA_Joystick::GetName()
-{
-#ifdef WITH_SDL
-#if SDL_VERSION_ATLEAST(2, 0, 0)
- return (SDL_CHECK(SDL_JoystickName)) ? SDL_JoystickName(m_private->m_joystick) : "";
-#else
- return (SDL_CHECK(SDL_JoystickName)) ? SDL_JoystickName(m_joyindex) : "";
-#endif
-#else /* WITH_SDL */
- return "";
-#endif /* WITH_SDL */
-}
diff --git a/source/gameengine/GameLogic/Joystick/SCA_Joystick.h b/source/gameengine/GameLogic/Joystick/SCA_Joystick.h
deleted file mode 100644
index c9221753d45..00000000000
--- a/source/gameengine/GameLogic/Joystick/SCA_Joystick.h
+++ /dev/null
@@ -1,214 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): snailrose.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file SCA_Joystick.h
- * \ingroup gamelogic
- */
-
-#ifndef __SCA_JOYSTICK_H__
-#define __SCA_JOYSTICK_H__
-
-#include "SCA_JoystickDefines.h"
-#ifdef WITH_SDL
-/* SDL force defines __SSE__ and __SSE2__ flags, which generates warnings
- * because we pass those defines via command line as well. For until there's
- * proper ifndef added to SDL headers we ignore the redefinition warning.
- */
-# ifdef _MSC_VER
-# pragma warning(push)
-# pragma warning(disable : 4005)
-# endif
-# include "SDL.h"
-# ifdef _MSC_VER
-# pragma warning(pop)
-# endif
-#endif
-
-/**
- * Basic Joystick class
- * I will make this class a singleton because there should be only one joystick
- * even if there are more than one scene using it and count how many scene are using it.
- * The underlying joystick should only be removed when the last scene is removed
- */
-
-class SCA_Joystick
-
-{
- static SCA_Joystick *m_instance[JOYINDEX_MAX];
- static int m_joynum;
- static int m_refCount;
-
- class PrivateData;
-#ifdef WITH_SDL
- PrivateData *m_private;
-#endif
- int m_joyindex;
-
- /**
- *support for JOYAXIS_MAX axes (in pairs)
- */
- int m_axis_array[JOYAXIS_MAX];
-
- /**
- *support for JOYHAT_MAX hats (each is a direction)
- */
- int m_hat_array[JOYHAT_MAX];
-
- /**
- * Precision or range of the axes
- */
- int m_prec;
-
- /**
- * max # of buttons avail
- */
-
- int m_axismax;
- int m_buttonmax;
- int m_hatmax;
-
- /** is the joystick initialized ?*/
- bool m_isinit;
-
-
- /** is triggered for each event type */
- bool m_istrig_axis;
- bool m_istrig_button;
- bool m_istrig_hat;
-
-#ifdef WITH_SDL
- /**
- * event callbacks
- */
- void OnAxisMotion(SDL_Event *sdl_event);
- void OnHatMotion(SDL_Event *sdl_event);
- void OnButtonUp(SDL_Event *sdl_event);
- void OnButtonDown(SDL_Event *sdl_event);
- void OnNothing(SDL_Event *sdl_event);
-#if 0 /* not used yet */
- void OnBallMotion(SDL_Event *sdl_event) {}
-#endif
-
-#endif /* WITH_SDL */
- /**
- * Open the joystick
- */
- bool CreateJoystickDevice(void);
-
- /**
- * Close the joystick
- */
- void DestroyJoystickDevice(void);
-
- /**
- * fills the axis member values
- */
- void pFillButtons(void);
-
- /**
- * returns m_axis_array
- */
-
- int pAxisTest(int axisnum);
- /**
- * returns m_axis_array
- */
- int pGetAxis(int axisnum, int udlr);
-
- SCA_Joystick(short int index);
-
- ~SCA_Joystick();
-
-public:
-
- static SCA_Joystick *GetInstance(short int joyindex);
- static void HandleEvents(void);
- void ReleaseInstance();
-
-
- /*
- */
- bool aAxisPairIsPositive(int axis);
- bool aAxisPairDirectionIsPositive(int axis, int dir); /* function assumes joysticks are in axis pairs */
- bool aAxisIsPositive(int axis_single); /* check a single axis only */
-
- bool aAnyButtonPressIsPositive(void);
- bool aButtonPressIsPositive(int button);
- bool aButtonReleaseIsPositive(int button);
- bool aHatIsPositive(int hatnum, int dir);
-
- /**
- * precision is default '3200' which is overridden by input
- */
-
- void cSetPrecision(int val);
-
- int GetAxisPosition(int index) {
- return m_axis_array[index];
- }
-
- int GetHat(int index) {
- return m_hat_array[index];
- }
-
- int GetThreshold(void) {
- return m_prec;
- }
-
- bool IsTrigAxis(void) {
- return m_istrig_axis;
- }
-
- bool IsTrigButton(void) {
- return m_istrig_button;
- }
-
- bool IsTrigHat(void) {
- return m_istrig_hat;
- }
-
- /**
- * returns the # of...
- */
-
- int GetNumberOfAxes(void);
- int GetNumberOfButtons(void);
- int GetNumberOfHats(void);
-
- /**
- * Test if the joystick is connected
- */
- int Connected(void);
-
- /**
- * Name of the joytsick
- */
- const char *GetName();
-};
-
-#endif
-
diff --git a/source/gameengine/GameLogic/Joystick/SCA_JoystickDefines.h b/source/gameengine/GameLogic/Joystick/SCA_JoystickDefines.h
deleted file mode 100644
index 566e5567507..00000000000
--- a/source/gameengine/GameLogic/Joystick/SCA_JoystickDefines.h
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): snailrose.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file SCA_JoystickDefines.h
- * \ingroup gamelogic
- */
-
-#ifndef __SCA_JOYSTICKDEFINES_H__
-#define __SCA_JOYSTICKDEFINES_H__
-
-#ifdef main
-#undef main
-#endif
-
-#ifndef DEBUG
-# define JOYSTICK_ECHO(x)
-#else
-# include <iostream>
-# define JOYSTICK_ECHO(x) std::cout << x << std::endl;
-#endif
-
-#define JOYINDEX_MAX 8
-#define JOYAXIS_MAX 16
-#define JOYBUT_MAX 18
-#define JOYHAT_MAX 4
-
-#define JOYAXIS_RIGHT 0
-#define JOYAXIS_UP 1
-#define JOYAXIS_DOWN 3
-#define JOYAXIS_LEFT 2
-
-#endif
diff --git a/source/gameengine/GameLogic/Joystick/SCA_JoystickEvents.cpp b/source/gameengine/GameLogic/Joystick/SCA_JoystickEvents.cpp
deleted file mode 100644
index 1dee1de9de2..00000000000
--- a/source/gameengine/GameLogic/Joystick/SCA_JoystickEvents.cpp
+++ /dev/null
@@ -1,137 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): snailrose.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/GameLogic/Joystick/SCA_JoystickEvents.cpp
- * \ingroup gamelogic
- */
-
-#include "SCA_Joystick.h"
-#include "SCA_JoystickPrivate.h"
-
-#ifdef _MSC_VER
-# include <cstdio> /* printf */
-#endif
-
-#ifdef WITH_SDL
-void SCA_Joystick::OnAxisMotion(SDL_Event* sdl_event)
-{
- if (sdl_event->jaxis.axis >= JOYAXIS_MAX)
- return;
-
- m_axis_array[sdl_event->jaxis.axis] = sdl_event->jaxis.value;
- m_istrig_axis = 1;
-}
-
-/* See notes below in the event loop */
-void SCA_Joystick::OnHatMotion(SDL_Event* sdl_event)
-{
- if (sdl_event->jhat.hat >= JOYHAT_MAX)
- return;
-
- m_hat_array[sdl_event->jhat.hat] = sdl_event->jhat.value;
- m_istrig_hat = 1;
-}
-
-/* See notes below in the event loop */
-void SCA_Joystick::OnButtonUp(SDL_Event* sdl_event)
-{
- m_istrig_button = 1;
-}
-
-
-void SCA_Joystick::OnButtonDown(SDL_Event* sdl_event)
-{
- //if (sdl_event->jbutton.button > m_buttonmax) /* unsigned int so always above 0 */
- // return;
- // sdl_event->jbutton.button;
-
- m_istrig_button = 1;
-}
-
-
-void SCA_Joystick::OnNothing(SDL_Event* sdl_event)
-{
- m_istrig_axis = m_istrig_button = m_istrig_hat = 0;
-}
-
-void SCA_Joystick::HandleEvents(void)
-{
- SDL_Event sdl_event;
-
-#ifdef WITH_SDL_DYNLOAD
- if (SDL_PollEvent == (void*)0) {
- return;
- }
-#endif
-
- int i;
- for (i=0; i<m_joynum; i++) { /* could use JOYINDEX_MAX but no reason to */
- if (SCA_Joystick::m_instance[i])
- SCA_Joystick::m_instance[i]->OnNothing(&sdl_event);
- }
-
- while (SDL_PollEvent(&sdl_event)) {
- /* Note! m_instance[sdl_event.jaxis.which]
- * will segfault if over JOYINDEX_MAX, not too nice but what are the chances? */
-
- /* Note!, with buttons, this wont care which button is pressed,
- * only to set 'm_istrig_button', actual pressed buttons are detected by SDL_JoystickGetButton */
-
- /* Note!, if you manage to press and release a button within 1 logic tick
- * it wont work as it should */
-
- switch (sdl_event.type) {
- case SDL_JOYAXISMOTION:
- SCA_Joystick::m_instance[sdl_event.jaxis.which]->OnAxisMotion(&sdl_event);
- break;
- case SDL_JOYHATMOTION:
- SCA_Joystick::m_instance[sdl_event.jhat.which]->OnHatMotion(&sdl_event);
- break;
- case SDL_JOYBUTTONUP:
- SCA_Joystick::m_instance[sdl_event.jbutton.which]->OnButtonUp(&sdl_event);
- break;
- case SDL_JOYBUTTONDOWN:
- SCA_Joystick::m_instance[sdl_event.jbutton.which]->OnButtonDown(&sdl_event);
- break;
-#if 0 /* Not used yet */
- case SDL_JOYBALLMOTION:
- SCA_Joystick::m_instance[sdl_event.jball.which]->OnBallMotion(&sdl_event);
- break;
-#endif
-#if SDL_VERSION_ATLEAST(2, 0, 0)
- case SDL_JOYDEVICEADDED:
- case SDL_JOYDEVICEREMOVED:
- /* pass */
- break;
-#endif
- default:
- printf("SCA_Joystick::HandleEvents, Unknown SDL event (%d), this should not happen\n", sdl_event.type);
- break;
- }
- }
-}
-#endif /* WITH_SDL */
diff --git a/source/gameengine/GameLogic/Joystick/SCA_JoystickPrivate.h b/source/gameengine/GameLogic/Joystick/SCA_JoystickPrivate.h
deleted file mode 100644
index 472a7353190..00000000000
--- a/source/gameengine/GameLogic/Joystick/SCA_JoystickPrivate.h
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): snailrose.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file SCA_JoystickPrivate.h
- * \ingroup gamelogic
- */
-
-#ifndef __SCA_JOYSTICKPRIVATE_H__
-#define __SCA_JOYSTICKPRIVATE_H__
-#include "SCA_Joystick.h"
-
-#ifdef WITH_SDL
-class SCA_Joystick::PrivateData
-{
-public:
- /*
- * The Joystick
- */
- SDL_Joystick* m_joystick;
-
- PrivateData()
- : m_joystick(NULL)
- {
- }
-};
-#endif /* WITH_SDL */
-
-#endif
diff --git a/source/gameengine/GameLogic/SCA_2DFilterActuator.cpp b/source/gameengine/GameLogic/SCA_2DFilterActuator.cpp
deleted file mode 100644
index 6a87d3ccb98..00000000000
--- a/source/gameengine/GameLogic/SCA_2DFilterActuator.cpp
+++ /dev/null
@@ -1,153 +0,0 @@
-/*
- * SCA_2DFilterActuator.cpp
- *
- *
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/GameLogic/SCA_2DFilterActuator.cpp
- * \ingroup gamelogic
- */
-
-
-#include <stddef.h>
-
-#include "SCA_IActuator.h"
-#include "SCA_2DFilterActuator.h"
-
-#include <iostream>
-
-SCA_2DFilterActuator::~SCA_2DFilterActuator()
-{
-}
-
-SCA_2DFilterActuator::SCA_2DFilterActuator(
- SCA_IObject *gameobj,
- RAS_2DFilterManager::RAS_2DFILTER_MODE type,
- short flag,
- float float_arg,
- int int_arg,
- RAS_IRasterizer* rasterizer,
- SCA_IScene* scene)
- : SCA_IActuator(gameobj, KX_ACT_2DFILTER),
- m_type(type),
- m_disableMotionBlur(flag),
- m_float_arg(float_arg),
- m_int_arg(int_arg),
- m_rasterizer(rasterizer),
- m_scene(scene)
-{
- m_gameobj = NULL;
- if (gameobj) {
- m_propNames = gameobj->GetPropertyNames();
- m_gameobj = gameobj;
- }
-}
-
-
-CValue* SCA_2DFilterActuator::GetReplica()
-{
- SCA_2DFilterActuator* replica = new SCA_2DFilterActuator(*this);
- replica->ProcessReplica();
- return replica;
-}
-
-
-bool SCA_2DFilterActuator::Update()
-{
- bool bNegativeEvent = IsNegativeEvent();
- RemoveAllEvents();
-
-
- if (bNegativeEvent)
- return false; // do nothing on negative events
-
- if ( m_type == RAS_2DFilterManager::RAS_2DFILTER_MOTIONBLUR )
- {
- if (!m_disableMotionBlur)
- m_rasterizer->EnableMotionBlur(m_float_arg);
- else
- m_rasterizer->DisableMotionBlur();
-
- return false;
- }
- else if (m_type < RAS_2DFilterManager::RAS_2DFILTER_NUMBER_OF_FILTERS)
- {
- m_scene->Update2DFilter(m_propNames, m_gameobj, m_type, m_int_arg, m_shaderText);
- }
- // once the filter is in place, no need to update it again => disable the actuator
- return false;
-}
-
-
-void SCA_2DFilterActuator::SetScene(SCA_IScene *scene)
-{
- m_scene = scene;
-}
-
-void SCA_2DFilterActuator::SetShaderText(const char *text)
-{
- m_shaderText = text;
-}
-
-#ifdef WITH_PYTHON
-
-/* ------------------------------------------------------------------------- */
-/* Python functions */
-/* ------------------------------------------------------------------------- */
-
-/* Integration hooks ------------------------------------------------------- */
-PyTypeObject SCA_2DFilterActuator::Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "SCA_2DFilterActuator",
- sizeof(PyObjectPlus_Proxy),
- 0,
- py_base_dealloc,
- 0,
- 0,
- 0,
- 0,
- py_base_repr,
- 0,0,0,0,0,0,0,0,0,
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
- 0,0,0,0,0,0,0,
- Methods,
- 0,
- 0,
- &SCA_IActuator::Type,
- 0,0,0,0,0,0,
- py_base_new
-};
-
-PyMethodDef SCA_2DFilterActuator::Methods[] = {
- /* add python functions to deal with m_msg... */
- {NULL,NULL}
-};
-
-PyAttributeDef SCA_2DFilterActuator::Attributes[] = {
- KX_PYATTRIBUTE_STRING_RW("shaderText", 0, 64000, false, SCA_2DFilterActuator, m_shaderText),
- KX_PYATTRIBUTE_SHORT_RW("disableMotionBlur", 0, 1, true, SCA_2DFilterActuator, m_disableMotionBlur),
- KX_PYATTRIBUTE_ENUM_RW("mode",RAS_2DFilterManager::RAS_2DFILTER_ENABLED,RAS_2DFilterManager::RAS_2DFILTER_NUMBER_OF_FILTERS,false,SCA_2DFilterActuator,m_type),
- KX_PYATTRIBUTE_INT_RW("passNumber", 0, 100, true, SCA_2DFilterActuator, m_int_arg),
- KX_PYATTRIBUTE_FLOAT_RW("value", 0.0, 100.0, SCA_2DFilterActuator, m_float_arg),
- { NULL } //Sentinel
-};
-
-#endif
diff --git a/source/gameengine/GameLogic/SCA_2DFilterActuator.h b/source/gameengine/GameLogic/SCA_2DFilterActuator.h
deleted file mode 100644
index 4635a8ad9f8..00000000000
--- a/source/gameengine/GameLogic/SCA_2DFilterActuator.h
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * SCA_2DFilterActuator.h
- *
- *
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file SCA_2DFilterActuator.h
- * \ingroup gamelogic
- */
-
-#ifndef __SCA_2DFILTERACTUATOR_H__
-#define __SCA_2DFILTERACTUATOR_H__
-
-#include "RAS_IRasterizer.h"
-#include "SCA_IActuator.h"
-#include "SCA_IScene.h"
-
-class SCA_2DFilterActuator : public SCA_IActuator
-{
- Py_Header
-
-private:
- vector<STR_String> m_propNames;
- RAS_2DFilterManager::RAS_2DFILTER_MODE m_type;
- short m_disableMotionBlur;
- float m_float_arg;
- int m_int_arg;
- STR_String m_shaderText;
- RAS_IRasterizer* m_rasterizer;
- SCA_IScene* m_scene;
-
-public:
-
- SCA_2DFilterActuator(
- class SCA_IObject* gameobj,
- RAS_2DFilterManager::RAS_2DFILTER_MODE type,
- short flag,
- float float_arg,
- int int_arg,
- RAS_IRasterizer* rasterizer,
- SCA_IScene* scene);
-
- void SetShaderText(const char *text);
- virtual ~SCA_2DFilterActuator();
- virtual bool Update();
-
- void SetScene(SCA_IScene *scene);
-
- virtual CValue* GetReplica();
-};
-#endif
diff --git a/source/gameengine/GameLogic/SCA_ANDController.cpp b/source/gameengine/GameLogic/SCA_ANDController.cpp
deleted file mode 100644
index 2cb7406779c..00000000000
--- a/source/gameengine/GameLogic/SCA_ANDController.cpp
+++ /dev/null
@@ -1,131 +0,0 @@
-/*
- * 'And' together all inputs
- *
- *
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/GameLogic/SCA_ANDController.cpp
- * \ingroup gamelogic
- */
-
-
-#include "SCA_ANDController.h"
-#include "SCA_ISensor.h"
-#include "SCA_LogicManager.h"
-#include "EXP_BoolValue.h"
-
-/* ------------------------------------------------------------------------- */
-/* Native functions */
-/* ------------------------------------------------------------------------- */
-
-SCA_ANDController::SCA_ANDController(SCA_IObject* gameobj)
- :
- SCA_IController(gameobj)
-{
-}
-
-
-
-SCA_ANDController::~SCA_ANDController()
-{
-}
-
-
-
-void SCA_ANDController::Trigger(SCA_LogicManager* logicmgr)
-{
-
- bool sensorresult = true;
-
- for (vector<SCA_ISensor*>::const_iterator is=m_linkedsensors.begin();
- !(is==m_linkedsensors.end());is++)
- {
- SCA_ISensor* sensor = *is;
- if (!sensor->GetState())
- {
- sensorresult = false;
- break;
- }
- }
-
- for (vector<SCA_IActuator*>::const_iterator i=m_linkedactuators.begin();
- !(i==m_linkedactuators.end());i++)
- {
- SCA_IActuator* actua = *i;
- logicmgr->AddActiveActuator(actua,sensorresult);
- }
-}
-
-
-
-CValue* SCA_ANDController::GetReplica()
-{
- CValue* replica = new SCA_ANDController(*this);
- // this will copy properties and so on...
- replica->ProcessReplica();
-
- return replica;
-}
-
-#ifdef WITH_PYTHON
-
-/* ------------------------------------------------------------------------- */
-/* Python functions */
-/* ------------------------------------------------------------------------- */
-
-/* Integration hooks ------------------------------------------------------- */
-PyTypeObject SCA_ANDController::Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "SCA_ANDController",
- sizeof(PyObjectPlus_Proxy),
- 0,
- py_base_dealloc,
- 0,
- 0,
- 0,
- 0,
- py_base_repr,
- 0,0,0,0,0,0,0,0,0,
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
- 0,0,0,0,0,0,0,
- Methods,
- 0,
- 0,
- &SCA_IController::Type,
- 0,0,0,0,0,0,
- py_base_new
-};
-
-PyMethodDef SCA_ANDController::Methods[] = {
- {NULL,NULL} //Sentinel
-};
-
-PyAttributeDef SCA_ANDController::Attributes[] = {
- { NULL } //Sentinel
-};
-#endif // WITH_PYTHON
-/* eof */
diff --git a/source/gameengine/GameLogic/SCA_ANDController.h b/source/gameengine/GameLogic/SCA_ANDController.h
deleted file mode 100644
index ff152d6d2fb..00000000000
--- a/source/gameengine/GameLogic/SCA_ANDController.h
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * SCA_ANDController.h
- *
- *
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file SCA_ANDController.h
- * \ingroup gamelogic
- */
-
-#ifndef __SCA_ANDCONTROLLER_H__
-#define __SCA_ANDCONTROLLER_H__
-
-#include "SCA_IController.h"
-
-class SCA_ANDController : public SCA_IController
-{
- Py_Header
- //virtual void Trigger(class SCA_LogicManager* logicmgr);
-public:
- SCA_ANDController(SCA_IObject* gameobj);
- virtual ~SCA_ANDController();
- virtual CValue* GetReplica();
- virtual void Trigger(SCA_LogicManager* logicmgr);
-};
-
-#endif /* __SCA_ANDCONTROLLER_H__ */
diff --git a/source/gameengine/GameLogic/SCA_ActuatorEventManager.cpp b/source/gameengine/GameLogic/SCA_ActuatorEventManager.cpp
deleted file mode 100644
index fcb236f0913..00000000000
--- a/source/gameengine/GameLogic/SCA_ActuatorEventManager.cpp
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/GameLogic/SCA_ActuatorEventManager.cpp
- * \ingroup gamelogic
- */
-
-
-#include "SCA_ISensor.h"
-#include "SCA_ActuatorEventManager.h"
-#include "SCA_ActuatorSensor.h"
-
-
-SCA_ActuatorEventManager::SCA_ActuatorEventManager(class SCA_LogicManager* logicmgr)
- : SCA_EventManager(logicmgr, ACTUATOR_EVENTMGR)
-{
-}
-
-
-
-SCA_ActuatorEventManager::~SCA_ActuatorEventManager()
-{
-
-}
-
-void SCA_ActuatorEventManager::NextFrame()
-{
- // check for changed actuator
- SG_DList::iterator<SCA_ISensor> it(m_sensors);
- for (it.begin();!it.end();++it)
- {
- (*it)->Activate(m_logicmgr);
- }
-}
-
-void SCA_ActuatorEventManager::UpdateFrame()
-{
- // update the state of actuator before executing them
- SG_DList::iterator<SCA_ActuatorSensor> it(m_sensors);
- for (it.begin();!it.end();++it)
- {
- (*it)->Update();
- }
-}
diff --git a/source/gameengine/GameLogic/SCA_ActuatorEventManager.h b/source/gameengine/GameLogic/SCA_ActuatorEventManager.h
deleted file mode 100644
index 997be1145db..00000000000
--- a/source/gameengine/GameLogic/SCA_ActuatorEventManager.h
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file SCA_ActuatorEventManager.h
- * \ingroup gamelogic
- */
-
-#ifndef __SCA_ACTUATOREVENTMANAGER_H__
-#define __SCA_ACTUATOREVENTMANAGER_H__
-
-#include "SCA_EventManager.h"
-
-#include <vector>
-
-using namespace std;
-
-class SCA_ActuatorEventManager : public SCA_EventManager
-{
-public:
- SCA_ActuatorEventManager(class SCA_LogicManager* logicmgr);
- virtual ~SCA_ActuatorEventManager();
- virtual void NextFrame();
- virtual void UpdateFrame();
- //SCA_LogicManager* GetLogicManager() { return m_logicmgr;}
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:SCA_ActuatorEventManager")
-#endif
-};
-
-#endif /* __SCA_ACTUATOREVENTMANAGER_H__ */
diff --git a/source/gameengine/GameLogic/SCA_ActuatorSensor.cpp b/source/gameengine/GameLogic/SCA_ActuatorSensor.cpp
deleted file mode 100644
index 8b7702228ce..00000000000
--- a/source/gameengine/GameLogic/SCA_ActuatorSensor.cpp
+++ /dev/null
@@ -1,171 +0,0 @@
-/*
- * Actuator sensor
- *
- *
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/GameLogic/SCA_ActuatorSensor.cpp
- * \ingroup gamelogic
- */
-
-
-#include <stddef.h>
-
-#include <iostream>
-#include "SCA_ActuatorSensor.h"
-#include "SCA_EventManager.h"
-#include "SCA_LogicManager.h"
-
-SCA_ActuatorSensor::SCA_ActuatorSensor(SCA_EventManager* eventmgr,
- SCA_IObject* gameobj,
- const STR_String& actname)
- : SCA_ISensor(gameobj,eventmgr),
- m_checkactname(actname)
-{
- m_actuator = GetParent()->FindActuator(m_checkactname);
- Init();
-}
-
-void SCA_ActuatorSensor::Init()
-{
- m_lastresult = m_invert?true:false;
- m_midresult = m_lastresult;
- m_reset = true;
-}
-
-CValue* SCA_ActuatorSensor::GetReplica()
-{
- SCA_ActuatorSensor* replica = new SCA_ActuatorSensor(*this);
- // m_range_expr must be recalculated on replica!
- replica->ProcessReplica();
- replica->Init();
-
- return replica;
-}
-
-void SCA_ActuatorSensor::ReParent(SCA_IObject* parent)
-{
- m_actuator = parent->FindActuator(m_checkactname);
- SCA_ISensor::ReParent(parent);
-}
-
-bool SCA_ActuatorSensor::IsPositiveTrigger()
-{
- bool result = m_lastresult;
- if (m_invert)
- result = !result;
-
- return result;
-}
-
-
-
-SCA_ActuatorSensor::~SCA_ActuatorSensor()
-{
-}
-
-
-
-bool SCA_ActuatorSensor::Evaluate()
-{
- if (m_actuator)
- {
- bool result = m_actuator->IsActive();
- bool reset = m_reset && m_level;
-
- m_reset = false;
- if (m_lastresult != result || m_midresult != result)
- {
- m_lastresult = m_midresult = result;
- return true;
- }
- return (reset) ? true : false;
- }
- return false;
-}
-
-void SCA_ActuatorSensor::Update()
-{
- if (m_actuator)
- {
- m_midresult = m_actuator->IsActive() && !m_actuator->IsNegativeEvent();
- }
-}
-
-#ifdef WITH_PYTHON
-
-/* ------------------------------------------------------------------------- */
-/* Python functions */
-/* ------------------------------------------------------------------------- */
-
-/* Integration hooks ------------------------------------------------------- */
-PyTypeObject SCA_ActuatorSensor::Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "SCA_ActuatorSensor",
- sizeof(PyObjectPlus_Proxy),
- 0,
- py_base_dealloc,
- 0,
- 0,
- 0,
- 0,
- py_base_repr,
- 0,0,0,0,0,0,0,0,0,
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
- 0,0,0,0,0,0,0,
- Methods,
- 0,
- 0,
- &SCA_ISensor::Type,
- 0,0,0,0,0,0,
- py_base_new
-};
-
-PyMethodDef SCA_ActuatorSensor::Methods[] = {
- {NULL,NULL} //Sentinel
-};
-
-PyAttributeDef SCA_ActuatorSensor::Attributes[] = {
- KX_PYATTRIBUTE_STRING_RW_CHECK("actuator",0,MAX_PROP_NAME,false,SCA_ActuatorSensor,m_checkactname,CheckActuator),
- { NULL } //Sentinel
-};
-
-int SCA_ActuatorSensor::CheckActuator(void *self, const PyAttributeDef*)
-{
- SCA_ActuatorSensor* sensor = reinterpret_cast<SCA_ActuatorSensor*>(self);
- SCA_IActuator* act = sensor->GetParent()->FindActuator(sensor->m_checkactname);
- if (act) {
- sensor->m_actuator = act;
- return 0;
- }
- PyErr_SetString(PyExc_AttributeError, "string does not correspond to an actuator");
- return 1;
-}
-
-#endif // WITH_PYTHON
-
-/* eof */
diff --git a/source/gameengine/GameLogic/SCA_ActuatorSensor.h b/source/gameengine/GameLogic/SCA_ActuatorSensor.h
deleted file mode 100644
index 6005bd3ac6c..00000000000
--- a/source/gameengine/GameLogic/SCA_ActuatorSensor.h
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-#ifndef __SCA_ACTUATORSENSOR_H__
-#define __SCA_ACTUATORSENSOR_H__
-
-/** \file SCA_ActuatorSensor.h
- * \ingroup gamelogic
- */
-
-#include "SCA_ISensor.h"
-#include "SCA_IActuator.h"
-
-class SCA_ActuatorSensor : public SCA_ISensor
-{
- Py_Header
- STR_String m_checkactname;
- bool m_lastresult;
- bool m_midresult;
- protected:
- SCA_IActuator* m_actuator;
-public:
- SCA_ActuatorSensor(class SCA_EventManager* eventmgr,
- SCA_IObject* gameobj,
- const STR_String& actname);
-
- virtual ~SCA_ActuatorSensor();
- virtual CValue* GetReplica();
- virtual void Init();
- virtual bool Evaluate();
- virtual bool IsPositiveTrigger();
- virtual void ReParent(SCA_IObject* parent);
- void Update();
-
-#ifdef WITH_PYTHON
-
- /* --------------------------------------------------------------------- */
- /* Python interface ---------------------------------------------------- */
- /* --------------------------------------------------------------------- */
-
- static int CheckActuator(void *self, const PyAttributeDef*);
-
-#endif /* WITH_PYTHON */
-};
-
-#endif /* __SCA_ACTUATORSENSOR_H__ */
diff --git a/source/gameengine/GameLogic/SCA_AlwaysEventManager.cpp b/source/gameengine/GameLogic/SCA_AlwaysEventManager.cpp
deleted file mode 100644
index 22746953a27..00000000000
--- a/source/gameengine/GameLogic/SCA_AlwaysEventManager.cpp
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * Manager for 'always' events. Since always sensors can operate in pulse
- * mode, they need to be activated.
- *
- *
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/GameLogic/SCA_AlwaysEventManager.cpp
- * \ingroup gamelogic
- */
-
-
-#include "SCA_AlwaysEventManager.h"
-#include "SCA_LogicManager.h"
-#include <vector>
-#include "SCA_ISensor.h"
-
-using namespace std;
-
-SCA_AlwaysEventManager::SCA_AlwaysEventManager(class SCA_LogicManager* logicmgr)
- : SCA_EventManager(logicmgr, ALWAYS_EVENTMGR)
-{
-}
-
-
-
-void SCA_AlwaysEventManager::NextFrame()
-{
- SG_DList::iterator<SCA_ISensor> it(m_sensors);
- for (it.begin();!it.end();++it)
- {
- (*it)->Activate(m_logicmgr);
- }
-}
-
diff --git a/source/gameengine/GameLogic/SCA_AlwaysEventManager.h b/source/gameengine/GameLogic/SCA_AlwaysEventManager.h
deleted file mode 100644
index 47293c75726..00000000000
--- a/source/gameengine/GameLogic/SCA_AlwaysEventManager.h
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file SCA_AlwaysEventManager.h
- * \ingroup gamelogic
- */
-
-#ifndef __SCA_ALWAYSEVENTMANAGER_H__
-#define __SCA_ALWAYSEVENTMANAGER_H__
-#include "SCA_EventManager.h"
-#include <vector>
-
-using namespace std;
-class SCA_AlwaysEventManager : public SCA_EventManager
-{
-public:
- SCA_AlwaysEventManager(class SCA_LogicManager* logicmgr);
- virtual void NextFrame();
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:SCA_AlwaysEventManager")
-#endif
-};
-
-#endif /* __SCA_ALWAYSEVENTMANAGER_H__ */
diff --git a/source/gameengine/GameLogic/SCA_AlwaysSensor.cpp b/source/gameengine/GameLogic/SCA_AlwaysSensor.cpp
deleted file mode 100644
index 1a6a82a33eb..00000000000
--- a/source/gameengine/GameLogic/SCA_AlwaysSensor.cpp
+++ /dev/null
@@ -1,139 +0,0 @@
-/*
- * Always trigger
- *
- *
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/GameLogic/SCA_AlwaysSensor.cpp
- * \ingroup gamelogic
- */
-
-#ifdef _MSC_VER
- /* This warning tells us about truncation of __long__ stl-generated names.
- * It can occasionally cause DevStudio to have internal compiler warnings. */
-# pragma warning( disable:4786 )
-#endif
-
-#include "SCA_AlwaysSensor.h"
-#include "SCA_LogicManager.h"
-#include "SCA_EventManager.h"
-
-/* ------------------------------------------------------------------------- */
-/* Native functions */
-/* ------------------------------------------------------------------------- */
-
-SCA_AlwaysSensor::SCA_AlwaysSensor(class SCA_EventManager* eventmgr,
- SCA_IObject* gameobj)
- : SCA_ISensor(gameobj,eventmgr)
-{
- //SetDrawColor(255,0,0);
- Init();
-}
-
-void SCA_AlwaysSensor::Init()
-{
- m_alwaysresult = true;
-}
-
-SCA_AlwaysSensor::~SCA_AlwaysSensor()
-{
- /* intentionally empty */
-}
-
-
-
-CValue* SCA_AlwaysSensor::GetReplica()
-{
- CValue* replica = new SCA_AlwaysSensor(*this);//m_float,GetName());
- // this will copy properties and so on...
- replica->ProcessReplica();
-
- return replica;
-}
-
-
-
-bool SCA_AlwaysSensor::IsPositiveTrigger()
-{
- return (m_invert ? false : true);
-}
-
-
-
-bool SCA_AlwaysSensor::Evaluate()
-{
- /* Nice! :) */
- //return true;
- /* even nicer ;) */
- //return false;
-
- /* nicest ! */
- bool result = m_alwaysresult;
- m_alwaysresult = false;
- return result;
-}
-
-#ifdef WITH_PYTHON
-
-/* ------------------------------------------------------------------------- */
-/* Python functions */
-/* ------------------------------------------------------------------------- */
-
-/* Integration hooks ------------------------------------------------------- */
-PyTypeObject SCA_AlwaysSensor::Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "SCA_AlwaysSensor",
- sizeof(PyObjectPlus_Proxy),
- 0,
- py_base_dealloc,
- 0,
- 0,
- 0,
- 0,
- py_base_repr,
- 0,0,0,0,0,0,0,0,0,
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
- 0,0,0,0,0,0,0,
- Methods,
- 0,
- 0,
- &SCA_ISensor::Type,
- 0,0,0,0,0,0,
- py_base_new
-};
-
-PyMethodDef SCA_AlwaysSensor::Methods[] = {
- {NULL,NULL} //Sentinel
-};
-
-PyAttributeDef SCA_AlwaysSensor::Attributes[] = {
- { NULL } //Sentinel
-};
-
-#endif
-
-/* eof */
diff --git a/source/gameengine/GameLogic/SCA_AlwaysSensor.h b/source/gameengine/GameLogic/SCA_AlwaysSensor.h
deleted file mode 100644
index e0ab4279b1c..00000000000
--- a/source/gameengine/GameLogic/SCA_AlwaysSensor.h
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * SCA_AlwaysSensor.h
- *
- *
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file SCA_AlwaysSensor.h
- * \ingroup gamelogic
- */
-
-#ifndef __SCA_ALWAYSSENSOR_H__
-#define __SCA_ALWAYSSENSOR_H__
-#include "SCA_ISensor.h"
-
-class SCA_AlwaysSensor : public SCA_ISensor
-{
- Py_Header
- bool m_alwaysresult;
-public:
- SCA_AlwaysSensor(class SCA_EventManager* eventmgr,
- SCA_IObject* gameobj);
- virtual ~SCA_AlwaysSensor();
- virtual CValue* GetReplica();
- virtual bool Evaluate();
- virtual bool IsPositiveTrigger();
- virtual void Init();
-};
-
-#endif /* __SCA_ALWAYSSENSOR_H__ */
diff --git a/source/gameengine/GameLogic/SCA_BasicEventManager.cpp b/source/gameengine/GameLogic/SCA_BasicEventManager.cpp
deleted file mode 100644
index e87f9b8f0e4..00000000000
--- a/source/gameengine/GameLogic/SCA_BasicEventManager.cpp
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * Manager for 'always' events. Since always sensors can operate in pulse
- * mode, they need to be activated.
- *
- *
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/GameLogic/SCA_BasicEventManager.cpp
- * \ingroup gamelogic
- */
-
-
-#include "SCA_BasicEventManager.h"
-#include "SCA_LogicManager.h"
-#include <vector>
-#include "SCA_ISensor.h"
-
-using namespace std;
-
-SCA_BasicEventManager::SCA_BasicEventManager(class SCA_LogicManager* logicmgr)
- : SCA_EventManager(logicmgr, BASIC_EVENTMGR)
-{
-}
-
-SCA_BasicEventManager::~SCA_BasicEventManager()
-{
-}
-
-void SCA_BasicEventManager::NextFrame()
-{
- SG_DList::iterator<SCA_ISensor> it(m_sensors);
- for (it.begin();!it.end();++it)
- {
- (*it)->Activate(m_logicmgr);
- }
-}
-
diff --git a/source/gameengine/GameLogic/SCA_BasicEventManager.h b/source/gameengine/GameLogic/SCA_BasicEventManager.h
deleted file mode 100644
index a015233454b..00000000000
--- a/source/gameengine/GameLogic/SCA_BasicEventManager.h
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * Manager for sensor that only need to call Update
- *
- *
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file SCA_BasicEventManager.h
- * \ingroup gamelogic
- */
-
-#ifndef __SCA_BASICEVENTMANAGER_H__
-#define __SCA_BASICEVENTMANAGER_H__
-
-#include "SCA_EventManager.h"
-#include <vector>
-
-using namespace std;
-
-class SCA_BasicEventManager : public SCA_EventManager
-{
-public:
- SCA_BasicEventManager(class SCA_LogicManager* logicmgr);
- ~SCA_BasicEventManager();
-
- virtual void NextFrame();
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:SCA_BasicEventManager")
-#endif
-};
-
-#endif /* __SCA_BASICEVENTMANAGER_H__ */
diff --git a/source/gameengine/GameLogic/SCA_DelaySensor.cpp b/source/gameengine/GameLogic/SCA_DelaySensor.cpp
deleted file mode 100644
index af751cffc2e..00000000000
--- a/source/gameengine/GameLogic/SCA_DelaySensor.cpp
+++ /dev/null
@@ -1,170 +0,0 @@
-/*
- * Delay trigger
- *
- *
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/GameLogic/SCA_DelaySensor.cpp
- * \ingroup gamelogic
- */
-
-#ifdef _MSC_VER
- /* This warning tells us about truncation of __long__ stl-generated names.
- * It can occasionally cause DevStudio to have internal compiler warnings. */
-# pragma warning( disable:4786 )
-#endif
-
-#include <stddef.h>
-
-#include "SCA_DelaySensor.h"
-#include "SCA_LogicManager.h"
-#include "SCA_EventManager.h"
-
-/* ------------------------------------------------------------------------- */
-/* Native functions */
-/* ------------------------------------------------------------------------- */
-
-SCA_DelaySensor::SCA_DelaySensor(class SCA_EventManager* eventmgr,
- SCA_IObject* gameobj,
- int delay,
- int duration,
- bool repeat)
- : SCA_ISensor(gameobj,eventmgr),
- m_repeat(repeat),
- m_delay(delay),
- m_duration(duration)
-{
- Init();
-}
-
-void SCA_DelaySensor::Init()
-{
- m_lastResult = false;
- m_frameCount = -1;
- m_reset = true;
-}
-
-SCA_DelaySensor::~SCA_DelaySensor()
-{
- /* intentionally empty */
-}
-
-CValue* SCA_DelaySensor::GetReplica()
-{
- CValue* replica = new SCA_DelaySensor(*this);
- // this will copy properties and so on...
- replica->ProcessReplica();
-
- return replica;
-}
-
-
-
-bool SCA_DelaySensor::IsPositiveTrigger()
-{
- return (m_invert ? !m_lastResult : m_lastResult);
-}
-
-bool SCA_DelaySensor::Evaluate()
-{
- bool trigger = false;
- bool result;
-
- if (m_frameCount==-1) {
- // this is needed to ensure ON trigger in case delay==0
- // and avoid spurious OFF trigger when duration==0
- m_lastResult = false;
- m_frameCount = 0;
- }
-
- if (m_frameCount<m_delay) {
- m_frameCount++;
- result = false;
- } else if (m_duration > 0) {
- if (m_frameCount < m_delay+m_duration) {
- m_frameCount++;
- result = true;
- } else {
- result = false;
- if (m_repeat)
- m_frameCount = -1;
- }
- } else {
- result = true;
- if (m_repeat)
- m_frameCount = -1;
- }
- if ((m_reset && m_level) || result != m_lastResult)
- trigger = true;
- m_reset = false;
- m_lastResult = result;
- return trigger;
-}
-
-#ifdef WITH_PYTHON
-
-/* ------------------------------------------------------------------------- */
-/* Python functions */
-/* ------------------------------------------------------------------------- */
-
-/* Integration hooks ------------------------------------------------------- */
-PyTypeObject SCA_DelaySensor::Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "SCA_DelaySensor",
- sizeof(PyObjectPlus_Proxy),
- 0,
- py_base_dealloc,
- 0,
- 0,
- 0,
- 0,
- py_base_repr,
- 0,0,0,0,0,0,0,0,0,
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
- 0,0,0,0,0,0,0,
- Methods,
- 0,
- 0,
- &SCA_ISensor::Type,
- 0,0,0,0,0,0,
- py_base_new
-};
-
-PyMethodDef SCA_DelaySensor::Methods[] = {
- {NULL,NULL} //Sentinel
-};
-
-PyAttributeDef SCA_DelaySensor::Attributes[] = {
- KX_PYATTRIBUTE_INT_RW("delay",0,100000,true,SCA_DelaySensor,m_delay),
- KX_PYATTRIBUTE_INT_RW("duration",0,100000,true,SCA_DelaySensor,m_duration),
- KX_PYATTRIBUTE_BOOL_RW("repeat",SCA_DelaySensor,m_repeat),
- { NULL } //Sentinel
-};
-
-#endif // WITH_PYTHON
-
-/* eof */
diff --git a/source/gameengine/GameLogic/SCA_DelaySensor.h b/source/gameengine/GameLogic/SCA_DelaySensor.h
deleted file mode 100644
index 9b39de7e099..00000000000
--- a/source/gameengine/GameLogic/SCA_DelaySensor.h
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * SCA_DelaySensor.h
- *
- *
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file SCA_DelaySensor.h
- * \ingroup gamelogic
- */
-
-#ifndef __SCA_DELAYSENSOR_H__
-#define __SCA_DELAYSENSOR_H__
-#include "SCA_ISensor.h"
-
-class SCA_DelaySensor : public SCA_ISensor
-{
- Py_Header
- bool m_lastResult;
- bool m_repeat;
- int m_delay;
- int m_duration;
- int m_frameCount;
-
-public:
- SCA_DelaySensor(class SCA_EventManager* eventmgr,
- SCA_IObject* gameobj,
- int delay,
- int duration,
- bool repeat);
- virtual ~SCA_DelaySensor();
- virtual CValue* GetReplica();
- virtual bool Evaluate();
- virtual bool IsPositiveTrigger();
- virtual void Init();
-
-
- /* --------------------------------------------------------------------- */
- /* Python interface ---------------------------------------------------- */
- /* --------------------------------------------------------------------- */
-};
-
-#endif /* __SCA_DELAYSENSOR_H__ */
diff --git a/source/gameengine/GameLogic/SCA_EventManager.cpp b/source/gameengine/GameLogic/SCA_EventManager.cpp
deleted file mode 100644
index ffe1ea2dc30..00000000000
--- a/source/gameengine/GameLogic/SCA_EventManager.cpp
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/GameLogic/SCA_EventManager.cpp
- * \ingroup gamelogic
- */
-
-
-#include <assert.h>
-#include "SCA_EventManager.h"
-#include "SCA_ISensor.h"
-
-
-SCA_EventManager::SCA_EventManager(SCA_LogicManager* logicmgr, EVENT_MANAGER_TYPE mgrtype)
- :m_logicmgr(logicmgr),
- m_mgrtype(mgrtype)
-{
-}
-
-
-
-SCA_EventManager::~SCA_EventManager()
-{
- // all sensors should be removed
- assert(m_sensors.Empty());
-}
-
-void SCA_EventManager::RegisterSensor(class SCA_ISensor* sensor)
-{
- m_sensors.AddBack(sensor);
-}
-
-void SCA_EventManager::RemoveSensor(class SCA_ISensor* sensor)
-{
- sensor->Delink();
-}
-
-void SCA_EventManager::NextFrame(double curtime, double fixedtime)
-{
- NextFrame();
-}
-
-void SCA_EventManager::NextFrame()
-{
- assert(false); // && "Event managers should override a NextFrame method");
-}
-
-void SCA_EventManager::EndFrame()
-{
-}
-
-void SCA_EventManager::UpdateFrame()
-{
-}
-
-int SCA_EventManager::GetType()
-{
- return (int) m_mgrtype;
-}
diff --git a/source/gameengine/GameLogic/SCA_EventManager.h b/source/gameengine/GameLogic/SCA_EventManager.h
deleted file mode 100644
index eb9a6d9aca1..00000000000
--- a/source/gameengine/GameLogic/SCA_EventManager.h
+++ /dev/null
@@ -1,91 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file SCA_EventManager.h
- * \ingroup gamelogic
- */
-
-#ifndef __SCA_EVENTMANAGER_H__
-#define __SCA_EVENTMANAGER_H__
-
-#include <vector>
-#include <set>
-#include <algorithm>
-
-#include "SG_DList.h"
-
-class SCA_EventManager
-{
-protected:
- class SCA_LogicManager* m_logicmgr; /* all event manager subclasses use this (other then TimeEventManager) */
-
- // use a set to speed-up insertion/removal
- //std::set <class SCA_ISensor*> m_sensors;
- SG_DList m_sensors;
-
-public:
- enum EVENT_MANAGER_TYPE {
- KEYBOARD_EVENTMGR = 0,
- MOUSE_EVENTMGR,
- ALWAYS_EVENTMGR,
- TOUCH_EVENTMGR,
- PROPERTY_EVENTMGR,
- TIME_EVENTMGR,
- RANDOM_EVENTMGR,
- RAY_EVENTMGR,
- NETWORK_EVENTMGR,
- JOY_EVENTMGR,
- ACTUATOR_EVENTMGR,
- BASIC_EVENTMGR
- };
-
- SCA_EventManager(SCA_LogicManager* logicmgr, EVENT_MANAGER_TYPE mgrtype);
- virtual ~SCA_EventManager();
-
- virtual void RemoveSensor(class SCA_ISensor* sensor);
- virtual void NextFrame(double curtime, double fixedtime);
- virtual void NextFrame();
- virtual void UpdateFrame();
- virtual void EndFrame();
- virtual void RegisterSensor(class SCA_ISensor* sensor);
- int GetType();
- //SG_DList &GetSensors() { return m_sensors; }
-
-
- void Replace_LogicManager(SCA_LogicManager* logicmgr) { m_logicmgr= logicmgr; }
-
-protected:
- EVENT_MANAGER_TYPE m_mgrtype;
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:SCA_EventManager")
-#endif
-};
-
-#endif
-
diff --git a/source/gameengine/GameLogic/SCA_ExpressionController.cpp b/source/gameengine/GameLogic/SCA_ExpressionController.cpp
deleted file mode 100644
index ef058e215d6..00000000000
--- a/source/gameengine/GameLogic/SCA_ExpressionController.cpp
+++ /dev/null
@@ -1,159 +0,0 @@
-/*
- * 'Expression Controller enables to calculate an expression that wires inputs to output
- *
- *
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/GameLogic/SCA_ExpressionController.cpp
- * \ingroup gamelogic
- */
-
-
-#include "SCA_ExpressionController.h"
-#include "SCA_ISensor.h"
-#include "SCA_LogicManager.h"
-#include "EXP_BoolValue.h"
-#include "EXP_InputParser.h"
-#include "MT_Transform.h" // for fuzzyZero
-
-#include <stdio.h>
-
-
-/* ------------------------------------------------------------------------- */
-/* Native functions */
-/* ------------------------------------------------------------------------- */
-
-SCA_ExpressionController::SCA_ExpressionController(SCA_IObject* gameobj,
- const STR_String& exprtext)
- :SCA_IController(gameobj),
- m_exprText(exprtext),
- m_exprCache(NULL)
-{
-}
-
-
-
-SCA_ExpressionController::~SCA_ExpressionController()
-{
- if (m_exprCache)
- m_exprCache->Release();
-}
-
-
-
-CValue* SCA_ExpressionController::GetReplica()
-{
- SCA_ExpressionController* replica = new SCA_ExpressionController(*this);
- replica->m_exprText = m_exprText;
- replica->m_exprCache = NULL;
- // this will copy properties and so on...
- replica->ProcessReplica();
-
- return replica;
-}
-
-
-// Forced deletion of precalculated expression to break reference loop
-// Use this function when you know that you won't use the sensor anymore
-void SCA_ExpressionController::Delete()
-{
- if (m_exprCache)
- {
- m_exprCache->Release();
- m_exprCache = NULL;
- }
- Release();
-}
-
-
-void SCA_ExpressionController::Trigger(SCA_LogicManager* logicmgr)
-{
-
- bool expressionresult = false;
- if (!m_exprCache)
- {
- CParser parser;
- parser.SetContext(this->AddRef());
- m_exprCache = parser.ProcessText(m_exprText);
- }
- if (m_exprCache)
- {
- CValue* value = m_exprCache->Calculate();
- if (value)
- {
- if (value->IsError())
- {
- printf("%s\n", value->GetText().ReadPtr());
- } else
- {
- float num = (float)value->GetNumber();
- expressionresult = !MT_fuzzyZero(num);
- }
- value->Release();
-
- }
- }
-
- for (vector<SCA_IActuator*>::const_iterator i=m_linkedactuators.begin();
- !(i==m_linkedactuators.end());i++)
- {
- SCA_IActuator* actua = *i;
- logicmgr->AddActiveActuator(actua,expressionresult);
- }
-}
-
-
-
-CValue* SCA_ExpressionController::FindIdentifier(const STR_String& identifiername)
-{
-
- CValue* identifierval = NULL;
-
- for (vector<SCA_ISensor*>::const_iterator is=m_linkedsensors.begin();
- !(is==m_linkedsensors.end());is++)
- {
- SCA_ISensor* sensor = *is;
- if (sensor->GetName() == identifiername)
- {
- identifierval = new CBoolValue(sensor->GetState());
- //identifierval = sensor->AddRef();
- break;
- }
-
- //if (!sensor->IsPositiveTrigger())
- //{
- // sensorresult = false;
- // break;
- //}
- }
-
- if (identifierval)
- return identifierval;
-
- return GetParent()->FindIdentifier(identifiername);
-
-}
diff --git a/source/gameengine/GameLogic/SCA_ExpressionController.h b/source/gameengine/GameLogic/SCA_ExpressionController.h
deleted file mode 100644
index c16944ccde1..00000000000
--- a/source/gameengine/GameLogic/SCA_ExpressionController.h
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * KX_EXPRESSIONController.h
- *
- *
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file SCA_ExpressionController.h
- * \ingroup gamelogic
- */
-
-#ifndef __SCA_EXPRESSIONCONTROLLER_H__
-#define __SCA_EXPRESSIONCONTROLLER_H__
-
-#include "SCA_IController.h"
-
-class SCA_ExpressionController : public SCA_IController
-{
-// Py_Header
- STR_String m_exprText;
- CExpression* m_exprCache;
-
-public:
- SCA_ExpressionController(SCA_IObject* gameobj,
- const STR_String& exprtext);
-
- virtual ~SCA_ExpressionController();
- virtual CValue* GetReplica();
- virtual void Trigger(SCA_LogicManager* logicmgr);
- virtual CValue* FindIdentifier(const STR_String& identifiername);
- /**
- * used to release the expression cache
- * so that self references are removed before the controller itself is released
- */
- virtual void Delete();
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:SCA_ExpressionController")
-#endif
-};
-
-#endif /* __SCA_EXPRESSIONCONTROLLER_H__ */
diff --git a/source/gameengine/GameLogic/SCA_IActuator.cpp b/source/gameengine/GameLogic/SCA_IActuator.cpp
deleted file mode 100644
index 9a355fdf3c9..00000000000
--- a/source/gameengine/GameLogic/SCA_IActuator.cpp
+++ /dev/null
@@ -1,140 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/GameLogic/SCA_IActuator.cpp
- * \ingroup gamelogic
- */
-
-
-#include "SCA_IActuator.h"
-#include <stdio.h>
-
-using namespace std;
-
-SCA_IActuator::SCA_IActuator(SCA_IObject* gameobj, KX_ACTUATOR_TYPE type) :
- SCA_ILogicBrick(gameobj),
- m_type(type),
- m_links(0),
- m_posevent(false),
- m_negevent(false)
-{
- // nothing to do
-}
-
-bool SCA_IActuator::Update(double curtime, bool frame)
-{
- if (frame)
- return Update();
-
- return true;
-}
-
-bool SCA_IActuator::Update()
-{
- assert(false && "Actuators should override an Update method.");
- return false;
-}
-
-void SCA_IActuator::Activate(SG_DList& head)
-{
- if (QEmpty())
- {
- InsertActiveQList(m_gameobj->m_activeActuators);
- head.AddBack(&m_gameobj->m_activeActuators);
- }
-}
-
-// this function is only used to deactivate actuators outside the logic loop
-// e.g. when an object is deleted.
-void SCA_IActuator::Deactivate()
-{
- if (QDelink())
- {
- // the actuator was in the active list
- if (m_gameobj->m_activeActuators.QEmpty())
- // the owner object has no more active actuators, remove it from the global list
- m_gameobj->m_activeActuators.Delink();
- }
-}
-
-
-void SCA_IActuator::ProcessReplica()
-{
- SCA_ILogicBrick::ProcessReplica();
- RemoveAllEvents();
- m_linkedcontrollers.clear();
-}
-
-
-
-SCA_IActuator::~SCA_IActuator()
-{
- RemoveAllEvents();
-}
-
-void SCA_IActuator::DecLink()
-{
- m_links--;
- if (m_links < 0)
- {
- printf("Warning: actuator %s has negative m_links: %d\n", m_name.Ptr(), m_links);
- m_links = 0;
- }
-}
-
-void SCA_IActuator::LinkToController(SCA_IController* controller)
-{
- m_linkedcontrollers.push_back(controller);
-}
-
-void SCA_IActuator::UnlinkController(SCA_IController* controller)
-{
- std::vector<class SCA_IController*>::iterator contit;
- for (contit = m_linkedcontrollers.begin();!(contit==m_linkedcontrollers.end());++contit)
- {
- if ((*contit) == controller)
- {
- *contit = m_linkedcontrollers.back();
- m_linkedcontrollers.pop_back();
- return;
- }
- }
- printf("Missing link from actuator %s:%s to controller %s:%s\n",
- m_gameobj->GetName().ReadPtr(), GetName().ReadPtr(),
- controller->GetParent()->GetName().ReadPtr(), controller->GetName().ReadPtr());
-}
-
-void SCA_IActuator::UnlinkAllControllers()
-{
- std::vector<class SCA_IController*>::iterator contit;
- for (contit = m_linkedcontrollers.begin();!(contit==m_linkedcontrollers.end());++contit)
- {
- (*contit)->UnlinkActuator(this);
- }
- m_linkedcontrollers.clear();
-}
-
diff --git a/source/gameengine/GameLogic/SCA_IActuator.h b/source/gameengine/GameLogic/SCA_IActuator.h
deleted file mode 100644
index b63cb633b4e..00000000000
--- a/source/gameengine/GameLogic/SCA_IActuator.h
+++ /dev/null
@@ -1,168 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file SCA_IActuator.h
- * \ingroup gamelogic
- */
-
-#ifndef __SCA_IACTUATOR_H__
-#define __SCA_IACTUATOR_H__
-
-#include "SCA_IController.h"
-#include <vector>
-
-/**
- * Use of SG_DList : None
- * Use of SG_QList : element of activated actuator list of their owner
- * Head: SCA_IObject::m_activeActuators
- */
-class SCA_IActuator : public SCA_ILogicBrick
-{
- friend class SCA_LogicManager;
-protected:
- int m_type;
- int m_links; // number of active links to controllers
- // when 0, the actuator is automatically stopped
- //std::vector<CValue*> m_events;
- bool m_posevent;
- bool m_negevent;
-
- std::vector<class SCA_IController*> m_linkedcontrollers;
-
- void RemoveAllEvents()
- {
- m_posevent = false;
- m_negevent = false;
- }
-
-
-public:
- /**
- * This class also inherits the default copy constructors
- */
- enum KX_ACTUATOR_TYPE {
- KX_ACT_OBJECT,
- KX_ACT_IPO,
- KX_ACT_CAMERA,
- KX_ACT_SOUND,
- KX_ACT_PROPERTY,
- KX_ACT_ADD_OBJECT,
- KX_ACT_END_OBJECT,
- KX_ACT_DYNAMIC,
- KX_ACT_REPLACE_MESH,
- KX_ACT_TRACKTO,
- KX_ACT_CONSTRAINT,
- KX_ACT_SCENE,
- KX_ACT_RANDOM,
- KX_ACT_MESSAGE,
- KX_ACT_ACTION,
- KX_ACT_CD,
- KX_ACT_GAME,
- KX_ACT_VISIBILITY,
- KX_ACT_2DFILTER,
- KX_ACT_PARENT,
- KX_ACT_SHAPEACTION,
- KX_ACT_STATE,
- KX_ACT_ARMATURE,
- KX_ACT_STEERING,
- KX_ACT_MOUSE,
- };
-
- SCA_IActuator(SCA_IObject* gameobj, KX_ACTUATOR_TYPE type);
-
- /**
- * UnlinkObject(...)
- * Certain actuator use gameobject pointers (like TractTo actuator)
- * This function can be called when an object is removed to make
- * sure that the actuator will not use it anymore.
- */
-
- virtual bool UnlinkObject(SCA_IObject* clientobj) { return false; }
-
- /**
- * Update(...)
- * Update the actuator based upon the events received since
- * the last call to Update, the current time and deltatime the
- * time elapsed in this frame ?
- * It is the responsibility of concrete Actuators to clear
- * their event's. This is usually done in the Update() method via
- * a call to RemoveAllEvents()
- */
-
-
- virtual bool Update(double curtime, bool frame);
- virtual bool Update();
-
- /**
- * Add an event to an actuator.
- */
- //void AddEvent(CValue* event)
- void AddEvent(bool event)
- {
- if (event)
- m_posevent = true;
- else
- m_negevent = true;
- }
-
- virtual void ProcessReplica();
-
- /**
- * Return true if all the current events
- * are negative. The definition of negative event is
- * not immediately clear. But usually refers to key-up events
- * or events where no action is required.
- */
- bool IsNegativeEvent() const
- {
- return !m_posevent && m_negevent;
- }
-
- virtual ~SCA_IActuator();
-
- /**
- * remove this actuator from the list of active actuators
- */
- virtual void Deactivate();
- virtual void Activate(SG_DList& head);
-
- void LinkToController(SCA_IController* controller);
- void UnlinkController(class SCA_IController* cont);
- void UnlinkAllControllers();
-
- void ClrLink() { m_links=0; }
- void IncLink() { m_links++; }
- virtual void DecLink();
- bool IsNoLink() const { return !m_links; }
- bool IsType(KX_ACTUATOR_TYPE type) { return m_type == type; }
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:SCA_IActuator")
-#endif
-};
-
-#endif /* __SCA_IACTUATOR_H__ */
diff --git a/source/gameengine/GameLogic/SCA_IController.cpp b/source/gameengine/GameLogic/SCA_IController.cpp
deleted file mode 100644
index c4176d66688..00000000000
--- a/source/gameengine/GameLogic/SCA_IController.cpp
+++ /dev/null
@@ -1,298 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/GameLogic/SCA_IController.cpp
- * \ingroup gamelogic
- */
-
-
-#include <stddef.h>
-
-#include "SCA_IController.h"
-#include "SCA_LogicManager.h"
-#include "SCA_IActuator.h"
-#include "SCA_ISensor.h"
-#include "EXP_PyObjectPlus.h"
-#include "EXP_ListWrapper.h"
-
-#include <stdio.h>
-
-SCA_IController::SCA_IController(SCA_IObject* gameobj)
- :
- SCA_ILogicBrick(gameobj),
- m_statemask(0),
- m_justActivated(false)
-{
-}
-
-
-
-SCA_IController::~SCA_IController()
-{
- //UnlinkAllActuators();
-}
-
-
-
-std::vector<class SCA_ISensor*>& SCA_IController::GetLinkedSensors()
-{
- return m_linkedsensors;
-}
-
-
-
-std::vector<class SCA_IActuator*>& SCA_IController::GetLinkedActuators()
-{
- return m_linkedactuators;
-}
-
-
-
-void SCA_IController::UnlinkAllSensors()
-{
- std::vector<class SCA_ISensor*>::iterator sensit;
- for (sensit = m_linkedsensors.begin();!(sensit==m_linkedsensors.end());++sensit)
- {
- if (IsActive())
- {
- (*sensit)->DecLink();
- }
- (*sensit)->UnlinkController(this);
- }
- m_linkedsensors.clear();
-}
-
-
-
-void SCA_IController::UnlinkAllActuators()
-{
- std::vector<class SCA_IActuator*>::iterator actit;
- for (actit = m_linkedactuators.begin();!(actit==m_linkedactuators.end());++actit)
- {
- if (IsActive())
- {
- (*actit)->DecLink();
- }
- (*actit)->UnlinkController(this);
- }
- m_linkedactuators.clear();
-}
-
-void SCA_IController::LinkToActuator(SCA_IActuator* actua)
-{
- m_linkedactuators.push_back(actua);
- if (IsActive())
- {
- actua->IncLink();
- }
-}
-
-void SCA_IController::UnlinkActuator(class SCA_IActuator* actua)
-{
- std::vector<class SCA_IActuator*>::iterator actit;
- for (actit = m_linkedactuators.begin();!(actit==m_linkedactuators.end());++actit)
- {
- if ((*actit) == actua)
- {
- if (IsActive())
- {
- (*actit)->DecLink();
- }
- *actit = m_linkedactuators.back();
- m_linkedactuators.pop_back();
- return;
- }
- }
- printf("Missing link from controller %s:%s to actuator %s:%s\n",
- m_gameobj->GetName().ReadPtr(), GetName().ReadPtr(),
- actua->GetParent()->GetName().ReadPtr(), actua->GetName().ReadPtr());
-}
-
-void SCA_IController::LinkToSensor(SCA_ISensor* sensor)
-{
- m_linkedsensors.push_back(sensor);
- if (IsActive())
- {
- sensor->IncLink();
- }
-}
-
-void SCA_IController::UnlinkSensor(class SCA_ISensor* sensor)
-{
- std::vector<class SCA_ISensor*>::iterator sensit;
- for (sensit = m_linkedsensors.begin();!(sensit==m_linkedsensors.end());++sensit)
- {
- if ((*sensit) == sensor)
- {
- if (IsActive())
- {
- sensor->DecLink();
- }
- *sensit = m_linkedsensors.back();
- m_linkedsensors.pop_back();
- return;
- }
- }
- printf("Missing link from controller %s:%s to sensor %s:%s\n",
- m_gameobj->GetName().ReadPtr(), GetName().ReadPtr(),
- sensor->GetParent()->GetName().ReadPtr(), sensor->GetName().ReadPtr());
-}
-
-
-void SCA_IController::ApplyState(unsigned int state)
-{
- std::vector<class SCA_IActuator*>::iterator actit;
- std::vector<class SCA_ISensor*>::iterator sensit;
-
- if (m_statemask & state)
- {
- if (!IsActive())
- {
- // reactive the controller, all the links to actuator are valid again
- for (actit = m_linkedactuators.begin();!(actit==m_linkedactuators.end());++actit)
- {
- (*actit)->IncLink();
- }
-
- for (sensit = m_linkedsensors.begin();!(sensit==m_linkedsensors.end());++sensit)
- {
- (*sensit)->IncLink();
- }
- SetActive(true);
- m_justActivated = true;
- }
- } else if (IsActive())
- {
- for (actit = m_linkedactuators.begin();!(actit==m_linkedactuators.end());++actit)
- {
- (*actit)->DecLink();
- }
- for (sensit = m_linkedsensors.begin();!(sensit==m_linkedsensors.end());++sensit)
- {
- (*sensit)->DecLink();
- }
- SetActive(false);
- m_justActivated = false;
- }
-}
-
-#ifdef WITH_PYTHON
-
-/* Python api */
-
-PyTypeObject SCA_IController::Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "SCA_IController",
- sizeof(PyObjectPlus_Proxy),
- 0,
- py_base_dealloc,
- 0,
- 0,
- 0,
- 0,
- py_base_repr,
- 0,0,0,0,0,0,0,0,0,
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
- 0,0,0,0,0,0,0,
- Methods,
- 0,
- 0,
- &SCA_ILogicBrick::Type,
- 0,0,0,0,0,0,
- py_base_new
-};
-
-PyMethodDef SCA_IController::Methods[] = {
- {NULL,NULL} //Sentinel
-};
-
-PyAttributeDef SCA_IController::Attributes[] = {
- KX_PYATTRIBUTE_RO_FUNCTION("state", SCA_IController, pyattr_get_state),
- KX_PYATTRIBUTE_RO_FUNCTION("sensors", SCA_IController, pyattr_get_sensors),
- KX_PYATTRIBUTE_RO_FUNCTION("actuators", SCA_IController, pyattr_get_actuators),
- KX_PYATTRIBUTE_BOOL_RW("useHighPriority",SCA_IController,m_bookmark),
- { NULL } //Sentinel
-};
-
-PyObject *SCA_IController::pyattr_get_state(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- SCA_IController* self = static_cast<SCA_IController*>(self_v);
- return PyLong_FromLong(self->m_statemask);
-}
-
-static int sca_icontroller_get_sensors_size_cb(void *self_v)
-{
- return ((SCA_IController *)self_v)->GetLinkedSensors().size();
-}
-
-static PyObject *sca_icontroller_get_sensors_item_cb(void *self_v, int index)
-{
- return ((SCA_IController *)self_v)->GetLinkedSensors()[index]->GetProxy();
-}
-
-static const char *sca_icontroller_get_sensors_item_name_cb(void *self_v, int index)
-{
- return ((SCA_IController *)self_v)->GetLinkedSensors()[index]->GetName().ReadPtr();
-}
-
-PyObject *SCA_IController::pyattr_get_sensors(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- return (new CListWrapper(self_v,
- ((SCA_IController *)self_v)->GetProxy(),
- NULL,
- sca_icontroller_get_sensors_size_cb,
- sca_icontroller_get_sensors_item_cb,
- sca_icontroller_get_sensors_item_name_cb,
- NULL))->NewProxy(true);
-}
-
-static int sca_icontroller_get_actuators_size_cb(void *self_v)
-{
- return ((SCA_IController *)self_v)->GetLinkedActuators().size();
-}
-
-static PyObject *sca_icontroller_get_actuators_item_cb(void *self_v, int index)
-{
- return ((SCA_IController *)self_v)->GetLinkedActuators()[index]->GetProxy();
-}
-
-static const char *sca_icontroller_get_actuators_item_name_cb(void *self_v, int index)
-{
- return ((SCA_IController *)self_v)->GetLinkedActuators()[index]->GetName().ReadPtr();
-}
-
-PyObject *SCA_IController::pyattr_get_actuators(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- return (new CListWrapper(self_v,
- ((SCA_IController *)self_v)->GetProxy(),
- NULL,
- sca_icontroller_get_actuators_size_cb,
- sca_icontroller_get_actuators_item_cb,
- sca_icontroller_get_actuators_item_name_cb,
- NULL))->NewProxy(true);
-}
-#endif // WITH_PYTHON
diff --git a/source/gameengine/GameLogic/SCA_IController.h b/source/gameengine/GameLogic/SCA_IController.h
deleted file mode 100644
index 4ec872c2316..00000000000
--- a/source/gameengine/GameLogic/SCA_IController.h
+++ /dev/null
@@ -1,112 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file SCA_IController.h
- * \ingroup gamelogic
- */
-
-#ifndef __SCA_ICONTROLLER_H__
-#define __SCA_ICONTROLLER_H__
-
-#include "SCA_ILogicBrick.h"
-#include "EXP_PyObjectPlus.h"
-
-/**
- * Use of SG_DList element: none
- * Use of SG_QList element: build ordered list of activated controller on the owner object
- * Head: SCA_IObject::m_activeControllers
- */
-class SCA_IController : public SCA_ILogicBrick
-{
- Py_Header
-protected:
- std::vector<class SCA_ISensor*> m_linkedsensors;
- std::vector<class SCA_IActuator*> m_linkedactuators;
- unsigned int m_statemask;
- bool m_justActivated;
- bool m_bookmark;
-public:
- SCA_IController(SCA_IObject* gameobj);
- virtual ~SCA_IController();
- virtual void Trigger(class SCA_LogicManager* logicmgr)=0;
- void LinkToSensor(SCA_ISensor* sensor);
- void LinkToActuator(SCA_IActuator*);
- std::vector<class SCA_ISensor*>& GetLinkedSensors();
- std::vector<class SCA_IActuator*>& GetLinkedActuators();
- void ReserveActuator(int num)
- {
- m_linkedactuators.reserve(num);
- }
- void UnlinkAllSensors();
- void UnlinkAllActuators();
- void UnlinkActuator(class SCA_IActuator* actua);
- void UnlinkSensor(class SCA_ISensor* sensor);
- void SetState(unsigned int state) { m_statemask = state; }
- void ApplyState(unsigned int state);
- void Deactivate()
- {
- // the controller can only be part of a sensor m_newControllers list
- Delink();
- }
- bool IsJustActivated()
- {
- return m_justActivated;
- }
- void ClrJustActivated()
- {
- m_justActivated = false;
- }
- void SetBookmark(bool bookmark)
- {
- m_bookmark = bookmark;
- }
- void Activate(SG_DList& head)
- {
- if (QEmpty())
- {
- if (m_bookmark)
- {
- m_gameobj->m_activeBookmarkedControllers.QAddBack(this);
- head.AddFront(&m_gameobj->m_activeBookmarkedControllers);
- }
- else
- {
- InsertActiveQList(m_gameobj->m_activeControllers);
- head.AddBack(&m_gameobj->m_activeControllers);
- }
- }
- }
-
-
-#ifdef WITH_PYTHON
- static PyObject* pyattr_get_state(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_sensors(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_actuators(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
-#endif /* WITH_PYTHON */
-};
-
-#endif /* __SCA_ICONTROLLER_H__ */
diff --git a/source/gameengine/GameLogic/SCA_IInputDevice.cpp b/source/gameengine/GameLogic/SCA_IInputDevice.cpp
deleted file mode 100644
index f4fce034c87..00000000000
--- a/source/gameengine/GameLogic/SCA_IInputDevice.cpp
+++ /dev/null
@@ -1,139 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/GameLogic/SCA_IInputDevice.cpp
- * \ingroup gamelogic
- */
-
-
-#include <assert.h>
-#include "SCA_IInputDevice.h"
-
-SCA_IInputDevice::SCA_IInputDevice()
- :
- m_currentTable(0)
-{
- ClearStatusTable(0);
- ClearStatusTable(1);
-}
-
-
-
-SCA_IInputDevice::~SCA_IInputDevice()
-{
-}
-
-void SCA_IInputDevice::HookEscape()
-{
- assert(false && "This device does not support hooking escape.");
-}
-
-void SCA_IInputDevice::ClearStatusTable(int tableid)
-{
- for (int i=0;i<SCA_IInputDevice::KX_MAX_KEYS;i++)
- m_eventStatusTables[tableid][i]=SCA_InputEvent(SCA_InputEvent::KX_NO_INPUTSTATUS,0);
-}
-
-
-
-const SCA_InputEvent& SCA_IInputDevice::GetEventValue(SCA_IInputDevice::KX_EnumInputs inputcode)
-{
-// cerr << "SCA_IInputDevice::GetEventValue" << endl;
- return m_eventStatusTables[m_currentTable][inputcode];
-}
-
-
-
-int SCA_IInputDevice::GetNumActiveEvents()
-{
- int num = 0;
-
- // cerr << "SCA_IInputDevice::GetNumActiveEvents" << endl;
-
- for (int i=0;i<SCA_IInputDevice::KX_MAX_KEYS;i++)
- {
- const SCA_InputEvent& event = m_eventStatusTables[m_currentTable][i];
- if ((event.m_status == SCA_InputEvent::KX_JUSTACTIVATED)
- || (event.m_status == SCA_InputEvent::KX_ACTIVE))
- num++;
- }
-
- return num;
-}
-
-
-
-int SCA_IInputDevice::GetNumJustEvents()
-{
- int num = 0;
-
- // cerr << "SCA_IInputDevice::GetNumJustEvents" << endl;
-
- for (int i=0;i<SCA_IInputDevice::KX_MAX_KEYS;i++)
- {
- const SCA_InputEvent& event = m_eventStatusTables[m_currentTable][i];
- if ((event.m_status == SCA_InputEvent::KX_JUSTACTIVATED)
- || (event.m_status == SCA_InputEvent::KX_JUSTRELEASED))
- num++;
- }
-
- return num;
-}
-
-
-
-void SCA_IInputDevice::NextFrame()
-{
- m_currentTable = 1 - m_currentTable;
-
- // cerr << "SCA_IInputDevice::NextFrame " << GetNumActiveEvents() << endl;
-
- for (int i=0;i<SCA_IInputDevice::KX_MAX_KEYS;i++)
- {
- switch (m_eventStatusTables[1 - m_currentTable][i].m_status)
- {
- case SCA_InputEvent::KX_NO_INPUTSTATUS:
- m_eventStatusTables[m_currentTable][i]
- = SCA_InputEvent(SCA_InputEvent::KX_NO_INPUTSTATUS, 1);
- break;
- case SCA_InputEvent::KX_JUSTACTIVATED:
- m_eventStatusTables[m_currentTable][i]
- = SCA_InputEvent(SCA_InputEvent::KX_ACTIVE, 1);
- break;
- case SCA_InputEvent::KX_ACTIVE:
- m_eventStatusTables[m_currentTable][i]
- = SCA_InputEvent(SCA_InputEvent::KX_ACTIVE, 1);
- break;
- case SCA_InputEvent::KX_JUSTRELEASED:
- m_eventStatusTables[m_currentTable][i]
- = SCA_InputEvent(SCA_InputEvent::KX_NO_INPUTSTATUS, 1);
- break;
- default:
- ; /* error */
- }
- }
-}
diff --git a/source/gameengine/GameLogic/SCA_IInputDevice.h b/source/gameengine/GameLogic/SCA_IInputDevice.h
deleted file mode 100644
index f306ae4f26b..00000000000
--- a/source/gameengine/GameLogic/SCA_IInputDevice.h
+++ /dev/null
@@ -1,334 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file SCA_IInputDevice.h
- * \ingroup gamelogic
- * \brief Interface for input devices. The defines for keyboard/system/mouse events
- * here are for internal use in the KX module.
- *
- */
-
-#ifndef __SCA_IINPUTDEVICE_H__
-#define __SCA_IINPUTDEVICE_H__
-
-#ifdef WITH_CXX_GUARDEDALLOC
-#include "MEM_guardedalloc.h"
-#endif
-
-class SCA_InputEvent
-{
-
-public:
- enum SCA_EnumInputs {
-
- KX_NO_INPUTSTATUS = 0,
- KX_JUSTACTIVATED,
- KX_ACTIVE,
- KX_JUSTRELEASED,
- };
-
- SCA_InputEvent(SCA_EnumInputs status=KX_NO_INPUTSTATUS,int eventval=0, int unicode=0)
- : m_status(status),
- m_eventval(eventval),
- m_unicode(unicode)
- {
-
- }
-
- SCA_EnumInputs m_status;
- int m_eventval;
- unsigned int m_unicode;
-};
-
-/* Originally from wm_event_types.h, now only used by GameEngine */
-#define MOUSEX MOUSEMOVE
-#define MOUSEY ACTIONMOUSE
-
-class SCA_IInputDevice
-{
-
-
-public:
-
- SCA_IInputDevice();
- virtual ~SCA_IInputDevice();
-
- enum KX_EnumInputs {
-
- KX_NOKEY = 0,
-
- // TIMERS
-
- KX_TIMER0,
- KX_TIMER1,
- KX_TIMER2,
-
- // SYSTEM
-
- /* Moved to avoid clashes with KX_RETKEY */
- KX_KEYBD,
- KX_RAWKEYBD,
- KX_REDRAW,
- KX_INPUTCHANGE,
- KX_QFULL,
- KX_WINFREEZE,
- KX_WINTHAW,
- /* thaw is 11 */
-
- /* move past retkey*/
- KX_WINCLOSE = 14,
- KX_WINQUIT,
- KX_Q_FIRSTTIME,
- /* sequence ends on 16 */
-
- // standard keyboard
-
- /* Because of the above preamble, KX_BEGINKEY is 15 ! This
- * means that KX_RETKEY on 13d (0Dh)) will double up with
- * KX_WINQUIT! Why is it 13? Because ascii 13d is Ctrl-M aka
- * CR! Its little brother, LF has 10d (0Ah). This is
- * dangerous, since the keyboards start scanning at
- * KX_BEGINKEY. I think the keyboard system should push its
- * key events instead of demanding the user to poll the
- * table... But that's for another time... The fix for now is
- * to move the above system events into a 'safe' (ie. unused)
- * range. I am loathe to move it away from this 'magical'
- * coincidence.. it's probably exploited somewhere. I hope the
- * close and quit events don't mess up 'normal' kb code
- * scanning.
- * */
- KX_BEGINKEY = 12,
-
- KX_RETKEY = 13,
- KX_SPACEKEY = 32,
- KX_PADASTERKEY = 42,
- KX_COMMAKEY = 44,
- KX_MINUSKEY = 45,
- KX_PERIODKEY = 46,
- KX_PLUSKEY = 47,
- KX_ZEROKEY = 48,
-
- KX_ONEKEY, // =49
- KX_TWOKEY,
- KX_THREEKEY,
- KX_FOURKEY,
- KX_FIVEKEY,
- KX_SIXKEY,
- KX_SEVENKEY,
- KX_EIGHTKEY,
- KX_NINEKEY, // = 57
-
- KX_AKEY = 97,
- KX_BKEY,
- KX_CKEY,
- KX_DKEY,
- KX_EKEY,
- KX_FKEY,
- KX_GKEY,
- KX_HKEY,
- KX_IKEY,
- KX_JKEY,
- KX_KKEY,
- KX_LKEY,
- KX_MKEY,
- KX_NKEY, // =110
- KX_OKEY,
- KX_PKEY,
- KX_QKEY,
- KX_RKEY,
- KX_SKEY,
- KX_TKEY,
- KX_UKEY,
- KX_VKEY,
- KX_WKEY,
- KX_XKEY, // =120
- KX_YKEY,
- KX_ZKEY, // =122
-
-
-
- KX_CAPSLOCKKEY, // 123
-
- KX_LEFTCTRLKEY, // 124
- KX_LEFTALTKEY,
- KX_RIGHTALTKEY,
- KX_RIGHTCTRLKEY,
- KX_RIGHTSHIFTKEY,
- KX_LEFTSHIFTKEY,// 129
-
- KX_ESCKEY, // 130
- KX_TABKEY, //131
-
-
- KX_LINEFEEDKEY, // 132
- KX_BACKSPACEKEY,
- KX_DELKEY,
- KX_SEMICOLONKEY, // 135
-
-
- KX_QUOTEKEY, //136
- KX_ACCENTGRAVEKEY, //137
-
- KX_SLASHKEY, //138
- KX_BACKSLASHKEY,
- KX_EQUALKEY,
- KX_LEFTBRACKETKEY,
- KX_RIGHTBRACKETKEY, // 142
-
- KX_LEFTARROWKEY, // 145
- KX_DOWNARROWKEY,
- KX_RIGHTARROWKEY,
- KX_UPARROWKEY, // 148
-
- KX_PAD2 ,
- KX_PAD4 ,
- KX_PAD6 ,
- KX_PAD8 ,
-
- KX_PAD1 ,
- KX_PAD3 ,
- KX_PAD5 ,
- KX_PAD7 ,
- KX_PAD9 ,
-
- KX_PADPERIOD,
- KX_PADSLASHKEY,
-
-
-
- KX_PAD0 ,
- KX_PADMINUS,
- KX_PADENTER,
- KX_PADPLUSKEY,
-
-
- KX_F1KEY ,
- KX_F2KEY ,
- KX_F3KEY ,
- KX_F4KEY ,
- KX_F5KEY ,
- KX_F6KEY ,
- KX_F7KEY ,
- KX_F8KEY ,
- KX_F9KEY ,
- KX_F10KEY,
- KX_F11KEY,
- KX_F12KEY,
- KX_F13KEY,
- KX_F14KEY,
- KX_F15KEY,
- KX_F16KEY,
- KX_F17KEY,
- KX_F18KEY,
- KX_F19KEY,
-
- KX_OSKEY,
-
- KX_PAUSEKEY,
- KX_INSERTKEY,
- KX_HOMEKEY ,
- KX_PAGEUPKEY,
- KX_PAGEDOWNKEY,
- KX_ENDKEY,
-
- // MOUSE
- KX_BEGINMOUSE,
-
- KX_BEGINMOUSEBUTTONS,
-
- KX_LEFTMOUSE,
- KX_MIDDLEMOUSE,
- KX_RIGHTMOUSE,
-
- KX_ENDMOUSEBUTTONS,
-
- KX_WHEELUPMOUSE,
- KX_WHEELDOWNMOUSE,
-
- KX_MOUSEX,
- KX_MOUSEY,
-
- KX_ENDMOUSE,
-
-
-
- KX_MAX_KEYS
-
- }; // enum
-
-
-protected:
- /**
- * m_eventStatusTables are two tables that contain current and previous
- * status of all events
- */
-
- SCA_InputEvent m_eventStatusTables[2][SCA_IInputDevice::KX_MAX_KEYS];
- /**
- * m_currentTable is index for m_keyStatusTable that toggle between 0 or 1
- */
- int m_currentTable;
- void ClearStatusTable(int tableid);
-
-public:
- virtual bool IsPressed(SCA_IInputDevice::KX_EnumInputs inputcode)=0;
- virtual const SCA_InputEvent& GetEventValue(SCA_IInputDevice::KX_EnumInputs inputcode);
-
- /**
- * Count active events(active and just_activated)
- */
- virtual int GetNumActiveEvents();
-
- /**
- * Get the number of remapping events (just_activated, just_released)
- */
- virtual int GetNumJustEvents();
-
- virtual void HookEscape();
-
- /**
- * Next frame: we calculate the new key states. This goes as follows:
- *
- * KX_NO_INPUTSTATUS -> KX_NO_INPUTSTATUS
- * KX_JUSTACTIVATED -> KX_ACTIVE
- * KX_ACTIVE -> KX_ACTIVE
- * KX_JUSTRELEASED -> KX_NO_INPUTSTATUS
- *
- * Getting new events provides the
- * KX_NO_INPUTSTATUS->KX_JUSTACTIVATED and
- * KX_ACTIVE->KX_JUSTRELEASED transitions.
- */
- virtual void NextFrame();
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:SCA_InputEvent")
-#endif
-};
-
-#endif /* __SCA_IINPUTDEVICE_H__ */
-
diff --git a/source/gameengine/GameLogic/SCA_ILogicBrick.cpp b/source/gameengine/GameLogic/SCA_ILogicBrick.cpp
deleted file mode 100644
index d0a6e4540c9..00000000000
--- a/source/gameengine/GameLogic/SCA_ILogicBrick.cpp
+++ /dev/null
@@ -1,271 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/GameLogic/SCA_ILogicBrick.cpp
- * \ingroup gamelogic
- */
-
-
-#include <stddef.h>
-
-#include "SCA_ILogicBrick.h"
-#include "EXP_PyObjectPlus.h"
-
-SCA_ILogicBrick::SCA_ILogicBrick(SCA_IObject* gameobj)
- :
- CValue(),
- m_gameobj(gameobj),
- m_logicManager(NULL),
- m_Execute_Priority(0),
- m_Execute_Ueber_Priority(0),
- m_bActive(false),
- m_eventval(0)
-{
- m_text = "KX_LogicBrick";
-}
-
-
-
-SCA_ILogicBrick::~SCA_ILogicBrick()
-{
- RemoveEvent();
-}
-
-
-
-void SCA_ILogicBrick::SetExecutePriority(int execute_Priority)
-{
- m_Execute_Priority = execute_Priority;
-}
-
-
-
-void SCA_ILogicBrick::SetUeberExecutePriority(int execute_Priority)
-{
- m_Execute_Ueber_Priority = execute_Priority;
-}
-
-
-
-void SCA_ILogicBrick::ReParent(SCA_IObject* parent)
-{
- m_gameobj = parent;
-}
-
-void SCA_ILogicBrick::Relink(CTR_Map<CTR_HashedPtr, void*> *obj_map)
-{
- // nothing to do
-}
-
-CValue* SCA_ILogicBrick::Calc(VALUE_OPERATOR op, CValue *val)
-{
- CValue* temp = new CBoolValue(false,"");
- CValue* result = temp->Calc(op,val);
- temp->Release();
-
- return result;
-}
-
-
-
-CValue* SCA_ILogicBrick::CalcFinal(VALUE_DATA_TYPE dtype,
- VALUE_OPERATOR op,
- CValue *val)
-{
- // same as bool implementation, so...
- CValue* temp = new CBoolValue(false,"");
- CValue* result = temp->CalcFinal(dtype,op,val);
- temp->Release();
-
- return result;
-}
-
-
-
-const STR_String& SCA_ILogicBrick::GetText()
-{
- if (m_name.Length())
- return m_name;
-
- return m_text;
-}
-
-
-
-double SCA_ILogicBrick::GetNumber()
-{
- return -1;
-}
-
-
-
-STR_String& SCA_ILogicBrick::GetName()
-{
- return m_name;
-}
-
-
-
-void SCA_ILogicBrick::SetName(const char *name)
-{
- m_name = name;
-}
-
-bool SCA_ILogicBrick::LessComparedTo(SCA_ILogicBrick* other)
-{
- return (this->m_Execute_Ueber_Priority < other->m_Execute_Ueber_Priority)
- || ((this->m_Execute_Ueber_Priority == other->m_Execute_Ueber_Priority) &&
- (this->m_Execute_Priority < other->m_Execute_Priority));
-}
-
-void SCA_ILogicBrick::SetLogicManager(SCA_LogicManager *logicmgr)
-{
- m_logicManager = logicmgr;
-}
-
-SCA_LogicManager *SCA_ILogicBrick::GetLogicManager()
-{
- return m_logicManager;
-}
-
-void SCA_ILogicBrick::RegisterEvent(CValue* eventval)
-{
- if (m_eventval)
- m_eventval->Release();
-
- m_eventval = eventval->AddRef();
-}
-
-
-void SCA_ILogicBrick::RemoveEvent()
-{
- if (m_eventval)
- {
- m_eventval->Release();
- m_eventval = NULL;
- }
-}
-
-
-
-CValue* SCA_ILogicBrick::GetEvent()
-{
- if (m_eventval)
- {
- return m_eventval->AddRef();
- }
-
- return NULL;
-}
-
-
-
-#ifdef WITH_PYTHON
-
-/* python stuff */
-
-PyTypeObject SCA_ILogicBrick::Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "SCA_ILogicBrick",
- sizeof(PyObjectPlus_Proxy),
- 0,
- py_base_dealloc,
- 0,
- 0,
- 0,
- 0,
- py_base_repr,
- 0,0,0,0,0,0,0,0,0,
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
- 0,0,0,0,0,0,0,
- Methods,
- 0,
- 0,
- &CValue::Type,
- 0,0,0,0,0,0,
- py_base_new
-};
-
-PyMethodDef SCA_ILogicBrick::Methods[] = {
- {NULL,NULL} //Sentinel
-};
-
-PyAttributeDef SCA_ILogicBrick::Attributes[] = {
- KX_PYATTRIBUTE_RO_FUNCTION("owner", SCA_ILogicBrick, pyattr_get_owner),
- KX_PYATTRIBUTE_INT_RW("executePriority",0,100000,false,SCA_ILogicBrick,m_Execute_Priority),
- KX_PYATTRIBUTE_STRING_RO("name", SCA_ILogicBrick, m_name),
- {NULL} //Sentinel
-};
-
-int SCA_ILogicBrick::CheckProperty(void *self, const PyAttributeDef *attrdef)
-{
- if (attrdef->m_type != KX_PYATTRIBUTE_TYPE_STRING || attrdef->m_length != 1) {
- PyErr_SetString(PyExc_AttributeError, "inconsistent check function for attribute type, report to blender.org");
- return 1;
- }
- SCA_ILogicBrick* brick = reinterpret_cast<SCA_ILogicBrick*>(self);
- STR_String* var = reinterpret_cast<STR_String*>((char*)self+attrdef->m_offset);
- CValue* prop = brick->GetParent()->FindIdentifier(*var);
- bool error = prop->IsError();
- prop->Release();
- if (error) {
- PyErr_SetString(PyExc_ValueError, "string does not correspond to a property");
- return 1;
- }
- return 0;
-}
-
-/*Attribute functions */
-PyObject *SCA_ILogicBrick::pyattr_get_owner(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- SCA_ILogicBrick* self = static_cast<SCA_ILogicBrick*>(self_v);
- CValue* parent = self->GetParent();
-
- if (parent)
- return parent->GetProxy();
-
- Py_RETURN_NONE;
-}
-
-
-
-/* Conversions for making life better. */
-bool SCA_ILogicBrick::PyArgToBool(int boolArg)
-{
- if (boolArg) {
- return true;
- } else {
- return false;
- }
-}
-
-PyObject *SCA_ILogicBrick::BoolToPyArg(bool boolarg)
-{
- return PyLong_FromLong(boolarg ? KX_TRUE: KX_FALSE);
-}
-
-#endif // WITH_PYTHON
diff --git a/source/gameengine/GameLogic/SCA_ILogicBrick.h b/source/gameengine/GameLogic/SCA_ILogicBrick.h
deleted file mode 100644
index f9ef18cc348..00000000000
--- a/source/gameengine/GameLogic/SCA_ILogicBrick.h
+++ /dev/null
@@ -1,167 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file SCA_ILogicBrick.h
- * \ingroup gamelogic
- */
-
-#ifndef __SCA_ILOGICBRICK_H__
-#define __SCA_ILOGICBRICK_H__
-
-#include "EXP_Value.h"
-#include "SCA_IObject.h"
-#include "EXP_BoolValue.h"
-#include "CTR_Map.h"
-#include "CTR_HashedPtr.h"
-
-class NG_NetworkScene;
-class SCA_IScene;
-class SCA_LogicManager;
-
-class SCA_ILogicBrick : public CValue
-{
- Py_Header
-protected:
- SCA_IObject* m_gameobj;
- SCA_LogicManager *m_logicManager;
- int m_Execute_Priority;
- int m_Execute_Ueber_Priority;
-
- bool m_bActive;
- CValue* m_eventval;
- STR_String m_text;
- STR_String m_name;
- //unsigned long m_drawcolor;
- void RegisterEvent(CValue* eventval);
- void RemoveEvent();
- CValue* GetEvent();
-
-public:
- SCA_ILogicBrick(SCA_IObject* gameobj);
- virtual ~SCA_ILogicBrick();
-
- void SetExecutePriority(int execute_Priority);
- void SetUeberExecutePriority(int execute_Priority);
-
- SCA_IObject* GetParent() { return m_gameobj; }
-
- virtual void ReParent(SCA_IObject* parent);
- virtual void Relink(CTR_Map<CTR_HashedPtr, void*> *obj_map);
- virtual void Delete() { Release(); }
-
- // act as a BoolValue (with value IsPositiveTrigger)
- virtual CValue* Calc(VALUE_OPERATOR op, CValue *val);
- virtual CValue* CalcFinal(VALUE_DATA_TYPE dtype, VALUE_OPERATOR op, CValue *val);
-
- virtual const STR_String & GetText();
- virtual double GetNumber();
- virtual STR_String& GetName();
- virtual void SetName(const char *);
-
- bool IsActive()
- {
- return m_bActive;
- }
-
- void SetActive(bool active)
- {
- m_bActive=active;
- }
-
- // insert in a QList at position corresponding to m_Execute_Priority
- void InsertActiveQList(SG_QList& head)
- {
- SG_QList::iterator<SCA_ILogicBrick> it(head);
- for (it.begin(); !it.end() && m_Execute_Priority > (*it)->m_Execute_Priority; ++it);
- it.add_back(this);
- }
-
- // insert in a QList at position corresponding to m_Execute_Priority
- // inside a longer list that contains elements of other objects.
- // Sorting is done only between the elements of the same object.
- // head is the head of the combined list
- // current points to the first element of the object in the list, NULL if none yet
- void InsertSelfActiveQList(SG_QList& head, SG_QList** current)
- {
- if (!*current)
- {
- // first element can be put anywhere
- head.QAddBack(this);
- *current = this;
- return;
- }
- // note: we assume current points actually to one o our element, skip the tests
- SG_QList::iterator<SCA_ILogicBrick> it(head,*current);
- if (m_Execute_Priority <= (*it)->m_Execute_Priority)
- {
- // this element comes before the first
- *current = this;
- }
- else {
- for (++it; !it.end() && (*it)->m_gameobj == m_gameobj && m_Execute_Priority > (*it)->m_Execute_Priority; ++it);
- }
- it.add_back(this);
- }
-
- virtual bool LessComparedTo(SCA_ILogicBrick* other);
-
- virtual void SetLogicManager(SCA_LogicManager *logicmgr);
- SCA_LogicManager *GetLogicManager();
-
- /* for moving logic bricks between scenes */
- virtual void Replace_IScene(SCA_IScene *val) {}
- virtual void Replace_NetworkScene(NG_NetworkScene *val) {}
-
-#ifdef WITH_PYTHON
- // python methods
-
- static PyObject* pyattr_get_owner(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
-
- // check that attribute is a property
- static int CheckProperty(void *self, const PyAttributeDef *attrdef);
-
- enum KX_BOOL_TYPE {
- KX_BOOL_NODEF = 0,
- KX_TRUE,
- KX_FALSE,
- KX_BOOL_MAX
- };
-
-
-protected:
- /* Some conversions to go with the bool type. */
- /** Convert a KX_TRUE, KX_FALSE in Python to a c++ value. */
- bool PyArgToBool(int boolArg);
-
- /** Convert a a c++ value to KX_TRUE, KX_FALSE in Python. */
- PyObject *BoolToPyArg(bool);
-
-#endif /* WITH_PYTHON */
-
-};
-
-#endif /* __SCA_ILOGICBRICK_H__ */
diff --git a/source/gameengine/GameLogic/SCA_IObject.cpp b/source/gameengine/GameLogic/SCA_IObject.cpp
deleted file mode 100644
index 526e695e792..00000000000
--- a/source/gameengine/GameLogic/SCA_IObject.cpp
+++ /dev/null
@@ -1,349 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/GameLogic/SCA_IObject.cpp
- * \ingroup gamelogic
- */
-
-#include <iostream>
-#include <algorithm>
-
-#include "SCA_IObject.h"
-#include "SCA_ISensor.h"
-#include "SCA_IController.h"
-#include "SCA_IActuator.h"
-#include "MT_Point3.h"
-#include "EXP_ListValue.h"
-
-MT_Point3 SCA_IObject::m_sDummy=MT_Point3(0,0,0);
-SG_QList SCA_IObject::m_activeBookmarkedControllers;
-
-SCA_IObject::SCA_IObject():
- CValue(),
- m_initState(0),
- m_state(0),
- m_firstState(NULL)
-{
- m_suspended = false;
-}
-
-SCA_IObject::~SCA_IObject()
-{
- SCA_SensorList::iterator its;
- for (its = m_sensors.begin(); !(its == m_sensors.end()); ++its)
- {
- //Use Delete for sensor to ensure proper cleaning
- (*its)->Delete();
- //((CValue*)(*its))->Release();
- }
- SCA_ControllerList::iterator itc;
- for (itc = m_controllers.begin(); !(itc == m_controllers.end()); ++itc)
- {
- //Use Delete for controller to ensure proper cleaning (expression controller)
- (*itc)->Delete();
- //((CValue*)(*itc))->Release();
- }
- SCA_ActuatorList::iterator ita;
- for (ita = m_registeredActuators.begin(); !(ita==m_registeredActuators.end()); ++ita)
- {
- (*ita)->UnlinkObject(this);
- }
- for (ita = m_actuators.begin(); !(ita==m_actuators.end()); ++ita)
- {
- (*ita)->Delete();
- }
-
- SCA_ObjectList::iterator ito;
- for (ito = m_registeredObjects.begin(); !(ito==m_registeredObjects.end()); ++ito)
- {
- (*ito)->UnlinkObject(this);
- }
-
- //T_InterpolatorList::iterator i;
- //for (i = m_interpolators.begin(); !(i == m_interpolators.end()); ++i) {
- // delete *i;
- //}
-}
-
-void SCA_IObject::AddSensor(SCA_ISensor* act)
-{
- act->AddRef();
- m_sensors.push_back(act);
-}
-
-
-
-void SCA_IObject::AddController(SCA_IController* act)
-{
- act->AddRef();
- m_controllers.push_back(act);
-}
-
-
-
-void SCA_IObject::AddActuator(SCA_IActuator* act)
-{
- act->AddRef();
- m_actuators.push_back(act);
-}
-
-void SCA_IObject::RegisterActuator(SCA_IActuator* act)
-{
- // don't increase ref count, it would create dead lock
- m_registeredActuators.push_back(act);
-}
-
-void SCA_IObject::UnregisterActuator(SCA_IActuator* act)
-{
- SCA_ActuatorList::iterator ita;
- for (ita = m_registeredActuators.begin(); ita != m_registeredActuators.end(); ++ita)
- {
- if ((*ita) == act) {
- (*ita) = m_registeredActuators.back();
- m_registeredActuators.pop_back();
- break;
- }
- }
-}
-
-void SCA_IObject::RegisterObject(SCA_IObject* obj)
-{
- // one object may be registered multiple times via constraint target
- // store multiple reference, this will serve as registration counter
- m_registeredObjects.push_back(obj);
-}
-
-void SCA_IObject::UnregisterObject(SCA_IObject* obj)
-{
- SCA_ObjectList::iterator ito;
- for (ito = m_registeredObjects.begin(); ito != m_registeredObjects.end(); ++ito)
- {
- if ((*ito) == obj) {
- (*ito) = m_registeredObjects.back();
- m_registeredObjects.pop_back();
- break;
- }
- }
-}
-
-void SCA_IObject::ReParentLogic()
-{
- SCA_ActuatorList& oldactuators = GetActuators();
- int act = 0;
- SCA_ActuatorList::iterator ita;
- for (ita = oldactuators.begin(); !(ita==oldactuators.end()); ++ita)
- {
- SCA_IActuator* newactuator = (SCA_IActuator*) (*ita)->GetReplica();
- newactuator->ReParent(this);
- // actuators are initially not connected to any controller
- newactuator->SetActive(false);
- newactuator->ClrLink();
- oldactuators[act++] = newactuator;
- }
-
- SCA_ControllerList& oldcontrollers = GetControllers();
- int con = 0;
- SCA_ControllerList::iterator itc;
- for (itc = oldcontrollers.begin(); !(itc==oldcontrollers.end()); ++itc)
- {
- SCA_IController* newcontroller = (SCA_IController*)(*itc)->GetReplica();
- newcontroller->ReParent(this);
- newcontroller->SetActive(false);
- oldcontrollers[con++]=newcontroller;
-
- }
- // convert sensors last so that actuators are already available for Actuator sensor
- SCA_SensorList& oldsensors = GetSensors();
- int sen = 0;
- SCA_SensorList::iterator its;
- for (its = oldsensors.begin(); !(its==oldsensors.end()); ++its)
- {
- SCA_ISensor* newsensor = (SCA_ISensor*)(*its)->GetReplica();
- newsensor->ReParent(this);
- newsensor->SetActive(false);
- // sensors are initially not connected to any controller
- newsensor->ClrLink();
- oldsensors[sen++] = newsensor;
- }
-
- // a new object cannot be client of any actuator
- m_registeredActuators.clear();
- m_registeredObjects.clear();
-}
-
-
-
-SCA_ISensor* SCA_IObject::FindSensor(const STR_String& sensorname)
-{
- SCA_ISensor* foundsensor = NULL;
-
- for (SCA_SensorList::iterator its = m_sensors.begin();!(its==m_sensors.end());++its)
- {
- if ((*its)->GetName() == sensorname)
- {
- foundsensor = (*its);
- break;
- }
- }
- return foundsensor;
-}
-
-
-
-SCA_IController* SCA_IObject::FindController(const STR_String& controllername)
-{
- SCA_IController* foundcontroller = NULL;
-
- for (SCA_ControllerList::iterator itc = m_controllers.begin();!(itc==m_controllers.end());++itc)
- {
- if ((*itc)->GetName() == controllername)
- {
- foundcontroller = (*itc);
- break;
- }
- }
- return foundcontroller;
-}
-
-
-
-SCA_IActuator* SCA_IObject::FindActuator(const STR_String& actuatorname)
-{
- SCA_IActuator* foundactuator = NULL;
-
- for (SCA_ActuatorList::iterator ita = m_actuators.begin();!(ita==m_actuators.end());++ita)
- {
- if ((*ita)->GetName() == actuatorname)
- {
- foundactuator = (*ita);
- break;
- }
- }
-
- return foundactuator;
-}
-
-
-void SCA_IObject::Suspend()
-{
- if ((!m_ignore_activity_culling)
- && (!m_suspended)) {
- m_suspended = true;
- /* flag suspend for all sensors */
- SCA_SensorList::iterator i = m_sensors.begin();
- while (i != m_sensors.end()) {
- (*i)->Suspend();
- ++i;
- }
- }
-}
-
-
-
-void SCA_IObject::Resume(void)
-{
- if (m_suspended) {
- m_suspended = false;
- /* unflag suspend for all sensors */
- SCA_SensorList::iterator i = m_sensors.begin();
- while (i != m_sensors.end()) {
- (*i)->Resume();
- ++i;
- }
- }
-}
-
-void SCA_IObject::SetState(unsigned int state)
-{
- unsigned int tmpstate;
- SCA_ControllerList::iterator contit;
-
- // we will update the state in two steps:
- // 1) set the new state bits that are 1
- // 2) clr the new state bits that are 0
- // This to ensure continuity if a sensor is attached to two states
- // that are switching state: no need to deactive and reactive the sensor
-
- tmpstate = m_state | state;
- if (tmpstate != m_state)
- {
- // update the status of the controllers
- for (contit = m_controllers.begin(); contit != m_controllers.end(); ++contit)
- {
- (*contit)->ApplyState(tmpstate);
- }
- }
- m_state = state;
- if (m_state != tmpstate)
- {
- for (contit = m_controllers.begin(); contit != m_controllers.end(); ++contit)
- {
- (*contit)->ApplyState(m_state);
- }
- }
-}
-
-#ifdef WITH_PYTHON
-
-/* ------------------------------------------------------------------------- */
-/* Python functions */
-/* ------------------------------------------------------------------------- */
-
-/* Integration hooks ------------------------------------------------------- */
-PyTypeObject SCA_IObject::Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "SCA_IObject",
- sizeof(PyObjectPlus_Proxy),
- 0,
- py_base_dealloc,
- 0,
- 0,
- 0,
- 0,
- py_base_repr,
- 0,0,0,0,0,0,0,0,0,
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
- 0,0,0,0,0,0,0,
- Methods,
- 0,
- 0,
- &CValue::Type,
- 0,0,0,0,0,0,
- py_base_new
-};
-
-PyMethodDef SCA_IObject::Methods[] = {
- //{"setOrientation", (PyCFunction) SCA_IObject::sPySetOrientation, METH_VARARGS},
- //{"getOrientation", (PyCFunction) SCA_IObject::sPyGetOrientation, METH_VARARGS},
- {NULL,NULL} //Sentinel
-};
-
-PyAttributeDef SCA_IObject::Attributes[] = {
- { NULL } //Sentinel
-};
-
-#endif // WITH_PYTHON
diff --git a/source/gameengine/GameLogic/SCA_IObject.h b/source/gameengine/GameLogic/SCA_IObject.h
deleted file mode 100644
index 29a21fd8708..00000000000
--- a/source/gameengine/GameLogic/SCA_IObject.h
+++ /dev/null
@@ -1,229 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-/** \file SCA_IObject.h
- * \ingroup gamelogic
- * \brief An abstract object that has some logic, python scripting and
- * reference counting Note: transformation stuff has been moved to
- * SceneGraph
- */
-
-#ifndef __SCA_IOBJECT_H__
-#define __SCA_IOBJECT_H__
-
-#include "EXP_Value.h"
-#include <vector>
-
-class SCA_IObject;
-class SCA_ISensor;
-class SCA_IController;
-class SCA_IActuator;
-
-#ifdef WITH_PYTHON
-template<class T> T PyVecTo(PyObject *);
-#endif
-
-typedef std::vector<SCA_ISensor *> SCA_SensorList;
-typedef std::vector<SCA_IController *> SCA_ControllerList;
-typedef std::vector<SCA_IActuator *> SCA_ActuatorList;
-typedef std::vector<SCA_IObject *> SCA_ObjectList;
-
-class SCA_IObject : public CValue
-{
-
- Py_Header
-
-protected:
- friend class KX_StateActuator;
- friend class SCA_IActuator;
- friend class SCA_IController;
- SCA_SensorList m_sensors;
- SCA_ControllerList m_controllers;
- SCA_ActuatorList m_actuators;
- SCA_ActuatorList m_registeredActuators; // actuators that use a pointer to this object
- SCA_ObjectList m_registeredObjects; // objects that hold reference to this object
-
- // SG_Dlist: element of objects with active actuators
- // Head: SCA_LogicManager::m_activeActuators
- // SG_QList: Head of active actuators list on this object
- // Elements: SCA_IActuator
- SG_QList m_activeActuators;
- // SG_Dlist: element of list os lists with active controllers
- // Head: SCA_LogicManager::m_activeControllers
- // SG_QList: Head of active controller list on this object
- // Elements: SCA_IController
- SG_QList m_activeControllers;
- // SG_Dlist: element of list of lists of active controllers
- // Head: SCA_LogicManager::m_activeControllers
- // SG_QList: Head of active bookmarked controller list globally
- // Elements: SCA_IController with bookmark option
- static SG_QList m_activeBookmarkedControllers;
-
- static class MT_Point3 m_sDummy;
-
- /**
- * Ignore activity culling requests?
- */
- bool m_ignore_activity_culling;
-
- /**
- * Ignore updates?
- */
- bool m_suspended;
-
- /**
- * init state of object (used when object is created)
- */
- unsigned int m_initState;
-
- /**
- * current state = bit mask of state that are active
- */
- unsigned int m_state;
-
- /**
- * pointer inside state actuator list for sorting
- */
- SG_QList* m_firstState;
-
-public:
-
- SCA_IObject();
- virtual ~SCA_IObject();
-
- SCA_ControllerList& GetControllers()
- {
- return m_controllers;
- }
- SCA_SensorList& GetSensors()
- {
- return m_sensors;
- }
- SCA_ActuatorList& GetActuators()
- {
- return m_actuators;
- }
- SG_QList& GetActiveActuators()
- {
- return m_activeActuators;
- }
-
- void AddSensor(SCA_ISensor* act);
- void ReserveSensor(int num)
- {
- m_sensors.reserve(num);
- }
- void AddController(SCA_IController* act);
- void ReserveController(int num)
- {
- m_controllers.reserve(num);
- }
- void AddActuator(SCA_IActuator* act);
- void ReserveActuator(int num)
- {
- m_actuators.reserve(num);
- }
- void RegisterActuator(SCA_IActuator* act);
- void UnregisterActuator(SCA_IActuator* act);
-
- void RegisterObject(SCA_IObject* objs);
- void UnregisterObject(SCA_IObject* objs);
- /**
- * UnlinkObject(...)
- * this object is informed that one of the object to which it holds a reference is deleted
- * returns true if there was indeed a reference.
- */
- virtual bool UnlinkObject(SCA_IObject* clientobj) { return false; }
-
- SCA_ISensor* FindSensor(const STR_String& sensorname);
- SCA_IActuator* FindActuator(const STR_String& actuatorname);
- SCA_IController* FindController(const STR_String& controllername);
-
- void SetCurrentTime(float currentTime) {}
-
- virtual void ReParentLogic();
-
- /**
- * Set whether or not to ignore activity culling requests
- */
- void SetIgnoreActivityCulling(bool b)
- {
- m_ignore_activity_culling = b;
- }
-
- /**
- * Set whether or not this object wants to ignore activity culling
- * requests
- */
- bool GetIgnoreActivityCulling()
- {
- return m_ignore_activity_culling;
- }
-
- /**
- * Suspend all progress.
- */
- void Suspend(void);
-
- /**
- * Resume progress
- */
- void Resume(void);
-
- /**
- * Set init state
- */
- void SetInitState(unsigned int initState) { m_initState = initState; }
-
- /**
- * initialize the state when object is created
- */
- void ResetState(void) { SetState(m_initState); }
-
- /**
- * Set the object state
- */
- void SetState(unsigned int state);
-
- /**
- * Get the object state
- */
- unsigned int GetState(void) { return m_state; }
-
-// const class MT_Point3& ConvertPythonPylist(PyObject *pylist);
-
- virtual int GetGameObjectType() {return -1;}
-
- typedef enum ObjectTypes {
- OBJ_ARMATURE=0,
- OBJ_CAMERA=1,
- OBJ_LIGHT=2,
- OBJ_TEXT=3
- } ObjectTypes;
-
-};
-
-#endif /* __SCA_IOBJECT_H__ */
diff --git a/source/gameengine/GameLogic/SCA_IScene.cpp b/source/gameengine/GameLogic/SCA_IScene.cpp
deleted file mode 100644
index a4c905096d7..00000000000
--- a/source/gameengine/GameLogic/SCA_IScene.cpp
+++ /dev/null
@@ -1,145 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/GameLogic/SCA_IScene.cpp
- * \ingroup gamelogic
- */
-
-
-#include "SCA_IScene.h"
-#include "EXP_Value.h"
-
-SCA_DebugProp::SCA_DebugProp(): m_obj(NULL)
-{
-}
-
-SCA_DebugProp::~SCA_DebugProp()
-{
- if (m_obj)
- m_obj->Release();
-}
-
-SCA_IScene::SCA_IScene()
-{
-}
-
-void SCA_IScene::RemoveAllDebugProperties()
-{
- for (std::vector<SCA_DebugProp*>::iterator it = m_debugList.begin();
- !(it==m_debugList.end());++it)
- {
- delete (*it);
- }
- m_debugList.clear();
-}
-
-
-SCA_IScene::~SCA_IScene()
-{
- RemoveAllDebugProperties();
-}
-
-
-std::vector<SCA_DebugProp*>& SCA_IScene::GetDebugProperties()
-{
- return m_debugList;
-}
-
-
-bool SCA_IScene::PropertyInDebugList( class CValue *gameobj, const STR_String &name )
-{
- for (std::vector<SCA_DebugProp*>::iterator it = m_debugList.begin();
- !(it==m_debugList.end());++it) {
- STR_String debugname = (*it)->m_name;
- CValue *debugobj = (*it)->m_obj;
-
- if (debugobj == gameobj && debugname == name)
- return true;
- }
- return false;
-}
-
-
-bool SCA_IScene::ObjectInDebugList( class CValue *gameobj )
-{
- for (std::vector<SCA_DebugProp*>::iterator it = m_debugList.begin();
- !(it==m_debugList.end());++it) {
- CValue* debugobj = (*it)->m_obj;
-
- if (debugobj == gameobj)
- return true;
- }
- return false;
-}
-
-
-void SCA_IScene::AddDebugProperty(class CValue* debugprop,
- const STR_String &name)
-{
- if (m_debugList.size() < DEBUG_MAX_DISPLAY) {
- SCA_DebugProp* dprop = new SCA_DebugProp();
- dprop->m_obj = debugprop;
- debugprop->AddRef();
- dprop->m_name = name;
- m_debugList.push_back(dprop);
- }
-}
-
-
-void SCA_IScene::RemoveDebugProperty(class CValue *gameobj,
- const STR_String &name)
-{
- vector<SCA_DebugProp*>::iterator it = m_debugList.begin();
- while (it != m_debugList.end()) {
- STR_String debugname = (*it)->m_name;
- CValue *debugobj = (*it)->m_obj;
-
- if (debugobj == gameobj && debugname == name) {
- delete (*it);
- m_debugList.erase(it);
- break;
- }
- ++it;
- }
-}
-
-
-void SCA_IScene::RemoveObjectDebugProperties(class CValue* gameobj)
-{
- vector<SCA_DebugProp*>::iterator it = m_debugList.begin();
- while (it != m_debugList.end()) {
- CValue* debugobj = (*it)->m_obj;
-
- if (debugobj == gameobj) {
- delete (*it);
- m_debugList.erase(it);
- continue;
- }
- ++it;
- }
-}
-
diff --git a/source/gameengine/GameLogic/SCA_IScene.h b/source/gameengine/GameLogic/SCA_IScene.h
deleted file mode 100644
index b76b5636b13..00000000000
--- a/source/gameengine/GameLogic/SCA_IScene.h
+++ /dev/null
@@ -1,87 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file SCA_IScene.h
- * \ingroup gamelogic
- */
-
-#ifndef __SCA_ISCENE_H__
-#define __SCA_ISCENE_H__
-
-#include <vector>
-
-#include "STR_String.h"
-#include "RAS_2DFilterManager.h"
-
-#ifdef WITH_CXX_GUARDEDALLOC
-#include "MEM_guardedalloc.h"
-#endif
-
-#define DEBUG_MAX_DISPLAY 100
-
-struct SCA_DebugProp
-{
- class CValue* m_obj;
- STR_String m_name;
- SCA_DebugProp();
- ~SCA_DebugProp();
-};
-
-class SCA_IScene
-{
- std::vector<SCA_DebugProp*> m_debugList;
-public:
- SCA_IScene();
- virtual ~SCA_IScene();
- virtual class SCA_IObject* AddReplicaObject(class CValue* gameobj,
- class CValue* locationobj,
- int lifespan=0)=0;
- virtual void RemoveObject(class CValue* gameobj)=0;
- virtual void DelayedRemoveObject(class CValue* gameobj)=0;
- //virtual void DelayedReleaseObject(class CValue* gameobj)=0;
-
- virtual void ReplaceMesh(class CValue* gameobj,
- void* meshobj, bool use_gfx, bool use_phys)=0;
- std::vector<SCA_DebugProp*>& GetDebugProperties();
- bool PropertyInDebugList(class CValue *gameobj, const STR_String &name);
- bool ObjectInDebugList(class CValue *gameobj);
- void RemoveAllDebugProperties();
- void AddDebugProperty(class CValue* debugprop, const STR_String &name);
- void RemoveDebugProperty(class CValue *gameobj, const STR_String &name);
- void RemoveObjectDebugProperties(class CValue* gameobj);
-
- virtual void Update2DFilter(std::vector<STR_String>& propNames, void* gameObj,
- RAS_2DFilterManager::RAS_2DFILTER_MODE filtermode,
- int pass, STR_String& text) {}
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:SCA_IScene")
-#endif
-};
-
-#endif /* __SCA_ISCENE_H__ */
diff --git a/source/gameengine/GameLogic/SCA_ISensor.cpp b/source/gameengine/GameLogic/SCA_ISensor.cpp
deleted file mode 100644
index 66dd69f93c4..00000000000
--- a/source/gameengine/GameLogic/SCA_ISensor.cpp
+++ /dev/null
@@ -1,471 +0,0 @@
-/*
- * Abstract class for sensor logic bricks
- *
- *
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/GameLogic/SCA_ISensor.cpp
- * \ingroup gamelogic
- */
-
-
-#include <stddef.h>
-
-#include "SCA_ISensor.h"
-#include "SCA_EventManager.h"
-#include "SCA_LogicManager.h"
-// needed for IsTriggered()
-#include "SCA_PythonController.h"
-
-#include <stdio.h>
-
-/* Native functions */
-void SCA_ISensor::ReParent(SCA_IObject* parent)
-{
- SCA_ILogicBrick::ReParent(parent);
- // will be done when the sensor is activated
- //m_eventmgr->RegisterSensor(this);
- //this->SetActive(false);
-}
-
-
-SCA_ISensor::SCA_ISensor(SCA_IObject* gameobj,
- class SCA_EventManager* eventmgr) :
- SCA_ILogicBrick(gameobj)
-{
- m_links = 0;
- m_suspended = false;
- m_invert = false;
- m_level = false;
- m_tap = false;
- m_reset = false;
- m_pos_ticks = 0;
- m_neg_ticks = 0;
- m_pos_pulsemode = false;
- m_neg_pulsemode = false;
- m_skipped_ticks = 0;
- m_state = false;
- m_prev_state = false;
-
- m_eventmgr = eventmgr;
-}
-
-
-SCA_ISensor::~SCA_ISensor()
-{
- // intentionally empty
-}
-
-void SCA_ISensor::ProcessReplica()
-{
- SCA_ILogicBrick::ProcessReplica();
- m_linkedcontrollers.clear();
-}
-
-bool SCA_ISensor::IsPositiveTrigger()
-{
- bool result = false;
-
- if (m_eventval) {
- result = (m_eventval->GetNumber() != 0.0);
- }
- if (m_invert) {
- result = !result;
- }
-
- return result;
-}
-
-void SCA_ISensor::SetPulseMode(bool posmode,
- bool negmode,
- int skippedticks)
-{
- m_pos_pulsemode = posmode;
- m_neg_pulsemode = negmode;
- m_skipped_ticks = skippedticks;
-}
-
-void SCA_ISensor::SetInvert(bool inv)
-{
- m_invert = inv;
-}
-
-void SCA_ISensor::SetLevel(bool lvl)
-{
- m_level = lvl;
-}
-
-void SCA_ISensor::SetTap(bool tap)
-{
- m_tap = tap;
-}
-
-
-double SCA_ISensor::GetNumber()
-{
- return GetState();
-}
-
-void SCA_ISensor::Suspend()
-{
- m_suspended = true;
-}
-
-bool SCA_ISensor::IsSuspended()
-{
- return m_suspended;
-}
-
-void SCA_ISensor::Resume()
-{
- m_suspended = false;
-}
-
-void SCA_ISensor::Init()
-{
- printf("Sensor %s has no init function, please report this bug to Blender.org\n", m_name.Ptr());
-}
-
-void SCA_ISensor::DecLink()
-{
- m_links--;
- if (m_links < 0)
- {
- printf("Warning: sensor %s has negative m_links: %d\n", m_name.Ptr(), m_links);
- m_links = 0;
- }
- if (!m_links)
- {
- // sensor is detached from all controllers, remove it from manager
- UnregisterToManager();
- }
-}
-
-void SCA_ISensor::RegisterToManager()
-{
- // sensor is just activated, initialize it
- Init();
- m_state = false;
- m_eventmgr->RegisterSensor(this);
-}
-
-void SCA_ISensor::Replace_EventManager(class SCA_LogicManager* logicmgr)
-{
- if (m_links) { /* true if we're used currently */
-
- m_eventmgr->RemoveSensor(this);
- m_eventmgr= logicmgr->FindEventManager(m_eventmgr->GetType());
- m_eventmgr->RegisterSensor(this);
- }
- else {
- m_eventmgr= logicmgr->FindEventManager(m_eventmgr->GetType());
- }
-}
-
-void SCA_ISensor::LinkToController(SCA_IController* controller)
-{
- m_linkedcontrollers.push_back(controller);
-}
-
-void SCA_ISensor::UnlinkController(SCA_IController* controller)
-{
- std::vector<class SCA_IController*>::iterator contit;
- for (contit = m_linkedcontrollers.begin();!(contit==m_linkedcontrollers.end());++contit)
- {
- if ((*contit) == controller)
- {
- *contit = m_linkedcontrollers.back();
- m_linkedcontrollers.pop_back();
- return;
- }
- }
- printf("Missing link from sensor %s:%s to controller %s:%s\n",
- m_gameobj->GetName().ReadPtr(), GetName().ReadPtr(),
- controller->GetParent()->GetName().ReadPtr(), controller->GetName().ReadPtr());
-}
-
-void SCA_ISensor::UnlinkAllControllers()
-{
- std::vector<class SCA_IController*>::iterator contit;
- for (contit = m_linkedcontrollers.begin();!(contit==m_linkedcontrollers.end());++contit)
- {
- (*contit)->UnlinkSensor(this);
- }
- m_linkedcontrollers.clear();
-}
-
-void SCA_ISensor::UnregisterToManager()
-{
- m_eventmgr->RemoveSensor(this);
- m_links = 0;
-}
-
-void SCA_ISensor::ActivateControllers(class SCA_LogicManager* logicmgr)
-{
- for (vector<SCA_IController*>::const_iterator c= m_linkedcontrollers.begin();
- c!=m_linkedcontrollers.end();++c)
- {
- SCA_IController* contr = *c;
- if (contr->IsActive())
- logicmgr->AddTriggeredController(contr, this);
- }
-}
-
-void SCA_ISensor::Activate(class SCA_LogicManager* logicmgr)
-{
-
- // calculate if a __triggering__ is wanted
- // don't evaluate a sensor that is not connected to any controller
- if (m_links && !m_suspended) {
- bool result = this->Evaluate();
- // store the state for the rest of the logic system
- m_prev_state = m_state;
- m_state = this->IsPositiveTrigger();
- if (result) {
- // the sensor triggered this frame
- if (m_state || !m_tap) {
- ActivateControllers(logicmgr);
- // reset these counters so that pulse are synchronized with transition
- m_pos_ticks = 0;
- m_neg_ticks = 0;
- } else
- {
- result = false;
- }
- } else
- {
- /* First, the pulsing behavior, if pulse mode is
- * active. It seems something goes wrong if pulse mode is
- * not set :( */
- if (m_pos_pulsemode) {
- m_pos_ticks++;
- if (m_pos_ticks > m_skipped_ticks) {
- if ( m_state )
- {
- ActivateControllers(logicmgr);
- result = true;
- }
- m_pos_ticks = 0;
- }
- }
- // negative pulse doesn't make sense in tap mode, skip
- if (m_neg_pulsemode && !m_tap)
- {
- m_neg_ticks++;
- if (m_neg_ticks > m_skipped_ticks) {
- if (!m_state )
- {
- ActivateControllers(logicmgr);
- result = true;
- }
- m_neg_ticks = 0;
- }
- }
- }
- if (m_tap)
- {
- // in tap mode: we send always a negative pulse immediately after a positive pulse
- if (!result)
- {
- // the sensor did not trigger on this frame
- if (m_prev_state)
- {
- // but it triggered on previous frame => send a negative pulse
- ActivateControllers(logicmgr);
- result = true;
- }
- // in any case, absence of trigger means sensor off
- m_state = false;
- }
- }
- if (!result && m_level)
- {
- // This level sensor is connected to at least one controller that was just made
- // active but it did not generate an event yet, do it now to those controllers only
- for (vector<SCA_IController*>::const_iterator c= m_linkedcontrollers.begin();
- c!=m_linkedcontrollers.end();++c)
- {
- SCA_IController* contr = *c;
- if (contr->IsJustActivated())
- logicmgr->AddTriggeredController(contr, this);
- }
- }
- }
-}
-
-#ifdef WITH_PYTHON
-
-/* ----------------------------------------------- */
-/* Python Functions */
-/* ----------------------------------------------- */
-
-KX_PYMETHODDEF_DOC_NOARGS(SCA_ISensor, reset,
-"reset()\n"
-"\tReset sensor internal state, effect depends on the type of sensor and settings.\n"
-"\tThe sensor is put in its initial state as if it was just activated.\n")
-{
- Init();
- m_prev_state = false;
- Py_RETURN_NONE;
-}
-
-/* ----------------------------------------------- */
-/* Python Integration Hooks */
-/* ----------------------------------------------- */
-
-PyTypeObject SCA_ISensor::Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "SCA_ISensor",
- sizeof(PyObjectPlus_Proxy),
- 0,
- py_base_dealloc,
- 0,
- 0,
- 0,
- 0,
- py_base_repr,
- 0,0,0,0,0,0,0,0,0,
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
- 0,0,0,0,0,0,0,
- Methods,
- 0,
- 0,
- &SCA_ILogicBrick::Type,
- 0,0,0,0,0,0,
- py_base_new
-};
-
-PyMethodDef SCA_ISensor::Methods[] = {
- KX_PYMETHODTABLE_NOARGS(SCA_ISensor, reset),
- {NULL,NULL} //Sentinel
-};
-
-PyAttributeDef SCA_ISensor::Attributes[] = {
- KX_PYATTRIBUTE_BOOL_RW("usePosPulseMode",SCA_ISensor,m_pos_pulsemode),
- KX_PYATTRIBUTE_BOOL_RW("useNegPulseMode",SCA_ISensor,m_neg_pulsemode),
- KX_PYATTRIBUTE_INT_RW("skippedTicks",0,100000,true,SCA_ISensor,m_skipped_ticks),
- KX_PYATTRIBUTE_BOOL_RW("invert",SCA_ISensor,m_invert),
- KX_PYATTRIBUTE_BOOL_RW_CHECK("level",SCA_ISensor,m_level,pyattr_check_level),
- KX_PYATTRIBUTE_BOOL_RW_CHECK("tap",SCA_ISensor,m_tap,pyattr_check_tap),
- KX_PYATTRIBUTE_RO_FUNCTION("triggered", SCA_ISensor, pyattr_get_triggered),
- KX_PYATTRIBUTE_RO_FUNCTION("positive", SCA_ISensor, pyattr_get_positive),
- KX_PYATTRIBUTE_RO_FUNCTION("status", SCA_ISensor, pyattr_get_status),
- KX_PYATTRIBUTE_RO_FUNCTION("pos_ticks", SCA_ISensor, pyattr_get_posTicks),
- KX_PYATTRIBUTE_RO_FUNCTION("neg_ticks", SCA_ISensor, pyattr_get_negTicks),
- KX_PYATTRIBUTE_RW_FUNCTION("frequency", SCA_ISensor, pyattr_get_frequency, pyattr_set_frequency),
- { NULL } //Sentinel
-};
-
-
-PyObject *SCA_ISensor::pyattr_get_triggered(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- SCA_ISensor* self = static_cast<SCA_ISensor*>(self_v);
- bool retval = false;
- if (SCA_PythonController::m_sCurrentController)
- retval = SCA_PythonController::m_sCurrentController->IsTriggered(self);
- return PyBool_FromLong(retval);
-}
-
-PyObject *SCA_ISensor::pyattr_get_positive(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- SCA_ISensor* self = static_cast<SCA_ISensor*>(self_v);
- return PyBool_FromLong(self->GetState());
-}
-
-PyObject *SCA_ISensor::pyattr_get_status(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- SCA_ISensor* self = static_cast<SCA_ISensor*>(self_v);
- int status = 0;
- if (self->GetState())
- {
- if (self->GetState() == self->GetPrevState())
- {
- status = 2;
- }
- else
- {
- status = 1;
- }
- }
- else if (self->GetState() != self->GetPrevState())
- {
- status = 3;
- }
- return PyLong_FromLong(status);
-}
-
-PyObject *SCA_ISensor::pyattr_get_posTicks(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- SCA_ISensor* self = static_cast<SCA_ISensor*>(self_v);
- return PyLong_FromLong(self->GetPosTicks());
-}
-
-PyObject *SCA_ISensor::pyattr_get_negTicks(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- SCA_ISensor* self = static_cast<SCA_ISensor*>(self_v);
- return PyLong_FromLong(self->GetNegTicks());
-}
-
-int SCA_ISensor::pyattr_check_level(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- SCA_ISensor* self = static_cast<SCA_ISensor*>(self_v);
- if (self->m_level)
- self->m_tap = false;
- return 0;
-}
-
-int SCA_ISensor::pyattr_check_tap(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- SCA_ISensor* self = static_cast<SCA_ISensor*>(self_v);
- if (self->m_tap)
- self->m_level = false;
- return 0;
-}
-
-PyObject *SCA_ISensor::pyattr_get_frequency(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- SCA_ISensor *self = static_cast<SCA_ISensor*>(self_v);
- ShowDeprecationWarning("SCA_ISensor.frequency", "SCA_ISensor.skippedTicks");
- return PyLong_FromLong(self->m_skipped_ticks);
-}
-
-int SCA_ISensor::pyattr_set_frequency(void *self_v, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- SCA_ISensor *self = static_cast<SCA_ISensor*>(self_v);
- ShowDeprecationWarning("SCA_ISensor.frequency", "SCA_ISensor.skippedTicks");
- if (PyLong_Check(value)) {
- self->m_skipped_ticks = PyLong_AsLong(value);
- return PY_SET_ATTR_SUCCESS;
- }
- else {
- PyErr_SetString(PyExc_TypeError, "sensor.frequency = int: Sensor, expected an integer");
- return PY_SET_ATTR_FAIL;
- }
-}
-#endif // WITH_PYTHON
-
-/* eof */
diff --git a/source/gameengine/GameLogic/SCA_ISensor.h b/source/gameengine/GameLogic/SCA_ISensor.h
deleted file mode 100644
index 1e82f3ab11f..00000000000
--- a/source/gameengine/GameLogic/SCA_ISensor.h
+++ /dev/null
@@ -1,220 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file SCA_ISensor.h
- * \ingroup gamelogic
- * \brief Interface Class for all logic Sensors. Implements
- * pulsemode and pulsefrequency, and event suppression.
- */
-
-#ifndef __SCA_ISENSOR_H__
-#define __SCA_ISENSOR_H__
-
-#include "SCA_IController.h"
-
-#include <vector>
-
-/**
- * Interface Class for all logic Sensors. Implements
- * pulsemode,pulsefrequency
- * Use of SG_DList element: link sensors to their respective event manager
- * Head: SCA_EventManager::m_sensors
- * Use of SG_QList element: not used
- */
-class SCA_ISensor : public SCA_ILogicBrick
-{
- Py_Header
-protected:
- class SCA_EventManager* m_eventmgr;
-
- /** Pulse positive pulses? */
- bool m_pos_pulsemode;
-
- /** Pulse negative pulses? */
- bool m_neg_pulsemode;
-
- /** Number of skipped ticks between two active pulses. */
- int m_skipped_ticks;
-
- /** Number of ticks since the last positive pulse. */
- int m_pos_ticks;
-
- /** Number of ticks since the last negative pulse. */
- int m_neg_ticks;
-
- /** invert the output signal*/
- bool m_invert;
-
- /** detect level instead of edge*/
- bool m_level;
-
- /** tap mode */
- bool m_tap;
-
- /** sensor has been reset */
- bool m_reset;
-
- /** Sensor must ignore updates? */
- bool m_suspended;
-
- /** number of connections to controller */
- int m_links;
-
- /** current sensor state */
- bool m_state;
-
- /** previous state (for tap option) */
- bool m_prev_state;
-
- std::vector<class SCA_IController*> m_linkedcontrollers;
-
-public:
-
- enum sensortype {
- ST_NONE = 0,
- ST_TOUCH,
- ST_NEAR,
- ST_RADAR,
- // to be updated as needed
- };
-
- SCA_ISensor(SCA_IObject* gameobj,
- class SCA_EventManager* eventmgr);
- ~SCA_ISensor();
- virtual void ReParent(SCA_IObject* parent);
-
- /** Because we want sensors to share some behavior, the Activate has */
- /* an implementation on this level. It requires an evaluate on the lower */
- /* level of individual sensors. Mapping the old activate()s is easy. */
- /* The IsPosTrig() also has to change, to keep things consistent. */
- void Activate(class SCA_LogicManager* logicmgr);
- virtual bool Evaluate() = 0;
- virtual bool IsPositiveTrigger();
- virtual void Init();
-
- virtual CValue* GetReplica()=0;
-
- /** Set parameters for the pulsing behavior.
- * \param posmode Trigger positive pulses?
- * \param negmode Trigger negative pulses?
- * \param freq Frequency to use when doing pulsing.
- */
- void SetPulseMode(bool posmode,
- bool negmode,
- int skippedticks);
-
- /** Set inversion of pulses on or off. */
- void SetInvert(bool inv);
- /** set the level detection on or off */
- void SetLevel(bool lvl);
- void SetTap(bool tap);
-
- virtual void RegisterToManager();
- virtual void UnregisterToManager();
- void Replace_EventManager(class SCA_LogicManager* logicmgr);
- void ReserveController(int num)
- {
- m_linkedcontrollers.reserve(num);
- }
- void LinkToController(SCA_IController* controller);
- void UnlinkController(SCA_IController* controller);
- void UnlinkAllControllers();
- void ActivateControllers(class SCA_LogicManager* logicmgr);
-
- virtual void ProcessReplica();
-
- virtual double GetNumber();
-
- virtual sensortype GetSensorType() { return ST_NONE; }
-
- /** Stop sensing for a while. */
- void Suspend();
-
- /** Is this sensor switched off? */
- bool IsSuspended();
-
- /** get the state of the sensor: positive or negative */
- bool GetState()
- {
- return m_state;
- }
-
- /** get the previous state of the sensor: positive or negative */
- bool GetPrevState()
- {
- return m_prev_state;
- }
-
- /** get the number of ticks since the last positive pulse */
- int GetPosTicks()
- {
- return m_pos_ticks;
- }
-
- /** get the number of ticks since the last negative pulse */
- int GetNegTicks()
- {
- return m_neg_ticks;
- }
-
- /** Resume sensing. */
- void Resume();
-
- void ClrLink()
- { m_links = 0; }
- void IncLink()
- { if (!m_links++) RegisterToManager(); }
- void DecLink();
- bool IsNoLink() const
- { return !m_links; }
-
-#ifdef WITH_PYTHON
- /* Python functions: */
- KX_PYMETHOD_DOC_NOARGS(SCA_ISensor,reset);
-
- static PyObject* pyattr_get_triggered(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_positive(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_status(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_posTicks(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_negTicks(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_frequency(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_frequency(void *self_v, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
-
- static int pyattr_check_level(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_check_tap(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
-
- enum SensorStatus {
- KX_SENSOR_INACTIVE = 0,
- KX_SENSOR_JUST_ACTIVATED,
- KX_SENSOR_ACTIVE,
- KX_SENSOR_JUST_DEACTIVATED
-
- };
-#endif /* WITH_PYTHON */
-};
-
-#endif /* __SCA_ISENSOR_H__ */
diff --git a/source/gameengine/GameLogic/SCA_JoystickManager.cpp b/source/gameengine/GameLogic/SCA_JoystickManager.cpp
deleted file mode 100644
index 780e4e9ce88..00000000000
--- a/source/gameengine/GameLogic/SCA_JoystickManager.cpp
+++ /dev/null
@@ -1,92 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/GameLogic/SCA_JoystickManager.cpp
- * \ingroup gamelogic
- */
-
-#include "SCA_JoystickSensor.h"
-#include "SCA_JoystickManager.h"
-#include "SCA_LogicManager.h"
-//#include <vector>
-#include "SCA_ISensor.h"
-
-//using namespace std;
-
-
-SCA_JoystickManager::SCA_JoystickManager(class SCA_LogicManager* logicmgr)
- : SCA_EventManager(logicmgr, JOY_EVENTMGR)
-{
- int i;
- for (i=0; i<JOYINDEX_MAX; i++) {
- m_joystick[i] = SCA_Joystick::GetInstance( i );
- }
-}
-
-
-SCA_JoystickManager::~SCA_JoystickManager()
-{
- int i;
- for (i=0; i<JOYINDEX_MAX; i++) {
- if (m_joystick[i])
- m_joystick[i]->ReleaseInstance();
- }
-}
-
-
-void SCA_JoystickManager::NextFrame(double curtime,double deltatime)
-{
- // We should always handle events in case we want to grab them with Python
-#ifdef WITH_SDL
- SCA_Joystick::HandleEvents(); /* Handle all SDL Joystick events */
-#endif
-
- if (m_sensors.Empty()) {
- return;
- }
- else {
- ;
- SG_DList::iterator<SCA_JoystickSensor> it(m_sensors);
- for (it.begin();!it.end();++it)
- {
- SCA_JoystickSensor* joysensor = *it;
- if (!joysensor->IsSuspended())
- {
- joysensor->Activate(m_logicmgr);
- }
- }
- }
-}
-
-
-SCA_Joystick *SCA_JoystickManager::GetJoystickDevice( short int joyindex)
-{
- /*
- *Return the instance of SCA_Joystick for use
- */
- return m_joystick[joyindex];
-}
diff --git a/source/gameengine/GameLogic/SCA_JoystickManager.h b/source/gameengine/GameLogic/SCA_JoystickManager.h
deleted file mode 100644
index 60dcaea4ef2..00000000000
--- a/source/gameengine/GameLogic/SCA_JoystickManager.h
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file SCA_JoystickManager.h
- * \ingroup gamelogic
- */
-
-#ifndef __SCA_JOYSTICKMANAGER_H__
-#define __SCA_JOYSTICKMANAGER_H__
-
-#include "SCA_EventManager.h"
-#include "Joystick/SCA_Joystick.h"
-#include <vector>
-
-using namespace std;
-class SCA_JoystickManager : public SCA_EventManager
-{
- /**
- * SDL Joystick Class Instance
- */
- SCA_Joystick *m_joystick[JOYINDEX_MAX];
-public:
- SCA_JoystickManager(class SCA_LogicManager* logicmgr);
- virtual ~SCA_JoystickManager();
- virtual void NextFrame(double curtime,double deltatime);
- SCA_Joystick* GetJoystickDevice(short int joyindex);
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:SCA_JoystickManager")
-#endif
-};
-
-#endif
-
diff --git a/source/gameengine/GameLogic/SCA_JoystickSensor.cpp b/source/gameengine/GameLogic/SCA_JoystickSensor.cpp
deleted file mode 100644
index 56df9692e72..00000000000
--- a/source/gameengine/GameLogic/SCA_JoystickSensor.cpp
+++ /dev/null
@@ -1,428 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/GameLogic/SCA_JoystickSensor.cpp
- * \ingroup gamelogic
- */
-
-#include "SCA_JoystickManager.h"
-#include "SCA_JoystickSensor.h"
-
-#include "SCA_EventManager.h"
-#include "SCA_LogicManager.h"
-
-#include "EXP_PyObjectPlus.h"
-
-#include <stdio.h>
-#include <stddef.h>
-#include <iostream>
-
-
-
-SCA_JoystickSensor::SCA_JoystickSensor(class SCA_JoystickManager* eventmgr,
- SCA_IObject* gameobj,
- short int joyindex,
- short int joymode,
- int axis, int axisf,int prec,
- int button,
- int hat, int hatf, bool allevents)
- :SCA_ISensor(gameobj,eventmgr),
- m_axis(axis),
- m_axisf(axisf),
- m_button(button),
- m_hat(hat),
- m_hatf(hatf),
- m_precision(prec),
- m_joymode(joymode),
- m_joyindex(joyindex),
- m_bAllEvents(allevents)
-{
-/*
-std::cout << " axis " << m_axis << std::endl;
-std::cout << " axis flag " << m_axisf << std::endl;
-std::cout << " precision " << m_precision << std::endl;
-std::cout << " button " << m_button << std::endl;
-std::cout << " hat " << m_hat << std::endl;
-std::cout << " hat flag " << m_hatf << std::endl;
-*/
- Init();
-}
-
-void SCA_JoystickSensor::Init()
-{
- m_istrig=(m_invert)?1:0;
- m_istrig_prev=0;
- m_reset = true;
-}
-
-SCA_JoystickSensor::~SCA_JoystickSensor()
-{
-}
-
-
-CValue* SCA_JoystickSensor::GetReplica()
-{
- SCA_JoystickSensor* replica = new SCA_JoystickSensor(*this);
- // this will copy properties and so on...
- replica->ProcessReplica();
- replica->Init();
- return replica;
-}
-
-
-bool SCA_JoystickSensor::IsPositiveTrigger()
-{
- bool result = m_istrig;
- if (m_invert)
- result = !result;
- return result;
-}
-
-
-bool SCA_JoystickSensor::Evaluate()
-{
- SCA_Joystick *js = ((SCA_JoystickManager *)m_eventmgr)->GetJoystickDevice(m_joyindex);
- bool result = false;
- bool reset = m_reset && m_level;
-
- if (js==NULL) /* no joystick - don't do anything */
- return false;
-
- m_reset = false;
-
- switch (m_joymode) {
- case KX_JOYSENSORMODE_AXIS:
- {
- /* what is what!
- * m_axisf == JOYAXIS_RIGHT, JOYAXIS_UP, JOYAXIS_DOWN, JOYAXIS_LEFT
- * m_axisf == 1 == up
- * m_axisf == 2 == left
- * m_axisf == 3 == down
- *
- * numberof== m_axis (1-4), range is half of JOYAXIS_MAX since
- * it assumes the axis joysticks are axis parirs (0,1), (2,3), etc
- * also note that this starts at 1 where functions its used
- * with expect a zero index.
- */
-
- if (!js->IsTrigAxis() && !reset) /* No events from SDL? - don't bother */
- return false;
-
- js->cSetPrecision(m_precision);
- if (m_bAllEvents) {
- if (js->aAxisPairIsPositive(m_axis-1)) { /* use zero based axis index internally */
- m_istrig = 1;
- result = true;
- }
- else {
- if (m_istrig) {
- m_istrig = 0;
- result = true;
- }
- }
- }
- else {
- if (js->aAxisPairDirectionIsPositive(m_axis-1, m_axisf)) { /* use zero based axis index internally */
- m_istrig = 1;
- result = true;
- }
- else {
- if (m_istrig) {
- m_istrig = 0;
- result = true;
- }
- }
- }
- break;
- }
- case KX_JOYSENSORMODE_AXIS_SINGLE:
- {
- /* Like KX_JOYSENSORMODE_AXIS but don't pair up axis */
- if (!js->IsTrigAxis() && !reset) /* No events from SDL? - don't bother */
- return false;
-
- /* No need for 'm_bAllEvents' check here since were only checking 1 axis */
- js->cSetPrecision(m_precision);
- if (js->aAxisIsPositive(m_axis-1)) { /* use zero based axis index internally */
- m_istrig = 1;
- result = true;
- }
- else {
- if (m_istrig) {
- m_istrig = 0;
- result = true;
- }
- }
- break;
- }
-
- case KX_JOYSENSORMODE_BUTTON:
- {
- /* what is what!
- * m_button = the actual button in question
- */
- if (!js->IsTrigButton() && !reset) /* No events from SDL? - don't bother */
- return false;
-
- if (( m_bAllEvents && js->aAnyButtonPressIsPositive()) || (!m_bAllEvents && js->aButtonPressIsPositive(m_button))) {
- m_istrig = 1;
- result = true;
- }
- else {
- if (m_istrig) {
- m_istrig = 0;
- result = true;
- }
- }
- break;
- }
- case KX_JOYSENSORMODE_HAT:
- {
- /* what is what!
- * numberof = m_hat -- max 4
- * direction= m_hatf -- max 12
- */
-
- if (!js->IsTrigHat() && !reset) /* No events from SDL? - don't bother */
- return false;
-
- if ((m_bAllEvents && js->GetHat(m_hat-1)) || js->aHatIsPositive(m_hat-1, m_hatf)) {
- m_istrig = 1;
- result = true;
- }
- else {
- if (m_istrig) {
- m_istrig = 0;
- result = true;
- }
- }
- break;
- }
- /* test for ball anyone ?*/
- default:
- printf("Error invalid switch statement\n");
- break;
- }
-
- /* if not all events are enabled, only send a positive pulse when
- * the button state changes */
- if (!m_bAllEvents) {
- if (m_istrig_prev == m_istrig) {
- result = false;
- }
- else {
- m_istrig_prev = m_istrig;
- }
- }
-
- if (reset)
- result = true;
-
- return result;
-}
-
-
-bool SCA_JoystickSensor::isValid(SCA_JoystickSensor::KX_JOYSENSORMODE m)
-{
- bool res = false;
- res = ((m > KX_JOYSENSORMODE_NODEF) && (m < KX_JOYSENSORMODE_MAX));
- return res;
-}
-
-#ifdef WITH_PYTHON
-
-/* ------------------------------------------------------------------------- */
-/* Python functions */
-/* ------------------------------------------------------------------------- */
-
-/* Integration hooks ------------------------------------------------------- */
-PyTypeObject SCA_JoystickSensor::Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "SCA_JoystickSensor",
- sizeof(PyObjectPlus_Proxy),
- 0,
- py_base_dealloc,
- 0,
- 0,
- 0,
- 0,
- py_base_repr,
- 0,0,0,0,0,0,0,0,0,
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
- 0,0,0,0,0,0,0,
- Methods,
- 0,
- 0,
- &SCA_ISensor::Type,
- 0,0,0,0,0,0,
- py_base_new
-};
-
-PyMethodDef SCA_JoystickSensor::Methods[] = {
- {"getButtonActiveList",(PyCFunction) SCA_JoystickSensor::sPyGetButtonActiveList, METH_NOARGS,(const char *)GetButtonActiveList_doc},
- {"getButtonStatus",(PyCFunction) SCA_JoystickSensor::sPyGetButtonStatus, METH_VARARGS,(const char *)GetButtonStatus_doc},
- {NULL,NULL} //Sentinel
-};
-
-PyAttributeDef SCA_JoystickSensor::Attributes[] = {
- KX_PYATTRIBUTE_SHORT_RW("index",0,JOYINDEX_MAX-1,true,SCA_JoystickSensor,m_joyindex),
- KX_PYATTRIBUTE_INT_RW("threshold",0,32768,true,SCA_JoystickSensor,m_precision),
- KX_PYATTRIBUTE_INT_RW("button",0,100,false,SCA_JoystickSensor,m_button),
- KX_PYATTRIBUTE_INT_LIST_RW_CHECK("axis",0,3,true,SCA_JoystickSensor,m_axis,2,CheckAxis),
- KX_PYATTRIBUTE_INT_LIST_RW_CHECK("hat",0,12,true,SCA_JoystickSensor,m_hat,2,CheckHat),
- KX_PYATTRIBUTE_RO_FUNCTION("axisValues", SCA_JoystickSensor, pyattr_get_axis_values),
- KX_PYATTRIBUTE_RO_FUNCTION("axisSingle", SCA_JoystickSensor, pyattr_get_axis_single),
- KX_PYATTRIBUTE_RO_FUNCTION("hatValues", SCA_JoystickSensor, pyattr_get_hat_values),
- KX_PYATTRIBUTE_RO_FUNCTION("hatSingle", SCA_JoystickSensor, pyattr_get_hat_single),
- KX_PYATTRIBUTE_RO_FUNCTION("numAxis", SCA_JoystickSensor, pyattr_get_num_axis),
- KX_PYATTRIBUTE_RO_FUNCTION("numButtons", SCA_JoystickSensor, pyattr_get_num_buttons),
- KX_PYATTRIBUTE_RO_FUNCTION("numHats", SCA_JoystickSensor, pyattr_get_num_hats),
- KX_PYATTRIBUTE_RO_FUNCTION("connected", SCA_JoystickSensor, pyattr_get_connected),
- { NULL } //Sentinel
-};
-
-/* get button active list -------------------------------------------------- */
-const char SCA_JoystickSensor::GetButtonActiveList_doc[] =
-"getButtonActiveList\n"
-"\tReturns a list containing the indices of the button currently pressed.\n";
-PyObject *SCA_JoystickSensor::PyGetButtonActiveList( )
-{
- SCA_Joystick *joy = ((SCA_JoystickManager *)m_eventmgr)->GetJoystickDevice(m_joyindex);
- PyObject *ls = PyList_New(0);
- PyObject *value;
- int i;
-
- if (joy) {
- for (i=0; i < joy->GetNumberOfButtons(); i++) {
- if (joy->aButtonPressIsPositive(i)) {
- value = PyLong_FromLong(i);
- PyList_Append(ls, value);
- Py_DECREF(value);
- }
- }
- }
- return ls;
-}
-
-/* get button status -------------------------------------------------- */
-const char SCA_JoystickSensor::GetButtonStatus_doc[] =
-"getButtonStatus(buttonIndex)\n"
-"\tReturns a bool of the current pressed state of the specified button.\n";
-PyObject *SCA_JoystickSensor::PyGetButtonStatus( PyObject *args )
-{
- SCA_Joystick *joy = ((SCA_JoystickManager *)m_eventmgr)->GetJoystickDevice(m_joyindex);
- int index;
-
- if (!PyArg_ParseTuple(args, "i:getButtonStatus", &index)) {
- return NULL;
- }
- if (joy && index >= 0 && index < joy->GetNumberOfButtons()) {
- return PyBool_FromLong(joy->aButtonPressIsPositive(index) ? 1 : 0);
- }
- return PyBool_FromLong(0);
-}
-
-PyObject *SCA_JoystickSensor::pyattr_get_axis_values(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- SCA_JoystickSensor* self = static_cast<SCA_JoystickSensor*>(self_v);
- SCA_Joystick *joy = ((SCA_JoystickManager *)self->m_eventmgr)->GetJoystickDevice(self->m_joyindex);
-
- int axis_index = (joy ? joy->GetNumberOfAxes() : 0);
- PyObject *list = PyList_New(axis_index);
-
- while (axis_index--) {
- PyList_SET_ITEM(list, axis_index, PyLong_FromLong(joy->GetAxisPosition(axis_index)));
- }
-
- return list;
-}
-
-PyObject *SCA_JoystickSensor::pyattr_get_axis_single(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- SCA_JoystickSensor* self = static_cast<SCA_JoystickSensor*>(self_v);
- SCA_Joystick *joy = ((SCA_JoystickManager *)self->m_eventmgr)->GetJoystickDevice(self->m_joyindex);
-
- if (self->m_joymode != KX_JOYSENSORMODE_AXIS_SINGLE) {
- PyErr_SetString(PyExc_AttributeError, "val = sensor.axisSingle: Joystick Sensor, not 'Single Axis' type");
- return NULL;
- }
-
- return PyLong_FromLong(joy ? joy->GetAxisPosition(self->m_axis - 1) : 0);
-}
-
-PyObject *SCA_JoystickSensor::pyattr_get_hat_values(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- SCA_JoystickSensor* self = static_cast<SCA_JoystickSensor*>(self_v);
- SCA_Joystick *joy = ((SCA_JoystickManager *)self->m_eventmgr)->GetJoystickDevice(self->m_joyindex);
-
- int hat_index = (joy ? joy->GetNumberOfHats() : 0);
- PyObject *list = PyList_New(hat_index);
-
- while (hat_index--) {
- PyList_SET_ITEM(list, hat_index, PyLong_FromLong(joy->GetHat(hat_index)));
- }
-
- return list;
-}
-
-PyObject *SCA_JoystickSensor::pyattr_get_hat_single(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- SCA_JoystickSensor* self = static_cast<SCA_JoystickSensor*>(self_v);
- SCA_Joystick *joy = ((SCA_JoystickManager *)self->m_eventmgr)->GetJoystickDevice(self->m_joyindex);
-
- return PyLong_FromLong(joy ? joy->GetHat(self->m_hat - 1) : 0);
-}
-
-PyObject *SCA_JoystickSensor::pyattr_get_num_axis(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- SCA_JoystickSensor* self = static_cast<SCA_JoystickSensor*>(self_v);
- SCA_Joystick *joy = ((SCA_JoystickManager *)self->m_eventmgr)->GetJoystickDevice(self->m_joyindex);
- return PyLong_FromLong( joy ? joy->GetNumberOfAxes() : 0 );
-}
-
-PyObject *SCA_JoystickSensor::pyattr_get_num_buttons(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- SCA_JoystickSensor* self = static_cast<SCA_JoystickSensor*>(self_v);
- SCA_Joystick *joy = ((SCA_JoystickManager *)self->m_eventmgr)->GetJoystickDevice(self->m_joyindex);
- return PyLong_FromLong( joy ? joy->GetNumberOfButtons() : 0 );
-}
-
-PyObject *SCA_JoystickSensor::pyattr_get_num_hats(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- SCA_JoystickSensor* self = static_cast<SCA_JoystickSensor*>(self_v);
- SCA_Joystick *joy = ((SCA_JoystickManager *)self->m_eventmgr)->GetJoystickDevice(self->m_joyindex);
- return PyLong_FromLong( joy ? joy->GetNumberOfHats() : 0 );
-}
-
-PyObject *SCA_JoystickSensor::pyattr_get_connected(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- SCA_JoystickSensor* self = static_cast<SCA_JoystickSensor*>(self_v);
- SCA_Joystick *joy = ((SCA_JoystickManager *)self->m_eventmgr)->GetJoystickDevice(self->m_joyindex);
- return PyBool_FromLong( joy ? joy->Connected() : 0 );
-}
-
-#endif
diff --git a/source/gameengine/GameLogic/SCA_JoystickSensor.h b/source/gameengine/GameLogic/SCA_JoystickSensor.h
deleted file mode 100644
index 6c6dc019a5e..00000000000
--- a/source/gameengine/GameLogic/SCA_JoystickSensor.h
+++ /dev/null
@@ -1,168 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file SCA_JoystickSensor.h
- * \ingroup gamelogic
- */
-
-
-#ifndef __JOYSENSOR_H__
-#define __JOYSENSOR_H__
-
-#include "SCA_ISensor.h"
-#include "Joystick/SCA_JoystickDefines.h"
-
-class SCA_JoystickSensor :public SCA_ISensor
-{
- Py_Header
-
- /**
- * Axis 1-JOYAXIS_MAX, MUST be followed by m_axisf
- */
- int m_axis;
- /**
- * Axis flag to find direction, MUST be an int
- */
- int m_axisf;
- /**
- * The actual button
- */
- int m_button;
- /**
- * Flag for a pressed or released button
- */
- int m_buttonf;
- /**
- * The actual hat 1-JOYHAT_MAX. MUST be followed by m_hatf
- */
- int m_hat;
- /**
- * Flag to find direction 1-12, MUST be an int
- */
- int m_hatf;
- /**
- * The threshold value the axis acts upon
- */
- int m_precision;
- /**
- * Is an event triggered ?
- */
- bool m_istrig;
- /**
- * Last trigger state for this sensors joystick,
- * Otherwise it will trigger all the time
- * this is used to see if the trigger state changes.
- */
- bool m_istrig_prev;
- /**
- * The mode to determine axis,button or hat
- */
- short int m_joymode;
- /**
- * Select which joystick to use
- */
- short int m_joyindex;
-
- /**
- * Detect all events for the currently selected type
- */
- bool m_bAllEvents;
-
- enum KX_JOYSENSORMODE {
- KX_JOYSENSORMODE_NODEF = 0,
- KX_JOYSENSORMODE_AXIS,
- KX_JOYSENSORMODE_BUTTON,
- KX_JOYSENSORMODE_HAT,
- KX_JOYSENSORMODE_AXIS_SINGLE,
- KX_JOYSENSORMODE_MAX
- };
- bool isValid(KX_JOYSENSORMODE);
-
-public:
- SCA_JoystickSensor(class SCA_JoystickManager* eventmgr,
- SCA_IObject* gameobj,
- short int joyindex,
- short int joymode,
- int axis, int axisf,int prec,
- int button,
- int hat, int hatf, bool allevents);
- virtual ~SCA_JoystickSensor();
- virtual CValue* GetReplica();
-
- virtual bool Evaluate();
- virtual bool IsPositiveTrigger();
- virtual void Init();
-
- short int GetJoyIndex(void) {
- return m_joyindex;
- }
-
-#ifdef WITH_PYTHON
-
- /* --------------------------------------------------------------------- */
- /* Python interface ---------------------------------------------------- */
- /* --------------------------------------------------------------------- */
-
- /* Joystick Index */
- KX_PYMETHOD_DOC_NOARGS(SCA_JoystickSensor,GetButtonActiveList)
- KX_PYMETHOD_DOC_VARARGS(SCA_JoystickSensor,GetButtonStatus)
-
- static PyObject* pyattr_get_axis_values(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_axis_single(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_hat_values(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_hat_single(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_num_axis(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_num_buttons(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_num_hats(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_connected(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
-
-
- /* attribute check */
- static int CheckAxis(void *self, const PyAttributeDef*)
- {
- SCA_JoystickSensor* sensor = reinterpret_cast<SCA_JoystickSensor*>(self);
- if (sensor->m_axis < 1)
- sensor->m_axis = 1;
- else if (sensor->m_axis > JOYAXIS_MAX)
- sensor->m_axis = JOYAXIS_MAX;
- return 0;
- }
- static int CheckHat(void *self, const PyAttributeDef*)
- {
- SCA_JoystickSensor* sensor = reinterpret_cast<SCA_JoystickSensor*>(self);
- if (sensor->m_hat < 1)
- sensor->m_hat = 1;
- else if (sensor->m_hat > JOYHAT_MAX)
- sensor->m_hat = JOYHAT_MAX;
- return 0;
- }
-
-#endif /* WITH_PYTHON */
-
-};
-
-#endif /* __JOYSENSOR_H__ */
diff --git a/source/gameengine/GameLogic/SCA_KeyboardManager.cpp b/source/gameengine/GameLogic/SCA_KeyboardManager.cpp
deleted file mode 100644
index 778ba9e9a2c..00000000000
--- a/source/gameengine/GameLogic/SCA_KeyboardManager.cpp
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
- * Manager for keyboard events
- *
- *
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/GameLogic/SCA_KeyboardManager.cpp
- * \ingroup gamelogic
- */
-
-
-#include "EXP_BoolValue.h"
-#include "SCA_KeyboardManager.h"
-#include "SCA_KeyboardSensor.h"
-#include "EXP_IntValue.h"
-#include <vector>
-
-SCA_KeyboardManager::SCA_KeyboardManager(SCA_LogicManager* logicmgr,
- SCA_IInputDevice* inputdev)
- : SCA_EventManager(logicmgr, KEYBOARD_EVENTMGR),
- m_inputDevice(inputdev)
-{
-}
-
-
-
-SCA_KeyboardManager::~SCA_KeyboardManager()
-{
-}
-
-
-
-SCA_IInputDevice* SCA_KeyboardManager::GetInputDevice()
-{
- return m_inputDevice;
-}
-
-
-
-void SCA_KeyboardManager::NextFrame()
-{
- //const SCA_InputEvent& event = GetEventValue(SCA_IInputDevice::KX_EnumInputs inputcode)=0;
-// cerr << "SCA_KeyboardManager::NextFrame"<< endl;
- SG_DList::iterator<SCA_ISensor> it(m_sensors);
- for (it.begin();!it.end();++it)
- {
- (*it)->Activate(m_logicmgr);
- }
-}
-
-bool SCA_KeyboardManager::IsPressed(SCA_IInputDevice::KX_EnumInputs inputcode)
-{
- return false;
- //return m_kxsystem->IsPressed(inputcode);
-}
-
diff --git a/source/gameengine/GameLogic/SCA_KeyboardManager.h b/source/gameengine/GameLogic/SCA_KeyboardManager.h
deleted file mode 100644
index cd1cbf4adee..00000000000
--- a/source/gameengine/GameLogic/SCA_KeyboardManager.h
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file SCA_KeyboardManager.h
- * \ingroup gamelogic
- * \brief Manager for keyboard events
- *
- */
-
-#ifndef __SCA_KEYBOARDMANAGER_H__
-#define __SCA_KEYBOARDMANAGER_H__
-
-
-#include "SCA_EventManager.h"
-
-#include <vector>
-
-using namespace std;
-
-#include "SCA_IInputDevice.h"
-
-
-class SCA_KeyboardManager : public SCA_EventManager
-{
- class SCA_IInputDevice* m_inputDevice;
-
-public:
- SCA_KeyboardManager(class SCA_LogicManager* logicmgr,class SCA_IInputDevice* inputdev);
- virtual ~SCA_KeyboardManager();
-
- bool IsPressed(SCA_IInputDevice::KX_EnumInputs inputcode);
-
- virtual void NextFrame();
- SCA_IInputDevice* GetInputDevice();
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:SCA_KeyboardManager")
-#endif
-};
-
-#endif /* __SCA_KEYBOARDMANAGER_H__ */
diff --git a/source/gameengine/GameLogic/SCA_KeyboardSensor.cpp b/source/gameengine/GameLogic/SCA_KeyboardSensor.cpp
deleted file mode 100644
index 414a685d358..00000000000
--- a/source/gameengine/GameLogic/SCA_KeyboardSensor.cpp
+++ /dev/null
@@ -1,668 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- * Sensor for keyboard input
- */
-
-/** \file gameengine/GameLogic/SCA_KeyboardSensor.cpp
- * \ingroup gamelogic
- */
-
-
-#include <stddef.h>
-
-#include "SCA_KeyboardSensor.h"
-#include "SCA_KeyboardManager.h"
-#include "SCA_LogicManager.h"
-#include "EXP_StringValue.h"
-#include "SCA_IInputDevice.h"
-
-extern "C" {
- #include "BLI_string_utf8.h"
- #include "BLI_string_cursor_utf8.h"
-}
-
-/* ------------------------------------------------------------------------- */
-/* Native functions */
-/* ------------------------------------------------------------------------- */
-
-SCA_KeyboardSensor::SCA_KeyboardSensor(SCA_KeyboardManager* keybdmgr,
- short int hotkey,
- short int qual,
- short int qual2,
- bool bAllKeys,
- const STR_String& targetProp,
- const STR_String& toggleProp,
- SCA_IObject* gameobj,
- short int exitKey)
- :SCA_ISensor(gameobj,keybdmgr),
- m_hotkey(hotkey),
- m_qual(qual),
- m_qual2(qual2),
- m_bAllKeys(bAllKeys),
- m_targetprop(targetProp),
- m_toggleprop(toggleProp)
-{
- if (hotkey == exitKey)
- keybdmgr->GetInputDevice()->HookEscape();
-// SetDrawColor(0xff0000ff);
- Init();
-}
-
-
-
-SCA_KeyboardSensor::~SCA_KeyboardSensor()
-{
-}
-
-void SCA_KeyboardSensor::Init()
-{
- // this function is used when the sensor is disconnected from all controllers
- // by the state engine. It reinitializes the sensor as if it was just created.
- // However, if the target key is pressed when the sensor is reactivated, it
- // will not generated an event (see remark in Evaluate()).
- m_val = (m_invert)?1:0;
- m_reset = true;
-}
-
-CValue* SCA_KeyboardSensor::GetReplica()
-{
- SCA_KeyboardSensor* replica = new SCA_KeyboardSensor(*this);
- // this will copy properties and so on...
- replica->ProcessReplica();
- replica->Init();
- return replica;
-}
-
-
-
-short int SCA_KeyboardSensor::GetHotkey()
-{
- return m_hotkey;
-}
-
-
-
-bool SCA_KeyboardSensor::IsPositiveTrigger()
-{
- bool result = (m_val != 0);
-
- if (m_invert)
- result = !result;
-
- return result;
-}
-
-
-
-bool SCA_KeyboardSensor::TriggerOnAllKeys()
-{
- return m_bAllKeys;
-}
-
-
-
-bool SCA_KeyboardSensor::Evaluate()
-{
- bool result = false;
- bool reset = m_reset && m_level;
- bool qual = true;
- bool qual_change = false;
- short int m_val_orig = m_val;
-
- SCA_IInputDevice* inputdev = ((SCA_KeyboardManager *)m_eventmgr)->GetInputDevice();
- // cerr << "SCA_KeyboardSensor::Eval event, sensing for "<< m_hotkey << " at device " << inputdev << "\n";
-
- /* See if we need to do logging: togPropState exists and is
- * different from 0 */
- CValue* myparent = GetParent();
- CValue* togPropState = myparent->GetProperty(m_toggleprop);
- if (togPropState &&
- (((int)togPropState->GetNumber()) != 0) )
- {
- LogKeystrokes();
- }
-
- m_reset = false;
-
- /* Now see whether events must be bounced. */
- if (m_bAllKeys)
- {
- bool justactivated = false;
- bool justreleased = false;
- bool active = false;
-
- for (int i=SCA_IInputDevice::KX_BEGINKEY ; i<= SCA_IInputDevice::KX_ENDKEY;i++)
- {
- const SCA_InputEvent & inevent = inputdev->GetEventValue((SCA_IInputDevice::KX_EnumInputs) i);
- switch (inevent.m_status)
- {
- case SCA_InputEvent::KX_JUSTACTIVATED:
- justactivated = true;
- break;
- case SCA_InputEvent::KX_JUSTRELEASED:
- justreleased = true;
- break;
- case SCA_InputEvent::KX_ACTIVE:
- active = true;
- break;
- case SCA_InputEvent::KX_NO_INPUTSTATUS:
- /* do nothing */
- break;
- }
- }
-
- if (justactivated)
- {
- m_val=1;
- result = true;
- } else
- {
- if (justreleased)
- {
- m_val=(active)?1:0;
- result = true;
- } else
- {
- if (active)
- {
- if (m_val == 0)
- {
- m_val = 1;
- if (m_level) {
- result = true;
- }
- }
- } else
- {
- if (m_val == 1)
- {
- m_val = 0;
- result = true;
- }
- }
- }
- if (m_tap)
- // special case for tap mode: only generate event for new activation
- result = false;
- }
-
-
- } else
- {
-
- // cerr << "======= SCA_KeyboardSensor::Evaluate:: peeking at key status" << endl;
- const SCA_InputEvent & inevent = inputdev->GetEventValue(
- (SCA_IInputDevice::KX_EnumInputs) m_hotkey);
-
- // cerr << "======= SCA_KeyboardSensor::Evaluate:: status: " << inevent.m_status << endl;
-
-
- /* Check qualifier keys
- * - see if the qualifiers we request are pressed - 'qual' true/false
- * - see if the qualifiers we request changed their state - 'qual_change' true/false
- */
- if (m_qual > 0) {
- const SCA_InputEvent & qualevent = inputdev->GetEventValue((SCA_IInputDevice::KX_EnumInputs) m_qual);
- switch (qualevent.m_status) {
- case SCA_InputEvent::KX_NO_INPUTSTATUS:
- qual = false;
- break;
- case SCA_InputEvent::KX_JUSTRELEASED:
- qual_change = true;
- qual = false;
- break;
- case SCA_InputEvent::KX_JUSTACTIVATED:
- qual_change = true;
- case SCA_InputEvent::KX_ACTIVE:
- /* do nothing */
- break;
- }
- }
- if (m_qual2 > 0 && qual==true) {
- const SCA_InputEvent & qualevent = inputdev->GetEventValue((SCA_IInputDevice::KX_EnumInputs) m_qual2);
- /* copy of above */
- switch (qualevent.m_status) {
- case SCA_InputEvent::KX_NO_INPUTSTATUS:
- qual = false;
- break;
- case SCA_InputEvent::KX_JUSTRELEASED:
- qual_change = true;
- qual = false;
- break;
- case SCA_InputEvent::KX_JUSTACTIVATED:
- qual_change = true;
- case SCA_InputEvent::KX_ACTIVE:
- /* do nothing */
- break;
- }
- }
- /* done reading qualifiers */
-
- if (inevent.m_status == SCA_InputEvent::KX_NO_INPUTSTATUS)
- {
- if (m_val == 1)
- {
- // this situation may occur after a scene suspend: the keyboard release
- // event was not captured, produce now the event off
- m_val = 0;
- result = true;
- }
- } else
- {
- if (inevent.m_status == SCA_InputEvent::KX_JUSTACTIVATED)
- {
- m_val=1;
- result = true;
- } else
- {
- if (inevent.m_status == SCA_InputEvent::KX_JUSTRELEASED)
- {
- m_val = 0;
- result = true;
- } else
- {
- if (inevent.m_status == SCA_InputEvent::KX_ACTIVE)
- {
- if (m_val == 0)
- {
- m_val = 1;
- if (m_level)
- {
- result = true;
- }
- }
- }
- }
- }
- }
-
- /* Modify the key state based on qual(s)
- * Tested carefully. don't touch unless your really sure.
- * note, this will only change the results if key modifiers are set.
- *
- * When all modifiers and keys are positive
- * - pulse true
- *
- * When ANY of the modifiers or main key become inactive,
- * - pulse false
- */
- if (qual==false) { /* one of the qualifiers are not pressed */
- if (m_val_orig && qual_change) { /* we were originally enabled, but a qualifier changed */
- result = true;
- } else {
- result = false;
- }
- m_val = 0; /* since one of the qualifiers is not on, set the state to false */
- } else { /* we done have any qualifiers or they are all pressed */
- if (m_val && qual_change) { /* the main key state is true and our qualifier just changed */
- result = true;
- }
- }
- /* done with key quals */
-
- }
-
- if (reset)
- // force an event
- result = true;
- return result;
-
-}
-
-void SCA_KeyboardSensor::AddToTargetProp(int keyIndex, int unicode)
-{
- if (IsPrintable(keyIndex)) {
- CValue* tprop = GetParent()->GetProperty(m_targetprop);
-
- if (IsDelete(keyIndex)) {
- /* Make a new property. Deletes can be ignored. */
- if (tprop) {
- /* overwrite the old property */
- /* strip one char, if possible */
- STR_String newprop = tprop->GetText();
- int oldlength = newprop.Length();
- if (oldlength >= 1 ) {
- int newlength=oldlength;
-
- BLI_str_cursor_step_prev_utf8(newprop, newprop.Length(), &newlength);
- newprop.SetLength(newlength);
-
- CStringValue * newstringprop = new CStringValue(newprop, m_targetprop);
- GetParent()->SetProperty(m_targetprop, newstringprop);
- newstringprop->Release();
- }
- }
- }
- else {
- char utf8_buf[7];
- size_t utf8_len;
-
- utf8_len = BLI_str_utf8_from_unicode(unicode, utf8_buf);
- utf8_buf[utf8_len] = '\0';
-
- STR_String newprop = tprop ? (tprop->GetText() + utf8_buf) : utf8_buf;
-
- CStringValue * newstringprop = new CStringValue(newprop, m_targetprop);
- GetParent()->SetProperty(m_targetprop, newstringprop);
- newstringprop->Release();
- }
- }
-}
-
-/**
- * Tests whether shift is pressed
- */
-bool SCA_KeyboardSensor::IsShifted(void)
-{
- SCA_IInputDevice* inputdev = ((SCA_KeyboardManager *)m_eventmgr)->GetInputDevice();
-
- if ( (inputdev->GetEventValue(SCA_IInputDevice::KX_RIGHTSHIFTKEY).m_status
- == SCA_InputEvent::KX_ACTIVE)
- || (inputdev->GetEventValue(SCA_IInputDevice::KX_RIGHTSHIFTKEY).m_status
- == SCA_InputEvent::KX_JUSTACTIVATED)
- || (inputdev->GetEventValue(SCA_IInputDevice::KX_LEFTSHIFTKEY).m_status
- == SCA_InputEvent::KX_ACTIVE)
- || (inputdev->GetEventValue(SCA_IInputDevice::KX_LEFTSHIFTKEY).m_status
- == SCA_InputEvent::KX_JUSTACTIVATED)
- ) {
- return true;
- }
- else {
- return false;
- }
-}
-
-void SCA_KeyboardSensor::LogKeystrokes(void)
-{
- SCA_IInputDevice* inputdev = ((SCA_KeyboardManager *)m_eventmgr)->GetInputDevice();
- int num = inputdev->GetNumActiveEvents();
-
- /* weird loop, this one... */
- if (num > 0)
- {
-
- int index = 0;
- /* Check on all keys whether they were pushed. This does not
- * untangle the ordering, so don't type too fast :) */
- for (int i=SCA_IInputDevice::KX_BEGINKEY ; i<= SCA_IInputDevice::KX_ENDKEY;i++)
- {
- const SCA_InputEvent & inevent = inputdev->GetEventValue((SCA_IInputDevice::KX_EnumInputs) i);
- if (inevent.m_status == SCA_InputEvent::KX_JUSTACTIVATED) //NO_INPUTSTATUS)
- {
- if (index < num)
- {
- AddToTargetProp(i, inevent.m_unicode);
- index++;
- }
- }
- }
- }
-}
-
-#ifdef WITH_PYTHON
-
-/* ------------------------------------------------------------------------- */
-/* Python Functions */
-/* ------------------------------------------------------------------------- */
-
-KX_PYMETHODDEF_DOC_O(SCA_KeyboardSensor, getKeyStatus,
-"getKeyStatus(keycode)\n"
-"\tGet the given key's status (KX_NO_INPUTSTATUS, KX_JUSTACTIVATED, KX_ACTIVE or KX_JUSTRELEASED).\n")
-{
- if (!PyLong_Check(value)) {
- PyErr_SetString(PyExc_ValueError, "sensor.getKeyStatus(int): Keyboard Sensor, expected an int");
- return NULL;
- }
-
- SCA_IInputDevice::KX_EnumInputs keycode = (SCA_IInputDevice::KX_EnumInputs)PyLong_AsLong(value);
-
- if ((keycode < SCA_IInputDevice::KX_BEGINKEY) ||
- (keycode > SCA_IInputDevice::KX_ENDKEY))
- {
- PyErr_SetString(PyExc_AttributeError, "sensor.getKeyStatus(int): Keyboard Sensor, invalid keycode specified!");
- return NULL;
- }
-
- SCA_IInputDevice* inputdev = ((SCA_KeyboardManager *)m_eventmgr)->GetInputDevice();
- const SCA_InputEvent & inevent = inputdev->GetEventValue(keycode);
- return PyLong_FromLong(inevent.m_status);
-}
-
-/* ------------------------------------------------------------------------- */
-/* Python Integration Hooks */
-/* ------------------------------------------------------------------------- */
-
-PyTypeObject SCA_KeyboardSensor::Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "SCA_KeyboardSensor",
- sizeof(PyObjectPlus_Proxy),
- 0,
- py_base_dealloc,
- 0,
- 0,
- 0,
- 0,
- py_base_repr,
- 0,0,0,0,0,0,0,0,0,
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
- 0,0,0,0,0,0,0,
- Methods,
- 0,
- 0,
- &SCA_ISensor::Type,
- 0,0,0,0,0,0,
- py_base_new
-};
-
-PyMethodDef SCA_KeyboardSensor::Methods[] = {
- KX_PYMETHODTABLE_O(SCA_KeyboardSensor, getKeyStatus),
- {NULL,NULL} //Sentinel
-};
-
-PyAttributeDef SCA_KeyboardSensor::Attributes[] = {
- KX_PYATTRIBUTE_RO_FUNCTION("events", SCA_KeyboardSensor, pyattr_get_events),
- KX_PYATTRIBUTE_BOOL_RW("useAllKeys",SCA_KeyboardSensor,m_bAllKeys),
- KX_PYATTRIBUTE_INT_RW("key",0,SCA_IInputDevice::KX_ENDKEY,true,SCA_KeyboardSensor,m_hotkey),
- KX_PYATTRIBUTE_SHORT_RW("hold1",0,SCA_IInputDevice::KX_ENDKEY,true,SCA_KeyboardSensor,m_qual),
- KX_PYATTRIBUTE_SHORT_RW("hold2",0,SCA_IInputDevice::KX_ENDKEY,true,SCA_KeyboardSensor,m_qual2),
- KX_PYATTRIBUTE_STRING_RW("toggleProperty",0,MAX_PROP_NAME,false,SCA_KeyboardSensor,m_toggleprop),
- KX_PYATTRIBUTE_STRING_RW("targetProperty",0,MAX_PROP_NAME,false,SCA_KeyboardSensor,m_targetprop),
- { NULL } //Sentinel
-};
-
-
-PyObject *SCA_KeyboardSensor::pyattr_get_events(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- SCA_KeyboardSensor* self = static_cast<SCA_KeyboardSensor*>(self_v);
-
- SCA_IInputDevice* inputdev = ((SCA_KeyboardManager *)self->m_eventmgr)->GetInputDevice();
-
- PyObject *resultlist = PyList_New(0);
-
- for (int i=SCA_IInputDevice::KX_BEGINKEY ; i<= SCA_IInputDevice::KX_ENDKEY;i++)
- {
- const SCA_InputEvent & inevent = inputdev->GetEventValue((SCA_IInputDevice::KX_EnumInputs) i);
- if (inevent.m_status != SCA_InputEvent::KX_NO_INPUTSTATUS)
- {
- PyObject *keypair = PyList_New(2);
- PyList_SET_ITEM(keypair,0,PyLong_FromLong(i));
- PyList_SET_ITEM(keypair,1,PyLong_FromLong(inevent.m_status));
- PyList_Append(resultlist,keypair);
- Py_DECREF(keypair);
- }
- }
- return resultlist;
-}
-
-#endif // WITH_PYTHON
-
-/* Accessed from python */
-
-// this code looks ugly, please use an ordinary hashtable
-
-char ToCharacter(int keyIndex, bool shifted)
-{
- /* numerals */
- if ( (keyIndex >= SCA_IInputDevice::KX_ZEROKEY)
- && (keyIndex <= SCA_IInputDevice::KX_NINEKEY) ) {
- if (shifted) {
- char numshift[] = ")!@#$%^&*(";
- return numshift[keyIndex - '0'];
- } else {
- return keyIndex - SCA_IInputDevice::KX_ZEROKEY + '0';
- }
- }
-
- /* letters... always lowercase... is that desirable? */
- if ( (keyIndex >= SCA_IInputDevice::KX_AKEY)
- && (keyIndex <= SCA_IInputDevice::KX_ZKEY) ) {
- if (shifted) {
- return keyIndex - SCA_IInputDevice::KX_AKEY + 'A';
- } else {
- return keyIndex - SCA_IInputDevice::KX_AKEY + 'a';
- }
- }
-
- if (keyIndex == SCA_IInputDevice::KX_SPACEKEY) {
- return ' ';
- }
- if (keyIndex == SCA_IInputDevice::KX_RETKEY || keyIndex == SCA_IInputDevice::KX_PADENTER) {
- return '\n';
- }
-
-
- if (keyIndex == SCA_IInputDevice::KX_PADASTERKEY) {
- return '*';
- }
-
- if (keyIndex == SCA_IInputDevice::KX_TABKEY) {
- return '\t';
- }
-
- /* comma to period */
- char commatoperiod[] = ",-.";
- char commatoperiodshifted[] = "<_>";
- if (keyIndex == SCA_IInputDevice::KX_COMMAKEY) {
- if (shifted) {
- return commatoperiodshifted[0];
- } else {
- return commatoperiod[0];
- }
- }
- if (keyIndex == SCA_IInputDevice::KX_MINUSKEY) {
- if (shifted) {
- return commatoperiodshifted[1];
- } else {
- return commatoperiod[1];
- }
- }
- if (keyIndex == SCA_IInputDevice::KX_PERIODKEY) {
- if (shifted) {
- return commatoperiodshifted[2];
- } else {
- return commatoperiod[2];
- }
- }
-
- /* semicolon to rightbracket */
- char semicolontorightbracket[] = ";\'`/\\=[]";
- char semicolontorightbracketshifted[] = ":\"~\?|+{}";
- if ((keyIndex >= SCA_IInputDevice::KX_SEMICOLONKEY)
- && (keyIndex <= SCA_IInputDevice::KX_RIGHTBRACKETKEY)) {
- if (shifted) {
- return semicolontorightbracketshifted[keyIndex - SCA_IInputDevice::KX_SEMICOLONKEY];
- } else {
- return semicolontorightbracket[keyIndex - SCA_IInputDevice::KX_SEMICOLONKEY];
- }
- }
-
- /* keypad2 to padplus */
- char pad2topadplus[] = "246813579. 0- +";
- if ((keyIndex >= SCA_IInputDevice::KX_PAD2)
- && (keyIndex <= SCA_IInputDevice::KX_PADPLUSKEY)) {
- return pad2topadplus[keyIndex - SCA_IInputDevice::KX_PAD2];
- }
-
- return '!';
-}
-
-
-
-/**
- * Determine whether this character can be printed. We cannot use
- * the library functions here, because we need to test our own
- * keycodes. */
-bool IsPrintable(int keyIndex)
-{
- /* only print
- * - numerals: KX_ZEROKEY to KX_NINEKEY
- * - alphas: KX_AKEY to KX_ZKEY.
- * - specials: KX_RETKEY, KX_PADASTERKEY, KX_PADCOMMAKEY to KX_PERIODKEY,
- * KX_TABKEY, KX_SEMICOLONKEY to KX_RIGHTBRACKETKEY,
- * KX_PAD2 to KX_PADPLUSKEY
- * - delete and backspace: also printable in the sense that they modify
- * the string
- * - retkey: should this be printable?
- * - virgule: prints a space... don't know which key that's supposed
- * to be...
- */
- if ( ((keyIndex >= SCA_IInputDevice::KX_ZEROKEY)
- && (keyIndex <= SCA_IInputDevice::KX_NINEKEY))
- || ((keyIndex >= SCA_IInputDevice::KX_AKEY)
- && (keyIndex <= SCA_IInputDevice::KX_ZKEY))
- || (keyIndex == SCA_IInputDevice::KX_SPACEKEY)
- || (keyIndex == SCA_IInputDevice::KX_RETKEY)
- || (keyIndex == SCA_IInputDevice::KX_PADENTER)
- || (keyIndex == SCA_IInputDevice::KX_PADASTERKEY)
- || (keyIndex == SCA_IInputDevice::KX_TABKEY)
- || ((keyIndex >= SCA_IInputDevice::KX_COMMAKEY)
- && (keyIndex <= SCA_IInputDevice::KX_PERIODKEY))
- || ((keyIndex >= SCA_IInputDevice::KX_SEMICOLONKEY)
- && (keyIndex <= SCA_IInputDevice::KX_RIGHTBRACKETKEY))
- || ((keyIndex >= SCA_IInputDevice::KX_PAD2)
- && (keyIndex <= SCA_IInputDevice::KX_PADPLUSKEY))
- || (keyIndex == SCA_IInputDevice::KX_DELKEY)
- || (keyIndex == SCA_IInputDevice::KX_BACKSPACEKEY)
- )
- {
- return true;
- } else {
- return false;
- }
-}
-
-/**
- * Tests whether this is a delete key.
- */
-bool IsDelete(int keyIndex)
-{
- if ( (keyIndex == SCA_IInputDevice::KX_DELKEY)
- || (keyIndex == SCA_IInputDevice::KX_BACKSPACEKEY) ) {
- return true;
- } else {
- return false;
- }
-}
diff --git a/source/gameengine/GameLogic/SCA_KeyboardSensor.h b/source/gameengine/GameLogic/SCA_KeyboardSensor.h
deleted file mode 100644
index 51d7756bd1f..00000000000
--- a/source/gameengine/GameLogic/SCA_KeyboardSensor.h
+++ /dev/null
@@ -1,141 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file SCA_KeyboardSensor.h
- * \ingroup gamelogic
- * \brief Sensor for keyboard input
- */
-
-#ifndef __SCA_KEYBOARDSENSOR_H__
-#define __SCA_KEYBOARDSENSOR_H__
-
-#include "SCA_ISensor.h"
-#include "EXP_BoolValue.h"
-#include <list>
-
-/**
- * The keyboard sensor listens to the keyboard, and passes on events
- * on selected keystrokes. It has an alternate mode in which it logs
- * keypresses to a property. Note that these modes are not mutually
- * exclusive. */
-class SCA_KeyboardSensor : public SCA_ISensor
-{
- Py_Header
-
- /**
- * the key this sensor is sensing for
- */
- int m_hotkey;
- short int m_qual,m_qual2;
- short int m_val;
- /**
- * If this toggle is true, all incoming key events generate a
- * response.
- */
- bool m_bAllKeys;
-
- /**
- * The name of the property to which logged text is appended. If
- * this property is not defined, no logging takes place.
- */
- STR_String m_targetprop;
- /**
- * The property that indicates whether or not to log text when in
- * logging mode. If the property equals 0, no logging is done. For
- * all other values, logging is active. Logging can only become
- * active if there is a property to log to. Logging is independent
- * from hotkey settings. */
- STR_String m_toggleprop;
-
- /**
- * Log the keystrokes from the current input buffer.
- */
- void LogKeystrokes(void);
-
- /**
- * Adds this key-code to the target prop.
- */
- void AddToTargetProp(int keyIndex, int unicode);
-
- /**
- * Tests whether shift is pressed.
- */
- bool IsShifted(void);
-
-public:
- SCA_KeyboardSensor(class SCA_KeyboardManager* keybdmgr,
- short int hotkey,
- short int qual,
- short int qual2,
- bool bAllKeys,
- const STR_String& targetProp,
- const STR_String& toggleProp,
- SCA_IObject* gameobj,
- short int exitKey);
- virtual ~SCA_KeyboardSensor();
- virtual CValue* GetReplica();
- virtual void Init();
-
-
- short int GetHotkey();
- virtual bool Evaluate();
- virtual bool IsPositiveTrigger();
- bool TriggerOnAllKeys();
-
-#ifdef WITH_PYTHON
- /* --------------------------------------------------------------------- */
- /* Python interface ---------------------------------------------------- */
- /* --------------------------------------------------------------------- */
-
- // KeyEvents:
- KX_PYMETHOD_DOC_NOARGS(SCA_KeyboardSensor,getEventList);
- // KeyStatus:
- KX_PYMETHOD_DOC_O(SCA_KeyboardSensor,getKeyStatus);
-
- static PyObject* pyattr_get_events(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef);
-#endif
-};
-
-
-/**
- * Transform keycodes to something printable.
- */
-char ToCharacter(int keyIndex, bool shifted);
-
-/**
- * Determine whether this character can be printed. We cannot use
- * the library functions here, because we need to test our own
- * keycodes. */
-bool IsPrintable(int keyIndex);
-
-/**
- * Tests whether this is a delete key.
- */
-bool IsDelete(int keyIndex);
-
-
-#endif /* __SCA_KEYBOARDSENSOR_H__ */
diff --git a/source/gameengine/GameLogic/SCA_LogicManager.cpp b/source/gameengine/GameLogic/SCA_LogicManager.cpp
deleted file mode 100644
index 978f6d6b836..00000000000
--- a/source/gameengine/GameLogic/SCA_LogicManager.cpp
+++ /dev/null
@@ -1,342 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- * Regulates the top-level logic behavior for one scene.
- */
-
-/** \file gameengine/GameLogic/SCA_LogicManager.cpp
- * \ingroup gamelogic
- */
-
-#include "EXP_Value.h"
-#include "SCA_LogicManager.h"
-#include "SCA_ISensor.h"
-#include "SCA_IController.h"
-#include "SCA_IActuator.h"
-#include "SCA_EventManager.h"
-#include "SCA_PythonController.h"
-#include <set>
-
-
-SCA_LogicManager::SCA_LogicManager()
-{
-}
-
-
-
-SCA_LogicManager::~SCA_LogicManager()
-{
- for (vector<SCA_EventManager*>::iterator it = m_eventmanagers.begin();!(it==m_eventmanagers.end());++it)
- {
- delete (*it);
- }
- m_eventmanagers.clear();
- assert(m_activeActuators.Empty());
-}
-
-#if 0
-// this kind of fixes bug 398 but breakes games, so better leave it out for now.
-// a removed object's gameobject (and logicbricks and stuff) didn't get released
-// because it was still in the m_mapStringToGameObjects map.
-void SCA_LogicManager::RemoveGameObject(const STR_String& gameobjname)
-{
- int numgameobj = m_mapStringToGameObjects.size();
- for (int i = 0; i < numgameobj; i++)
- {
- CValue** gameobjptr = m_mapStringToGameObjects.at(i);
- assert(gameobjptr);
-
- if (gameobjptr)
- {
- if ((*gameobjptr)->GetName() == gameobjname)
- (*gameobjptr)->Release();
- }
- }
-
- m_mapStringToGameObjects.remove(gameobjname);
-}
-#endif
-
-
-void SCA_LogicManager::RegisterEventManager(SCA_EventManager* eventmgr)
-{
- m_eventmanagers.push_back(eventmgr);
-}
-
-
-
-void SCA_LogicManager::RegisterGameObjectName(const STR_String& gameobjname,
- CValue* gameobj)
-{
- STR_HashedString mn = gameobjname;
- m_mapStringToGameObjects.insert(mn,gameobj);
-}
-
-
-
-void SCA_LogicManager::RegisterGameMeshName(const STR_String& gamemeshname, void* blendobj)
-{
- STR_HashedString mn = gamemeshname;
- m_map_gamemeshname_to_blendobj.insert(mn, blendobj);
-}
-
-
-
-void SCA_LogicManager::RegisterGameObj(void* blendobj, CValue* gameobj)
-{
- m_map_blendobj_to_gameobj.insert(CHashedPtr(blendobj), gameobj);
-}
-
-void SCA_LogicManager::UnregisterGameObj(void* blendobj, CValue* gameobj)
-{
- void **obp = m_map_blendobj_to_gameobj[CHashedPtr(blendobj)];
- if (obp && (CValue*)(*obp) == gameobj)
- m_map_blendobj_to_gameobj.remove(CHashedPtr(blendobj));
-}
-
-CValue* SCA_LogicManager::GetGameObjectByName(const STR_String& gameobjname)
-{
- STR_HashedString mn = gameobjname;
- CValue** gameptr = m_mapStringToGameObjects[mn];
-
- if (gameptr)
- return *gameptr;
-
- return NULL;
-}
-
-
-CValue* SCA_LogicManager::FindGameObjByBlendObj(void* blendobj)
-{
- void **obp= m_map_blendobj_to_gameobj[CHashedPtr(blendobj)];
- return obp?(CValue*)(*obp):NULL;
-}
-
-
-
-void* SCA_LogicManager::FindBlendObjByGameMeshName(const STR_String& gamemeshname)
-{
- STR_HashedString mn = gamemeshname;
- void **obp= m_map_gamemeshname_to_blendobj[mn];
- return obp?*obp:NULL;
-}
-
-
-
-void SCA_LogicManager::RemoveSensor(SCA_ISensor* sensor)
-{
- sensor->UnlinkAllControllers();
- sensor->UnregisterToManager();
-}
-
-void SCA_LogicManager::RemoveController(SCA_IController* controller)
-{
- controller->UnlinkAllSensors();
- controller->UnlinkAllActuators();
- controller->Deactivate();
-}
-
-
-void SCA_LogicManager::RemoveActuator(SCA_IActuator* actuator)
-{
- actuator->UnlinkAllControllers();
- actuator->Deactivate();
- actuator->SetActive(false);
-}
-
-
-
-void SCA_LogicManager::RegisterToSensor(SCA_IController* controller,SCA_ISensor* sensor)
-{
- sensor->LinkToController(controller);
- controller->LinkToSensor(sensor);
-}
-
-
-
-void SCA_LogicManager::RegisterToActuator(SCA_IController* controller,SCA_IActuator* actua)
-{
- actua->LinkToController(controller);
- controller->LinkToActuator(actua);
-}
-
-
-
-void SCA_LogicManager::BeginFrame(double curtime, double fixedtime)
-{
- for (vector<SCA_EventManager*>::const_iterator ie=m_eventmanagers.begin(); !(ie==m_eventmanagers.end()); ie++)
- (*ie)->NextFrame(curtime, fixedtime);
-
- for (SG_QList* obj = (SG_QList*)m_triggeredControllerSet.Remove();
- obj != NULL;
- obj = (SG_QList*)m_triggeredControllerSet.Remove())
- {
- for (SCA_IController* contr = (SCA_IController*)obj->QRemove();
- contr != NULL;
- contr = (SCA_IController*)obj->QRemove())
- {
- contr->Trigger(this);
- contr->ClrJustActivated();
- }
- }
-}
-
-
-
-void SCA_LogicManager::UpdateFrame(double curtime, bool frame)
-{
- for (vector<SCA_EventManager*>::const_iterator ie=m_eventmanagers.begin(); !(ie==m_eventmanagers.end()); ie++)
- (*ie)->UpdateFrame();
-
- SG_DList::iterator<SG_QList> io(m_activeActuators);
- for (io.begin(); !io.end(); )
- {
- SG_QList* ahead = *io;
- // increment now so that we can remove the current element
- ++io;
- SG_QList::iterator<SCA_IActuator> ia(*ahead);
- for (ia.begin(); !ia.end(); )
- {
- SCA_IActuator* actua = *ia;
- // increment first to allow removal of inactive actuators.
- ++ia;
- if (!actua->Update(curtime, frame))
- {
- // this actuator is not active anymore, remove
- actua->QDelink();
- actua->SetActive(false);
- } else if (actua->IsNoLink())
- {
- // This actuator has no more links but it still active
- // make sure it will get a negative event on next frame to stop it
- // Do this check after Update() rather than before to make sure
- // that all the actuators that are activated at same time than a state
- // actuator have a chance to execute.
- bool event = false;
- actua->RemoveAllEvents();
- actua->AddEvent(event);
- }
- }
- if (ahead->QEmpty())
- {
- // no more active controller, remove from main list
- ahead->Delink();
- }
- }
-}
-
-
-
-void *SCA_LogicManager::GetActionByName(const STR_String& actname)
-{
- STR_HashedString an = actname;
- void** actptr = m_mapStringToActions[an];
-
- if (actptr)
- return *actptr;
-
- return NULL;
-}
-
-
-
-void* SCA_LogicManager::GetMeshByName(const STR_String& meshname)
-{
- STR_HashedString mn = meshname;
- void** meshptr = m_mapStringToMeshes[mn];
-
- if (meshptr)
- return *meshptr;
-
- return NULL;
-}
-
-
-
-void SCA_LogicManager::RegisterMeshName(const STR_String& meshname,void* mesh)
-{
- STR_HashedString mn = meshname;
- m_mapStringToMeshes.insert(mn,mesh);
-}
-
-void SCA_LogicManager::UnregisterMeshName(const STR_String& meshname,void* mesh)
-{
- STR_HashedString mn = meshname;
- m_mapStringToMeshes.remove(mn);
-}
-
-
-void SCA_LogicManager::RegisterActionName(const STR_String& actname,void* action)
-{
- STR_HashedString an = actname;
- m_mapStringToActions.insert(an, action);
-}
-
-
-
-void SCA_LogicManager::EndFrame()
-{
- for (vector<SCA_EventManager*>::const_iterator ie=m_eventmanagers.begin();
- !(ie==m_eventmanagers.end());ie++)
- {
- (*ie)->EndFrame();
- }
-}
-
-
-void SCA_LogicManager::AddTriggeredController(SCA_IController* controller, SCA_ISensor* sensor)
-{
- controller->Activate(m_triggeredControllerSet);
-
-#ifdef WITH_PYTHON
-
- // so that the controller knows which sensor has activited it
- // only needed for python controller
- // Note that this is safe even if the controller is subclassed.
- if (controller->GetType() == &SCA_PythonController::Type)
- {
- SCA_PythonController* pythonController = (SCA_PythonController*)controller;
- pythonController->AddTriggeredSensor(sensor);
- }
-#endif
-}
-
-SCA_EventManager* SCA_LogicManager::FindEventManager(int eventmgrtype)
-{
- // find an eventmanager of a certain type
- SCA_EventManager* eventmgr = NULL;
-
- for (vector<SCA_EventManager*>::const_iterator i=
- m_eventmanagers.begin();!(i==m_eventmanagers.end());i++)
- {
- SCA_EventManager* emgr = *i;
- if (emgr->GetType() == eventmgrtype)
- {
- eventmgr = emgr;
- break;
- }
- }
- return eventmgr;
-}
diff --git a/source/gameengine/GameLogic/SCA_LogicManager.h b/source/gameengine/GameLogic/SCA_LogicManager.h
deleted file mode 100644
index 7319bb537dd..00000000000
--- a/source/gameengine/GameLogic/SCA_LogicManager.h
+++ /dev/null
@@ -1,154 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-/** \file SCA_LogicManager.h
- * \ingroup gamelogic
- * \brief Regulates the top-level logic behavior for one scene.
- */
-#ifndef __SCA_LOGICMANAGER_H__
-#define __SCA_LOGICMANAGER_H__
-
-#ifdef _MSC_VER
-# pragma warning (disable:4786)
-#endif
-
-#include <vector>
-//#include "CTR_Map.h"
-#include <set>
-#include <map>
-#include <list>
-
-#include "CTR_Map.h"
-#include "STR_HashedString.h"
-#include "EXP_Value.h"
-#include "SG_QList.h"
-
-#include "EXP_HashedPtr.h"
-
-using namespace std;
-typedef std::list<class SCA_IController*> controllerlist;
-typedef std::map<class SCA_ISensor*,controllerlist > sensormap_t;
-
-/**
- * This manager handles sensor, controllers and actuators.
- * logic executes each frame the following way:
- * find triggering sensors
- * build list of controllers that are triggered by these triggering sensors
- * process all triggered controllers
- * during this phase actuators can be added to the active actuator list
- * process all active actuators
- * clear triggering sensors
- * clear triggered controllers
- * (actuators may be active during a longer timeframe)
- */
-
-#include "SCA_ILogicBrick.h"
-#include "SCA_IActuator.h"
-#include "SCA_EventManager.h"
-
-
-class SCA_LogicManager
-{
- vector<class SCA_EventManager*> m_eventmanagers;
-
- // SG_DList: Head of objects having activated actuators
- // element: SCA_IObject::m_activeActuators
- SG_DList m_activeActuators;
- // SG_DList: Head of objects having activated controllers
- // element: SCA_IObject::m_activeControllers
- SG_DList m_triggeredControllerSet;
-
- // need to find better way for this
- // also known as FactoryManager...
- CTR_Map<STR_HashedString,CValue*> m_mapStringToGameObjects;
- CTR_Map<STR_HashedString,void*> m_mapStringToMeshes;
- CTR_Map<STR_HashedString,void*> m_mapStringToActions;
-
- CTR_Map<STR_HashedString,void*> m_map_gamemeshname_to_blendobj;
- CTR_Map<CHashedPtr,void*> m_map_blendobj_to_gameobj;
-public:
- SCA_LogicManager();
- virtual ~SCA_LogicManager();
-
- //void SetKeyboardManager(SCA_KeyboardManager* keyboardmgr) { m_keyboardmgr=keyboardmgr;}
- void RegisterEventManager(SCA_EventManager* eventmgr);
- void RegisterToSensor(SCA_IController* controller,
- class SCA_ISensor* sensor);
- void RegisterToActuator(SCA_IController* controller,
- class SCA_IActuator* actuator);
-
- void BeginFrame(double curtime, double fixedtime);
- void UpdateFrame(double curtime, bool frame);
- void EndFrame();
- void AddActiveActuator(SCA_IActuator* actua,bool event)
- {
- actua->SetActive(true);
- actua->Activate(m_activeActuators);
- actua->AddEvent(event);
- }
-
- void AddTriggeredController(SCA_IController* controller, SCA_ISensor* sensor);
- SCA_EventManager* FindEventManager(int eventmgrtype);
- vector<class SCA_EventManager*> GetEventManagers() { return m_eventmanagers; }
-
- void RemoveGameObject(const STR_String& gameobjname);
-
- /**
- * remove Logic Bricks from the running logicmanager
- */
- void RemoveSensor(SCA_ISensor* sensor);
- void RemoveController(SCA_IController* controller);
- void RemoveActuator(SCA_IActuator* actuator);
-
-
- // for the scripting... needs a FactoryManager later (if we would have time... ;)
- void RegisterMeshName(const STR_String& meshname,void* mesh);
- void UnregisterMeshName(const STR_String& meshname,void* mesh);
- CTR_Map<STR_HashedString,void*>& GetMeshMap() { return m_mapStringToMeshes; }
- CTR_Map<STR_HashedString,void*>& GetActionMap() { return m_mapStringToActions; }
-
- void RegisterActionName(const STR_String& actname,void* action);
-
- void* GetActionByName (const STR_String& actname);
- void* GetMeshByName(const STR_String& meshname);
-
- void RegisterGameObjectName(const STR_String& gameobjname,CValue* gameobj);
- class CValue* GetGameObjectByName(const STR_String& gameobjname);
-
- void RegisterGameMeshName(const STR_String& gamemeshname, void* blendobj);
- void* FindBlendObjByGameMeshName(const STR_String& gamemeshname);
-
- void RegisterGameObj(void* blendobj, CValue* gameobj);
- void UnregisterGameObj(void* blendobj, CValue* gameobj);
- CValue* FindGameObjByBlendObj(void* blendobj);
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:SCA_LogicManager")
-#endif
-};
-
-#endif /* __SCA_LOGICMANAGER_H__ */
diff --git a/source/gameengine/GameLogic/SCA_MouseManager.cpp b/source/gameengine/GameLogic/SCA_MouseManager.cpp
deleted file mode 100644
index 51c03d1e350..00000000000
--- a/source/gameengine/GameLogic/SCA_MouseManager.cpp
+++ /dev/null
@@ -1,112 +0,0 @@
-/*
- * Manager for mouse events
- *
- *
- *
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/GameLogic/SCA_MouseManager.cpp
- * \ingroup gamelogic
- */
-
-
-#ifdef _MSC_VER
- /* This warning tells us about truncation of __long__ stl-generated names.
- * It can occasionally cause DevStudio to have internal compiler warnings. */
-# pragma warning( disable:4786 )
-#endif
-
-#include "EXP_BoolValue.h"
-#include "SCA_MouseManager.h"
-#include "SCA_MouseSensor.h"
-#include "EXP_IntValue.h"
-#include "RAS_ICanvas.h"
-
-
-SCA_MouseManager::SCA_MouseManager(SCA_LogicManager* logicmgr,
- SCA_IInputDevice* mousedev,
- RAS_ICanvas* canvas)
- : SCA_EventManager(logicmgr, MOUSE_EVENTMGR),
- m_mousedevice (mousedev),
- m_canvas(canvas)
-{
- m_xpos = 0;
- m_ypos = 0;
-}
-
-
-
-SCA_MouseManager::~SCA_MouseManager()
-{
-}
-
-
-
-SCA_IInputDevice* SCA_MouseManager::GetInputDevice()
-{
- return m_mousedevice;
-}
-
-
-
-void SCA_MouseManager::NextFrame()
-{
- if (m_mousedevice)
- {
- SG_DList::iterator<SCA_ISensor> it(m_sensors);
- for (it.begin();!it.end();++it)
- {
- SCA_MouseSensor* mousesensor = (SCA_MouseSensor*)(*it);
- // (0,0) is the Upper Left corner in our local window
- // coordinates
- if (!mousesensor->IsSuspended())
- {
- const SCA_InputEvent& event1 =
- m_mousedevice->GetEventValue(SCA_IInputDevice::KX_MOUSEX);
- const SCA_InputEvent& event2 =
- m_mousedevice->GetEventValue(SCA_IInputDevice::KX_MOUSEY);
-
- int mx = this->m_canvas->GetMouseX(event1.m_eventval);
- int my = this->m_canvas->GetMouseY(event2.m_eventval);
-
- mousesensor->setX(mx);
- mousesensor->setY(my);
-
- mousesensor->Activate(m_logicmgr);
- }
- }
- }
-}
-
-bool SCA_MouseManager::IsPressed(SCA_IInputDevice::KX_EnumInputs inputcode)
-{
- /* We should guard for non-mouse events maybe? A rather silly side */
- /* effect here is that position-change events are considered presses as */
- /* well. */
-
- return m_mousedevice->IsPressed(inputcode);
-}
diff --git a/source/gameengine/GameLogic/SCA_MouseManager.h b/source/gameengine/GameLogic/SCA_MouseManager.h
deleted file mode 100644
index a57e52070a7..00000000000
--- a/source/gameengine/GameLogic/SCA_MouseManager.h
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file SCA_MouseManager.h
- * \ingroup gamelogic
- * \brief Manager for mouse events.
- *
- */
-
-
-#ifndef __SCA_MOUSEMANAGER_H__
-#define __SCA_MOUSEMANAGER_H__
-
-
-#include "SCA_EventManager.h"
-
-#include <vector>
-
-using namespace std;
-
-#include "SCA_IInputDevice.h"
-
-
-class SCA_MouseManager : public SCA_EventManager
-{
-
- class SCA_IInputDevice* m_mousedevice;
- class RAS_ICanvas* m_canvas;
-
- unsigned short m_xpos; // Cached location of the mouse pointer
- unsigned short m_ypos;
-
-public:
- SCA_MouseManager(class SCA_LogicManager* logicmgr,class SCA_IInputDevice* mousedev, class RAS_ICanvas* canvas);
- virtual ~SCA_MouseManager();
-
- /**
- * Checks whether a mouse button is depressed. Ignores requests on non-
- * mouse related events. Can also flag mouse movement.
- */
- bool IsPressed(SCA_IInputDevice::KX_EnumInputs inputcode);
- virtual void NextFrame();
- SCA_IInputDevice* GetInputDevice();
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:SCA_MouseManager")
-#endif
-};
-
-#endif /* __SCA_MOUSEMANAGER_H__ */
diff --git a/source/gameengine/GameLogic/SCA_MouseSensor.cpp b/source/gameengine/GameLogic/SCA_MouseSensor.cpp
deleted file mode 100644
index 2479e859dea..00000000000
--- a/source/gameengine/GameLogic/SCA_MouseSensor.cpp
+++ /dev/null
@@ -1,317 +0,0 @@
-/*
- * Sensor for mouse input
- *
- *
- *
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): José I. Romero (cleanup and fixes)
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/GameLogic/SCA_MouseSensor.cpp
- * \ingroup gamelogic
- */
-
-
-#include <stddef.h>
-
-#include "SCA_MouseSensor.h"
-#include "SCA_EventManager.h"
-#include "SCA_MouseManager.h"
-#include "SCA_LogicManager.h"
-#include "SCA_IInputDevice.h"
-#include "EXP_ConstExpr.h"
-#include <iostream>
-
-/* ------------------------------------------------------------------------- */
-/* Native functions */
-/* ------------------------------------------------------------------------- */
-
-SCA_MouseSensor::SCA_MouseSensor(SCA_MouseManager* eventmgr,
- int startx,int starty,
- short int mousemode,
- SCA_IObject* gameobj)
- : SCA_ISensor(gameobj,eventmgr),
- m_x(startx),
- m_y(starty)
-{
- m_mousemode = mousemode;
- m_triggermode = true;
-
- UpdateHotkey(this);
- Init();
-}
-
-void SCA_MouseSensor::Init()
-{
- m_val = (m_invert)?1:0; /* stores the latest attribute */
- m_reset = true;
-}
-
-SCA_MouseSensor::~SCA_MouseSensor()
-{
- /* Nothing to be done here. */
-}
-
-void SCA_MouseSensor::UpdateHotkey(void *self)
-{
- // gosh, this function is so damn stupid
- // its here because of a design mistake in the mouse sensor, it should only
- // have 3 trigger modes (button, wheel, move), and let the user set the
- // hotkey separately, like the other sensors. but instead it has a mode for
- // each friggin key and i have to update the hotkey based on it... genius!
- SCA_MouseSensor* sensor = reinterpret_cast<SCA_MouseSensor*>(self);
-
- switch (sensor->m_mousemode) {
- case KX_MOUSESENSORMODE_LEFTBUTTON:
- sensor->m_hotkey = SCA_IInputDevice::KX_LEFTMOUSE;
- break;
- case KX_MOUSESENSORMODE_MIDDLEBUTTON:
- sensor->m_hotkey = SCA_IInputDevice::KX_MIDDLEMOUSE;
- break;
- case KX_MOUSESENSORMODE_RIGHTBUTTON:
- sensor->m_hotkey = SCA_IInputDevice::KX_RIGHTMOUSE;
- break;
- case KX_MOUSESENSORMODE_WHEELUP:
- sensor->m_hotkey = SCA_IInputDevice::KX_WHEELUPMOUSE;
- break;
- case KX_MOUSESENSORMODE_WHEELDOWN:
- sensor->m_hotkey = SCA_IInputDevice::KX_WHEELDOWNMOUSE;
- break;
- default:
- ; /* ignore, no hotkey */
- }
-}
-
-CValue* SCA_MouseSensor::GetReplica()
-{
- SCA_MouseSensor* replica = new SCA_MouseSensor(*this);
- // this will copy properties and so on...
- replica->ProcessReplica();
- replica->Init();
-
- return replica;
-}
-
-
-
-bool SCA_MouseSensor::IsPositiveTrigger()
-{
- bool result = (m_val != 0);
- if (m_invert)
- result = !result;
-
- return result;
-}
-
-
-
-short int SCA_MouseSensor::GetModeKey()
-{
- return m_mousemode;
-}
-
-
-
-SCA_IInputDevice::KX_EnumInputs SCA_MouseSensor::GetHotKey()
-{
- return m_hotkey;
-}
-
-
-
-bool SCA_MouseSensor::Evaluate()
-{
- bool result = false;
- bool reset = m_reset && m_level;
- SCA_IInputDevice* mousedev = ((SCA_MouseManager *)m_eventmgr)->GetInputDevice();
-
- m_reset = false;
- switch (m_mousemode) {
- case KX_MOUSESENSORMODE_LEFTBUTTON:
- case KX_MOUSESENSORMODE_MIDDLEBUTTON:
- case KX_MOUSESENSORMODE_RIGHTBUTTON:
- case KX_MOUSESENSORMODE_WHEELUP:
- case KX_MOUSESENSORMODE_WHEELDOWN:
- {
- const SCA_InputEvent& mevent = mousedev->GetEventValue(m_hotkey);
- switch (mevent.m_status) {
- case SCA_InputEvent::KX_JUSTACTIVATED:
- m_val = 1;
- result = true;
- break;
- case SCA_InputEvent::KX_JUSTRELEASED:
- m_val = 0;
- result = true;
- break;
- case SCA_InputEvent::KX_ACTIVE:
- if (m_val == 0)
- {
- m_val = 1;
- if (m_level)
- result = true;
- }
- break;
- default:
- if (m_val == 1)
- {
- m_val = 0;
- result = true;
- }
- break;
- }
- break;
- }
- case KX_MOUSESENSORMODE_MOVEMENT:
- {
- const SCA_InputEvent& eventX = mousedev->GetEventValue(SCA_IInputDevice::KX_MOUSEX);
- const SCA_InputEvent& eventY = mousedev->GetEventValue(SCA_IInputDevice::KX_MOUSEY);
-
- if (eventX.m_status == SCA_InputEvent::KX_JUSTACTIVATED ||
- eventY.m_status == SCA_InputEvent::KX_JUSTACTIVATED ||
- eventX.m_status == SCA_InputEvent::KX_ACTIVE ||
- eventY.m_status == SCA_InputEvent::KX_ACTIVE)
- {
- m_val = 1;
- result = true;
- }
- else if (eventX.m_status == SCA_InputEvent::KX_JUSTRELEASED ||
- eventY.m_status == SCA_InputEvent::KX_JUSTRELEASED )
- {
- m_val = 0;
- result = true;
- }
- else //KX_NO_IMPUTSTATUS
- {
- if (m_val == 1)
- {
- m_val = 0;
- result = true;
- }
- }
-
- break;
- }
- default:
- ; /* error */
- }
-
- if (reset)
- // force an event
- result = true;
- return result;
-}
-
-void SCA_MouseSensor::setX(short x)
-{
- m_x = x;
-}
-
-void SCA_MouseSensor::setY(short y)
-{
- m_y = y;
-}
-
-bool SCA_MouseSensor::isValid(SCA_MouseSensor::KX_MOUSESENSORMODE m)
-{
- return ((m > KX_MOUSESENSORMODE_NODEF) && (m < KX_MOUSESENSORMODE_MAX));
-}
-
-#ifdef WITH_PYTHON
-
-/* ------------------------------------------------------------------------- */
-/* Python functions */
-/* ------------------------------------------------------------------------- */
-
-KX_PYMETHODDEF_DOC_O(SCA_MouseSensor, getButtonStatus,
-"getButtonStatus(button)\n"
-"\tGet the given button's status (KX_INPUT_NONE, KX_INPUT_NONE, KX_INPUT_JUST_ACTIVATED, KX_INPUT_ACTIVE, KX_INPUT_JUST_RELEASED).\n")
-{
- if (PyLong_Check(value))
- {
- SCA_IInputDevice::KX_EnumInputs button = (SCA_IInputDevice::KX_EnumInputs)PyLong_AsLong(value);
-
- if ((button < SCA_IInputDevice::KX_LEFTMOUSE) ||
- (button > SCA_IInputDevice::KX_RIGHTMOUSE))
- {
- PyErr_SetString(PyExc_ValueError, "sensor.getButtonStatus(int): Mouse Sensor, invalid button specified!");
- return NULL;
- }
-
- SCA_IInputDevice* mousedev = ((SCA_MouseManager *)m_eventmgr)->GetInputDevice();
- const SCA_InputEvent& event = mousedev->GetEventValue(button);
- return PyLong_FromLong(event.m_status);
- }
-
- Py_RETURN_NONE;
-}
-
-/* ------------------------------------------------------------------------- */
-/* Python Integration Hooks */
-/* ------------------------------------------------------------------------- */
-
-PyTypeObject SCA_MouseSensor::Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "SCA_MouseSensor",
- sizeof(PyObjectPlus_Proxy),
- 0,
- py_base_dealloc,
- 0,
- 0,
- 0,
- 0,
- py_base_repr,
- 0,0,0,0,0,0,0,0,0,
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
- 0,0,0,0,0,0,0,
- Methods,
- 0,
- 0,
- &SCA_ISensor::Type,
- 0,0,0,0,0,0,
- py_base_new
-};
-
-PyMethodDef SCA_MouseSensor::Methods[] = {
- KX_PYMETHODTABLE_O(SCA_MouseSensor, getButtonStatus),
- {NULL,NULL} //Sentinel
-};
-
-int SCA_MouseSensor::UpdateHotkeyPy(void *self, const PyAttributeDef*)
-{
- UpdateHotkey(self);
- // return value is used in py_setattro(),
- // 0=attribute checked ok (see Attributes array definition)
- return 0;
-}
-
-PyAttributeDef SCA_MouseSensor::Attributes[] = {
- KX_PYATTRIBUTE_SHORT_RW_CHECK("mode",KX_MOUSESENSORMODE_NODEF,KX_MOUSESENSORMODE_MAX-1,true,SCA_MouseSensor,m_mousemode,UpdateHotkeyPy),
- KX_PYATTRIBUTE_SHORT_LIST_RO("position",SCA_MouseSensor,m_x,2),
- { NULL } //Sentinel
-};
-
-#endif // WITH_PYTHON
-
-/* eof */
diff --git a/source/gameengine/GameLogic/SCA_MouseSensor.h b/source/gameengine/GameLogic/SCA_MouseSensor.h
deleted file mode 100644
index 2660aaeacb5..00000000000
--- a/source/gameengine/GameLogic/SCA_MouseSensor.h
+++ /dev/null
@@ -1,120 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): José I. Romero (cleanup and fixes)
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file SCA_MouseSensor.h
- * \ingroup gamelogic
- * \brief Senses mouse events
- */
-
-#ifndef __SCA_MOUSESENSOR_H__
-#define __SCA_MOUSESENSOR_H__
-
-#include "SCA_ISensor.h"
-#include "EXP_BoolValue.h"
-#include "SCA_IInputDevice.h"
-
-class SCA_MouseSensor : public SCA_ISensor
-{
- Py_Header
-
- /**
- * Use SCA_IInputDevice values to encode the mouse mode for now.
- */
- short int m_mousemode;
- /**
- * Triggermode true means all mouse events trigger. Useful mainly
- * for button presses.
- */
- bool m_triggermode;
- /**
- * Remember the last state update
- */
- int m_val;
-
- SCA_IInputDevice::KX_EnumInputs m_hotkey;
-
- /**
- * valid x coordinate, MUST be followed by y coordinate
- */
- short m_x;
-
- /**
- * valid y coordinate
- */
- short m_y;
-
- public:
- /**
- * Allowable modes for the trigger status of the mouse sensor.
- */
- enum KX_MOUSESENSORMODE {
- KX_MOUSESENSORMODE_NODEF = 0,
- KX_MOUSESENSORMODE_LEFTBUTTON,
- KX_MOUSESENSORMODE_MIDDLEBUTTON,
- KX_MOUSESENSORMODE_RIGHTBUTTON,
- KX_MOUSESENSORMODE_WHEELUP,
- KX_MOUSESENSORMODE_WHEELDOWN,
- KX_MOUSESENSORMODE_POSITION,
- KX_MOUSESENSORMODE_POSITIONX,
- KX_MOUSESENSORMODE_POSITIONY,
- KX_MOUSESENSORMODE_MOVEMENT,
- KX_MOUSESENSORMODE_MAX
- };
-
- bool isValid(KX_MOUSESENSORMODE);
-
- SCA_MouseSensor(class SCA_MouseManager* keybdmgr,
- int startx,int starty,
- short int mousemode,
- SCA_IObject* gameobj);
-
- virtual ~SCA_MouseSensor();
- virtual CValue* GetReplica();
- virtual bool Evaluate();
- virtual void Init();
- virtual bool IsPositiveTrigger();
- short int GetModeKey();
- SCA_IInputDevice::KX_EnumInputs GetHotKey();
- void setX(short x);
- void setY(short y);
-
- static void UpdateHotkey(void *self);
-
-
-#ifdef WITH_PYTHON
- /* --------------------------------------------------------------------- */
- /* Python interface ---------------------------------------------------- */
- /* --------------------------------------------------------------------- */
-
- static int UpdateHotkeyPy(void *self, const PyAttributeDef *);
-
- // get button status
- KX_PYMETHOD_DOC_O(SCA_MouseSensor,getButtonStatus);
-#endif
-};
-
-#endif /* __SCA_MOUSESENSOR_H__ */
diff --git a/source/gameengine/GameLogic/SCA_NANDController.cpp b/source/gameengine/GameLogic/SCA_NANDController.cpp
deleted file mode 100644
index 6a00c110e2b..00000000000
--- a/source/gameengine/GameLogic/SCA_NANDController.cpp
+++ /dev/null
@@ -1,133 +0,0 @@
-/*
- * 'Nand' together all inputs
- *
- *
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/GameLogic/SCA_NANDController.cpp
- * \ingroup gamelogic
- */
-
-
-#include "SCA_NANDController.h"
-#include "SCA_ISensor.h"
-#include "SCA_LogicManager.h"
-#include "EXP_BoolValue.h"
-
-/* ------------------------------------------------------------------------- */
-/* Native functions */
-/* ------------------------------------------------------------------------- */
-
-SCA_NANDController::SCA_NANDController(SCA_IObject* gameobj)
- :
- SCA_IController(gameobj)
-{
-}
-
-
-
-SCA_NANDController::~SCA_NANDController()
-{
-}
-
-
-
-void SCA_NANDController::Trigger(SCA_LogicManager* logicmgr)
-{
-
- bool sensorresult = false;
-
- for (vector<SCA_ISensor*>::const_iterator is=m_linkedsensors.begin();
- !(is==m_linkedsensors.end());is++)
- {
- SCA_ISensor* sensor = *is;
- if (!sensor->GetState())
- {
- sensorresult = true;
- break;
- }
- }
-
- for (vector<SCA_IActuator*>::const_iterator i=m_linkedactuators.begin();
- !(i==m_linkedactuators.end());i++)
- {
- SCA_IActuator* actua = *i;
- logicmgr->AddActiveActuator(actua,sensorresult);
- }
-}
-
-
-
-CValue* SCA_NANDController::GetReplica()
-{
- CValue* replica = new SCA_NANDController(*this);
- // this will copy properties and so on...
- replica->ProcessReplica();
-
- return replica;
-}
-
-#ifdef WITH_PYTHON
-
-/* ------------------------------------------------------------------------- */
-/* Python functions */
-/* ------------------------------------------------------------------------- */
-
-/* Integration hooks ------------------------------------------------------- */
-PyTypeObject SCA_NANDController::Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "SCA_NANDController",
- sizeof(PyObjectPlus_Proxy),
- 0,
- py_base_dealloc,
- 0,
- 0,
- 0,
- 0,
- py_base_repr,
- 0,0,0,0,0,0,0,0,0,
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
- 0,0,0,0,0,0,0,
- Methods,
- 0,
- 0,
- &SCA_IController::Type,
- 0,0,0,0,0,0,
- py_base_new
-};
-
-PyMethodDef SCA_NANDController::Methods[] = {
- {NULL,NULL} //Sentinel
-};
-
-PyAttributeDef SCA_NANDController::Attributes[] = {
- { NULL } //Sentinel
-};
-
-#endif
-
-/* eof */
diff --git a/source/gameengine/GameLogic/SCA_NANDController.h b/source/gameengine/GameLogic/SCA_NANDController.h
deleted file mode 100644
index a3f02908dd2..00000000000
--- a/source/gameengine/GameLogic/SCA_NANDController.h
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file SCA_NANDController.h
- * \ingroup gamelogic
- */
-
-#ifndef __SCA_NANDCONTROLLER_H__
-#define __SCA_NANDCONTROLLER_H__
-
-#include "SCA_IController.h"
-
-class SCA_NANDController : public SCA_IController
-{
- Py_Header
- //virtual void Trigger(class SCA_LogicManager* logicmgr);
-public:
- SCA_NANDController(SCA_IObject* gameobj);
- virtual ~SCA_NANDController();
- virtual CValue* GetReplica();
- virtual void Trigger(SCA_LogicManager* logicmgr);
-
- /* --------------------------------------------------------------------- */
- /* Python interface ---------------------------------------------------- */
- /* --------------------------------------------------------------------- */
-};
-
-#endif /* __SCA_NANDCONTROLLER_H__ */
diff --git a/source/gameengine/GameLogic/SCA_NORController.cpp b/source/gameengine/GameLogic/SCA_NORController.cpp
deleted file mode 100644
index fb09617e060..00000000000
--- a/source/gameengine/GameLogic/SCA_NORController.cpp
+++ /dev/null
@@ -1,133 +0,0 @@
-/*
- * 'Nor' together all inputs
- *
- *
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/GameLogic/SCA_NORController.cpp
- * \ingroup gamelogic
- */
-
-
-#include "SCA_NORController.h"
-#include "SCA_ISensor.h"
-#include "SCA_LogicManager.h"
-#include "EXP_BoolValue.h"
-
-/* ------------------------------------------------------------------------- */
-/* Native functions */
-/* ------------------------------------------------------------------------- */
-
-SCA_NORController::SCA_NORController(SCA_IObject* gameobj)
- :
- SCA_IController(gameobj)
-{
-}
-
-
-
-SCA_NORController::~SCA_NORController()
-{
-}
-
-
-
-void SCA_NORController::Trigger(SCA_LogicManager* logicmgr)
-{
-
- bool sensorresult = true;
-
- for (vector<SCA_ISensor*>::const_iterator is=m_linkedsensors.begin();
- !(is==m_linkedsensors.end());is++)
- {
- SCA_ISensor* sensor = *is;
- if (sensor->GetState())
- {
- sensorresult = false;
- break;
- }
- }
-
- for (vector<SCA_IActuator*>::const_iterator i=m_linkedactuators.begin();
- !(i==m_linkedactuators.end());i++)
- {
- SCA_IActuator* actua = *i;
- logicmgr->AddActiveActuator(actua,sensorresult);
- }
-}
-
-
-
-CValue* SCA_NORController::GetReplica()
-{
- CValue* replica = new SCA_NORController(*this);
- // this will copy properties and so on...
- replica->ProcessReplica();
-
- return replica;
-}
-
-#ifdef WITH_PYTHON
-
-/* ------------------------------------------------------------------------- */
-/* Python functions */
-/* ------------------------------------------------------------------------- */
-
-/* Integration hooks ------------------------------------------------------- */
-PyTypeObject SCA_NORController::Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "SCA_NORController",
- sizeof(PyObjectPlus_Proxy),
- 0,
- py_base_dealloc,
- 0,
- 0,
- 0,
- 0,
- py_base_repr,
- 0,0,0,0,0,0,0,0,0,
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
- 0,0,0,0,0,0,0,
- Methods,
- 0,
- 0,
- &SCA_IController::Type,
- 0,0,0,0,0,0,
- py_base_new
-};
-
-PyMethodDef SCA_NORController::Methods[] = {
- {NULL,NULL} //Sentinel
-};
-
-PyAttributeDef SCA_NORController::Attributes[] = {
- { NULL } //Sentinel
-};
-
-#endif // WITH_PYTHON
-
-/* eof */
diff --git a/source/gameengine/GameLogic/SCA_NORController.h b/source/gameengine/GameLogic/SCA_NORController.h
deleted file mode 100644
index ec8159de8d1..00000000000
--- a/source/gameengine/GameLogic/SCA_NORController.h
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file SCA_NORController.h
- * \ingroup gamelogic
- */
-
-#ifndef __SCA_NORCONTROLLER_H__
-#define __SCA_NORCONTROLLER_H__
-
-#include "SCA_IController.h"
-
-class SCA_NORController : public SCA_IController
-{
- Py_Header
- //virtual void Trigger(class SCA_LogicManager* logicmgr);
-public:
- SCA_NORController(SCA_IObject* gameobj);
- virtual ~SCA_NORController();
- virtual CValue* GetReplica();
- virtual void Trigger(SCA_LogicManager* logicmgr);
-};
-
-#endif /* __SCA_NORCONTROLLER_H__ */
diff --git a/source/gameengine/GameLogic/SCA_ORController.cpp b/source/gameengine/GameLogic/SCA_ORController.cpp
deleted file mode 100644
index 8a59bdf1b89..00000000000
--- a/source/gameengine/GameLogic/SCA_ORController.cpp
+++ /dev/null
@@ -1,129 +0,0 @@
-/*
- * 'Or' together all inputs
- *
- *
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/GameLogic/SCA_ORController.cpp
- * \ingroup gamelogic
- */
-
-
-#include "SCA_ORController.h"
-#include "SCA_ISensor.h"
-#include "SCA_LogicManager.h"
-#include "EXP_BoolValue.h"
-
-/* ------------------------------------------------------------------------- */
-/* Native functions */
-/* ------------------------------------------------------------------------- */
-
-SCA_ORController::SCA_ORController(SCA_IObject* gameobj)
- :SCA_IController(gameobj)
-{
-}
-
-
-
-SCA_ORController::~SCA_ORController()
-{
-}
-
-
-
-CValue* SCA_ORController::GetReplica()
-{
- CValue* replica = new SCA_ORController(*this);
- // this will copy properties and so on...
- replica->ProcessReplica();
-
- return replica;
-}
-
-
-void SCA_ORController::Trigger(SCA_LogicManager* logicmgr)
-{
-
- bool sensorresult = false;
- SCA_ISensor* sensor;
-
- vector<SCA_ISensor*>::const_iterator is=m_linkedsensors.begin();
- while ( (!sensorresult) && (!(is==m_linkedsensors.end())) )
- {
- sensor = *is;
- if (sensor->GetState()) sensorresult = true;
- is++;
- }
-
- for (vector<SCA_IActuator*>::const_iterator i=m_linkedactuators.begin();
- !(i==m_linkedactuators.end());i++)
- {
- SCA_IActuator* actua = *i;
- logicmgr->AddActiveActuator(actua,sensorresult);
- }
-}
-
-#ifdef WITH_PYTHON
-
-/* ------------------------------------------------------------------------- */
-/* Python functions */
-/* ------------------------------------------------------------------------- */
-
-/* Integration hooks ------------------------------------------------------- */
-PyTypeObject SCA_ORController::Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "SCA_ORController",
- sizeof(PyObjectPlus_Proxy),
- 0,
- py_base_dealloc,
- 0,
- 0,
- 0,
- 0,
- py_base_repr,
- 0,0,0,0,0,0,0,0,0,
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
- 0,0,0,0,0,0,0,
- Methods,
- 0,
- 0,
- &SCA_IController::Type,
- 0,0,0,0,0,0,
- py_base_new
-};
-
-PyMethodDef SCA_ORController::Methods[] = {
- {NULL,NULL} //Sentinel
-};
-
-PyAttributeDef SCA_ORController::Attributes[] = {
- { NULL } //Sentinel
-};
-
-#endif // WITH_PYTHON
-
-/* eof */
diff --git a/source/gameengine/GameLogic/SCA_ORController.h b/source/gameengine/GameLogic/SCA_ORController.h
deleted file mode 100644
index 9499c893c72..00000000000
--- a/source/gameengine/GameLogic/SCA_ORController.h
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file SCA_ORController.h
- * \ingroup gamelogic
- */
-
-#ifndef __SCA_ORCONTROLLER_H__
-#define __SCA_ORCONTROLLER_H__
-
-#include "SCA_IController.h"
-
-class SCA_ORController : public SCA_IController
-{
- Py_Header
- //virtual void Trigger(class SCA_LogicManager* logicmgr);
-public:
- SCA_ORController(SCA_IObject* gameobj);
-
- virtual ~SCA_ORController();
- virtual CValue* GetReplica();
- virtual void Trigger(SCA_LogicManager* logicmgr);
-};
-
-#endif /* __SCA_ORCONTROLLER_H__ */
diff --git a/source/gameengine/GameLogic/SCA_PropertyActuator.cpp b/source/gameengine/GameLogic/SCA_PropertyActuator.cpp
deleted file mode 100644
index f2907ca6361..00000000000
--- a/source/gameengine/GameLogic/SCA_PropertyActuator.cpp
+++ /dev/null
@@ -1,293 +0,0 @@
-/*
- * Assign, change, copy properties
- *
- *
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/GameLogic/SCA_PropertyActuator.cpp
- * \ingroup gamelogic
- */
-
-
-#include <stddef.h>
-
-#include "SCA_PropertyActuator.h"
-#include "EXP_InputParser.h"
-#include "EXP_Operator2Expr.h"
-#include "EXP_ConstExpr.h"
-
-/* ------------------------------------------------------------------------- */
-/* Native functions */
-/* ------------------------------------------------------------------------- */
-
-SCA_PropertyActuator::SCA_PropertyActuator(SCA_IObject* gameobj,SCA_IObject* sourceObj,const STR_String& propname,const STR_String& expr,int acttype)
- : SCA_IActuator(gameobj, KX_ACT_PROPERTY),
- m_type(acttype),
- m_propname(propname),
- m_exprtxt(expr),
- m_sourceObj(sourceObj)
-{
- // protect ourselves against someone else deleting the source object
- // don't protect against ourselves: it would create a dead lock
- if (m_sourceObj)
- m_sourceObj->RegisterActuator(this);
-}
-
-SCA_PropertyActuator::~SCA_PropertyActuator()
-{
- if (m_sourceObj)
- m_sourceObj->UnregisterActuator(this);
-}
-
-bool SCA_PropertyActuator::Update()
-{
- bool result = false;
-
- bool bNegativeEvent = IsNegativeEvent();
- RemoveAllEvents();
- CValue* propowner = GetParent();
-
- if (bNegativeEvent)
- {
- if (m_type==KX_ACT_PROP_LEVEL)
- {
- CValue* newval = new CBoolValue(false);
- CValue* oldprop = propowner->GetProperty(m_propname);
- if (oldprop)
- {
- oldprop->SetValue(newval);
- }
- newval->Release();
- }
- return false;
- }
-
-
- CParser parser;
- parser.SetContext( propowner->AddRef());
-
- CExpression* userexpr= NULL;
-
- if (m_type==KX_ACT_PROP_TOGGLE)
- {
- /* don't use */
- CValue* newval;
- CValue* oldprop = propowner->GetProperty(m_propname);
- if (oldprop)
- {
- newval = new CBoolValue((oldprop->GetNumber()==0.0) ? true:false);
- oldprop->SetValue(newval);
- } else
- { /* as not been assigned, evaluate as false, so assign true */
- newval = new CBoolValue(true);
- propowner->SetProperty(m_propname,newval);
- }
- newval->Release();
- }
- else if (m_type==KX_ACT_PROP_LEVEL)
- {
- CValue* newval = new CBoolValue(true);
- CValue* oldprop = propowner->GetProperty(m_propname);
- if (oldprop)
- {
- oldprop->SetValue(newval);
- } else
- {
- propowner->SetProperty(m_propname,newval);
- }
- newval->Release();
- }
- else if ((userexpr = parser.ProcessText(m_exprtxt))) {
- switch (m_type)
- {
-
- case KX_ACT_PROP_ASSIGN:
- {
-
- CValue* newval = userexpr->Calculate();
- CValue* oldprop = propowner->GetProperty(m_propname);
- if (oldprop)
- {
- oldprop->SetValue(newval);
- } else
- {
- propowner->SetProperty(m_propname,newval);
- }
- newval->Release();
- break;
- }
- case KX_ACT_PROP_ADD:
- {
- CValue* oldprop = propowner->GetProperty(m_propname);
- if (oldprop)
- {
- // int waarde = (int)oldprop->GetNumber(); /*unused*/
- CExpression* expr = new COperator2Expr(VALUE_ADD_OPERATOR,new CConstExpr(oldprop->AddRef()),
- userexpr->AddRef());
-
- CValue* newprop = expr->Calculate();
- oldprop->SetValue(newprop);
- newprop->Release();
- expr->Release();
-
- }
-
- break;
- }
- case KX_ACT_PROP_COPY:
- {
- if (m_sourceObj)
- {
- CValue* copyprop = m_sourceObj->GetProperty(m_exprtxt);
- if (copyprop)
- {
- CValue *val = copyprop->GetReplica();
- GetParent()->SetProperty(
- m_propname,
- val);
- val->Release();
-
- }
- }
- break;
- }
- /* case KX_ACT_PROP_TOGGLE: */ /* accounted for above, no need for userexpr */
- default:
- {
-
- }
- }
-
- userexpr->Release();
- }
-
- return result;
-}
-
- bool
-
-SCA_PropertyActuator::
-
-isValid(
-
- SCA_PropertyActuator::KX_ACT_PROP_MODE mode
-
-) {
- bool res = false;
- res = ((mode > KX_ACT_PROP_NODEF) && (mode < KX_ACT_PROP_MAX));
- return res;
-}
-
-
- CValue*
-
-SCA_PropertyActuator::
-
-GetReplica()
-{
-
- SCA_PropertyActuator* replica = new SCA_PropertyActuator(*this);
-
- replica->ProcessReplica();
- return replica;
-
-};
-
-void SCA_PropertyActuator::ProcessReplica()
-{
- // no need to check for self reference like in the constructor:
- // the replica will always have a different parent
- if (m_sourceObj)
- m_sourceObj->RegisterActuator(this);
- SCA_IActuator::ProcessReplica();
-}
-
-bool SCA_PropertyActuator::UnlinkObject(SCA_IObject* clientobj)
-{
- if (clientobj == m_sourceObj)
- {
- // this object is being deleted, we cannot continue to track it.
- m_sourceObj = NULL;
- return true;
- }
- return false;
-}
-
-void SCA_PropertyActuator::Relink(CTR_Map<CTR_HashedPtr, void*> *obj_map)
-{
- void **h_obj = (*obj_map)[m_sourceObj];
- if (h_obj) {
- if (m_sourceObj)
- m_sourceObj->UnregisterActuator(this);
- m_sourceObj = (SCA_IObject*)(*h_obj);
- m_sourceObj->RegisterActuator(this);
- }
-}
-
-#ifdef WITH_PYTHON
-
-/* ------------------------------------------------------------------------- */
-/* Python functions */
-/* ------------------------------------------------------------------------- */
-
-/* Integration hooks ------------------------------------------------------- */
-PyTypeObject SCA_PropertyActuator::Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "SCA_PropertyActuator",
- sizeof(PyObjectPlus_Proxy),
- 0,
- py_base_dealloc,
- 0,
- 0,
- 0,
- 0,
- py_base_repr,
- 0,0,0,0,0,0,0,0,0,
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
- 0,0,0,0,0,0,0,
- Methods,
- 0,
- 0,
- &SCA_IActuator::Type,
- 0,0,0,0,0,0,
- py_base_new
-};
-
-PyMethodDef SCA_PropertyActuator::Methods[] = {
- {NULL,NULL} //Sentinel
-};
-
-PyAttributeDef SCA_PropertyActuator::Attributes[] = {
- KX_PYATTRIBUTE_STRING_RW_CHECK("propName",0,MAX_PROP_NAME,false,SCA_PropertyActuator,m_propname,CheckProperty),
- KX_PYATTRIBUTE_STRING_RW("value",0,100,false,SCA_PropertyActuator,m_exprtxt),
- KX_PYATTRIBUTE_INT_RW("mode", KX_ACT_PROP_NODEF+1, KX_ACT_PROP_MAX-1, false, SCA_PropertyActuator, m_type), /* ATTR_TODO add constents to game logic dict */
- { NULL } //Sentinel
-};
-
-#endif
-
-/* eof */
diff --git a/source/gameengine/GameLogic/SCA_PropertyActuator.h b/source/gameengine/GameLogic/SCA_PropertyActuator.h
deleted file mode 100644
index 228ecf94bc4..00000000000
--- a/source/gameengine/GameLogic/SCA_PropertyActuator.h
+++ /dev/null
@@ -1,90 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file SCA_PropertyActuator.h
- * \ingroup gamelogic
- */
-
-#ifndef __SCA_PROPERTYACTUATOR_H__
-#define __SCA_PROPERTYACTUATOR_H__
-
-#include "SCA_IActuator.h"
-
-class SCA_PropertyActuator : public SCA_IActuator
-{
- Py_Header
-
- enum KX_ACT_PROP_MODE {
- KX_ACT_PROP_NODEF = 0,
- KX_ACT_PROP_ASSIGN,
- KX_ACT_PROP_ADD,
- KX_ACT_PROP_COPY,
- KX_ACT_PROP_TOGGLE,
- KX_ACT_PROP_LEVEL,
- KX_ACT_PROP_MAX
- };
-
- /**check whether this value is valid */
- bool isValid(KX_ACT_PROP_MODE mode);
-
- int m_type;
- STR_String m_propname;
- STR_String m_exprtxt;
- SCA_IObject* m_sourceObj; // for copy property actuator
-
-public:
-
-
-
- SCA_PropertyActuator(
- SCA_IObject* gameobj,
- SCA_IObject* sourceObj,
- const STR_String& propname,
- const STR_String& expr,
- int acttype);
-
-
- ~SCA_PropertyActuator();
-
- CValue*
- GetReplica(
- );
-
- virtual void ProcessReplica();
- virtual bool UnlinkObject(SCA_IObject* clientobj);
- virtual void Relink(CTR_Map<CTR_HashedPtr, void*> *obj_map);
-
- virtual bool
- Update();
-
- /* --------------------------------------------------------------------- */
- /* Python interface ---------------------------------------------------- */
- /* --------------------------------------------------------------------- */
-
-};
-
-#endif /* __KX_PROPERTYACTUATOR_DOC */
diff --git a/source/gameengine/GameLogic/SCA_PropertyEventManager.cpp b/source/gameengine/GameLogic/SCA_PropertyEventManager.cpp
deleted file mode 100644
index 854069690da..00000000000
--- a/source/gameengine/GameLogic/SCA_PropertyEventManager.cpp
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/GameLogic/SCA_PropertyEventManager.cpp
- * \ingroup gamelogic
- */
-
-
-#include "SCA_ISensor.h"
-#include "SCA_PropertyEventManager.h"
-
-
-SCA_PropertyEventManager::SCA_PropertyEventManager(class SCA_LogicManager* logicmgr)
- : SCA_EventManager(logicmgr, PROPERTY_EVENTMGR)
-{
-}
-
-
-
-SCA_PropertyEventManager::~SCA_PropertyEventManager()
-{
-
-}
-
-void SCA_PropertyEventManager::NextFrame()
-{
- // check for changed properties
- SG_DList::iterator<SCA_ISensor> it(m_sensors);
- for (it.begin();!it.end();++it)
- {
- (*it)->Activate(m_logicmgr);
- }
-}
diff --git a/source/gameengine/GameLogic/SCA_PropertyEventManager.h b/source/gameengine/GameLogic/SCA_PropertyEventManager.h
deleted file mode 100644
index 554fe686df2..00000000000
--- a/source/gameengine/GameLogic/SCA_PropertyEventManager.h
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file SCA_PropertyEventManager.h
- * \ingroup gamelogic
- */
-
-#ifndef __SCA_PROPERTYEVENTMANAGER_H__
-#define __SCA_PROPERTYEVENTMANAGER_H__
-
-#include "SCA_EventManager.h"
-
-#include <vector>
-
-using namespace std;
-
-class SCA_PropertyEventManager : public SCA_EventManager
-{
-public:
- SCA_PropertyEventManager(class SCA_LogicManager* logicmgr);
- virtual ~SCA_PropertyEventManager();
- virtual void NextFrame();
- //SCA_LogicManager* GetLogicManager() { return m_logicmgr;}
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:SCA_PropertyEventManager")
-#endif
-};
-
-#endif /* __SCA_PROPERTYEVENTMANAGER_H__ */
diff --git a/source/gameengine/GameLogic/SCA_PropertySensor.cpp b/source/gameengine/GameLogic/SCA_PropertySensor.cpp
deleted file mode 100644
index e34a5296139..00000000000
--- a/source/gameengine/GameLogic/SCA_PropertySensor.cpp
+++ /dev/null
@@ -1,332 +0,0 @@
-/*
- * Property sensor
- *
- *
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/GameLogic/SCA_PropertySensor.cpp
- * \ingroup gamelogic
- */
-
-
-#include <stddef.h>
-
-#include <iostream>
-#include "SCA_PropertySensor.h"
-#include "EXP_Operator2Expr.h"
-#include "EXP_ConstExpr.h"
-#include "EXP_InputParser.h"
-#include "EXP_StringValue.h"
-#include "SCA_EventManager.h"
-#include "SCA_LogicManager.h"
-#include "EXP_BoolValue.h"
-#include "EXP_FloatValue.h"
-#include <stdio.h>
-
-SCA_PropertySensor::SCA_PropertySensor(SCA_EventManager* eventmgr,
- SCA_IObject* gameobj,
- const STR_String& propname,
- const STR_String& propval,
- const STR_String& propmaxval,
- KX_PROPSENSOR_TYPE checktype)
- : SCA_ISensor(gameobj,eventmgr),
- m_checktype(checktype),
- m_checkpropval(propval),
- m_checkpropmaxval(propmaxval),
- m_checkpropname(propname)
-{
- //CParser pars;
- //pars.SetContext(this->AddRef());
- //CValue* resultval = m_rightexpr->Calculate();
-
- CValue* orgprop = GetParent()->FindIdentifier(m_checkpropname);
- if (!orgprop->IsError())
- {
- m_previoustext = orgprop->GetText();
- }
- orgprop->Release();
-
- Init();
-}
-
-void SCA_PropertySensor::Init()
-{
- m_recentresult = false;
- m_lastresult = m_invert?true:false;
- m_reset = true;
-}
-
-CValue* SCA_PropertySensor::GetReplica()
-{
- SCA_PropertySensor* replica = new SCA_PropertySensor(*this);
- // m_range_expr must be recalculated on replica!
- replica->ProcessReplica();
- replica->Init();
-
- return replica;
-}
-
-
-
-bool SCA_PropertySensor::IsPositiveTrigger()
-{
- bool result = m_recentresult;//CheckPropertyCondition();
- if (m_invert)
- result = !result;
-
- return result;
-}
-
-
-
-SCA_PropertySensor::~SCA_PropertySensor()
-{
-}
-
-
-
-bool SCA_PropertySensor::Evaluate()
-{
- bool result = CheckPropertyCondition();
- bool reset = m_reset && m_level;
-
- m_reset = false;
- if (m_lastresult!=result)
- {
- m_lastresult = result;
- return true;
- }
- return (reset) ? true : false;
-}
-
-
-bool SCA_PropertySensor::CheckPropertyCondition()
-{
- m_recentresult=false;
- bool result=false;
- bool reverse = false;
- switch (m_checktype)
- {
- case KX_PROPSENSOR_NOTEQUAL:
- reverse = true;
- ATTR_FALLTHROUGH;
- case KX_PROPSENSOR_EQUAL:
- {
- CValue* orgprop = GetParent()->FindIdentifier(m_checkpropname);
- if (!orgprop->IsError())
- {
- const STR_String& testprop = orgprop->GetText();
- // Force strings to upper case, to avoid confusion in
- // bool tests. It's stupid the prop's identity is lost
- // on the way here...
- if ((&testprop == &CBoolValue::sTrueString) || (&testprop == &CBoolValue::sFalseString)) {
- m_checkpropval.Upper();
- }
- result = (testprop == m_checkpropval);
-
- /* Patch: floating point values cant use strings usefully since you can have "0.0" == "0.0000"
- * this could be made into a generic Value class function for comparing values with a string.
- */
- if (result==false && (orgprop->GetValueType() == VALUE_FLOAT_TYPE)) {
- float f;
- if (sscanf(m_checkpropval.ReadPtr(), "%f", &f) == 1) {
- result = (f == ((CFloatValue *)orgprop)->GetFloat());
- }
- else {
- /* error */
- }
- }
- /* end patch */
- }
- orgprop->Release();
-
- if (reverse)
- result = !result;
- break;
-
- }
-
- case KX_PROPSENSOR_EXPRESSION:
- {
-#if 0
- if (m_rightexpr)
- {
- CValue* resultval = m_rightexpr->Calculate();
- if (resultval->IsError())
- {
- int i=0;
- STR_String errortest = resultval->GetText();
- printf(errortest);
-
- } else
- {
- result = resultval->GetNumber() != 0;
- }
- }
-#endif
- break;
- }
- case KX_PROPSENSOR_INTERVAL:
- {
- CValue* orgprop = GetParent()->FindIdentifier(m_checkpropname);
- if (!orgprop->IsError())
- {
- const float min = m_checkpropval.ToFloat();
- const float max = m_checkpropmaxval.ToFloat();
- float val;
-
- if (orgprop->GetValueType() == VALUE_STRING_TYPE) {
- val = orgprop->GetText().ToFloat();
- }
- else {
- val = orgprop->GetNumber();
- }
-
- result = (min <= val) && (val <= max);
- }
- orgprop->Release();
-
- break;
- }
- case KX_PROPSENSOR_CHANGED:
- {
- CValue* orgprop = GetParent()->FindIdentifier(m_checkpropname);
-
- if (!orgprop->IsError())
- {
- if (m_previoustext != orgprop->GetText())
- {
- m_previoustext = orgprop->GetText();
- result = true;
- }
- }
- orgprop->Release();
-
- //cout << " \nSens:Prop:changed!"; /* need implementation here!!! */
- break;
- }
- case KX_PROPSENSOR_LESSTHAN:
- reverse = true;
- ATTR_FALLTHROUGH;
- case KX_PROPSENSOR_GREATERTHAN:
- {
- CValue* orgprop = GetParent()->FindIdentifier(m_checkpropname);
- if (!orgprop->IsError())
- {
- const float ref = m_checkpropval.ToFloat();
- float val;
-
- if (orgprop->GetValueType() == VALUE_STRING_TYPE) {
- val = orgprop->GetText().ToFloat();
- }
- else {
- val = orgprop->GetNumber();
- }
-
- if (reverse) {
- result = val < ref;
- }
- else {
- result = val > ref;
- }
-
- }
- orgprop->Release();
-
- break;
- }
- default:
- ; /* error */
- }
-
- //the concept of Edge and Level triggering has unwanted effect for KX_PROPSENSOR_CHANGED
- //see Game Engine bugtracker [ #3809 ]
- m_recentresult = result;
-
- return result;
-}
-
-CValue* SCA_PropertySensor::FindIdentifier(const STR_String& identifiername)
-{
- return GetParent()->FindIdentifier(identifiername);
-}
-
-#ifdef WITH_PYTHON
-
-/* ------------------------------------------------------------------------- */
-/* Python functions */
-/* ------------------------------------------------------------------------- */
-
-int SCA_PropertySensor::validValueForProperty(void *self, const PyAttributeDef*)
-{
- /* If someone actually do type checking please make sure the 'max' and 'min'
- * are checked as well (currently they are calling the PrecalculateRangeExpression
- * function directly */
-
- /* There is no type checking at this moment, unfortunately... */
- return 0;
-}
-
-/* Integration hooks ------------------------------------------------------- */
-PyTypeObject SCA_PropertySensor::Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "SCA_PropertySensor",
- sizeof(PyObjectPlus_Proxy),
- 0,
- py_base_dealloc,
- 0,
- 0,
- 0,
- 0,
- py_base_repr,
- 0,0,0,0,0,0,0,0,0,
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
- 0,0,0,0,0,0,0,
- Methods,
- 0,
- 0,
- &SCA_ISensor::Type,
- 0,0,0,0,0,0,
- py_base_new
-};
-
-PyMethodDef SCA_PropertySensor::Methods[] = {
- {NULL,NULL} //Sentinel
-};
-
-PyAttributeDef SCA_PropertySensor::Attributes[] = {
- KX_PYATTRIBUTE_INT_RW("mode",KX_PROPSENSOR_NODEF,KX_PROPSENSOR_MAX-1,false,SCA_PropertySensor,m_checktype),
- KX_PYATTRIBUTE_STRING_RW_CHECK("propName",0,MAX_PROP_NAME,false,SCA_PropertySensor,m_checkpropname,CheckProperty),
- KX_PYATTRIBUTE_STRING_RW_CHECK("value",0,100,false,SCA_PropertySensor,m_checkpropval,validValueForProperty),
- KX_PYATTRIBUTE_STRING_RW_CHECK("min",0,100,false,SCA_PropertySensor,m_checkpropval,validValueForProperty),
- KX_PYATTRIBUTE_STRING_RW_CHECK("max",0,100,false,SCA_PropertySensor,m_checkpropmaxval,validValueForProperty),
- { NULL } //Sentinel
-};
-
-#endif // WITH_PYTHON
-
-/* eof */
diff --git a/source/gameengine/GameLogic/SCA_PropertySensor.h b/source/gameengine/GameLogic/SCA_PropertySensor.h
deleted file mode 100644
index f9cfb5fb1d2..00000000000
--- a/source/gameengine/GameLogic/SCA_PropertySensor.h
+++ /dev/null
@@ -1,98 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file SCA_PropertySensor.h
- * \ingroup gamelogic
- * \brief Property sensor
- */
-
-#ifndef __SCA_PROPERTYSENSOR_H__
-#define __SCA_PROPERTYSENSOR_H__
-
-#include "SCA_ISensor.h"
-
-class SCA_PropertySensor : public SCA_ISensor
-{
- Py_Header
- //class CExpression* m_rightexpr;
- int m_checktype;
- STR_String m_checkpropval;
- STR_String m_checkpropmaxval;
- STR_String m_checkpropname;
- STR_String m_previoustext;
- bool m_lastresult;
- bool m_recentresult;
-
- protected:
-
-public:
- enum KX_PROPSENSOR_TYPE {
- KX_PROPSENSOR_NODEF = 0,
- KX_PROPSENSOR_EQUAL,
- KX_PROPSENSOR_NOTEQUAL,
- KX_PROPSENSOR_INTERVAL,
- KX_PROPSENSOR_CHANGED,
- KX_PROPSENSOR_EXPRESSION,
- KX_PROPSENSOR_LESSTHAN,
- KX_PROPSENSOR_GREATERTHAN,
- KX_PROPSENSOR_MAX
- };
-
- const STR_String S_KX_PROPSENSOR_EQ_STRING;
-
- SCA_PropertySensor(class SCA_EventManager* eventmgr,
- SCA_IObject* gameobj,
- const STR_String& propname,
- const STR_String& propval,
- const STR_String& propmaxval,
- KX_PROPSENSOR_TYPE checktype);
-
- virtual ~SCA_PropertySensor();
- virtual CValue* GetReplica();
- virtual void Init();
- bool CheckPropertyCondition();
-
- virtual bool Evaluate();
- virtual bool IsPositiveTrigger();
- virtual CValue* FindIdentifier(const STR_String& identifiername);
-
-#ifdef WITH_PYTHON
-
- /* --------------------------------------------------------------------- */
- /* Python interface ---------------------------------------------------- */
- /* --------------------------------------------------------------------- */
-
- /**
- * Test whether this is a sensible value (type check)
- */
- static int validValueForProperty(void* self, const PyAttributeDef*);
-
-#endif
-};
-
-#endif
-
diff --git a/source/gameengine/GameLogic/SCA_PythonController.cpp b/source/gameengine/GameLogic/SCA_PythonController.cpp
deleted file mode 100644
index fd2e723741c..00000000000
--- a/source/gameengine/GameLogic/SCA_PythonController.cpp
+++ /dev/null
@@ -1,539 +0,0 @@
-/*
- * Execute Python scripts
- *
- *
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/GameLogic/SCA_PythonController.cpp
- * \ingroup gamelogic
- */
-
-
-#include <stddef.h>
-
-#include "SCA_PythonController.h"
-#include "SCA_LogicManager.h"
-#include "SCA_ISensor.h"
-#include "SCA_IActuator.h"
-#include "EXP_PyObjectPlus.h"
-
-#ifdef WITH_PYTHON
-#include "compile.h"
-#include "eval.h"
-#endif // WITH_PYTHON
-
-#include <algorithm>
-
-
-// initialize static member variables
-SCA_PythonController* SCA_PythonController::m_sCurrentController = NULL;
-
-
-SCA_PythonController::SCA_PythonController(SCA_IObject* gameobj, int mode)
- : SCA_IController(gameobj),
-#ifdef WITH_PYTHON
- m_bytecode(NULL),
- m_function(NULL),
-#endif
- m_function_argc(0),
- m_bModified(true),
- m_debug(false),
- m_mode(mode)
-#ifdef WITH_PYTHON
- , m_pythondictionary(NULL)
-#endif
-
-{
-
-}
-
-#if 0
-//debugging
-CValue *SCA_PythonController::AddRef()
-{
- //printf("AddRef refcount = %i\n",GetRefCount());
- return CValue::AddRef();
-}
-int SCA_PythonController::Release()
-{
- //printf("Release refcount = %i\n",GetRefCount());
- return CValue::Release();
-}
-#endif
-
-SCA_PythonController::~SCA_PythonController()
-{
-
-#ifdef WITH_PYTHON
- //printf("released python byte script\n");
-
- Py_XDECREF(m_bytecode);
- Py_XDECREF(m_function);
-
- if (m_pythondictionary) {
- // break any circular references in the dictionary
- PyDict_Clear(m_pythondictionary);
- Py_DECREF(m_pythondictionary);
- }
-#endif
-}
-
-
-
-CValue* SCA_PythonController::GetReplica()
-{
- SCA_PythonController* replica = new SCA_PythonController(*this);
-
-#ifdef WITH_PYTHON
- /* why is this needed at all??? - m_bytecode is NULL'd below so this doesnt make sense
- * but removing it crashes blender (with YoFrankie). so leave in for now - Campbell */
- Py_XINCREF(replica->m_bytecode);
-
- Py_XINCREF(replica->m_function); // this is ok since its not set to NULL
- replica->m_bModified = replica->m_bytecode == NULL;
-
- // The replica->m_pythondictionary is stolen - replace with a copy.
- if (m_pythondictionary)
- replica->m_pythondictionary = PyDict_Copy(m_pythondictionary);
-
-#if 0
- // The other option is to incref the replica->m_pythondictionary -
- // the replica objects can then share data.
- if (m_pythondictionary)
- Py_INCREF(replica->m_pythondictionary);
-#endif
-
-#endif /* WITH_PYTHON */
-
- // this will copy properties and so on...
- replica->ProcessReplica();
-
- return replica;
-}
-
-
-
-void SCA_PythonController::SetScriptText(const STR_String& text)
-{
- m_scriptText = text;
- m_bModified = true;
-}
-
-
-
-void SCA_PythonController::SetScriptName(const STR_String& name)
-{
- m_scriptName = name;
-}
-
-
-#ifdef WITH_PYTHON
-void SCA_PythonController::SetNamespace(PyObject* pythondictionary)
-{
- if (m_pythondictionary)
- {
- PyDict_Clear(m_pythondictionary);
- Py_DECREF(m_pythondictionary);
- }
- m_pythondictionary = PyDict_Copy(pythondictionary); /* new reference */
-
- /* Without __file__ set the sys.argv[0] is used for the filename
- * which ends up with lines from the blender binary being printed in the console */
- PyObject *value = PyUnicode_From_STR_String(m_scriptName);
- PyDict_SetItemString(m_pythondictionary, "__file__", value);
- Py_DECREF(value);
-
-}
-#endif
-
-bool SCA_PythonController::IsTriggered(class SCA_ISensor* sensor)
-{
- if (std::find(m_triggeredSensors.begin(), m_triggeredSensors.end(), sensor) !=
- m_triggeredSensors.end())
- {
- return true;
- }
- else {
- return false;
- }
-}
-
-#ifdef WITH_PYTHON
-
-/* warning, self is not the SCA_PythonController, its a PyObjectPlus_Proxy */
-PyObject *SCA_PythonController::sPyGetCurrentController(PyObject *self)
-{
- if (m_sCurrentController==NULL)
- {
- PyErr_SetString(PyExc_SystemError, "bge.logic.getCurrentController(), this function is being run outside the python controllers context, or blenders internal state is corrupt.");
- return NULL;
- }
- return m_sCurrentController->GetProxy();
-}
-
-SCA_IActuator* SCA_PythonController::LinkedActuatorFromPy(PyObject *value)
-{
- // for safety, todo: only allow for registered actuators (pointertable)
- // we don't want to crash gameengine/blender by python scripts
- std::vector<SCA_IActuator*> lacts = m_sCurrentController->GetLinkedActuators();
- std::vector<SCA_IActuator*>::iterator it;
-
- if (PyUnicode_Check(value)) {
- /* get the actuator from the name */
- const char *name= _PyUnicode_AsString(value);
- for (it = lacts.begin(); it!= lacts.end(); ++it) {
- if ( name == (*it)->GetName() ) {
- return *it;
- }
- }
- }
- else if (PyObject_TypeCheck(value, &SCA_IActuator::Type)) {
- PyObjectPlus *value_plus= BGE_PROXY_REF(value);
- for (it = lacts.begin(); it!= lacts.end(); ++it) {
- if (static_cast<SCA_IActuator*>(value_plus) == (*it)) {
- return *it;
- }
- }
- }
-
- /* set the exception */
- PyErr_Format(PyExc_ValueError,
- "%R not in this python controllers actuator list", value);
-
- return NULL;
-}
-
-const char* SCA_PythonController::sPyGetCurrentController__doc__ = "getCurrentController()";
-
-PyTypeObject SCA_PythonController::Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "SCA_PythonController",
- sizeof(PyObjectPlus_Proxy),
- 0,
- py_base_dealloc,
- 0,
- 0,
- 0,
- 0,
- py_base_repr,
- 0,0,0,0,0,0,0,0,0,
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
- 0,0,0,0,0,0,0,
- Methods,
- 0,
- 0,
- &SCA_IController::Type,
- 0,0,0,0,0,0,
- py_base_new
-};
-
-PyMethodDef SCA_PythonController::Methods[] = {
- {"activate", (PyCFunction) SCA_PythonController::sPyActivate, METH_O},
- {"deactivate", (PyCFunction) SCA_PythonController::sPyDeActivate, METH_O},
- {NULL,NULL} //Sentinel
-};
-
-PyAttributeDef SCA_PythonController::Attributes[] = {
- KX_PYATTRIBUTE_RW_FUNCTION("script", SCA_PythonController, pyattr_get_script, pyattr_set_script),
- KX_PYATTRIBUTE_INT_RO("mode", SCA_PythonController, m_mode),
- { NULL } //Sentinel
-};
-
-void SCA_PythonController::ErrorPrint(const char *error_msg)
-{
- // If GetParent() is NULL, then most likely the object this controller
- // was attached to is gone (e.g., removed by LibFree()). Also, GetName()
- // can be a bad pointer if GetParent() is NULL, so better be safe and
- // flag it as unavailable as well
- const char *obj_name, *ctr_name;
- if (GetParent()) {
- obj_name = GetParent()->GetName().ReadPtr();
- ctr_name = GetName().ReadPtr();
- } else {
- obj_name = ctr_name = "Unavailable";
- }
- printf("%s - object '%s', controller '%s':\n", error_msg, obj_name, ctr_name);
- PyErr_Print();
-
- /* Added in 2.48a, the last_traceback can reference Objects for example, increasing
- * their user count. Not to mention holding references to wrapped data.
- * This is especially bad when the PyObject for the wrapped data is freed, after blender
- * has already dealocated the pointer */
- PySys_SetObject("last_traceback", NULL);
- PyErr_Clear(); /* just to be sure */
-}
-
-bool SCA_PythonController::Compile()
-{
- //printf("py script modified '%s'\n", m_scriptName.Ptr());
- m_bModified= false;
-
- // if a script already exists, decref it before replace the pointer to a new script
- if (m_bytecode) {
- Py_DECREF(m_bytecode);
- m_bytecode=NULL;
- }
-
- // recompile the scripttext into bytecode
- m_bytecode = Py_CompileString(m_scriptText.Ptr(), m_scriptName.Ptr(), Py_file_input);
-
- if (m_bytecode) {
- return true;
- } else {
- ErrorPrint("Python error compiling script");
- return false;
- }
-}
-
-bool SCA_PythonController::Import()
-{
- //printf("py module modified '%s'\n", m_scriptName.Ptr());
- m_bModified= false;
-
- /* in case we re-import */
- Py_XDECREF(m_function);
- m_function= NULL;
-
- STR_String mod_path_str= m_scriptText; /* just for storage, use C style string access */
- char *mod_path= mod_path_str.Ptr();
- char *function_string;
-
- function_string= strrchr(mod_path, '.');
-
- if (function_string == NULL) {
- printf("Python module name formatting error in object '%s', controller '%s':\n\texpected 'SomeModule.Func', got '%s'\n", GetParent()->GetName().Ptr(), GetName().Ptr(), m_scriptText.Ptr());
- return false;
- }
-
- *function_string= '\0';
- function_string++;
-
- // Import the module and print an error if it's not found
- PyObject *mod = PyImport_ImportModule(mod_path);
-
- if (mod == NULL) {
- ErrorPrint("Python module can't be imported");
- return false;
- }
-
- if (m_debug)
- mod = PyImport_ReloadModule(mod);
-
- if (mod == NULL) {
- ErrorPrint("Python module can't be reloaded");
- return false;
- }
-
- // Get the function object
- m_function = PyObject_GetAttrString(mod, function_string);
-
- // DECREF the module as we don't need it anymore
- Py_DECREF(mod);
-
- if (m_function==NULL) {
- if (PyErr_Occurred())
- ErrorPrint("Python controller found the module but could not access the function");
- else
- printf("Python module error in object '%s', controller '%s':\n '%s' module found but function missing\n", GetParent()->GetName().Ptr(), GetName().Ptr(), m_scriptText.Ptr());
- return false;
- }
-
- if (!PyCallable_Check(m_function)) {
- Py_DECREF(m_function);
- m_function = NULL;
- printf("Python module function error in object '%s', controller '%s':\n '%s' not callable\n", GetParent()->GetName().Ptr(), GetName().Ptr(), m_scriptText.Ptr());
- return false;
- }
-
- m_function_argc = 0; /* rare cases this could be a function that isn't defined in python, assume zero args */
- if (PyFunction_Check(m_function)) {
- m_function_argc= ((PyCodeObject *)PyFunction_GET_CODE(m_function))->co_argcount;
- }
-
- if (m_function_argc > 1) {
- Py_DECREF(m_function);
- m_function = NULL;
- printf("Python module function in object '%s', controller '%s':\n '%s' takes %d args, should be zero or 1 controller arg\n", GetParent()->GetName().Ptr(), GetName().Ptr(), m_scriptText.Ptr(), m_function_argc);
- return false;
- }
-
- return true;
-}
-
-
-void SCA_PythonController::Trigger(SCA_LogicManager* logicmgr)
-{
- m_sCurrentController = this;
-
- PyObject *excdict= NULL;
- PyObject *resultobj= NULL;
-
- switch (m_mode) {
- case SCA_PYEXEC_SCRIPT:
- {
- if (m_bModified)
- if (Compile()==false) // sets m_bModified to false
- return;
- if (!m_bytecode)
- return;
-
- /*
- * This part here with excdict is a temporary patch
- * to avoid python/gameengine crashes when python
- * inadvertently holds references to game objects
- * in global variables.
- *
- * The idea is always make a fresh dictionary, and
- * destroy it right after it is used to make sure
- * python won't hold any gameobject references.
- *
- * Note that the PyDict_Clear _is_ necessary before
- * the Py_DECREF() because it is possible for the
- * variables inside the dictionary to hold references
- * to the dictionary (ie. generate a cycle), so we
- * break it by hand, then DECREF (which in this case
- * should always ensure excdict is cleared).
- */
-
- excdict= PyDict_Copy(m_pythondictionary);
-
- resultobj = PyEval_EvalCode((PyObject *)m_bytecode, excdict, excdict);
-
- /* PyRun_SimpleString(m_scriptText.Ptr()); */
- break;
- }
- case SCA_PYEXEC_MODULE:
- {
- if (m_bModified || m_debug)
- if (Import()==false) // sets m_bModified to false
- return;
- if (!m_function)
- return;
-
- PyObject *args= NULL;
-
- if (m_function_argc==1) {
- args = PyTuple_New(1);
- PyTuple_SET_ITEM(args, 0, GetProxy());
- }
-
- resultobj = PyObject_CallObject(m_function, args);
- Py_XDECREF(args);
- break;
- }
-
- } /* end switch */
-
-
- /* Free the return value and print the error */
- if (resultobj)
- Py_DECREF(resultobj);
- else
- ErrorPrint("Python script error");
-
- if (excdict) /* Only for SCA_PYEXEC_SCRIPT types */
- {
- /* clear after PyErrPrint - seems it can be using
- * something in this dictionary and crash? */
- // This doesn't appear to be needed anymore
- //PyDict_Clear(excdict);
- Py_DECREF(excdict);
- }
-
- m_triggeredSensors.clear();
- m_sCurrentController = NULL;
-}
-
-PyObject *SCA_PythonController::PyActivate(PyObject *value)
-{
- if (m_sCurrentController != this) {
- PyErr_SetString(PyExc_SystemError, "Cannot activate an actuator from a non-active controller");
- return NULL;
- }
-
- SCA_IActuator* actu = LinkedActuatorFromPy(value);
- if (actu==NULL)
- return NULL;
-
- m_logicManager->AddActiveActuator((SCA_IActuator*)actu, true);
- Py_RETURN_NONE;
-}
-
-PyObject *SCA_PythonController::PyDeActivate(PyObject *value)
-{
- if (m_sCurrentController != this) {
- PyErr_SetString(PyExc_SystemError, "Cannot deactivate an actuator from a non-active controller");
- return NULL;
- }
-
- SCA_IActuator* actu = LinkedActuatorFromPy(value);
- if (actu==NULL)
- return NULL;
-
- m_logicManager->AddActiveActuator((SCA_IActuator*)actu, false);
- Py_RETURN_NONE;
-}
-
-PyObject *SCA_PythonController::pyattr_get_script(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- //SCA_PythonController* self = static_cast<SCA_PythonController*>(static_cast<SCA_IController*>(static_cast<SCA_ILogicBrick*>(static_cast<CValue*>(static_cast<PyObjectPlus*>(self_v)))));
- // static_cast<void *>(dynamic_cast<Derived *>(obj)) - static_cast<void *>(obj)
-
- SCA_PythonController* self = static_cast<SCA_PythonController*>(self_v);
- return PyUnicode_From_STR_String(self->m_scriptText);
-}
-
-
-
-int SCA_PythonController::pyattr_set_script(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- SCA_PythonController* self = static_cast<SCA_PythonController*>(self_v);
-
- const char *scriptArg = _PyUnicode_AsString(value);
-
- if (scriptArg==NULL) {
- PyErr_SetString(PyExc_TypeError, "controller.script = string: Python Controller, expected a string script text");
- return PY_SET_ATTR_FAIL;
- }
-
- /* set scripttext sets m_bModified to true,
- * so next time the script is needed, a reparse into byte code is done */
- self->SetScriptText(scriptArg);
-
- return PY_SET_ATTR_SUCCESS;
-}
-
-#else // WITH_PYTHON
-
-void SCA_PythonController::Trigger(SCA_LogicManager* logicmgr)
-{
- /* intentionally blank */
-}
-
-#endif // WITH_PYTHON
-
-/* eof */
diff --git a/source/gameengine/GameLogic/SCA_PythonController.h b/source/gameengine/GameLogic/SCA_PythonController.h
deleted file mode 100644
index 11241da9117..00000000000
--- a/source/gameengine/GameLogic/SCA_PythonController.h
+++ /dev/null
@@ -1,118 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file SCA_PythonController.h
- * \ingroup gamelogic
- * \brief Execute Python scripts
- */
-
-#ifndef __SCA_PYTHONCONTROLLER_H__
-#define __SCA_PYTHONCONTROLLER_H__
-
-#include "SCA_IController.h"
-#include "SCA_LogicManager.h"
-#include "EXP_BoolValue.h"
-
-#include <vector>
-
-class SCA_IObject;
-class SCA_PythonController : public SCA_IController
-{
- Py_Header
-#ifdef WITH_PYTHON
- struct _object * m_bytecode; /* SCA_PYEXEC_SCRIPT only */
- PyObject* m_function; /* SCA_PYEXEC_MODULE only */
-#endif
- int m_function_argc;
- bool m_bModified;
- bool m_debug; /* use with SCA_PYEXEC_MODULE for reloading every logic run */
- int m_mode;
-
-
- protected:
- STR_String m_scriptText;
- STR_String m_scriptName;
-#ifdef WITH_PYTHON
- PyObject* m_pythondictionary; /* for SCA_PYEXEC_SCRIPT only */
- PyObject* m_pythonfunction; /* for SCA_PYEXEC_MODULE only */
-#endif
- std::vector<class SCA_ISensor*> m_triggeredSensors;
-
- public:
- enum SCA_PyExecMode
- {
- SCA_PYEXEC_SCRIPT = 0,
- SCA_PYEXEC_MODULE,
- SCA_PYEXEC_MAX
- };
-
- static SCA_PythonController* m_sCurrentController; // protected !!!
-
- //for debugging
- //virtual CValue* AddRef();
- //virtual int Release(); // Release a reference to this value (when reference count reaches 0, the value is removed from the heap)
-
- SCA_PythonController(SCA_IObject* gameobj, int mode);
- virtual ~SCA_PythonController();
-
- virtual CValue* GetReplica();
- virtual void Trigger(class SCA_LogicManager* logicmgr);
-
- void SetScriptText(const STR_String& text);
- void SetScriptName(const STR_String& name);
-#ifdef WITH_PYTHON
- void SetNamespace(PyObject* pythondictionary);
-#endif
- void SetDebug(bool debug) { m_debug = debug; }
- void AddTriggeredSensor(class SCA_ISensor* sensor)
- { m_triggeredSensors.push_back(sensor); }
- bool IsTriggered(class SCA_ISensor* sensor);
- bool Compile();
- bool Import();
- void ErrorPrint(const char *error_msg);
-
-#ifdef WITH_PYTHON
- static const char *sPyGetCurrentController__doc__;
- static PyObject *sPyGetCurrentController(PyObject *self);
- static const char *sPyAddActiveActuator__doc__;
- static PyObject *sPyAddActiveActuator(PyObject *self,
- PyObject *args);
- static SCA_IActuator* LinkedActuatorFromPy(PyObject *value);
-
-
- KX_PYMETHOD_O(SCA_PythonController,Activate);
- KX_PYMETHOD_O(SCA_PythonController,DeActivate);
- KX_PYMETHOD_O(SCA_PythonController,SetScript);
- KX_PYMETHOD_NOARGS(SCA_PythonController,GetScript);
-
-
- static PyObject* pyattr_get_script(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_script(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
-#endif
-};
-
-#endif /* __SCA_PYTHONCONTROLLER_H__ */
diff --git a/source/gameengine/GameLogic/SCA_PythonJoystick.cpp b/source/gameengine/GameLogic/SCA_PythonJoystick.cpp
deleted file mode 100644
index 9b24ad7bcf2..00000000000
--- a/source/gameengine/GameLogic/SCA_PythonJoystick.cpp
+++ /dev/null
@@ -1,188 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * Contributor(s): Mitchell Stokes.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/GameLogic/SCA_PythonJoystick.cpp
- * \ingroup gamelogic
- */
-
-
-#include "SCA_PythonJoystick.h"
-#include "./Joystick/SCA_Joystick.h"
-#include "SCA_IInputDevice.h"
-
-//#include "GHOST_C-api.h"
-
-/* ------------------------------------------------------------------------- */
-/* Native functions */
-/* ------------------------------------------------------------------------- */
-
-SCA_PythonJoystick::SCA_PythonJoystick(SCA_Joystick* joystick)
-: PyObjectPlus(),
-m_joystick(joystick)
-{
-#ifdef WITH_PYTHON
- m_event_dict = PyDict_New();
-#endif
-}
-
-SCA_PythonJoystick::~SCA_PythonJoystick()
-{
- // The joystick reference we got in the constructor was a new instance,
- // so we release it here
- m_joystick->ReleaseInstance();
-
-#ifdef WITH_PYTHON
- PyDict_Clear(m_event_dict);
- Py_DECREF(m_event_dict);
-#endif
-}
-
-#ifdef WITH_PYTHON
-
-/* ------------------------------------------------------------------------- */
-/* Python functions */
-/* ------------------------------------------------------------------------- */
-PyObject* SCA_PythonJoystick::py_repr(void)
-{
- return PyUnicode_FromString(m_joystick->GetName());
-}
-
-
-/* Integration hooks ------------------------------------------------------- */
-PyTypeObject SCA_PythonJoystick::Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "SCA_PythonJoystick",
- sizeof(PyObjectPlus_Proxy),
- 0,
- py_base_dealloc,
- 0,
- 0,
- 0,
- 0,
- py_base_repr,
- 0,0,0,0,0,0,0,0,0,
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
- 0,0,0,0,0,0,0,
- Methods,
- 0,
- 0,
- &PyObjectPlus::Type,
- 0,0,0,0,0,0,
- py_base_new
-};
-
-PyMethodDef SCA_PythonJoystick::Methods[] = {
- {NULL,NULL} //Sentinel
-};
-
-PyAttributeDef SCA_PythonJoystick::Attributes[] = {
- KX_PYATTRIBUTE_RO_FUNCTION("numButtons", SCA_PythonJoystick, pyattr_get_num_x),
- KX_PYATTRIBUTE_RO_FUNCTION("numHats", SCA_PythonJoystick, pyattr_get_num_x),
- KX_PYATTRIBUTE_RO_FUNCTION("numAxis", SCA_PythonJoystick, pyattr_get_num_x),
- KX_PYATTRIBUTE_RO_FUNCTION("activeButtons", SCA_PythonJoystick, pyattr_get_active_buttons),
- KX_PYATTRIBUTE_RO_FUNCTION("hatValues", SCA_PythonJoystick, pyattr_get_hat_values),
- KX_PYATTRIBUTE_RO_FUNCTION("axisValues", SCA_PythonJoystick, pyattr_get_axis_values),
- KX_PYATTRIBUTE_RO_FUNCTION("name", SCA_PythonJoystick, pyattr_get_name),
- { NULL } //Sentinel
-};
-
-// Use one function for numAxis, numButtons, and numHats
-PyObject* SCA_PythonJoystick::pyattr_get_num_x(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- SCA_PythonJoystick* self = static_cast<SCA_PythonJoystick*>(self_v);
-
- if (strcmp(attrdef->m_name, "numButtons") == 0)
- return PyLong_FromLong(self->m_joystick->GetNumberOfButtons());
- else if (strcmp(attrdef->m_name, "numAxis") == 0)
- return PyLong_FromLong(self->m_joystick->GetNumberOfAxes());
- else if (strcmp(attrdef->m_name, "numHats") == 0)
- return PyLong_FromLong(self->m_joystick->GetNumberOfHats());
-
- // If we got here, we have a problem...
- PyErr_SetString(PyExc_AttributeError, "invalid attribute");
- return NULL;
-}
-
-PyObject* SCA_PythonJoystick::pyattr_get_active_buttons(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- SCA_PythonJoystick* self = static_cast<SCA_PythonJoystick*>(self_v);
-
- const int button_number = self->m_joystick->GetNumberOfButtons();
-
- PyObject *list = PyList_New(0);
- PyObject *value;
-
- for (int i=0; i < button_number; i++) {
- if (self->m_joystick->aButtonPressIsPositive(i)) {
- value = PyLong_FromLong(i);
- PyList_Append(list, value);
- Py_DECREF(value);
- }
- }
-
- return list;
-}
-
-PyObject* SCA_PythonJoystick::pyattr_get_hat_values(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- SCA_PythonJoystick* self = static_cast<SCA_PythonJoystick*>(self_v);
-
- int hat_index = self->m_joystick->GetNumberOfHats();
- PyObject *list = PyList_New(hat_index);
-
- while (hat_index--) {
- PyList_SET_ITEM(list, hat_index, PyLong_FromLong(self->m_joystick->GetHat(hat_index)));
- }
-
- return list;
-}
-
-PyObject* SCA_PythonJoystick::pyattr_get_axis_values(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- SCA_PythonJoystick* self = static_cast<SCA_PythonJoystick*>(self_v);
-
- int axis_index = self->m_joystick->GetNumberOfAxes();
- PyObject *list = PyList_New(axis_index);
- int position;
-
- while (axis_index--) {
- position = self->m_joystick->GetAxisPosition(axis_index);
-
- // We get back a range from -32768 to 32767, so we use an if here to
- // get a perfect -1.0 to 1.0 mapping. Some oddball system might have an
- // actual min of -32767 for shorts, so we use SHRT_MIN/MAX to be safe.
- if (position < 0)
- PyList_SET_ITEM(list, axis_index, PyFloat_FromDouble(position/((double)-SHRT_MIN)));
- else
- PyList_SET_ITEM(list, axis_index, PyFloat_FromDouble(position/(double)SHRT_MAX));
- }
-
- return list;
-}
-
-PyObject* SCA_PythonJoystick::pyattr_get_name(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- SCA_PythonJoystick* self = static_cast<SCA_PythonJoystick*>(self_v);
-
- return PyUnicode_FromString(self->m_joystick->GetName());
-}
-#endif
diff --git a/source/gameengine/GameLogic/SCA_PythonJoystick.h b/source/gameengine/GameLogic/SCA_PythonJoystick.h
deleted file mode 100644
index ecde00d28b9..00000000000
--- a/source/gameengine/GameLogic/SCA_PythonJoystick.h
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * Contributor(s): Mitchell Stokes.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file SCA_PythonJoystick.h
- * \ingroup gamelogic
- */
-
-#ifndef __SCA_PYTHONJOYSTICK_H__
-#define __SCA_PYTHONJOYSTICK_H__
-
-#include "EXP_PyObjectPlus.h"
-
-class SCA_PythonJoystick : public PyObjectPlus
-{
- Py_Header
-private:
- class SCA_Joystick *m_joystick;
-#ifdef WITH_PYTHON
- PyObject* m_event_dict;
-#endif
-public:
- SCA_PythonJoystick(class SCA_Joystick* joystick);
- virtual ~SCA_PythonJoystick();
-
-#ifdef WITH_PYTHON
- virtual PyObject* py_repr(void);
-
- static PyObject* pyattr_get_num_x(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_active_buttons(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_hat_values(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_axis_values(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_name(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef);
-#endif
-};
-
-#endif //__SCA_PYTHONJOYSTICK_H__
-
diff --git a/source/gameengine/GameLogic/SCA_PythonKeyboard.cpp b/source/gameengine/GameLogic/SCA_PythonKeyboard.cpp
deleted file mode 100644
index 9a96a7b0334..00000000000
--- a/source/gameengine/GameLogic/SCA_PythonKeyboard.cpp
+++ /dev/null
@@ -1,153 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/GameLogic/SCA_PythonKeyboard.cpp
- * \ingroup gamelogic
- */
-
-
-#include "SCA_PythonKeyboard.h"
-#include "SCA_IInputDevice.h"
-
-#include "GHOST_C-api.h"
-
-/* ------------------------------------------------------------------------- */
-/* Native functions */
-/* ------------------------------------------------------------------------- */
-
-SCA_PythonKeyboard::SCA_PythonKeyboard(SCA_IInputDevice* keyboard)
-: PyObjectPlus(),
-m_keyboard(keyboard)
-{
-#ifdef WITH_PYTHON
- m_event_dict = PyDict_New();
-#endif
-}
-
-SCA_PythonKeyboard::~SCA_PythonKeyboard()
-{
-#ifdef WITH_PYTHON
- PyDict_Clear(m_event_dict);
- Py_DECREF(m_event_dict);
-#endif
-}
-
-#ifdef WITH_PYTHON
-
-/* ------------------------------------------------------------------------- */
-/* Python functions */
-/* ------------------------------------------------------------------------- */
-
-/* clipboard */
-static PyObject *gPyGetClipboard(PyObject *args, PyObject *kwds)
-{
- char *buf = (char *)GHOST_getClipboard(0);
- return PyUnicode_FromString(buf?buf:"");
-}
-
-static PyObject *gPySetClipboard(PyObject *args, PyObject *value)
-{
- char* buf;
- if (!PyArg_ParseTuple(value,"s:setClipboard",&buf))
- Py_RETURN_NONE;
-
- GHOST_putClipboard((GHOST_TInt8 *)buf, 0);
- Py_RETURN_NONE;
-}
-
-/* Integration hooks ------------------------------------------------------- */
-PyTypeObject SCA_PythonKeyboard::Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "SCA_PythonKeyboard",
- sizeof(PyObjectPlus_Proxy),
- 0,
- py_base_dealloc,
- 0,
- 0,
- 0,
- 0,
- py_base_repr,
- 0,0,0,0,0,0,0,0,0,
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
- 0,0,0,0,0,0,0,
- Methods,
- 0,
- 0,
- &PyObjectPlus::Type,
- 0,0,0,0,0,0,
- py_base_new
-};
-
-PyMethodDef SCA_PythonKeyboard::Methods[] = {
- {"getClipboard", (PyCFunction) gPyGetClipboard, METH_VARARGS, "getCliboard doc"},
- {"setClipboard", (PyCFunction) gPySetClipboard, METH_VARARGS, "setCliboard doc"},
- {NULL,NULL} //Sentinel
-};
-
-PyAttributeDef SCA_PythonKeyboard::Attributes[] = {
- KX_PYATTRIBUTE_RO_FUNCTION("events", SCA_PythonKeyboard, pyattr_get_events),
- KX_PYATTRIBUTE_RO_FUNCTION("active_events", SCA_PythonKeyboard, pyattr_get_active_events),
- { NULL } //Sentinel
-};
-
-PyObject *SCA_PythonKeyboard::pyattr_get_events(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- SCA_PythonKeyboard* self = static_cast<SCA_PythonKeyboard*>(self_v);
-
- for (int i = SCA_IInputDevice::KX_BEGINKEY; i <= SCA_IInputDevice::KX_ENDKEY; i++) {
- const SCA_InputEvent & inevent = self->m_keyboard->GetEventValue((SCA_IInputDevice::KX_EnumInputs)i);
- PyObject *key = PyLong_FromLong(i);
- PyObject *value = PyLong_FromLong(inevent.m_status);
-
- PyDict_SetItem(self->m_event_dict, key, value);
-
- Py_DECREF(key);
- Py_DECREF(value);
- }
- Py_INCREF(self->m_event_dict);
- return self->m_event_dict;
-}
-
-PyObject *SCA_PythonKeyboard::pyattr_get_active_events(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- SCA_PythonKeyboard* self = static_cast<SCA_PythonKeyboard*>(self_v);
-
- PyDict_Clear(self->m_event_dict);
-
- for (int i = SCA_IInputDevice::KX_BEGINKEY; i <= SCA_IInputDevice::KX_ENDKEY; i++) {
- const SCA_InputEvent & inevent = self->m_keyboard->GetEventValue((SCA_IInputDevice::KX_EnumInputs)i);
-
- if (inevent.m_status != SCA_InputEvent::KX_NO_INPUTSTATUS) {
- PyObject *key = PyLong_FromLong(i);
- PyObject *value = PyLong_FromLong(inevent.m_status);
-
- PyDict_SetItem(self->m_event_dict, key, value);
-
- Py_DECREF(key);
- Py_DECREF(value);
- }
- }
- Py_INCREF(self->m_event_dict);
- return self->m_event_dict;
-}
-
-#endif
diff --git a/source/gameengine/GameLogic/SCA_PythonKeyboard.h b/source/gameengine/GameLogic/SCA_PythonKeyboard.h
deleted file mode 100644
index 3cbe250378c..00000000000
--- a/source/gameengine/GameLogic/SCA_PythonKeyboard.h
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file SCA_PythonKeyboard.h
- * \ingroup gamelogic
- */
-
-#ifndef __SCA_PYTHONKEYBOARD_H__
-#define __SCA_PYTHONKEYBOARD_H__
-
-#include "EXP_PyObjectPlus.h"
-
-class SCA_PythonKeyboard : public PyObjectPlus
-{
- Py_Header
-private:
- class SCA_IInputDevice *m_keyboard;
-#ifdef WITH_PYTHON
- PyObject *m_event_dict;
-#endif
-public:
- SCA_PythonKeyboard(class SCA_IInputDevice* keyboard);
- virtual ~SCA_PythonKeyboard();
-
-#ifdef WITH_PYTHON
- static PyObject* pyattr_get_events(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_active_events(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef);
-#endif
-};
-
-#endif /* __SCA_PYTHONKEYBOARD_H__ */
diff --git a/source/gameengine/GameLogic/SCA_PythonMouse.cpp b/source/gameengine/GameLogic/SCA_PythonMouse.cpp
deleted file mode 100644
index 184b306a665..00000000000
--- a/source/gameengine/GameLogic/SCA_PythonMouse.cpp
+++ /dev/null
@@ -1,206 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/GameLogic/SCA_PythonMouse.cpp
- * \ingroup gamelogic
- */
-
-
-#include "SCA_PythonMouse.h"
-#include "SCA_IInputDevice.h"
-#include "RAS_ICanvas.h"
-
-/* ------------------------------------------------------------------------- */
-/* Native functions */
-/* ------------------------------------------------------------------------- */
-
-SCA_PythonMouse::SCA_PythonMouse(SCA_IInputDevice* mouse, RAS_ICanvas* canvas)
-: PyObjectPlus(),
-m_mouse(mouse),
-m_canvas(canvas)
-{
-#ifdef WITH_PYTHON
- m_event_dict = PyDict_New();
-#endif
-}
-
-SCA_PythonMouse::~SCA_PythonMouse()
-{
-#ifdef WITH_PYTHON
- PyDict_Clear(m_event_dict);
- Py_DECREF(m_event_dict);
-#endif
-}
-
-#ifdef WITH_PYTHON
-
-/* ------------------------------------------------------------------------- */
-/* Python functions */
-/* ------------------------------------------------------------------------- */
-
-/* Integration hooks ------------------------------------------------------- */
-PyTypeObject SCA_PythonMouse::Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "SCA_PythonMouse",
- sizeof(PyObjectPlus_Proxy),
- 0,
- py_base_dealloc,
- 0,
- 0,
- 0,
- 0,
- py_base_repr,
- 0,0,0,0,0,0,0,0,0,
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
- 0,0,0,0,0,0,0,
- Methods,
- 0,
- 0,
- &PyObjectPlus::Type,
- 0,0,0,0,0,0,
- py_base_new
-};
-
-PyMethodDef SCA_PythonMouse::Methods[] = {
- {NULL,NULL} //Sentinel
-};
-
-PyAttributeDef SCA_PythonMouse::Attributes[] = {
- KX_PYATTRIBUTE_RO_FUNCTION("events", SCA_PythonMouse, pyattr_get_events),
- KX_PYATTRIBUTE_RO_FUNCTION("active_events", SCA_PythonMouse, pyattr_get_active_events),
- KX_PYATTRIBUTE_RW_FUNCTION("position", SCA_PythonMouse, pyattr_get_position, pyattr_set_position),
- KX_PYATTRIBUTE_RW_FUNCTION("visible", SCA_PythonMouse, pyattr_get_visible, pyattr_set_visible),
- { NULL } //Sentinel
-};
-
-PyObject *SCA_PythonMouse::pyattr_get_events(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- SCA_PythonMouse* self = static_cast<SCA_PythonMouse*>(self_v);
-
- for (int i = SCA_IInputDevice::KX_BEGINMOUSE; i <= SCA_IInputDevice::KX_ENDMOUSE; i++) {
- const SCA_InputEvent &inevent = self->m_mouse->GetEventValue((SCA_IInputDevice::KX_EnumInputs)i);
- PyObject *key = PyLong_FromLong(i);
- PyObject *value = PyLong_FromLong(inevent.m_status);
-
- PyDict_SetItem(self->m_event_dict, key, value);
-
- Py_DECREF(key);
- Py_DECREF(value);
- }
- Py_INCREF(self->m_event_dict);
- return self->m_event_dict;
-}
-
-PyObject *SCA_PythonMouse::pyattr_get_active_events(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- SCA_PythonMouse* self = static_cast<SCA_PythonMouse*>(self_v);
-
- PyDict_Clear(self->m_event_dict);
-
- for (int i = SCA_IInputDevice::KX_BEGINMOUSE; i <= SCA_IInputDevice::KX_ENDMOUSE; i++) {
- const SCA_InputEvent &inevent = self->m_mouse->GetEventValue((SCA_IInputDevice::KX_EnumInputs)i);
-
- if (inevent.m_status != SCA_InputEvent::KX_NO_INPUTSTATUS) {
-
- PyObject *key = PyLong_FromLong(i);
- PyObject *value = PyLong_FromLong(inevent.m_status);
-
- PyDict_SetItem(self->m_event_dict, key, value);
-
- Py_DECREF(key);
- Py_DECREF(value);
- }
- }
- Py_INCREF(self->m_event_dict);
- return self->m_event_dict;
-}
-
-PyObject *SCA_PythonMouse::pyattr_get_position(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- SCA_PythonMouse* self = static_cast<SCA_PythonMouse*>(self_v);
- const SCA_InputEvent & xevent = self->m_mouse->GetEventValue(SCA_IInputDevice::KX_MOUSEX);
- const SCA_InputEvent & yevent = self->m_mouse->GetEventValue(SCA_IInputDevice::KX_MOUSEY);
-
- float x_coord, y_coord;
-
- x_coord = self->m_canvas->GetMouseNormalizedX(xevent.m_eventval);
- y_coord = self->m_canvas->GetMouseNormalizedY(yevent.m_eventval);
-
- PyObject *ret = PyTuple_New(2);
-
- PyTuple_SET_ITEM(ret, 0, PyFloat_FromDouble(x_coord));
- PyTuple_SET_ITEM(ret, 1, PyFloat_FromDouble(y_coord));
-
- return ret;
-}
-
-int SCA_PythonMouse::pyattr_set_position(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- SCA_PythonMouse* self = static_cast<SCA_PythonMouse*>(self_v);
- int x, y;
- float pyx, pyy;
- if (!PyArg_ParseTuple(value, "ff:position", &pyx, &pyy))
- return PY_SET_ATTR_FAIL;
-
- x = (int)(pyx*self->m_canvas->GetWidth());
- y = (int)(pyy*self->m_canvas->GetHeight());
-
- self->m_canvas->SetMousePosition(x, y);
-
- return PY_SET_ATTR_SUCCESS;
-}
-
-PyObject *SCA_PythonMouse::pyattr_get_visible(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- SCA_PythonMouse* self = static_cast<SCA_PythonMouse*>(self_v);
-
- int visible;
-
- if (self->m_canvas->GetMouseState() == RAS_ICanvas::MOUSE_INVISIBLE)
- visible = 0;
- else
- visible = 1;
-
- return PyBool_FromLong(visible);
-}
-
-int SCA_PythonMouse::pyattr_set_visible(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- SCA_PythonMouse* self = static_cast<SCA_PythonMouse*>(self_v);
-
- int visible = PyObject_IsTrue(value);
-
- if (visible == -1)
- {
- PyErr_SetString(PyExc_AttributeError, "SCA_PythonMouse.visible = bool: SCA_PythonMouse, expected True or False");
- return PY_SET_ATTR_FAIL;
- }
-
- if (visible)
- self->m_canvas->SetMouseState(RAS_ICanvas::MOUSE_NORMAL);
- else
- self->m_canvas->SetMouseState(RAS_ICanvas::MOUSE_INVISIBLE);
-
- return PY_SET_ATTR_SUCCESS;
-}
-
-#endif
diff --git a/source/gameengine/GameLogic/SCA_PythonMouse.h b/source/gameengine/GameLogic/SCA_PythonMouse.h
deleted file mode 100644
index 6dde90b3482..00000000000
--- a/source/gameengine/GameLogic/SCA_PythonMouse.h
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file SCA_PythonMouse.h
- * \ingroup gamelogic
- */
-
-#ifndef __SCA_PYTHONMOUSE_H__
-#define __SCA_PYTHONMOUSE_H__
-
-#include "EXP_PyObjectPlus.h"
-
-class SCA_PythonMouse : public PyObjectPlus
-{
- Py_Header
-private:
- class SCA_IInputDevice *m_mouse;
- class RAS_ICanvas *m_canvas;
-#ifdef WITH_PYTHON
- PyObject *m_event_dict;
-#endif
-public:
- SCA_PythonMouse(class SCA_IInputDevice* mouse, class RAS_ICanvas* canvas);
- virtual ~SCA_PythonMouse();
-
- void Show(bool visible);
-
-#ifdef WITH_PYTHON
- KX_PYMETHOD_DOC(SCA_PythonMouse, show);
-
- static PyObject *pyattr_get_events(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject *pyattr_get_active_events(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject *pyattr_get_position(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_position(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static PyObject *pyattr_get_visible(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_visible(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
-#endif
-};
-
-#endif /* __SCA_PYTHONMOUSE_H__ */
diff --git a/source/gameengine/GameLogic/SCA_RandomActuator.cpp b/source/gameengine/GameLogic/SCA_RandomActuator.cpp
deleted file mode 100644
index 8d75be9089d..00000000000
--- a/source/gameengine/GameLogic/SCA_RandomActuator.cpp
+++ /dev/null
@@ -1,543 +0,0 @@
-/*
- * Set random/camera stuff
- *
- *
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/GameLogic/SCA_RandomActuator.cpp
- * \ingroup gamelogic
- */
-
-
-#include <stddef.h>
-#include <math.h>
-
-#include "EXP_BoolValue.h"
-#include "EXP_IntValue.h"
-#include "EXP_FloatValue.h"
-#include "SCA_IActuator.h"
-#include "SCA_RandomActuator.h"
-#include "MT_Transform.h"
-
-/* ------------------------------------------------------------------------- */
-/* Native functions */
-/* ------------------------------------------------------------------------- */
-
-SCA_RandomActuator::SCA_RandomActuator(SCA_IObject *gameobj,
- long seed,
- SCA_RandomActuator::KX_RANDOMACT_MODE mode,
- float para1,
- float para2,
- const STR_String &propName)
- : SCA_IActuator(gameobj, KX_ACT_RANDOM),
- m_propname(propName),
- m_parameter1(para1),
- m_parameter2(para2),
- m_distribution(mode)
-{
- m_base = new SCA_RandomNumberGenerator(seed);
- m_counter = 0;
- enforceConstraints();
-}
-
-
-
-SCA_RandomActuator::~SCA_RandomActuator()
-{
- m_base->Release();
-}
-
-
-
-CValue* SCA_RandomActuator::GetReplica()
-{
- SCA_RandomActuator* replica = new SCA_RandomActuator(*this);
- // replication just copy the m_base pointer => common random generator
- replica->ProcessReplica();
- return replica;
-}
-
-void SCA_RandomActuator::ProcessReplica()
-{
- SCA_IActuator::ProcessReplica();
- // increment reference count so that we can release the generator at the end
- m_base->AddRef();
-}
-
-
-
-bool SCA_RandomActuator::Update()
-{
- //bool result = false; /*unused*/
- bool bNegativeEvent = IsNegativeEvent();
-
- RemoveAllEvents();
-
-
- CValue *tmpval = NULL;
-
- if (bNegativeEvent)
- return false; // do nothing on negative events
-
- switch (m_distribution) {
- case KX_RANDOMACT_BOOL_CONST: {
- /* un petit peu filthy */
- bool res = !(m_parameter1 < 0.5);
- tmpval = new CBoolValue(res);
- }
- break;
- case KX_RANDOMACT_BOOL_UNIFORM: {
- /* flip a coin */
- bool res;
- if (m_counter > 31) {
- m_previous = m_base->Draw();
- res = ((m_previous & 0x1) == 0);
- m_counter = 1;
- } else {
- res = (((m_previous >> m_counter) & 0x1) == 0);
- m_counter++;
- }
- tmpval = new CBoolValue(res);
- }
- break;
- case KX_RANDOMACT_BOOL_BERNOUILLI: {
- /* 'percentage' */
- bool res;
- res = (m_base->DrawFloat() < m_parameter1);
- tmpval = new CBoolValue(res);
- }
- break;
- case KX_RANDOMACT_INT_CONST: {
- /* constant */
- tmpval = new CIntValue((int) floor(m_parameter1));
- }
- break;
- case KX_RANDOMACT_INT_UNIFORM: {
- /* uniform (toss a die) */
- int res;
- /* The [0, 1] interval is projected onto the [min, max+1] domain, */
- /* and then rounded. */
- res = (int)floor( ((m_parameter2 - m_parameter1 + 1) * m_base->DrawFloat()) + m_parameter1);
- tmpval = new CIntValue(res);
- }
- break;
- case KX_RANDOMACT_INT_POISSON: {
- /* poisson (queues) */
- /* If x_1, x_2, ... is a sequence of random numbers with uniform */
- /* distribution between zero and one, k is the first integer for */
- /* which the product x_1*x_2*...*x_k < exp(-\lamba). */
- float a, b;
- int res = 0;
- /* The - sign is important here! The number to test for, a, must be */
- /* between 0 and 1. */
- a = exp(-m_parameter1);
- /* a quickly reaches 0.... so we guard explicitly for that. */
- if (a < FLT_MIN) a = FLT_MIN;
- b = m_base->DrawFloat();
- while (b >= a) {
- b = b * m_base->DrawFloat();
- res++;
- };
- tmpval = new CIntValue(res);
- }
- break;
- case KX_RANDOMACT_FLOAT_CONST: {
- /* constant */
- tmpval = new CFloatValue(m_parameter1);
- }
- break;
- case KX_RANDOMACT_FLOAT_UNIFORM: {
- float res = ((m_parameter2 - m_parameter1) * m_base->DrawFloat()) + m_parameter1;
- tmpval = new CFloatValue(res);
- }
- break;
- case KX_RANDOMACT_FLOAT_NORMAL: {
- /* normal (big numbers): para1 = mean, para2 = std dev */
-
- /* 070301 - nzc: Changed the termination condition. I think I
- * made a small mistake here, but it only affects distro's where
- * the seed equals 0. In that case, the algorithm locks. Let's
- * just guard that case separately.
- */
-
- float x = 0.0, y = 0.0, s = 0.0, t = 0.0;
- if (m_base->GetSeed() == 0) {
- /* 070301 - nzc: Just taking the mean here seems reasonable. */
- tmpval = new CFloatValue(m_parameter1);
- }
- else {
- /* 070301 - nzc
- * Now, with seed != 0, we will most assuredly get some
- * sensible values. The termination condition states two
- * things:
- * 1. s >= 0 is not allowed: to prevent the distro from
- * getting a bias towards high values. This is a small
- * correction, really, and might also be left out.
- * 2. s == 0 is not allowed: to prevent a division by zero
- * when renormalising the drawn value to the desired
- * distribution shape. As a side effect, the distro will
- * never yield the exact mean.
- * I am not sure whether this is consistent, since the error
- * cause by #2 is of the same magnitude as the one
- * prevented by #1. The error introduced into the SD will be
- * improved, though. By how much? Hard to say... If you like
- * the maths, feel free to analyse. Be aware that this is
- * one of the really old standard algorithms. I think the
- * original came in Fortran, was translated to Pascal, and
- * then someone came up with the C code. My guess it that
- * this will be quite sufficient here.
- */
- do {
- x = 2.0f * m_base->DrawFloat() - 1.0f;
- y = 2.0f * m_base->DrawFloat() - 1.0f;
- s = x * x + y * y;
- } while ((s >= 1.0f) || (s == 0.0f));
- t = x * sqrtf((-2.0 * log(s)) / s);
- tmpval = new CFloatValue(m_parameter1 + m_parameter2 * t);
- }
- }
- break;
- case KX_RANDOMACT_FLOAT_NEGATIVE_EXPONENTIAL: {
- /* 1st order fall-off. I am very partial to using the half-life as */
- /* controlling parameter. Using the 'normal' exponent is not very */
- /* intuitive... */
- /* tmpval = new CFloatValue( (1.0 / m_parameter1) */
- tmpval = new CFloatValue((m_parameter1) * (-log(1.0 - m_base->DrawFloat())));
-
- }
- break;
- default:
- {
- /* unknown distribution... */
- static bool randomWarning = false;
- if (!randomWarning) {
- randomWarning = true;
- std::cout << "RandomActuator '" << GetName() << "' has an unknown distribution." << std::endl;
- }
- return false;
- }
- }
-
- /* Round up: assign it */
- CValue *prop = GetParent()->GetProperty(m_propname);
- if (prop) {
- prop->SetValue(tmpval);
- }
- tmpval->Release();
-
- return false;
-}
-
-void SCA_RandomActuator::enforceConstraints()
-{
- /* The constraints that are checked here are the ones fundamental to */
- /* the various distributions. Limitations of the algorithms are checked */
- /* elsewhere (or they should be... ). */
- switch (m_distribution) {
- case KX_RANDOMACT_BOOL_CONST:
- case KX_RANDOMACT_BOOL_UNIFORM:
- case KX_RANDOMACT_INT_CONST:
- case KX_RANDOMACT_INT_UNIFORM:
- case KX_RANDOMACT_FLOAT_UNIFORM:
- case KX_RANDOMACT_FLOAT_CONST:
- ; /* Nothing to be done here. We allow uniform distro's to have */
- /* 'funny' domains, i.e. max < min. This does not give problems. */
- break;
- case KX_RANDOMACT_BOOL_BERNOUILLI:
- /* clamp to [0, 1] */
- if (m_parameter1 < 0.0) {
- m_parameter1 = 0.0;
- } else if (m_parameter1 > 1.0) {
- m_parameter1 = 1.0;
- }
- break;
- case KX_RANDOMACT_INT_POISSON:
- /* non-negative */
- if (m_parameter1 < 0.0) {
- m_parameter1 = 0.0;
- }
- break;
- case KX_RANDOMACT_FLOAT_NORMAL:
- /* standard dev. is non-negative */
- if (m_parameter2 < 0.0) {
- m_parameter2 = 0.0;
- }
- break;
- case KX_RANDOMACT_FLOAT_NEGATIVE_EXPONENTIAL:
- /* halflife must be non-negative */
- if (m_parameter1 < 0.0) {
- m_parameter1 = 0.0;
- }
- break;
- default:
- ; /* unknown distribution... */
- }
-}
-
-#ifdef WITH_PYTHON
-
-/* ------------------------------------------------------------------------- */
-/* Python functions */
-/* ------------------------------------------------------------------------- */
-
-/* Integration hooks ------------------------------------------------------- */
-PyTypeObject SCA_RandomActuator::Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "SCA_RandomActuator",
- sizeof(PyObjectPlus_Proxy),
- 0,
- py_base_dealloc,
- 0,
- 0,
- 0,
- 0,
- py_base_repr,
- 0,0,0,0,0,0,0,0,0,
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
- 0,0,0,0,0,0,0,
- Methods,
- 0,
- 0,
- &SCA_IActuator::Type,
- 0,0,0,0,0,0,
- py_base_new
-};
-
-PyMethodDef SCA_RandomActuator::Methods[] = {
- KX_PYMETHODTABLE(SCA_RandomActuator, setBoolConst),
- KX_PYMETHODTABLE_NOARGS(SCA_RandomActuator, setBoolUniform),
- KX_PYMETHODTABLE(SCA_RandomActuator, setBoolBernouilli),
-
- KX_PYMETHODTABLE(SCA_RandomActuator, setIntConst),
- KX_PYMETHODTABLE(SCA_RandomActuator, setIntUniform),
- KX_PYMETHODTABLE(SCA_RandomActuator, setIntPoisson),
-
- KX_PYMETHODTABLE(SCA_RandomActuator, setFloatConst),
- KX_PYMETHODTABLE(SCA_RandomActuator, setFloatUniform),
- KX_PYMETHODTABLE(SCA_RandomActuator, setFloatNormal),
- KX_PYMETHODTABLE(SCA_RandomActuator, setFloatNegativeExponential),
- {NULL,NULL} //Sentinel
-};
-
-PyAttributeDef SCA_RandomActuator::Attributes[] = {
- KX_PYATTRIBUTE_FLOAT_RO("para1",SCA_RandomActuator,m_parameter1),
- KX_PYATTRIBUTE_FLOAT_RO("para2",SCA_RandomActuator,m_parameter2),
- KX_PYATTRIBUTE_ENUM_RO("distribution",SCA_RandomActuator,m_distribution),
- KX_PYATTRIBUTE_STRING_RW_CHECK("propName",0,MAX_PROP_NAME,false,SCA_RandomActuator,m_propname,CheckProperty),
- KX_PYATTRIBUTE_RW_FUNCTION("seed",SCA_RandomActuator,pyattr_get_seed,pyattr_set_seed),
- { NULL } //Sentinel
-};
-
-PyObject *SCA_RandomActuator::pyattr_get_seed(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef)
-{
- SCA_RandomActuator* act = static_cast<SCA_RandomActuator*>(self);
- return PyLong_FromLong(act->m_base->GetSeed());
-}
-
-int SCA_RandomActuator::pyattr_set_seed(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- SCA_RandomActuator* act = static_cast<SCA_RandomActuator*>(self);
- if (PyLong_Check(value)) {
- act->m_base->SetSeed(PyLong_AsLong(value));
- return PY_SET_ATTR_SUCCESS;
- }
- else {
- PyErr_SetString(PyExc_TypeError, "actuator.seed = int: Random Actuator, expected an integer");
- return PY_SET_ATTR_FAIL;
- }
-}
-
-/* 11. setBoolConst */
-KX_PYMETHODDEF_DOC_VARARGS(SCA_RandomActuator, setBoolConst,
-"setBoolConst(value)\n"
-"\t- value: 0 or 1\n"
-"\tSet this generator to produce a constant boolean value.\n")
-{
- int paraArg;
- if (!PyArg_ParseTuple(args, "i:setBoolConst", &paraArg)) {
- return NULL;
- }
-
- m_distribution = KX_RANDOMACT_BOOL_CONST;
- m_parameter1 = (paraArg) ? 1.0 : 0.0;
-
- Py_RETURN_NONE;
-}
-/* 12. setBoolUniform, */
-KX_PYMETHODDEF_DOC_NOARGS(SCA_RandomActuator, setBoolUniform,
-"setBoolUniform()\n"
-"\tSet this generator to produce true and false, each with 50%% chance of occurring\n")
-{
- /* no args */
- m_distribution = KX_RANDOMACT_BOOL_UNIFORM;
- enforceConstraints();
- Py_RETURN_NONE;
-}
-/* 13. setBoolBernouilli, */
-KX_PYMETHODDEF_DOC_VARARGS(SCA_RandomActuator, setBoolBernouilli,
-"setBoolBernouilli(value)\n"
-"\t- value: a float between 0 and 1\n"
-"\tReturn false value * 100%% of the time.\n")
-{
- float paraArg;
- if (!PyArg_ParseTuple(args, "f:setBoolBernouilli", &paraArg)) {
- return NULL;
- }
-
- m_distribution = KX_RANDOMACT_BOOL_BERNOUILLI;
- m_parameter1 = paraArg;
- enforceConstraints();
- Py_RETURN_NONE;
-}
-/* 14. setIntConst,*/
-KX_PYMETHODDEF_DOC_VARARGS(SCA_RandomActuator, setIntConst,
-"setIntConst(value)\n"
-"\t- value: integer\n"
-"\tAlways return value\n")
-{
- int paraArg;
- if (!PyArg_ParseTuple(args, "i:setIntConst", &paraArg)) {
- return NULL;
- }
-
- m_distribution = KX_RANDOMACT_INT_CONST;
- m_parameter1 = paraArg;
- enforceConstraints();
- Py_RETURN_NONE;
-}
-/* 15. setIntUniform,*/
-KX_PYMETHODDEF_DOC_VARARGS(SCA_RandomActuator, setIntUniform,
-"setIntUniform(lower_bound, upper_bound)\n"
-"\t- lower_bound: integer\n"
-"\t- upper_bound: integer\n"
-"\tReturn a random integer between lower_bound and\n"
-"\tupper_bound. The boundaries are included.\n")
-{
- int paraArg1, paraArg2;
- if (!PyArg_ParseTuple(args, "ii:setIntUniform", &paraArg1, &paraArg2)) {
- return NULL;
- }
-
- m_distribution = KX_RANDOMACT_INT_UNIFORM;
- m_parameter1 = paraArg1;
- m_parameter2 = paraArg2;
- enforceConstraints();
- Py_RETURN_NONE;
-}
-/* 16. setIntPoisson, */
-KX_PYMETHODDEF_DOC_VARARGS(SCA_RandomActuator, setIntPoisson,
-"setIntPoisson(value)\n"
-"\t- value: float\n"
-"\tReturn a Poisson-distributed number. This performs a series\n"
-"\tof Bernouilli tests with parameter value. It returns the\n"
-"\tnumber of tries needed to achieve succes.\n")
-{
- float paraArg;
- if (!PyArg_ParseTuple(args, "f:setIntPoisson", &paraArg)) {
- return NULL;
- }
-
- m_distribution = KX_RANDOMACT_INT_POISSON;
- m_parameter1 = paraArg;
- enforceConstraints();
- Py_RETURN_NONE;
-}
-/* 17. setFloatConst */
-KX_PYMETHODDEF_DOC_VARARGS(SCA_RandomActuator, setFloatConst,
-"setFloatConst(value)\n"
-"\t- value: float\n"
-"\tAlways return value\n")
-{
- float paraArg;
- if (!PyArg_ParseTuple(args, "f:setFloatConst", &paraArg)) {
- return NULL;
- }
-
- m_distribution = KX_RANDOMACT_FLOAT_CONST;
- m_parameter1 = paraArg;
- enforceConstraints();
- Py_RETURN_NONE;
-}
-/* 18. setFloatUniform, */
-KX_PYMETHODDEF_DOC_VARARGS(SCA_RandomActuator, setFloatUniform,
-"setFloatUniform(lower_bound, upper_bound)\n"
-"\t- lower_bound: float\n"
-"\t- upper_bound: float\n"
-"\tReturn a random integer between lower_bound and\n"
-"\tupper_bound.\n")
-{
- float paraArg1, paraArg2;
- if (!PyArg_ParseTuple(args, "ff:setFloatUniform", &paraArg1, &paraArg2)) {
- return NULL;
- }
-
- m_distribution = KX_RANDOMACT_FLOAT_UNIFORM;
- m_parameter1 = paraArg1;
- m_parameter2 = paraArg2;
- enforceConstraints();
- Py_RETURN_NONE;
-}
-/* 19. setFloatNormal, */
-KX_PYMETHODDEF_DOC_VARARGS(SCA_RandomActuator, setFloatNormal,
-"setFloatNormal(mean, standard_deviation)\n"
-"\t- mean: float\n"
-"\t- standard_deviation: float\n"
-"\tReturn normal-distributed numbers. The average is mean, and the\n"
-"\tdeviation from the mean is characterized by standard_deviation.\n")
-{
- float paraArg1, paraArg2;
- if (!PyArg_ParseTuple(args, "ff:setFloatNormal", &paraArg1, &paraArg2)) {
- return NULL;
- }
-
- m_distribution = KX_RANDOMACT_FLOAT_NORMAL;
- m_parameter1 = paraArg1;
- m_parameter2 = paraArg2;
- enforceConstraints();
- Py_RETURN_NONE;
-}
-/* 20. setFloatNegativeExponential, */
-KX_PYMETHODDEF_DOC_VARARGS(SCA_RandomActuator, setFloatNegativeExponential,
-"setFloatNegativeExponential(half_life)\n"
-"\t- half_life: float\n"
-"\tReturn negative-exponentially distributed numbers. The half-life 'time'\n"
-"\tis characterized by half_life.\n")
-{
- float paraArg;
- if (!PyArg_ParseTuple(args, "f:setFloatNegativeExponential", &paraArg)) {
- return NULL;
- }
-
- m_distribution = KX_RANDOMACT_FLOAT_NEGATIVE_EXPONENTIAL;
- m_parameter1 = paraArg;
- enforceConstraints();
- Py_RETURN_NONE;
-}
-
-#endif
-
-/* eof */
diff --git a/source/gameengine/GameLogic/SCA_RandomActuator.h b/source/gameengine/GameLogic/SCA_RandomActuator.h
deleted file mode 100644
index 32b29fc4f43..00000000000
--- a/source/gameengine/GameLogic/SCA_RandomActuator.h
+++ /dev/null
@@ -1,120 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file SCA_RandomActuator.h
- * \ingroup gamelogic
- * \brief Draw a random number, and put it in a property
- */
-
-#ifndef __SCA_RANDOMACTUATOR_H__
-#define __SCA_RANDOMACTUATOR_H__
-
-#include "SCA_IActuator.h"
-#include "SCA_RandomNumberGenerator.h"
-
-class SCA_RandomActuator : public SCA_IActuator
-{
- Py_Header
- /** Property to assign to */
- STR_String m_propname;
-
- /** First parameter. The meaning of the parameters depends on the
- * distribution */
- float m_parameter1;
- /** Second parameter. The meaning of the parameters depends on the
- * distribution */
- float m_parameter2;
-
- /** The base generator */
- SCA_RandomNumberGenerator *m_base;
-
- /** just a generic, persistent counter */
- int m_counter;
-
- /** cache for the previous draw */
- long m_previous;
-
- /** apply constraints for the chosen distribution to the parameters */
- void enforceConstraints(void);
-
- public:
-
- enum KX_RANDOMACT_MODE {
- KX_RANDOMACT_NODEF,
- KX_RANDOMACT_BOOL_CONST,
- KX_RANDOMACT_BOOL_UNIFORM,
- KX_RANDOMACT_BOOL_BERNOUILLI,
- KX_RANDOMACT_INT_CONST,
- KX_RANDOMACT_INT_UNIFORM,
- KX_RANDOMACT_INT_POISSON,
- KX_RANDOMACT_FLOAT_CONST,
- KX_RANDOMACT_FLOAT_UNIFORM,
- KX_RANDOMACT_FLOAT_NORMAL,
- KX_RANDOMACT_FLOAT_NEGATIVE_EXPONENTIAL,
- KX_RANDOMACT_MAX
- };
- /** distribution type */
- KX_RANDOMACT_MODE m_distribution;
-
- SCA_RandomActuator(class SCA_IObject* gameobj,
- long seed,
- KX_RANDOMACT_MODE mode,
- float para1,
- float para2,
- const STR_String &propName);
- virtual ~SCA_RandomActuator();
- virtual bool Update();
-
- virtual CValue* GetReplica();
- virtual void ProcessReplica();
-
-#ifdef WITH_PYTHON
-
- /* --------------------------------------------------------------------- */
- /* Python interface ---------------------------------------------------- */
- /* --------------------------------------------------------------------- */
-
- static PyObject *pyattr_get_seed(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_seed(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
-
- KX_PYMETHOD_DOC_VARARGS(SCA_RandomActuator, setBoolConst);
- KX_PYMETHOD_DOC_NOARGS(SCA_RandomActuator, setBoolUniform);
- KX_PYMETHOD_DOC_VARARGS(SCA_RandomActuator, setBoolBernouilli);
- KX_PYMETHOD_DOC_VARARGS(SCA_RandomActuator, setIntConst);
- KX_PYMETHOD_DOC_VARARGS(SCA_RandomActuator, setIntUniform);
- KX_PYMETHOD_DOC_VARARGS(SCA_RandomActuator, setIntPoisson);
- KX_PYMETHOD_DOC_VARARGS(SCA_RandomActuator, setFloatConst);
- KX_PYMETHOD_DOC_VARARGS(SCA_RandomActuator, setFloatUniform);
- KX_PYMETHOD_DOC_VARARGS(SCA_RandomActuator, setFloatNormal);
- KX_PYMETHOD_DOC_VARARGS(SCA_RandomActuator, setFloatNegativeExponential);
-
-#endif /* WITH_PYTHON */
-
-}; /* end of class KX_EditObjectActuator : public SCA_PropertyActuator */
-
-#endif
-
diff --git a/source/gameengine/GameLogic/SCA_RandomEventManager.cpp b/source/gameengine/GameLogic/SCA_RandomEventManager.cpp
deleted file mode 100644
index 2ec6eb1db1b..00000000000
--- a/source/gameengine/GameLogic/SCA_RandomEventManager.cpp
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- * Manager for random events
- *
- *
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/GameLogic/SCA_RandomEventManager.cpp
- * \ingroup gamelogic
- */
-
-#include "SCA_RandomEventManager.h"
-#include "SCA_LogicManager.h"
-#include "SCA_ISensor.h"
-#include <vector>
-using namespace std;
-
-#include <iostream>
-#include <stdio.h>
-
-SCA_RandomEventManager::SCA_RandomEventManager(class SCA_LogicManager* logicmgr)
- : SCA_EventManager(logicmgr, RANDOM_EVENTMGR)
-{
-}
-
-
-void SCA_RandomEventManager::NextFrame()
-{
- SG_DList::iterator<SCA_ISensor> it(m_sensors);
- for (it.begin();!it.end();++it)
- {
- (*it)->Activate(m_logicmgr);
- }
-}
-
diff --git a/source/gameengine/GameLogic/SCA_RandomEventManager.h b/source/gameengine/GameLogic/SCA_RandomEventManager.h
deleted file mode 100644
index 2d83c5fcdca..00000000000
--- a/source/gameengine/GameLogic/SCA_RandomEventManager.h
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file SCA_RandomEventManager.h
- * \ingroup gamelogic
- * \brief Manager for random events
- */
-
-#ifndef __SCA_RANDOMEVENTMANAGER_H__
-#define __SCA_RANDOMEVENTMANAGER_H__
-
-#include "SCA_EventManager.h"
-#include <vector>
-
-using namespace std;
-
-class SCA_RandomEventManager : public SCA_EventManager
-{
-public:
- SCA_RandomEventManager(class SCA_LogicManager* logicmgr);
-
- virtual void NextFrame();
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:SCA_RandomEventManager")
-#endif
-};
-
-#endif /* __SCA_RANDOMEVENTMANAGER_H__ */
diff --git a/source/gameengine/GameLogic/SCA_RandomNumberGenerator.cpp b/source/gameengine/GameLogic/SCA_RandomNumberGenerator.cpp
deleted file mode 100644
index eca678f4e89..00000000000
--- a/source/gameengine/GameLogic/SCA_RandomNumberGenerator.cpp
+++ /dev/null
@@ -1,133 +0,0 @@
-/** \file gameengine/GameLogic/SCA_RandomNumberGenerator.cpp
- * \ingroup gamelogic
- */
-/**
- * Generate random numbers that can be used by other components. We
- * convert to different types/distributions elsewhere. This just
- * delivers a clean, random bitvector.
- *
- */
-
-/* A C-program for MT19937: Real number version */
-/* genrand() generates one pseudorandom real number (double) */
-/* which is uniformly distributed on [0,1]-interval, for each */
-/* call. sgenrand(seed) set initial values to the working area */
-/* of 624 words. Before genrand(), sgenrand(seed) must be */
-/* called once. (seed is any 32-bit integer except for 0). */
-/* Integer generator is obtained by modifying two lines. */
-/* Coded by Takuji Nishimura, considering the suggestions by */
-/* Topher Cooper and Marc Rieffel in July-Aug. 1997. */
-
-/* This library is free software; you can redistribute it and/or */
-/* modify it under the terms of the GNU Library General Public */
-/* License as published by the Free Software Foundation; either */
-/* version 2 of the License, or (at your option) any later */
-/* version. */
-/* This library is distributed in the hope that it will be useful, */
-/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
-/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. */
-/* See the GNU Library General Public License for more details. */
-/* You should have received a copy of the GNU Library General */
-/* Public License along with this library; if not, write to the */
-/* Free Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA */
-/* 02110-1301, USA */
-
-/* Copyright (C) 1997 Makoto Matsumoto and Takuji Nishimura. */
-/* When you use this, send an email to: matumoto@math.keio.ac.jp */
-/* with an appropriate reference to your work. */
-
-#include <limits.h>
-#include "SCA_RandomNumberGenerator.h"
-
-/* Period parameters */
-#define N 624
-#define M 397
-#define MATRIX_A 0x9908b0df /* constant vector a */
-#define UPPER_MASK 0x80000000 /* most significant w-r bits */
-#define LOWER_MASK 0x7fffffff /* least significant r bits */
-
-/* Tempering parameters */
-#define TEMPERING_MASK_B 0x9d2c5680
-#define TEMPERING_MASK_C 0xefc60000
-#define TEMPERING_SHIFT_U(y) (y >> 11)
-#define TEMPERING_SHIFT_S(y) (y << 7)
-#define TEMPERING_SHIFT_T(y) (y << 15)
-#define TEMPERING_SHIFT_L(y) (y >> 18)
-
-SCA_RandomNumberGenerator::SCA_RandomNumberGenerator(long seed)
-{
- // int mti = N + 1; /*unused*/
- m_seed = seed;
- m_refcount = 1;
- SetStartVector();
-}
-
-SCA_RandomNumberGenerator::~SCA_RandomNumberGenerator()
-{
- /* intentionally empty */
-}
-
-void SCA_RandomNumberGenerator::SetStartVector(void)
-{
- /* setting initial seeds to mt[N] using */
- /* the generator Line 25 of Table 1 in */
- /* [KNUTH 1981, The Art of Computer Programming */
- /* Vol. 2 (2nd Ed.), pp102] */
- mt[0] = m_seed & 0xffffffff;
- for (mti = 1; mti < N; mti++)
- mt[mti] = (69069 * mt[mti-1]) & 0xffffffff;
-}
-
-long SCA_RandomNumberGenerator::GetSeed() { return m_seed; }
-void SCA_RandomNumberGenerator::SetSeed(long newseed)
-{
- m_seed = newseed;
- SetStartVector();
-}
-
-/**
- * This is the important part: copied verbatim :)
- */
-unsigned long SCA_RandomNumberGenerator::Draw()
-{
- static unsigned long mag01[2] = { 0x0, MATRIX_A };
- /* mag01[x] = x * MATRIX_A for x=0,1 */
-
- unsigned long y;
-
- if (mti >= N) { /* generate N words at one time */
- int kk;
-
- /* I set this in the constructor, so it is always satisfied ! */
- // if (mti == N+1) /* if sgenrand() has not been called, */
- // GEN_srand(4357); /* a default initial seed is used */
-
- for (kk = 0; kk < N - M; kk++) {
- y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK);
- mt[kk] = mt[kk+M] ^ (y >> 1) ^ mag01[y & 0x1];
- }
- for (; kk < N-1; kk++) {
- y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK);
- mt[kk] = mt[kk+(M-N)] ^ (y >> 1) ^ mag01[y & 0x1];
- }
- y = (mt[N-1] & UPPER_MASK) | (mt[0] & LOWER_MASK);
- mt[N-1] = mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1];
-
- mti = 0;
- }
-
- y = mt[mti++];
- y ^= TEMPERING_SHIFT_U(y);
- y ^= TEMPERING_SHIFT_S(y) & TEMPERING_MASK_B;
- y ^= TEMPERING_SHIFT_T(y) & TEMPERING_MASK_C;
- y ^= TEMPERING_SHIFT_L(y);
-
- return y;
-}
-
-float SCA_RandomNumberGenerator::DrawFloat()
-{
- return ( (float) Draw()/ (unsigned long) 0xffffffff );
-}
-
-/* eof */
diff --git a/source/gameengine/GameLogic/SCA_RandomNumberGenerator.h b/source/gameengine/GameLogic/SCA_RandomNumberGenerator.h
deleted file mode 100644
index 10818cb4e8f..00000000000
--- a/source/gameengine/GameLogic/SCA_RandomNumberGenerator.h
+++ /dev/null
@@ -1,85 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file SCA_RandomNumberGenerator.h
- * \ingroup gamelogic
- * \brief Generate random numbers that can be used by other components. Each
- * generator needs its own generator, so that the seed can be set
- * on a per-generator basis.
- */
-
-#ifndef __SCA_RANDOMNUMBERGENERATOR_H__
-#define __SCA_RANDOMNUMBERGENERATOR_H__
-
-#ifdef WITH_CXX_GUARDEDALLOC
-#include "MEM_guardedalloc.h"
-#endif
-
-class SCA_RandomNumberGenerator {
-
- /* reference counted for memleak */
- int m_refcount;
-
- /** base seed */
- long m_seed;
-
- /* A bit silly.. The N parameter is a define in the .cpp file */
- /** the array for the state vector */
- /* unsigned long mt[N]; */
- unsigned long mt[624];
-
- /** mti==N+1 means mt[KX_MT_VectorLength] is not initialized */
- int mti; /* initialized in the cpp file */
-
- /** Calculate a start vector */
- void SetStartVector(void);
- public:
- SCA_RandomNumberGenerator(long seed);
- ~SCA_RandomNumberGenerator();
- unsigned long Draw();
- float DrawFloat();
- long GetSeed();
- void SetSeed(long newseed);
- SCA_RandomNumberGenerator* AddRef()
- {
- ++m_refcount;
- return this;
- }
- void Release()
- {
- if (--m_refcount == 0)
- delete this;
- }
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:SCA_RandomNumberGenerator")
-#endif
-};
-
-#endif /* __SCA_RANDOMNUMBERGENERATOR_H__ */
-
diff --git a/source/gameengine/GameLogic/SCA_RandomSensor.cpp b/source/gameengine/GameLogic/SCA_RandomSensor.cpp
deleted file mode 100644
index 8f2dc8d80f5..00000000000
--- a/source/gameengine/GameLogic/SCA_RandomSensor.cpp
+++ /dev/null
@@ -1,187 +0,0 @@
-/*
- * Generate random pulses
- *
- *
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/GameLogic/SCA_RandomSensor.cpp
- * \ingroup gamelogic
- */
-
-
-#include <stddef.h>
-
-#include "SCA_RandomSensor.h"
-#include "SCA_EventManager.h"
-#include "SCA_RandomEventManager.h"
-#include "SCA_LogicManager.h"
-#include "EXP_ConstExpr.h"
-#include <iostream>
-
-/* ------------------------------------------------------------------------- */
-/* Native functions */
-/* ------------------------------------------------------------------------- */
-
-SCA_RandomSensor::SCA_RandomSensor(SCA_EventManager* eventmgr,
- SCA_IObject* gameobj,
- int startseed)
- : SCA_ISensor(gameobj,eventmgr)
-{
- m_basegenerator = new SCA_RandomNumberGenerator(startseed);
- Init();
-}
-
-
-
-SCA_RandomSensor::~SCA_RandomSensor()
-{
- m_basegenerator->Release();
-}
-
-void SCA_RandomSensor::Init()
-{
- m_iteration = 0;
- m_interval = 0;
- m_lastdraw = false;
- m_currentDraw = m_basegenerator->Draw();
-}
-
-
-CValue* SCA_RandomSensor::GetReplica()
-{
- CValue* replica = new SCA_RandomSensor(*this);
- // this will copy properties and so on...
- replica->ProcessReplica();
-
- return replica;
-}
-
-void SCA_RandomSensor::ProcessReplica()
-{
- SCA_ISensor::ProcessReplica();
- // increment reference count so that we can release the generator at this end
- m_basegenerator->AddRef();
-}
-
-
-bool SCA_RandomSensor::IsPositiveTrigger()
-{
- return (m_invert !=m_lastdraw);
-}
-
-
-bool SCA_RandomSensor::Evaluate()
-{
- /* Random generator is the generator from Line 25 of Table 1 in */
- /* [KNUTH 1981, The Art of Computer Programming Vol. 2 */
- /* (2nd Ed.), pp102] */
- /* It's a very simple max. length sequence generator. We can */
- /* draw 32 bool values before having to generate the next */
- /* sequence value. There are some theorems that will tell you */
- /* this is a reasonable way of generating bools. Check Knuth. */
- /* Furthermore, we only draw each <delay>-eth frame. */
-
- bool evaluateResult = false;
-
- if (++m_interval > m_skipped_ticks) {
- bool drawResult = false;
- m_interval = 0;
- if (m_iteration > 31) {
- m_currentDraw = m_basegenerator->Draw();
- drawResult = (m_currentDraw & 0x1) == 0;
- m_iteration = 1;
- } else {
- drawResult = ((m_currentDraw >> m_iteration) & 0x1) == 0;
- m_iteration++;
- }
- evaluateResult = drawResult != m_lastdraw;
- m_lastdraw = drawResult;
- }
-
- /* now pass this result to some controller */
- return evaluateResult;
-}
-
-#ifdef WITH_PYTHON
-
-/* ------------------------------------------------------------------------- */
-/* Python functions */
-/* ------------------------------------------------------------------------- */
-
-/* Integration hooks ------------------------------------------------------- */
-PyTypeObject SCA_RandomSensor::Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "SCA_RandomSensor",
- sizeof(PyObjectPlus_Proxy),
- 0,
- py_base_dealloc,
- 0,
- 0,
- 0,
- 0,
- py_base_repr,
- 0,0,0,0,0,0,0,0,0,
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
- 0,0,0,0,0,0,0,
- Methods,
- 0,
- 0,
- &SCA_ISensor::Type,
- 0,0,0,0,0,0,
- py_base_new
-};
-
-PyMethodDef SCA_RandomSensor::Methods[] = {
- {NULL,NULL} //Sentinel
-};
-
-PyAttributeDef SCA_RandomSensor::Attributes[] = {
- KX_PYATTRIBUTE_BOOL_RO("lastDraw",SCA_RandomSensor,m_lastdraw),
- KX_PYATTRIBUTE_RW_FUNCTION("seed", SCA_RandomSensor, pyattr_get_seed, pyattr_set_seed),
- {NULL} //Sentinel
-};
-
-PyObject *SCA_RandomSensor::pyattr_get_seed(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- SCA_RandomSensor* self = static_cast<SCA_RandomSensor*>(self_v);
- return PyLong_FromLong(self->m_basegenerator->GetSeed());
-}
-
-int SCA_RandomSensor::pyattr_set_seed(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- SCA_RandomSensor* self = static_cast<SCA_RandomSensor*>(self_v);
- if (!PyLong_Check(value)) {
- PyErr_SetString(PyExc_TypeError, "sensor.seed = int: Random Sensor, expected an integer");
- return PY_SET_ATTR_FAIL;
- }
- self->m_basegenerator->SetSeed(PyLong_AsLong(value));
- return PY_SET_ATTR_SUCCESS;
-}
-
-#endif // WITH_PYTHON
-
-/* eof */
diff --git a/source/gameengine/GameLogic/SCA_RandomSensor.h b/source/gameengine/GameLogic/SCA_RandomSensor.h
deleted file mode 100644
index 66107b7b74b..00000000000
--- a/source/gameengine/GameLogic/SCA_RandomSensor.h
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file SCA_RandomSensor.h
- * \ingroup gamelogic
- * \brief Generate random pulses
- */
-
-#ifndef __SCA_RANDOMSENSOR_H__
-#define __SCA_RANDOMSENSOR_H__
-
-#include "SCA_ISensor.h"
-#include "EXP_BoolValue.h"
-#include "SCA_RandomNumberGenerator.h"
-
-class SCA_RandomSensor : public SCA_ISensor
-{
- Py_Header
-
- unsigned int m_currentDraw;
- int m_iteration;
- int m_interval;
- SCA_RandomNumberGenerator *m_basegenerator;
- bool m_lastdraw;
-public:
- SCA_RandomSensor(class SCA_EventManager* rndmgr,
- SCA_IObject* gameobj,
- int startseed);
- virtual ~SCA_RandomSensor();
- virtual CValue* GetReplica();
- virtual void ProcessReplica();
- virtual bool Evaluate();
- virtual bool IsPositiveTrigger();
- virtual void Init();
-
-#ifdef WITH_PYTHON
-
- /* --------------------------------------------------------------------- */
- /* Python interface ---------------------------------------------------- */
- /* --------------------------------------------------------------------- */
-
- static PyObject* pyattr_get_seed(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_seed(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
-#endif
-};
-
-#endif /* __SCA_RANDOMSENSOR_H__ */
diff --git a/source/gameengine/GameLogic/SCA_TimeEventManager.cpp b/source/gameengine/GameLogic/SCA_TimeEventManager.cpp
deleted file mode 100644
index c56a1496823..00000000000
--- a/source/gameengine/GameLogic/SCA_TimeEventManager.cpp
+++ /dev/null
@@ -1,120 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/GameLogic/SCA_TimeEventManager.cpp
- * \ingroup gamelogic
- */
-
-#ifdef _MSC_VER
- /* This warning tells us about truncation of __long__ stl-generated names.
- * It can occasionally cause DevStudio to have internal compiler warnings. */
-# pragma warning(disable:4786)
-#endif
-
-#include "SCA_TimeEventManager.h"
-
-#include "SCA_LogicManager.h"
-#include "EXP_FloatValue.h"
-
-SCA_TimeEventManager::SCA_TimeEventManager(SCA_LogicManager* logicmgr)
-: SCA_EventManager(NULL, TIME_EVENTMGR)
-{
-}
-
-
-
-SCA_TimeEventManager::~SCA_TimeEventManager()
-{
- for (vector<CValue*>::iterator it = m_timevalues.begin();
- !(it == m_timevalues.end()); ++it)
- {
- (*it)->Release();
- }
-}
-
-
-
-void SCA_TimeEventManager::RegisterSensor(SCA_ISensor* sensor)
-{
- // not yet
-}
-
-void SCA_TimeEventManager::RemoveSensor(SCA_ISensor* sensor)
-{
- // empty
-}
-
-
-
-void SCA_TimeEventManager::NextFrame(double curtime, double fixedtime)
-{
- if (m_timevalues.size() > 0 && fixedtime > 0.0)
- {
- CFloatValue* floatval = new CFloatValue(curtime);
-
- // update sensors, but ... need deltatime !
- for (vector<CValue*>::iterator it = m_timevalues.begin();
- !(it == m_timevalues.end()); ++it)
- {
- float newtime = (*it)->GetNumber() + fixedtime;
- floatval->SetFloat(newtime);
- (*it)->SetValue(floatval);
- }
-
- floatval->Release();
- }
-}
-
-
-
-void SCA_TimeEventManager::AddTimeProperty(CValue* timeval)
-{
- timeval->AddRef();
- m_timevalues.push_back(timeval);
-}
-
-
-
-void SCA_TimeEventManager::RemoveTimeProperty(CValue* timeval)
-{
- for (vector<CValue*>::iterator it = m_timevalues.begin();
- !(it == m_timevalues.end()); ++it)
- {
- if ((*it) == timeval)
- {
- this->m_timevalues.erase(it);
- timeval->Release();
- break;
- }
- }
-}
-
-vector<CValue*> SCA_TimeEventManager::GetTimeValues()
-{
- return m_timevalues;
-}
-
diff --git a/source/gameengine/GameLogic/SCA_TimeEventManager.h b/source/gameengine/GameLogic/SCA_TimeEventManager.h
deleted file mode 100644
index 38d7e3fc4d4..00000000000
--- a/source/gameengine/GameLogic/SCA_TimeEventManager.h
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file SCA_TimeEventManager.h
- * \ingroup gamelogic
- */
-
-#ifndef __SCA_TIMEEVENTMANAGER_H__
-#define __SCA_TIMEEVENTMANAGER_H__
-
-#include "SCA_EventManager.h"
-#include "EXP_Value.h"
-#include <vector>
-
-using namespace std;
-
-class SCA_TimeEventManager : public SCA_EventManager
-{
- vector<CValue*> m_timevalues; // values that need their time updated regularly
-
-public:
- SCA_TimeEventManager(class SCA_LogicManager* logicmgr);
- virtual ~SCA_TimeEventManager();
-
- virtual void NextFrame(double curtime, double fixedtime);
- virtual void RegisterSensor(class SCA_ISensor* sensor);
- virtual void RemoveSensor(class SCA_ISensor* sensor);
- void AddTimeProperty(CValue* timeval);
- void RemoveTimeProperty(CValue* timeval);
-
- vector<CValue*> GetTimeValues();
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:SCA_TimeEventManager")
-#endif
-};
-
-#endif /* __SCA_TIMEEVENTMANAGER_H__ */
diff --git a/source/gameengine/GameLogic/SCA_XNORController.cpp b/source/gameengine/GameLogic/SCA_XNORController.cpp
deleted file mode 100644
index f97d11cabf3..00000000000
--- a/source/gameengine/GameLogic/SCA_XNORController.cpp
+++ /dev/null
@@ -1,137 +0,0 @@
-/*
- * 'Xnor' together all inputs
- *
- *
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/GameLogic/SCA_XNORController.cpp
- * \ingroup gamelogic
- */
-
-
-#include "SCA_XNORController.h"
-#include "SCA_ISensor.h"
-#include "SCA_LogicManager.h"
-#include "EXP_BoolValue.h"
-
-/* ------------------------------------------------------------------------- */
-/* Native functions */
-/* ------------------------------------------------------------------------- */
-
-SCA_XNORController::SCA_XNORController(SCA_IObject* gameobj)
- :
- SCA_IController(gameobj)
-{
-}
-
-
-
-SCA_XNORController::~SCA_XNORController()
-{
-}
-
-
-
-void SCA_XNORController::Trigger(SCA_LogicManager* logicmgr)
-{
-
- bool sensorresult = true;
-
- for (vector<SCA_ISensor*>::const_iterator is=m_linkedsensors.begin();
- !(is==m_linkedsensors.end());is++)
- {
- SCA_ISensor* sensor = *is;
- if (sensor->GetState())
- {
- if (sensorresult == false)
- {
- sensorresult = true;
- break;
- }
- sensorresult = false;
- }
- }
-
- for (vector<SCA_IActuator*>::const_iterator i=m_linkedactuators.begin();
- !(i==m_linkedactuators.end());i++)
- {
- SCA_IActuator* actua = *i;
- logicmgr->AddActiveActuator(actua,sensorresult);
- }
-}
-
-
-
-CValue* SCA_XNORController::GetReplica()
-{
- CValue* replica = new SCA_XNORController(*this);
- // this will copy properties and so on...
- replica->ProcessReplica();
-
- return replica;
-}
-
-#ifdef WITH_PYTHON
-
-/* ------------------------------------------------------------------------- */
-/* Python functions */
-/* ------------------------------------------------------------------------- */
-
-/* Integration hooks ------------------------------------------------------- */
-PyTypeObject SCA_XNORController::Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "SCA_XNORController",
- sizeof(PyObjectPlus_Proxy),
- 0,
- py_base_dealloc,
- 0,
- 0,
- 0,
- 0,
- py_base_repr,
- 0,0,0,0,0,0,0,0,0,
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
- 0,0,0,0,0,0,0,
- Methods,
- 0,
- 0,
- &SCA_IController::Type,
- 0,0,0,0,0,0,
- py_base_new
-};
-
-PyMethodDef SCA_XNORController::Methods[] = {
- {NULL,NULL} //Sentinel
-};
-
-PyAttributeDef SCA_XNORController::Attributes[] = {
- { NULL } //Sentinel
-};
-
-#endif // WITH_PYTHON
-
-/* eof */
diff --git a/source/gameengine/GameLogic/SCA_XNORController.h b/source/gameengine/GameLogic/SCA_XNORController.h
deleted file mode 100644
index c257b71273e..00000000000
--- a/source/gameengine/GameLogic/SCA_XNORController.h
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file SCA_XNORController.h
- * \ingroup gamelogic
- */
-
-#ifndef __SCA_XNORCONTROLLER_H__
-#define __SCA_XNORCONTROLLER_H__
-
-#include "SCA_IController.h"
-
-class SCA_XNORController : public SCA_IController
-{
- Py_Header
- //virtual void Trigger(class SCA_LogicManager* logicmgr);
-public:
- SCA_XNORController(SCA_IObject* gameobj);
- virtual ~SCA_XNORController();
- virtual CValue* GetReplica();
- virtual void Trigger(SCA_LogicManager* logicmgr);
-
- /* --------------------------------------------------------------------- */
- /* Python interface ---------------------------------------------------- */
- /* --------------------------------------------------------------------- */
-
-};
-
-#endif /* __SCA_XNORCONTROLLER_H__ */
diff --git a/source/gameengine/GameLogic/SCA_XORController.cpp b/source/gameengine/GameLogic/SCA_XORController.cpp
deleted file mode 100644
index bb1ea822bd8..00000000000
--- a/source/gameengine/GameLogic/SCA_XORController.cpp
+++ /dev/null
@@ -1,136 +0,0 @@
-/*
- * 'Xor' together all inputs
- *
- *
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/GameLogic/SCA_XORController.cpp
- * \ingroup gamelogic
- */
-
-
-#include "SCA_XORController.h"
-#include "SCA_ISensor.h"
-#include "SCA_LogicManager.h"
-#include "EXP_BoolValue.h"
-
-/* ------------------------------------------------------------------------- */
-/* Native functions */
-/* ------------------------------------------------------------------------- */
-
-SCA_XORController::SCA_XORController(SCA_IObject* gameobj)
- :
- SCA_IController(gameobj)
-{
-}
-
-
-
-SCA_XORController::~SCA_XORController()
-{
-}
-
-
-
-void SCA_XORController::Trigger(SCA_LogicManager* logicmgr)
-{
-
- bool sensorresult = false;
-
- for (vector<SCA_ISensor*>::const_iterator is=m_linkedsensors.begin();
- !(is==m_linkedsensors.end());is++)
- {
- SCA_ISensor* sensor = *is;
- if (sensor->GetState())
- {
- if (sensorresult == true)
- {
- sensorresult = false;
- break;
- }
- sensorresult = true;
- }
- }
-
- for (vector<SCA_IActuator*>::const_iterator i=m_linkedactuators.begin();
- !(i==m_linkedactuators.end());i++)
- {
- SCA_IActuator* actua = *i;
- logicmgr->AddActiveActuator(actua,sensorresult);
- }
-}
-
-
-
-CValue* SCA_XORController::GetReplica()
-{
- CValue* replica = new SCA_XORController(*this);
- // this will copy properties and so on...
- replica->ProcessReplica();
-
- return replica;
-}
-
-#ifdef WITH_PYTHON
-
-/* ------------------------------------------------------------------------- */
-/* Python functions */
-/* ------------------------------------------------------------------------- */
-
-/* Integration hooks ------------------------------------------------------- */
-PyTypeObject SCA_XORController::Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "SCA_XORController",
- sizeof(PyObjectPlus_Proxy),
- 0,
- py_base_dealloc,
- 0,
- 0,
- 0,
- 0,
- py_base_repr,
- 0,0,0,0,0,0,0,0,0,
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
- 0,0,0,0,0,0,0,
- Methods,
- 0,
- 0,
- &SCA_IController::Type,
- 0,0,0,0,0,0,
- py_base_new
-};
-
-PyMethodDef SCA_XORController::Methods[] = {
- {NULL,NULL} //Sentinel
-};
-
-PyAttributeDef SCA_XORController::Attributes[] = {
- { NULL } //Sentinel
-};
-#endif // WITH_PYTHON
-
-/* eof */
diff --git a/source/gameengine/GameLogic/SCA_XORController.h b/source/gameengine/GameLogic/SCA_XORController.h
deleted file mode 100644
index c64a3380ede..00000000000
--- a/source/gameengine/GameLogic/SCA_XORController.h
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file SCA_XORController.h
- * \ingroup gamelogic
- */
-
-#ifndef __SCA_XORCONTROLLER_H__
-#define __SCA_XORCONTROLLER_H__
-
-#include "SCA_IController.h"
-
-class SCA_XORController : public SCA_IController
-{
- Py_Header
- //virtual void Trigger(class SCA_LogicManager* logicmgr);
-public:
- SCA_XORController(SCA_IObject* gameobj);
- virtual ~SCA_XORController();
- virtual CValue* GetReplica();
- virtual void Trigger(SCA_LogicManager* logicmgr);
-};
-
-#endif /* __SCA_XORCONTROLLER_H__ */
diff --git a/source/gameengine/GamePlayer/CMakeLists.txt b/source/gameengine/GamePlayer/CMakeLists.txt
deleted file mode 100644
index e77609985dc..00000000000
--- a/source/gameengine/GamePlayer/CMakeLists.txt
+++ /dev/null
@@ -1,27 +0,0 @@
-# ***** BEGIN GPL LICENSE BLOCK *****
-#
-# This program is free software; you can redistribute it and/or
-# modify it under the terms of the GNU General Public License
-# as published by the Free Software Foundation; either version 2
-# of the License, or (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software Foundation,
-# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
-#
-# The Original Code is Copyright (C) 2006, Blender Foundation
-# All rights reserved.
-#
-# The Original Code is: all of this file.
-#
-# Contributor(s): Jacques Beaurain.
-#
-# ***** END GPL LICENSE BLOCK *****
-
-add_subdirectory(common)
-add_subdirectory(ghost)
diff --git a/source/gameengine/GamePlayer/common/CMakeLists.txt b/source/gameengine/GamePlayer/common/CMakeLists.txt
deleted file mode 100644
index e6c980de566..00000000000
--- a/source/gameengine/GamePlayer/common/CMakeLists.txt
+++ /dev/null
@@ -1,75 +0,0 @@
-# ***** BEGIN GPL LICENSE BLOCK *****
-#
-# This program is free software; you can redistribute it and/or
-# modify it under the terms of the GNU General Public License
-# as published by the Free Software Foundation; either version 2
-# of the License, or (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software Foundation,
-# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
-#
-# The Original Code is Copyright (C) 2006, Blender Foundation
-# All rights reserved.
-#
-# The Original Code is: all of this file.
-#
-# Contributor(s): Jacques Beaurain.
-#
-# ***** END GPL LICENSE BLOCK *****
-
-set(INC
- .
- ../ghost
- ../../BlenderRoutines
- ../../Converter
- ../../Expressions
- ../../GameLogic
- ../../Ketsji
- ../../Network
- ../../Network/LoopBackNetwork
- ../../Physics/common
- ../../Rasterizer
- ../../Rasterizer/RAS_OpenGLRasterizer
- ../../SceneGraph
- ../../../blender
- ../../../blender/blenfont
- ../../../blender/blenkernel
- ../../../blender/blenlib
- ../../../blender/blenloader
- ../../../blender/gpu
- ../../../blender/imbuf
- ../../../blender/makesdna
- ../../../../intern/container
- ../../../../intern/ghost
- ../../../../intern/glew-mx
- ../../../../intern/guardedalloc
- ../../../../intern/string
-)
-
-set(INC_SYS
- ../../../../intern/moto/include
- ${GLEW_INCLUDE_PATH}
- ${PYTHON_INCLUDE_DIRS}
- ${PNG_INCLUDE_DIRS}
- ${ZLIB_INCLUDE_DIRS}
-)
-
-set(SRC
- GPC_Canvas.cpp
- GPC_KeyboardDevice.cpp
- GPC_MouseDevice.cpp
-
- GPC_Canvas.h
- GPC_KeyboardDevice.h
- GPC_MouseDevice.h
-)
-
-add_definitions(${GL_DEFINITIONS})
-
-blender_add_lib_nolist(ge_player_common "${SRC}" "${INC}" "${INC_SYS}")
diff --git a/source/gameengine/GamePlayer/common/GPC_Canvas.cpp b/source/gameengine/GamePlayer/common/GPC_Canvas.cpp
deleted file mode 100644
index 2b355407d46..00000000000
--- a/source/gameengine/GamePlayer/common/GPC_Canvas.cpp
+++ /dev/null
@@ -1,168 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/GamePlayer/common/GPC_Canvas.cpp
- * \ingroup player
- */
-
-
-#include "RAS_IPolygonMaterial.h"
-#include "GPC_Canvas.h"
-
-#include "DNA_scene_types.h"
-#include "DNA_space_types.h"
-
-#include "BKE_image.h"
-#include "MEM_guardedalloc.h"
-
-
-GPC_Canvas::GPC_Canvas(
- int width,
- int height
-) :
- m_width(width),
- m_height(height)
-{
- // initialize area so that it's available for game logic on frame 1 (ImageViewport)
- m_displayarea.m_x1 = 0;
- m_displayarea.m_y1 = 0;
- m_displayarea.m_x2 = width;
- m_displayarea.m_y2 = height;
- m_frame = 1;
-
- glGetIntegerv(GL_VIEWPORT, (GLint*)m_viewport);
-}
-
-
-GPC_Canvas::~GPC_Canvas()
-{
-}
-
-
-void GPC_Canvas::Resize(int width, int height)
-{
- m_width = width;
- m_height = height;
-
- // initialize area so that it's available for game logic on frame 1 (ImageViewport)
- m_displayarea.m_x1 = 0;
- m_displayarea.m_y1 = 0;
- m_displayarea.m_x2 = width;
- m_displayarea.m_y2 = height;
-}
-
-
-void GPC_Canvas::ClearColor(float r, float g, float b, float a)
-{
- ::glClearColor(r,g,b,a);
-}
-
-void GPC_Canvas::SetViewPort(int x1, int y1, int x2, int y2)
-{
- /* x1 and y1 are the min pixel coordinate (e.g. 0)
- x2 and y2 are the max pixel coordinate
- the width,height is calculated including both pixels
- therefore: max - min + 1
- */
-
- /* XXX, nasty, this needs to go somewhere else,
- * but where... definitely need to clean up this
- * whole canvas/rendertools mess.
- */
- glEnable(GL_SCISSOR_TEST);
-
- m_viewport[0] = x1;
- m_viewport[1] = y1;
- m_viewport[2] = x2-x1 + 1;
- m_viewport[3] = y2-y1 + 1;
-
- glViewport(x1,y1,x2-x1 + 1,y2-y1 + 1);
- glScissor(x1,y1,x2-x1 + 1,y2-y1 + 1);
-}
-
-void GPC_Canvas::UpdateViewPort(int x1, int y1, int x2, int y2)
-{
- m_viewport[0] = x1;
- m_viewport[1] = y1;
- m_viewport[2] = x2;
- m_viewport[3] = y2;
-}
-
-const int *GPC_Canvas::GetViewPort()
-{
-#ifdef DEBUG
- // If we're in a debug build, we might as well make sure our values don't differ
- // from what the gpu thinks we have. This could lead to nasty, hard to find bugs.
- int viewport[4];
- glGetIntegerv(GL_VIEWPORT, viewport);
- assert(viewport[0] == m_viewport[0]);
- assert(viewport[1] == m_viewport[1]);
- assert(viewport[2] == m_viewport[2]);
- assert(viewport[3] == m_viewport[3]);
-#endif
-
- return m_viewport;
-}
-
-void GPC_Canvas::ClearBuffer(
- int type
-) {
-
- int ogltype = 0;
- if (type & RAS_ICanvas::COLOR_BUFFER )
- ogltype |= GL_COLOR_BUFFER_BIT;
- if (type & RAS_ICanvas::DEPTH_BUFFER )
- ogltype |= GL_DEPTH_BUFFER_BIT;
-
- ::glClear(ogltype);
-}
-
- void
-GPC_Canvas::
-MakeScreenShot(
- const char* filename
-) {
- // copy image data
- unsigned int dumpsx = GetWidth();
- unsigned int dumpsy = GetHeight();
- unsigned int *pixels = (unsigned int *)MEM_mallocN(sizeof(int) * dumpsx * dumpsy, "pixels");
-
- if (!pixels) {
- std::cout << "Cannot allocate pixels array" << std::endl;
- return;
- }
-
- glReadPixels(0, 0, dumpsx, dumpsy, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
-
- // initialize image file format data
- ImageFormatData *im_format = (ImageFormatData *)MEM_mallocN(sizeof(ImageFormatData), "im_format");
- BKE_imformat_defaults(im_format);
-
- /* save_screenshot() frees dumprect and im_format */
- save_screenshot(filename, dumpsx, dumpsy, pixels, im_format);
-}
-
diff --git a/source/gameengine/GamePlayer/common/GPC_Canvas.h b/source/gameengine/GamePlayer/common/GPC_Canvas.h
deleted file mode 100644
index 688ed8ac0f4..00000000000
--- a/source/gameengine/GamePlayer/common/GPC_Canvas.h
+++ /dev/null
@@ -1,147 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file GPC_Canvas.h
- * \ingroup player
- */
-
-#ifndef __GPC_CANVAS_H__
-#define __GPC_CANVAS_H__
-
-#include "RAS_ICanvas.h"
-#include "RAS_Rect.h"
-
-#ifdef WIN32
-# pragma warning (disable:4786) // suppress stl-MSVC debug info warning
-# include <windows.h>
-#endif /* WIN32 */
-
-#include "GPU_glew.h"
-
-#include <map>
-
-
-class GPC_Canvas : public RAS_ICanvas
-{
-protected:
-
- /** Width of the context. */
- int m_width;
- /** Height of the context. */
- int m_height;
- /** Rect that defines the area used for rendering,
- * relative to the context */
- RAS_Rect m_displayarea;
-
- int m_viewport[4];
-
-public:
-
- GPC_Canvas(int width, int height);
-
- virtual ~GPC_Canvas();
-
- void Resize(int width, int height);
-
- virtual void ResizeWindow(int width, int height) {}
-
- virtual void GetDisplayDimensions(int &width, int &height) {}
-
- /**
- * \section Methods inherited from abstract base class RAS_ICanvas.
- */
-
- int
- GetWidth(
- ) const {
- return m_width;
- }
-
- int
- GetHeight(
- ) const {
- return m_height;
- }
-
- const
- RAS_Rect &
- GetDisplayArea(
- ) const {
- return m_displayarea;
- };
-
- void
- SetDisplayArea(
- RAS_Rect *rect
- ) {
- m_displayarea= *rect;
- };
-
- RAS_Rect &
- GetWindowArea(
- ) {
- return m_displayarea;
- }
-
- void
- BeginFrame(
- ) {};
-
- /**
- * Draws overlay banners and progress bars.
- */
- void
- EndFrame(
- ) {};
-
- void SetViewPort(int x1, int y1, int x2, int y2);
- void UpdateViewPort(int x1, int y1, int x2, int y2);
- const int *GetViewPort();
-
- void ClearColor(float r, float g, float b, float a);
-
- /**
- * \section Methods inherited from abstract base class RAS_ICanvas.
- * Semantics are not yet honored.
- */
-
- void SetMouseState(RAS_MouseState mousestate)
- {
- // not yet
- }
-
- void SetMousePosition(int x, int y)
- {
- // not yet
- }
-
- virtual void MakeScreenShot(const char* filename);
-
- void ClearBuffer(int type);
-};
-
-#endif /* __GPC_CANVAS_H__ */
diff --git a/source/gameengine/GamePlayer/common/GPC_KeyboardDevice.cpp b/source/gameengine/GamePlayer/common/GPC_KeyboardDevice.cpp
deleted file mode 100644
index 0821d1d3b23..00000000000
--- a/source/gameengine/GamePlayer/common/GPC_KeyboardDevice.cpp
+++ /dev/null
@@ -1,128 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/GamePlayer/common/GPC_KeyboardDevice.cpp
- * \ingroup player
- */
-
-
-#include "GPC_KeyboardDevice.h"
-
-#include <cstdlib>
-
-/**
- * NextFrame toggles currentTable with previousTable,
- * and copies relevant event information from previous to current table
- * (pressed keys need to be remembered).
- */
-void GPC_KeyboardDevice::NextFrame()
-{
- SCA_IInputDevice::NextFrame();
-
- // Now convert justpressed key events into regular (active) keyevents
- int previousTable = 1-m_currentTable;
- for (int keyevent= KX_BEGINKEY; keyevent<= KX_ENDKEY;keyevent++)
- {
- SCA_InputEvent& oldevent = m_eventStatusTables[previousTable][keyevent];
- if (oldevent.m_status == SCA_InputEvent::KX_JUSTACTIVATED ||
- oldevent.m_status == SCA_InputEvent::KX_ACTIVE )
- {
- m_eventStatusTables[m_currentTable][keyevent] = oldevent;
- m_eventStatusTables[m_currentTable][keyevent].m_status = SCA_InputEvent::KX_ACTIVE;
- //m_eventStatusTables[m_currentTable][keyevent].m_status = SCA_InputEvent::KX_JUSTACTIVATED;
- }
- }
-}
-
-
-
-/**
- * ConvertBPEvent translates Windows keyboard events into ketsji kbd events.
- * Extra event information is stored, like ramp-mode (just released/pressed)
- */
-bool GPC_KeyboardDevice::ConvertEvent(int incode, int val, unsigned int unicode)
-{
- bool result = false;
-
- // convert event
- KX_EnumInputs kxevent = this->ToNative(incode);
-
- // only process it, if it's a key
- if (kxevent >= KX_BEGINKEY && kxevent <= KX_ENDKEY)
- {
- int previousTable = 1-m_currentTable;
-
- if (val > 0)
- {
- if (kxevent == SCA_IInputDevice::KX_ESCKEY && val != 0 && !m_hookesc)
- result = true;
-
- // todo: convert val ??
- m_eventStatusTables[m_currentTable][kxevent].m_eventval = val ; //???
- m_eventStatusTables[m_currentTable][kxevent].m_unicode = unicode ;
-
- switch (m_eventStatusTables[previousTable][kxevent].m_status)
- {
- case SCA_InputEvent::KX_JUSTACTIVATED:
- case SCA_InputEvent::KX_ACTIVE:
- {
- m_eventStatusTables[m_currentTable][kxevent].m_status = SCA_InputEvent::KX_ACTIVE;
- break;
- }
-
- case SCA_InputEvent::KX_NO_INPUTSTATUS:
- default:
- {
- m_eventStatusTables[m_currentTable][kxevent].m_status = SCA_InputEvent::KX_JUSTACTIVATED;
- }
- }
-
- } else
- {
-
- switch (m_eventStatusTables[previousTable][kxevent].m_status)
- {
- case SCA_InputEvent::KX_JUSTACTIVATED:
- case SCA_InputEvent::KX_ACTIVE:
- {
- m_eventStatusTables[m_currentTable][kxevent].m_status = SCA_InputEvent::KX_JUSTRELEASED;
- break;
- }
- default:
- {
- m_eventStatusTables[m_currentTable][kxevent].m_status = SCA_InputEvent::KX_NO_INPUTSTATUS;
- }
- }
- }
- }
- return result;
-}
-
-void GPC_KeyboardDevice::HookEscape()
-{
- m_hookesc = true;
-}
diff --git a/source/gameengine/GamePlayer/common/GPC_KeyboardDevice.h b/source/gameengine/GamePlayer/common/GPC_KeyboardDevice.h
deleted file mode 100644
index d9842a42e0a..00000000000
--- a/source/gameengine/GamePlayer/common/GPC_KeyboardDevice.h
+++ /dev/null
@@ -1,90 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file GPC_KeyboardDevice.h
- * \ingroup player
- */
-
-#ifndef __GPC_KEYBOARDDEVICE_H__
-#define __GPC_KEYBOARDDEVICE_H__
-
-#ifdef WIN32
-#pragma warning (disable:4786)
-#endif /* WIN32 */
-
-#include "SCA_IInputDevice.h"
-
-#include <map>
-
-
-/**
- * System independent implementation of SCA_IInputDevice.
- * System dependent keyboard devices need only to inherit this class
- * and fill the m_reverseKeyTranslateTable key translation map.
- * \see SCA_IInputDevice
- */
-
-class GPC_KeyboardDevice : public SCA_IInputDevice
-{
-protected:
-
- /**
- * This map converts system dependent keyboard codes into Ketsji codes.
- * System dependent keyboard codes are stored as ints.
- */
- std::map<int, KX_EnumInputs> m_reverseKeyTranslateTable;
- short m_exitkey;
-
-public:
- bool m_hookesc;
- GPC_KeyboardDevice()
- : m_hookesc(false)
- {
- }
-
- virtual ~GPC_KeyboardDevice(void)
- {
- }
-
- virtual bool IsPressed(SCA_IInputDevice::KX_EnumInputs inputcode)
- {
- return false;
- }
-
- virtual void NextFrame();
-
- virtual KX_EnumInputs ToNative(int incode)
- {
- return m_reverseKeyTranslateTable[incode];
- }
-
- virtual bool ConvertEvent(int incode, int val, unsigned int unicode);
-
- virtual void HookEscape();
-};
-
-#endif /* __GPC_KEYBOARDDEVICE_H__ */
diff --git a/source/gameengine/GamePlayer/common/GPC_MouseDevice.cpp b/source/gameengine/GamePlayer/common/GPC_MouseDevice.cpp
deleted file mode 100644
index 94045d532af..00000000000
--- a/source/gameengine/GamePlayer/common/GPC_MouseDevice.cpp
+++ /dev/null
@@ -1,214 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/GamePlayer/common/GPC_MouseDevice.cpp
- * \ingroup player
- */
-
-
-#include "GPC_MouseDevice.h"
-
-GPC_MouseDevice::GPC_MouseDevice()
-{
-
-}
-GPC_MouseDevice::~GPC_MouseDevice()
-{
-
-}
-
-/**
- * IsPressed gives boolean information about mouse status, true if pressed, false if not.
- */
-bool GPC_MouseDevice::IsPressed(SCA_IInputDevice::KX_EnumInputs inputcode)
-{
- const SCA_InputEvent & inevent = m_eventStatusTables[m_currentTable][inputcode];
- bool pressed = (inevent.m_status == SCA_InputEvent::KX_JUSTACTIVATED ||
- inevent.m_status == SCA_InputEvent::KX_ACTIVE);
- return pressed;
-}
-
-
-/**
- * NextFrame toggles currentTable with previousTable,
- * and copies relevant event information from previous to current table
- * (pressed keys need to be remembered).
- */
-void GPC_MouseDevice::NextFrame()
-{
- SCA_IInputDevice::NextFrame();
-
- // Convert just pressed events into regular (active) events
- int previousTable = 1-m_currentTable;
- for (int mouseevent= KX_BEGINMOUSE; mouseevent< KX_ENDMOUSEBUTTONS; mouseevent++) {
- SCA_InputEvent& oldevent = m_eventStatusTables[previousTable][mouseevent];
- if (oldevent.m_status == SCA_InputEvent::KX_JUSTACTIVATED ||
- oldevent.m_status == SCA_InputEvent::KX_ACTIVE)
- {
- m_eventStatusTables[m_currentTable][mouseevent] = oldevent;
- m_eventStatusTables[m_currentTable][mouseevent].m_status = SCA_InputEvent::KX_ACTIVE;
- }
- }
- for (int mousemove= KX_ENDMOUSEBUTTONS; mousemove< KX_ENDMOUSE; mousemove++) {
- SCA_InputEvent& oldevent = m_eventStatusTables[previousTable][mousemove];
- m_eventStatusTables[m_currentTable][mousemove] = oldevent;
- if (oldevent.m_status == SCA_InputEvent::KX_JUSTACTIVATED ||
- oldevent.m_status == SCA_InputEvent::KX_ACTIVE)
- {
- m_eventStatusTables[m_currentTable][mousemove].m_status = SCA_InputEvent::KX_JUSTRELEASED;
- }
- else {
- if (oldevent.m_status == SCA_InputEvent::KX_JUSTRELEASED) {
- m_eventStatusTables[m_currentTable][mousemove].m_status = SCA_InputEvent::KX_NO_INPUTSTATUS;
- }
- }
- }
-}
-
-
-bool GPC_MouseDevice::ConvertButtonEvent(TButtonId button, bool isDown)
-{
- bool result = false;
-
- switch (button)
- {
- case buttonLeft:
- result = ConvertEvent(KX_LEFTMOUSE, isDown, 0);
- break;
- case buttonMiddle:
- result = ConvertEvent(KX_MIDDLEMOUSE, isDown, 0);
- break;
- case buttonRight:
- result = ConvertEvent(KX_RIGHTMOUSE, isDown, 0);
- break;
- case buttonWheelUp:
- result = ConvertEvent(KX_WHEELUPMOUSE, isDown, 0);
- break;
- case buttonWheelDown:
- result = ConvertEvent(KX_WHEELDOWNMOUSE, isDown, 0);
- break;
- default:
- // Should not happen!
- break;
- }
-
- return result;
-}
-
-/**
- * Splits combined button and x,y cursor move events into separate Ketsji
- * x and y move and button events.
- */
-bool GPC_MouseDevice::ConvertButtonEvent(TButtonId button, bool isDown, int x, int y)
-{
- // First update state tables for cursor move.
- bool result = ConvertMoveEvent(x, y);
-
- // Now update for button state.
- if (result) {
- result = ConvertButtonEvent(button, isDown);
- }
-
- return result;
-}
-
-/**
- * Splits combined x,y move into separate Ketsji x and y move events.
- */
-bool GPC_MouseDevice::ConvertMoveEvent(int x, int y)
-{
- bool result;
-
- // Convert to local coordinates?
- result = ConvertEvent(KX_MOUSEX, x, 0);
- if (result) {
- result = ConvertEvent(KX_MOUSEY, y, 0);
- }
-
- return result;
-}
-
-
-bool GPC_MouseDevice::ConvertEvent(KX_EnumInputs kxevent, int eventval, unsigned int unicode)
-{
- bool result = true;
-
- // Only process it, if it's a mouse event
- if (kxevent > KX_BEGINMOUSE && kxevent < KX_ENDMOUSE) {
- int previousTable = 1-m_currentTable;
-
- if (eventval > 0) {
- m_eventStatusTables[m_currentTable][kxevent].m_eventval = eventval;
-
- switch (m_eventStatusTables[previousTable][kxevent].m_status)
- {
- case SCA_InputEvent::KX_ACTIVE:
- case SCA_InputEvent::KX_JUSTACTIVATED:
- {
- m_eventStatusTables[m_currentTable][kxevent].m_status = SCA_InputEvent::KX_ACTIVE;
- break;
- }
- case SCA_InputEvent::KX_JUSTRELEASED:
- {
- if ( kxevent > KX_BEGINMOUSEBUTTONS && kxevent < KX_ENDMOUSEBUTTONS)
- {
- m_eventStatusTables[m_currentTable][kxevent].m_status = SCA_InputEvent::KX_JUSTACTIVATED;
- } else
- {
- m_eventStatusTables[m_currentTable][kxevent].m_status = SCA_InputEvent::KX_ACTIVE;
-
- }
- break;
- }
- default:
- {
- m_eventStatusTables[m_currentTable][kxevent].m_status = SCA_InputEvent::KX_JUSTACTIVATED;
- }
- }
-
- }
- else {
- switch (m_eventStatusTables[previousTable][kxevent].m_status)
- {
- case SCA_InputEvent::KX_JUSTACTIVATED:
- case SCA_InputEvent::KX_ACTIVE:
- {
- m_eventStatusTables[m_currentTable][kxevent].m_status = SCA_InputEvent::KX_JUSTRELEASED;
- break;
- }
- default:
- {
- m_eventStatusTables[m_currentTable][kxevent].m_status = SCA_InputEvent::KX_NO_INPUTSTATUS;
- }
- }
- }
- }
- else {
- result = false;
- }
- return result;
-}
diff --git a/source/gameengine/GamePlayer/common/GPC_MouseDevice.h b/source/gameengine/GamePlayer/common/GPC_MouseDevice.h
deleted file mode 100644
index 24922197723..00000000000
--- a/source/gameengine/GamePlayer/common/GPC_MouseDevice.h
+++ /dev/null
@@ -1,103 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file GPC_MouseDevice.h
- * \ingroup player
- */
-
-#ifndef __GPC_MOUSEDEVICE_H__
-#define __GPC_MOUSEDEVICE_H__
-
-#ifdef WIN32
-#pragma warning (disable:4786)
-#endif /* WIN32 */
-
-#include "SCA_IInputDevice.h"
-
-
-/**
- * Generic Ketsji mouse device.
- * \see SCA_IInputDevice
- */
-class GPC_MouseDevice : public SCA_IInputDevice
-{
-public:
- /**
- * Button identifier.
- */
- typedef enum {
- buttonLeft,
- buttonMiddle,
- buttonRight,
- buttonWheelUp,
- buttonWheelDown
- } TButtonId;
-
- GPC_MouseDevice();
- virtual ~GPC_MouseDevice(void);
-
- virtual bool IsPressed(SCA_IInputDevice::KX_EnumInputs inputcode);
- virtual void NextFrame();
-
- /**
- * Call this routine to update the mouse device when a button state changes.
- * \param button Which button state changes.
- * \param isDown The new state of the button.
- * \return Indication as to whether the event was processed.
- */
- virtual bool ConvertButtonEvent(TButtonId button, bool isDown);
-
- /**
- * Call this routine to update the mouse device when a button state and
- * cursor position changes at the same time (e.g. in Win32 messages).
- * \param button Which button state changes.
- * \param isDown The new state of the button.
- * \param x Position x-coordinate of the cursor at the time of the state change.
- * \param y Position y-coordinate of the cursor at the time of the state change.
- * \return Indication as to whether the event was processed.
- */
- virtual bool ConvertButtonEvent(TButtonId button, bool isDown, int x, int y);
-
- /**
- * Call this routine to update the mouse device when the cursor has moved.
- * \param x Position x-coordinate of the cursor.
- * \param y Position y-coordinate of the cursor.
- * \return Indication as to whether the event was processed.
- */
- virtual bool ConvertMoveEvent(int x, int y);
-
-protected:
- /**
- * This routine converts a single mouse event to a Ketsji mouse event.
- * \param kxevent Ketsji event code.
- * \param eventval Value for this event.
- * \return Indication as to whether the event was processed.
- */
- virtual bool ConvertEvent(KX_EnumInputs kxevent, int eventval, unsigned int unicode);
-};
-
-#endif /* __GPC_MOUSEDEVICE_H__ */
diff --git a/source/gameengine/GamePlayer/ghost/CMakeLists.txt b/source/gameengine/GamePlayer/ghost/CMakeLists.txt
deleted file mode 100644
index 5bce9fcd248..00000000000
--- a/source/gameengine/GamePlayer/ghost/CMakeLists.txt
+++ /dev/null
@@ -1,112 +0,0 @@
-# ***** BEGIN GPL LICENSE BLOCK *****
-#
-# This program is free software; you can redistribute it and/or
-# modify it under the terms of the GNU General Public License
-# as published by the Free Software Foundation; either version 2
-# of the License, or (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software Foundation,
-# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
-#
-# The Original Code is Copyright (C) 2006, Blender Foundation
-# All rights reserved.
-#
-# The Original Code is: all of this file.
-#
-# Contributor(s): Jacques Beaurain.
-#
-# ***** END GPL LICENSE BLOCK *****
-
-set(INC
- .
- ../common
- ../../BlenderRoutines
- ../../Converter
- ../../Expressions
- ../../GameLogic
- ../../Ketsji
- ../../Network
- ../../Network/LoopBackNetwork
- ../../Physics/common
- ../../Rasterizer
- ../../Rasterizer/RAS_OpenGLRasterizer
- ../../SceneGraph
- ../../../blender
- ../../../blender/blenfont
- ../../../blender/blenkernel
- ../../../blender/blenlib
- ../../../blender/blenloader
- ../../../blender/blentranslation
- ../../../blender/depsgraph
- ../../../blender/gpu
- ../../../blender/imbuf
- ../../../blender/makesdna
- ../../../blender/makesrna
- ../../../../intern/container
- ../../../../intern/ghost
- ../../../../intern/glew-mx
- ../../../../intern/guardedalloc
- ../../../../intern/string
- ../../../../intern/memutil
-)
-
-set(INC_SYS
- ../../../../intern/moto/include
- ${GLEW_INCLUDE_PATH}
- ${PYTHON_INCLUDE_DIRS}
- ${BOOST_INCLUDE_DIR}
-)
-
-set(SRC
- GPG_Application.cpp
- GPG_Canvas.cpp
- GPG_KeyboardDevice.cpp
- GPG_System.cpp
- GPG_ghost.cpp
-
- GPG_Application.h
- GPG_Canvas.h
- GPG_KeyboardDevice.h
- GPG_System.h
-)
-
-add_definitions(${GL_DEFINITIONS})
-
-if(WIN32)
- blender_include_dirs(../../../../intern/utfconv)
-endif()
-
-if(WITH_INPUT_NDOF)
- add_definitions(-DWITH_INPUT_NDOF)
-endif(WITH_INPUT_NDOF)
-
-if(WITH_CODEC_FFMPEG)
- add_definitions(-DWITH_FFMPEG)
-endif()
-
-if(WITH_INTERNATIONAL)
- add_definitions(-DWITH_INTERNATIONAL)
-endif()
-
-if(WITH_AUDASPACE)
- add_definitions(-DWITH_AUDASPACE)
-
- list(APPEND INC_SYS
- ${AUDASPACE_C_INCLUDE_DIRS}
- )
-endif()
-
-if(WITH_SDL AND WITH_SDL_DYNLOAD)
- list(APPEND INC
- ../../../../extern/sdlew/include
- )
- add_definitions(-DWITH_SDL_DYNLOAD)
-endif()
-
-blender_add_lib_nolist(ge_player_ghost "${SRC}" "${INC}" "${INC_SYS}")
diff --git a/source/gameengine/GamePlayer/ghost/GPG_Application.cpp b/source/gameengine/GamePlayer/ghost/GPG_Application.cpp
deleted file mode 100644
index 1b6b6defdf9..00000000000
--- a/source/gameengine/GamePlayer/ghost/GPG_Application.cpp
+++ /dev/null
@@ -1,998 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- * GHOST Blender Player application implementation file.
- */
-
-/** \file gameengine/GamePlayer/ghost/GPG_Application.cpp
- * \ingroup player
- */
-
-
-#ifdef WIN32
-# pragma warning (disable:4786) // suppress stl-MSVC debug info warning
-# include <windows.h>
-#endif
-
-#include "GPU_glew.h"
-#include "GPU_extensions.h"
-#include "GPU_init_exit.h"
-
-#include "GPG_Application.h"
-#include "BL_BlenderDataConversion.h"
-
-#include <iostream>
-#include <MT_assert.h>
-#include <stdlib.h>
-
-/**********************************
- * Begin Blender include block
- **********************************/
-#ifdef __cplusplus
-extern "C"
-{
-#endif // __cplusplus
-#include "BLI_blenlib.h"
-#include "BLO_readfile.h"
-#include "BKE_global.h"
-#include "BKE_main.h"
-#include "BKE_sound.h"
-#include "IMB_imbuf.h"
-#include "DNA_scene_types.h"
-#ifdef __cplusplus
-}
-#endif // __cplusplus
-/**********************************
- * End Blender include block
- **********************************/
-
-
-#include "BL_System.h"
-#include "KX_KetsjiEngine.h"
-
-// include files needed by "KX_BlenderSceneConverter.h"
-#include "CTR_Map.h"
-#include "SCA_IActuator.h"
-#include "RAS_MeshObject.h"
-#include "RAS_OpenGLRasterizer.h"
-#include "RAS_ListRasterizer.h"
-#include "KX_PythonInit.h"
-#include "KX_PyConstraintBinding.h"
-#include "BL_Material.h" // MAXTEX
-
-#include "KX_BlenderSceneConverter.h"
-#include "NG_LoopBackNetworkDeviceInterface.h"
-
-#include "GPC_MouseDevice.h"
-#include "GPG_Canvas.h"
-#include "GPG_KeyboardDevice.h"
-#include "GPG_System.h"
-
-#include "STR_String.h"
-
-#include "GHOST_ISystem.h"
-#include "GHOST_IEvent.h"
-#include "GHOST_IEventConsumer.h"
-#include "GHOST_IWindow.h"
-#include "GHOST_Rect.h"
-
-#ifdef WITH_AUDASPACE
-# include <AUD_Device.h>
-#endif
-
-static void frameTimerProc(GHOST_ITimerTask* task, GHOST_TUns64 time);
-
-static GHOST_ISystem* fSystem = 0;
-static const int kTimerFreq = 10;
-
-GPG_Application::GPG_Application(GHOST_ISystem* system)
- : m_startSceneName(""),
- m_startScene(0),
- m_maggie(0),
- m_kxStartScene(NULL),
- m_exitRequested(0),
- m_system(system),
- m_mainWindow(0),
- m_frameTimer(0),
- m_cursor(GHOST_kStandardCursorFirstCursor),
- m_engineInitialized(0),
- m_engineRunning(0),
- m_isEmbedded(false),
- m_ketsjiengine(0),
- m_kxsystem(0),
- m_keyboard(0),
- m_mouse(0),
- m_canvas(0),
- m_rasterizer(0),
- m_sceneconverter(0),
- m_networkdevice(0),
- m_blendermat(0),
- m_blenderglslmat(0),
- m_pyGlobalDictString(0),
- m_pyGlobalDictString_Length(0)
-{
- fSystem = system;
-}
-
-
-
-GPG_Application::~GPG_Application(void)
-{
- if (m_pyGlobalDictString) {
- delete [] m_pyGlobalDictString;
- m_pyGlobalDictString = 0;
- m_pyGlobalDictString_Length = 0;
- }
-
- exitEngine();
- fSystem->disposeWindow(m_mainWindow);
-}
-
-
-
-bool GPG_Application::SetGameEngineData(struct Main* maggie, Scene *scene, GlobalSettings *gs, int argc, char **argv)
-{
- bool result = false;
-
- if (maggie != NULL && scene != NULL)
- {
-// XXX G.scene = scene;
- m_maggie = maggie;
- m_startSceneName = scene->id.name+2;
- m_startScene = scene;
- result = true;
- }
-
- /* Python needs these */
- m_argc= argc;
- m_argv= argv;
-
- /* Global Settings */
- m_globalSettings= gs;
-
- return result;
-}
-
-
-#ifdef WIN32
-#define SCR_SAVE_MOUSE_MOVE_THRESHOLD 15
-
-static HWND found_ghost_window_hwnd;
-static GHOST_IWindow* ghost_window_to_find;
-static WNDPROC ghost_wnd_proc;
-static POINT scr_save_mouse_pos;
-
-static LRESULT CALLBACK screenSaverWindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
-{
- BOOL close = false;
- switch (uMsg)
- {
- case WM_MOUSEMOVE:
- {
- POINT pt;
- GetCursorPos(&pt);
- LONG dx = scr_save_mouse_pos.x - pt.x;
- LONG dy = scr_save_mouse_pos.y - pt.y;
- if (abs(dx) > SCR_SAVE_MOUSE_MOVE_THRESHOLD
- || abs(dy) > SCR_SAVE_MOUSE_MOVE_THRESHOLD)
- {
- close = true;
- }
- scr_save_mouse_pos = pt;
- break;
- }
- case WM_LBUTTONDOWN:
- case WM_MBUTTONDOWN:
- case WM_RBUTTONDOWN:
- case WM_KEYDOWN:
- close = true;
- }
- if (close)
- PostMessage(hwnd,WM_CLOSE,0,0);
- return CallWindowProc(ghost_wnd_proc, hwnd, uMsg, wParam, lParam);
-}
-
-BOOL CALLBACK findGhostWindowHWNDProc(HWND hwnd, LPARAM lParam)
-{
- GHOST_IWindow *p = (GHOST_IWindow*) GetWindowLongPtr(hwnd, GWLP_USERDATA);
- BOOL ret = true;
- if (p == ghost_window_to_find)
- {
- found_ghost_window_hwnd = hwnd;
- ret = false;
- }
- return ret;
-}
-
-static HWND findGhostWindowHWND(GHOST_IWindow* window)
-{
- found_ghost_window_hwnd = NULL;
- ghost_window_to_find = window;
- EnumWindows(findGhostWindowHWNDProc, NULL);
- return found_ghost_window_hwnd;
-}
-
-bool GPG_Application::startScreenSaverPreview(
- HWND parentWindow,
- const bool stereoVisual,
- const int stereoMode,
- const GHOST_TUns16 samples)
-{
- bool success = false;
-
- RECT rc;
- if (GetWindowRect(parentWindow, &rc))
- {
- int windowWidth = rc.right - rc.left;
- int windowHeight = rc.bottom - rc.top;
- STR_String title = "";
- GHOST_GLSettings glSettings = {0};
-
- if (stereoVisual) {
- glSettings.flags |= GHOST_glStereoVisual;
- }
- glSettings.numOfAASamples = samples;
-
- m_mainWindow = fSystem->createWindow(title, 0, 0, windowWidth, windowHeight, GHOST_kWindowStateMinimized,
- GHOST_kDrawingContextTypeOpenGL, glSettings);
- if (!m_mainWindow) {
- printf("error: could not create main window\n");
- exit(-1);
- }
-
- HWND ghost_hwnd = findGhostWindowHWND(m_mainWindow);
- if (!ghost_hwnd) {
- printf("error: could find main window\n");
- exit(-1);
- }
-
- SetParent(ghost_hwnd, parentWindow);
- LONG_PTR style = GetWindowLongPtr(ghost_hwnd, GWL_STYLE);
- LONG_PTR exstyle = GetWindowLongPtr(ghost_hwnd, GWL_EXSTYLE);
-
- RECT adjrc = { 0, 0, windowWidth, windowHeight };
- AdjustWindowRectEx(&adjrc, style, false, exstyle);
-
- style = (style & (~(WS_POPUP|WS_OVERLAPPEDWINDOW|WS_OVERLAPPED|WS_CAPTION|WS_SYSMENU|WS_THICKFRAME|WS_MINIMIZEBOX|WS_MAXIMIZEBOX|WS_TILEDWINDOW ))) | WS_CHILD;
- SetWindowLongPtr(ghost_hwnd, GWL_STYLE, style);
- SetWindowPos(ghost_hwnd, NULL, adjrc.left, adjrc.top, 0, 0, SWP_NOZORDER|SWP_NOSIZE|SWP_NOACTIVATE);
-
- /* Check the size of the client rectangle of the window and resize the window
- * so that the client rectangle has the size requested.
- */
- m_mainWindow->setClientSize(windowWidth, windowHeight);
-
- success = initEngine(m_mainWindow, stereoMode);
- if (success) {
- success = startEngine();
- }
-
- }
- return success;
-}
-
-bool GPG_Application::startScreenSaverFullScreen(
- int width,
- int height,
- int bpp,int frequency,
- const bool stereoVisual,
- const int stereoMode,
- const GHOST_TUns16 samples)
-{
- bool ret = startFullScreen(width, height, bpp, frequency, stereoVisual, stereoMode, 0, samples);
- if (ret)
- {
- HWND ghost_hwnd = findGhostWindowHWND(m_mainWindow);
- if (ghost_hwnd != NULL)
- {
- GetCursorPos(&scr_save_mouse_pos);
- ghost_wnd_proc = (WNDPROC) GetWindowLongPtr(ghost_hwnd, GWLP_WNDPROC);
- SetWindowLongPtr(ghost_hwnd,GWLP_WNDPROC, (uintptr_t) screenSaverWindowProc);
- }
- }
- return ret;
-}
-
-#endif
-
-bool GPG_Application::startWindow(
- STR_String& title,
- int windowLeft,
- int windowTop,
- int windowWidth,
- int windowHeight,
- const bool stereoVisual,
- const int stereoMode,
- const int alphaBackground,
- const GHOST_TUns16 samples)
-{
- GHOST_GLSettings glSettings = {0};
- bool success;
- // Create the main window
- //STR_String title ("Blender Player - GHOST");
- if (stereoVisual)
- glSettings.flags |= GHOST_glStereoVisual;
- if (alphaBackground)
- glSettings.flags |= GHOST_glAlphaBackground;
- glSettings.numOfAASamples = samples;
-
- m_mainWindow = fSystem->createWindow(title, windowLeft, windowTop, windowWidth, windowHeight, GHOST_kWindowStateNormal,
- GHOST_kDrawingContextTypeOpenGL, glSettings);
- if (!m_mainWindow) {
- printf("error: could not create main window\n");
- exit(-1);
- }
-
- /* Check the size of the client rectangle of the window and resize the window
- * so that the client rectangle has the size requested.
- */
- m_mainWindow->setClientSize(windowWidth, windowHeight);
- m_mainWindow->setCursorVisibility(false);
-
- success = initEngine(m_mainWindow, stereoMode);
- if (success) {
- success = startEngine();
- }
- return success;
-}
-
-bool GPG_Application::startEmbeddedWindow(
- STR_String& title,
- const GHOST_TEmbedderWindowID parentWindow,
- const bool stereoVisual,
- const int stereoMode,
- const int alphaBackground,
- const GHOST_TUns16 samples)
-{
- GHOST_TWindowState state = GHOST_kWindowStateNormal;
- GHOST_GLSettings glSettings = {0};
-
- if (stereoVisual)
- glSettings.flags |= GHOST_glStereoVisual;
- if (alphaBackground)
- glSettings.flags |= GHOST_glAlphaBackground;
- glSettings.numOfAASamples = samples;
-
- if (parentWindow != 0)
- state = GHOST_kWindowStateEmbedded;
- m_mainWindow = fSystem->createWindow(title, 0, 0, 0, 0, state,
- GHOST_kDrawingContextTypeOpenGL, glSettings, parentWindow);
-
- if (!m_mainWindow) {
- printf("error: could not create main window\n");
- exit(-1);
- }
- m_isEmbedded = true;
-
- bool success = initEngine(m_mainWindow, stereoMode);
- if (success) {
- success = startEngine();
- }
- return success;
-}
-
-
-bool GPG_Application::startFullScreen(
- int width,
- int height,
- int bpp,int frequency,
- const bool stereoVisual,
- const int stereoMode,
- const int alphaBackground,
- const GHOST_TUns16 samples,
- bool useDesktop)
-{
- bool success;
- GHOST_TUns32 sysWidth=0, sysHeight=0;
- fSystem->getMainDisplayDimensions(sysWidth, sysHeight);
- // Create the main window
- GHOST_DisplaySetting setting;
- setting.xPixels = (useDesktop) ? sysWidth : width;
- setting.yPixels = (useDesktop) ? sysHeight : height;
- setting.bpp = bpp;
- setting.frequency = frequency;
-
- fSystem->beginFullScreen(setting, &m_mainWindow, stereoVisual, alphaBackground, samples);
- m_mainWindow->setCursorVisibility(false);
- /* note that X11 ignores this (it uses a window internally for fullscreen) */
- m_mainWindow->setState(GHOST_kWindowStateFullScreen);
-
- success = initEngine(m_mainWindow, stereoMode);
- if (success) {
- success = startEngine();
- }
- return success;
-}
-
-
-
-
-bool GPG_Application::StartGameEngine(int stereoMode)
-{
- bool success = initEngine(m_mainWindow, stereoMode);
-
- if (success)
- success = startEngine();
-
- return success;
-}
-
-
-
-void GPG_Application::StopGameEngine()
-{
- exitEngine();
-}
-
-
-
-bool GPG_Application::processEvent(GHOST_IEvent* event)
-{
- bool handled = true;
-
- switch (event->getType())
- {
- case GHOST_kEventUnknown:
- break;
-
- case GHOST_kEventButtonDown:
- handled = handleButton(event, true);
- break;
-
- case GHOST_kEventButtonUp:
- handled = handleButton(event, false);
- break;
-
- case GHOST_kEventWheel:
- handled = handleWheel(event);
- break;
-
- case GHOST_kEventCursorMove:
- handled = handleCursorMove(event);
- break;
-
- case GHOST_kEventKeyDown:
- handleKey(event, true);
- break;
-
- case GHOST_kEventKeyUp:
- handleKey(event, false);
- break;
-
-
- case GHOST_kEventWindowClose:
- case GHOST_kEventQuit:
- m_exitRequested = KX_EXIT_REQUEST_OUTSIDE;
- break;
-
- case GHOST_kEventWindowActivate:
- handled = false;
- break;
- case GHOST_kEventWindowDeactivate:
- handled = false;
- break;
-
- // The player now runs as often as it can (repsecting vsync and fixedtime).
- // This allows the player to break 100fps, but this code is being left here
- // as reference. (see EngineNextFrame)
- //case GHOST_kEventWindowUpdate:
- // {
- // GHOST_IWindow* window = event->getWindow();
- // if (!m_system->validWindow(window)) break;
- // // Update the state of the game engine
- // if (m_kxsystem && !m_exitRequested)
- // {
- // // Proceed to next frame
- // window->activateDrawingContext();
-
- // // first check if we want to exit
- // m_exitRequested = m_ketsjiengine->GetExitCode();
- //
- // // kick the engine
- // bool renderFrame = m_ketsjiengine->NextFrame();
- // if (renderFrame)
- // {
- // // render the frame
- // m_ketsjiengine->Render();
- // }
- // }
- // m_exitString = m_ketsjiengine->GetExitString();
- // }
- // break;
- //
- case GHOST_kEventWindowSize:
- {
- GHOST_IWindow* window = event->getWindow();
- if (!m_system->validWindow(window)) break;
- if (m_canvas) {
- GHOST_Rect bnds;
- window->getClientBounds(bnds);
- m_canvas->Resize(bnds.getWidth(), bnds.getHeight());
- m_ketsjiengine->Resize();
- }
- }
- break;
-
- default:
- handled = false;
- break;
- }
- return handled;
-}
-
-
-
-int GPG_Application::getExitRequested(void)
-{
- return m_exitRequested;
-}
-
-
-GlobalSettings* GPG_Application::getGlobalSettings(void)
-{
- return m_ketsjiengine->GetGlobalSettings();
-}
-
-
-
-const STR_String& GPG_Application::getExitString(void)
-{
- return m_exitString;
-}
-
-
-
-bool GPG_Application::initEngine(GHOST_IWindow* window, const int stereoMode)
-{
- if (!m_engineInitialized)
- {
- GPU_init();
-
- // get and set the preferences
- SYS_SystemHandle syshandle = SYS_GetSystem();
- if (!syshandle)
- return false;
-
- // SYS_WriteCommandLineInt(syshandle, "fixedtime", 0);
- // SYS_WriteCommandLineInt(syshandle, "vertexarrays",1);
- GameData *gm= &m_startScene->gm;
- bool properties = (SYS_GetCommandLineInt(syshandle, "show_properties", 0) != 0);
- bool profile = (SYS_GetCommandLineInt(syshandle, "show_profile", 0) != 0);
-
- bool showPhysics = (gm->flag & GAME_SHOW_PHYSICS);
- SYS_WriteCommandLineInt(syshandle, "show_physics", showPhysics);
-
- bool fixed_framerate= (SYS_GetCommandLineInt(syshandle, "fixedtime", (gm->flag & GAME_ENABLE_ALL_FRAMES)) != 0);
- bool frameRate = (SYS_GetCommandLineInt(syshandle, "show_framerate", 0) != 0);
- bool useLists = false; // (SYS_GetCommandLineInt(syshandle, "displaylists", gm->flag & GAME_DISPLAY_LISTS) != 0) && GPU_display_list_support();
- bool nodepwarnings = (SYS_GetCommandLineInt(syshandle, "ignore_deprecation_warnings", 1) != 0);
- bool restrictAnimFPS = (gm->flag & GAME_RESTRICT_ANIM_UPDATES) != 0;
-
- m_blendermat = (SYS_GetCommandLineInt(syshandle, "blender_material", 1) != 0);
- m_blenderglslmat = (SYS_GetCommandLineInt(syshandle, "blender_glsl_material", 1) != 0);
-
- // create the canvas, rasterizer and rendertools
- m_canvas = new GPG_Canvas(window);
- if (!m_canvas)
- return false;
-
- if (gm->vsync == VSYNC_ADAPTIVE)
- m_canvas->SetSwapInterval(-1);
- else
- m_canvas->SetSwapInterval((gm->vsync == VSYNC_ON) ? 1 : 0);
-
- m_canvas->Init();
- if (gm->flag & GAME_SHOW_MOUSE)
- m_canvas->SetMouseState(RAS_ICanvas::MOUSE_NORMAL);
-
- RAS_STORAGE_TYPE raster_storage = RAS_AUTO_STORAGE;
-
- if (gm->raster_storage == RAS_STORE_VBO) {
- raster_storage = RAS_VBO;
- }
- else if (gm->raster_storage == RAS_STORE_VA) {
- raster_storage = RAS_VA;
- }
- //Don't use displaylists with VBOs
- //If auto starts using VBOs, make sure to check for that here
- if (useLists && raster_storage != RAS_VBO)
- m_rasterizer = new RAS_ListRasterizer(m_canvas, true, raster_storage);
- else
- m_rasterizer = new RAS_OpenGLRasterizer(m_canvas, raster_storage);
-
- /* Stereo parameters - Eye Separation from the UI - stereomode from the command-line/UI */
- m_rasterizer->SetStereoMode((RAS_IRasterizer::StereoMode) stereoMode);
- m_rasterizer->SetEyeSeparation(m_startScene->gm.eyeseparation);
-
- if (!m_rasterizer)
- goto initFailed;
-
- m_rasterizer->PrintHardwareInfo();
-
- // create the inputdevices
- m_keyboard = new GPG_KeyboardDevice();
- if (!m_keyboard)
- goto initFailed;
-
- m_mouse = new GPC_MouseDevice();
- if (!m_mouse)
- goto initFailed;
-
- // create a networkdevice
- m_networkdevice = new NG_LoopBackNetworkDeviceInterface();
- if (!m_networkdevice)
- goto initFailed;
-
- BKE_sound_init(m_maggie);
-
- // create a ketsjisystem (only needed for timing and stuff)
- m_kxsystem = new GPG_System (m_system);
- if (!m_kxsystem)
- goto initFailed;
-
- // create the ketsjiengine
- m_ketsjiengine = new KX_KetsjiEngine(m_kxsystem);
-
- // set the devices
- m_ketsjiengine->SetKeyboardDevice(m_keyboard);
- m_ketsjiengine->SetMouseDevice(m_mouse);
- m_ketsjiengine->SetNetworkDevice(m_networkdevice);
- m_ketsjiengine->SetCanvas(m_canvas);
- m_ketsjiengine->SetRasterizer(m_rasterizer);
-
- KX_KetsjiEngine::SetExitKey(ConvertKeyCode(gm->exitkey));
-#ifdef WITH_PYTHON
- CValue::SetDeprecationWarnings(nodepwarnings);
-#else
- (void)nodepwarnings;
-#endif
-
- m_ketsjiengine->SetUseFixedTime(fixed_framerate);
- m_ketsjiengine->SetTimingDisplay(frameRate, profile, properties);
- m_ketsjiengine->SetRestrictAnimationFPS(restrictAnimFPS);
-
- //set the global settings (carried over if restart/load new files)
- m_ketsjiengine->SetGlobalSettings(m_globalSettings);
- m_ketsjiengine->SetRender(true);
-
- m_engineInitialized = true;
- }
-
- return m_engineInitialized;
-initFailed:
- BKE_sound_exit();
- delete m_kxsystem;
- delete m_networkdevice;
- delete m_mouse;
- delete m_keyboard;
- delete m_rasterizer;
- delete m_canvas;
- m_canvas = NULL;
- m_rasterizer = NULL;
- m_keyboard = NULL;
- m_mouse = NULL;
- m_networkdevice = NULL;
- m_kxsystem = NULL;
- return false;
-}
-
-
-
-bool GPG_Application::startEngine(void)
-{
- if (m_engineRunning) {
- return false;
- }
-
- // Temporary hack to disable banner display for NaN approved content.
- /*
- m_canvas->SetBannerDisplayEnabled(true);
- Camera* cam;
- cam = (Camera*)scene->camera->data;
- if (cam) {
- if (((cam->flag) & 48)==48) {
- m_canvas->SetBannerDisplayEnabled(false);
- }
- }
- else {
- showError(CString("Camera data invalid."));
- return false;
- }
- */
-
- // create a scene converter, create and convert the stratingscene
- m_sceneconverter = new KX_BlenderSceneConverter(m_maggie, m_ketsjiengine);
- if (m_sceneconverter)
- {
- STR_String m_kxStartScenename = m_startSceneName.Ptr();
- m_ketsjiengine->SetSceneConverter(m_sceneconverter);
-
- // if (always_use_expand_framing)
- // sceneconverter->SetAlwaysUseExpandFraming(true);
- if (m_blendermat)
- m_sceneconverter->SetMaterials(true);
- if (m_blenderglslmat && (m_globalSettings->matmode == GAME_MAT_GLSL))
- m_sceneconverter->SetGLSLMaterials(true);
- if (m_startScene->gm.flag & GAME_NO_MATERIAL_CACHING)
- m_sceneconverter->SetCacheMaterials(false);
-
- m_kxStartScene = new KX_Scene(m_keyboard,
- m_mouse,
- m_networkdevice,
- m_kxStartScenename,
- m_startScene,
- m_canvas);
-
-#ifdef WITH_PYTHON
- // some python things
- PyObject *gameLogic, *gameLogic_keys;
- setupGamePython(m_ketsjiengine, m_kxStartScene, m_maggie, NULL, &gameLogic, &gameLogic_keys, m_argc, m_argv);
-#endif // WITH_PYTHON
-
- //initialize Dome Settings
- if (m_startScene->gm.stereoflag == STEREO_DOME)
- m_ketsjiengine->InitDome(m_startScene->gm.dome.res, m_startScene->gm.dome.mode, m_startScene->gm.dome.angle, m_startScene->gm.dome.resbuf, m_startScene->gm.dome.tilt, m_startScene->gm.dome.warptext);
-
- // initialize 3D Audio Settings
- AUD_Device* device = BKE_sound_get_device();
- AUD_Device_setSpeedOfSound(device, m_startScene->audio.speed_of_sound);
- AUD_Device_setDopplerFactor(device, m_startScene->audio.doppler_factor);
- AUD_Device_setDistanceModel(device, AUD_DistanceModel(m_startScene->audio.distance_model));
-
-#ifdef WITH_PYTHON
- // Set the GameLogic.globalDict from marshal'd data, so we can
- // load new blend files and keep data in GameLogic.globalDict
- loadGamePythonConfig(m_pyGlobalDictString, m_pyGlobalDictString_Length);
-#endif
- m_sceneconverter->ConvertScene(
- m_kxStartScene,
- m_rasterizer,
- m_canvas);
- m_ketsjiengine->AddScene(m_kxStartScene);
-
- // Create a timer that is used to kick the engine
- if (!m_frameTimer) {
- m_frameTimer = m_system->installTimer(0, kTimerFreq, frameTimerProc, m_mainWindow);
- }
- m_rasterizer->Init();
- m_ketsjiengine->StartEngine(true);
- m_engineRunning = true;
-
- // Set the animation playback rate for ipo's and actions
- // the framerate below should patch with FPS macro defined in blendef.h
- // Could be in StartEngine set the framerate, we need the scene to do this
- Scene *scene= m_kxStartScene->GetBlenderScene(); // needed for macro
- m_ketsjiengine->SetAnimFrameRate(FPS);
- }
-
- if (!m_engineRunning)
- {
- stopEngine();
- }
-
- return m_engineRunning;
-}
-
-
-void GPG_Application::stopEngine()
-{
-#ifdef WITH_PYTHON
- // GameLogic.globalDict gets converted into a buffer, and sorted in
- // m_pyGlobalDictString so we can restore after python has stopped
- // and started between .blend file loads.
- if (m_pyGlobalDictString) {
- delete [] m_pyGlobalDictString;
- m_pyGlobalDictString = 0;
- }
-
- m_pyGlobalDictString_Length = saveGamePythonConfig(&m_pyGlobalDictString);
-#endif
-
- m_ketsjiengine->StopEngine();
- m_networkdevice->Disconnect();
-
- if (m_sceneconverter) {
- delete m_sceneconverter;
- m_sceneconverter = 0;
- }
- if (m_system && m_frameTimer) {
- m_system->removeTimer(m_frameTimer);
- m_frameTimer = 0;
- }
-
- m_engineRunning = false;
-}
-
-void GPG_Application::EngineNextFrame()
-{
- // Update the state of the game engine
- if (m_kxsystem && !m_exitRequested)
- {
- // Proceed to next frame
- if (m_mainWindow)
- m_mainWindow->activateDrawingContext();
-
- // first check if we want to exit
- m_exitRequested = m_ketsjiengine->GetExitCode();
-
- // kick the engine
- bool renderFrame = m_ketsjiengine->NextFrame();
- if (renderFrame && m_mainWindow)
- {
- // render the frame
- m_ketsjiengine->Render();
- }
- }
- m_exitString = m_ketsjiengine->GetExitString();
-}
-
-void GPG_Application::exitEngine()
-{
- // We only want to kill the engine if it has been initialized
- if (!m_engineInitialized)
- return;
-
- BKE_sound_exit();
- if (m_ketsjiengine)
- {
- stopEngine();
- delete m_ketsjiengine;
- m_ketsjiengine = 0;
- }
- if (m_kxsystem)
- {
- delete m_kxsystem;
- m_kxsystem = 0;
- }
- if (m_networkdevice)
- {
- delete m_networkdevice;
- m_networkdevice = 0;
- }
- if (m_mouse)
- {
- delete m_mouse;
- m_mouse = 0;
- }
- if (m_keyboard)
- {
- delete m_keyboard;
- m_keyboard = 0;
- }
- if (m_rasterizer)
- {
- delete m_rasterizer;
- m_rasterizer = 0;
- }
- if (m_canvas)
- {
- delete m_canvas;
- m_canvas = 0;
- }
-
- GPU_exit();
-
-#ifdef WITH_PYTHON
- // Call this after we're sure nothing needs Python anymore (e.g., destructors)
- exitGamePlayerPythonScripting();
-#endif
-
- m_exitRequested = 0;
- m_engineInitialized = false;
-}
-
-bool GPG_Application::handleWheel(GHOST_IEvent* event)
-{
- bool handled = false;
- MT_assert(event);
- if (m_mouse)
- {
- GHOST_TEventDataPtr eventData = ((GHOST_IEvent*)event)->getData();
- GHOST_TEventWheelData* wheelData = static_cast<GHOST_TEventWheelData*>(eventData);
- GPC_MouseDevice::TButtonId button;
- if (wheelData->z > 0)
- button = GPC_MouseDevice::buttonWheelUp;
- else
- button = GPC_MouseDevice::buttonWheelDown;
- m_mouse->ConvertButtonEvent(button, true);
- handled = true;
- }
- return handled;
-}
-
-bool GPG_Application::handleButton(GHOST_IEvent* event, bool isDown)
-{
- bool handled = false;
- MT_assert(event);
- if (m_mouse)
- {
- GHOST_TEventDataPtr eventData = ((GHOST_IEvent*)event)->getData();
- GHOST_TEventButtonData* buttonData = static_cast<GHOST_TEventButtonData*>(eventData);
- GPC_MouseDevice::TButtonId button;
- switch (buttonData->button)
- {
- case GHOST_kButtonMaskMiddle:
- button = GPC_MouseDevice::buttonMiddle;
- break;
- case GHOST_kButtonMaskRight:
- button = GPC_MouseDevice::buttonRight;
- break;
- case GHOST_kButtonMaskLeft:
- default:
- button = GPC_MouseDevice::buttonLeft;
- break;
- }
- m_mouse->ConvertButtonEvent(button, isDown);
- handled = true;
- }
- return handled;
-}
-
-
-bool GPG_Application::handleCursorMove(GHOST_IEvent* event)
-{
- bool handled = false;
- MT_assert(event);
- if (m_mouse && m_mainWindow)
- {
- GHOST_TEventDataPtr eventData = ((GHOST_IEvent*)event)->getData();
- GHOST_TEventCursorData* cursorData = static_cast<GHOST_TEventCursorData*>(eventData);
- GHOST_TInt32 x, y;
- m_mainWindow->screenToClient(cursorData->x, cursorData->y, x, y);
- m_mouse->ConvertMoveEvent(x, y);
- handled = true;
- }
- return handled;
-}
-
-
-bool GPG_Application::handleKey(GHOST_IEvent* event, bool isDown)
-{
- bool handled = false;
- MT_assert(event);
- if (m_keyboard)
- {
- GHOST_TEventDataPtr eventData = ((GHOST_IEvent*)event)->getData();
- GHOST_TEventKeyData* keyData = static_cast<GHOST_TEventKeyData*>(eventData);
- unsigned int unicode = keyData->utf8_buf[0] ? BLI_str_utf8_as_unicode(keyData->utf8_buf) : keyData->ascii;
-
- if (m_keyboard->ToNative(keyData->key) == KX_KetsjiEngine::GetExitKey() && !m_keyboard->m_hookesc && !m_isEmbedded) {
- m_exitRequested = KX_EXIT_REQUEST_OUTSIDE;
- }
- m_keyboard->ConvertEvent(keyData->key, isDown, unicode);
- handled = true;
- }
- return handled;
-}
-
-
-
-static void frameTimerProc(GHOST_ITimerTask* task, GHOST_TUns64 time)
-{
- GHOST_IWindow* window = (GHOST_IWindow*)task->getUserData();
- if (fSystem->validWindow(window)) {
- window->invalidate();
- }
-}
diff --git a/source/gameengine/GamePlayer/ghost/GPG_Application.h b/source/gameengine/GamePlayer/ghost/GPG_Application.h
deleted file mode 100644
index e757cc10e32..00000000000
--- a/source/gameengine/GamePlayer/ghost/GPG_Application.h
+++ /dev/null
@@ -1,181 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file GPG_Application.h
- * \ingroup player
- * \brief GHOST Blender Player application declaration file.
- */
-
-#include "GHOST_IEventConsumer.h"
-#include "STR_String.h"
-
-#ifdef WIN32
-#include <wtypes.h>
-#endif
-
-#include "KX_KetsjiEngine.h"
-
-class KX_KetsjiEngine;
-class KX_Scene;
-class KX_ISceneConverter;
-class NG_LoopBackNetworkDeviceInterface;
-class RAS_IRasterizer;
-class GHOST_IEvent;
-class GHOST_ISystem;
-class GHOST_ITimerTask;
-class GHOST_IWindow;
-class GPC_MouseDevice;
-class GPG_Canvas;
-class GPG_KeyboardDevice;
-class GPG_System;
-struct Main;
-struct Scene;
-
-class GPG_Application : public GHOST_IEventConsumer
-{
-public:
- GPG_Application(GHOST_ISystem* system);
- ~GPG_Application(void);
-
- bool SetGameEngineData(struct Main* maggie, struct Scene* scene, GlobalSettings* gs, int argc, char** argv);
- bool startWindow(STR_String& title,
- int windowLeft, int windowTop,
- int windowWidth, int windowHeight,
- const bool stereoVisual, const int stereoMode, const int alphaBackground=0, const GHOST_TUns16 samples=0);
- bool startFullScreen(int width, int height,
- int bpp, int frequency,
- const bool stereoVisual, const int stereoMode, const int alphaBackground = 0,
- const GHOST_TUns16 samples=0, bool useDesktop=false);
- bool startEmbeddedWindow(STR_String& title, const GHOST_TEmbedderWindowID parent_window,
- const bool stereoVisual, const int stereoMode, const int alphaBackground=0, const GHOST_TUns16 samples=0);
-#ifdef WIN32
- bool startScreenSaverFullScreen(int width, int height,
- int bpp, int frequency,
- const bool stereoVisual, const int stereoMode, const GHOST_TUns16 samples=0);
- bool startScreenSaverPreview(HWND parentWindow,
- const bool stereoVisual, const int stereoMode, const GHOST_TUns16 samples=0);
-#endif
-
- virtual bool processEvent(GHOST_IEvent* event);
- int getExitRequested(void);
- const STR_String& getExitString(void);
- GlobalSettings* getGlobalSettings(void);
-
- inline KX_Scene *GetStartScene() const
- {
- return m_kxStartScene;
- }
-
- bool StartGameEngine(int stereoMode);
- void StopGameEngine();
- void EngineNextFrame();
-
-protected:
- bool handleWheel(GHOST_IEvent* event);
- bool handleButton(GHOST_IEvent* event, bool isDown);
- bool handleCursorMove(GHOST_IEvent* event);
- bool handleKey(GHOST_IEvent* event, bool isDown);
-
- /**
- * Initializes the game engine.
- */
- bool initEngine(GHOST_IWindow* window, int stereoMode);
-
- /**
- * Starts the game engine.
- */
- bool startEngine(void);
-
- /**
- * Stop the game engine.
- */
- void stopEngine(void);
-
- /**
- * Shuts the game engine down.
- */
- void exitEngine(void);
- short m_exitkey;
-
- /* The game data */
- STR_String m_startSceneName;
- struct Scene* m_startScene;
- struct Main* m_maggie;
- KX_Scene *m_kxStartScene;
-
- /* Exit state. */
- int m_exitRequested;
- STR_String m_exitString;
- GlobalSettings* m_globalSettings;
-
- /* GHOST system abstraction. */
- GHOST_ISystem* m_system;
- /* Main window. */
- GHOST_IWindow* m_mainWindow;
- /* Timer to advance frames. */
- GHOST_ITimerTask* m_frameTimer;
- /* The cursor shape displayed. */
- GHOST_TStandardCursor m_cursor;
-
- /** Engine construction state. */
- bool m_engineInitialized;
- /** Engine state. */
- bool m_engineRunning;
- /** Running on embedded window */
- bool m_isEmbedded;
-
- /** the gameengine itself */
- KX_KetsjiEngine* m_ketsjiengine;
- /** The game engine's system abstraction. */
- GPG_System* m_kxsystem;
- /** The game engine's keyboard abstraction. */
- GPG_KeyboardDevice* m_keyboard;
- /** The game engine's mouse abstraction. */
- GPC_MouseDevice* m_mouse;
- /** The game engine's canvas abstraction. */
- GPG_Canvas* m_canvas;
- /** the rasterizer */
- RAS_IRasterizer* m_rasterizer;
- /** Converts Blender data files. */
- KX_ISceneConverter* m_sceneconverter;
- /** Network interface. */
- NG_LoopBackNetworkDeviceInterface* m_networkdevice;
-
- bool m_blendermat;
- bool m_blenderglslmat;
-
- /*
- * GameLogic.globalDict as a string so that loading new blend files can use the same dict.
- * Do this because python starts/stops when loading blend files.
- */
- char* m_pyGlobalDictString;
- int m_pyGlobalDictString_Length;
-
- /* argc and argv need to be passed on to python */
- int m_argc;
- char** m_argv;
-};
diff --git a/source/gameengine/GamePlayer/ghost/GPG_Canvas.cpp b/source/gameengine/GamePlayer/ghost/GPG_Canvas.cpp
deleted file mode 100644
index 09eb1691dae..00000000000
--- a/source/gameengine/GamePlayer/ghost/GPG_Canvas.cpp
+++ /dev/null
@@ -1,177 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/GamePlayer/ghost/GPG_Canvas.cpp
- * \ingroup player
- */
-
-
-#include "GPG_Canvas.h"
-#include <assert.h>
-#include "GHOST_ISystem.h"
-
-GPG_Canvas::GPG_Canvas(GHOST_IWindow* window)
-: GPC_Canvas(0, 0), m_window(window)
-{
- if (m_window)
- {
- GHOST_Rect bnds;
- m_window->getClientBounds(bnds);
- this->Resize(bnds.getWidth(), bnds.getHeight());
- }
-}
-
-
-GPG_Canvas::~GPG_Canvas(void)
-{
-}
-
-
-void GPG_Canvas::Init()
-{
- if (m_window)
- {
- m_window->setDrawingContextType(GHOST_kDrawingContextTypeOpenGL);
- assert(m_window->getDrawingContextType() == GHOST_kDrawingContextTypeOpenGL);
- }
-}
-
-void GPG_Canvas::SetMousePosition(int x, int y)
-{
- GHOST_ISystem* system = GHOST_ISystem::getSystem();
- if (system && m_window)
- {
- GHOST_TInt32 gx = (GHOST_TInt32)x;
- GHOST_TInt32 gy = (GHOST_TInt32)y;
- GHOST_TInt32 cx;
- GHOST_TInt32 cy;
- m_window->clientToScreen(gx, gy, cx, cy);
- system->setCursorPosition(cx, cy);
- }
-}
-
-
-void GPG_Canvas::SetMouseState(RAS_MouseState mousestate)
-{
- m_mousestate = mousestate;
-
- if (m_window)
- {
- switch (mousestate)
- {
- case MOUSE_INVISIBLE:
- m_window->setCursorVisibility(false);
- break;
- case MOUSE_WAIT:
- m_window->setCursorShape(GHOST_kStandardCursorWait);
- m_window->setCursorVisibility(true);
- break;
- case MOUSE_NORMAL:
- m_window->setCursorShape(GHOST_kStandardCursorDefault);
- m_window->setCursorVisibility(true);
- break;
- }
- }
-}
-
-
-void GPG_Canvas::SwapBuffers()
-{
- if (m_window)
- {
- m_window->swapBuffers();
- }
-}
-
-void GPG_Canvas::SetSwapInterval(int interval)
-{
- if (m_window)
- m_window->setSwapInterval(interval);
-}
-
-bool GPG_Canvas::GetSwapInterval(int& intervalOut)
-{
- if (m_window)
- return (bool)m_window->getSwapInterval(intervalOut);
-
- return false;
-}
-
-void GPG_Canvas::GetDisplayDimensions(int &width, int &height)
- {
- unsigned int uiwidth;
- unsigned int uiheight;
-
- GHOST_ISystem *system = GHOST_ISystem::getSystem();
- system->getMainDisplayDimensions(uiwidth, uiheight);
-
- width = uiwidth;
- height = uiheight;
-}
-
-void GPG_Canvas::ResizeWindow(int width, int height)
-{
- if (m_window->getState() == GHOST_kWindowStateFullScreen)
- {
- GHOST_ISystem* system = GHOST_ISystem::getSystem();
- GHOST_DisplaySetting setting;
- setting.xPixels = width;
- setting.yPixels = height;
- //XXX allow these to be changed or kept from previous state
- setting.bpp = 32;
- setting.frequency = 60;
-
- system->updateFullScreen(setting, &m_window);
- }
-
- m_window->setClientSize(width, height);
-
- Resize(width, height);
-}
-
-void GPG_Canvas::SetFullScreen(bool enable)
-{
- if (enable)
- m_window->setState(GHOST_kWindowStateFullScreen);
- else
- m_window->setState(GHOST_kWindowStateNormal);
-}
-
-bool GPG_Canvas::GetFullScreen()
-{
- return m_window->getState() == GHOST_kWindowStateFullScreen;
-}
-
-float GPG_Canvas::GetMouseNormalizedX(int x)
-{
- return float(x)/this->GetWidth();
-}
-
-float GPG_Canvas::GetMouseNormalizedY(int y)
-{
- return float(y)/this->GetHeight();
-}
diff --git a/source/gameengine/GamePlayer/ghost/GPG_Canvas.h b/source/gameengine/GamePlayer/ghost/GPG_Canvas.h
deleted file mode 100644
index 18afbf6cd9e..00000000000
--- a/source/gameengine/GamePlayer/ghost/GPG_Canvas.h
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file GPG_Canvas.h
- * \ingroup player
- */
-
-#ifndef __GPG_CANVAS_H__
-#define __GPG_CANVAS_H__
-
-#ifdef WIN32
-#pragma warning (disable:4786)
-#endif /* WIN32 */
-
-#include "GPC_Canvas.h"
-
-#include "GHOST_IWindow.h"
-
-
-class GPG_Canvas : public GPC_Canvas
-{
-protected:
- /** GHOST window. */
- GHOST_IWindow* m_window;
-
-public:
- GPG_Canvas(GHOST_IWindow* window);
- virtual ~GPG_Canvas(void);
-
- virtual void Init(void);
- virtual void SetMousePosition(int x, int y);
- virtual void SetMouseState(RAS_MouseState mousestate);
- virtual void SwapBuffers();
- virtual void SetSwapInterval(int interval);
- virtual bool GetSwapInterval(int& intervalOut);
-
- virtual int GetMouseX(int x) { return x; }
- virtual int GetMouseY(int y) { return y; }
- virtual float GetMouseNormalizedX(int x);
- virtual float GetMouseNormalizedY(int y);
-
- virtual void GetDisplayDimensions(int &width, int &height);
-
- virtual void ResizeWindow(int width, int height);
- virtual void SetFullScreen(bool enable);
- virtual bool GetFullScreen();
-
- bool BeginDraw() { return true; }
- void EndDraw() {};
-};
-
-#endif /* __GPG_CANVAS_H__ */
diff --git a/source/gameengine/GamePlayer/ghost/GPG_KeyboardDevice.cpp b/source/gameengine/GamePlayer/ghost/GPG_KeyboardDevice.cpp
deleted file mode 100644
index eefaa3730cf..00000000000
--- a/source/gameengine/GamePlayer/ghost/GPG_KeyboardDevice.cpp
+++ /dev/null
@@ -1,165 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- * GHOST Blender Player keyboard device implementation.
- */
-
-/** \file gameengine/GamePlayer/ghost/GPG_KeyboardDevice.cpp
- * \ingroup player
- */
-
-
-#include "GPG_KeyboardDevice.h"
-
-GPG_KeyboardDevice::GPG_KeyboardDevice(void)
-{
- m_reverseKeyTranslateTable[GHOST_kKeyA ] = KX_AKEY ;
- m_reverseKeyTranslateTable[GHOST_kKeyB ] = KX_BKEY ;
- m_reverseKeyTranslateTable[GHOST_kKeyC ] = KX_CKEY ;
- m_reverseKeyTranslateTable[GHOST_kKeyD ] = KX_DKEY ;
- m_reverseKeyTranslateTable[GHOST_kKeyE ] = KX_EKEY ;
- m_reverseKeyTranslateTable[GHOST_kKeyF ] = KX_FKEY ;
- m_reverseKeyTranslateTable[GHOST_kKeyG ] = KX_GKEY ;
- m_reverseKeyTranslateTable[GHOST_kKeyH ] = KX_HKEY ;
- m_reverseKeyTranslateTable[GHOST_kKeyI ] = KX_IKEY ;
- m_reverseKeyTranslateTable[GHOST_kKeyJ ] = KX_JKEY ;
- m_reverseKeyTranslateTable[GHOST_kKeyK ] = KX_KKEY ;
- m_reverseKeyTranslateTable[GHOST_kKeyL ] = KX_LKEY ;
- m_reverseKeyTranslateTable[GHOST_kKeyM ] = KX_MKEY ;
- m_reverseKeyTranslateTable[GHOST_kKeyN ] = KX_NKEY ;
- m_reverseKeyTranslateTable[GHOST_kKeyO ] = KX_OKEY ;
- m_reverseKeyTranslateTable[GHOST_kKeyP ] = KX_PKEY ;
- m_reverseKeyTranslateTable[GHOST_kKeyQ ] = KX_QKEY ;
- m_reverseKeyTranslateTable[GHOST_kKeyR ] = KX_RKEY ;
- m_reverseKeyTranslateTable[GHOST_kKeyS ] = KX_SKEY ;
- m_reverseKeyTranslateTable[GHOST_kKeyT ] = KX_TKEY ;
- m_reverseKeyTranslateTable[GHOST_kKeyU ] = KX_UKEY ;
- m_reverseKeyTranslateTable[GHOST_kKeyV ] = KX_VKEY ;
- m_reverseKeyTranslateTable[GHOST_kKeyW ] = KX_WKEY ;
- m_reverseKeyTranslateTable[GHOST_kKeyX ] = KX_XKEY ;
- m_reverseKeyTranslateTable[GHOST_kKeyY ] = KX_YKEY ;
- m_reverseKeyTranslateTable[GHOST_kKeyZ ] = KX_ZKEY ;
-
- m_reverseKeyTranslateTable[GHOST_kKey0 ] = KX_ZEROKEY ;
- m_reverseKeyTranslateTable[GHOST_kKey1 ] = KX_ONEKEY ;
- m_reverseKeyTranslateTable[GHOST_kKey2 ] = KX_TWOKEY ;
- m_reverseKeyTranslateTable[GHOST_kKey3 ] = KX_THREEKEY ;
- m_reverseKeyTranslateTable[GHOST_kKey4 ] = KX_FOURKEY ;
- m_reverseKeyTranslateTable[GHOST_kKey5 ] = KX_FIVEKEY ;
- m_reverseKeyTranslateTable[GHOST_kKey6 ] = KX_SIXKEY ;
- m_reverseKeyTranslateTable[GHOST_kKey7 ] = KX_SEVENKEY ;
- m_reverseKeyTranslateTable[GHOST_kKey8 ] = KX_EIGHTKEY ;
- m_reverseKeyTranslateTable[GHOST_kKey9 ] = KX_NINEKEY ;
-
- // Middle keyboard area keys
- m_reverseKeyTranslateTable[GHOST_kKeyPause ] = KX_PAUSEKEY ;
- m_reverseKeyTranslateTable[GHOST_kKeyInsert ] = KX_INSERTKEY ;
- m_reverseKeyTranslateTable[GHOST_kKeyDelete ] = KX_DELKEY ;
- m_reverseKeyTranslateTable[GHOST_kKeyHome ] = KX_HOMEKEY ;
- m_reverseKeyTranslateTable[GHOST_kKeyEnd ] = KX_ENDKEY ;
- m_reverseKeyTranslateTable[GHOST_kKeyUpPage ] = KX_PAGEUPKEY ;
- m_reverseKeyTranslateTable[GHOST_kKeyDownPage ] = KX_PAGEDOWNKEY ;
-
- // Arrow keys
- m_reverseKeyTranslateTable[GHOST_kKeyUpArrow ] = KX_UPARROWKEY ;
- m_reverseKeyTranslateTable[GHOST_kKeyDownArrow ] = KX_DOWNARROWKEY ;
- m_reverseKeyTranslateTable[GHOST_kKeyLeftArrow ] = KX_LEFTARROWKEY ;
- m_reverseKeyTranslateTable[GHOST_kKeyRightArrow ] = KX_RIGHTARROWKEY ;
-
- // Function keys
- m_reverseKeyTranslateTable[GHOST_kKeyF1 ] = KX_F1KEY ;
- m_reverseKeyTranslateTable[GHOST_kKeyF2 ] = KX_F2KEY ;
- m_reverseKeyTranslateTable[GHOST_kKeyF3 ] = KX_F3KEY ;
- m_reverseKeyTranslateTable[GHOST_kKeyF4 ] = KX_F4KEY ;
- m_reverseKeyTranslateTable[GHOST_kKeyF5 ] = KX_F5KEY ;
- m_reverseKeyTranslateTable[GHOST_kKeyF6 ] = KX_F6KEY ;
- m_reverseKeyTranslateTable[GHOST_kKeyF7 ] = KX_F7KEY ;
- m_reverseKeyTranslateTable[GHOST_kKeyF8 ] = KX_F8KEY ;
- m_reverseKeyTranslateTable[GHOST_kKeyF9 ] = KX_F9KEY ;
- m_reverseKeyTranslateTable[GHOST_kKeyF10 ] = KX_F10KEY ;
- m_reverseKeyTranslateTable[GHOST_kKeyF11 ] = KX_F11KEY ;
- m_reverseKeyTranslateTable[GHOST_kKeyF12 ] = KX_F12KEY ;
- m_reverseKeyTranslateTable[GHOST_kKeyF13 ] = KX_F13KEY ;
- m_reverseKeyTranslateTable[GHOST_kKeyF14 ] = KX_F14KEY ;
- m_reverseKeyTranslateTable[GHOST_kKeyF15 ] = KX_F15KEY ;
- m_reverseKeyTranslateTable[GHOST_kKeyF16 ] = KX_F16KEY ;
- m_reverseKeyTranslateTable[GHOST_kKeyF17 ] = KX_F17KEY ;
- m_reverseKeyTranslateTable[GHOST_kKeyF18 ] = KX_F18KEY ;
- m_reverseKeyTranslateTable[GHOST_kKeyF19 ] = KX_F19KEY ;
-
-
- // Numpad keys
- m_reverseKeyTranslateTable[GHOST_kKeyNumpad0 ] = KX_PAD0 ;
- m_reverseKeyTranslateTable[GHOST_kKeyNumpad1 ] = KX_PAD1 ;
- m_reverseKeyTranslateTable[GHOST_kKeyNumpad2 ] = KX_PAD2 ;
- m_reverseKeyTranslateTable[GHOST_kKeyNumpad3 ] = KX_PAD3 ;
- m_reverseKeyTranslateTable[GHOST_kKeyNumpad4 ] = KX_PAD4 ;
- m_reverseKeyTranslateTable[GHOST_kKeyNumpad5 ] = KX_PAD5 ;
- m_reverseKeyTranslateTable[GHOST_kKeyNumpad6 ] = KX_PAD6 ;
- m_reverseKeyTranslateTable[GHOST_kKeyNumpad7 ] = KX_PAD7 ;
- m_reverseKeyTranslateTable[GHOST_kKeyNumpad8 ] = KX_PAD8 ;
- m_reverseKeyTranslateTable[GHOST_kKeyNumpad9 ] = KX_PAD9 ;
- m_reverseKeyTranslateTable[GHOST_kKeyNumpadAsterisk ] = KX_PADASTERKEY ;
- m_reverseKeyTranslateTable[GHOST_kKeyNumpadPlus ] = KX_PADPLUSKEY ;
- m_reverseKeyTranslateTable[GHOST_kKeyNumpadPeriod ] = KX_PADPERIOD ;
- m_reverseKeyTranslateTable[GHOST_kKeyNumpadMinus ] = KX_PADMINUS ;
- m_reverseKeyTranslateTable[GHOST_kKeyNumpadSlash ] = KX_PADSLASHKEY ;
- m_reverseKeyTranslateTable[GHOST_kKeyNumpadEnter ] = KX_PADENTER ;
-
- // Other keys
- m_reverseKeyTranslateTable[GHOST_kKeyCapsLock ] = KX_CAPSLOCKKEY ;
- m_reverseKeyTranslateTable[GHOST_kKeyEsc ] = KX_ESCKEY ;
- m_reverseKeyTranslateTable[GHOST_kKeyTab ] = KX_TABKEY ;
- m_reverseKeyTranslateTable[GHOST_kKeySpace ] = KX_SPACEKEY ;
- m_reverseKeyTranslateTable[GHOST_kKeyEnter ] = KX_RETKEY ;
- m_reverseKeyTranslateTable[GHOST_kKeyBackSpace ] = KX_BACKSPACEKEY ;
- m_reverseKeyTranslateTable[GHOST_kKeySemicolon ] = KX_SEMICOLONKEY ;
- m_reverseKeyTranslateTable[GHOST_kKeyPeriod ] = KX_PERIODKEY ;
- m_reverseKeyTranslateTable[GHOST_kKeyComma ] = KX_COMMAKEY ;
- m_reverseKeyTranslateTable[GHOST_kKeyQuote ] = KX_QUOTEKEY ;
- m_reverseKeyTranslateTable[GHOST_kKeyAccentGrave ] = KX_ACCENTGRAVEKEY ;
- m_reverseKeyTranslateTable[GHOST_kKeyMinus ] = KX_MINUSKEY ;
- m_reverseKeyTranslateTable[GHOST_kKeyPlus ] = KX_PLUSKEY ;
- m_reverseKeyTranslateTable[GHOST_kKeySlash ] = KX_SLASHKEY ;
- m_reverseKeyTranslateTable[GHOST_kKeyBackslash ] = KX_BACKSLASHKEY ;
- m_reverseKeyTranslateTable[GHOST_kKeyEqual ] = KX_EQUALKEY ;
- m_reverseKeyTranslateTable[GHOST_kKeyLeftBracket ] = KX_LEFTBRACKETKEY ;
- m_reverseKeyTranslateTable[GHOST_kKeyRightBracket ] = KX_RIGHTBRACKETKEY ;
-
- m_reverseKeyTranslateTable[GHOST_kKeyOS ] = KX_OSKEY ;
-
- // Modifier keys.
- m_reverseKeyTranslateTable[GHOST_kKeyLeftControl ] = KX_LEFTCTRLKEY ;
- m_reverseKeyTranslateTable[GHOST_kKeyRightControl ] = KX_RIGHTCTRLKEY ;
- m_reverseKeyTranslateTable[GHOST_kKeyLeftAlt ] = KX_LEFTALTKEY ;
- m_reverseKeyTranslateTable[GHOST_kKeyRightAlt ] = KX_RIGHTALTKEY ;
- m_reverseKeyTranslateTable[GHOST_kKeyLeftShift ] = KX_LEFTSHIFTKEY ;
- m_reverseKeyTranslateTable[GHOST_kKeyRightShift ] = KX_RIGHTSHIFTKEY ;
-}
-
-
-GPG_KeyboardDevice::~GPG_KeyboardDevice(void)
-{
-}
diff --git a/source/gameengine/GamePlayer/ghost/GPG_KeyboardDevice.h b/source/gameengine/GamePlayer/ghost/GPG_KeyboardDevice.h
deleted file mode 100644
index ff8d56db40a..00000000000
--- a/source/gameengine/GamePlayer/ghost/GPG_KeyboardDevice.h
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file GPG_KeyboardDevice.h
- * \ingroup player
- * \brief GHOST Blender Player keyboard device.
- */
-
-#ifndef __GPG_KEYBOARDDEVICE_H__
-#define __GPG_KEYBOARDDEVICE_H__
-
-#ifdef WIN32
-#pragma warning (disable:4786)
-#endif /* WIN32 */
-
-#include "GHOST_Types.h"
-#include "GPC_KeyboardDevice.h"
-
-/**
- * GHOST implementation of GPC_KeyboardDevice.
- * The contructor fills the keyboard code translation map.
- * Base class GPC_KeyboardDevice does the rest.
- * \see SCA_IInputDevice
- */
-class GPG_KeyboardDevice : public GPC_KeyboardDevice
-{
-public:
- GPG_KeyboardDevice(void);
- virtual ~GPG_KeyboardDevice(void);
-};
-
-#endif /* __GPG_KEYBOARDDEVICE_H__ */
diff --git a/source/gameengine/GamePlayer/ghost/GPG_System.cpp b/source/gameengine/GamePlayer/ghost/GPG_System.cpp
deleted file mode 100644
index 669ab0532d9..00000000000
--- a/source/gameengine/GamePlayer/ghost/GPG_System.cpp
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- * Blender Player system on GHOST.
- */
-
-/** \file gameengine/GamePlayer/ghost/GPG_System.cpp
- * \ingroup player
- */
-
-
-#include "GPG_System.h"
-#include <assert.h>
-#include "GHOST_ISystem.h"
-
-GPG_System::GPG_System(GHOST_ISystem* system)
-: m_system(system)
-{
- assert(m_system);
-}
-
-
-double GPG_System::GetTimeInSeconds()
-{
- GHOST_TInt64 millis = (GHOST_TInt64)m_system->getMilliSeconds();
- double time = (double)millis;
- time /= 1000.0;
- return time;
-}
-
-
diff --git a/source/gameengine/GamePlayer/ghost/GPG_System.h b/source/gameengine/GamePlayer/ghost/GPG_System.h
deleted file mode 100644
index 1ec7a06d1cf..00000000000
--- a/source/gameengine/GamePlayer/ghost/GPG_System.h
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file GPG_System.h
- * \ingroup player
- * \brief Blender Player system on GHOST.
- */
-
-#ifndef __GPG_SYSTEM_H__
-#define __GPG_SYSTEM_H__
-
-#ifdef WIN32
-#pragma warning (disable:4786) // suppress stl-MSVC debug info warning
-#endif /* WIN32 */
-
-#include "KX_ISystem.h"
-
-class GHOST_ISystem;
-
-class GPG_System : public KX_ISystem
-{
- GHOST_ISystem* m_system;
-
-public:
- GPG_System(GHOST_ISystem* system);
-
- virtual double GetTimeInSeconds();
-};
-
-#endif /* __GPG_SYSTEM_H__ */
diff --git a/source/gameengine/GamePlayer/ghost/GPG_ghost.cpp b/source/gameengine/GamePlayer/ghost/GPG_ghost.cpp
deleted file mode 100644
index 998058193bb..00000000000
--- a/source/gameengine/GamePlayer/ghost/GPG_ghost.cpp
+++ /dev/null
@@ -1,1228 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- * Start up of the Blender Player on GHOST.
- */
-
-/** \file gameengine/GamePlayer/ghost/GPG_ghost.cpp
- * \ingroup player
- */
-
-
-#include <iostream>
-#include <math.h>
-
-#ifdef __linux__
-#ifdef __alpha__
-#include <signal.h>
-#endif /* __alpha__ */
-#endif /* __linux__ */
-
-#include "KX_KetsjiEngine.h"
-#include "KX_PythonInit.h"
-#include "KX_PythonMain.h"
-#include "KX_PyConstraintBinding.h" // for PHY_SetActiveEnvironment
-
-/**********************************
- * Begin Blender include block
- **********************************/
-#ifdef __cplusplus
-extern "C"
-{
-#endif // __cplusplus
-#include "MEM_guardedalloc.h"
-#include "MEM_CacheLimiterC-Api.h"
-
-#include "BLI_threads.h"
-#include "BLI_mempool.h"
-#include "BLI_blenlib.h"
-
-#include "DNA_scene_types.h"
-#include "DNA_userdef_types.h"
-#include "DNA_genfile.h"
-
-#include "BLO_readfile.h"
-#include "BLO_runtime.h"
-
-#include "BKE_appdir.h"
-#include "BKE_blender.h"
-#include "BKE_global.h"
-#include "BKE_icons.h"
-#include "BKE_image.h"
-#include "BKE_node.h"
-#include "BKE_report.h"
-#include "BKE_library.h"
-#include "BKE_library_remap.h"
-#include "BKE_modifier.h"
-#include "BKE_material.h"
-#include "BKE_text.h"
-#include "BKE_sound.h"
-
-#include "DEG_depsgraph.h"
-
-#include "IMB_imbuf.h"
-#include "IMB_moviecache.h"
-
-#ifdef __APPLE__
- int GHOST_HACK_getFirstFile(char buf[]);
-#endif
-
-// For BLF
-#include "BLF_api.h"
-#include "BLT_translation.h"
-#include "BLT_lang.h"
-extern int datatoc_bfont_ttf_size;
-extern char datatoc_bfont_ttf[];
-extern int datatoc_bmonofont_ttf_size;
-extern char datatoc_bmonofont_ttf[];
-
-#ifdef __cplusplus
-}
-#endif // __cplusplus
-
-#include "GPU_draw.h"
-
-/**********************************
- * End Blender include block
- **********************************/
-
-#include "BL_System.h"
-#include "GPG_Application.h"
-
-#include "GHOST_ISystem.h"
-#include "RAS_IRasterizer.h"
-
-#include "BKE_main.h"
-
-#include "RNA_define.h"
-
-#ifdef WIN32
-# include <windows.h>
-# if !defined(DEBUG)
-# include <wincon.h>
-# endif // !defined(DEBUG)
-# if defined(_MSC_VER) && defined(_M_X64)
-# include <math.h> /* needed for _set_FMA3_enable */
-# endif
-# include "utfconv.h"
-#endif // WIN32
-
-#ifdef WITH_SDL_DYNLOAD
-# include "sdlew.h"
-#endif
-
-const int kMinWindowWidth = 100;
-const int kMinWindowHeight = 100;
-
-static void mem_error_cb(const char *errorStr)
-{
- fprintf(stderr, "%s", errorStr);
- fflush(stderr);
-}
-
-// library.c will only free window managers with a callback function.
-// We don't actually use a wmWindowManager, but loading a blendfile
-// loads wmWindows, so we need to free those.
-static void wm_free(bContext *C, wmWindowManager *wm)
-{
- BLI_freelistN(&wm->windows);
-}
-
-#ifdef WIN32
-typedef enum {
- SCREEN_SAVER_MODE_NONE = 0,
- SCREEN_SAVER_MODE_PREVIEW,
- SCREEN_SAVER_MODE_SAVER,
- SCREEN_SAVER_MODE_CONFIGURATION,
- SCREEN_SAVER_MODE_PASSWORD,
-} ScreenSaverMode;
-
-static ScreenSaverMode scr_saver_mode = SCREEN_SAVER_MODE_NONE;
-static HWND scr_saver_hwnd = NULL;
-
-static BOOL scr_saver_init(int argc, char **argv)
-{
- scr_saver_mode = SCREEN_SAVER_MODE_NONE;
- scr_saver_hwnd = NULL;
- BOOL ret = false;
-
- int len = ::strlen(argv[0]);
- if (len > 4 && !::stricmp(".scr", argv[0] + len - 4))
- {
- scr_saver_mode = SCREEN_SAVER_MODE_CONFIGURATION;
- ret = true;
- if (argc >= 2)
- {
- if (argc >= 3)
- {
- scr_saver_hwnd = (HWND) ::atoi(argv[2]);
- }
- if (!::stricmp("/c", argv[1]))
- {
- scr_saver_mode = SCREEN_SAVER_MODE_CONFIGURATION;
- if (scr_saver_hwnd == NULL)
- scr_saver_hwnd = ::GetForegroundWindow();
- }
- else if (!::stricmp("/s", argv[1]))
- {
- scr_saver_mode = SCREEN_SAVER_MODE_SAVER;
- }
- else if (!::stricmp("/a", argv[1]))
- {
- scr_saver_mode = SCREEN_SAVER_MODE_PASSWORD;
- }
- else if (!::stricmp("/p", argv[1])
- || !::stricmp("/l", argv[1]))
- {
- scr_saver_mode = SCREEN_SAVER_MODE_PREVIEW;
- }
- }
- }
- return ret;
-}
-
-#endif /* WIN32 */
-
-static void usage(const char* program, bool isBlenderPlayer)
-{
- const char * consoleoption;
- const char * example_filename = "";
- const char * example_pathname = "";
-
-#ifdef _WIN32
- consoleoption = "[-c] ";
-#else
- consoleoption = "";
-#endif
-
- if (isBlenderPlayer) {
- example_filename = "filename.blend";
-#ifdef _WIN32
- example_pathname = "c:\\";
-#else
- example_pathname = "/home/user/";
-#endif
- }
- printf("\n");
- printf("usage: %s [--options] %s\n\n", program, example_filename);
- printf("Available options are: [-w [w h l t]] [-f [fw fh fb ff]] %s[-g gamengineoptions] ", consoleoption);
- printf("[-s stereomode] [-m aasamples]\n");
- printf("Optional parameters must be passed in order.\n");
- printf("Default values are set in the blend file.\n\n");
- printf(" -h: Prints this command summary\n\n");
- printf(" -w: display in a window\n");
- printf(" --Optional parameters--\n");
- printf(" w = window width\n");
- printf(" h = window height\n");
- printf(" l = window left coordinate\n");
- printf(" t = window top coordinate\n");
- printf(" Note: To define 'w' or 'h', both must be used.");
- printf("Also, to define 'l' or 't', all four parameters must be used.\n");
- printf(" Example: -w or -w 500 300 or -w 500 300 0 0\n\n");
- printf(" -f: start game in fullscreen mode\n");
- printf(" --Optional parameters--\n");
- printf(" fw = fullscreen mode pixel width (use 0 to detect automatically)\n");
- printf(" fh = fullscreen mode pixel height (use 0 to detect automatically)\n");
- printf(" fb = fullscreen mode bits per pixel (default unless set in the blend file: 32)\n");
- printf(" ff = fullscreen mode frequency (default unless set in the blend file: 60)\n");
- printf(" Note: To define 'fw'' or 'fh'', both must be used.\n");
- printf(" Example: -f or -f 1024 768 or -f 0 0 16 or -f 1024 728 16 30\n\n");
- printf(" -s: start player in stereoscopy mode (requires 3D capable hardware)\n");
- printf(" stereomode: nostereo (default unless stereo is set in the blend file)\n");
- printf(" anaglyph (Red-Blue glasses)\n");
- printf(" sidebyside (Left Right)\n");
- printf(" syncdoubling (Above Below)\n");
- printf(" 3dtvtopbottom (Squashed Top-Bottom for passive glasses)\n");
- printf(" interlace (Interlace horizontally)\n");
- printf(" vinterlace (Vertical interlace for autostereo display)\n");
- printf(" hwpageflip (Quad buffered shutter glasses)\n");
- printf(" Example: -s sidebyside or -s vinterlace\n\n");
- printf(" -D: start player in dome mode\n");
- printf(" --Optional parameters--\n");
- printf(" angle = field of view in degrees\n");
- printf(" tilt = tilt angle in degrees\n");
- printf(" warpdata = a file to use for warping the image (absolute path)\n");
- printf(" mode: fisheye (Fisheye)\n");
- printf(" truncatedfront (Front-Truncated)\n");
- printf(" truncatedrear (Rear-Truncated)\n");
- printf(" cubemap (Cube Map)\n");
- printf(" sphericalpanoramic (Spherical Panoramic)\n");
- printf(" Example: -D or -D mode cubemap\n\n");
- printf(" -m: maximum anti-aliasing (eg. 2,4,8,16)\n\n");
- printf(" -i: parent window's ID\n\n");
-#ifdef _WIN32
- printf(" -c: keep console window open\n\n");
-#endif
- printf(" -d: turn debugging on\n\n");
- printf(" -g: game engine options:\n\n");
- printf(" Name Default Description\n");
- printf(" ------------------------------------------------------------------------\n");
- printf(" fixedtime 0 \"Enable all frames\"\n");
- printf(" nomipmap 0 Disable mipmaps\n");
- printf(" show_framerate 0 Show the frame rate\n");
- printf(" show_properties 0 Show debug properties\n");
- printf(" show_profile 0 Show profiling information\n");
- printf(" blender_material 0 Enable material settings\n");
- printf(" ignore_deprecation_warnings 1 Ignore deprecation warnings\n");
- printf("\n");
- printf(" - : all arguments after this are ignored, allowing python to access them from sys.argv\n");
- printf("\n");
- printf("example: %s -w 320 200 10 10 -g noaudio %s%s\n", program, example_pathname, example_filename);
- printf("example: %s -g show_framerate = 0 %s%s\n", program, example_pathname, example_filename);
- printf("example: %s -i 232421 -m 16 %s%s\n\n", program, example_pathname, example_filename);
-}
-
-static void get_filename(int argc, char **argv, char *filename)
-{
-#ifdef __APPLE__
- /* On Mac we park the game file (called game.blend) in the application bundle.
- * The executable is located in the bundle as well.
- * Therefore, we can locate the game relative to the executable.
- */
- int srclen = ::strlen(argv[0]);
- int len = 0;
- char *gamefile = NULL;
-
- filename[0] = '\0';
-
- if (argc > 1) {
- if (BLI_exists(argv[argc-1])) {
- BLI_strncpy(filename, argv[argc-1], FILE_MAX);
- }
- if (::strncmp(argv[argc-1], "-psn_", 5)==0) {
- static char firstfilebuf[512];
- if (GHOST_HACK_getFirstFile(firstfilebuf)) {
- BLI_strncpy(filename, firstfilebuf, FILE_MAX);
- }
- }
- }
-
- srclen -= ::strlen("MacOS/blenderplayer");
- if (srclen > 0) {
- len = srclen + ::strlen("Resources/game.blend");
- gamefile = new char [len + 1];
- ::strcpy(gamefile, argv[0]);
- ::strcpy(gamefile + srclen, "Resources/game.blend");
- //::printf("looking for file: %s\n", filename);
-
- if (BLI_exists(gamefile))
- BLI_strncpy(filename, gamefile, FILE_MAX);
-
- delete [] gamefile;
- }
-
-#else
- filename[0] = '\0';
-
- if (argc > 1)
- BLI_strncpy(filename, argv[argc-1], FILE_MAX);
-#endif // !_APPLE
-}
-
-static BlendFileData *load_game_data(const char *progname, char *filename = NULL, char *relativename = NULL)
-{
- ReportList reports;
- BlendFileData *bfd = NULL;
-
- BKE_reports_init(&reports, RPT_STORE);
-
- /* try to load ourself, will only work if we are a runtime */
- if (BLO_is_a_runtime(progname)) {
- bfd= BLO_read_runtime(progname, &reports);
- if (bfd) {
- bfd->type= BLENFILETYPE_RUNTIME;
- BLI_strncpy(bfd->main->name, progname, sizeof(bfd->main->name));
- }
- } else {
- bfd= BLO_read_from_file(progname, &reports, BLO_READ_SKIP_NONE);
- }
-
- if (!bfd && filename) {
- bfd = load_game_data(filename);
- if (!bfd) {
- printf("Loading %s failed: ", filename);
- BKE_reports_print(&reports, RPT_ERROR);
- }
- }
-
- BKE_reports_clear(&reports);
-
- return bfd;
-}
-
-static bool GPG_NextFrame(GHOST_ISystem* system, GPG_Application *app, int &exitcode, STR_String &exitstring, GlobalSettings *gs)
-{
- bool run = true;
- system->processEvents(false);
- system->dispatchEvents();
- app->EngineNextFrame();
- if ((exitcode = app->getExitRequested())) {
- run = false;
- exitstring = app->getExitString();
- *gs = *app->getGlobalSettings();
- }
- return run;
-}
-
-struct GPG_NextFrameState {
- GHOST_ISystem* system;
- GPG_Application *app;
- GlobalSettings *gs;
-} gpg_nextframestate;
-
-static int GPG_PyNextFrame(void *state0)
-{
- GPG_NextFrameState *state = (GPG_NextFrameState *) state0;
- int exitcode;
- STR_String exitstring;
- bool run = GPG_NextFrame(state->system, state->app, exitcode, exitstring, state->gs);
- if (run) return 0;
- else {
- if (exitcode)
- fprintf(stderr, "Exit code %d: %s\n", exitcode, exitstring.ReadPtr());
- return 1;
- }
-}
-
-int main(
- int argc,
-#ifdef WIN32
- char **UNUSED(argv_c)
-#else
- char **argv
-#endif
- )
-{
- int i;
- int argc_py_clamped= argc; /* use this so python args can be added after ' - ' */
- bool error = false;
- SYS_SystemHandle syshandle = SYS_GetSystem();
- bool fullScreen = false;
- bool fullScreenParFound = false;
- bool windowParFound = false;
-#ifdef WIN32
- bool closeConsole = true;
-#endif
- RAS_IRasterizer::StereoMode stereomode = RAS_IRasterizer::RAS_STEREO_NOSTEREO;
- bool stereoWindow = false;
- bool stereoParFound = false;
- int stereoFlag = STEREO_NOSTEREO;
- int domeFov = -1;
- int domeTilt = -200;
- int domeMode = 0;
- char* domeWarp = NULL;
- Text *domeText = NULL;
- int windowLeft = 100;
- int windowTop = 100;
- int windowWidth = 640;
- int windowHeight = 480;
- GHOST_TUns32 fullScreenWidth = 0;
- GHOST_TUns32 fullScreenHeight= 0;
- int fullScreenBpp = 32;
- int fullScreenFrequency = 60;
- GHOST_TEmbedderWindowID parentWindow = 0;
- bool isBlenderPlayer = false; //true when lauching from blender or command line. false for bundled player
- int validArguments=0;
- bool samplesParFound = false;
- GHOST_TUns16 aasamples = 0;
- int alphaBackground = 0;
-
-#ifdef WIN32
- char **argv;
- int argv_num;
-
- /* We delay loading of openmp so we can set the policy here. */
-# if defined(_MSC_VER)
- _putenv_s("OMP_WAIT_POLICY", "PASSIVE");
-# endif
-
- /* FMA3 support in the 2013 CRT is broken on Vista and Windows 7 RTM (fixed in SP1). Just disable it. */
-# if defined(_MSC_VER) && defined(_M_X64)
- _set_FMA3_enable(0);
-# endif
-
- /* Win32 Unicode Args */
- /* NOTE: cannot use guardedalloc malloc here, as it's not yet initialized
- * (it depends on the args passed in, which is what we're getting here!)
- */
- {
- wchar_t **argv_16 = CommandLineToArgvW(GetCommandLineW(), &argc);
- argv = (char**)malloc(argc * sizeof(char *));
- for (argv_num = 0; argv_num < argc; argv_num++) {
- argv[argv_num] = alloc_utf_8_from_16(argv_16[argv_num], 0);
- }
- LocalFree(argv_16);
- }
-#endif /* WIN32 */
-
-#ifdef __linux__
-#ifdef __alpha__
- signal (SIGFPE, SIG_IGN);
-#endif /* __alpha__ */
-#endif /* __linux__ */
-
-#ifdef WITH_SDL_DYNLOAD
- sdlewInit();
-#endif
-
- BKE_appdir_program_path_init(argv[0]);
- BKE_tempdir_init(NULL);
-
- // We don't use threads directly in the BGE, but we need to call this so things like
- // freeing up GPU_Textures works correctly.
- BLI_threadapi_init();
-
- DNA_sdna_current_init();
-
- RNA_init();
-
- init_nodesystem();
-
- BKE_blender_globals_init();
-
- // We load our own G.main, so free the one that BKE_blender_globals_init() gives us
- BKE_main_free(G.main);
- G.main = NULL;
-
- MEM_CacheLimiter_set_disabled(true);
- IMB_init();
- BKE_images_init();
- BKE_modifier_init();
- DEG_register_node_types();
-
-#ifdef WITH_FFMPEG
- IMB_ffmpeg_init();
-#endif
-
- // Setup builtin font for BLF (mostly copied from creator.c, wm_init_exit.c and interface_style.c)
- BLF_init();
- BLT_lang_init();
- BLT_lang_set("");
-
- BLF_load_mem("default", (unsigned char*)datatoc_bfont_ttf, datatoc_bfont_ttf_size);
- if (blf_mono_font == -1)
- blf_mono_font = BLF_load_mem_unique("monospace", (unsigned char*)datatoc_bmonofont_ttf, datatoc_bmonofont_ttf_size);
-
- // Parse command line options
-#if defined(DEBUG)
- printf("argv[0] = '%s'\n", argv[0]);
-#endif
-
-#ifdef WIN32
- if (scr_saver_init(argc, argv))
- {
- switch (scr_saver_mode)
- {
- case SCREEN_SAVER_MODE_CONFIGURATION:
- MessageBox(scr_saver_hwnd, "This screen saver has no options that you can set", "Screen Saver", MB_OK);
- break;
- case SCREEN_SAVER_MODE_PASSWORD:
- /* This is W95 only, which we currently do not support.
- * Fall-back to normal screen saver behavior in that case... */
- case SCREEN_SAVER_MODE_SAVER:
- fullScreen = true;
- fullScreenParFound = true;
- break;
-
- case SCREEN_SAVER_MODE_PREVIEW:
- /* This will actually be handled somewhere below... */
- break;
- }
- }
-#endif
- // XXX add the ability to change this values to the command line parsing.
- U.mixbufsize = 2048;
- U.audiodevice = 2;
- U.audiorate = 44100;
- U.audioformat = 0x24;
- U.audiochannels = 2;
-
- // XXX this one too
- U.anisotropic_filter = 2;
- // enable fast mipmap generation
- U.use_gpu_mipmap = 1;
-
- BKE_sound_init_once();
-
- // Initialize a default material for meshes without materials.
- init_def_material();
-
- BKE_library_callback_free_window_manager_set(wm_free);
-
- /* if running blenderplayer the last argument can't be parsed since it has to be the filename. else it is bundled */
- isBlenderPlayer = !BLO_is_a_runtime(argv[0]);
- if (isBlenderPlayer)
- validArguments = argc - 1;
- else
- validArguments = argc;
-
-
- /* Parsing command line arguments (can be set from WM_OT_blenderplayer_start) */
-#if defined(DEBUG)
- printf("Parsing command line arguments...\n");
- printf("Num of arguments is: %i\n", validArguments-1); //-1 because i starts at 1
-#endif
-
- for (i = 1; (i < validArguments) && !error
-#ifdef WIN32
- && scr_saver_mode == SCREEN_SAVER_MODE_NONE
-#endif
- ;)
-
- {
-#if defined(DEBUG)
- printf("argv[%d] = '%s'\n", i, argv[i]);
-#endif
- if (argv[i][0] == '-')
- {
- /* ignore all args after " - ", allow python to have own args */
- if (argv[i][1]=='\0') {
- argc_py_clamped= i;
- break;
- }
-
- switch (argv[i][1])
- {
- case 'g': //game engine options (show_framerate, fixedtime, etc)
- {
- i++;
- if (i <= validArguments)
- {
- char* paramname = argv[i];
- // Check for single value versus assignment
- if (i+1 <= validArguments && (*(argv[i+1]) == '='))
- {
- i++;
- if (i + 1 <= validArguments)
- {
- i++;
- // Assignment
- SYS_WriteCommandLineInt(syshandle, paramname, atoi(argv[i]));
- SYS_WriteCommandLineFloat(syshandle, paramname, atof(argv[i]));
- SYS_WriteCommandLineString(syshandle, paramname, argv[i]);
-#if defined(DEBUG)
- printf("%s = '%s'\n", paramname, argv[i]);
-#endif
- i++;
- }
- else
- {
- error = true;
- printf("error: argument assignment %s without value.\n", paramname);
- }
- }
- else
- {
-// SYS_WriteCommandLineInt(syshandle, argv[i++], 1);
- }
- }
- break;
- }
- case 'd': //debug on
- {
- i++;
- G.debug |= G_DEBUG;
- MEM_set_memory_debug();
-#ifndef NDEBUG
- BLI_mempool_set_memory_debug();
-#endif
- break;
- }
- case 'f': //fullscreen mode
- {
- i++;
- fullScreen = true;
- fullScreenParFound = true;
- if ((i + 2) <= validArguments && argv[i][0] != '-' && argv[i+1][0] != '-')
- {
- fullScreenWidth = atoi(argv[i++]);
- fullScreenHeight = atoi(argv[i++]);
- if ((i + 1) <= validArguments && argv[i][0] != '-')
- {
- fullScreenBpp = atoi(argv[i++]);
- if ((i + 1) <= validArguments && argv[i][0] != '-')
- fullScreenFrequency = atoi(argv[i++]);
- }
- }
- else if ((i + 1) <= validArguments && argv[i][0] != '-' && argv[i+1][0] != '-')
- {
- error = true;
- printf("error: to define fullscreen width or height, both options must be used.\n");
- }
- break;
- }
- case 'w': //display in a window
- {
- i++;
- fullScreen = false;
- windowParFound = true;
-
- // Parse window position and size options
- if ((i + 2) <= validArguments && argv[i][0] != '-' && argv[i+1][0] != '-')
- {
- windowWidth = atoi(argv[i++]);
- windowHeight = atoi(argv[i++]);
-
- if ((i + 2) <= validArguments && argv[i][0] != '-' && argv[i+1][0] != '-')
- {
- windowLeft = atoi(argv[i++]);
- windowTop = atoi(argv[i++]);
- }
- else if ((i + 1) <= validArguments && argv[i][0] != '-' && argv[i+1][0] != '-')
- {
- error = true;
- printf("error: to define the window left or right coordinates, both options must be used.\n");
- }
- }
- else if ((i + 1) <= validArguments && argv[i][0] != '-' && argv[i+1][0] != '-')
- {
- error = true;
- printf("error: to define the window's width or height, both options must be used.\n");
- }
- break;
- }
- case 'h': //display help
- {
- usage(argv[0], isBlenderPlayer);
- return 0;
- break;
- }
- case 'i': //parent window ID
- {
- i++;
- if ( (i + 1) <= validArguments )
- parentWindow = (GHOST_TEmbedderWindowID)atoll(argv[i++]);
- else {
- error = true;
- printf("error: too few options for parent window argument.\n");
- }
-#if defined(DEBUG)
- printf("XWindows ID = %d\n", parentWindow);
-#endif // defined(DEBUG)
- break;
- }
- case 'm': //maximum anti-aliasing (eg. 2,4,8,16)
- {
- i++;
- samplesParFound = true;
- if ((i+1) <= validArguments )
- aasamples = atoi(argv[i++]);
- else
- {
- error = true;
- printf("error: No argument supplied for -m");
- }
- break;
- }
- case 'c': //keep console (windows only)
- {
- i++;
-#ifdef WIN32
- closeConsole = false;
-#endif
- break;
- }
- case 's': //stereo mode
- {
- i++;
- if ((i + 1) <= validArguments)
- {
- stereoParFound = true;
- stereoFlag = STEREO_ENABLED;
-
- if (!strcmp(argv[i], "nostereo")) // may not be redundant if the file has different setting
- {
- stereomode = RAS_IRasterizer::RAS_STEREO_NOSTEREO;
- stereoFlag = STEREO_NOSTEREO;
- }
-
- // only the hardware pageflip method needs a stereo window
- else if (!strcmp(argv[i], "hwpageflip")) {
- stereomode = RAS_IRasterizer::RAS_STEREO_QUADBUFFERED;
- stereoWindow = true;
- }
- else if (!strcmp(argv[i], "syncdoubling"))
- stereomode = RAS_IRasterizer::RAS_STEREO_ABOVEBELOW;
-
- else if (!strcmp(argv[i], "3dtvtopbottom"))
- stereomode = RAS_IRasterizer::RAS_STEREO_3DTVTOPBOTTOM;
-
- else if (!strcmp(argv[i], "anaglyph"))
- stereomode = RAS_IRasterizer::RAS_STEREO_ANAGLYPH;
-
- else if (!strcmp(argv[i], "sidebyside"))
- stereomode = RAS_IRasterizer::RAS_STEREO_SIDEBYSIDE;
-
- else if (!strcmp(argv[i], "interlace"))
- stereomode = RAS_IRasterizer::RAS_STEREO_INTERLACED;
-
- else if (!strcmp(argv[i], "vinterlace"))
- stereomode = RAS_IRasterizer::RAS_STEREO_VINTERLACE;
-
-#if 0
-// // future stuff
-// else if (!strcmp(argv[i], "stencil")
-// stereomode = RAS_STEREO_STENCIL;
-#endif
- else
- {
- error = true;
- printf("error: stereomode '%s' unrecognized.\n", argv[i]);
- }
-
- i++;
- }
- else
- {
- error = true;
- printf("error: too few options for stereo argument.\n");
- }
- break;
- }
- case 'D': //dome mode
- {
- stereoFlag = STEREO_DOME;
- stereomode = RAS_IRasterizer::RAS_STEREO_DOME;
- i++;
- if ((i + 1) <= validArguments)
- {
- if (!strcmp(argv[i], "angle")) {
- i++;
- domeFov = atoi(argv[i++]);
- }
- if (!strcmp(argv[i], "tilt")) {
- i++;
- domeTilt = atoi(argv[i++]);
- }
- if (!strcmp(argv[i], "warpdata")) {
- i++;
- domeWarp = argv[i++];
- }
- if (!strcmp(argv[i], "mode")) {
- i++;
- if (!strcmp(argv[i], "fisheye"))
- domeMode = DOME_FISHEYE;
-
- else if (!strcmp(argv[i], "truncatedfront"))
- domeMode = DOME_TRUNCATED_FRONT;
-
- else if (!strcmp(argv[i], "truncatedrear"))
- domeMode = DOME_TRUNCATED_REAR;
-
- else if (!strcmp(argv[i], "cubemap"))
- domeMode = DOME_ENVMAP;
-
- else if (!strcmp(argv[i], "sphericalpanoramic"))
- domeMode = DOME_PANORAM_SPH;
-
- else
- printf("error: %s is not a valid dome mode.\n", argv[i]);
- }
- i++;
- }
- break;
- }
- case 'a': // allow window to blend with display background
- {
- i++;
- alphaBackground = 1;
- break;
- }
- default: //not recognized
- {
- printf("Unknown argument: %s\n", argv[i++]);
- break;
- }
- }
- }
- else
- {
- i++;
- }
- }
-
- if ((windowWidth < kMinWindowWidth) || (windowHeight < kMinWindowHeight))
- {
- error = true;
- printf("error: window size too small.\n");
- }
-
- if (error )
- {
- usage(argv[0], isBlenderPlayer);
- return 0;
- }
-
-#ifdef WIN32
- if (scr_saver_mode != SCREEN_SAVER_MODE_CONFIGURATION)
-#endif
- {
- // Create the system
- if (GHOST_ISystem::createSystem() == GHOST_kSuccess) {
- GHOST_ISystem* system = GHOST_ISystem::getSystem();
- assertd(system);
-
- if (!fullScreenWidth || !fullScreenHeight)
- system->getMainDisplayDimensions(fullScreenWidth, fullScreenHeight);
- // process first batch of events. If the user
- // drops a file on top off the blenderplayer icon, we
- // receive an event with the filename
-
- system->processEvents(0);
-
- // this bracket is needed for app (see below) to get out
- // of scope before GHOST_ISystem::disposeSystem() is called.
- {
- int exitcode = KX_EXIT_REQUEST_NO_REQUEST;
- STR_String exitstring = "";
- GPG_Application app(system);
- bool firstTimeRunning = true;
- char filename[FILE_MAX];
- char pathname[FILE_MAX];
- char *titlename;
-
- get_filename(argc_py_clamped, argv, filename);
- if (filename[0])
- BLI_path_cwd(filename, sizeof(filename));
-
-
- // fill the GlobalSettings with the first scene files
- // those may change during the game and persist after using Game Actuator
- GlobalSettings gs;
-
- do {
- // Read the Blender file
- BlendFileData *bfd;
-
- // if we got an exitcode 3 (KX_EXIT_REQUEST_START_OTHER_GAME) load a different file
- if (exitcode == KX_EXIT_REQUEST_START_OTHER_GAME)
- {
- char basedpath[FILE_MAX];
-
- // base the actuator filename relative to the last file
- BLI_strncpy(basedpath, exitstring.Ptr(), sizeof(basedpath));
- BLI_path_abs(basedpath, pathname);
-
- bfd = load_game_data(basedpath);
-
- if (!bfd) {
- // just add "//" in front of it
- char temppath[FILE_MAX] = "//";
- BLI_strncpy(temppath + 2, basedpath, FILE_MAX - 2);
-
- BLI_path_abs(temppath, pathname);
- bfd = load_game_data(temppath);
- }
- }
- else {
- bfd = load_game_data(BKE_appdir_program_path(), filename[0]? filename: NULL);
- }
-
-#if defined(DEBUG)
- printf("Game data loaded from %s\n", filename);
-#endif
-
- if (!bfd) {
- usage(argv[0], isBlenderPlayer);
- error = true;
- exitcode = KX_EXIT_REQUEST_QUIT_GAME;
- }
- else {
- /* Setting options according to the blend file if not overriden in the command line */
-#ifdef WIN32
-#if !defined(DEBUG)
- if (closeConsole) {
- system->toggleConsole(0); // Close a console window
- }
-#endif // !defined(DEBUG)
-#endif // WIN32
- Main *maggie = bfd->main;
- Scene *scene = bfd->curscene;
- G.main = maggie;
-
- if (firstTimeRunning) {
- G.fileflags = bfd->fileflags;
-
- gs.matmode= scene->gm.matmode;
- gs.glslflag= scene->gm.flag;
- }
-
- //Seg Fault; icon.c gIcons == 0
- BKE_icons_init(1);
-
- titlename = maggie->name;
-
- // Check whether the game should be displayed full-screen
- if ((!fullScreenParFound) && (!windowParFound)) {
- // Only use file settings when command line did not override
- if ((scene->gm.playerflag & GAME_PLAYER_FULLSCREEN)) {
- //printf("fullscreen option found in Blender file\n");
- fullScreen = true;
- fullScreenWidth= scene->gm.xplay;
- fullScreenHeight= scene->gm.yplay;
- fullScreenFrequency= scene->gm.freqplay;
- fullScreenBpp = scene->gm.depth;
- }
- else
- {
- fullScreen = false;
- windowWidth = scene->gm.xplay;
- windowHeight = scene->gm.yplay;
- }
- }
-
-
- // Check whether the game should be displayed in stereo (dome included)
- if (!stereoParFound) {
- // Only use file settings when command line did not override
- if (scene->gm.stereoflag == STEREO_ENABLED) {
- stereomode = (RAS_IRasterizer::StereoMode) scene->gm.stereomode;
- if (stereomode == RAS_IRasterizer::RAS_STEREO_QUADBUFFERED)
- stereoWindow = true;
- }
- }
- else {
- scene->gm.stereoflag = STEREO_ENABLED;
- }
-
- if (!samplesParFound)
- aasamples = scene->gm.aasamples;
-
- // Dome specific settings
- if (stereoFlag == STEREO_DOME) {
- stereomode = RAS_IRasterizer::RAS_STEREO_DOME;
- scene->gm.stereoflag = STEREO_DOME;
- if (domeFov > 89)
- scene->gm.dome.angle = domeFov;
- if (domeTilt > -180)
- scene->gm.dome.tilt = domeTilt;
- if (domeMode > 0)
- scene->gm.dome.mode = domeMode;
- if (domeWarp) {
- //XXX to do: convert relative to absolute path
- domeText= BKE_text_load(G.main, domeWarp, "");
- if (!domeText)
- printf("error: invalid warpdata text file - %s\n", domeWarp);
- else
- scene->gm.dome.warptext = domeText;
- }
- }
-
- // GPG_Application app (system, maggie, startscenename);
- app.SetGameEngineData(maggie, scene, &gs, argc, argv); /* this argc cant be argc_py_clamped, since python uses it */
- BLI_strncpy(pathname, maggie->name, sizeof(pathname));
- if (G.main != maggie) {
- BLI_strncpy(G.main->name, maggie->name, sizeof(G.main->name));
- }
-#ifdef WITH_PYTHON
- setGamePythonPath(G.main->name);
-#endif
- if (firstTimeRunning) {
- firstTimeRunning = false;
-
- if (fullScreen) {
-#ifdef WIN32
- if (scr_saver_mode == SCREEN_SAVER_MODE_SAVER)
- {
- app.startScreenSaverFullScreen(fullScreenWidth, fullScreenHeight, fullScreenBpp, fullScreenFrequency,
- stereoWindow, stereomode, aasamples);
- }
- else
-#endif
- {
- app.startFullScreen(fullScreenWidth, fullScreenHeight, fullScreenBpp, fullScreenFrequency,
- stereoWindow, stereomode, alphaBackground, aasamples, (scene->gm.playerflag & GAME_PLAYER_DESKTOP_RESOLUTION));
- }
- }
- else
- {
-#ifdef __APPLE__
- // on Mac's we'll show the executable name instead of the 'game.blend' name
- char tempname[1024], *appstring;
- ::strcpy(tempname, titlename);
-
- appstring = strstr(tempname, ".app/");
- if (appstring) {
- appstring[2] = 0;
- titlename = &tempname[0];
- }
-#endif
- // Strip the path so that we have the name of the game file
- STR_String path = titlename;
-#ifndef WIN32
- vector<STR_String> parts = path.Explode('/');
-#else // WIN32
- vector<STR_String> parts = path.Explode('\\');
-#endif // WIN32
- STR_String title;
- if (parts.size()) {
- title = parts[parts.size()-1];
- parts = title.Explode('.');
- if (parts.size() > 1)
- {
- title = parts[0];
- }
- }
- else {
- title = "blenderplayer";
- }
-#ifdef WIN32
- if (scr_saver_mode == SCREEN_SAVER_MODE_PREVIEW)
- {
- app.startScreenSaverPreview(scr_saver_hwnd, stereoWindow, stereomode, aasamples);
- }
- else
-#endif
- {
- if (parentWindow != 0)
- app.startEmbeddedWindow(title, parentWindow, stereoWindow, stereomode, aasamples);
- else
- app.startWindow(title, windowLeft, windowTop, windowWidth, windowHeight,
- stereoWindow, stereomode, alphaBackground, aasamples);
-
- if (SYS_GetCommandLineInt(syshandle, "nomipmap", 0)) {
- GPU_set_mipmap(0);
- }
-
- GPU_set_anisotropic(U.anisotropic_filter);
- GPU_set_gpu_mipmapping(U.use_gpu_mipmap);
- }
- }
- }
- else {
- app.StartGameEngine(stereomode);
- exitcode = KX_EXIT_REQUEST_NO_REQUEST;
- }
-
- // Add the application as event consumer
- system->addEventConsumer(&app);
-
- // Enter main loop
- bool run = true;
- char *python_main = NULL;
- pynextframestate.state = NULL;
- pynextframestate.func = NULL;
-#ifdef WITH_PYTHON
- python_main = KX_GetPythonMain(scene);
-#endif // WITH_PYTHON
- if (python_main) {
- char *python_code = KX_GetPythonCode(maggie, python_main);
- if (python_code) {
-#ifdef WITH_PYTHON
- // Set python environement variable.
- KX_Scene *startscene = app.GetStartScene();
- KX_SetActiveScene(startscene);
- PHY_SetActiveEnvironment(startscene->GetPhysicsEnvironment());
-
- gpg_nextframestate.system = system;
- gpg_nextframestate.app = &app;
- gpg_nextframestate.gs = &gs;
- pynextframestate.state = &gpg_nextframestate;
- pynextframestate.func = &GPG_PyNextFrame;
-
- printf("Yielding control to Python script '%s'...\n", python_main);
- PyRun_SimpleString(python_code);
- printf("Exit Python script '%s'\n", python_main);
-#endif // WITH_PYTHON
- MEM_freeN(python_code);
- }
- else {
- fprintf(stderr, "ERROR: cannot yield control to Python: no Python text data-block named '%s'\n", python_main);
- }
- }
- else {
- while (run) {
- run = GPG_NextFrame(system, &app, exitcode, exitstring, &gs);
- }
- }
- app.StopGameEngine();
-
- /* 'app' is freed automatic when out of scope.
- * removal is needed else the system will free an already freed value */
- system->removeEventConsumer(&app);
-
- BLO_blendfiledata_free(bfd);
- /* G.main == bfd->main, it gets referenced in free_nodesystem so we can't have a dangling pointer */
- G.main = NULL;
- if (python_main) MEM_freeN(python_main);
- }
- } while (exitcode == KX_EXIT_REQUEST_RESTART_GAME || exitcode == KX_EXIT_REQUEST_START_OTHER_GAME);
- }
-
- // Seg Fault; icon.c gIcons == 0
- BKE_icons_free();
-
- // Dispose the system
- GHOST_ISystem::disposeSystem();
- }
- else {
- error = true;
- printf("error: couldn't create a system.\n");
- }
- }
-
- /* refer to WM_exit_ext() and BKE_blender_free(),
- * these are not called in the player but we need to match some of there behavior here,
- * if the order of function calls or blenders state isn't matching that of blender proper,
- * we may get troubles later on */
-
- free_nodesystem();
-
- // Cleanup
- RNA_exit();
- BLF_exit();
-
-#ifdef WITH_INTERNATIONAL
- BLF_free_unifont();
- BLF_free_unifont_mono();
- BLT_lang_free();
-#endif
-
- IMB_exit();
- BKE_images_exit();
- DEG_free_node_types();
- IMB_moviecache_destruct();
-
- SYS_DeleteSystem(syshandle);
-
- int totblock= MEM_get_memory_blocks_in_use();
- if (totblock!=0) {
- printf("Error Totblock: %d\n",totblock);
- MEM_set_error_callback(mem_error_cb);
- MEM_printmemlist();
- }
-
- BKE_tempdir_session_purge();
-
-#ifdef WIN32
- while (argv_num) {
- free(argv[--argv_num]);
- }
- free(argv);
- argv = NULL;
-#endif
-
- return error ? -1 : 0;
-}
diff --git a/source/gameengine/Ketsji/BL_Action.cpp b/source/gameengine/Ketsji/BL_Action.cpp
deleted file mode 100644
index 7175eb877dd..00000000000
--- a/source/gameengine/Ketsji/BL_Action.cpp
+++ /dev/null
@@ -1,534 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * Contributor(s): Mitchell Stokes.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file BL_Action.cpp
- * \ingroup ketsji
- */
-
-#include <cstdlib>
-#include <stdio.h>
-
-#include "BL_Action.h"
-#include "BL_ArmatureObject.h"
-#include "BL_DeformableGameObject.h"
-#include "BL_ShapeDeformer.h"
-#include "KX_IpoConvert.h"
-#include "KX_GameObject.h"
-
-#include "SG_Controller.h"
-
-// These three are for getting the action from the logic manager
-#include "KX_Scene.h"
-#include "SCA_LogicManager.h"
-
-extern "C" {
-#include "BKE_animsys.h"
-#include "BKE_action.h"
-#include "RNA_access.h"
-#include "RNA_define.h"
-
-// Needed for material IPOs
-#include "BKE_material.h"
-#include "DNA_material_types.h"
-#include "DNA_scene_types.h"
-}
-
-#include "MEM_guardedalloc.h"
-#include "BKE_library.h"
-#include "BKE_global.h"
-
-#include "BLI_threads.h" // for lock
-
-/* Lock to solve animation thread issues.
- * A spin lock is better than a mutex in case of short wait
- * because spin lock stop the thread by a loop contrary to mutex
- * which switch all memory, process.
- */
-static SpinLock BL_ActionLock;
-
-BL_Action::BL_Action(class KX_GameObject* gameobj)
-:
- m_action(NULL),
- m_tmpaction(NULL),
- m_blendpose(NULL),
- m_blendinpose(NULL),
- m_obj(gameobj),
- m_startframe(0.f),
- m_endframe(0.f),
- m_localframe(0.f),
- m_blendin(0.f),
- m_blendframe(0.f),
- m_blendstart(0.f),
- m_speed(0.f),
- m_priority(0),
- m_playmode(ACT_MODE_PLAY),
- m_blendmode(ACT_BLEND_BLEND),
- m_ipo_flags(0),
- m_done(true),
- m_calc_localtime(true),
- m_initializedTime(false)
-{
-}
-
-BL_Action::~BL_Action()
-{
- if (m_blendpose)
- BKE_pose_free(m_blendpose);
- if (m_blendinpose)
- BKE_pose_free(m_blendinpose);
- ClearControllerList();
-
- if (m_tmpaction) {
- BKE_libblock_free(G.main, m_tmpaction);
- m_tmpaction = NULL;
- }
-}
-
-void BL_Action::ClearControllerList()
-{
- // Clear out the controller list
- std::vector<SG_Controller*>::iterator it;
- for (it = m_sg_contr_list.begin(); it != m_sg_contr_list.end(); it++)
- {
- m_obj->GetSGNode()->RemoveSGController((*it));
- delete *it;
- }
-
- m_sg_contr_list.clear();
-}
-
-bool BL_Action::Play(const char* name,
- float start,
- float end,
- short priority,
- float blendin,
- short play_mode,
- float layer_weight,
- short ipo_flags,
- float playback_speed,
- short blend_mode)
-{
-
- // Only start playing a new action if we're done, or if
- // the new action has a higher priority
- if (!IsDone() && priority > m_priority)
- return false;
- m_priority = priority;
- bAction* prev_action = m_action;
-
- KX_Scene* kxscene = m_obj->GetScene();
-
- // First try to load the action
- m_action = (bAction*)kxscene->GetLogicManager()->GetActionByName(name);
- if (!m_action)
- {
- printf("Failed to load action: %s\n", name);
- m_done = true;
- return false;
- }
-
- // If we have the same settings, don't play again
- // This is to resolve potential issues with pulses on sensors such as the ones
- // reported in bug #29412. The fix is here so it works for both logic bricks and Python.
- // However, this may eventually lead to issues where a user wants to override an already
- // playing action with the same action and settings. If this becomes an issue,
- // then this fix may have to be re-evaluated.
- if (!IsDone() && m_action == prev_action && m_startframe == start && m_endframe == end
- && m_priority == priority && m_speed == playback_speed)
- return false;
-
- // Keep a copy of the action for threading purposes
- if (m_tmpaction) {
- BKE_libblock_free(G.main, m_tmpaction);
- m_tmpaction = NULL;
- }
- m_tmpaction = BKE_action_copy(G.main, m_action);
-
- // First get rid of any old controllers
- ClearControllerList();
-
- // Create an SG_Controller
- SG_Controller *sg_contr = BL_CreateIPO(m_action, m_obj, kxscene->GetSceneConverter());
- m_sg_contr_list.push_back(sg_contr);
- m_obj->GetSGNode()->AddSGController(sg_contr);
- sg_contr->SetObject(m_obj->GetSGNode());
-
- // World
- sg_contr = BL_CreateWorldIPO(m_action, kxscene->GetBlenderScene()->world, kxscene->GetSceneConverter());
- if (sg_contr) {
- m_sg_contr_list.push_back(sg_contr);
- m_obj->GetSGNode()->AddSGController(sg_contr);
- sg_contr->SetObject(m_obj->GetSGNode());
- }
-
- // Try obcolor
- sg_contr = BL_CreateObColorIPO(m_action, m_obj, kxscene->GetSceneConverter());
- if (sg_contr) {
- m_sg_contr_list.push_back(sg_contr);
- m_obj->GetSGNode()->AddSGController(sg_contr);
- sg_contr->SetObject(m_obj->GetSGNode());
- }
-
- // Now try materials
- if (m_obj->GetBlenderObject()->totcol==1) {
- Material *mat = give_current_material(m_obj->GetBlenderObject(), 1);
- if (mat) {
- sg_contr = BL_CreateMaterialIpo(m_action, mat, 0, m_obj, kxscene->GetSceneConverter());
- if (sg_contr) {
- m_sg_contr_list.push_back(sg_contr);
- m_obj->GetSGNode()->AddSGController(sg_contr);
- sg_contr->SetObject(m_obj->GetSGNode());
- }
- }
- } else {
- Material *mat;
- STR_HashedString matname;
-
- for (int matidx = 1; matidx <= m_obj->GetBlenderObject()->totcol; ++matidx) {
- mat = give_current_material(m_obj->GetBlenderObject(), matidx);
- if (mat) {
- matname = mat->id.name;
- sg_contr = BL_CreateMaterialIpo(m_action, mat, matname.hash(), m_obj, kxscene->GetSceneConverter());
- if (sg_contr) {
- m_sg_contr_list.push_back(sg_contr);
- m_obj->GetSGNode()->AddSGController(sg_contr);
- sg_contr->SetObject(m_obj->GetSGNode());
- }
- }
- }
- }
-
- // Extra controllers
- if (m_obj->GetGameObjectType() == SCA_IObject::OBJ_LIGHT)
- {
- sg_contr = BL_CreateLampIPO(m_action, m_obj, kxscene->GetSceneConverter());
- m_sg_contr_list.push_back(sg_contr);
- m_obj->GetSGNode()->AddSGController(sg_contr);
- sg_contr->SetObject(m_obj->GetSGNode());
- }
- else if (m_obj->GetGameObjectType() == SCA_IObject::OBJ_CAMERA)
- {
- sg_contr = BL_CreateCameraIPO(m_action, m_obj, kxscene->GetSceneConverter());
- m_sg_contr_list.push_back(sg_contr);
- m_obj->GetSGNode()->AddSGController(sg_contr);
- sg_contr->SetObject(m_obj->GetSGNode());
- }
-
- m_ipo_flags = ipo_flags;
- InitIPO();
-
- // Setup blendin shapes/poses
- if (m_obj->GetGameObjectType() == SCA_IObject::OBJ_ARMATURE)
- {
- BL_ArmatureObject *obj = (BL_ArmatureObject*)m_obj;
- obj->GetPose(&m_blendinpose);
- }
- else
- {
- BL_DeformableGameObject *obj = (BL_DeformableGameObject*)m_obj;
- BL_ShapeDeformer *shape_deformer = dynamic_cast<BL_ShapeDeformer*>(obj->GetDeformer());
-
- if (shape_deformer && shape_deformer->GetKey())
- {
- obj->GetShape(m_blendinshape);
-
- // Now that we have the previous blend shape saved, we can clear out the key to avoid any
- // further interference.
- KeyBlock *kb;
- for (kb=(KeyBlock *)shape_deformer->GetKey()->block.first; kb; kb=(KeyBlock *)kb->next)
- kb->curval = 0.f;
- }
- }
-
- // Now that we have an action, we have something we can play
- m_starttime = -1.f; // We get the start time on our first update
- m_startframe = m_localframe = start;
- m_endframe = end;
- m_blendin = blendin;
- m_playmode = play_mode;
- m_blendmode = blend_mode;
- m_blendframe = 0.f;
- m_blendstart = 0.f;
- m_speed = playback_speed;
- m_layer_weight = layer_weight;
-
- m_done = false;
- m_initializedTime = false;
-
- return true;
-}
-
-bool BL_Action::IsDone()
-{
- return m_done;
-}
-
-void BL_Action::InitIPO()
-{
- // Initialize the IPOs
- std::vector<SG_Controller*>::iterator it;
- for (it = m_sg_contr_list.begin(); it != m_sg_contr_list.end(); it++)
- {
- (*it)->SetOption(SG_Controller::SG_CONTR_IPO_RESET, true);
- (*it)->SetOption(SG_Controller::SG_CONTR_IPO_IPO_AS_FORCE, m_ipo_flags & ACT_IPOFLAG_FORCE);
- (*it)->SetOption(SG_Controller::SG_CONTR_IPO_IPO_ADD, m_ipo_flags & ACT_IPOFLAG_ADD);
- (*it)->SetOption(SG_Controller::SG_CONTR_IPO_LOCAL, m_ipo_flags & ACT_IPOFLAG_LOCAL);
- }
-}
-
-bAction *BL_Action::GetAction()
-{
- return (IsDone()) ? NULL : m_action;
-}
-
-float BL_Action::GetFrame()
-{
- return m_localframe;
-}
-
-const char *BL_Action::GetName()
-{
- if (m_action != NULL) {
- return m_action->id.name + 2;
- }
- else {
- return "";
- }
-
-
-}
-
-void BL_Action::SetFrame(float frame)
-{
- // Clamp the frame to the start and end frame
- if (frame < min(m_startframe, m_endframe))
- frame = min(m_startframe, m_endframe);
- else if (frame > max(m_startframe, m_endframe))
- frame = max(m_startframe, m_endframe);
-
- m_localframe = frame;
- m_calc_localtime = false;
-}
-
-void BL_Action::SetPlayMode(short play_mode)
-{
- m_playmode = play_mode;
-}
-
-void BL_Action::SetTimes(float start, float end)
-{
- m_startframe = start;
- m_endframe = end;
-}
-
-void BL_Action::SetLocalTime(float curtime)
-{
- float dt = (curtime-m_starttime)*(float)KX_KetsjiEngine::GetAnimFrameRate()*m_speed;
-
- if (m_endframe < m_startframe)
- dt = -dt;
-
- m_localframe = m_startframe + dt;
-}
-
-void BL_Action::ResetStartTime(float curtime)
-{
- float dt = (m_localframe > m_startframe) ? m_localframe - m_startframe : m_startframe - m_localframe;
-
- m_starttime = curtime - dt / ((float)KX_KetsjiEngine::GetAnimFrameRate()*m_speed);
- SetLocalTime(curtime);
-}
-
-void BL_Action::IncrementBlending(float curtime)
-{
- // Setup m_blendstart if we need to
- if (m_blendstart == 0.f)
- m_blendstart = curtime;
-
- // Bump the blend frame
- m_blendframe = (curtime - m_blendstart)*(float)KX_KetsjiEngine::GetAnimFrameRate();
-
- // Clamp
- if (m_blendframe>m_blendin)
- m_blendframe = m_blendin;
-}
-
-
-void BL_Action::BlendShape(Key* key, float srcweight, std::vector<float>& blendshape)
-{
- vector<float>::const_iterator it;
- float dstweight;
- KeyBlock *kb;
-
- dstweight = 1.0F - srcweight;
- //printf("Dst: %f\tSrc: %f\n", srcweight, dstweight);
- for (it=blendshape.begin(), kb = (KeyBlock *)key->block.first;
- kb && it != blendshape.end();
- kb = (KeyBlock *)kb->next, it++)
- {
- //printf("OirgKeys: %f\t%f\n", kb->curval, (*it));
- kb->curval = kb->curval * dstweight + (*it) * srcweight;
- //printf("NewKey: %f\n", kb->curval);
- }
- //printf("\n");
-}
-
-void BL_Action::Update(float curtime)
-{
- // Don't bother if we're done with the animation
- if (m_done)
- return;
-
- curtime -= (float)KX_KetsjiEngine::GetSuspendedDelta();
-
- // Grab the start time here so we don't end up with a negative m_localframe when
- // suspending and resuming scenes.
- if (!m_initializedTime) {
- m_starttime = curtime;
- m_initializedTime = true;
- }
-
- if (m_calc_localtime)
- SetLocalTime(curtime);
- else
- {
- ResetStartTime(curtime);
- m_calc_localtime = true;
- }
-
- // Handle wrap around
- if (m_localframe < min(m_startframe, m_endframe) || m_localframe > max(m_startframe, m_endframe)) {
- switch (m_playmode) {
- case ACT_MODE_PLAY:
- // Clamp
- m_localframe = m_endframe;
- m_done = true;
- break;
- case ACT_MODE_LOOP:
- // Put the time back to the beginning
- m_localframe = m_startframe;
- m_starttime = curtime;
- break;
- case ACT_MODE_PING_PONG:
- // Swap the start and end frames
- float temp = m_startframe;
- m_startframe = m_endframe;
- m_endframe = temp;
-
- m_starttime = curtime;
-
- break;
- }
- }
-
- if (m_obj->GetGameObjectType() == SCA_IObject::OBJ_ARMATURE)
- {
- BL_ArmatureObject *obj = (BL_ArmatureObject*)m_obj;
-
- if (m_layer_weight >= 0)
- obj->GetPose(&m_blendpose);
-
- // Extract the pose from the action
- obj->SetPoseByAction(m_tmpaction, m_localframe);
-
- // Handle blending between armature actions
- if (m_blendin && m_blendframe<m_blendin)
- {
- IncrementBlending(curtime);
-
- // Calculate weight
- float weight = 1.f - (m_blendframe/m_blendin);
-
- // Blend the poses
- obj->BlendInPose(m_blendinpose, weight, ACT_BLEND_BLEND);
- }
-
-
- // Handle layer blending
- if (m_layer_weight >= 0)
- obj->BlendInPose(m_blendpose, m_layer_weight, m_blendmode);
-
- obj->UpdateTimestep(curtime);
- }
- else
- {
- BL_DeformableGameObject *obj = (BL_DeformableGameObject*)m_obj;
- BL_ShapeDeformer *shape_deformer = dynamic_cast<BL_ShapeDeformer*>(obj->GetDeformer());
-
- // Handle shape actions if we have any
- if (shape_deformer && shape_deformer->GetKey())
- {
- Key *key = shape_deformer->GetKey();
-
- PointerRNA ptrrna;
- RNA_id_pointer_create(&key->id, &ptrrna);
-
- animsys_evaluate_action(&ptrrna, m_tmpaction, NULL, m_localframe);
-
- // Handle blending between shape actions
- if (m_blendin && m_blendframe < m_blendin)
- {
- IncrementBlending(curtime);
-
- float weight = 1.f - (m_blendframe/m_blendin);
-
- // We go through and clear out the keyblocks so there isn't any interference
- // from other shape actions
- KeyBlock *kb;
- for (kb=(KeyBlock *)key->block.first; kb; kb=(KeyBlock *)kb->next)
- kb->curval = 0.f;
-
- // Now blend the shape
- BlendShape(key, weight, m_blendinshape);
- }
-
- // Handle layer blending
- if (m_layer_weight >= 0)
- {
- obj->GetShape(m_blendshape);
- BlendShape(key, m_layer_weight, m_blendshape);
- }
-
- obj->SetActiveAction(NULL, 0, curtime);
- }
- }
-
- BLI_spin_lock(&BL_ActionLock);
- /* This function is not thread safe because of recursive scene graph transform
- * updates on children. e.g: If an object and one of its children is animated,
- * the both can write transform at the same time. A thread lock avoid problems. */
- m_obj->UpdateIPO(m_localframe, m_ipo_flags & ACT_IPOFLAG_CHILD);
- BLI_spin_unlock(&BL_ActionLock);
-
- if (m_done)
- ClearControllerList();
-}
-
-void BL_Action::InitLock()
-{
- BLI_spin_init(&BL_ActionLock);
-}
-
-void BL_Action::EndLock()
-{
- BLI_spin_end(&BL_ActionLock);
-}
diff --git a/source/gameengine/Ketsji/BL_Action.h b/source/gameengine/Ketsji/BL_Action.h
deleted file mode 100644
index f4c2975a547..00000000000
--- a/source/gameengine/Ketsji/BL_Action.h
+++ /dev/null
@@ -1,151 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * Contributor(s): Mitchell Stokes.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file BL_Action.h
- * \ingroup ketsji
- */
-
-#ifndef __BL_ACTION_H__
-#define __BL_ACTION_H__
-
-
-#include <vector>
-
-#ifdef WITH_CXX_GUARDEDALLOC
-#include "MEM_guardedalloc.h"
-#endif
-
-class BL_Action
-{
-private:
- struct bAction* m_action;
- struct bAction* m_tmpaction;
- struct bPose* m_blendpose;
- struct bPose* m_blendinpose;
- std::vector<class SG_Controller*> m_sg_contr_list;
- class KX_GameObject* m_obj;
- std::vector<float> m_blendshape;
- std::vector<float> m_blendinshape;
-
- float m_startframe;
- float m_endframe;
- /// The current action frame.
- float m_localframe;
- float m_starttime;
-
- float m_blendin;
- float m_blendframe;
- float m_blendstart;
-
- float m_layer_weight;
-
- float m_speed;
-
- short m_priority;
-
- short m_playmode;
- short m_blendmode;
-
- short m_ipo_flags;
-
- bool m_done;
- bool m_calc_localtime;
- /// Set to true when m_starttime is initialized in Update.
- bool m_initializedTime;
-
- void ClearControllerList();
- void InitIPO();
- void SetLocalTime(float curtime);
- void ResetStartTime(float curtime);
- void IncrementBlending(float curtime);
- void BlendShape(struct Key* key, float srcweight, std::vector<float>& blendshape);
-public:
- BL_Action(class KX_GameObject* gameobj);
- ~BL_Action();
-
- /**
- * Play an action
- */
- bool Play(const char* name,
- float start,
- float end,
- short priority,
- float blendin,
- short play_mode,
- float layer_weight,
- short ipo_flags,
- float playback_speed,
- short blend_mode);
- /**
- * Whether or not the action is still playing
- */
- bool IsDone();
- /**
- * Update the action's frame, etc.
- */
- void Update(float curtime);
-
- // Accessors
- float GetFrame();
- const char *GetName();
-
- struct bAction *GetAction();
-
- // Mutators
- void SetFrame(float frame);
- void SetPlayMode(short play_mode);
- void SetTimes(float start, float end);
-
- enum
- {
- ACT_MODE_PLAY = 0,
- ACT_MODE_LOOP,
- ACT_MODE_PING_PONG,
- ACT_MODE_MAX,
- };
-
- enum
- {
- ACT_BLEND_BLEND=0,
- ACT_BLEND_ADD=1,
- ACT_BLEND_MAX,
- };
-
- enum
- {
- ACT_IPOFLAG_FORCE = 1,
- ACT_IPOFLAG_LOCAL = 2,
- ACT_IPOFLAG_ADD = 4,
- ACT_IPOFLAG_CHILD = 8,
- };
-
- /// Initialize a lock for animation thread issues.
- static void InitLock();
- /// Finalize a lock for animation thread issues.
- static void EndLock();
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:BL_Action")
-#endif
-};
-
-#endif /* BL_ACTION */
diff --git a/source/gameengine/Ketsji/BL_ActionManager.cpp b/source/gameengine/Ketsji/BL_ActionManager.cpp
deleted file mode 100644
index 35f605f1a5f..00000000000
--- a/source/gameengine/Ketsji/BL_ActionManager.cpp
+++ /dev/null
@@ -1,164 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * Contributor(s): Mitchell Stokes.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file BL_ActionManager.cpp
- * \ingroup ketsji
- */
-
-#include "BL_Action.h"
-#include "BL_ActionManager.h"
-#include "DNA_ID.h"
-
-#define IS_TAGGED(_id) ((_id) && (((ID *)_id)->tag & LIB_TAG_DOIT))
-
-BL_ActionManager::BL_ActionManager(class KX_GameObject *obj):
- m_obj(obj),
- m_prevUpdate(-1.0f)
-{
-}
-
-BL_ActionManager::~BL_ActionManager()
-{
- BL_ActionMap::iterator it;
-
- for (it = m_layers.begin(); it != m_layers.end(); it++)
- delete it->second;
-
- m_layers.clear();
-}
-
-BL_Action *BL_ActionManager::GetAction(short layer)
-{
- BL_ActionMap::iterator it = m_layers.find(layer);
-
- return (it != m_layers.end()) ? it->second : 0;
-}
-
-float BL_ActionManager::GetActionFrame(short layer)
-{
- BL_Action *action = GetAction(layer);
-
- return action ? action->GetFrame() : 0.f;
-}
-
-const char *BL_ActionManager::GetActionName(short layer)
-{
- BL_Action *action = GetAction(layer);
- return action ? action->GetName() : "";
-}
-
-void BL_ActionManager::SetActionFrame(short layer, float frame)
-{
- BL_Action *action = GetAction(layer);
-
- if (action) action->SetFrame(frame);
-}
-
-struct bAction *BL_ActionManager::GetCurrentAction(short layer)
-{
- BL_Action *action = GetAction(layer);
-
- return action ? action->GetAction() : 0;
-}
-
-void BL_ActionManager::SetPlayMode(short layer, short mode)
-{
- BL_Action *action = GetAction(layer);
-
- if (action) action->SetPlayMode(mode);
-}
-
-void BL_ActionManager::SetTimes(short layer, float start, float end)
-{
- BL_Action *action = GetAction(layer);
-
- if (action) action->SetTimes(start, end);
-}
-
-bool BL_ActionManager::PlayAction(const char* name,
- float start,
- float end,
- short layer,
- short priority,
- float blendin,
- short play_mode,
- float layer_weight,
- short ipo_flags,
- float playback_speed,
- short blend_mode)
-{
- // Only this method will create layer if non-existent
- BL_Action *action = GetAction(layer);
- if (!action) {
- action = new BL_Action(m_obj);
- m_layers[layer] = action;
- }
-
- // Disable layer blending on the first layer
- if (layer == 0) layer_weight = -1.f;
-
- return action->Play(name, start, end, priority, blendin, play_mode, layer_weight, ipo_flags, playback_speed, blend_mode);
-}
-
-void BL_ActionManager::StopAction(short layer)
-{
- BL_Action *action = GetAction(layer);
-
- if (action) {
- m_layers.erase(layer);
- delete action;
- }
-}
-
-void BL_ActionManager::RemoveTaggedActions()
-{
- for (BL_ActionMap::iterator it = m_layers.begin(); it != m_layers.end();) {
- if (IS_TAGGED(it->second->GetAction())) {
- delete it->second;
- m_layers.erase(it++);
- }
- else
- ++it;
- }
-}
-
-bool BL_ActionManager::IsActionDone(short layer)
-{
- BL_Action *action = GetAction(layer);
-
- return action ? action->IsDone() : true;
-}
-
-void BL_ActionManager::Update(float curtime)
-{
- if (m_prevUpdate == curtime)
- return;
- m_prevUpdate = curtime;
-
- BL_ActionMap::iterator it;
- for (it = m_layers.begin(); it != m_layers.end(); ++it)
- {
- if (!it->second->IsDone()) {
- it->second->Update(curtime);
- }
- }
-}
diff --git a/source/gameengine/Ketsji/BL_ActionManager.h b/source/gameengine/Ketsji/BL_ActionManager.h
deleted file mode 100644
index 69c6d611df0..00000000000
--- a/source/gameengine/Ketsji/BL_ActionManager.h
+++ /dev/null
@@ -1,132 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * Contributor(s): Mitchell Stokes.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file BL_ActionManager.h
- * \ingroup ketsji
- */
-
-#ifndef __BL_ACTIONMANAGER_H__
-#define __BL_ACTIONMANAGER_H__
-
-#ifdef WITH_CXX_GUARDEDALLOC
- #include "MEM_guardedalloc.h"
-#endif
-
-#include <map>
-
-// Currently, we use the max value of a short.
-// We should switch to unsigned short; doesn't make sense to support negative layers.
-// This will also give us 64k layers instead of 32k.
-#define MAX_ACTION_LAYERS 32767
-
-class BL_Action;
-
-/**
- * BL_ActionManager is responsible for handling a KX_GameObject's actions.
- */
-class BL_ActionManager
-{
-private:
- typedef std::map<short,BL_Action*> BL_ActionMap;
-
- class KX_GameObject* m_obj;
- BL_ActionMap m_layers;
-
- // The last update time to avoid double animation update.
- float m_prevUpdate;
-
- /**
- * Check if an action exists
- */
- BL_Action* GetAction(short layer);
-
-public:
- BL_ActionManager(class KX_GameObject* obj);
- ~BL_ActionManager();
-
- bool PlayAction(const char* name,
- float start,
- float end,
- short layer=0,
- short priority=0,
- float blendin=0.f,
- short play_mode=0,
- float layer_weight=0.f,
- short ipo_flags=0,
- float playback_speed=1.f,
- short blend_mode=0);
- /**
- * Gets the current frame of an action
- */
- float GetActionFrame(short layer);
-
- /**
- * Gets the name of the current action
- */
- const char *GetActionName(short layer);
-
- /**
- * Sets the current frame of an action
- */
- void SetActionFrame(short layer, float frame);
-
- /**
- * Gets the currently running action on the given layer
- */
- struct bAction *GetCurrentAction(short layer);
-
- /**
- * Sets play mode of the action on the given layer
- */
- void SetPlayMode(short layer, short mode);
-
- /**
- * Sets the start and end times of the action on the given layer
- */
- void SetTimes(short layer, float start, float end);
-
- /**
- * Stop playing the action on the given layer
- */
- void StopAction(short layer);
-
- /**
- * Remove playing tagged actions.
- */
- void RemoveTaggedActions();
-
- /**
- * Check if an action has finished playing
- */
- bool IsActionDone(short layer);
-
- /**
- * Update any running actions
- */
- void Update(float);
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:BL_ActionManager")
-#endif
-};
-
-#endif /* BL_ACTIONMANAGER */
diff --git a/source/gameengine/Ketsji/BL_BlenderShader.cpp b/source/gameengine/Ketsji/BL_BlenderShader.cpp
deleted file mode 100644
index 572218e691d..00000000000
--- a/source/gameengine/Ketsji/BL_BlenderShader.cpp
+++ /dev/null
@@ -1,188 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Ketsji/BL_BlenderShader.cpp
- * \ingroup ketsji
- */
-
-#include "DNA_customdata_types.h"
-#include "DNA_material_types.h"
-#include "DNA_scene_types.h"
-
-#include "BLI_utildefines.h"
-
-#include "BKE_global.h"
-#include "BKE_main.h"
-#include "BKE_DerivedMesh.h"
-
-#include "BL_BlenderShader.h"
-#include "BL_Material.h"
-
-#include "GPU_material.h"
-#include "GPU_shader.h"
-
-#include "RAS_BucketManager.h"
-#include "RAS_MeshObject.h"
-#include "RAS_IRasterizer.h"
-
-BL_BlenderShader::BL_BlenderShader(KX_Scene *scene, struct Material *ma, int lightlayer)
-:
- mMat(ma),
- mLightLayer(lightlayer),
- mGPUMat(NULL)
-{
- mBlenderScene = scene->GetBlenderScene();
- mAlphaBlend = GPU_BLEND_SOLID;
-
- ReloadMaterial();
-}
-
-BL_BlenderShader::~BL_BlenderShader()
-{
- if (mGPUMat)
- GPU_material_unbind(mGPUMat);
-}
-
-void BL_BlenderShader::ReloadMaterial()
-{
- mGPUMat = (mMat) ? GPU_material_from_blender(mBlenderScene, mMat, false) : NULL;
-}
-
-void BL_BlenderShader::SetProg(bool enable, double time, RAS_IRasterizer* rasty)
-{
- if (VerifyShader()) {
- if (enable) {
- assert(rasty != NULL); // XXX Kinda hacky, but SetProg() should always have the rasterizer if enable is true
-
- float viewmat[4][4], viewinvmat[4][4];
- const MT_Matrix4x4& view = rasty->GetViewMatrix();
- const MT_Matrix4x4& viewinv = rasty->GetViewInvMatrix();
- view.getValue(&viewmat[0][0]);
- viewinv.getValue(&viewinvmat[0][0]);
-
- GPU_material_bind(mGPUMat, mLightLayer, mBlenderScene->lay, time, 1, viewmat, viewinvmat, NULL);
- }
- else
- GPU_material_unbind(mGPUMat);
- }
-}
-
-int BL_BlenderShader::GetAttribNum()
-{
- GPUVertexAttribs attribs;
- int i, enabled = 0;
-
- if (!VerifyShader())
- return enabled;
-
- GPU_material_vertex_attributes(mGPUMat, &attribs);
-
- for (i = 0; i < attribs.totlayer; i++)
- if (attribs.layer[i].glindex+1 > enabled)
- enabled= attribs.layer[i].glindex+1;
-
- if (enabled > BL_MAX_ATTRIB)
- enabled = BL_MAX_ATTRIB;
-
- return enabled;
-}
-
-void BL_BlenderShader::SetAttribs(RAS_IRasterizer* ras, const BL_Material *mat)
-{
- GPUVertexAttribs attribs;
- GPUMaterial *gpumat;
- int i, attrib_num, uv = 0;
-
- ras->SetAttribNum(0);
-
- if (!VerifyShader())
- return;
-
- gpumat = mGPUMat;
- if (ras->GetDrawingMode() == RAS_IRasterizer::KX_TEXTURED || (ras->GetDrawingMode() == RAS_IRasterizer::KX_SHADOW &&
- mat->alphablend != GEMAT_SOLID && !ras->GetUsingOverrideShader())) {
- GPU_material_vertex_attributes(gpumat, &attribs);
- attrib_num = GetAttribNum();
-
- ras->SetTexCoordNum(0);
- ras->SetAttribNum(attrib_num);
- for (i = 0; i < attrib_num; i++)
- ras->SetAttrib(RAS_IRasterizer::RAS_TEXCO_DISABLE, i);
-
- for (i = 0; i < attribs.totlayer; i++) {
- if (attribs.layer[i].glindex > attrib_num)
- continue;
-
- if (attribs.layer[i].type == CD_MTFACE)
- ras->SetAttrib(RAS_IRasterizer::RAS_TEXCO_UV, attribs.layer[i].glindex, uv++);
- else if (attribs.layer[i].type == CD_TANGENT)
- ras->SetAttrib(RAS_IRasterizer::RAS_TEXTANGENT, attribs.layer[i].glindex);
- else if (attribs.layer[i].type == CD_ORCO)
- ras->SetAttrib(RAS_IRasterizer::RAS_TEXCO_ORCO, attribs.layer[i].glindex);
- else if (attribs.layer[i].type == CD_NORMAL)
- ras->SetAttrib(RAS_IRasterizer::RAS_TEXCO_NORM, attribs.layer[i].glindex);
- else if (attribs.layer[i].type == CD_MCOL)
- ras->SetAttrib(RAS_IRasterizer::RAS_TEXCO_VCOL, attribs.layer[i].glindex);
- else
- ras->SetAttrib(RAS_IRasterizer::RAS_TEXCO_DISABLE, attribs.layer[i].glindex);
- }
- }
-}
-
-void BL_BlenderShader::Update(const RAS_MeshSlot & ms, RAS_IRasterizer* rasty )
-{
- float obmat[4][4], viewmat[4][4], obcol[4];
- GPUMaterial *gpumat;
-
- gpumat = mGPUMat;
-
- if (!gpumat || !GPU_material_bound(gpumat))
- return;
-
- MT_Matrix4x4 model;
- model.setValue(ms.m_OpenGLMatrix);
-
- // note: getValue gives back column major as needed by OpenGL
- model.getValue(&obmat[0][0]);
-
- if (ms.m_bObjectColor)
- ms.m_RGBAcolor.getValue(&obcol[0]);
- else
- obcol[0] = obcol[1] = obcol[2] = obcol[3] = 1.0f;
-
- rasty->GetViewMatrix().getValue(&viewmat[0][0]);
- float auto_bump_scale = ms.m_pDerivedMesh!=0 ? ms.m_pDerivedMesh->auto_bump_scale : 1.0f;
- GPU_material_bind_uniforms(gpumat, obmat, viewmat, obcol, auto_bump_scale, NULL, NULL);
-
- mAlphaBlend = GPU_material_alpha_blend(gpumat, obcol);
-}
-
-int BL_BlenderShader::GetAlphaBlend()
-{
- return mAlphaBlend;
-}
-
-bool BL_BlenderShader::Equals(BL_BlenderShader *blshader)
-{
- /* to avoid unneeded state switches */
- return (blshader && mMat == blshader->mMat && mLightLayer == blshader->mLightLayer);
-}
-
-// eof
diff --git a/source/gameengine/Ketsji/BL_BlenderShader.h b/source/gameengine/Ketsji/BL_BlenderShader.h
deleted file mode 100644
index e03bb5a11d9..00000000000
--- a/source/gameengine/Ketsji/BL_BlenderShader.h
+++ /dev/null
@@ -1,96 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) Blender Foundation
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file BL_BlenderShader.h
- * \ingroup ketsji
- */
-
-#ifndef __BL_BLENDERSHADER_H__
-#define __BL_BLENDERSHADER_H__
-
-#include "GPU_material.h"
-
-#include "MT_Matrix4x4.h"
-#include "MT_Matrix3x3.h"
-#include "MT_Tuple2.h"
-#include "MT_Tuple3.h"
-#include "MT_Tuple4.h"
-
-#include "RAS_IPolygonMaterial.h"
-
-#include "KX_Scene.h"
-
-struct Material;
-struct Scene;
-class BL_Material;
-
-#define BL_MAX_ATTRIB 16
-
-/**
- * BL_BlenderShader
- * Blender GPU shader material
- */
-class BL_BlenderShader
-{
-private:
- struct Scene *mBlenderScene;
- struct Material *mMat;
- int mLightLayer;
- int mAlphaBlend;
- GPUMaterial *mGPUMat;
-
- bool VerifyShader()
- {
- return (NULL != mGPUMat);
- }
-
-public:
- BL_BlenderShader(KX_Scene *scene, struct Material *ma, int lightlayer);
- virtual ~BL_BlenderShader();
-
- bool Ok()
- {
- // same as VerifyShared
- return (NULL != mGPUMat);
- }
- void SetProg(bool enable, double time=0.0, RAS_IRasterizer* rasty=NULL);
-
- int GetAttribNum();
- void SetAttribs(class RAS_IRasterizer* ras, const BL_Material *mat);
- void Update(const class RAS_MeshSlot & ms, class RAS_IRasterizer* rasty);
- void ReloadMaterial();
- int GetAlphaBlend();
-
- bool Equals(BL_BlenderShader *blshader);
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:BL_BlenderShader")
-#endif
-};
-
-#endif /* __BL_BLENDERSHADER_H__ */
diff --git a/source/gameengine/Ketsji/BL_Material.cpp b/source/gameengine/Ketsji/BL_Material.cpp
deleted file mode 100644
index 40384b43054..00000000000
--- a/source/gameengine/Ketsji/BL_Material.cpp
+++ /dev/null
@@ -1,123 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Ketsji/BL_Material.cpp
- * \ingroup ketsji
- */
-
-#include "BL_Material.h"
-#include "DNA_material_types.h"
-#include "DNA_texture_types.h"
-#include "DNA_image_types.h"
-#include "DNA_mesh_types.h"
-#include "IMB_imbuf_types.h"
-#include "IMB_imbuf.h"
-
-MTex* getMTexFromMaterial(Material *mat, int index)
-{
- if (mat && (index >= 0) && (index < MAX_MTEX)) {
- return mat->mtex[index];
- }
- else {
- return NULL;
- }
-}
-
-BL_Material::BL_Material()
-{
- Initialize();
-}
-
-void BL_Material::Initialize()
-{
- rgb[0] = 0xFFFFFFFFL;
- rgb[1] = 0xFFFFFFFFL;
- rgb[2] = 0xFFFFFFFFL;
- rgb[3] = 0xFFFFFFFFL;
- IdMode = 0;
- ras_mode = 0;
- glslmat = 0;
- tile = 0;
- matname = "NoMaterial";
- matcolor[0] = 0.5f;
- matcolor[1] = 0.5f;
- matcolor[2] = 0.5f;
- matcolor[3] = 0.5f;
- speccolor[0] = 1.f;
- speccolor[1] = 1.f;
- speccolor[2] = 1.f;
- alphablend = 0;
- hard = 50.f;
- spec_f = 0.5f;
- alpha = 1.f;
- emit = 0.f;
- material = 0;
- materialindex = 0;
- amb=0.5f;
- num_enabled = 0;
- num_users = 1;
- share = false;
-
- int i;
-
- for (i = 0; i < MAXTEX; i++) // :(
- {
- mapping[i].mapping = 0;
- mapping[i].offsets[0] = 0.f;
- mapping[i].offsets[1] = 0.f;
- mapping[i].offsets[2] = 0.f;
- mapping[i].scale[0] = 1.f;
- mapping[i].scale[1] = 1.f;
- mapping[i].scale[2] = 1.f;
- mapping[i].projplane[0] = PROJX;
- mapping[i].projplane[1] = PROJY;
- mapping[i].projplane[2] = PROJZ;
- mapping[i].objconame = "";
- mtexname[i] = "NULL";
- imageId[i]="NULL";
- flag[i] = 0;
- texname[i] = "NULL";
- tilexrep[i] = 1;
- tileyrep[i] = 1;
- color_blend[i] = 1.f;
- blend_mode[i] = 0;
- img[i] = 0;
- cubemap[i] = 0;
- }
-}
-
-void BL_Material::SetSharedMaterial(bool v)
-{
- if ((v && num_users == -1) || num_users > 1 )
- share = true;
- else
- share = false;
-}
-
-bool BL_Material::IsShared()
-{
- return share;
-}
-
-void BL_Material::SetUsers(int num)
-{
- num_users = num;
-}
-
diff --git a/source/gameengine/Ketsji/BL_Material.h b/source/gameengine/Ketsji/BL_Material.h
deleted file mode 100644
index 710c02f4871..00000000000
--- a/source/gameengine/Ketsji/BL_Material.h
+++ /dev/null
@@ -1,182 +0,0 @@
-
-/** \file BL_Material.h
- * \ingroup ketsji
- */
-
-#ifndef __BL_MATERIAL_H__
-#define __BL_MATERIAL_H__
-
-#include "STR_String.h"
-#include "MT_Point2.h"
-#include "DNA_meshdata_types.h"
-
-#ifdef WITH_CXX_GUARDEDALLOC
-#include "MEM_guardedalloc.h"
-#endif
-
-// --
-struct MTex;
-struct Material;
-struct Image;
-struct MTFace;
-struct MTex;
-struct Material;
-struct EnvMap;
-// --
-
-/** max units
- * this will default to users available units
- * to build with more available, just increment this value
- * although the more you add the slower the search time will be.
- * we will go for eight, which should be enough
- */
-#define MAXTEX 8 //match in RAS_TexVert & RAS_OpenGLRasterizer
-
-// different mapping modes
-class BL_Mapping
-{
-public:
- int mapping;
- float scale[3];
- float offsets[3];
- int projplane[3];
- STR_String objconame;
- STR_String uvCoName;
-};
-
-// base material struct
-class BL_Material
-{
-private:
- int num_users;
- bool share;
-
-public:
- // -----------------------------------
- BL_Material();
- void Initialize();
-
- int IdMode;
- unsigned int ras_mode;
- bool glslmat;
-
- STR_String texname[MAXTEX];
- unsigned int flag[MAXTEX];
- int tile,tilexrep[MAXTEX],tileyrep[MAXTEX];
- STR_String matname;
- STR_String mtexname[MAXTEX];
- int materialindex;
-
- float matcolor[4];
- float speccolor[3];
- short alphablend, pad;
-
- float hard, spec_f;
- float alpha, emit, color_blend[MAXTEX], ref;
- float amb;
-
- int blend_mode[MAXTEX];
-
- int num_enabled;
-
- BL_Mapping mapping[MAXTEX];
- STR_String imageId[MAXTEX];
-
-
- Material* material;
- Image* img[MAXTEX];
- EnvMap* cubemap[MAXTEX];
-
- unsigned int rgb[4];
-
- void SetSharedMaterial(bool v);
- bool IsShared();
- void SetUsers(int num);
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:BL_Material")
-#endif
-};
-
-// BL_Material::IdMode
-enum BL_IdMode {
- DEFAULT_BLENDER=-1,
- TEXFACE,
- ONETEX,
- TWOTEX,
- GREATERTHAN2
-};
-
-// BL_Material::blend_mode[index]
-enum BL_BlendMode
-{
- BLEND_MIX=1,
- BLEND_ADD,
- BLEND_SUB,
- BLEND_MUL,
- BLEND_SCR
-};
-
-// -------------------------------------
-// BL_Material::flag[index]
-enum BL_flag
-{
- MIPMAP=1, // set to use mipmaps
- CALCALPHA=2, // additive
- USEALPHA=4, // use actual alpha channel
- TEXALPHA=8, // use alpha combiner functions
- TEXNEG=16, // negate blending
- /*HASIPO=32,*/ // unused, commeted for now.
- USENEGALPHA=64
-};
-
-// BL_Material::ras_mode
-enum BL_ras_mode
-{
- // POLY_VIS=1,
- COLLIDER=2,
- ZSORT=4,
- ALPHA=8,
- // TRIANGLE=16,
- USE_LIGHT=32,
- WIRE=64,
- CAST_SHADOW=128,
- TEX=256,
- TWOSIDED=512,
- ONLY_SHADOW=1024,
-};
-
-// -------------------------------------
-// BL_Material::mapping[index]::mapping
-enum BL_MappingFlag
-{
- USEENV =1,
- // --
- USEREFL =2,
- USEOBJ =4,
- USENORM =8,
- USEORCO =16,
- USEUV =32,
- USETANG =64,
- DISABLE =128,
- USECUSTOMUV=256
-};
-
-// BL_Material::BL_Mapping::projplane
-enum BL_MappingProj
-{
- PROJN=0,
- PROJX,
- PROJY,
- PROJZ
-};
-
-// ------------------------------------
-//extern void initBL_Material(BL_Material* mat);
-extern MTex* getMTexFromMaterial(Material *mat, int index);
-// ------------------------------------
-
-#endif
-
-
diff --git a/source/gameengine/Ketsji/BL_Shader.cpp b/source/gameengine/Ketsji/BL_Shader.cpp
deleted file mode 100644
index d344e18c313..00000000000
--- a/source/gameengine/Ketsji/BL_Shader.cpp
+++ /dev/null
@@ -1,1478 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Ketsji/BL_Shader.cpp
- * \ingroup ketsji
- */
-
-#include "GPU_glew.h"
-
-#include <iostream>
-#include "BL_Shader.h"
-#include "BL_Material.h"
-
-#include "MT_assert.h"
-#include "MT_Matrix4x4.h"
-#include "MT_Matrix3x3.h"
-#include "KX_PyMath.h"
-#include "KX_PythonInit.h"
-#include "MEM_guardedalloc.h"
-
-#include "RAS_MeshObject.h"
-#include "RAS_IRasterizer.h"
-
-#define spit(x) std::cout << x << std::endl;
-
-#define SORT_UNIFORMS 1
-#define UNIFORM_MAX_LEN (int)sizeof(float) * 16
-#define MAX_LOG_LEN 262144 // bounds
-
-BL_Uniform::BL_Uniform(int data_size)
- :
- mLoc(-1),
- mDirty(true),
- mType(UNI_NONE),
- mTranspose(0),
- mDataLen(data_size)
-{
-#ifdef SORT_UNIFORMS
- MT_assert((int)mDataLen <= UNIFORM_MAX_LEN);
- mData = (void *)MEM_mallocN(mDataLen, "shader-uniform-alloc");
-#endif
-}
-
-BL_Uniform::~BL_Uniform()
-{
-#ifdef SORT_UNIFORMS
- if (mData) {
- MEM_freeN(mData);
- mData = NULL;
- }
-#endif
-}
-
-bool BL_Uniform::Apply(class BL_Shader *shader)
-{
-#ifdef SORT_UNIFORMS
- RAS_IRasterizer *ras;
- MT_assert(mType > UNI_NONE && mType < UNI_MAX && mData);
-
- if (!mDirty)
- return false;
-
- mDirty = false;
- switch (mType) {
- case UNI_FLOAT:
- {
- float *f = (float *)mData;
- glUniform1fARB(mLoc, (GLfloat)*f);
- break;
- }
- case UNI_FLOAT_EYE:
- {
- float *f = (float*)mData;
- ras = KX_GetActiveEngine()->GetRasterizer();
- *f = (ras->GetEye() == RAS_IRasterizer::RAS_STEREO_LEFTEYE) ? 0.0f : 0.5f;
- glUniform1fARB(mLoc, (GLfloat)*f);
- mDirty = (ras->Stereo()) ? true : false;
- break;
- }
- case UNI_INT:
- {
- int *f = (int *)mData;
- glUniform1iARB(mLoc, (GLint)*f);
- break;
- }
- case UNI_FLOAT2:
- {
- float *f = (float *)mData;
- glUniform2fvARB(mLoc, 1, (GLfloat *)f);
- break;
- }
- case UNI_FLOAT3:
- {
- float *f = (float *)mData;
- glUniform3fvARB(mLoc, 1, (GLfloat *)f);
- break;
- }
- case UNI_FLOAT4:
- {
- float *f = (float *)mData;
- glUniform4fvARB(mLoc, 1, (GLfloat *)f);
- break;
- }
- case UNI_INT2:
- {
- int *f = (int *)mData;
- glUniform2ivARB(mLoc, 1, (GLint *)f);
- break;
- }
- case UNI_INT3:
- {
- int *f = (int *)mData;
- glUniform3ivARB(mLoc, 1, (GLint *)f);
- break;
- }
- case UNI_INT4:
- {
- int *f = (int *)mData;
- glUniform4ivARB(mLoc, 1, (GLint *)f);
- break;
- }
- case UNI_MAT4:
- {
- float *f = (float *)mData;
- glUniformMatrix4fvARB(mLoc, 1, mTranspose ? GL_TRUE : GL_FALSE, (GLfloat *)f);
- break;
- }
- case UNI_MAT3:
- {
- float *f = (float *)mData;
- glUniformMatrix3fvARB(mLoc, 1, mTranspose ? GL_TRUE : GL_FALSE, (GLfloat *)f);
- break;
- }
- }
- return mDirty;
-#endif
-}
-
-void BL_Uniform::SetData(int location, int type, bool transpose)
-{
-#ifdef SORT_UNIFORMS
- mType = type;
- mLoc = location;
- mDirty = true;
-#endif
-}
-
-bool BL_Shader::Ok()const
-{
- return (mShader != 0 && mOk && mUse);
-}
-
-BL_Shader::BL_Shader()
- :
- PyObjectPlus(),
- mShader(0),
- mPass(1),
- mOk(0),
- mUse(0),
- mAttr(0),
- vertProg(NULL),
- fragProg(NULL),
- mError(0),
- mDirty(true)
-{
- // if !GLEW_ARB_shader_objects this class will not be used
- //for (int i=0; i<MAXTEX; i++) {
- // mSampler[i] = BL_Sampler();
- //}
-}
-
-BL_Shader::~BL_Shader()
-{
- //for (int i=0; i<MAXTEX; i++) {
- // if (mSampler[i].mOwn) {
- // if (mSampler[i].mTexture)
- // mSampler[i].mTexture->DeleteTex();
- // }
- //}
- ClearUniforms();
-
- if (mShader) {
- glDeleteObjectARB(mShader);
- mShader = 0;
- }
-
- vertProg = NULL;
- fragProg = NULL;
- mOk = 0;
- glUseProgramObjectARB(0);
-}
-
-void BL_Shader::ClearUniforms()
-{
- BL_UniformVec::iterator it = mUniforms.begin();
- while (it != mUniforms.end()) {
- delete *it;
- it++;
- }
- mUniforms.clear();
-
- BL_UniformVecDef::iterator itp = mPreDef.begin();
- while (itp != mPreDef.end()) {
- delete *itp;
- itp++;
- }
- mPreDef.clear();
-}
-
-BL_Uniform *BL_Shader::FindUniform(const int location)
-{
-#ifdef SORT_UNIFORMS
- BL_UniformVec::iterator it = mUniforms.begin();
- while (it != mUniforms.end()) {
- if ((*it)->GetLocation() == location) {
- return *it;
- }
- it++;
- }
-#endif
- return NULL;
-}
-
-void BL_Shader::SetUniformfv(int location, int type, float *param, int size, bool transpose)
-{
-#ifdef SORT_UNIFORMS
- BL_Uniform *uni = FindUniform(location);
-
- if (uni) {
- memcpy(uni->getData(), param, size);
- uni->SetData(location, type, transpose);
- }
- else {
- uni = new BL_Uniform(size);
- memcpy(uni->getData(), param, size);
- uni->SetData(location, type, transpose);
- mUniforms.push_back(uni);
- }
-
- mDirty = true;
-#endif
-}
-
-void BL_Shader::SetUniformiv(int location, int type, int *param, int size, bool transpose)
-{
-#ifdef SORT_UNIFORMS
- BL_Uniform *uni = FindUniform(location);
-
- if (uni) {
- memcpy(uni->getData(), param, size);
- uni->SetData(location, type, transpose);
- }
- else {
- uni = new BL_Uniform(size);
- memcpy(uni->getData(), param, size);
- uni->SetData(location, type, transpose);
- mUniforms.push_back(uni);
- }
-
- mDirty = true;
-#endif
-}
-
-void BL_Shader::ApplyShader()
-{
-#ifdef SORT_UNIFORMS
- if (!mDirty) {
- return;
- }
-
- mDirty = false;
- for (unsigned int i=0; i<mUniforms.size(); i++) {
- mDirty |= mUniforms[i]->Apply(this);
- }
-#endif
-}
-
-void BL_Shader::UnloadShader()
-{
- //
-}
-
-bool BL_Shader::LinkProgram()
-{
- int vertlen = 0, fraglen = 0, proglen = 0;
- int vertstatus = 0, fragstatus = 0, progstatus = 0;
- unsigned int tmpVert = 0, tmpFrag = 0, tmpProg = 0;
- int char_len = 0;
- char *logInf = NULL;
-
- if (mError) {
- goto programError;
- }
-
- if (!vertProg || !fragProg) {
- spit("Invalid GLSL sources");
- return false;
- }
-
- if (!GLEW_ARB_fragment_shader) {
- spit("Fragment shaders not supported");
- return false;
- }
-
- if (!GLEW_ARB_vertex_shader) {
- spit("Vertex shaders not supported");
- return false;
- }
-
- if (vertProg[0] != 0) {
- // -- vertex shader ------------------
- tmpVert = glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB);
- glShaderSourceARB(tmpVert, 1, (const char**)&vertProg, 0);
- glCompileShaderARB(tmpVert);
- glGetObjectParameterivARB(tmpVert, GL_OBJECT_INFO_LOG_LENGTH_ARB, (GLint*)&vertlen);
-
- // print info if any
- if (vertlen > 0 && vertlen < MAX_LOG_LEN) {
- logInf = (char*)MEM_mallocN(vertlen, "vert-log");
- glGetInfoLogARB(tmpVert, vertlen, (GLsizei*)&char_len, logInf);
- if (char_len > 0) {
- spit("---- Vertex Shader Error ----");
- spit(logInf);
- }
- MEM_freeN(logInf);
- logInf = 0;
- }
- // check for compile errors
- glGetObjectParameterivARB(tmpVert, GL_OBJECT_COMPILE_STATUS_ARB, (GLint*)&vertstatus);
- if (!vertstatus) {
- spit("---- Vertex shader failed to compile ----");
- goto programError;
- }
- }
-
- if (fragProg[0] != 0) {
- // -- fragment shader ----------------
- tmpFrag = glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB);
- glShaderSourceARB(tmpFrag, 1, (const char**)&fragProg, 0);
- glCompileShaderARB(tmpFrag);
- glGetObjectParameterivARB(tmpFrag, GL_OBJECT_INFO_LOG_LENGTH_ARB, (GLint*)&fraglen);
- if (fraglen > 0 && fraglen < MAX_LOG_LEN) {
- logInf = (char*)MEM_mallocN(fraglen, "frag-log");
- glGetInfoLogARB(tmpFrag, fraglen, (GLsizei*)&char_len, logInf);
- if (char_len > 0) {
- spit("---- Fragment Shader Error ----");
- spit(logInf);
- }
- MEM_freeN(logInf);
- logInf = 0;
- }
-
- glGetObjectParameterivARB(tmpFrag, GL_OBJECT_COMPILE_STATUS_ARB, (GLint*)&fragstatus);
- if (!fragstatus) {
- spit("---- Fragment shader failed to compile ----");
- goto programError;
- }
- }
-
- if (!tmpFrag && !tmpVert) {
- spit("---- No shader given ----");
- goto programError;
- }
-
- // -- program ------------------------
- // set compiled vert/frag shader & link
- tmpProg = glCreateProgramObjectARB();
- if (tmpVert) {
- glAttachObjectARB(tmpProg, tmpVert);
- }
- if (tmpFrag) {
- glAttachObjectARB(tmpProg, tmpFrag);
- }
- glLinkProgramARB(tmpProg);
- glGetObjectParameterivARB(tmpProg, GL_OBJECT_INFO_LOG_LENGTH_ARB, (GLint *)&proglen);
- glGetObjectParameterivARB(tmpProg, GL_OBJECT_LINK_STATUS_ARB, (GLint *)&progstatus);
-
- if (proglen > 0 && proglen < MAX_LOG_LEN) {
- logInf = (char *)MEM_mallocN(proglen, "prog-log");
- glGetInfoLogARB(tmpProg, proglen, (GLsizei *)&char_len, logInf);
-
- if (char_len > 0) {
- spit("---- GLSL Program ----");
- spit(logInf);
- }
-
- MEM_freeN(logInf);
- logInf = 0;
- }
-
- if (!progstatus) {
- spit("---- GLSL program failed to link ----");
- goto programError;
- }
-
- // set
- mShader = tmpProg;
- if (tmpVert) {
- glDeleteObjectARB(tmpVert);
- }
- if (tmpFrag) {
- glDeleteObjectARB(tmpFrag);
- }
- mOk = 1;
- mError = 0;
- return true;
-
-programError:
- if (tmpVert) {
- glDeleteObjectARB(tmpVert);
- tmpVert = 0;
- }
-
- if (tmpFrag) {
- glDeleteObjectARB(tmpFrag);
- tmpFrag = 0;
- }
-
- if (tmpProg) {
- glDeleteObjectARB(tmpProg);
- tmpProg = 0;
- }
-
- mOk = 0;
- mUse = 0;
- mError = 1;
- return false;
-}
-
-const char *BL_Shader::GetVertPtr()
-{
- return vertProg ? vertProg : NULL;
-}
-
-const char *BL_Shader::GetFragPtr()
-{
- return fragProg ? fragProg : NULL;
-}
-
-void BL_Shader::SetVertPtr(char *vert)
-{
- vertProg = vert;
-}
-
-void BL_Shader::SetFragPtr(char *frag)
-{
- fragProg = frag;
-}
-
-unsigned int BL_Shader::GetProg()
-{
- return mShader;
-}
-
-//const BL_Sampler *BL_Shader::GetSampler(int i)
-//{
-// MT_assert(i<=MAXTEX);
-// return &mSampler[i];
-//}
-
-void BL_Shader::SetSampler(int loc, int unit)
-{
- if (GLEW_ARB_fragment_shader && GLEW_ARB_vertex_shader && GLEW_ARB_shader_objects) {
- glUniform1iARB(loc, unit);
- }
-}
-
-//void BL_Shader::InitializeSampler(int unit, BL_Texture *texture)
-//{
-// MT_assert(unit <= MAXTEX);
-// mSampler[unit].mTexture = texture;
-// mSampler[unit].mLoc = -1;
-// mSampler[unit].mOwn = 0;
-//}
-
-void BL_Shader::SetProg(bool enable)
-{
- if (GLEW_ARB_fragment_shader && GLEW_ARB_vertex_shader && GLEW_ARB_shader_objects) {
- if (mShader != 0 && mOk && enable) {
- glUseProgramObjectARB(mShader);
- }
- else {
- glUseProgramObjectARB(0);
- }
- }
-}
-
-void BL_Shader::Update(const RAS_MeshSlot &ms, RAS_IRasterizer *rasty)
-{
- if (!Ok() || !mPreDef.size()) {
- return;
- }
-
- if (GLEW_ARB_fragment_shader && GLEW_ARB_vertex_shader && GLEW_ARB_shader_objects) {
- MT_Matrix4x4 model;
- model.setValue(ms.m_OpenGLMatrix);
- const MT_Matrix4x4 &view = rasty->GetViewMatrix();
-
- if (mAttr == SHD_TANGENT) {
- ms.m_mesh->SetMeshModified(true);
- }
-
- BL_UniformVecDef::iterator it;
- for (it = mPreDef.begin(); it != mPreDef.end(); it++) {
- BL_DefUniform *uni = (*it);
-
- if (uni->mLoc == -1) {
- continue;
- }
-
- switch (uni->mType) {
- case MODELMATRIX:
- {
- SetUniform(uni->mLoc, model);
- break;
- }
- case MODELMATRIX_TRANSPOSE:
- {
- SetUniform(uni->mLoc, model, true);
- break;
- }
- case MODELMATRIX_INVERSE:
- {
- model.invert();
- SetUniform(uni->mLoc, model);
- break;
- }
- case MODELMATRIX_INVERSETRANSPOSE:
- {
- model.invert();
- SetUniform(uni->mLoc, model, true);
- break;
- }
- case MODELVIEWMATRIX:
- {
- SetUniform(uni->mLoc, view * model);
- break;
- }
- case MODELVIEWMATRIX_TRANSPOSE:
- {
- MT_Matrix4x4 mat(view * model);
- SetUniform(uni->mLoc, mat, true);
- break;
- }
- case MODELVIEWMATRIX_INVERSE:
- {
- MT_Matrix4x4 mat(view * model);
- mat.invert();
- SetUniform(uni->mLoc, mat);
- break;
- }
- case MODELVIEWMATRIX_INVERSETRANSPOSE:
- {
- MT_Matrix4x4 mat(view * model);
- mat.invert();
- SetUniform(uni->mLoc, mat, true);
- break;
- }
- case CAM_POS:
- {
- MT_Point3 pos(rasty->GetCameraPosition());
- SetUniform(uni->mLoc, pos);
- break;
- }
- case VIEWMATRIX:
- {
- SetUniform(uni->mLoc, view);
- break;
- }
- case VIEWMATRIX_TRANSPOSE:
- {
- SetUniform(uni->mLoc, view, true);
- break;
- }
- case VIEWMATRIX_INVERSE:
- {
- MT_Matrix4x4 viewinv = view;
- viewinv.invert();
- SetUniform(uni->mLoc, view);
- break;
- }
- case VIEWMATRIX_INVERSETRANSPOSE:
- {
- MT_Matrix4x4 viewinv = view;
- viewinv.invert();
- SetUniform(uni->mLoc, view, true);
- break;
- }
- case CONSTANT_TIMER:
- {
- SetUniform(uni->mLoc, (float)rasty->GetTime());
- break;
- }
- default:
- break;
- }
- }
- }
-}
-
-int BL_Shader::GetAttribLocation(const char *name)
-{
- if (GLEW_ARB_fragment_shader && GLEW_ARB_vertex_shader && GLEW_ARB_shader_objects) {
- return glGetAttribLocationARB(mShader, name);
- }
-
- return -1;
-}
-
-void BL_Shader::BindAttribute(const char *attr, int loc)
-{
- if (GLEW_ARB_fragment_shader && GLEW_ARB_vertex_shader && GLEW_ARB_shader_objects) {
- glBindAttribLocationARB(mShader, loc, attr);
- }
-}
-
-int BL_Shader::GetUniformLocation(const char *name)
-{
- if (GLEW_ARB_fragment_shader && GLEW_ARB_vertex_shader && GLEW_ARB_shader_objects) {
- MT_assert(mShader != 0);
- int location = glGetUniformLocationARB(mShader, name);
-
- if (location == -1) {
- spit("Invalid uniform value: " << name << ".");
- }
-
- return location;
- }
- return -1;
-}
-
-void BL_Shader::SetUniform(int uniform, const MT_Tuple2 &vec)
-{
- if (GLEW_ARB_fragment_shader && GLEW_ARB_vertex_shader && GLEW_ARB_shader_objects) {
- float value[2];
- vec.getValue(value);
- glUniform2fvARB(uniform, 1, value);
- }
-}
-
-void BL_Shader::SetUniform(int uniform, const MT_Tuple3 &vec)
-{
- if (GLEW_ARB_fragment_shader && GLEW_ARB_vertex_shader && GLEW_ARB_shader_objects) {
- float value[3];
- vec.getValue(value);
- glUniform3fvARB(uniform, 1, value);
- }
-}
-
-void BL_Shader::SetUniform(int uniform, const MT_Tuple4 &vec)
-{
- if (GLEW_ARB_fragment_shader && GLEW_ARB_vertex_shader && GLEW_ARB_shader_objects) {
- float value[4];
- vec.getValue(value);
- glUniform4fvARB(uniform, 1, value);
- }
-}
-
-void BL_Shader::SetUniform(int uniform, const unsigned int &val)
-{
- if (GLEW_ARB_fragment_shader && GLEW_ARB_vertex_shader && GLEW_ARB_shader_objects) {
- glUniform1iARB(uniform, val);
- }
-}
-
-void BL_Shader::SetUniform(int uniform, const int val)
-{
- if (GLEW_ARB_fragment_shader && GLEW_ARB_vertex_shader && GLEW_ARB_shader_objects) {
- glUniform1iARB(uniform, val);
- }
-}
-
-void BL_Shader::SetUniform(int uniform, const float &val)
-{
- if (GLEW_ARB_fragment_shader && GLEW_ARB_vertex_shader && GLEW_ARB_shader_objects) {
- glUniform1fARB(uniform, val);
- }
-}
-
-void BL_Shader::SetUniform(int uniform, const MT_Matrix4x4 &vec, bool transpose)
-{
- if (GLEW_ARB_fragment_shader && GLEW_ARB_vertex_shader && GLEW_ARB_shader_objects) {
- float value[16];
- // note: getValue gives back column major as needed by OpenGL
- vec.getValue(value);
- glUniformMatrix4fvARB(uniform, 1, transpose ? GL_TRUE : GL_FALSE, value);
- }
-}
-
-void BL_Shader::SetUniform(int uniform, const MT_Matrix3x3 &vec, bool transpose)
-{
- if (GLEW_ARB_fragment_shader && GLEW_ARB_vertex_shader && GLEW_ARB_shader_objects) {
- float value[9];
- value[0] = (float)vec[0][0];
- value[1] = (float)vec[1][0];
- value[2] = (float)vec[2][0];
- value[3] = (float)vec[0][1];
- value[4] = (float)vec[1][1];
- value[5] = (float)vec[2][1];
- value[6] = (float)vec[0][2];
- value[7] = (float)vec[1][2];
- value[8] = (float)vec[2][2];
- glUniformMatrix3fvARB(uniform, 1, transpose ? GL_TRUE : GL_FALSE, value);
- }
-}
-
-void BL_Shader::SetUniform(int uniform, const float *val, int len)
-{
- if (GLEW_ARB_fragment_shader && GLEW_ARB_vertex_shader && GLEW_ARB_shader_objects) {
- if (len == 2) {
- glUniform2fvARB(uniform, 1, (GLfloat *)val);
- }
- else if (len == 3) {
- glUniform3fvARB(uniform, 1, (GLfloat *)val);
- }
- else if (len == 4) {
- glUniform4fvARB(uniform, 1, (GLfloat *)val);
- }
- else {
- MT_assert(0);
- }
- }
-}
-
-void BL_Shader::SetUniform(int uniform, const int *val, int len)
-{
- if (GLEW_ARB_fragment_shader && GLEW_ARB_vertex_shader && GLEW_ARB_shader_objects) {
- if (len == 2) {
- glUniform2ivARB(uniform, 1, (GLint *)val);
- }
- else if (len == 3) {
- glUniform3ivARB(uniform, 1, (GLint *)val);
- }
- else if (len == 4) {
- glUniform4ivARB(uniform, 1, (GLint *)val);
- }
- else {
- MT_assert(0);
- }
- }
-}
-
-#ifdef WITH_PYTHON
-PyMethodDef BL_Shader::Methods[] = {
- // creation
- KX_PYMETHODTABLE(BL_Shader, setSource),
- KX_PYMETHODTABLE(BL_Shader, delSource),
- KX_PYMETHODTABLE(BL_Shader, getVertexProg),
- KX_PYMETHODTABLE(BL_Shader, getFragmentProg),
- KX_PYMETHODTABLE(BL_Shader, setNumberOfPasses),
- KX_PYMETHODTABLE(BL_Shader, validate),
- // access functions
- KX_PYMETHODTABLE(BL_Shader, isValid),
- KX_PYMETHODTABLE(BL_Shader, setUniformEyef),
- KX_PYMETHODTABLE(BL_Shader, setUniform1f),
- KX_PYMETHODTABLE(BL_Shader, setUniform2f),
- KX_PYMETHODTABLE(BL_Shader, setUniform3f),
- KX_PYMETHODTABLE(BL_Shader, setUniform4f),
- KX_PYMETHODTABLE(BL_Shader, setUniform1i),
- KX_PYMETHODTABLE(BL_Shader, setUniform2i),
- KX_PYMETHODTABLE(BL_Shader, setUniform3i),
- KX_PYMETHODTABLE(BL_Shader, setUniform4i),
- KX_PYMETHODTABLE(BL_Shader, setAttrib),
- KX_PYMETHODTABLE(BL_Shader, setUniformfv),
- KX_PYMETHODTABLE(BL_Shader, setUniformiv),
- KX_PYMETHODTABLE(BL_Shader, setUniformDef),
- KX_PYMETHODTABLE(BL_Shader, setSampler),
- KX_PYMETHODTABLE(BL_Shader, setUniformMatrix4),
- KX_PYMETHODTABLE(BL_Shader, setUniformMatrix3),
- {NULL, NULL} //Sentinel
-};
-
-PyAttributeDef BL_Shader::Attributes[] = {
- {NULL} //Sentinel
-};
-
-PyTypeObject BL_Shader::Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "BL_Shader",
- sizeof(PyObjectPlus_Proxy),
- 0,
- py_base_dealloc,
- 0,
- 0,
- 0,
- 0,
- py_base_repr,
- 0, 0, 0, 0, 0, 0, 0, 0, 0,
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
- 0, 0, 0, 0, 0, 0, 0,
- Methods,
- 0,
- 0,
- &PyObjectPlus::Type,
- 0, 0, 0, 0, 0, 0,
- py_base_new
-};
-
-KX_PYMETHODDEF_DOC(BL_Shader, setSource, " setSource(vertexProgram, fragmentProgram)")
-{
- if (mShader != 0 && mOk) {
- // already set...
- Py_RETURN_NONE;
- }
-
- char *v, *f;
- int apply = 0;
-
- if (PyArg_ParseTuple(args, "ssi:setSource", &v, &f, &apply)) {
- vertProg = v;
- fragProg = f;
-
- if (LinkProgram()) {
- glUseProgramObjectARB(mShader);
- mUse = apply != 0;
- Py_RETURN_NONE;
- }
-
- vertProg = NULL;
- fragProg = NULL;
- mUse = 0;
- Py_RETURN_NONE;
- }
- return NULL;
-}
-
-
-KX_PYMETHODDEF_DOC(BL_Shader, delSource, "delSource( )")
-{
- ClearUniforms();
- glUseProgramObjectARB(0);
- glDeleteObjectARB(mShader);
- mShader = 0;
- mOk = 0;
- mUse = 0;
- Py_RETURN_NONE;
-}
-
-KX_PYMETHODDEF_DOC(BL_Shader, isValid, "isValid()")
-{
- return PyBool_FromLong((mShader != 0 && mOk));
-}
-
-KX_PYMETHODDEF_DOC(BL_Shader, getVertexProg, "getVertexProg( )")
-{
- return PyUnicode_FromString(vertProg ? vertProg : "");
-}
-
-KX_PYMETHODDEF_DOC(BL_Shader, getFragmentProg, "getFragmentProg( )")
-{
- return PyUnicode_FromString(fragProg ? fragProg : "");
-}
-
-KX_PYMETHODDEF_DOC(BL_Shader, validate, "validate()")
-{
- if (mError) {
- Py_RETURN_NONE;
- }
-
- if (mShader == 0) {
- PyErr_SetString(PyExc_TypeError, "shader.validate(): BL_Shader, invalid shader object");
- return NULL;
- }
-
- int stat = 0;
- glValidateProgramARB(mShader);
- glGetObjectParameterivARB(mShader, GL_OBJECT_VALIDATE_STATUS_ARB, (GLint *)&stat);
-
- if (stat > 0 && stat < MAX_LOG_LEN) {
- int char_len = 0;
- char *logInf = (char *)MEM_mallocN(stat, "validate-log");
-
- glGetInfoLogARB(mShader, stat, (GLsizei *)&char_len, logInf);
-
- if (char_len > 0) {
- spit("---- GLSL Validation ----");
- spit(logInf);
- }
- MEM_freeN(logInf);
- logInf = NULL;
- }
- Py_RETURN_NONE;
-}
-
-
-KX_PYMETHODDEF_DOC(BL_Shader, setSampler, "setSampler(name, index)")
-{
- if (mError) {
- Py_RETURN_NONE;
- }
-
- const char *uniform;
- int index = -1;
-
- if (PyArg_ParseTuple(args, "si:setSampler", &uniform, &index)) {
- int loc = GetUniformLocation(uniform);
-
- if (loc != -1) {
- if (index >= MAXTEX || index < 0) {
- spit("Invalid texture sample index: " << index);
- }
-#ifdef SORT_UNIFORMS
- SetUniformiv(loc, BL_Uniform::UNI_INT, &index, (sizeof(int)));
-#else
- SetUniform(loc, index);
-#endif
- //if (index <= MAXTEX)
- // mSampler[index].mLoc = loc;
- //else
- // spit("Invalid texture sample index: " << index);
- }
- Py_RETURN_NONE;
- }
- return NULL;
-}
-
-KX_PYMETHODDEF_DOC(BL_Shader, setNumberOfPasses, "setNumberOfPasses( max-pass )")
-{
- int pass = 1;
-
- if (!PyArg_ParseTuple(args, "i:setNumberOfPasses", &pass)) {
- return NULL;
- }
-
- mPass = 1;
- Py_RETURN_NONE;
-}
-
-/// access functions
-KX_PYMETHODDEF_DOC(BL_Shader, setUniform1f, "setUniform1f(name, fx)")
-{
- if (mError) {
- Py_RETURN_NONE;
- }
-
- const char *uniform;
- float value = 0.0f;
-
- if (PyArg_ParseTuple(args, "sf:setUniform1f", &uniform, &value)) {
- int loc = GetUniformLocation(uniform);
-
- if (loc != -1) {
-#ifdef SORT_UNIFORMS
- SetUniformfv(loc, BL_Uniform::UNI_FLOAT, &value, sizeof(float));
-#else
- SetUniform(loc, (float)value);
-#endif
- }
- Py_RETURN_NONE;
- }
- return NULL;
-}
-
-KX_PYMETHODDEF_DOC(BL_Shader, setUniform2f, "setUniform2f(name, fx, fy)")
-{
- if (mError) {
- Py_RETURN_NONE;
- }
-
- const char *uniform;
- float array[2] = {0.0f, 0.0f};
-
- if (PyArg_ParseTuple(args, "sff:setUniform2f", &uniform, &array[0], &array[1])) {
- int loc = GetUniformLocation(uniform);
-
- if (loc != -1) {
-#ifdef SORT_UNIFORMS
- SetUniformfv(loc, BL_Uniform::UNI_FLOAT2, array, (sizeof(float) * 2));
-#else
- SetUniform(loc, array, 2);
-#endif
- }
- Py_RETURN_NONE;
- }
- return NULL;
-}
-
-KX_PYMETHODDEF_DOC(BL_Shader, setUniform3f, "setUniform3f(name, fx,fy,fz) ")
-{
- if (mError) {
- Py_RETURN_NONE;
- }
-
- const char *uniform;
- float array[3] = {0.0f, 0.0f, 0.0f};
-
- if (PyArg_ParseTuple(args, "sfff:setUniform3f", &uniform, &array[0], &array[1], &array[2])) {
- int loc = GetUniformLocation(uniform);
-
- if (loc != -1) {
-#ifdef SORT_UNIFORMS
- SetUniformfv(loc, BL_Uniform::UNI_FLOAT3, array, (sizeof(float) * 3));
-#else
- SetUniform(loc, array, 3);
-#endif
- }
- Py_RETURN_NONE;
- }
- return NULL;
-}
-
-KX_PYMETHODDEF_DOC(BL_Shader, setUniform4f, "setUniform4f(name, fx,fy,fz, fw) ")
-{
- if (mError) {
- Py_RETURN_NONE;
- }
-
- const char *uniform;
- float array[4] = {0.0f, 0.0f, 0.0f, 0.0f};
-
- if (PyArg_ParseTuple(args, "sffff:setUniform4f", &uniform, &array[0], &array[1], &array[2], &array[3])) {
- int loc = GetUniformLocation(uniform);
-
- if (loc != -1) {
-#ifdef SORT_UNIFORMS
- SetUniformfv(loc, BL_Uniform::UNI_FLOAT4, array, (sizeof(float) * 4));
-#else
- SetUniform(loc, array, 4);
-#endif
- }
- Py_RETURN_NONE;
- }
- return NULL;
-}
-
-KX_PYMETHODDEF_DOC(BL_Shader, setUniformEyef, "setUniformEyef(name)")
-{
- if (mError) {
- Py_RETURN_NONE;
- }
- const char *uniform;
- float value = 0.0f;
- if (PyArg_ParseTuple(args, "s:setUniformEyef", &uniform)) {
- int loc = GetUniformLocation(uniform);
- if (loc != -1) {
-#ifdef SORT_UNIFORMS
- SetUniformfv(loc, BL_Uniform::UNI_FLOAT_EYE, &value, sizeof(float));
-#else
- SetUniform(loc, (int)value);
-#endif
- }
- Py_RETURN_NONE;
- }
- return NULL;
-}
-
-KX_PYMETHODDEF_DOC(BL_Shader, setUniform1i, "setUniform1i(name, ix)")
-{
- if (mError) {
- Py_RETURN_NONE;
- }
-
- const char *uniform;
- int value = 0;
-
- if (PyArg_ParseTuple(args, "si:setUniform1i", &uniform, &value)) {
- int loc = GetUniformLocation(uniform);
-
- if (loc != -1) {
-#ifdef SORT_UNIFORMS
- SetUniformiv(loc, BL_Uniform::UNI_INT, &value, sizeof(int));
-#else
- SetUniform(loc, (int)value);
-#endif
- }
- Py_RETURN_NONE;
- }
- return NULL;
-}
-
-KX_PYMETHODDEF_DOC(BL_Shader, setUniform2i, "setUniform2i(name, ix, iy)")
-{
- if (mError) {
- Py_RETURN_NONE;
- }
-
- const char *uniform;
- int array[2] = {0, 0};
-
- if (PyArg_ParseTuple(args, "sii:setUniform2i", &uniform, &array[0], &array[1])) {
- int loc = GetUniformLocation(uniform);
-
- if (loc != -1) {
-#ifdef SORT_UNIFORMS
- SetUniformiv(loc, BL_Uniform::UNI_INT2, array, sizeof(int) * 2);
-#else
- SetUniform(loc, array, 2);
-#endif
- }
- Py_RETURN_NONE;
- }
- return NULL;
-}
-
-KX_PYMETHODDEF_DOC(BL_Shader, setUniform3i, "setUniform3i(name, ix,iy,iz) ")
-{
- if (mError) {
- Py_RETURN_NONE;
- }
-
- const char *uniform;
- int array[3] = {0, 0, 0};
-
- if (PyArg_ParseTuple(args, "siii:setUniform3i", &uniform, &array[0], &array[1], &array[2])) {
- int loc = GetUniformLocation(uniform);
-
- if (loc != -1) {
-#ifdef SORT_UNIFORMS
- SetUniformiv(loc, BL_Uniform::UNI_INT3, array, sizeof(int) * 3);
-#else
- SetUniform(loc, array, 3);
-#endif
- }
- Py_RETURN_NONE;
- }
- return NULL;
-}
-
-KX_PYMETHODDEF_DOC(BL_Shader, setUniform4i, "setUniform4i(name, ix,iy,iz, iw) ")
-{
- if (mError) {
- Py_RETURN_NONE;
- }
-
- const char *uniform;
- int array[4] = {0, 0, 0, 0};
-
- if (PyArg_ParseTuple(args, "siiii:setUniform4i", &uniform, &array[0], &array[1], &array[2], &array[3])) {
- int loc = GetUniformLocation(uniform);
-
- if (loc != -1) {
-#ifdef SORT_UNIFORMS
- SetUniformiv(loc, BL_Uniform::UNI_INT4, array, sizeof(int) * 4);
-#else
- SetUniform(loc, array, 4);
-#endif
- }
- Py_RETURN_NONE;
- }
- return NULL;
-}
-
-KX_PYMETHODDEF_DOC(BL_Shader, setUniformfv, "setUniformfv(float (list2 or list3 or list4))")
-{
- if (mError) {
- Py_RETURN_NONE;
- }
-
- const char *uniform = "";
- PyObject *listPtr = NULL;
- float array_data[4] = {0.0f, 0.0f, 0.0f, 0.0f};
-
- if (PyArg_ParseTuple(args, "sO:setUniformfv", &uniform, &listPtr)) {
- int loc = GetUniformLocation(uniform);
- if (loc != -1) {
- if (PySequence_Check(listPtr)) {
- unsigned int list_size = PySequence_Size(listPtr);
-
- for (unsigned int i = 0; (i < list_size && i < 4); i++) {
- PyObject *item = PySequence_GetItem(listPtr, i);
- array_data[i] = (float)PyFloat_AsDouble(item);
- Py_DECREF(item);
- }
-
- switch (list_size) {
- case 2:
- {
- float array2[2] = {array_data[0], array_data[1]};
-#ifdef SORT_UNIFORMS
- SetUniformfv(loc, BL_Uniform::UNI_FLOAT2, array2, sizeof(float) * 2);
-#else
- SetUniform(loc, array2, 2);
-#endif
- Py_RETURN_NONE;
- break;
- }
- case 3:
- {
- float array3[3] = {array_data[0], array_data[1], array_data[2]};
-#ifdef SORT_UNIFORMS
- SetUniformfv(loc, BL_Uniform::UNI_FLOAT3, array3, sizeof(float) * 3);
-#else
- SetUniform(loc, array3, 3);
-#endif
- Py_RETURN_NONE;
- break;
- }
- case 4:
- {
- float array4[4] = {array_data[0], array_data[1], array_data[2], array_data[3]};
-#ifdef SORT_UNIFORMS
- SetUniformfv(loc, BL_Uniform::UNI_FLOAT4, array4, sizeof(float) * 4);
-#else
- SetUniform(loc, array4, 4);
-#endif
- Py_RETURN_NONE;
- break;
- }
- default:
- {
- PyErr_SetString(PyExc_TypeError,
- "shader.setUniform4i(name, ix,iy,iz, iw): BL_Shader. invalid list size");
- return NULL;
- break;
- }
- }
- }
- }
- }
- return NULL;
-}
-
-KX_PYMETHODDEF_DOC(BL_Shader, setUniformiv, "setUniformiv(uniform_name, (list2 or list3 or list4))")
-{
- if (mError) {
- Py_RETURN_NONE;
- }
-
- const char *uniform = "";
- PyObject *listPtr = NULL;
- int array_data[4] = {0, 0, 0, 0};
-
- if (!PyArg_ParseTuple(args, "sO:setUniformiv", &uniform, &listPtr)) {
- return NULL;
- }
-
- int loc = GetUniformLocation(uniform);
-
- if (loc == -1) {
- PyErr_SetString(PyExc_TypeError,
- "shader.setUniformiv(...): BL_Shader, first string argument is not a valid uniform value");
- return NULL;
- }
-
- if (!PySequence_Check(listPtr)) {
- PyErr_SetString(PyExc_TypeError, "shader.setUniformiv(...): BL_Shader, second argument is not a sequence");
- return NULL;
- }
-
- unsigned int list_size = PySequence_Size(listPtr);
-
- for (unsigned int i = 0; (i < list_size && i < 4); i++) {
- PyObject *item = PySequence_GetItem(listPtr, i);
- array_data[i] = PyLong_AsLong(item);
- Py_DECREF(item);
- }
-
- if (PyErr_Occurred()) {
- PyErr_SetString(PyExc_TypeError,
- "shader.setUniformiv(...): BL_Shader, one or more values in the list is not an int");
- return NULL;
- }
-
- // Sanity checks done!
- switch (list_size) {
- case 2:
- {
- int array2[2] = {array_data[0], array_data[1]};
-#ifdef SORT_UNIFORMS
- SetUniformiv(loc, BL_Uniform::UNI_INT2, array2, sizeof(int) * 2);
-#else
- SetUniform(loc, array2, 2);
-#endif
- Py_RETURN_NONE;
- break;
- }
- case 3:
- {
- int array3[3] = {array_data[0], array_data[1], array_data[2]};
-#ifdef SORT_UNIFORMS
- SetUniformiv(loc, BL_Uniform::UNI_INT3, array3, sizeof(int) * 3);
-#else
- SetUniform(loc, array3, 3);
-#endif
- Py_RETURN_NONE;
- break;
- }
- case 4:
- {
- int array4[4] = {array_data[0], array_data[1], array_data[2], array_data[3]};
-#ifdef SORT_UNIFORMS
- SetUniformiv(loc, BL_Uniform::UNI_INT4, array4, sizeof(int) * 4);
-#else
- SetUniform(loc, array4, 4);
-#endif
- Py_RETURN_NONE;
- break;
- }
- default:
- {
- PyErr_SetString(PyExc_TypeError,
- "shader.setUniformiv(...): BL_Shader, second argument, invalid list size, expected an int "
- "list between 2 and 4");
- return NULL;
- break;
- }
- }
- Py_RETURN_NONE;
-}
-
-KX_PYMETHODDEF_DOC(BL_Shader, setUniformMatrix4,
- "setUniformMatrix4(uniform_name, mat-4x4, transpose(row-major=true, col-major=false)")
-{
- if (mError) {
- Py_RETURN_NONE;
- }
-
- float matr[16] = {
- 1.0f, 0.0f, 0.0f, 0.0f,
- 0.0f, 1.0f, 0.0f, 0.0f,
- 0.0f, 0.0f, 1.0f, 0.0f,
- 0.0f, 0.0f, 0.0f, 1.0f
- };
-
- const char *uniform;
- PyObject *matrix = NULL;
- int transp = 0; // python use column major by default, so no transpose....
-
- if (!PyArg_ParseTuple(args, "sO|i:setUniformMatrix4", &uniform, &matrix, &transp)) {
- return NULL;
- }
-
- int loc = GetUniformLocation(uniform);
-
- if (loc == -1) {
- PyErr_SetString(PyExc_TypeError,
- "shader.setUniformMatrix4(...): BL_Shader, first string argument is not a valid uniform value");
- return NULL;
- }
-
- MT_Matrix4x4 mat;
-
- if (!PyMatTo(matrix, mat)) {
- PyErr_SetString(PyExc_TypeError,
- "shader.setUniformMatrix4(...): BL_Shader, second argument cannot be converted into a 4x4 matrix");
- return NULL;
- }
-
- // Sanity checks done!
-#ifdef SORT_UNIFORMS
- mat.getValue(matr);
- SetUniformfv(loc, BL_Uniform::UNI_MAT4, matr, (sizeof(float) * 16), (transp != 0));
-#else
- SetUniform(loc, mat, (transp != 0));
-#endif
- Py_RETURN_NONE;
-}
-
-
-KX_PYMETHODDEF_DOC(BL_Shader, setUniformMatrix3,
- "setUniformMatrix3(uniform_name, list[3x3], transpose(row-major=true, col-major=false)")
-{
- if (mError) {
- Py_RETURN_NONE;
- }
-
- float matr[9] = {
- 1.0f, 0.0f, 0.0f,
- 0.0f, 1.0f, 0.0f,
- 0.0f, 0.0f, 1.0f,
- };
-
- const char *uniform;
- PyObject *matrix = NULL;
- int transp = 0; // python use column major by default, so no transpose....
-
- if (!PyArg_ParseTuple(args, "sO|i:setUniformMatrix3", &uniform, &matrix, &transp)) {
- return NULL;
- }
-
- int loc = GetUniformLocation(uniform);
-
- if (loc == -1) {
- PyErr_SetString(PyExc_TypeError,
- "shader.setUniformMatrix3(...): BL_Shader, first string argument is not a valid uniform value");
- return NULL;
- }
-
- MT_Matrix3x3 mat;
-
- if (!PyMatTo(matrix, mat)) {
- PyErr_SetString(PyExc_TypeError,
- "shader.setUniformMatrix3(...): BL_Shader, second argument cannot be converted into a 3x3 matrix");
- return NULL;
- }
-
-#ifdef SORT_UNIFORMS
- mat.getValue3x3(matr);
- SetUniformfv(loc, BL_Uniform::UNI_MAT3, matr, (sizeof(float) * 9), (transp != 0));
-#else
- SetUniform(loc, mat, (transp != 0));
-#endif
- Py_RETURN_NONE;
-}
-
-KX_PYMETHODDEF_DOC(BL_Shader, setAttrib, "setAttrib(enum)")
-{
- if (mError) {
- Py_RETURN_NONE;
- }
-
- int attr = 0;
-
- if (!PyArg_ParseTuple(args, "i:setAttrib", &attr)) {
- return NULL;
- }
-
- attr = SHD_TANGENT; // user input is ignored for now, there is only 1 attr
-
- if (mShader == 0) {
- PyErr_SetString(PyExc_ValueError, "shader.setAttrib() BL_Shader, invalid shader object");
- return NULL;
- }
-
- mAttr = attr;
- glUseProgramObjectARB(mShader);
- glBindAttribLocationARB(mShader, mAttr, "Tangent");
- Py_RETURN_NONE;
-}
-
-
-KX_PYMETHODDEF_DOC(BL_Shader, setUniformDef, "setUniformDef(name, enum)")
-{
- if (mError) {
- Py_RETURN_NONE;
- }
-
- const char *uniform;
- int nloc = 0;
- if (PyArg_ParseTuple(args, "si:setUniformDef", &uniform, &nloc)) {
- int loc = GetUniformLocation(uniform);
-
- if (loc != -1) {
- bool defined = false;
- BL_UniformVecDef::iterator it = mPreDef.begin();
- while (it != mPreDef.end()) {
- if ((*it)->mLoc == loc) {
- defined = true;
- break;
- }
- it++;
- }
-
- if (defined) {
- Py_RETURN_NONE;
- }
-
- BL_DefUniform *uni = new BL_DefUniform();
- uni->mLoc = loc;
- uni->mType = nloc;
- uni->mFlag = 0;
- mPreDef.push_back(uni);
- Py_RETURN_NONE;
- }
- }
- return NULL;
-}
-
-#endif // WITH_PYTHON
-
-// eof
diff --git a/source/gameengine/Ketsji/BL_Shader.h b/source/gameengine/Ketsji/BL_Shader.h
deleted file mode 100644
index 5de715d67d4..00000000000
--- a/source/gameengine/Ketsji/BL_Shader.h
+++ /dev/null
@@ -1,241 +0,0 @@
-
-/** \file BL_Shader.h
- * \ingroup ketsji
- */
-
-#ifndef __BL_SHADER_H__
-#define __BL_SHADER_H__
-
-#include "EXP_PyObjectPlus.h"
-#include "BL_Material.h"
-#include "BL_Texture.h"
-#include "MT_Matrix4x4.h"
-#include "MT_Matrix3x3.h"
-#include "MT_Tuple2.h"
-#include "MT_Tuple3.h"
-#include "MT_Tuple4.h"
-
-/**
- * BL_Sampler
- * Sampler access
- */
-class BL_Sampler
-{
-public:
- BL_Sampler()
- :
- mLoc(-1)
- {
- }
-
- int mLoc; // Sampler location
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:BL_Sampler")
-#endif
-};
-
-/**
- * BL_Uniform
- * uniform storage
- */
-class BL_Uniform
-{
-private:
- int mLoc; // Uniform location
- void *mData; // Memory allocated for variable
- bool mDirty; // Caching variable
- int mType; // Enum UniformTypes
- bool mTranspose; // Transpose matrices
- const int mDataLen; // Length of our data
-public:
- BL_Uniform(int data_size);
- ~BL_Uniform();
-
- enum UniformTypes {
- UNI_NONE = 0,
- UNI_INT,
- UNI_FLOAT,
- UNI_INT2,
- UNI_FLOAT2,
- UNI_INT3,
- UNI_FLOAT3,
- UNI_INT4,
- UNI_FLOAT4,
- UNI_MAT3,
- UNI_MAT4,
- UNI_FLOAT_EYE,
- UNI_MAX
- };
-
- bool Apply(class BL_Shader *shader);
- void SetData(int location, int type, bool transpose = false);
- int GetLocation() { return mLoc; }
- void *getData() { return mData; }
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:BL_Uniform")
-#endif
-};
-
-/**
- * BL_DefUniform
- * pre defined uniform storage
- */
-class BL_DefUniform
-{
-public:
- BL_DefUniform()
- :
- mType(0),
- mLoc(0),
- mFlag(0)
- {
- }
-
- int mType;
- int mLoc;
- unsigned int mFlag;
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:BL_DefUniform")
-#endif
-};
-
-/**
- * BL_Shader
- * shader access
- */
-class BL_Shader : public PyObjectPlus
-{
- Py_Header
-private:
- typedef std::vector<BL_Uniform *> BL_UniformVec;
- typedef std::vector<BL_DefUniform *> BL_UniformVecDef;
-
- unsigned int mShader; // Shader object
- int mPass; // 1.. unused
- bool mOk; // Valid and ok
- bool mUse;
- //BL_Sampler mSampler[MAXTEX]; // Number of samplers
- int mAttr; // Tangent attribute
- const char *vertProg; // Vertex program string
- const char *fragProg; // Fragment program string
- bool mError;
- bool mDirty;
-
- // Stored uniform variables
- BL_UniformVec mUniforms;
- BL_UniformVecDef mPreDef;
-
- // Compiles and links the shader
- bool LinkProgram();
-
- // search by location
- BL_Uniform *FindUniform(const int location);
-
- // clears uniform data
- void ClearUniforms();
-
-public:
- BL_Shader();
- virtual ~BL_Shader();
-
- // Unused for now tangent is set as tex coords
- enum AttribTypes {
- SHD_TANGENT = 1
- };
-
- enum GenType {
- MODELVIEWMATRIX,
- MODELVIEWMATRIX_TRANSPOSE,
- MODELVIEWMATRIX_INVERSE,
- MODELVIEWMATRIX_INVERSETRANSPOSE,
- MODELMATRIX,
- MODELMATRIX_TRANSPOSE,
- MODELMATRIX_INVERSE,
- MODELMATRIX_INVERSETRANSPOSE,
- VIEWMATRIX,
- VIEWMATRIX_TRANSPOSE,
- VIEWMATRIX_INVERSE,
- VIEWMATRIX_INVERSETRANSPOSE,
- CAM_POS,
- CONSTANT_TIMER
- };
-
- const char *GetVertPtr();
- const char *GetFragPtr();
- void SetVertPtr(char *vert);
- void SetFragPtr(char *frag);
- int getNumPass() { return mPass; }
- bool GetError() { return mError; }
-
- //const BL_Sampler *GetSampler(int i);
- void SetSampler(int loc, int unit);
- bool Ok() const;
- unsigned int GetProg();
- void SetProg(bool enable);
- int GetAttribute() { return mAttr; }
-
- // Apply methods : sets colected uniforms
- void ApplyShader();
- void UnloadShader();
-
- // Update predefined uniforms each render call
- void Update(const class RAS_MeshSlot &ms, class RAS_IRasterizer *rasty);
-
- // Set sampler units (copied)
- //void InitializeSampler(int unit, BL_Texture *texture);
- void SetUniformfv(int location, int type, float *param, int size, bool transpose = false);
- void SetUniformiv(int location, int type, int *param, int size, bool transpose = false);
- int GetAttribLocation(const char *name);
- void BindAttribute(const char *attr, int loc);
- int GetUniformLocation(const char *name);
- void SetUniform(int uniform, const MT_Tuple2 &vec);
- void SetUniform(int uniform, const MT_Tuple3 &vec);
- void SetUniform(int uniform, const MT_Tuple4 &vec);
- void SetUniform(int uniform, const MT_Matrix4x4 &vec, bool transpose = false);
- void SetUniform(int uniform, const MT_Matrix3x3 &vec, bool transpose = false);
- void SetUniform(int uniform, const float &val);
- void SetUniform(int uniform, const float *val, int len);
- void SetUniform(int uniform, const int *val, int len);
- void SetUniform(int uniform, const unsigned int &val);
- void SetUniform(int uniform, const int val);
-
- // Python interface
-#ifdef WITH_PYTHON
- virtual PyObject *py_repr()
- {
- return PyUnicode_FromFormat("BL_Shader\n\tvertex shader:%s\n\n\tfragment shader%s\n\n", vertProg, fragProg);
- }
-
- // -----------------------------------
- KX_PYMETHOD_DOC(BL_Shader, setSource);
- KX_PYMETHOD_DOC(BL_Shader, delSource);
- KX_PYMETHOD_DOC(BL_Shader, getVertexProg);
- KX_PYMETHOD_DOC(BL_Shader, getFragmentProg);
- KX_PYMETHOD_DOC(BL_Shader, setNumberOfPasses);
- KX_PYMETHOD_DOC(BL_Shader, isValid);
- KX_PYMETHOD_DOC(BL_Shader, validate);
-
- // -----------------------------------
- KX_PYMETHOD_DOC(BL_Shader, setUniform4f);
- KX_PYMETHOD_DOC(BL_Shader, setUniform3f);
- KX_PYMETHOD_DOC(BL_Shader, setUniform2f);
- KX_PYMETHOD_DOC(BL_Shader, setUniform1f);
- KX_PYMETHOD_DOC(BL_Shader, setUniform4i);
- KX_PYMETHOD_DOC(BL_Shader, setUniform3i);
- KX_PYMETHOD_DOC(BL_Shader, setUniform2i);
- KX_PYMETHOD_DOC(BL_Shader, setUniform1i);
- KX_PYMETHOD_DOC(BL_Shader, setUniformEyef);
- KX_PYMETHOD_DOC(BL_Shader, setUniformfv);
- KX_PYMETHOD_DOC(BL_Shader, setUniformiv);
- KX_PYMETHOD_DOC(BL_Shader, setUniformMatrix4);
- KX_PYMETHOD_DOC(BL_Shader, setUniformMatrix3);
- KX_PYMETHOD_DOC(BL_Shader, setUniformDef);
- KX_PYMETHOD_DOC(BL_Shader, setAttrib);
- KX_PYMETHOD_DOC(BL_Shader, setSampler);
-#endif
-};
-
-#endif /* __BL_SHADER_H__ */
diff --git a/source/gameengine/Ketsji/BL_Texture.cpp b/source/gameengine/Ketsji/BL_Texture.cpp
deleted file mode 100644
index c3b799b9424..00000000000
--- a/source/gameengine/Ketsji/BL_Texture.cpp
+++ /dev/null
@@ -1,759 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Ketsji/BL_Texture.cpp
- * \ingroup ketsji
- */
-
-#include "GPU_glew.h"
-
-#include <iostream>
-#include <map>
-#include <stdlib.h>
-
-#include "BL_Material.h"
-#include "BL_Texture.h"
-#include "MT_assert.h"
-
-#include "DNA_texture_types.h"
-#include "DNA_image_types.h"
-#include "IMB_imbuf_types.h"
-#include "BKE_image.h"
-#include "BLI_blenlib.h"
-
-#include "RAS_ICanvas.h"
-#include "RAS_Rect.h"
-
-#include "KX_GameObject.h"
-
-#define spit(x) std::cout << x << std::endl;
-
-#include "MEM_guardedalloc.h"
-#include "GPU_draw.h"
-#include "GPU_extensions.h"
-
-extern "C" {
- // envmaps
- #include "IMB_imbuf.h"
- void my_envmap_split_ima(EnvMap *env, ImBuf *ibuf);
- void my_free_envmapdata(EnvMap *env);
-}
-
-// (n&(n-1)) zeros the least significant bit of n
-static int is_power_of_2_i(int num)
-{
- return ((num)&(num-1))==0;
-}
-static int power_of_2_min_i(int num)
-{
- while (!is_power_of_2_i(num))
- num= num&(num-1);
- return num;
-}
-
-// Place holder for a full texture manager
-class BL_TextureObject
-{
-public:
- unsigned int gl_texture;
- void* ref_buffer;
-};
-
-typedef std::map<char*, BL_TextureObject> BL_TextureMap;
-static BL_TextureMap g_textureManager;
-static GLint g_max_units = -1;
-
-
-BL_Texture::BL_Texture()
-: mTexture(0),
- mOk(0),
- mNeedsDeleted(0),
- mType(0),
- mUnit(0),
- mEnvState(0)
-{
- // --
-}
-
-BL_Texture::~BL_Texture()
-{
- // --
-}
-
-void BL_Texture::DeleteTex()
-{
- if ( mNeedsDeleted ) {
- glDeleteTextures(1, (GLuint*)&mTexture);
- mNeedsDeleted = 0;
- mOk = 0;
- }
-
- if (mEnvState) {
- glDeleteLists((GLuint)mEnvState, 1);
- mEnvState =0;
- }
-
- if (mDisableState) {
- glDeleteLists((GLuint)mDisableState, 1);
- mDisableState =0;
- }
- g_textureManager.clear();
-}
-
-
-bool BL_Texture::InitFromImage(int unit, Image *img, bool mipmap)
-{
-
- ImBuf *ibuf;
- if (!img || img->ok==0)
- {
- mOk = false;
- return mOk;
- }
-
- ibuf= BKE_image_acquire_ibuf(img, NULL, NULL);
- if (ibuf==NULL)
- {
- img->ok = 0;
- mOk = false;
- return mOk;
- }
-
- mipmap = mipmap && GPU_get_mipmap();
-
- mTexture = img->bindcode[TEXTARGET_TEXTURE_2D];
- mType = GL_TEXTURE_2D;
- mUnit = unit;
-
- ActivateUnit(mUnit);
-
- if (mTexture != 0) {
- glBindTexture(GL_TEXTURE_2D, mTexture );
- Validate();
- BKE_image_release_ibuf(img, ibuf, NULL);
- return mOk;
- }
-
- // look for an existing gl image
- BL_TextureMap::iterator mapLook = g_textureManager.find(img->id.name);
- if (mapLook != g_textureManager.end())
- {
- if (mapLook->second.gl_texture != 0)
- {
- mTexture = mapLook->second.gl_texture;
- glBindTexture(GL_TEXTURE_2D, mTexture);
- mOk = IsValid();
- BKE_image_release_ibuf(img, ibuf, NULL);
- return mOk;
- }
- }
-
- mNeedsDeleted = 1;
- glGenTextures(1, (GLuint*)&mTexture);
-
-#ifdef WITH_DDS
- if (ibuf->ftype == IMB_FTYPE_DDS)
- InitGLCompressedTex(ibuf, mipmap);
- else
- InitGLTex(ibuf->rect, ibuf->x, ibuf->y, mipmap);
-#else
- InitGLTex(ibuf->rect, ibuf->x, ibuf->y, mipmap);
-#endif
-
- // track created units
- BL_TextureObject obj;
- obj.gl_texture = mTexture;
- obj.ref_buffer = img;
- g_textureManager.insert(std::pair<char*, BL_TextureObject>((char*)img->id.name, obj));
-
-
- glDisable(GL_TEXTURE_2D);
- ActivateUnit(0);
- Validate();
-
- BKE_image_release_ibuf(img, ibuf, NULL);
-
- return mOk;
-}
-
-void BL_Texture::InitGLTex(unsigned int *pix,int x,int y,bool mipmap)
-{
- if (!GPU_full_non_power_of_two_support() && (!is_power_of_2_i(x) || !is_power_of_2_i(y)) ) {
- InitNonPow2Tex(pix, x,y,mipmap);
- return;
- }
-
- glBindTexture(GL_TEXTURE_2D, mTexture );
- if ( mipmap ) {
- int i;
- ImBuf *ibuf;
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
-
- ibuf = IMB_allocFromBuffer(pix, NULL, x, y);
-
- IMB_makemipmap(ibuf, true);
-
- for (i = 0; i < ibuf->miptot; i++) {
- ImBuf *mip = IMB_getmipmap(ibuf, i);
-
- glTexImage2D(GL_TEXTURE_2D, i, GL_RGBA, mip->x, mip->y, 0, GL_RGBA, GL_UNSIGNED_BYTE, mip->rect);
- }
- IMB_freeImBuf(ibuf);
- }
- else {
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
- glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, x, y, 0, GL_RGBA, GL_UNSIGNED_BYTE, pix );
- }
-
- if (GLEW_EXT_texture_filter_anisotropic)
- glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, GPU_get_anisotropic());
- glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
-}
-
-void BL_Texture::InitGLCompressedTex(ImBuf *ibuf, bool mipmap)
-{
-#ifndef WITH_DDS
- // Fall back to uncompressed if DDS isn't enabled
- InitGLTex(ibuf->rect, ibuf->x, ibuf->y, mipmap);
- return;
-#else
- glBindTexture(GL_TEXTURE_2D, mTexture);
-
- if (GPU_upload_dxt_texture(ibuf) == 0) {
- InitGLTex(ibuf->rect, ibuf->x, ibuf->y, mipmap);
- return;
- }
-#endif
-}
-
-void BL_Texture::InitNonPow2Tex(unsigned int *pix,int x,int y,bool mipmap)
-{
- int nx= power_of_2_min_i(x);
- int ny= power_of_2_min_i(y);
-
- ImBuf *ibuf = IMB_allocFromBuffer(pix, NULL, x, y);
- IMB_scaleImBuf(ibuf, nx, ny);
-
- glBindTexture(GL_TEXTURE_2D, mTexture );
-
- if ( mipmap ) {
- int i;
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
-
- IMB_makemipmap(ibuf, true);
-
- for (i = 0; i < ibuf->miptot; i++) {
- ImBuf *mip = IMB_getmipmap(ibuf, i);
-
- glTexImage2D(GL_TEXTURE_2D, i, GL_RGBA, mip->x, mip->y, 0, GL_RGBA, GL_UNSIGNED_BYTE, mip->rect);
- }
- }
- else {
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
- glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, nx, ny, 0, GL_RGBA, GL_UNSIGNED_BYTE, ibuf->rect );
- }
-
- if (GLEW_EXT_texture_filter_anisotropic)
- glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, GPU_get_anisotropic());
- glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
- IMB_freeImBuf(ibuf);
-}
-
-
-bool BL_Texture::InitCubeMap(int unit, EnvMap *cubemap)
-{
- if (!GLEW_ARB_texture_cube_map)
- {
- spit("cubemaps not supported");
- mOk = false;
- return mOk;
- }
- else if (!cubemap || cubemap->ima->ok==0)
- {
- mOk = false;
- return mOk;
- }
-
- ImBuf *ibuf= BKE_image_acquire_ibuf(cubemap->ima, NULL, NULL);
- if (ibuf==0)
- {
- cubemap->ima->ok = 0;
- mOk = false;
- return mOk;
- }
-
- mNeedsDeleted = 1;
- mType = GL_TEXTURE_CUBE_MAP_ARB;
- mTexture = 0;
- mUnit = unit;
-
- ActivateUnit(mUnit);
-
- BL_TextureMap::iterator mapLook = g_textureManager.find(cubemap->ima->id.name);
- if (mapLook != g_textureManager.end())
- {
- if (mapLook->second.gl_texture != 0 && mapLook->second.ref_buffer == cubemap->ima)
- {
- mTexture = mapLook->second.gl_texture;
- glBindTexture(GL_TEXTURE_CUBE_MAP_ARB, mTexture);
- mOk = IsValid();
- BKE_image_release_ibuf(cubemap->ima, ibuf, NULL);
- return mOk;
- }
- }
-
-
- glGenTextures(1, (GLuint*)&mTexture);
- glBindTexture(GL_TEXTURE_CUBE_MAP_ARB, mTexture);
-
-
- // track created units
- BL_TextureObject obj;
- obj.gl_texture = mTexture;
- obj.ref_buffer = cubemap->ima;
- g_textureManager.insert(std::pair<char*, BL_TextureObject>((char*)cubemap->ima->id.name, obj));
-
-
- bool needs_split = false;
- if (!cubemap->cube[0])
- {
- needs_split = true;
- spit ("Re-Generating texture buffer");
- }
-
- if (needs_split)
- my_envmap_split_ima(cubemap, ibuf);
-
-
- if (!is_power_of_2_i(cubemap->cube[0]->x) || !is_power_of_2_i(cubemap->cube[0]->y))
- {
- spit("invalid envmap size please render with CubeRes @ power of two");
-
- my_free_envmapdata(cubemap);
- mOk = false;
- BKE_image_release_ibuf(cubemap->ima, ibuf, NULL);
- return mOk;
- }
-
-
-#define SetCubeMapFace(face, num) \
- glTexImage2D(face, 0,GL_RGBA, \
- cubemap->cube[num]->x, \
- cubemap->cube[num]->y, \
- 0, GL_RGBA, GL_UNSIGNED_BYTE, \
- cubemap->cube[num]->rect)
-
- SetCubeMapFace(GL_TEXTURE_CUBE_MAP_POSITIVE_X_ARB, 5);
- SetCubeMapFace(GL_TEXTURE_CUBE_MAP_NEGATIVE_X_ARB, 3);
- SetCubeMapFace(GL_TEXTURE_CUBE_MAP_POSITIVE_Y_ARB, 0);
- SetCubeMapFace(GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_ARB, 1);
- SetCubeMapFace(GL_TEXTURE_CUBE_MAP_POSITIVE_Z_ARB, 2);
- SetCubeMapFace(GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_ARB, 4);
-
- glTexParameteri( GL_TEXTURE_CUBE_MAP_ARB, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
- glTexParameteri( GL_TEXTURE_CUBE_MAP_ARB, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
- glTexParameteri( GL_TEXTURE_CUBE_MAP_ARB, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
- glTexParameteri( GL_TEXTURE_CUBE_MAP_ARB, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
- if (GLEW_VERSION_1_2)
- glTexParameteri( GL_TEXTURE_CUBE_MAP_ARB, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE );
-
- if (needs_split)
- my_free_envmapdata(cubemap);
-
-
-
- glDisable(GL_TEXTURE_CUBE_MAP_ARB);
- ActivateUnit(0);
-
- mOk = IsValid();
-
- BKE_image_release_ibuf(cubemap->ima, ibuf, NULL);
-
- return mOk;
-}
-
-bool BL_Texture::IsValid()
-{
- return (mTexture!= 0)?glIsTexture(mTexture)!=0:false;
-}
-
-
-void BL_Texture::Validate()
-{
- mOk = IsValid();
-}
-
-
-bool BL_Texture::Ok()
-{
- return (mTexture!= 0);
-}
-
-
-unsigned int BL_Texture::GetTextureType() const
-{
- return mType;
-}
-
-int BL_Texture::GetMaxUnits()
-{
- if (g_max_units < 0) {
- GLint unit = 0;
- glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS_ARB, &unit);
- g_max_units = (MAXTEX >= unit) ? unit : MAXTEX;
- }
-
- return g_max_units;
-}
-
-void BL_Texture::ActivateFirst()
-{
- if (GLEW_ARB_multitexture)
- glActiveTextureARB(GL_TEXTURE0_ARB);
-}
-
-void BL_Texture::ActivateUnit(int unit)
-{
- if (GLEW_ARB_multitexture)
- if (unit <= MAXTEX)
- glActiveTextureARB(GL_TEXTURE0_ARB+unit);
-}
-
-
-void BL_Texture::DisableUnit()
-{
- if (GLEW_ARB_multitexture)
- glActiveTextureARB(GL_TEXTURE0_ARB+mUnit);
-
- glMatrixMode(GL_TEXTURE);
- glLoadIdentity();
- glMatrixMode(GL_MODELVIEW);
-
- if (GLEW_ARB_texture_cube_map && glIsEnabled(GL_TEXTURE_CUBE_MAP_ARB))
- glDisable(GL_TEXTURE_CUBE_MAP_ARB);
- else
- {
- if (glIsEnabled(GL_TEXTURE_2D))
- glDisable(GL_TEXTURE_2D);
- }
-
- glDisable(GL_TEXTURE_GEN_S);
- glDisable(GL_TEXTURE_GEN_T);
- glDisable(GL_TEXTURE_GEN_R);
- glDisable(GL_TEXTURE_GEN_Q);
- glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );
-}
-
-
-void BL_Texture::DisableAllTextures()
-{
- for (int i=0; i<MAXTEX; i++) {
- if (GLEW_ARB_multitexture)
- glActiveTextureARB(GL_TEXTURE0_ARB+i);
-
- glMatrixMode(GL_TEXTURE);
- glLoadIdentity();
- glMatrixMode(GL_MODELVIEW);
- glDisable(GL_TEXTURE_2D);
- glDisable(GL_TEXTURE_GEN_S);
- glDisable(GL_TEXTURE_GEN_T);
- glDisable(GL_TEXTURE_GEN_R);
- glDisable(GL_TEXTURE_GEN_Q);
- glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );
- }
-
- if (GLEW_ARB_multitexture)
- glActiveTextureARB(GL_TEXTURE0_ARB);
-}
-
-
-void BL_Texture::ActivateTexture()
-{
- if (GLEW_ARB_multitexture)
- glActiveTextureARB(GL_TEXTURE0_ARB+mUnit);
-
- if (mType == GL_TEXTURE_CUBE_MAP_ARB && GLEW_ARB_texture_cube_map)
- {
- glBindTexture( GL_TEXTURE_CUBE_MAP_ARB, mTexture );
- glEnable(GL_TEXTURE_CUBE_MAP_ARB);
- }
- else {
- if (GLEW_ARB_texture_cube_map )
- glDisable(GL_TEXTURE_CUBE_MAP_ARB);
-
- glBindTexture( GL_TEXTURE_2D, mTexture );
- glEnable(GL_TEXTURE_2D);
- }
-}
-
-void BL_Texture::SetMapping(int mode)
-{
-
- if (!(mode &USEREFL)) {
- glDisable(GL_TEXTURE_GEN_S);
- glDisable(GL_TEXTURE_GEN_T);
- glDisable(GL_TEXTURE_GEN_R);
- glDisable(GL_TEXTURE_GEN_Q);
- return;
- }
-
- if ( mType == GL_TEXTURE_CUBE_MAP_ARB &&
- GLEW_ARB_texture_cube_map &&
- mode &USEREFL)
- {
- glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_REFLECTION_MAP_ARB );
- glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_REFLECTION_MAP_ARB );
- glTexGeni(GL_R, GL_TEXTURE_GEN_MODE, GL_REFLECTION_MAP_ARB );
-
- glEnable(GL_TEXTURE_GEN_S);
- glEnable(GL_TEXTURE_GEN_T);
- glEnable(GL_TEXTURE_GEN_R);
- glDisable(GL_TEXTURE_GEN_Q);
- return;
- }
- else
- {
- glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP );
- glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP );
-
- glEnable(GL_TEXTURE_GEN_S);
- glEnable(GL_TEXTURE_GEN_T);
- glDisable(GL_TEXTURE_GEN_R);
- glDisable(GL_TEXTURE_GEN_Q);
- }
-}
-
-
-void BL_Texture::setTexEnv(BL_Material *mat, bool modulate)
-{
- if (modulate || !GLEW_ARB_texture_env_combine) {
- glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );
- return;
- }
-
- if (glIsList(mEnvState))
- {
- glCallList(mEnvState);
- return;
- }
- if (!mEnvState)
- mEnvState = glGenLists(1);
-
- glNewList(mEnvState, GL_COMPILE_AND_EXECUTE);
-
- glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_ARB );
-
- GLfloat blend_operand = GL_SRC_COLOR;
- GLfloat blend_operand_prev = GL_SRC_COLOR;
- GLfloat alphaOp = GL_SRC_ALPHA;
-
- GLenum combiner = GL_COMBINE_RGB_ARB;
- GLenum source0 = GL_SOURCE0_RGB_ARB;
- GLenum source1 = GL_SOURCE1_RGB_ARB;
- GLenum source2 = GL_SOURCE2_RGB_ARB;
- GLenum op0 = GL_OPERAND0_RGB_ARB;
- GLenum op1 = GL_OPERAND1_RGB_ARB;
- GLenum op2 = GL_OPERAND2_RGB_ARB;
-
- // switch to alpha combiners
- if ( mat->flag[mUnit] &TEXALPHA ) {
- combiner = GL_COMBINE_ALPHA_ARB;
- source0 = GL_SOURCE0_ALPHA_ARB;
- source1 = GL_SOURCE1_ALPHA_ARB;
- source2 = GL_SOURCE2_ALPHA_ARB;
- op0 = GL_OPERAND0_ALPHA_ARB;
- op1 = GL_OPERAND1_ALPHA_ARB;
- op2 = GL_OPERAND2_ALPHA_ARB;
- blend_operand = GL_SRC_ALPHA;
- blend_operand_prev = GL_SRC_ALPHA;
- // invert
- if (mat->flag[mUnit] &TEXNEG) {
- blend_operand_prev = GL_ONE_MINUS_SRC_ALPHA;
- blend_operand = GL_ONE_MINUS_SRC_ALPHA;
- }
- }
- else {
- if (mat->flag[mUnit] &TEXNEG) {
- blend_operand_prev=GL_ONE_MINUS_SRC_COLOR;
- blend_operand = GL_ONE_MINUS_SRC_COLOR;
- }
- }
- bool using_alpha = false;
-
- if (mat->flag[mUnit] &USEALPHA) {
- alphaOp = GL_ONE_MINUS_SRC_ALPHA;
- using_alpha=true;
- }
- else if (mat->flag[mUnit] &USENEGALPHA) {
- alphaOp = GL_SRC_ALPHA;
- using_alpha = true;
- }
-
- switch (mat->blend_mode[mUnit]) {
- case BLEND_MIX:
- {
- // ------------------------------
- if (!using_alpha) {
- GLfloat base_col[4];
- base_col[0] = base_col[1] = base_col[2] = 0.f;
- base_col[3] = 1.f-mat->color_blend[mUnit];
- glTexEnvfv( GL_TEXTURE_ENV, GL_TEXTURE_ENV_COLOR,base_col );
- }
- glTexEnvf( GL_TEXTURE_ENV, combiner, GL_INTERPOLATE_ARB);
- glTexEnvf( GL_TEXTURE_ENV, source0, GL_PREVIOUS_ARB);
- glTexEnvf( GL_TEXTURE_ENV, op0, blend_operand_prev );
- glTexEnvf( GL_TEXTURE_ENV, source1, GL_TEXTURE );
- glTexEnvf( GL_TEXTURE_ENV, op1, blend_operand);
- if (!using_alpha)
- glTexEnvf( GL_TEXTURE_ENV, source2, GL_CONSTANT_ARB );
- else
- glTexEnvf( GL_TEXTURE_ENV, source2, GL_TEXTURE );
-
- glTexEnvf( GL_TEXTURE_ENV, op2, alphaOp);
- }break;
- case BLEND_MUL:
- {
- // ------------------------------
- glTexEnvf( GL_TEXTURE_ENV, combiner, GL_MODULATE);
- glTexEnvf( GL_TEXTURE_ENV, source0, GL_PREVIOUS_ARB);
- glTexEnvf( GL_TEXTURE_ENV, op0, blend_operand_prev);
- glTexEnvf( GL_TEXTURE_ENV, source1, GL_TEXTURE );
- if (using_alpha)
- glTexEnvf( GL_TEXTURE_ENV, op1, alphaOp);
- else
- glTexEnvf( GL_TEXTURE_ENV, op1, blend_operand);
- }break;
- case BLEND_ADD:
- {
- // ------------------------------
- glTexEnvf( GL_TEXTURE_ENV, combiner, GL_ADD_SIGNED_ARB);
- glTexEnvf( GL_TEXTURE_ENV, source0, GL_PREVIOUS_ARB );
- glTexEnvf( GL_TEXTURE_ENV, op0, blend_operand_prev );
- glTexEnvf( GL_TEXTURE_ENV, source1, GL_TEXTURE );
- if (using_alpha)
- glTexEnvf( GL_TEXTURE_ENV, op1, alphaOp);
- else
- glTexEnvf( GL_TEXTURE_ENV, op1, blend_operand);
- }break;
- case BLEND_SUB:
- {
- // ------------------------------
- glTexEnvf( GL_TEXTURE_ENV, combiner, GL_SUBTRACT_ARB);
- glTexEnvf( GL_TEXTURE_ENV, source0, GL_PREVIOUS_ARB );
- glTexEnvf( GL_TEXTURE_ENV, op0, blend_operand_prev );
- glTexEnvf( GL_TEXTURE_ENV, source1, GL_TEXTURE );
- glTexEnvf( GL_TEXTURE_ENV, op1, blend_operand);
- }break;
- case BLEND_SCR:
- {
- // ------------------------------
- glTexEnvf( GL_TEXTURE_ENV, combiner, GL_ADD);
- glTexEnvf( GL_TEXTURE_ENV, source0, GL_PREVIOUS_ARB );
- glTexEnvf( GL_TEXTURE_ENV, op0, blend_operand_prev );
- glTexEnvf( GL_TEXTURE_ENV, source1, GL_TEXTURE );
- if (using_alpha)
- glTexEnvf( GL_TEXTURE_ENV, op1, alphaOp);
- else
- glTexEnvf( GL_TEXTURE_ENV, op1, blend_operand);
- } break;
- }
- glTexEnvf( GL_TEXTURE_ENV, GL_RGB_SCALE_ARB, 1.0f);
-
- glEndList();
-}
-
-int BL_Texture::GetPow2(int n)
-{
- if (!is_power_of_2_i(n))
- n = power_of_2_min_i(n);
-
- return n;
-}
-
-void BL_Texture::SplitEnvMap(EnvMap *map)
-{
- if (!map || !map->ima || (map->ima && !map->ima->ok)) return;
- ImBuf *ibuf= BKE_image_acquire_ibuf(map->ima, NULL, NULL);
- if (ibuf) {
- my_envmap_split_ima(map, ibuf);
- BKE_image_release_ibuf(map->ima, ibuf, NULL);
- }
-}
-
-unsigned int BL_Texture::mDisableState = 0;
-
-extern "C" {
-
-void my_envmap_split_ima(EnvMap *env, ImBuf *ibuf)
-{
- int dx, part;
-
- my_free_envmapdata(env);
-
- dx= ibuf->y;
- dx/= 2;
- if (3*dx != ibuf->x) {
- printf("Incorrect envmap size\n");
- env->ok= 0;
- env->ima->ok= 0;
- }
- else {
- for (part=0; part<6; part++) {
- env->cube[part] = IMB_allocImBuf(dx, dx, 24, IB_rect);
- }
- IMB_rectcpy(env->cube[0], ibuf,
- 0, 0, 0, 0, dx, dx);
- IMB_rectcpy(env->cube[1], ibuf,
- 0, 0, dx, 0, dx, dx);
- IMB_rectcpy(env->cube[2], ibuf,
- 0, 0, 2*dx, 0, dx, dx);
- IMB_rectcpy(env->cube[3], ibuf,
- 0, 0, 0, dx, dx, dx);
- IMB_rectcpy(env->cube[4], ibuf,
- 0, 0, dx, dx, dx, dx);
- IMB_rectcpy(env->cube[5], ibuf,
- 0, 0, 2*dx, dx, dx, dx);
-
- env->ok= 2;// ENV_OSA
- }
-}
-
-
-void my_free_envmapdata(EnvMap *env)
-{
- unsigned int part;
-
- for (part=0; part<6; part++) {
- ImBuf *ibuf= env->cube[part];
- if (ibuf) {
- IMB_freeImBuf(ibuf);
- env->cube[part] = NULL;
- }
- }
- env->ok= 0;
-}
-
-
-} // extern C
-
diff --git a/source/gameengine/Ketsji/BL_Texture.h b/source/gameengine/Ketsji/BL_Texture.h
deleted file mode 100644
index cd18ef93822..00000000000
--- a/source/gameengine/Ketsji/BL_Texture.h
+++ /dev/null
@@ -1,82 +0,0 @@
-
-/** \file BL_Texture.h
- * \ingroup ketsji
- */
-
-#ifndef __BL_TEXTURE_H__
-#define __BL_TEXTURE_H__
-
-// #include <vector>
-// #include <map>
-
-#include "MT_Matrix4x4.h"
-#include "KX_Camera.h"
-
-// --
-struct Image;
-struct EnvMap;
-class BL_Material;
-class RAS_Rect;
-class RAS_ICanvas;
-//class RTData;
-
-#include "STR_String.h"
-
-class BL_Texture
-{
-private:
- unsigned int mTexture; // Bound texture unit data
- bool mOk; // ...
- bool mNeedsDeleted; // If generated
- unsigned int mType; // enum TEXTURE_2D | CUBE_MAP
- int mUnit; // Texture unit associated with mTexture
- unsigned int mEnvState; // cache textureEnv
- static unsigned int mDisableState; // speed up disabling calls
-
- void InitNonPow2Tex(unsigned int *p,int x,int y,bool mipmap );
- void InitGLTex(unsigned int *p,int x,int y,bool mipmap );
- void InitGLCompressedTex(struct ImBuf *p, bool mipmap);
-public:
- BL_Texture();
- ~BL_Texture( );
-
- bool Ok();
- int GetUnit() {return mUnit;}
- void SetUnit(int unit) {mUnit = unit;}
-
- unsigned int GetTextureType() const;
- void DeleteTex();
-
- bool InitFromImage(int unit, Image *img, bool mipmap);
- bool InitCubeMap(int unit,EnvMap *cubemap );
-
- bool IsValid();
- void Validate();
-
- static void ActivateFirst();
- static void DisableAllTextures();
- static void ActivateUnit(int unit);
- static int GetMaxUnits();
- static int GetPow2(int x);
- static void SplitEnvMap(EnvMap *map);
-
-
- void ActivateTexture();
- void SetMapping(int mode);
- void DisableUnit();
- void setTexEnv(BL_Material *mat, bool modulate=false);
- unsigned int swapTexture (unsigned int newTex) {
- // swap texture codes
- unsigned int tmp = mTexture;
- mTexture = newTex;
- // return original texture code
- return tmp;
- }
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:BL_Texture")
-#endif
-};
-
-#endif /* __BL_TEXTURE_H__ */
diff --git a/source/gameengine/Ketsji/CMakeLists.txt b/source/gameengine/Ketsji/CMakeLists.txt
deleted file mode 100644
index cb7c0180f30..00000000000
--- a/source/gameengine/Ketsji/CMakeLists.txt
+++ /dev/null
@@ -1,265 +0,0 @@
-# ***** BEGIN GPL LICENSE BLOCK *****
-#
-# This program is free software; you can redistribute it and/or
-# modify it under the terms of the GNU General Public License
-# as published by the Free Software Foundation; either version 2
-# of the License, or (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software Foundation,
-# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
-#
-# The Original Code is Copyright (C) 2006, Blender Foundation
-# All rights reserved.
-#
-# The Original Code is: all of this file.
-#
-# Contributor(s): Jacques Beaurain.
-#
-# ***** END GPL LICENSE BLOCK *****
-
-set(INC
- .
- KXNetwork
- ../BlenderRoutines
- ../Converter
- ../Expressions
- ../GameLogic
- ../Network
- ../Network/LoopBackNetwork
- ../Physics/common
- ../Rasterizer
- ../Rasterizer/RAS_OpenGLRasterizer
- ../SceneGraph
- ../../blender
- ../../blender/blenfont
- ../../blender/blenkernel
- ../../blender/blenlib
- ../../blender/blenloader
- ../../blender/gpu
- ../../blender/imbuf
- ../../blender/makesdna
- ../../blender/makesrna
- ../../blender/python
- ../../blender/python/generic
- ../../blender/python/mathutils
- ../../../intern/container
- ../../../intern/glew-mx
- ../../../intern/guardedalloc
- ../../../intern/string
-)
-
-set(INC_SYS
- ../../../intern/moto/include
- ../../../extern/recastnavigation/Recast/Include
- ../../../extern/recastnavigation/Detour/Include
- ${PTHREADS_INCLUDE_DIRS}
- ${GLEW_INCLUDE_PATH}
- ${BOOST_INCLUDE_DIR}
-)
-
-set(SRC
- BL_Action.cpp
- BL_ActionManager.cpp
- BL_BlenderShader.cpp
- BL_Material.cpp
- BL_Shader.cpp
- BL_Texture.cpp
- KX_ArmatureSensor.cpp
- KX_BlenderMaterial.cpp
- KX_Camera.cpp
- KX_CameraActuator.cpp
- KX_CameraIpoSGController.cpp
- KX_CharacterWrapper.cpp
- KX_ConstraintActuator.cpp
- KX_ConstraintWrapper.cpp
- KX_Dome.cpp
- KX_EmptyObject.cpp
- KX_FontObject.cpp
- KX_GameActuator.cpp
- KX_GameObject.cpp
- KX_IpoConvert.cpp
- KX_IPO_SGController.cpp
- KX_KetsjiEngine.cpp
- KX_Light.cpp
- KX_LightIpoSGController.cpp
- KX_MaterialIpoController.cpp
- KX_MeshProxy.cpp
- KX_MotionState.cpp
- KX_MouseActuator.cpp
- KX_MouseFocusSensor.cpp
- KX_NavMeshObject.cpp
- KX_NearSensor.cpp
- KX_ObColorIpoSGController.cpp
- KX_ObjectActuator.cpp
- KX_ObstacleSimulation.cpp
- KX_OrientationInterpolator.cpp
- KX_ParentActuator.cpp
- KX_PolyProxy.cpp
- KX_PositionInterpolator.cpp
- KX_PyConstraintBinding.cpp
- KX_PyMath.cpp
- KX_PythonInit.cpp
- KX_PythonInitTypes.cpp
- KX_PythonMain.cpp
- KX_RadarSensor.cpp
- KX_RayCast.cpp
- KX_RayEventManager.cpp
- KX_RaySensor.cpp
- KX_SCA_AddObjectActuator.cpp
- KX_SCA_DynamicActuator.cpp
- KX_SCA_EndObjectActuator.cpp
- KX_SCA_ReplaceMeshActuator.cpp
- KX_SG_BoneParentNodeRelationship.cpp
- KX_SG_NodeRelationships.cpp
- KX_ScalarInterpolator.cpp
- KX_ScalingInterpolator.cpp
- KX_Scene.cpp
- KX_SceneActuator.cpp
- KX_SoundActuator.cpp
- KX_StateActuator.cpp
- KX_SteeringActuator.cpp
- KX_TimeCategoryLogger.cpp
- KX_TimeLogger.cpp
- KX_TouchEventManager.cpp
- KX_TouchSensor.cpp
- KX_TrackToActuator.cpp
- KX_VehicleWrapper.cpp
- KX_VertexProxy.cpp
- KX_VisibilityActuator.cpp
- KX_WorldInfo.cpp
- KX_WorldIpoController.cpp
-
- BL_Action.h
- BL_ActionManager.h
- BL_BlenderShader.h
- BL_Material.h
- BL_Shader.h
- BL_Texture.h
- KX_ArmatureSensor.h
- KX_BlenderMaterial.h
- KX_Camera.h
- KX_CameraActuator.h
- KX_CameraIpoSGController.h
- KX_CharacterWrapper.h
- KX_ClientObjectInfo.h
- KX_ConstraintActuator.h
- KX_ConstraintWrapper.h
- KX_Dome.h
- KX_EmptyObject.h
- KX_FontObject.h
- KX_GameActuator.h
- KX_GameObject.h
- KX_IInterpolator.h
- KX_IpoConvert.h
- KX_IPOTransform.h
- KX_IPO_SGController.h
- KX_IScalarInterpolator.h
- KX_ISceneConverter.h
- KX_ISystem.h
- KX_KetsjiEngine.h
- KX_Light.h
- KX_LightIpoSGController.h
- KX_MaterialIpoController.h
- KX_MeshProxy.h
- KX_MotionState.h
- KX_MouseActuator.h
- KX_MouseFocusSensor.h
- KX_NavMeshObject.h
- KX_NearSensor.h
- KX_ObColorIpoSGController.h
- KX_ObjectActuator.h
- KX_ObstacleSimulation.h
- KX_OrientationInterpolator.h
- KX_ParentActuator.h
- KX_PhysicsEngineEnums.h
- KX_PolyProxy.h
- KX_PositionInterpolator.h
- KX_PyConstraintBinding.h
- KX_PyMath.h
- KX_PythonInit.h
- KX_PythonInitTypes.h
- KX_PythonMain.h
- KX_RadarSensor.h
- KX_RayCast.h
- KX_RayEventManager.h
- KX_RaySensor.h
- KX_SCA_AddObjectActuator.h
- KX_SCA_DynamicActuator.h
- KX_SCA_EndObjectActuator.h
- KX_SCA_ReplaceMeshActuator.h
- KX_SG_BoneParentNodeRelationship.h
- KX_SG_NodeRelationships.h
- KX_ScalarInterpolator.h
- KX_ScalingInterpolator.h
- KX_Scene.h
- KX_SceneActuator.h
- KX_SoundActuator.h
- KX_StateActuator.h
- KX_SteeringActuator.h
- KX_TimeCategoryLogger.h
- KX_TimeLogger.h
- KX_TouchEventManager.h
- KX_TouchSensor.h
- KX_TrackToActuator.h
- KX_VehicleWrapper.h
- KX_VertexProxy.h
- KX_VisibilityActuator.h
- KX_WorldInfo.h
- KX_WorldIpoController.h
-
- # orphan headers (not apart of a library)
- ../Physics/common/PHY_DynamicTypes.h
- ../Physics/common/PHY_ICharacter.h
- ../Physics/common/PHY_IController.h
- ../Physics/common/PHY_IGraphicController.h
- ../Physics/common/PHY_IMotionState.h
- ../Physics/common/PHY_IPhysicsController.h
- ../Physics/common/PHY_IPhysicsEnvironment.h
- ../Physics/common/PHY_IVehicle.h
- ../Physics/common/PHY_Pro.h
-
-)
-
-add_definitions(${GL_DEFINITIONS})
-
-if(WITH_IMAGE_DDS)
- add_definitions(-DWITH_DDS)
-endif()
-
-if(WITH_SDL)
- list(APPEND INC_SYS
- ${SDL_INCLUDE_DIR}
- )
- add_definitions(-DWITH_SDL)
-endif()
-
-if(WITH_CODEC_FFMPEG)
- add_definitions(-DWITH_FFMPEG)
-endif()
-
-if(WITH_AUDASPACE)
- add_definitions(-DWITH_AUDASPACE)
-
- list(APPEND INC_SYS
- ${AUDASPACE_C_INCLUDE_DIRS}
- ${AUDASPACE_PY_INCLUDE_DIRS}
- )
-endif()
-
-if(WITH_BULLET)
- list(APPEND INC
- ../Physics/Bullet
- )
- list(APPEND INC_SYS
- ${BULLET_INCLUDE_DIRS}
- )
- add_definitions(-DWITH_BULLET)
-endif()
-
-blender_add_lib(ge_logic_ketsji "${SRC}" "${INC}" "${INC_SYS}")
diff --git a/source/gameengine/Ketsji/KXNetwork/CMakeLists.txt b/source/gameengine/Ketsji/KXNetwork/CMakeLists.txt
deleted file mode 100644
index cfc6ded4e65..00000000000
--- a/source/gameengine/Ketsji/KXNetwork/CMakeLists.txt
+++ /dev/null
@@ -1,56 +0,0 @@
-# ***** BEGIN GPL LICENSE BLOCK *****
-#
-# This program is free software; you can redistribute it and/or
-# modify it under the terms of the GNU General Public License
-# as published by the Free Software Foundation; either version 2
-# of the License, or (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software Foundation,
-# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
-#
-# The Original Code is Copyright (C) 2006, Blender Foundation
-# All rights reserved.
-#
-# The Original Code is: all of this file.
-#
-# Contributor(s): Jacques Beaurain.
-#
-# ***** END GPL LICENSE BLOCK *****
-
-set(INC
- .
- ..
- ../../Expressions
- ../../GameLogic
- ../../Network
- ../../SceneGraph
- ../../../blender/blenlib
- ../../../../intern/container
- ../../../../intern/string
-)
-
-set(INC_SYS
- ../../../../intern/moto/include
-)
-
-set(SRC
- KX_NetworkEventManager.cpp
- KX_NetworkMessageActuator.cpp
- KX_NetworkMessageSensor.cpp
- KX_NetworkObjectActuator.cpp
- KX_NetworkObjectSensor.cpp
-
- KX_NetworkEventManager.h
- KX_NetworkMessageActuator.h
- KX_NetworkMessageSensor.h
- KX_NetworkObjectActuator.h
- KX_NetworkObjectSensor.h
-)
-
-blender_add_lib(ge_logic_network "${SRC}" "${INC}" "${INC_SYS}")
diff --git a/source/gameengine/Ketsji/KXNetwork/KX_NetworkEventManager.cpp b/source/gameengine/Ketsji/KXNetwork/KX_NetworkEventManager.cpp
deleted file mode 100644
index 8c6392ee825..00000000000
--- a/source/gameengine/Ketsji/KXNetwork/KX_NetworkEventManager.cpp
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- * Ketsji Logic Extension: Network Event Manager generic implementation
- */
-
-/** \file gameengine/Ketsji/KXNetwork/KX_NetworkEventManager.cpp
- * \ingroup ketsjinet
- */
-
-
-// Ketsji specific sensor part
-#include "SCA_ISensor.h"
-
-// Ketsji specific network part
-#include "KX_NetworkEventManager.h"
-
-// Network module specific
-#include "NG_NetworkDeviceInterface.h"
-#include "NG_NetworkMessage.h"
-#include "NG_NetworkObject.h"
-
-KX_NetworkEventManager::KX_NetworkEventManager(class SCA_LogicManager*
-logicmgr, class NG_NetworkDeviceInterface *ndi) :
-SCA_EventManager(logicmgr, NETWORK_EVENTMGR), m_ndi(ndi)
-{
- //printf("KX_NetworkEventManager constructor\n");
-}
-
-KX_NetworkEventManager::~KX_NetworkEventManager()
-{
- //printf("KX_NetworkEventManager destructor\n");
-}
-
-void KX_NetworkEventManager::NextFrame()
-{
-// printf("KX_NetworkEventManager::proceed %.2f - %.2f\n", curtime, deltatime);
- // each frame, the logicmanager will call the network
- // eventmanager to look for network events, and process it's
- // 'network' sensors
- SG_DList::iterator<SCA_ISensor> it(m_sensors);
- for (it.begin();!it.end();++it)
- {
-// printf("KX_NetworkEventManager::proceed sensor %.2f\n", curtime);
- // process queue
- (*it)->Activate(m_logicmgr);
- }
-
- // now a list of triggerer sensors has been built
-}
-
-void KX_NetworkEventManager::EndFrame()
-{
-}
-
diff --git a/source/gameengine/Ketsji/KXNetwork/KX_NetworkEventManager.h b/source/gameengine/Ketsji/KXNetwork/KX_NetworkEventManager.h
deleted file mode 100644
index 9a13b6d53e2..00000000000
--- a/source/gameengine/Ketsji/KXNetwork/KX_NetworkEventManager.h
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file KX_NetworkEventManager.h
- * \ingroup ketsjinet
- * \brief Ketsji Logic Extension: Network Event Manager class
- */
-
-#ifndef __KX_NETWORKEVENTMANAGER_H__
-#define __KX_NETWORKEVENTMANAGER_H__
-
-#include "SCA_EventManager.h"
-
-class KX_NetworkEventManager : public SCA_EventManager
-{
- class NG_NetworkDeviceInterface* m_ndi;
-
-public:
- KX_NetworkEventManager(class SCA_LogicManager* logicmgr,
- class NG_NetworkDeviceInterface *ndi);
- virtual ~KX_NetworkEventManager ();
-
- virtual void NextFrame();
- virtual void EndFrame();
-
- SCA_LogicManager* GetLogicManager() { return m_logicmgr; }
- class NG_NetworkDeviceInterface* GetNetworkDevice() {
- return m_ndi; }
-};
-
-#endif /* __KX_NETWORKEVENTMANAGER_H__ */
diff --git a/source/gameengine/Ketsji/KXNetwork/KX_NetworkMessageActuator.cpp b/source/gameengine/Ketsji/KXNetwork/KX_NetworkMessageActuator.cpp
deleted file mode 100644
index 2741907bfe6..00000000000
--- a/source/gameengine/Ketsji/KXNetwork/KX_NetworkMessageActuator.cpp
+++ /dev/null
@@ -1,139 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- * Ketsji Logic Extension: Network Message Actuator generic implementation
- */
-
-/** \file gameengine/Ketsji/KXNetwork/KX_NetworkMessageActuator.cpp
- * \ingroup ketsjinet
- */
-
-
-#include <stddef.h>
-
-#include "NG_NetworkScene.h"
-#include "KX_NetworkMessageActuator.h"
-
-KX_NetworkMessageActuator::KX_NetworkMessageActuator(
- SCA_IObject* gameobj, // the actuator controlling object
- NG_NetworkScene* networkscene, // needed for replication
- const STR_String &toPropName,
- const STR_String &subject,
- int bodyType,
- const STR_String &body) :
- SCA_IActuator(gameobj, KX_ACT_MESSAGE),
- m_networkscene(networkscene),
- m_toPropName(toPropName),
- m_subject(subject),
- m_bPropBody(bodyType),
- m_body(body)
-{
-}
-
-KX_NetworkMessageActuator::~KX_NetworkMessageActuator()
-{
-}
-
-// returns true if the actuators needs to be running over several frames
-bool KX_NetworkMessageActuator::Update()
-{
- //printf("update messageactuator\n");
- bool bNegativeEvent = IsNegativeEvent();
- RemoveAllEvents();
-
- if (bNegativeEvent) {
- return false; // do nothing on negative events
- //printf("messageactuator false event\n");
- }
- //printf("messageactuator true event\n");
-
- if (m_bPropBody) // ACT_MESG_PROP in DNA_actuator_types.h
- {
- m_networkscene->SendMessage(
- m_toPropName,
- GetParent()->GetName(),
- m_subject,
- GetParent()->GetPropertyText(m_body));
- } else
- {
- m_networkscene->SendMessage(
- m_toPropName,
- GetParent()->GetName(),
- m_subject,
- m_body);
- }
- return false;
-}
-
-CValue* KX_NetworkMessageActuator::GetReplica()
-{
- KX_NetworkMessageActuator* replica = new KX_NetworkMessageActuator(*this);
- replica->ProcessReplica();
-
- return replica;
-}
-
-#ifdef WITH_PYTHON
-
-/* -------------------------------------------------------------------- */
-/* Python interface --------------------------------------------------- */
-/* -------------------------------------------------------------------- */
-
-/* Integration hooks -------------------------------------------------- */
-PyTypeObject KX_NetworkMessageActuator::Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "KX_NetworkMessageActuator",
- sizeof(PyObjectPlus_Proxy),
- 0,
- py_base_dealloc,
- 0,
- 0,
- 0,
- 0,
- py_base_repr,
- 0,0,0,0,0,0,0,0,0,
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
- 0,0,0,0,0,0,0,
- Methods,
- 0,
- 0,
- &SCA_IActuator::Type,
- 0,0,0,0,0,0,
- py_base_new
-};
-
-PyMethodDef KX_NetworkMessageActuator::Methods[] = {
- {NULL,NULL} // Sentinel
-};
-
-PyAttributeDef KX_NetworkMessageActuator::Attributes[] = {
- KX_PYATTRIBUTE_STRING_RW("propName", 0, MAX_PROP_NAME, false, KX_NetworkMessageActuator, m_toPropName),
- KX_PYATTRIBUTE_STRING_RW("subject", 0, 100, false, KX_NetworkMessageActuator, m_subject),
- KX_PYATTRIBUTE_BOOL_RW("usePropBody", KX_NetworkMessageActuator, m_bPropBody),
- KX_PYATTRIBUTE_STRING_RW("body", 0, 16384, false, KX_NetworkMessageActuator, m_body),
- { NULL } //Sentinel
-};
-
-#endif // WITH_PYTHON
diff --git a/source/gameengine/Ketsji/KXNetwork/KX_NetworkMessageActuator.h b/source/gameengine/Ketsji/KXNetwork/KX_NetworkMessageActuator.h
deleted file mode 100644
index 325a7be9bd7..00000000000
--- a/source/gameengine/Ketsji/KXNetwork/KX_NetworkMessageActuator.h
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file KX_NetworkMessageActuator.h
- * \ingroup ketsjinet
- * \brief Ketsji Logic Extension: Network Message Actuator class
- */
-
-#ifndef __KX_NETWORKMESSAGEACTUATOR_H__
-#define __KX_NETWORKMESSAGEACTUATOR_H__
-
-#include "STR_String.h"
-#include "SCA_IActuator.h"
-#include "NG_NetworkMessage.h"
-
-class KX_NetworkMessageActuator : public SCA_IActuator
-{
- Py_Header
- bool m_lastEvent;
- class NG_NetworkScene* m_networkscene; // needed for replication
- STR_String m_toPropName;
- STR_String m_subject;
- bool m_bPropBody;
- STR_String m_body;
-public:
- KX_NetworkMessageActuator(
- SCA_IObject* gameobj,
- NG_NetworkScene* networkscene,
- const STR_String &toPropName,
- const STR_String &subject,
- int bodyType,
- const STR_String &body);
- virtual ~KX_NetworkMessageActuator();
-
- virtual bool Update();
- virtual CValue* GetReplica();
- virtual void Replace_NetworkScene(NG_NetworkScene *val)
- {
- m_networkscene= val;
- };
-
- /* ------------------------------------------------------------ */
- /* Python interface ------------------------------------------- */
- /* ------------------------------------------------------------ */
-
-};
-
-#endif /* __KX_NETWORKMESSAGEACTUATOR_H__ */
diff --git a/source/gameengine/Ketsji/KXNetwork/KX_NetworkMessageSensor.cpp b/source/gameengine/Ketsji/KXNetwork/KX_NetworkMessageSensor.cpp
deleted file mode 100644
index 1fadd9382e0..00000000000
--- a/source/gameengine/Ketsji/KXNetwork/KX_NetworkMessageSensor.cpp
+++ /dev/null
@@ -1,224 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- * Ketsji Logic Extension: Network Message Sensor generic implementation
- */
-
-/** \file gameengine/Ketsji/KXNetwork/KX_NetworkMessageSensor.cpp
- * \ingroup ketsjinet
- */
-
-
-#include <stddef.h>
-
-#include "KX_NetworkMessageSensor.h"
-#include "KX_NetworkEventManager.h"
-#include "NG_NetworkMessage.h"
-#include "NG_NetworkScene.h"
-#include "NG_NetworkObject.h"
-#include "SCA_IObject.h"
-#include "EXP_InputParser.h"
-#include "EXP_ListValue.h"
-#include "EXP_StringValue.h"
-
-#ifdef NAN_NET_DEBUG
- #include <iostream>
-#endif
-
-KX_NetworkMessageSensor::KX_NetworkMessageSensor(
- class KX_NetworkEventManager* eventmgr, // our eventmanager
- class NG_NetworkScene *NetworkScene, // our scene
- SCA_IObject* gameobj, // the sensor controlling object
- const STR_String &subject
- ) :
- SCA_ISensor(gameobj,eventmgr),
- m_NetworkScene(NetworkScene),
- m_subject(subject),
- m_frame_message_count (0),
- m_BodyList(NULL),
- m_SubjectList(NULL)
-{
- Init();
-}
-
-void KX_NetworkMessageSensor::Init()
-{
- m_IsUp = false;
-}
-
-KX_NetworkMessageSensor::~KX_NetworkMessageSensor()
-{
-}
-
-CValue* KX_NetworkMessageSensor::GetReplica()
-{
- // This is the standard sensor implementation of GetReplica
- // There may be more network message sensor specific stuff to do here.
- CValue* replica = new KX_NetworkMessageSensor(*this);
-
- if (replica == NULL) return NULL;
- replica->ProcessReplica();
-
- return replica;
-}
-
-// Return true only for flank (UP and DOWN)
-bool KX_NetworkMessageSensor::Evaluate()
-{
- bool result = false;
- bool WasUp = m_IsUp;
-
- m_IsUp = false;
-
- if (m_BodyList) {
- m_BodyList->Release();
- m_BodyList = NULL;
- }
-
- if (m_SubjectList) {
- m_SubjectList->Release();
- m_SubjectList = NULL;
- }
-
- STR_String& toname=GetParent()->GetName();
- STR_String& subject = this->m_subject;
-
- vector<NG_NetworkMessage*> messages =
- m_NetworkScene->FindMessages(toname,"",subject,true);
-
- m_frame_message_count = messages.size();
-
- if (!messages.empty()) {
-#ifdef NAN_NET_DEBUG
- printf("KX_NetworkMessageSensor found one or more messages\n");
-#endif
- m_IsUp = true;
- m_BodyList = new CListValue();
- m_SubjectList = new CListValue();
- }
-
- vector<NG_NetworkMessage*>::iterator mesit;
- for (mesit=messages.begin();mesit!=messages.end();mesit++)
- {
- // save the body
- const STR_String& body = (*mesit)->GetMessageText();
- // save the subject
- const STR_String& messub = (*mesit)->GetSubject();
-#ifdef NAN_NET_DEBUG
- if (body) {
- cout << "body [" << body << "]\n";
- }
-#endif
- m_BodyList->Add(new CStringValue(body,"body"));
- // Store Subject
- m_SubjectList->Add(new CStringValue(messub,"subject"));
-
- // free the message
- (*mesit)->Release();
- }
- messages.clear();
-
- result = (WasUp != m_IsUp);
-
- // Return always true if a message was received otherwise we can loose messages
- if (m_IsUp)
- return true;
- // Is it useful to return also true when the first frame without a message??
- // This will cause a fast on/off cycle that seems useless!
- return result;
-}
-
-// return true for being up (no flank needed)
-bool KX_NetworkMessageSensor::IsPositiveTrigger()
-{
-// printf("KX_NetworkMessageSensor IsPositiveTrigger\n");
- //attempt to fix [ #3809 ] IPO Actuator does not work with some Sensors
- //a better solution is to properly introduce separate Edge and Level triggering concept
-
- return m_IsUp;
-}
-
-#ifdef WITH_PYTHON
-
-/* --------------------------------------------------------------------- */
-/* Python interface ---------------------------------------------------- */
-/* --------------------------------------------------------------------- */
-
-/* Integration hooks --------------------------------------------------- */
-PyTypeObject KX_NetworkMessageSensor::Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "KX_NetworkMessageSensor",
- sizeof(PyObjectPlus_Proxy),
- 0,
- py_base_dealloc,
- 0,
- 0,
- 0,
- 0,
- py_base_repr,
- 0,0,0,0,0,0,0,0,0,
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
- 0,0,0,0,0,0,0,
- Methods,
- 0,
- 0,
- &SCA_ISensor::Type,
- 0,0,0,0,0,0,
- py_base_new
-};
-
-PyMethodDef KX_NetworkMessageSensor::Methods[] = {
- {NULL,NULL} //Sentinel
-};
-
-PyAttributeDef KX_NetworkMessageSensor::Attributes[] = {
- KX_PYATTRIBUTE_STRING_RW("subject", 0, 100, false, KX_NetworkMessageSensor, m_subject),
- KX_PYATTRIBUTE_INT_RO("frameMessageCount", KX_NetworkMessageSensor, m_frame_message_count),
- KX_PYATTRIBUTE_RO_FUNCTION("bodies", KX_NetworkMessageSensor, pyattr_get_bodies),
- KX_PYATTRIBUTE_RO_FUNCTION("subjects", KX_NetworkMessageSensor, pyattr_get_subjects),
- { NULL } //Sentinel
-};
-
-PyObject *KX_NetworkMessageSensor::pyattr_get_bodies(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_NetworkMessageSensor *self = static_cast<KX_NetworkMessageSensor*>(self_v);
- if (self->m_BodyList) {
- return self->m_BodyList->GetProxy();
- } else {
- return (new CListValue())->NewProxy(true);
- }
-}
-
-PyObject *KX_NetworkMessageSensor::pyattr_get_subjects(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_NetworkMessageSensor *self = static_cast<KX_NetworkMessageSensor*>(self_v);
- if (self->m_SubjectList) {
- return self->m_SubjectList->GetProxy();
- } else {
- return (new CListValue())->NewProxy(true);
- }
-}
-
-#endif // WITH_PYTHON
diff --git a/source/gameengine/Ketsji/KXNetwork/KX_NetworkMessageSensor.h b/source/gameengine/Ketsji/KXNetwork/KX_NetworkMessageSensor.h
deleted file mode 100644
index a1f0692b7b3..00000000000
--- a/source/gameengine/Ketsji/KXNetwork/KX_NetworkMessageSensor.h
+++ /dev/null
@@ -1,90 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file KX_NetworkMessageSensor.h
- * \ingroup ketsjinet
- * \brief Ketsji Logic Extension: Network Message Sensor class
- */
-#ifndef __KX_NETWORKMESSAGESENSOR_H__
-#define __KX_NETWORKMESSAGESENSOR_H__
-
-#include "SCA_ISensor.h"
-
-class KX_NetworkEventManager;
-class NG_NetworkScene;
-
-class KX_NetworkMessageSensor : public SCA_ISensor
-{
- // note: Py_Header MUST BE the first listed here
- Py_Header
- NG_NetworkScene *m_NetworkScene;
-
- // The subject we filter on.
- STR_String m_subject;
-
- // The number of messages caught since the last frame.
- int m_frame_message_count;
-
- bool m_IsUp;
-
- class CListValue* m_BodyList;
- class CListValue* m_SubjectList;
-public:
- KX_NetworkMessageSensor(
- KX_NetworkEventManager* eventmgr, // our eventmanager
- NG_NetworkScene *NetworkScene, // our scene
- SCA_IObject* gameobj, // the sensor controlling object
- const STR_String &subject
- );
- virtual ~KX_NetworkMessageSensor();
-
- virtual CValue* GetReplica();
- virtual bool Evaluate();
- virtual bool IsPositiveTrigger();
- virtual void Init();
- void EndFrame();
-
- virtual void Replace_NetworkScene(NG_NetworkScene *val)
- {
- m_NetworkScene= val;
- };
-
-#ifdef WITH_PYTHON
-
- /* ------------------------------------------------------------- */
- /* Python interface -------------------------------------------- */
- /* ------------------------------------------------------------- */
-
- /* attributes */
- static PyObject* pyattr_get_bodies(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_subjects(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef);
-
-#endif /* WITH_PYTHON */
-
-};
-
-#endif /* __KX_NETWORKMESSAGESENSOR_H__ */
diff --git a/source/gameengine/Ketsji/KXNetwork/KX_NetworkObjectActuator.cpp b/source/gameengine/Ketsji/KXNetwork/KX_NetworkObjectActuator.cpp
deleted file mode 100644
index b8032f8e037..00000000000
--- a/source/gameengine/Ketsji/KXNetwork/KX_NetworkObjectActuator.cpp
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Ketsji/KXNetwork/KX_NetworkObjectActuator.cpp
- * \ingroup ketsjinet
- */
-
diff --git a/source/gameengine/Ketsji/KXNetwork/KX_NetworkObjectActuator.h b/source/gameengine/Ketsji/KXNetwork/KX_NetworkObjectActuator.h
deleted file mode 100644
index 36e0e6c39ec..00000000000
--- a/source/gameengine/Ketsji/KXNetwork/KX_NetworkObjectActuator.h
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Ketsji/KXNetwork/KX_NetworkObjectActuator.h
- * \ingroup ketsjinet
- */
-
-
diff --git a/source/gameengine/Ketsji/KXNetwork/KX_NetworkObjectSensor.cpp b/source/gameengine/Ketsji/KXNetwork/KX_NetworkObjectSensor.cpp
deleted file mode 100644
index bc6da2e4143..00000000000
--- a/source/gameengine/Ketsji/KXNetwork/KX_NetworkObjectSensor.cpp
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Ketsji/KXNetwork/KX_NetworkObjectSensor.cpp
- * \ingroup ketsjinet
- */
-
-
diff --git a/source/gameengine/Ketsji/KXNetwork/KX_NetworkObjectSensor.h b/source/gameengine/Ketsji/KXNetwork/KX_NetworkObjectSensor.h
deleted file mode 100644
index 00aa53feb27..00000000000
--- a/source/gameengine/Ketsji/KXNetwork/KX_NetworkObjectSensor.h
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Ketsji/KXNetwork/KX_NetworkObjectSensor.h
- * \ingroup ketsjinet
- */
-
-
diff --git a/source/gameengine/Ketsji/KX_ArmatureSensor.cpp b/source/gameengine/Ketsji/KX_ArmatureSensor.cpp
deleted file mode 100644
index c111a4de0eb..00000000000
--- a/source/gameengine/Ketsji/KX_ArmatureSensor.cpp
+++ /dev/null
@@ -1,208 +0,0 @@
-/*
- * Armature sensor
- *
- *
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Ketsji/KX_ArmatureSensor.cpp
- * \ingroup ketsji
- */
-
-
-#include "DNA_action_types.h"
-#include "DNA_constraint_types.h"
-#include "BKE_constraint.h"
-#include "DNA_sensor_types.h"
-
-#include "BL_ArmatureObject.h"
-#include "KX_ArmatureSensor.h"
-#include "SCA_EventManager.h"
-#include "SCA_LogicManager.h"
-
-KX_ArmatureSensor::KX_ArmatureSensor(class SCA_EventManager* eventmgr,
- SCA_IObject* gameobj,
- const char *posechannel,
- const char *constraintname,
- int type,
- float value)
- : SCA_ISensor(gameobj,eventmgr),
- m_constraint(NULL),
- m_posechannel(posechannel),
- m_constraintname(constraintname),
- m_type(type),
- m_value(value)
-{
- FindConstraint();
-}
-
-void KX_ArmatureSensor::Init()
-{
- m_lastresult = m_invert?true:false;
- m_result = false;
- m_reset = true;
-}
-
-void KX_ArmatureSensor::FindConstraint()
-{
- m_constraint = NULL;
-
- if (m_gameobj->GetGameObjectType() == SCA_IObject::OBJ_ARMATURE) {
- BL_ArmatureObject* armobj = (BL_ArmatureObject*)m_gameobj;
- // get the persistent pose structure
- bPose* pose = armobj->GetOrigPose();
- bPoseChannel* pchan;
- bConstraint* pcon;
- // and locate the constraint
- for (pchan = (bPoseChannel*)pose->chanbase.first; pchan; pchan=(bPoseChannel*)pchan->next) {
- if (!strcmp(pchan->name, m_posechannel)) {
- // now locate the constraint
- for (pcon = (bConstraint *)pchan->constraints.first; pcon; pcon = (bConstraint *)pcon->next) {
- if (!strcmp(pcon->name, m_constraintname)) {
- if (pcon->flag & CONSTRAINT_DISABLE)
- /* this constraint is not valid, can't use it */
- break;
- m_constraint = pcon;
- break;
- }
- }
- break;
- }
- }
- }
-}
-
-
-CValue* KX_ArmatureSensor::GetReplica()
-{
- KX_ArmatureSensor* replica = new KX_ArmatureSensor(*this);
- // m_range_expr must be recalculated on replica!
- replica->ProcessReplica();
- return replica;
-}
-
-void KX_ArmatureSensor::ReParent(SCA_IObject* parent)
-{
- SCA_ISensor::ReParent(parent);
- // must remap the constraint
- FindConstraint();
-}
-
-bool KX_ArmatureSensor::IsPositiveTrigger()
-{
- return (m_invert) ? !m_result : m_result;
-}
-
-
-KX_ArmatureSensor::~KX_ArmatureSensor()
-{
-}
-
-bool KX_ArmatureSensor::Evaluate()
-{
- bool reset = m_reset && m_level;
-
- m_reset = false;
- if (!m_constraint)
- return false;
- switch (m_type) {
- case SENS_ARM_STATE_CHANGED:
- m_result = !(m_constraint->flag & CONSTRAINT_OFF);
- break;
- case SENS_ARM_LIN_ERROR_BELOW:
- m_result = (m_constraint->lin_error < m_value);
- break;
- case SENS_ARM_LIN_ERROR_ABOVE:
- m_result = (m_constraint->lin_error > m_value);
- break;
- case SENS_ARM_ROT_ERROR_BELOW:
- m_result = (m_constraint->rot_error < m_value);
- break;
- case SENS_ARM_ROT_ERROR_ABOVE:
- m_result = (m_constraint->rot_error > m_value);
- break;
- }
- if (m_lastresult!=m_result)
- {
- m_lastresult = m_result;
- return true;
- }
- return (reset) ? true : false;
-}
-
-#ifdef WITH_PYTHON
-
-/* ------------------------------------------------------------------------- */
-/* Python functions */
-/* ------------------------------------------------------------------------- */
-
-/* Integration hooks ------------------------------------------------------- */
-PyTypeObject KX_ArmatureSensor::Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "KX_ArmatureSensor",
- sizeof(PyObjectPlus_Proxy),
- 0,
- py_base_dealloc,
- 0,
- 0,
- 0,
- 0,
- py_base_repr,
- 0,0,0,0,0,0,0,0,0,
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
- 0,0,0,0,0,0,0,
- Methods,
- 0,
- 0,
- &SCA_ISensor::Type,
- 0,0,0,0,0,0,
- py_base_new
-};
-
-PyMethodDef KX_ArmatureSensor::Methods[] = {
- {NULL,NULL} //Sentinel
-};
-
-PyAttributeDef KX_ArmatureSensor::Attributes[] = {
- KX_PYATTRIBUTE_RO_FUNCTION("constraint", KX_ArmatureSensor, pyattr_get_constraint),
- KX_PYATTRIBUTE_FLOAT_RW("value",-FLT_MAX,FLT_MAX,KX_ArmatureSensor,m_value),
- KX_PYATTRIBUTE_INT_RW("type",0,SENS_ARM_MAXTYPE,false,KX_ArmatureSensor,m_type),
- { NULL } //Sentinel
-};
-
-PyObject *KX_ArmatureSensor::pyattr_get_constraint(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_ArmatureSensor* sensor = static_cast<KX_ArmatureSensor*>(self);
- if (sensor->m_gameobj->GetGameObjectType() == SCA_IObject::OBJ_ARMATURE) {
- BL_ArmatureObject* armobj = (BL_ArmatureObject*)sensor->m_gameobj;
- BL_ArmatureConstraint* constraint = armobj->GetConstraint(sensor->m_posechannel, sensor->m_constraintname);
- if (constraint)
- return constraint->GetProxy();
- }
- Py_RETURN_NONE;
-}
-
-#endif // WITH_PYTHON
diff --git a/source/gameengine/Ketsji/KX_ArmatureSensor.h b/source/gameengine/Ketsji/KX_ArmatureSensor.h
deleted file mode 100644
index b3ea905d198..00000000000
--- a/source/gameengine/Ketsji/KX_ArmatureSensor.h
+++ /dev/null
@@ -1,90 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file KX_ArmatureSensor.h
- * \ingroup ketsji
- * \brief Property sensor
- */
-
-#ifndef __KX_ARMATURESENSOR_H__
-#define __KX_ARMATURESENSOR_H__
-
-struct bConstraint;
-
-#include "SCA_ISensor.h"
-#include "DNA_sensor_types.h"
-
-class KX_ArmatureSensor : public SCA_ISensor
-{
- Py_Header
- //class CExpression* m_rightexpr;
-
-protected:
-
-public:
- KX_ArmatureSensor(class SCA_EventManager* eventmgr,
- SCA_IObject* gameobj,
- const char *posechannel,
- const char *constraintname,
- int type,
- float value);
-
- /**
- * For property sensor, it is used to release the pre-calculated expression
- * so that self references are removed before the sensor itself is released
- */
- virtual ~KX_ArmatureSensor();
- virtual CValue* GetReplica();
- virtual void ReParent(SCA_IObject* parent);
- virtual void Init();
- virtual bool Evaluate();
- virtual bool IsPositiveTrigger();
-
- // identify the constraint that this actuator controls
- void FindConstraint();
-
-#ifdef WITH_PYTHON
-
- /* --------------------------------------------------------------------- */
- /* Python interface ---------------------------------------------------- */
- /* --------------------------------------------------------------------- */
- static PyObject *pyattr_get_constraint(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef);
-
-#endif /* WITH_PYTHON */
-
-private:
- struct bConstraint* m_constraint;
- STR_String m_posechannel;
- STR_String m_constraintname;
- int m_type;
- float m_value;
- bool m_result;
- bool m_lastresult;
-};
-
-#endif
-
diff --git a/source/gameengine/Ketsji/KX_BlenderMaterial.cpp b/source/gameengine/Ketsji/KX_BlenderMaterial.cpp
deleted file mode 100644
index 98d27ef3685..00000000000
--- a/source/gameengine/Ketsji/KX_BlenderMaterial.cpp
+++ /dev/null
@@ -1,1334 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Ketsji/KX_BlenderMaterial.cpp
- * \ingroup ketsji
- */
-
-#include "GPU_glew.h"
-
-#include "KX_BlenderMaterial.h"
-#include "BL_Material.h"
-#include "KX_Scene.h"
-#include "KX_Light.h"
-#include "KX_GameObject.h"
-#include "KX_MeshProxy.h"
-#include "KX_PyMath.h"
-
-#include "MT_Vector3.h"
-#include "MT_Vector4.h"
-#include "MT_Matrix4x4.h"
-
-#include "RAS_BucketManager.h"
-#include "RAS_MeshObject.h"
-#include "RAS_IRasterizer.h"
-
-#include "GPU_draw.h"
-
-#include "STR_HashedString.h"
-
-// ------------------------------------
-#include "DNA_object_types.h"
-#include "DNA_material_types.h"
-#include "DNA_image_types.h"
-#include "DNA_meshdata_types.h"
-#include "BKE_mesh.h"
-// ------------------------------------
-#include "BLI_utildefines.h"
-#include "BLI_math.h"
-
-#define spit(x) std::cout << x << std::endl;
-
-BL_Shader *KX_BlenderMaterial::mLastShader = NULL;
-BL_BlenderShader *KX_BlenderMaterial::mLastBlenderShader = NULL;
-
-//static PyObject *gTextureDict = 0;
-
-KX_BlenderMaterial::KX_BlenderMaterial()
-: PyObjectPlus(),
- RAS_IPolyMaterial(),
- mMaterial(NULL),
- mShader(0),
- mBlenderShader(0),
- mScene(NULL),
- mUserDefBlend(0),
- mModified(0),
- mConstructed(false),
- mPass(0)
-{
-}
-
-void KX_BlenderMaterial::Initialize(
- KX_Scene *scene,
- BL_Material *data,
- GameSettings *game,
- int lightlayer)
-{
- RAS_IPolyMaterial::Initialize(
- data->texname[0],
- data->matname,
- data->materialindex,
- data->tile,
- data->tilexrep[0],
- data->tileyrep[0],
- data->alphablend,
- ((data->ras_mode &ALPHA)!=0),
- ((data->ras_mode &ZSORT)!=0),
- ((data->ras_mode &USE_LIGHT)!=0),
- ((data->ras_mode &TEX)),
- game
- );
- Material *ma = data->material;
-
- // Save material data to restore on exit
- mSavedData.r = ma->r;
- mSavedData.g = ma->g;
- mSavedData.b = ma->b;
- mSavedData.a = ma->alpha;
- mSavedData.specr = ma->specr;
- mSavedData.specg = ma->specg;
- mSavedData.specb = ma->specb;
- mSavedData.spec = ma->spec;
- mSavedData.ref = ma->ref;
- mSavedData.hardness = ma->har;
- mSavedData.emit = ma->emit;
-
- mMaterial = data;
- mShader = 0;
- mBlenderShader = 0;
- mScene = scene;
- mUserDefBlend = 0;
- mModified = 0;
- mConstructed = false;
- mPass = 0;
- mLightLayer = lightlayer;
- // --------------------------------
- // RAS_IPolyMaterial variables...
- m_flag |= RAS_BLENDERMAT;
- m_flag |= (mMaterial->IdMode>=ONETEX)? RAS_MULTITEX: 0;
- m_flag |= ((mMaterial->ras_mode & USE_LIGHT)!=0)? RAS_MULTILIGHT: 0;
- m_flag |= (mMaterial->glslmat)? RAS_BLENDERGLSL: 0;
- m_flag |= ((mMaterial->ras_mode & CAST_SHADOW)!=0)? RAS_CASTSHADOW: 0;
- m_flag |= ((mMaterial->ras_mode & ONLY_SHADOW)!=0)? RAS_ONLYSHADOW: 0;
-
- // test the sum of the various modes for equality
- // so we can ether accept or reject this material
- // as being equal, this is rather important to
- // prevent material bleeding
- for (int i=0; i<BL_Texture::GetMaxUnits(); i++) {
- m_multimode += (mMaterial->flag[i] + mMaterial->blend_mode[i]);
- }
- m_multimode += mMaterial->IdMode+ (mMaterial->ras_mode & ~(USE_LIGHT));
-}
-
-KX_BlenderMaterial::~KX_BlenderMaterial()
-{
- Material *ma = mMaterial->material;
- // Restore Blender material data
- ma->r = mSavedData.r;
- ma->g = mSavedData.g;
- ma->b = mSavedData.b;
- ma->alpha = mSavedData.a;
- ma->specr = mSavedData.specr;
- ma->specg = mSavedData.specg;
- ma->specb = mSavedData.specb;
- ma->spec = mSavedData.spec;
- ma->ref = mSavedData.ref;
- ma->har = mSavedData.hardness;
- ma->emit = mSavedData.emit;
-
- // cleanup work
- if (mConstructed)
- // clean only if material was actually used
- OnExit();
-}
-
-unsigned int* KX_BlenderMaterial::GetMCol() const
-{
- // fonts on polys
- return mMaterial->rgb;
-}
-
-void KX_BlenderMaterial::GetMaterialRGBAColor(unsigned char *rgba) const
-{
- if (mMaterial) {
- *rgba++ = (unsigned char)(mMaterial->matcolor[0] * 255.0f);
- *rgba++ = (unsigned char)(mMaterial->matcolor[1] * 255.0f);
- *rgba++ = (unsigned char)(mMaterial->matcolor[2] * 255.0f);
- *rgba++ = (unsigned char)(mMaterial->matcolor[3] * 255.0f);
- } else
- RAS_IPolyMaterial::GetMaterialRGBAColor(rgba);
-}
-
-Material *KX_BlenderMaterial::GetBlenderMaterial() const
-{
- return mMaterial->material;
-}
-
-Image *KX_BlenderMaterial::GetBlenderImage() const
-{
- return mMaterial->material ? mMaterial->material->edit_image : NULL;
-}
-
-Scene* KX_BlenderMaterial::GetBlenderScene() const
-{
- return mScene->GetBlenderScene();
-}
-
-void KX_BlenderMaterial::ReleaseMaterial()
-{
- if (mBlenderShader)
- mBlenderShader->ReloadMaterial();
-}
-
-void KX_BlenderMaterial::InitTextures()
-{
- // for each unique material...
- int i;
- for (i=0; i<BL_Texture::GetMaxUnits(); i++) {
- if ( mMaterial->mapping[i].mapping & USEENV ) {
- if (!GLEW_ARB_texture_cube_map) {
- spit("CubeMap textures not supported");
- continue;
- }
- if (!mTextures[i].InitCubeMap(i, mMaterial->cubemap[i] ) )
- spit("unable to initialize image("<<i<<") in "<<
- mMaterial->matname<< ", image will not be available");
- }
- /* If we're using glsl materials, the textures are handled by bf_gpu, so don't load them twice!
- * However, if we're using a custom shader, then we still need to load the textures ourselves. */
- else if (!mMaterial->glslmat || mShader) {
- if ( mMaterial->img[i] ) {
- if ( ! mTextures[i].InitFromImage(i, mMaterial->img[i], (mMaterial->flag[i] &MIPMAP)!=0 ))
- spit("unable to initialize image("<<i<<") in "<<
- mMaterial->matname<< ", image will not be available");
- }
- }
- }
-}
-
-void KX_BlenderMaterial::OnConstruction()
-{
- if (mConstructed)
- // when material are reused between objects
- return;
-
- if (mMaterial->glslmat)
- SetBlenderGLSLShader();
-
- InitTextures();
-
- mBlendFunc[0] =0;
- mBlendFunc[1] =0;
- mConstructed = true;
-}
-
-void KX_BlenderMaterial::EndFrame()
-{
- if (mLastBlenderShader) {
- mLastBlenderShader->SetProg(false);
- mLastBlenderShader = NULL;
- }
-
- if (mLastShader) {
- mLastShader->SetProg(false);
- mLastShader = NULL;
- }
-}
-
-void KX_BlenderMaterial::OnExit()
-{
- if ( mShader ) {
- //note, the shader here is allocated, per unique material
- //and this function is called per face
- if (mShader == mLastShader) {
- mShader->SetProg(false);
- mLastShader = NULL;
- }
-
- delete mShader;
- mShader = 0;
- }
-
- if ( mBlenderShader ) {
- if (mBlenderShader == mLastBlenderShader) {
- mBlenderShader->SetProg(false);
- mLastBlenderShader = NULL;
- }
-
- delete mBlenderShader;
- mBlenderShader = 0;
- }
-
- BL_Texture::ActivateFirst();
- for (int i=0; i<BL_Texture::GetMaxUnits(); i++) {
- if (!mTextures[i].Ok()) continue;
- BL_Texture::ActivateUnit(i);
- mTextures[i].DeleteTex();
- mTextures[i].DisableUnit();
- }
-}
-
-
-void KX_BlenderMaterial::setShaderData( bool enable, RAS_IRasterizer *ras)
-{
- MT_assert(GLEW_ARB_shader_objects && mShader);
-
- int i;
- if ( !enable || !mShader->Ok() ) {
- // frame cleanup.
- if (mShader == mLastShader) {
- mShader->SetProg(false);
- mLastShader = NULL;
- }
-
- ras->SetAlphaBlend(GPU_BLEND_SOLID);
- BL_Texture::DisableAllTextures();
- return;
- }
-
- BL_Texture::DisableAllTextures();
- mShader->SetProg(true);
- mLastShader = mShader;
-
- BL_Texture::ActivateFirst();
-
- mShader->ApplyShader();
-
- // for each enabled unit
- for (i=0; i<BL_Texture::GetMaxUnits(); i++) {
- if (!mTextures[i].Ok()) continue;
- mTextures[i].ActivateTexture();
- mTextures[0].SetMapping(mMaterial->mapping[i].mapping);
- }
-
- if (!mUserDefBlend) {
- ras->SetAlphaBlend(mMaterial->alphablend);
- }
- else {
- ras->SetAlphaBlend(GPU_BLEND_SOLID);
- ras->SetAlphaBlend(-1); // indicates custom mode
-
- // tested to be valid enums
- glEnable(GL_BLEND);
- glBlendFunc(mBlendFunc[0], mBlendFunc[1]);
- }
-}
-
-void KX_BlenderMaterial::setBlenderShaderData( bool enable, RAS_IRasterizer *ras)
-{
- if ( !enable || !mBlenderShader->Ok() ) {
- ras->SetAlphaBlend(GPU_BLEND_SOLID);
-
- // frame cleanup.
- if (mLastBlenderShader) {
- mLastBlenderShader->SetProg(false);
- mLastBlenderShader= NULL;
- }
- else
- BL_Texture::DisableAllTextures();
-
- return;
- }
-
- if (!mBlenderShader->Equals(mLastBlenderShader)) {
- ras->SetAlphaBlend(mMaterial->alphablend);
-
- if (mLastBlenderShader)
- mLastBlenderShader->SetProg(false);
- else
- BL_Texture::DisableAllTextures();
-
- mBlenderShader->SetProg(true, ras->GetTime(), ras);
- mLastBlenderShader= mBlenderShader;
- }
-}
-
-void KX_BlenderMaterial::setTexData( bool enable, RAS_IRasterizer *ras)
-{
- BL_Texture::DisableAllTextures();
-
- if ( !enable ) {
- ras->SetAlphaBlend(GPU_BLEND_SOLID);
- return;
- }
-
- BL_Texture::ActivateFirst();
-
- if ( mMaterial->IdMode == DEFAULT_BLENDER ) {
- ras->SetAlphaBlend(mMaterial->alphablend);
- return;
- }
-
- if ( mMaterial->IdMode == TEXFACE ) {
- // no material connected to the object
- if ( mTextures[0].Ok() ) {
- mTextures[0].ActivateTexture();
- mTextures[0].setTexEnv(0, true);
- mTextures[0].SetMapping(mMaterial->mapping[0].mapping);
- ras->SetAlphaBlend(mMaterial->alphablend);
- }
- return;
- }
-
- int mode = 0,i=0;
- for (i=0; i<BL_Texture::GetMaxUnits(); i++) {
- if ( !mTextures[i].Ok() ) continue;
-
- mTextures[i].ActivateTexture();
- mTextures[i].setTexEnv(mMaterial);
- mode = mMaterial->mapping[i].mapping;
-
- if (mode &USEOBJ)
- setObjectMatrixData(i, ras);
- else
- mTextures[i].SetMapping(mode);
-
- if (!(mode &USEOBJ))
- setTexMatrixData( i );
- }
-
- if (!mUserDefBlend) {
- ras->SetAlphaBlend(mMaterial->alphablend);
- }
- else {
- ras->SetAlphaBlend(GPU_BLEND_SOLID);
- ras->SetAlphaBlend(-1); // indicates custom mode
-
- glEnable(GL_BLEND);
- glBlendFunc(mBlendFunc[0], mBlendFunc[1]);
- }
-}
-
-void
-KX_BlenderMaterial::ActivatShaders(
- RAS_IRasterizer* rasty,
- TCachingInfo& cachingInfo)const
-{
- KX_BlenderMaterial *tmp = const_cast<KX_BlenderMaterial*>(this);
-
- // reset...
- if (tmp->mMaterial->IsShared())
- cachingInfo =0;
-
- if (mLastBlenderShader) {
- mLastBlenderShader->SetProg(false);
- mLastBlenderShader= NULL;
- }
-
- if (GetCachingInfo() != cachingInfo) {
-
- if (!cachingInfo)
- tmp->setShaderData(false, rasty);
-
- cachingInfo = GetCachingInfo();
-
- if (rasty->GetDrawingMode() == RAS_IRasterizer::KX_TEXTURED)
- tmp->setShaderData(true, rasty);
- else if (rasty->GetDrawingMode() == RAS_IRasterizer::KX_SHADOW && mMaterial->alphablend != GEMAT_SOLID && !rasty->GetUsingOverrideShader())
- tmp->setShaderData(true, rasty);
- else
- tmp->setShaderData(false, rasty);
-
- if (mMaterial->ras_mode &TWOSIDED)
- rasty->SetCullFace(false);
- else
- rasty->SetCullFace(true);
-
- if ((mMaterial->ras_mode &WIRE) ||
- (rasty->GetDrawingMode() <= RAS_IRasterizer::KX_WIREFRAME))
- {
- if (mMaterial->ras_mode &WIRE)
- rasty->SetCullFace(false);
- rasty->SetLines(true);
- }
- else
- rasty->SetLines(false);
- ActivatGLMaterials(rasty);
- ActivateTexGen(rasty);
- }
-
- //ActivatGLMaterials(rasty);
- //ActivateTexGen(rasty);
-}
-
-void
-KX_BlenderMaterial::ActivateBlenderShaders(
- RAS_IRasterizer* rasty,
- TCachingInfo& cachingInfo)const
-{
- KX_BlenderMaterial *tmp = const_cast<KX_BlenderMaterial*>(this);
-
- if (mLastShader) {
- mLastShader->SetProg(false);
- mLastShader= NULL;
- }
-
- if (GetCachingInfo() != cachingInfo) {
- if (!cachingInfo)
- tmp->setBlenderShaderData(false, rasty);
-
- cachingInfo = GetCachingInfo();
-
- if (rasty->GetDrawingMode() == RAS_IRasterizer::KX_TEXTURED)
- tmp->setBlenderShaderData(true, rasty);
- else if (rasty->GetDrawingMode() == RAS_IRasterizer::KX_SHADOW && mMaterial->alphablend != GEMAT_SOLID && !rasty->GetUsingOverrideShader())
- tmp->setBlenderShaderData(true, rasty);
- else
- tmp->setBlenderShaderData(false, rasty);
-
- if (mMaterial->ras_mode &TWOSIDED)
- rasty->SetCullFace(false);
- else
- rasty->SetCullFace(true);
-
- if ((mMaterial->ras_mode &WIRE) ||
- (rasty->GetDrawingMode() <= RAS_IRasterizer::KX_WIREFRAME))
- {
- if (mMaterial->ras_mode &WIRE)
- rasty->SetCullFace(false);
- rasty->SetLines(true);
- }
- else
- rasty->SetLines(false);
-
- ActivatGLMaterials(rasty);
- mBlenderShader->SetAttribs(rasty, mMaterial);
- }
-}
-
-void
-KX_BlenderMaterial::ActivateMat(
- RAS_IRasterizer* rasty,
- TCachingInfo& cachingInfo
- )const
-{
- KX_BlenderMaterial *tmp = const_cast<KX_BlenderMaterial*>(this);
-
- if (mLastShader) {
- mLastShader->SetProg(false);
- mLastShader= NULL;
- }
-
- if (mLastBlenderShader) {
- mLastBlenderShader->SetProg(false);
- mLastBlenderShader= NULL;
- }
-
- if (GetCachingInfo() != cachingInfo) {
- if (!cachingInfo)
- tmp->setTexData( false,rasty );
-
- cachingInfo = GetCachingInfo();
-
- if (rasty->GetDrawingMode() == RAS_IRasterizer::KX_TEXTURED)
- tmp->setTexData( true,rasty );
- else if (rasty->GetDrawingMode() == RAS_IRasterizer::KX_SHADOW && mMaterial->alphablend != GEMAT_SOLID && !rasty->GetUsingOverrideShader())
- tmp->setTexData(true, rasty);
- else
- tmp->setTexData( false,rasty);
-
- if (mMaterial->ras_mode &TWOSIDED)
- rasty->SetCullFace(false);
- else
- rasty->SetCullFace(true);
-
- if ((mMaterial->ras_mode &WIRE) ||
- (rasty->GetDrawingMode() <= RAS_IRasterizer::KX_WIREFRAME))
- {
- if (mMaterial->ras_mode &WIRE)
- rasty->SetCullFace(false);
- rasty->SetLines(true);
- }
- else
- rasty->SetLines(false);
- ActivatGLMaterials(rasty);
- ActivateTexGen(rasty);
- }
-
- //ActivatGLMaterials(rasty);
- //ActivateTexGen(rasty);
-}
-
-bool
-KX_BlenderMaterial::Activate(
- RAS_IRasterizer* rasty,
- TCachingInfo& cachingInfo
- )const
-{
- if (GLEW_ARB_shader_objects && (mShader && mShader->Ok())) {
- if ((mPass++) < mShader->getNumPass() ) {
- ActivatShaders(rasty, cachingInfo);
- return true;
- }
- else {
- if (mShader == mLastShader) {
- mShader->SetProg(false);
- mLastShader = NULL;
- }
- mPass = 0;
- return false;
- }
- }
- else if ( GLEW_ARB_shader_objects && (mBlenderShader && mBlenderShader->Ok() ) ) {
- if (mPass++ == 0) {
- ActivateBlenderShaders(rasty, cachingInfo);
- return true;
- }
- else {
- mPass = 0;
- return false;
- }
- }
- else {
- if (mPass++ == 0) {
- ActivateMat(rasty, cachingInfo);
- return true;
- }
- else {
- mPass = 0;
- return false;
- }
- }
-}
-
-bool KX_BlenderMaterial::UsesLighting(RAS_IRasterizer *rasty) const
-{
- if (!RAS_IPolyMaterial::UsesLighting(rasty))
- return false;
-
- if (mShader && mShader->Ok())
- return true;
- else if (mBlenderShader && mBlenderShader->Ok())
- return false;
- else
- return true;
-}
-
-void KX_BlenderMaterial::ActivateMeshSlot(const RAS_MeshSlot & ms, RAS_IRasterizer* rasty) const
-{
- if (mShader && GLEW_ARB_shader_objects) {
- mShader->Update(ms, rasty);
- }
- else if (mBlenderShader && GLEW_ARB_shader_objects) {
- int alphablend;
-
- mBlenderShader->Update(ms, rasty);
-
- /* we do blend modes here, because they can change per object
- * with the same material due to obcolor/obalpha */
- alphablend = mBlenderShader->GetAlphaBlend();
- if (ELEM(alphablend, GEMAT_SOLID, GEMAT_ALPHA, GEMAT_ALPHA_SORT) && mMaterial->alphablend != GEMAT_SOLID)
- alphablend = mMaterial->alphablend;
-
- rasty->SetAlphaBlend(alphablend);
- }
-}
-
-void KX_BlenderMaterial::ActivatGLMaterials( RAS_IRasterizer* rasty )const
-{
- if (mShader || !mBlenderShader) {
- rasty->SetSpecularity(
- mMaterial->speccolor[0]*mMaterial->spec_f,
- mMaterial->speccolor[1]*mMaterial->spec_f,
- mMaterial->speccolor[2]*mMaterial->spec_f,
- mMaterial->spec_f
- );
-
- rasty->SetShinyness( mMaterial->hard );
-
- rasty->SetDiffuse(
- mMaterial->matcolor[0]*mMaterial->ref+mMaterial->emit,
- mMaterial->matcolor[1]*mMaterial->ref+mMaterial->emit,
- mMaterial->matcolor[2]*mMaterial->ref+mMaterial->emit,
- 1.0f);
-
- rasty->SetEmissive(
- mMaterial->matcolor[0]*mMaterial->emit,
- mMaterial->matcolor[1]*mMaterial->emit,
- mMaterial->matcolor[2]*mMaterial->emit,
- 1.0f );
-
- rasty->SetAmbient(mMaterial->amb);
- }
-
- if (mMaterial->material)
- rasty->SetPolygonOffset(-mMaterial->material->zoffs, 0.0f);
-}
-
-
-void KX_BlenderMaterial::ActivateTexGen(RAS_IRasterizer *ras) const
-{
- if (ras->GetDrawingMode() == RAS_IRasterizer::KX_TEXTURED ||
- (ras->GetDrawingMode() == RAS_IRasterizer::KX_SHADOW && mMaterial->alphablend != GEMAT_SOLID && !ras->GetUsingOverrideShader())) {
- ras->SetAttribNum(0);
- if (mShader && GLEW_ARB_shader_objects) {
- if (mShader->GetAttribute() == BL_Shader::SHD_TANGENT) {
- ras->SetAttrib(RAS_IRasterizer::RAS_TEXCO_DISABLE, 0);
- ras->SetAttrib(RAS_IRasterizer::RAS_TEXTANGENT, 1);
- ras->SetAttribNum(2);
- }
- }
-
- ras->SetTexCoordNum(mMaterial->num_enabled);
-
- for (int i=0; i<BL_Texture::GetMaxUnits(); i++) {
- int mode = mMaterial->mapping[i].mapping;
-
- if ( mode &(USEREFL|USEOBJ))
- ras->SetTexCoord(RAS_IRasterizer::RAS_TEXCO_GEN, i);
- else if (mode &USEORCO)
- ras->SetTexCoord(RAS_IRasterizer::RAS_TEXCO_ORCO, i);
- else if (mode &USENORM)
- ras->SetTexCoord(RAS_IRasterizer::RAS_TEXCO_NORM, i);
- else if (mode &USEUV)
- ras->SetTexCoord(RAS_IRasterizer::RAS_TEXCO_UV, i);
- else if (mode &USETANG)
- ras->SetTexCoord(RAS_IRasterizer::RAS_TEXTANGENT, i);
- else
- ras->SetTexCoord(RAS_IRasterizer::RAS_TEXCO_DISABLE, i);
- }
- }
-}
-
-void KX_BlenderMaterial::setTexMatrixData(int i)
-{
- glMatrixMode(GL_TEXTURE);
- glLoadIdentity();
-
- if ( GLEW_ARB_texture_cube_map &&
- mTextures[i].GetTextureType() == GL_TEXTURE_CUBE_MAP_ARB &&
- mMaterial->mapping[i].mapping & USEREFL) {
- glScalef(
- mMaterial->mapping[i].scale[0],
- -mMaterial->mapping[i].scale[1],
- -mMaterial->mapping[i].scale[2]
- );
- }
- else
- {
- glScalef(
- mMaterial->mapping[i].scale[0],
- mMaterial->mapping[i].scale[1],
- mMaterial->mapping[i].scale[2]
- );
- }
- glTranslatef(
- mMaterial->mapping[i].offsets[0],
- mMaterial->mapping[i].offsets[1],
- mMaterial->mapping[i].offsets[2]
- );
-
- glMatrixMode(GL_MODELVIEW);
-
-}
-
-static void GetProjPlane(BL_Material *mat, int index,int num, float*param)
-{
- param[0]=param[1]=param[2]=param[3]=0.f;
- if ( mat->mapping[index].projplane[num] == PROJX )
- param[0] = 1.f;
- else if ( mat->mapping[index].projplane[num] == PROJY )
- param[1] = 1.f;
- else if ( mat->mapping[index].projplane[num] == PROJZ)
- param[2] = 1.f;
-}
-
-void KX_BlenderMaterial::setObjectMatrixData(int i, RAS_IRasterizer *ras)
-{
- KX_GameObject *obj =
- (KX_GameObject*)
- mScene->GetObjectList()->FindValue(mMaterial->mapping[i].objconame);
-
- if (!obj) return;
-
- glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR );
- glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR );
- glTexGeni(GL_R, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR );
-
- GLenum plane = GL_EYE_PLANE;
-
- // figure plane gen
- float proj[4] = {0.f,0.f,0.f,0.f};
- GetProjPlane(mMaterial, i, 0, proj);
- glTexGenfv(GL_S, plane, proj);
-
- GetProjPlane(mMaterial, i, 1, proj);
- glTexGenfv(GL_T, plane, proj);
-
- GetProjPlane(mMaterial, i, 2, proj);
- glTexGenfv(GL_R, plane, proj);
-
- glEnable(GL_TEXTURE_GEN_S);
- glEnable(GL_TEXTURE_GEN_T);
- glEnable(GL_TEXTURE_GEN_R);
-
- const MT_Matrix4x4& mvmat = ras->GetViewMatrix();
-
- glMatrixMode(GL_TEXTURE);
- glLoadIdentity();
- glScalef(
- mMaterial->mapping[i].scale[0],
- mMaterial->mapping[i].scale[1],
- mMaterial->mapping[i].scale[2]
- );
-
- MT_Point3 pos = obj->NodeGetWorldPosition();
- MT_Vector4 matmul = MT_Vector4(pos[0], pos[1], pos[2], 1.f);
- MT_Vector4 t = mvmat*matmul;
-
- glTranslatef( (float)(-t[0]), (float)(-t[1]), (float)(-t[2]) );
-
- glMatrixMode(GL_MODELVIEW);
-
-}
-
-// ------------------------------------
-void KX_BlenderMaterial::UpdateIPO(
- MT_Vector4 rgba,
- MT_Vector3 specrgb,
- MT_Scalar hard,
- MT_Scalar spec,
- MT_Scalar ref,
- MT_Scalar emit,
- MT_Scalar alpha
- )
-{
- // only works one deep now
-
- // GLSL Multitexture Input
- mMaterial->material->specr = mMaterial->speccolor[0] = (float)(specrgb)[0];
- mMaterial->material->specg = mMaterial->speccolor[1] = (float)(specrgb)[1];
- mMaterial->material->specb = mMaterial->speccolor[2] = (float)(specrgb)[2];
- mMaterial->material->r = mMaterial->matcolor[0] = (float)(rgba[0]);
- mMaterial->material->g = mMaterial->matcolor[1] = (float)(rgba[1]);
- mMaterial->material->b = mMaterial->matcolor[2] = (float)(rgba[2]);
- mMaterial->material->alpha = mMaterial->alpha = (float)(rgba[3]);
- mMaterial->material->har = mMaterial->hard = (float)(hard);
- mMaterial->material->emit = mMaterial->emit = (float)(emit);
- mMaterial->material->spec = mMaterial->spec_f = (float)(spec);
- mMaterial->material->ref = mMaterial->ref = (float)(ref);
-}
-
-void KX_BlenderMaterial::Replace_IScene(SCA_IScene *val)
-{
- mScene= static_cast<KX_Scene *>(val);
-
- OnConstruction();
-}
-
-BL_Material *KX_BlenderMaterial::GetBLMaterial()
-{
- return mMaterial;
-}
-
-void KX_BlenderMaterial::SetBlenderGLSLShader()
-{
- if (!mBlenderShader)
- mBlenderShader = new BL_BlenderShader(mScene, mMaterial->material, mLightLayer);
-
- if (!mBlenderShader->Ok()) {
- delete mBlenderShader;
- mBlenderShader = 0;
- }
-}
-
-#ifdef USE_MATHUTILS
-
-#define MATHUTILS_COL_CB_MATERIAL_SPECULAR_COLOR 1
-#define MATHUTILS_COL_CB_MATERIAL_DIFFUSE_COLOR 2
-
-static unsigned char mathutils_kxblendermaterial_color_cb_index = -1; /* index for our callbacks */
-
-static int mathutils_kxblendermaterial_generic_check(BaseMathObject *bmo)
-{
- KX_BlenderMaterial *self = static_cast<KX_BlenderMaterial *>BGE_PROXY_REF(bmo->cb_user);
- if (!self)
- return -1;
-
- return 0;
-}
-
-static int mathutils_kxblendermaterial_color_get(BaseMathObject *bmo, int subtype)
-{
- KX_BlenderMaterial *self = static_cast<KX_BlenderMaterial*>BGE_PROXY_REF(bmo->cb_user);
- if (!self)
- return -1;
-
- switch (subtype) {
- case MATHUTILS_COL_CB_MATERIAL_DIFFUSE_COLOR:
- {
- copy_v3_v3(bmo->data, self->GetBLMaterial()->matcolor);
- break;
- }
- case MATHUTILS_COL_CB_MATERIAL_SPECULAR_COLOR:
- {
- copy_v3_v3(bmo->data, self->GetBLMaterial()->speccolor);
- break;
- }
- }
-
- return 0;
-}
-
-static int mathutils_kxblendermaterial_color_set(BaseMathObject *bmo, int subtype)
-{
- KX_BlenderMaterial *self = static_cast<KX_BlenderMaterial *>BGE_PROXY_REF(bmo->cb_user);
- if (!self)
- return -1;
-
- switch (subtype) {
- case MATHUTILS_COL_CB_MATERIAL_DIFFUSE_COLOR:
- {
- BL_Material *mat = self->GetBLMaterial();
- copy_v3_v3(mat->matcolor, bmo->data);
- mat->material->r = bmo->data[0];
- mat->material->g = bmo->data[1];
- mat->material->b = bmo->data[2];
- break;
- }
- case MATHUTILS_COL_CB_MATERIAL_SPECULAR_COLOR:
- {
- BL_Material *mat = self->GetBLMaterial();
- copy_v3_v3(mat->speccolor, bmo->data);
- mat->material->specr = bmo->data[0];
- mat->material->specg = bmo->data[1];
- mat->material->specb = bmo->data[2];
- break;
- }
- }
-
- return 0;
-}
-
-static int mathutils_kxblendermaterial_color_get_index(BaseMathObject *bmo, int subtype, int index)
-{
- /* lazy, avoid repeteing the case statement */
- if (mathutils_kxblendermaterial_color_get(bmo, subtype) == -1)
- return -1;
- return 0;
-}
-
-static int mathutils_kxblendermaterial_color_set_index(BaseMathObject *bmo, int subtype, int index)
-{
- float f = bmo->data[index];
-
- /* lazy, avoid repeateing the case statement */
- if (mathutils_kxblendermaterial_color_get(bmo, subtype) == -1)
- return -1;
-
- bmo->data[index] = f;
- return mathutils_kxblendermaterial_color_set(bmo, subtype);
-}
-
-static Mathutils_Callback mathutils_kxblendermaterial_color_cb = {
- mathutils_kxblendermaterial_generic_check,
- mathutils_kxblendermaterial_color_get,
- mathutils_kxblendermaterial_color_set,
- mathutils_kxblendermaterial_color_get_index,
- mathutils_kxblendermaterial_color_set_index
-};
-
-
-void KX_BlenderMaterial_Mathutils_Callback_Init()
-{
- // register mathutils callbacks, ok to run more than once.
- mathutils_kxblendermaterial_color_cb_index = Mathutils_RegisterCallback(&mathutils_kxblendermaterial_color_cb);
-}
-
-#endif // USE_MATHUTILS
-
-#ifdef WITH_PYTHON
-
-PyMethodDef KX_BlenderMaterial::Methods[] =
-{
- KX_PYMETHODTABLE( KX_BlenderMaterial, getShader ),
- KX_PYMETHODTABLE( KX_BlenderMaterial, getMaterialIndex ),
- KX_PYMETHODTABLE( KX_BlenderMaterial, getTextureBindcode ),
- KX_PYMETHODTABLE( KX_BlenderMaterial, setBlending ),
- {NULL,NULL} //Sentinel
-};
-
-PyAttributeDef KX_BlenderMaterial::Attributes[] = {
- KX_PYATTRIBUTE_RO_FUNCTION("shader", KX_BlenderMaterial, pyattr_get_shader),
- KX_PYATTRIBUTE_RO_FUNCTION("material_index", KX_BlenderMaterial, pyattr_get_materialIndex),
- KX_PYATTRIBUTE_RW_FUNCTION("blending", KX_BlenderMaterial, pyattr_get_blending, pyattr_set_blending),
- KX_PYATTRIBUTE_RW_FUNCTION("alpha", KX_BlenderMaterial, pyattr_get_alpha, pyattr_set_alpha),
- KX_PYATTRIBUTE_RW_FUNCTION("hardness", KX_BlenderMaterial, pyattr_get_hardness, pyattr_set_hardness),
- KX_PYATTRIBUTE_RW_FUNCTION("specularIntensity", KX_BlenderMaterial, pyattr_get_specular_intensity, pyattr_set_specular_intensity),
- KX_PYATTRIBUTE_RW_FUNCTION("specularColor", KX_BlenderMaterial, pyattr_get_specular_color, pyattr_set_specular_color),
- KX_PYATTRIBUTE_RW_FUNCTION("diffuseIntensity", KX_BlenderMaterial, pyattr_get_diffuse_intensity, pyattr_set_diffuse_intensity),
- KX_PYATTRIBUTE_RW_FUNCTION("diffuseColor", KX_BlenderMaterial, pyattr_get_diffuse_color, pyattr_set_diffuse_color),
- KX_PYATTRIBUTE_RW_FUNCTION("emit", KX_BlenderMaterial, pyattr_get_emit, pyattr_set_emit),
-
- { NULL } //Sentinel
-};
-
-PyTypeObject KX_BlenderMaterial::Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "KX_BlenderMaterial",
- sizeof(PyObjectPlus_Proxy),
- 0,
- py_base_dealloc,
- 0,
- 0,
- 0,
- 0,
- py_base_repr,
- 0,0,0,0,0,0,0,0,0,
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
- 0,0,0,0,0,0,0,
- Methods,
- 0,
- 0,
- &PyObjectPlus::Type,
- 0,0,0,0,0,0,
- py_base_new
-};
-
-PyObject *KX_BlenderMaterial::pyattr_get_shader(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_BlenderMaterial* self = static_cast<KX_BlenderMaterial*>(self_v);
- return self->PygetShader(NULL, NULL);
-}
-
-PyObject *KX_BlenderMaterial::pyattr_get_materialIndex(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_BlenderMaterial* self = static_cast<KX_BlenderMaterial*>(self_v);
- return PyLong_FromLong(self->GetMaterialIndex());
-}
-
-PyObject *KX_BlenderMaterial::pyattr_get_blending(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_BlenderMaterial* self = static_cast<KX_BlenderMaterial*>(self_v);
- unsigned int* bfunc = self->getBlendFunc();
- return Py_BuildValue("(ll)", (long int)bfunc[0], (long int)bfunc[1]);
-}
-
-PyObject *KX_BlenderMaterial::pyattr_get_alpha(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_BlenderMaterial *self = static_cast<KX_BlenderMaterial *>(self_v);
- return PyFloat_FromDouble(self->GetBLMaterial()->alpha);
-}
-
-int KX_BlenderMaterial::pyattr_set_alpha(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_BlenderMaterial *self = static_cast<KX_BlenderMaterial *>(self_v);
- float val = PyFloat_AsDouble(value);
-
- if (val == -1 && PyErr_Occurred()) {
- PyErr_Format(PyExc_AttributeError, "material.%s = float: KX_BlenderMaterial, expected a float", attrdef->m_name);
- return PY_SET_ATTR_FAIL;
- }
-
- CLAMP(val, 0.0f, 1.0f);
-
- BL_Material *mat = self->GetBLMaterial();
- mat->alpha = mat->material->alpha = val;
- return PY_SET_ATTR_SUCCESS;
-}
-PyObject *KX_BlenderMaterial::pyattr_get_hardness(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_BlenderMaterial *self = static_cast<KX_BlenderMaterial *>(self_v);
- return PyLong_FromLong(self->GetBLMaterial()->hard);
-}
-
-int KX_BlenderMaterial::pyattr_set_hardness(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_BlenderMaterial *self = static_cast<KX_BlenderMaterial *>(self_v);
- int val = PyLong_AsLong(value);
-
- if (val == -1 && PyErr_Occurred()) {
- PyErr_Format(PyExc_AttributeError, "material.%s = int: KX_BlenderMaterial, expected a int", attrdef->m_name);
- return PY_SET_ATTR_FAIL;
- }
-
- CLAMP(val, 1, 511);
-
- BL_Material *mat = self->GetBLMaterial();
- mat->hard = mat->material->har = val;
- return PY_SET_ATTR_SUCCESS;
-}
-
-PyObject *KX_BlenderMaterial::pyattr_get_specular_intensity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_BlenderMaterial *self = static_cast<KX_BlenderMaterial *>(self_v);
- return PyFloat_FromDouble(self->GetBLMaterial()->spec_f);
-}
-
-int KX_BlenderMaterial::pyattr_set_specular_intensity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_BlenderMaterial *self = static_cast<KX_BlenderMaterial *>(self_v);
- float val = PyFloat_AsDouble(value);
-
- if (val == -1 && PyErr_Occurred()) {
- PyErr_Format(PyExc_AttributeError, "material.%s = float: KX_BlenderMaterial, expected a float", attrdef->m_name);
- return PY_SET_ATTR_FAIL;
- }
-
- CLAMP(val, 0.0f, 1.0f);
-
- BL_Material *mat = self->GetBLMaterial();
- mat->spec_f = mat->material->spec = val;
- return PY_SET_ATTR_SUCCESS;
-}
-
-PyObject *KX_BlenderMaterial::pyattr_get_specular_color(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
-#ifdef USE_MATHUTILS
- return Color_CreatePyObject_cb(BGE_PROXY_FROM_REF(self_v), mathutils_kxblendermaterial_color_cb_index, MATHUTILS_COL_CB_MATERIAL_SPECULAR_COLOR);
-#else
- KX_BlenderMaterial *self = static_cast<KX_BlenderMaterial *>(self_v);
- return PyColorFromVector(MT_Vector3(self->GetBLMaterial()->speccolor));
-#endif
-}
-
-int KX_BlenderMaterial::pyattr_set_specular_color(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_BlenderMaterial *self = static_cast<KX_BlenderMaterial *>(self_v);
- MT_Vector3 color;
- if (!PyVecTo(value, color))
- return PY_SET_ATTR_FAIL;
-
- BL_Material *mat = self->GetBLMaterial();
- color.getValue(mat->speccolor);
- mat->material->specr = color[0];
- mat->material->specg = color[1];
- mat->material->specb = color[2];
- return PY_SET_ATTR_SUCCESS;
-}
-
-PyObject *KX_BlenderMaterial::pyattr_get_diffuse_intensity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_BlenderMaterial *self = static_cast<KX_BlenderMaterial *>(self_v);
- return PyFloat_FromDouble(self->GetBLMaterial()->ref);
-}
-
-int KX_BlenderMaterial::pyattr_set_diffuse_intensity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_BlenderMaterial *self = static_cast<KX_BlenderMaterial *>(self_v);
- float val = PyFloat_AsDouble(value);
-
- if (val == -1 && PyErr_Occurred()) {
- PyErr_Format(PyExc_AttributeError, "material.%s = float: KX_BlenderMaterial, expected a float", attrdef->m_name);
- return PY_SET_ATTR_FAIL;
- }
-
- CLAMP(val, 0.0f, 1.0f);
-
- BL_Material *mat = self->GetBLMaterial();
- mat->ref = mat->material->ref = val;
- return PY_SET_ATTR_SUCCESS;
-}
-
-PyObject *KX_BlenderMaterial::pyattr_get_diffuse_color(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
-#ifdef USE_MATHUTILS
- return Color_CreatePyObject_cb(BGE_PROXY_FROM_REF(self_v), mathutils_kxblendermaterial_color_cb_index, MATHUTILS_COL_CB_MATERIAL_DIFFUSE_COLOR);
-#else
- KX_BlenderMaterial *self = static_cast<KX_BlenderMaterial *>(self_v);
- return PyColorFromVector(MT_Vector3(self->GetBLMaterial()->matcolor));
-#endif
-}
-
-int KX_BlenderMaterial::pyattr_set_diffuse_color(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_BlenderMaterial *self = static_cast<KX_BlenderMaterial *>(self_v);
- MT_Vector3 color;
- if (!PyVecTo(value, color))
- return PY_SET_ATTR_FAIL;
-
- BL_Material *mat = self->GetBLMaterial();
- color.getValue(mat->matcolor);
- mat->material->r = color[0];
- mat->material->g = color[1];
- mat->material->b = color[2];
- return PY_SET_ATTR_SUCCESS;
-}
-
-PyObject *KX_BlenderMaterial::pyattr_get_emit(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_BlenderMaterial *self = static_cast<KX_BlenderMaterial *>(self_v);
- return PyFloat_FromDouble(self->GetBLMaterial()->emit);
-}
-
-int KX_BlenderMaterial::pyattr_set_emit(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_BlenderMaterial *self = static_cast<KX_BlenderMaterial *>(self_v);
- float val = PyFloat_AsDouble(value);
-
- if (val == -1 && PyErr_Occurred()) {
- PyErr_Format(PyExc_AttributeError, "material.%s = float: KX_BlenderMaterial, expected a float", attrdef->m_name);
- return PY_SET_ATTR_FAIL;
- }
-
- CLAMP(val, 0.0f, 2.0f);
-
- BL_Material *mat = self->GetBLMaterial();
- mat->emit = mat->material->emit = val;
- return PY_SET_ATTR_SUCCESS;
-}
-
-int KX_BlenderMaterial::pyattr_set_blending(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_BlenderMaterial* self = static_cast<KX_BlenderMaterial*>(self_v);
- PyObject *obj = self->PysetBlending(value, NULL);
- if (obj)
- {
- Py_DECREF(obj);
- return 0;
- }
- return -1;
-}
-
-KX_PYMETHODDEF_DOC( KX_BlenderMaterial, getShader , "getShader()")
-{
- if ( !GLEW_ARB_fragment_shader) {
- if (!mModified)
- spit("Fragment shaders not supported");
-
- mModified = true;
- Py_RETURN_NONE;
- }
-
- if ( !GLEW_ARB_vertex_shader) {
- if (!mModified)
- spit("Vertex shaders not supported");
-
- mModified = true;
- Py_RETURN_NONE;
- }
-
- if (!GLEW_ARB_shader_objects) {
- if (!mModified)
- spit("GLSL not supported");
- mModified = true;
- Py_RETURN_NONE;
- }
- else {
- // returns Py_None on error
- // the calling script will need to check
-
- if (!mShader && !mModified) {
- mShader = new BL_Shader();
- mModified = true;
-
- // Using a custom shader, make sure to initialize textures
- InitTextures();
- }
-
- if (mShader && !mShader->GetError()) {
- m_flag &= ~RAS_BLENDERGLSL;
- mMaterial->SetSharedMaterial(true);
- mScene->GetBucketManager()->ReleaseDisplayLists(this);
- return mShader->GetProxy();
- }
- else {
- // decref all references to the object
- // then delete it!
- // We will then go back to fixed functionality
- // for this material
- if (mShader) {
- delete mShader; /* will handle python de-referencing */
- mShader=0;
- }
- }
- Py_RETURN_NONE;
- }
- PyErr_SetString(PyExc_ValueError, "material.getShader(): KX_BlenderMaterial, GLSL Error");
- return NULL;
-}
-
-KX_PYMETHODDEF_DOC( KX_BlenderMaterial, getMaterialIndex, "getMaterialIndex()")
-{
- return PyLong_FromLong(GetMaterialIndex());
-}
-
-KX_PYMETHODDEF_DOC( KX_BlenderMaterial, getTexture, "getTexture( index )" )
-{
- // TODO: enable python switching
- return NULL;
-}
-
-KX_PYMETHODDEF_DOC( KX_BlenderMaterial, setTexture , "setTexture( index, tex)")
-{
- // TODO: enable python switching
- return NULL;
-}
-
-static const unsigned int GL_array[11] = {
- GL_ZERO,
- GL_ONE,
- GL_SRC_COLOR,
- GL_ONE_MINUS_SRC_COLOR,
- GL_DST_COLOR,
- GL_ONE_MINUS_DST_COLOR,
- GL_SRC_ALPHA,
- GL_ONE_MINUS_SRC_ALPHA,
- GL_DST_ALPHA,
- GL_ONE_MINUS_DST_ALPHA,
- GL_SRC_ALPHA_SATURATE
-};
-
-KX_PYMETHODDEF_DOC( KX_BlenderMaterial, setBlending , "setBlending( bge.logic.src, bge.logic.dest)")
-{
- unsigned int b[2];
- if (PyArg_ParseTuple(args, "ii:setBlending", &b[0], &b[1]))
- {
- bool value_found[2] = {false, false};
- for (int i=0; i<11; i++)
- {
- if (b[0] == GL_array[i]) {
- value_found[0] = true;
- mBlendFunc[0] = b[0];
- }
- if (b[1] == GL_array[i]) {
- value_found[1] = true;
- mBlendFunc[1] = b[1];
- }
- if (value_found[0] && value_found[1]) break;
- }
- if (!value_found[0] || !value_found[1]) {
- PyErr_SetString(PyExc_ValueError, "material.setBlending(int, int): KX_BlenderMaterial, invalid enum.");
- return NULL;
- }
- mUserDefBlend = true;
- Py_RETURN_NONE;
- }
- return NULL;
-}
-
-KX_PYMETHODDEF_DOC(KX_BlenderMaterial, getTextureBindcode, "getTextureBindcode(texslot)")
-{
- unsigned int texslot;
- if (!PyArg_ParseTuple(args, "i:texslot", &texslot)) {
- PyErr_SetString(PyExc_ValueError, "material.getTextureBindcode(texslot): KX_BlenderMaterial, expected an int.");
- return NULL;
- }
- Image *ima = getImage(texslot);
- if (ima) {
- unsigned int *bindcode = ima->bindcode;
- return PyLong_FromLong(*bindcode);
- }
- PyErr_SetString(PyExc_ValueError, "material.getTextureBindcode(texslot): KX_BlenderMaterial, invalid texture slot.");
- return NULL;
-}
-
-#endif // WITH_PYTHON
diff --git a/source/gameengine/Ketsji/KX_BlenderMaterial.h b/source/gameengine/Ketsji/KX_BlenderMaterial.h
deleted file mode 100644
index c562ee0c583..00000000000
--- a/source/gameengine/Ketsji/KX_BlenderMaterial.h
+++ /dev/null
@@ -1,200 +0,0 @@
-
-/** \file KX_BlenderMaterial.h
- * \ingroup ketsji
- */
-
-#ifndef __KX_BLENDERMATERIAL_H__
-#define __KX_BLENDERMATERIAL_H__
-
-#include <vector>
-
-
-#include "RAS_IPolygonMaterial.h"
-#include "BL_Material.h"
-#include "BL_Texture.h"
-#include "BL_Shader.h"
-#include "BL_BlenderShader.h"
-
-#include "EXP_PyObjectPlus.h"
-
-#include "MT_Vector3.h"
-#include "MT_Vector4.h"
-
-#ifdef WITH_CXX_GUARDEDALLOC
-#include "MEM_guardedalloc.h"
-#endif
-
-#include "SCA_IScene.h" /* only for Replace_IScene */
-#include "KX_Scene.h"
-
-struct MTFace;
-class KX_Scene;
-
-
-#ifdef USE_MATHUTILS
-void KX_BlenderMaterial_Mathutils_Callback_Init(void);
-#endif
-
-class KX_BlenderMaterial : public PyObjectPlus, public RAS_IPolyMaterial
-{
- Py_Header
-public:
- // --------------------------------
- KX_BlenderMaterial();
- void Initialize(
- class KX_Scene* scene,
- BL_Material* mat,
- GameSettings* game,
- int lightlayer
- );
-
- virtual ~KX_BlenderMaterial();
-
- // --------------------------------
- virtual TCachingInfo GetCachingInfo(void) const {
- return (void*) this;
- }
-
- virtual
- bool Activate(
- RAS_IRasterizer* rasty,
- TCachingInfo& cachingInfo
- ) const;
-
- virtual
- void ActivateMeshSlot(
- const RAS_MeshSlot & ms,
- RAS_IRasterizer* rasty
- ) const;
-
- void ActivateMat(
- RAS_IRasterizer* rasty,
- TCachingInfo& cachingInfo
- )const;
-
- void ActivatShaders(
- RAS_IRasterizer* rasty,
- TCachingInfo& cachingInfo
- )const;
-
- void ActivateBlenderShaders(
- RAS_IRasterizer* rasty,
- TCachingInfo& cachingInfo
- )const;
-
- Material* GetBlenderMaterial() const;
- Image* GetBlenderImage() const;
- unsigned int* GetMCol() const;
- BL_Texture * getTex (unsigned int idx) {
- return (idx < MAXTEX) ? mTextures + idx : NULL;
- }
- Image * getImage (unsigned int idx) {
- return (idx < MAXTEX && mMaterial) ? mMaterial->img[idx] : NULL;
- }
- unsigned int* getBlendFunc() {
- return mBlendFunc;
- }
- // for ipos
- void UpdateIPO(
- MT_Vector4 rgba, MT_Vector3 specrgb,
- MT_Scalar hard, MT_Scalar spec,
- MT_Scalar ref, MT_Scalar emit, MT_Scalar alpha
- );
-
- virtual void Replace_IScene(SCA_IScene *val);
-
- BL_Material *GetBLMaterial();
-
-#ifdef WITH_PYTHON
- // --------------------------------
- virtual PyObject *py_repr(void) { return PyUnicode_From_STR_String(mMaterial->matname); }
-
- static PyObject *pyattr_get_shader(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject *pyattr_get_materialIndex(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject *pyattr_get_blending(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_blending(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static PyObject *pyattr_get_alpha(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_alpha(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static PyObject *pyattr_get_hardness(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_hardness(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static PyObject *pyattr_get_specular_intensity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_specular_intensity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static PyObject *pyattr_get_specular_color(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_specular_color(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static PyObject *pyattr_get_diffuse_intensity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_diffuse_intensity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static PyObject *pyattr_get_diffuse_color(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_diffuse_color(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static PyObject *pyattr_get_emit(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_emit(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
-
- KX_PYMETHOD_DOC(KX_BlenderMaterial, getShader);
- KX_PYMETHOD_DOC(KX_BlenderMaterial, getMaterialIndex);
- KX_PYMETHOD_DOC(KX_BlenderMaterial, getTexture);
- KX_PYMETHOD_DOC(KX_BlenderMaterial, setTexture);
- KX_PYMETHOD_DOC(KX_BlenderMaterial, getTextureBindcode);
-
- KX_PYMETHOD_DOC(KX_BlenderMaterial, setBlending);
-#endif /* WITH_PYTHON */
-
- // --------------------------------
- // pre calculate to avoid pops/lag at startup
- virtual void OnConstruction();
-
- static void EndFrame();
-
-private:
- BL_Material* mMaterial;
- BL_Shader* mShader;
- BL_BlenderShader* mBlenderShader;
- KX_Scene* mScene;
- BL_Texture mTextures[MAXTEX]; // texture array
- bool mUserDefBlend;
- unsigned int mBlendFunc[2];
- bool mModified;
- bool mConstructed; // if false, don't clean on exit
- int mLightLayer;
-
- struct {
- float r, g, b, a;
- float specr, specg, specb;
- float spec;
- float ref;
- float hardness;
- float emit;
- } mSavedData;
-
- void InitTextures();
-
- void SetBlenderGLSLShader();
-
- void ActivatGLMaterials( RAS_IRasterizer* rasty )const;
- void ActivateTexGen( RAS_IRasterizer *ras ) const;
-
- bool UsesLighting(RAS_IRasterizer *rasty) const;
- void GetMaterialRGBAColor(unsigned char *rgba) const;
- Scene* GetBlenderScene() const;
- void ReleaseMaterial();
-
- // message centers
- void setTexData( bool enable,RAS_IRasterizer *ras);
- void setBlenderShaderData( bool enable, RAS_IRasterizer *ras);
- void setShaderData( bool enable, RAS_IRasterizer *ras);
-
- void setObjectMatrixData(int i, RAS_IRasterizer *ras);
- void setTexMatrixData(int i);
-
- void setLightData();
-
- // cleanup stuff
- void OnExit();
-
- // shader chacing
- static BL_BlenderShader *mLastBlenderShader;
- static BL_Shader *mLastShader;
-
- mutable int mPass;
-};
-
-
-#endif
diff --git a/source/gameengine/Ketsji/KX_Camera.cpp b/source/gameengine/Ketsji/KX_Camera.cpp
deleted file mode 100644
index b22873aa862..00000000000
--- a/source/gameengine/Ketsji/KX_Camera.cpp
+++ /dev/null
@@ -1,1166 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- * Camera in the gameengine. Cameras are also used for views.
- */
-
-/** \file gameengine/Ketsji/KX_Camera.cpp
- * \ingroup ketsji
- */
-
-#include "GPU_glew.h"
-#include "GPU_matrix.h"
-#include "KX_Camera.h"
-#include "KX_Scene.h"
-#include "KX_PythonInit.h"
-#include "EXP_Python.h"
-#include "KX_PyMath.h"
-
-#include "RAS_ICanvas.h"
-
-KX_Camera::KX_Camera(void* sgReplicationInfo,
- SG_Callbacks callbacks,
- const RAS_CameraData& camdata,
- bool frustum_culling,
- bool delete_node)
- :
- KX_GameObject(sgReplicationInfo,callbacks),
- m_camdata(camdata),
- m_dirty(true),
- m_normalized(false),
- m_frustum_culling(frustum_culling),
- m_set_projection_matrix(false),
- m_set_frustum_center(false),
- m_delete_node(delete_node)
-{
- // setting a name would be nice...
- m_name = "cam";
- m_projection_matrix.setIdentity();
- m_modelview_matrix.setIdentity();
-}
-
-
-KX_Camera::~KX_Camera()
-{
- if (m_delete_node && m_pSGNode)
- {
- // for shadow camera, avoids memleak
- delete m_pSGNode;
- m_pSGNode = NULL;
- }
-}
-
-
-CValue* KX_Camera::GetReplica()
-{
- KX_Camera* replica = new KX_Camera(*this);
-
- // this will copy properties and so on...
- replica->ProcessReplica();
-
- return replica;
-}
-
-void KX_Camera::ProcessReplica()
-{
- KX_GameObject::ProcessReplica();
- // replicated camera are always registered in the scene
- m_delete_node = false;
-}
-
-MT_Transform KX_Camera::GetWorldToCamera() const
-{
- MT_Transform camtrans;
- camtrans.invert(MT_Transform(NodeGetWorldPosition(), NodeGetWorldOrientation()));
-
- return camtrans;
-}
-
-
-
-MT_Transform KX_Camera::GetCameraToWorld() const
-{
- return MT_Transform(NodeGetWorldPosition(), NodeGetWorldOrientation());
-}
-
-
-
-void KX_Camera::CorrectLookUp(MT_Scalar speed)
-{
-}
-
-
-
-const MT_Point3 KX_Camera::GetCameraLocation() const
-{
- /* this is the camera locatio in cam coords... */
- //return m_trans1.getOrigin();
- //return MT_Point3(0,0,0); <-----
- /* .... I want it in world coords */
- //MT_Transform trans;
- //trans.setBasis(NodeGetWorldOrientation());
-
- return NodeGetWorldPosition();
-}
-
-
-
-/* I want the camera orientation as well. */
-const MT_Quaternion KX_Camera::GetCameraOrientation() const
-{
- return NodeGetWorldOrientation().getRotation();
-}
-
-
-
-/**
- * Sets the projection matrix that is used by the rasterizer.
- */
-void KX_Camera::SetProjectionMatrix(const MT_Matrix4x4 & mat)
-{
- m_projection_matrix = mat;
- m_dirty = true;
- m_set_projection_matrix = true;
- m_set_frustum_center = false;
-}
-
-
-
-/**
- * Sets the modelview matrix that is used by the rasterizer.
- */
-void KX_Camera::SetModelviewMatrix(const MT_Matrix4x4 & mat)
-{
- m_modelview_matrix = mat;
- m_dirty = true;
- m_set_frustum_center = false;
-}
-
-
-
-/**
- * Gets the projection matrix that is used by the rasterizer.
- */
-const MT_Matrix4x4& KX_Camera::GetProjectionMatrix() const
-{
- return m_projection_matrix;
-}
-
-
-
-/**
- * Gets the modelview matrix that is used by the rasterizer.
- */
-const MT_Matrix4x4& KX_Camera::GetModelviewMatrix() const
-{
- return m_modelview_matrix;
-}
-
-
-bool KX_Camera::hasValidProjectionMatrix() const
-{
- return m_set_projection_matrix;
-}
-
-void KX_Camera::InvalidateProjectionMatrix(bool valid)
-{
- m_set_projection_matrix = valid;
-}
-
-
-/**
- * These getters retrieve the clip data and the focal length
- */
-float KX_Camera::GetLens() const
-{
- return m_camdata.m_lens;
-}
-
-float KX_Camera::GetScale() const
-{
- return m_camdata.m_scale;
-}
-
-/**
- * Gets the horizontal size of the sensor - for camera matching.
- */
-float KX_Camera::GetSensorWidth() const
-{
- return m_camdata.m_sensor_x;
-}
-
-/**
- * Gets the vertical size of the sensor - for camera matching.
- */
-float KX_Camera::GetSensorHeight() const
-{
- return m_camdata.m_sensor_y;
-}
-/** Gets the mode FOV is calculating from sensor dimensions */
-short KX_Camera::GetSensorFit() const
-{
- return m_camdata.m_sensor_fit;
-}
-
-/**
- * Gets the horizontal shift of the sensor - for camera matching.
- */
-float KX_Camera::GetShiftHorizontal() const
-{
- return m_camdata.m_shift_x;
-}
-
-/**
- * Gets the vertical shift of the sensor - for camera matching.
- */
-float KX_Camera::GetShiftVertical() const
-{
- return m_camdata.m_shift_y;
-}
-
-float KX_Camera::GetCameraNear() const
-{
- return m_camdata.m_clipstart;
-}
-
-
-
-float KX_Camera::GetCameraFar() const
-{
- return m_camdata.m_clipend;
-}
-
-float KX_Camera::GetFocalLength() const
-{
- return m_camdata.m_focallength;
-}
-
-
-
-RAS_CameraData* KX_Camera::GetCameraData()
-{
- return &m_camdata;
-}
-
-void KX_Camera::ExtractClipPlanes()
-{
- if (!m_dirty)
- return;
-
- MT_Matrix4x4 m = m_projection_matrix * m_modelview_matrix;
- // Left clip plane
- m_planes[0] = m[3] + m[0];
- // Right clip plane
- m_planes[1] = m[3] - m[0];
- // Top clip plane
- m_planes[2] = m[3] - m[1];
- // Bottom clip plane
- m_planes[3] = m[3] + m[1];
- // Near clip plane
- m_planes[4] = m[3] + m[2];
- // Far clip plane
- m_planes[5] = m[3] - m[2];
-
- m_dirty = false;
- m_normalized = false;
-}
-
-void KX_Camera::NormalizeClipPlanes()
-{
- if (m_normalized)
- return;
-
- for (unsigned int p = 0; p < 6; p++)
- {
- MT_Scalar factor = sqrtf(m_planes[p][0]*m_planes[p][0] + m_planes[p][1]*m_planes[p][1] + m_planes[p][2]*m_planes[p][2]);
- if (!MT_fuzzyZero(factor))
- m_planes[p] /= factor;
- }
-
- m_normalized = true;
-}
-
-void KX_Camera::ExtractFrustumSphere()
-{
- if (m_set_frustum_center)
- return;
-
- // compute sphere for the general case and not only symmetric frustum:
- // the mirror code in ImageRender can use very asymmetric frustum.
- // We will put the sphere center on the line that goes from origin to the center of the far clipping plane
- // This is the optimal position if the frustum is symmetric or very asymmetric and probably close
- // to optimal for the general case. The sphere center position is computed so that the distance to
- // the near and far extreme frustum points are equal.
-
- // get the transformation matrix from device coordinate to camera coordinate
- MT_Matrix4x4 clip_camcs_matrix = m_projection_matrix;
- clip_camcs_matrix.invert();
-
- if (m_projection_matrix[3][3] == MT_Scalar(0.0f))
- {
- // frustum projection
- // detect which of the corner of the far clipping plane is the farthest to the origin
- MT_Vector4 nfar; // far point in device normalized coordinate
- MT_Point3 farpoint; // most extreme far point in camera coordinate
- MT_Point3 nearpoint;// most extreme near point in camera coordinate
- MT_Point3 farcenter(0.0f, 0.0f, 0.0f);// center of far cliping plane in camera coordinate
- MT_Scalar F=-1.0f, N; // square distance of far and near point to origin
- MT_Scalar f, n; // distance of far and near point to z axis. f is always > 0 but n can be < 0
- MT_Scalar e, s; // far and near clipping distance (<0)
- MT_Scalar c; // slope of center line = distance of far clipping center to z axis / far clipping distance
- MT_Scalar z; // projection of sphere center on z axis (<0)
- // tmp value
- MT_Vector4 npoint(1.0f, 1.0f, 1.0f, 1.0f);
- MT_Vector4 hpoint;
- MT_Point3 point;
- MT_Scalar len;
- for (int i=0; i<4; i++)
- {
- hpoint = clip_camcs_matrix*npoint;
- point.setValue(hpoint[0]/hpoint[3], hpoint[1]/hpoint[3], hpoint[2]/hpoint[3]);
- len = point.dot(point);
- if (len > F)
- {
- nfar = npoint;
- farpoint = point;
- F = len;
- }
- // rotate by 90 degree along the z axis to walk through the 4 extreme points of the far clipping plane
- len = npoint[0];
- npoint[0] = -npoint[1];
- npoint[1] = len;
- farcenter += point;
- }
- // the far center is the average of the far clipping points
- farcenter *= 0.25f;
- // the extreme near point is the opposite point on the near clipping plane
- nfar.setValue(-nfar[0], -nfar[1], -1.0f, 1.0f);
- nfar = clip_camcs_matrix*nfar;
- nearpoint.setValue(nfar[0]/nfar[3], nfar[1]/nfar[3], nfar[2]/nfar[3]);
- // this is a frustum projection
- N = nearpoint.dot(nearpoint);
- e = farpoint[2];
- s = nearpoint[2];
- // projection on XY plane for distance to axis computation
- MT_Point2 farxy(farpoint[0], farpoint[1]);
- // f is forced positive by construction
- f = farxy.length();
- // get corresponding point on the near plane
- farxy *= s/e;
- // this formula preserve the sign of n
- n = f*s/e - MT_Point2(nearpoint[0]-farxy[0], nearpoint[1]-farxy[1]).length();
- c = MT_Point2(farcenter[0], farcenter[1]).length()/e;
- // the big formula, it simplifies to (F-N)/(2(e-s)) for the symmetric case
- z = (F-N)/(2.0f*(e-s+c*(f-n)));
- m_frustum_center = MT_Point3(farcenter[0]*z/e, farcenter[1]*z/e, z);
- m_frustum_radius = m_frustum_center.distance(farpoint);
- }
- else
- {
- // orthographic projection
- // The most extreme points on the near and far plane. (normalized device coords)
- MT_Vector4 hnear(1.0f, 1.0f, 1.0f, 1.0f), hfar(-1.0f, -1.0f, -1.0f, 1.0f);
-
- // Transform to hom camera local space
- hnear = clip_camcs_matrix*hnear;
- hfar = clip_camcs_matrix*hfar;
-
- // Tranform to 3d camera local space.
- MT_Point3 nearpoint(hnear[0]/hnear[3], hnear[1]/hnear[3], hnear[2]/hnear[3]);
- MT_Point3 farpoint(hfar[0]/hfar[3], hfar[1]/hfar[3], hfar[2]/hfar[3]);
-
- // just use mediant point
- m_frustum_center = (farpoint + nearpoint)*0.5f;
- m_frustum_radius = m_frustum_center.distance(farpoint);
- }
- // Transform to world space.
- m_frustum_center = GetCameraToWorld()(m_frustum_center);
- m_frustum_radius /= fabsf(NodeGetWorldScaling()[NodeGetWorldScaling().closestAxis()]);
-
- m_set_frustum_center = true;
-}
-
-bool KX_Camera::PointInsideFrustum(const MT_Point3& x)
-{
- ExtractClipPlanes();
-
- for ( unsigned int i = 0; i < 6 ; i++ )
- {
- if (m_planes[i][0] * x[0] + m_planes[i][1] * x[1] + m_planes[i][2] * x[2] + m_planes[i][3] < 0.0f)
- return false;
- }
- return true;
-}
-
-int KX_Camera::BoxInsideFrustum(const MT_Point3 *box)
-{
- ExtractClipPlanes();
-
- unsigned int insideCount = 0;
- // 6 view frustum planes
- for ( unsigned int p = 0; p < 6 ; p++ )
- {
- unsigned int behindCount = 0;
- // 8 box vertices.
- for (unsigned int v = 0; v < 8 ; v++)
- {
- if (m_planes[p][0] * box[v][0] + m_planes[p][1] * box[v][1] + m_planes[p][2] * box[v][2] + m_planes[p][3] < 0.0f)
- behindCount++;
- }
-
- // 8 points behind this plane
- if (behindCount == 8)
- return OUTSIDE;
-
- // Every box vertex is on the front side of this plane
- if (!behindCount)
- insideCount++;
- }
-
- // All box vertices are on the front side of all frustum planes.
- if (insideCount == 6)
- return INSIDE;
-
- return INTERSECT;
-}
-
-int KX_Camera::SphereInsideFrustum(const MT_Point3& center, const MT_Scalar &radius)
-{
- ExtractFrustumSphere();
- if (center.distance2(m_frustum_center) > (radius + m_frustum_radius)*(radius + m_frustum_radius))
- return OUTSIDE;
-
- unsigned int p;
- ExtractClipPlanes();
- NormalizeClipPlanes();
-
- MT_Scalar distance;
- int intersect = INSIDE;
- // distance: <-------- OUTSIDE -----|----- INTERSECT -----0----- INTERSECT -----|----- INSIDE -------->
- // -radius radius
- for (p = 0; p < 6; p++)
- {
- distance = m_planes[p][0]*center[0] + m_planes[p][1]*center[1] + m_planes[p][2]*center[2] + m_planes[p][3];
- if (fabsf(distance) <= radius)
- intersect = INTERSECT;
- else if (distance < -radius)
- return OUTSIDE;
- }
-
- return intersect;
-}
-
-bool KX_Camera::GetFrustumCulling() const
-{
- return m_frustum_culling;
-}
-
-void KX_Camera::EnableViewport(bool viewport)
-{
- InvalidateProjectionMatrix(false); // We need to reset projection matrix
- m_camdata.m_viewport = viewport;
-}
-
-void KX_Camera::SetViewport(int left, int bottom, int right, int top)
-{
- m_camdata.m_viewportleft = left;
- m_camdata.m_viewportbottom = bottom;
- m_camdata.m_viewportright = right;
- m_camdata.m_viewporttop = top;
-}
-
-bool KX_Camera::GetViewport() const
-{
- return m_camdata.m_viewport;
-}
-
-int KX_Camera::GetViewportLeft() const
-{
- return m_camdata.m_viewportleft;
-}
-
-int KX_Camera::GetViewportBottom() const
-{
- return m_camdata.m_viewportbottom;
-}
-
-int KX_Camera::GetViewportRight() const
-{
- return m_camdata.m_viewportright;
-}
-
-int KX_Camera::GetViewportTop() const
-{
- return m_camdata.m_viewporttop;
-}
-
-#ifdef WITH_PYTHON
-//----------------------------------------------------------------------------
-//Python
-
-
-PyMethodDef KX_Camera::Methods[] = {
- KX_PYMETHODTABLE(KX_Camera, sphereInsideFrustum),
- KX_PYMETHODTABLE_O(KX_Camera, boxInsideFrustum),
- KX_PYMETHODTABLE_O(KX_Camera, pointInsideFrustum),
- KX_PYMETHODTABLE_NOARGS(KX_Camera, getCameraToWorld),
- KX_PYMETHODTABLE_NOARGS(KX_Camera, getWorldToCamera),
- KX_PYMETHODTABLE(KX_Camera, setViewport),
- KX_PYMETHODTABLE_NOARGS(KX_Camera, setOnTop),
- KX_PYMETHODTABLE_O(KX_Camera, getScreenPosition),
- KX_PYMETHODTABLE(KX_Camera, getScreenVect),
- KX_PYMETHODTABLE(KX_Camera, getScreenRay),
- {NULL,NULL} //Sentinel
-};
-
-PyAttributeDef KX_Camera::Attributes[] = {
-
- KX_PYATTRIBUTE_BOOL_RW("frustum_culling", KX_Camera, m_frustum_culling),
- KX_PYATTRIBUTE_RW_FUNCTION("perspective", KX_Camera, pyattr_get_perspective, pyattr_set_perspective),
-
- KX_PYATTRIBUTE_RW_FUNCTION("lens", KX_Camera, pyattr_get_lens, pyattr_set_lens),
- KX_PYATTRIBUTE_RW_FUNCTION("fov", KX_Camera, pyattr_get_fov, pyattr_set_fov),
- KX_PYATTRIBUTE_RW_FUNCTION("ortho_scale", KX_Camera, pyattr_get_ortho_scale, pyattr_set_ortho_scale),
- KX_PYATTRIBUTE_RW_FUNCTION("near", KX_Camera, pyattr_get_near, pyattr_set_near),
- KX_PYATTRIBUTE_RW_FUNCTION("far", KX_Camera, pyattr_get_far, pyattr_set_far),
- KX_PYATTRIBUTE_RW_FUNCTION("shift_x", KX_Camera, pyattr_get_shift_x, pyattr_set_shift_x),
- KX_PYATTRIBUTE_RW_FUNCTION("shift_y", KX_Camera, pyattr_get_shift_y, pyattr_set_shift_y),
-
- KX_PYATTRIBUTE_RW_FUNCTION("useViewport", KX_Camera, pyattr_get_use_viewport, pyattr_set_use_viewport),
-
- KX_PYATTRIBUTE_RW_FUNCTION("projection_matrix", KX_Camera, pyattr_get_projection_matrix, pyattr_set_projection_matrix),
- KX_PYATTRIBUTE_RO_FUNCTION("modelview_matrix", KX_Camera, pyattr_get_modelview_matrix),
- KX_PYATTRIBUTE_RO_FUNCTION("camera_to_world", KX_Camera, pyattr_get_camera_to_world),
- KX_PYATTRIBUTE_RO_FUNCTION("world_to_camera", KX_Camera, pyattr_get_world_to_camera),
-
- /* Grrr, functions for constants? */
- KX_PYATTRIBUTE_RO_FUNCTION("INSIDE", KX_Camera, pyattr_get_INSIDE),
- KX_PYATTRIBUTE_RO_FUNCTION("OUTSIDE", KX_Camera, pyattr_get_OUTSIDE),
- KX_PYATTRIBUTE_RO_FUNCTION("INTERSECT", KX_Camera, pyattr_get_INTERSECT),
-
- { NULL } //Sentinel
-};
-
-PyTypeObject KX_Camera::Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "KX_Camera",
- sizeof(PyObjectPlus_Proxy),
- 0,
- py_base_dealloc,
- 0,
- 0,
- 0,
- 0,
- py_base_repr,
- 0,
- &KX_GameObject::Sequence,
- &KX_GameObject::Mapping,
- 0,0,0,
- NULL,
- NULL,
- 0,
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
- 0,0,0,0,0,0,0,
- Methods,
- 0,
- 0,
- &KX_GameObject::Type,
- 0,0,0,0,0,0,
- py_base_new
-};
-
-KX_PYMETHODDEF_DOC_VARARGS(KX_Camera, sphereInsideFrustum,
-"sphereInsideFrustum(center, radius) -> Integer\n"
-"\treturns INSIDE, OUTSIDE or INTERSECT if the given sphere is\n"
-"\tinside/outside/intersects this camera's viewing frustum.\n\n"
-"\tcenter = the center of the sphere (in world coordinates.)\n"
-"\tradius = the radius of the sphere\n\n"
-"\tExample:\n"
-"\timport bge.logic\n\n"
-"\tco = bge.logic.getCurrentController()\n"
-"\tcam = co.GetOwner()\n\n"
-"\t# A sphere of radius 4.0 located at [x, y, z] = [1.0, 1.0, 1.0]\n"
-"\tif (cam.sphereInsideFrustum([1.0, 1.0, 1.0], 4) != cam.OUTSIDE):\n"
-"\t\t# Sphere is inside frustum !\n"
-"\t\t# Do something useful !\n"
-"\telse:\n"
-"\t\t# Sphere is outside frustum\n"
-)
-{
- PyObject *pycenter;
- float radius;
- if (PyArg_ParseTuple(args, "Of:sphereInsideFrustum", &pycenter, &radius))
- {
- MT_Point3 center;
- if (PyVecTo(pycenter, center))
- {
- return PyLong_FromLong(SphereInsideFrustum(center, radius)); /* new ref */
- }
- }
-
- PyErr_SetString(PyExc_TypeError, "camera.sphereInsideFrustum(center, radius): KX_Camera, expected arguments: (center, radius)");
-
- return NULL;
-}
-
-KX_PYMETHODDEF_DOC_O(KX_Camera, boxInsideFrustum,
-"boxInsideFrustum(box) -> Integer\n"
-"\treturns INSIDE, OUTSIDE or INTERSECT if the given box is\n"
-"\tinside/outside/intersects this camera's viewing frustum.\n\n"
-"\tbox = a list of the eight (8) corners of the box (in world coordinates.)\n\n"
-"\tExample:\n"
-"\timport bge.logic\n\n"
-"\tco = bge.logic.getCurrentController()\n"
-"\tcam = co.GetOwner()\n\n"
-"\tbox = []\n"
-"\tbox.append([-1.0, -1.0, -1.0])\n"
-"\tbox.append([-1.0, -1.0, 1.0])\n"
-"\tbox.append([-1.0, 1.0, -1.0])\n"
-"\tbox.append([-1.0, 1.0, 1.0])\n"
-"\tbox.append([ 1.0, -1.0, -1.0])\n"
-"\tbox.append([ 1.0, -1.0, 1.0])\n"
-"\tbox.append([ 1.0, 1.0, -1.0])\n"
-"\tbox.append([ 1.0, 1.0, 1.0])\n\n"
-"\tif (cam.boxInsideFrustum(box) != cam.OUTSIDE):\n"
-"\t\t# Box is inside/intersects frustum !\n"
-"\t\t# Do something useful !\n"
-"\telse:\n"
-"\t\t# Box is outside the frustum !\n"
-)
-{
- unsigned int num_points = PySequence_Size(value);
- if (num_points != 8)
- {
- PyErr_Format(PyExc_TypeError, "camera.boxInsideFrustum(box): KX_Camera, expected eight (8) points, got %d", num_points);
- return NULL;
- }
-
- MT_Point3 box[8];
- for (unsigned int p = 0; p < 8 ; p++)
- {
- PyObject *item = PySequence_GetItem(value, p); /* new ref */
- bool error = !PyVecTo(item, box[p]);
- Py_DECREF(item);
- if (error)
- return NULL;
- }
-
- return PyLong_FromLong(BoxInsideFrustum(box)); /* new ref */
-}
-
-KX_PYMETHODDEF_DOC_O(KX_Camera, pointInsideFrustum,
-"pointInsideFrustum(point) -> Bool\n"
-"\treturns 1 if the given point is inside this camera's viewing frustum.\n\n"
-"\tpoint = The point to test (in world coordinates.)\n\n"
-"\tExample:\n"
-"\timport bge.logic\n\n"
-"\tco = bge.logic.getCurrentController()\n"
-"\tcam = co.GetOwner()\n\n"
-"\t# Test point [0.0, 0.0, 0.0]"
-"\tif (cam.pointInsideFrustum([0.0, 0.0, 0.0])):\n"
-"\t\t# Point is inside frustum !\n"
-"\t\t# Do something useful !\n"
-"\telse:\n"
-"\t\t# Box is outside the frustum !\n"
-)
-{
- MT_Point3 point;
- if (PyVecTo(value, point))
- {
- return PyLong_FromLong(PointInsideFrustum(point)); /* new ref */
- }
-
- PyErr_SetString(PyExc_TypeError, "camera.pointInsideFrustum(point): KX_Camera, expected point argument.");
- return NULL;
-}
-
-KX_PYMETHODDEF_DOC_NOARGS(KX_Camera, getCameraToWorld,
-"getCameraToWorld() -> Matrix4x4\n"
-"\treturns the camera to world transformation matrix, as a list of four lists of four values.\n\n"
-"\tie: [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]])\n"
-)
-{
- return PyObjectFrom(GetCameraToWorld()); /* new ref */
-}
-
-KX_PYMETHODDEF_DOC_NOARGS(KX_Camera, getWorldToCamera,
-"getWorldToCamera() -> Matrix4x4\n"
-"\treturns the world to camera transformation matrix, as a list of four lists of four values.\n\n"
-"\tie: [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]])\n"
-)
-{
- return PyObjectFrom(GetWorldToCamera()); /* new ref */
-}
-
-KX_PYMETHODDEF_DOC_VARARGS(KX_Camera, setViewport,
-"setViewport(left, bottom, right, top)\n"
-"Sets this camera's viewport\n")
-{
- int left, bottom, right, top;
- if (!PyArg_ParseTuple(args,"iiii:setViewport",&left, &bottom, &right, &top))
- return NULL;
-
- SetViewport(left, bottom, right, top);
- Py_RETURN_NONE;
-}
-
-KX_PYMETHODDEF_DOC_NOARGS(KX_Camera, setOnTop,
-"setOnTop()\n"
-"Sets this camera's viewport on top\n")
-{
- class KX_Scene* scene = KX_GetActiveScene();
- scene->SetCameraOnTop(this);
- Py_RETURN_NONE;
-}
-
-PyObject *KX_Camera::pyattr_get_perspective(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_Camera* self = static_cast<KX_Camera*>(self_v);
- return PyBool_FromLong(self->m_camdata.m_perspective);
-}
-
-int KX_Camera::pyattr_set_perspective(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_Camera* self = static_cast<KX_Camera*>(self_v);
- int param = PyObject_IsTrue( value );
- if (param == -1) {
- PyErr_SetString(PyExc_AttributeError, "camera.perspective = bool: KX_Camera, expected True/False or 0/1");
- return PY_SET_ATTR_FAIL;
- }
-
- self->m_camdata.m_perspective= param;
- self->InvalidateProjectionMatrix();
- return PY_SET_ATTR_SUCCESS;
-}
-
-PyObject *KX_Camera::pyattr_get_lens(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_Camera* self = static_cast<KX_Camera*>(self_v);
- return PyFloat_FromDouble(self->m_camdata.m_lens);
-}
-
-int KX_Camera::pyattr_set_lens(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_Camera* self = static_cast<KX_Camera*>(self_v);
- float param = PyFloat_AsDouble(value);
- if (param == -1) {
- PyErr_SetString(PyExc_AttributeError, "camera.lens = float: KX_Camera, expected a float greater than zero");
- return PY_SET_ATTR_FAIL;
- }
-
- self->m_camdata.m_lens= param;
- self->m_set_projection_matrix = false;
- return PY_SET_ATTR_SUCCESS;
-}
-
-PyObject *KX_Camera::pyattr_get_fov(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_Camera* self = static_cast<KX_Camera*>(self_v);
-
- float lens = self->m_camdata.m_lens;
- float width = self->m_camdata.m_sensor_x;
- float fov = 2.0f * atanf(0.5f * width / lens);
-
- return PyFloat_FromDouble(fov * MT_DEGS_PER_RAD);
-}
-
-int KX_Camera::pyattr_set_fov(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_Camera* self = static_cast<KX_Camera*>(self_v);
- float fov = PyFloat_AsDouble(value);
- if (fov <= 0.0f) {
- PyErr_SetString(PyExc_AttributeError, "camera.fov = float: KX_Camera, expected a float greater than zero");
- return PY_SET_ATTR_FAIL;
- }
-
- fov *= MT_RADS_PER_DEG;
- float width = self->m_camdata.m_sensor_x;
- float lens = width / (2.0f * tanf(0.5f * fov));
-
- self->m_camdata.m_lens= lens;
- self->m_set_projection_matrix = false;
- return PY_SET_ATTR_SUCCESS;
-}
-
-PyObject *KX_Camera::pyattr_get_ortho_scale(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_Camera* self = static_cast<KX_Camera*>(self_v);
- return PyFloat_FromDouble(self->m_camdata.m_scale);
-}
-
-int KX_Camera::pyattr_set_ortho_scale(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_Camera* self = static_cast<KX_Camera*>(self_v);
- float param = PyFloat_AsDouble(value);
- if (param == -1) {
- PyErr_SetString(PyExc_AttributeError, "camera.ortho_scale = float: KX_Camera, expected a float greater than zero");
- return PY_SET_ATTR_FAIL;
- }
-
- self->m_camdata.m_scale= param;
- self->m_set_projection_matrix = false;
- return PY_SET_ATTR_SUCCESS;
-}
-
-PyObject *KX_Camera::pyattr_get_near(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_Camera* self = static_cast<KX_Camera*>(self_v);
- return PyFloat_FromDouble(self->m_camdata.m_clipstart);
-}
-
-int KX_Camera::pyattr_set_near(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_Camera* self = static_cast<KX_Camera*>(self_v);
- float param = PyFloat_AsDouble(value);
- if (param == -1) {
- PyErr_SetString(PyExc_AttributeError, "camera.near = float: KX_Camera, expected a float greater than zero");
- return PY_SET_ATTR_FAIL;
- }
-
- self->m_camdata.m_clipstart= param;
- self->m_set_projection_matrix = false;
- return PY_SET_ATTR_SUCCESS;
-}
-
-PyObject *KX_Camera::pyattr_get_far(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_Camera* self = static_cast<KX_Camera*>(self_v);
- return PyFloat_FromDouble(self->m_camdata.m_clipend);
-}
-
-int KX_Camera::pyattr_set_far(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_Camera* self = static_cast<KX_Camera*>(self_v);
- float param = PyFloat_AsDouble(value);
- if (param == -1) {
- PyErr_SetString(PyExc_AttributeError, "camera.far = float: KX_Camera, expected a float greater than zero");
- return PY_SET_ATTR_FAIL;
- }
-
- self->m_camdata.m_clipend= param;
- self->m_set_projection_matrix = false;
- return PY_SET_ATTR_SUCCESS;
-}
-
-PyObject *KX_Camera::pyattr_get_shift_x(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_Camera* self = static_cast<KX_Camera*>(self_v);
- return PyFloat_FromDouble(self->m_camdata.m_shift_x);
-}
-
-int KX_Camera::pyattr_set_shift_x(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_Camera* self = static_cast<KX_Camera*>(self_v);
- float param = PyFloat_AsDouble(value);
- if (param == -1) {
- PyErr_SetString(PyExc_AttributeError, "camera.shift_x = float: KX_Camera, expected a float greater than zero");
- return PY_SET_ATTR_FAIL;
- }
-
- self->m_camdata.m_shift_x = param;
- self->m_set_projection_matrix = false;
- return PY_SET_ATTR_SUCCESS;
-}
-
-PyObject *KX_Camera::pyattr_get_shift_y(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_Camera* self = static_cast<KX_Camera*>(self_v);
- return PyFloat_FromDouble(self->m_camdata.m_shift_y);
-}
-
-int KX_Camera::pyattr_set_shift_y(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_Camera* self = static_cast<KX_Camera*>(self_v);
- float param = PyFloat_AsDouble(value);
- if (param == -1) {
- PyErr_SetString(PyExc_AttributeError, "camera.shift_y = float: KX_Camera, expected a float greater than zero");
- return PY_SET_ATTR_FAIL;
- }
-
- self->m_camdata.m_shift_y = param;
- self->m_set_projection_matrix = false;
- return PY_SET_ATTR_SUCCESS;
-}
-
-PyObject *KX_Camera::pyattr_get_use_viewport(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_Camera* self = static_cast<KX_Camera*>(self_v);
- return PyBool_FromLong(self->GetViewport());
-}
-
-int KX_Camera::pyattr_set_use_viewport(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_Camera* self = static_cast<KX_Camera*>(self_v);
- int param = PyObject_IsTrue( value );
- if (param == -1) {
- PyErr_SetString(PyExc_AttributeError, "camera.useViewport = bool: KX_Camera, expected True or False");
- return PY_SET_ATTR_FAIL;
- }
- self->EnableViewport((bool)param);
- return PY_SET_ATTR_SUCCESS;
-}
-
-
-PyObject *KX_Camera::pyattr_get_projection_matrix(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_Camera* self = static_cast<KX_Camera*>(self_v);
- return PyObjectFrom(self->GetProjectionMatrix());
-}
-
-int KX_Camera::pyattr_set_projection_matrix(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_Camera* self = static_cast<KX_Camera*>(self_v);
- MT_Matrix4x4 mat;
- if (!PyMatTo(value, mat))
- return PY_SET_ATTR_FAIL;
-
- self->SetProjectionMatrix(mat);
- return PY_SET_ATTR_SUCCESS;
-}
-
-PyObject *KX_Camera::pyattr_get_modelview_matrix(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_Camera* self = static_cast<KX_Camera*>(self_v);
- return PyObjectFrom(self->GetWorldToCamera());
-}
-
-PyObject *KX_Camera::pyattr_get_camera_to_world(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_Camera* self = static_cast<KX_Camera*>(self_v);
- return PyObjectFrom(self->GetCameraToWorld());
-}
-
-PyObject *KX_Camera::pyattr_get_world_to_camera(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_Camera* self = static_cast<KX_Camera*>(self_v);
- return PyObjectFrom(self->GetWorldToCamera());
-}
-
-
-PyObject *KX_Camera::pyattr_get_INSIDE(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{ return PyLong_FromLong(INSIDE); }
-PyObject *KX_Camera::pyattr_get_OUTSIDE(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{ return PyLong_FromLong(OUTSIDE); }
-PyObject *KX_Camera::pyattr_get_INTERSECT(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{ return PyLong_FromLong(INTERSECT); }
-
-
-bool ConvertPythonToCamera(PyObject *value, KX_Camera **object, bool py_none_ok, const char *error_prefix)
-{
- if (value==NULL) {
- PyErr_Format(PyExc_TypeError, "%s, python pointer NULL, should never happen", error_prefix);
- *object = NULL;
- return false;
- }
-
- if (value==Py_None) {
- *object = NULL;
-
- if (py_none_ok) {
- return true;
- } else {
- PyErr_Format(PyExc_TypeError, "%s, expected KX_Camera or a KX_Camera name, None is invalid", error_prefix);
- return false;
- }
- }
-
- if (PyUnicode_Check(value)) {
- STR_String value_str = _PyUnicode_AsString(value);
- *object = KX_GetActiveScene()->FindCamera(value_str);
-
- if (*object) {
- return true;
- } else {
- PyErr_Format(PyExc_ValueError,
- "%s, requested name \"%s\" did not match any KX_Camera in this scene",
- error_prefix, _PyUnicode_AsString(value));
- return false;
- }
- }
-
- if (PyObject_TypeCheck(value, &KX_Camera::Type)) {
- *object = static_cast<KX_Camera*>BGE_PROXY_REF(value);
-
- /* sets the error */
- if (*object==NULL) {
- PyErr_Format(PyExc_SystemError, "%s, " BGE_PROXY_ERROR_MSG, error_prefix);
- return false;
- }
-
- return true;
- }
-
- *object = NULL;
-
- if (py_none_ok) {
- PyErr_Format(PyExc_TypeError, "%s, expect a KX_Camera, a string or None", error_prefix);
- } else {
- PyErr_Format(PyExc_TypeError, "%s, expect a KX_Camera or a string", error_prefix);
- }
-
- return false;
-}
-
-KX_PYMETHODDEF_DOC_O(KX_Camera, getScreenPosition,
-"getScreenPosition()\n"
-)
-
-{
- MT_Vector3 vect;
- KX_GameObject *obj = NULL;
-
- if (!PyVecTo(value, vect))
- {
- PyErr_Clear();
-
- if (ConvertPythonToGameObject(GetScene()->GetLogicManager(), value, &obj, true, ""))
- {
- PyErr_Clear();
- vect = MT_Vector3(obj->NodeGetWorldPosition());
- }
- else
- {
- PyErr_SetString(PyExc_TypeError, "Error in getScreenPosition. Expected a Vector3 or a KX_GameObject or a string for a name of a KX_GameObject");
- return NULL;
- }
- }
-
- const GLint *viewport;
- GLfloat vec[3];
- GLfloat win[3];
- GLfloat modelmatrix[4][4];
- GLfloat projmatrix[4][4];
-
- MT_Matrix4x4 m_modelmatrix = this->GetWorldToCamera();
- MT_Matrix4x4 m_projmatrix = this->GetProjectionMatrix();
-
- vect.getValue(vec);
- m_modelmatrix.getValue((float*) modelmatrix);
- m_projmatrix.getValue((float*) projmatrix);
-
- viewport = KX_GetActiveEngine()->GetCanvas()->GetViewPort();
-
- gpuProject(vec, modelmatrix, projmatrix, viewport, win);
-
- vect[0] = (win[0] - viewport[0]) / viewport[2];
- vect[1] = (win[1] - viewport[1]) / viewport[3];
-
- vect[1] = 1.0f - vect[1]; //to follow Blender window coordinate system (Top-Down)
-
- PyObject *ret = PyTuple_New(2);
- if (ret) {
- PyTuple_SET_ITEM(ret, 0, PyFloat_FromDouble(vect[0]));
- PyTuple_SET_ITEM(ret, 1, PyFloat_FromDouble(vect[1]));
- return ret;
- }
-
- return NULL;
-}
-
-KX_PYMETHODDEF_DOC_VARARGS(KX_Camera, getScreenVect,
-"getScreenVect()\n"
-)
-{
- double x,y;
- if (!PyArg_ParseTuple(args,"dd:getScreenVect",&x,&y))
- return NULL;
-
- y = 1.0 - y; //to follow Blender window coordinate system (Top-Down)
-
- const GLint *viewport;
- GLfloat vec[3];
- GLfloat win[3];
- GLfloat modelmatrix[4][4];
- GLfloat projmatrix[4][4];
-
- MT_Matrix4x4 m_modelmatrix = this->GetWorldToCamera();
- MT_Matrix4x4 m_projmatrix = this->GetProjectionMatrix();
-
- m_modelmatrix.getValue((float*) modelmatrix);
- m_projmatrix.getValue((float*) projmatrix);
-
- viewport = KX_GetActiveEngine()->GetCanvas()->GetViewPort();
-
- vec[0] = x * viewport[2];
- vec[1] = y * viewport[3];
-
- vec[0] += viewport[0];
- vec[1] += viewport[1];
-
- vec[2] = 0.f;
-
- gpuUnProject(vec, modelmatrix, projmatrix, viewport, win);
-
- MT_Point3 campos = this->GetCameraLocation();
- MT_Point3 screenpos(win[0], win[1], win[2]);
- MT_Vector3 vect = campos - screenpos;
- vect.normalize();
- return PyObjectFrom(vect);
-}
-
-KX_PYMETHODDEF_DOC_VARARGS(KX_Camera, getScreenRay,
-"getScreenRay()\n"
-)
-{
- MT_Vector3 vect;
- double x,y,dist;
- char *propName = NULL;
-
- if (!PyArg_ParseTuple(args,"ddd|s:getScreenRay",&x,&y,&dist,&propName))
- return NULL;
-
- PyObject *argValue = PyTuple_New(2);
- PyTuple_SET_ITEM(argValue, 0, PyFloat_FromDouble(x));
- PyTuple_SET_ITEM(argValue, 1, PyFloat_FromDouble(y));
-
- if (!PyVecTo(PygetScreenVect(argValue), vect))
- {
- Py_DECREF(argValue);
- PyErr_SetString(PyExc_TypeError,
- "Error in getScreenRay. Invalid 2D coordinate. "
- "Expected a normalized 2D screen coordinate, "
- "a distance and an optional property argument");
- return NULL;
- }
- Py_DECREF(argValue);
-
- dist = -dist;
- vect += this->GetCameraLocation();
-
- argValue = (propName?PyTuple_New(3):PyTuple_New(2));
- if (argValue) {
- PyTuple_SET_ITEM(argValue, 0, PyObjectFrom(vect));
- PyTuple_SET_ITEM(argValue, 1, PyFloat_FromDouble(dist));
- if (propName)
- PyTuple_SET_ITEM(argValue, 2, PyUnicode_FromString(propName));
-
- PyObject *ret= this->PyrayCastTo(argValue,NULL);
- Py_DECREF(argValue);
- return ret;
- }
-
- return NULL;
-}
-#endif
diff --git a/source/gameengine/Ketsji/KX_Camera.h b/source/gameengine/Ketsji/KX_Camera.h
deleted file mode 100644
index 8addf0b7aed..00000000000
--- a/source/gameengine/Ketsji/KX_Camera.h
+++ /dev/null
@@ -1,334 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file KX_Camera.h
- * \ingroup ketsji
- * \brief Camera in the gameengine. Cameras are also used for views.
- */
-
-#ifndef __KX_CAMERA_H__
-#define __KX_CAMERA_H__
-
-
-#include "MT_Transform.h"
-#include "MT_Matrix3x3.h"
-#include "MT_Matrix4x4.h"
-#include "MT_Vector3.h"
-#include "MT_Point3.h"
-#include "KX_GameObject.h"
-#include "EXP_IntValue.h"
-#include "RAS_CameraData.h"
-
-#ifdef WITH_PYTHON
-/* utility conversion function */
-bool ConvertPythonToCamera(PyObject *value, KX_Camera **object, bool py_none_ok, const char *error_prefix);
-#endif
-
-class KX_Camera : public KX_GameObject
-{
- Py_Header
-protected:
- friend class KX_Scene;
- /** Camera parameters (clips distances, focal length). These
- * params are closely tied to Blender. In the gameengine, only the
- * projection and modelview matrices are relevant. There's a
- * conversion being done in the engine class. Why is it stored
- * here? It doesn't really have a function here. */
- RAS_CameraData m_camdata;
-
- // Never used, I think...
-// void MoveTo(const MT_Point3& movevec)
-// {
-#if 0
- MT_Transform camtrans;
- camtrans.invert(m_trans1);
- MT_Matrix3x3 camorient = camtrans.getBasis();
- camtrans.translate(camorient.inverse()*movevec);
- m_trans1.invert(camtrans);
-#endif
-// }
-
- /**
- * Storage for the projection matrix that is passed to the
- * rasterizer. */
- MT_Matrix4x4 m_projection_matrix;
- //MT_Matrix4x4 m_projection_matrix1;
-
- /**
- * Storage for the modelview matrix that is passed to the
- * rasterizer. */
- MT_Matrix4x4 m_modelview_matrix;
-
- /**
- * true if the view frustum (modelview/projection matrix)
- * has changed - the clip planes (m_planes) will have to be
- * regenerated.
- */
- bool m_dirty;
- /**
- * true if the frustum planes have been normalized.
- */
- bool m_normalized;
-
- /**
- * View Frustum clip planes.
- */
- MT_Vector4 m_planes[6];
-
- /**
- * This camera is frustum culling.
- * Some cameras (ie if the game was started from a non camera view should not cull.)
- */
- bool m_frustum_culling;
-
- /**
- * true if this camera has a valid projection matrix.
- */
- bool m_set_projection_matrix;
-
- /**
- * The center point of the frustum.
- */
- MT_Point3 m_frustum_center;
- MT_Scalar m_frustum_radius;
- bool m_set_frustum_center;
-
- /**
- * whether the camera should delete the node itself (only for shadow camera)
- */
- bool m_delete_node;
-
- /**
- * Extracts the camera clip frames from the projection and world-to-camera matrices.
- */
- void ExtractClipPlanes();
- /**
- * Normalize the camera clip frames.
- */
- void NormalizeClipPlanes();
- /**
- * Extracts the bound sphere of the view frustum.
- */
- void ExtractFrustumSphere();
- /**
- * return the clip plane
- */
- MT_Vector4 *GetNormalizedClipPlanes()
- {
- ExtractClipPlanes();
- NormalizeClipPlanes();
- return m_planes;
- }
-
-public:
-
- enum { INSIDE, INTERSECT, OUTSIDE };
-
- KX_Camera(void* sgReplicationInfo,SG_Callbacks callbacks,const RAS_CameraData& camdata, bool frustum_culling = true, bool delete_node = false);
- virtual ~KX_Camera();
-
- /**
- * Inherited from CValue -- return a new copy of this
- * instance allocated on the heap. Ownership of the new
- * object belongs with the caller.
- */
- virtual CValue*
- GetReplica(
- );
- virtual void ProcessReplica();
-
- MT_Transform GetWorldToCamera() const;
- MT_Transform GetCameraToWorld() const;
-
- /**
- * Not implemented.
- */
- void CorrectLookUp(MT_Scalar speed);
- const MT_Point3 GetCameraLocation() const;
-
- /* I want the camera orientation as well. */
- const MT_Quaternion GetCameraOrientation() const;
-
- /** Sets the projection matrix that is used by the rasterizer. */
- void SetProjectionMatrix(const MT_Matrix4x4 & mat);
-
- /** Sets the modelview matrix that is used by the rasterizer. */
- void SetModelviewMatrix(const MT_Matrix4x4 & mat);
-
- /** Gets the projection matrix that is used by the rasterizer. */
- const MT_Matrix4x4& GetProjectionMatrix() const;
-
- /** returns true if this camera has been set a projection matrix. */
- bool hasValidProjectionMatrix() const;
-
- /** Sets the validity of the projection matrix. Call this if you change camera
- * data (eg lens, near plane, far plane) and require the projection matrix to be
- * recalculated.
- */
- void InvalidateProjectionMatrix(bool valid = false);
-
- /** Gets the modelview matrix that is used by the rasterizer.
- * \warning If the Camera is a dynamic object then this method may return garbage. Use GetWorldToCamera() instead.
- */
- const MT_Matrix4x4& GetModelviewMatrix() const;
-
- /** Gets the aperture. */
- float GetLens() const;
- /** Gets the ortho scale. */
- float GetScale() const;
- /** Gets the horizontal size of the sensor - for camera matching */
- float GetSensorWidth() const;
- /** Gets the vertical size of the sensor - for camera matching */
- float GetSensorHeight() const;
- /** Gets the mode FOV is calculating from sensor dimensions */
- short GetSensorFit() const;
- /** Gets the horizontal shift of the sensor - for camera matching */
- float GetShiftHorizontal() const;
- /** Gets the vertical shift of the sensor - for camera matching */
- float GetShiftVertical() const;
- /** Gets the near clip distance. */
- float GetCameraNear() const;
- /** Gets the far clip distance. */
- float GetCameraFar() const;
- /** Gets the focal length (only used for stereo rendering) */
- float GetFocalLength() const;
- /** Gets all camera data. */
- RAS_CameraData* GetCameraData();
-
- /**
- * Tests if the given sphere is inside this camera's view frustum.
- *
- * \param center The center of the sphere, in world coordinates.
- * \param radius The radius of the sphere.
- * \return INSIDE, INTERSECT, or OUTSIDE depending on the sphere's relation to the frustum.
- */
- int SphereInsideFrustum(const MT_Point3& center, const MT_Scalar &radius);
- /**
- * Tests the given eight corners of a box with the view frustum.
- *
- * \param box a pointer to eight MT_Point3 representing the world coordinates of the corners of the box.
- * \return INSIDE, INTERSECT, or OUTSIDE depending on the box's relation to the frustum.
- */
- int BoxInsideFrustum(const MT_Point3 *box);
- /**
- * Tests the given point against the view frustum.
- * \return true if the given point is inside or on the view frustum; false if it is outside.
- */
- bool PointInsideFrustum(const MT_Point3& x);
-
- /**
- * Gets this camera's culling status.
- */
- bool GetFrustumCulling() const;
-
- /**
- * Sets this camera's viewport status.
- */
- void EnableViewport(bool viewport);
-
- /**
- * Sets this camera's viewport.
- */
- void SetViewport(int left, int bottom, int right, int top);
-
- /**
- * Gets this camera's viewport status.
- */
- bool GetViewport() const;
-
- /**
- * Gets this camera's viewport left.
- */
- int GetViewportLeft() const;
-
- /**
- * Gets this camera's viewport bottom.
- */
- int GetViewportBottom() const;
-
- /**
- * Gets this camera's viewport right.
- */
- int GetViewportRight() const;
-
- /**
- * Gets this camera's viewport top.
- */
- int GetViewportTop() const;
-
- virtual int GetGameObjectType() { return OBJ_CAMERA; }
-
-#ifdef WITH_PYTHON
- KX_PYMETHOD_DOC_VARARGS(KX_Camera, sphereInsideFrustum);
- KX_PYMETHOD_DOC_O(KX_Camera, boxInsideFrustum);
- KX_PYMETHOD_DOC_O(KX_Camera, pointInsideFrustum);
-
- KX_PYMETHOD_DOC_NOARGS(KX_Camera, getCameraToWorld);
- KX_PYMETHOD_DOC_NOARGS(KX_Camera, getWorldToCamera);
-
- KX_PYMETHOD_DOC_VARARGS(KX_Camera, setViewport);
- KX_PYMETHOD_DOC_NOARGS(KX_Camera, setOnTop);
-
- KX_PYMETHOD_DOC_O(KX_Camera, getScreenPosition);
- KX_PYMETHOD_DOC_VARARGS(KX_Camera, getScreenVect);
- KX_PYMETHOD_DOC_VARARGS(KX_Camera, getScreenRay);
-
- static PyObject* pyattr_get_perspective(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_perspective(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
-
- static PyObject* pyattr_get_lens(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_lens(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static PyObject* pyattr_get_fov(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_fov(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static PyObject* pyattr_get_ortho_scale(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_ortho_scale(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static PyObject* pyattr_get_near(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_near(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static PyObject* pyattr_get_far(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_far(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static PyObject* pyattr_get_shift_x(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_shift_x(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static PyObject* pyattr_get_shift_y(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_shift_y(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
-
- static PyObject* pyattr_get_use_viewport(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_use_viewport(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
-
- static PyObject* pyattr_get_projection_matrix(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_projection_matrix(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
-
- static PyObject* pyattr_get_modelview_matrix(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_camera_to_world(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_world_to_camera(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
-
- static PyObject* pyattr_get_INSIDE(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_OUTSIDE(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_INTERSECT(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
-#endif
-};
-
-#endif /* __KX_CAMERA_H__ */
diff --git a/source/gameengine/Ketsji/KX_CameraActuator.cpp b/source/gameengine/Ketsji/KX_CameraActuator.cpp
deleted file mode 100644
index e488bf3c30a..00000000000
--- a/source/gameengine/Ketsji/KX_CameraActuator.cpp
+++ /dev/null
@@ -1,428 +0,0 @@
-/*
- * KX_CameraActuator.cpp
- *
- *
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- *
- */
-
-/** \file gameengine/Ketsji/KX_CameraActuator.cpp
- * \ingroup ketsji
- */
-
-#include "BLI_math_vector.h"
-
-#include "KX_CameraActuator.h"
-#include <math.h>
-#include <float.h>
-#include "KX_GameObject.h"
-
-#include "EXP_PyObjectPlus.h"
-
-/* ------------------------------------------------------------------------- */
-/* Native functions */
-/* ------------------------------------------------------------------------- */
-
-KX_CameraActuator::KX_CameraActuator(
- SCA_IObject* gameobj,
- SCA_IObject *obj,
- float hght,
- float minhght,
- float maxhght,
- short axis,
- float damping
-):
- SCA_IActuator(gameobj, KX_ACT_CAMERA),
- m_ob (obj),
- m_height (hght),
- m_minHeight (minhght),
- m_maxHeight (maxhght),
- m_axis(axis),
- m_damping (damping)
-{
- if (m_ob)
- m_ob->RegisterActuator(this);
-}
-
-KX_CameraActuator::~KX_CameraActuator()
-{
- if (m_ob)
- m_ob->UnregisterActuator(this);
-}
-
- CValue*
-KX_CameraActuator::
-GetReplica(
-) {
- KX_CameraActuator* replica = new KX_CameraActuator(*this);
- replica->ProcessReplica();
- return replica;
-};
-
-void KX_CameraActuator::ProcessReplica()
-{
- if (m_ob)
- m_ob->RegisterActuator(this);
- SCA_IActuator::ProcessReplica();
-}
-
-bool KX_CameraActuator::UnlinkObject(SCA_IObject* clientobj)
-{
- if (clientobj == m_ob)
- {
- // this object is being deleted, we cannot continue to track it.
- m_ob = NULL;
- return true;
- }
- return false;
-}
-
-
-void KX_CameraActuator::Relink(CTR_Map<CTR_HashedPtr, void*> *obj_map)
-{
- void **h_obj = (*obj_map)[m_ob];
- if (h_obj) {
- if (m_ob)
- m_ob->UnregisterActuator(this);
- m_ob = (SCA_IObject*)(*h_obj);
- m_ob->RegisterActuator(this);
- }
-}
-
-/* copied from blender BLI_math ... don't know if there's an equivalent */
-
-static void Kx_VecUpMat3(float vec[3], float mat[3][3], short axis)
-{
-
- // Construct a camera matrix s.t. the specified axis
-
- // maps to the given vector (*vec). Also defines the rotation
-
- // about this axis by mapping one of the other axis to the y-axis.
-
-
- float inp;
- short cox = 0, coy = 0, coz = 0;
-
- /* up range has no meaning, is not really up!
- * see: VecUpMat3old
- */
-
- if (axis==0) {
- cox= 0; coy= 1; coz= 2; /* Y up Z tr */
- }
- if (axis==1) {
- cox= 1; coy= 2; coz= 0; /* Z up X tr */
- }
- if (axis==2) {
- cox= 2; coy= 0; coz= 1; /* X up Y tr */
- }
- if (axis==3) {
- cox= 0; coy= 1; coz= 2; /* Y op -Z tr */
- vec[0] = -vec[0];
- vec[1] = -vec[1];
- vec[2] = -vec[2];
- }
- if (axis==4) {
- cox= 1; coy= 0; coz= 2; /* */
- }
- if (axis==5) {
- cox= 2; coy= 1; coz= 0; /* Y up X tr */
- }
-
- mat[coz][0] = vec[0];
- mat[coz][1] = vec[1];
- mat[coz][2] = vec[2];
- if (normalize_v3((float *)mat[coz]) == 0.f) {
- /* this is a very abnormal situation: the camera has reach the object center exactly
- * We will choose a completely arbitrary direction */
- mat[coz][0] = 1.0f;
- mat[coz][1] = 0.0f;
- mat[coz][2] = 0.0f;
- }
-
- inp = mat[coz][2];
- mat[coy][0] = - inp * mat[coz][0];
- mat[coy][1] = - inp * mat[coz][1];
- mat[coy][2] = 1.0f - inp * mat[coz][2];
-
- if (normalize_v3((float *)mat[coy]) == 0.f) {
- /* the camera is vertical, chose the y axis arbitrary */
- mat[coy][0] = 0.f;
- mat[coy][1] = 1.f;
- mat[coy][2] = 0.f;
- }
-
- cross_v3_v3v3(mat[cox], mat[coy], mat[coz]);
-}
-
-bool KX_CameraActuator::Update(double curtime, bool frame)
-{
- /* wondering... is it really necessary/desirable to suppress negative */
- /* events here? */
- bool bNegativeEvent = IsNegativeEvent();
- RemoveAllEvents();
-
- if (bNegativeEvent || !m_ob)
- return false;
-
- KX_GameObject *obj = (KX_GameObject*) GetParent();
- MT_Point3 from = obj->NodeGetWorldPosition();
- MT_Matrix3x3 frommat = obj->NodeGetWorldOrientation();
- /* These casts are _very_ dangerous!!! */
- MT_Point3 lookat = ((KX_GameObject*)m_ob)->NodeGetWorldPosition();
- MT_Matrix3x3 actormat = ((KX_GameObject*)m_ob)->NodeGetWorldOrientation();
-
- float fp1[3]={0}, fp2[3]={0}, rc[3];
- float inp, fac; //, factor = 0.0; /* some factor... */
- float mindistsq, maxdistsq, distsq;
- float mat[3][3];
-
- /* The rules: */
- /* CONSTRAINT 1: not implemented */
- /* CONSTRAINT 2: can camera see actor? */
- /* CONSTRAINT 3: fixed height relative to floor below actor. */
- /* CONSTRAINT 4: camera rotates behind actor */
- /* CONSTRAINT 5: minimum / maximum distance */
- /* CONSTRAINT 6: again: fixed height relative to floor below actor */
- /* CONSTRAINT 7: track to floor below actor */
- /* CONSTRAINT 8: look a little bit left or right, depending on how the
- *
- * character is looking (horizontal x)
- */
-
- /* ...and then set the camera position. Since we assume the parent of */
- /* this actuator is always a camera, just set the parent position and */
- /* rotation. We do not check whether we really have a camera as parent. */
- /* It may be better to turn this into a general tracking actuator later */
- /* on, since lots of plausible relations can be filled in here. */
-
- /* ... set up some parameters ... */
- /* missing here: the 'floorloc' of the actor's shadow */
-
- mindistsq= m_minHeight*m_minHeight;
- maxdistsq= m_maxHeight*m_maxHeight;
-
- /* C1: not checked... is a future option */
-
- /* C2: blender test_visibility function. Can this be a ray-test? */
-
- /* C3: fixed height */
- from[2] = (15.0f * from[2] + lookat[2] + m_height) / 16.0f;
-
-
- /* C4: camera behind actor */
- switch (m_axis) {
- case OB_POSX:
- /* X */
- fp1[0] = actormat[0][0];
- fp1[1] = actormat[1][0];
- fp1[2] = actormat[2][0];
-
- fp2[0] = frommat[0][0];
- fp2[1] = frommat[1][0];
- fp2[2] = frommat[2][0];
- break;
- case OB_POSY:
- /* Y */
- fp1[0] = actormat[0][1];
- fp1[1] = actormat[1][1];
- fp1[2] = actormat[2][1];
-
- fp2[0] = frommat[0][1];
- fp2[1] = frommat[1][1];
- fp2[2] = frommat[2][1];
- break;
- case OB_NEGX:
- /* -X */
- fp1[0] = -actormat[0][0];
- fp1[1] = -actormat[1][0];
- fp1[2] = -actormat[2][0];
-
- fp2[0] = frommat[0][0];
- fp2[1] = frommat[1][0];
- fp2[2] = frommat[2][0];
- break;
- case OB_NEGY:
- /* -Y */
- fp1[0] = -actormat[0][1];
- fp1[1] = -actormat[1][1];
- fp1[2] = -actormat[2][1];
-
- fp2[0] = frommat[0][1];
- fp2[1] = frommat[1][1];
- fp2[2] = frommat[2][1];
- break;
- default:
- assert(0);
- break;
- }
-
- inp = fp1[0]*fp2[0] + fp1[1]*fp2[1] + fp1[2]*fp2[2];
- fac = (-1.0f + inp) * m_damping;
-
- from[0] += fac * fp1[0];
- from[1] += fac * fp1[1];
- from[2] += fac * fp1[2];
-
- /* only for it lies: cross test and perpendicular bites up */
- if (inp < 0.0f) {
- /* Don't do anything if the cross product is too small.
- * The camera up-axis becomes unstable and starts to oscillate.
- * The 0.01f threshold is arbitrary but seems to work well in practice. */
- float cross = fp1[0] * fp2[1] - fp1[1] * fp2[0];
- if (cross > 0.01f) {
- from[0] -= fac * fp1[1];
- from[1] += fac * fp1[0];
- }
- else if (cross < -0.01f) {
- from[0] += fac * fp1[1];
- from[1] -= fac * fp1[0];
- }
- }
-
- /* CONSTRAINT 5: minimum / maximum distance */
-
- rc[0] = (lookat[0]-from[0]);
- rc[1] = (lookat[1]-from[1]);
- rc[2] = (lookat[2]-from[2]);
- distsq = rc[0]*rc[0] + rc[1]*rc[1] + rc[2]*rc[2];
-
- if (distsq > maxdistsq) {
- distsq = 0.15f * (distsq - maxdistsq) / distsq;
-
- from[0] += distsq*rc[0];
- from[1] += distsq*rc[1];
- from[2] += distsq*rc[2];
- }
- else if (distsq < mindistsq) {
- distsq = 0.15f * (mindistsq - distsq) / mindistsq;
-
- from[0] -= distsq*rc[0];
- from[1] -= distsq*rc[1];
- from[2] -= distsq*rc[2];
- }
-
-
- /* CONSTRAINT 7: track to floor below actor */
- rc[0] = (lookat[0]-from[0]);
- rc[1] = (lookat[1]-from[1]);
- rc[2] = (lookat[2]-from[2]);
- Kx_VecUpMat3(rc, mat, 3); /* y up Track -z */
-
-
-
-
- /* now set the camera position and rotation */
-
- obj->NodeSetLocalPosition(from);
-
- actormat[0][0] = mat[0][0]; actormat[0][1] = mat[1][0]; actormat[0][2] = mat[2][0];
- actormat[1][0] = mat[0][1]; actormat[1][1] = mat[1][1]; actormat[1][2] = mat[2][1];
- actormat[2][0] = mat[0][2]; actormat[2][1] = mat[1][2]; actormat[2][2] = mat[2][2];
- obj->NodeSetLocalOrientation(actormat);
-
- return true;
-}
-
-CValue *KX_CameraActuator::findObject(const char *obName)
-{
- /* hook to object system */
- return NULL;
-}
-
-#ifdef WITH_PYTHON
-
-/* ------------------------------------------------------------------------- */
-/* Python functions */
-/* ------------------------------------------------------------------------- */
-
-/* Integration hooks ------------------------------------------------------- */
-PyTypeObject KX_CameraActuator::Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "KX_CameraActuator",
- sizeof(PyObjectPlus_Proxy),
- 0,
- py_base_dealloc,
- 0,
- 0,
- 0,
- 0,
- py_base_repr,
- 0,0,0,0,0,0,0,0,0,
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
- 0,0,0,0,0,0,0,
- Methods,
- 0,
- 0,
- &SCA_IActuator::Type,
- 0,0,0,0,0,0,
- py_base_new
-};
-
-PyMethodDef KX_CameraActuator::Methods[] = {
- {NULL, NULL} //Sentinel
-};
-
-PyAttributeDef KX_CameraActuator::Attributes[] = {
- KX_PYATTRIBUTE_FLOAT_RW("min",-FLT_MAX,FLT_MAX,KX_CameraActuator,m_minHeight),
- KX_PYATTRIBUTE_FLOAT_RW("max",-FLT_MAX,FLT_MAX,KX_CameraActuator,m_maxHeight),
- KX_PYATTRIBUTE_FLOAT_RW("height",-FLT_MAX,FLT_MAX,KX_CameraActuator,m_height),
- KX_PYATTRIBUTE_SHORT_RW("axis", 0, 5, true, KX_CameraActuator, m_axis),
- KX_PYATTRIBUTE_RW_FUNCTION("object", KX_CameraActuator, pyattr_get_object, pyattr_set_object),
- KX_PYATTRIBUTE_FLOAT_RW("damping",0.f,10.f,KX_CameraActuator,m_damping),
- {NULL}
-};
-
-PyObject *KX_CameraActuator::pyattr_get_object(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_CameraActuator* self = static_cast<KX_CameraActuator*>(self_v);
- if (self->m_ob==NULL)
- Py_RETURN_NONE;
- else
- return self->m_ob->GetProxy();
-}
-
-int KX_CameraActuator::pyattr_set_object(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_CameraActuator* self = static_cast<KX_CameraActuator*>(self_v);
- KX_GameObject *gameobj;
-
- if (!ConvertPythonToGameObject(self->GetLogicManager(), value, &gameobj, true, "actuator.object = value: KX_CameraActuator"))
- return PY_SET_ATTR_FAIL; // ConvertPythonToGameObject sets the error
-
- if (self->m_ob)
- self->m_ob->UnregisterActuator(self);
-
- if ((self->m_ob = (SCA_IObject*)gameobj))
- self->m_ob->RegisterActuator(self);
-
- return PY_SET_ATTR_SUCCESS;
-}
-
-#endif // WITH_PYTHON
-
-/* eof */
diff --git a/source/gameengine/Ketsji/KX_CameraActuator.h b/source/gameengine/Ketsji/KX_CameraActuator.h
deleted file mode 100644
index fb0a7d88dd9..00000000000
--- a/source/gameengine/Ketsji/KX_CameraActuator.h
+++ /dev/null
@@ -1,138 +0,0 @@
-/*
- * KX_CameraActuator.h
- *
- *
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file KX_CameraActuator.h
- * \ingroup ketsji
- */
-
-#ifndef __KX_CAMERAACTUATOR_H__
-#define __KX_CAMERAACTUATOR_H__
-
-#include "SCA_IActuator.h"
-#include "MT_Scalar.h"
-#include "SCA_LogicManager.h"
-
-/**
- * The camera actuator does a Robbie Muller perspective for you. This is a
- * weird set of rules that positions the camera sort of behind the object,
- * tracking, while avoiding any objects between the 'ideal' position and the
- * actor being tracked.
- */
-
-
-class KX_CameraActuator : public SCA_IActuator
-{
- Py_Header
-private :
- /** Object that will be tracked. */
- SCA_IObject *m_ob;
-
- /** height (float), */
- //const MT_Scalar m_height;
- /** min (float), */
- //const MT_Scalar m_minHeight;
- /** max (float), */
- //const MT_Scalar m_maxHeight;
-
- /** height (float), */
- float m_height;
-
- /** min (float), */
- float m_minHeight;
-
- /** max (float), */
- float m_maxHeight;
-
- /** axis the camera tries to get behind: +x/+y/-x/-y */
- short m_axis;
-
- /** damping (float), */
- float m_damping;
-
- /* get the KX_IGameObject with this name */
- CValue *findObject(const char *obName);
-
- /* parse x or y to a toggle pick */
- bool string2axischoice(const char *axisString);
-
- public:
- static STR_String X_AXIS_STRING;
- static STR_String Y_AXIS_STRING;
-
- /**
- * Set the bool toggle to true to use x lock, false for y lock
- */
- KX_CameraActuator(
-
- SCA_IObject *gameobj,
- //const CValue *ob,
- SCA_IObject *ob,
- float hght,
- float minhght,
- float maxhght,
- short axis,
- float damping
- );
-
-
- ~KX_CameraActuator();
-
-
-
- /** Methods Inherited from CValue */
- CValue* GetReplica();
- virtual void ProcessReplica();
-
-
- /** Methods inherited from SCA_IActuator */
- virtual bool Update(
- double curtime,
- bool frame
- );
- virtual bool UnlinkObject(SCA_IObject* clientobj);
-
- /** Methods inherited from SCA_ILogicBrick */
- virtual void Relink(CTR_Map<CTR_HashedPtr, void*> *obj_map);
-
-#ifdef WITH_PYTHON
-
- /* --------------------------------------------------------------------- */
- /* Python interface ---------------------------------------------------- */
- /* --------------------------------------------------------------------- */
-
- /* set object to look at */
- static PyObject* pyattr_get_object(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_object(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
-
-#endif /* WITH_PYTHON */
-
-};
-
-#endif /* __KX_CAMERAACTUATOR_H__ */
diff --git a/source/gameengine/Ketsji/KX_CameraIpoSGController.cpp b/source/gameengine/Ketsji/KX_CameraIpoSGController.cpp
deleted file mode 100644
index a1c726209e1..00000000000
--- a/source/gameengine/Ketsji/KX_CameraIpoSGController.cpp
+++ /dev/null
@@ -1,126 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Ketsji/KX_CameraIpoSGController.cpp
- * \ingroup ketsji
- */
-
-
-#include "KX_CameraIpoSGController.h"
-#include "KX_ScalarInterpolator.h"
-#include "KX_Camera.h"
-#include "RAS_CameraData.h"
-
-#if defined(_WIN64)
-typedef unsigned __int64 uint_ptr;
-#else
-typedef unsigned long uint_ptr;
-#endif
-
-bool KX_CameraIpoSGController::Update(double currentTime)
-{
- if (m_modified)
- {
- T_InterpolatorList::iterator i;
- for (i = m_interpolators.begin(); !(i == m_interpolators.end()); ++i) {
- (*i)->Execute(m_ipotime);
- }
-
- SG_Spatial* ob = (SG_Spatial*)m_pObject;
- KX_Camera* kxcamera = (KX_Camera*) ob->GetSGClientObject();
- RAS_CameraData* camdata = kxcamera->GetCameraData();
-
- if (m_modify_lens)
- camdata->m_lens = m_lens;
-
- if (m_modify_clipstart )
- camdata->m_clipstart = m_clipstart;
-
- if (m_modify_clipend)
- camdata->m_clipend = m_clipend;
-
- if (m_modify_lens || m_modify_clipstart || m_modify_clipend)
- kxcamera->InvalidateProjectionMatrix();
-
- m_modified=false;
- }
- return false;
-}
-
-
-void KX_CameraIpoSGController::AddInterpolator(KX_IInterpolator* interp)
-{
- this->m_interpolators.push_back(interp);
-}
-
-SG_Controller* KX_CameraIpoSGController::GetReplica(class SG_Node* destnode)
-{
- KX_CameraIpoSGController* iporeplica = new KX_CameraIpoSGController(*this);
- // clear object that ipo acts on
- iporeplica->ClearObject();
-
- // dirty hack, ask Gino for a better solution in the ipo implementation
- // hacken en zagen, in what we call datahiding, not written for replication :(
-
- T_InterpolatorList oldlist = m_interpolators;
- iporeplica->m_interpolators.clear();
-
- T_InterpolatorList::iterator i;
- for (i = oldlist.begin(); !(i == oldlist.end()); ++i) {
- KX_ScalarInterpolator* copyipo = new KX_ScalarInterpolator(*((KX_ScalarInterpolator*)*i));
- iporeplica->AddInterpolator(copyipo);
-
- MT_Scalar* scaal = ((KX_ScalarInterpolator*)*i)->GetTarget();
- uint_ptr orgbase = (uint_ptr)this;
- uint_ptr orgloc = (uint_ptr)scaal;
- uint_ptr offset = orgloc-orgbase;
- uint_ptr newaddrbase = (uint_ptr)iporeplica + offset;
- MT_Scalar* blaptr = (MT_Scalar*) newaddrbase;
- copyipo->SetNewTarget((MT_Scalar*)blaptr);
- }
-
- return iporeplica;
-}
-
-KX_CameraIpoSGController::~KX_CameraIpoSGController()
-{
-
- T_InterpolatorList::iterator i;
- for (i = m_interpolators.begin(); !(i == m_interpolators.end()); ++i) {
- delete (*i);
- }
-
-}
-
- void
-KX_CameraIpoSGController::SetOption(
- int option,
- int value)
-{
- /* Setting options */
-
-}
diff --git a/source/gameengine/Ketsji/KX_CameraIpoSGController.h b/source/gameengine/Ketsji/KX_CameraIpoSGController.h
deleted file mode 100644
index 1f6f211622c..00000000000
--- a/source/gameengine/Ketsji/KX_CameraIpoSGController.h
+++ /dev/null
@@ -1,97 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file KX_CameraIpoSGController.h
- * \ingroup ketsji
- */
-
-#ifndef __KX_CAMERAIPOSGCONTROLLER_H__
-#define __KX_CAMERAIPOSGCONTROLLER_H__
-
-#include "SG_Controller.h"
-#include "SG_Spatial.h"
-
-#include "KX_IInterpolator.h"
-
-struct RAS_CameraData;
-
-class KX_CameraIpoSGController : public SG_Controller
-{
-public:
- MT_Scalar m_lens;
- MT_Scalar m_clipstart;
- MT_Scalar m_clipend;
-
-private:
- T_InterpolatorList m_interpolators;
- unsigned short m_modify_lens : 1;
- unsigned short m_modify_clipstart : 1;
- unsigned short m_modify_clipend : 1;
- bool m_modified;
-
- double m_ipotime;
-public:
- KX_CameraIpoSGController() :
- m_modify_lens(false),
- m_modify_clipstart(false),
- m_modify_clipend(false),
- m_modified(true),
- m_ipotime(0.0)
- {}
-
- ~KX_CameraIpoSGController();
- SG_Controller* GetReplica(class SG_Node* destnode);
- bool Update(double time);
-
- void
- SetOption(
- int option,
- int value
- );
-
- void SetSimulatedTime(double time) {
- m_ipotime = time;
- m_modified = true;
- }
- void SetModifyLens(bool modify) {
- m_modify_lens = modify;
- }
- void SetModifyClipEnd(bool modify) {
- m_modify_clipend = modify;
- }
- void SetModifyClipStart(bool modify) {
- m_modify_clipstart = modify;
- }
- void AddInterpolator(KX_IInterpolator* interp);
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:KX_CameraIpoSGController")
-#endif
-};
-
-#endif /* __KX_CAMERAIPOSGCONTROLLER_H__ */
diff --git a/source/gameengine/Ketsji/KX_CharacterWrapper.cpp b/source/gameengine/Ketsji/KX_CharacterWrapper.cpp
deleted file mode 100644
index 44f06a9f1eb..00000000000
--- a/source/gameengine/Ketsji/KX_CharacterWrapper.cpp
+++ /dev/null
@@ -1,167 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Ketsji/KX_CharacterWrapper.cpp
- * \ingroup ketsji
- */
-
-#include "KX_CharacterWrapper.h"
-#include "PHY_ICharacter.h"
-#include "KX_PyMath.h"
-#include "BLI_utildefines.h"
-
-KX_CharacterWrapper::KX_CharacterWrapper(PHY_ICharacter* character) :
- PyObjectPlus(),
- m_character(character)
-{
-}
-
-KX_CharacterWrapper::~KX_CharacterWrapper()
-{
-}
-
-#ifdef WITH_PYTHON
-
-PyTypeObject KX_CharacterWrapper::Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "KX_CharacterWrapper",
- sizeof(PyObjectPlus_Proxy),
- 0,
- py_base_dealloc,
- 0,
- 0,
- 0,
- 0,
- py_base_repr,
- 0,0,0,0,0,0,0,0,0,
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
- 0,0,0,0,0,0,0,
- Methods,
- 0,
- 0,
- &PyObjectPlus::Type,
- 0,0,0,0,0,0,
- py_base_new
-};
-
-PyAttributeDef KX_CharacterWrapper::Attributes[] = {
- KX_PYATTRIBUTE_RO_FUNCTION("onGround", KX_CharacterWrapper, pyattr_get_onground),
- KX_PYATTRIBUTE_RW_FUNCTION("gravity", KX_CharacterWrapper, pyattr_get_gravity, pyattr_set_gravity),
- KX_PYATTRIBUTE_RW_FUNCTION("maxJumps", KX_CharacterWrapper, pyattr_get_max_jumps, pyattr_set_max_jumps),
- KX_PYATTRIBUTE_RO_FUNCTION("jumpCount", KX_CharacterWrapper, pyattr_get_jump_count),
- KX_PYATTRIBUTE_RW_FUNCTION("walkDirection", KX_CharacterWrapper, pyattr_get_walk_dir, pyattr_set_walk_dir),
- { NULL } //Sentinel
-};
-
-PyObject *KX_CharacterWrapper::pyattr_get_onground(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_CharacterWrapper* self = static_cast<KX_CharacterWrapper*>(self_v);
-
- return PyBool_FromLong(self->m_character->OnGround());
-}
-
-PyObject *KX_CharacterWrapper::pyattr_get_gravity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_CharacterWrapper* self = static_cast<KX_CharacterWrapper*>(self_v);
-
- return PyFloat_FromDouble(self->m_character->GetGravity());
-}
-
-int KX_CharacterWrapper::pyattr_set_gravity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_CharacterWrapper* self = static_cast<KX_CharacterWrapper*>(self_v);
- double param = PyFloat_AsDouble(value);
-
- if (param == -1)
- {
- PyErr_SetString(PyExc_ValueError, "KX_CharacterWrapper.gravity: expected a float");
- return PY_SET_ATTR_FAIL;
- }
-
- self->m_character->SetGravity((float)param);
- return PY_SET_ATTR_SUCCESS;
-}
-
-PyObject *KX_CharacterWrapper::pyattr_get_max_jumps(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_CharacterWrapper* self = static_cast<KX_CharacterWrapper*>(self_v);
-
- return PyLong_FromLong(self->m_character->GetMaxJumps());
-}
-
-int KX_CharacterWrapper::pyattr_set_max_jumps(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_CharacterWrapper* self = static_cast<KX_CharacterWrapper*>(self_v);
- long param = PyLong_AsLong(value);
-
- if (param == -1)
- {
- PyErr_SetString(PyExc_ValueError, "KX_CharacterWrapper.maxJumps: expected an integer");
- return PY_SET_ATTR_FAIL;
- }
-
- CLAMP(param, 0, 255);
-
- self->m_character->SetMaxJumps(param);
- return PY_SET_ATTR_SUCCESS;
-}
-
-PyObject *KX_CharacterWrapper::pyattr_get_jump_count(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_CharacterWrapper* self = static_cast<KX_CharacterWrapper*>(self_v);
-
- return PyLong_FromLong(self->m_character->GetJumpCount());
-}
-
-PyObject *KX_CharacterWrapper::pyattr_get_walk_dir(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_CharacterWrapper* self = static_cast<KX_CharacterWrapper*>(self_v);
-
- return PyObjectFrom(self->m_character->GetWalkDirection());
-}
-
-int KX_CharacterWrapper::pyattr_set_walk_dir(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_CharacterWrapper* self = static_cast<KX_CharacterWrapper*>(self_v);
- MT_Vector3 dir;
- if (!PyVecTo(value, dir)) {
- PyErr_SetString(PyExc_TypeError, "KX_CharacterWrapper.walkDirection: expected a vector");
- return PY_SET_ATTR_FAIL;
- }
-
- self->m_character->SetWalkDirection(dir);
- return PY_SET_ATTR_SUCCESS;
-}
-
-PyMethodDef KX_CharacterWrapper::Methods[] = {
- KX_PYMETHODTABLE_NOARGS(KX_CharacterWrapper, jump),
- {NULL,NULL} //Sentinel
-};
-
-KX_PYMETHODDEF_DOC_NOARGS(KX_CharacterWrapper, jump,
- "jump()\n"
- "makes the character jump.\n")
-{
- m_character->Jump();
-
- Py_RETURN_NONE;
-}
-
-#endif // WITH_PYTHON
diff --git a/source/gameengine/Ketsji/KX_CharacterWrapper.h b/source/gameengine/Ketsji/KX_CharacterWrapper.h
deleted file mode 100644
index dd7ba680ec7..00000000000
--- a/source/gameengine/Ketsji/KX_CharacterWrapper.h
+++ /dev/null
@@ -1,40 +0,0 @@
-
-/** \file KX_CharacterWrapper.h
- * \ingroup ketsji
- */
-
-#ifndef __KX_CHARACTERWRAPPER_H__
-#define __KX_CHARACTERWRAPPER_H__
-
-#include "EXP_Value.h"
-#include "PHY_DynamicTypes.h"
-class PHY_ICharacter;
-
-
-///Python interface to character physics
-class KX_CharacterWrapper : public PyObjectPlus
-{
- Py_Header
-
-public:
- KX_CharacterWrapper(PHY_ICharacter* character);
- virtual ~KX_CharacterWrapper();
-#ifdef WITH_PYTHON
- KX_PYMETHOD_DOC_NOARGS(KX_CharacterWrapper, jump);
-
- static PyObject* pyattr_get_onground(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef);
-
- static PyObject* pyattr_get_gravity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_gravity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static PyObject* pyattr_get_max_jumps(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_max_jumps(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static PyObject* pyattr_get_jump_count(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_walk_dir(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_walk_dir(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
-#endif // WITH_PYTHON
-
-private:
- PHY_ICharacter* m_character;
-};
-
-#endif /* __KX_CHARACTERWRAPPER_H__ */
diff --git a/source/gameengine/Ketsji/KX_ClientObjectInfo.h b/source/gameengine/Ketsji/KX_ClientObjectInfo.h
deleted file mode 100644
index 81ae5b58009..00000000000
--- a/source/gameengine/Ketsji/KX_ClientObjectInfo.h
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file KX_ClientObjectInfo.h
- * \ingroup ketsji
- */
-
-#ifndef __KX_CLIENTOBJECTINFO_H__
-#define __KX_CLIENTOBJECTINFO_H__
-
-/* Note, the way this works with/without sumo is a bit odd */
-
-#include <list>
-
-class SCA_ISensor;
-class KX_GameObject;
-/**
- * Client Type and Additional Info. This structure can be use instead of a bare void* pointer, for safeness, and additional info for callbacks
- */
-struct KX_ClientObjectInfo
-{
- enum clienttype {
- STATIC,
- ACTOR,
- RESERVED1,
- SENSOR,
- OBSENSOR,
- OBACTORSENSOR
- } m_type;
- KX_GameObject* m_gameobject;
- std::list<SCA_ISensor*> m_sensors;
-public:
- KX_ClientObjectInfo(KX_GameObject *gameobject, clienttype type = STATIC) :
- m_type(type),
- m_gameobject(gameobject)
- {}
-
- KX_ClientObjectInfo(const KX_ClientObjectInfo &copy) :
- m_type(copy.m_type),
- m_gameobject(copy.m_gameobject)
- {
- }
-
- virtual ~KX_ClientObjectInfo() {}
-
- virtual bool hasCollisionCallback()
- {
- return m_sensors.size() != 0;
- }
-
- bool isActor() { return m_type <= ACTOR; }
- bool isSensor() { return m_type >= SENSOR && m_type <= OBACTORSENSOR; }
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:KX_ClientObjectInfo")
-#endif
-};
-
-#endif /* __KX_CLIENTOBJECTINFO_H__ */
diff --git a/source/gameengine/Ketsji/KX_ConstraintActuator.cpp b/source/gameengine/Ketsji/KX_ConstraintActuator.cpp
deleted file mode 100644
index 27c074393b4..00000000000
--- a/source/gameengine/Ketsji/KX_ConstraintActuator.cpp
+++ /dev/null
@@ -1,629 +0,0 @@
-/*
- * Apply a constraint to a position or rotation value
- *
- *
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Ketsji/KX_ConstraintActuator.cpp
- * \ingroup ketsji
- */
-
-
-#include "SCA_IActuator.h"
-#include "KX_ConstraintActuator.h"
-#include "SCA_IObject.h"
-#include "MT_Point3.h"
-#include "MT_Matrix3x3.h"
-#include "KX_GameObject.h"
-#include "KX_RayCast.h"
-#include "KX_PythonInit.h" // KX_GetActiveScene
-#include "RAS_MeshObject.h"
-
-#include <stdio.h>
-
-/* ------------------------------------------------------------------------- */
-/* Native functions */
-/* ------------------------------------------------------------------------- */
-
-KX_ConstraintActuator::KX_ConstraintActuator(SCA_IObject *gameobj,
- int posDampTime,
- int rotDampTime,
- float minBound,
- float maxBound,
- float refDir[3],
- int locrotxyz,
- int time,
- int option,
- char *property) :
- SCA_IActuator(gameobj, KX_ACT_CONSTRAINT),
- m_refDirVector(refDir),
- m_currentTime(0)
-{
- m_refDirection[0] = refDir[0];
- m_refDirection[1] = refDir[1];
- m_refDirection[2] = refDir[2];
- m_posDampTime = posDampTime;
- m_rotDampTime = rotDampTime;
- m_locrot = locrotxyz;
- m_option = option;
- m_activeTime = time;
- if (property) {
- m_property = property;
- } else {
- m_property = "";
- }
- /* The units of bounds are determined by the type of constraint. To */
- /* make the constraint application easier and more transparent later on, */
- /* I think converting the bounds to the applicable domain makes more */
- /* sense. */
- switch (m_locrot) {
- case KX_ACT_CONSTRAINT_ORIX:
- case KX_ACT_CONSTRAINT_ORIY:
- case KX_ACT_CONSTRAINT_ORIZ:
- {
- MT_Scalar len = m_refDirVector.length();
- if (MT_fuzzyZero(len)) {
- // missing a valid direction
- std::cout << "WARNING: Constraint actuator " << GetName() << ": There is no valid reference direction!" << std::endl;
- m_locrot = KX_ACT_CONSTRAINT_NODEF;
- } else {
- m_refDirection[0] /= len;
- m_refDirection[1] /= len;
- m_refDirection[2] /= len;
- m_refDirVector /= len;
- }
- m_minimumBound = cosf(minBound);
- m_maximumBound = cosf(maxBound);
- m_minimumSine = sinf(minBound);
- m_maximumSine = sinf(maxBound);
- }
- break;
- default:
- m_minimumBound = minBound;
- m_maximumBound = maxBound;
- m_minimumSine = 0.f;
- m_maximumSine = 0.f;
- break;
- }
-
-} /* End of constructor */
-
-KX_ConstraintActuator::~KX_ConstraintActuator()
-{
- // there's nothing to be done here, really....
-} /* end of destructor */
-
-bool KX_ConstraintActuator::RayHit(KX_ClientObjectInfo *client, KX_RayCast *result, void *UNUSED(data))
-{
-
- m_hitObject = client->m_gameobject;
-
- bool bFound = false;
-
- if (m_property.IsEmpty())
- {
- bFound = true;
- }
- else
- {
- if (m_option & KX_ACT_CONSTRAINT_MATERIAL) {
- for (unsigned int i = 0; i < m_hitObject->GetMeshCount(); ++i) {
- RAS_MeshObject *meshObj = m_hitObject->GetMesh(i);
- for (unsigned int j = 0; j < meshObj->NumMaterials(); ++j) {
- bFound = strcmp(m_property.ReadPtr(), meshObj->GetMaterialName(j).ReadPtr() + 2) == 0;
- if (bFound)
- break;
- }
- }
- }
- else {
- bFound = m_hitObject->GetProperty(m_property) != NULL;
- }
- }
- // update the hit status
- result->m_hitFound = bFound;
- // stop looking
- return true;
-}
-
-/* This function is used to pre-filter the object before casting the ray on them.
- * This is useful for "X-Ray" option when we want to see "through" unwanted object.
- */
-bool KX_ConstraintActuator::NeedRayCast(KX_ClientObjectInfo *client, void *UNUSED(data))
-{
- if (client->m_type > KX_ClientObjectInfo::ACTOR)
- {
- // Unknown type of object, skip it.
- // Should not occur as the sensor objects are filtered in RayTest()
- printf("Invalid client type %d found in ray casting\n", client->m_type);
- return false;
- }
- // no X-Ray function yet
- return true;
-}
-
-bool KX_ConstraintActuator::Update(double curtime, bool frame)
-{
-
- bool result = false;
- bool bNegativeEvent = IsNegativeEvent();
- RemoveAllEvents();
-
- if (!bNegativeEvent) {
- /* Constraint clamps the values to the specified range, with a sort of */
- /* low-pass filtered time response, if the damp time is unequal to 0. */
-
- /* Having to retrieve location/rotation and setting it afterwards may not */
- /* be efficient enough... Something to look at later. */
- KX_GameObject *obj = (KX_GameObject*) GetParent();
- MT_Point3 position = obj->NodeGetWorldPosition();
- MT_Point3 newposition;
- MT_Vector3 normal, direction, refDirection;
- MT_Matrix3x3 rotation = obj->NodeGetWorldOrientation();
- MT_Scalar filter, newdistance, cosangle;
- int axis, sign;
-
- if (m_posDampTime) {
- filter = m_posDampTime/(1.0f+m_posDampTime);
- } else {
- filter = 0.0f;
- }
- switch (m_locrot) {
- case KX_ACT_CONSTRAINT_ORIX:
- case KX_ACT_CONSTRAINT_ORIY:
- case KX_ACT_CONSTRAINT_ORIZ:
- switch (m_locrot) {
- case KX_ACT_CONSTRAINT_ORIX:
- direction[0] = rotation[0][0];
- direction[1] = rotation[1][0];
- direction[2] = rotation[2][0];
- axis = 0;
- break;
- case KX_ACT_CONSTRAINT_ORIY:
- direction[0] = rotation[0][1];
- direction[1] = rotation[1][1];
- direction[2] = rotation[2][1];
- axis = 1;
- break;
- default:
- direction[0] = rotation[0][2];
- direction[1] = rotation[1][2];
- direction[2] = rotation[2][2];
- axis = 2;
- break;
- }
- if ((m_maximumBound < (1.0f-FLT_EPSILON)) || (m_minimumBound < (1.0f-FLT_EPSILON))) {
- // reference direction needs to be evaluated
- // 1. get the cosine between current direction and target
- cosangle = direction.dot(m_refDirVector);
- if (cosangle >= (m_maximumBound-FLT_EPSILON) && cosangle <= (m_minimumBound+FLT_EPSILON)) {
- // no change to do
- result = true;
- goto CHECK_TIME;
- }
- // 2. define a new reference direction
- // compute local axis with reference direction as X and
- // Y in direction X refDirection plane
- MT_Vector3 zaxis = m_refDirVector.cross(direction);
- if (MT_fuzzyZero2(zaxis.length2())) {
- // direction and refDirection are identical,
- // choose any other direction to define plane
- if (direction[0] < 0.9999f)
- zaxis = m_refDirVector.cross(MT_Vector3(1.0f,0.0f,0.0f));
- else
- zaxis = m_refDirVector.cross(MT_Vector3(0.0f,1.0f,0.0f));
- }
- MT_Vector3 yaxis = zaxis.cross(m_refDirVector);
- yaxis.normalize();
- if (cosangle > m_minimumBound) {
- // angle is too close to reference direction,
- // choose a new reference that is exactly at minimum angle
- refDirection = m_minimumBound * m_refDirVector + m_minimumSine * yaxis;
- } else {
- // angle is too large, choose new reference direction at maximum angle
- refDirection = m_maximumBound * m_refDirVector + m_maximumSine * yaxis;
- }
- } else {
- refDirection = m_refDirVector;
- }
- // apply damping on the direction
- direction = filter*direction + (1.0f-filter)*refDirection;
- obj->AlignAxisToVect(direction, axis);
- result = true;
- goto CHECK_TIME;
- case KX_ACT_CONSTRAINT_DIRPX:
- case KX_ACT_CONSTRAINT_DIRPY:
- case KX_ACT_CONSTRAINT_DIRPZ:
- case KX_ACT_CONSTRAINT_DIRNX:
- case KX_ACT_CONSTRAINT_DIRNY:
- case KX_ACT_CONSTRAINT_DIRNZ:
- switch (m_locrot) {
- case KX_ACT_CONSTRAINT_DIRPX:
- normal[0] = rotation[0][0];
- normal[1] = rotation[1][0];
- normal[2] = rotation[2][0];
- axis = 0; // axis according to KX_GameObject::AlignAxisToVect()
- sign = 0; // X axis will be parrallel to direction of ray
- break;
- case KX_ACT_CONSTRAINT_DIRPY:
- normal[0] = rotation[0][1];
- normal[1] = rotation[1][1];
- normal[2] = rotation[2][1];
- axis = 1;
- sign = 0;
- break;
- case KX_ACT_CONSTRAINT_DIRPZ:
- normal[0] = rotation[0][2];
- normal[1] = rotation[1][2];
- normal[2] = rotation[2][2];
- axis = 2;
- sign = 0;
- break;
- case KX_ACT_CONSTRAINT_DIRNX:
- normal[0] = -rotation[0][0];
- normal[1] = -rotation[1][0];
- normal[2] = -rotation[2][0];
- axis = 0;
- sign = 1;
- break;
- case KX_ACT_CONSTRAINT_DIRNY:
- normal[0] = -rotation[0][1];
- normal[1] = -rotation[1][1];
- normal[2] = -rotation[2][1];
- axis = 1;
- sign = 1;
- break;
- case KX_ACT_CONSTRAINT_DIRNZ:
- normal[0] = -rotation[0][2];
- normal[1] = -rotation[1][2];
- normal[2] = -rotation[2][2];
- axis = 2;
- sign = 1;
- break;
- }
- normal.normalize();
- if (m_option & KX_ACT_CONSTRAINT_LOCAL) {
- // direction of the ray is along the local axis
- direction = normal;
- } else {
- switch (m_locrot) {
- case KX_ACT_CONSTRAINT_DIRPX:
- direction = MT_Vector3(1.0f,0.0f,0.0f);
- break;
- case KX_ACT_CONSTRAINT_DIRPY:
- direction = MT_Vector3(0.0f,1.0f,0.0f);
- break;
- case KX_ACT_CONSTRAINT_DIRPZ:
- direction = MT_Vector3(0.0f,0.0f,1.0f);
- break;
- case KX_ACT_CONSTRAINT_DIRNX:
- direction = MT_Vector3(-1.0f,0.0f,0.0f);
- break;
- case KX_ACT_CONSTRAINT_DIRNY:
- direction = MT_Vector3(0.0f,-1.0f,0.0f);
- break;
- case KX_ACT_CONSTRAINT_DIRNZ:
- direction = MT_Vector3(0.0f,0.0f,-1.0f);
- break;
- }
- }
- {
- MT_Point3 topoint = position + (m_maximumBound) * direction;
- PHY_IPhysicsEnvironment* pe = KX_GetActiveScene()->GetPhysicsEnvironment();
- PHY_IPhysicsController *spc = obj->GetPhysicsController();
-
- if (!pe) {
- std::cout << "WARNING: Constraint actuator " << GetName() << ": There is no physics environment!" << std::endl;
- goto CHECK_TIME;
- }
- if (!spc) {
- // the object is not physical, we probably want to avoid hitting its own parent
- KX_GameObject *parent = obj->GetParent();
- if (parent) {
- spc = parent->GetPhysicsController();
- }
- }
- KX_RayCast::Callback<KX_ConstraintActuator, void> callback(this,dynamic_cast<PHY_IPhysicsController*>(spc));
- result = KX_RayCast::RayTest(pe, position, topoint, callback);
- if (result) {
- MT_Vector3 newnormal = callback.m_hitNormal;
- // compute new position & orientation
- if ((m_option & (KX_ACT_CONSTRAINT_NORMAL|KX_ACT_CONSTRAINT_DISTANCE)) == 0) {
- // if none option is set, the actuator does nothing but detect ray
- // (works like a sensor)
- goto CHECK_TIME;
- }
- if (m_option & KX_ACT_CONSTRAINT_NORMAL) {
- MT_Scalar rotFilter;
- // apply damping on the direction
- if (m_rotDampTime) {
- rotFilter = m_rotDampTime/(1.0f+m_rotDampTime);
- } else {
- rotFilter = filter;
- }
- newnormal = rotFilter*normal - (1.0f-rotFilter)*newnormal;
- obj->AlignAxisToVect((sign)?-newnormal:newnormal, axis);
- if (m_option & KX_ACT_CONSTRAINT_LOCAL) {
- direction = newnormal;
- direction.normalize();
- }
- }
- if (m_option & KX_ACT_CONSTRAINT_DISTANCE) {
- if (m_posDampTime) {
- newdistance = filter*(position-callback.m_hitPoint).length()+(1.0f-filter)*m_minimumBound;
- } else {
- newdistance = m_minimumBound;
- }
- // logically we should cancel the speed along the ray direction as we set the
- // position along that axis
- spc = obj->GetPhysicsController();
- if (spc && spc->IsDynamic()) {
- MT_Vector3 linV = spc->GetLinearVelocity();
- // cancel the projection along the ray direction
- MT_Scalar fallspeed = linV.dot(direction);
- if (!MT_fuzzyZero(fallspeed))
- spc->SetLinearVelocity(linV-fallspeed*direction,false);
- }
- } else {
- newdistance = (position-callback.m_hitPoint).length();
- }
- newposition = callback.m_hitPoint-newdistance*direction;
- } else if (m_option & KX_ACT_CONSTRAINT_PERMANENT) {
- // no contact but still keep running
- result = true;
- goto CHECK_TIME;
- }
- }
- break;
- case KX_ACT_CONSTRAINT_FHPX:
- case KX_ACT_CONSTRAINT_FHPY:
- case KX_ACT_CONSTRAINT_FHPZ:
- case KX_ACT_CONSTRAINT_FHNX:
- case KX_ACT_CONSTRAINT_FHNY:
- case KX_ACT_CONSTRAINT_FHNZ:
- switch (m_locrot) {
- case KX_ACT_CONSTRAINT_FHPX:
- normal[0] = -rotation[0][0];
- normal[1] = -rotation[1][0];
- normal[2] = -rotation[2][0];
- direction = MT_Vector3(1.0f,0.0f,0.0f);
- break;
- case KX_ACT_CONSTRAINT_FHPY:
- normal[0] = -rotation[0][1];
- normal[1] = -rotation[1][1];
- normal[2] = -rotation[2][1];
- direction = MT_Vector3(0.0f,1.0f,0.0f);
- break;
- case KX_ACT_CONSTRAINT_FHPZ:
- normal[0] = -rotation[0][2];
- normal[1] = -rotation[1][2];
- normal[2] = -rotation[2][2];
- direction = MT_Vector3(0.0f,0.0f,1.0f);
- break;
- case KX_ACT_CONSTRAINT_FHNX:
- normal[0] = rotation[0][0];
- normal[1] = rotation[1][0];
- normal[2] = rotation[2][0];
- direction = MT_Vector3(-1.0f,0.0f,0.0f);
- break;
- case KX_ACT_CONSTRAINT_FHNY:
- normal[0] = rotation[0][1];
- normal[1] = rotation[1][1];
- normal[2] = rotation[2][1];
- direction = MT_Vector3(0.0f,-1.0f,0.0f);
- break;
- case KX_ACT_CONSTRAINT_FHNZ:
- normal[0] = rotation[0][2];
- normal[1] = rotation[1][2];
- normal[2] = rotation[2][2];
- direction = MT_Vector3(0.0f,0.0f,-1.0f);
- break;
- }
- normal.normalize();
- {
- PHY_IPhysicsEnvironment* pe = KX_GetActiveScene()->GetPhysicsEnvironment();
- PHY_IPhysicsController *spc = obj->GetPhysicsController();
-
- if (!pe) {
- std::cout << "WARNING: Constraint actuator " << GetName() << ": There is no physics environment!" << std::endl;
- goto CHECK_TIME;
- }
- if (!spc || !spc->IsDynamic()) {
- // the object is not dynamic, it won't support setting speed
- goto CHECK_TIME;
- }
- m_hitObject = NULL;
- // distance of Fh area is stored in m_minimum
- MT_Point3 topoint = position + (m_minimumBound+spc->GetRadius()) * direction;
- KX_RayCast::Callback<KX_ConstraintActuator, void> callback(this, spc);
- result = KX_RayCast::RayTest(pe, position, topoint, callback);
- // we expect a hit object
- if (!m_hitObject)
- result = false;
- if (result)
- {
- MT_Vector3 newnormal = callback.m_hitNormal;
- // compute new position & orientation
- MT_Scalar distance = (callback.m_hitPoint-position).length()-spc->GetRadius();
- // estimate the velocity of the hit point
- MT_Point3 relativeHitPoint;
- relativeHitPoint = (callback.m_hitPoint-m_hitObject->NodeGetWorldPosition());
- MT_Vector3 velocityHitPoint = m_hitObject->GetVelocity(relativeHitPoint);
- MT_Vector3 relativeVelocity = spc->GetLinearVelocity() - velocityHitPoint;
- MT_Scalar relativeVelocityRay = direction.dot(relativeVelocity);
- MT_Scalar springExtent = 1.0f - distance/m_minimumBound;
- // Fh force is stored in m_maximum
- MT_Scalar springForce = springExtent * m_maximumBound;
- // damping is stored in m_refDirection [0] = damping, [1] = rot damping
- MT_Scalar springDamp = relativeVelocityRay * m_refDirVector[0];
- MT_Vector3 newVelocity = spc->GetLinearVelocity()-(springForce+springDamp)*direction;
- if (m_option & KX_ACT_CONSTRAINT_NORMAL)
- {
- newVelocity+=(springForce+springDamp)*(newnormal-newnormal.dot(direction)*direction);
- }
- spc->SetLinearVelocity(newVelocity, false);
- if (m_option & KX_ACT_CONSTRAINT_DOROTFH)
- {
- MT_Vector3 angSpring = (normal.cross(newnormal))*m_maximumBound;
- MT_Vector3 angVelocity = spc->GetAngularVelocity();
- // remove component that is parallel to normal
- angVelocity -= angVelocity.dot(newnormal)*newnormal;
- MT_Vector3 angDamp = angVelocity * ((m_refDirVector[1]>MT_EPSILON)?m_refDirVector[1]:m_refDirVector[0]);
- spc->SetAngularVelocity(spc->GetAngularVelocity()+(angSpring-angDamp), false);
- }
- } else if (m_option & KX_ACT_CONSTRAINT_PERMANENT) {
- // no contact but still keep running
- result = true;
- }
- // don't set the position with this constraint
- goto CHECK_TIME;
- }
- break;
- case KX_ACT_CONSTRAINT_LOCX:
- case KX_ACT_CONSTRAINT_LOCY:
- case KX_ACT_CONSTRAINT_LOCZ:
- newposition = position = obj->GetSGNode()->GetLocalPosition();
- switch (m_locrot) {
- case KX_ACT_CONSTRAINT_LOCX:
- Clamp(newposition[0], m_minimumBound, m_maximumBound);
- break;
- case KX_ACT_CONSTRAINT_LOCY:
- Clamp(newposition[1], m_minimumBound, m_maximumBound);
- break;
- case KX_ACT_CONSTRAINT_LOCZ:
- Clamp(newposition[2], m_minimumBound, m_maximumBound);
- break;
- }
- result = true;
- if (m_posDampTime) {
- newposition = filter*position + (1.0f-filter)*newposition;
- }
- obj->NodeSetLocalPosition(newposition);
- goto CHECK_TIME;
- }
- if (result) {
- // set the new position but take into account parent if any
- obj->NodeSetWorldPosition(newposition);
- }
- CHECK_TIME:
- if (result && m_activeTime > 0 ) {
- if (++m_currentTime >= m_activeTime)
- result = false;
- }
- }
- if (!result) {
- m_currentTime = 0;
- }
- return result;
-} /* end of KX_ConstraintActuator::Update(double curtime,double deltatime) */
-
-void KX_ConstraintActuator::Clamp(MT_Scalar &var,
- float min,
- float max) {
- if (var < min) {
- var = min;
- } else if (var > max) {
- var = max;
- }
-}
-
-
-bool KX_ConstraintActuator::IsValidMode(KX_ConstraintActuator::KX_CONSTRAINTTYPE m)
-{
- bool res = false;
-
- if ( (m > KX_ACT_CONSTRAINT_NODEF) && (m < KX_ACT_CONSTRAINT_MAX)) {
- res = true;
- }
-
- return res;
-}
-
-#ifdef WITH_PYTHON
-
-/* ------------------------------------------------------------------------- */
-/* Python functions */
-/* ------------------------------------------------------------------------- */
-
-/* Integration hooks ------------------------------------------------------- */
-PyTypeObject KX_ConstraintActuator::Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "KX_ConstraintActuator",
- sizeof(PyObjectPlus_Proxy),
- 0,
- py_base_dealloc,
- 0,
- 0,
- 0,
- 0,
- py_base_repr,
- 0,0,0,0,0,0,0,0,0,
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
- 0,0,0,0,0,0,0,
- Methods,
- 0,
- 0,
- &SCA_IActuator::Type,
- 0,0,0,0,0,0,
- py_base_new
-};
-
-PyMethodDef KX_ConstraintActuator::Methods[] = {
- {NULL,NULL} //Sentinel
-};
-
-PyAttributeDef KX_ConstraintActuator::Attributes[] = {
- KX_PYATTRIBUTE_INT_RW("damp",0,100,true,KX_ConstraintActuator,m_posDampTime),
- KX_PYATTRIBUTE_INT_RW("rotDamp",0,100,true,KX_ConstraintActuator,m_rotDampTime),
- KX_PYATTRIBUTE_FLOAT_ARRAY_RW_CHECK("direction",-FLT_MAX,FLT_MAX,KX_ConstraintActuator,m_refDirection,3,pyattr_check_direction),
- KX_PYATTRIBUTE_INT_RW("option",0,0xFFFF,false,KX_ConstraintActuator,m_option),
- KX_PYATTRIBUTE_INT_RW("time",0,1000,true,KX_ConstraintActuator,m_activeTime),
- KX_PYATTRIBUTE_STRING_RW("propName",0,MAX_PROP_NAME,true,KX_ConstraintActuator,m_property),
- KX_PYATTRIBUTE_FLOAT_RW("min",-FLT_MAX,FLT_MAX,KX_ConstraintActuator,m_minimumBound),
- KX_PYATTRIBUTE_FLOAT_RW("distance",-FLT_MAX,FLT_MAX,KX_ConstraintActuator,m_minimumBound),
- KX_PYATTRIBUTE_FLOAT_RW("max",-FLT_MAX,FLT_MAX,KX_ConstraintActuator,m_maximumBound),
- KX_PYATTRIBUTE_FLOAT_RW("rayLength",0,2000.f,KX_ConstraintActuator,m_maximumBound),
- KX_PYATTRIBUTE_INT_RW("limit",KX_ConstraintActuator::KX_ACT_CONSTRAINT_NODEF+1,KX_ConstraintActuator::KX_ACT_CONSTRAINT_MAX-1,false,KX_ConstraintActuator,m_locrot),
- { NULL } //Sentinel
-};
-
-int KX_ConstraintActuator::pyattr_check_direction(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_ConstraintActuator* act = static_cast<KX_ConstraintActuator*>(self);
- MT_Vector3 dir(act->m_refDirection);
- MT_Scalar len = dir.length();
- if (MT_fuzzyZero(len)) {
- PyErr_SetString(PyExc_ValueError, "actuator.direction = vec: KX_ConstraintActuator, invalid direction");
- return 1;
- }
- act->m_refDirVector = dir/len;
- return 0;
-}
-
-#endif
-
-/* eof */
diff --git a/source/gameengine/Ketsji/KX_ConstraintActuator.h b/source/gameengine/Ketsji/KX_ConstraintActuator.h
deleted file mode 100644
index af617655d5e..00000000000
--- a/source/gameengine/Ketsji/KX_ConstraintActuator.h
+++ /dev/null
@@ -1,152 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file KX_ConstraintActuator.h
- * \ingroup ketsji
- */
-
-#ifndef __KX_CONSTRAINTACTUATOR_H__
-#define __KX_CONSTRAINTACTUATOR_H__
-
-#include "SCA_IActuator.h"
-#include "MT_Scalar.h"
-#include "MT_Vector3.h"
-#include "KX_ClientObjectInfo.h"
-
-#include "BLI_utildefines.h"
-
-class KX_RayCast;
-class KX_GameObject;
-
-class KX_ConstraintActuator : public SCA_IActuator
-{
- Py_Header
-protected:
- // Damp time (int),
- int m_posDampTime;
- int m_rotDampTime;
- // min (float)
- float m_minimumBound;
- // max (float)
- float m_maximumBound;
- // sinus of minimum angle
- float m_minimumSine;
- // sinus of maximum angle
- float m_maximumSine;
- // reference direction
- float m_refDirection[3];
- MT_Vector3 m_refDirVector; // same as m_refDirection
- // locrotxyz choice (pick one): only one choice allowed at a time!
- int m_locrot;
- // active time of actuator
- int m_activeTime;
- int m_currentTime;
- // option
- int m_option;
- // property to check
- STR_String m_property;
- // hit object
- KX_GameObject* m_hitObject;
-
- /**
- * Clamp <var> to <min>, <max>. Borders are included (in as far as
- * float comparisons are good for equality...).
- */
- void Clamp(MT_Scalar &var, float min, float max);
-
-
- public:
- // m_locrot
- enum KX_CONSTRAINTTYPE {
- KX_ACT_CONSTRAINT_NODEF = 0,
- KX_ACT_CONSTRAINT_LOCX,
- KX_ACT_CONSTRAINT_LOCY,
- KX_ACT_CONSTRAINT_LOCZ,
- KX_ACT_CONSTRAINT_ROTX,
- KX_ACT_CONSTRAINT_ROTY,
- KX_ACT_CONSTRAINT_ROTZ,
- KX_ACT_CONSTRAINT_DIRPX,
- KX_ACT_CONSTRAINT_DIRPY,
- KX_ACT_CONSTRAINT_DIRPZ,
- KX_ACT_CONSTRAINT_DIRNX,
- KX_ACT_CONSTRAINT_DIRNY,
- KX_ACT_CONSTRAINT_DIRNZ,
- KX_ACT_CONSTRAINT_ORIX,
- KX_ACT_CONSTRAINT_ORIY,
- KX_ACT_CONSTRAINT_ORIZ,
- KX_ACT_CONSTRAINT_FHPX,
- KX_ACT_CONSTRAINT_FHPY,
- KX_ACT_CONSTRAINT_FHPZ,
- KX_ACT_CONSTRAINT_FHNX,
- KX_ACT_CONSTRAINT_FHNY,
- KX_ACT_CONSTRAINT_FHNZ,
- KX_ACT_CONSTRAINT_MAX
- };
- // match ACT_CONST_... values from BIF_interface.h
- enum KX_CONSTRAINTOPT {
- KX_ACT_CONSTRAINT_NORMAL = 64,
- KX_ACT_CONSTRAINT_MATERIAL = 128,
- KX_ACT_CONSTRAINT_PERMANENT = 256,
- KX_ACT_CONSTRAINT_DISTANCE = 512,
- KX_ACT_CONSTRAINT_LOCAL = 1024,
- KX_ACT_CONSTRAINT_DOROTFH = 2048
- };
- bool IsValidMode(KX_CONSTRAINTTYPE m);
- /// \see KX_RayCast
- bool RayHit(KX_ClientObjectInfo *client, KX_RayCast *result, void *UNUSED(data));
- /// \see KX_RayCast
- bool NeedRayCast(KX_ClientObjectInfo *client, void *UNUSED(data));
-
- KX_ConstraintActuator(SCA_IObject* gameobj,
- int posDamptime,
- int rotDampTime,
- float min,
- float max,
- float refDir[3],
- int locrot,
- int time,
- int option,
- char *property);
- virtual ~KX_ConstraintActuator();
- virtual CValue* GetReplica() {
- KX_ConstraintActuator* replica = new KX_ConstraintActuator(*this);
- replica->ProcessReplica();
- return replica;
- };
-
- virtual bool Update(double curtime, bool frame);
-
- /* --------------------------------------------------------------------- */
- /* Python interface ---------------------------------------------------- */
- /* --------------------------------------------------------------------- */
-
- static int pyattr_check_direction(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_check_min(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef);
-
-};
-
-#endif /* __KX_CONSTRAINTACTUATOR_H__ */
diff --git a/source/gameengine/Ketsji/KX_ConstraintWrapper.cpp b/source/gameengine/Ketsji/KX_ConstraintWrapper.cpp
deleted file mode 100644
index 2f32b5e3216..00000000000
--- a/source/gameengine/Ketsji/KX_ConstraintWrapper.cpp
+++ /dev/null
@@ -1,133 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Ketsji/KX_ConstraintWrapper.cpp
- * \ingroup ketsji
- */
-
-
-#include "EXP_PyObjectPlus.h"
-#include "KX_ConstraintWrapper.h"
-#include "PHY_IPhysicsEnvironment.h"
-
-KX_ConstraintWrapper::KX_ConstraintWrapper(
- PHY_ConstraintType ctype,
- int constraintId,
- PHY_IPhysicsEnvironment* physenv) :
- PyObjectPlus(),
- m_constraintId(constraintId),
- m_constraintType(ctype),
- m_physenv(physenv)
-{
-}
-KX_ConstraintWrapper::~KX_ConstraintWrapper()
-{
-}
-
-#ifdef WITH_PYTHON
-
-PyObject *KX_ConstraintWrapper::PyGetConstraintId()
-{
- return PyLong_FromLong(m_constraintId);
-}
-
-
-PyObject *KX_ConstraintWrapper::PyGetParam(PyObject *args, PyObject *kwds)
-{
- int dof;
- float value;
-
- if (!PyArg_ParseTuple(args,"i:getParam",&dof))
- return NULL;
-
- value = m_physenv->GetConstraintParam(m_constraintId,dof);
- return PyFloat_FromDouble(value);
-
-}
-
-PyObject *KX_ConstraintWrapper::PySetParam(PyObject *args, PyObject *kwds)
-{
- int dof;
- float minLimit,maxLimit;
-
- if (!PyArg_ParseTuple(args,"iff:setParam",&dof,&minLimit,&maxLimit))
- return NULL;
-
- m_physenv->SetConstraintParam(m_constraintId,dof,minLimit,maxLimit);
- Py_RETURN_NONE;
-}
-
-
-//python specific stuff
-PyTypeObject KX_ConstraintWrapper::Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "KX_ConstraintWrapper",
- sizeof(PyObjectPlus_Proxy),
- 0,
- py_base_dealloc,
- 0,
- 0,
- 0,
- 0,
- py_base_repr,
- 0,0,0,0,0,0,0,0,0,
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
- 0,0,0,0,0,0,0,
- Methods,
- 0,
- 0,
- &PyObjectPlus::Type,
- 0,0,0,0,0,0,
- py_base_new
-};
-
-PyMethodDef KX_ConstraintWrapper::Methods[] = {
- {"getConstraintId",(PyCFunction) KX_ConstraintWrapper::sPyGetConstraintId, METH_NOARGS},
- {"setParam",(PyCFunction) KX_ConstraintWrapper::sPySetParam, METH_VARARGS},
- {"getParam",(PyCFunction) KX_ConstraintWrapper::sPyGetParam, METH_VARARGS},
- {NULL,NULL} //Sentinel
-};
-
-PyAttributeDef KX_ConstraintWrapper::Attributes[] = {
- KX_PYATTRIBUTE_RO_FUNCTION("constraint_id", KX_ConstraintWrapper, pyattr_get_constraintId),
- KX_PYATTRIBUTE_RO_FUNCTION("constraint_type", KX_ConstraintWrapper, pyattr_get_constraintType),
- { NULL } //Sentinel
-};
-
-PyObject *KX_ConstraintWrapper::pyattr_get_constraintId(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_ConstraintWrapper* self = static_cast<KX_ConstraintWrapper*>(self_v);
- return self->PyGetConstraintId();
-}
-
-PyObject *KX_ConstraintWrapper::pyattr_get_constraintType(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_ConstraintWrapper* self = static_cast<KX_ConstraintWrapper*>(self_v);
- return PyLong_FromLong(self->m_constraintType);
-}
-
-#endif // WITH_PYTHON
diff --git a/source/gameengine/Ketsji/KX_ConstraintWrapper.h b/source/gameengine/Ketsji/KX_ConstraintWrapper.h
deleted file mode 100644
index 5e20b7a9aca..00000000000
--- a/source/gameengine/Ketsji/KX_ConstraintWrapper.h
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file KX_ConstraintWrapper.h
- * \ingroup ketsji
- */
-
-#ifndef __KX_CONSTRAINTWRAPPER_H__
-#define __KX_CONSTRAINTWRAPPER_H__
-
-#include "EXP_Value.h"
-#include "PHY_DynamicTypes.h"
-
-class KX_ConstraintWrapper : public PyObjectPlus
-{
- Py_Header
-public:
- KX_ConstraintWrapper(PHY_ConstraintType ctype,int constraintId,class PHY_IPhysicsEnvironment* physenv);
- virtual ~KX_ConstraintWrapper ();
- int getConstraintId() { return m_constraintId; }
-
-#ifdef WITH_PYTHON
- KX_PYMETHOD_NOARGS(KX_ConstraintWrapper,GetConstraintId);
- KX_PYMETHOD(KX_ConstraintWrapper,SetParam);
- KX_PYMETHOD(KX_ConstraintWrapper,GetParam);
-
- static PyObject *pyattr_get_constraintId(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject *pyattr_get_constraintType(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
-#endif
-
-private:
- int m_constraintId;
- PHY_ConstraintType m_constraintType;
- PHY_IPhysicsEnvironment* m_physenv;
-};
-
-#endif /* __KX_CONSTRAINTWRAPPER_H__ */
diff --git a/source/gameengine/Ketsji/KX_Dome.cpp b/source/gameengine/Ketsji/KX_Dome.cpp
deleted file mode 100644
index 7abff85d39c..00000000000
--- a/source/gameengine/Ketsji/KX_Dome.cpp
+++ /dev/null
@@ -1,2051 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * Contributor(s): Dalai Felinto
- *
- * This code is originally inspired on some of the ideas and codes from Paul Bourke.
- * Developed as part of a Research and Development project for
- * SAT - La Société des arts technologiques.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Ketsji/KX_Dome.cpp
- * \ingroup ketsji
- */
-
-#include "KX_Dome.h"
-
-#ifdef WITH_PYTHON
-#include <structmember.h>
-#endif
-
-#include <float.h>
-#include <math.h>
-
-#include "DNA_scene_types.h"
-#include "RAS_CameraData.h"
-#include "BLI_math.h"
-
-#include "GPU_matrix.h"
-
-// constructor
-KX_Dome::KX_Dome (
- RAS_ICanvas* canvas,
- /// rasterizer
- RAS_IRasterizer* rasterizer,
- /// engine
- KX_KetsjiEngine* engine,
-
- short res, //resolution of the mesh
- short mode, //mode - fisheye, truncated, warped, panoramic, ...
- short angle,
- float resbuf, //size adjustment of the buffer
- short tilt,
- struct Text* warptext
-
- ):
- dlistSupported(false),
- canvaswidth(-1), canvasheight(-1),
- m_drawingmode(rasterizer->GetDrawingMode()),
- m_resolution(res),
- m_mode(mode),
- m_angle(angle),
- m_resbuffer(resbuf),
- m_tilt(tilt),
- m_canvas(canvas),
- m_rasterizer(rasterizer),
- m_engine(engine)
-{
- warp.usemesh = false;
- fboSupported = false;
-
- if (mode >= DOME_NUM_MODES)
- m_mode = DOME_FISHEYE;
-
- if (warptext) // it there is a text data try to warp it
- {
- char *buf;
- buf = txt_to_buf(warptext);
- if (buf)
- {
- warp.usemesh = ParseWarpMesh(STR_String(buf));
- MEM_freeN(buf);
- }
- }
-
- //setting the viewport size
- const int *viewport = m_canvas->GetViewPort();
-
- SetViewPort(viewport);
-
- switch (m_mode) {
- case DOME_FISHEYE:
- if (m_angle <= 180) {
- cubetop.resize(1);
- cubebottom.resize(1);
- cubeleft.resize(2);
- cuberight.resize(2);
-
- CreateMeshDome180();
- m_numfaces = 4;
- }
- else if (m_angle > 180) {
- cubetop.resize(2);
- cubebottom.resize(2);
- cubeleft.resize(2);
- cubefront.resize(2);
- cuberight.resize(2);
-
- CreateMeshDome250();
- m_numfaces = 5;
- } break;
- case DOME_ENVMAP:
- m_angle = 360;
- m_numfaces = 6;
- break;
- case DOME_PANORAM_SPH:
- cubeleft.resize(2);
- cubeleftback.resize(2);
- cuberight.resize(2);
- cuberightback.resize(2);
- cubetop.resize(2);
- cubebottom.resize(2);
-
- m_angle = 360;
- CreateMeshPanorama();
- m_numfaces = 6;
- break;
- default: //DOME_TRUNCATED_FRONT and DOME_TRUNCATED_REAR
- if (m_angle <= 180) {
- cubetop.resize(1);
- cubebottom.resize(1);
- cubeleft.resize(2);
- cuberight.resize(2);
-
- CreateMeshDome180();
- m_numfaces = 4;
- }
- else if (m_angle > 180) {
- cubetop.resize(2);
- cubebottom.resize(2);
- cubeleft.resize(2);
- cubefront.resize(2);
- cuberight.resize(2);
-
- CreateMeshDome250();
- m_numfaces = 5;
- } break;
- }
-
- m_numimages =(warp.usemesh?m_numfaces+1:m_numfaces);
-
- CalculateCameraOrientation();
-
- CreateGLImages();
-
- if (warp.usemesh)
- fboSupported = CreateFBO();
-
- dlistSupported = CreateDL();
-}
-
-// destructor
-KX_Dome::~KX_Dome (void)
-{
- ClearGLImages();
-
- if (fboSupported)
- glDeleteFramebuffersEXT(1, &warp.fboId);
-
- if (dlistSupported)
- glDeleteLists(dlistId, (GLsizei) m_numimages);
-}
-
-void KX_Dome::SetViewPort(const int viewport[4])
-{
- if (canvaswidth != m_viewport.GetWidth() || canvasheight != m_viewport.GetHeight())
- {
- m_viewport.SetLeft(viewport[0]);
- m_viewport.SetBottom(viewport[1]);
- m_viewport.SetRight(viewport[2]);
- m_viewport.SetTop(viewport[3]);
-
- CalculateImageSize();
- }
-}
-
-void KX_Dome::CreateGLImages(void)
-{
- glGenTextures(m_numimages, (GLuint*)&domefacesId);
-
- for (int j=0;j<m_numfaces;j++) {
- glBindTexture(GL_TEXTURE_2D, domefacesId[j]);
- glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8, m_imagesize, m_imagesize, 0, GL_RGB8,
- GL_UNSIGNED_BYTE, NULL);
- glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, 0, 0, m_imagesize, m_imagesize, 0);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
- }
- if (warp.usemesh) {
- glBindTexture(GL_TEXTURE_2D, domefacesId[m_numfaces]);
- glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8, warp.imagesize, warp.imagesize, 0, GL_RGB8,
- GL_UNSIGNED_BYTE, NULL);
- glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, 0, 0, warp.imagesize, warp.imagesize, 0);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
- }
-}
-
-void KX_Dome::ClearGLImages(void)
-{
- glDeleteTextures(m_numimages, (GLuint*)&domefacesId);
-#if 0
- for (int i=0;i<m_numimages;i++)
- if (glIsTexture(domefacesId[i]))
- glDeleteTextures(1, (GLuint*)&domefacesId[i]);
-#endif
-}
-
-void KX_Dome::CalculateImageSize(void)
-{
- /*
- * - determine the minimum buffer size
- * - reduce the buffer for better performance
- * - create a power of 2 texture bigger than the buffer
- */
- canvaswidth = m_canvas->GetWidth();
- canvasheight = m_canvas->GetHeight();
-
- m_buffersize = (canvaswidth > canvasheight?canvasheight:canvaswidth);
- m_buffersize = (int)(m_buffersize*m_resbuffer); //reduce buffer size for better performance
-
- int i = 0;
- while ((1 << i) <= m_buffersize)
- i++;
- m_imagesize = (1 << i);
-
- if (warp.usemesh) {
- // warp FBO needs to be up to twice as big as m_buffersize to get more resolution
- warp.imagesize = m_imagesize;
- if (m_buffersize == m_imagesize)
- warp.imagesize *= 2;
-
- //if FBO is not working/supported, we use the canvas dimension as buffer
- warp.bufferwidth = canvaswidth;
- warp.bufferheight = canvasheight;
- }
-}
-
-bool KX_Dome::CreateDL()
-{
- dlistId = glGenLists((GLsizei) m_numimages);
- if (dlistId != 0) {
- if (m_mode == DOME_FISHEYE || m_mode == DOME_TRUNCATED_FRONT || m_mode == DOME_TRUNCATED_REAR) {
- glNewList(dlistId, GL_COMPILE);
- GLDrawTriangles(cubetop, nfacestop);
- glEndList();
-
- glNewList(dlistId+1, GL_COMPILE);
- GLDrawTriangles(cubebottom, nfacesbottom);
- glEndList();
-
- glNewList(dlistId+2, GL_COMPILE);
- GLDrawTriangles(cubeleft, nfacesleft);
- glEndList();
-
- glNewList(dlistId+3, GL_COMPILE);
- GLDrawTriangles(cuberight, nfacesright);
- glEndList();
-
- if (m_angle > 180) {
- glNewList(dlistId+4, GL_COMPILE);
- GLDrawTriangles(cubefront, nfacesfront);
- glEndList();
- }
- }
- else if (m_mode == DOME_PANORAM_SPH)
- {
- glNewList(dlistId, GL_COMPILE);
- GLDrawTriangles(cubetop, nfacestop);
- glEndList();
-
- glNewList(dlistId+1, GL_COMPILE);
- GLDrawTriangles(cubebottom, nfacesbottom);
- glEndList();
-
- glNewList(dlistId+2, GL_COMPILE);
- GLDrawTriangles(cubeleft, nfacesleft);
- glEndList();
-
- glNewList(dlistId+3, GL_COMPILE);
- GLDrawTriangles(cuberight, nfacesright);
- glEndList();
-
- glNewList(dlistId+4, GL_COMPILE);
- GLDrawTriangles(cubeleftback, nfacesleftback);
- glEndList();
-
- glNewList(dlistId+5, GL_COMPILE);
- GLDrawTriangles(cuberightback, nfacesrightback);
- glEndList();
- }
-
- if (warp.usemesh) {
- glNewList((dlistId + m_numfaces), GL_COMPILE);
- GLDrawWarpQuads();
- glEndList();
- }
-
- //clearing the vectors
- cubetop.clear();
- cubebottom.clear();
- cuberight.clear();
- cubeleft.clear();
- cubefront.clear();
- cubeleftback.clear();
- cuberightback.clear();
- warp.nodes.clear();
-
- } else // genList failed
- return false;
-
- return true;
-}
-
-bool KX_Dome::CreateFBO(void)
-{
- if (!GLEW_EXT_framebuffer_object)
- {
- printf("Dome Error: FrameBuffer unsupported. Using low resolution warp image.");
- return false;
- }
-
- glGenFramebuffersEXT(1, &warp.fboId);
- if (warp.fboId==0)
- {
- printf("Dome Error: Invalid frame buffer object. Using low resolution warp image.");
- return false;
- }
-
- glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, warp.fboId);
-
- glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT,
- GL_TEXTURE_2D, domefacesId[m_numfaces], 0);
-
- GLenum status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
-
- if (status == GL_FRAMEBUFFER_UNSUPPORTED_EXT)
- {
- printf("Dome Error: FrameBuffer settings unsupported. Using low resolution warp image.");
- return false;
- }
- else if (status != GL_FRAMEBUFFER_COMPLETE_EXT)
- {
- glDeleteFramebuffersEXT(1, &warp.fboId);
- return false;
- }
-
- glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
-
- //nothing failed: we can use the whole FBO as buffersize
- warp.bufferwidth = warp.bufferheight = warp.imagesize;
- return true;
-}
-
-void KX_Dome::GLDrawTriangles(vector <DomeFace>& face, int nfaces)
-{
- int i,j;
- glBegin(GL_TRIANGLES);
- for (i=0;i<nfaces;i++) {
- for (j=0;j<3;j++) {
- glTexCoord2f(face[i].u[j],face[i].v[j]);
- glVertex3f((GLfloat)face[i].verts[j][0],(GLfloat)face[i].verts[j][1],(GLfloat)face[i].verts[j][2]);
- }
- }
- glEnd();
-}
-
-void KX_Dome::GLDrawWarpQuads(void)
-{
- int i, j, i2;
-
- float uv_width = (float)(warp.bufferwidth) / warp.imagesize;
- float uv_height = (float)(warp.bufferheight) / warp.imagesize;
-
- if (warp.mode ==2 ) {
- glBegin(GL_QUADS);
- for (i=0;i<warp.n_height-1;i++) {
- for (j=0;j<warp.n_width-1;j++) {
- if (warp.nodes[i][j].i < 0 || warp.nodes[i+1][j].i < 0 || warp.nodes[i+1][j+1].i < 0 || warp.nodes[i][j+1].i < 0)
- continue;
-
- glColor3f(warp.nodes[i][j+1].i, warp.nodes[i][j+1].i, warp.nodes[i][j+1].i);
- glTexCoord2f((warp.nodes[i][j+1].u * uv_width), (warp.nodes[i][j+1].v * uv_height));
- glVertex3f(warp.nodes[i][j+1].x, warp.nodes[i][j+1].y,0.0f);
-
- glColor3f(warp.nodes[i+1][j+1].i, warp.nodes[i+1][j+1].i, warp.nodes[i+1][j+1].i);
- glTexCoord2f((warp.nodes[i+1][j+1].u * uv_width), (warp.nodes[i+1][j+1].v * uv_height));
- glVertex3f(warp.nodes[i+1][j+1].x, warp.nodes[i+1][j+1].y,0.0f);
-
- glColor3f(warp.nodes[i+1][j].i, warp.nodes[i+1][j].i, warp.nodes[i+1][j].i);
- glTexCoord2f((warp.nodes[i+1][j].u * uv_width), (warp.nodes[i+1][j].v * uv_height));
- glVertex3f(warp.nodes[i+1][j].x, warp.nodes[i+1][j].y,0.0f);
-
- glColor3f(warp.nodes[i][j].i, warp.nodes[i][j].i, warp.nodes[i][j].i);
- glTexCoord2f((warp.nodes[i][j].u * uv_width), (warp.nodes[i][j].v * uv_height));
- glVertex3f(warp.nodes[i][j].x, warp.nodes[i][j].y,0.0f);
- }
- }
- glEnd();
- }
- else if (warp.mode == 1) {
- glBegin(GL_QUADS);
- for (i=0;i<warp.n_height-1;i++) {
- for (j=0;j<warp.n_width-1;j++) {
- i2 = (i+1) % warp.n_width; // Wrap around, i = warp.n_width = 0
-
- if (warp.nodes[i][j].i < 0 || warp.nodes[i2][j].i < 0 || warp.nodes[i2][j+1].i < 0 || warp.nodes[i][j+1].i < 0)
- continue;
-
- glColor3f(warp.nodes[i][j].i,warp.nodes[i][j].i,warp.nodes[i][j].i);
- glTexCoord2f((warp.nodes[i][j].u * uv_width), (warp.nodes[i][j].v * uv_height));
- glVertex3f(warp.nodes[i][j].x,warp.nodes[i][j].y,0.0f);
-
- glColor3f(warp.nodes[i2][j].i,warp.nodes[i2][j].i,warp.nodes[i2][j].i);
- glTexCoord2f((warp.nodes[i2][j].u * uv_width), (warp.nodes[i2][j].v * uv_height));
- glVertex3f(warp.nodes[i2][j].x,warp.nodes[i2][j].y,0.0f);
-
- glColor3f(warp.nodes[i2][j+1].i,warp.nodes[i2][j+1].i,warp.nodes[i2][j+1].i);
- glTexCoord2f((warp.nodes[i2][j+1].u * uv_width), (warp.nodes[i2][j+1].v * uv_height));
- glVertex3f(warp.nodes[i2][j+1].x,warp.nodes[i2][j+1].y,0.0f);
-
- glColor3f(warp.nodes[i2][j+1].i,warp.nodes[i2][j+1].i,warp.nodes[i2][j+1].i);
- glTexCoord2f((warp.nodes[i2][j+1].u * uv_width), (warp.nodes[i2][j+1].v * uv_height));
- glVertex3f(warp.nodes[i2][j+1].x,warp.nodes[i2][j+1].y,0.0f);
-
- }
- }
- glEnd();
- }
- else {
- printf("Dome Error: Warp Mode %d unsupported. Try 1 for Polar Mesh or 2 for Fisheye.\n", warp.mode);
- }
-}
-
-
-bool KX_Dome::ParseWarpMesh(STR_String text)
-{
- /*
- * //Notes about the supported data format:
- * File example::
- * mode
- * width height
- * n0_x n0_y n0_u n0_v n0_i
- * n1_x n1_y n1_u n1_v n1_i
- * n2_x n1_y n2_u n2_v n2_i
- * n3_x n3_y n3_u n3_v n3_i
- * (...)
- * First line is the image type the mesh is support to be applied to: 2 = fisheye, 1=radial
- * The next line has the mesh dimensions
- * Rest of the lines are the nodes of the mesh. Each line has x y u v i
- * (x,y) are the normalized screen coordinates
- * (u,v) texture coordinates
- * i a multiplicative intensity factor
- *
- * x varies from -screen aspect to screen aspect
- * y varies from -1 to 1
- * u and v vary from 0 to 1
- * i ranges from 0 to 1, if negative don't draw that mesh node
- */
- int i;
- int nodeX=0, nodeY=0;
-
- vector<STR_String> columns, lines;
-
- lines = text.Explode('\n');
- if (lines.size() < 6) {
- printf("Dome Error: Warp Mesh File with insufficient data!\n");
- return false;
- }
- columns = lines[1].Explode(' ');
- if (columns.size() == 1)
- columns = lines[1].Explode('\t');
-
- if (columns.size() !=2) {
- printf("Dome Error: Warp Mesh File incorrect. The second line should contain: width height.\n");
- return false;
- }
-
- warp.mode = atoi(lines[0]);// 1 = radial, 2 = fisheye
-
- warp.n_width = atoi(columns[0]);
- warp.n_height = atoi(columns[1]);
-
- if ((int)lines.size() < 2 + (warp.n_width * warp.n_height)) {
- printf("Dome Error: Warp Mesh File with insufficient data!\n");
- return false;
- }
- else {
- warp.nodes = vector<vector<WarpMeshNode> > (warp.n_height, vector<WarpMeshNode>(warp.n_width));
-
- for (i=2; i-2 < (warp.n_width*warp.n_height); i++) {
- columns = lines[i].Explode(' ');
- if (columns.size() == 1)
- columns = lines[i].Explode('\t');
-
- if (columns.size() == 5) {
- nodeX = (i-2)%warp.n_width;
- nodeY = ((i-2) - nodeX) / warp.n_width;
-
- warp.nodes[nodeY][nodeX].x = atof(columns[0]);
- warp.nodes[nodeY][nodeX].y = atof(columns[1]);
- warp.nodes[nodeY][nodeX].u = atof(columns[2]);
- warp.nodes[nodeY][nodeX].v = atof(columns[3]);
- warp.nodes[nodeY][nodeX].i = atof(columns[4]);
- }
- else {
- warp.nodes.clear();
- printf("Dome Error: Warp Mesh File with wrong number of fields. You should use 5: x y u v i.\n");
- return false;
- }
- }
- }
- return true;
-}
-
-void KX_Dome::CreateMeshDome180(void)
-{
- /*
- * 1)- Define the faces of half of a cube
- * - each face is made out of 2 triangles
- * 2) Subdivide the faces
- * - more resolution == more curved lines
- * 3) Spherize the cube
- * - normalize the verts
- * 4) Flatten onto xz plane
- * - transform it onto an equidistant spherical projection techniques to transform the sphere onto a dome image
- */
- int i,j;
- float uv_ratio = (float)(m_buffersize-1) / m_imagesize;
-
- m_radangle = DEG2RADF(m_angle); //calculates the radians angle, used for flattening
-
- //creating faces for the env mapcube 180deg Dome
- // Top Face - just a triangle
- cubetop[0].verts[0][0] = (float)(-M_SQRT2) / 2.0f;
- cubetop[0].verts[0][1] = 0.0f;
- cubetop[0].verts[0][2] = 0.5f;
- cubetop[0].u[0] = 0.0;
- cubetop[0].v[0] = uv_ratio;
-
- cubetop[0].verts[1][0] = 0.0f;
- cubetop[0].verts[1][1] = (float)M_SQRT2 / 2.0f;
- cubetop[0].verts[1][2] = 0.5f;
- cubetop[0].u[1] = 0.0;
- cubetop[0].v[1] = 0.0;
-
- cubetop[0].verts[2][0] = (float)M_SQRT2 / 2.0f;
- cubetop[0].verts[2][1] = 0.0f;
- cubetop[0].verts[2][2] = 0.5f;
- cubetop[0].u[2] = uv_ratio;
- cubetop[0].v[2] = 0.0;
-
- nfacestop = 1;
-
- /* Bottom face - just a triangle */
- cubebottom[0].verts[0][0] = (float)(-M_SQRT2) / 2.0f;
- cubebottom[0].verts[0][1] = 0.0f;
- cubebottom[0].verts[0][2] = -0.5f;
- cubebottom[0].u[0] = uv_ratio;
- cubebottom[0].v[0] = 0.0;
-
- cubebottom[0].verts[1][0] = (float)M_SQRT2 / 2.0f;
- cubebottom[0].verts[1][1] = 0;
- cubebottom[0].verts[1][2] = -0.5f;
- cubebottom[0].u[1] = 0.0;
- cubebottom[0].v[1] = uv_ratio;
-
- cubebottom[0].verts[2][0] = 0.0f;
- cubebottom[0].verts[2][1] = (float)M_SQRT2 / 2.0f;
- cubebottom[0].verts[2][2] = -0.5f;
- cubebottom[0].u[2] = 0.0;
- cubebottom[0].v[2] = 0.0;
-
- nfacesbottom = 1;
-
- /* Left face - two triangles */
-
- cubeleft[0].verts[0][0] = (float)(-M_SQRT2) / 2.0f;
- cubeleft[0].verts[0][1] = 0.0f;
- cubeleft[0].verts[0][2] = -0.5f;
- cubeleft[0].u[0] = 0.0;
- cubeleft[0].v[0] = 0.0;
-
- cubeleft[0].verts[1][0] = 0.0f;
- cubeleft[0].verts[1][1] = (float)M_SQRT2 / 2.0f;
- cubeleft[0].verts[1][2] = -0.5f;
- cubeleft[0].u[1] = uv_ratio;
- cubeleft[0].v[1] = 0.0;
-
- cubeleft[0].verts[2][0] = (float)(-M_SQRT2) / 2.0f;
- cubeleft[0].verts[2][1] = 0.0f;
- cubeleft[0].verts[2][2] = 0.5f;
- cubeleft[0].u[2] = 0.0;
- cubeleft[0].v[2] = uv_ratio;
-
- //second triangle
- cubeleft[1].verts[0][0] = (float)(-M_SQRT2) / 2.0f;
- cubeleft[1].verts[0][1] = 0.0f;
- cubeleft[1].verts[0][2] = 0.5f;
- cubeleft[1].u[0] = 0.0;
- cubeleft[1].v[0] = uv_ratio;
-
- cubeleft[1].verts[1][0] = 0.0f;
- cubeleft[1].verts[1][1] = (float)M_SQRT2 / 2.0f;
- cubeleft[1].verts[1][2] = -0.5f;
- cubeleft[1].u[1] = uv_ratio;
- cubeleft[1].v[1] = 0.0;
-
- cubeleft[1].verts[2][0] = 0.0f;
- cubeleft[1].verts[2][1] = (float)M_SQRT2 / 2.0f;
- cubeleft[1].verts[2][2] = 0.5f;
- cubeleft[1].u[2] = uv_ratio;
- cubeleft[1].v[2] = uv_ratio;
-
- nfacesleft = 2;
-
- /* Right face - two triangles */
- cuberight[0].verts[0][0] = 0.0f;
- cuberight[0].verts[0][1] = (float)M_SQRT2 / 2.0f;
- cuberight[0].verts[0][2] = -0.5f;
- cuberight[0].u[0] = 0.0;
- cuberight[0].v[0] = 0.0;
-
- cuberight[0].verts[1][0] = (float)M_SQRT2 / 2.0f;
- cuberight[0].verts[1][1] = 0.0f;
- cuberight[0].verts[1][2] = -0.5f;
- cuberight[0].u[1] = uv_ratio;
- cuberight[0].v[1] = 0.0;
-
- cuberight[0].verts[2][0] = (float)M_SQRT2 / 2.0f;
- cuberight[0].verts[2][1] = 0.0f;
- cuberight[0].verts[2][2] = 0.5f;
- cuberight[0].u[2] = uv_ratio;
- cuberight[0].v[2] = uv_ratio;
-
- //second triangle
- cuberight[1].verts[0][0] = 0.0f;
- cuberight[1].verts[0][1] = (float)M_SQRT2 / 2.0f;
- cuberight[1].verts[0][2] = -0.5f;
- cuberight[1].u[0] = 0.0;
- cuberight[1].v[0] = 0.0;
-
- cuberight[1].verts[1][0] = (float)M_SQRT2 / 2.0f;
- cuberight[1].verts[1][1] = 0.0f;
- cuberight[1].verts[1][2] = 0.5f;
- cuberight[1].u[1] = uv_ratio;
- cuberight[1].v[1] = uv_ratio;
-
- cuberight[1].verts[2][0] = 0.0f;
- cuberight[1].verts[2][1] = (float)M_SQRT2 / 2.0f;
- cuberight[1].verts[2][2] = 0.5f;
- cuberight[1].u[2] = 0.0;
- cuberight[1].v[2] = uv_ratio;
-
- nfacesright = 2;
-
- //Refine a triangular mesh by bisecting each edge forms 3 new triangles for each existing triangle on each iteration
- //Could be made more efficient for drawing if the triangles were ordered in a fan. Not that important since we are using DisplayLists
-
- for (i=0;i<m_resolution;i++) {
- cubetop.resize(4*nfacestop);
- SplitFace(cubetop,&nfacestop);
- cubebottom.resize(4*nfacesbottom);
- SplitFace(cubebottom,&nfacesbottom);
- cubeleft.resize(4*nfacesleft);
- SplitFace(cubeleft,&nfacesleft);
- cuberight.resize(4*nfacesright);
- SplitFace(cuberight,&nfacesright);
- }
-
- // Turn into a hemisphere
- for (j=0;j<3;j++) {
- for (i=0;i<nfacestop;i++)
- cubetop[i].verts[j].normalize();
- for (i=0;i<nfacesbottom;i++)
- cubebottom[i].verts[j].normalize();
- for (i=0;i<nfacesleft;i++)
- cubeleft[i].verts[j].normalize();
- for (i=0;i<nfacesright;i++)
- cuberight[i].verts[j].normalize();
- }
-
- //flatten onto xz plane
- for (i=0;i<nfacestop;i++)
- FlattenDome(cubetop[i].verts);
- for (i=0;i<nfacesbottom;i++)
- FlattenDome(cubebottom[i].verts);
- for (i=0;i<nfacesleft;i++)
- FlattenDome(cubeleft[i].verts);
- for (i=0;i<nfacesright;i++)
- FlattenDome(cuberight[i].verts);
-
-}
-
-void KX_Dome::CreateMeshDome250(void)
-{
- /*
- * 1)- Define the faces of a cube without the back face
- * - each face is made out of 2 triangles
- * 2) Subdivide the faces
- * - more resolution == more curved lines
- * 3) Spherize the cube
- * - normalize the verts
- * 4) Flatten onto xz plane
- * - transform it onto an equidistant spherical projection techniques to transform the sphere onto a dome image
- */
-
- int i,j;
- float uv_height, uv_base;
- float verts_height;
-
- float rad_ang = m_angle * MT_PI / 180.0f;
- float uv_ratio = (float)(m_buffersize-1) / m_imagesize;
-
- m_radangle = m_angle * (float)M_PI/180.0f;//calculates the radians angle, used for flattening
- /*
- * verts_height is the exactly needed height of the cube faces (not always 1.0).
- * When we want some horizontal information (e.g. for horizontal 220deg domes) we don't need to create and tessellate the whole cube.
- * Therefore the lateral cube faces could be small, and the tessellate mesh would be completely used.
- * (if we always worked with verts_height = 1.0, we would be discarding a lot of the calculated and tessellated geometry).
- *
- * So I came out with this formula:
- * verts_height = tan((rad_ang/2) - (MT_PI/2))*sqrt(2.0);
- *
- * Here we take half the sphere(rad_ang/2) and subtract a quarter of it (MT_PI/2)
- * Therefore we have the length in radians of the dome/sphere over the horizon.
- * Once we take the tangent of that angle, you have the verts coordinate corresponding to the verts on the side faces.
- * Then we need to multiply it by sqrt(2.0) to get the coordinate of the verts on the diagonal of the original cube.
- */
- verts_height = tanf((rad_ang / 2.0f) - (MT_PI / 2.0f)) * (float)M_SQRT2;
-
- uv_height = uv_ratio * ( (verts_height / 2.0f) + 0.5f);
- uv_base = uv_ratio * (1.0f - ((verts_height / 2.0f) + 0.5f));
-
- //creating faces for the env mapcube 180deg Dome
- // Front Face - 2 triangles
- cubefront[0].verts[0][0] =-1.0f;
- cubefront[0].verts[0][1] = 1.0f;
- cubefront[0].verts[0][2] =-1.0f;
- cubefront[0].u[0] = 0.0;
- cubefront[0].v[0] = 0.0;
-
- cubefront[0].verts[1][0] = 1.0f;
- cubefront[0].verts[1][1] = 1.0f;
- cubefront[0].verts[1][2] = 1.0f;
- cubefront[0].u[1] = uv_ratio;
- cubefront[0].v[1] = uv_ratio;
-
- cubefront[0].verts[2][0] =-1.0f;
- cubefront[0].verts[2][1] = 1.0f;
- cubefront[0].verts[2][2] = 1.0f;
- cubefront[0].u[2] = 0.0;
- cubefront[0].v[2] = uv_ratio;
-
- //second triangle
- cubefront[1].verts[0][0] = 1.0f;
- cubefront[1].verts[0][1] = 1.0f;
- cubefront[1].verts[0][2] = 1.0f;
- cubefront[1].u[0] = uv_ratio;
- cubefront[1].v[0] = uv_ratio;
-
- cubefront[1].verts[1][0] =-1.0f;
- cubefront[1].verts[1][1] = 1.0f;
- cubefront[1].verts[1][2] =-1.0f;
- cubefront[1].u[1] = 0.0;
- cubefront[1].v[1] = 0.0;
-
- cubefront[1].verts[2][0] = 1.0f;
- cubefront[1].verts[2][1] = 1.0f;
- cubefront[1].verts[2][2] =-1.0f;
- cubefront[1].u[2] = uv_ratio;
- cubefront[1].v[2] = 0.0;
-
- nfacesfront = 2;
-
- // Left Face - 2 triangles
- cubeleft[0].verts[0][0] =-1.0f;
- cubeleft[0].verts[0][1] = 1.0f;
- cubeleft[0].verts[0][2] =-1.0f;
- cubeleft[0].u[0] = uv_ratio;
- cubeleft[0].v[0] = 0.0;
-
- cubeleft[0].verts[1][0] =-1.0f;
- cubeleft[0].verts[1][1] =-verts_height;
- cubeleft[0].verts[1][2] = 1.0f;
- cubeleft[0].u[1] = uv_base;
- cubeleft[0].v[1] = uv_ratio;
-
- cubeleft[0].verts[2][0] =-1.0f;
- cubeleft[0].verts[2][1] =-verts_height;
- cubeleft[0].verts[2][2] =-1.0f;
- cubeleft[0].u[2] = uv_base;
- cubeleft[0].v[2] = 0.0;
-
- //second triangle
- cubeleft[1].verts[0][0] =-1.0f;
- cubeleft[1].verts[0][1] =-verts_height;
- cubeleft[1].verts[0][2] = 1.0f;
- cubeleft[1].u[0] = uv_base;
- cubeleft[1].v[0] = uv_ratio;
-
- cubeleft[1].verts[1][0] =-1.0f;
- cubeleft[1].verts[1][1] = 1.0f;
- cubeleft[1].verts[1][2] =-1.0f;
- cubeleft[1].u[1] = uv_ratio;
- cubeleft[1].v[1] = 0.0;
-
- cubeleft[1].verts[2][0] =-1.0f;
- cubeleft[1].verts[2][1] = 1.0f;
- cubeleft[1].verts[2][2] = 1.0f;
- cubeleft[1].u[2] = uv_ratio;
- cubeleft[1].v[2] = uv_ratio;
-
- nfacesleft = 2;
-
- // right Face - 2 triangles
- cuberight[0].verts[0][0] = 1.0f;
- cuberight[0].verts[0][1] = 1.0f;
- cuberight[0].verts[0][2] = 1.0f;
- cuberight[0].u[0] = 0.0;
- cuberight[0].v[0] = uv_ratio;
-
- cuberight[0].verts[1][0] = 1.0f;
- cuberight[0].verts[1][1] =-verts_height;
- cuberight[0].verts[1][2] =-1.0f;
- cuberight[0].u[1] = uv_height;
- cuberight[0].v[1] = 0.0;
-
- cuberight[0].verts[2][0] = 1.0f;
- cuberight[0].verts[2][1] =-verts_height;
- cuberight[0].verts[2][2] = 1.0f;
- cuberight[0].u[2] = uv_height;
- cuberight[0].v[2] = uv_ratio;
-
- //second triangle
- cuberight[1].verts[0][0] = 1.0f;
- cuberight[1].verts[0][1] =-verts_height;
- cuberight[1].verts[0][2] =-1.0f;
- cuberight[1].u[0] = uv_height;
- cuberight[1].v[0] = 0.0;
-
- cuberight[1].verts[1][0] = 1.0f;
- cuberight[1].verts[1][1] = 1.0f;
- cuberight[1].verts[1][2] = 1.0f;
- cuberight[1].u[1] = 0.0;
- cuberight[1].v[1] = uv_ratio;
-
- cuberight[1].verts[2][0] = 1.0f;
- cuberight[1].verts[2][1] = 1.0f;
- cuberight[1].verts[2][2] =-1.0f;
- cuberight[1].u[2] = 0.0;
- cuberight[1].v[2] = 0.0;
-
- nfacesright = 2;
-
- // top Face - 2 triangles
- cubetop[0].verts[0][0] =-1.0f;
- cubetop[0].verts[0][1] = 1.0f;
- cubetop[0].verts[0][2] = 1.0f;
- cubetop[0].u[0] = 0.0;
- cubetop[0].v[0] = 0.0;
-
- cubetop[0].verts[1][0] = 1.0f;
- cubetop[0].verts[1][1] =-verts_height;
- cubetop[0].verts[1][2] = 1.0f;
- cubetop[0].u[1] = uv_ratio;
- cubetop[0].v[1] = uv_height;
-
- cubetop[0].verts[2][0] =-1.0f;
- cubetop[0].verts[2][1] =-verts_height;
- cubetop[0].verts[2][2] = 1.0f;
- cubetop[0].u[2] = 0.0;
- cubetop[0].v[2] = uv_height;
-
- //second triangle
- cubetop[1].verts[0][0] = 1.0f;
- cubetop[1].verts[0][1] =-verts_height;
- cubetop[1].verts[0][2] = 1.0f;
- cubetop[1].u[0] = uv_ratio;
- cubetop[1].v[0] = uv_height;
-
- cubetop[1].verts[1][0] =-1.0f;
- cubetop[1].verts[1][1] = 1.0f;
- cubetop[1].verts[1][2] = 1.0f;
- cubetop[1].u[1] = 0.0;
- cubetop[1].v[1] = 0.0;
-
- cubetop[1].verts[2][0] = 1.0f;
- cubetop[1].verts[2][1] = 1.0f;
- cubetop[1].verts[2][2] = 1.0f;
- cubetop[1].u[2] = uv_ratio;
- cubetop[1].v[2] = 0.0;
-
- nfacestop = 2;
-
- // bottom Face - 2 triangles
- cubebottom[0].verts[0][0] =-1.0f;
- cubebottom[0].verts[0][1] =-verts_height;
- cubebottom[0].verts[0][2] =-1.0f;
- cubebottom[0].u[0] = 0.0;
- cubebottom[0].v[0] = uv_base;
-
- cubebottom[0].verts[1][0] = 1.0f;
- cubebottom[0].verts[1][1] = 1.0f;
- cubebottom[0].verts[1][2] =-1.0f;
- cubebottom[0].u[1] = uv_ratio;
- cubebottom[0].v[1] = uv_ratio;
-
- cubebottom[0].verts[2][0] =-1.0f;
- cubebottom[0].verts[2][1] = 1.0f;
- cubebottom[0].verts[2][2] =-1.0f;
- cubebottom[0].u[2] = 0.0;
- cubebottom[0].v[2] = uv_ratio;
-
- //second triangle
- cubebottom[1].verts[0][0] = 1.0f;
- cubebottom[1].verts[0][1] = 1.0f;
- cubebottom[1].verts[0][2] =-1.0f;
- cubebottom[1].u[0] = uv_ratio;
- cubebottom[1].v[0] = uv_ratio;
-
- cubebottom[1].verts[1][0] =-1.0f;
- cubebottom[1].verts[1][1] =-verts_height;
- cubebottom[1].verts[1][2] =-1.0f;
- cubebottom[1].u[1] = 0.0;
- cubebottom[1].v[1] = uv_base;
-
- cubebottom[1].verts[2][0] = 1.0f;
- cubebottom[1].verts[2][1] =-verts_height;
- cubebottom[1].verts[2][2] =-1.0f;
- cubebottom[1].u[2] = uv_ratio;
- cubebottom[1].v[2] = uv_base;
-
- nfacesbottom = 2;
-
- //Refine a triangular mesh by bisecting each edge forms 3 new triangles for each existing triangle on each iteration
- //It could be made more efficient for drawing if the triangles were ordered in a strip!
-
- for (i=0;i<m_resolution;i++) {
- cubefront.resize(4*nfacesfront);
- SplitFace(cubefront,&nfacesfront);
- cubetop.resize(4*nfacestop);
- SplitFace(cubetop,&nfacestop);
- cubebottom.resize(4*nfacesbottom);
- SplitFace(cubebottom,&nfacesbottom);
- cubeleft.resize(4*nfacesleft);
- SplitFace(cubeleft,&nfacesleft);
- cuberight.resize(4*nfacesright);
- SplitFace(cuberight,&nfacesright);
- }
-
- // Turn into a hemisphere/sphere
- for (j=0;j<3;j++) {
- for (i=0;i<nfacesfront;i++)
- cubefront[i].verts[j].normalize();
- for (i=0;i<nfacestop;i++)
- cubetop[i].verts[j].normalize();
- for (i=0;i<nfacesbottom;i++)
- cubebottom[i].verts[j].normalize();
- for (i=0;i<nfacesleft;i++)
- cubeleft[i].verts[j].normalize();
- for (i=0;i<nfacesright;i++)
- cuberight[i].verts[j].normalize();
- }
-
- //flatten onto xz plane
- for (i=0;i<nfacesfront;i++)
- FlattenDome(cubefront[i].verts);
- for (i=0;i<nfacestop;i++)
- FlattenDome(cubetop[i].verts);
- for (i=0;i<nfacesbottom;i++)
- FlattenDome(cubebottom[i].verts);
- for (i=0;i<nfacesleft;i++)
- FlattenDome(cubeleft[i].verts);
- for (i=0;i<nfacesright;i++)
- FlattenDome(cuberight[i].verts);
-}
-
-void KX_Dome::CreateMeshPanorama(void)
-{
- /*
- * 1)- Define the faces of a cube without the top and bottom faces
- * - each face is made out of 2 triangles
- * 2) Subdivide the faces
- * - more resolution == more curved lines
- * 3) Spherize the cube
- * - normalize the verts t
- * 4) Flatten onto xz plane
- * - use spherical projection techniques to transform the sphere onto a flat panorama
- */
- int i,j;
-
- float uv_ratio = (float)(m_buffersize-1) / m_imagesize;
-
- /* Top face - two triangles */
- cubetop[0].verts[0][0] = (float)(-M_SQRT2);
- cubetop[0].verts[0][1] = 0.0f;
- cubetop[0].verts[0][2] = 1.0f;
- cubetop[0].u[0] = 0.0;
- cubetop[0].v[0] = uv_ratio;
-
- cubetop[0].verts[1][0] = 0.0f;
- cubetop[0].verts[1][1] = (float)M_SQRT2;
- cubetop[0].verts[1][2] = 1.0f;
- cubetop[0].u[1] = 0.0;
- cubetop[0].v[1] = 0.0;
-
- //second triangle
- cubetop[0].verts[2][0] = (float)M_SQRT2;
- cubetop[0].verts[2][1] = 0.0f;
- cubetop[0].verts[2][2] = 1.0f;
- cubetop[0].u[2] = uv_ratio;
- cubetop[0].v[2] = 0.0;
-
- cubetop[1].verts[0][0] = (float)M_SQRT2;
- cubetop[1].verts[0][1] = 0.0f;
- cubetop[1].verts[0][2] = 1.0f;
- cubetop[1].u[0] = uv_ratio;
- cubetop[1].v[0] = 0.0;
-
- cubetop[1].verts[1][0] = 0.0f;
- cubetop[1].verts[1][1] = (float)(-M_SQRT2);
- cubetop[1].verts[1][2] = 1.0f;
- cubetop[1].u[1] = uv_ratio;
- cubetop[1].v[1] = uv_ratio;
-
- cubetop[1].verts[2][0] = (float)(-M_SQRT2);
- cubetop[1].verts[2][1] = 0.0f;
- cubetop[1].verts[2][2] = 1.0f;
- cubetop[1].u[2] = 0.0;
- cubetop[1].v[2] = uv_ratio;
-
- nfacestop = 2;
-
- /* Bottom face - two triangles */
- cubebottom[0].verts[0][0] = (float)(-M_SQRT2);
- cubebottom[0].verts[0][1] = 0.0f;
- cubebottom[0].verts[0][2] = -1.0f;
- cubebottom[0].u[0] = uv_ratio;
- cubebottom[0].v[0] = 0.0;
-
- cubebottom[0].verts[1][0] = (float)M_SQRT2;
- cubebottom[0].verts[1][1] = 0.0f;
- cubebottom[0].verts[1][2] = -1.0f;
- cubebottom[0].u[1] = 0.0;
- cubebottom[0].v[1] = uv_ratio;
-
- cubebottom[0].verts[2][0] = 0.0f;
- cubebottom[0].verts[2][1] = (float)M_SQRT2;
- cubebottom[0].verts[2][2] = -1.0f;
- cubebottom[0].u[2] = 0.0;
- cubebottom[0].v[2] = 0.0;
-
- //second triangle
- cubebottom[1].verts[0][0] = (float)M_SQRT2;
- cubebottom[1].verts[0][1] = 0.0f;
- cubebottom[1].verts[0][2] = -1.0f;
- cubebottom[1].u[0] = 0.0;
- cubebottom[1].v[0] = uv_ratio;
-
- cubebottom[1].verts[1][0] = (float)(-M_SQRT2);
- cubebottom[1].verts[1][1] = 0.0f;
- cubebottom[1].verts[1][2] = -1.0f;
- cubebottom[1].u[1] = uv_ratio;
- cubebottom[1].v[1] = 0.0;
-
- cubebottom[1].verts[2][0] = 0.0f;
- cubebottom[1].verts[2][1] = (float)(-M_SQRT2);
- cubebottom[1].verts[2][2] = -1.0f;
- cubebottom[1].u[2] = uv_ratio;
- cubebottom[1].v[2] = uv_ratio;
-
- nfacesbottom = 2;
-
- /* Left Back (135deg) face - two triangles */
-
- cubeleftback[0].verts[0][0] = 0.0f;
- cubeleftback[0].verts[0][1] = (float)(-M_SQRT2);
- cubeleftback[0].verts[0][2] = -1.0f;
- cubeleftback[0].u[0] = 0.0;
- cubeleftback[0].v[0] = 0.0;
-
- cubeleftback[0].verts[1][0] = (float)(-M_SQRT2);
- cubeleftback[0].verts[1][1] = 0.0f;
- cubeleftback[0].verts[1][2] = -1.0f;
- cubeleftback[0].u[1] = uv_ratio;
- cubeleftback[0].v[1] = 0.0;
-
- cubeleftback[0].verts[2][0] = 0.0f;
- cubeleftback[0].verts[2][1] = (float)(-M_SQRT2);
- cubeleftback[0].verts[2][2] = 1.0f;
- cubeleftback[0].u[2] = 0.0;
- cubeleftback[0].v[2] = uv_ratio;
-
- //second triangle
- cubeleftback[1].verts[0][0] = 0.0f;
- cubeleftback[1].verts[0][1] = (float)(-M_SQRT2);
- cubeleftback[1].verts[0][2] = 1.0f;
- cubeleftback[1].u[0] = 0.0;
- cubeleftback[1].v[0] = uv_ratio;
-
- cubeleftback[1].verts[1][0] = (float)(-M_SQRT2);
- cubeleftback[1].verts[1][1] = 0.0f;
- cubeleftback[1].verts[1][2] = -1.0f;
- cubeleftback[1].u[1] = uv_ratio;
- cubeleftback[1].v[1] = 0.0;
-
- cubeleftback[1].verts[2][0] = (float)(-M_SQRT2);
- cubeleftback[1].verts[2][1] = 0.0f;
- cubeleftback[1].verts[2][2] = 1.0f;
- cubeleftback[1].u[2] = uv_ratio;
- cubeleftback[1].v[2] = uv_ratio;
-
- nfacesleftback = 2;
-
- /* Left face - two triangles */
-
- cubeleft[0].verts[0][0] = (float)(-M_SQRT2);
- cubeleft[0].verts[0][1] = 0.0f;
- cubeleft[0].verts[0][2] = -1.0f;
- cubeleft[0].u[0] = 0.0;
- cubeleft[0].v[0] = 0.0;
-
- cubeleft[0].verts[1][0] = 0.0f;
- cubeleft[0].verts[1][1] = (float)M_SQRT2;
- cubeleft[0].verts[1][2] = -1.0f;
- cubeleft[0].u[1] = uv_ratio;
- cubeleft[0].v[1] = 0.0;
-
- cubeleft[0].verts[2][0] = (float)(-M_SQRT2);
- cubeleft[0].verts[2][1] = 0.0f;
- cubeleft[0].verts[2][2] = 1.0f;
- cubeleft[0].u[2] = 0.0;
- cubeleft[0].v[2] = uv_ratio;
-
- //second triangle
- cubeleft[1].verts[0][0] = (float)(-M_SQRT2);
- cubeleft[1].verts[0][1] = 0.0f;
- cubeleft[1].verts[0][2] = 1.0f;
- cubeleft[1].u[0] = 0.0;
- cubeleft[1].v[0] = uv_ratio;
-
- cubeleft[1].verts[1][0] = 0.0f;
- cubeleft[1].verts[1][1] = (float)M_SQRT2;
- cubeleft[1].verts[1][2] = -1.0f;
- cubeleft[1].u[1] = uv_ratio;
- cubeleft[1].v[1] = 0.0;
-
- cubeleft[1].verts[2][0] = 0.0f;
- cubeleft[1].verts[2][1] = (float)M_SQRT2;
- cubeleft[1].verts[2][2] = 1.0f;
- cubeleft[1].u[2] = uv_ratio;
- cubeleft[1].v[2] = uv_ratio;
-
- nfacesleft = 2;
-
- /* Right face - two triangles */
- cuberight[0].verts[0][0] = 0.0f;
- cuberight[0].verts[0][1] = (float)M_SQRT2;
- cuberight[0].verts[0][2] = -1.0f;
- cuberight[0].u[0] = 0.0;
- cuberight[0].v[0] = 0.0;
-
- cuberight[0].verts[1][0] = (float)M_SQRT2;
- cuberight[0].verts[1][1] = 0.0f;
- cuberight[0].verts[1][2] = -1.0f;
- cuberight[0].u[1] = uv_ratio;
- cuberight[0].v[1] = 0.0;
-
- cuberight[0].verts[2][0] = (float)M_SQRT2;
- cuberight[0].verts[2][1] = 0.0f;
- cuberight[0].verts[2][2] = 1.0f;
- cuberight[0].u[2] = uv_ratio;
- cuberight[0].v[2] = uv_ratio;
-
- //second triangle
- cuberight[1].verts[0][0] = 0.0f;
- cuberight[1].verts[0][1] = (float)M_SQRT2;
- cuberight[1].verts[0][2] = -1.0f;
- cuberight[1].u[0] = 0.0;
- cuberight[1].v[0] = 0.0;
-
- cuberight[1].verts[1][0] = (float)M_SQRT2;
- cuberight[1].verts[1][1] = 0.0f;
- cuberight[1].verts[1][2] = 1.0f;
- cuberight[1].u[1] = uv_ratio;
- cuberight[1].v[1] = uv_ratio;
-
- cuberight[1].verts[2][0] = 0.0f;
- cuberight[1].verts[2][1] = (float)M_SQRT2;
- cuberight[1].verts[2][2] = 1.0f;
- cuberight[1].u[2] = 0.0f;
- cuberight[1].v[2] = uv_ratio;
-
- nfacesright = 2;
-
- /* Right Back (-135deg) face - two triangles */
- cuberightback[0].verts[0][0] = (float)M_SQRT2;
- cuberightback[0].verts[0][1] = 0.0f;
- cuberightback[0].verts[0][2] = -1.0f;
- cuberightback[0].u[0] = 0.0;
- cuberightback[0].v[0] = 0.0;
-
- cuberightback[0].verts[1][0] = 0.0f;
- cuberightback[0].verts[1][1] = (float)(-M_SQRT2);
- cuberightback[0].verts[1][2] = -1.0f;
- cuberightback[0].u[1] = uv_ratio;
- cuberightback[0].v[1] = 0.0;
-
- cuberightback[0].verts[2][0] = 0.0f;
- cuberightback[0].verts[2][1] = (float)(-M_SQRT2);
- cuberightback[0].verts[2][2] = 1.0f;
- cuberightback[0].u[2] = uv_ratio;
- cuberightback[0].v[2] = uv_ratio;
-
- //second triangle
- cuberightback[1].verts[0][0] = (float)M_SQRT2;
- cuberightback[1].verts[0][1] = 0.0f;
- cuberightback[1].verts[0][2] = -1.0f;
- cuberightback[1].u[0] = 0.0;
- cuberightback[1].v[0] = 0.0;
-
- cuberightback[1].verts[1][0] = 0.0f;
- cuberightback[1].verts[1][1] = (float)(-M_SQRT2);
- cuberightback[1].verts[1][2] = 1.0f;
- cuberightback[1].u[1] = uv_ratio;
- cuberightback[1].v[1] = uv_ratio;
-
- cuberightback[1].verts[2][0] = (float)M_SQRT2;
- cuberightback[1].verts[2][1] = 0.0f;
- cuberightback[1].verts[2][2] = 1.0f;
- cuberightback[1].u[2] = 0.0;
- cuberightback[1].v[2] = uv_ratio;
-
- nfacesrightback = 2;
-
- // Subdivide the faces
- for (i=0;i<m_resolution;i++)
- {
- cubetop.resize(4*nfacestop);
- SplitFace(cubetop,&nfacestop);
-
- cubebottom.resize(4*nfacesbottom);
- SplitFace(cubebottom,&nfacesbottom);
-
- cubeleft.resize(4*nfacesleft);
- SplitFace(cubeleft,&nfacesleft);
-
- cuberight.resize(4*nfacesright);
- SplitFace(cuberight,&nfacesright);
-
- cubeleftback.resize(4*nfacesleftback);
- SplitFace(cubeleftback,&nfacesleftback);
-
- cuberightback.resize(4*nfacesrightback);
- SplitFace(cuberightback,&nfacesrightback);
- }
-
- // Spherize the cube
- for (j=0;j<3;j++)
- {
- for (i=0;i<nfacestop;i++)
- cubetop[i].verts[j].normalize();
-
- for (i=0;i<nfacesbottom;i++)
- cubebottom[i].verts[j].normalize();
-
- for (i=0;i<nfacesleftback;i++)
- cubeleftback[i].verts[j].normalize();
-
- for (i=0;i<nfacesleft;i++)
- cubeleft[i].verts[j].normalize();
-
- for (i=0;i<nfacesright;i++)
- cuberight[i].verts[j].normalize();
-
- for (i=0;i<nfacesrightback;i++)
- cuberightback[i].verts[j].normalize();
- }
-
- //Flatten onto xz plane
- for (i=0;i<nfacesleftback;i++)
- FlattenPanorama(cubeleftback[i].verts);
-
- for (i=0;i<nfacesleft;i++)
- FlattenPanorama(cubeleft[i].verts);
-
- for (i=0;i<nfacesright;i++)
- FlattenPanorama(cuberight[i].verts);
-
- for (i=0;i<nfacesrightback;i++)
- FlattenPanorama(cuberightback[i].verts);
-
- for (i=0;i<nfacestop;i++)
- FlattenPanorama(cubetop[i].verts);
-
- for (i=0;i<nfacesbottom;i++)
- FlattenPanorama(cubebottom[i].verts);
-}
-
-void KX_Dome::FlattenDome(MT_Vector3 verts[3])
-{
- double phi, r;
-
- for (int i=0;i<3;i++) {
- r = atan2(sqrt(verts[i][0]*verts[i][0] + verts[i][2]*verts[i][2]), verts[i][1]);
- r /= (double)this->m_radangle / 2.0;
-
- phi = atan2(verts[i][2], verts[i][0]);
-
- verts[i][0] = r * cos(phi);
- verts[i][1] = 0.0f;
- verts[i][2] = r * sin(phi);
-
- if (r > 1.0) {
- //round the border
- verts[i][0] = cos(phi);
- verts[i][1] = -3.0f;
- verts[i][2] = sin(phi);
- }
- }
-}
-
-void KX_Dome::FlattenPanorama(MT_Vector3 verts[3])
-{
-// it creates a full spherical panoramic (360deg)
- int i;
- double phi, theta;
- bool edge=false;
-
- for (i=0;i<3;i++) {
- phi = atan2(verts[i][1], verts[i][0]);
- phi *= -1.0; //flipping
-
- if (phi == -MT_PI) //It's on the edge
- edge=true;
-
- verts[i][0] = phi / MT_PI;
- verts[i][1] = 0.0f;
-
- theta = asin(verts[i][2]);
- verts[i][2] = theta / MT_PI;
- }
- if (edge) {
- bool right=false;
-
- for (i=0;i<3;i++) {
- if (fmodf(verts[i][0],1.0f) > 0.0f) {
- right=true;
- break;
- }
- }
- if (right) {
- for (i=0;i<3;i++) {
- if (verts[i][0] < 0.0f)
- verts[i][0] *= -1.0f;
- }
- }
- }
-}
-
-void KX_Dome::SplitFace(vector <DomeFace>& face, int *nfaces)
-{
- int i;
- int n1, n2;
-
- n1 = n2 = *nfaces;
-
- for (i=0;i<n1;i++) {
-
- face[n2].verts[0] = (face[i].verts[0] + face[i].verts[1]) /2;
- face[n2].verts[1] = face[i].verts[1];
- face[n2].verts[2] = (face[i].verts[1] + face[i].verts[2]) /2;
- face[n2].u[0] = (face[i].u[0] + face[i].u[1]) /2;
- face[n2].u[1] = face[i].u[1];
- face[n2].u[2] = (face[i].u[1] + face[i].u[2]) /2;
- face[n2].v[0] = (face[i].v[0] + face[i].v[1]) /2;
- face[n2].v[1] = face[i].v[1];
- face[n2].v[2] = (face[i].v[1] + face[i].v[2]) /2;
-
- face[n2+1].verts[0] = (face[i].verts[1] + face[i].verts[2]) /2;
- face[n2+1].verts[1] = face[i].verts[2];
- face[n2+1].verts[2] = (face[i].verts[2] + face[i].verts[0]) /2;
- face[n2+1].u[0] = (face[i].u[1] + face[i].u[2]) /2;
- face[n2+1].u[1] = face[i].u[2];
- face[n2+1].u[2] = (face[i].u[2] + face[i].u[0]) /2;
- face[n2+1].v[0] = (face[i].v[1] + face[i].v[2]) /2;
- face[n2+1].v[1] = face[i].v[2];
- face[n2+1].v[2] = (face[i].v[2] + face[i].v[0]) /2;
-
- face[n2+2].verts[0] = (face[i].verts[0] + face[i].verts[1]) /2;
- face[n2+2].verts[1] = (face[i].verts[1] + face[i].verts[2]) /2;
- face[n2+2].verts[2] = (face[i].verts[2] + face[i].verts[0]) /2;
- face[n2+2].u[0] = (face[i].u[0] + face[i].u[1]) /2;
- face[n2+2].u[1] = (face[i].u[1] + face[i].u[2]) /2;
- face[n2+2].u[2] = (face[i].u[2] + face[i].u[0]) /2;
- face[n2+2].v[0] = (face[i].v[0] + face[i].v[1]) /2;
- face[n2+2].v[1] = (face[i].v[1] + face[i].v[2]) /2;
- face[n2+2].v[2] = (face[i].v[2] + face[i].v[0]) /2;
-
- //face[i].verts[0] = face[i].verts[0];
- face[i].verts[1] = (face[i].verts[0] + face[i].verts[1]) /2;
- face[i].verts[2] = (face[i].verts[0] + face[i].verts[2]) /2;
- //face[i].u[0] = face[i].u[0];
- face[i].u[1] = (face[i].u[0] + face[i].u[1]) /2;
- face[i].u[2] = (face[i].u[0] + face[i].u[2]) /2;
- //face[i].v[0] = face[i].v[0];
- face[i].v[1] = (face[i].v[0] + face[i].v[1]) /2;
- face[i].v[2] = (face[i].v[0] + face[i].v[2]) /2;
-
- n2 += 3; // number of faces
- }
- *nfaces = n2;
-}
-
-void KX_Dome::CalculateFrustum(KX_Camera *cam)
-{
-#if 0
- // manually creating a 90deg Field of View Frustum
-
- // the original formula:
- top = tan(fov*3.14159f/30.0f)) * near [for fov in degrees]
- fov*0.5f = arctan ((top-bottom)*0.5f / near) [for fov in radians]
- bottom = -top
- left = aspect * bottom
- right = aspect * top
-
- // the equivalent GLU call is:
- glMatrixMode(GL_PROJECTION);
- glLoadIdentity();
- gluPerspective(90.0f,1.0f,cam->GetCameraNear(),cam->GetCameraFar());
-#endif
-
- RAS_FrameFrustum m_frustum; //90 deg. Frustum
-
- m_frustum.camnear = cam->GetCameraNear();
- m_frustum.camfar = cam->GetCameraFar();
-
-// float top = tan(90.0f*MT_PI/360.0f) * m_frustum.camnear;
- float top = m_frustum.camnear; // for deg = 90deg, tan = 1
-
- m_frustum.x1 = -top;
- m_frustum.x2 = top;
- m_frustum.y1 = -top;
- m_frustum.y2 = top;
-
- m_projmat = m_rasterizer->GetFrustumMatrix(
- m_frustum.x1, m_frustum.x2, m_frustum.y1, m_frustum.y2, m_frustum.camnear, m_frustum.camfar);
-}
-
-void KX_Dome::CalculateCameraOrientation()
-{
-/*
- * Uses 4 cameras for angles up to 180deg
- * Uses 5 cameras for angles up to 250deg
- * Uses 6 cameras for angles up to 360deg
- */
- int i;
- float deg45 = MT_PI / 4.0f;
- MT_Scalar c = cosf(deg45);
- MT_Scalar s = sinf(deg45);
-
- if (m_angle <= 180 && (m_mode == DOME_FISHEYE
- || m_mode == DOME_TRUNCATED_FRONT
- || m_mode == DOME_TRUNCATED_REAR)) {
-
- m_locRot[0] = MT_Matrix3x3( // 90deg - Top
- c, -s, 0.0f,
- 0.0f,0.0f, -1.0f,
- s, c, 0.0f);
-
- m_locRot[1] = MT_Matrix3x3( // 90deg - Bottom
- -s, c, 0.0f,
- 0.0f,0.0f, 1.0f,
- s, c, 0.0f);
-
- m_locRot[2] = MT_Matrix3x3( // 45deg - Left
- c, 0.0f, s,
- 0, 1.0f, 0.0f,
- -s, 0.0f, c);
-
- m_locRot[3] = MT_Matrix3x3( // 45deg - Right
- c, 0.0f, -s,
- 0.0f, 1.0f, 0.0f,
- s, 0.0f, c);
-
- } else if (m_mode == DOME_ENVMAP || (m_angle > 180 && (m_mode == DOME_FISHEYE
- || m_mode == DOME_TRUNCATED_FRONT
- || m_mode == DOME_TRUNCATED_REAR))) {
-
- m_locRot[0] = MT_Matrix3x3( // 90deg - Top
- 1.0f, 0.0f, 0.0f,
- 0.0f, 0.0f,-1.0f,
- 0.0f, 1.0f, 0.0f);
-
- m_locRot[1] = MT_Matrix3x3( // 90deg - Bottom
- 1.0f, 0.0f, 0.0f,
- 0.0f, 0.0f, 1.0f,
- 0.0f,-1.0f, 0.0f);
-
- m_locRot[2] = MT_Matrix3x3( // -90deg - Left
- 0.0f, 0.0f, 1.0f,
- 0.0f, 1.0f, 0.0f,
- -1.0f, 0.0f, 0.0f);
-
- m_locRot[3] = MT_Matrix3x3( // 90deg - Right
- 0.0f, 0.0f,-1.0f,
- 0.0f, 1.0f, 0.0f,
- 1.0f, 0.0f, 0.0f);
-
- m_locRot[4] = MT_Matrix3x3( // 0deg - Front
- 1.0f, 0.0f, 0.0f,
- 0.0f, 1.0f, 0.0f,
- 0.0f, 0.0f, 1.0f);
-
- m_locRot[5] = MT_Matrix3x3( // 180deg - Back - USED for ENVMAP only
- -1.0f, 0.0f, 0.0f,
- 0.0f, 1.0f, 0.0f,
- 0.0f, 0.0f,-1.0f);
-
- } else if (m_mode == DOME_PANORAM_SPH) {
-
- m_locRot[0] = MT_Matrix3x3( // Top
- c, s, 0.0f,
- 0.0f,0.0f, -1.0f,
- -s, c, 0.0f);
-
- m_locRot[1] = MT_Matrix3x3( // Bottom
- c, s, 0.0f,
- 0.0f, 0.0f, 1.0f,
- s, -c, 0.0f);
-
- m_locRot[2] = MT_Matrix3x3( // 45deg - Left
- -s, 0.0f, c,
- 0, 1.0f, 0.0f,
- -c, 0.0f, -s);
-
- m_locRot[3] = MT_Matrix3x3( // 45deg - Right
- c, 0.0f, s,
- 0, 1.0f, 0.0f,
- -s, 0.0f, c);
-
- m_locRot[4] = MT_Matrix3x3( // 135deg - LeftBack
- -s, 0.0f, -c,
- 0.0f, 1.0f, 0.0f,
- c, 0.0f, -s);
-
- m_locRot[5] = MT_Matrix3x3( // 135deg - RightBack
- c, 0.0f, -s,
- 0.0f, 1.0f, 0.0f,
- s, 0.0f, c);
- }
-
- // rotating the camera in horizontal axis
- if (m_tilt)
- {
- float tiltdeg = ((m_tilt % 360) * 2 * MT_PI) / 360;
- c = cosf(tiltdeg);
- s = sinf(tiltdeg);
-
- MT_Matrix3x3 tilt_mat = MT_Matrix3x3(
- 1.0f, 0.0f, 0.0f,
- 0.0f, c, -s,
- 0.0f, s, c
- );
-
- for (i =0;i<6;i++)
- m_locRot[i] = tilt_mat * m_locRot[i];
- }
-}
-
-void KX_Dome::RotateCamera(KX_Camera* cam, int i)
-{
-// I'm not using it, I'm doing inline calls for these commands
-// but it's nice to have it here in case I need it
-
- MT_Matrix3x3 camori = cam->GetSGNode()->GetLocalOrientation();
-
- cam->NodeSetLocalOrientation(camori*m_locRot[i]);
- cam->NodeUpdateGS(0.f);
-
- MT_Transform camtrans(cam->GetWorldToCamera());
- MT_Matrix4x4 viewmat(camtrans);
- m_rasterizer->SetViewMatrix(viewmat, cam->NodeGetWorldOrientation(), cam->NodeGetWorldPosition(), cam->NodeGetLocalScaling(), cam->GetCameraData()->m_perspective);
- cam->SetModelviewMatrix(viewmat);
-
- // restore the original orientation
- cam->NodeSetLocalOrientation(camori);
- cam->NodeUpdateGS(0.f);
-}
-
-void KX_Dome::Draw(void)
-{
-
- if (fboSupported) {
- glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, warp.fboId);
-
- glViewport(0,0,warp.imagesize, warp.imagesize);
- glScissor(0,0,warp.imagesize, warp.imagesize);
- }
-
- switch (m_mode) {
- case DOME_FISHEYE:
- DrawDomeFisheye();
- break;
- case DOME_ENVMAP:
- DrawEnvMap();
- break;
- case DOME_PANORAM_SPH:
- DrawPanorama();
- break;
- case DOME_TRUNCATED_FRONT:
- DrawDomeFisheye();
- break;
- case DOME_TRUNCATED_REAR:
- DrawDomeFisheye();
- break;
- }
-
- if (warp.usemesh)
- {
- if (fboSupported)
- {
- m_canvas->SetViewPort(0, 0, m_canvas->GetWidth(), m_canvas->GetHeight());
- glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
- }
- else
- {
- glBindTexture(GL_TEXTURE_2D, domefacesId[m_numfaces]);
- glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, m_viewport.GetLeft(), m_viewport.GetBottom(), warp.bufferwidth, warp.bufferheight);
- }
- DrawDomeWarped();
- }
-}
-
-void KX_Dome::DrawEnvMap(void)
-{
- glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
- glMatrixMode(GL_PROJECTION);
- glLoadIdentity();
-
- // Making the viewport always square
-
- int can_width = m_viewport.GetRight();
- int can_height = m_viewport.GetTop();
-
- float ortho_width, ortho_height;
-
- if (warp.usemesh)
- glOrtho((-1.0), 1.0, (-0.66), 0.66, 0.0, 0.0); //stretch the image to reduce resolution lost
-
- else {
- if (can_width/3 <= can_height/2) {
- ortho_width = 1.0f;
- ortho_height = (float)can_height/can_width;
- }
- else {
- ortho_height = 2.0f / 3;
- ortho_width = (float)can_width/can_height * ortho_height;
- }
-
- glOrtho((-ortho_width), ortho_width, (-ortho_height), ortho_height, -20.0f, 10.0f);
- }
-
- glMatrixMode(GL_TEXTURE);
- glLoadIdentity();
- glMatrixMode(GL_MODELVIEW);
- glLoadIdentity();
- gpuLookAt(0.0f,0.0f,1.0f, 0.0f,0.0f,0.0f, 0.0f,1.0f,0.0f);
-
- glPolygonMode(GL_FRONT, GL_FILL);
- glShadeModel(GL_SMOOTH);
- glDisable(GL_LIGHTING);
- glDisable(GL_DEPTH_TEST);
-
- glEnable(GL_TEXTURE_2D);
- glColor3f(1.0f,1.0f,1.0f);
-
- float uv_ratio = (float)(m_buffersize-1) / m_imagesize;
- double onebythree = 1.0f / 3;
-
- // domefacesId[0] => (top)
- glBindTexture(GL_TEXTURE_2D, domefacesId[0]);
- glBegin(GL_QUADS);
- glTexCoord2f(uv_ratio,uv_ratio);
- glVertex3f( onebythree, 0.0f, 3.0f);
- glTexCoord2f(0.0f,uv_ratio);
- glVertex3f(-onebythree, 0.0f, 3.0f);
- glTexCoord2f(0.0f,0.0f);
- glVertex3f(-onebythree,-2 * onebythree, 3.0f);
- glTexCoord2f(uv_ratio,0.0f);
- glVertex3f(onebythree,-2 * onebythree, 3.0f);
- glEnd();
-
- // domefacesId[1] => (bottom)
- glBindTexture(GL_TEXTURE_2D, domefacesId[1]);
- glBegin(GL_QUADS);
- glTexCoord2f(uv_ratio,uv_ratio);
- glVertex3f(-onebythree, 0.0f, 3.0f);
- glTexCoord2f(0.0f,uv_ratio);
- glVertex3f(-1.0f, 0.0f, 3.0f);
- glTexCoord2f(0.0f,0.0f);
- glVertex3f(-1.0f,-2 * onebythree, 3.0f);
- glTexCoord2f(uv_ratio,0.0f);
- glVertex3f(-onebythree,-2 * onebythree, 3.0f);
- glEnd();
-
- // domefacesId[2] => -90deg (left)
- glBindTexture(GL_TEXTURE_2D, domefacesId[2]);
- glBegin(GL_QUADS);
- glTexCoord2f(uv_ratio,uv_ratio);
- glVertex3f(-onebythree, 2 * onebythree, 3.0f);
- glTexCoord2f(0.0f,uv_ratio);
- glVertex3f(-1.0f, 2 * onebythree, 3.0f);
- glTexCoord2f(0.0f,0.0f);
- glVertex3f(-1.0f, 0.0f, 3.0f);
- glTexCoord2f(uv_ratio,0.0f);
- glVertex3f(-onebythree, 0.0f, 3.0f);
- glEnd();
-
- // domefacesId[3] => 90deg (right)
- glBindTexture(GL_TEXTURE_2D, domefacesId[3]);
- glBegin(GL_QUADS);
- glTexCoord2f(uv_ratio,uv_ratio);
- glVertex3f( 1.0f, 2 * onebythree, 3.0f);
- glTexCoord2f(0.0f,uv_ratio);
- glVertex3f( onebythree, 2 * onebythree, 3.0f);
- glTexCoord2f(0.0f,0.0f);
- glVertex3f( onebythree, 0.0f, 3.0f);
- glTexCoord2f(uv_ratio,0.0f);
- glVertex3f(1.0f, 0.0f, 3.0f);
- glEnd();
-
- // domefacesId[4] => 0deg (front)
- glBindTexture(GL_TEXTURE_2D, domefacesId[4]);
- glBegin(GL_QUADS);
- glTexCoord2f(uv_ratio,uv_ratio);
- glVertex3f( 1.0f, 0.0f, 3.0f);
- glTexCoord2f(0.0f,uv_ratio);
- glVertex3f( onebythree, 0.0f, 3.0f);
- glTexCoord2f(0.0f,0.0f);
- glVertex3f( onebythree,-2 * onebythree, 3.0f);
- glTexCoord2f(uv_ratio,0.0f);
- glVertex3f(1.0f, -2 * onebythree, 3.0f);
- glEnd();
-
- // domefacesId[5] => 180deg (back)
- glBindTexture(GL_TEXTURE_2D, domefacesId[5]);
- glBegin(GL_QUADS);
- glTexCoord2f(uv_ratio,uv_ratio);
- glVertex3f( onebythree, 2 * onebythree, 3.0f);
- glTexCoord2f(0.0f,uv_ratio);
- glVertex3f(-onebythree, 2 * onebythree, 3.0f);
- glTexCoord2f(0.0f,0.0f);
- glVertex3f(-onebythree, 0.0f, 3.0f);
- glTexCoord2f(uv_ratio,0.0f);
- glVertex3f(onebythree, 0.0f, 3.0f);
- glEnd();
-
- glDisable(GL_TEXTURE_2D);
- glEnable(GL_DEPTH_TEST);
-}
-
-void KX_Dome::DrawDomeFisheye(void)
-{
- int i;
-
- glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
- glMatrixMode(GL_PROJECTION);
- glLoadIdentity();
-
- // Making the viewport always square
-
- int can_width = m_viewport.GetRight();
- int can_height = m_viewport.GetTop();
-
- float ortho_width, ortho_height;
-
- if (m_mode == DOME_FISHEYE) {
- if (warp.usemesh)
- glOrtho((-1.0f), 1.0f, (-1.0f), 1.0f, -20.0f, 10.0f); //stretch the image to reduce resolution lost
-
- else {
- if (can_width < can_height) {
- ortho_width = 1.0f;
- ortho_height = (float)can_height/can_width;
- }
- else {
- ortho_width = (float)can_width/can_height;
- ortho_height = 1.0f;
- }
-
- glOrtho((-ortho_width), ortho_width, (-ortho_height), ortho_height, -20.0f, 10.0f);
- }
- }
- else if (m_mode == DOME_TRUNCATED_FRONT)
- {
- ortho_width = 1.0f;
- ortho_height = 2.0f * ((float)can_height / can_width) - 1.0f;
-
- glOrtho((-ortho_width), ortho_width, (-ortho_height), ortho_width, -20.0f, 10.0f);
- }
- else { //m_mode == DOME_TRUNCATED_REAR
- ortho_width = 1.0f;
- ortho_height = 2.0f * ((float)can_height / can_width) - 1.0f;
-
- glOrtho((-ortho_width), ortho_width, (-ortho_width), ortho_height, -20.0f, 10.0f);
- }
-
- glMatrixMode(GL_TEXTURE);
- glLoadIdentity();
- glMatrixMode(GL_MODELVIEW);
- glLoadIdentity();
- gpuLookAt(0.0f,-1.0f,0.0f, 0.0f,0.0f,0.0f, 0.0f,0.0f,1.0f);
-
- if (m_drawingmode == RAS_IRasterizer::KX_WIREFRAME)
- glPolygonMode(GL_FRONT, GL_LINE);
- else
- glPolygonMode(GL_FRONT, GL_FILL);
-
- glShadeModel(GL_SMOOTH);
- glDisable(GL_LIGHTING);
- glDisable(GL_DEPTH_TEST);
-
- glEnable(GL_TEXTURE_2D);
- glColor3f(1.0f,1.0f,1.0f);
-
- if (dlistSupported) {
- for (i=0;i<m_numfaces;i++) {
- glBindTexture(GL_TEXTURE_2D, domefacesId[i]);
- glCallList(dlistId+i);
- }
- }
- else { // DisplayLists not supported
- // top triangle
- glBindTexture(GL_TEXTURE_2D, domefacesId[0]);
- GLDrawTriangles(cubetop, nfacestop);
-
- // bottom triangle
- glBindTexture(GL_TEXTURE_2D, domefacesId[1]);
- GLDrawTriangles(cubebottom, nfacesbottom);
-
- // left triangle
- glBindTexture(GL_TEXTURE_2D, domefacesId[2]);
- GLDrawTriangles(cubeleft, nfacesleft);
-
- // right triangle
- glBindTexture(GL_TEXTURE_2D, domefacesId[3]);
- GLDrawTriangles(cuberight, nfacesright);
-
- if (m_angle > 180) {
- // front triangle
- glBindTexture(GL_TEXTURE_2D, domefacesId[4]);
- GLDrawTriangles(cubefront, nfacesfront);
- }
- }
- glDisable(GL_TEXTURE_2D);
- glEnable(GL_DEPTH_TEST);
-}
-
-void KX_Dome::DrawPanorama(void)
-{
- int i;
- glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
- glMatrixMode(GL_PROJECTION);
- glLoadIdentity();
-
- // Making the viewport always square
-
- int can_width = m_viewport.GetRight();
- int can_height = m_viewport.GetTop();
-
- float ortho_height = 1.0f;
- float ortho_width = 1.0f;
-
- if (warp.usemesh)
- glOrtho((-1.0f), 1.0f, (-0.5f), 0.5f, -20.0f, 10.0f); //stretch the image to reduce resolution lost
-
- else {
- //using all the screen
- if ((can_width / 2) <= (can_height)) {
- ortho_width = 1.0f;
- ortho_height = (float)can_height/can_width;
- }
- else {
- ortho_width = (float)can_width / can_height * 0.5f;
- ortho_height = 0.5f;
- }
-
- glOrtho((-ortho_width), ortho_width, (-ortho_height), ortho_height, -20.0f, 10.0f);
- }
-
- glMatrixMode(GL_TEXTURE);
- glLoadIdentity();
- glMatrixMode(GL_MODELVIEW);
- glLoadIdentity();
- gpuLookAt(0.0f,-1.0f,0.0f, 0.0f,0.0f,0.0f, 0.0f,0.0f,1.0f);
-
- if (m_drawingmode == RAS_IRasterizer::KX_WIREFRAME)
- glPolygonMode(GL_FRONT, GL_LINE);
- else
- glPolygonMode(GL_FRONT, GL_FILL);
-
- glShadeModel(GL_SMOOTH);
- glDisable(GL_LIGHTING);
- glDisable(GL_DEPTH_TEST);
-
- glEnable(GL_TEXTURE_2D);
- glColor3f(1.0f,1.0f,1.0f);
-
- if (dlistSupported) {
- for (i=0;i<m_numfaces;i++) {
- glBindTexture(GL_TEXTURE_2D, domefacesId[i]);
- glCallList(dlistId+i);
- }
- }
- else {
- // domefacesId[4] => (top)
- glBindTexture(GL_TEXTURE_2D, domefacesId[0]);
- GLDrawTriangles(cubetop, nfacestop);
-
- // domefacesId[5] => (bottom)
- glBindTexture(GL_TEXTURE_2D, domefacesId[1]);
- GLDrawTriangles(cubebottom, nfacesbottom);
-
- // domefacesId[1] => -45deg (left)
- glBindTexture(GL_TEXTURE_2D, domefacesId[2]);
- GLDrawTriangles(cubeleft, nfacesleft);
-
- // domefacesId[2] => 45deg (right)
- glBindTexture(GL_TEXTURE_2D, domefacesId[3]);
- GLDrawTriangles(cuberight, nfacesright);
-
- // domefacesId[0] => -135deg (leftback)
- glBindTexture(GL_TEXTURE_2D, domefacesId[4]);
- GLDrawTriangles(cubeleftback, nfacesleftback);
-
- // domefacesId[3] => 135deg (rightback)
- glBindTexture(GL_TEXTURE_2D, domefacesId[5]);
- GLDrawTriangles(cuberightback, nfacesrightback);
- }
- glDisable(GL_TEXTURE_2D);
- glEnable(GL_DEPTH_TEST);
-}
-
-void KX_Dome::DrawDomeWarped(void)
-{
- glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
- glMatrixMode(GL_PROJECTION);
- glLoadIdentity();
-
- // Making the viewport always square
- int can_width = m_viewport.GetRight();
- int can_height = m_viewport.GetTop();
-
- double screen_ratio = can_width/ (double) can_height;
-
- glOrtho(-screen_ratio,screen_ratio,-1.0f,1.0f,-20.0f,10.0f);
-
-
- glMatrixMode(GL_TEXTURE);
- glLoadIdentity();
- glMatrixMode(GL_MODELVIEW);
- glLoadIdentity();
- gpuLookAt(0.0f, 0.0f, 1.0f, 0.0f,0.0f,0.0f, 0.0f,1.0f,0.0f);
-
- if (m_drawingmode == RAS_IRasterizer::KX_WIREFRAME)
- glPolygonMode(GL_FRONT, GL_LINE);
- else
- glPolygonMode(GL_FRONT, GL_FILL);
-
- glShadeModel(GL_SMOOTH);
- glDisable(GL_LIGHTING);
- glDisable(GL_DEPTH_TEST);
-
- glEnable(GL_TEXTURE_2D);
- glColor3f(1.0f,1.0f,1.0f);
-
- if (dlistSupported) {
- glBindTexture(GL_TEXTURE_2D, domefacesId[m_numfaces]);
- glCallList(dlistId + m_numfaces);
- }
- else {
- glBindTexture(GL_TEXTURE_2D, domefacesId[m_numfaces]);
- GLDrawWarpQuads();
- }
- glDisable(GL_TEXTURE_2D);
- glEnable(GL_DEPTH_TEST);
-}
-
-void KX_Dome::BindImages(int i)
-{
- glBindTexture(GL_TEXTURE_2D, domefacesId[i]);
- glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, m_viewport.GetLeft(), m_viewport.GetBottom(), m_buffersize, m_buffersize);
-}
-
-void KX_Dome::RenderDomeFrame(KX_Scene* scene, KX_Camera* cam, int i)
-{
- if (!cam)
- return;
-
- m_canvas->SetViewPort(0,0,m_buffersize-1,m_buffersize-1);
-
-// m_rasterizer->SetAmbient();
- m_rasterizer->DisplayFog();
-
- CalculateFrustum(cam); //calculates m_projmat
- cam->SetProjectionMatrix(m_projmat);
- m_rasterizer->SetProjectionMatrix(cam->GetProjectionMatrix());
-// Dome_RotateCamera(cam,i);
-
- MT_Matrix3x3 camori = cam->GetSGNode()->GetLocalOrientation();
-
- cam->NodeSetLocalOrientation(camori*m_locRot[i]);
- cam->NodeUpdateGS(0.f);
-
- MT_Transform camtrans(cam->GetWorldToCamera());
- MT_Matrix4x4 viewmat(camtrans);
- m_rasterizer->SetViewMatrix(viewmat, cam->NodeGetWorldOrientation(), cam->NodeGetWorldPosition(), cam->NodeGetLocalScaling(), 1.0f);
- cam->SetModelviewMatrix(viewmat);
-
- // restore the original orientation
- cam->NodeSetLocalOrientation(camori);
- cam->NodeUpdateGS(0.f);
-
- scene->CalculateVisibleMeshes(m_rasterizer,cam);
-
- m_engine->UpdateAnimations(scene);
-
- scene->RenderBuckets(camtrans, m_rasterizer);
-}
-
diff --git a/source/gameengine/Ketsji/KX_Dome.h b/source/gameengine/Ketsji/KX_Dome.h
deleted file mode 100644
index 5a0c4588ae2..00000000000
--- a/source/gameengine/Ketsji/KX_Dome.h
+++ /dev/null
@@ -1,197 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * Contributor(s): Dalai Felinto
- *
- * This source uses some of the ideas and code from Paul Bourke.
- * Developed as part of a Research and Development project for
- * SAT - La Société des arts technologiques.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file KX_Dome.h
- * \ingroup ketsji
- */
-
-#ifndef __KX_DOME_H__
-#define __KX_DOME_H__
-
-#include "KX_Scene.h"
-#include "KX_Camera.h"
-#include "DNA_screen_types.h"
-#include "RAS_ICanvas.h"
-#include "RAS_IRasterizer.h"
-#include "KX_KetsjiEngine.h"
-
-#include "GPU_glew.h"
-#include <vector>
-
-#include "MEM_guardedalloc.h"
-#include "BKE_text.h"
-
-//Dome modes: limit hardcoded in buttons_scene.c
-#define DOME_FISHEYE 1
-#define DOME_TRUNCATED_FRONT 2
-#define DOME_TRUNCATED_REAR 3
-#define DOME_ENVMAP 4
-#define DOME_PANORAM_SPH 5
-#define DOME_NUM_MODES 6
-
-
-/// class for render 3d scene
-class KX_Dome
-{
-public:
- /// constructor
- KX_Dome (RAS_ICanvas* m_canvas,
- /// rasterizer
- RAS_IRasterizer* m_rasterizer,
- /// engine
- KX_KetsjiEngine* m_engine,
-
- short res,
- short mode,
- short angle,
- float resbuf,
- short tilt,
- struct Text* warptext
- );
-
- /// destructor
- virtual ~KX_Dome (void);
-
- //openGL checks:
- bool dlistSupported;
- bool fboSupported;
-
- //openGL names:
- GLuint domefacesId[7]; /* ID of the images -- room for 7 images, using only 4 for 180deg x 360deg dome,
- * 6 for panoramic and +1 for warp mesh */
- GLuint dlistId; /* ID of the Display Lists of the images (used as an offset) */
-
- typedef struct {
- double u[3], v[3];
- MT_Vector3 verts[3]; //three verts
- } DomeFace;
-
- //mesh warp functions
- typedef struct {
- double x, y, u, v, i;
- } WarpMeshNode;
-
- struct {
- bool usemesh;
- int mode;
- int n_width, n_height; //nodes width and height
- int imagesize;
- int bufferwidth, bufferheight;
- GLuint fboId;
- vector <vector <WarpMeshNode> > nodes;
- } warp;
-
- bool ParseWarpMesh(STR_String text);
-
- vector <DomeFace> cubetop, cubebottom, cuberight, cubeleft, cubefront, cubeback; //for fisheye
- vector <DomeFace> cubeleftback, cuberightback; //for panorama
-
- int nfacestop, nfacesbottom, nfacesleft, nfacesright, nfacesfront, nfacesback;
- int nfacesleftback, nfacesrightback;
-
- int GetNumberRenders() { return m_numfaces; }
-
- void RenderDome(void);
- void RenderDomeFrame(KX_Scene* scene, KX_Camera* cam, int i);
- void BindImages(int i);
-
- void SetViewPort(const int viewport[4]);
- void CalculateFrustum(KX_Camera* cam);
- void RotateCamera(KX_Camera* cam, int i);
-
- //Mesh creation Functions
- void CreateMeshDome180(void);
- void CreateMeshDome250(void);
- void CreateMeshPanorama(void);
-
- void SplitFace(vector <DomeFace>& face, int *nfaces);
-
- void FlattenDome(MT_Vector3 verts[3]);
- void FlattenPanorama(MT_Vector3 verts[3]);
-
- //Draw functions
- void GLDrawTriangles(vector <DomeFace>& face, int nfaces);
- void GLDrawWarpQuads(void);
- void Draw(void);
- void DrawDomeFisheye(void);
- void DrawEnvMap(void);
- void DrawPanorama(void);
- void DrawDomeWarped(void);
-
- //setting up openGL
- void CreateGLImages(void);
- void ClearGLImages(void);//called on resize
- bool CreateDL(void); //create Display Lists
- void ClearDL(void); //remove Display Lists
- bool CreateFBO(void);//create FBO (for warp mesh)
- void ClearFBO(void); //remove FBO
-
- void CalculateCameraOrientation();
- void CalculateImageSize(); //set m_imagesize
-
- int canvaswidth;
- int canvasheight;
-
-protected:
- int m_drawingmode;
-
- int m_imagesize;
- int m_buffersize; // canvas small dimension
- int m_numfaces; // 4 to 6 depending on the kind of dome image
- int m_numimages; //numfaces +1 if we have warp mesh
-
- short m_resolution; //resolution to tessellate the mesh
- short m_mode; // the mode (truncated, warped, panoramic,...)
- short m_angle; //the angle of the fisheye
- float m_radangle; //the angle of the fisheye in radians
- float m_resbuffer; //the resolution of the buffer
- short m_tilt; //the dome tilt (camera rotation on horizontal axis)
-
- RAS_Rect m_viewport;
-
- MT_Matrix4x4 m_projmat;
-
- MT_Matrix3x3 m_locRot[6]; // the rotation matrix
-
- /// rendered scene
- KX_Scene * m_scene;
-
- /// canvas
- RAS_ICanvas* m_canvas;
- /// rasterizer
- RAS_IRasterizer* m_rasterizer;
- /// render tools
- RAS_IRenderTools* m_rendertools;
- /// engine
- KX_KetsjiEngine* m_engine;
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:KX_Dome")
-#endif
-};
-
-#endif /* __KX_DOME_H__ */
diff --git a/source/gameengine/Ketsji/KX_EmptyObject.cpp b/source/gameengine/Ketsji/KX_EmptyObject.cpp
deleted file mode 100644
index 670329a4350..00000000000
--- a/source/gameengine/Ketsji/KX_EmptyObject.cpp
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Ketsji/KX_EmptyObject.cpp
- * \ingroup ketsji
- */
-
-#include "KX_EmptyObject.h"
-
-KX_EmptyObject::~KX_EmptyObject()
-{
-
-}
diff --git a/source/gameengine/Ketsji/KX_EmptyObject.h b/source/gameengine/Ketsji/KX_EmptyObject.h
deleted file mode 100644
index 63a0782a544..00000000000
--- a/source/gameengine/Ketsji/KX_EmptyObject.h
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file KX_EmptyObject.h
- * \ingroup ketsji
- */
-
-#ifndef __KX_EMPTYOBJECT_H__
-#define __KX_EMPTYOBJECT_H__
-#include "KX_GameObject.h"
-
-class KX_EmptyObject : public KX_GameObject
-{
-public:
- KX_EmptyObject(void* sgReplicationInfo,SG_Callbacks callbacks) :
- KX_GameObject(sgReplicationInfo,callbacks)
- {};
- virtual ~KX_EmptyObject();
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:KX_EmptyObject")
-#endif
-};
-
-#endif /* __KX_EMPTYOBJECT_H__ */
diff --git a/source/gameengine/Ketsji/KX_FontObject.cpp b/source/gameengine/Ketsji/KX_FontObject.cpp
deleted file mode 100644
index ae79284288d..00000000000
--- a/source/gameengine/Ketsji/KX_FontObject.cpp
+++ /dev/null
@@ -1,300 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Ketsji/KX_FontObject.cpp
- * \ingroup ketsji
- */
-
-#include "KX_FontObject.h"
-#include "DNA_curve_types.h"
-#include "DNA_vfont_types.h"
-#include "KX_Scene.h"
-#include "KX_PythonInit.h"
-#include "BLI_math.h"
-#include "EXP_StringValue.h"
-#include "RAS_IRasterizer.h"
-
-/* paths needed for font load */
-#include "BLI_blenlib.h"
-#include "BKE_global.h"
-#include "BKE_font.h"
-#include "BKE_main.h"
-#include "DNA_packedFile_types.h"
-
-extern "C" {
-#include "BLF_api.h"
-}
-
-#define BGE_FONT_RES 100
-
-/* proptotype */
-int GetFontId(VFont *font);
-
-static std::vector<STR_String> split_string(STR_String str)
-{
- std::vector<STR_String> text = std::vector<STR_String>();
-
- /* Split the string upon new lines */
- int begin=0, end=0;
- while (end < str.Length())
- {
- if (str.GetAt(end) == '\n')
- {
- text.push_back(str.Mid(begin, end-begin));
- begin = end+1;
- }
- end++;
- }
- //Now grab the last line
- text.push_back(str.Mid(begin, end-begin));
-
- return text;
-}
-
-KX_FontObject::KX_FontObject(void* sgReplicationInfo,
- SG_Callbacks callbacks,
- RAS_IRasterizer* rasterizer,
- Object *ob,
- bool do_color_management):
- KX_GameObject(sgReplicationInfo, callbacks),
- m_object(ob),
- m_dpi(72),
- m_resolution(1.f),
- m_rasterizer(rasterizer),
- m_do_color_management(do_color_management)
-{
- Curve *text = static_cast<Curve *> (ob->data);
- m_text = split_string(text->str);
- m_fsize = text->fsize;
- m_line_spacing = text->linedist;
- m_offset = MT_Vector3(text->xof, text->yof, 0);
-
- m_fontid = GetFontId(text->vfont);
-
- /* initialize the color with the object color and store it in the KX_Object class
- * This is a workaround waiting for the fix:
- * [#25487] BGE: Object Color only works when it has a keyed frame */
- copy_v4_v4(m_color, (const float*) ob->col);
- this->SetObjectColor((const MT_Vector4&) m_color);
-}
-
-KX_FontObject::~KX_FontObject()
-{
- //remove font from the scene list
- //it's handled in KX_Scene::NewRemoveObject
-}
-
-CValue* KX_FontObject::GetReplica()
-{
- KX_FontObject* replica = new KX_FontObject(*this);
- replica->ProcessReplica();
- return replica;
-}
-
-void KX_FontObject::ProcessReplica()
-{
- KX_GameObject::ProcessReplica();
-}
-
-int GetFontId(VFont *vfont)
-{
- PackedFile *packedfile=NULL;
- int fontid = -1;
-
- if (vfont->packedfile) {
- packedfile= vfont->packedfile;
- fontid= BLF_load_mem(vfont->name, (unsigned char*)packedfile->data, packedfile->size);
-
- if (fontid == -1) {
- printf("ERROR: packed font \"%s\" could not be loaded.\n", vfont->name);
- fontid = BLF_load("default");
- }
- return fontid;
- }
-
- /* once we have packed working we can load the builtin font */
- const char *filepath = vfont->name;
- if (BKE_vfont_is_builtin(vfont)) {
- fontid = BLF_load("default");
-
- /* XXX the following code is supposed to work (after you add get_builtin_packedfile to BKE_font.h )
- * unfortunately it's crashing on blf_glyph.c:173 because gc->glyph_width_max is 0
- */
- // packedfile=get_builtin_packedfile();
- // fontid= BLF_load_mem(font->name, (unsigned char*)packedfile->data, packedfile->size);
- // return fontid;
-
- return BLF_load("default");
- }
-
- /* convert from absolute to relative */
- char expanded[256]; // font names can be bigger than FILE_MAX (240)
- BLI_strncpy(expanded, filepath, 256);
- BLI_path_abs(expanded, G.main->name);
-
- fontid = BLF_load(expanded);
-
- /* fallback */
- if (fontid == -1)
- fontid = BLF_load("default");
-
- return fontid;
-}
-
-void KX_FontObject::DrawFontText()
-{
- /* Allow for some logic brick control */
- if (this->GetProperty("Text"))
- m_text = split_string(this->GetProperty("Text")->GetText());
-
- /* only draws the text if visible */
- if (this->GetVisible() == 0) return;
-
- /* update the animated color */
- this->GetObjectColor().getValue(m_color);
-
- /* Font Objects don't use the glsl shader, this color management code is copied from gpu_shader_material.glsl */
- float color[4];
- if (m_do_color_management) {
- linearrgb_to_srgb_v4(color, m_color);
- }
- else {
- copy_v4_v4(color, m_color);
- }
-
- /* HARDCODED MULTIPLICATION FACTOR - this will affect the render resolution directly */
- const float RES = BGE_FONT_RES * m_resolution;
-
- const float size = m_fsize * this->NodeGetWorldScaling()[0] * RES;
- const float aspect = m_fsize / size;
-
- /* Get a working copy of the OpenGLMatrix to use */
- float *mat = GetOpenGLMatrix();
-
- /* Account for offset */
- MT_Vector3 offset = this->NodeGetWorldOrientation() * m_offset * this->NodeGetWorldScaling();
- mat[12] += offset[0]; mat[13] += offset[1]; mat[14] += offset[2];
-
- /* Orient the spacing vector */
- MT_Vector3 spacing = MT_Vector3(0.0f, m_fsize*m_line_spacing, 0.0f);
- spacing = this->NodeGetWorldOrientation() * spacing * this->NodeGetWorldScaling()[1];
-
- /* Draw each line, taking spacing into consideration */
- for (int i=0; i<m_text.size(); ++i)
- {
- if (i!=0)
- {
- mat[12] -= spacing[0];
- mat[13] -= spacing[1];
- mat[14] -= spacing[2];
- }
- m_rasterizer->RenderText3D(m_fontid, m_text[i], int(size), m_dpi, color, mat, aspect);
- }
-}
-
-#ifdef WITH_PYTHON
-
-/* ------------------------------------------------------------------------- */
-/* Python Integration Hooks */
-/* ------------------------------------------------------------------------- */
-
-PyTypeObject KX_FontObject::Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "KX_FontObject",
- sizeof(PyObjectPlus_Proxy),
- 0,
- py_base_dealloc,
- 0,
- 0,
- 0,
- 0,
- py_base_repr,
- 0,
- &KX_GameObject::Sequence,
- &KX_GameObject::Mapping,
- 0,0,0,
- NULL,
- NULL,
- 0,
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
- 0,0,0,0,0,0,0,
- Methods,
- 0,
- 0,
- &KX_GameObject::Type,
- 0,0,0,0,0,0,
- py_base_new
-};
-
-PyMethodDef KX_FontObject::Methods[] = {
- {NULL,NULL} //Sentinel
-};
-
-PyAttributeDef KX_FontObject::Attributes[] = {
- //KX_PYATTRIBUTE_STRING_RW("text", 0, 280, false, KX_FontObject, m_text[0]), //arbitrary limit. 280 = 140 unicode chars in unicode
- KX_PYATTRIBUTE_RW_FUNCTION("text", KX_FontObject, pyattr_get_text, pyattr_set_text),
- KX_PYATTRIBUTE_FLOAT_RW("size", 0.0001f, 10000.0f, KX_FontObject, m_fsize),
- KX_PYATTRIBUTE_FLOAT_RW("resolution", 0.0001f, 10000.0f, KX_FontObject, m_resolution),
- /* KX_PYATTRIBUTE_INT_RW("dpi", 0, 10000, false, KX_FontObject, m_dpi), */// no real need for expose this I think
- { NULL } //Sentinel
-};
-
-PyObject *KX_FontObject::pyattr_get_text(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_FontObject* self = static_cast<KX_FontObject*>(self_v);
- STR_String str = STR_String();
- for (int i=0; i<self->m_text.size(); ++i)
- {
- if (i!=0)
- str += '\n';
- str += self->m_text[i];
- }
- return PyUnicode_From_STR_String(str);
-}
-
-int KX_FontObject::pyattr_set_text(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_FontObject* self = static_cast<KX_FontObject*>(self_v);
- if (!PyUnicode_Check(value))
- return PY_SET_ATTR_FAIL;
- const char *chars = _PyUnicode_AsString(value);
-
- /* Allow for some logic brick control */
- CValue* tprop = self->GetProperty("Text");
- if (tprop) {
- CValue *newstringprop = new CStringValue(STR_String(chars), "Text");
- self->SetProperty("Text", newstringprop);
- newstringprop->Release();
- }
- else {
- self->m_text = split_string(STR_String(chars));
- }
-
- return PY_SET_ATTR_SUCCESS;
-}
-
-#endif // WITH_PYTHON
diff --git a/source/gameengine/Ketsji/KX_FontObject.h b/source/gameengine/Ketsji/KX_FontObject.h
deleted file mode 100644
index bf70eedfde6..00000000000
--- a/source/gameengine/Ketsji/KX_FontObject.h
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file KX_FontObject.h
- * \ingroup ketsji
- */
-
-#ifndef __KX_FONTOBJECT_H__
-#define __KX_FONTOBJECT_H__
-#include "KX_GameObject.h"
-
-class KX_FontObject : public KX_GameObject
-{
-public:
- Py_Header
- KX_FontObject(void* sgReplicationInfo,
- SG_Callbacks callbacks,
- RAS_IRasterizer* rasterizer,
- Object *ob,
- bool do_color_management);
-
- virtual ~KX_FontObject();
-
- void DrawFontText();
-
- /**
- * Inherited from CValue -- return a new copy of this
- * instance allocated on the heap. Ownership of the new
- * object belongs with the caller.
- */
- virtual CValue* GetReplica();
- virtual void ProcessReplica();
- virtual int GetGameObjectType() { return OBJ_TEXT; }
-
-protected:
- std::vector<STR_String> m_text;
- Object* m_object;
- int m_fontid;
- int m_dpi;
- float m_fsize;
- float m_resolution;
- float m_color[4];
- float m_line_spacing;
- MT_Vector3 m_offset;
-
- class RAS_IRasterizer* m_rasterizer; //needed for drawing routine
-
- bool m_do_color_management;
-
-#ifdef WITH_PYTHON
- static PyObject* pyattr_get_text(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_text(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
-#endif
-
-};
-
-#endif /* __KX_FONTOBJECT_H__ */
diff --git a/source/gameengine/Ketsji/KX_GameActuator.cpp b/source/gameengine/Ketsji/KX_GameActuator.cpp
deleted file mode 100644
index f1bd253f8b3..00000000000
--- a/source/gameengine/Ketsji/KX_GameActuator.cpp
+++ /dev/null
@@ -1,267 +0,0 @@
-/*
- * global game stuff
- *
- *
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Ketsji/KX_GameActuator.cpp
- * \ingroup ketsji
- */
-
-
-#include <stddef.h>
-
-#include "SCA_IActuator.h"
-#include "KX_GameActuator.h"
-//#include <iostream>
-#include "KX_Scene.h"
-#include "KX_KetsjiEngine.h"
-#include "KX_PythonInit.h" /* for config load/saving */
-#include "RAS_ICanvas.h"
-
-#include <stdio.h>
-#include <stdlib.h>
-
-/* ------------------------------------------------------------------------- */
-/* Native functions */
-/* ------------------------------------------------------------------------- */
-
-KX_GameActuator::KX_GameActuator(SCA_IObject *gameobj,
- int mode,
- const STR_String& filename,
- const STR_String& loadinganimationname,
- SCA_IScene* scene,
- KX_KetsjiEngine* ketsjiengine)
- : SCA_IActuator(gameobj, KX_ACT_GAME)
-{
- m_mode = mode;
- m_filename = filename;
- m_loadinganimationname = loadinganimationname;
- m_scene = scene;
- m_ketsjiengine = ketsjiengine;
-} /* End of constructor */
-
-
-
-KX_GameActuator::~KX_GameActuator()
-{
- // there's nothing to be done here, really....
-} /* end of destructor */
-
-
-
-CValue* KX_GameActuator::GetReplica()
-{
- KX_GameActuator* replica = new KX_GameActuator(*this);
- replica->ProcessReplica();
-
- return replica;
-}
-
-
-
-bool KX_GameActuator::Update()
-{
- // bool result = false; /*unused*/
- bool bNegativeEvent = IsNegativeEvent();
- RemoveAllEvents();
-
- if (bNegativeEvent)
- return false; // do nothing on negative events
-
- switch (m_mode)
- {
- case KX_GAME_LOAD:
- case KX_GAME_START:
- {
- if (m_ketsjiengine)
- {
- STR_String exitstring = "start other game";
- m_ketsjiengine->RequestExit(KX_EXIT_REQUEST_START_OTHER_GAME);
- m_ketsjiengine->SetNameNextGame(m_filename);
- m_scene->AddDebugProperty((this)->GetParent(), exitstring);
- }
-
- break;
- }
- case KX_GAME_RESTART:
- {
- if (m_ketsjiengine)
- {
- STR_String exitstring = "restarting game";
- m_ketsjiengine->RequestExit(KX_EXIT_REQUEST_RESTART_GAME);
- m_ketsjiengine->SetNameNextGame(m_filename);
- m_scene->AddDebugProperty((this)->GetParent(), exitstring);
- }
- break;
- }
- case KX_GAME_QUIT:
- {
- if (m_ketsjiengine)
- {
- STR_String exitstring = "quiting game";
- m_ketsjiengine->RequestExit(KX_EXIT_REQUEST_QUIT_GAME);
- m_scene->AddDebugProperty((this)->GetParent(), exitstring);
- }
- break;
- }
- case KX_GAME_SAVECFG:
- {
-#ifdef WITH_PYTHON
- if (m_ketsjiengine)
- {
- char mashal_path[512];
- char *marshal_buffer = NULL;
- unsigned int marshal_length;
- FILE *fp = NULL;
-
- pathGamePythonConfig(mashal_path);
- marshal_length = saveGamePythonConfig(&marshal_buffer);
-
- if (marshal_length && marshal_buffer) {
- fp = fopen(mashal_path, "wb");
- if (fp) {
- if (fwrite(marshal_buffer, 1, marshal_length, fp) != marshal_length) {
- printf("Warning: could not write marshal data\n");
- }
- fclose(fp);
- } else {
- printf("Warning: could not open marshal file\n");
- }
- } else {
- printf("Warning: could not create marshal buffer\n");
- }
- if (marshal_buffer)
- delete [] marshal_buffer;
- }
- break;
-#endif // WITH_PYTHON
- }
- case KX_GAME_LOADCFG:
- {
-#ifdef WITH_PYTHON
- if (m_ketsjiengine)
- {
- char mashal_path[512];
- char *marshal_buffer;
- int marshal_length;
- FILE *fp = NULL;
- int result;
-
- pathGamePythonConfig(mashal_path);
-
- fp = fopen(mashal_path, "rb");
- if (fp) {
- // obtain file size:
- fseek (fp , 0 , SEEK_END);
- marshal_length = ftell(fp);
- if (marshal_length == -1) {
- printf("warning: could not read position of '%s'\n", mashal_path);
- fclose(fp);
- break;
- }
- rewind(fp);
-
- marshal_buffer = (char*) malloc (sizeof(char)*marshal_length);
-
- result = fread (marshal_buffer, 1, marshal_length, fp);
-
- if (result == marshal_length) {
- loadGamePythonConfig(marshal_buffer, marshal_length);
- } else {
- printf("warning: could not read all of '%s'\n", mashal_path);
- }
-
- free(marshal_buffer);
- fclose(fp);
- } else {
- printf("warning: could not open '%s'\n", mashal_path);
- }
- }
- break;
-#endif // WITH_PYTHON
- }
- case KX_GAME_SCREENSHOT:
- {
- RAS_ICanvas *canvas = m_ketsjiengine->GetCanvas();
- if (canvas) {
- canvas->MakeScreenShot(m_filename);
- }
- else {
- printf("KX_GAME_SCREENSHOT error: Rasterizer not available");
- }
- break;
- }
- default:
- ; /* do nothing? this is an internal error !!! */
- }
-
- return false;
-}
-
-
-#ifdef WITH_PYTHON
-
-/* ------------------------------------------------------------------------- */
-/* Python functions */
-/* ------------------------------------------------------------------------- */
-
-/* Integration hooks ------------------------------------------------------- */
-PyTypeObject KX_GameActuator::Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "KX_GameActuator",
- sizeof(PyObjectPlus_Proxy),
- 0,
- py_base_dealloc,
- 0,
- 0,
- 0,
- 0,
- py_base_repr,
- 0,0,0,0,0,0,0,0,0,
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
- 0,0,0,0,0,0,0,
- Methods,
- 0,
- 0,
- &SCA_IActuator::Type,
- 0,0,0,0,0,0,
- py_base_new
-};
-
-PyMethodDef KX_GameActuator::Methods[] =
-{
- {NULL,NULL} //Sentinel
-};
-
-PyAttributeDef KX_GameActuator::Attributes[] = {
- KX_PYATTRIBUTE_STRING_RW("fileName",0,100,false,KX_GameActuator,m_filename),
- KX_PYATTRIBUTE_INT_RW("mode", KX_GAME_NODEF+1, KX_GAME_MAX-1, true, KX_GameActuator, m_mode),
- { NULL } //Sentinel
-};
-
-#endif // WITH_PYTHON
diff --git a/source/gameengine/Ketsji/KX_GameActuator.h b/source/gameengine/Ketsji/KX_GameActuator.h
deleted file mode 100644
index 57472836bb2..00000000000
--- a/source/gameengine/Ketsji/KX_GameActuator.h
+++ /dev/null
@@ -1,91 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file KX_GameActuator.h
- * \ingroup ketsji
- * \brief actuator for global game stuff
- */
-
-#ifndef __KX_GAMEACTUATOR_H__
-#define __KX_GAMEACTUATOR_H__
-
-#include "SCA_IActuator.h"
-
-#include "SCA_IScene.h" /* Replace_IScene only */
-#include "KX_Scene.h" /* Replace_IScene only */
-
-class KX_GameActuator : public SCA_IActuator
-{
- Py_Header
-protected:
- int m_mode;
- bool m_restart;
- STR_String m_filename;
- STR_String m_loadinganimationname;
- class SCA_IScene* m_scene;
- class KX_KetsjiEngine* m_ketsjiengine;
-
- public:
- enum KX_GameActuatorMode
- {
- KX_GAME_NODEF = 0,
- KX_GAME_LOAD,
- KX_GAME_START,
- KX_GAME_RESTART,
- KX_GAME_QUIT,
- KX_GAME_SAVECFG,
- KX_GAME_LOADCFG,
- KX_GAME_SCREENSHOT,
- KX_GAME_MAX
-
- };
-
- KX_GameActuator(SCA_IObject* gameobj,
- int mode,
- const STR_String& filename,
- const STR_String& loadinganimationname,
- SCA_IScene* scene,
- KX_KetsjiEngine* ketsjiEngine);
- virtual ~KX_GameActuator();
-
- virtual CValue* GetReplica();
-
- virtual bool Update();
-
- virtual void Replace_IScene(SCA_IScene *val)
- {
- m_scene= val;
- };
-
- /* --------------------------------------------------------------------- */
- /* Python interface ---------------------------------------------------- */
- /* --------------------------------------------------------------------- */
-
-}; /* end of class KX_GameActuator */
-
-#endif
-
diff --git a/source/gameengine/Ketsji/KX_GameObject.cpp b/source/gameengine/Ketsji/KX_GameObject.cpp
deleted file mode 100644
index 3244400e1bd..00000000000
--- a/source/gameengine/Ketsji/KX_GameObject.cpp
+++ /dev/null
@@ -1,4203 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- * Game object wrapper
- */
-
-/** \file gameengine/Ketsji/KX_GameObject.cpp
- * \ingroup ketsji
- */
-
-#ifdef _MSC_VER
- /* This warning tells us about truncation of __long__ stl-generated names.
- * It can occasionally cause DevStudio to have internal compiler warnings. */
-# pragma warning( disable:4786 )
-#endif
-
-#include "RAS_IPolygonMaterial.h"
-#include "KX_BlenderMaterial.h"
-#include "KX_GameObject.h"
-#include "KX_Camera.h" // only for their ::Type
-#include "KX_Light.h" // only for their ::Type
-#include "KX_FontObject.h" // only for their ::Type
-#include "RAS_MeshObject.h"
-#include "KX_NavMeshObject.h"
-#include "KX_MeshProxy.h"
-#include "KX_PolyProxy.h"
-#include <stdio.h> // printf
-#include "SG_Controller.h"
-#include "PHY_IGraphicController.h"
-#include "SG_Node.h"
-#include "KX_ClientObjectInfo.h"
-#include "RAS_BucketManager.h"
-#include "KX_RayCast.h"
-#include "KX_PythonInit.h"
-#include "KX_PyMath.h"
-#include "SCA_IActuator.h"
-#include "SCA_ISensor.h"
-#include "SCA_IController.h"
-#include "NG_NetworkScene.h" //Needed for sendMessage()
-#include "KX_ObstacleSimulation.h"
-#include "KX_Scene.h"
-
-#include "BKE_object.h"
-
-#include "BL_ActionManager.h"
-#include "BL_Action.h"
-
-#include "EXP_PyObjectPlus.h" /* python stuff */
-#include "EXP_ListWrapper.h"
-#include "BLI_utildefines.h"
-
-#ifdef WITH_PYTHON
-# include "EXP_PythonCallBack.h"
-# include "python_utildefines.h"
-#endif
-
-// This file defines relationships between parents and children
-// in the game engine.
-
-#include "KX_SG_NodeRelationships.h"
-
-#include "BLI_math.h"
-
-static MT_Point3 dummy_point= MT_Point3(0.0f, 0.0f, 0.0f);
-static MT_Vector3 dummy_scaling = MT_Vector3(1.0f, 1.0f, 1.0f);
-static MT_Matrix3x3 dummy_orientation = MT_Matrix3x3(1.0f, 0.0f, 0.0f,
- 0.0f, 1.0f, 0.0f,
- 0.0f, 0.0f, 1.0f);
-
-KX_GameObject::KX_GameObject(
- void* sgReplicationInfo,
- SG_Callbacks callbacks)
- : SCA_IObject(),
- m_bDyna(false),
- m_layer(0),
- m_currentLodLevel(0),
- m_previousLodLevel(0),
- m_pBlenderObject(NULL),
- m_pBlenderGroupObject(NULL),
- m_bUseObjectColor(false),
- m_bIsNegativeScaling(false),
- m_objectColor(1.0f, 1.0f, 1.0f, 1.0f),
- m_bVisible(true),
- m_bCulled(true),
- m_bOccluder(false),
- m_pPhysicsController(NULL),
- m_pGraphicController(NULL),
- m_pObstacleSimulation(NULL),
- m_pInstanceObjects(NULL),
- m_pDupliGroupObject(NULL),
- m_actionManager(NULL),
- m_bRecordAnimation(false),
- m_isDeformable(false)
-
-#ifdef WITH_PYTHON
- , m_attr_dict(NULL),
- m_collisionCallbacks(NULL)
-#endif
-{
- m_ignore_activity_culling = false;
- m_pClient_info = new KX_ClientObjectInfo(this, KX_ClientObjectInfo::ACTOR);
- m_pSGNode = new SG_Node(this,sgReplicationInfo,callbacks);
-
- // define the relationship between this node and it's parent.
-
- KX_NormalParentRelation * parent_relation =
- KX_NormalParentRelation::New();
- m_pSGNode->SetParentRelation(parent_relation);
-};
-
-
-
-KX_GameObject::~KX_GameObject()
-{
-#ifdef WITH_PYTHON
- if (m_attr_dict) {
- PyDict_Clear(m_attr_dict); /* in case of circular refs or other weird cases */
- /* Py_CLEAR: Py_DECREF's and NULL's */
- Py_CLEAR(m_attr_dict);
- }
- // Unregister collision callbacks
- // Do this before we start freeing physics information like m_pClient_info
- if (m_collisionCallbacks) {
- UnregisterCollisionCallbacks();
- Py_CLEAR(m_collisionCallbacks);
- }
-#endif // WITH_PYTHON
-
- RemoveMeshes();
-
- // is this delete somewhere ?
- //if (m_sumoObj)
- // delete m_sumoObj;
- delete m_pClient_info;
- //if (m_pSGNode)
- // delete m_pSGNode;
- if (m_pSGNode)
- {
- // must go through controllers and make sure they will not use us anymore
- // This is important for KX_BulletPhysicsControllers that unregister themselves
- // from the object when they are deleted.
- SGControllerList::iterator contit;
- SGControllerList& controllers = m_pSGNode->GetSGControllerList();
- for (contit = controllers.begin();contit!=controllers.end();++contit)
- {
- (*contit)->ClearObject();
- }
- m_pSGNode->SetSGClientObject(NULL);
-
- /* m_pSGNode is freed in KX_Scene::RemoveNodeDestructObject */
- }
- if (m_pGraphicController)
- {
- delete m_pGraphicController;
- }
-
- if (m_pPhysicsController)
- {
- delete m_pPhysicsController;
- }
-
- if (m_pObstacleSimulation)
- {
- m_pObstacleSimulation->DestroyObstacleForObj(this);
- }
-
- if (m_actionManager)
- {
- delete m_actionManager;
- }
-
- if (m_pDupliGroupObject)
- {
- m_pDupliGroupObject->Release();
- }
-
- if (m_pInstanceObjects)
- {
- m_pInstanceObjects->Release();
- }
-}
-
-KX_GameObject* KX_GameObject::GetClientObject(KX_ClientObjectInfo *info)
-{
- if (!info)
- return NULL;
- return info->m_gameobject;
-}
-
-CValue* KX_GameObject:: Calc(VALUE_OPERATOR op, CValue *val)
-{
- return NULL;
-}
-
-
-
-CValue* KX_GameObject::CalcFinal(VALUE_DATA_TYPE dtype, VALUE_OPERATOR op, CValue *val)
-{
- return NULL;
-}
-
-
-
-const STR_String & KX_GameObject::GetText()
-{
- return m_text;
-}
-
-
-
-double KX_GameObject::GetNumber()
-{
- return 0;
-}
-
-
-
-STR_String& KX_GameObject::GetName()
-{
- return m_name;
-}
-
-
-/* Set the name of the value */
-void KX_GameObject::SetName(const char *name)
-{
- m_name = name;
-}
-
-PHY_IPhysicsController* KX_GameObject::GetPhysicsController()
-{
- return m_pPhysicsController;
-}
-
-KX_GameObject* KX_GameObject::GetDupliGroupObject()
-{
- return m_pDupliGroupObject;
-}
-
-CListValue* KX_GameObject::GetInstanceObjects()
-{
- return m_pInstanceObjects;
-}
-
-void KX_GameObject::AddInstanceObjects(KX_GameObject* obj)
-{
- if (!m_pInstanceObjects)
- m_pInstanceObjects = new CListValue();
-
- obj->AddRef();
- m_pInstanceObjects->Add(obj);
-}
-
-void KX_GameObject::RemoveInstanceObject(KX_GameObject* obj)
-{
- assert(m_pInstanceObjects);
- m_pInstanceObjects->RemoveValue(obj);
- obj->Release();
-}
-
-void KX_GameObject::RemoveDupliGroupObject()
-{
- if (m_pDupliGroupObject) {
- m_pDupliGroupObject->Release();
- m_pDupliGroupObject = NULL;
- }
-}
-
-void KX_GameObject::SetDupliGroupObject(KX_GameObject* obj)
-{
- obj->AddRef();
- m_pDupliGroupObject = obj;
-}
-
-void KX_GameObject::AddConstraint(bRigidBodyJointConstraint *cons)
-{
- m_constraints.push_back(cons);
-}
-
-std::vector<bRigidBodyJointConstraint*> KX_GameObject::GetConstraints()
-{
- return m_constraints;
-}
-
-void KX_GameObject::ClearConstraints()
-{
- m_constraints.clear();
-}
-
-KX_GameObject* KX_GameObject::GetParent()
-{
- KX_GameObject* result = NULL;
- SG_Node* node = m_pSGNode;
-
- while (node && !result)
- {
- node = node->GetSGParent();
- if (node)
- result = (KX_GameObject*)node->GetSGClientObject();
- }
-
- return result;
-
-}
-
-void KX_GameObject::SetParent(KX_Scene *scene, KX_GameObject* obj, bool addToCompound, bool ghost)
-{
- // check on valid node in case a python controller holds a reference to a deleted object
- if (obj &&
- GetSGNode() && // object is not zombi
- obj->GetSGNode() && // object is not zombi
- GetSGNode()->GetSGParent() != obj->GetSGNode() && // not already parented to same object
- !GetSGNode()->IsAncessor(obj->GetSGNode()) && // no parenting loop
- this != obj) // not the object itself
- {
- // Make sure the objects have some scale
- MT_Vector3 scale1 = NodeGetWorldScaling();
- MT_Vector3 scale2 = obj->NodeGetWorldScaling();
- if (fabs(scale2[0]) < (MT_Scalar)FLT_EPSILON ||
- fabs(scale2[1]) < (MT_Scalar)FLT_EPSILON ||
- fabs(scale2[2]) < (MT_Scalar)FLT_EPSILON ||
- fabs(scale1[0]) < (MT_Scalar)FLT_EPSILON ||
- fabs(scale1[1]) < (MT_Scalar)FLT_EPSILON ||
- fabs(scale1[2]) < (MT_Scalar)FLT_EPSILON) { return; }
-
- // Remove us from our old parent and set our new parent
- RemoveParent(scene);
- obj->GetSGNode()->AddChild(GetSGNode());
-
- if (m_pPhysicsController)
- {
- m_pPhysicsController->SuspendDynamics(ghost);
- }
- // Set us to our new scale, position, and orientation
- scale2[0] = 1.0f/scale2[0];
- scale2[1] = 1.0f/scale2[1];
- scale2[2] = 1.0f/scale2[2];
- scale1 = scale1 * scale2;
- MT_Matrix3x3 invori = obj->NodeGetWorldOrientation().inverse();
- MT_Vector3 newpos = invori*(NodeGetWorldPosition()-obj->NodeGetWorldPosition())*scale2;
-
- NodeSetLocalScale(scale1);
- NodeSetLocalPosition(MT_Point3(newpos[0],newpos[1],newpos[2]));
- NodeSetLocalOrientation(invori*NodeGetWorldOrientation());
- NodeUpdateGS(0.f);
- // object will now be a child, it must be removed from the parent list
- CListValue* rootlist = scene->GetRootParentList();
- if (rootlist->RemoveValue(this))
- // the object was in parent list, decrement ref count as it's now removed
- Release();
- // if the new parent is a compound object, add this object shape to the compound shape.
- // step 0: verify this object has physical controller
- if (m_pPhysicsController && addToCompound)
- {
- // step 1: find the top parent (not necessarily obj)
- KX_GameObject* rootobj = (KX_GameObject*)obj->GetSGNode()->GetRootSGParent()->GetSGClientObject();
- // step 2: verify it has a physical controller and compound shape
- if (rootobj != NULL &&
- rootobj->m_pPhysicsController != NULL &&
- rootobj->m_pPhysicsController->IsCompound())
- {
- rootobj->m_pPhysicsController->AddCompoundChild(m_pPhysicsController);
- }
- }
- // graphically, the object hasn't change place, no need to update m_pGraphicController
- }
-}
-
-void KX_GameObject::RemoveParent(KX_Scene *scene)
-{
- // check on valid node in case a python controller holds a reference to a deleted object
- if (GetSGNode() && GetSGNode()->GetSGParent())
- {
- // get the root object to remove us from compound object if needed
- KX_GameObject* rootobj = (KX_GameObject*)GetSGNode()->GetRootSGParent()->GetSGClientObject();
- // Set us to the right spot
- GetSGNode()->SetLocalScale(GetSGNode()->GetWorldScaling());
- GetSGNode()->SetLocalOrientation(GetSGNode()->GetWorldOrientation());
- GetSGNode()->SetLocalPosition(GetSGNode()->GetWorldPosition());
-
- // Remove us from our parent
- GetSGNode()->DisconnectFromParent();
- NodeUpdateGS(0.f);
- // the object is now a root object, add it to the parentlist
- CListValue* rootlist = scene->GetRootParentList();
- if (!rootlist->SearchValue(this))
- // object was not in root list, add it now and increment ref count
- rootlist->Add(AddRef());
- if (m_pPhysicsController)
- {
- // in case this controller was added as a child shape to the parent
- if (rootobj != NULL &&
- rootobj->m_pPhysicsController != NULL &&
- rootobj->m_pPhysicsController->IsCompound())
- {
- rootobj->m_pPhysicsController->RemoveCompoundChild(m_pPhysicsController);
- }
- m_pPhysicsController->RestoreDynamics();
- if (m_pPhysicsController->IsDynamic() && (rootobj != NULL && rootobj->m_pPhysicsController))
- {
- // dynamic object should remember the velocity they had while being parented
- MT_Point3 childPoint = GetSGNode()->GetWorldPosition();
- MT_Point3 rootPoint = rootobj->GetSGNode()->GetWorldPosition();
- MT_Point3 relPoint;
- relPoint = (childPoint-rootPoint);
- MT_Vector3 linVel = rootobj->m_pPhysicsController->GetVelocity(relPoint);
- MT_Vector3 angVel = rootobj->m_pPhysicsController->GetAngularVelocity();
- m_pPhysicsController->SetLinearVelocity(linVel, false);
- m_pPhysicsController->SetAngularVelocity(angVel, false);
- }
- }
- // graphically, the object hasn't change place, no need to update m_pGraphicController
- }
-}
-
-BL_ActionManager* KX_GameObject::GetActionManager()
-{
- // We only want to create an action manager if we need it
- if (!m_actionManager)
- {
- GetScene()->AddAnimatedObject(this);
- m_actionManager = new BL_ActionManager(this);
- }
- return m_actionManager;
-}
-
-bool KX_GameObject::PlayAction(const char* name,
- float start,
- float end,
- short layer,
- short priority,
- float blendin,
- short play_mode,
- float layer_weight,
- short ipo_flags,
- float playback_speed,
- short blend_mode)
-{
- return GetActionManager()->PlayAction(name, start, end, layer, priority, blendin, play_mode, layer_weight, ipo_flags, playback_speed, blend_mode);
-}
-
-void KX_GameObject::StopAction(short layer)
-{
- GetActionManager()->StopAction(layer);
-}
-
-void KX_GameObject::RemoveTaggedActions()
-{
- GetActionManager()->RemoveTaggedActions();
-}
-
-bool KX_GameObject::IsActionDone(short layer)
-{
- return GetActionManager()->IsActionDone(layer);
-}
-
-void KX_GameObject::UpdateActionManager(float curtime)
-{
- GetActionManager()->Update(curtime);
-}
-
-float KX_GameObject::GetActionFrame(short layer)
-{
- return GetActionManager()->GetActionFrame(layer);
-}
-
-const char *KX_GameObject::GetActionName(short layer)
-{
- return GetActionManager()->GetActionName(layer);
-}
-
-void KX_GameObject::SetActionFrame(short layer, float frame)
-{
- GetActionManager()->SetActionFrame(layer, frame);
-}
-
-bAction *KX_GameObject::GetCurrentAction(short layer)
-{
- return GetActionManager()->GetCurrentAction(layer);
-}
-
-void KX_GameObject::SetPlayMode(short layer, short mode)
-{
- GetActionManager()->SetPlayMode(layer, mode);
-}
-
-void KX_GameObject::SetTimes(short layer, float start, float end)
-{
- GetActionManager()->SetTimes(layer, start, end);
-}
-
-void KX_GameObject::ProcessReplica()
-{
- SCA_IObject::ProcessReplica();
-
- m_pGraphicController = NULL;
- m_pPhysicsController = NULL;
- m_pSGNode = NULL;
-
- /* Dupli group and instance list are set later in replication.
- * See KX_Scene::DupliGroupRecurse. */
- m_pDupliGroupObject = NULL;
- m_pInstanceObjects = NULL;
- m_pClient_info = new KX_ClientObjectInfo(*m_pClient_info);
- m_pClient_info->m_gameobject = this;
- m_actionManager = NULL;
- m_state = 0;
-
- KX_Scene* scene = KX_GetActiveScene();
- KX_ObstacleSimulation* obssimulation = scene->GetObstacleSimulation();
- struct Object* blenderobject = GetBlenderObject();
- if (obssimulation && (blenderobject->gameflag & OB_HASOBSTACLE))
- {
- obssimulation->AddObstacleForObj(this);
- }
-
-#ifdef WITH_PYTHON
- if (m_attr_dict)
- m_attr_dict= PyDict_Copy(m_attr_dict);
-#endif
-
-}
-
-static void setGraphicController_recursive(SG_Node* node)
-{
- NodeList& children = node->GetSGChildren();
-
- for (NodeList::iterator childit = children.begin();!(childit==children.end());++childit)
- {
- SG_Node* childnode = (*childit);
- KX_GameObject *clientgameobj = static_cast<KX_GameObject*>( (*childit)->GetSGClientObject());
- if (clientgameobj != NULL) // This is a GameObject
- clientgameobj->ActivateGraphicController(false);
-
- // if the childobj is NULL then this may be an inverse parent link
- // so a non recursive search should still look down this node.
- setGraphicController_recursive(childnode);
- }
-}
-
-
-void KX_GameObject::ActivateGraphicController(bool recurse)
-{
- if (m_pGraphicController)
- {
- m_pGraphicController->Activate(m_bVisible);
- }
- if (recurse)
- {
- setGraphicController_recursive(GetSGNode());
- }
-}
-
-void KX_GameObject::SetUserCollisionGroup(unsigned short group)
-{
- m_userCollisionGroup = group;
- if (m_pPhysicsController)
- m_pPhysicsController->RefreshCollisions();
-}
-void KX_GameObject::SetUserCollisionMask(unsigned short mask)
-{
- m_userCollisionMask = mask;
- if (m_pPhysicsController)
- m_pPhysicsController->RefreshCollisions();
-}
-
-unsigned short KX_GameObject::GetUserCollisionGroup()
-{
- return m_userCollisionGroup;
-}
-unsigned short KX_GameObject::GetUserCollisionMask()
-{
- return m_userCollisionMask;
-}
-
-bool KX_GameObject::CheckCollision(KX_GameObject* other)
-{
- return this->m_userCollisionGroup & other->m_userCollisionMask;
-}
-
-CValue* KX_GameObject::GetReplica()
-{
- KX_GameObject* replica = new KX_GameObject(*this);
-
- // this will copy properties and so on...
- replica->ProcessReplica();
-
- return replica;
-}
-
-bool KX_GameObject::IsDynamicsSuspended() const
-{
- if (m_pPhysicsController)
- return m_pPhysicsController->IsSuspended();
- return false;
-}
-
-float KX_GameObject::getLinearDamping() const
-{
- if (m_pPhysicsController)
- return m_pPhysicsController->GetLinearDamping();
- return 0;
-}
-
-float KX_GameObject::getAngularDamping() const
-{
- if (m_pPhysicsController)
- return m_pPhysicsController->GetAngularDamping();
- return 0;
-}
-
-void KX_GameObject::setLinearDamping(float damping)
-{
- if (m_pPhysicsController)
- m_pPhysicsController->SetLinearDamping(damping);
-}
-
-
-void KX_GameObject::setAngularDamping(float damping)
-{
- if (m_pPhysicsController)
- m_pPhysicsController->SetAngularDamping(damping);
-}
-
-
-void KX_GameObject::setDamping(float linear, float angular)
-{
- if (m_pPhysicsController)
- m_pPhysicsController->SetDamping(linear, angular);
-}
-
-
-void KX_GameObject::ApplyForce(const MT_Vector3& force,bool local)
-{
- if (m_pPhysicsController)
- m_pPhysicsController->ApplyForce(force,local);
-}
-
-
-
-void KX_GameObject::ApplyTorque(const MT_Vector3& torque,bool local)
-{
- if (m_pPhysicsController)
- m_pPhysicsController->ApplyTorque(torque,local);
-}
-
-
-
-void KX_GameObject::ApplyMovement(const MT_Vector3& dloc,bool local)
-{
- if (GetSGNode())
- {
- if (m_pPhysicsController) // (IsDynamic())
- {
- m_pPhysicsController->RelativeTranslate(dloc,local);
- }
- GetSGNode()->RelativeTranslate(dloc,GetSGNode()->GetSGParent(),local);
- }
-}
-
-
-
-void KX_GameObject::ApplyRotation(const MT_Vector3& drot,bool local)
-{
- MT_Matrix3x3 rotmat(drot);
-
- if (GetSGNode()) {
- GetSGNode()->RelativeRotate(rotmat,local);
-
- if (m_pPhysicsController) { // (IsDynamic())
- m_pPhysicsController->RelativeRotate(rotmat,local);
- }
- }
-}
-
-
-
-/**
- * GetOpenGL Matrix, returns an OpenGL 'compatible' matrix
- */
-float *KX_GameObject::GetOpenGLMatrix()
-{
- // todo: optimize and only update if necessary
- float *fl = m_OpenGL_4x4Matrix.getPointer();
- if (GetSGNode()) {
- MT_Transform trans;
-
- trans.setOrigin(GetSGNode()->GetWorldPosition());
- trans.setBasis(GetSGNode()->GetWorldOrientation());
-
- MT_Vector3 scaling = GetSGNode()->GetWorldScaling();
- m_bIsNegativeScaling = ((scaling[0] < 0.0f) ^ (scaling[1] < 0.0f) ^ (scaling[2] < 0.0f)) ? true : false;
- trans.scale(scaling[0], scaling[1], scaling[2]);
- trans.getValue(fl);
- GetSGNode()->ClearDirty();
- }
- return fl;
-}
-
-void KX_GameObject::UpdateBlenderObjectMatrix(Object* blendobj)
-{
- if (!blendobj)
- blendobj = m_pBlenderObject;
- if (blendobj) {
- const MT_Matrix3x3& rot = NodeGetWorldOrientation();
- const MT_Vector3& scale = NodeGetWorldScaling();
- const MT_Vector3& pos = NodeGetWorldPosition();
- rot.getValue(blendobj->obmat[0]);
- pos.getValue(blendobj->obmat[3]);
- mul_v3_fl(blendobj->obmat[0], scale[0]);
- mul_v3_fl(blendobj->obmat[1], scale[1]);
- mul_v3_fl(blendobj->obmat[2], scale[2]);
- }
-}
-
-void KX_GameObject::AddMeshUser()
-{
- for (size_t i=0;i<m_meshes.size();i++)
- {
- m_meshes[i]->AddMeshUser(this, &m_meshSlots, GetDeformer());
- }
- // set the part of the mesh slot that never change
- float *fl = GetOpenGLMatrixPtr()->getPointer();
-
- SG_QList::iterator<RAS_MeshSlot> mit(m_meshSlots);
-// RAS_MeshSlot* ms;
- for (mit.begin(); !mit.end(); ++mit)
- {
- (*mit)->m_OpenGLMatrix = fl;
- }
- UpdateBuckets(false);
-}
-
-static void UpdateBuckets_recursive(SG_Node* node)
-{
- NodeList& children = node->GetSGChildren();
-
- for (NodeList::iterator childit = children.begin();!(childit==children.end());++childit)
- {
- SG_Node* childnode = (*childit);
- KX_GameObject *clientgameobj = static_cast<KX_GameObject*>( (*childit)->GetSGClientObject());
- if (clientgameobj != NULL) // This is a GameObject
- clientgameobj->UpdateBuckets(0);
-
- // if the childobj is NULL then this may be an inverse parent link
- // so a non recursive search should still look down this node.
- UpdateBuckets_recursive(childnode);
- }
-}
-
-void KX_GameObject::UpdateBuckets( bool recursive )
-{
- if (GetSGNode()) {
- RAS_MeshSlot *ms;
-
- if (GetSGNode()->IsDirty())
- GetOpenGLMatrix();
-
- SG_QList::iterator<RAS_MeshSlot> mit(m_meshSlots);
- for (mit.begin(); !mit.end(); ++mit)
- {
- ms = *mit;
- ms->m_bObjectColor = m_bUseObjectColor;
- ms->m_RGBAcolor = m_objectColor;
- ms->m_bVisible = m_bVisible;
- ms->m_bCulled = m_bCulled || !m_bVisible;
- if (!ms->m_bCulled)
- ms->m_bucket->ActivateMesh(ms);
-
- /* split if necessary */
-#ifdef USE_SPLIT
- ms->Split();
-#endif
- }
-
- if (recursive) {
- UpdateBuckets_recursive(GetSGNode());
- }
- }
-}
-
-void KX_GameObject::RemoveMeshes()
-{
- for (size_t i=0;i<m_meshes.size();i++)
- m_meshes[i]->RemoveFromBuckets(this);
-
- //note: meshes can be shared, and are deleted by KX_BlenderSceneConverter
-
- m_meshes.clear();
-}
-
-void KX_GameObject::AddLodMesh(RAS_MeshObject* mesh)
-{
- m_lodmeshes.push_back(mesh);
-}
-
-
-static float calcHysteresis(KX_Scene *kxscene, LodLevel *lod)
-{
- float hystvariance = 0.0f;
-
- if (!kxscene->IsActivedLodHysteresis())
- return hystvariance;
-
- short hysteresis = 0;
- // if exists, LoD level hysteresis will override scene hysteresis
- if (lod->next->flags & OB_LOD_USE_HYST)
- hysteresis = lod->next->obhysteresis;
- else
- hysteresis = kxscene->GetLodHysteresisValue();
-
- return hystvariance = MT_abs(lod->next->distance - lod->distance) * hysteresis / 100;
-}
-
-void KX_GameObject::UpdateLod(MT_Vector3 &cam_pos)
-{
- // Handle dupligroups
- if (m_pInstanceObjects) {
- KX_GameObject *instob;
- int count = m_pInstanceObjects->GetCount();
- for (int i = 0; i < count; i++) {
- instob = (KX_GameObject*)m_pInstanceObjects->GetValue(i);
- instob->UpdateLod(cam_pos);
- }
- }
-
- if (m_lodmeshes.empty())
- return;
-
- MT_Vector3 delta = NodeGetWorldPosition() - cam_pos;
- float distance2 = delta.length2();
-
- int level = 0;
- float hystvariance = 0.0f;
- Object *bob = GetBlenderObject();
- LodLevel *lod = (LodLevel *)bob->lodlevels.first;
- KX_Scene *kxscene = GetScene();
-
- for (; lod; lod = lod->next, level++) {
- if (!lod->source || lod->source->type != OB_MESH)
- level--;
-
- if (!lod->next)
- break;
-
- if (level == m_previousLodLevel || level == (m_previousLodLevel + 1)) {
- hystvariance = calcHysteresis(kxscene, lod);
- float newdistance = lod->next->distance + hystvariance;
- if (newdistance * newdistance > distance2)
- break;
- }
- else if (level == (m_previousLodLevel - 1)) {
- hystvariance = calcHysteresis(kxscene, lod);
- float newdistance = lod->next->distance - hystvariance;
- if (newdistance * newdistance > distance2)
- break;
- }
- }
-
- RAS_MeshObject *mesh = m_lodmeshes[level];
- m_currentLodLevel = level;
- if (mesh != m_meshes[0]) {
- m_previousLodLevel = level;
- GetScene()->ReplaceMesh(this, mesh, true, false);
- }
-}
-
-void KX_GameObject::UpdateTransform()
-{
- // HACK: saves function call for dynamic object, they are handled differently
- if (m_pPhysicsController && !m_pPhysicsController->IsDynamic())
- m_pPhysicsController->SetTransform();
- if (m_pGraphicController)
- // update the culling tree
- m_pGraphicController->SetGraphicTransform();
-
-}
-
-void KX_GameObject::UpdateTransformFunc(SG_IObject* node, void* gameobj, void* scene)
-{
- ((KX_GameObject*)gameobj)->UpdateTransform();
-}
-
-void KX_GameObject::SynchronizeTransform()
-{
- // only used for sensor object, do full synchronization as bullet doesn't do it
- if (m_pPhysicsController)
- m_pPhysicsController->SetTransform();
- if (m_pGraphicController)
- m_pGraphicController->SetGraphicTransform();
-}
-
-void KX_GameObject::SynchronizeTransformFunc(SG_IObject* node, void* gameobj, void* scene)
-{
- ((KX_GameObject*)gameobj)->SynchronizeTransform();
-}
-
-
-void KX_GameObject::SetDebugColor(unsigned int bgra)
-{
- for (size_t i=0;i<m_meshes.size();i++)
- m_meshes[i]->DebugColor(bgra);
-}
-
-
-
-void KX_GameObject::ResetDebugColor()
-{
- SetDebugColor(0xff000000);
-}
-
-void KX_GameObject::InitIPO(bool ipo_as_force,
- bool ipo_add,
- bool ipo_local)
-{
- SGControllerList::iterator it = GetSGNode()->GetSGControllerList().begin();
-
- while (it != GetSGNode()->GetSGControllerList().end()) {
- (*it)->SetOption(SG_Controller::SG_CONTR_IPO_RESET, true);
- (*it)->SetOption(SG_Controller::SG_CONTR_IPO_IPO_AS_FORCE, ipo_as_force);
- (*it)->SetOption(SG_Controller::SG_CONTR_IPO_IPO_ADD, ipo_add);
- (*it)->SetOption(SG_Controller::SG_CONTR_IPO_LOCAL, ipo_local);
- it++;
- }
-}
-
-void KX_GameObject::UpdateIPO(float curframetime,
- bool recurse)
-{
- /* This function shouldn't call BL_Action::Update, not even indirectly,
- * as it will cause deadlock due to the lock in BL_Action::Update. */
-
- // just the 'normal' update procedure.
- GetSGNode()->SetSimulatedTime(curframetime,recurse);
- GetSGNode()->UpdateWorldData(curframetime);
- UpdateTransform();
-}
-
-// IPO update
-void
-KX_GameObject::UpdateMaterialData(
- dword matname_hash,
- MT_Vector4 rgba,
- MT_Vector3 specrgb,
- MT_Scalar hard,
- MT_Scalar spec,
- MT_Scalar ref,
- MT_Scalar emit,
- MT_Scalar alpha
-
- )
-{
- int mesh = 0;
- if (((unsigned int)mesh < m_meshes.size()) && mesh >= 0) {
- list<RAS_MeshMaterial>::iterator mit = m_meshes[mesh]->GetFirstMaterial();
-
- for (; mit != m_meshes[mesh]->GetLastMaterial(); ++mit)
- {
- RAS_IPolyMaterial* poly = mit->m_bucket->GetPolyMaterial();
-
- if (poly->GetFlag() & RAS_BLENDERMAT )
- {
- KX_BlenderMaterial *m = static_cast<KX_BlenderMaterial*>(poly);
-
- if (matname_hash == 0)
- {
- m->UpdateIPO(rgba, specrgb,hard,spec,ref,emit, alpha);
- // if mesh has only one material attached to it then use original hack with no need to edit vertices (better performance)
- SetObjectColor(rgba);
- }
- else
- {
- if (matname_hash == poly->GetMaterialNameHash())
- {
- m->UpdateIPO(rgba, specrgb,hard,spec,ref,emit, alpha);
- m_meshes[mesh]->SetVertexColor(poly,rgba);
-
- // no break here, because one blender material can be split into several game engine materials
- // (e.g. one uvsphere material is split into one material at poles with ras_mode TRIANGLE and one material for the body
- // if here was a break then would miss some vertices if material was split
- }
- }
- }
- }
- }
-}
-bool
-KX_GameObject::GetVisible(
- void
- )
-{
- return m_bVisible;
-}
-
-static void setVisible_recursive(SG_Node* node, bool v)
-{
- NodeList& children = node->GetSGChildren();
-
- for (NodeList::iterator childit = children.begin();!(childit==children.end());++childit)
- {
- SG_Node* childnode = (*childit);
- KX_GameObject *clientgameobj = static_cast<KX_GameObject*>( (*childit)->GetSGClientObject());
- if (clientgameobj != NULL) // This is a GameObject
- clientgameobj->SetVisible(v, 0);
-
- // if the childobj is NULL then this may be an inverse parent link
- // so a non recursive search should still look down this node.
- setVisible_recursive(childnode, v);
- }
-}
-
-
-void
-KX_GameObject::SetVisible(
- bool v,
- bool recursive
- )
-{
- if (GetSGNode()) {
- m_bVisible = v;
- if (m_pGraphicController)
- m_pGraphicController->Activate(m_bVisible);
- if (recursive)
- setVisible_recursive(GetSGNode(), v);
- }
-}
-
-static void setOccluder_recursive(SG_Node* node, bool v)
-{
- NodeList& children = node->GetSGChildren();
-
- for (NodeList::iterator childit = children.begin();!(childit==children.end());++childit)
- {
- SG_Node* childnode = (*childit);
- KX_GameObject *clientgameobj = static_cast<KX_GameObject*>( (*childit)->GetSGClientObject());
- if (clientgameobj != NULL) // This is a GameObject
- clientgameobj->SetOccluder(v, false);
-
- // if the childobj is NULL then this may be an inverse parent link
- // so a non recursive search should still look down this node.
- setOccluder_recursive(childnode, v);
- }
-}
-
-void
-KX_GameObject::SetOccluder(
- bool v,
- bool recursive
- )
-{
- if (GetSGNode()) {
- m_bOccluder = v;
- if (recursive)
- setOccluder_recursive(GetSGNode(), v);
- }
-}
-
-static void setDebug_recursive(SG_Node *node, bool debug)
-{
- NodeList& children = node->GetSGChildren();
- KX_Scene *scene = KX_GetActiveScene();
-
- for (NodeList::iterator childit = children.begin();!(childit==children.end());++childit) {
- SG_Node *childnode = (*childit);
- KX_GameObject *clientgameobj = static_cast<KX_GameObject*>( (*childit)->GetSGClientObject());
- if (clientgameobj != NULL) {
- if (debug) {
- if (!scene->ObjectInDebugList(clientgameobj))
- scene->AddObjectDebugProperties(clientgameobj);
- }
- else
- scene->RemoveObjectDebugProperties(clientgameobj);
- }
-
- /* if the childobj is NULL then this may be an inverse parent link
- * so a non recursive search should still look down this node. */
- setDebug_recursive(childnode, debug);
- }
-}
-
-void KX_GameObject::SetUseDebugProperties( bool debug, bool recursive )
-{
- KX_Scene *scene = KX_GetActiveScene();
-
- if (debug) {
- if (!scene->ObjectInDebugList(this))
- scene->AddObjectDebugProperties(this);
- }
- else
- scene->RemoveObjectDebugProperties(this);
-
- if (recursive)
- setDebug_recursive(GetSGNode(), debug);
-}
-
-void
-KX_GameObject::SetLayer(
- int l
- )
-{
- m_layer = l;
-}
-
-int
-KX_GameObject::GetLayer(
- void
- )
-{
- return m_layer;
-}
-
-void KX_GameObject::addLinearVelocity(const MT_Vector3& lin_vel,bool local)
-{
- if (m_pPhysicsController)
- {
- MT_Vector3 lv = local ? NodeGetWorldOrientation() * lin_vel : lin_vel;
- m_pPhysicsController->SetLinearVelocity(lv + m_pPhysicsController->GetLinearVelocity(), 0);
- }
-}
-
-
-
-void KX_GameObject::setLinearVelocity(const MT_Vector3& lin_vel,bool local)
-{
- if (m_pPhysicsController)
- m_pPhysicsController->SetLinearVelocity(lin_vel,local);
-}
-
-
-
-void KX_GameObject::setAngularVelocity(const MT_Vector3& ang_vel,bool local)
-{
- if (m_pPhysicsController)
- m_pPhysicsController->SetAngularVelocity(ang_vel,local);
-}
-
-
-void KX_GameObject::ResolveCombinedVelocities(
- const MT_Vector3 & lin_vel,
- const MT_Vector3 & ang_vel,
- bool lin_vel_local,
- bool ang_vel_local
-) {
- if (m_pPhysicsController)
- {
-
- MT_Vector3 lv = lin_vel_local ? NodeGetWorldOrientation() * lin_vel : lin_vel;
- MT_Vector3 av = ang_vel_local ? NodeGetWorldOrientation() * ang_vel : ang_vel;
- m_pPhysicsController->ResolveCombinedVelocities(
- lv.x(),lv.y(),lv.z(),av.x(),av.y(),av.z());
- }
-}
-
-
-void KX_GameObject::SetObjectColor(const MT_Vector4& rgbavec)
-{
- m_bUseObjectColor = true;
- m_objectColor = rgbavec;
-}
-
-const MT_Vector4& KX_GameObject::GetObjectColor()
-{
- return m_objectColor;
-}
-
-void KX_GameObject::AlignAxisToVect(const MT_Vector3& dir, int axis, float fac)
-{
- const MT_Scalar eps = 3.0f * MT_EPSILON;
- MT_Matrix3x3 orimat;
- MT_Vector3 vect,ori,z,x,y;
- MT_Scalar len;
-
- // check on valid node in case a python controller holds a reference to a deleted object
- if (!GetSGNode())
- return;
-
- vect = dir;
- len = vect.length();
- if (MT_fuzzyZero(len))
- {
- cout << "alignAxisToVect() Error: Null vector!\n";
- return;
- }
-
- if (fac <= 0.0f) {
- return;
- }
-
- // normalize
- vect /= len;
- orimat = GetSGNode()->GetWorldOrientation();
- switch (axis)
- {
- case 0: // align x axis of new coord system to vect
- ori.setValue(orimat[0][2], orimat[1][2], orimat[2][2]); // pivot axis
- if (1.0f - MT_abs(vect.dot(ori)) < eps) { // vect parallel to pivot?
- ori.setValue(orimat[0][1], orimat[1][1], orimat[2][1]); // change the pivot!
- }
-
- if (fac == 1.0f) {
- x = vect;
- } else {
- x = (vect * fac) + ((orimat * MT_Vector3(1.0f, 0.0f, 0.0f)) * (1.0f - fac));
- len = x.length();
- if (MT_fuzzyZero(len)) x = vect;
- else x /= len;
- }
- y = ori.cross(x);
- z = x.cross(y);
- break;
- case 1: // y axis
- ori.setValue(orimat[0][0], orimat[1][0], orimat[2][0]);
- if (1.0f - MT_abs(vect.dot(ori)) < eps) {
- ori.setValue(orimat[0][2], orimat[1][2], orimat[2][2]);
- }
-
- if (fac == 1.0f) {
- y = vect;
- } else {
- y = (vect * fac) + ((orimat * MT_Vector3(0.0f, 1.0f, 0.0f)) * (1.0f - fac));
- len = y.length();
- if (MT_fuzzyZero(len)) y = vect;
- else y /= len;
- }
- z = ori.cross(y);
- x = y.cross(z);
- break;
- case 2: // z axis
- ori.setValue(orimat[0][1], orimat[1][1], orimat[2][1]);
- if (1.0f - MT_abs(vect.dot(ori)) < eps) {
- ori.setValue(orimat[0][0], orimat[1][0], orimat[2][0]);
- }
-
- if (fac == 1.0f) {
- z = vect;
- } else {
- z = (vect * fac) + ((orimat * MT_Vector3(0.0f, 0.0f, 1.0f)) * (1.0f - fac));
- len = z.length();
- if (MT_fuzzyZero(len)) z = vect;
- else z /= len;
- }
- x = ori.cross(z);
- y = z.cross(x);
- break;
- default: // invalid axis specified
- cout << "alignAxisToVect(): Invalid axis '" << axis <<"'\n";
- return;
- }
- x.normalize(); // normalize the new base vectors
- y.normalize();
- z.normalize();
- orimat.setValue(x[0], y[0], z[0],
- x[1], y[1], z[1],
- x[2], y[2], z[2]);
-
- if (GetSGNode()->GetSGParent() != NULL)
- {
- // the object is a child, adapt its local orientation so that
- // the global orientation is aligned as we want (cancelling out the parent orientation)
- MT_Matrix3x3 invori = GetSGNode()->GetSGParent()->GetWorldOrientation().inverse();
- NodeSetLocalOrientation(invori*orimat);
- }
- else {
- NodeSetLocalOrientation(orimat);
- }
-}
-
-MT_Scalar KX_GameObject::GetMass()
-{
- if (m_pPhysicsController)
- {
- return m_pPhysicsController->GetMass();
- }
- return 0.0f;
-}
-
-MT_Vector3 KX_GameObject::GetLocalInertia()
-{
- MT_Vector3 local_inertia(0.0f,0.0f,0.0f);
- if (m_pPhysicsController)
- {
- local_inertia = m_pPhysicsController->GetLocalInertia();
- }
- return local_inertia;
-}
-
-MT_Vector3 KX_GameObject::GetLinearVelocity(bool local)
-{
- MT_Vector3 velocity(0.0f,0.0f,0.0f), locvel;
- MT_Matrix3x3 ori;
- if (m_pPhysicsController)
- {
- velocity = m_pPhysicsController->GetLinearVelocity();
-
- if (local)
- {
- ori = GetSGNode()->GetWorldOrientation();
-
- locvel = velocity * ori;
- return locvel;
- }
- }
- return velocity;
-}
-
-MT_Vector3 KX_GameObject::GetAngularVelocity(bool local)
-{
- MT_Vector3 velocity(0.0f,0.0f,0.0f), locvel;
- MT_Matrix3x3 ori;
- if (m_pPhysicsController)
- {
- velocity = m_pPhysicsController->GetAngularVelocity();
-
- if (local)
- {
- ori = GetSGNode()->GetWorldOrientation();
-
- locvel = velocity * ori;
- return locvel;
- }
- }
- return velocity;
-}
-
-MT_Vector3 KX_GameObject::GetVelocity(const MT_Point3& point)
-{
- if (m_pPhysicsController)
- {
- return m_pPhysicsController->GetVelocity(point);
- }
- return MT_Vector3(0.0f,0.0f,0.0f);
-}
-
-// scenegraph node stuff
-
-void KX_GameObject::NodeSetLocalPosition(const MT_Point3& trans)
-{
- // check on valid node in case a python controller holds a reference to a deleted object
- if (!GetSGNode())
- return;
-
- if (m_pPhysicsController && !GetSGNode()->GetSGParent())
- {
- // don't update physic controller if the object is a child:
- // 1) the transformation will not be right
- // 2) in this case, the physic controller is necessarily a static object
- // that is updated from the normal kinematic synchronization
- m_pPhysicsController->SetPosition(trans);
- }
-
- GetSGNode()->SetLocalPosition(trans);
-
-}
-
-
-
-void KX_GameObject::NodeSetLocalOrientation(const MT_Matrix3x3& rot)
-{
- // check on valid node in case a python controller holds a reference to a deleted object
- if (!GetSGNode())
- return;
-
- if (m_pPhysicsController && !GetSGNode()->GetSGParent())
- {
- // see note above
- m_pPhysicsController->SetOrientation(rot);
- }
- GetSGNode()->SetLocalOrientation(rot);
-}
-
-void KX_GameObject::NodeSetGlobalOrientation(const MT_Matrix3x3& rot)
-{
- // check on valid node in case a python controller holds a reference to a deleted object
- if (!GetSGNode())
- return;
-
- if (GetSGNode()->GetSGParent())
- GetSGNode()->SetLocalOrientation(GetSGNode()->GetSGParent()->GetWorldOrientation().inverse()*rot);
- else
- NodeSetLocalOrientation(rot);
-}
-
-void KX_GameObject::NodeSetLocalScale(const MT_Vector3& scale)
-{
- // check on valid node in case a python controller holds a reference to a deleted object
- if (!GetSGNode())
- return;
-
- if (m_pPhysicsController && !GetSGNode()->GetSGParent())
- {
- // see note above
- m_pPhysicsController->SetScaling(scale);
- }
- GetSGNode()->SetLocalScale(scale);
-}
-
-
-
-void KX_GameObject::NodeSetRelativeScale(const MT_Vector3& scale)
-{
- if (GetSGNode())
- {
- GetSGNode()->RelativeScale(scale);
- if (m_pPhysicsController && (!GetSGNode()->GetSGParent()))
- {
- // see note above
- // we can use the local scale: it's the same thing for a root object
- // and the world scale is not yet updated
- MT_Vector3 newscale = GetSGNode()->GetLocalScale();
- m_pPhysicsController->SetScaling(newscale);
- }
- }
-}
-
-void KX_GameObject::NodeSetWorldScale(const MT_Vector3& scale)
-{
- if (!GetSGNode())
- return;
- SG_Node* parent = GetSGNode()->GetSGParent();
- if (parent != NULL)
- {
- // Make sure the objects have some scale
- MT_Vector3 p_scale = parent->GetWorldScaling();
- if (fabs(p_scale[0]) < (MT_Scalar)FLT_EPSILON ||
- fabs(p_scale[1]) < (MT_Scalar)FLT_EPSILON ||
- fabs(p_scale[2]) < (MT_Scalar)FLT_EPSILON)
- {
- return;
- }
-
- p_scale[0] = 1/p_scale[0];
- p_scale[1] = 1/p_scale[1];
- p_scale[2] = 1/p_scale[2];
-
- NodeSetLocalScale(scale * p_scale);
- }
- else
- {
- NodeSetLocalScale(scale);
- }
-}
-
-void KX_GameObject::NodeSetWorldPosition(const MT_Point3& trans)
-{
- if (!GetSGNode())
- return;
- SG_Node* parent = GetSGNode()->GetSGParent();
- if (parent != NULL)
- {
- // Make sure the objects have some scale
- MT_Vector3 scale = parent->GetWorldScaling();
- if (fabs(scale[0]) < (MT_Scalar)FLT_EPSILON ||
- fabs(scale[1]) < (MT_Scalar)FLT_EPSILON ||
- fabs(scale[2]) < (MT_Scalar)FLT_EPSILON)
- {
- return;
- }
- scale[0] = 1.0f/scale[0];
- scale[1] = 1.0f/scale[1];
- scale[2] = 1.0f/scale[2];
- MT_Matrix3x3 invori = parent->GetWorldOrientation().inverse();
- MT_Vector3 newpos = invori*(trans-parent->GetWorldPosition())*scale;
- NodeSetLocalPosition(MT_Point3(newpos[0],newpos[1],newpos[2]));
- }
- else
- {
- NodeSetLocalPosition(trans);
- }
-}
-
-
-void KX_GameObject::NodeUpdateGS(double time)
-{
- if (GetSGNode())
- GetSGNode()->UpdateWorldData(time);
-}
-
-
-
-const MT_Matrix3x3& KX_GameObject::NodeGetWorldOrientation() const
-{
- // check on valid node in case a python controller holds a reference to a deleted object
- if (!GetSGNode())
- return dummy_orientation;
- return GetSGNode()->GetWorldOrientation();
-}
-
-const MT_Matrix3x3& KX_GameObject::NodeGetLocalOrientation() const
-{
- // check on valid node in case a python controller holds a reference to a deleted object
- if (!GetSGNode())
- return dummy_orientation;
- return GetSGNode()->GetLocalOrientation();
-}
-
-const MT_Vector3& KX_GameObject::NodeGetWorldScaling() const
-{
- // check on valid node in case a python controller holds a reference to a deleted object
- if (!GetSGNode())
- return dummy_scaling;
-
- return GetSGNode()->GetWorldScaling();
-}
-
-const MT_Vector3& KX_GameObject::NodeGetLocalScaling() const
-{
- // check on valid node in case a python controller holds a reference to a deleted object
- if (!GetSGNode())
- return dummy_scaling;
-
- return GetSGNode()->GetLocalScale();
-}
-
-const MT_Point3& KX_GameObject::NodeGetWorldPosition() const
-{
- // check on valid node in case a python controller holds a reference to a deleted object
- if (GetSGNode())
- return GetSGNode()->GetWorldPosition();
- else
- return dummy_point;
-}
-
-const MT_Point3& KX_GameObject::NodeGetLocalPosition() const
-{
- // check on valid node in case a python controller holds a reference to a deleted object
- if (GetSGNode())
- return GetSGNode()->GetLocalPosition();
- else
- return dummy_point;
-}
-
-
-void KX_GameObject::UnregisterCollisionCallbacks()
-{
- if (!GetPhysicsController()) {
- printf("Warning, trying to unregister collision callbacks for object without collisions: %s!\n", GetName().ReadPtr());
- return;
- }
-
- // Unregister from callbacks
- KX_Scene* scene = GetScene();
- PHY_IPhysicsEnvironment* pe = scene->GetPhysicsEnvironment();
- PHY_IPhysicsController* spc = GetPhysicsController();
- // If we are the last to unregister on this physics controller
- if (pe->RemoveCollisionCallback(spc)) {
- // If we are a sensor object
- if (m_pClient_info->isSensor())
- // Remove sensor body from physics world
- pe->RemoveSensor(spc);
- }
-}
-
-void KX_GameObject::RegisterCollisionCallbacks()
-{
- if (!GetPhysicsController()) {
- printf("Warning, trying to register collision callbacks for object without collisions: %s!\n", GetName().ReadPtr());
- return;
- }
-
- // Register from callbacks
- KX_Scene* scene = GetScene();
- PHY_IPhysicsEnvironment* pe = scene->GetPhysicsEnvironment();
- PHY_IPhysicsController* spc = GetPhysicsController();
- // If we are the first to register on this physics controller
- if (pe->RequestCollisionCallback(spc)) {
- // If we are a sensor object
- if (m_pClient_info->isSensor())
- // Add sensor body to physics world
- pe->AddSensor(spc);
- }
-}
-void KX_GameObject::RunCollisionCallbacks(KX_GameObject *collider, const MT_Vector3 &point, const MT_Vector3 &normal)
-{
-#ifdef WITH_PYTHON
- if (!m_collisionCallbacks || PyList_GET_SIZE(m_collisionCallbacks) == 0)
- return;
-
- PyObject *args[] = {collider->GetProxy(), PyObjectFrom(point), PyObjectFrom(normal)};
- RunPythonCallBackList(m_collisionCallbacks, args, 1, ARRAY_SIZE(args));
-
- for (unsigned int i = 0; i < ARRAY_SIZE(args); ++i) {
- Py_DECREF(args[i]);
- }
-#endif
-}
-
-/* Suspend/ resume: for the dynamic behavior, there is a simple
- * method. For the residual motion, there is not. I wonder what the
- * correct solution is for Sumo. Remove from the motion-update tree?
- *
- * So far, only switch the physics and logic.
- * */
-
-void KX_GameObject::Resume(void)
-{
- if (m_suspended) {
- SCA_IObject::Resume();
- // Child objects must be static, so we block changing to dynamic
- if (GetPhysicsController() && !GetParent())
- GetPhysicsController()->RestoreDynamics();
-
- m_suspended = false;
- }
-}
-
-void KX_GameObject::Suspend()
-{
- if ((!m_ignore_activity_culling) && (!m_suspended)) {
- SCA_IObject::Suspend();
- if (GetPhysicsController())
- GetPhysicsController()->SuspendDynamics();
- m_suspended = true;
- }
-}
-
-static void walk_children(SG_Node* node, CListValue* list, bool recursive)
-{
- if (!node)
- return;
- NodeList& children = node->GetSGChildren();
-
- for (NodeList::iterator childit = children.begin();!(childit==children.end());++childit)
- {
- SG_Node* childnode = (*childit);
- CValue* childobj = (CValue*)childnode->GetSGClientObject();
- if (childobj != NULL) // This is a GameObject
- {
- // add to the list
- list->Add(childobj->AddRef());
- }
-
- // if the childobj is NULL then this may be an inverse parent link
- // so a non recursive search should still look down this node.
- if (recursive || childobj==NULL) {
- walk_children(childnode, list, recursive);
- }
- }
-}
-
-CListValue* KX_GameObject::GetChildren()
-{
- CListValue* list = new CListValue();
- walk_children(GetSGNode(), list, 0); /* GetSGNode() is always valid or it would have raised an exception before this */
- return list;
-}
-
-CListValue* KX_GameObject::GetChildrenRecursive()
-{
- CListValue* list = new CListValue();
- walk_children(GetSGNode(), list, 1);
- return list;
-}
-
-KX_Scene* KX_GameObject::GetScene()
-{
- SG_Node* node = this->GetSGNode();
- if (node == NULL) {
- // this happens for object in non active layers, rely on static scene then
- return KX_GetActiveScene();
- }
- return static_cast<KX_Scene*>(node->GetSGClientInfo());
-}
-
-/* ---------------------------------------------------------------------
- * Some stuff taken from the header
- * --------------------------------------------------------------------- */
-void KX_GameObject::Relink(CTR_Map<CTR_HashedPtr, void*> *map_parameter)
-{
- // we will relink the sensors and actuators that use object references
- // if the object is part of the replicated hierarchy, use the new
- // object reference instead
- SCA_SensorList& sensorlist = GetSensors();
- SCA_SensorList::iterator sit;
- for (sit=sensorlist.begin(); sit != sensorlist.end(); sit++)
- {
- (*sit)->Relink(map_parameter);
- }
- SCA_ActuatorList& actuatorlist = GetActuators();
- SCA_ActuatorList::iterator ait;
- for (ait=actuatorlist.begin(); ait != actuatorlist.end(); ait++)
- {
- (*ait)->Relink(map_parameter);
- }
-}
-
-#ifdef USE_MATHUTILS
-
-/* These require an SGNode */
-#define MATHUTILS_VEC_CB_POS_LOCAL 1
-#define MATHUTILS_VEC_CB_POS_GLOBAL 2
-#define MATHUTILS_VEC_CB_SCALE_LOCAL 3
-#define MATHUTILS_VEC_CB_SCALE_GLOBAL 4
-#define MATHUTILS_VEC_CB_INERTIA_LOCAL 5
-#define MATHUTILS_VEC_CB_OBJECT_COLOR 6
-#define MATHUTILS_VEC_CB_LINVEL_LOCAL 7
-#define MATHUTILS_VEC_CB_LINVEL_GLOBAL 8
-#define MATHUTILS_VEC_CB_ANGVEL_LOCAL 9
-#define MATHUTILS_VEC_CB_ANGVEL_GLOBAL 10
-
-static unsigned char mathutils_kxgameob_vector_cb_index= -1; /* index for our callbacks */
-
-static int mathutils_kxgameob_generic_check(BaseMathObject *bmo)
-{
- KX_GameObject* self = static_cast<KX_GameObject*>BGE_PROXY_REF(bmo->cb_user);
- if (self == NULL)
- return -1;
-
- return 0;
-}
-
-static int mathutils_kxgameob_vector_get(BaseMathObject *bmo, int subtype)
-{
- KX_GameObject* self = static_cast<KX_GameObject*>BGE_PROXY_REF(bmo->cb_user);
- if (self == NULL)
- return -1;
-
-#define PHYS_ERR(attr) PyErr_SetString(PyExc_AttributeError, "KX_GameObject." attr ", is missing a physics controller")
-
- switch (subtype) {
- case MATHUTILS_VEC_CB_POS_LOCAL:
- self->NodeGetLocalPosition().getValue(bmo->data);
- break;
- case MATHUTILS_VEC_CB_POS_GLOBAL:
- self->NodeGetWorldPosition().getValue(bmo->data);
- break;
- case MATHUTILS_VEC_CB_SCALE_LOCAL:
- self->NodeGetLocalScaling().getValue(bmo->data);
- break;
- case MATHUTILS_VEC_CB_SCALE_GLOBAL:
- self->NodeGetWorldScaling().getValue(bmo->data);
- break;
- case MATHUTILS_VEC_CB_INERTIA_LOCAL:
- if (!self->GetPhysicsController()) return PHYS_ERR("localInertia"), -1;
- self->GetPhysicsController()->GetLocalInertia().getValue(bmo->data);
- break;
- case MATHUTILS_VEC_CB_OBJECT_COLOR:
- self->GetObjectColor().getValue(bmo->data);
- break;
- case MATHUTILS_VEC_CB_LINVEL_LOCAL:
- if (!self->GetPhysicsController()) return PHYS_ERR("localLinearVelocity"), -1;
- self->GetLinearVelocity(true).getValue(bmo->data);
- break;
- case MATHUTILS_VEC_CB_LINVEL_GLOBAL:
- if (!self->GetPhysicsController()) return PHYS_ERR("worldLinearVelocity"), -1;
- self->GetLinearVelocity(false).getValue(bmo->data);
- break;
- case MATHUTILS_VEC_CB_ANGVEL_LOCAL:
- if (!self->GetPhysicsController()) return PHYS_ERR("localLinearVelocity"), -1;
- self->GetAngularVelocity(true).getValue(bmo->data);
- break;
- case MATHUTILS_VEC_CB_ANGVEL_GLOBAL:
- if (!self->GetPhysicsController()) return PHYS_ERR("worldLinearVelocity"), -1;
- self->GetAngularVelocity(false).getValue(bmo->data);
- break;
-
- }
-
-#undef PHYS_ERR
-
- return 0;
-}
-
-static int mathutils_kxgameob_vector_set(BaseMathObject *bmo, int subtype)
-{
- KX_GameObject* self = static_cast<KX_GameObject*>BGE_PROXY_REF(bmo->cb_user);
- if (self == NULL)
- return -1;
-
- switch (subtype) {
- case MATHUTILS_VEC_CB_POS_LOCAL:
- self->NodeSetLocalPosition(MT_Point3(bmo->data));
- self->NodeUpdateGS(0.f);
- break;
- case MATHUTILS_VEC_CB_POS_GLOBAL:
- self->NodeSetWorldPosition(MT_Point3(bmo->data));
- self->NodeUpdateGS(0.f);
- break;
- case MATHUTILS_VEC_CB_SCALE_LOCAL:
- self->NodeSetLocalScale(MT_Point3(bmo->data));
- self->NodeUpdateGS(0.f);
- break;
- case MATHUTILS_VEC_CB_SCALE_GLOBAL:
- PyErr_SetString(PyExc_AttributeError, "KX_GameObject.worldScale is read-only");
- return -1;
- case MATHUTILS_VEC_CB_INERTIA_LOCAL:
- /* read only */
- break;
- case MATHUTILS_VEC_CB_OBJECT_COLOR:
- self->SetObjectColor(MT_Vector4(bmo->data));
- break;
- case MATHUTILS_VEC_CB_LINVEL_LOCAL:
- self->setLinearVelocity(MT_Point3(bmo->data),true);
- break;
- case MATHUTILS_VEC_CB_LINVEL_GLOBAL:
- self->setLinearVelocity(MT_Point3(bmo->data),false);
- break;
- case MATHUTILS_VEC_CB_ANGVEL_LOCAL:
- self->setAngularVelocity(MT_Point3(bmo->data),true);
- break;
- case MATHUTILS_VEC_CB_ANGVEL_GLOBAL:
- self->setAngularVelocity(MT_Point3(bmo->data),false);
- break;
- }
-
- return 0;
-}
-
-static int mathutils_kxgameob_vector_get_index(BaseMathObject *bmo, int subtype, int index)
-{
- /* lazy, avoid repeteing the case statement */
- if (mathutils_kxgameob_vector_get(bmo, subtype) == -1)
- return -1;
- return 0;
-}
-
-static int mathutils_kxgameob_vector_set_index(BaseMathObject *bmo, int subtype, int index)
-{
- float f= bmo->data[index];
-
- /* lazy, avoid repeteing the case statement */
- if (mathutils_kxgameob_vector_get(bmo, subtype) == -1)
- return -1;
-
- bmo->data[index] = f;
- return mathutils_kxgameob_vector_set(bmo, subtype);
-}
-
-static Mathutils_Callback mathutils_kxgameob_vector_cb = {
- mathutils_kxgameob_generic_check,
- mathutils_kxgameob_vector_get,
- mathutils_kxgameob_vector_set,
- mathutils_kxgameob_vector_get_index,
- mathutils_kxgameob_vector_set_index
-};
-
-/* Matrix */
-#define MATHUTILS_MAT_CB_ORI_LOCAL 1
-#define MATHUTILS_MAT_CB_ORI_GLOBAL 2
-
-static unsigned char mathutils_kxgameob_matrix_cb_index= -1; /* index for our callbacks */
-
-static int mathutils_kxgameob_matrix_get(BaseMathObject *bmo, int subtype)
-{
- KX_GameObject* self = static_cast<KX_GameObject*>BGE_PROXY_REF(bmo->cb_user);
- if (self == NULL)
- return -1;
-
- switch (subtype) {
- case MATHUTILS_MAT_CB_ORI_LOCAL:
- self->NodeGetLocalOrientation().getValue3x3(bmo->data);
- break;
- case MATHUTILS_MAT_CB_ORI_GLOBAL:
- self->NodeGetWorldOrientation().getValue3x3(bmo->data);
- break;
- }
-
- return 0;
-}
-
-
-static int mathutils_kxgameob_matrix_set(BaseMathObject *bmo, int subtype)
-{
- KX_GameObject* self = static_cast<KX_GameObject*>BGE_PROXY_REF(bmo->cb_user);
- if (self == NULL)
- return -1;
-
- MT_Matrix3x3 mat3x3;
- switch (subtype) {
- case MATHUTILS_MAT_CB_ORI_LOCAL:
- mat3x3.setValue3x3(bmo->data);
- self->NodeSetLocalOrientation(mat3x3);
- self->NodeUpdateGS(0.f);
- break;
- case MATHUTILS_MAT_CB_ORI_GLOBAL:
- mat3x3.setValue3x3(bmo->data);
- self->NodeSetLocalOrientation(mat3x3);
- self->NodeUpdateGS(0.f);
- break;
- }
-
- return 0;
-}
-
-static Mathutils_Callback mathutils_kxgameob_matrix_cb = {
- mathutils_kxgameob_generic_check,
- mathutils_kxgameob_matrix_get,
- mathutils_kxgameob_matrix_set,
- NULL,
- NULL
-};
-
-
-void KX_GameObject_Mathutils_Callback_Init(void)
-{
- // register mathutils callbacks, ok to run more than once.
- mathutils_kxgameob_vector_cb_index= Mathutils_RegisterCallback(&mathutils_kxgameob_vector_cb);
- mathutils_kxgameob_matrix_cb_index= Mathutils_RegisterCallback(&mathutils_kxgameob_matrix_cb);
-}
-
-#endif // USE_MATHUTILS
-
-#ifdef WITH_PYTHON
-/* ------- python stuff ---------------------------------------------------*/
-PyMethodDef KX_GameObject::Methods[] = {
- {"applyForce", (PyCFunction) KX_GameObject::sPyApplyForce, METH_VARARGS},
- {"applyTorque", (PyCFunction) KX_GameObject::sPyApplyTorque, METH_VARARGS},
- {"applyRotation", (PyCFunction) KX_GameObject::sPyApplyRotation, METH_VARARGS},
- {"applyMovement", (PyCFunction) KX_GameObject::sPyApplyMovement, METH_VARARGS},
- {"getLinearVelocity", (PyCFunction) KX_GameObject::sPyGetLinearVelocity, METH_VARARGS},
- {"setLinearVelocity", (PyCFunction) KX_GameObject::sPySetLinearVelocity, METH_VARARGS},
- {"getAngularVelocity", (PyCFunction) KX_GameObject::sPyGetAngularVelocity, METH_VARARGS},
- {"setAngularVelocity", (PyCFunction) KX_GameObject::sPySetAngularVelocity, METH_VARARGS},
- {"getVelocity", (PyCFunction) KX_GameObject::sPyGetVelocity, METH_VARARGS},
- {"setDamping", (PyCFunction) KX_GameObject::sPySetDamping, METH_VARARGS},
- {"getReactionForce", (PyCFunction) KX_GameObject::sPyGetReactionForce, METH_NOARGS},
- {"alignAxisToVect",(PyCFunction) KX_GameObject::sPyAlignAxisToVect, METH_VARARGS},
- {"getAxisVect",(PyCFunction) KX_GameObject::sPyGetAxisVect, METH_O},
- {"suspendDynamics", (PyCFunction)KX_GameObject::sPySuspendDynamics, METH_VARARGS},
- {"restoreDynamics", (PyCFunction)KX_GameObject::sPyRestoreDynamics,METH_NOARGS},
- {"enableRigidBody", (PyCFunction)KX_GameObject::sPyEnableRigidBody,METH_NOARGS},
- {"disableRigidBody", (PyCFunction)KX_GameObject::sPyDisableRigidBody,METH_NOARGS},
- {"applyImpulse", (PyCFunction) KX_GameObject::sPyApplyImpulse, METH_VARARGS},
- {"setCollisionMargin", (PyCFunction) KX_GameObject::sPySetCollisionMargin, METH_O},
- {"setParent", (PyCFunction)KX_GameObject::sPySetParent,METH_VARARGS},
- {"setVisible",(PyCFunction) KX_GameObject::sPySetVisible, METH_VARARGS},
- {"setOcclusion",(PyCFunction) KX_GameObject::sPySetOcclusion, METH_VARARGS},
- {"removeParent", (PyCFunction)KX_GameObject::sPyRemoveParent,METH_NOARGS},
-
-
- {"getPhysicsId", (PyCFunction)KX_GameObject::sPyGetPhysicsId,METH_NOARGS},
- {"getPropertyNames", (PyCFunction)KX_GameObject::sPyGetPropertyNames,METH_NOARGS},
- {"replaceMesh",(PyCFunction) KX_GameObject::sPyReplaceMesh, METH_VARARGS},
- {"endObject",(PyCFunction) KX_GameObject::sPyEndObject, METH_NOARGS},
- {"reinstancePhysicsMesh", (PyCFunction)KX_GameObject::sPyReinstancePhysicsMesh,METH_VARARGS},
-
- KX_PYMETHODTABLE(KX_GameObject, rayCastTo),
- KX_PYMETHODTABLE(KX_GameObject, rayCast),
- KX_PYMETHODTABLE_O(KX_GameObject, getDistanceTo),
- KX_PYMETHODTABLE_O(KX_GameObject, getVectTo),
- KX_PYMETHODTABLE(KX_GameObject, sendMessage),
- KX_PYMETHODTABLE(KX_GameObject, addDebugProperty),
-
- KX_PYMETHODTABLE_KEYWORDS(KX_GameObject, playAction),
- KX_PYMETHODTABLE(KX_GameObject, stopAction),
- KX_PYMETHODTABLE(KX_GameObject, getActionFrame),
- KX_PYMETHODTABLE(KX_GameObject, getActionName),
- KX_PYMETHODTABLE(KX_GameObject, setActionFrame),
- KX_PYMETHODTABLE(KX_GameObject, isPlayingAction),
-
- // dict style access for props
- {"get",(PyCFunction) KX_GameObject::sPyget, METH_VARARGS},
-
- {NULL,NULL} //Sentinel
-};
-
-PyAttributeDef KX_GameObject::Attributes[] = {
- KX_PYATTRIBUTE_INT_RO("currentLodLevel", KX_GameObject, m_currentLodLevel),
- KX_PYATTRIBUTE_RO_FUNCTION("name", KX_GameObject, pyattr_get_name),
- KX_PYATTRIBUTE_RO_FUNCTION("parent", KX_GameObject, pyattr_get_parent),
- KX_PYATTRIBUTE_RO_FUNCTION("groupMembers", KX_GameObject, pyattr_get_group_members),
- KX_PYATTRIBUTE_RO_FUNCTION("groupObject", KX_GameObject, pyattr_get_group_object),
- KX_PYATTRIBUTE_RO_FUNCTION("scene", KX_GameObject, pyattr_get_scene),
- KX_PYATTRIBUTE_RO_FUNCTION("life", KX_GameObject, pyattr_get_life),
- KX_PYATTRIBUTE_RW_FUNCTION("mass", KX_GameObject, pyattr_get_mass, pyattr_set_mass),
- KX_PYATTRIBUTE_RO_FUNCTION("isSuspendDynamics", KX_GameObject, pyattr_get_is_suspend_dynamics),
- KX_PYATTRIBUTE_RW_FUNCTION("linVelocityMin", KX_GameObject, pyattr_get_lin_vel_min, pyattr_set_lin_vel_min),
- KX_PYATTRIBUTE_RW_FUNCTION("linVelocityMax", KX_GameObject, pyattr_get_lin_vel_max, pyattr_set_lin_vel_max),
- KX_PYATTRIBUTE_RW_FUNCTION("angularVelocityMin", KX_GameObject, pyattr_get_ang_vel_min, pyattr_set_ang_vel_min),
- KX_PYATTRIBUTE_RW_FUNCTION("angularVelocityMax", KX_GameObject, pyattr_get_ang_vel_max, pyattr_set_ang_vel_max),
- KX_PYATTRIBUTE_RW_FUNCTION("visible", KX_GameObject, pyattr_get_visible, pyattr_set_visible),
- KX_PYATTRIBUTE_RW_FUNCTION("record_animation", KX_GameObject, pyattr_get_record_animation, pyattr_set_record_animation),
- KX_PYATTRIBUTE_BOOL_RW ("occlusion", KX_GameObject, m_bOccluder),
- KX_PYATTRIBUTE_RW_FUNCTION("position", KX_GameObject, pyattr_get_worldPosition, pyattr_set_localPosition),
- KX_PYATTRIBUTE_RO_FUNCTION("localInertia", KX_GameObject, pyattr_get_localInertia),
- KX_PYATTRIBUTE_RW_FUNCTION("orientation",KX_GameObject,pyattr_get_worldOrientation,pyattr_set_localOrientation),
- KX_PYATTRIBUTE_RW_FUNCTION("scaling", KX_GameObject, pyattr_get_worldScaling, pyattr_set_localScaling),
- KX_PYATTRIBUTE_RW_FUNCTION("timeOffset",KX_GameObject, pyattr_get_timeOffset,pyattr_set_timeOffset),
- KX_PYATTRIBUTE_RW_FUNCTION("collisionCallbacks", KX_GameObject, pyattr_get_collisionCallbacks, pyattr_set_collisionCallbacks),
- KX_PYATTRIBUTE_RW_FUNCTION("collisionGroup", KX_GameObject, pyattr_get_collisionGroup, pyattr_set_collisionGroup),
- KX_PYATTRIBUTE_RW_FUNCTION("collisionMask", KX_GameObject, pyattr_get_collisionMask, pyattr_set_collisionMask),
- KX_PYATTRIBUTE_RW_FUNCTION("state", KX_GameObject, pyattr_get_state, pyattr_set_state),
- KX_PYATTRIBUTE_RO_FUNCTION("meshes", KX_GameObject, pyattr_get_meshes),
- KX_PYATTRIBUTE_RW_FUNCTION("localOrientation",KX_GameObject,pyattr_get_localOrientation,pyattr_set_localOrientation),
- KX_PYATTRIBUTE_RW_FUNCTION("worldOrientation",KX_GameObject,pyattr_get_worldOrientation,pyattr_set_worldOrientation),
- KX_PYATTRIBUTE_RW_FUNCTION("localPosition", KX_GameObject, pyattr_get_localPosition, pyattr_set_localPosition),
- KX_PYATTRIBUTE_RW_FUNCTION("worldPosition", KX_GameObject, pyattr_get_worldPosition, pyattr_set_worldPosition),
- KX_PYATTRIBUTE_RW_FUNCTION("localScale", KX_GameObject, pyattr_get_localScaling, pyattr_set_localScaling),
- KX_PYATTRIBUTE_RW_FUNCTION("worldScale", KX_GameObject, pyattr_get_worldScaling, pyattr_set_worldScaling),
- KX_PYATTRIBUTE_RW_FUNCTION("localTransform", KX_GameObject, pyattr_get_localTransform, pyattr_set_localTransform),
- KX_PYATTRIBUTE_RW_FUNCTION("worldTransform", KX_GameObject, pyattr_get_worldTransform, pyattr_set_worldTransform),
- KX_PYATTRIBUTE_RW_FUNCTION("linearVelocity", KX_GameObject, pyattr_get_localLinearVelocity, pyattr_set_worldLinearVelocity),
- KX_PYATTRIBUTE_RW_FUNCTION("localLinearVelocity", KX_GameObject, pyattr_get_localLinearVelocity, pyattr_set_localLinearVelocity),
- KX_PYATTRIBUTE_RW_FUNCTION("worldLinearVelocity", KX_GameObject, pyattr_get_worldLinearVelocity, pyattr_set_worldLinearVelocity),
- KX_PYATTRIBUTE_RW_FUNCTION("angularVelocity", KX_GameObject, pyattr_get_localAngularVelocity, pyattr_set_worldAngularVelocity),
- KX_PYATTRIBUTE_RW_FUNCTION("localAngularVelocity", KX_GameObject, pyattr_get_localAngularVelocity, pyattr_set_localAngularVelocity),
- KX_PYATTRIBUTE_RW_FUNCTION("worldAngularVelocity", KX_GameObject, pyattr_get_worldAngularVelocity, pyattr_set_worldAngularVelocity),
- KX_PYATTRIBUTE_RW_FUNCTION("linearDamping", KX_GameObject, pyattr_get_linearDamping, pyattr_set_linearDamping),
- KX_PYATTRIBUTE_RW_FUNCTION("angularDamping", KX_GameObject, pyattr_get_angularDamping, pyattr_set_angularDamping),
- KX_PYATTRIBUTE_RO_FUNCTION("children", KX_GameObject, pyattr_get_children),
- KX_PYATTRIBUTE_RO_FUNCTION("childrenRecursive", KX_GameObject, pyattr_get_children_recursive),
- KX_PYATTRIBUTE_RO_FUNCTION("attrDict", KX_GameObject, pyattr_get_attrDict),
- KX_PYATTRIBUTE_RW_FUNCTION("color", KX_GameObject, pyattr_get_obcolor, pyattr_set_obcolor),
- KX_PYATTRIBUTE_RW_FUNCTION("debug", KX_GameObject, pyattr_get_debug, pyattr_set_debug),
- KX_PYATTRIBUTE_RW_FUNCTION("debugRecursive", KX_GameObject, pyattr_get_debugRecursive, pyattr_set_debugRecursive),
-
- /* experimental, don't rely on these yet */
- KX_PYATTRIBUTE_RO_FUNCTION("sensors", KX_GameObject, pyattr_get_sensors),
- KX_PYATTRIBUTE_RO_FUNCTION("controllers", KX_GameObject, pyattr_get_controllers),
- KX_PYATTRIBUTE_RO_FUNCTION("actuators", KX_GameObject, pyattr_get_actuators),
- {NULL} //Sentinel
-};
-
-PyObject *KX_GameObject::PyReplaceMesh(PyObject *args)
-{
- KX_Scene *scene = KX_GetActiveScene();
- SCA_LogicManager *logicmgr = GetScene()->GetLogicManager();
-
- PyObject *value;
- int use_gfx= 1, use_phys= 0;
- RAS_MeshObject *new_mesh;
-
- if (!PyArg_ParseTuple(args,"O|ii:replaceMesh", &value, &use_gfx, &use_phys))
- return NULL;
-
- if (!ConvertPythonToMesh(logicmgr, value, &new_mesh, false, "gameOb.replaceMesh(value): KX_GameObject"))
- return NULL;
-
- scene->ReplaceMesh(this, new_mesh, (bool)use_gfx, (bool)use_phys);
- Py_RETURN_NONE;
-}
-
-PyObject *KX_GameObject::PyEndObject()
-{
- KX_Scene* scene = GetScene();
-
- scene->DelayedRemoveObject(this);
-
- Py_RETURN_NONE;
-
-}
-
-PyObject *KX_GameObject::PyReinstancePhysicsMesh(PyObject *args)
-{
- KX_GameObject *gameobj= NULL;
- RAS_MeshObject *mesh= NULL;
- SCA_LogicManager *logicmgr = GetScene()->GetLogicManager();
-
- PyObject *gameobj_py= NULL;
- PyObject *mesh_py= NULL;
-
- if ( !PyArg_ParseTuple(args,"|OO:reinstancePhysicsMesh",&gameobj_py, &mesh_py) ||
- (gameobj_py && !ConvertPythonToGameObject(logicmgr, gameobj_py, &gameobj, true, "gameOb.reinstancePhysicsMesh(obj, mesh): KX_GameObject")) ||
- (mesh_py && !ConvertPythonToMesh(logicmgr, mesh_py, &mesh, true, "gameOb.reinstancePhysicsMesh(obj, mesh): KX_GameObject"))
- ) {
- return NULL;
- }
-
- /* gameobj and mesh can be NULL */
- if (GetPhysicsController() && GetPhysicsController()->ReinstancePhysicsShape(gameobj, mesh))
- Py_RETURN_TRUE;
-
- Py_RETURN_FALSE;
-}
-
-static PyObject *Map_GetItem(PyObject *self_v, PyObject *item)
-{
- KX_GameObject* self = static_cast<KX_GameObject*>BGE_PROXY_REF(self_v);
- const char *attr_str= _PyUnicode_AsString(item);
- CValue* resultattr;
- PyObject *pyconvert;
-
- if (self == NULL) {
- PyErr_SetString(PyExc_SystemError, "val = gameOb[key]: KX_GameObject, " BGE_PROXY_ERROR_MSG);
- return NULL;
- }
-
- /* first see if the attributes a string and try get the cvalue attribute */
- if (attr_str && (resultattr=self->GetProperty(attr_str))) {
- pyconvert = resultattr->ConvertValueToPython();
- return pyconvert ? pyconvert:resultattr->GetProxy();
- }
- /* no CValue attribute, try get the python only m_attr_dict attribute */
- else if (self->m_attr_dict && (pyconvert=PyDict_GetItem(self->m_attr_dict, item))) {
-
- if (attr_str)
- PyErr_Clear();
- Py_INCREF(pyconvert);
- return pyconvert;
- }
- else {
- if (attr_str) PyErr_Format(PyExc_KeyError, "value = gameOb[key]: KX_GameObject, key \"%s\" does not exist", attr_str);
- else PyErr_SetString(PyExc_KeyError, "value = gameOb[key]: KX_GameObject, key does not exist");
- return NULL;
- }
-
-}
-
-
-static int Map_SetItem(PyObject *self_v, PyObject *key, PyObject *val)
-{
- KX_GameObject* self = static_cast<KX_GameObject*>BGE_PROXY_REF(self_v);
- const char *attr_str= _PyUnicode_AsString(key);
- if (attr_str==NULL)
- PyErr_Clear();
-
- if (self == NULL) {
- PyErr_SetString(PyExc_SystemError, "gameOb[key] = value: KX_GameObject, " BGE_PROXY_ERROR_MSG);
- return -1;
- }
-
- if (val==NULL) { /* del ob["key"] */
- int del= 0;
-
- /* try remove both just in case */
- if (attr_str)
- del |= (self->RemoveProperty(attr_str)==true) ? 1:0;
-
- if (self->m_attr_dict)
- del |= (PyDict_DelItem(self->m_attr_dict, key)==0) ? 1:0;
-
- if (del==0) {
- if (attr_str) PyErr_Format(PyExc_KeyError, "gameOb[key] = value: KX_GameObject, key \"%s\" could not be set", attr_str);
- else PyErr_SetString(PyExc_KeyError, "del gameOb[key]: KX_GameObject, key could not be deleted");
- return -1;
- }
- else if (self->m_attr_dict) {
- PyErr_Clear(); /* PyDict_DelItem sets an error when it fails */
- }
- }
- else { /* ob["key"] = value */
- bool set = false;
-
- /* as CValue */
- if (attr_str && PyObject_TypeCheck(val, &PyObjectPlus::Type)==0) /* don't allow GameObjects for eg to be assigned to CValue props */
- {
- CValue *vallie = self->ConvertPythonToValue(val, false, "gameOb[key] = value: ");
-
- if (vallie) {
- CValue* oldprop = self->GetProperty(attr_str);
-
- if (oldprop)
- oldprop->SetValue(vallie);
- else
- self->SetProperty(attr_str, vallie);
-
- vallie->Release();
- set = true;
-
- /* try remove dict value to avoid double ups */
- if (self->m_attr_dict) {
- if (PyDict_DelItem(self->m_attr_dict, key) != 0)
- PyErr_Clear();
- }
- }
- else if (PyErr_Occurred()) {
- return -1;
- }
- }
-
- if (set == false) {
- if (self->m_attr_dict==NULL) /* lazy init */
- self->m_attr_dict= PyDict_New();
-
-
- if (PyDict_SetItem(self->m_attr_dict, key, val)==0)
- {
- if (attr_str)
- self->RemoveProperty(attr_str); /* overwrite the CValue if it exists */
- set = true;
- }
- else {
- if (attr_str) PyErr_Format(PyExc_KeyError, "gameOb[key] = value: KX_GameObject, key \"%s\" not be added to internal dictionary", attr_str);
- else PyErr_SetString(PyExc_KeyError, "gameOb[key] = value: KX_GameObject, key not be added to internal dictionary");
- }
- }
-
- if (set == false) {
- return -1; /* pythons error value */
- }
-
- }
-
- return 0; /* success */
-}
-
-static int Seq_Contains(PyObject *self_v, PyObject *value)
-{
- KX_GameObject* self = static_cast<KX_GameObject*>BGE_PROXY_REF(self_v);
-
- if (self == NULL) {
- PyErr_SetString(PyExc_SystemError, "val in gameOb: KX_GameObject, " BGE_PROXY_ERROR_MSG);
- return -1;
- }
-
- if (PyUnicode_Check(value) && self->GetProperty(_PyUnicode_AsString(value)))
- return 1;
-
- if (self->m_attr_dict && PyDict_GetItem(self->m_attr_dict, value))
- return 1;
-
- return 0;
-}
-
-
-PyMappingMethods KX_GameObject::Mapping = {
- (lenfunc)NULL , /*inquiry mp_length */
- (binaryfunc)Map_GetItem, /*binaryfunc mp_subscript */
- (objobjargproc)Map_SetItem, /*objobjargproc mp_ass_subscript */
-};
-
-PySequenceMethods KX_GameObject::Sequence = {
- NULL, /* Cant set the len otherwise it can evaluate as false */
- NULL, /* sq_concat */
- NULL, /* sq_repeat */
- NULL, /* sq_item */
- NULL, /* sq_slice */
- NULL, /* sq_ass_item */
- NULL, /* sq_ass_slice */
- (objobjproc)Seq_Contains, /* sq_contains */
- (binaryfunc) NULL, /* sq_inplace_concat */
- (ssizeargfunc) NULL, /* sq_inplace_repeat */
-};
-
-PyTypeObject KX_GameObject::Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "KX_GameObject",
- sizeof(PyObjectPlus_Proxy),
- 0,
- py_base_dealloc,
- 0,
- 0,
- 0,
- 0,
- py_base_repr,
- 0,
- &Sequence,
- &Mapping,
- 0,0,0,
- NULL,
- NULL,
- 0,
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
- 0,0,0,0,0,0,0,
- Methods,
- 0,
- 0,
- &SCA_IObject::Type,
- 0,0,0,0,0,0,
- py_base_new
-};
-
-PyObject *KX_GameObject::pyattr_get_name(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
- return PyUnicode_From_STR_String(self->GetName());
-}
-
-PyObject *KX_GameObject::pyattr_get_parent(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
- KX_GameObject* parent = self->GetParent();
- if (parent) {
- return parent->GetProxy();
- }
- Py_RETURN_NONE;
-}
-
-PyObject *KX_GameObject::pyattr_get_group_members(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
- CListValue* instances = self->GetInstanceObjects();
- if (instances) {
- return instances->GetProxy();
- }
- Py_RETURN_NONE;
-}
-
-PyObject* KX_GameObject::pyattr_get_collisionCallbacks(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
-
- // Only objects with a physics controller should have collision callbacks
- if (!self->GetPhysicsController()) {
- PyErr_SetString(PyExc_AttributeError, "KX_GameObject.collisionCallbacks: attribute only available for objects with collisions enabled");
- return NULL;
- }
-
- // Return the existing callbacks
- if (self->m_collisionCallbacks == NULL)
- {
- self->m_collisionCallbacks = PyList_New(0);
- // Subscribe to collision update from KX_TouchManager
- self->RegisterCollisionCallbacks();
- }
- Py_INCREF(self->m_collisionCallbacks);
- return self->m_collisionCallbacks;
-}
-
-int KX_GameObject::pyattr_set_collisionCallbacks(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
-
- // Only objects with a physics controller should have collision callbacks
- if (!self->GetPhysicsController()) {
- PyErr_SetString(PyExc_AttributeError, "KX_GameObject.collisionCallbacks: attribute only available for objects with collisions enabled");
- return PY_SET_ATTR_FAIL;
- }
-
- if (!PyList_CheckExact(value))
- {
- PyErr_SetString(PyExc_ValueError, "Expected a list");
- return PY_SET_ATTR_FAIL;
- }
-
- if (self->m_collisionCallbacks == NULL) {
- self->RegisterCollisionCallbacks();
- } else {
- Py_DECREF(self->m_collisionCallbacks);
- }
-
- Py_INCREF(value);
-
-
- self->m_collisionCallbacks = value;
-
- return PY_SET_ATTR_SUCCESS;
-}
-
-PyObject *KX_GameObject::pyattr_get_collisionGroup(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
- return PyLong_FromLong(self->GetUserCollisionGroup());
-}
-
-int KX_GameObject::pyattr_set_collisionGroup(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
- int val = PyLong_AsLong(value);
-
- if (val == -1 && PyErr_Occurred()) {
- PyErr_SetString(PyExc_TypeError, "gameOb.collisionGroup = int: KX_GameObject, expected an int bit field");
- return PY_SET_ATTR_FAIL;
- }
-
- if (val == 0 || val & ~((1 << OB_MAX_COL_MASKS) - 1)) {
- PyErr_Format(PyExc_AttributeError, "gameOb.collisionGroup = int: KX_GameObject, expected a int bit field, 0 < group < %i", (1 << OB_MAX_COL_MASKS));
- return PY_SET_ATTR_FAIL;
- }
-
- self->SetUserCollisionGroup(val);
- return PY_SET_ATTR_SUCCESS;
-}
-
-PyObject *KX_GameObject::pyattr_get_collisionMask(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
- return PyLong_FromLong(self->GetUserCollisionMask());
-}
-
-int KX_GameObject::pyattr_set_collisionMask(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
- int val = PyLong_AsLong(value);
-
- if (val == -1 && PyErr_Occurred()) {
- PyErr_SetString(PyExc_TypeError, "gameOb.collisionMask = int: KX_GameObject, expected an int bit field");
- return PY_SET_ATTR_FAIL;
- }
-
- if (val == 0 || val & ~((1 << OB_MAX_COL_MASKS) - 1)) {
- PyErr_Format(PyExc_AttributeError, "gameOb.collisionMask = int: KX_GameObject, expected a int bit field, 0 < mask < %i", (1 << OB_MAX_COL_MASKS));
- return PY_SET_ATTR_FAIL;
- }
-
- self->SetUserCollisionMask(val);
- return PY_SET_ATTR_SUCCESS;
-}
-
-PyObject* KX_GameObject::pyattr_get_scene(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_GameObject *self = static_cast<KX_GameObject*>(self_v);
- KX_Scene *scene = self->GetScene();
- if (scene) {
- return scene->GetProxy();
- }
- Py_RETURN_NONE;
-}
-
-PyObject *KX_GameObject::pyattr_get_group_object(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
- KX_GameObject* pivot = self->GetDupliGroupObject();
- if (pivot) {
- return pivot->GetProxy();
- }
- Py_RETURN_NONE;
-}
-
-PyObject *KX_GameObject::pyattr_get_life(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
-
- CValue *life = self->GetProperty("::timebomb");
- if (life)
- // this convert the timebomb seconds to frames, hard coded 50.0f (assuming 50fps)
- // value hardcoded in KX_Scene::AddReplicaObject()
- return PyFloat_FromDouble(life->GetNumber() * 50.0);
- else
- Py_RETURN_NONE;
-}
-
-PyObject *KX_GameObject::pyattr_get_mass(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
- PHY_IPhysicsController *spc = self->GetPhysicsController();
- return PyFloat_FromDouble(spc ? spc->GetMass() : 0.0f);
-}
-
-int KX_GameObject::pyattr_set_mass(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
- PHY_IPhysicsController *spc = self->GetPhysicsController();
- MT_Scalar val = PyFloat_AsDouble(value);
- if (val < 0.0f) { /* also accounts for non float */
- PyErr_SetString(PyExc_AttributeError, "gameOb.mass = float: KX_GameObject, expected a float zero or above");
- return PY_SET_ATTR_FAIL;
- }
-
- if (spc)
- spc->SetMass(val);
-
- return PY_SET_ATTR_SUCCESS;
-}
-
-PyObject *KX_GameObject::pyattr_get_is_suspend_dynamics(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
-
- // Only objects with a physics controller can be suspended
- if (!self->GetPhysicsController()) {
- PyErr_SetString(PyExc_AttributeError, "This object has not Physics Controller");
- return NULL;
- }
-
- return PyBool_FromLong(self->IsDynamicsSuspended());
-}
-
-PyObject *KX_GameObject::pyattr_get_lin_vel_min(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
- PHY_IPhysicsController *spc = self->GetPhysicsController();
- return PyFloat_FromDouble(spc ? spc->GetLinVelocityMin() : 0.0f);
-}
-
-int KX_GameObject::pyattr_set_lin_vel_min(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
- PHY_IPhysicsController *spc = self->GetPhysicsController();
- MT_Scalar val = PyFloat_AsDouble(value);
- if (val < 0.0f) { /* also accounts for non float */
- PyErr_SetString(PyExc_AttributeError, "gameOb.linVelocityMin = float: KX_GameObject, expected a float zero or above");
- return PY_SET_ATTR_FAIL;
- }
-
- if (spc)
- spc->SetLinVelocityMin(val);
-
- return PY_SET_ATTR_SUCCESS;
-}
-
-PyObject *KX_GameObject::pyattr_get_lin_vel_max(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
- PHY_IPhysicsController *spc = self->GetPhysicsController();
- return PyFloat_FromDouble(spc ? spc->GetLinVelocityMax() : 0.0f);
-}
-
-int KX_GameObject::pyattr_set_lin_vel_max(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
- PHY_IPhysicsController *spc = self->GetPhysicsController();
- MT_Scalar val = PyFloat_AsDouble(value);
- if (val < 0.0f) { /* also accounts for non float */
- PyErr_SetString(PyExc_AttributeError, "gameOb.linVelocityMax = float: KX_GameObject, expected a float zero or above");
- return PY_SET_ATTR_FAIL;
- }
-
- if (spc)
- spc->SetLinVelocityMax(val);
-
- return PY_SET_ATTR_SUCCESS;
-}
-
-PyObject *KX_GameObject::pyattr_get_ang_vel_min(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_GameObject *self = static_cast<KX_GameObject*>(self_v);
- PHY_IPhysicsController *spc = self->GetPhysicsController();
- return PyFloat_FromDouble(spc ? spc->GetAngularVelocityMin() : 0.0f);
-}
-
-int KX_GameObject::pyattr_set_ang_vel_min(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_GameObject *self = static_cast<KX_GameObject*>(self_v);
- PHY_IPhysicsController *spc = self->GetPhysicsController();
- MT_Scalar val = PyFloat_AsDouble(value);
- if (val < 0.0f) { /* also accounts for non float */
- PyErr_SetString(PyExc_AttributeError,
- "gameOb.angularVelocityMin = float: KX_GameObject, expected a nonnegative float");
- return PY_SET_ATTR_FAIL;
- }
-
- if (spc)
- spc->SetAngularVelocityMin(val);
-
- return PY_SET_ATTR_SUCCESS;
-}
-
-PyObject *KX_GameObject::pyattr_get_ang_vel_max(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_GameObject *self = static_cast<KX_GameObject*>(self_v);
- PHY_IPhysicsController *spc = self->GetPhysicsController();
- return PyFloat_FromDouble(spc ? spc->GetAngularVelocityMax() : 0.0f);
-}
-
-int KX_GameObject::pyattr_set_ang_vel_max(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_GameObject *self = static_cast<KX_GameObject*>(self_v);
- PHY_IPhysicsController *spc = self->GetPhysicsController();
- MT_Scalar val = PyFloat_AsDouble(value);
- if (val < 0.0f) { /* also accounts for non float */
- PyErr_SetString(PyExc_AttributeError,
- "gameOb.angularVelocityMax = float: KX_GameObject, expected a nonnegative float");
- return PY_SET_ATTR_FAIL;
- }
-
- if (spc)
- spc->SetAngularVelocityMax(val);
-
- return PY_SET_ATTR_SUCCESS;
-}
-
-
-PyObject *KX_GameObject::pyattr_get_visible(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
- return PyBool_FromLong(self->GetVisible());
-}
-
-int KX_GameObject::pyattr_set_visible(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
- int param = PyObject_IsTrue( value );
- if (param == -1) {
- PyErr_SetString(PyExc_AttributeError, "gameOb.visible = bool: KX_GameObject, expected True or False");
- return PY_SET_ATTR_FAIL;
- }
-
- self->SetVisible(param, false);
- self->UpdateBuckets(false);
- return PY_SET_ATTR_SUCCESS;
-}
-
-PyObject *KX_GameObject::pyattr_get_record_animation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
- return PyBool_FromLong(self->IsRecordAnimation());
-}
-
-int KX_GameObject::pyattr_set_record_animation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
- int param = PyObject_IsTrue(value);
- if (param == -1) {
- PyErr_SetString(PyExc_AttributeError, "gameOb.record_animation = bool: KX_GameObject, expected boolean");
- return PY_SET_ATTR_FAIL;
- }
-
- self->SetRecordAnimation(param);
-
- return PY_SET_ATTR_SUCCESS;
-}
-
-
-
-PyObject *KX_GameObject::pyattr_get_worldPosition(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
-#ifdef USE_MATHUTILS
- return Vector_CreatePyObject_cb(
- BGE_PROXY_FROM_REF_BORROW(self_v), 3,
- mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_POS_GLOBAL);
-#else
- KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
- return PyObjectFrom(self->NodeGetWorldPosition());
-#endif
-}
-
-int KX_GameObject::pyattr_set_worldPosition(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
- MT_Point3 pos;
- if (!PyVecTo(value, pos))
- return PY_SET_ATTR_FAIL;
-
- self->NodeSetWorldPosition(pos);
- self->NodeUpdateGS(0.f);
- return PY_SET_ATTR_SUCCESS;
-}
-
-PyObject *KX_GameObject::pyattr_get_localPosition(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
-#ifdef USE_MATHUTILS
- return Vector_CreatePyObject_cb(
- BGE_PROXY_FROM_REF_BORROW(self_v), 3,
- mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_POS_LOCAL);
-#else
- KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
- return PyObjectFrom(self->NodeGetLocalPosition());
-#endif
-}
-
-int KX_GameObject::pyattr_set_localPosition(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
- MT_Point3 pos;
- if (!PyVecTo(value, pos))
- return PY_SET_ATTR_FAIL;
-
- self->NodeSetLocalPosition(pos);
- self->NodeUpdateGS(0.f);
- return PY_SET_ATTR_SUCCESS;
-}
-
-PyObject *KX_GameObject::pyattr_get_localInertia(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
-#ifdef USE_MATHUTILS
- return Vector_CreatePyObject_cb(
- BGE_PROXY_FROM_REF_BORROW(self_v), 3,
- mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_INERTIA_LOCAL);
-#else
- KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
- if (self->GetPhysicsController1())
- return PyObjectFrom(self->GetPhysicsController1()->GetLocalInertia());
- return Py_BuildValue("fff", 0.0f, 0.0f, 0.0f);
-#endif
-}
-
-PyObject *KX_GameObject::pyattr_get_worldOrientation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
-#ifdef USE_MATHUTILS
- return Matrix_CreatePyObject_cb(
- BGE_PROXY_FROM_REF_BORROW(self_v), 3, 3,
- mathutils_kxgameob_matrix_cb_index, MATHUTILS_MAT_CB_ORI_GLOBAL);
-#else
- KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
- return PyObjectFrom(self->NodeGetWorldOrientation());
-#endif
-}
-
-int KX_GameObject::pyattr_set_worldOrientation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
-
- /* if value is not a sequence PyOrientationTo makes an error */
- MT_Matrix3x3 rot;
- if (!PyOrientationTo(value, rot, "gameOb.worldOrientation = sequence: KX_GameObject, "))
- return PY_SET_ATTR_FAIL;
-
- self->NodeSetGlobalOrientation(rot);
-
- self->NodeUpdateGS(0.f);
- return PY_SET_ATTR_SUCCESS;
-}
-
-PyObject *KX_GameObject::pyattr_get_localOrientation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
-#ifdef USE_MATHUTILS
- return Matrix_CreatePyObject_cb(
- BGE_PROXY_FROM_REF_BORROW(self_v), 3, 3,
- mathutils_kxgameob_matrix_cb_index, MATHUTILS_MAT_CB_ORI_LOCAL);
-#else
- KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
- return PyObjectFrom(self->NodeGetLocalOrientation());
-#endif
-}
-
-int KX_GameObject::pyattr_set_localOrientation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
-
- /* if value is not a sequence PyOrientationTo makes an error */
- MT_Matrix3x3 rot;
- if (!PyOrientationTo(value, rot, "gameOb.localOrientation = sequence: KX_GameObject, "))
- return PY_SET_ATTR_FAIL;
-
- self->NodeSetLocalOrientation(rot);
- self->NodeUpdateGS(0.f);
- return PY_SET_ATTR_SUCCESS;
-}
-
-PyObject *KX_GameObject::pyattr_get_worldScaling(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
-#ifdef USE_MATHUTILS
- return Vector_CreatePyObject_cb(
- BGE_PROXY_FROM_REF_BORROW(self_v), 3,
- mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_SCALE_GLOBAL);
-#else
- KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
- return PyObjectFrom(self->NodeGetWorldScaling());
-#endif
-}
-
-int KX_GameObject::pyattr_set_worldScaling(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
- MT_Vector3 scale;
- if (!PyVecTo(value, scale))
- return PY_SET_ATTR_FAIL;
-
- self->NodeSetWorldScale(scale);
- self->NodeUpdateGS(0.f);
- return PY_SET_ATTR_SUCCESS;
-}
-
-PyObject *KX_GameObject::pyattr_get_localScaling(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
-#ifdef USE_MATHUTILS
- return Vector_CreatePyObject_cb(
- BGE_PROXY_FROM_REF_BORROW(self_v), 3,
- mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_SCALE_LOCAL);
-#else
- KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
- return PyObjectFrom(self->NodeGetLocalScaling());
-#endif
-}
-
-int KX_GameObject::pyattr_set_localScaling(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
- MT_Vector3 scale;
- if (!PyVecTo(value, scale))
- return PY_SET_ATTR_FAIL;
-
- self->NodeSetLocalScale(scale);
- self->NodeUpdateGS(0.f);
- return PY_SET_ATTR_SUCCESS;
-}
-
-PyObject *KX_GameObject::pyattr_get_localTransform(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
-
- float mat[16];
-
- MT_Transform trans;
-
- trans.setOrigin(self->GetSGNode()->GetLocalPosition());
- trans.setBasis(self->GetSGNode()->GetLocalOrientation());
-
- MT_Vector3 scaling = self->GetSGNode()->GetLocalScale();
- trans.scale(scaling[0], scaling[1], scaling[2]);
-
- trans.getValue(mat);
-
- return PyObjectFrom(MT_Matrix4x4(mat));
-}
-
-int KX_GameObject::pyattr_set_localTransform(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
- MT_Matrix4x4 temp;
- if (!PyMatTo(value, temp))
- return PY_SET_ATTR_FAIL;
-
- float transform[4][4];
- float loc[3], size[3];
- float rot[3][3];
- MT_Matrix3x3 orientation;
-
- temp.getValue(*transform);
- mat4_to_loc_rot_size(loc, rot, size, transform);
-
- self->NodeSetLocalPosition(MT_Point3(loc));
-
- //MT_Matrix3x3's constructor expects a 4x4 matrix
- orientation = MT_Matrix3x3();
- orientation.setValue3x3(*rot);
- self->NodeSetLocalOrientation(orientation);
-
- self->NodeSetLocalScale(MT_Vector3(size));
-
- return PY_SET_ATTR_SUCCESS;
-}
-
-PyObject *KX_GameObject::pyattr_get_worldTransform(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
-
- return PyObjectFrom(MT_Matrix4x4(self->GetOpenGLMatrix()));
-}
-
-int KX_GameObject::pyattr_set_worldTransform(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
- MT_Matrix4x4 temp;
- if (!PyMatTo(value, temp))
- return PY_SET_ATTR_FAIL;
-
- float transform[4][4];
- float loc[3], size[3];
- float rot[3][3];
- MT_Matrix3x3 orientation;
-
- temp.getValue(*transform);
- mat4_to_loc_rot_size(loc, rot, size, transform);
-
- self->NodeSetWorldPosition(MT_Point3(loc));
-
- //MT_Matrix3x3's constructor expects a 4x4 matrix
- orientation = MT_Matrix3x3();
- orientation.setValue3x3(*rot);
- self->NodeSetGlobalOrientation(orientation);
-
- self->NodeSetWorldScale(MT_Vector3(size));
-
- return PY_SET_ATTR_SUCCESS;
-}
-
-PyObject *KX_GameObject::pyattr_get_worldLinearVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
-#ifdef USE_MATHUTILS
- return Vector_CreatePyObject_cb(
- BGE_PROXY_FROM_REF_BORROW(self_v), 3,
- mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_LINVEL_GLOBAL);
-#else
- KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
- return PyObjectFrom(GetLinearVelocity(false));
-#endif
-}
-
-int KX_GameObject::pyattr_set_worldLinearVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
- MT_Vector3 velocity;
- if (!PyVecTo(value, velocity))
- return PY_SET_ATTR_FAIL;
-
- self->setLinearVelocity(velocity, false);
-
- return PY_SET_ATTR_SUCCESS;
-}
-
-PyObject *KX_GameObject::pyattr_get_localLinearVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
-#ifdef USE_MATHUTILS
- return Vector_CreatePyObject_cb(
- BGE_PROXY_FROM_REF_BORROW(self_v), 3,
- mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_LINVEL_LOCAL);
-#else
- KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
- return PyObjectFrom(GetLinearVelocity(true));
-#endif
-}
-
-int KX_GameObject::pyattr_set_localLinearVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
- MT_Vector3 velocity;
- if (!PyVecTo(value, velocity))
- return PY_SET_ATTR_FAIL;
-
- self->setLinearVelocity(velocity, true);
-
- return PY_SET_ATTR_SUCCESS;
-}
-
-PyObject *KX_GameObject::pyattr_get_worldAngularVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
-#ifdef USE_MATHUTILS
- return Vector_CreatePyObject_cb(
- BGE_PROXY_FROM_REF_BORROW(self_v), 3,
- mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_ANGVEL_GLOBAL);
-#else
- KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
- return PyObjectFrom(GetAngularVelocity(false));
-#endif
-}
-
-int KX_GameObject::pyattr_set_worldAngularVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
- MT_Vector3 velocity;
- if (!PyVecTo(value, velocity))
- return PY_SET_ATTR_FAIL;
-
- self->setAngularVelocity(velocity, false);
-
- return PY_SET_ATTR_SUCCESS;
-}
-
-PyObject *KX_GameObject::pyattr_get_localAngularVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
-#ifdef USE_MATHUTILS
- return Vector_CreatePyObject_cb(
- BGE_PROXY_FROM_REF_BORROW(self_v), 3,
- mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_ANGVEL_LOCAL);
-#else
- KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
- return PyObjectFrom(GetAngularVelocity(true));
-#endif
-}
-
-int KX_GameObject::pyattr_set_localAngularVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
- MT_Vector3 velocity;
- if (!PyVecTo(value, velocity))
- return PY_SET_ATTR_FAIL;
-
- self->setAngularVelocity(velocity, true);
-
- return PY_SET_ATTR_SUCCESS;
-}
-
-PyObject *KX_GameObject::pyattr_get_linearDamping(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
- return PyFloat_FromDouble(self->getLinearDamping());
-}
-
-int KX_GameObject::pyattr_set_linearDamping(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
- float val = PyFloat_AsDouble(value);
- self->setLinearDamping(val);
- return PY_SET_ATTR_SUCCESS;
-}
-
-PyObject *KX_GameObject::pyattr_get_angularDamping(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
- return PyFloat_FromDouble(self->getAngularDamping());
-}
-
-int KX_GameObject::pyattr_set_angularDamping(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
- float val = PyFloat_AsDouble(value);
- self->setAngularDamping(val);
- return PY_SET_ATTR_SUCCESS;
-}
-
-
-PyObject *KX_GameObject::pyattr_get_timeOffset(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
- SG_Node* sg_parent;
- if (self->GetSGNode() && (sg_parent = self->GetSGNode()->GetSGParent()) != NULL && sg_parent->IsSlowParent()) {
- return PyFloat_FromDouble(static_cast<KX_SlowParentRelation *>(sg_parent->GetParentRelation())->GetTimeOffset());
- } else {
- return PyFloat_FromDouble(0.0f);
- }
-}
-
-int KX_GameObject::pyattr_set_timeOffset(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
- if (self->GetSGNode()) {
- MT_Scalar val = PyFloat_AsDouble(value);
- SG_Node *sg_parent= self->GetSGNode()->GetSGParent();
- if (val < 0.0f) { /* also accounts for non float */
- PyErr_SetString(PyExc_AttributeError, "gameOb.timeOffset = float: KX_GameObject, expected a float zero or above");
- return PY_SET_ATTR_FAIL;
- }
- if (sg_parent && sg_parent->IsSlowParent())
- static_cast<KX_SlowParentRelation *>(sg_parent->GetParentRelation())->SetTimeOffset(val);
- }
- return PY_SET_ATTR_SUCCESS;
-}
-
-PyObject *KX_GameObject::pyattr_get_state(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
- int state = 0;
- state |= self->GetState();
- return PyLong_FromLong(state);
-}
-
-int KX_GameObject::pyattr_set_state(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
- int state_i = PyLong_AsLong(value);
- unsigned int state = 0;
-
- if (state_i == -1 && PyErr_Occurred()) {
- PyErr_SetString(PyExc_TypeError, "gameOb.state = int: KX_GameObject, expected an int bit field");
- return PY_SET_ATTR_FAIL;
- }
-
- state |= state_i;
- if ((state & ((1<<30)-1)) == 0) {
- PyErr_SetString(PyExc_AttributeError, "gameOb.state = int: KX_GameObject, state bitfield was not between 0 and 30 (1<<0 and 1<<29)");
- return PY_SET_ATTR_FAIL;
- }
- self->SetState(state);
- return PY_SET_ATTR_SUCCESS;
-}
-
-PyObject *KX_GameObject::pyattr_get_meshes(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
- PyObject *meshes= PyList_New(self->m_meshes.size());
- int i;
-
- for (i=0; i < (int)self->m_meshes.size(); i++)
- {
- KX_MeshProxy* meshproxy = new KX_MeshProxy(self->m_meshes[i]);
- PyList_SET_ITEM(meshes, i, meshproxy->NewProxy(true));
- }
-
- return meshes;
-}
-
-PyObject *KX_GameObject::pyattr_get_obcolor(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
-#ifdef USE_MATHUTILS
- return Vector_CreatePyObject_cb(
- BGE_PROXY_FROM_REF_BORROW(self_v), 4,
- mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_OBJECT_COLOR);
-#else
- KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
- return PyObjectFrom(self->GetObjectColor());
-#endif
-}
-
-int KX_GameObject::pyattr_set_obcolor(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
- MT_Vector4 obcolor;
- if (!PyVecTo(value, obcolor))
- return PY_SET_ATTR_FAIL;
-
- self->SetObjectColor(obcolor);
- return PY_SET_ATTR_SUCCESS;
-}
-
-static int kx_game_object_get_sensors_size_cb(void *self_v)
-{
- return ((KX_GameObject *)self_v)->GetSensors().size();
-}
-
-static PyObject *kx_game_object_get_sensors_item_cb(void *self_v, int index)
-{
- return ((KX_GameObject *)self_v)->GetSensors()[index]->GetProxy();
-}
-
-static const char *kx_game_object_get_sensors_item_name_cb(void *self_v, int index)
-{
- return ((KX_GameObject *)self_v)->GetSensors()[index]->GetName().ReadPtr();
-}
-
-/* These are experimental! */
-PyObject *KX_GameObject::pyattr_get_sensors(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- return (new CListWrapper(self_v,
- ((KX_GameObject *)self_v)->GetProxy(),
- NULL,
- kx_game_object_get_sensors_size_cb,
- kx_game_object_get_sensors_item_cb,
- kx_game_object_get_sensors_item_name_cb,
- NULL))->NewProxy(true);
-}
-
-static int kx_game_object_get_controllers_size_cb(void *self_v)
-{
- return ((KX_GameObject *)self_v)->GetControllers().size();
-}
-
-static PyObject *kx_game_object_get_controllers_item_cb(void *self_v, int index)
-{
- return ((KX_GameObject *)self_v)->GetControllers()[index]->GetProxy();
-}
-
-static const char *kx_game_object_get_controllers_item_name_cb(void *self_v, int index)
-{
- return ((KX_GameObject *)self_v)->GetControllers()[index]->GetName().ReadPtr();
-}
-
-PyObject *KX_GameObject::pyattr_get_controllers(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- return (new CListWrapper(self_v,
- ((KX_GameObject *)self_v)->GetProxy(),
- NULL,
- kx_game_object_get_controllers_size_cb,
- kx_game_object_get_controllers_item_cb,
- kx_game_object_get_controllers_item_name_cb,
- NULL))->NewProxy(true);
-}
-
-static int kx_game_object_get_actuators_size_cb(void *self_v)
-{
- return ((KX_GameObject *)self_v)->GetActuators().size();
-}
-
-static PyObject *kx_game_object_get_actuators_item_cb(void *self_v, int index)
-{
- return ((KX_GameObject *)self_v)->GetActuators()[index]->GetProxy();
-}
-
-static const char *kx_game_object_get_actuators_item_name_cb(void *self_v, int index)
-{
- return ((KX_GameObject *)self_v)->GetActuators()[index]->GetName().ReadPtr();
-}
-
-PyObject *KX_GameObject::pyattr_get_actuators(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- return (new CListWrapper(self_v,
- ((KX_GameObject *)self_v)->GetProxy(),
- NULL,
- kx_game_object_get_actuators_size_cb,
- kx_game_object_get_actuators_item_cb,
- kx_game_object_get_actuators_item_name_cb,
- NULL))->NewProxy(true);
-}
-/* End experimental */
-
-PyObject *KX_GameObject::pyattr_get_children(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
- return self->GetChildren()->NewProxy(true);
-}
-
-PyObject *KX_GameObject::pyattr_get_children_recursive(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
- return self->GetChildrenRecursive()->NewProxy(true);
-}
-
-PyObject *KX_GameObject::pyattr_get_attrDict(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
-
- if (self->m_attr_dict==NULL)
- self->m_attr_dict= PyDict_New();
-
- Py_INCREF(self->m_attr_dict);
- return self->m_attr_dict;
-}
-
-PyObject *KX_GameObject::pyattr_get_debug(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_Scene *scene = KX_GetActiveScene();
- KX_GameObject *self = static_cast<KX_GameObject*>(self_v);
-
- return PyBool_FromLong(scene->ObjectInDebugList(self));
-}
-
-int KX_GameObject::pyattr_set_debug(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_GameObject *self = static_cast<KX_GameObject*>(self_v);
- int param = PyObject_IsTrue(value);
-
- if (param == -1) {
- PyErr_SetString(PyExc_AttributeError, "gameOb.debug = bool: KX_GameObject, expected True or False");
- return PY_SET_ATTR_FAIL;
- }
-
- self->SetUseDebugProperties(param, false);
-
- return PY_SET_ATTR_SUCCESS;
-}
-
-PyObject *KX_GameObject::pyattr_get_debugRecursive(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_Scene *scene = KX_GetActiveScene();
- KX_GameObject *self = static_cast<KX_GameObject*>(self_v);
-
- return PyBool_FromLong(scene->ObjectInDebugList(self));
-}
-
-int KX_GameObject::pyattr_set_debugRecursive(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_GameObject *self = static_cast<KX_GameObject*>(self_v);
- int param = PyObject_IsTrue(value);
-
- if (param == -1) {
- PyErr_SetString(PyExc_AttributeError, "gameOb.debugRecursive = bool: KX_GameObject, expected True or False");
- return PY_SET_ATTR_FAIL;
- }
-
- self->SetUseDebugProperties(param, true);
-
- return PY_SET_ATTR_SUCCESS;
-}
-
-PyObject *KX_GameObject::PyApplyForce(PyObject *args)
-{
- int local = 0;
- PyObject *pyvect;
-
- if (PyArg_ParseTuple(args, "O|i:applyForce", &pyvect, &local)) {
- MT_Vector3 force;
- if (PyVecTo(pyvect, force)) {
- ApplyForce(force, (local!=0));
- Py_RETURN_NONE;
- }
- }
- return NULL;
-}
-
-PyObject *KX_GameObject::PyApplyTorque(PyObject *args)
-{
- int local = 0;
- PyObject *pyvect;
-
- if (PyArg_ParseTuple(args, "O|i:applyTorque", &pyvect, &local)) {
- MT_Vector3 torque;
- if (PyVecTo(pyvect, torque)) {
- ApplyTorque(torque, (local!=0));
- Py_RETURN_NONE;
- }
- }
- return NULL;
-}
-
-PyObject *KX_GameObject::PyApplyRotation(PyObject *args)
-{
- int local = 0;
- PyObject *pyvect;
-
- if (PyArg_ParseTuple(args, "O|i:applyRotation", &pyvect, &local)) {
- MT_Vector3 rotation;
- if (PyVecTo(pyvect, rotation)) {
- ApplyRotation(rotation, (local!=0));
- Py_RETURN_NONE;
- }
- }
- return NULL;
-}
-
-PyObject *KX_GameObject::PyApplyMovement(PyObject *args)
-{
- int local = 0;
- PyObject *pyvect;
-
- if (PyArg_ParseTuple(args, "O|i:applyMovement", &pyvect, &local)) {
- MT_Vector3 movement;
- if (PyVecTo(pyvect, movement)) {
- ApplyMovement(movement, (local!=0));
- Py_RETURN_NONE;
- }
- }
- return NULL;
-}
-
-PyObject *KX_GameObject::PyGetLinearVelocity(PyObject *args)
-{
- // only can get the velocity if we have a physics object connected to us...
- int local = 0;
- if (PyArg_ParseTuple(args,"|i:getLinearVelocity",&local))
- {
- return PyObjectFrom(GetLinearVelocity((local!=0)));
- }
- else
- {
- return NULL;
- }
-}
-
-PyObject *KX_GameObject::PySetLinearVelocity(PyObject *args)
-{
- int local = 0;
- PyObject *pyvect;
-
- if (PyArg_ParseTuple(args,"O|i:setLinearVelocity",&pyvect,&local)) {
- MT_Vector3 velocity;
- if (PyVecTo(pyvect, velocity)) {
- setLinearVelocity(velocity, (local!=0));
- Py_RETURN_NONE;
- }
- }
- return NULL;
-}
-
-PyObject *KX_GameObject::PyGetAngularVelocity(PyObject *args)
-{
- // only can get the velocity if we have a physics object connected to us...
- int local = 0;
- if (PyArg_ParseTuple(args,"|i:getAngularVelocity",&local))
- {
- return PyObjectFrom(GetAngularVelocity((local!=0)));
- }
- else
- {
- return NULL;
- }
-}
-
-PyObject *KX_GameObject::PySetAngularVelocity(PyObject *args)
-{
- int local = 0;
- PyObject *pyvect;
-
- if (PyArg_ParseTuple(args,"O|i:setAngularVelocity",&pyvect,&local)) {
- MT_Vector3 velocity;
- if (PyVecTo(pyvect, velocity)) {
- setAngularVelocity(velocity, (local!=0));
- Py_RETURN_NONE;
- }
- }
- return NULL;
-}
-
-PyObject *KX_GameObject::PySetDamping(PyObject *args)
-{
- float linear;
- float angular;
-
- if (!PyArg_ParseTuple(args,"ff|i:setDamping", &linear, &angular))
- return NULL;
-
- setDamping(linear, angular);
- Py_RETURN_NONE;
-}
-
-PyObject *KX_GameObject::PySetVisible(PyObject *args)
-{
- int visible, recursive = 0;
- if (!PyArg_ParseTuple(args,"i|i:setVisible",&visible, &recursive))
- return NULL;
-
- SetVisible(visible ? true:false, recursive ? true:false);
- UpdateBuckets(recursive ? true:false);
- Py_RETURN_NONE;
-
-}
-
-PyObject *KX_GameObject::PySetOcclusion(PyObject *args)
-{
- int occlusion, recursive = 0;
- if (!PyArg_ParseTuple(args,"i|i:setOcclusion",&occlusion, &recursive))
- return NULL;
-
- SetOccluder(occlusion ? true:false, recursive ? true:false);
- Py_RETURN_NONE;
-}
-
-PyObject *KX_GameObject::PyGetVelocity(PyObject *args)
-{
- // only can get the velocity if we have a physics object connected to us...
- MT_Point3 point(0.0f,0.0f,0.0f);
- PyObject *pypos = NULL;
-
- if (!PyArg_ParseTuple(args, "|O:getVelocity", &pypos) || (pypos && !PyVecTo(pypos, point)))
- return NULL;
-
- return PyObjectFrom(GetVelocity(point));
-}
-
-PyObject *KX_GameObject::PyGetReactionForce()
-{
- // only can get the velocity if we have a physics object connected to us...
-
- // XXX - Currently not working with bullet intergration, see KX_BulletPhysicsController.cpp's getReactionForce
-#if 0
- if (GetPhysicsController1())
- return PyObjectFrom(GetPhysicsController1()->getReactionForce());
- return PyObjectFrom(dummy_point);
-#endif
-
- return Py_BuildValue("fff", 0.0f, 0.0f, 0.0f);
-
-}
-
-
-
-PyObject *KX_GameObject::PyEnableRigidBody()
-{
- if (GetPhysicsController())
- GetPhysicsController()->SetRigidBody(true);
-
- Py_RETURN_NONE;
-}
-
-
-
-PyObject *KX_GameObject::PyDisableRigidBody()
-{
- if (GetPhysicsController())
- GetPhysicsController()->SetRigidBody(false);
-
- Py_RETURN_NONE;
-}
-
-
-PyObject *KX_GameObject::PySetParent(PyObject *args)
-{
- KX_Scene *scene = KX_GetActiveScene();
- SCA_LogicManager *logicmgr = GetScene()->GetLogicManager();
- PyObject *pyobj;
- KX_GameObject *obj;
- int addToCompound=1, ghost=1;
-
- if (!PyArg_ParseTuple(args,"O|ii:setParent", &pyobj, &addToCompound, &ghost)) {
- return NULL; // Python sets a simple error
- }
- if (!ConvertPythonToGameObject(logicmgr, pyobj, &obj, true, "gameOb.setParent(obj): KX_GameObject"))
- return NULL;
- if (obj)
- this->SetParent(scene, obj, addToCompound, ghost);
- Py_RETURN_NONE;
-}
-
-PyObject *KX_GameObject::PyRemoveParent()
-{
- KX_Scene *scene = KX_GetActiveScene();
-
- this->RemoveParent(scene);
- Py_RETURN_NONE;
-}
-
-
-PyObject *KX_GameObject::PySetCollisionMargin(PyObject *value)
-{
- float collisionMargin = PyFloat_AsDouble(value);
-
- if (collisionMargin==-1 && PyErr_Occurred()) {
- PyErr_SetString(PyExc_TypeError, "expected a float");
- return NULL;
- }
-
- if (m_pPhysicsController)
- {
- m_pPhysicsController->SetMargin(collisionMargin);
- Py_RETURN_NONE;
- }
- PyErr_SetString(PyExc_RuntimeError, "This object has no physics controller");
- return NULL;
-}
-
-
-
-PyObject *KX_GameObject::PyApplyImpulse(PyObject *args)
-{
- PyObject *pyattach;
- PyObject *pyimpulse;
- int local = 0;
-
- if (!m_pPhysicsController) {
- PyErr_SetString(PyExc_RuntimeError, "This object has no physics controller");
- return NULL;
- }
-
- if (PyArg_ParseTuple(args, "OO|i:applyImpulse", &pyattach, &pyimpulse, &local))
- {
- MT_Point3 attach;
- MT_Vector3 impulse;
- if (PyVecTo(pyattach, attach) && PyVecTo(pyimpulse, impulse))
- {
- m_pPhysicsController->ApplyImpulse(attach, impulse, (local!=0));
- Py_RETURN_NONE;
- }
-
- }
-
- return NULL;
-}
-
-
-
-PyObject *KX_GameObject::PySuspendDynamics(PyObject *args)
-{
- bool ghost = false;
-
- if (!PyArg_ParseTuple(args, "|b", &ghost))
- return NULL;
-
- if (GetPhysicsController())
- GetPhysicsController()->SuspendDynamics(ghost);
-
- Py_RETURN_NONE;
-}
-
-
-
-PyObject *KX_GameObject::PyRestoreDynamics()
-{
- // Child objects must be static, so we block changing to dynamic
- if (GetPhysicsController() && !GetParent())
- GetPhysicsController()->RestoreDynamics();
- Py_RETURN_NONE;
-}
-
-
-PyObject *KX_GameObject::PyAlignAxisToVect(PyObject *args)
-{
- PyObject *pyvect;
- int axis = 2; //z axis is the default
- float fac = 1.0f;
-
- if (PyArg_ParseTuple(args,"O|if:alignAxisToVect",&pyvect,&axis, &fac))
- {
- MT_Vector3 vect;
- if (PyVecTo(pyvect, vect)) {
- if (fac > 0.0f) {
- if (fac> 1.0f) fac = 1.0f;
-
- AlignAxisToVect(vect, axis, fac);
- NodeUpdateGS(0.f);
- }
- Py_RETURN_NONE;
- }
- }
- return NULL;
-}
-
-PyObject *KX_GameObject::PyGetAxisVect(PyObject *value)
-{
- MT_Vector3 vect;
- if (PyVecTo(value, vect))
- {
- return PyObjectFrom(NodeGetWorldOrientation() * vect);
- }
- return NULL;
-}
-
-
-PyObject *KX_GameObject::PyGetPhysicsId()
-{
- PHY_IPhysicsController* ctrl = GetPhysicsController();
- unsigned long long physid = 0;
- if (ctrl)
- {
- physid = (unsigned long long)ctrl;
- }
- return PyLong_FromUnsignedLongLong(physid);
-}
-
-PyObject *KX_GameObject::PyGetPropertyNames()
-{
- PyObject *list= ConvertKeysToPython();
-
- if (m_attr_dict) {
- PyObject *key, *value;
- Py_ssize_t pos = 0;
-
- while (PyDict_Next(m_attr_dict, &pos, &key, &value)) {
- PyList_Append(list, key);
- }
- }
- return list;
-}
-
-KX_PYMETHODDEF_DOC_O(KX_GameObject, getDistanceTo,
-"getDistanceTo(other): get distance to another point/KX_GameObject")
-{
- MT_Point3 b;
- if (PyVecTo(value, b))
- {
- return PyFloat_FromDouble(NodeGetWorldPosition().distance(b));
- }
- PyErr_Clear();
-
- SCA_LogicManager *logicmgr = GetScene()->GetLogicManager();
- KX_GameObject *other;
- if (ConvertPythonToGameObject(logicmgr, value, &other, false, "gameOb.getDistanceTo(value): KX_GameObject"))
- {
- return PyFloat_FromDouble(NodeGetWorldPosition().distance(other->NodeGetWorldPosition()));
- }
-
- return NULL;
-}
-
-KX_PYMETHODDEF_DOC_O(KX_GameObject, getVectTo,
-"getVectTo(other): get vector and the distance to another point/KX_GameObject\n"
-"Returns a 3-tuple with (distance,worldVector,localVector)\n")
-{
- MT_Point3 toPoint, fromPoint;
- MT_Vector3 toDir, locToDir;
- MT_Scalar distance;
-
- SCA_LogicManager *logicmgr = GetScene()->GetLogicManager();
- PyObject *returnValue;
-
- if (!PyVecTo(value, toPoint))
- {
- PyErr_Clear();
-
- KX_GameObject *other;
- if (ConvertPythonToGameObject(logicmgr, value, &other, false, "")) /* error will be overwritten */
- {
- toPoint = other->NodeGetWorldPosition();
- } else
- {
- PyErr_SetString(PyExc_TypeError, "gameOb.getVectTo(other): KX_GameObject, expected a 3D Vector or KX_GameObject type");
- return NULL;
- }
- }
-
- fromPoint = NodeGetWorldPosition();
- toDir = toPoint-fromPoint;
- distance = toDir.length();
-
- if (MT_fuzzyZero(distance))
- {
- //cout << "getVectTo() Error: Null vector!\n";
- locToDir = toDir = MT_Vector3(0.0f,0.0f,0.0f);
- distance = 0.0f;
- } else {
- toDir.normalize();
- locToDir = toDir * NodeGetWorldOrientation();
- }
-
- returnValue = PyTuple_New(3);
- if (returnValue) { // very unlikely to fail, python sets a memory error here.
- PyTuple_SET_ITEM(returnValue, 0, PyFloat_FromDouble(distance));
- PyTuple_SET_ITEM(returnValue, 1, PyObjectFrom(toDir));
- PyTuple_SET_ITEM(returnValue, 2, PyObjectFrom(locToDir));
- }
- return returnValue;
-}
-
-struct KX_GameObject::RayCastData
-{
- RayCastData(STR_String prop, bool xray, short mask)
- :m_prop(prop),
- m_xray(xray),
- m_mask(mask),
- m_hitObject(NULL)
- {
- }
-
- STR_String m_prop;
- bool m_xray;
- unsigned short m_mask;
- KX_GameObject *m_hitObject;
-};
-
-bool KX_GameObject::RayHit(KX_ClientObjectInfo *client, KX_RayCast *result, RayCastData *rayData)
-{
- KX_GameObject* hitKXObj = client->m_gameobject;
-
- // if X-ray option is selected, the unwnted objects were not tested, so get here only with true hit
- // if not, all objects were tested and the front one may not be the correct one.
- if ((rayData->m_xray || rayData->m_prop.Length() == 0 || hitKXObj->GetProperty(rayData->m_prop) != NULL) &&
- hitKXObj->GetUserCollisionGroup() & rayData->m_mask)
- {
- rayData->m_hitObject = hitKXObj;
- return true;
- }
- // return true to stop RayCast::RayTest from looping, the above test was decisive
- // We would want to loop only if we want to get more than one hit point
- return true;
-}
-
-/* this function is used to pre-filter the object before casting the ray on them.
- * This is useful for "X-Ray" option when we want to see "through" unwanted object.
- */
-bool KX_GameObject::NeedRayCast(KX_ClientObjectInfo *client, RayCastData *rayData)
-{
- KX_GameObject* hitKXObj = client->m_gameobject;
-
- if (client->m_type > KX_ClientObjectInfo::ACTOR)
- {
- // Unknown type of object, skip it.
- // Should not occur as the sensor objects are filtered in RayTest()
- printf("Invalid client type %d found in ray casting\n", client->m_type);
- return false;
- }
-
- // if X-Ray option is selected, skip object that don't match the criteria as we see through them
- // if not, test all objects because we don't know yet which one will be on front
- if ((!rayData->m_xray || rayData->m_prop.Length() == 0 || hitKXObj->GetProperty(rayData->m_prop) != NULL) &&
- hitKXObj->GetUserCollisionGroup() & rayData->m_mask)
- {
- return true;
- }
- // skip the object
- return false;
-}
-
-KX_PYMETHODDEF_DOC(KX_GameObject, rayCastTo,
-"rayCastTo(other,dist,prop): look towards another point/KX_GameObject and return first object hit within dist that matches prop\n"
-" prop = property name that object must have; can be omitted => detect any object\n"
-" dist = max distance to look (can be negative => look behind); 0 or omitted => detect up to other\n"
-" other = 3-tuple or object reference")
-{
- MT_Point3 toPoint;
- PyObject *pyarg;
- float dist = 0.0f;
- char *propName = NULL;
- SCA_LogicManager *logicmgr = GetScene()->GetLogicManager();
-
- if (!PyArg_ParseTuple(args,"O|fs:rayCastTo", &pyarg, &dist, &propName)) {
- return NULL; // python sets simple error
- }
-
- if (!PyVecTo(pyarg, toPoint))
- {
- KX_GameObject *other;
- PyErr_Clear();
-
- if (ConvertPythonToGameObject(logicmgr, pyarg, &other, false, "")) /* error will be overwritten */
- {
- toPoint = other->NodeGetWorldPosition();
- } else
- {
- PyErr_SetString(PyExc_TypeError, "gameOb.rayCastTo(other,dist,prop): KX_GameObject, the first argument to rayCastTo must be a vector or a KX_GameObject");
- return NULL;
- }
- }
- MT_Point3 fromPoint = NodeGetWorldPosition();
-
- if (dist != 0.0f)
- toPoint = fromPoint + dist * (toPoint-fromPoint).safe_normalized();
-
- PHY_IPhysicsEnvironment* pe = GetScene()->GetPhysicsEnvironment();
- PHY_IPhysicsController *spc = GetPhysicsController();
- KX_GameObject *parent = GetParent();
- if (!spc && parent)
- spc = parent->GetPhysicsController();
-
- RayCastData rayData(propName, false, (1u << OB_MAX_COL_MASKS) - 1);
- KX_RayCast::Callback<KX_GameObject, RayCastData> callback(this, spc, &rayData);
- if (KX_RayCast::RayTest(pe, fromPoint, toPoint, callback) && rayData.m_hitObject) {
- return rayData.m_hitObject->GetProxy();
- }
-
- Py_RETURN_NONE;
-}
-
-/* faster then Py_BuildValue since some scripts call raycast a lot */
-static PyObject *none_tuple_3()
-{
- PyObject *ret= PyTuple_New(3);
- PyTuple_SET_ITEM(ret, 0, Py_None);
- PyTuple_SET_ITEM(ret, 1, Py_None);
- PyTuple_SET_ITEM(ret, 2, Py_None);
-
- Py_INCREF(Py_None);
- Py_INCREF(Py_None);
- Py_INCREF(Py_None);
- return ret;
-}
-static PyObject *none_tuple_4()
-{
- PyObject *ret= PyTuple_New(4);
- PyTuple_SET_ITEM(ret, 0, Py_None);
- PyTuple_SET_ITEM(ret, 1, Py_None);
- PyTuple_SET_ITEM(ret, 2, Py_None);
- PyTuple_SET_ITEM(ret, 3, Py_None);
-
- Py_INCREF(Py_None);
- Py_INCREF(Py_None);
- Py_INCREF(Py_None);
- Py_INCREF(Py_None);
- return ret;
-}
-
-static PyObject *none_tuple_5()
-{
- PyObject *ret= PyTuple_New(5);
- PyTuple_SET_ITEM(ret, 0, Py_None);
- PyTuple_SET_ITEM(ret, 1, Py_None);
- PyTuple_SET_ITEM(ret, 2, Py_None);
- PyTuple_SET_ITEM(ret, 3, Py_None);
- PyTuple_SET_ITEM(ret, 4, Py_None);
-
- Py_INCREF(Py_None);
- Py_INCREF(Py_None);
- Py_INCREF(Py_None);
- Py_INCREF(Py_None);
- Py_INCREF(Py_None);
- return ret;
-}
-
-KX_PYMETHODDEF_DOC(KX_GameObject, rayCast,
- "rayCast(to,from,dist,prop,face,xray,poly,mask): cast a ray and return 3-tuple (object,hit,normal) or 4-tuple (object,hit,normal,polygon) or 4-tuple (object,hit,normal,polygon,hituv) of contact point with object within dist that matches prop.\n"
- " If no hit, return (None,None,None) or (None,None,None,None) or (None,None,None,None,None).\n"
-" to = 3-tuple or object reference for destination of ray (if object, use center of object)\n"
-" from = 3-tuple or object reference for origin of ray (if object, use center of object)\n"
-" Can be None or omitted => start from self object center\n"
-" dist = max distance to look (can be negative => look behind); 0 or omitted => detect up to to\n"
-" prop = property name that object must have; can be omitted => detect any object\n"
-" face = normal option: 1=>return face normal; 0 or omitted => normal is oriented towards origin\n"
-" xray = X-ray option: 1=>skip objects that don't match prop; 0 or omitted => stop on first object\n"
-" poly = polygon option: 1=>return value is a 4-tuple and the 4th element is a KX_PolyProxy object\n"
-" which can be None if hit object has no mesh or if there is no hit\n"
-" 2=>return value is a 5-tuple, the 4th element is the KX_PolyProxy object\n"
-" and the 5th element is the vector of UV coordinates at the hit point of the None if there is no UV mapping\n"
-" If 0 or omitted, return value is a 3-tuple\n"
-" mask = collision mask: the collision mask that ray can hit, 0 < mask < 65536\n"
-"Note: The object on which you call this method matters: the ray will ignore it.\n"
-" prop and xray option interact as follow:\n"
-" prop off, xray off: return closest hit or no hit if there is no object on the full extend of the ray\n"
-" prop off, xray on : idem\n"
-" prop on, xray off: return closest hit if it matches prop, no hit otherwise\n"
-" prop on, xray on : return closest hit matching prop or no hit if there is no object matching prop on the full extend of the ray\n")
-{
- MT_Point3 toPoint;
- MT_Point3 fromPoint;
- PyObject *pyto;
- PyObject *pyfrom = NULL;
- float dist = 0.0f;
- char *propName = NULL;
- KX_GameObject *other;
- int face=0, xray=0, poly=0;
- int mask = (1 << OB_MAX_COL_MASKS) - 1;
- SCA_LogicManager *logicmgr = GetScene()->GetLogicManager();
-
- if (!PyArg_ParseTuple(args,"O|Ofsiiii:rayCast", &pyto, &pyfrom, &dist, &propName, &face, &xray, &poly, &mask)) {
- return NULL; // Python sets a simple error
- }
-
- if (!PyVecTo(pyto, toPoint))
- {
- PyErr_Clear();
-
- if (ConvertPythonToGameObject(logicmgr, pyto, &other, false, "")) /* error will be overwritten */
- {
- toPoint = other->NodeGetWorldPosition();
- } else
- {
- PyErr_SetString(PyExc_TypeError, "the first argument to rayCast must be a vector or a KX_GameObject");
- return NULL;
- }
- }
- if (!pyfrom || pyfrom == Py_None)
- {
- fromPoint = NodeGetWorldPosition();
- }
- else if (!PyVecTo(pyfrom, fromPoint))
- {
- PyErr_Clear();
-
- if (ConvertPythonToGameObject(logicmgr, pyfrom, &other, false, "")) /* error will be overwritten */
- {
- fromPoint = other->NodeGetWorldPosition();
- } else
- {
- PyErr_SetString(PyExc_TypeError, "gameOb.rayCast(to,from,dist,prop,face,xray,poly,mask): KX_GameObject, the second optional argument to rayCast must be a vector or a KX_GameObject");
- return NULL;
- }
- }
-
- if (mask == 0 || mask & ~((1 << OB_MAX_COL_MASKS) - 1)) {
- PyErr_Format(PyExc_TypeError, "gameOb.rayCast(to,from,dist,prop,face,xray,poly,mask): KX_GameObject, mask argument to rayCast must be a int bitfield, 0 < mask < %i", (1 << OB_MAX_COL_MASKS));
- return NULL;
- }
-
- if (dist != 0.0f) {
- MT_Vector3 toDir = toPoint-fromPoint;
- if (MT_fuzzyZero(toDir.length2())) {
- //return Py_BuildValue("OOO", Py_None, Py_None, Py_None);
- return none_tuple_3();
- }
- toDir.normalize();
- toPoint = fromPoint + (dist) * toDir;
- } else if (MT_fuzzyZero((toPoint-fromPoint).length2())) {
- //return Py_BuildValue("OOO", Py_None, Py_None, Py_None);
- return none_tuple_3();
- }
-
- PHY_IPhysicsEnvironment* pe = GetScene()->GetPhysicsEnvironment();
- PHY_IPhysicsController *spc = GetPhysicsController();
- KX_GameObject *parent = GetParent();
- if (!spc && parent)
- spc = parent->GetPhysicsController();
-
- // to get the hit results
- RayCastData rayData(propName, xray, mask);
- KX_RayCast::Callback<KX_GameObject, RayCastData> callback(this, spc, &rayData, face, (poly == 2));
-
- if (KX_RayCast::RayTest(pe, fromPoint, toPoint, callback) && rayData.m_hitObject) {
- PyObject *returnValue = (poly == 2) ? PyTuple_New(5) : (poly) ? PyTuple_New(4) : PyTuple_New(3);
- if (returnValue) { // unlikely this would ever fail, if it does python sets an error
- PyTuple_SET_ITEM(returnValue, 0, rayData.m_hitObject->GetProxy());
- PyTuple_SET_ITEM(returnValue, 1, PyObjectFrom(callback.m_hitPoint));
- PyTuple_SET_ITEM(returnValue, 2, PyObjectFrom(callback.m_hitNormal));
- if (poly)
- {
- if (callback.m_hitMesh)
- {
- // if this field is set, then we can trust that m_hitPolygon is a valid polygon
- RAS_Polygon* polygon = callback.m_hitMesh->GetPolygon(callback.m_hitPolygon);
- KX_PolyProxy* polyproxy = new KX_PolyProxy(callback.m_hitMesh, polygon);
- PyTuple_SET_ITEM(returnValue, 3, polyproxy->NewProxy(true));
- if (poly == 2)
- {
- if (callback.m_hitUVOK)
- PyTuple_SET_ITEM(returnValue, 4, PyObjectFrom(callback.m_hitUV));
- else {
- Py_INCREF(Py_None);
- PyTuple_SET_ITEM(returnValue, 4, Py_None);
- }
- }
- }
- else
- {
- Py_INCREF(Py_None);
- PyTuple_SET_ITEM(returnValue, 3, Py_None);
- if (poly==2)
- {
- Py_INCREF(Py_None);
- PyTuple_SET_ITEM(returnValue, 4, Py_None);
- }
- }
- }
- }
- return returnValue;
- }
- // no hit
- if (poly == 2)
- return none_tuple_5();
- else if (poly)
- return none_tuple_4();
- else
- return none_tuple_3();
-}
-
-KX_PYMETHODDEF_DOC_VARARGS(KX_GameObject, sendMessage,
- "sendMessage(subject, [body, to])\n"
-"sends a message in same manner as a message actuator"
-"subject = Subject of the message (string)"
-"body = Message body (string)"
-"to = Name of object to send the message to")
-{
- KX_Scene *scene = KX_GetActiveScene();
- char* subject;
- char* body = (char *)"";
- char* to = (char *)"";
- const STR_String& from = GetName();
-
- if (!PyArg_ParseTuple(args, "s|ss:sendMessage", &subject, &body, &to))
- return NULL;
-
- scene->GetNetworkScene()->SendMessage(to, from, subject, body);
- Py_RETURN_NONE;
-}
-
-static void layer_check(short &layer, const char *method_name)
-{
- if (layer < 0 || layer >= MAX_ACTION_LAYERS)
- {
- printf("KX_GameObject.%s(): given layer (%d) is out of range (0 - %d), setting to 0.\n", method_name, layer, MAX_ACTION_LAYERS-1);
- layer = 0;
- }
-}
-
-KX_PYMETHODDEF_DOC(KX_GameObject, playAction,
- "playAction(name, start_frame, end_frame, layer=0, priority=0 blendin=0, play_mode=ACT_MODE_PLAY, layer_weight=0.0, ipo_flags=0, speed=1.0)\n"
- "Plays an action\n")
-{
- const char* name;
- float start, end, blendin=0.f, speed=1.f, layer_weight=0.f;
- short layer=0, priority=0;
- short ipo_flags=0;
- short play_mode=0;
- short blend_mode=0;
-
- static const char *kwlist[] = {"name", "start_frame", "end_frame", "layer", "priority", "blendin", "play_mode", "layer_weight", "ipo_flags", "speed", "blend_mode", NULL};
-
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "sff|hhfhfhfh:playAction", const_cast<char**>(kwlist),
- &name, &start, &end, &layer, &priority, &blendin, &play_mode, &layer_weight, &ipo_flags, &speed, &blend_mode))
- return NULL;
-
- layer_check(layer, "playAction");
-
- if (play_mode < 0 || play_mode > BL_Action::ACT_MODE_MAX)
- {
- printf("KX_GameObject.playAction(): given play_mode (%d) is out of range (0 - %d), setting to ACT_MODE_PLAY", play_mode, BL_Action::ACT_MODE_MAX-1);
- play_mode = BL_Action::ACT_MODE_PLAY;
- }
-
- if (blend_mode < 0 || blend_mode > BL_Action::ACT_BLEND_MAX)
- {
- printf("KX_GameObject.playAction(): given blend_mode (%d) is out of range (0 - %d), setting to ACT_BLEND_BLEND", blend_mode, BL_Action::ACT_BLEND_MAX-1);
- blend_mode = BL_Action::ACT_BLEND_BLEND;
- }
-
- if (layer_weight < 0.f || layer_weight > 1.f)
- {
- printf("KX_GameObject.playAction(): given layer_weight (%f) is out of range (0.0 - 1.0), setting to 0.0", layer_weight);
- layer_weight = 0.f;
- }
-
- PlayAction(name, start, end, layer, priority, blendin, play_mode, layer_weight, ipo_flags, speed, blend_mode);
-
- Py_RETURN_NONE;
-}
-
-KX_PYMETHODDEF_DOC(KX_GameObject, stopAction,
- "stopAction(layer=0)\n"
- "Stop playing the action on the given layer\n")
-{
- short layer = 0;
-
- if (!PyArg_ParseTuple(args, "|h:stopAction", &layer))
- return NULL;
-
- layer_check(layer, "stopAction");
-
- StopAction(layer);
-
- Py_RETURN_NONE;
-}
-
-KX_PYMETHODDEF_DOC(KX_GameObject, getActionFrame,
- "getActionFrame(layer=0)\n"
- "Gets the current frame of the action playing in the supplied layer\n")
-{
- short layer = 0;
-
- if (!PyArg_ParseTuple(args, "|h:getActionFrame", &layer))
- return NULL;
-
- layer_check(layer, "getActionFrame");
-
- return PyFloat_FromDouble(GetActionFrame(layer));
-}
-
-KX_PYMETHODDEF_DOC(KX_GameObject, getActionName,
- "getActionName(layer=0)\n"
- "Gets the name of the current action playing in the supplied layer\n")
-{
- short layer = 0;
-
- if (!PyArg_ParseTuple(args, "|h:getActionName", &layer))
- return NULL;
-
- layer_check(layer, "getActionName");
-
- return PyUnicode_FromString(GetActionName(layer));
-}
-
-KX_PYMETHODDEF_DOC(KX_GameObject, setActionFrame,
- "setActionFrame(frame, layer=0)\n"
- "Set the current frame of the action playing in the supplied layer\n")
-{
- short layer = 0;
- float frame;
-
- if (!PyArg_ParseTuple(args, "f|h:setActionFrame", &frame, &layer))
- return NULL;
-
- layer_check(layer, "setActionFrame");
-
- SetActionFrame(layer, frame);
-
- Py_RETURN_NONE;
-}
-
-KX_PYMETHODDEF_DOC(KX_GameObject, isPlayingAction,
- "isPlayingAction(layer=0)\n"
- "Checks to see if there is an action playing in the given layer\n")
-{
- short layer = 0;
-
- if (!PyArg_ParseTuple(args, "|h:isPlayingAction", &layer))
- return NULL;
-
- layer_check(layer, "isPlayingAction");
-
- return PyBool_FromLong(!IsActionDone(layer));
-}
-
-
-KX_PYMETHODDEF_DOC(KX_GameObject, addDebugProperty,
-"addDebugProperty(name, visible=1)\n"
-"Added or remove a debug property to the debug list.\n")
-{
- KX_Scene *scene = KX_GetActiveScene();
- char *name;
- int visible = 1;
-
- if (!PyArg_ParseTuple(args,"s|i:debugProperty", &name , &visible))
- return NULL;
-
- if (visible) {
- if (!scene->PropertyInDebugList(this, name))
- scene->AddDebugProperty(this, name);
- }
- else {
- scene->RemoveDebugProperty(this, name);
- }
-
- Py_RETURN_NONE;
-}
-
-
-/* dict style access */
-
-
-/* Matches python dict.get(key, [default]) */
-PyObject *KX_GameObject::Pyget(PyObject *args)
-{
- PyObject *key;
- PyObject *def = Py_None;
- PyObject *ret;
-
- if (!PyArg_ParseTuple(args, "O|O:get", &key, &def))
- return NULL;
-
-
- if (PyUnicode_Check(key)) {
- CValue *item = GetProperty(_PyUnicode_AsString(key));
- if (item) {
- ret = item->ConvertValueToPython();
- if (ret)
- return ret;
- else
- return item->GetProxy();
- }
- }
-
- if (m_attr_dict && (ret=PyDict_GetItem(m_attr_dict, key))) {
- Py_INCREF(ret);
- return ret;
- }
-
- Py_INCREF(def);
- return def;
-}
-
-bool ConvertPythonToGameObject(SCA_LogicManager *manager, PyObject *value, KX_GameObject **object, bool py_none_ok, const char *error_prefix)
-{
- if (value==NULL) {
- PyErr_Format(PyExc_TypeError, "%s, python pointer NULL, should never happen", error_prefix);
- *object = NULL;
- return false;
- }
-
- if (value==Py_None) {
- *object = NULL;
-
- if (py_none_ok) {
- return true;
- } else {
- PyErr_Format(PyExc_TypeError, "%s, expected KX_GameObject or a KX_GameObject name, None is invalid", error_prefix);
- return false;
- }
- }
-
- if (PyUnicode_Check(value)) {
- *object = (KX_GameObject*)manager->GetGameObjectByName(STR_String( _PyUnicode_AsString(value) ));
-
- if (*object) {
- return true;
- } else {
- PyErr_Format(PyExc_ValueError, "%s, requested name \"%s\" did not match any KX_GameObject in this scene", error_prefix, _PyUnicode_AsString(value));
- return false;
- }
- }
-
- if (PyObject_TypeCheck(value, &KX_GameObject::Type) ||
- PyObject_TypeCheck(value, &KX_LightObject::Type) ||
- PyObject_TypeCheck(value, &KX_Camera::Type) ||
- PyObject_TypeCheck(value, &KX_FontObject::Type) ||
- PyObject_TypeCheck(value, &KX_NavMeshObject::Type))
- {
- *object = static_cast<KX_GameObject*>BGE_PROXY_REF(value);
-
- /* sets the error */
- if (*object==NULL) {
- PyErr_Format(PyExc_SystemError, "%s, " BGE_PROXY_ERROR_MSG, error_prefix);
- return false;
- }
-
- return true;
- }
-
- *object = NULL;
-
- if (py_none_ok) {
- PyErr_Format(PyExc_TypeError, "%s, expect a KX_GameObject, a string or None", error_prefix);
- } else {
- PyErr_Format(PyExc_TypeError, "%s, expect a KX_GameObject or a string", error_prefix);
- }
-
- return false;
-}
-#endif // WITH_PYTHON
diff --git a/source/gameengine/Ketsji/KX_GameObject.h b/source/gameengine/Ketsji/KX_GameObject.h
deleted file mode 100644
index 9c582d3e27a..00000000000
--- a/source/gameengine/Ketsji/KX_GameObject.h
+++ /dev/null
@@ -1,1142 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file KX_GameObject.h
- * \ingroup ketsji
- * \brief General KX game object.
- */
-
-#ifndef __KX_GAMEOBJECT_H__
-#define __KX_GAMEOBJECT_H__
-
-#ifdef _MSC_VER
- /* get rid of this stupid "warning 'this' used in initialiser list", generated by VC when including Solid/Sumo */
-# pragma warning (disable:4355)
-#endif
-
-#include <stddef.h>
-
-#include "EXP_ListValue.h"
-#include "SCA_IObject.h"
-#include "SG_Node.h"
-#include "MT_Transform.h"
-#include "MT_CmMatrix4x4.h"
-#include "CTR_Map.h"
-#include "CTR_HashedPtr.h"
-#include "KX_Scene.h"
-#include "KX_KetsjiEngine.h" /* for m_anim_framerate */
-#include "DNA_constraint_types.h" /* for constraint replication */
-#include "DNA_object_types.h"
-#include "SCA_LogicManager.h" /* for ConvertPythonToGameObject to search object names */
-
-//Forward declarations.
-struct KX_ClientObjectInfo;
-class KX_RayCast;
-class RAS_MeshObject;
-class PHY_IGraphicController;
-class PHY_IPhysicsEnvironment;
-class PHY_IPhysicsController;
-class BL_ActionManager;
-struct Object;
-class KX_ObstacleSimulation;
-struct bAction;
-
-#ifdef WITH_PYTHON
-/* utility conversion function */
-bool ConvertPythonToGameObject(SCA_LogicManager *logicmgr, PyObject *value, KX_GameObject **object, bool py_none_ok, const char *error_prefix);
-#endif
-
-#ifdef USE_MATHUTILS
-void KX_GameObject_Mathutils_Callback_Init(void);
-#endif
-
-/**
- * KX_GameObject is the main class for dynamic objects.
- */
-class KX_GameObject : public SCA_IObject
-{
- Py_Header
-protected:
-
- bool m_bDyna;
- KX_ClientObjectInfo* m_pClient_info;
- STR_String m_name;
- STR_String m_text;
- int m_layer;
- std::vector<RAS_MeshObject*> m_meshes;
- std::vector<RAS_MeshObject*> m_lodmeshes;
- int m_currentLodLevel;
- short m_previousLodLevel;
- SG_QList m_meshSlots; // head of mesh slots of this
- struct Object* m_pBlenderObject;
- struct Object* m_pBlenderGroupObject;
-
- bool m_bUseObjectColor;
- bool m_bIsNegativeScaling;
- MT_Vector4 m_objectColor;
-
- // Bit fields for user control over physics collisions
- unsigned short m_userCollisionGroup;
- unsigned short m_userCollisionMask;
-
- // visible = user setting
- // culled = while rendering, depending on camera
- bool m_bVisible;
- bool m_bCulled;
- bool m_bOccluder;
-
- PHY_IPhysicsController* m_pPhysicsController;
- PHY_IGraphicController* m_pGraphicController;
-
- SG_Node* m_pSGNode;
-
- MT_CmMatrix4x4 m_OpenGL_4x4Matrix;
- std::vector<bRigidBodyJointConstraint*> m_constraints;
-
- KX_ObstacleSimulation* m_pObstacleSimulation;
-
- CListValue* m_pInstanceObjects;
- KX_GameObject* m_pDupliGroupObject;
-
- // The action manager is used to play/stop/update actions
- BL_ActionManager* m_actionManager;
-
- BL_ActionManager* GetActionManager();
-
- bool m_bRecordAnimation;
-
-public:
- bool m_isDeformable;
-
- /**
- * KX_GameObject custom infos for ray cast, it contains property name,
- * collision mask, xray flag and hited object.
- * This structure is created during ray cast and passed as argument
- * "data" to functions KX_GameObject::NeedRayCast and KX_GameObject::RayHit.
- */
- struct RayCastData;
-
- /**
- * Helper function for modules that can't include KX_ClientObjectInfo.h
- */
- static KX_GameObject* GetClientObject(KX_ClientObjectInfo* info);
-
-#ifdef WITH_PYTHON
- // Python attributes that wont convert into CValue
- //
- // there are 2 places attributes can be stored, in the CValue,
- // where attributes are converted into BGE's CValue types
- // these can be used with property actuators
- //
- // For the python API, For types that cannot be converted into CValues (lists, dicts, GameObjects)
- // these will be put into "m_attr_dict", logic bricks cannot access them.
- //
- // rules for setting attributes.
- //
- // * there should NEVER be a CValue and a m_attr_dict attribute with matching names. get/sets make sure of this.
- // * if CValue conversion fails, use a PyObject in "m_attr_dict"
- // * when assigning a value, first see if it can be a CValue, if it can remove the "m_attr_dict" and set the CValue
- //
- PyObject* m_attr_dict;
- PyObject* m_collisionCallbacks;
-#endif
-
- virtual void /* This function should be virtual - derived classed override it */
- Relink(
- CTR_Map<CTR_HashedPtr, void*> *map
- );
-
- /**
- * Compute an OpenGl compatible 4x4 matrix. Has the
- * side effect of storing the result internally. The
- * memory for the matrix remains the property of this class.
- */
- float *
- GetOpenGLMatrix(
- );
-
- /**
- * Return a pointer to a MT_CmMatrix4x4 storing the
- * opengl transformation for this object. This is updated
- * by a call to GetOpenGLMatrix(). This class owns the
- * memory for the returned matrix.
- */
-
- MT_CmMatrix4x4 *
- GetOpenGLMatrixPtr(
- ) {
- return &m_OpenGL_4x4Matrix;
- };
-
- /**
- * Update the blender object obmat field from the object world position
- * if blendobj is NULL, update the object pointed by m_pBlenderObject
- * The user must take action to restore the matrix before leaving the GE.
- * Used in Armature evaluation
- */
- void
- UpdateBlenderObjectMatrix(Object* blendobj=NULL);
-
- /**
- * Used for constraint replication for group instances.
- * The list of constraints is filled during data conversion.
- */
- void AddConstraint(bRigidBodyJointConstraint *cons);
- std::vector<bRigidBodyJointConstraint*> GetConstraints();
- void ClearConstraints();
-
- /**
- * Get a pointer to the game object that is the parent of
- * this object. Or NULL if there is no parent. The returned
- * object is part of a reference counting scheme. Calling
- * this function ups the reference count on the returned
- * object. It is the responsibility of the caller to decrement
- * the reference count when you have finished with it.
- */
- KX_GameObject*
- GetParent(
- );
-
- /**
- * Sets the parent of this object to a game object
- */
- void SetParent(KX_Scene *scene, KX_GameObject *obj, bool addToCompound=true, bool ghost=true);
-
- /**
- * Removes the parent of this object to a game object
- */
- void RemoveParent(KX_Scene *scene);
-
- /*********************************
- * group reference API
- *********************************/
-
- KX_GameObject*
- GetDupliGroupObject(
- );
-
- CListValue*
- GetInstanceObjects(
- );
-
- void
- SetDupliGroupObject(KX_GameObject*
- );
-
- void
- AddInstanceObjects(KX_GameObject*
- );
-
- void
- RemoveDupliGroupObject(
- );
-
- void
- RemoveInstanceObject(KX_GameObject*
- );
- /*********************************
- * Animation API
- *********************************/
-
- /**
- * Adds an action to the object's action manager
- */
- bool PlayAction(const char* name,
- float start,
- float end,
- short layer=0,
- short priority=0,
- float blendin=0.f,
- short play_mode=0,
- float layer_weight=0.f,
- short ipo_flags=0,
- float playback_speed=1.f,
- short blend_mode=0);
-
- /**
- * Gets the current frame of an action
- */
- float GetActionFrame(short layer);
-
- /**
- * Gets the name of the current action
- */
- const char *GetActionName(short layer);
-
- /**
- * Sets the current frame of an action
- */
- void SetActionFrame(short layer, float frame);
-
- /**
- * Gets the currently running action on the given layer
- */
- bAction *GetCurrentAction(short layer);
-
- /**
- * Sets play mode of the action on the given layer
- */
- void SetPlayMode(short layer, short mode);
-
- /**
- * Sets the start and end times of the action on the given layer
- */
- void SetTimes(short layer, float start, float end);
-
- /**
- * Stop playing the action on the given layer
- */
- void StopAction(short layer);
-
- /**
- * Remove playing tagged actions.
- */
- void RemoveTaggedActions();
-
- /**
- * Check if an action has finished playing
- */
- bool IsActionDone(short layer);
-
- /**
- * Kick the object's action manager
- */
- void UpdateActionManager(float curtime);
-
- /*********************************
- * End Animation API
- *********************************/
-
- /**
- * Construct a game object. This class also inherits the
- * default constructors - use those with care!
- */
-
- KX_GameObject(
- void* sgReplicationInfo,
- SG_Callbacks callbacks
- );
-
- virtual
- ~KX_GameObject(
- );
-
- /**
- * \section Stuff which is here due to poor design.
- * Inherited from CValue and needs an implementation.
- * Do not expect these functions do to anything sensible.
- */
-
- /**
- * Inherited from CValue -- does nothing!
- */
- CValue*
- Calc(
- VALUE_OPERATOR op,
- CValue *val
- );
-
- /**
- * Inherited from CValue -- does nothing!
- */
- CValue*
- CalcFinal(
- VALUE_DATA_TYPE dtype,
- VALUE_OPERATOR op,
- CValue *val
- );
-
- /**
- * Inherited from CValue -- does nothing!
- */
- const
- STR_String &
- GetText(
- );
-
- /**
- * Inherited from CValue -- does nothing!
- */
- double
- GetNumber(
- );
-
- /**
- * \section Inherited from CValue. These are the useful
- * part of the CValue interface that this class implements.
- */
-
- /**
- * Inherited from CValue -- returns the name of this object.
- */
- STR_String&
- GetName(
- );
-
- /**
- * Inherited from CValue -- set the name of this object.
- */
- void
- SetName(
- const char *name
- );
-
- /**
- * Inherited from CValue -- return a new copy of this
- * instance allocated on the heap. Ownership of the new
- * object belongs with the caller.
- */
- virtual CValue*
- GetReplica(
- );
-
- /**
- * Inherited from CValue -- Makes sure any internal
- * data owned by this class is deep copied. Called internally
- */
- virtual void
- ProcessReplica();
-
- /**
- * Return the linear velocity of the game object.
- */
- MT_Vector3
- GetLinearVelocity(
- bool local=false
- );
-
- /**
- * Return the linear velocity of a given point in world coordinate
- * but relative to center of object ([0,0,0]=center of object)
- */
- MT_Vector3
- GetVelocity(
- const MT_Point3& position
- );
-
- /**
- * Return the mass of the object
- */
- MT_Scalar
- GetMass();
-
- /**
- * Return the local inertia vector of the object
- */
- MT_Vector3
- GetLocalInertia();
-
- /**
- * Return the angular velocity of the game object.
- */
- MT_Vector3
- GetAngularVelocity(
- bool local=false
- );
-
- /**
- * Align the object to a given normal.
- */
- void
- AlignAxisToVect(
- const MT_Vector3& vect,
- int axis = 2,
- float fac = 1.0
- );
-
- /**
- * Quick'n'dirty obcolor ipo stuff
- */
-
- void
- SetObjectColor(
- const MT_Vector4& rgbavec
- );
-
- const MT_Vector4&
- GetObjectColor();
-
-
- void
- ResolveCombinedVelocities(
- const MT_Vector3 & lin_vel,
- const MT_Vector3 & ang_vel,
- bool lin_vel_local,
- bool ang_vel_local
- );
-
- /**
- * \return a pointer to the physics controller owned by this class.
- */
-
- PHY_IPhysicsController* GetPhysicsController();
-
- void SetPhysicsController(PHY_IPhysicsController* physicscontroller,bool isDynamic)
- {
- m_bDyna = isDynamic;
- m_pPhysicsController = physicscontroller;
- }
-
- virtual class RAS_Deformer* GetDeformer()
- {
- return 0;
- }
- virtual void SetDeformer(class RAS_Deformer* deformer)
- {
-
- }
-
- /**
- * \return a pointer to the graphic controller owner by this class
- */
- PHY_IGraphicController* GetGraphicController()
- {
- return m_pGraphicController;
- }
-
- void SetGraphicController(PHY_IGraphicController* graphiccontroller)
- {
- m_pGraphicController = graphiccontroller;
- }
- /*
- * @add/remove the graphic controller to the physic system
- */
- void ActivateGraphicController(bool recurse);
-
- /** Set the object's collison group
- * \param filter The group bitfield
- */
- void SetUserCollisionGroup(unsigned short filter);
-
- /** Set the object's collison mask
- * \param filter The mask bitfield
- */
- void SetUserCollisionMask(unsigned short mask);
- unsigned short GetUserCollisionGroup();
- unsigned short GetUserCollisionMask();
- /**
- * Extra broadphase check for user controllable collisions
- */
- bool CheckCollision(KX_GameObject *other);
-
- /**
- * \section Coordinate system manipulation functions
- */
-
- void NodeSetLocalPosition(const MT_Point3& trans );
-
- void NodeSetLocalOrientation(const MT_Matrix3x3& rot );
- void NodeSetGlobalOrientation(const MT_Matrix3x3& rot );
-
- void NodeSetLocalScale( const MT_Vector3& scale );
- void NodeSetWorldScale( const MT_Vector3& scale );
-
- void NodeSetRelativeScale( const MT_Vector3& scale );
-
- // adapt local position so that world position is set to desired position
- void NodeSetWorldPosition(const MT_Point3& trans);
-
- void
- NodeUpdateGS(
- double time
- );
-
- const MT_Matrix3x3& NodeGetWorldOrientation( ) const;
- const MT_Vector3& NodeGetWorldScaling( ) const;
- const MT_Point3& NodeGetWorldPosition( ) const;
-
- const MT_Matrix3x3& NodeGetLocalOrientation( ) const;
- const MT_Vector3& NodeGetLocalScaling( ) const;
- const MT_Point3& NodeGetLocalPosition( ) const;
-
- /**
- * \section scene graph node accessor functions.
- */
-
- SG_Node* GetSGNode( )
- {
- return m_pSGNode;
- }
-
- const SG_Node* GetSGNode( ) const
- {
- return m_pSGNode;
- }
-
- /**
- * \section blender object accessor functions.
- */
-
- struct Object* GetBlenderObject( )
- {
- return m_pBlenderObject;
- }
-
- void SetBlenderObject(struct Object* obj)
- {
- m_pBlenderObject = obj;
- }
-
- struct Object* GetBlenderGroupObject( )
- {
- return m_pBlenderGroupObject;
- }
-
- void SetBlenderGroupObject(struct Object* obj)
- {
- m_pBlenderGroupObject = obj;
- }
-
- bool IsDupliGroup()
- {
- return (m_pBlenderObject &&
- (m_pBlenderObject->transflag & OB_DUPLIGROUP) &&
- m_pBlenderObject->dup_group != NULL) ? true : false;
- }
-
- /**
- * Set the Scene graph node for this game object.
- * warning - it is your responsibility to make sure
- * all controllers look at this new node. You must
- * also take care of the memory associated with the
- * old node. This class takes ownership of the new
- * node.
- */
- void SetSGNode(SG_Node* node )
- {
- m_pSGNode = node;
- }
-
- //Is it a dynamic/physics object ?
- bool IsDynamic() const
- {
- return m_bDyna;
- }
-
- bool IsDynamicsSuspended() const;
-
- /**
- * Should we record animation for this object?
- */
-
- void SetRecordAnimation(bool recordAnimation)
- {
- m_bRecordAnimation = recordAnimation;
- }
-
- bool IsRecordAnimation() const
- {
- return m_bRecordAnimation;
- }
-
- /**
- * Check if this object has a vertex parent relationship
- */
- bool IsVertexParent( )
- {
- return (m_pSGNode && m_pSGNode->GetSGParent() && m_pSGNode->GetSGParent()->IsVertexParent());
- }
-
- /// \see KX_RayCast
- bool RayHit(KX_ClientObjectInfo *client, KX_RayCast *result, RayCastData *rayData);
- /// \see KX_RayCast
- bool NeedRayCast(KX_ClientObjectInfo *client, RayCastData *rayData);
-
-
- /**
- * \section Physics accessors for this node.
- *
- * All these calls get passed directly to the physics controller
- * owned by this object.
- * This is real interface bloat. Why not just use the physics controller
- * directly? I think this is because the python interface is in the wrong
- * place.
- */
-
- void
- ApplyForce(
- const MT_Vector3& force, bool local
- );
-
- void
- ApplyTorque(
- const MT_Vector3& torque,
- bool local
- );
-
- void
- ApplyRotation(
- const MT_Vector3& drot,
- bool local
- );
-
- void
- ApplyMovement(
- const MT_Vector3& dloc,
- bool local
- );
-
- void
- addLinearVelocity(
- const MT_Vector3& lin_vel,
- bool local
- );
-
- void
- setLinearVelocity(
- const MT_Vector3& lin_vel,
- bool local
- );
-
- void
- setAngularVelocity(
- const MT_Vector3& ang_vel,
- bool local
- );
-
- virtual float getLinearDamping() const;
- virtual float getAngularDamping() const;
- virtual void setLinearDamping(float damping);
- virtual void setAngularDamping(float damping);
- virtual void setDamping(float linear, float angular);
-
- /**
- * Update the physics object transform based upon the current SG_Node
- * position.
- */
- void
- UpdateTransform(
- );
-
- static void UpdateTransformFunc(SG_IObject* node, void* gameobj, void* scene);
-
- /**
- * only used for sensor objects
- */
- void SynchronizeTransform();
-
- static void SynchronizeTransformFunc(SG_IObject* node, void* gameobj, void* scene);
-
- /**
- * Function to set IPO option at start of IPO
- */
- void
- InitIPO(
- bool ipo_as_force,
- bool ipo_add,
- bool ipo_local
- );
-
- /**
- * Odd function to update an ipo. ???
- */
- void
- UpdateIPO(
- float curframetime,
- bool recurse
- );
- /**
- * Updates Material Ipo data
- */
- void
- UpdateMaterialData(
- dword matname_hash,
- MT_Vector4 rgba,
- MT_Vector3 specrgb,
- MT_Scalar hard,
- MT_Scalar spec,
- MT_Scalar ref,
- MT_Scalar emit,
- MT_Scalar alpha
- );
-
- /**
- * \section Mesh accessor functions.
- */
-
- /**
- * Update buckets to indicate that there is a new
- * user of this object's meshes.
- */
- void
- AddMeshUser(
- );
-
- /**
- * Update buckets with data about the mesh after
- * creating or duplicating the object, changing
- * visibility, object color, .. .
- */
- void
- UpdateBuckets(
- bool recursive
- );
-
- /**
- * Clear the meshes associated with this class
- * and remove from the bucketing system.
- * Don't think this actually deletes any of the meshes.
- */
- void
- RemoveMeshes(
- );
-
- /**
- * Add a mesh to the set of meshes associated with this
- * node. Meshes added in this way are not deleted by this class.
- * Make sure you call RemoveMeshes() before deleting the
- * mesh though,
- */
- void
- AddMesh(
- RAS_MeshObject* mesh
- ) {
- m_meshes.push_back(mesh);
- }
-
- /**
- * Add a level of detail mesh to the object. These should
- * be added in order.
- */
- void
- AddLodMesh(
- RAS_MeshObject* mesh
- );
-
- /**
- * Updates the current lod level based on distance from camera.
- */
- void
- UpdateLod(
- MT_Vector3 &cam_pos
- );
-
- /**
- * Pick out a mesh associated with the integer 'num'.
- */
- RAS_MeshObject*
- GetMesh(
- int num
- ) const {
- return m_meshes[num];
- }
-
- /**
- * Return the number of meshes currently associated with this
- * game object.
- */
- int
- GetMeshCount(
- ) const {
- return m_meshes.size();
- }
-
- /**
- * Set the debug color of the meshes associated with this
- * class. Does this still work?
- */
- void
- SetDebugColor(
- unsigned int bgra
- );
-
- /**
- * Reset the debug color of meshes associated with this class.
- */
- void
- ResetDebugColor(
- );
-
- /**
- * Was this object marked visible? (only for the explicit
- * visibility system).
- */
- bool
- GetVisible(
- void
- );
-
- /**
- * Set visibility flag of this object
- */
- void
- SetVisible(
- bool b,
- bool recursive
- );
-
- /**
- * Was this object culled?
- */
- inline bool
- GetCulled(
- void
- ) { return m_bCulled; }
-
- /**
- * Set culled flag of this object
- */
- inline void
- SetCulled(
- bool c
- ) { m_bCulled = c; }
-
- /**
- * Is this object an occluder?
- */
- inline bool
- GetOccluder(
- void
- ) { return m_bOccluder; }
-
- /**
- * Set occluder flag of this object
- */
- void
- SetOccluder(
- bool v,
- bool recursive
- );
-
- /**
- * Change the layer of the object (when it is added in another layer
- * than the original layer)
- */
- virtual void
- SetLayer(
- int l
- );
-
- /**
- * Get the object layer
- */
- int
- GetLayer(
- void
- );
-
- /**
- * Get the negative scaling state
- */
- bool
- IsNegativeScaling(
- void
- ) { return m_bIsNegativeScaling; }
-
- /**
- * \section Logic bubbling methods.
- */
-
- void RegisterCollisionCallbacks();
- void UnregisterCollisionCallbacks();
- void RunCollisionCallbacks(KX_GameObject *collider, const MT_Vector3 &point, const MT_Vector3 &normal);
- /**
- * Stop making progress
- */
- void Suspend(void);
-
- /**
- * Resume making progress
- */
- void Resume(void);
-
- void RegisterObstacle(KX_ObstacleSimulation* obstacleSimulation)
- {
- m_pObstacleSimulation = obstacleSimulation;
- }
-
- void UnregisterObstacle()
- {
- m_pObstacleSimulation = NULL;
- }
-
- /**
- * add debug object to the debuglist.
- */
- void SetUseDebugProperties(bool debug, bool recursive);
-
- KX_ClientObjectInfo* getClientInfo() { return m_pClient_info; }
-
- CListValue* GetChildren();
- CListValue* GetChildrenRecursive();
-
- KX_Scene* GetScene();
-
-#ifdef WITH_PYTHON
- /**
- * \section Python interface functions.
- */
- virtual PyObject *py_repr(void)
- {
- return PyUnicode_From_STR_String(GetName());
- }
-
- KX_PYMETHOD_O(KX_GameObject,SetWorldPosition);
- KX_PYMETHOD_VARARGS(KX_GameObject, ApplyForce);
- KX_PYMETHOD_VARARGS(KX_GameObject, ApplyTorque);
- KX_PYMETHOD_VARARGS(KX_GameObject, ApplyRotation);
- KX_PYMETHOD_VARARGS(KX_GameObject, ApplyMovement);
- KX_PYMETHOD_VARARGS(KX_GameObject,GetLinearVelocity);
- KX_PYMETHOD_VARARGS(KX_GameObject,SetLinearVelocity);
- KX_PYMETHOD_VARARGS(KX_GameObject,GetAngularVelocity);
- KX_PYMETHOD_VARARGS(KX_GameObject,SetAngularVelocity);
- KX_PYMETHOD_VARARGS(KX_GameObject,GetVelocity);
- KX_PYMETHOD_VARARGS(KX_GameObject,SetDamping);
-
- KX_PYMETHOD_NOARGS(KX_GameObject,GetReactionForce);
-
-
- KX_PYMETHOD_NOARGS(KX_GameObject,GetVisible);
- KX_PYMETHOD_VARARGS(KX_GameObject,SetVisible);
- KX_PYMETHOD_VARARGS(KX_GameObject,SetOcclusion);
- KX_PYMETHOD_NOARGS(KX_GameObject,GetState);
- KX_PYMETHOD_O(KX_GameObject,SetState);
- KX_PYMETHOD_VARARGS(KX_GameObject,AlignAxisToVect);
- KX_PYMETHOD_O(KX_GameObject,GetAxisVect);
- KX_PYMETHOD_VARARGS(KX_GameObject,SuspendDynamics);
- KX_PYMETHOD_NOARGS(KX_GameObject,RestoreDynamics);
- KX_PYMETHOD_NOARGS(KX_GameObject,EnableRigidBody);
- KX_PYMETHOD_NOARGS(KX_GameObject,DisableRigidBody);
- KX_PYMETHOD_VARARGS(KX_GameObject,ApplyImpulse);
- KX_PYMETHOD_O(KX_GameObject,SetCollisionMargin);
- KX_PYMETHOD_NOARGS(KX_GameObject,GetParent);
- KX_PYMETHOD_VARARGS(KX_GameObject,SetParent);
- KX_PYMETHOD_NOARGS(KX_GameObject,RemoveParent);
- KX_PYMETHOD_NOARGS(KX_GameObject,GetChildren);
- KX_PYMETHOD_NOARGS(KX_GameObject,GetChildrenRecursive);
- KX_PYMETHOD_VARARGS(KX_GameObject,GetMesh);
- KX_PYMETHOD_NOARGS(KX_GameObject,GetPhysicsId);
- KX_PYMETHOD_NOARGS(KX_GameObject,GetPropertyNames);
- KX_PYMETHOD_VARARGS(KX_GameObject,ReplaceMesh);
- KX_PYMETHOD_NOARGS(KX_GameObject,EndObject);
- KX_PYMETHOD_DOC(KX_GameObject,rayCastTo);
- KX_PYMETHOD_DOC(KX_GameObject,rayCast);
- KX_PYMETHOD_DOC_O(KX_GameObject,getDistanceTo);
- KX_PYMETHOD_DOC_O(KX_GameObject,getVectTo);
- KX_PYMETHOD_DOC_VARARGS(KX_GameObject, sendMessage);
- KX_PYMETHOD_VARARGS(KX_GameObject, ReinstancePhysicsMesh);
- KX_PYMETHOD_DOC(KX_GameObject, addDebugProperty);
-
- KX_PYMETHOD_DOC(KX_GameObject, playAction);
- KX_PYMETHOD_DOC(KX_GameObject, stopAction);
- KX_PYMETHOD_DOC(KX_GameObject, getActionFrame);
- KX_PYMETHOD_DOC(KX_GameObject, getActionName);
- KX_PYMETHOD_DOC(KX_GameObject, setActionFrame);
- KX_PYMETHOD_DOC(KX_GameObject, isPlayingAction);
-
- /* Dict access */
- KX_PYMETHOD_VARARGS(KX_GameObject,get);
-
- /* attributes */
- static PyObject* pyattr_get_name(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_parent(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
-
- static PyObject* pyattr_get_group_object(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_group_members(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_scene(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef);
-
- static PyObject* pyattr_get_life(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_mass(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_mass(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static PyObject* pyattr_get_is_suspend_dynamics(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_lin_vel_min(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_lin_vel_min(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static PyObject* pyattr_get_lin_vel_max(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_lin_vel_max(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static PyObject* pyattr_get_ang_vel_min(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_ang_vel_min(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static PyObject* pyattr_get_ang_vel_max(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_ang_vel_max(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static PyObject* pyattr_get_visible(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_visible(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static PyObject* pyattr_get_record_animation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_record_animation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static PyObject* pyattr_get_worldPosition(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_worldPosition(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static PyObject* pyattr_get_localPosition(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_localPosition(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static PyObject* pyattr_get_localInertia(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_localInertia(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static PyObject* pyattr_get_worldOrientation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_worldOrientation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static PyObject* pyattr_get_localOrientation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_localOrientation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static PyObject* pyattr_get_worldScaling(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_worldScaling(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static PyObject* pyattr_get_localScaling(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_localScaling(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static PyObject* pyattr_get_localTransform(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_localTransform(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static PyObject* pyattr_get_worldTransform(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_worldTransform(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static PyObject* pyattr_get_worldLinearVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_worldLinearVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static PyObject* pyattr_get_localLinearVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_localLinearVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static PyObject* pyattr_get_worldAngularVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_worldAngularVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static PyObject* pyattr_get_localAngularVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_localAngularVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static PyObject* pyattr_get_timeOffset(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_timeOffset(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static PyObject* pyattr_get_state(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_state(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static PyObject* pyattr_get_meshes(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_children(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_children_recursive(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_attrDict(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_obcolor(void *selv_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_obcolor(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static PyObject* pyattr_get_collisionCallbacks(void *selv_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_collisionCallbacks(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static PyObject* pyattr_get_collisionGroup(void *selv_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_collisionGroup(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static PyObject* pyattr_get_collisionMask(void *selv_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_collisionMask(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static PyObject* pyattr_get_debug(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_debug(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static PyObject* pyattr_get_debugRecursive(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_debugRecursive(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static PyObject* pyattr_get_linearDamping(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_linearDamping(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static PyObject* pyattr_get_angularDamping(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_angularDamping(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
-
- /* Experimental! */
- static PyObject* pyattr_get_sensors(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_controllers(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_actuators(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
-
- /* getitem/setitem */
- static PyMappingMethods Mapping;
- static PySequenceMethods Sequence;
-#endif
-};
-
-
-
-#endif /* __KX_GAMEOBJECT_H__ */
diff --git a/source/gameengine/Ketsji/KX_IInterpolator.h b/source/gameengine/Ketsji/KX_IInterpolator.h
deleted file mode 100644
index 6c0bf2d85cc..00000000000
--- a/source/gameengine/Ketsji/KX_IInterpolator.h
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file KX_IInterpolator.h
- * \ingroup ketsji
- */
-
-#ifndef __KX_IINTERPOLATOR_H__
-#define __KX_IINTERPOLATOR_H__
-
-#include <vector>
-
-#ifdef WITH_CXX_GUARDEDALLOC
-#include "MEM_guardedalloc.h"
-#endif
-
-class KX_IInterpolator {
-public:
- virtual ~KX_IInterpolator() {}
-
- virtual void Execute(float currentTime) const = 0;
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:KX_IInterpolator")
-#endif
-};
-
-typedef std::vector<KX_IInterpolator *> T_InterpolatorList;
-
-#endif
-
diff --git a/source/gameengine/Ketsji/KX_IPOTransform.h b/source/gameengine/Ketsji/KX_IPOTransform.h
deleted file mode 100644
index a81c432b01e..00000000000
--- a/source/gameengine/Ketsji/KX_IPOTransform.h
+++ /dev/null
@@ -1,87 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file KX_IPOTransform.h
- * \ingroup ketsji
- * \brief An abstract object you can move around in a 3d world, and has some logic
- */
-
-#ifndef __KX_IPOTRANSFORM_H__
-#define __KX_IPOTRANSFORM_H__
-
-#include "MT_Transform.h"
-
-class KX_IPOTransform {
-public:
- KX_IPOTransform() :
- m_position(0.0f, 0.0f, 0.0f),
- m_eulerAngles(0.0f, 0.0f, 0.0f),
- m_scaling(1.0f, 1.0f, 1.0f),
- m_deltaPosition(0.0f, 0.0f, 0.0f),
- m_deltaEulerAngles(0.0f, 0.0f, 0.0f),
- m_deltaScaling(0.0f, 0.0f, 0.0f)
- {}
-
- MT_Transform GetTransform() const {
- return MT_Transform(m_position + m_deltaPosition,
- MT_Matrix3x3(m_eulerAngles + m_deltaEulerAngles,
- m_scaling + m_deltaScaling));
- }
-
- MT_Point3& GetPosition() { return m_position; }
- MT_Vector3& GetEulerAngles() { return m_eulerAngles; }
- MT_Vector3& GetScaling() { return m_scaling; }
-
- const MT_Point3& GetPosition() const { return m_position; }
- const MT_Vector3& GetEulerAngles() const { return m_eulerAngles; }
- const MT_Vector3& GetScaling() const { return m_scaling; }
-
- MT_Vector3& GetDeltaPosition() { return m_deltaPosition; }
- MT_Vector3& GetDeltaEulerAngles() { return m_deltaEulerAngles; }
- MT_Vector3& GetDeltaScaling() { return m_deltaScaling; }
-
- void SetPosition(const MT_Point3& pos) { m_position = pos; }
- void SetEulerAngles(const MT_Vector3& eul) { m_eulerAngles = eul; }
- void SetScaling(const MT_Vector3& scaling) { m_scaling = scaling; }
-
- void ClearDeltaStuff() {
- m_deltaPosition.setValue(0.0f, 0.0f, 0.0f);
- m_deltaEulerAngles.setValue(0.0f, 0.0f, 0.0f);
- m_deltaScaling.setValue(0.0f, 0.0f, 0.0f);
- }
-
-protected:
- MT_Point3 m_position;
- MT_Vector3 m_eulerAngles;
- MT_Vector3 m_scaling;
- MT_Vector3 m_deltaPosition;
- MT_Vector3 m_deltaEulerAngles;
- MT_Vector3 m_deltaScaling;
-};
-
-#endif
-
diff --git a/source/gameengine/Ketsji/KX_IPO_SGController.cpp b/source/gameengine/Ketsji/KX_IPO_SGController.cpp
deleted file mode 100644
index be1a4b4ef3a..00000000000
--- a/source/gameengine/Ketsji/KX_IPO_SGController.cpp
+++ /dev/null
@@ -1,373 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- * Scenegraph controller for ipos.
- */
-
-/** \file gameengine/Ketsji/KX_IPO_SGController.cpp
- * \ingroup ketsji
- */
-
-
-#if defined(_WIN64)
-typedef unsigned __int64 uint_ptr;
-#else
-typedef unsigned long uint_ptr;
-#endif
-
-#ifdef _MSC_VER
- /* This warning tells us about truncation of __long__ stl-generated names.
- * It can occasionally cause DevStudio to have internal compiler warnings. */
-# pragma warning(disable:4786)
-#endif
-
-#include "KX_IPO_SGController.h"
-#include "KX_ScalarInterpolator.h"
-#include "KX_GameObject.h"
-#include "PHY_IPhysicsController.h"
-#include "DNA_ipo_types.h"
-#include "BLI_math.h"
-
-// All objects should start on frame 1! Will we ever need an object to
-// start on another frame, the 1.0 should change.
-KX_IpoSGController::KX_IpoSGController()
-: m_ipo_as_force(false),
- m_ipo_add(false),
- m_ipo_local(false),
- m_modified(true),
- m_ipotime(1.0),
- m_ipo_start_initialized(false),
- m_ipo_start_euler(0.0f, 0.0f, 0.0f),
- m_ipo_euler_initialized(false)
-{
- m_game_object = NULL;
- for (int i = 0; i < KX_MAX_IPO_CHANNELS; i++)
- m_ipo_channels_active[i] = false;
-}
-
-
-void KX_IpoSGController::SetOption(int option, int value)
-{
- switch (option) {
- case SG_CONTR_IPO_IPO_AS_FORCE:
- m_ipo_as_force = (value != 0);
- m_modified = true;
- break;
- case SG_CONTR_IPO_IPO_ADD:
- m_ipo_add = (value != 0);
- m_modified = true;
- break;
- case SG_CONTR_IPO_RESET:
- if (m_ipo_start_initialized && value) {
- m_ipo_start_initialized = false;
- m_modified = true;
- }
- break;
- case SG_CONTR_IPO_LOCAL:
- if (value/* && ((SG_Node*)m_pObject)->GetSGParent() == NULL*/) {
- // only accept local Ipo if the object has no parent
- m_ipo_local = true;
- }
- else {
- m_ipo_local = false;
- }
- m_modified = true;
- break;
- default:
- ; /* just ignore the rest */
- }
-}
-
-void KX_IpoSGController::UpdateSumoReference()
-{
- if (m_game_object) {
- }
-}
-
-void KX_IpoSGController::SetGameObject(KX_GameObject *go)
-{
- m_game_object = go;
-}
-
-bool KX_IpoSGController::Update(double currentTime)
-{
- if (m_modified) {
- T_InterpolatorList::iterator i;
- for (i = m_interpolators.begin(); i != m_interpolators.end(); ++i) {
- (*i)->Execute(m_ipotime);//currentTime);
- }
-
- SG_Spatial *ob = (SG_Spatial *)m_pObject;
-
- //initialization on the first frame of the IPO
- if (!m_ipo_start_initialized) {
- m_ipo_start_point = ob->GetLocalPosition();
- m_ipo_start_orient = ob->GetLocalOrientation();
- m_ipo_start_scale = ob->GetLocalScale();
- m_ipo_start_initialized = true;
- if (!m_ipo_euler_initialized) {
- // do it only once to avoid angle discontinuities
- m_ipo_start_orient.getEuler(m_ipo_start_euler[0], m_ipo_start_euler[1], m_ipo_start_euler[2]);
- m_ipo_euler_initialized = true;
- }
- }
-
- //modifies position?
- if (m_ipo_channels_active[OB_LOC_X] || m_ipo_channels_active[OB_LOC_Y] || m_ipo_channels_active[OB_LOC_Z] ||
- m_ipo_channels_active[OB_DLOC_X] || m_ipo_channels_active[OB_DLOC_Y] || m_ipo_channels_active[OB_DLOC_Z])
- {
- if (m_ipo_as_force == true) {
- if (m_game_object && ob && m_game_object->GetPhysicsController()) {
- MT_Vector3 vec = m_ipo_local ?
- ob->GetWorldOrientation() * m_ipo_xform.GetPosition() :
- m_ipo_xform.GetPosition();
- m_game_object->GetPhysicsController()->ApplyForce(vec, false);
- }
- }
- else {
- // Local ipo should be defined with the object position at (0,0,0)
- // Local transform is applied to the object based on initial position
- MT_Point3 newPosition(0.0f, 0.0f, 0.0f);
-
- if (!m_ipo_add)
- newPosition = ob->GetLocalPosition();
- //apply separate IPO channels if there is any data in them
- //Loc and dLoc act by themselves or are additive
- //LocX and dLocX
- if (m_ipo_channels_active[OB_LOC_X]) {
- newPosition[0] = (m_ipo_channels_active[OB_DLOC_X] ? m_ipo_xform.GetPosition()[0] + m_ipo_xform.GetDeltaPosition()[0] : m_ipo_xform.GetPosition()[0]);
- }
- else if (m_ipo_channels_active[OB_DLOC_X] && m_ipo_start_initialized) {
- newPosition[0] = (((!m_ipo_add) ? m_ipo_start_point[0] : 0.0f) + m_ipo_xform.GetDeltaPosition()[0]);
- }
- //LocY and dLocY
- if (m_ipo_channels_active[OB_LOC_Y]) {
- newPosition[1] = (m_ipo_channels_active[OB_DLOC_Y] ? m_ipo_xform.GetPosition()[1] + m_ipo_xform.GetDeltaPosition()[1] : m_ipo_xform.GetPosition()[1]);
- }
- else if (m_ipo_channels_active[OB_DLOC_Y] && m_ipo_start_initialized) {
- newPosition[1] = (((!m_ipo_add) ? m_ipo_start_point[1] : 0.0f) + m_ipo_xform.GetDeltaPosition()[1]);
- }
- //LocZ and dLocZ
- if (m_ipo_channels_active[OB_LOC_Z]) {
- newPosition[2] = (m_ipo_channels_active[OB_DLOC_Z] ? m_ipo_xform.GetPosition()[2] + m_ipo_xform.GetDeltaPosition()[2] : m_ipo_xform.GetPosition()[2]);
- }
- else if (m_ipo_channels_active[OB_DLOC_Z] && m_ipo_start_initialized) {
- newPosition[2] = (((!m_ipo_add) ? m_ipo_start_point[2] : 0.0f) + m_ipo_xform.GetDeltaPosition()[2]);
- }
- if (m_ipo_add) {
- if (m_ipo_local)
- newPosition = m_ipo_start_point + m_ipo_start_scale*(m_ipo_start_orient*newPosition);
- else
- newPosition = m_ipo_start_point + newPosition;
- }
- if (m_game_object)
- m_game_object->NodeSetLocalPosition(newPosition);
- }
- }
- //modifies orientation?
- if (m_ipo_channels_active[OB_ROT_X] || m_ipo_channels_active[OB_ROT_Y] || m_ipo_channels_active[OB_ROT_Z] ||
- m_ipo_channels_active[OB_DROT_X] || m_ipo_channels_active[OB_DROT_Y] || m_ipo_channels_active[OB_DROT_Z])
- {
- if (m_ipo_as_force) {
- if (m_game_object && ob) {
- m_game_object->ApplyTorque(m_ipo_local ?
- ob->GetWorldOrientation() * m_ipo_xform.GetEulerAngles() :
- m_ipo_xform.GetEulerAngles(), false);
- }
- }
- else if (m_ipo_add) {
- if (m_ipo_start_initialized) {
- double yaw = 0.0, pitch = 0.0, roll = 0.0; //delta Euler angles
-
- //RotX and dRotX
- if (m_ipo_channels_active[OB_ROT_X])
- yaw += m_ipo_xform.GetEulerAngles()[0];
- if (m_ipo_channels_active[OB_DROT_X])
- yaw += m_ipo_xform.GetDeltaEulerAngles()[0];
-
- //RotY dRotY
- if (m_ipo_channels_active[OB_ROT_Y])
- pitch += m_ipo_xform.GetEulerAngles()[1];
- if (m_ipo_channels_active[OB_DROT_Y])
- pitch += m_ipo_xform.GetDeltaEulerAngles()[1];
-
- //RotZ and dRotZ
- if (m_ipo_channels_active[OB_ROT_Z])
- roll += m_ipo_xform.GetEulerAngles()[2];
- if (m_ipo_channels_active[OB_DROT_Z])
- roll += m_ipo_xform.GetDeltaEulerAngles()[2];
-
- MT_Matrix3x3 rotation(MT_Vector3(yaw, pitch, roll));
- if (m_ipo_local)
- rotation = m_ipo_start_orient * rotation;
- else
- rotation = rotation * m_ipo_start_orient;
- if (m_game_object)
- m_game_object->NodeSetLocalOrientation(rotation);
- }
- }
- else if (m_ipo_channels_active[OB_ROT_X] || m_ipo_channels_active[OB_ROT_Y] || m_ipo_channels_active[OB_ROT_Z]) {
- if (m_ipo_euler_initialized) {
- // assume all channel absolute
- // All 3 channels should be specified but if they are not, we will take
- // the value at the start of the game to avoid angle sign reversal
- double yaw = m_ipo_start_euler[0], pitch = m_ipo_start_euler[1], roll = m_ipo_start_euler[2];
-
- //RotX and dRotX
- if (m_ipo_channels_active[OB_ROT_X]) {
- yaw = (m_ipo_channels_active[OB_DROT_X] ? (m_ipo_xform.GetEulerAngles()[0] + m_ipo_xform.GetDeltaEulerAngles()[0]) : m_ipo_xform.GetEulerAngles()[0] );
- }
- else if (m_ipo_channels_active[OB_DROT_X]) {
- yaw += m_ipo_xform.GetDeltaEulerAngles()[0];
- }
-
- //RotY dRotY
- if (m_ipo_channels_active[OB_ROT_Y]) {
- pitch = (m_ipo_channels_active[OB_DROT_Y] ? (m_ipo_xform.GetEulerAngles()[1] + m_ipo_xform.GetDeltaEulerAngles()[1]) : m_ipo_xform.GetEulerAngles()[1] );
- }
- else if (m_ipo_channels_active[OB_DROT_Y]) {
- pitch += m_ipo_xform.GetDeltaEulerAngles()[1];
- }
-
- //RotZ and dRotZ
- if (m_ipo_channels_active[OB_ROT_Z]) {
- roll = (m_ipo_channels_active[OB_DROT_Z] ? (m_ipo_xform.GetEulerAngles()[2] + m_ipo_xform.GetDeltaEulerAngles()[2]) : m_ipo_xform.GetEulerAngles()[2] );
- }
- else if (m_ipo_channels_active[OB_DROT_Z]) {
- roll += m_ipo_xform.GetDeltaEulerAngles()[2];
- }
- if (m_game_object)
- m_game_object->NodeSetLocalOrientation(MT_Vector3(yaw, pitch, roll));
- }
- }
- else if (m_ipo_start_initialized) {
- // only DROT, treat as Add
- double yaw = 0.0, pitch = 0.0, roll = 0.0; //delta Euler angles
-
- //dRotX
- if (m_ipo_channels_active[OB_DROT_X])
- yaw = m_ipo_xform.GetDeltaEulerAngles()[0];
-
- //dRotY
- if (m_ipo_channels_active[OB_DROT_Y])
- pitch = m_ipo_xform.GetDeltaEulerAngles()[1];
-
- //dRotZ
- if (m_ipo_channels_active[OB_DROT_Z])
- roll = m_ipo_xform.GetDeltaEulerAngles()[2];
-
- // dRot are always local
- MT_Matrix3x3 rotation(MT_Vector3(yaw, pitch, roll));
- rotation = m_ipo_start_orient * rotation;
- if (m_game_object)
- m_game_object->NodeSetLocalOrientation(rotation);
- }
- }
- //modifies scale?
- if (m_ipo_channels_active[OB_SIZE_X] || m_ipo_channels_active[OB_SIZE_Y] || m_ipo_channels_active[OB_SIZE_Z] ||
- m_ipo_channels_active[OB_DSIZE_X] || m_ipo_channels_active[OB_DSIZE_Y] || m_ipo_channels_active[OB_DSIZE_Z])
- {
- //default is no scale change
- MT_Vector3 newScale(1.0f, 1.0f, 1.0f);
- if (!m_ipo_add)
- newScale = ob->GetLocalScale();
-
- if (m_ipo_channels_active[OB_SIZE_X]) {
- newScale[0] = (m_ipo_channels_active[OB_DSIZE_X] ? (m_ipo_xform.GetScaling()[0] + m_ipo_xform.GetDeltaScaling()[0]) : m_ipo_xform.GetScaling()[0]);
- }
- else if (m_ipo_channels_active[OB_DSIZE_X] && m_ipo_start_initialized) {
- newScale[0] = (m_ipo_xform.GetDeltaScaling()[0] + ((!m_ipo_add) ? m_ipo_start_scale[0] : 0.0f));
- }
-
- //RotY dRotY
- if (m_ipo_channels_active[OB_SIZE_Y]) {
- newScale[1] = (m_ipo_channels_active[OB_DSIZE_Y] ? (m_ipo_xform.GetScaling()[1] + m_ipo_xform.GetDeltaScaling()[1]): m_ipo_xform.GetScaling()[1]);
- }
- else if (m_ipo_channels_active[OB_DSIZE_Y] && m_ipo_start_initialized) {
- newScale[1] = (m_ipo_xform.GetDeltaScaling()[1] + ((!m_ipo_add)?m_ipo_start_scale[1] : 0.0f));
- }
-
- //RotZ and dRotZ
- if (m_ipo_channels_active[OB_SIZE_Z]) {
- newScale[2] = (m_ipo_channels_active[OB_DSIZE_Z] ? (m_ipo_xform.GetScaling()[2] + m_ipo_xform.GetDeltaScaling()[2]) : m_ipo_xform.GetScaling()[2]);
- }
- else if (m_ipo_channels_active[OB_DSIZE_Z] && m_ipo_start_initialized) {
- newScale[2] = (m_ipo_xform.GetDeltaScaling()[2] + ((!m_ipo_add)?m_ipo_start_scale[2] : 1.0f));
- }
-
- if (m_ipo_add) {
- newScale = m_ipo_start_scale * newScale;
- }
- if (m_game_object)
- m_game_object->NodeSetLocalScale(newScale);
- }
- m_modified = false;
- }
- return false;
-}
-
-void KX_IpoSGController::AddInterpolator(KX_IInterpolator *interp)
-{
- m_interpolators.push_back(interp);
-}
-
-SG_Controller *KX_IpoSGController::GetReplica(SG_Node *destnode)
-{
- KX_IpoSGController *iporeplica = new KX_IpoSGController(*this);
- // clear object that ipo acts on in the replica.
- iporeplica->ClearObject();
- iporeplica->SetGameObject((KX_GameObject *)destnode->GetSGClientObject());
-
- // dirty hack, ask Gino for a better solution in the ipo implementation
- // hacken en zagen, in what we call datahiding, not written for replication :(
-
- T_InterpolatorList oldlist = m_interpolators;
- iporeplica->m_interpolators.clear();
-
- T_InterpolatorList::iterator i;
- for (i = oldlist.begin(); i != oldlist.end(); ++i) {
- KX_ScalarInterpolator *copyipo = new KX_ScalarInterpolator(*((KX_ScalarInterpolator *)*i));
- iporeplica->AddInterpolator(copyipo);
-
- MT_Scalar *scaal = ((KX_ScalarInterpolator *)*i)->GetTarget();
- uint_ptr orgbase = (uint_ptr)&m_ipo_xform;
- uint_ptr orgloc = (uint_ptr)scaal;
- uint_ptr offset = orgloc - orgbase;
- uint_ptr newaddrbase = (uint_ptr)&iporeplica->m_ipo_xform;
- newaddrbase += offset;
- MT_Scalar *blaptr = (MT_Scalar *) newaddrbase;
- copyipo->SetNewTarget((MT_Scalar *)blaptr);
- }
-
- return iporeplica;
-}
-
-KX_IpoSGController::~KX_IpoSGController()
-{
- T_InterpolatorList::iterator i;
- for (i = m_interpolators.begin(); i != m_interpolators.end(); ++i) {
- delete (*i);
- }
-}
diff --git a/source/gameengine/Ketsji/KX_IPO_SGController.h b/source/gameengine/Ketsji/KX_IPO_SGController.h
deleted file mode 100644
index 3318761bb88..00000000000
--- a/source/gameengine/Ketsji/KX_IPO_SGController.h
+++ /dev/null
@@ -1,124 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file KX_IPO_SGController.h
- * \ingroup ketsji
- */
-
-#ifndef __KX_IPO_SGCONTROLLER_H__
-#define __KX_IPO_SGCONTROLLER_H__
-
-#include "SG_Controller.h"
-#include "SG_Spatial.h"
-
-#include "KX_IPOTransform.h"
-#include "KX_IInterpolator.h"
-
-#define KX_MAX_IPO_CHANNELS 19 //note- [0] is not used
-
-class KX_IpoSGController : public SG_Controller
-{
- KX_IPOTransform m_ipo_xform;
- T_InterpolatorList m_interpolators;
-
- /** Flag for each IPO channel that can be applied to a game object */
- bool m_ipo_channels_active[KX_MAX_IPO_CHANNELS];
-
- /** Interpret the ipo as a force rather than a displacement? */
- bool m_ipo_as_force;
-
- /** Add Ipo curve to current loc/rot/scale */
- bool m_ipo_add;
-
- /** Ipo must be applied in local coordinate rather than in global coordinates (used for force and Add mode)*/
- bool m_ipo_local;
-
- /** Were settings altered since the last update? */
- bool m_modified;
-
- /** Local time of this ipo.*/
- double m_ipotime;
-
- /** Location of the object when the IPO is first fired (for local transformations) */
- MT_Point3 m_ipo_start_point;
-
- /** Orientation of the object when the IPO is first fired (for local transformations) */
- MT_Matrix3x3 m_ipo_start_orient;
-
- /** Scale of the object when the IPO is first fired (for local transformations) */
- MT_Vector3 m_ipo_start_scale;
-
- /** if IPO initial position has been set for local normal IPO */
- bool m_ipo_start_initialized;
-
- /** Euler angles at the start of the game, needed for incomplete ROT Ipo curves */
- MT_Vector3 m_ipo_start_euler;
-
- /** true is m_ipo_start_euler has been initialized */
- bool m_ipo_euler_initialized;
-
- /** A reference to the original game object. */
- class KX_GameObject *m_game_object;
-
-public:
- KX_IpoSGController();
-
- virtual ~KX_IpoSGController();
-
- virtual SG_Controller *GetReplica(class SG_Node *destnode);
-
- void SetOption(int option, int value);
-
- /** Set sumo data. */
- void UpdateSumoReference();
- /** Set reference to the corresponding game object. */
- void SetGameObject(class KX_GameObject *go);
-
- void SetIPOChannelActive(int index, bool value) {
- //indexes found in makesdna\DNA_ipo_types.h
- m_ipo_channels_active[index] = value;
- }
-
- KX_IPOTransform &GetIPOTransform()
- {
- return m_ipo_xform;
- }
-
- void AddInterpolator(KX_IInterpolator *interp);
- virtual bool Update(double time);
- virtual void SetSimulatedTime(double time)
- {
- m_ipotime = time;
- m_modified = true;
- }
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:KX_IpoSGController")
-#endif
-};
-
-#endif /* __KX_IPO_SGCONTROLLER_H__ */
diff --git a/source/gameengine/Ketsji/KX_IScalarInterpolator.h b/source/gameengine/Ketsji/KX_IScalarInterpolator.h
deleted file mode 100644
index 1e822c49c6d..00000000000
--- a/source/gameengine/Ketsji/KX_IScalarInterpolator.h
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file KX_IScalarInterpolator.h
- * \ingroup ketsji
- */
-
-#ifndef __KX_ISCALARINTERPOLATOR_H__
-#define __KX_ISCALARINTERPOLATOR_H__
-
-#ifdef WITH_CXX_GUARDEDALLOC
-#include "MEM_guardedalloc.h"
-#endif
-
-class KX_IScalarInterpolator {
-public:
- virtual ~KX_IScalarInterpolator() {}
-
- virtual float GetValue(float currentTime) const = 0;
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:KX_IScalarInterpolator")
-#endif
-};
-
-#endif
-
diff --git a/source/gameengine/Ketsji/KX_ISceneConverter.h b/source/gameengine/Ketsji/KX_ISceneConverter.h
deleted file mode 100644
index 1963fc7c48f..00000000000
--- a/source/gameengine/Ketsji/KX_ISceneConverter.h
+++ /dev/null
@@ -1,103 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file KX_ISceneConverter.h
- * \ingroup ketsji
- */
-
-#ifndef __KX_ISCENECONVERTER_H__
-#define __KX_ISCENECONVERTER_H__
-
-#include "STR_String.h"
-#include "EXP_Python.h"
-
-#ifdef WITH_CXX_GUARDEDALLOC
-#include "MEM_guardedalloc.h"
-#endif
-
-struct Scene;
-
-class KX_ISceneConverter
-{
-
-public:
- KX_ISceneConverter() {}
- virtual ~KX_ISceneConverter () {}
-
- /*
- * scenename: name of the scene to be converted,
- * if the scenename is empty, convert the 'default' scene (whatever this means)
- * destinationscene: pass an empty scene, everything goes into this
- * dictobj: python dictionary (for pythoncontrollers)
- */
- virtual void ConvertScene(
- class KX_Scene* destinationscene,
- class RAS_IRasterizer* rendertools,
- class RAS_ICanvas* canvas,
- bool libloading=false)=0;
-
- virtual void RemoveScene(class KX_Scene *scene)=0;
-
- // handle any pending merges from asynchronous loads
- virtual void MergeAsyncLoads()=0;
- virtual void FinalizeAsyncLoads() = 0;
-
- virtual void SetAlwaysUseExpandFraming(bool to_what) = 0;
-
- virtual void SetNewFileName(const STR_String& filename) = 0;
- virtual bool TryAndLoadNewFile() = 0;
-
- virtual void ResetPhysicsObjectsAnimationIpo(bool clearIpo) = 0;
-
- ///this generates ipo curves for position, rotation, allowing to use game physics in animation
- virtual void WritePhysicsObjectToAnimationIpo(int frameNumber) = 0;
- virtual void TestHandlesPhysicsObjectToAnimationIpo() = 0;
-
- ///this is for reseting the position,rotation and scale of the gameobjet that is not dynamic
- virtual void resetNoneDynamicObjectToIpo()=0;
-
- // use blender materials
- virtual void SetMaterials(bool val) =0;
- virtual bool GetMaterials()=0;
-
- // use blender glsl materials
- virtual void SetGLSLMaterials(bool val) =0;
- virtual bool GetGLSLMaterials()=0;
-
- // cache materials during conversion
- virtual void SetCacheMaterials(bool val) =0;
- virtual bool GetCacheMaterials()=0;
-
- virtual struct Scene* GetBlenderSceneForName(const STR_String& name)=0;
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:KX_ISceneConverter")
-#endif
-};
-
-#endif /* __KX_ISCENECONVERTER_H__ */
diff --git a/source/gameengine/Ketsji/KX_ISystem.h b/source/gameengine/Ketsji/KX_ISystem.h
deleted file mode 100644
index 4ba71f8d239..00000000000
--- a/source/gameengine/Ketsji/KX_ISystem.h
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file KX_ISystem.h
- * \ingroup ketsji
- * \brief Abstract system
- */
-
-#ifndef __KX_ISYSTEM_H__
-#define __KX_ISYSTEM_H__
-
-#include <vector>
-using namespace std;
-
-#include "STR_String.h"
-
-#ifdef WITH_CXX_GUARDEDALLOC
-#include "MEM_guardedalloc.h"
-#endif
-
-/**
- * System Abstraction, needed only for getting some timing stuff from the host.
- */
-class KX_ISystem
-{
-public:
- KX_ISystem() {};
- virtual ~KX_ISystem() {};
-
- virtual double GetTimeInSeconds()=0;
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:KX_ISystem")
-#endif
-};
-
-#endif
-
diff --git a/source/gameengine/Ketsji/KX_IpoConvert.cpp b/source/gameengine/Ketsji/KX_IpoConvert.cpp
deleted file mode 100644
index 7b00760ee7b..00000000000
--- a/source/gameengine/Ketsji/KX_IpoConvert.cpp
+++ /dev/null
@@ -1,441 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Ketsji/KX_IpoConvert.cpp
- * \ingroup bgeconv
- */
-
-#ifdef _MSC_VER
- /* don't show stl-warnings */
-# pragma warning (disable:4786)
-#endif
-
-#include "BKE_material.h" /* give_current_material */
-
-#include "KX_GameObject.h"
-#include "KX_IpoConvert.h"
-#include "KX_IInterpolator.h"
-#include "KX_ScalarInterpolator.h"
-
-#include "KX_BlenderScalarInterpolator.h"
-#include "KX_BlenderSceneConverter.h"
-
-
-/* This little block needed for linking to Blender... */
-#ifdef WIN32
-#include "BLI_winstuff.h"
-#endif
-
-#include "DNA_object_types.h"
-#include "DNA_action_types.h"
-#include "DNA_anim_types.h"
-#include "DNA_ipo_types.h"
-#include "DNA_lamp_types.h"
-#include "DNA_world_types.h"
-#include "DNA_camera_types.h"
-#include "DNA_material_types.h"
-/* end of blender include block */
-
-#include "KX_IPO_SGController.h"
-#include "KX_LightIpoSGController.h"
-#include "KX_CameraIpoSGController.h"
-#include "KX_WorldIpoController.h"
-#include "KX_ObColorIpoSGController.h"
-#include "KX_MaterialIpoController.h"
-
-#include "SG_Node.h"
-
-#include "STR_HashedString.h"
-
-static BL_InterpolatorList *GetAdtList(struct bAction *for_act, KX_BlenderSceneConverter *converter)
-{
- BL_InterpolatorList *adtList= converter->FindInterpolatorList(for_act);
-
- if (!adtList) {
- adtList = new BL_InterpolatorList(for_act);
- converter->RegisterInterpolatorList(adtList, for_act);
- }
-
- return adtList;
-}
-
-SG_Controller *BL_CreateIPO(struct bAction *action, KX_GameObject* gameobj, KX_BlenderSceneConverter *converter)
-{
- KX_IpoSGController* ipocontr = new KX_IpoSGController();
- ipocontr->SetGameObject(gameobj);
-
- Object* blenderobject = gameobj->GetBlenderObject();
-
- ipocontr->GetIPOTransform().SetPosition(MT_Point3(blenderobject->loc));
- ipocontr->GetIPOTransform().SetEulerAngles(MT_Vector3(blenderobject->rot));
- ipocontr->GetIPOTransform().SetScaling(MT_Vector3(blenderobject->size));
-
- const char *rotmode, *drotmode;
-
- switch (blenderobject->rotmode) {
- case ROT_MODE_AXISANGLE:
- rotmode = "rotation_axis_angle";
- drotmode = "delta_rotation_axis_angle";
- break;
- case ROT_MODE_QUAT: /* XXX, this isn't working, currently only eulers are supported [#28853] */
- rotmode = "rotation_quaternion";
- drotmode = "delta_rotation_quaternion";
- break;
- default:
- rotmode = "rotation_euler";
- drotmode = "delta_rotation_euler";
- break;
- }
-
- BL_InterpolatorList *adtList= GetAdtList(action, converter);
-
- // For each active channel in the adtList add an
- // interpolator to the game object.
-
- KX_IInterpolator *interpolator;
- KX_IScalarInterpolator *interp;
-
- for (int i=0; i<3; i++) {
- if ((interp = adtList->GetScalarInterpolator("location", i))) {
- interpolator= new KX_ScalarInterpolator(&(ipocontr->GetIPOTransform().GetPosition()[i]), interp);
- ipocontr->AddInterpolator(interpolator);
- ipocontr->SetIPOChannelActive(OB_LOC_X+i, true);
- }
- }
- for (int i=0; i<3; i++) {
- if ((interp = adtList->GetScalarInterpolator("delta_location", i))) {
- interpolator= new KX_ScalarInterpolator(&(ipocontr->GetIPOTransform().GetDeltaPosition()[i]), interp);
- ipocontr->AddInterpolator(interpolator);
- ipocontr->SetIPOChannelActive(OB_DLOC_X+i, true);
- }
- }
- for (int i=0; i<3; i++) {
- if ((interp = adtList->GetScalarInterpolator(rotmode, i))) {
- interpolator= new KX_ScalarInterpolator(&(ipocontr->GetIPOTransform().GetEulerAngles()[i]), interp);
- ipocontr->AddInterpolator(interpolator);
- ipocontr->SetIPOChannelActive(OB_ROT_X+i, true);
- }
- }
- for (int i=0; i<3; i++) {
- if ((interp = adtList->GetScalarInterpolator(drotmode, i))) {
- interpolator= new KX_ScalarInterpolator(&(ipocontr->GetIPOTransform().GetDeltaEulerAngles()[i]), interp);
- ipocontr->AddInterpolator(interpolator);
- ipocontr->SetIPOChannelActive(OB_DROT_X+i, true);
- }
- }
- for (int i=0; i<3; i++) {
- if ((interp = adtList->GetScalarInterpolator("scale", i))) {
- interpolator= new KX_ScalarInterpolator(&(ipocontr->GetIPOTransform().GetScaling()[i]), interp);
- ipocontr->AddInterpolator(interpolator);
- ipocontr->SetIPOChannelActive(OB_SIZE_X+i, true);
- }
- }
- for (int i=0; i<3; i++) {
- if ((interp = adtList->GetScalarInterpolator("delta_scale", i))) {
- interpolator= new KX_ScalarInterpolator(&(ipocontr->GetIPOTransform().GetDeltaScaling()[i]), interp);
- ipocontr->AddInterpolator(interpolator);
- ipocontr->SetIPOChannelActive(OB_DSIZE_X+i, true);
- }
- }
-
-
- return ipocontr;
-}
-
-
-SG_Controller *BL_CreateObColorIPO(struct bAction *action, KX_GameObject* gameobj, KX_BlenderSceneConverter *converter)
-{
- KX_ObColorIpoSGController* ipocontr_obcol=NULL;
- KX_IInterpolator *interpolator;
- KX_IScalarInterpolator *interp;
- BL_InterpolatorList *adtList= GetAdtList(action, converter);
-
- for (int i=0; i<4; i++) {
- if ((interp = adtList->GetScalarInterpolator("color", i))) {
- if (!ipocontr_obcol) {
- ipocontr_obcol = new KX_ObColorIpoSGController();
- }
- interpolator= new KX_ScalarInterpolator(&ipocontr_obcol->m_rgba[i], interp);
- ipocontr_obcol->AddInterpolator(interpolator);
- }
- }
-
- return ipocontr_obcol;
-}
-
-SG_Controller *BL_CreateLampIPO(struct bAction *action, KX_GameObject* lightobj, KX_BlenderSceneConverter *converter)
-{
- KX_LightIpoSGController* ipocontr = new KX_LightIpoSGController();
-
- Lamp *blenderlamp = (Lamp*)lightobj->GetBlenderObject()->data;
-
- ipocontr->m_energy = blenderlamp->energy;
- ipocontr->m_col_rgb[0] = blenderlamp->r;
- ipocontr->m_col_rgb[1] = blenderlamp->g;
- ipocontr->m_col_rgb[2] = blenderlamp->b;
- ipocontr->m_dist = blenderlamp->dist;
-
- BL_InterpolatorList *adtList= GetAdtList(action, converter);
-
- // For each active channel in the adtList add an
- // interpolator to the game object.
-
- KX_IInterpolator *interpolator;
- KX_IScalarInterpolator *interp;
-
- if ((interp= adtList->GetScalarInterpolator("energy", 0))) {
- interpolator= new KX_ScalarInterpolator(&ipocontr->m_energy, interp);
- ipocontr->AddInterpolator(interpolator);
- ipocontr->SetModifyEnergy(true);
- }
-
- if ((interp = adtList->GetScalarInterpolator("distance", 0))) {
- interpolator= new KX_ScalarInterpolator(&ipocontr->m_dist, interp);
- ipocontr->AddInterpolator(interpolator);
- ipocontr->SetModifyDist(true);
- }
-
- for (int i=0; i<3; i++) {
- if ((interp = adtList->GetScalarInterpolator("color", i))) {
- interpolator= new KX_ScalarInterpolator(&ipocontr->m_col_rgb[i], interp);
- ipocontr->AddInterpolator(interpolator);
- ipocontr->SetModifyColor(true);
- }
- }
-
- return ipocontr;
-}
-
-SG_Controller *BL_CreateCameraIPO(struct bAction *action, KX_GameObject* cameraobj, KX_BlenderSceneConverter *converter)
-{
- KX_CameraIpoSGController* ipocontr = new KX_CameraIpoSGController();
-
- Camera *blendercamera = (Camera*)cameraobj->GetBlenderObject()->data;
-
- ipocontr->m_lens = blendercamera->lens;
- ipocontr->m_clipstart = blendercamera->clipsta;
- ipocontr->m_clipend = blendercamera->clipend;
-
- BL_InterpolatorList *adtList= GetAdtList(action, converter);
-
- // For each active channel in the adtList add an
- // interpolator to the game object.
-
- KX_IInterpolator *interpolator;
- KX_IScalarInterpolator *interp;
-
- if ((interp = adtList->GetScalarInterpolator("lens", 0))) {
- interpolator= new KX_ScalarInterpolator(&ipocontr->m_lens, interp);
- ipocontr->AddInterpolator(interpolator);
- ipocontr->SetModifyLens(true);
- }
-
- if ((interp = adtList->GetScalarInterpolator("clip_start", 0))) {
- interpolator= new KX_ScalarInterpolator(&ipocontr->m_clipstart, interp);
- ipocontr->AddInterpolator(interpolator);
- ipocontr->SetModifyClipStart(true);
- }
-
- if ((interp = adtList->GetScalarInterpolator("clip_end", 0))) {
- interpolator= new KX_ScalarInterpolator(&ipocontr->m_clipend, interp);
- ipocontr->AddInterpolator(interpolator);
- ipocontr->SetModifyClipEnd(true);
- }
-
- return ipocontr;
-}
-
-
-SG_Controller * BL_CreateWorldIPO( bAction *action, struct World *blenderworld, KX_BlenderSceneConverter *converter )
-{
- KX_WorldIpoController *ipocontr = NULL;
-
- if (blenderworld) {
- BL_InterpolatorList *adtList = GetAdtList(action, converter);
-
- // For each active channel in the adtList add an interpolator to the game object.
- KX_IInterpolator *interpolator;
- KX_IScalarInterpolator *interp;
-
- for (int i=0; i<3; i++) {
- if ((interp = adtList->GetScalarInterpolator("ambient_color", i))) {
- if (!ipocontr) {
- ipocontr = new KX_WorldIpoController();
- }
- interpolator = new KX_ScalarInterpolator(&ipocontr->m_ambi_rgb[i], interp);
- ipocontr->AddInterpolator(interpolator);
- ipocontr->SetModifyAmbientColor(true);
- }
- }
-
- for (int i=0; i<3; i++) {
- if ((interp = adtList->GetScalarInterpolator("horizon_color", i))) {
- if (!ipocontr) {
- ipocontr = new KX_WorldIpoController();
- }
- interpolator = new KX_ScalarInterpolator(&ipocontr->m_hori_rgb[i], interp);
- ipocontr->AddInterpolator(interpolator);
- ipocontr->SetModifyHorizonColor(true);
- }
- }
-
- if ((interp = adtList->GetScalarInterpolator("mist_settings.start", 0))) {
- if (!ipocontr) {
- ipocontr = new KX_WorldIpoController();
- }
- interpolator = new KX_ScalarInterpolator(&ipocontr->m_mist_start, interp);
- ipocontr->AddInterpolator(interpolator);
- ipocontr->SetModifyMistStart(true);
- }
-
- if ((interp = adtList->GetScalarInterpolator("mist_settings.depth", 0))) {
- if (!ipocontr) {
- ipocontr = new KX_WorldIpoController();
- }
- interpolator = new KX_ScalarInterpolator(&ipocontr->m_mist_dist, interp);
- ipocontr->AddInterpolator(interpolator);
- ipocontr->SetModifyMistDist(true);
- }
-
- if ((interp = adtList->GetScalarInterpolator("mist_settings.intensity", 0))) {
- if (!ipocontr) {
- ipocontr = new KX_WorldIpoController();
- }
- interpolator = new KX_ScalarInterpolator(&ipocontr->m_mist_intensity, interp);
- ipocontr->AddInterpolator(interpolator);
- ipocontr->SetModifyMistIntensity(true);
- }
-
- if (ipocontr) {
- ipocontr->m_mist_start = blenderworld->miststa;
- ipocontr->m_mist_dist = blenderworld->mistdist;
- ipocontr->m_mist_intensity = blenderworld->misi;
- ipocontr->m_hori_rgb[0] = blenderworld->horr;
- ipocontr->m_hori_rgb[1] = blenderworld->horg;
- ipocontr->m_hori_rgb[2] = blenderworld->horb;
- ipocontr->m_ambi_rgb[0] = blenderworld->ambr;
- ipocontr->m_ambi_rgb[1] = blenderworld->ambg;
- ipocontr->m_ambi_rgb[2] = blenderworld->ambb;
- }
- }
- return ipocontr;
-}
-
-SG_Controller *BL_CreateMaterialIpo(
- struct bAction *action,
- Material* blendermaterial,
- dword matname_hash,
- KX_GameObject* gameobj,
- KX_BlenderSceneConverter *converter
- )
-{
- KX_MaterialIpoController* ipocontr = NULL;
-
- BL_InterpolatorList *adtList= GetAdtList(action, converter);
- KX_IInterpolator *interpolator;
- KX_IScalarInterpolator *sinterp;
-
- // --
- for (int i=0; i<3; i++) {
- if ((sinterp = adtList->GetScalarInterpolator("diffuse_color", i))) {
- if (!ipocontr) {
- ipocontr = new KX_MaterialIpoController(matname_hash);
- }
- interpolator= new KX_ScalarInterpolator(&ipocontr->m_rgba[i], sinterp);
- ipocontr->AddInterpolator(interpolator);
- }
- }
-
- if ((sinterp = adtList->GetScalarInterpolator("alpha", 0))) {
- if (!ipocontr) {
- ipocontr = new KX_MaterialIpoController(matname_hash);
- }
- interpolator= new KX_ScalarInterpolator(&ipocontr->m_rgba[3], sinterp);
- ipocontr->AddInterpolator(interpolator);
- }
-
- for (int i=0; i<3; i++) {
- if ((sinterp = adtList->GetScalarInterpolator("specular_color", i))) {
- if (!ipocontr) {
- ipocontr = new KX_MaterialIpoController(matname_hash);
- }
- interpolator= new KX_ScalarInterpolator(&ipocontr->m_specrgb[i], sinterp);
- ipocontr->AddInterpolator(interpolator);
- }
- }
-
- if ((sinterp = adtList->GetScalarInterpolator("specular_hardness", 0))) {
- if (!ipocontr) {
- ipocontr = new KX_MaterialIpoController(matname_hash);
- }
- interpolator= new KX_ScalarInterpolator(&ipocontr->m_hard, sinterp);
- ipocontr->AddInterpolator(interpolator);
- }
-
- if ((sinterp = adtList->GetScalarInterpolator("specular_intensity", 0))) {
- if (!ipocontr) {
- ipocontr = new KX_MaterialIpoController(matname_hash);
- }
- interpolator= new KX_ScalarInterpolator(&ipocontr->m_spec, sinterp);
- ipocontr->AddInterpolator(interpolator);
- }
-
- if ((sinterp = adtList->GetScalarInterpolator("diffuse_intensity", 0))) {
- if (!ipocontr) {
- ipocontr = new KX_MaterialIpoController(matname_hash);
- }
- interpolator= new KX_ScalarInterpolator(&ipocontr->m_ref, sinterp);
- ipocontr->AddInterpolator(interpolator);
- }
-
- if ((sinterp = adtList->GetScalarInterpolator("emit", 0))) {
- if (!ipocontr) {
- ipocontr = new KX_MaterialIpoController(matname_hash);
- }
- interpolator= new KX_ScalarInterpolator(&ipocontr->m_emit, sinterp);
- ipocontr->AddInterpolator(interpolator);
- }
-
- if (ipocontr) {
- ipocontr->m_rgba[0] = blendermaterial->r;
- ipocontr->m_rgba[1] = blendermaterial->g;
- ipocontr->m_rgba[2] = blendermaterial->b;
- ipocontr->m_rgba[3] = blendermaterial->alpha;
-
- ipocontr->m_specrgb[0] = blendermaterial->specr;
- ipocontr->m_specrgb[1] = blendermaterial->specg;
- ipocontr->m_specrgb[2] = blendermaterial->specb;
-
- ipocontr->m_hard = blendermaterial->har;
- ipocontr->m_spec = blendermaterial->spec;
- ipocontr->m_ref = blendermaterial->ref;
- ipocontr->m_emit = blendermaterial->emit;
- ipocontr->m_alpha = blendermaterial->alpha;
- }
-
- return ipocontr;
-}
diff --git a/source/gameengine/Ketsji/KX_IpoConvert.h b/source/gameengine/Ketsji/KX_IpoConvert.h
deleted file mode 100644
index 6db43552811..00000000000
--- a/source/gameengine/Ketsji/KX_IpoConvert.h
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file KX_IpoConvert.h
- * \ingroup bgeconv
- */
-
-#ifndef __KX_IPOCONVERT_H__
-#define __KX_IPOCONVERT_H__
-
-struct Object;
-struct bAction;
-class SG_Controller;
-class KX_GameObject;
-class KX_BlenderSceneConverter;
-
-SG_Controller *BL_CreateIPO(bAction *action,
- KX_GameObject* gameobj,
- KX_BlenderSceneConverter *converter);
-
-SG_Controller *BL_CreateObColorIPO(bAction *action,
- KX_GameObject* gameobj,
- KX_BlenderSceneConverter *converter);
-
-SG_Controller *BL_CreateLampIPO(bAction *action,
- KX_GameObject* lightobj,
- KX_BlenderSceneConverter *converter);
-
-SG_Controller *BL_CreateWorldIPO(bAction *action,
- struct World *blenderworld,
- KX_BlenderSceneConverter *converter);
-
-SG_Controller *BL_CreateCameraIPO(bAction *action,
- KX_GameObject* cameraobj,
- KX_BlenderSceneConverter *converter);
-
-SG_Controller *BL_CreateMaterialIpo(
- bAction *action,
- struct Material* blendermaterial,
- dword matname_hash,
- KX_GameObject* gameobj,
- KX_BlenderSceneConverter *converter);
-
-
-#endif /* __KX_IPOCONVERT_H__ */
diff --git a/source/gameengine/Ketsji/KX_KetsjiEngine.cpp b/source/gameengine/Ketsji/KX_KetsjiEngine.cpp
deleted file mode 100644
index d82a0fd533b..00000000000
--- a/source/gameengine/Ketsji/KX_KetsjiEngine.cpp
+++ /dev/null
@@ -1,2081 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- * The engine ties all game modules together.
- */
-
-/** \file gameengine/Ketsji/KX_KetsjiEngine.cpp
- * \ingroup ketsji
- */
-
-#ifdef _MSC_VER
-# pragma warning (disable:4786)
-#endif
-
-#include <iostream>
-#include <stdio.h>
-
-#include "BLI_task.h"
-
-#include "KX_KetsjiEngine.h"
-
-#include "EXP_ListValue.h"
-#include "EXP_IntValue.h"
-#include "EXP_VectorValue.h"
-#include "EXP_BoolValue.h"
-#include "EXP_FloatValue.h"
-
-#include "RAS_BucketManager.h"
-#include "RAS_Rect.h"
-#include "RAS_IRasterizer.h"
-#include "RAS_ICanvas.h"
-#include "RAS_ILightObject.h"
-#include "MT_Vector3.h"
-#include "MT_Transform.h"
-#include "SCA_IInputDevice.h"
-#include "KX_Camera.h"
-#include "KX_Dome.h"
-#include "KX_Light.h"
-#include "KX_PythonInit.h"
-#include "KX_PyConstraintBinding.h"
-#include "PHY_IPhysicsEnvironment.h"
-
-#include "NG_NetworkScene.h"
-#include "NG_NetworkDeviceInterface.h"
-
-#include "KX_WorldInfo.h"
-#include "KX_ISceneConverter.h"
-#include "KX_TimeCategoryLogger.h"
-
-#include "RAS_FramingManager.h"
-#include "DNA_world_types.h"
-#include "DNA_scene_types.h"
-
-#include "KX_NavMeshObject.h"
-
-#include "BL_Action.h" // For managing action lock.
-
-#define DEFAULT_LOGIC_TIC_RATE 60.0
-//#define DEFAULT_PHYSICS_TIC_RATE 60.0
-
-const char KX_KetsjiEngine::m_profileLabels[tc_numCategories][15] = {
- "Physics:", // tc_physics
- "Logic:", // tc_logic
- "Animations:", // tc_animations
- "Network:", // tc_network
- "Scenegraph:", // tc_scenegraph
- "Rasterizer:", // tc_rasterizer
- "Services:", // tc_services
- "Overhead:", // tc_overhead
- "Outside:", // tc_outside
- "GPU Latency:" // tc_latency
-};
-
-double KX_KetsjiEngine::m_ticrate = DEFAULT_LOGIC_TIC_RATE;
-int KX_KetsjiEngine::m_maxLogicFrame = 5;
-int KX_KetsjiEngine::m_maxPhysicsFrame = 5;
-double KX_KetsjiEngine::m_anim_framerate = 25.0;
-double KX_KetsjiEngine::m_suspendedtime = 0.0;
-double KX_KetsjiEngine::m_suspendeddelta = 0.0;
-double KX_KetsjiEngine::m_average_framerate = 0.0;
-bool KX_KetsjiEngine::m_restrict_anim_fps = false;
-short KX_KetsjiEngine::m_exitkey = 130; // ESC Key
-bool KX_KetsjiEngine::m_doRender = true;
-
-/**
- * Constructor of the Ketsji Engine
- */
-KX_KetsjiEngine::KX_KetsjiEngine(KX_ISystem* system)
- : m_canvas(NULL),
- m_rasterizer(NULL),
- m_kxsystem(system),
- m_sceneconverter(NULL),
- m_networkdevice(NULL),
-#ifdef WITH_PYTHON
- m_pythondictionary(NULL),
-#endif
- m_keyboarddevice(NULL),
- m_mousedevice(NULL),
-
- m_bInitialized(false),
- m_activecam(0),
- m_bFixedTime(false),
- m_useExternalClock(false),
-
- m_firstframe(true),
-
- m_frameTime(0.f),
- m_clockTime(0.f),
- m_previousClockTime(0.f),
- m_previousAnimTime(0.f),
- m_timescale(1.0f),
- m_previousRealTime(0.0f),
-
-
- m_exitcode(KX_EXIT_REQUEST_NO_REQUEST),
- m_exitstring(""),
-
- m_cameraZoom(1.0f),
-
- m_overrideCam(false),
- m_overrideCamUseOrtho(false),
- m_overrideCamNear(0.0f),
- m_overrideCamFar(0.0f),
- m_overrideCamZoom(1.0f),
-
- m_stereo(false),
- m_curreye(0),
-
- m_logger(NULL),
-
- // Set up timing info display variables
- m_show_framerate(false),
- m_show_profile(false),
- m_showProperties(false),
- m_showBackground(false),
- m_show_debug_properties(false),
- m_autoAddDebugProperties(true),
-
- m_animation_record(false),
-
- // Default behavior is to hide the cursor every frame.
- m_hideCursor(false),
-
- m_overrideFrameColor(false),
- m_overrideFrameColorR(0.0f),
- m_overrideFrameColorG(0.0f),
- m_overrideFrameColorB(0.0f),
- m_overrideFrameColorA(0.0f),
-
- m_usedome(false)
-{
- // Initialize the time logger
- m_logger = new KX_TimeCategoryLogger (25);
-
- for (int i = tc_first; i < tc_numCategories; i++)
- m_logger->AddCategory((KX_TimeCategory)i);
-
-#ifdef WITH_PYTHON
- m_pyprofiledict = PyDict_New();
-#endif
-
- m_taskscheduler = BLI_task_scheduler_create(TASK_SCHEDULER_AUTO_THREADS);
-
- BL_Action::InitLock();
-}
-
-
-
-/**
- * Destructor of the Ketsji Engine, release all memory
- */
-KX_KetsjiEngine::~KX_KetsjiEngine()
-{
- delete m_logger;
- if (m_usedome)
- delete m_dome;
-
-#ifdef WITH_PYTHON
- Py_CLEAR(m_pyprofiledict);
-#endif
-
- if (m_taskscheduler)
- BLI_task_scheduler_free(m_taskscheduler);
-
- BL_Action::EndLock();
-}
-
-
-
-void KX_KetsjiEngine::SetKeyboardDevice(SCA_IInputDevice* keyboarddevice)
-{
- MT_assert(keyboarddevice);
- m_keyboarddevice = keyboarddevice;
-}
-
-
-
-void KX_KetsjiEngine::SetMouseDevice(SCA_IInputDevice* mousedevice)
-{
- MT_assert(mousedevice);
- m_mousedevice = mousedevice;
-}
-
-
-
-void KX_KetsjiEngine::SetNetworkDevice(NG_NetworkDeviceInterface* networkdevice)
-{
- MT_assert(networkdevice);
- m_networkdevice = networkdevice;
-}
-
-
-void KX_KetsjiEngine::SetCanvas(RAS_ICanvas* canvas)
-{
- MT_assert(canvas);
- m_canvas = canvas;
-}
-
-
-
-void KX_KetsjiEngine::SetRasterizer(RAS_IRasterizer* rasterizer)
-{
- MT_assert(rasterizer);
- m_rasterizer = rasterizer;
-}
-
-#ifdef WITH_PYTHON
-/*
- * At the moment the bge.logic module is imported into 'pythondictionary' after this function is called.
- * if this function ever changes to assign a copy, make sure the game logic module is imported into this dictionary before hand.
- */
-void KX_KetsjiEngine::SetPyNamespace(PyObject *pythondictionary)
-{
- MT_assert(pythondictionary);
- m_pythondictionary = pythondictionary;
-}
-
-PyObject* KX_KetsjiEngine::GetPyProfileDict()
-{
- Py_INCREF(m_pyprofiledict);
- return m_pyprofiledict;
-}
-#endif
-
-
-void KX_KetsjiEngine::SetSceneConverter(KX_ISceneConverter* sceneconverter)
-{
- MT_assert(sceneconverter);
- m_sceneconverter = sceneconverter;
-}
-
-void KX_KetsjiEngine::InitDome(short res, short mode, short angle, float resbuf, short tilt, struct Text* text)
-{
- m_dome = new KX_Dome(m_canvas, m_rasterizer,this, res, mode, angle, resbuf, tilt, text);
- m_usedome = true;
-}
-
-void KX_KetsjiEngine::RenderDome()
-{
- const GLint *viewport = m_canvas->GetViewPort();
-
- m_dome->SetViewPort(viewport);
-
- KX_Scene* firstscene = *m_scenes.begin();
- const RAS_FrameSettings &framesettings = firstscene->GetFramingType();
-
- m_logger->StartLog(tc_rasterizer, m_kxsystem->GetTimeInSeconds(), true);
-
- // hiding mouse cursor each frame
- // (came back when going out of focus and then back in again)
- if (m_hideCursor)
- m_canvas->SetMouseState(RAS_ICanvas::MOUSE_INVISIBLE);
-
- // clear the entire game screen with the border color
- // only once per frame
-
- m_canvas->BeginDraw();
-
- // BeginFrame() sets the actual drawing area. You can use a part of the window
- if (!BeginFrame())
- return;
-
- KX_SceneList::iterator sceneit;
- KX_Scene* scene = NULL;
-
- int n_renders=m_dome->GetNumberRenders(); // usually 4 or 6
- for (int i=0;i<n_renders;i++) {
- m_canvas->ClearBuffer(RAS_ICanvas::COLOR_BUFFER|RAS_ICanvas::DEPTH_BUFFER);
- for (sceneit = m_scenes.begin();sceneit != m_scenes.end(); sceneit++)
- // for each scene, call the proceed functions
- {
- scene = *sceneit;
- KX_SetActiveScene(scene);
- KX_Camera* cam = scene->GetActiveCamera();
-
- // pass the scene's worldsettings to the rasterizer
- scene->GetWorldInfo()->UpdateWorldSettings();
-
- // shadow buffers
- if (i == 0) {
- RenderShadowBuffers(scene);
- }
- // Avoid drawing the scene with the active camera twice when its viewport is enabled
- if (cam && !cam->GetViewport())
- {
- if (scene->IsClearingZBuffer())
- m_rasterizer->ClearDepthBuffer();
-
- m_rasterizer->SetAuxilaryClientInfo(scene);
-
- // do the rendering
- m_dome->RenderDomeFrame(scene,cam, i);
- // render all the font objects for this scene
- scene->RenderFonts();
- }
-
- list<class KX_Camera*>* cameras = scene->GetCameras();
-
- // Draw the scene once for each camera with an enabled viewport
- list<KX_Camera*>::iterator it = cameras->begin();
- while (it != cameras->end()) {
- if ((*it)->GetViewport())
- {
- if (scene->IsClearingZBuffer())
- m_rasterizer->ClearDepthBuffer();
-
- m_rasterizer->SetAuxilaryClientInfo(scene);
-
- // do the rendering
- m_dome->RenderDomeFrame(scene, (*it),i);
- // render all the font objects for this scene
- scene->RenderFonts();
- }
-
- it++;
- }
- // Part of PostRenderScene()
- m_rasterizer->MotionBlur();
- scene->Render2DFilters(m_canvas);
- // no RunDrawingCallBacks
- // no FlushDebugLines
- }
- m_dome->BindImages(i);
- }
-
- m_canvas->EndFrame();//XXX do we really need that?
-
- m_canvas->SetViewPort(0, 0, m_canvas->GetWidth(), m_canvas->GetHeight());
-
- if (m_overrideFrameColor) //XXX why do we want
- {
- // Do not use the framing bar color set in the Blender scenes
- m_canvas->ClearColor(
- m_overrideFrameColorR,
- m_overrideFrameColorG,
- m_overrideFrameColorB,
- m_overrideFrameColorA
- );
- }
- else
- {
- // Use the framing bar color set in the Blender scenes
- m_canvas->ClearColor(
- framesettings.BarRed(),
- framesettings.BarGreen(),
- framesettings.BarBlue(),
- 1.0
- );
- }
- m_dome->Draw();
-
- // Draw Callback for the last scene
-#ifdef WITH_PYTHON
- PHY_SetActiveEnvironment(scene->GetPhysicsEnvironment());
- scene->RunDrawingCallbacks(scene->GetPostDrawCB());
-#endif
- EndFrame();
-}
-
-/**
- * Ketsji Init(), Initializes data-structures and converts data from
- * Blender into Ketsji native (realtime) format also sets up the
- * graphics context
- */
-void KX_KetsjiEngine::StartEngine(bool clearIpo)
-{
- m_clockTime = m_kxsystem->GetTimeInSeconds();
- m_frameTime = m_kxsystem->GetTimeInSeconds();
- m_previousClockTime = m_kxsystem->GetTimeInSeconds();
- m_previousRealTime = m_kxsystem->GetTimeInSeconds();
-
- m_firstframe = true;
- m_bInitialized = true;
- // there is always one scene enabled at startup
- Scene* scene = m_scenes[0]->GetBlenderScene();
- if (scene)
- {
- m_ticrate = scene->gm.ticrate ? scene->gm.ticrate : DEFAULT_LOGIC_TIC_RATE;
- m_maxLogicFrame = scene->gm.maxlogicstep ? scene->gm.maxlogicstep : 5;
- m_maxPhysicsFrame = scene->gm.maxphystep ? scene->gm.maxlogicstep : 5;
- }
- else
- {
- m_ticrate = DEFAULT_LOGIC_TIC_RATE;
- m_maxLogicFrame = 5;
- m_maxPhysicsFrame = 5;
- }
-
- if (m_animation_record)
- {
- m_sceneconverter->ResetPhysicsObjectsAnimationIpo(clearIpo);
- m_sceneconverter->WritePhysicsObjectToAnimationIpo(m_currentFrame);
- }
-}
-
-void KX_KetsjiEngine::ClearFrame()
-{
- // clear unless we're drawing overlapping stereo
- if (m_rasterizer->InterlacedStereo() &&
- m_rasterizer->GetEye() == RAS_IRasterizer::RAS_STEREO_RIGHTEYE)
- return;
-
- // clear the viewports with the background color of the first scene
- bool doclear = false;
- KX_SceneList::iterator sceneit;
- RAS_Rect clearvp, area, viewport;
-
- for (sceneit = m_scenes.begin(); sceneit != m_scenes.end(); sceneit++)
- {
- KX_Scene* scene = *sceneit;
- //const RAS_FrameSettings &framesettings = scene->GetFramingType();
- list<class KX_Camera*>* cameras = scene->GetCameras();
-
- list<KX_Camera*>::iterator it;
- for (it = cameras->begin(); it != cameras->end(); it++)
- {
- GetSceneViewport(scene, (*it), area, viewport);
-
- if (!doclear) {
- clearvp = viewport;
- doclear = true;
- }
- else {
- if (viewport.GetLeft() < clearvp.GetLeft())
- clearvp.SetLeft(viewport.GetLeft());
- if (viewport.GetBottom() < clearvp.GetBottom())
- clearvp.SetBottom(viewport.GetBottom());
- if (viewport.GetRight() > clearvp.GetRight())
- clearvp.SetRight(viewport.GetRight());
- if (viewport.GetTop() > clearvp.GetTop())
- clearvp.SetTop(viewport.GetTop());
-
- }
- }
- }
-
- if (doclear) {
- KX_Scene* firstscene = *m_scenes.begin();
- firstscene->GetWorldInfo()->UpdateBackGround();
-
- m_canvas->SetViewPort(clearvp.GetLeft(), clearvp.GetBottom(),
- clearvp.GetRight(), clearvp.GetTop());
- m_rasterizer->ClearColorBuffer();
- }
-}
-
-bool KX_KetsjiEngine::BeginFrame()
-{
- // set the area used for rendering (stereo can assign only a subset)
- m_rasterizer->SetRenderArea();
-
- if (m_canvas->BeginDraw())
- {
- ClearFrame();
-
- m_rasterizer->BeginFrame(m_kxsystem->GetTimeInSeconds());
-
- return true;
- }
-
- return false;
-}
-
-
-void KX_KetsjiEngine::EndFrame()
-{
- m_rasterizer->MotionBlur();
-
- // Show profiling info
- m_logger->StartLog(tc_overhead, m_kxsystem->GetTimeInSeconds(), true);
- if (m_show_framerate || m_show_profile || (m_show_debug_properties))
- {
- RenderDebugProperties();
- }
-
- double tottime = m_logger->GetAverage();
- if (tottime < 1e-6)
- tottime = 1e-6;
-
-#ifdef WITH_PYTHON
- for (int i = tc_first; i < tc_numCategories; ++i) {
- double time = m_logger->GetAverage((KX_TimeCategory)i);
- PyObject *val = PyTuple_New(2);
- PyTuple_SetItem(val, 0, PyFloat_FromDouble(time*1000.0));
- PyTuple_SetItem(val, 1, PyFloat_FromDouble(time/tottime * 100.0));
-
- PyDict_SetItemString(m_pyprofiledict, m_profileLabels[i], val);
- Py_DECREF(val);
- }
-#endif
-
- m_average_framerate = 1.0/tottime;
-
- // Go to next profiling measurement, time spent after this call is shown in the next frame.
- m_logger->NextMeasurement(m_kxsystem->GetTimeInSeconds());
-
- m_logger->StartLog(tc_rasterizer, m_kxsystem->GetTimeInSeconds(), true);
- m_rasterizer->EndFrame();
- // swap backbuffer (drawing into this buffer) <-> front/visible buffer
- m_logger->StartLog(tc_latency, m_kxsystem->GetTimeInSeconds(), true);
- m_rasterizer->SwapBuffers();
- m_logger->StartLog(tc_rasterizer, m_kxsystem->GetTimeInSeconds(), true);
-
- m_canvas->EndDraw();
-}
-
-//#include "PIL_time.h"
-//#include "LinearMath/btQuickprof.h"
-
-
-bool KX_KetsjiEngine::NextFrame()
-{
- double timestep = m_timescale / m_ticrate;
- double framestep = timestep;
- // static hidden::Clock sClock;
-
- m_logger->StartLog(tc_services, m_kxsystem->GetTimeInSeconds(),true);
-
- //float dt = sClock.getTimeMicroseconds() * 0.000001f;
- //sClock.reset();
-
- /*
- * Clock advancement. There is basically three case:
- * - m_useExternalClock is true, the user is responsible to advance the time
- * manually using setClockTime, so here, we do not do anything.
- * - m_useExternalClock is false, m_bFixedTime is true, we advance for one
- * timestep, which already handle the time scaling parameter
- * - m_useExternalClock is false, m_bFixedTime is false, we consider how much
- * time has elapsed since last call and we scale this time by the time
- * scaling parameter. If m_timescale is 1.0 (default value), the clock
- * corresponds to the computer clock.
- *
- * Once clockTime has been computed, we will compute how many logic frames
- * will be executed before the next rendering phase (which will occur at "clockTime").
- * The game time elapsing between two logic frames (called framestep)
- * depends on several variables:
- * - ticrate
- * - max_physic_frame
- * - max_logic_frame
- * XXX The logic over computation framestep is definitively not clear (and
- * I'm not even sure it is correct). If needed frame is strictly greater
- * than max_physics_frame, we are doing a jump in game time, but keeping
- * framestep = 1 / ticrate, while if frames is greater than
- * max_logic_frame, we increase framestep.
- *
- * XXX render.fps is not considred anywhere.
- */
- if (!m_useExternalClock) {
- if (m_bFixedTime) {
- m_clockTime += timestep;
- }
- else {
- double current_time = m_kxsystem->GetTimeInSeconds();
- double dt = current_time - m_previousRealTime;
- m_previousRealTime = current_time;
- // m_clockTime += dt;
- m_clockTime += dt * m_timescale;
- }
- }
-
- double deltatime = m_clockTime - m_frameTime;
- if (deltatime<0.0)
- {
- // We got here too quickly, which means there is nothing to do, just return and don't render.
- // Not sure if this is the best fix, but it seems to stop the jumping framerate issue (#33088)
- return false;
- }
-
- // Compute the number of logic frames to do each update (fixed tic bricks)
- int frames = int(deltatime * m_ticrate / m_timescale + 1e-6);
-// if (frames>1)
-// printf("****************************************");
-// printf("dt = %f, deltatime = %f, frames = %d\n",dt, deltatime,frames);
-
-// if (!frames)
-// PIL_sleep_ms(1);
- KX_SceneList::iterator sceneit;
-
- if (frames>m_maxPhysicsFrame)
- {
-
- // printf("framedOut: %d\n",frames);
- m_frameTime+=(frames-m_maxPhysicsFrame)*timestep;
- frames = m_maxPhysicsFrame;
- }
-
-
- bool doRender = frames>0;
-
- if (frames > m_maxLogicFrame)
- {
- framestep = (frames*timestep)/m_maxLogicFrame;
- frames = m_maxLogicFrame;
- }
-
- while (frames)
- {
-
-
- m_frameTime += framestep;
-
- m_sceneconverter->MergeAsyncLoads();
-
- for (sceneit = m_scenes.begin();sceneit != m_scenes.end(); ++sceneit)
- // for each scene, call the proceed functions
- {
- KX_Scene* scene = *sceneit;
-
- /* Suspension holds the physics and logic processing for an
- * entire scene. Objects can be suspended individually, and
- * the settings for that precede the logic and physics
- * update. */
- m_logger->StartLog(tc_logic, m_kxsystem->GetTimeInSeconds(), true);
-
- m_sceneconverter->resetNoneDynamicObjectToIpo(); // this is for none dynamic objects with ipo
-
- scene->UpdateObjectActivity();
-
- if (!scene->IsSuspended())
- {
- // if the scene was suspended recalculate the delta tu "curtime"
- m_suspendedtime = scene->getSuspendedTime();
- if (scene->getSuspendedTime()!=0.0)
- scene->setSuspendedDelta(scene->getSuspendedDelta()+m_clockTime-scene->getSuspendedTime());
- m_suspendeddelta = scene->getSuspendedDelta();
-
-
- m_logger->StartLog(tc_network, m_kxsystem->GetTimeInSeconds(), true);
- SG_SetActiveStage(SG_STAGE_NETWORK);
- scene->GetNetworkScene()->proceed(m_frameTime);
-
- //m_logger->StartLog(tc_scenegraph, m_kxsystem->GetTimeInSeconds(), true);
- //SG_SetActiveStage(SG_STAGE_NETWORK_UPDATE);
- //scene->UpdateParents(m_frameTime);
-
- m_logger->StartLog(tc_physics, m_kxsystem->GetTimeInSeconds(), true);
- SG_SetActiveStage(SG_STAGE_PHYSICS1);
- // set Python hooks for each scene
-#ifdef WITH_PYTHON
- PHY_SetActiveEnvironment(scene->GetPhysicsEnvironment());
-#endif
- KX_SetActiveScene(scene);
-
- scene->GetPhysicsEnvironment()->EndFrame();
-
- // Update scenegraph after physics step. This maps physics calculations
- // into node positions.
- //m_logger->StartLog(tc_scenegraph, m_kxsystem->GetTimeInSeconds(), true);
- //SG_SetActiveStage(SG_STAGE_PHYSICS1_UPDATE);
- //scene->UpdateParents(m_frameTime);
-
- // Process sensors, and controllers
- m_logger->StartLog(tc_logic, m_kxsystem->GetTimeInSeconds(), true);
- SG_SetActiveStage(SG_STAGE_CONTROLLER);
- scene->LogicBeginFrame(m_frameTime);
-
- // Scenegraph needs to be updated again, because Logic Controllers
- // can affect the local matrices.
- m_logger->StartLog(tc_scenegraph, m_kxsystem->GetTimeInSeconds(), true);
- SG_SetActiveStage(SG_STAGE_CONTROLLER_UPDATE);
- scene->UpdateParents(m_frameTime);
-
- // Process actuators
-
- // Do some cleanup work for this logic frame
- m_logger->StartLog(tc_logic, m_kxsystem->GetTimeInSeconds(), true);
- SG_SetActiveStage(SG_STAGE_ACTUATOR);
- scene->LogicUpdateFrame(m_frameTime, true);
-
- scene->LogicEndFrame();
-
- // Actuators can affect the scenegraph
- m_logger->StartLog(tc_scenegraph, m_kxsystem->GetTimeInSeconds(), true);
- SG_SetActiveStage(SG_STAGE_ACTUATOR_UPDATE);
- scene->UpdateParents(m_frameTime);
-
- // update levels of detail
- scene->UpdateObjectLods();
-
- m_logger->StartLog(tc_physics, m_kxsystem->GetTimeInSeconds(), true);
- SG_SetActiveStage(SG_STAGE_PHYSICS2);
- scene->GetPhysicsEnvironment()->BeginFrame();
-
- // Perform physics calculations on the scene. This can involve
- // many iterations of the physics solver.
- scene->GetPhysicsEnvironment()->ProceedDeltaTime(m_frameTime,timestep,framestep);//m_deltatimerealDeltaTime);
-
- m_logger->StartLog(tc_scenegraph, m_kxsystem->GetTimeInSeconds(), true);
- SG_SetActiveStage(SG_STAGE_PHYSICS2_UPDATE);
- scene->UpdateParents(m_frameTime);
-
-
- if (m_animation_record)
- {
- m_sceneconverter->WritePhysicsObjectToAnimationIpo(++m_currentFrame);
- }
-
- scene->setSuspendedTime(0.0);
- } // suspended
- else
- if (scene->getSuspendedTime()==0.0)
- scene->setSuspendedTime(m_clockTime);
-
- m_logger->StartLog(tc_services, m_kxsystem->GetTimeInSeconds(), true);
-
- // invalidates the shadow buffer from previous render/ImageRender because the scene has changed
- scene->SetShadowDone(false);
- }
-
- // update system devices
- m_logger->StartLog(tc_logic, m_kxsystem->GetTimeInSeconds(), true);
- if (m_keyboarddevice)
- m_keyboarddevice->NextFrame();
-
- if (m_mousedevice)
- m_mousedevice->NextFrame();
-
- if (m_networkdevice)
- m_networkdevice->NextFrame();
-
- // scene management
- ProcessScheduledScenes();
-
- frames--;
- }
-
- // Start logging time spent outside main loop
- m_logger->StartLog(tc_outside, m_kxsystem->GetTimeInSeconds(), true);
-
- return doRender && m_doRender;
-}
-
-
-
-void KX_KetsjiEngine::Render()
-{
- if (m_usedome) {
- RenderDome();
- return;
- }
- KX_Scene* firstscene = *m_scenes.begin();
- const RAS_FrameSettings &framesettings = firstscene->GetFramingType();
-
- m_logger->StartLog(tc_rasterizer, m_kxsystem->GetTimeInSeconds(), true);
- SG_SetActiveStage(SG_STAGE_RENDER);
-
- // hiding mouse cursor each frame
- // (came back when going out of focus and then back in again)
- if (m_hideCursor)
- m_canvas->SetMouseState(RAS_ICanvas::MOUSE_INVISIBLE);
-
- // clear the entire game screen with the border color
- // only once per frame
- m_canvas->BeginDraw();
- if (m_rasterizer->GetDrawingMode() == RAS_IRasterizer::KX_TEXTURED) {
- m_canvas->SetViewPort(0, 0, m_canvas->GetWidth(), m_canvas->GetHeight());
- if (m_overrideFrameColor)
- {
- // Do not use the framing bar color set in the Blender scenes
- m_canvas->ClearColor(
- m_overrideFrameColorR,
- m_overrideFrameColorG,
- m_overrideFrameColorB,
- m_overrideFrameColorA
- );
- }
- else
- {
- // Use the framing bar color set in the Blender scenes
- m_canvas->ClearColor(
- framesettings.BarRed(),
- framesettings.BarGreen(),
- framesettings.BarBlue(),
- 1.0
- );
- }
- // clear the -whole- viewport
- m_canvas->ClearBuffer(RAS_ICanvas::COLOR_BUFFER|RAS_ICanvas::DEPTH_BUFFER);
- }
-
- m_rasterizer->SetEye(RAS_IRasterizer::RAS_STEREO_LEFTEYE);
-
- // BeginFrame() sets the actual drawing area. You can use a part of the window
- if (!BeginFrame())
- return;
-
- KX_SceneList::iterator sceneit;
- for (sceneit = m_scenes.begin();sceneit != m_scenes.end(); sceneit++)
- // for each scene, call the proceed functions
- {
- KX_Scene* scene = *sceneit;
- KX_Camera* cam = scene->GetActiveCamera();
- // pass the scene's worldsettings to the rasterizer
- scene->GetWorldInfo()->UpdateWorldSettings();
-
- // this is now done incrementally in KX_Scene::CalculateVisibleMeshes
- //scene->UpdateMeshTransformations();
-
- // shadow buffers
- RenderShadowBuffers(scene);
-
- // Avoid drawing the scene with the active camera twice when its viewport is enabled
- if (cam && !cam->GetViewport())
- {
- if (scene->IsClearingZBuffer())
- m_rasterizer->ClearDepthBuffer();
-
- m_rasterizer->SetAuxilaryClientInfo(scene);
-
- // do the rendering
- RenderFrame(scene, cam);
- }
-
- list<class KX_Camera*>* cameras = scene->GetCameras();
-
- // Draw the scene once for each camera with an enabled viewport
- list<KX_Camera*>::iterator it = cameras->begin();
- while (it != cameras->end()) {
- if ((*it)->GetViewport())
- {
- if (scene->IsClearingZBuffer())
- m_rasterizer->ClearDepthBuffer();
-
- m_rasterizer->SetAuxilaryClientInfo(scene);
-
- // do the rendering
- RenderFrame(scene, (*it));
- }
-
- it++;
- }
- PostRenderScene(scene);
- }
-
- // only one place that checks for stereo
- if (m_rasterizer->Stereo())
- {
- m_rasterizer->SetEye(RAS_IRasterizer::RAS_STEREO_RIGHTEYE);
-
- if (!BeginFrame())
- return;
-
-
- for (sceneit = m_scenes.begin();sceneit != m_scenes.end(); sceneit++)
- // for each scene, call the proceed functions
- {
- KX_Scene* scene = *sceneit;
- KX_Camera* cam = scene->GetActiveCamera();
-
- // pass the scene's worldsettings to the rasterizer
- scene->GetWorldInfo()->UpdateWorldSettings();
-
- if (scene->IsClearingZBuffer())
- m_rasterizer->ClearDepthBuffer();
-
- // pass the scene, for picking and raycasting (shadows)
- m_rasterizer->SetAuxilaryClientInfo(scene);
-
- // do the rendering
- //RenderFrame(scene);
- RenderFrame(scene, cam);
-
- list<class KX_Camera*>* cameras = scene->GetCameras();
-
- // Draw the scene once for each camera with an enabled viewport
- list<KX_Camera*>::iterator it = cameras->begin();
- while (it != cameras->end()) {
- if ((*it)->GetViewport())
- {
- if (scene->IsClearingZBuffer())
- m_rasterizer->ClearDepthBuffer();
-
- m_rasterizer->SetAuxilaryClientInfo(scene);
-
- // do the rendering
- RenderFrame(scene, (*it));
- }
-
- it++;
- }
- PostRenderScene(scene);
- }
- } // if (m_rasterizer->Stereo())
-
- EndFrame();
-}
-
-
-
-void KX_KetsjiEngine::RequestExit(int exitrequestmode)
-{
- m_exitcode = exitrequestmode;
-}
-
-
-
-void KX_KetsjiEngine::SetNameNextGame(const STR_String& nextgame)
-{
- m_exitstring = nextgame;
-}
-
-
-
-int KX_KetsjiEngine::GetExitCode()
-{
- // if a game actuator has set an exit code or if there are no scenes left
- if (!m_exitcode)
- {
- if (m_scenes.begin() == m_scenes.end())
- m_exitcode = KX_EXIT_REQUEST_NO_SCENES_LEFT;
- }
-
- // check if the window has been closed.
- if (!m_exitcode)
- {
- //if (!m_canvas->Check()) {
- // m_exitcode = KX_EXIT_REQUEST_OUTSIDE;
- //}
- }
-
- return m_exitcode;
-}
-
-
-
-const STR_String& KX_KetsjiEngine::GetExitString()
-{
- return m_exitstring;
-}
-
-void KX_KetsjiEngine::EnableCameraOverride(const STR_String& forscene)
-{
- m_overrideCam = true;
- m_overrideSceneName = forscene;
-}
-
-void KX_KetsjiEngine::SetCameraZoom(float camzoom)
-{
- m_cameraZoom = camzoom;
-}
-
-void KX_KetsjiEngine::SetCameraOverrideUseOrtho(bool useOrtho)
-{
- m_overrideCamUseOrtho = useOrtho;
-}
-
-void KX_KetsjiEngine::SetCameraOverrideProjectionMatrix(const MT_CmMatrix4x4& mat)
-{
- m_overrideCamProjMat = mat;
-}
-
-void KX_KetsjiEngine::SetCameraOverrideViewMatrix(const MT_CmMatrix4x4& mat)
-{
- m_overrideCamViewMat = mat;
-}
-
-void KX_KetsjiEngine::SetCameraOverrideClipping(float nearfrust, float farfrust)
-{
- m_overrideCamNear = nearfrust;
- m_overrideCamFar = farfrust;
-}
-
-void KX_KetsjiEngine::SetCameraOverrideLens(float lens)
-{
- m_overrideCamLens = lens;
-}
-
-void KX_KetsjiEngine::SetCameraOverrideZoom(float camzoom)
-{
- m_overrideCamZoom = camzoom;
-}
-
-void KX_KetsjiEngine::GetSceneViewport(KX_Scene *scene, KX_Camera* cam, RAS_Rect& area, RAS_Rect& viewport)
-{
- // In this function we make sure the rasterizer settings are up-to-date.
- // We compute the viewport so that logic using this information is up-to-date.
-
- // Note we postpone computation of the projection matrix
- // so that we are using the latest camera position.
- if (cam->GetViewport()) {
- RAS_Rect userviewport;
-
- userviewport.SetLeft(cam->GetViewportLeft());
- userviewport.SetBottom(cam->GetViewportBottom());
- userviewport.SetRight(cam->GetViewportRight());
- userviewport.SetTop(cam->GetViewportTop());
-
- // Don't do bars on user specified viewport
- RAS_FrameSettings settings = scene->GetFramingType();
- if (settings.FrameType() == RAS_FrameSettings::e_frame_bars)
- settings.SetFrameType(RAS_FrameSettings::e_frame_extend);
-
- RAS_FramingManager::ComputeViewport(
- scene->GetFramingType(),
- userviewport,
- viewport
- );
-
- area = userviewport;
- }
- else if ( !m_overrideCam || (scene->GetName() != m_overrideSceneName) || m_overrideCamUseOrtho ) {
- RAS_FramingManager::ComputeViewport(
- scene->GetFramingType(),
- m_canvas->GetDisplayArea(),
- viewport
- );
-
- area = m_canvas->GetDisplayArea();
- } else {
- viewport.SetLeft(0);
- viewport.SetBottom(0);
- viewport.SetRight(int(m_canvas->GetWidth()));
- viewport.SetTop(int(m_canvas->GetHeight()));
-
- area = m_canvas->GetDisplayArea();
- }
-}
-
-void KX_KetsjiEngine::UpdateAnimations(KX_Scene *scene)
-{
- if (scene->IsSuspended()) {
- return;
- }
-
- // Handle the animations independently of the logic time step
- if (GetRestrictAnimationFPS()) {
- double anim_timestep = 1.0 / KX_GetActiveScene()->GetAnimationFPS();
- if (m_frameTime - m_previousAnimTime > anim_timestep || m_frameTime == m_previousAnimTime) {
- // Sanity/debug print to make sure we're actually going at the fps we want (should be close to anim_timestep)
- // printf("Anim fps: %f\n", 1.0/(m_frameTime - m_previousAnimTime));
- m_previousAnimTime = m_frameTime;
- for (KX_SceneList::iterator sceneit = m_scenes.begin(); sceneit != m_scenes.end(); ++sceneit)
- (*sceneit)->UpdateAnimations(m_frameTime);
- }
- }
- else
- scene->UpdateAnimations(m_frameTime);
-}
-
-void KX_KetsjiEngine::RenderShadowBuffers(KX_Scene *scene)
-{
- CListValue *lightlist = scene->GetLightList();
- int i, drawmode;
-
- m_rasterizer->SetAuxilaryClientInfo(scene);
-
- for (i=0; i<lightlist->GetCount(); i++) {
- KX_GameObject *gameobj = (KX_GameObject*)lightlist->GetValue(i);
-
- KX_LightObject *light = (KX_LightObject*)gameobj;
- RAS_ILightObject *raslight = light->GetLightData();
-
- raslight->Update();
-
- if (light->GetVisible() && m_rasterizer->GetDrawingMode() == RAS_IRasterizer::KX_TEXTURED &&
- raslight->HasShadowBuffer())
- {
- /* make temporary camera */
- RAS_CameraData camdata = RAS_CameraData();
- KX_Camera *cam = new KX_Camera(scene, scene->m_callbacks, camdata, true, true);
- cam->SetName("__shadow__cam__");
-
- MT_Transform camtrans;
-
- /* switch drawmode for speed */
- drawmode = m_rasterizer->GetDrawingMode();
- m_rasterizer->SetDrawingMode(RAS_IRasterizer::KX_SHADOW);
-
- /* binds framebuffer object, sets up camera .. */
- raslight->BindShadowBuffer(m_canvas, cam, camtrans);
-
- /* update scene */
- scene->CalculateVisibleMeshes(m_rasterizer, cam, raslight->GetShadowLayer());
-
- m_logger->StartLog(tc_animations, m_kxsystem->GetTimeInSeconds(), true);
- SG_SetActiveStage(SG_STAGE_ANIMATION_UPDATE);
- UpdateAnimations(scene);
- m_logger->StartLog(tc_rasterizer, m_kxsystem->GetTimeInSeconds(), true);
- SG_SetActiveStage(SG_STAGE_RENDER);
-
- /* render */
- m_rasterizer->ClearDepthBuffer();
- m_rasterizer->ClearColorBuffer();
- scene->RenderBuckets(camtrans, m_rasterizer);
-
- /* unbind framebuffer object, restore drawmode, free camera */
- raslight->UnbindShadowBuffer();
- m_rasterizer->SetDrawingMode(drawmode);
- cam->Release();
- }
- }
- /* remember that we have a valid shadow buffer for that scene */
- scene->SetShadowDone(true);
-}
-
-// update graphics
-void KX_KetsjiEngine::RenderFrame(KX_Scene* scene, KX_Camera* cam)
-{
- bool override_camera;
- RAS_Rect viewport, area;
- float nearfrust, farfrust, focallength;
-// KX_Camera* cam = scene->GetActiveCamera();
-
- if (!cam)
- return;
-
- KX_SetActiveScene(scene);
-
-#ifdef WITH_PYTHON
- scene->RunDrawingCallbacks(scene->GetPreDrawSetupCB());
-#endif
-
- GetSceneViewport(scene, cam, area, viewport);
-
- // store the computed viewport in the scene
- scene->SetSceneViewport(viewport);
-
- // set the viewport for this frame and scene
- m_canvas->SetViewPort(viewport.GetLeft(), viewport.GetBottom(),
- viewport.GetRight(), viewport.GetTop());
-
- // see KX_BlenderMaterial::Activate
- //m_rasterizer->SetAmbient();
- m_rasterizer->DisplayFog();
-
- override_camera = m_overrideCam && (scene->GetName() == m_overrideSceneName);
- override_camera = override_camera && (cam->GetName() == "__default__cam__");
-
- if (override_camera && m_overrideCamUseOrtho) {
- m_rasterizer->SetProjectionMatrix(m_overrideCamProjMat);
- if (!cam->hasValidProjectionMatrix()) {
- // needed to get frustum planes for culling
- MT_Matrix4x4 projmat;
- projmat.setValue(m_overrideCamProjMat.getPointer());
- cam->SetProjectionMatrix(projmat);
- }
- } else if (cam->hasValidProjectionMatrix())
- {
- m_rasterizer->SetProjectionMatrix(cam->GetProjectionMatrix());
- } else
- {
- RAS_FrameFrustum frustum;
- bool orthographic = !cam->GetCameraData()->m_perspective;
- nearfrust = cam->GetCameraNear();
- farfrust = cam->GetCameraFar();
- focallength = cam->GetFocalLength();
- MT_Matrix4x4 projmat;
-
- if (override_camera) {
- nearfrust = m_overrideCamNear;
- farfrust = m_overrideCamFar;
- }
-
- float camzoom = override_camera ? m_overrideCamZoom : m_cameraZoom;
- if (orthographic) {
-
- RAS_FramingManager::ComputeOrtho(
- scene->GetFramingType(),
- area,
- viewport,
- cam->GetScale(),
- nearfrust,
- farfrust,
- cam->GetSensorFit(),
- cam->GetShiftHorizontal(),
- cam->GetShiftVertical(),
- frustum
- );
- if (!cam->GetViewport()) {
- frustum.x1 *= camzoom;
- frustum.x2 *= camzoom;
- frustum.y1 *= camzoom;
- frustum.y2 *= camzoom;
- }
- projmat = m_rasterizer->GetOrthoMatrix(
- frustum.x1, frustum.x2, frustum.y1, frustum.y2, frustum.camnear, frustum.camfar);
-
- } else {
- RAS_FramingManager::ComputeFrustum(
- scene->GetFramingType(),
- area,
- viewport,
- cam->GetLens(),
- cam->GetSensorWidth(),
- cam->GetSensorHeight(),
- cam->GetSensorFit(),
- cam->GetShiftHorizontal(),
- cam->GetShiftVertical(),
- nearfrust,
- farfrust,
- frustum
- );
-
- if (!cam->GetViewport()) {
- frustum.x1 *= camzoom;
- frustum.x2 *= camzoom;
- frustum.y1 *= camzoom;
- frustum.y2 *= camzoom;
- }
- projmat = m_rasterizer->GetFrustumMatrix(
- frustum.x1, frustum.x2, frustum.y1, frustum.y2, frustum.camnear, frustum.camfar, focallength);
- }
- cam->SetProjectionMatrix(projmat);
-
- // Otherwise the projection matrix for each eye will be the same...
- if (!orthographic && m_rasterizer->Stereo())
- cam->InvalidateProjectionMatrix();
- }
-
- MT_Transform camtrans(cam->GetWorldToCamera());
- MT_Matrix4x4 viewmat(camtrans);
-
- m_rasterizer->SetViewMatrix(viewmat, cam->NodeGetWorldOrientation(), cam->NodeGetWorldPosition(), cam->NodeGetLocalScaling(), cam->GetCameraData()->m_perspective);
- cam->SetModelviewMatrix(viewmat);
-
- // The following actually reschedules all vertices to be
- // redrawn. There is a cache between the actual rescheduling
- // and this call though. Visibility is imparted when this call
- // runs through the individual objects.
-
- m_logger->StartLog(tc_scenegraph, m_kxsystem->GetTimeInSeconds(), true);
- SG_SetActiveStage(SG_STAGE_CULLING);
-
- scene->CalculateVisibleMeshes(m_rasterizer,cam);
-
- m_logger->StartLog(tc_animations, m_kxsystem->GetTimeInSeconds(), true);
- SG_SetActiveStage(SG_STAGE_ANIMATION_UPDATE);
- UpdateAnimations(scene);
-
- m_logger->StartLog(tc_rasterizer, m_kxsystem->GetTimeInSeconds(), true);
- SG_SetActiveStage(SG_STAGE_RENDER);
-
-#ifdef WITH_PYTHON
- PHY_SetActiveEnvironment(scene->GetPhysicsEnvironment());
- // Run any pre-drawing python callbacks
- scene->RunDrawingCallbacks(scene->GetPreDrawCB());
-#endif
-
- scene->RenderBuckets(camtrans, m_rasterizer);
-
- // render all the font objects for this scene
- scene->RenderFonts();
-
- if (scene->GetPhysicsEnvironment())
- scene->GetPhysicsEnvironment()->DebugDrawWorld();
-}
-
-/*
- * To run once per scene
- */
-void KX_KetsjiEngine::PostRenderScene(KX_Scene* scene)
-{
- KX_SetActiveScene(scene);
-
- // We need to first make sure our viewport is correct (enabling multiple viewports can mess this up)
- m_canvas->SetViewPort(0, 0, m_canvas->GetWidth(), m_canvas->GetHeight());
-
- m_rasterizer->FlushDebugShapes(scene);
- scene->Render2DFilters(m_canvas);
-
-#ifdef WITH_PYTHON
- PHY_SetActiveEnvironment(scene->GetPhysicsEnvironment());
- scene->RunDrawingCallbacks(scene->GetPostDrawCB());
-
- // Python draw callback can also call debug draw functions, so we have to clear debug shapes.
- m_rasterizer->FlushDebugShapes(scene);
-#endif
-}
-
-void KX_KetsjiEngine::StopEngine()
-{
- if (m_bInitialized)
- {
- m_sceneconverter->FinalizeAsyncLoads();
-
- if (m_animation_record)
- {
-// printf("TestHandlesPhysicsObjectToAnimationIpo\n");
- m_sceneconverter->TestHandlesPhysicsObjectToAnimationIpo();
- }
-
- KX_SceneList::iterator sceneit;
- for (sceneit = m_scenes.begin();sceneit != m_scenes.end() ; sceneit++)
- {
- KX_Scene* scene = *sceneit;
- m_sceneconverter->RemoveScene(scene);
- }
- m_scenes.clear();
-
- // cleanup all the stuff
- m_rasterizer->Exit();
- }
-}
-
-// Scene Management is able to switch between scenes
-// and have several scenes running in parallel
-void KX_KetsjiEngine::AddScene(KX_Scene* scene)
-{
- m_scenes.push_back(scene);
- PostProcessScene(scene);
-}
-
-
-
-void KX_KetsjiEngine::PostProcessScene(KX_Scene* scene)
-{
- bool override_camera = (m_overrideCam && (scene->GetName() == m_overrideSceneName));
-
- SG_SetActiveStage(SG_STAGE_SCENE);
-
- // if there is no activecamera, or the camera is being
- // overridden we need to construct a temporary camera
- if (!scene->GetActiveCamera() || override_camera)
- {
- KX_Camera* activecam = NULL;
-
- RAS_CameraData camdata = RAS_CameraData();
- if (override_camera)
- {
- camdata.m_lens = m_overrideCamLens;
- camdata.m_clipstart = m_overrideCamNear;
- camdata.m_clipend = m_overrideCamFar;
-
- camdata.m_perspective= !m_overrideCamUseOrtho;
- }
- activecam = new KX_Camera(scene,KX_Scene::m_callbacks,camdata);
- activecam->SetName("__default__cam__");
-
- // set transformation
- if (override_camera) {
- const MT_CmMatrix4x4& cammatdata = m_overrideCamViewMat;
- MT_Transform trans = MT_Transform(cammatdata.getPointer());
- MT_Transform camtrans;
- camtrans.invert(trans);
-
- activecam->NodeSetLocalPosition(camtrans.getOrigin());
- activecam->NodeSetLocalOrientation(camtrans.getBasis());
- activecam->NodeUpdateGS(0);
- } else {
- activecam->NodeSetLocalPosition(MT_Point3(0.0f, 0.0f, 0.0f));
- activecam->NodeSetLocalOrientation(MT_Vector3(0.0f, 0.0f, 0.0f));
- activecam->NodeUpdateGS(0);
- }
-
- scene->AddCamera(activecam);
- scene->SetActiveCamera(activecam);
- scene->GetObjectList()->Add(activecam->AddRef());
- scene->GetRootParentList()->Add(activecam->AddRef());
- // done with activecam
- activecam->Release();
- }
-
- scene->UpdateParents(0.0);
-}
-
-
-
-void KX_KetsjiEngine::RenderDebugProperties()
-{
- STR_String debugtxt;
- int title_xmargin = -7;
- int title_y_top_margin = 4;
- int title_y_bottom_margin = 2;
-
- int const_xindent = 4;
- int const_ysize = 14;
-
- int xcoord = 12; // mmmm, these constants were taken from blender source
- int ycoord = 17; // to 'mimic' behavior
-
- int profile_indent = 72;
-
- float tottime = m_logger->GetAverage();
- if (tottime < 1e-6f) {
- tottime = 1e-6f;
- }
-
- // Set viewport to entire canvas
- RAS_Rect viewport;
- m_canvas->SetViewPort(0, 0, int(m_canvas->GetWidth()), int(m_canvas->GetHeight()));
-
- if (m_show_framerate || m_show_profile) {
- /* Title for profiling("Profile") */
- m_rasterizer->RenderText2D(RAS_IRasterizer::RAS_TEXT_PADDED,
- "Profile",
- xcoord + const_xindent + title_xmargin, // Adds the constant x indent (0 for now) to the title x margin
- ycoord,
- m_canvas->GetWidth() /* RdV, TODO ?? */,
- m_canvas->GetHeight() /* RdV, TODO ?? */);
-
- // Increase the indent by default increase
- ycoord += const_ysize;
- // Add the title indent afterwards
- ycoord += title_y_bottom_margin;
- }
-
- /* Framerate display */
- if (m_show_framerate) {
- m_rasterizer->RenderText2D(RAS_IRasterizer::RAS_TEXT_PADDED,
- "Frametime :",
- xcoord + const_xindent,
- ycoord,
- m_canvas->GetWidth() /* RdV, TODO ?? */,
- m_canvas->GetHeight() /* RdV, TODO ?? */);
-
- debugtxt.Format("%5.1fms (%.1ffps)", tottime * 1000.0f, 1.0f/tottime);
- m_rasterizer->RenderText2D(RAS_IRasterizer::RAS_TEXT_PADDED,
- debugtxt.ReadPtr(),
- xcoord + const_xindent + profile_indent,
- ycoord,
- m_canvas->GetWidth() /* RdV, TODO ?? */,
- m_canvas->GetHeight() /* RdV, TODO ?? */);
- // Increase the indent by default increase
- ycoord += const_ysize;
- }
-
- /* Profile display */
- if (m_show_profile) {
- for (int j = tc_first; j < tc_numCategories; j++) {
- m_rasterizer->RenderText2D(RAS_IRasterizer::RAS_TEXT_PADDED,
- m_profileLabels[j],
- xcoord + const_xindent,
- ycoord,
- m_canvas->GetWidth(),
- m_canvas->GetHeight());
-
- double time = m_logger->GetAverage((KX_TimeCategory)j);
-
- debugtxt.Format("%5.2fms | %d%%", (float)time*1000.f, (int)((float)time/tottime * 100.f));
- m_rasterizer->RenderText2D(RAS_IRasterizer::RAS_TEXT_PADDED,
- debugtxt.ReadPtr(),
- xcoord + const_xindent + profile_indent, ycoord,
- m_canvas->GetWidth(),
- m_canvas->GetHeight());
-
- m_rasterizer->RenderBox2D(xcoord + (int)(2.2f * profile_indent), ycoord, m_canvas->GetWidth(), m_canvas->GetHeight(), (float)time/tottime);
- ycoord += const_ysize;
- }
- }
- // Add the ymargin for titles below the other section of debug info
- ycoord += title_y_top_margin;
-
- /* Property display */
- if (m_show_debug_properties) {
-
- /* Title for debugging("Debug properties") */
- m_rasterizer->RenderText2D(RAS_IRasterizer::RAS_TEXT_PADDED,
- "Debug Properties",
- xcoord + const_xindent + title_xmargin, // Adds the constant x indent (0 for now) to the title x margin
- ycoord,
- m_canvas->GetWidth() /* RdV, TODO ?? */,
- m_canvas->GetHeight() /* RdV, TODO ?? */);
-
- // Increase the indent by default increase
- ycoord += const_ysize;
- // Add the title indent afterwards
- ycoord += title_y_bottom_margin;
-
- /* Calculate amount of properties that can displayed. */
- unsigned propsAct = 0;
- unsigned propsMax = (m_canvas->GetHeight() - ycoord) / const_ysize;
-
- KX_SceneList::iterator sceneit;
- for (sceneit = m_scenes.begin();sceneit != m_scenes.end(); sceneit++) {
- KX_Scene* scene = *sceneit;
- /* the 'normal' debug props */
- vector<SCA_DebugProp*>& debugproplist = scene->GetDebugProperties();
-
- for (unsigned i=0; i < debugproplist.size() && propsAct < propsMax; i++)
- {
- CValue *propobj = debugproplist[i]->m_obj;
- STR_String objname = propobj->GetName();
- STR_String propname = debugproplist[i]->m_name;
- propsAct++;
- if (propname == "__state__") {
- // reserve name for object state
- KX_GameObject* gameobj = static_cast<KX_GameObject*>(propobj);
- unsigned int state = gameobj->GetState();
- debugtxt = objname + "." + propname + " = ";
- bool first = true;
- for (int statenum=1;state;state >>= 1, statenum++)
- {
- if (state & 1)
- {
- if (!first)
- {
- debugtxt += ",";
- }
- debugtxt += STR_String(statenum);
- first = false;
- }
- }
- m_rasterizer->RenderText2D(RAS_IRasterizer::RAS_TEXT_PADDED,
- debugtxt.ReadPtr(),
- xcoord + const_xindent,
- ycoord,
- m_canvas->GetWidth(),
- m_canvas->GetHeight());
- ycoord += const_ysize;
- }
- else {
- CValue *propval = propobj->GetProperty(propname);
- if (propval) {
- STR_String text = propval->GetText();
- debugtxt = objname + ": '" + propname + "' = " + text;
- m_rasterizer->RenderText2D(RAS_IRasterizer::RAS_TEXT_PADDED,
- debugtxt.ReadPtr(),
- xcoord + const_xindent,
- ycoord,
- m_canvas->GetWidth(),
- m_canvas->GetHeight());
- ycoord += const_ysize;
- }
- }
- }
- }
- }
-}
-
-
-KX_SceneList* KX_KetsjiEngine::CurrentScenes()
-{
- return &m_scenes;
-}
-
-
-
-KX_Scene* KX_KetsjiEngine::FindScene(const STR_String& scenename)
-{
- KX_SceneList::iterator sceneit = m_scenes.begin();
-
- // bit risky :) better to split the second clause
- while ( (sceneit != m_scenes.end())
- && ((*sceneit)->GetName() != scenename))
- {
- sceneit++;
- }
-
- return ((sceneit == m_scenes.end()) ? NULL : *sceneit);
-}
-
-
-
-void KX_KetsjiEngine::ConvertAndAddScene(const STR_String& scenename,bool overlay)
-{
- // only add scene when it doesn't exist!
- if (FindScene(scenename)) {
- printf("warning: scene %s already exists, not added!\n",scenename.ReadPtr());
- }
- else {
- if (overlay) {
- m_addingOverlayScenes.push_back(scenename);
- }
- else {
- m_addingBackgroundScenes.push_back(scenename);
- }
- }
-}
-
-
-
-
-void KX_KetsjiEngine::RemoveScene(const STR_String& scenename)
-{
- if (FindScene(scenename))
- {
- m_removingScenes.push_back(scenename);
- }
- else
- {
-// STR_String tmpname = scenename;
- std::cout << "warning: scene " << scenename << " does not exist, not removed!" << std::endl;
- }
-}
-
-
-
-void KX_KetsjiEngine::RemoveScheduledScenes()
-{
- if (m_removingScenes.size())
- {
- vector<STR_String>::iterator scenenameit;
- for (scenenameit=m_removingScenes.begin();scenenameit != m_removingScenes.end();scenenameit++)
- {
- STR_String scenename = *scenenameit;
-
- KX_SceneList::iterator sceneit;
- for (sceneit = m_scenes.begin();sceneit != m_scenes.end() ; sceneit++)
- {
- KX_Scene* scene = *sceneit;
- if (scene->GetName()==scenename)
- {
- m_sceneconverter->RemoveScene(scene);
- m_scenes.erase(sceneit);
- break;
- }
- }
- }
- m_removingScenes.clear();
- }
-}
-
-KX_Scene* KX_KetsjiEngine::CreateScene(Scene *scene, bool libloading)
-{
- KX_Scene* tmpscene = new KX_Scene(m_keyboarddevice,
- m_mousedevice,
- m_networkdevice,
- scene->id.name+2,
- scene,
- m_canvas);
-
- m_sceneconverter->ConvertScene(tmpscene,
- m_rasterizer,
- m_canvas,
- libloading);
-
- return tmpscene;
-}
-
-KX_Scene* KX_KetsjiEngine::CreateScene(const STR_String& scenename)
-{
- Scene *scene = m_sceneconverter->GetBlenderSceneForName(scenename);
- if (!scene)
- return NULL;
- return CreateScene(scene);
-}
-
-void KX_KetsjiEngine::AddScheduledScenes()
-{
- vector<STR_String>::iterator scenenameit;
-
- if (m_addingOverlayScenes.size())
- {
- for (scenenameit = m_addingOverlayScenes.begin();
- scenenameit != m_addingOverlayScenes.end();
- scenenameit++)
- {
- STR_String scenename = *scenenameit;
- KX_Scene* tmpscene = CreateScene(scenename);
- if (tmpscene) {
- m_scenes.push_back(tmpscene);
- PostProcessScene(tmpscene);
- } else {
- printf("warning: scene %s could not be found, not added!\n",scenename.ReadPtr());
- }
- }
- m_addingOverlayScenes.clear();
- }
-
- if (m_addingBackgroundScenes.size())
- {
- for (scenenameit = m_addingBackgroundScenes.begin();
- scenenameit != m_addingBackgroundScenes.end();
- scenenameit++)
- {
- STR_String scenename = *scenenameit;
- KX_Scene* tmpscene = CreateScene(scenename);
- if (tmpscene) {
- m_scenes.insert(m_scenes.begin(),tmpscene);
- PostProcessScene(tmpscene);
- } else {
- printf("warning: scene %s could not be found, not added!\n",scenename.ReadPtr());
- }
- }
- m_addingBackgroundScenes.clear();
- }
-}
-
-
-
-bool KX_KetsjiEngine::ReplaceScene(const STR_String& oldscene,const STR_String& newscene)
-{
- // Don't allow replacement if the new scene doesn't exist.
- // Allows smarter game design (used to have no check here).
- // Note that it creates a small backward compatbility issue
- // for a game that did a replace followed by a lib load with the
- // new scene in the lib => it won't work anymore, the lib
- // must be loaded before doing the replace.
- if (m_sceneconverter->GetBlenderSceneForName(newscene) != NULL) {
- m_replace_scenes.push_back(std::make_pair(oldscene,newscene));
- return true;
- }
- return false;
-}
-
-// replace scene is not the same as removing and adding because the
-// scene must be in exact the same place (to maintain drawingorder)
-// (nzc) - should that not be done with a scene-display list? It seems
-// stupid to rely on the mem allocation order...
-void KX_KetsjiEngine::ReplaceScheduledScenes()
-{
- if (m_replace_scenes.size())
- {
- vector<pair<STR_String,STR_String> >::iterator scenenameit;
-
- for (scenenameit = m_replace_scenes.begin();
- scenenameit != m_replace_scenes.end();
- scenenameit++)
- {
- STR_String oldscenename = (*scenenameit).first;
- STR_String newscenename = (*scenenameit).second;
- int i=0;
- /* Scenes are not supposed to be included twice... I think */
- KX_SceneList::iterator sceneit;
- for (sceneit = m_scenes.begin();sceneit != m_scenes.end() ; sceneit++) {
- KX_Scene* scene = *sceneit;
- if (scene->GetName() == oldscenename) {
- // avoid crash if the new scene doesn't exist, just do nothing
- Scene *blScene = m_sceneconverter->GetBlenderSceneForName(newscenename);
- if (blScene) {
- m_sceneconverter->RemoveScene(scene);
- KX_Scene* tmpscene = CreateScene(blScene);
- m_scenes[i]=tmpscene;
- PostProcessScene(tmpscene);
- }
- else {
- printf("warning: scene %s could not be found, not replaced!\n",newscenename.ReadPtr());
- }
- }
- i++;
- }
- }
- m_replace_scenes.clear();
- }
-}
-
-
-
-void KX_KetsjiEngine::SuspendScene(const STR_String& scenename)
-{
- KX_Scene* scene = FindScene(scenename);
- if (scene) scene->Suspend();
-}
-
-
-
-void KX_KetsjiEngine::ResumeScene(const STR_String& scenename)
-{
- KX_Scene* scene = FindScene(scenename);
- if (scene) scene->Resume();
-}
-
-
-
-void KX_KetsjiEngine::SetUseFixedTime(bool bUseFixedTime)
-{
- m_bFixedTime = bUseFixedTime;
-}
-
-void KX_KetsjiEngine::SetUseExternalClock(bool useExternalClock)
-{
- m_useExternalClock = useExternalClock;
-}
-
-void KX_KetsjiEngine::SetAnimRecordMode(bool animation_record, int startFrame)
-{
- m_animation_record = animation_record;
- if (animation_record)
- {
- // when recording physics keyframes, run at a variable (capped) frame rate (fixed time == full speed)
- m_bFixedTime = false;
- }
- m_currentFrame = startFrame;
-}
-
-int KX_KetsjiEngine::getAnimRecordFrame() const
-{
- return m_currentFrame;
-}
-
-void KX_KetsjiEngine::setAnimRecordFrame(int framenr)
-{
- m_currentFrame = framenr;
-}
-
-bool KX_KetsjiEngine::GetUseFixedTime(void) const
-{
- return m_bFixedTime;
-}
-
-bool KX_KetsjiEngine::GetUseExternalClock(void) const
-{
- return m_useExternalClock;
-}
-
-double KX_KetsjiEngine::GetSuspendedDelta()
-{
- return m_suspendeddelta;
-}
-
-double KX_KetsjiEngine::GetTicRate()
-{
- return m_ticrate;
-}
-
-void KX_KetsjiEngine::SetTicRate(double ticrate)
-{
- m_ticrate = ticrate;
-}
-
-double KX_KetsjiEngine::GetTimeScale() const
-{
- return m_timescale;
-}
-
-void KX_KetsjiEngine::SetTimeScale(double timescale)
-{
- m_timescale = timescale;
-}
-
-int KX_KetsjiEngine::GetMaxLogicFrame()
-{
- return m_maxLogicFrame;
-}
-
-void KX_KetsjiEngine::SetMaxLogicFrame(int frame)
-{
- m_maxLogicFrame = frame;
-}
-
-int KX_KetsjiEngine::GetMaxPhysicsFrame()
-{
- return m_maxPhysicsFrame;
-}
-
-void KX_KetsjiEngine::SetMaxPhysicsFrame(int frame)
-{
- m_maxPhysicsFrame = frame;
-}
-
-bool KX_KetsjiEngine::GetRestrictAnimationFPS()
-{
- return m_restrict_anim_fps;
-}
-
-void KX_KetsjiEngine::SetRestrictAnimationFPS(bool bRestrictAnimFPS)
-{
- m_restrict_anim_fps = bRestrictAnimFPS;
-}
-
-double KX_KetsjiEngine::GetAnimFrameRate()
-{
- return m_anim_framerate;
-}
-
-double KX_KetsjiEngine::GetClockTime(void) const
-{
- return m_clockTime;
-}
-
-void KX_KetsjiEngine::SetClockTime(double externalClockTime)
-{
- m_clockTime = externalClockTime;
-}
-
-double KX_KetsjiEngine::GetFrameTime(void) const
-{
- return m_frameTime;
-}
-
-double KX_KetsjiEngine::GetRealTime(void) const
-{
- return m_kxsystem->GetTimeInSeconds();
-}
-
-void KX_KetsjiEngine::SetAnimFrameRate(double framerate)
-{
- m_anim_framerate = framerate;
-}
-
-double KX_KetsjiEngine::GetAverageFrameRate()
-{
- return m_average_framerate;
-}
-
-void KX_KetsjiEngine::SetExitKey(short key)
-{
- m_exitkey = key;
-}
-
-short KX_KetsjiEngine::GetExitKey()
-{
- return m_exitkey;
-}
-
-void KX_KetsjiEngine::SetRender(bool render)
-{
- m_doRender = render;
-}
-
-bool KX_KetsjiEngine::GetRender()
-{
- return m_doRender;
-}
-
-void KX_KetsjiEngine::SetShowFramerate(bool frameRate)
-{
- m_show_framerate = frameRate;
-}
-
-bool KX_KetsjiEngine::GetShowFramerate()
-{
- return m_show_framerate;
-}
-
-void KX_KetsjiEngine::SetShowProfile(bool profile)
-{
- m_show_profile = profile;
-}
-
-bool KX_KetsjiEngine::GetShowProfile()
-{
- return m_show_profile;
-}
-
-void KX_KetsjiEngine::SetShowProperties(bool properties)
-{
- m_show_debug_properties = properties;
-}
-
-bool KX_KetsjiEngine::GetShowProperties()
-{
- return m_show_debug_properties;
-}
-
-void KX_KetsjiEngine::SetAutoAddDebugProperties(bool add)
-{
- m_autoAddDebugProperties = add;
-}
-
-bool KX_KetsjiEngine::GetAutoAddDebugProperties()
-{
- return m_autoAddDebugProperties;
-}
-
-void KX_KetsjiEngine::SetTimingDisplay(bool frameRate, bool profile, bool properties)
-{
- m_show_framerate = frameRate;
- m_show_profile = profile;
- m_show_debug_properties = properties;
-}
-
-
-
-void KX_KetsjiEngine::GetTimingDisplay(bool& frameRate, bool& profile, bool& properties) const
-{
- frameRate = m_show_framerate;
- profile = m_show_profile;
- properties = m_show_debug_properties;
-}
-
-
-
-void KX_KetsjiEngine::ProcessScheduledScenes(void)
-{
- // Check whether there will be changes to the list of scenes
- if (m_addingOverlayScenes.size() ||
- m_addingBackgroundScenes.size() ||
- m_replace_scenes.size() ||
- m_removingScenes.size()) {
-
- // Change the scene list
- ReplaceScheduledScenes();
- RemoveScheduledScenes();
- AddScheduledScenes();
- }
-}
-
-
-void KX_KetsjiEngine::SetHideCursor(bool hideCursor)
-{
- m_hideCursor = hideCursor;
-}
-
-
-bool KX_KetsjiEngine::GetHideCursor(void) const
-{
- return m_hideCursor;
-}
-
-
-void KX_KetsjiEngine::SetUseOverrideFrameColor(bool overrideFrameColor)
-{
- m_overrideFrameColor = overrideFrameColor;
-}
-
-
-bool KX_KetsjiEngine::GetUseOverrideFrameColor(void) const
-{
- return m_overrideFrameColor;
-}
-
-
-void KX_KetsjiEngine::SetOverrideFrameColor(float r, float g, float b, float a)
-{
- m_overrideFrameColorR = r;
- m_overrideFrameColorG = g;
- m_overrideFrameColorB = b;
- m_overrideFrameColorA = a;
-}
-
-
-void KX_KetsjiEngine::GetOverrideFrameColor(float& r, float& g, float& b, float& a) const
-{
- r = m_overrideFrameColorR;
- g = m_overrideFrameColorG;
- b = m_overrideFrameColorB;
- a = m_overrideFrameColorA;
-}
-
-
-void KX_KetsjiEngine::Resize()
-{
- KX_SceneList::iterator sceneit;
-
- /* extended mode needs to recalculate camera frusta when */
- KX_Scene* firstscene = *m_scenes.begin();
- const RAS_FrameSettings &framesettings = firstscene->GetFramingType();
-
- if (framesettings.FrameType() == RAS_FrameSettings::e_frame_extend) {
- for (sceneit = m_scenes.begin(); sceneit != m_scenes.end(); sceneit++) {
- KX_Camera* cam = ((KX_Scene *)*sceneit)->GetActiveCamera();
- cam->InvalidateProjectionMatrix();
- }
- }
-}
-
-
-void KX_KetsjiEngine::SetGlobalSettings(GlobalSettings* gs)
-{
- m_globalsettings.matmode = gs->matmode;
- m_globalsettings.glslflag = gs->glslflag;
-}
-
-GlobalSettings* KX_KetsjiEngine::GetGlobalSettings(void)
-{
- return &m_globalsettings;
-}
-
diff --git a/source/gameengine/Ketsji/KX_KetsjiEngine.h b/source/gameengine/Ketsji/KX_KetsjiEngine.h
deleted file mode 100644
index 1756214b6dd..00000000000
--- a/source/gameengine/Ketsji/KX_KetsjiEngine.h
+++ /dev/null
@@ -1,553 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- *
- */
-
-/** \file KX_KetsjiEngine.h
- * \ingroup ketsji
- */
-
-#ifndef __KX_KETSJIENGINE_H__
-#define __KX_KETSJIENGINE_H__
-
-#include "MT_CmMatrix4x4.h"
-#include "MT_Matrix4x4.h"
-#include "STR_String.h"
-#include "KX_ISystem.h"
-#include "KX_Scene.h"
-#include "EXP_Python.h"
-#include "KX_WorldInfo.h"
-#include <vector>
-
-struct TaskScheduler;
-class KX_TimeCategoryLogger;
-
-#define LEFT_EYE 1
-#define RIGHT_EYE 2
-
-enum KX_ExitRequestMode
-{
- KX_EXIT_REQUEST_NO_REQUEST = 0,
- KX_EXIT_REQUEST_QUIT_GAME,
- KX_EXIT_REQUEST_RESTART_GAME,
- KX_EXIT_REQUEST_START_OTHER_GAME,
- KX_EXIT_REQUEST_NO_SCENES_LEFT,
- KX_EXIT_REQUEST_BLENDER_ESC,
- KX_EXIT_REQUEST_OUTSIDE,
- KX_EXIT_REQUEST_MAX
-};
-
-typedef struct {
- short matmode;
- short glslflag;
-} GlobalSettings;
-
-/**
- * KX_KetsjiEngine is the core game engine class.
- */
-class KX_KetsjiEngine
-{
-
-private:
- class RAS_ICanvas* m_canvas; // 2D Canvas (2D Rendering Device Context)
- class RAS_IRasterizer* m_rasterizer; // 3D Rasterizer (3D Rendering)
- class KX_ISystem* m_kxsystem;
- class KX_ISceneConverter* m_sceneconverter;
- class NG_NetworkDeviceInterface* m_networkdevice;
-#ifdef WITH_PYTHON
- /* borrowed from sys.modules["__main__"], don't manage ref's */
- PyObject* m_pythondictionary;
- PyObject* m_pyprofiledict;
-#endif
- class SCA_IInputDevice* m_keyboarddevice;
- class SCA_IInputDevice* m_mousedevice;
- class KX_Dome* m_dome; // dome stereo mode
-
- /** Lists of scenes scheduled to be removed at the end of the frame. */
- std::vector<STR_String> m_removingScenes;
- /** Lists of overley scenes scheduled to be added at the end of the frame. */
- std::vector<STR_String> m_addingOverlayScenes;
- /** Lists of background scenes scheduled to be added at the end of the frame. */
- std::vector<STR_String> m_addingBackgroundScenes;
- /** Lists of scenes scheduled to be replaced at the end of the frame. */
- std::vector<std::pair<STR_String,STR_String> > m_replace_scenes;
-
- /* The current list of scenes. */
- KX_SceneList m_scenes;
- /* State variable recording the presence of object debug info in the current scene list. */
- bool m_propertiesPresent;
-
- bool m_bInitialized;
- int m_activecam;
- bool m_bFixedTime;
- bool m_useExternalClock;
-
-
- bool m_firstframe;
- int m_currentFrame;
-
- double m_frameTime; // current logic game time
- double m_clockTime; // game time for the next rendering step
- double m_previousClockTime; // game time of the previous rendering step
- double m_previousAnimTime; //game time when the animations were last updated
- double m_remainingTime;
- double m_timescale; // time scaling parameter. if > 1.0, time goes faster than real-time. If < 1.0, times goes slower than real-time.
- double m_previousRealTime;
-
- static int m_maxLogicFrame; /* maximum number of consecutive logic frame */
- static int m_maxPhysicsFrame; /* maximum number of consecutive physics frame */
- static double m_ticrate;
- static double m_anim_framerate; /* for animation playback only - ipo and action */
-
- static bool m_restrict_anim_fps;
-
- static double m_suspendedtime;
- static double m_suspendeddelta;
-
- static short m_exitkey; /* Key used to exit the BGE */
-
- static bool m_doRender; /* whether or not the scene should be rendered after the logic frame */
-
- int m_exitcode;
- STR_String m_exitstring;
-
- float m_cameraZoom;
-
- bool m_overrideCam;
- STR_String m_overrideSceneName;
-
- bool m_overrideCamUseOrtho;
- MT_CmMatrix4x4 m_overrideCamProjMat;
- MT_CmMatrix4x4 m_overrideCamViewMat;
- float m_overrideCamNear;
- float m_overrideCamFar;
- float m_overrideCamLens;
- /// Default camera zoom.
- float m_overrideCamZoom;
-
- bool m_stereo;
- int m_curreye;
-
- /** Categories for profiling display. */
- typedef enum {
- tc_first = 0,
- tc_physics = 0,
- tc_logic,
- tc_animations,
- tc_network,
- tc_scenegraph,
- tc_rasterizer,
- tc_services, // time spent in miscelaneous activities
- tc_overhead, // profile info drawing overhead
- tc_outside, // time spent outside main loop
- tc_latency, // time spent waiting on the gpu
- tc_numCategories
- } KX_TimeCategory;
-
- /** Time logger. */
- KX_TimeCategoryLogger* m_logger;
-
- /** Labels for profiling display. */
- static const char m_profileLabels[tc_numCategories][15];
- /** Last estimated framerate */
- static double m_average_framerate;
- /** Show the framerate on the game display? */
- bool m_show_framerate;
- /** Show profiling info on the game display? */
- bool m_show_profile;
- /** Show any debug (scene) object properties on the game display? */
- bool m_showProperties;
- /** Show background behind text for readability? */
- bool m_showBackground;
- /** Show debug properties on the game display*/
- bool m_show_debug_properties;
- /** Automatic add debug properties to the debug list*/
- bool m_autoAddDebugProperties;
-
- /** record physics into keyframes */
- bool m_animation_record;
-
- /** Hide cursor every frame? */
- bool m_hideCursor;
-
- /** Override framing bars color? */
- bool m_overrideFrameColor;
- /** Red component of framing bar color. */
- float m_overrideFrameColorR;
- /** Green component of framing bar color. */
- float m_overrideFrameColorG;
- /** Blue component of framing bar color. */
- float m_overrideFrameColorB;
- /** alpha component of framing bar color. */
- float m_overrideFrameColorA;
-
- /** Settings that doesn't go away with Game Actuator */
- GlobalSettings m_globalsettings;
-
- /** Task scheduler for multi-threading */
- TaskScheduler* m_taskscheduler;
-
- void RenderFrame(KX_Scene* scene, KX_Camera* cam);
- void PostRenderScene(KX_Scene* scene);
- void RenderDebugProperties();
-
-public:
- KX_KetsjiEngine(class KX_ISystem* system);
- virtual ~KX_KetsjiEngine();
-
- // set the devices and stuff. the client must take care of creating these
- void SetKeyboardDevice(SCA_IInputDevice* keyboarddevice);
- void SetMouseDevice(SCA_IInputDevice* mousedevice);
- void SetNetworkDevice(NG_NetworkDeviceInterface* networkdevice);
- void SetCanvas(RAS_ICanvas* canvas);
- void SetRasterizer(RAS_IRasterizer* rasterizer);
-#ifdef WITH_PYTHON
- void SetPyNamespace(PyObject *pythondictionary);
- PyObject* GetPyNamespace() { return m_pythondictionary; }
- PyObject* GetPyProfileDict();
-#endif
- void SetSceneConverter(KX_ISceneConverter* sceneconverter);
- KX_ISceneConverter* GetSceneConverter() { return m_sceneconverter; }
- void SetAnimRecordMode(bool animation_record, int startFrame);
-
- int getAnimRecordFrame() const;
- void setAnimRecordFrame(int framenr);
-
- RAS_IRasterizer* GetRasterizer() { return m_rasterizer; }
- RAS_ICanvas* GetCanvas() { return m_canvas; }
- SCA_IInputDevice* GetKeyboardDevice() { return m_keyboarddevice; }
- SCA_IInputDevice* GetMouseDevice() { return m_mousedevice; }
-
- TaskScheduler* GetTaskScheduler() { return m_taskscheduler; }
-
- /// Dome functions
- void InitDome(short res, short mode, short angle, float resbuf, short tilt, struct Text* text);
- void EndDome();
- void RenderDome();
- bool m_usedome;
-
- ///returns true if an update happened to indicate -> Render
- bool NextFrame();
- void Render();
- void RenderShadowBuffers(KX_Scene *scene);
-
- void StartEngine(bool clearIpo);
- void StopEngine();
- void Export(const STR_String& filename);
-
- void RequestExit(int exitrequestmode);
- void SetNameNextGame(const STR_String& nextgame);
- int GetExitCode();
- const STR_String& GetExitString();
-
- KX_SceneList* CurrentScenes();
- KX_Scene* FindScene(const STR_String& scenename);
- void AddScene(class KX_Scene* scene);
- void ConvertAndAddScene(const STR_String& scenename,bool overlay);
-
- void RemoveScene(const STR_String& scenename);
- bool ReplaceScene(const STR_String& oldscene,const STR_String& newscene);
- void SuspendScene(const STR_String& scenename);
- void ResumeScene(const STR_String& scenename);
-
- void GetSceneViewport(KX_Scene* scene, KX_Camera* cam, RAS_Rect& area, RAS_Rect& viewport);
-
- /// Sets zoom for camera objects, useful only with extend and scale framing mode.
- void SetCameraZoom(float camzoom);
-
- void EnableCameraOverride(const STR_String& forscene);
-
- void SetCameraOverrideUseOrtho(bool useOrtho);
- void SetCameraOverrideProjectionMatrix(const MT_CmMatrix4x4& mat);
- void SetCameraOverrideViewMatrix(const MT_CmMatrix4x4& mat);
- void SetCameraOverrideClipping(float near, float far);
- void SetCameraOverrideLens(float lens);
- /// Sets zoom for default camera, = 2 in embedded mode.
- void SetCameraOverrideZoom(float camzoom);
-
- // Update animations for object in this scene
- void UpdateAnimations(KX_Scene *scene);
-
- /**
- * Sets display of all frames.
- * \param bUseFixedTime New setting for display all frames.
- */
- void SetUseFixedTime(bool bUseFixedTime);
-
- /**
- * Returns display of all frames.
- * \return Current setting for display all frames.
- */
- bool GetUseFixedTime(void) const;
-
- /**
- * Sets if the BGE relies on a external clock or its own internal clock
- */
- void SetUseExternalClock(bool bUseExternalClock);
-
- /**
- * Returns if we rely on an external clock
- * \return Current setting
- */
- bool GetUseExternalClock(void) const;
-
- /**
- * Returns next render frame game time
- */
- double GetClockTime(void) const;
-
- /**
- * Set the next render frame game time. It will impact also frame time, as
- * this one is derived from clocktime
- */
- void SetClockTime(double externalClockTime);
-
- /**
- * Returns current logic frame game time
- */
- double GetFrameTime(void) const;
-
- /**
- * Returns the real (system) time
- */
- double GetRealTime(void) const;
-
- /**
- * Returns the difference between the local time of the scene (when it
- * was running and not suspended) and the "curtime"
- */
- static double GetSuspendedDelta();
-
- /**
- * Gets the number of logic updates per second.
- */
- static double GetTicRate();
- /**
- * Sets the number of logic updates per second.
- */
- static void SetTicRate(double ticrate);
- /**
- * Gets the maximum number of logic frame before render frame
- */
- static int GetMaxLogicFrame();
- /**
- * Sets the maximum number of logic frame before render frame
- */
- static void SetMaxLogicFrame(int frame);
- /**
- * Gets the maximum number of physics frame before render frame
- */
- static int GetMaxPhysicsFrame();
- /**
- * Sets the maximum number of physics frame before render frame
- */
- static void SetMaxPhysicsFrame(int frame);
-
- /**
- * Gets whether or not to lock animation updates to the animframerate
- */
- static bool GetRestrictAnimationFPS();
-
- /**
- * Sets whether or not to lock animation updates to the animframerate
- */
- static void SetRestrictAnimationFPS(bool bRestrictAnimFPS);
-
- /**
- * Gets the framerate for playing animations. (actions and ipos)
- */
- static double GetAnimFrameRate();
- /**
- * Sets the framerate for playing animations. (actions and ipos)
- */
- static void SetAnimFrameRate(double framerate);
-
- /**
- * Gets the last estimated average framerate
- */
- static double GetAverageFrameRate();
-
- /**
- * Gets the time scale multiplier
- */
- double GetTimeScale() const;
-
- /**
- * Sets the time scale multiplier
- */
- void SetTimeScale(double scale);
-
- static void SetExitKey(short key);
-
- static short GetExitKey();
-
- /**
- * Activate or deactivates the render of the scene after the logic frame
- * \param render true (render) or false (do not render)
- */
- static void SetRender(bool render);
- /**
- * Get the current render flag value
- */
- static bool GetRender();
-
- /**
- * \Sets the display for frame rate on or off.
- */
- void SetShowFramerate(bool frameRate);
-
- /**
- * \Gets the display for frame rate on or off.
- */
- bool GetShowFramerate();
-
- /**
- * \Sets the display for individual components on or off.
- */
- void SetShowProfile(bool profile);
-
- /**
- * \Gets the display for individual components on or off.
- */
- bool GetShowProfile();
-
- /**
- * \Sets the display of scene object debug properties on or off.
- */
- void SetShowProperties(bool properties);
-
- /**
- * \Gets the display of scene object debug properties on or off.
- */
- bool GetShowProperties();
-
- /**
- * \Sets if the auto adding of scene object debug properties on or off.
- */
- bool GetAutoAddDebugProperties();
-
- /**
- * \Sets the auto adding of scene object debug properties on or off.
- */
- void SetAutoAddDebugProperties(bool add);
-
- /**
- * Activates or deactivates timing information display.
- * \param frameRate Display for frame rate on or off.
- * \param profile Display for individual components on or off.
- * \param properties Display of scene object debug properties on or off.
- */
- void SetTimingDisplay(bool frameRate, bool profile, bool properties);
-
- /**
- * Returns status of timing information display.
- * \param frameRate Display for frame rate on or off.
- * \param profile Display for individual components on or off.
- * \param properties Display of scene object debug properties on or off.
- */
- void GetTimingDisplay(bool& frameRate, bool& profile, bool& properties) const;
-
- /**
- * Sets cursor hiding on every frame.
- * \param hideCursor Turns hiding on or off.
- */
- void SetHideCursor(bool hideCursor);
-
- /**
- * Returns the current setting for cursor hiding.
- * \return The current setting for cursor hiding.
- */
- bool GetHideCursor(void) const;
-
- /**
- * Enables/disables the use of the framing bar color of the Blender file's scenes.
- * \param overrideFrameColor The new setting.
- */
- void SetUseOverrideFrameColor(bool overrideFrameColor);
-
- /**
- * Check if the frame color is being overridden.
- */
- bool GetUseOverrideFrameColor(void) const;
-
- /**
- * Set the color used for framing bar color instead of the one in the Blender file's scenes.
- * \param r Red component of the override color.
- * \param g Green component of the override color.
- * \param b Blue component of the override color.
- */
- void SetOverrideFrameColor(float r, float g, float b, float a);
-
- /**
- * Returns the color used for framing bar color instead of the one in the Blender file's scenes.
- * \param r Red component of the override color.
- * \param g Green component of the override color.
- * \param b Blue component of the override color.
- */
- void GetOverrideFrameColor(float& r, float& g, float& b, float& a) const;
-
- KX_Scene* CreateScene(const STR_String& scenename);
- KX_Scene* CreateScene(Scene *scene, bool libloading=false);
-
- GlobalSettings* GetGlobalSettings(void);
- void SetGlobalSettings(GlobalSettings* gs);
-
- /**
- * Invalidate all the camera matrices and handle other
- * needed changes when resized.
- * It's only called from Blenderplayer.
- */
- void Resize();
-
-protected:
- /**
- * Processes all scheduled scene activity.
- * At the end, if the scene lists have changed,
- * SceneListsChanged(void) is called.
- * \see SceneListsChanged(void).
- */
- void ProcessScheduledScenes(void);
-
- /**
- * This method is invoked when the scene lists have changed.
- */
-
- void RemoveScheduledScenes(void);
- void AddScheduledScenes(void);
- void ReplaceScheduledScenes(void);
- void PostProcessScene(class KX_Scene* scene);
-
- bool BeginFrame();
- void ClearFrame();
- void EndFrame();
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:KX_KetsjiEngine")
-#endif
-};
-
-#endif /* __KX_KETSJIENGINE_H__ */
diff --git a/source/gameengine/Ketsji/KX_Light.cpp b/source/gameengine/Ketsji/KX_Light.cpp
deleted file mode 100644
index fcdcdf4a02a..00000000000
--- a/source/gameengine/Ketsji/KX_Light.cpp
+++ /dev/null
@@ -1,479 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Ketsji/KX_Light.cpp
- * \ingroup ketsji
- */
-
-#ifdef _MSC_VER
-# pragma warning (disable:4786)
-#endif
-
-#include <stdio.h>
-#include "DNA_scene_types.h"
-
-#include "KX_Light.h"
-#include "KX_Camera.h"
-#include "RAS_IRasterizer.h"
-#include "RAS_ICanvas.h"
-#include "RAS_ILightObject.h"
-
-#include "KX_PyMath.h"
-
-#include "DNA_object_types.h"
-#include "DNA_lamp_types.h"
-
-#include "BKE_scene.h"
-#include "MEM_guardedalloc.h"
-
-#include "BLI_math.h"
-
-KX_LightObject::KX_LightObject(void* sgReplicationInfo,SG_Callbacks callbacks,
- RAS_IRasterizer* rasterizer,
- RAS_ILightObject* lightobj,
- bool glsl)
- : KX_GameObject(sgReplicationInfo,callbacks),
- m_rasterizer(rasterizer)
-{
- m_lightobj = lightobj;
- m_lightobj->m_scene = sgReplicationInfo;
- m_lightobj->m_light = this;
- m_rasterizer->AddLight(m_lightobj);
- m_lightobj->m_glsl = glsl;
- m_blenderscene = ((KX_Scene*)sgReplicationInfo)->GetBlenderScene();
-};
-
-
-KX_LightObject::~KX_LightObject()
-{
- if (m_lightobj) {
- m_rasterizer->RemoveLight(m_lightobj);
- delete(m_lightobj);
- }
-}
-
-
-CValue* KX_LightObject::GetReplica()
-{
-
- KX_LightObject* replica = new KX_LightObject(*this);
-
- replica->ProcessReplica();
-
- replica->m_lightobj = m_lightobj->Clone();
- replica->m_lightobj->m_light = replica;
- m_rasterizer->AddLight(replica->m_lightobj);
-
- return replica;
-}
-
-void KX_LightObject::UpdateScene(KX_Scene *kxscene)
-{
- m_lightobj->m_scene = (void*)kxscene;
- m_blenderscene = kxscene->GetBlenderScene();
-}
-
-void KX_LightObject::SetLayer(int layer)
-{
- KX_GameObject::SetLayer(layer);
- m_lightobj->m_layer = layer;
-}
-
-#ifdef WITH_PYTHON
-/* ------------------------------------------------------------------------- */
-/* Python Integration Hooks */
-/* ------------------------------------------------------------------------- */
-
-PyTypeObject KX_LightObject::Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "KX_LightObject",
- sizeof(PyObjectPlus_Proxy),
- 0,
- py_base_dealloc,
- 0,
- 0,
- 0,
- 0,
- py_base_repr,
- 0,
- &KX_GameObject::Sequence,
- &KX_GameObject::Mapping,
- 0,0,0,
- NULL,
- NULL,
- 0,
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
- 0,0,0,0,0,0,0,
- Methods,
- 0,
- 0,
- &KX_GameObject::Type,
- 0,0,0,0,0,0,
- py_base_new
-};
-
-PyMethodDef KX_LightObject::Methods[] = {
- {NULL,NULL} //Sentinel
-};
-
-PyAttributeDef KX_LightObject::Attributes[] = {
- KX_PYATTRIBUTE_RW_FUNCTION("layer", KX_LightObject, pyattr_get_layer, pyattr_set_layer),
- KX_PYATTRIBUTE_RW_FUNCTION("energy", KX_LightObject, pyattr_get_energy, pyattr_set_energy),
- KX_PYATTRIBUTE_RW_FUNCTION("distance", KX_LightObject, pyattr_get_distance, pyattr_set_distance),
- KX_PYATTRIBUTE_RW_FUNCTION("color", KX_LightObject, pyattr_get_color, pyattr_set_color),
- KX_PYATTRIBUTE_RW_FUNCTION("lin_attenuation", KX_LightObject, pyattr_get_lin_attenuation, pyattr_set_lin_attenuation),
- KX_PYATTRIBUTE_RW_FUNCTION("quad_attenuation", KX_LightObject, pyattr_get_quad_attenuation, pyattr_set_quad_attenuation),
- KX_PYATTRIBUTE_RW_FUNCTION("spotsize", KX_LightObject, pyattr_get_spotsize, pyattr_set_spotsize),
- KX_PYATTRIBUTE_RW_FUNCTION("spotblend", KX_LightObject, pyattr_get_spotblend, pyattr_set_spotblend),
- KX_PYATTRIBUTE_RO_FUNCTION("shadowClipStart", KX_LightObject, pyattr_get_shadow_clip_start),
- KX_PYATTRIBUTE_RO_FUNCTION("shadowClipEnd", KX_LightObject, pyattr_get_shadow_clip_end),
- KX_PYATTRIBUTE_RO_FUNCTION("shadowFrustumSize", KX_LightObject, pyattr_get_shadow_frustum_size),
- KX_PYATTRIBUTE_RO_FUNCTION("shadowBias", KX_LightObject, pyattr_get_shadow_bias),
- KX_PYATTRIBUTE_RO_FUNCTION("shadowBleedBias", KX_LightObject, pyattr_get_shadow_bleed_bias),
- KX_PYATTRIBUTE_RO_FUNCTION("shadowBindId", KX_LightObject, pyattr_get_shadow_bind_code),
- KX_PYATTRIBUTE_RO_FUNCTION("shadowMapType", KX_LightObject, pyattr_get_shadow_map_type),
- KX_PYATTRIBUTE_RO_FUNCTION("shadowColor", KX_LightObject, pyattr_get_shadow_color),
- KX_PYATTRIBUTE_RO_FUNCTION("useShadow", KX_LightObject, pyattr_get_shadow_active),
- KX_PYATTRIBUTE_RO_FUNCTION("shadowMatrix", KX_LightObject, pyattr_get_shadow_matrix),
- KX_PYATTRIBUTE_RO_FUNCTION("SPOT", KX_LightObject, pyattr_get_typeconst),
- KX_PYATTRIBUTE_RO_FUNCTION("SUN", KX_LightObject, pyattr_get_typeconst),
- KX_PYATTRIBUTE_RO_FUNCTION("NORMAL", KX_LightObject, pyattr_get_typeconst),
- KX_PYATTRIBUTE_RW_FUNCTION("type", KX_LightObject, pyattr_get_type, pyattr_set_type),
- { NULL } //Sentinel
-};
-
-PyObject *KX_LightObject::pyattr_get_layer(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_LightObject *self = static_cast<KX_LightObject *>(self_v);
- return PyLong_FromLong(self->m_lightobj->m_layer);
-}
-
-int KX_LightObject::pyattr_set_layer(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_LightObject *self = static_cast<KX_LightObject *>(self_v);
- int layer = PyLong_AsLong(value);
-
- if (layer == -1 && PyErr_Occurred()) {
- PyErr_Format(PyExc_TypeError, "expected an integer for attribute \"%s\"", attrdef->m_name);
- return PY_SET_ATTR_FAIL;
- }
-
- if (layer < 1) {
- PyErr_Format(PyExc_TypeError, "expected an integer greater than 1 for attribute \"%s\"", attrdef->m_name);
- return PY_SET_ATTR_FAIL;
- }
- else if (layer > MAX_LIGHT_LAYERS) {
- PyErr_Format(PyExc_TypeError, "expected an integer less than %i for attribute \"%s\"", MAX_LIGHT_LAYERS, attrdef->m_name);
- return PY_SET_ATTR_FAIL;
- }
-
- self->SetLayer(layer);
- return PY_SET_ATTR_SUCCESS;
-}
-
-PyObject *KX_LightObject::pyattr_get_energy(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_LightObject* self = static_cast<KX_LightObject*>(self_v);
- return PyFloat_FromDouble(self->m_lightobj->m_energy);
-}
-
-int KX_LightObject::pyattr_set_energy(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_LightObject* self = static_cast<KX_LightObject*>(self_v);
-
- if (PyFloat_Check(value)) {
- float val = PyFloat_AsDouble(value);
- if (val < 0)
- val = 0;
- else if (val > 10)
- val = 10;
-
- self->m_lightobj->m_energy = val;
- return PY_SET_ATTR_SUCCESS;
- }
-
- PyErr_Format(PyExc_TypeError, "expected float value for attribute \"%s\"", attrdef->m_name);
- return PY_SET_ATTR_FAIL;
-}
-
-PyObject *KX_LightObject::pyattr_get_shadow_clip_start(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_LightObject *self = static_cast<KX_LightObject *>(self_v);
- return PyFloat_FromDouble(self->m_lightobj->m_shadowclipstart);
-}
-
-PyObject *KX_LightObject::pyattr_get_shadow_clip_end(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_LightObject *self = static_cast<KX_LightObject *>(self_v);
- return PyFloat_FromDouble(self->m_lightobj->m_shadowclipend);
-}
-
-PyObject *KX_LightObject::pyattr_get_shadow_frustum_size(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_LightObject *self = static_cast<KX_LightObject *>(self_v);
- return PyFloat_FromDouble(self->m_lightobj->m_shadowfrustumsize);
-}
-
-PyObject *KX_LightObject::pyattr_get_shadow_bind_code(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_LightObject *self = static_cast<KX_LightObject *>(self_v);
- return PyLong_FromLong(self->m_lightobj->GetShadowBindCode());
-}
-
-PyObject *KX_LightObject::pyattr_get_shadow_bias(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_LightObject *self = static_cast<KX_LightObject *>(self_v);
- return PyFloat_FromDouble(self->m_lightobj->m_shadowbias);
-}
-
-PyObject *KX_LightObject::pyattr_get_shadow_bleed_bias(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_LightObject *self = static_cast<KX_LightObject *>(self_v);
- return PyFloat_FromDouble(self->m_lightobj->m_shadowbleedbias);
-}
-
-PyObject *KX_LightObject::pyattr_get_shadow_map_type(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_LightObject *self = static_cast<KX_LightObject *>(self_v);
- return PyLong_FromLong(self->m_lightobj->m_shadowmaptype);
-}
-
-PyObject *KX_LightObject::pyattr_get_shadow_matrix(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_LightObject *self = static_cast<KX_LightObject *>(self_v);
- return PyObjectFrom(self->m_lightobj->GetShadowMatrix());
-}
-
-PyObject *KX_LightObject::pyattr_get_shadow_color(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_LightObject *self = static_cast<KX_LightObject *>(self_v);
- return PyColorFromVector(MT_Vector3(self->m_lightobj->m_shadowcolor));
-}
-
-PyObject *KX_LightObject::pyattr_get_shadow_active(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_LightObject *self = static_cast<KX_LightObject *>(self_v);
- return PyBool_FromLong(self->m_lightobj->HasShadowBuffer());
-}
-
-PyObject *KX_LightObject::pyattr_get_distance(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_LightObject* self = static_cast<KX_LightObject*>(self_v);
- return PyFloat_FromDouble(self->m_lightobj->m_distance);
-}
-
-int KX_LightObject::pyattr_set_distance(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_LightObject* self = static_cast<KX_LightObject*>(self_v);
-
- if (PyFloat_Check(value)) {
- float val = PyFloat_AsDouble(value);
- if (val < 0.01f)
- val = 0.01f;
- else if (val > 5000.f)
- val = 5000.f;
-
- self->m_lightobj->m_distance = val;
- return PY_SET_ATTR_SUCCESS;
- }
-
- PyErr_Format(PyExc_TypeError, "expected float value for attribute \"%s\"", attrdef->m_name);
- return PY_SET_ATTR_FAIL;
-}
-
-PyObject *KX_LightObject::pyattr_get_color(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_LightObject* self = static_cast<KX_LightObject*>(self_v);
- return Py_BuildValue("[fff]", self->m_lightobj->m_color[0], self->m_lightobj->m_color[1], self->m_lightobj->m_color[2]);
-}
-
-int KX_LightObject::pyattr_set_color(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_LightObject* self = static_cast<KX_LightObject*>(self_v);
-
- MT_Vector3 color;
- if (PyVecTo(value, color))
- {
- self->m_lightobj->m_color[0] = color[0];
- self->m_lightobj->m_color[1] = color[1];
- self->m_lightobj->m_color[2] = color[2];
- return PY_SET_ATTR_SUCCESS;
- }
- return PY_SET_ATTR_FAIL;
-}
-
-PyObject *KX_LightObject::pyattr_get_lin_attenuation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_LightObject* self = static_cast<KX_LightObject*>(self_v);
- return PyFloat_FromDouble(self->m_lightobj->m_att1);
-}
-
-int KX_LightObject::pyattr_set_lin_attenuation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_LightObject* self = static_cast<KX_LightObject*>(self_v);
-
- if (PyFloat_Check(value)) {
- float val = PyFloat_AsDouble(value);
- if (val < 0.f)
- val = 0.f;
- else if (val > 1.f)
- val = 1.f;
-
- self->m_lightobj->m_att1 = val;
- return PY_SET_ATTR_SUCCESS;
- }
-
- PyErr_Format(PyExc_TypeError, "expected float value for attribute \"%s\"", attrdef->m_name);
- return PY_SET_ATTR_FAIL;
-}
-
-PyObject *KX_LightObject::pyattr_get_quad_attenuation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_LightObject* self = static_cast<KX_LightObject*>(self_v);
- return PyFloat_FromDouble(self->m_lightobj->m_att2);
-}
-
-int KX_LightObject::pyattr_set_quad_attenuation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_LightObject* self = static_cast<KX_LightObject*>(self_v);
-
- if (PyFloat_Check(value)) {
- float val = PyFloat_AsDouble(value);
- if (val < 0.f)
- val = 0.f;
- else if (val > 1.f)
- val = 1.f;
-
- self->m_lightobj->m_att2 = val;
- return PY_SET_ATTR_SUCCESS;
- }
-
- PyErr_Format(PyExc_TypeError, "expected float value for attribute \"%s\"", attrdef->m_name);
- return PY_SET_ATTR_FAIL;
-}
-
-PyObject *KX_LightObject::pyattr_get_spotsize(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_LightObject* self = static_cast<KX_LightObject*>(self_v);
- return PyFloat_FromDouble(RAD2DEG(self->m_lightobj->m_spotsize));
-}
-
-int KX_LightObject::pyattr_set_spotsize(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_LightObject* self = static_cast<KX_LightObject*>(self_v);
-
- if (PyFloat_Check(value)) {
- double val = PyFloat_AsDouble(value);
- if (val < 0.0)
- val = 0.0;
- else if (val > 180.0)
- val = 180.0;
-
- self->m_lightobj->m_spotsize = (float)DEG2RAD(val);
- return PY_SET_ATTR_SUCCESS;
- }
-
- PyErr_Format(PyExc_TypeError, "expected float value for attribute \"%s\"", attrdef->m_name);
- return PY_SET_ATTR_FAIL;
-}
-PyObject *KX_LightObject::pyattr_get_spotblend(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_LightObject* self = static_cast<KX_LightObject*>(self_v);
- return PyFloat_FromDouble(self->m_lightobj->m_spotblend);
-}
-
-int KX_LightObject::pyattr_set_spotblend(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_LightObject* self = static_cast<KX_LightObject*>(self_v);
-
- if (PyFloat_Check(value)) {
- float val = (float)PyFloat_AsDouble(value);
- if (val < 0.f)
- val = 0.f;
- else if (val > 1.f)
- val = 1.f;
-
- self->m_lightobj->m_spotblend = val;
- return PY_SET_ATTR_SUCCESS;
- }
-
- PyErr_Format(PyExc_TypeError, "expected float value for attribute \"%s\"", attrdef->m_name);
- return PY_SET_ATTR_FAIL;
-}
-
-PyObject *KX_LightObject::pyattr_get_typeconst(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- PyObject *retvalue;
-
- const char* type = attrdef->m_name;
-
- if (!strcmp(type, "SPOT")) {
- retvalue = PyLong_FromLong(RAS_ILightObject::LIGHT_SPOT);
- } else if (!strcmp(type, "SUN")) {
- retvalue = PyLong_FromLong(RAS_ILightObject::LIGHT_SUN);
- } else if (!strcmp(type, "NORMAL")) {
- retvalue = PyLong_FromLong(RAS_ILightObject::LIGHT_NORMAL);
- }
- else {
- /* should never happen */
- PyErr_SetString(PyExc_TypeError, "light.type: internal error, invalid light type");
- retvalue = NULL;
- }
-
- return retvalue;
-}
-
-PyObject *KX_LightObject::pyattr_get_type(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_LightObject* self = static_cast<KX_LightObject*>(self_v);
- return PyLong_FromLong(self->m_lightobj->m_type);
-}
-
-int KX_LightObject::pyattr_set_type(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_LightObject* self = static_cast<KX_LightObject*>(self_v);
- const int val = PyLong_AsLong(value);
- if ((val==-1 && PyErr_Occurred()) || val<0 || val>2) {
- PyErr_SetString(PyExc_ValueError, "light.type= val: KX_LightObject, expected an int between 0 and 2");
- return PY_SET_ATTR_FAIL;
- }
-
- switch (val) {
- case 0:
- self->m_lightobj->m_type = self->m_lightobj->LIGHT_SPOT;
- break;
- case 1:
- self->m_lightobj->m_type = self->m_lightobj->LIGHT_SUN;
- break;
- case 2:
- self->m_lightobj->m_type = self->m_lightobj->LIGHT_NORMAL;
- break;
- }
-
- return PY_SET_ATTR_SUCCESS;
-}
-#endif // WITH_PYTHON
diff --git a/source/gameengine/Ketsji/KX_Light.h b/source/gameengine/Ketsji/KX_Light.h
deleted file mode 100644
index b354fca4d41..00000000000
--- a/source/gameengine/Ketsji/KX_Light.h
+++ /dev/null
@@ -1,100 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file KX_Light.h
- * \ingroup ketsji
- */
-
-#ifndef __KX_LIGHT_H__
-#define __KX_LIGHT_H__
-
-#include "KX_GameObject.h"
-
-#define MAX_LIGHT_LAYERS ((1 << 20) - 1)
-
-struct GPULamp;
-struct Scene;
-struct Base;
-class KX_Camera;
-class RAS_IRasterizer;
-class RAS_ILightObject;
-class MT_Transform;
-
-class KX_LightObject : public KX_GameObject
-{
- Py_Header
-protected:
- RAS_ILightObject* m_lightobj;
- class RAS_IRasterizer* m_rasterizer; //needed for registering and replication of lightobj
- Scene* m_blenderscene;
-
-public:
- KX_LightObject(void* sgReplicationInfo,SG_Callbacks callbacks,RAS_IRasterizer* rasterizer,RAS_ILightObject* lightobj, bool glsl);
- virtual ~KX_LightObject();
- virtual CValue* GetReplica();
- RAS_ILightObject* GetLightData() { return m_lightobj;}
-
- void UpdateScene(class KX_Scene *kxscene);
- virtual void SetLayer(int layer);
-
- virtual int GetGameObjectType() { return OBJ_LIGHT; }
-
-#ifdef WITH_PYTHON
- /* attributes */
- static PyObject* pyattr_get_layer(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_layer(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static PyObject* pyattr_get_energy(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_energy(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static PyObject *pyattr_get_shadow_clip_start(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject *pyattr_get_shadow_clip_end(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject *pyattr_get_shadow_frustum_size(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject *pyattr_get_shadow_bind_code(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject *pyattr_get_shadow_bias(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject *pyattr_get_shadow_bleed_bias(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject *pyattr_get_shadow_map_type(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject *pyattr_get_shadow_color(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject *pyattr_get_shadow_active(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject *pyattr_get_shadow_matrix(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_distance(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_distance(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static PyObject* pyattr_get_color(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_color(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static PyObject* pyattr_get_lin_attenuation(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_lin_attenuation(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static PyObject* pyattr_get_quad_attenuation(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_quad_attenuation(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static PyObject* pyattr_get_spotsize(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_spotsize(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static PyObject* pyattr_get_spotblend(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_spotblend(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static PyObject* pyattr_get_typeconst(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_type(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_type(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
-#endif
-};
-
-#endif /* __KX_LIGHT_H__ */
diff --git a/source/gameengine/Ketsji/KX_LightIpoSGController.cpp b/source/gameengine/Ketsji/KX_LightIpoSGController.cpp
deleted file mode 100644
index 6b641f7a63f..00000000000
--- a/source/gameengine/Ketsji/KX_LightIpoSGController.cpp
+++ /dev/null
@@ -1,122 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Ketsji/KX_LightIpoSGController.cpp
- * \ingroup ketsji
- */
-
-
-#include "KX_LightIpoSGController.h"
-#include "KX_ScalarInterpolator.h"
-#include "KX_Light.h"
-#include "RAS_ILightObject.h"
-
-#if defined(_WIN64)
-typedef unsigned __int64 uint_ptr;
-#else
-typedef unsigned long uint_ptr;
-#endif
-
-bool KX_LightIpoSGController::Update(double currentTime)
-{
- if (m_modified)
- {
- T_InterpolatorList::iterator i;
- for (i = m_interpolators.begin(); !(i == m_interpolators.end()); ++i) {
- (*i)->Execute(m_ipotime);//currentTime);
- }
-
- RAS_ILightObject *lightobj;
-
- SG_Spatial* ob = (SG_Spatial*)m_pObject;
- KX_LightObject* kxlight = (KX_LightObject*) ob->GetSGClientObject();
- lightobj = kxlight->GetLightData();
- //lightobj = (KX_Light*)
-
- if (m_modify_energy) {
- lightobj->m_energy = m_energy;
- }
-
- if (m_modify_color) {
- lightobj->m_color[0] = m_col_rgb[0];
- lightobj->m_color[1] = m_col_rgb[1];
- lightobj->m_color[2] = m_col_rgb[2];
- }
-
- if (m_modify_dist) {
- lightobj->m_distance = m_dist;
- }
-
- m_modified=false;
- }
- return false;
-}
-
-
-void KX_LightIpoSGController::AddInterpolator(KX_IInterpolator* interp)
-{
- this->m_interpolators.push_back(interp);
-}
-
-SG_Controller* KX_LightIpoSGController::GetReplica(class SG_Node* destnode)
-{
- KX_LightIpoSGController* iporeplica = new KX_LightIpoSGController(*this);
- // clear object that ipo acts on
- iporeplica->ClearObject();
-
- // dirty hack, ask Gino for a better solution in the ipo implementation
- // hacken en zagen, in what we call datahiding, not written for replication :(
-
- T_InterpolatorList oldlist = m_interpolators;
- iporeplica->m_interpolators.clear();
-
- T_InterpolatorList::iterator i;
- for (i = oldlist.begin(); !(i == oldlist.end()); ++i) {
- KX_ScalarInterpolator* copyipo = new KX_ScalarInterpolator(*((KX_ScalarInterpolator*)*i));
- iporeplica->AddInterpolator(copyipo);
-
- MT_Scalar* scaal = ((KX_ScalarInterpolator*)*i)->GetTarget();
- uint_ptr orgbase = (uint_ptr)this;
- uint_ptr orgloc = (uint_ptr)scaal;
- uint_ptr offset = orgloc-orgbase;
- uint_ptr newaddrbase = (uint_ptr)iporeplica + offset;
- MT_Scalar* blaptr = (MT_Scalar*) newaddrbase;
- copyipo->SetNewTarget((MT_Scalar*)blaptr);
- }
-
- return iporeplica;
-}
-
-KX_LightIpoSGController::~KX_LightIpoSGController()
-{
-
- T_InterpolatorList::iterator i;
- for (i = m_interpolators.begin(); !(i == m_interpolators.end()); ++i) {
- delete (*i);
- }
-
-}
diff --git a/source/gameengine/Ketsji/KX_LightIpoSGController.h b/source/gameengine/Ketsji/KX_LightIpoSGController.h
deleted file mode 100644
index 151ced6b8f8..00000000000
--- a/source/gameengine/Ketsji/KX_LightIpoSGController.h
+++ /dev/null
@@ -1,105 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file KX_LightIpoSGController.h
- * \ingroup ketsji
- */
-
-#ifndef __KX_LIGHTIPOSGCONTROLLER_H__
-#define __KX_LIGHTIPOSGCONTROLLER_H__
-
-#include "SG_Controller.h"
-#include "SG_Spatial.h"
-
-#include "KX_IInterpolator.h"
-
-class RAS_ILightObject;
-
-class KX_LightIpoSGController : public SG_Controller
-{
-public:
- MT_Scalar m_energy;
- MT_Scalar m_col_rgb[3];
- MT_Scalar m_dist;
-
-private:
- T_InterpolatorList m_interpolators;
- unsigned short m_modify_energy : 1;
- unsigned short m_modify_color : 1;
- unsigned short m_modify_dist : 1;
- bool m_modified;
-
- double m_ipotime;
-public:
- KX_LightIpoSGController() :
- m_modify_energy(false),
- m_modify_color(false),
- m_modify_dist(false),
- m_modified(true),
- m_ipotime(0.0)
- {}
-
- virtual ~KX_LightIpoSGController();
-
- virtual SG_Controller* GetReplica(class SG_Node* destnode);
-
- virtual bool Update(double time);
-
- virtual void SetSimulatedTime(double time) {
- m_ipotime = time;
- m_modified = true;
- }
-
- void SetModifyEnergy(bool modify) {
- m_modify_energy = modify;
- }
-
- void SetModifyColor(bool modify) {
- m_modify_color = modify;
- }
-
- void SetModifyDist(bool modify) {
- m_modify_dist = modify;
- }
-
- void
- SetOption(
- int option,
- int value
- ) {
- // intentionally empty
- };
-
- void AddInterpolator(KX_IInterpolator* interp);
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:KX_LightIpoSGController")
-#endif
-};
-
-#endif /* __KX_LIGHTIPOSGCONTROLLER_H__ */
diff --git a/source/gameengine/Ketsji/KX_MaterialIpoController.cpp b/source/gameengine/Ketsji/KX_MaterialIpoController.cpp
deleted file mode 100644
index 1faf8f17d54..00000000000
--- a/source/gameengine/Ketsji/KX_MaterialIpoController.cpp
+++ /dev/null
@@ -1,105 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Ketsji/KX_MaterialIpoController.cpp
- * \ingroup ketsji
- */
-
-#include "KX_MaterialIpoController.h"
-#include "KX_ScalarInterpolator.h"
-#include "KX_GameObject.h"
-
-#include "BLI_sys_types.h" // for intptr_t support
-
-bool KX_MaterialIpoController::Update(double currentTime)
-{
- if (m_modified)
- {
- T_InterpolatorList::iterator i;
- for (i = m_interpolators.begin(); !(i == m_interpolators.end()); ++i) {
- (*i)->Execute(m_ipotime);
- }
-
-
- SG_Spatial* ob = (SG_Spatial*)m_pObject;
- KX_GameObject* kxgameobj= (KX_GameObject*) ob->GetSGClientObject();
-
- //kxgameobj->SetObjectColor(m_rgba);
- kxgameobj->UpdateMaterialData(
- m_matname_hash,
- m_rgba,
- m_specrgb,
- m_hard,
- m_spec,
- m_ref,
- m_emit,
- m_alpha
- );
-
- m_modified=false;
- }
- return false;
-}
-
-
-void KX_MaterialIpoController::AddInterpolator(KX_IInterpolator* interp)
-{
- this->m_interpolators.push_back(interp);
-}
-
-SG_Controller* KX_MaterialIpoController::GetReplica(class SG_Node* destnode)
-{
- KX_MaterialIpoController* iporeplica = new KX_MaterialIpoController(*this);
- // clear object that ipo acts on
- iporeplica->ClearObject();
-
- // dirty hack, ask Gino for a better solution in the ipo implementation
- // hacken en zagen, in what we call datahiding, not written for replication :(
-
- T_InterpolatorList oldlist = m_interpolators;
- iporeplica->m_interpolators.clear();
-
- T_InterpolatorList::iterator i;
- for (i = oldlist.begin(); !(i == oldlist.end()); ++i) {
- KX_ScalarInterpolator* copyipo = new KX_ScalarInterpolator(*((KX_ScalarInterpolator*)*i));
- iporeplica->AddInterpolator(copyipo);
-
- MT_Scalar* scaal = ((KX_ScalarInterpolator*)*i)->GetTarget();
- intptr_t orgbase = (intptr_t)this;
- intptr_t orgloc = (intptr_t)scaal;
- intptr_t offset = orgloc-orgbase;
- intptr_t newaddrbase = (intptr_t)iporeplica + offset;
- MT_Scalar* blaptr = (MT_Scalar*) newaddrbase;
- copyipo->SetNewTarget((MT_Scalar*)blaptr);
- }
-
- return iporeplica;
-}
-
-KX_MaterialIpoController::~KX_MaterialIpoController()
-{
-
- T_InterpolatorList::iterator i;
- for (i = m_interpolators.begin(); !(i == m_interpolators.end()); ++i) {
- delete (*i);
- }
-
-}
-
diff --git a/source/gameengine/Ketsji/KX_MaterialIpoController.h b/source/gameengine/Ketsji/KX_MaterialIpoController.h
deleted file mode 100644
index a7e9c2cc1c5..00000000000
--- a/source/gameengine/Ketsji/KX_MaterialIpoController.h
+++ /dev/null
@@ -1,65 +0,0 @@
-
-/** \file KX_MaterialIpoController.h
- * \ingroup ketsji
- */
-
-#ifndef __KX_MATERIALIPOCONTROLLER_H__
-#define __KX_MATERIALIPOCONTROLLER_H__
-
-
-
-#include "SG_Controller.h"
-#include "SG_Spatial.h"
-#include "KX_IInterpolator.h"
-
-#include "STR_String.h" //typedef dword
-
-class KX_MaterialIpoController : public SG_Controller
-{
-public:
- MT_Vector4 m_rgba;
- MT_Vector3 m_specrgb;
- MT_Scalar m_hard;
- MT_Scalar m_spec;
- MT_Scalar m_ref;
- MT_Scalar m_emit;
- MT_Scalar m_alpha;
-
-private:
- T_InterpolatorList m_interpolators;
- bool m_modified;
-
- double m_ipotime;
- dword m_matname_hash;
-public:
- KX_MaterialIpoController(dword matname_hash) :
- m_modified(true),
- m_ipotime(0.0),
- m_matname_hash(matname_hash)
- {}
- virtual ~KX_MaterialIpoController();
- virtual SG_Controller* GetReplica(class SG_Node* destnode);
- virtual bool Update(double time);
- virtual void SetSimulatedTime(double time) {
- m_ipotime = time;
- m_modified = true;
- }
-
- void
- SetOption(
- int option,
- int value
- ) {
- // intentionally empty
- };
-
-
- void AddInterpolator(KX_IInterpolator* interp);
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:KX_MaterialIpoController")
-#endif
-};
-
-#endif /* __KX_MATERIALIPOCONTROLLER_H__ */
diff --git a/source/gameengine/Ketsji/KX_MeshProxy.cpp b/source/gameengine/Ketsji/KX_MeshProxy.cpp
deleted file mode 100644
index 8da3542b4d6..00000000000
--- a/source/gameengine/Ketsji/KX_MeshProxy.cpp
+++ /dev/null
@@ -1,464 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Ketsji/KX_MeshProxy.cpp
- * \ingroup ketsji
- */
-
-
-#ifdef WITH_PYTHON
-
-#include "KX_MeshProxy.h"
-#include "RAS_IPolygonMaterial.h"
-#include "RAS_MeshObject.h"
-
-#include "KX_VertexProxy.h"
-#include "KX_PolyProxy.h"
-
-#include "KX_BlenderMaterial.h"
-
-#include "KX_PyMath.h"
-
-#include "SCA_LogicManager.h"
-
-#include "EXP_PyObjectPlus.h"
-
-PyTypeObject KX_MeshProxy::Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "KX_MeshProxy",
- sizeof(PyObjectPlus_Proxy),
- 0,
- py_base_dealloc,
- 0,
- 0,
- 0,
- 0,
- py_base_repr,
- 0,0,0,0,0,0,0,0,0,
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
- 0,0,0,0,0,0,0,
- Methods,
- 0,
- 0,
- &CValue::Type,
- 0,0,0,0,0,0,
- py_base_new
-};
-
-PyMethodDef KX_MeshProxy::Methods[] = {
- {"getMaterialName", (PyCFunction)KX_MeshProxy::sPyGetMaterialName,METH_VARARGS},
- {"getTextureName", (PyCFunction)KX_MeshProxy::sPyGetTextureName,METH_VARARGS},
- {"getVertexArrayLength", (PyCFunction)KX_MeshProxy::sPyGetVertexArrayLength,METH_VARARGS},
- {"getVertex", (PyCFunction)KX_MeshProxy::sPyGetVertex,METH_VARARGS},
- {"getPolygon", (PyCFunction)KX_MeshProxy::sPyGetPolygon,METH_VARARGS},
- {"transform", (PyCFunction)KX_MeshProxy::sPyTransform,METH_VARARGS},
- {"transformUV", (PyCFunction)KX_MeshProxy::sPyTransformUV,METH_VARARGS},
- //{"getIndexArrayLength", (PyCFunction)KX_MeshProxy::sPyGetIndexArrayLength,METH_VARARGS},
- {NULL,NULL} //Sentinel
-};
-
-PyAttributeDef KX_MeshProxy::Attributes[] = {
- KX_PYATTRIBUTE_RO_FUNCTION("materials", KX_MeshProxy, pyattr_get_materials),
- KX_PYATTRIBUTE_RO_FUNCTION("numPolygons", KX_MeshProxy, pyattr_get_numPolygons),
- KX_PYATTRIBUTE_RO_FUNCTION("numMaterials", KX_MeshProxy, pyattr_get_numMaterials),
-
- { NULL } //Sentinel
-};
-
-void KX_MeshProxy::SetMeshModified(bool v)
-{
- m_meshobj->SetMeshModified(v);
-}
-
-KX_MeshProxy::KX_MeshProxy(RAS_MeshObject* mesh)
- : CValue(), m_meshobj(mesh)
-{
-}
-
-KX_MeshProxy::~KX_MeshProxy()
-{
-}
-
-
-
-// stuff for cvalue related things
-CValue* KX_MeshProxy::Calc(VALUE_OPERATOR op, CValue *val) { return NULL;}
-CValue* KX_MeshProxy::CalcFinal(VALUE_DATA_TYPE dtype, VALUE_OPERATOR op, CValue *val) { return NULL;}
-
-const STR_String & KX_MeshProxy::GetText() {return m_meshobj->GetName();};
-double KX_MeshProxy::GetNumber() { return -1;}
-STR_String& KX_MeshProxy::GetName() { return m_meshobj->GetName();}
-void KX_MeshProxy::SetName(const char *name) { };
-CValue* KX_MeshProxy::GetReplica() { return NULL;}
-
-
-// stuff for python integration
-
-PyObject *KX_MeshProxy::PyGetMaterialName(PyObject *args, PyObject *kwds)
-{
- int matid= 1;
- STR_String matname;
-
- if (PyArg_ParseTuple(args,"i:getMaterialName",&matid))
- {
- matname = m_meshobj->GetMaterialName(matid);
- }
- else {
- return NULL;
- }
-
- return PyUnicode_From_STR_String(matname);
-
-}
-
-
-PyObject *KX_MeshProxy::PyGetTextureName(PyObject *args, PyObject *kwds)
-{
- int matid= 1;
- STR_String matname;
-
- if (PyArg_ParseTuple(args,"i:getTextureName",&matid))
- {
- matname = m_meshobj->GetTextureName(matid);
- }
- else {
- return NULL;
- }
-
- return PyUnicode_From_STR_String(matname);
-
-}
-
-PyObject *KX_MeshProxy::PyGetVertexArrayLength(PyObject *args, PyObject *kwds)
-{
- int matid= 0;
- int length = 0;
-
-
- if (!PyArg_ParseTuple(args,"i:getVertexArrayLength",&matid))
- return NULL;
-
-
- RAS_MeshMaterial *mmat = m_meshobj->GetMeshMaterial(matid); /* can be NULL*/
-
- if (mmat)
- {
- RAS_IPolyMaterial* mat = mmat->m_bucket->GetPolyMaterial();
- if (mat)
- length = m_meshobj->NumVertices(mat);
- }
-
- return PyLong_FromLong(length);
-}
-
-
-PyObject *KX_MeshProxy::PyGetVertex(PyObject *args, PyObject *kwds)
-{
- int vertexindex;
- int matindex;
-
- if (!PyArg_ParseTuple(args,"ii:getVertex",&matindex,&vertexindex))
- return NULL;
-
- RAS_TexVert* vertex = m_meshobj->GetVertex(matindex,vertexindex);
-
- if (vertex==NULL) {
- PyErr_SetString(PyExc_ValueError, "mesh.getVertex(mat_idx, vert_idx): KX_MeshProxy, could not get a vertex at the given indices");
- return NULL;
- }
-
- return (new KX_VertexProxy(this, vertex))->NewProxy(true);
-}
-
-PyObject *KX_MeshProxy::PyGetPolygon(PyObject *args, PyObject *kwds)
-{
- int polyindex= 1;
- PyObject *polyob = NULL;
-
- if (!PyArg_ParseTuple(args,"i:getPolygon",&polyindex))
- return NULL;
-
- if (polyindex<0 || polyindex >= m_meshobj->NumPolygons())
- {
- PyErr_SetString(PyExc_AttributeError, "mesh.getPolygon(int): KX_MeshProxy, invalid polygon index");
- return NULL;
- }
-
-
- RAS_Polygon* polygon = m_meshobj->GetPolygon(polyindex);
- if (polygon)
- {
- polyob = (new KX_PolyProxy(m_meshobj, polygon))->NewProxy(true);
- }
- else {
- PyErr_SetString(PyExc_AttributeError, "mesh.getPolygon(int): KX_MeshProxy, polygon is NULL, unknown reason");
- }
- return polyob;
-}
-
-PyObject *KX_MeshProxy::PyTransform(PyObject *args, PyObject *kwds)
-{
- int matindex;
- PyObject *pymat;
- bool ok = false;
-
- MT_Matrix4x4 transform;
-
- if (!PyArg_ParseTuple(args,"iO:transform", &matindex, &pymat) ||
- !PyMatTo(pymat, transform))
- {
- return NULL;
- }
-
- MT_Matrix4x4 ntransform = transform.inverse().transposed();
- ntransform[0][3] = ntransform[1][3] = ntransform[2][3] = 0.0f;
-
- /* transform mesh verts */
- unsigned int mit_index = 0;
- for (list<RAS_MeshMaterial>::iterator mit = m_meshobj->GetFirstMaterial();
- (mit != m_meshobj->GetLastMaterial());
- ++mit, ++mit_index)
- {
- if (matindex == -1) {
- /* always transform */
- }
- else if (matindex == mit_index) {
- /* we found the right index! */
- }
- else {
- continue;
- }
-
- RAS_MeshSlot *slot = mit->m_baseslot;
- RAS_MeshSlot::iterator it;
- ok = true;
-
- for (slot->begin(it); !slot->end(it); slot->next(it)) {
- size_t i;
- for (i = it.startvertex; i < it.endvertex; i++) {
- RAS_TexVert *vert = &it.vertex[i];
- vert->Transform(transform, ntransform);
- }
- }
-
- /* if we set a material index, quit when done */
- if (matindex == mit_index) {
- break;
- }
- }
-
- if (ok == false) {
- PyErr_Format(PyExc_ValueError,
- "mesh.transform(...): invalid material index %d", matindex);
- return NULL;
- }
-
- m_meshobj->SetMeshModified(true);
-
- Py_RETURN_NONE;
-}
-
-PyObject *KX_MeshProxy::PyTransformUV(PyObject *args, PyObject *kwds)
-{
- int matindex;
- PyObject *pymat;
- int uvindex = -1;
- int uvindex_from = -1;
- bool ok = false;
-
- MT_Matrix4x4 transform;
-
- if (!PyArg_ParseTuple(args,"iO|iii:transformUV", &matindex, &pymat, &uvindex, &uvindex_from) ||
- !PyMatTo(pymat, transform))
- {
- return NULL;
- }
-
- if (uvindex < -1 || uvindex > 1) {
- PyErr_Format(PyExc_ValueError,
- "mesh.transformUV(...): invalid uv_index %d", uvindex);
- return NULL;
- }
- if (uvindex_from < -1 || uvindex_from > 1) {
- PyErr_Format(PyExc_ValueError,
- "mesh.transformUV(...): invalid uv_index_from %d", uvindex);
- return NULL;
- }
- if (uvindex_from == uvindex) {
- uvindex_from = -1;
- }
-
- /* transform mesh verts */
- unsigned int mit_index = 0;
- for (list<RAS_MeshMaterial>::iterator mit = m_meshobj->GetFirstMaterial();
- (mit != m_meshobj->GetLastMaterial());
- ++mit, ++mit_index)
- {
- if (matindex == -1) {
- /* always transform */
- }
- else if (matindex == mit_index) {
- /* we found the right index! */
- }
- else {
- continue;
- }
-
- RAS_MeshSlot *slot = mit->m_baseslot;
- RAS_MeshSlot::iterator it;
- ok = true;
-
- for (slot->begin(it); !slot->end(it); slot->next(it)) {
- size_t i;
-
- for (i = it.startvertex; i < it.endvertex; i++) {
- RAS_TexVert *vert = &it.vertex[i];
- if (uvindex_from != -1) {
- if (uvindex_from == 0) vert->SetUV(1, vert->getUV(0));
- else vert->SetUV(0, vert->getUV(1));
- }
-
- switch (uvindex) {
- case 0:
- vert->TransformUV(0, transform);
- break;
- case 1:
- vert->TransformUV(1, transform);
- break;
- case -1:
- vert->TransformUV(0, transform);
- vert->TransformUV(1, transform);
- break;
- }
- }
- }
-
- /* if we set a material index, quit when done */
- if (matindex == mit_index) {
- break;
- }
- }
-
- if (ok == false) {
- PyErr_Format(PyExc_ValueError,
- "mesh.transformUV(...): invalid material index %d", matindex);
- return NULL;
- }
-
- m_meshobj->SetMeshModified(true);
-
- Py_RETURN_NONE;
-}
-
-PyObject *KX_MeshProxy::pyattr_get_materials(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_MeshProxy* self = static_cast<KX_MeshProxy*>(self_v);
-
- int tot= self->m_meshobj->NumMaterials();
- int i;
-
- PyObject *materials = PyList_New( tot );
-
- list<RAS_MeshMaterial>::iterator mit= self->m_meshobj->GetFirstMaterial();
-
-
- for (i=0; i<tot; mit++, i++) {
- RAS_IPolyMaterial *polymat = mit->m_bucket->GetPolyMaterial();
- KX_BlenderMaterial *mat = static_cast<KX_BlenderMaterial *>(polymat);
- PyList_SET_ITEM(materials, i, mat->GetProxy());
- }
- return materials;
-}
-
-PyObject *KX_MeshProxy::pyattr_get_numMaterials(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_MeshProxy * self = static_cast<KX_MeshProxy *> (self_v);
- return PyLong_FromLong(self->m_meshobj->NumMaterials());
-}
-
-PyObject *KX_MeshProxy::pyattr_get_numPolygons(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_MeshProxy * self = static_cast<KX_MeshProxy *> (self_v);
- return PyLong_FromLong(self->m_meshobj->NumPolygons());
-}
-
-/* a close copy of ConvertPythonToGameObject but for meshes */
-bool ConvertPythonToMesh(SCA_LogicManager *logicmgr, PyObject *value, RAS_MeshObject **object, bool py_none_ok, const char *error_prefix)
-{
- if (value==NULL) {
- PyErr_Format(PyExc_TypeError, "%s, python pointer NULL, should never happen", error_prefix);
- *object = NULL;
- return false;
- }
-
- if (value==Py_None) {
- *object = NULL;
-
- if (py_none_ok) {
- return true;
- } else {
- PyErr_Format(PyExc_TypeError, "%s, expected KX_MeshProxy or a KX_MeshProxy name, None is invalid", error_prefix);
- return false;
- }
- }
-
- if (PyUnicode_Check(value)) {
- *object = (RAS_MeshObject*)logicmgr->GetMeshByName(STR_String( _PyUnicode_AsString(value) ));
-
- if (*object) {
- return true;
- } else {
- PyErr_Format(PyExc_ValueError, "%s, requested name \"%s\" did not match any KX_MeshProxy in this scene", error_prefix, _PyUnicode_AsString(value));
- return false;
- }
- }
-
- if (PyObject_TypeCheck(value, &KX_MeshProxy::Type)) {
- KX_MeshProxy *kx_mesh = static_cast<KX_MeshProxy*>BGE_PROXY_REF(value);
-
- /* sets the error */
- if (kx_mesh==NULL) {
- PyErr_Format(PyExc_SystemError, "%s, " BGE_PROXY_ERROR_MSG, error_prefix);
- return false;
- }
-
- *object = kx_mesh->GetMesh();
- return true;
- }
-
- *object = NULL;
-
- if (py_none_ok) {
- PyErr_Format(PyExc_TypeError, "%s, expect a KX_MeshProxy, a string or None", error_prefix);
- } else {
- PyErr_Format(PyExc_TypeError, "%s, expect a KX_MeshProxy or a string", error_prefix);
- }
-
- return false;
-}
-
-#endif // WITH_PYTHON
diff --git a/source/gameengine/Ketsji/KX_MeshProxy.h b/source/gameengine/Ketsji/KX_MeshProxy.h
deleted file mode 100644
index dbd7987f785..00000000000
--- a/source/gameengine/Ketsji/KX_MeshProxy.h
+++ /dev/null
@@ -1,85 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file KX_MeshProxy.h
- * \ingroup ketsji
- */
-
-#ifndef __KX_MESHPROXY_H__
-#define __KX_MESHPROXY_H__
-
-#ifdef WITH_PYTHON
-
-#include "SCA_IObject.h"
-
-class SCA_LogicManager;
-/* utility conversion function */
-bool ConvertPythonToMesh(SCA_LogicManager *logicmgr, PyObject *value, class RAS_MeshObject **object, bool py_none_ok, const char *error_prefix);
-
-class KX_MeshProxy : public CValue
-{
- Py_Header
-
- class RAS_MeshObject* m_meshobj;
-public:
- KX_MeshProxy(class RAS_MeshObject* mesh);
- virtual ~KX_MeshProxy();
-
- void SetMeshModified(bool v);
-
- // stuff for cvalue related things
- virtual CValue* Calc(VALUE_OPERATOR op, CValue *val);
- virtual CValue* CalcFinal(VALUE_DATA_TYPE dtype, VALUE_OPERATOR op, CValue *val);
- virtual const STR_String & GetText();
- virtual double GetNumber();
- virtual RAS_MeshObject* GetMesh() { return m_meshobj; }
- virtual STR_String& GetName();
- virtual void SetName(const char *name); // Set the name of the value
- virtual CValue* GetReplica();
-
-// stuff for python integration
-
- KX_PYMETHOD(KX_MeshProxy,GetNumMaterials); // Deprecated
- KX_PYMETHOD(KX_MeshProxy,GetMaterialName);
- KX_PYMETHOD(KX_MeshProxy,GetTextureName);
- KX_PYMETHOD_NOARGS(KX_MeshProxy,GetNumPolygons); // Deprecated
-
- // both take materialid (int)
- KX_PYMETHOD(KX_MeshProxy,GetVertexArrayLength);
- KX_PYMETHOD(KX_MeshProxy,GetVertex);
- KX_PYMETHOD(KX_MeshProxy,GetPolygon);
- KX_PYMETHOD(KX_MeshProxy,Transform);
- KX_PYMETHOD(KX_MeshProxy,TransformUV);
-
- static PyObject *pyattr_get_materials(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject *pyattr_get_numMaterials(void *self, const KX_PYATTRIBUTE_DEF * attrdef);
- static PyObject *pyattr_get_numPolygons(void *self, const KX_PYATTRIBUTE_DEF * attrdef);
-};
-
-#endif /* WITH_PYTHON */
-
-#endif /* __KX_MESHPROXY_H__ */
diff --git a/source/gameengine/Ketsji/KX_MotionState.cpp b/source/gameengine/Ketsji/KX_MotionState.cpp
deleted file mode 100644
index 4728f71a6ea..00000000000
--- a/source/gameengine/Ketsji/KX_MotionState.cpp
+++ /dev/null
@@ -1,106 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Ketsji/KX_MotionState.cpp
- * \ingroup ketsji
- */
-
-#include "KX_MotionState.h"
-#include "SG_Spatial.h"
-
-KX_MotionState::KX_MotionState(SG_Spatial* node) : m_node(node)
-{
-
-}
-
-KX_MotionState::~KX_MotionState()
-{
-}
-
-void KX_MotionState::GetWorldPosition(float& posX,float& posY,float& posZ)
-{
- const MT_Point3& pos = m_node->GetWorldPosition();
- posX = pos[0];
- posY = pos[1];
- posZ = pos[2];
-}
-
-void KX_MotionState::GetWorldScaling(float& scaleX,float& scaleY,float& scaleZ)
-{
- const MT_Vector3& scale = m_node->GetWorldScaling();
- scaleX = scale[0];
- scaleY = scale[1];
- scaleZ = scale[2];
-}
-
-void KX_MotionState::GetWorldOrientation(float& quatIma0,float& quatIma1,float& quatIma2,float& quatReal)
-{
- MT_Quaternion orn = m_node->GetWorldOrientation().getRotation();
- quatIma0 = orn[0];
- quatIma1 = orn[1];
- quatIma2 = orn[2];
- quatReal = orn[3];
-}
-
-void KX_MotionState::GetWorldOrientation(float* ori)
-{
- const MT_Matrix3x3& mat = m_node->GetWorldOrientation();
- mat.getValue(ori);
-}
-
-void KX_MotionState::SetWorldOrientation(const float* ori)
-{
- m_node->SetLocalOrientation(ori);
-}
-
-void KX_MotionState::SetWorldPosition(float posX,float posY,float posZ)
-{
- m_node->SetLocalPosition(MT_Point3(posX,posY,posZ));
- //m_node->SetWorldPosition(MT_Point3(posX,posY,posZ));
-}
-
-void KX_MotionState::SetWorldOrientation(float quatIma0,float quatIma1,float quatIma2,float quatReal)
-{
- MT_Quaternion orn;
- orn[0] = quatIma0;
- orn[1] = quatIma1;
- orn[2] = quatIma2;
- orn[3] = quatReal;
-
- m_node->SetLocalOrientation(orn);
- //m_node->SetWorldOrientation(orn);
-
-}
-
-void KX_MotionState::CalculateWorldTransformations()
-{
- //Not needed, will be done in KX_Scene::UpdateParents() after the physics simulation
- //bool parentUpdated = false;
- //m_node->ComputeWorldTransforms(NULL, parentUpdated);
-}
-
-
diff --git a/source/gameengine/Ketsji/KX_MotionState.h b/source/gameengine/Ketsji/KX_MotionState.h
deleted file mode 100644
index 38046fe4ff9..00000000000
--- a/source/gameengine/Ketsji/KX_MotionState.h
+++ /dev/null
@@ -1,65 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file KX_MotionState.h
- * \ingroup ketsji
- */
-
-#ifndef __KX_MOTIONSTATE_H__
-#define __KX_MOTIONSTATE_H__
-
-#include "PHY_IMotionState.h"
-
-#ifdef WITH_CXX_GUARDEDALLOC
-#include "MEM_guardedalloc.h"
-#endif
-
-class KX_MotionState : public PHY_IMotionState
-{
- class SG_Spatial* m_node;
-
-public:
- KX_MotionState(class SG_Spatial* spatial);
- virtual ~KX_MotionState();
-
- virtual void GetWorldPosition(float& posX,float& posY,float& posZ);
- virtual void GetWorldScaling(float& scaleX,float& scaleY,float& scaleZ);
- virtual void GetWorldOrientation(float& quatIma0,float& quatIma1,float& quatIma2,float& quatReal);
- virtual void SetWorldPosition(float posX,float posY,float posZ);
- virtual void SetWorldOrientation(float quatIma0,float quatIma1,float quatIma2,float quatReal);
- virtual void GetWorldOrientation(float* ori);
- virtual void SetWorldOrientation(const float* ori);
-
- virtual void CalculateWorldTransformations();
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:KX_MotionState")
-#endif
-};
-
-#endif /* __KX_MOTIONSTATE_H__ */
diff --git a/source/gameengine/Ketsji/KX_MouseActuator.cpp b/source/gameengine/Ketsji/KX_MouseActuator.cpp
deleted file mode 100644
index 6aa0d588b50..00000000000
--- a/source/gameengine/Ketsji/KX_MouseActuator.cpp
+++ /dev/null
@@ -1,539 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * Contributor(s): Geoffrey Gollmer, Jorge Bernal
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-#include "KX_MouseActuator.h"
-#include "KX_KetsjiEngine.h"
-#include "SCA_MouseManager.h"
-#include "SCA_IInputDevice.h"
-#include "RAS_ICanvas.h"
-#include "KX_GameObject.h"
-#include "MT_Vector3.h"
-#include "MT_Scalar.h"
-#include "MT_assert.h"
-#include "limits.h"
-
-#include "BLI_math.h"
-
-#ifdef HAVE_CONFIG_H
-#include <config.h>
-#endif
-
-/* ------------------------------------------------------------------------- */
-/* Native functions */
-/* ------------------------------------------------------------------------- */
-
-KX_MouseActuator::KX_MouseActuator(
- SCA_IObject* gameobj,
-
- KX_KetsjiEngine* ketsjiEngine,
- SCA_MouseManager* eventmgr,
- int acttype,
- bool visible,
- bool* use_axis,
- float* threshold,
- bool* reset,
- int* object_axis,
- bool* local,
- float* sensitivity,
- float* limit_x,
- float* limit_y
-):
- SCA_IActuator(gameobj, KX_ACT_MOUSE),
- m_ketsji(ketsjiEngine),
- m_eventmgr(eventmgr),
- m_type(acttype),
- m_visible(visible),
- m_use_axis_x(use_axis[0]),
- m_use_axis_y(use_axis[1]),
- m_reset_x(reset[0]),
- m_reset_y(reset[1]),
- m_local_x(local[0]),
- m_local_y(local[1])
-{
- m_canvas = m_ketsji->GetCanvas();
- m_oldposition[0] = m_oldposition[1] = -1.f;
- m_limit_x[0] = limit_x[0];
- m_limit_x[1] = limit_x[1];
- m_limit_y[0] = limit_y[0];
- m_limit_y[1] = limit_y[1];
- m_threshold[0] = threshold[0];
- m_threshold[1] = threshold[1];
- m_object_axis[0] = object_axis[0];
- m_object_axis[1] = object_axis[1];
- m_sensitivity[0] = sensitivity[0];
- m_sensitivity[1] = sensitivity[1];
- m_angle[0] = 0.f;
- m_angle[1] = 0.f;
-}
-
-KX_MouseActuator::~KX_MouseActuator()
-{
-}
-
-bool KX_MouseActuator::Update()
-{
- bool result = false;
-
- bool bNegativeEvent = IsNegativeEvent();
- RemoveAllEvents();
-
- if (bNegativeEvent)
- return false; // do nothing on negative events
-
- KX_GameObject *parent = static_cast<KX_GameObject *>(GetParent());
-
- m_mouse = ((SCA_MouseManager *)m_eventmgr)->GetInputDevice();
-
- switch (m_type) {
- case KX_ACT_MOUSE_VISIBILITY:
- {
- if (m_visible) {
- if (m_canvas) {
- m_canvas->SetMouseState(RAS_ICanvas::MOUSE_NORMAL);
- }
- }
- else {
- if (m_canvas) {
- m_canvas->SetMouseState(RAS_ICanvas::MOUSE_INVISIBLE);
- }
- }
- break;
- }
- case KX_ACT_MOUSE_LOOK:
- {
- if (m_mouse) {
-
- float position[2];
- float movement[2];
- MT_Vector3 rotation;
- float setposition[2] = {0.0f};
- float center_x = 0.5f, center_y = 0.5f;
-
- getMousePosition(position);
-
- movement[0] = position[0];
- movement[1] = position[1];
-
- //preventing undesired drifting when resolution is odd
- if ((m_canvas->GetWidth() % 2) != 0) {
- center_x = ((m_canvas->GetWidth() - 1.0f) / 2.0f) / (m_canvas->GetWidth());
- }
- if ((m_canvas->GetHeight() % 2) != 0) {
- center_y = ((m_canvas->GetHeight() - 1.0f) / 2.0f) / (m_canvas->GetHeight());
- }
-
- //preventing initial skipping.
- if ((m_oldposition[0] <= -0.9f) && (m_oldposition[1] <= -0.9f)) {
-
- if (m_reset_x) {
- m_oldposition[0] = center_x;
- }
- else {
- m_oldposition[0] = position[0];
- }
-
- if (m_reset_y) {
- m_oldposition[1] = center_y;
- }
- else {
- m_oldposition[1] = position[1];
- }
- setMousePosition(m_oldposition[0], m_oldposition[1]);
- break;
- }
-
- //Calculating X axis.
- if (m_use_axis_x) {
-
- if (m_reset_x) {
- setposition[0] = center_x;
- movement[0] -= center_x;
- }
- else {
- setposition[0] = position[0];
- movement[0] -= m_oldposition[0];
- }
-
- movement[0] *= -1.0f;
-
- /* Don't apply the rotation when we are under a certain threshold for mouse
- movement */
-
- if (((movement[0] > (m_threshold[0] / 10.0f)) ||
- ((movement[0] * (-1.0f)) > (m_threshold[0] / 10.0f)))) {
-
- movement[0] *= m_sensitivity[0];
-
- if ((m_limit_x[0] != 0.0f) && ((m_angle[0] + movement[0]) <= m_limit_x[0])) {
- movement[0] = m_limit_x[0] - m_angle[0];
- }
-
- if ((m_limit_x[1] != 0.0f) && ((m_angle[0] + movement[0]) >= m_limit_x[1])) {
- movement[0] = m_limit_x[1] - m_angle[0];
- }
-
- m_angle[0] += movement[0];
-
- switch (m_object_axis[0]) {
- case KX_ACT_MOUSE_OBJECT_AXIS_X:
- {
- rotation = MT_Vector3(movement[0], 0.0f, 0.0f);
- break;
- }
- case KX_ACT_MOUSE_OBJECT_AXIS_Y:
- {
- rotation = MT_Vector3(0.0f, movement[0], 0.0f);
- break;
- }
- case KX_ACT_MOUSE_OBJECT_AXIS_Z:
- {
- rotation = MT_Vector3(0.0f, 0.0f, movement[0]);
- break;
- }
- default:
- break;
- }
- parent->ApplyRotation(rotation, m_local_x);
- }
- }
- else {
- setposition[0] = center_x;
- }
-
- //Calculating Y axis.
- if (m_use_axis_y) {
-
- if (m_reset_y) {
- setposition[1] = center_y;
- movement[1] -= center_y;
- }
- else {
- setposition[1] = position[1];
- movement[1] -= m_oldposition[1];
- }
-
- movement[1] *= -1.0f;
-
- /* Don't apply the rotation when we are under a certain threshold for mouse
- movement */
-
- if (((movement[1] > (m_threshold[1] / 10.0f)) ||
- ((movement[1] * (-1.0f)) > (m_threshold[1] / 10.0f)))) {
-
- movement[1] *= m_sensitivity[1];
-
- if ((m_limit_y[0] != 0.0f) && ((m_angle[1] + movement[1]) <= m_limit_y[0])) {
- movement[1] = m_limit_y[0] - m_angle[1];
- }
-
- if ((m_limit_y[1] != 0.0f) && ((m_angle[1] + movement[1]) >= m_limit_y[1])) {
- movement[1] = m_limit_y[1] - m_angle[1];
- }
-
- m_angle[1] += movement[1];
-
- switch (m_object_axis[1])
- {
- case KX_ACT_MOUSE_OBJECT_AXIS_X:
- {
- rotation = MT_Vector3(movement[1], 0.0f, 0.0f);
- break;
- }
- case KX_ACT_MOUSE_OBJECT_AXIS_Y:
- {
- rotation = MT_Vector3(0.0f, movement[1], 0.0f);
- break;
- }
- case KX_ACT_MOUSE_OBJECT_AXIS_Z:
- {
- rotation = MT_Vector3(0.0f, 0.0f, movement[1]);
- break;
- }
- default:
- break;
- }
- parent->ApplyRotation(rotation, m_local_y);
- }
- }
- else {
- setposition[1] = center_y;
- }
-
- // only trigger mouse event when it is necessary
- if (m_oldposition[0] != position[0] || m_oldposition[1] != position[1]) {
- setMousePosition(setposition[0], setposition[1]);
- }
-
- m_oldposition[0] = position[0];
- m_oldposition[1] = position[1];
-
- }
- else {
- //printf("\nNo input device detected for mouse actuator\n");
- }
- break;
- }
- default:
- break;
- }
- return result;
-}
-
-bool KX_MouseActuator::isValid(KX_MouseActuator::KX_ACT_MOUSE_MODE mode)
-{
- return ((mode > KX_ACT_MOUSE_NODEF) && (mode < KX_ACT_MOUSE_MAX));
-}
-
-
-CValue* KX_MouseActuator::GetReplica()
-{
- KX_MouseActuator* replica = new KX_MouseActuator(*this);
-
- replica->ProcessReplica();
- return replica;
-}
-
-void KX_MouseActuator::ProcessReplica()
-{
- SCA_IActuator::ProcessReplica();
-}
-
-void KX_MouseActuator::getMousePosition(float* pos)
-{
- MT_assert(m_mouse);
- const SCA_InputEvent & xevent = m_mouse->GetEventValue(SCA_IInputDevice::KX_MOUSEX);
- const SCA_InputEvent & yevent = m_mouse->GetEventValue(SCA_IInputDevice::KX_MOUSEY);
-
- pos[0] = m_canvas->GetMouseNormalizedX(xevent.m_eventval);
- pos[1] = m_canvas->GetMouseNormalizedY(yevent.m_eventval);
-}
-
-void KX_MouseActuator::setMousePosition(float fx, float fy)
-{
- int x, y;
-
- x = (int)(fx * m_canvas->GetWidth());
- y = (int)(fy * m_canvas->GetHeight());
-
- m_canvas->SetMousePosition(x, y);
-}
-
-#ifdef WITH_PYTHON
-
-/* ------------------------------------------------------------------------- */
-/* Python functions */
-/* ------------------------------------------------------------------------- */
-
-/* Integration hooks ------------------------------------------------------- */
-PyTypeObject KX_MouseActuator::Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "KX_MouseActuator",
- sizeof(PyObjectPlus_Proxy),
- 0,
- py_base_dealloc,
- 0,
- 0,
- 0,
- 0,
- py_base_repr,
- 0,0,0,0,0,0,0,0,0,
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
- 0,0,0,0,0,0,0,
- Methods,
- 0,
- 0,
- &SCA_IActuator::Type,
- 0,0,0,0,0,0,
- py_base_new
-};
-
-PyMethodDef KX_MouseActuator::Methods[] = {
- {"reset", (PyCFunction) KX_MouseActuator::sPyReset, METH_NOARGS,"reset() : undo rotation caused by actuator\n"},
- {NULL,NULL} //Sentinel
-};
-
-
-
-PyAttributeDef KX_MouseActuator::Attributes[] = {
- KX_PYATTRIBUTE_BOOL_RW("visible", KX_MouseActuator, m_visible),
- KX_PYATTRIBUTE_BOOL_RW("use_axis_x", KX_MouseActuator, m_use_axis_x),
- KX_PYATTRIBUTE_BOOL_RW("use_axis_y", KX_MouseActuator, m_use_axis_y),
- KX_PYATTRIBUTE_FLOAT_ARRAY_RW("threshold", 0.0f, 0.5f, KX_MouseActuator, m_threshold, 2),
- KX_PYATTRIBUTE_BOOL_RW("reset_x", KX_MouseActuator, m_reset_x),
- KX_PYATTRIBUTE_BOOL_RW("reset_y", KX_MouseActuator, m_reset_y),
- KX_PYATTRIBUTE_INT_ARRAY_RW("object_axis", 0, 2, 1, KX_MouseActuator, m_object_axis, 2),
- KX_PYATTRIBUTE_BOOL_RW("local_x", KX_MouseActuator, m_local_x),
- KX_PYATTRIBUTE_BOOL_RW("local_y", KX_MouseActuator, m_local_y),
- KX_PYATTRIBUTE_FLOAT_ARRAY_RW("sensitivity", -FLT_MAX, FLT_MAX, KX_MouseActuator, m_sensitivity, 2),
- KX_PYATTRIBUTE_RW_FUNCTION("limit_x", KX_MouseActuator, pyattr_get_limit_x, pyattr_set_limit_x),
- KX_PYATTRIBUTE_RW_FUNCTION("limit_y", KX_MouseActuator, pyattr_get_limit_y, pyattr_set_limit_y),
- KX_PYATTRIBUTE_RW_FUNCTION("angle", KX_MouseActuator, pyattr_get_angle, pyattr_set_angle),
- { NULL } //Sentinel
-};
-
-PyObject* KX_MouseActuator::pyattr_get_limit_x(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_MouseActuator* self= static_cast<KX_MouseActuator*>(self_v);
- return Py_BuildValue("[f,f]", (self->m_limit_x[0] / (float)M_PI * 180.0f), (self->m_limit_x[1] / (float)M_PI * 180.0f));
-}
-
-int KX_MouseActuator::pyattr_set_limit_x(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- PyObject *item1, *item2;
- KX_MouseActuator* self= static_cast<KX_MouseActuator*>(self_v);
-
- if (!PyList_Check(value))
- return PY_SET_ATTR_FAIL;
-
- if (PyList_Size(value) != 2)
- return PY_SET_ATTR_FAIL;
-
- item1 = PyList_GET_ITEM(value, 0);
- item2 = PyList_GET_ITEM(value, 1);
-
- if (!(PyFloat_Check(item1)) || !(PyFloat_Check(item2))) {
- return PY_SET_ATTR_FAIL;
- }
- else {
- self->m_limit_x[0] = (float)((PyFloat_AsDouble(item1) * M_PI) / 180.0f);
- self->m_limit_x[1] = (float)((PyFloat_AsDouble(item2) * M_PI) / 180.0f);
- }
-
- return PY_SET_ATTR_SUCCESS;
-}
-
-PyObject* KX_MouseActuator::pyattr_get_limit_y(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_MouseActuator* self= static_cast<KX_MouseActuator*>(self_v);
- return Py_BuildValue("[f,f]", (self->m_limit_y[0] / (float)M_PI * 180.0f), (self->m_limit_y[1] / (float)M_PI * 180.0f));
-}
-
-int KX_MouseActuator::pyattr_set_limit_y(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- PyObject *item1, *item2;
- KX_MouseActuator* self= static_cast<KX_MouseActuator*>(self_v);
-
- if (!PyList_Check(value))
- return PY_SET_ATTR_FAIL;
-
- if (PyList_Size(value) != 2)
- return PY_SET_ATTR_FAIL;
-
- item1 = PyList_GET_ITEM(value, 0);
- item2 = PyList_GET_ITEM(value, 1);
-
- if (!(PyFloat_Check(item1)) || !(PyFloat_Check(item2))) {
- return PY_SET_ATTR_FAIL;
- }
- else {
- self->m_limit_y[0] = (float)((PyFloat_AsDouble(item1) * M_PI) / 180.0f);
- self->m_limit_y[1] = (float)((PyFloat_AsDouble(item2) * M_PI) / 180.0f);
- }
-
- return PY_SET_ATTR_SUCCESS;
-}
-
-PyObject* KX_MouseActuator::pyattr_get_angle(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_MouseActuator* self= static_cast<KX_MouseActuator*>(self_v);
- return Py_BuildValue("[f,f]", (self->m_angle[0] / (float)M_PI * 180.0f), (self->m_angle[1] / (float)M_PI * 180.0f));
-}
-
-int KX_MouseActuator::pyattr_set_angle(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- PyObject *item1, *item2;
- KX_MouseActuator* self= static_cast<KX_MouseActuator*>(self_v);
-
- if (!PyList_Check(value))
- return PY_SET_ATTR_FAIL;
-
- if (PyList_Size(value) != 2)
- return PY_SET_ATTR_FAIL;
-
- item1 = PyList_GET_ITEM(value, 0);
- item2 = PyList_GET_ITEM(value, 1);
-
- if (!(PyFloat_Check(item1)) || !(PyFloat_Check(item2))) {
- return PY_SET_ATTR_FAIL;
- }
- else {
- self->m_angle[0] = ((float)(PyFloat_AsDouble(item1) * M_PI) / 180.0f);
- self->m_angle[1] = ((float)(PyFloat_AsDouble(item2) * M_PI) / 180.0f);
- }
-
- return PY_SET_ATTR_SUCCESS;
-}
-
-PyObject* KX_MouseActuator::PyReset()
-{
- MT_Vector3 rotation;
- KX_GameObject *parent = static_cast<KX_GameObject *>(GetParent());
-
- switch (m_object_axis[0]) {
- case KX_ACT_MOUSE_OBJECT_AXIS_X:
- {
- rotation = MT_Vector3(-1.0f * m_angle[0], 0.0f, 0.0f);
- break;
- }
- case KX_ACT_MOUSE_OBJECT_AXIS_Y:
- {
- rotation = MT_Vector3(0.0f, -1.0f * m_angle[0], 0.0f);
- break;
- }
- case KX_ACT_MOUSE_OBJECT_AXIS_Z:
- {
- rotation = MT_Vector3(0.0f, 0.0f, -1.0f * m_angle[0]);
- break;
- }
- default:
- break;
- }
- parent->ApplyRotation(rotation, m_local_x);
-
- switch (m_object_axis[1]) {
- case KX_ACT_MOUSE_OBJECT_AXIS_X:
- {
- rotation = MT_Vector3(-1.0f * m_angle[1], 0.0f, 0.0f);
- break;
- }
- case KX_ACT_MOUSE_OBJECT_AXIS_Y:
- {
- rotation = MT_Vector3(0.0f, -1.0f * m_angle[1], 0.0f);
- break;
- }
- case KX_ACT_MOUSE_OBJECT_AXIS_Z:
- {
- rotation = MT_Vector3(0.0f, 0.0f, -1.0f * m_angle[1]);
- break;
- }
- default:
- break;
- }
- parent->ApplyRotation(rotation, m_local_y);
-
- m_angle[0] = 0.0f;
- m_angle[1] = 0.0f;
-
- Py_RETURN_NONE;
-}
-
-#endif /* WITH_PYTHON */
diff --git a/source/gameengine/Ketsji/KX_MouseActuator.h b/source/gameengine/Ketsji/KX_MouseActuator.h
deleted file mode 100644
index e244e271428..00000000000
--- a/source/gameengine/Ketsji/KX_MouseActuator.h
+++ /dev/null
@@ -1,132 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * Contributor(s): Geoffrey Gollmer, Jorge Bernal
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-#ifndef __KX_MOUSEACTUATOR
-#define __KX_MOUSEACTUATOR
-
-#include "SCA_IActuator.h"
-
-class KX_KetsjiEngine;
-class SCA_MouseManager;
-class SCA_IInputDevice;
-class RAS_ICanvas;
-
-class KX_MouseActuator : public SCA_IActuator
-{
- Py_Header
-
-private:
-
- KX_KetsjiEngine* m_ketsji;
- SCA_MouseManager* m_eventmgr;
- SCA_IInputDevice* m_mouse;
- RAS_ICanvas* m_canvas;
- int m_type;
-
- bool m_visible;
-
- bool m_use_axis_x; /* 0 for calculate axis, 1 for ignore axis */
- bool m_use_axis_y;
- float m_threshold[2];
- bool m_reset_x; /* 0=reset, 1=free */
- bool m_reset_y;
- int m_object_axis[2]; /* 0=x, 1=y, 2=z */
- bool m_local_x; /* 0=local, 1=global*/
- bool m_local_y;
- float m_sensitivity[2];
- float m_limit_x[2];
- float m_limit_y[2];
-
- float m_oldposition[2];
- float m_angle[2];
-
-public:
-
- enum KX_ACT_MOUSE_OBJECT_AXIS {
- KX_ACT_MOUSE_OBJECT_AXIS_X = 0,
- KX_ACT_MOUSE_OBJECT_AXIS_Y,
- KX_ACT_MOUSE_OBJECT_AXIS_Z
- };
-
- enum KX_ACT_MOUSE_MODE {
- KX_ACT_MOUSE_NODEF = 0,
- KX_ACT_MOUSE_VISIBILITY,
- KX_ACT_MOUSE_LOOK,
- KX_ACT_MOUSE_MAX
- };
-
- KX_MouseActuator(
- SCA_IObject* gameobj,
- KX_KetsjiEngine* ketsjiEngine,
- SCA_MouseManager* eventmgr,
- int acttype,
- bool visible,
- bool* use_axis,
- float* threshold,
- bool* reset,
- int* object_axis,
- bool* local,
- float* sensitivity,
- float* limit_x,
- float* limit_y
- );
-
-
- ~KX_MouseActuator();
-
- CValue* GetReplica();
- virtual void ProcessReplica();
-
- virtual bool Update();
-
- /* check whether this value is valid */
- bool isValid(KX_ACT_MOUSE_MODE mode);
-
- virtual void getMousePosition(float*);
- virtual void setMousePosition(float, float);
-
-
-#ifdef WITH_PYTHON
-
- /* --------------------------------------------------------------------- */
- /* Python interface ---------------------------------------------------- */
- /* --------------------------------------------------------------------- */
-
- /* Methods */
-
- KX_PYMETHOD_DOC_NOARGS(KX_MouseActuator,Reset);
-
- /* Attributes */
-
- static PyObject* pyattr_get_limit_x(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_limit_x(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
-
- static PyObject* pyattr_get_limit_y(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_limit_y(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
-
- static PyObject* pyattr_get_angle(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_angle(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
-#endif /* WITH_PYTHON */
-
-};
-
-#endif //__KX_MOUSEACTUATOR_DOC
diff --git a/source/gameengine/Ketsji/KX_MouseFocusSensor.cpp b/source/gameengine/Ketsji/KX_MouseFocusSensor.cpp
deleted file mode 100644
index 451078d4a36..00000000000
--- a/source/gameengine/Ketsji/KX_MouseFocusSensor.cpp
+++ /dev/null
@@ -1,520 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- * KX_MouseFocusSensor determines mouse in/out/over events.
- */
-
-/** \file gameengine/Ketsji/KX_MouseFocusSensor.cpp
- * \ingroup ketsji
- */
-
-#ifdef _MSC_VER
- /* This warning tells us about truncation of __long__ stl-generated names.
- * It can occasionally cause DevStudio to have internal compiler warnings. */
-# pragma warning(disable:4786)
-#endif
-
-#include <stdio.h>
-
-#include "MT_Point3.h"
-#include "RAS_FramingManager.h"
-#include "RAS_ICanvas.h"
-#include "RAS_IRasterizer.h"
-#include "RAS_MeshObject.h"
-#include "SCA_IScene.h"
-#include "KX_Scene.h"
-#include "KX_Camera.h"
-#include "KX_MouseFocusSensor.h"
-#include "KX_PyMath.h"
-
-#include "KX_RayCast.h"
-#include "PHY_IPhysicsController.h"
-#include "PHY_IPhysicsEnvironment.h"
-
-
-#include "KX_ClientObjectInfo.h"
-
-/* ------------------------------------------------------------------------- */
-/* Native functions */
-/* ------------------------------------------------------------------------- */
-
-KX_MouseFocusSensor::KX_MouseFocusSensor(SCA_MouseManager* eventmgr,
- int startx,
- int starty,
- short int mousemode,
- int focusmode,
- bool bTouchPulse,
- const STR_String& propname,
- bool bFindMaterial,
- bool bXRay,
- KX_Scene* kxscene,
- KX_KetsjiEngine *kxengine,
- SCA_IObject* gameobj)
- : SCA_MouseSensor(eventmgr, startx, starty, mousemode, gameobj),
- m_focusmode(focusmode),
- m_bTouchPulse(bTouchPulse),
- m_bXRay(bXRay),
- m_bFindMaterial(bFindMaterial),
- m_propertyname(propname),
- m_kxscene(kxscene),
- m_kxengine(kxengine)
-{
- Init();
-}
-
-void KX_MouseFocusSensor::Init()
-{
- m_mouse_over_in_previous_frame = (m_invert)?true:false;
- m_positive_event = false;
- m_hitObject = 0;
- m_hitObject_Last = NULL;
- m_reset = true;
-
- m_hitPosition.setValue(0,0,0);
- m_prevTargetPoint.setValue(0,0,0);
- m_prevSourcePoint.setValue(0,0,0);
- m_hitNormal.setValue(0,0,1);
-}
-
-bool KX_MouseFocusSensor::Evaluate()
-{
- bool result = false;
- bool obHasFocus = false;
- bool reset = m_reset && m_level;
-
-// cout << "evaluate focus mouse sensor "<<endl;
- m_reset = false;
- if (m_focusmode) {
- /* Focus behavior required. Test mouse-on. The rest is
- * equivalent to handling a key. */
- obHasFocus = ParentObjectHasFocus();
-
- if (!obHasFocus) {
- m_positive_event = false;
- if (m_mouse_over_in_previous_frame) {
- result = true;
- }
- } else {
- m_positive_event = true;
- if (!m_mouse_over_in_previous_frame) {
- result = true;
- }
- else if (m_bTouchPulse && (m_hitObject != m_hitObject_Last)) {
- result = true;
- }
- }
- if (reset) {
- // force an event
- result = true;
- }
- } else {
- /* No focus behavior required: revert to the basic mode. This
- * mode is never used, because the converter never makes this
- * sensor for a mouse-key event. It is here for
- * completeness. */
- result = SCA_MouseSensor::Evaluate();
- m_positive_event = (m_val!=0);
- }
-
- m_mouse_over_in_previous_frame = obHasFocus;
- m_hitObject_Last = (void *)m_hitObject;
-
- return result;
-}
-
-bool KX_MouseFocusSensor::RayHit(KX_ClientObjectInfo *client_info, KX_RayCast *result, void *UNUSED(data))
-{
- KX_GameObject* hitKXObj = client_info->m_gameobject;
-
- /* Is this me? In the ray test, there are a lot of extra checks
- * for aliasing artifacts from self-hits. That doesn't happen
- * here, so a simple test suffices. Or does the camera also get
- * self-hits? (No, and the raysensor shouldn't do it either, since
- * self-hits are excluded by setting the correct ignore-object.)
- * Hitspots now become valid. */
- KX_GameObject* thisObj = (KX_GameObject*) GetParent();
-
- bool bFound = false;
-
- if ((m_focusmode == 2) || hitKXObj == thisObj)
- {
- if (m_propertyname.Length() == 0)
- {
- bFound = true;
- }
- else
- {
- if (m_bFindMaterial) {
- for (unsigned int i = 0; i < hitKXObj->GetMeshCount(); ++i) {
- RAS_MeshObject *meshObj = hitKXObj->GetMesh(i);
- for (unsigned int j = 0; j < meshObj->NumMaterials(); ++j) {
- bFound = strcmp(m_propertyname.ReadPtr(), meshObj->GetMaterialName(j).ReadPtr() + 2) == 0;
- if (bFound)
- break;
- }
- }
- }
- else {
- bFound = hitKXObj->GetProperty(m_propertyname) != NULL;
- }
- }
-
- if (bFound)
- {
- m_hitObject = hitKXObj;
- m_hitPosition = result->m_hitPoint;
- m_hitNormal = result->m_hitNormal;
- m_hitUV = result->m_hitUV;
- return true;
- }
- }
-
- return true; // object must be visible to trigger
- //return false; // occluded objects can trigger
-}
-
-/* this function is used to pre-filter the object before casting the ray on them.
- * This is useful for "X-Ray" option when we want to see "through" unwanted object.
- */
-bool KX_MouseFocusSensor::NeedRayCast(KX_ClientObjectInfo *client, void *UNUSED(data))
-{
- KX_GameObject *hitKXObj = client->m_gameobject;
-
- if (client->m_type > KX_ClientObjectInfo::ACTOR)
- {
- // Unknown type of object, skip it.
- // Should not occur as the sensor objects are filtered in RayTest()
- printf("Invalid client type %d found ray casting\n", client->m_type);
- return false;
- }
- if (m_bXRay && m_propertyname.Length() != 0)
- {
- if (m_bFindMaterial)
- {
- bool found = false;
- for (unsigned int i = 0; i < hitKXObj->GetMeshCount(); ++i) {
- RAS_MeshObject *meshObj = hitKXObj->GetMesh(i);
- for (unsigned int j = 0; j < meshObj->NumMaterials(); ++j) {
- found = strcmp(m_propertyname.ReadPtr(), meshObj->GetMaterialName(j).ReadPtr() + 2) == 0;
- if (found)
- break;
- }
- }
- if (!found)
- return false;
- }
- else
- {
- if (hitKXObj->GetProperty(m_propertyname) == NULL)
- return false;
- }
- }
- return true;
-}
-
-bool KX_MouseFocusSensor::ParentObjectHasFocusCamera(KX_Camera *cam)
-{
- /* All screen handling in the gameengine is done by GL,
- * specifically the model/view and projection parts. The viewport
- * part is in the creator.
- *
- * The theory is this:
- * WCS - world coordinates
- * -> wcs_camcs_trafo ->
- * camCS - camera coordinates
- * -> camcs_clip_trafo ->
- * clipCS - normalized device coordinates?
- * -> normview_win_trafo
- * winCS - window coordinates
- *
- * The first two transforms are respectively the model/view and
- * the projection matrix. These are passed to the rasterizer, and
- * we store them in the camera for easy access.
- *
- * For normalized device coords (xn = x/w, yn = y/w/zw) the
- * windows coords become (lb = left bottom)
- *
- * xwin = [(xn + 1.0) * width]/2 + x_lb
- * ywin = [(yn + 1.0) * height]/2 + y_lb
- *
- * Inverting (blender y is flipped!):
- *
- * xn = 2(xwin - x_lb)/width - 1.0
- * yn = 2(ywin - y_lb)/height - 1.0
- * = 2(height - y_blender - y_lb)/height - 1.0
- * = 1.0 - 2(y_blender - y_lb)/height
- *
- * */
-
-
- /* Because we don't want to worry about resize events, camera
- * changes and all that crap, we just determine this over and
- * over. Stop whining. We have lots of other calculations to do
- * here as well. These reads are not the main cost. If there is no
- * canvas, the test is irrelevant. The 1.0 makes sure the
- * calculations don't bomb. Maybe we should explicitly guard for
- * division by 0.0...*/
-
- RAS_Rect area, viewport;
- short m_y_inv = m_kxengine->GetCanvas()->GetHeight()-m_y;
-
- m_kxengine->GetSceneViewport(m_kxscene, cam, area, viewport);
-
- /* Check if the mouse is in the viewport */
- if (( m_x < viewport.m_x2 && // less than right
- m_x > viewport.m_x1 && // more than then left
- m_y_inv < viewport.m_y2 && // below top
- m_y_inv > viewport.m_y1) == 0) // above bottom
- {
- return false;
- }
-
- float height = float(viewport.m_y2 - viewport.m_y1 + 1);
- float width = float(viewport.m_x2 - viewport.m_x1 + 1);
-
- float x_lb = float(viewport.m_x1);
- float y_lb = float(viewport.m_y1);
-
- MT_Vector4 frompoint;
- MT_Vector4 topoint;
-
- /* m_y_inv - inverting for a bounds check is only part of it, now make relative to view bounds */
- m_y_inv = (viewport.m_y2 - m_y_inv) + viewport.m_y1;
-
-
- /* There's some strangeness I don't fully get here... These values
- * _should_ be wrong! - see from point Z values */
-
-
- /* build the from and to point in normalized device coordinates
- * Normalized device coordinates are [-1,1] in x, y, z
- *
- * The actual z coordinates used don't have to be exact just infront and
- * behind of the near and far clip planes.
- */
- frompoint.setValue( (2 * (m_x-x_lb) / width) - 1.0f,
- 1.0f - (2 * (m_y_inv - y_lb) / height),
- -1.0f,
- 1.0f );
-
- topoint.setValue( (2 * (m_x-x_lb) / width) - 1.0f,
- 1.0f - (2 * (m_y_inv-y_lb) / height),
- 1.0f,
- 1.0f );
-
- /* camera to world */
- MT_Matrix4x4 camcs_wcs_matrix = MT_Matrix4x4(cam->GetCameraToWorld());
-
- /* badly defined, the first time round.... I wonder why... I might
- * want to guard against floating point errors here.*/
- MT_Matrix4x4 clip_camcs_matrix = MT_Matrix4x4(cam->GetProjectionMatrix());
- clip_camcs_matrix.invert();
-
- /* shoot-points: clip to cam to wcs . win to clip was already done.*/
- frompoint = clip_camcs_matrix * frompoint;
- topoint = clip_camcs_matrix * topoint;
- /* clipstart = - (frompoint[2] / frompoint[3])
- * clipend = - (topoint[2] / topoint[3]) */
- frompoint = camcs_wcs_matrix * frompoint;
- topoint = camcs_wcs_matrix * topoint;
-
- /* from hom wcs to 3d wcs: */
- m_prevSourcePoint.setValue( frompoint[0]/frompoint[3],
- frompoint[1]/frompoint[3],
- frompoint[2]/frompoint[3]);
-
- m_prevTargetPoint.setValue( topoint[0]/topoint[3],
- topoint[1]/topoint[3],
- topoint[2]/topoint[3]);
-
- /* 2. Get the object from PhysicsEnvironment */
- /* Shoot! Beware that the first argument here is an
- * ignore-object. We don't ignore anything... */
- PHY_IPhysicsController* physics_controller = cam->GetPhysicsController();
- PHY_IPhysicsEnvironment* physics_environment = m_kxscene->GetPhysicsEnvironment();
-
- // get UV mapping
- KX_RayCast::Callback<KX_MouseFocusSensor, void> callback(this,physics_controller,NULL,false,true);
-
- KX_RayCast::RayTest(physics_environment, m_prevSourcePoint, m_prevTargetPoint, callback);
-
- if (m_hitObject)
- return true;
-
- return false;
-}
-
-bool KX_MouseFocusSensor::ParentObjectHasFocus()
-{
- m_hitObject = 0;
- m_hitPosition.setValue(0,0,0);
- m_hitNormal.setValue(1,0,0);
-
- KX_Camera *cam= m_kxscene->GetActiveCamera();
-
- if (ParentObjectHasFocusCamera(cam))
- return true;
-
- list<class KX_Camera*>* cameras = m_kxscene->GetCameras();
- list<KX_Camera*>::iterator it = cameras->begin();
-
- while (it != cameras->end()) {
- if (((*it) != cam) && (*it)->GetViewport())
- if (ParentObjectHasFocusCamera(*it))
- return true;
-
- it++;
- }
-
- return false;
-}
-
-const MT_Point3& KX_MouseFocusSensor::RaySource() const
-{
- return m_prevSourcePoint;
-}
-
-const MT_Point3& KX_MouseFocusSensor::RayTarget() const
-{
- return m_prevTargetPoint;
-}
-
-const MT_Point3& KX_MouseFocusSensor::HitPosition() const
-{
- return m_hitPosition;
-}
-
-const MT_Vector3& KX_MouseFocusSensor::HitNormal() const
-{
- return m_hitNormal;
-}
-
-const MT_Vector2& KX_MouseFocusSensor::HitUV() const
-{
- return m_hitUV;
-}
-
-#ifdef WITH_PYTHON
-
-/* ------------------------------------------------------------------------- */
-/* Python functions */
-/* ------------------------------------------------------------------------- */
-
-/* Integration hooks ------------------------------------------------------- */
-PyTypeObject KX_MouseFocusSensor::Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "KX_MouseFocusSensor",
- sizeof(PyObjectPlus_Proxy),
- 0,
- py_base_dealloc,
- 0,
- 0,
- 0,
- 0,
- py_base_repr,
- 0,0,0,0,0,0,0,0,0,
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
- 0,0,0,0,0,0,0,
- Methods,
- 0,
- 0,
- &SCA_MouseSensor::Type,
- 0,0,0,0,0,0,
- py_base_new
-};
-
-PyMethodDef KX_MouseFocusSensor::Methods[] = {
- {NULL,NULL} //Sentinel
-};
-
-PyAttributeDef KX_MouseFocusSensor::Attributes[] = {
- KX_PYATTRIBUTE_RO_FUNCTION("raySource", KX_MouseFocusSensor, pyattr_get_ray_source),
- KX_PYATTRIBUTE_RO_FUNCTION("rayTarget", KX_MouseFocusSensor, pyattr_get_ray_target),
- KX_PYATTRIBUTE_RO_FUNCTION("rayDirection", KX_MouseFocusSensor, pyattr_get_ray_direction),
- KX_PYATTRIBUTE_RO_FUNCTION("hitObject", KX_MouseFocusSensor, pyattr_get_hit_object),
- KX_PYATTRIBUTE_RO_FUNCTION("hitPosition", KX_MouseFocusSensor, pyattr_get_hit_position),
- KX_PYATTRIBUTE_RO_FUNCTION("hitNormal", KX_MouseFocusSensor, pyattr_get_hit_normal),
- KX_PYATTRIBUTE_RO_FUNCTION("hitUV", KX_MouseFocusSensor, pyattr_get_hit_uv),
- KX_PYATTRIBUTE_BOOL_RW("usePulseFocus", KX_MouseFocusSensor, m_bTouchPulse),
- KX_PYATTRIBUTE_BOOL_RW("useXRay", KX_MouseFocusSensor, m_bXRay),
- KX_PYATTRIBUTE_BOOL_RW("useMaterial", KX_MouseFocusSensor, m_bFindMaterial),
- KX_PYATTRIBUTE_STRING_RW("propName", 0, MAX_PROP_NAME, false, KX_MouseFocusSensor, m_propertyname),
- { NULL } //Sentinel
-};
-
-/* Attributes */
-PyObject *KX_MouseFocusSensor::pyattr_get_ray_source(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_MouseFocusSensor* self = static_cast<KX_MouseFocusSensor*>(self_v);
- return PyObjectFrom(self->RaySource());
-}
-
-PyObject *KX_MouseFocusSensor::pyattr_get_ray_target(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_MouseFocusSensor* self = static_cast<KX_MouseFocusSensor*>(self_v);
- return PyObjectFrom(self->RayTarget());
-}
-
-PyObject *KX_MouseFocusSensor::pyattr_get_ray_direction(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_MouseFocusSensor* self = static_cast<KX_MouseFocusSensor*>(self_v);
- MT_Vector3 dir = self->RayTarget() - self->RaySource();
- if (MT_fuzzyZero(dir)) dir.setValue(0,0,0);
- else dir.normalize();
- return PyObjectFrom(dir);
-}
-
-PyObject *KX_MouseFocusSensor::pyattr_get_hit_object(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_MouseFocusSensor* self = static_cast<KX_MouseFocusSensor*>(self_v);
-
- if (self->m_hitObject)
- return self->m_hitObject->GetProxy();
-
- Py_RETURN_NONE;
-}
-
-PyObject *KX_MouseFocusSensor::pyattr_get_hit_position(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_MouseFocusSensor* self = static_cast<KX_MouseFocusSensor*>(self_v);
- return PyObjectFrom(self->HitPosition());
-}
-
-PyObject *KX_MouseFocusSensor::pyattr_get_hit_normal(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_MouseFocusSensor* self = static_cast<KX_MouseFocusSensor*>(self_v);
- return PyObjectFrom(self->HitNormal());
-}
-
-PyObject *KX_MouseFocusSensor::pyattr_get_hit_uv(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_MouseFocusSensor* self = static_cast<KX_MouseFocusSensor*>(self_v);
- return PyObjectFrom(self->HitUV());
-}
-
-#endif // WITH_PYTHON
-
-/* eof */
-
diff --git a/source/gameengine/Ketsji/KX_MouseFocusSensor.h b/source/gameengine/Ketsji/KX_MouseFocusSensor.h
deleted file mode 100644
index dd9295b2ff4..00000000000
--- a/source/gameengine/Ketsji/KX_MouseFocusSensor.h
+++ /dev/null
@@ -1,208 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file KX_MouseFocusSensor.h
- * \ingroup ketsji
- * \brief KX_MouseFocusSensor determines mouse in/out/over events.
- */
-
-#ifndef __KX_MOUSEFOCUSSENSOR_H__
-#define __KX_MOUSEFOCUSSENSOR_H__
-
-#include "SCA_MouseSensor.h"
-
-#include "BLI_utildefines.h"
-
-class KX_RayCast;
-
-/**
- * The mouse focus sensor extends the basic SCA_MouseSensor. It has
- * been placed in KX because it needs access to the rasterizer and
- * SuMO.
- *
- * - extend the valid modes?
- * - */
-class KX_MouseFocusSensor : public SCA_MouseSensor
-{
-
- Py_Header
-
- public:
-
- KX_MouseFocusSensor(class SCA_MouseManager* eventmgr,
- int startx,
- int starty,
- short int mousemode,
- int focusmode,
- bool bTouchPulse,
- const STR_String& propname,
- bool bFindMaterial,
- bool bXRay,
- KX_Scene* kxscene,
- KX_KetsjiEngine* kxengine,
- SCA_IObject* gameobj);
-
- virtual ~KX_MouseFocusSensor() { }
- virtual CValue* GetReplica() {
- CValue* replica = new KX_MouseFocusSensor(*this);
- // this will copy properties and so on...
- replica->ProcessReplica();
- return replica;
- };
-
- virtual void Replace_IScene(SCA_IScene *val)
- {
- m_kxscene= static_cast<KX_Scene *>(val);
- };
-
-
- /**
- * \attention Overrides default evaluate.
- */
- virtual bool Evaluate();
- virtual void Init();
-
- virtual bool IsPositiveTrigger() {
- bool result = m_positive_event;
- if (m_invert) result = !result;
- return result;
- };
-
- /// \see KX_RayCast
- bool RayHit(KX_ClientObjectInfo *client, KX_RayCast *result, void *UNUSED(data));
- /// \see KX_RayCast
- bool NeedRayCast(KX_ClientObjectInfo *client, void *UNUSED(data));
-
- const MT_Point3& RaySource() const;
- const MT_Point3& RayTarget() const;
- const MT_Point3& HitPosition() const;
- const MT_Vector3& HitNormal() const;
- const MT_Vector2& HitUV() const;
-
-#ifdef WITH_PYTHON
-
- /* --------------------------------------------------------------------- */
- /* Python interface ---------------------------------------------------- */
- /* --------------------------------------------------------------------- */
-
- /* attributes */
- static PyObject* pyattr_get_ray_source(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_ray_target(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_ray_direction(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_hit_object(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_hit_position(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_hit_normal(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_hit_uv(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef);
-
-#endif /* WITH_PYTHON */
-
- /* --------------------------------------------------------------------- */
- SCA_IObject* m_hitObject;
- void* m_hitObject_Last; /* only use for comparison, never access */
-
- private:
- /**
- * The focus mode. 1 for handling focus, 0 for not handling, 2 for focus on any object
- */
- int m_focusmode;
-
- /**
- * Flags whether the previous test showed a mouse-over.
- */
- bool m_mouse_over_in_previous_frame;
-
- /**
- * Flags whether changes in hit object should trigger a pulse
- */
- bool m_bTouchPulse;
-
- /**
- * Flags get through other objects
- */
- bool m_bXRay;
-
- /**
- * Flags material
- */
- bool m_bFindMaterial;
-
- /**
- * Property or material name
- */
- STR_String m_propertyname;
-
- /**
- * Flags whether the previous test evaluated positive.
- */
- bool m_positive_event;
-
- /**
- * Tests whether the object is in mouse focus for this camera
- */
- bool ParentObjectHasFocusCamera(KX_Camera *cam);
-
- /**
- * Tests whether the object is in mouse focus in this scene.
- */
- bool ParentObjectHasFocus(void);
-
- /**
- * (in game world coordinates) the place where the object was hit.
- */
- MT_Point3 m_hitPosition;
-
- /**
- * (in game world coordinates) the position to which to shoot the ray.
- */
- MT_Point3 m_prevTargetPoint;
-
- /**
- * (in game world coordinates) the position from which to shoot the ray.
- */
- MT_Point3 m_prevSourcePoint;
-
- /**
- * (in game world coordinates) the face normal of the vertex where
- * the object was hit. */
- MT_Vector3 m_hitNormal;
-
- /**
- * UV texture coordinate of the hit point if any, (0,0) otherwise
- */
- MT_Vector2 m_hitUV;
-
- /**
- * The KX scene that holds the camera. The camera position
- * determines a part of the start location of the picking ray. */
- KX_Scene* m_kxscene;
-
- /**
- * The KX engine is needed for computing the viewport */
- KX_KetsjiEngine* m_kxengine;
-};
-
-#endif /* __KX_MOUSESENSOR */
diff --git a/source/gameengine/Ketsji/KX_NavMeshObject.cpp b/source/gameengine/Ketsji/KX_NavMeshObject.cpp
deleted file mode 100644
index 83accb1d7a5..00000000000
--- a/source/gameengine/Ketsji/KX_NavMeshObject.cpp
+++ /dev/null
@@ -1,747 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-#include "MEM_guardedalloc.h"
-
-#include "BLI_math_vector.h"
-#include "KX_NavMeshObject.h"
-#include "RAS_MeshObject.h"
-#include "RAS_Polygon.h"
-
-#include "DNA_mesh_types.h"
-#include "DNA_meshdata_types.h"
-
-extern "C" {
-#include "BKE_scene.h"
-#include "BKE_customdata.h"
-#include "BKE_cdderivedmesh.h"
-#include "BKE_DerivedMesh.h"
-#include "BKE_navmesh_conversion.h"
-}
-
-#include "KX_PythonInit.h"
-#include "KX_PyMath.h"
-#include "EXP_Value.h"
-#include "Recast.h"
-#include "DetourStatNavMeshBuilder.h"
-#include "KX_ObstacleSimulation.h"
-
-#define MAX_PATH_LEN 256
-static const float polyPickExt[3] = {2, 4, 2};
-
-static void calcMeshBounds(const float* vert, int nverts, float* bmin, float* bmax)
-{
- bmin[0] = bmax[0] = vert[0];
- bmin[1] = bmax[1] = vert[1];
- bmin[2] = bmax[2] = vert[2];
- for (int i=1; i<nverts; i++)
- {
- if (bmin[0]>vert[3*i+0]) bmin[0] = vert[3*i+0];
- if (bmin[1]>vert[3*i+1]) bmin[1] = vert[3*i+1];
- if (bmin[2]>vert[3*i+2]) bmin[2] = vert[3*i+2];
-
- if (bmax[0]<vert[3*i+0]) bmax[0] = vert[3*i+0];
- if (bmax[1]<vert[3*i+1]) bmax[1] = vert[3*i+1];
- if (bmax[2]<vert[3*i+2]) bmax[2] = vert[3*i+2];
- }
-}
-
-inline void flipAxes(float* vec)
-{
- std::swap(vec[1],vec[2]);
-}
-KX_NavMeshObject::KX_NavMeshObject(void* sgReplicationInfo, SG_Callbacks callbacks)
-: KX_GameObject(sgReplicationInfo, callbacks)
-, m_navMesh(NULL)
-{
-
-}
-
-KX_NavMeshObject::~KX_NavMeshObject()
-{
- if (m_navMesh)
- delete m_navMesh;
-}
-
-CValue* KX_NavMeshObject::GetReplica()
-{
- KX_NavMeshObject* replica = new KX_NavMeshObject(*this);
- replica->ProcessReplica();
- return replica;
-}
-
-void KX_NavMeshObject::ProcessReplica()
-{
- KX_GameObject::ProcessReplica();
- m_navMesh = NULL; /* without this, building frees the navmesh we copied from */
- if (!BuildNavMesh()) {
- std::cout << "Error in " << __func__ << ": unable to build navigation mesh" << std::endl;
- return;
- }
- KX_Scene* scene = KX_GetActiveScene();
- KX_ObstacleSimulation* obssimulation = scene->GetObstacleSimulation();
- if (obssimulation)
- obssimulation->AddObstaclesForNavMesh(this);
-}
-
-bool KX_NavMeshObject::BuildVertIndArrays(float *&vertices, int& nverts,
- unsigned short* &polys, int& npolys, unsigned short *&dmeshes,
- float *&dvertices, int &ndvertsuniq, unsigned short *&dtris,
- int& ndtris, int &vertsPerPoly)
-{
- /* TODO: This doesn't work currently because of eval_ctx. */
-#if 0
- DerivedMesh* dm = mesh_create_derived_no_virtual(GetScene()->GetBlenderScene(), GetBlenderObject(),
- NULL, CD_MASK_MESH);
- CustomData *pdata = dm->getPolyDataLayout(dm);
- int* recastData = (int*) CustomData_get_layer(pdata, CD_RECAST);
- if (recastData)
- {
- int *dtrisToPolysMap=NULL, *dtrisToTrisMap=NULL, *trisToFacesMap=NULL;
- int nAllVerts = 0;
- float *allVerts = NULL;
- buildNavMeshDataByDerivedMesh(dm, &vertsPerPoly, &nAllVerts, &allVerts, &ndtris, &dtris,
- &npolys, &dmeshes, &polys, &dtrisToPolysMap, &dtrisToTrisMap, &trisToFacesMap);
-
- MEM_SAFE_FREE(dtrisToPolysMap);
- MEM_SAFE_FREE(dtrisToTrisMap);
- MEM_SAFE_FREE(trisToFacesMap);
-
- unsigned short *verticesMap = (unsigned short *)MEM_mallocN(sizeof(*verticesMap) * nAllVerts, __func__);
- memset(verticesMap, 0xff, sizeof(*verticesMap) * nAllVerts);
- int curIdx = 0;
- //vertices - mesh verts
- //iterate over all polys and create map for their vertices first...
- for (int polyidx=0; polyidx<npolys; polyidx++)
- {
- unsigned short* poly = &polys[polyidx*vertsPerPoly*2];
- for (int i=0; i<vertsPerPoly; i++)
- {
- unsigned short idx = poly[i];
- if (idx==0xffff)
- break;
- if (verticesMap[idx]==0xffff)
- {
- verticesMap[idx] = curIdx++;
- }
- poly[i] = verticesMap[idx];
- }
- }
- nverts = curIdx;
- //...then iterate over detailed meshes
- //transform indices to local ones (for each navigation polygon)
- for (int polyidx=0; polyidx<npolys; polyidx++)
- {
- unsigned short *poly = &polys[polyidx*vertsPerPoly*2];
- int nv = polyNumVerts(poly, vertsPerPoly);
- unsigned short *dmesh = &dmeshes[4*polyidx];
- unsigned short tribase = dmesh[2];
- unsigned short trinum = dmesh[3];
- unsigned short vbase = curIdx;
- for (int j=0; j<trinum; j++)
- {
- unsigned short* dtri = &dtris[(tribase+j)*3*2];
- for (int k=0; k<3; k++)
- {
- int newVertexIdx = verticesMap[dtri[k]];
- if (newVertexIdx==0xffff)
- {
- newVertexIdx = curIdx++;
- verticesMap[dtri[k]] = newVertexIdx;
- }
-
- if (newVertexIdx<nverts)
- {
- //it's polygon vertex ("shared")
- int idxInPoly = polyFindVertex(poly, vertsPerPoly, newVertexIdx);
- if (idxInPoly==-1)
- {
- printf("Building NavMeshObject: Error! Can't find vertex in polygon\n");
- return false;
- }
- dtri[k] = idxInPoly;
- }
- else
- {
- dtri[k] = newVertexIdx - vbase + nv;
- }
- }
- }
- dmesh[0] = vbase-nverts; //verts base
- dmesh[1] = curIdx-vbase; //verts num
- }
-
- vertices = new float[nverts*3];
- ndvertsuniq = curIdx - nverts;
- if (ndvertsuniq>0)
- {
- dvertices = new float[ndvertsuniq*3];
- }
- for (int vi=0; vi<nAllVerts; vi++)
- {
- int newIdx = verticesMap[vi];
- if (newIdx!=0xffff)
- {
- if (newIdx<nverts)
- {
- //navigation mesh vertex
- memcpy(vertices+3*newIdx, allVerts+3*vi, 3*sizeof(float));
- }
- else
- {
- //detailed mesh vertex
- memcpy(dvertices+3*(newIdx-nverts), allVerts+3*vi, 3*sizeof(float));
- }
- }
- }
-
- MEM_SAFE_FREE(allVerts);
-
- MEM_freeN(verticesMap);
- }
- else
- {
- //create from RAS_MeshObject (detailed mesh is fake)
- RAS_MeshObject* meshobj = GetMesh(0);
- vertsPerPoly = 3;
- nverts = meshobj->m_sharedvertex_map.size();
- if (nverts >= 0xffff)
- return false;
- //calculate count of tris
- int nmeshpolys = meshobj->NumPolygons();
- npolys = nmeshpolys;
- for (int p=0; p<nmeshpolys; p++)
- {
- int vertcount = meshobj->GetPolygon(p)->VertexCount();
- npolys+=vertcount-3;
- }
-
- //create verts
- vertices = new float[nverts*3];
- float* vert = vertices;
- for (int vi=0; vi<nverts; vi++)
- {
- const float* pos = !meshobj->m_sharedvertex_map[vi].empty() ? meshobj->GetVertexLocation(vi) : NULL;
- if (pos)
- copy_v3_v3(vert, pos);
- else
- {
- memset(vert, 0, 3*sizeof(float)); //vertex isn't in any poly, set dummy zero coordinates
- }
- vert+=3;
- }
-
- //create tris
- polys = (unsigned short *)MEM_callocN(sizeof(unsigned short)*3*2*npolys, "BuildVertIndArrays polys");
- memset(polys, 0xff, sizeof(unsigned short)*3*2*npolys);
- unsigned short *poly = polys;
- RAS_Polygon* raspoly;
- for (int p=0; p<nmeshpolys; p++)
- {
- raspoly = meshobj->GetPolygon(p);
- for (int v=0; v<raspoly->VertexCount()-2; v++)
- {
- poly[0] = raspoly->GetVertex(0)->getOrigIndex();
- for (size_t i=1; i<3; i++)
- {
- poly[i] = raspoly->GetVertex(v+i)->getOrigIndex();
- }
- poly += 6;
- }
- }
- dmeshes = NULL;
- dvertices = NULL;
- ndvertsuniq = 0;
- dtris = NULL;
- ndtris = npolys;
- }
- dm->release(dm);
-
- return true;
-#endif
- return false;
-}
-
-
-bool KX_NavMeshObject::BuildNavMesh()
-{
- if (m_navMesh)
- {
- delete m_navMesh;
- m_navMesh = NULL;
- }
-
- if (GetMeshCount()==0)
- {
- printf("Can't find mesh for navmesh object: %s\n", m_name.ReadPtr());
- return false;
- }
-
- float *vertices = NULL, *dvertices = NULL;
- unsigned short *polys = NULL, *dtris = NULL, *dmeshes = NULL;
- int nverts = 0, npolys = 0, ndvertsuniq = 0, ndtris = 0;
- int vertsPerPoly = 0;
- if (!BuildVertIndArrays(vertices, nverts, polys, npolys,
- dmeshes, dvertices, ndvertsuniq, dtris, ndtris, vertsPerPoly )
- || vertsPerPoly<3)
- {
- printf("Can't build navigation mesh data for object:%s\n", m_name.ReadPtr());
- if (vertices) {
- delete[] vertices;
- }
- if (dvertices) {
- delete[] dvertices;
- }
- return false;
- }
-
- MT_Point3 pos;
- if (dmeshes==NULL)
- {
- for (int i=0; i<nverts; i++)
- {
- flipAxes(&vertices[i*3]);
- }
- for (int i=0; i<ndvertsuniq; i++)
- {
- flipAxes(&dvertices[i*3]);
- }
- }
-
- if (!buildMeshAdjacency(polys, npolys, nverts, vertsPerPoly)) {
- std::cout << __func__ << ": unable to build mesh adjacency information." << std::endl;
- delete[] vertices;
- return false;
- }
-
- float cs = 0.2f;
-
- if (!nverts || !npolys)
- {
- if (vertices) delete[] vertices;
- return false;
- }
-
- float bmin[3], bmax[3];
- calcMeshBounds(vertices, nverts, bmin, bmax);
- //quantize vertex pos
- unsigned short* vertsi = new unsigned short[3*nverts];
- float ics = 1.f/cs;
- for (int i=0; i<nverts; i++)
- {
- vertsi[3*i+0] = static_cast<unsigned short>((vertices[3*i+0]-bmin[0])*ics);
- vertsi[3*i+1] = static_cast<unsigned short>((vertices[3*i+1]-bmin[1])*ics);
- vertsi[3*i+2] = static_cast<unsigned short>((vertices[3*i+2]-bmin[2])*ics);
- }
-
- // Calculate data size
- const int headerSize = sizeof(dtStatNavMeshHeader);
- const int vertsSize = sizeof(float)*3*nverts;
- const int polysSize = sizeof(dtStatPoly)*npolys;
- const int nodesSize = sizeof(dtStatBVNode)*npolys*2;
- const int detailMeshesSize = sizeof(dtStatPolyDetail)*npolys;
- const int detailVertsSize = sizeof(float)*3*ndvertsuniq;
- const int detailTrisSize = sizeof(unsigned char)*4*ndtris;
-
- const int dataSize = headerSize + vertsSize + polysSize + nodesSize +
- detailMeshesSize + detailVertsSize + detailTrisSize;
- unsigned char* data = new unsigned char[dataSize];
- if (!data)
- return false;
- memset(data, 0, dataSize);
-
- unsigned char* d = data;
- dtStatNavMeshHeader* header = (dtStatNavMeshHeader*)d; d += headerSize;
- float* navVerts = (float*)d; d += vertsSize;
- dtStatPoly* navPolys = (dtStatPoly*)d; d += polysSize;
- dtStatBVNode* navNodes = (dtStatBVNode*)d; d += nodesSize;
- dtStatPolyDetail* navDMeshes = (dtStatPolyDetail*)d; d += detailMeshesSize;
- float* navDVerts = (float*)d; d += detailVertsSize;
- unsigned char* navDTris = (unsigned char*)d; d += detailTrisSize;
-
- // Store header
- header->magic = DT_STAT_NAVMESH_MAGIC;
- header->version = DT_STAT_NAVMESH_VERSION;
- header->npolys = npolys;
- header->nverts = nverts;
- header->cs = cs;
- header->bmin[0] = bmin[0];
- header->bmin[1] = bmin[1];
- header->bmin[2] = bmin[2];
- header->bmax[0] = bmax[0];
- header->bmax[1] = bmax[1];
- header->bmax[2] = bmax[2];
- header->ndmeshes = npolys;
- header->ndverts = ndvertsuniq;
- header->ndtris = ndtris;
-
- // Store vertices
- for (int i = 0; i < nverts; ++i)
- {
- const unsigned short* iv = &vertsi[i*3];
- float* v = &navVerts[i*3];
- v[0] = bmin[0] + iv[0] * cs;
- v[1] = bmin[1] + iv[1] * cs;
- v[2] = bmin[2] + iv[2] * cs;
- }
- //memcpy(navVerts, vertices, nverts*3*sizeof(float));
-
- // Store polygons
- const unsigned short* src = polys;
- for (int i = 0; i < npolys; ++i)
- {
- dtStatPoly* p = &navPolys[i];
- p->nv = 0;
- for (int j = 0; j < vertsPerPoly; ++j)
- {
- if (src[j] == 0xffff) break;
- p->v[j] = src[j];
- p->n[j] = src[vertsPerPoly+j]+1;
- p->nv++;
- }
- src += vertsPerPoly*2;
- }
-
- header->nnodes = createBVTree(vertsi, nverts, polys, npolys, vertsPerPoly,
- cs, cs, npolys*2, navNodes);
-
-
- if (dmeshes==NULL)
- {
- //create fake detail meshes
- for (int i = 0; i < npolys; ++i)
- {
- dtStatPolyDetail& dtl = navDMeshes[i];
- dtl.vbase = 0;
- dtl.nverts = 0;
- dtl.tbase = i;
- dtl.ntris = 1;
- }
- // setup triangles.
- unsigned char* tri = navDTris;
- for (size_t i=0; i<ndtris; i++)
- {
- for (size_t j=0; j<3; j++)
- tri[4*i+j] = j;
- }
- }
- else
- {
- //verts
- memcpy(navDVerts, dvertices, ndvertsuniq*3*sizeof(float));
- //tris
- unsigned char* tri = navDTris;
- for (size_t i=0; i<ndtris; i++)
- {
- for (size_t j=0; j<3; j++)
- tri[4*i+j] = dtris[6*i+j];
- }
- //detailed meshes
- for (int i = 0; i < npolys; ++i)
- {
- dtStatPolyDetail& dtl = navDMeshes[i];
- dtl.vbase = dmeshes[i*4+0];
- dtl.nverts = dmeshes[i*4+1];
- dtl.tbase = dmeshes[i*4+2];
- dtl.ntris = dmeshes[i*4+3];
- }
- }
-
- m_navMesh = new dtStatNavMesh;
- m_navMesh->init(data, dataSize, true);
-
- delete [] vertices;
-
- /* navmesh conversion is using C guarded alloc for memory allocaitons */
- MEM_freeN(polys);
- if (dmeshes) MEM_freeN(dmeshes);
- if (dtris) MEM_freeN(dtris);
-
- if (dvertices)
- delete [] dvertices;
-
- if (vertsi)
- delete [] vertsi;
-
- return true;
-}
-
-dtStatNavMesh* KX_NavMeshObject::GetNavMesh()
-{
- return m_navMesh;
-}
-
-void KX_NavMeshObject::DrawNavMesh(NavMeshRenderMode renderMode)
-{
- if (!m_navMesh)
- return;
- MT_Vector3 color(0.f, 0.f, 0.f);
-
- switch (renderMode)
- {
- case RM_POLYS :
- case RM_WALLS :
- for (int pi=0; pi<m_navMesh->getPolyCount(); pi++)
- {
- const dtStatPoly* poly = m_navMesh->getPoly(pi);
-
- for (int i = 0, j = (int)poly->nv-1; i < (int)poly->nv; j = i++)
- {
- if (poly->n[j] && renderMode==RM_WALLS)
- continue;
- const float* vif = m_navMesh->getVertex(poly->v[i]);
- const float* vjf = m_navMesh->getVertex(poly->v[j]);
- MT_Point3 vi(vif[0], vif[2], vif[1]);
- MT_Point3 vj(vjf[0], vjf[2], vjf[1]);
- vi = TransformToWorldCoords(vi);
- vj = TransformToWorldCoords(vj);
- KX_RasterizerDrawDebugLine(vi, vj, color);
- }
- }
- break;
- case RM_TRIS :
- for (int i = 0; i < m_navMesh->getPolyDetailCount(); ++i)
- {
- const dtStatPoly* p = m_navMesh->getPoly(i);
- const dtStatPolyDetail* pd = m_navMesh->getPolyDetail(i);
-
- for (int j = 0; j < pd->ntris; ++j)
- {
- const unsigned char* t = m_navMesh->getDetailTri(pd->tbase+j);
- MT_Point3 tri[3];
- for (int k = 0; k < 3; ++k)
- {
- const float* v;
- if (t[k] < p->nv)
- v = m_navMesh->getVertex(p->v[t[k]]);
- else
- v = m_navMesh->getDetailVertex(pd->vbase+(t[k]-p->nv));
- float pos[3];
- rcVcopy(pos, v);
- flipAxes(pos);
- tri[k].setValue(pos);
- }
-
- for (int k=0; k<3; k++)
- tri[k] = TransformToWorldCoords(tri[k]);
-
- for (int k=0; k<3; k++)
- KX_RasterizerDrawDebugLine(tri[k], tri[(k+1)%3], color);
- }
- }
- break;
- default:
- /* pass */
- break;
- }
-}
-
-MT_Point3 KX_NavMeshObject::TransformToLocalCoords(const MT_Point3& wpos)
-{
- MT_Matrix3x3 orientation = NodeGetWorldOrientation();
- const MT_Vector3& scaling = NodeGetWorldScaling();
- orientation.scale(scaling[0], scaling[1], scaling[2]);
- MT_Transform worldtr(NodeGetWorldPosition(), orientation);
- MT_Transform invworldtr;
- invworldtr.invert(worldtr);
- MT_Point3 lpos = invworldtr(wpos);
- return lpos;
-}
-
-MT_Point3 KX_NavMeshObject::TransformToWorldCoords(const MT_Point3& lpos)
-{
- MT_Matrix3x3 orientation = NodeGetWorldOrientation();
- const MT_Vector3& scaling = NodeGetWorldScaling();
- orientation.scale(scaling[0], scaling[1], scaling[2]);
- MT_Transform worldtr(NodeGetWorldPosition(), orientation);
- MT_Point3 wpos = worldtr(lpos);
- return wpos;
-}
-
-int KX_NavMeshObject::FindPath(const MT_Point3& from, const MT_Point3& to, float* path, int maxPathLen)
-{
- if (!m_navMesh)
- return 0;
- MT_Point3 localfrom = TransformToLocalCoords(from);
- MT_Point3 localto = TransformToLocalCoords(to);
- float spos[3], epos[3];
- localfrom.getValue(spos); flipAxes(spos);
- localto.getValue(epos); flipAxes(epos);
- dtStatPolyRef sPolyRef = m_navMesh->findNearestPoly(spos, polyPickExt);
- dtStatPolyRef ePolyRef = m_navMesh->findNearestPoly(epos, polyPickExt);
-
- int pathLen = 0;
- if (sPolyRef && ePolyRef)
- {
- dtStatPolyRef* polys = new dtStatPolyRef[maxPathLen];
- int npolys;
- npolys = m_navMesh->findPath(sPolyRef, ePolyRef, spos, epos, polys, maxPathLen);
- if (npolys)
- {
- pathLen = m_navMesh->findStraightPath(spos, epos, polys, npolys, path, maxPathLen);
- for (int i=0; i<pathLen; i++)
- {
- flipAxes(&path[i*3]);
- MT_Point3 waypoint(&path[i*3]);
- waypoint = TransformToWorldCoords(waypoint);
- waypoint.getValue(&path[i*3]);
- }
- }
-
- delete[] polys;
- }
-
- return pathLen;
-}
-
-float KX_NavMeshObject::Raycast(const MT_Point3& from, const MT_Point3& to)
-{
- if (!m_navMesh)
- return 0.f;
- MT_Point3 localfrom = TransformToLocalCoords(from);
- MT_Point3 localto = TransformToLocalCoords(to);
- float spos[3], epos[3];
- localfrom.getValue(spos); flipAxes(spos);
- localto.getValue(epos); flipAxes(epos);
- dtStatPolyRef sPolyRef = m_navMesh->findNearestPoly(spos, polyPickExt);
- float t=0;
- static dtStatPolyRef polys[MAX_PATH_LEN];
- m_navMesh->raycast(sPolyRef, spos, epos, t, polys, MAX_PATH_LEN);
- return t;
-}
-
-void KX_NavMeshObject::DrawPath(const float *path, int pathLen, const MT_Vector3& color)
-{
- MT_Vector3 a,b;
- for (int i=0; i<pathLen-1; i++)
- {
- a.setValue(&path[3*i]);
- b.setValue(&path[3*(i+1)]);
- KX_RasterizerDrawDebugLine(a, b, color);
- }
-}
-
-
-#ifdef WITH_PYTHON
-//----------------------------------------------------------------------------
-//Python
-
-PyTypeObject KX_NavMeshObject::Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "KX_NavMeshObject",
- sizeof(PyObjectPlus_Proxy),
- 0,
- py_base_dealloc,
- 0,
- 0,
- 0,
- 0,
- py_base_repr,
- 0,
- 0,
- 0,
- 0,0,0,0,0,0,
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
- 0,0,0,0,0,0,0,
- Methods,
- 0,
- 0,
- &KX_GameObject::Type,
- 0,0,0,0,0,0,
- py_base_new
-};
-
-PyAttributeDef KX_NavMeshObject::Attributes[] = {
- { NULL } //Sentinel
-};
-
-//KX_PYMETHODTABLE_NOARGS(KX_GameObject, getD),
-PyMethodDef KX_NavMeshObject::Methods[] = {
- KX_PYMETHODTABLE(KX_NavMeshObject, findPath),
- KX_PYMETHODTABLE(KX_NavMeshObject, raycast),
- KX_PYMETHODTABLE(KX_NavMeshObject, draw),
- KX_PYMETHODTABLE(KX_NavMeshObject, rebuild),
- {NULL,NULL} //Sentinel
-};
-
-KX_PYMETHODDEF_DOC(KX_NavMeshObject, findPath,
- "findPath(start, goal): find path from start to goal points\n"
- "Returns a path as list of points)\n")
-{
- PyObject *ob_from, *ob_to;
- if (!PyArg_ParseTuple(args,"OO:getPath",&ob_from,&ob_to))
- return NULL;
- MT_Point3 from, to;
- if (!PyVecTo(ob_from, from) || !PyVecTo(ob_to, to))
- return NULL;
-
- float path[MAX_PATH_LEN*3];
- int pathLen = FindPath(from, to, path, MAX_PATH_LEN);
- PyObject *pathList = PyList_New( pathLen );
- for (int i=0; i<pathLen; i++)
- {
- MT_Point3 point(&path[3*i]);
- PyList_SET_ITEM(pathList, i, PyObjectFrom(point));
- }
-
- return pathList;
-}
-
-KX_PYMETHODDEF_DOC(KX_NavMeshObject, raycast,
- "raycast(start, goal): raycast from start to goal points\n"
- "Returns hit factor)\n")
-{
- PyObject *ob_from, *ob_to;
- if (!PyArg_ParseTuple(args,"OO:getPath",&ob_from,&ob_to))
- return NULL;
- MT_Point3 from, to;
- if (!PyVecTo(ob_from, from) || !PyVecTo(ob_to, to))
- return NULL;
- float hit = Raycast(from, to);
- return PyFloat_FromDouble(hit);
-}
-
-KX_PYMETHODDEF_DOC(KX_NavMeshObject, draw,
- "draw(mode): navigation mesh debug drawing\n"
- "mode: WALLS, POLYS, TRIS\n")
-{
- int arg;
- NavMeshRenderMode renderMode = RM_TRIS;
- if (PyArg_ParseTuple(args,"i:rebuild",&arg) && arg>=0 && arg<RM_MAX)
- renderMode = (NavMeshRenderMode)arg;
- DrawNavMesh(renderMode);
- Py_RETURN_NONE;
-}
-
-KX_PYMETHODDEF_DOC_NOARGS(KX_NavMeshObject, rebuild,
- "rebuild(): rebuild navigation mesh\n")
-{
- BuildNavMesh();
- Py_RETURN_NONE;
-}
-
-#endif // WITH_PYTHON
diff --git a/source/gameengine/Ketsji/KX_NavMeshObject.h b/source/gameengine/Ketsji/KX_NavMeshObject.h
deleted file mode 100644
index af178f9aaee..00000000000
--- a/source/gameengine/Ketsji/KX_NavMeshObject.h
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-#ifndef __KX_NAVMESHOBJECT_H__
-#define __KX_NAVMESHOBJECT_H__
-#include "DetourStatNavMesh.h"
-#include "KX_GameObject.h"
-#include "EXP_PyObjectPlus.h"
-#include <vector>
-
-class RAS_MeshObject;
-class MT_Transform;
-
-class KX_NavMeshObject: public KX_GameObject
-{
- Py_Header
-
-protected:
- dtStatNavMesh* m_navMesh;
-
- bool BuildVertIndArrays(float *&vertices, int& nverts,
- unsigned short* &polys, int& npolys, unsigned short *&dmeshes,
- float *&dvertices, int &ndvertsuniq, unsigned short* &dtris,
- int& ndtris, int &vertsPerPoly);
-
-public:
- KX_NavMeshObject(void* sgReplicationInfo, SG_Callbacks callbacks);
- ~KX_NavMeshObject();
-
- virtual CValue* GetReplica();
- virtual void ProcessReplica();
-
-
- bool BuildNavMesh();
- dtStatNavMesh* GetNavMesh();
- int FindPath(const MT_Point3& from, const MT_Point3& to, float* path, int maxPathLen);
- float Raycast(const MT_Point3& from, const MT_Point3& to);
-
- enum NavMeshRenderMode {RM_WALLS, RM_POLYS, RM_TRIS, RM_MAX};
- void DrawNavMesh(NavMeshRenderMode mode);
- void DrawPath(const float *path, int pathLen, const MT_Vector3& color);
-
- MT_Point3 TransformToLocalCoords(const MT_Point3& wpos);
- MT_Point3 TransformToWorldCoords(const MT_Point3& lpos);
-#ifdef WITH_PYTHON
- /* --------------------------------------------------------------------- */
- /* Python interface ---------------------------------------------------- */
- /* --------------------------------------------------------------------- */
-
- KX_PYMETHOD_DOC(KX_NavMeshObject, findPath);
- KX_PYMETHOD_DOC(KX_NavMeshObject, raycast);
- KX_PYMETHOD_DOC(KX_NavMeshObject, draw);
- KX_PYMETHOD_DOC_NOARGS(KX_NavMeshObject, rebuild);
-#endif /* WITH_PYTHON */
-};
-
-#endif /* __KX_NAVMESHOBJECT_H__ */
diff --git a/source/gameengine/Ketsji/KX_NearSensor.cpp b/source/gameengine/Ketsji/KX_NearSensor.cpp
deleted file mode 100644
index 92ab8f412d9..00000000000
--- a/source/gameengine/Ketsji/KX_NearSensor.cpp
+++ /dev/null
@@ -1,292 +0,0 @@
-/*
- * Sense if other objects are near
- *
- *
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Ketsji/KX_NearSensor.cpp
- * \ingroup ketsji
- */
-
-
-#include "KX_NearSensor.h"
-#include "SCA_LogicManager.h"
-#include "KX_GameObject.h"
-#include "KX_TouchEventManager.h"
-#include "KX_Scene.h" // needed to create a replica
-#include "PHY_IPhysicsEnvironment.h"
-#include "PHY_IPhysicsController.h"
-#include "PHY_IMotionState.h"
-
-KX_NearSensor::KX_NearSensor(SCA_EventManager* eventmgr,
- KX_GameObject* gameobj,
- float margin,
- float resetmargin,
- bool bFindMaterial,
- const STR_String& touchedpropname,
- PHY_IPhysicsController* ctrl)
- :KX_TouchSensor(eventmgr,
- gameobj,
- bFindMaterial,
- false,
- touchedpropname),
- m_Margin(margin),
- m_ResetMargin(resetmargin)
-
-{
-
- gameobj->getClientInfo()->m_sensors.remove(this);
- m_client_info = new KX_ClientObjectInfo(gameobj, KX_ClientObjectInfo::SENSOR);
- m_client_info->m_sensors.push_back(this);
-
- //DT_ShapeHandle shape = (DT_ShapeHandle) vshape;
- m_physCtrl = ctrl;
- if (m_physCtrl)
- {
- m_physCtrl->SetMargin(m_Margin);
- m_physCtrl->SetNewClientInfo(m_client_info);
- }
- SynchronizeTransform();
-}
-
-void KX_NearSensor::SynchronizeTransform()
-{
- // The near and radar sensors are using a different physical object which is
- // not linked to the parent object, must synchronize it.
- if (m_physCtrl)
- {
- PHY_IMotionState* motionState = m_physCtrl->GetMotionState();
- KX_GameObject* parent = ((KX_GameObject*)GetParent());
- const MT_Point3& pos = parent->NodeGetWorldPosition();
- float ori[12];
- parent->NodeGetWorldOrientation().getValue(ori);
- motionState->SetWorldPosition(pos[0], pos[1], pos[2]);
- motionState->SetWorldOrientation(ori);
- m_physCtrl->WriteMotionStateToDynamics(true);
- }
-}
-
-CValue* KX_NearSensor::GetReplica()
-{
- KX_NearSensor* replica = new KX_NearSensor(*this);
- replica->ProcessReplica();
- return replica;
-}
-
-void KX_NearSensor::ProcessReplica()
-{
- KX_TouchSensor::ProcessReplica();
-
- m_client_info = new KX_ClientObjectInfo(m_client_info->m_gameobject, KX_ClientObjectInfo::SENSOR);
-
- if (m_physCtrl)
- {
- m_physCtrl = m_physCtrl->GetReplicaForSensors();
- if (m_physCtrl)
- {
- //static_cast<KX_TouchEventManager*>(m_eventmgr)->GetPhysicsEnvironment()->addSensor(replica->m_physCtrl);
- m_physCtrl->SetMargin(m_Margin);
- m_physCtrl->SetNewClientInfo(m_client_info);
- }
-
- }
-}
-
-void KX_NearSensor::ReParent(SCA_IObject* parent)
-{
- SCA_ISensor::ReParent(parent);
- m_client_info->m_gameobject = static_cast<KX_GameObject*>(parent);
- m_client_info->m_sensors.push_back(this);
- //Synchronize here with the actual parent.
- SynchronizeTransform();
-}
-
-
-
-KX_NearSensor::~KX_NearSensor()
-{
- // for nearsensor, the sensor is the 'owner' of sumoobj
- // for touchsensor, it's the parent
- if (m_physCtrl)
- {
- //static_cast<KX_TouchEventManager*>(m_eventmgr)->GetPhysicsEnvironment()->removeSensor(m_physCtrl);
- delete m_physCtrl;
- m_physCtrl = NULL;
- }
-
-
- if (m_client_info)
- delete m_client_info;
-}
-
-void KX_NearSensor::SetPhysCtrlRadius()
-{
- if (m_bTriggered)
- {
- if (m_physCtrl)
- {
- m_physCtrl->SetRadius(m_ResetMargin);
- }
- } else
- {
- if (m_physCtrl)
- {
- m_physCtrl->SetRadius(m_Margin);
- }
- }
-}
-
-bool KX_NearSensor::Evaluate()
-{
- bool result = false;
-// KX_GameObject* parent = static_cast<KX_GameObject*>(GetParent());
-
- if (m_bTriggered != m_bLastTriggered)
- {
- m_bLastTriggered = m_bTriggered;
-
- SetPhysCtrlRadius();
-
- result = true;
- }
-
- return result;
-}
-
-// this function is called at broad phase stage to check if the two controller
-// need to interact at all. It is used for Near/Radar sensor that don't need to
-// check collision with object not included in filter
-bool KX_NearSensor::BroadPhaseFilterCollision(void*obj1,void*obj2)
-{
- KX_GameObject* parent = static_cast<KX_GameObject*>(GetParent());
-
- // need the mapping from PHY_IPhysicsController to gameobjects now
- assert(obj1==m_physCtrl && obj2);
- KX_ClientObjectInfo *client_info = static_cast<KX_ClientObjectInfo*>((static_cast<PHY_IPhysicsController*>(obj2))->GetNewClientInfo());
-
- KX_GameObject* gameobj = ( client_info ?
- client_info->m_gameobject :
- NULL);
-
- if (gameobj && (gameobj != parent))
- {
- // only take valid colliders
- if (client_info->m_type == KX_ClientObjectInfo::ACTOR)
- {
- if ((m_touchedpropname.Length() == 0) ||
- (gameobj->GetProperty(m_touchedpropname)))
- {
- return true;
- }
- }
- }
-
- return false;
-}
-
-bool KX_NearSensor::NewHandleCollision(void *obj1, void *obj2, const PHY_CollData *coll_data)
-{
-// KX_TouchEventManager* toucheventmgr = static_cast<KX_TouchEventManager*>(m_eventmgr);
-// KX_GameObject* parent = static_cast<KX_GameObject*>(GetParent());
-
- // need the mapping from PHY_IPhysicsController to gameobjects now
-
- KX_ClientObjectInfo *client_info = static_cast<KX_ClientObjectInfo*> (obj1 == m_physCtrl?
- ((PHY_IPhysicsController*)obj2)->GetNewClientInfo() :
- ((PHY_IPhysicsController*)obj1)->GetNewClientInfo());
-
- KX_GameObject* gameobj = ( client_info ?
- client_info->m_gameobject :
- NULL);
-
- // Add the same check as in SCA_ISensor::Activate(),
- // we don't want to record collision when the sensor is not active.
- if (m_links && !m_suspended &&
- gameobj /* done in BroadPhaseFilterCollision() && (gameobj != parent)*/)
- {
- if (!m_colliders->SearchValue(gameobj))
- m_colliders->Add(gameobj->AddRef());
- // only take valid colliders
- // These checks are done already in BroadPhaseFilterCollision()
- //if (client_info->m_type == KX_ClientObjectInfo::ACTOR)
- //{
- // if ((m_touchedpropname.Length() == 0) ||
- // (gameobj->GetProperty(m_touchedpropname)))
- // {
- m_bTriggered = true;
- m_hitObject = gameobj;
- // }
- //}
- }
-
- return false; // was DT_CONTINUE; but this was defined in Sumo as false
-}
-
-#ifdef WITH_PYTHON
-
-/* ------------------------------------------------------------------------- */
-/* Python Functions */
-/* ------------------------------------------------------------------------- */
-
-/* ------------------------------------------------------------------------- */
-/* Python Integration Hooks */
-/* ------------------------------------------------------------------------- */
-
-PyTypeObject KX_NearSensor::Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "KX_NearSensor",
- sizeof(PyObjectPlus_Proxy),
- 0,
- py_base_dealloc,
- 0,
- 0,
- 0,
- 0,
- py_base_repr,
- 0,0,0,0,0,0,0,0,0,
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
- 0,0,0,0,0,0,0,
- Methods,
- 0,
- 0,
- &KX_TouchSensor::Type,
- 0,0,0,0,0,0,
- py_base_new
-};
-
-PyMethodDef KX_NearSensor::Methods[] = {
- //No methods
- {NULL,NULL} //Sentinel
-};
-
-PyAttributeDef KX_NearSensor::Attributes[] = {
- KX_PYATTRIBUTE_FLOAT_RW_CHECK("distance", 0, 10000, KX_NearSensor, m_Margin, CheckResetDistance),
- KX_PYATTRIBUTE_FLOAT_RW_CHECK("resetDistance", 0, 10000, KX_NearSensor, m_ResetMargin, CheckResetDistance),
- {NULL} //Sentinel
-};
-
-#endif // WITH_PYTHON
diff --git a/source/gameengine/Ketsji/KX_NearSensor.h b/source/gameengine/Ketsji/KX_NearSensor.h
deleted file mode 100644
index ef6e15f602f..00000000000
--- a/source/gameengine/Ketsji/KX_NearSensor.h
+++ /dev/null
@@ -1,107 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file KX_NearSensor.h
- * \ingroup ketsji
- * \brief Sense if other objects are near
- */
-
-#ifndef __KX_NEARSENSOR_H__
-#define __KX_NEARSENSOR_H__
-
-#include "KX_TouchSensor.h"
-#include "KX_ClientObjectInfo.h"
-
-class KX_Scene;
-struct PHY_CollData;
-
-class KX_NearSensor : public KX_TouchSensor
-{
- Py_Header
-protected:
- float m_Margin;
- float m_ResetMargin;
-
- KX_ClientObjectInfo* m_client_info;
-public:
- KX_NearSensor(class SCA_EventManager* eventmgr,
- class KX_GameObject* gameobj,
- float margin,
- float resetmargin,
- bool bFindMaterial,
- const STR_String& touchedpropname,
- PHY_IPhysicsController* ctrl);
-#if 0
-public:
- KX_NearSensor(class SCA_EventManager* eventmgr,
- class KX_GameObject* gameobj,
- double margin,
- double resetmargin,
- bool bFindMaterial,
- const STR_String& touchedpropname,
- class KX_Scene* scene);
-#endif
- virtual ~KX_NearSensor();
- virtual void SynchronizeTransform();
- virtual CValue* GetReplica();
- virtual void ProcessReplica();
- virtual void SetPhysCtrlRadius();
- virtual bool Evaluate();
-
- virtual void ReParent(SCA_IObject* parent);
- virtual bool NewHandleCollision(void* obj1,void* obj2,
- const PHY_CollData * coll_data);
- virtual bool BroadPhaseFilterCollision(void*obj1,void*obj2);
- virtual bool BroadPhaseSensorFilterCollision(void* obj1,void* obj2) { return false; }
- virtual sensortype GetSensorType() { return ST_NEAR; }
-
-#ifdef WITH_PYTHON
-
- /* --------------------------------------------------------------------- */
- /* Python interface ---------------------------------------------------- */
- /* --------------------------------------------------------------------- */
-
- //No methods
-
- //This method is used to make sure the distance does not exceed the reset distance
- static int CheckResetDistance(void *self, const PyAttributeDef*)
- {
- KX_NearSensor* sensor = reinterpret_cast<KX_NearSensor*>(self);
-
- if (sensor->m_Margin > sensor->m_ResetMargin)
- sensor->m_ResetMargin = sensor->m_Margin;
-
- sensor->SetPhysCtrlRadius();
-
- return 0;
- }
-
-#endif /* WITH_PYTHON */
-
-};
-
-#endif /* __KX_NEARSENSOR_H__ */
diff --git a/source/gameengine/Ketsji/KX_ObColorIpoSGController.cpp b/source/gameengine/Ketsji/KX_ObColorIpoSGController.cpp
deleted file mode 100644
index 7f81f221c07..00000000000
--- a/source/gameengine/Ketsji/KX_ObColorIpoSGController.cpp
+++ /dev/null
@@ -1,110 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Ketsji/KX_ObColorIpoSGController.cpp
- * \ingroup ketsji
- */
-
-
-#include "KX_ObColorIpoSGController.h"
-#include "KX_ScalarInterpolator.h"
-#include "KX_GameObject.h"
-
-#if defined(_WIN64)
-typedef unsigned __int64 uint_ptr;
-#else
-typedef unsigned long uint_ptr;
-#endif
-
-
-bool KX_ObColorIpoSGController::Update(double currentTime)
-{
- if (m_modified)
- {
- SG_Spatial* ob = (SG_Spatial*)m_pObject;
- KX_GameObject* kxgameobj= (KX_GameObject*) ob->GetSGClientObject();
-
- m_rgba = kxgameobj->GetObjectColor();
-
- T_InterpolatorList::iterator i;
- for (i = m_interpolators.begin(); !(i == m_interpolators.end()); ++i) {
- (*i)->Execute(m_ipotime);
- }
-
-
- kxgameobj->SetObjectColor(m_rgba);
-
-
- m_modified=false;
- }
- return false;
-}
-
-
-void KX_ObColorIpoSGController::AddInterpolator(KX_IInterpolator* interp)
-{
- this->m_interpolators.push_back(interp);
-}
-
-SG_Controller* KX_ObColorIpoSGController::GetReplica(class SG_Node* destnode)
-{
- KX_ObColorIpoSGController* iporeplica = new KX_ObColorIpoSGController(*this);
- // clear object that ipo acts on
- iporeplica->ClearObject();
-
- // dirty hack, ask Gino for a better solution in the ipo implementation
- // hacken en zagen, in what we call datahiding, not written for replication :(
-
- T_InterpolatorList oldlist = m_interpolators;
- iporeplica->m_interpolators.clear();
-
- T_InterpolatorList::iterator i;
- for (i = oldlist.begin(); !(i == oldlist.end()); ++i) {
- KX_ScalarInterpolator* copyipo = new KX_ScalarInterpolator(*((KX_ScalarInterpolator*)*i));
- iporeplica->AddInterpolator(copyipo);
-
- MT_Scalar* scaal = ((KX_ScalarInterpolator*)*i)->GetTarget();
- uint_ptr orgbase = (uint_ptr)this;
- uint_ptr orgloc = (uint_ptr)scaal;
- uint_ptr offset = orgloc-orgbase;
- uint_ptr newaddrbase = (uint_ptr)iporeplica + offset;
- MT_Scalar* blaptr = (MT_Scalar*) newaddrbase;
- copyipo->SetNewTarget((MT_Scalar*)blaptr);
- }
-
- return iporeplica;
-}
-
-KX_ObColorIpoSGController::~KX_ObColorIpoSGController()
-{
-
- T_InterpolatorList::iterator i;
- for (i = m_interpolators.begin(); !(i == m_interpolators.end()); ++i) {
- delete (*i);
- }
-
-}
diff --git a/source/gameengine/Ketsji/KX_ObColorIpoSGController.h b/source/gameengine/Ketsji/KX_ObColorIpoSGController.h
deleted file mode 100644
index a7b0b2c4ffc..00000000000
--- a/source/gameengine/Ketsji/KX_ObColorIpoSGController.h
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file KX_ObColorIpoSGController.h
- * \ingroup ketsji
- */
-
-#ifndef __KX_OBCOLORIPOSGCONTROLLER_H__
-#define __KX_OBCOLORIPOSGCONTROLLER_H__
-
-#include "SG_Controller.h"
-#include "SG_Spatial.h"
-#include "KX_IInterpolator.h"
-
-class KX_ObColorIpoSGController : public SG_Controller
-{
-public:
- MT_Vector4 m_rgba;
-
-
-private:
- T_InterpolatorList m_interpolators;
- bool m_modified;
-
- double m_ipotime;
-public:
- KX_ObColorIpoSGController() :
- m_modified(true),
- m_ipotime(0.0)
- {}
- virtual ~KX_ObColorIpoSGController();
- virtual SG_Controller* GetReplica(class SG_Node* destnode);
- virtual bool Update(double time);
- virtual void SetSimulatedTime(double time) {
- m_ipotime = time;
- m_modified = true;
- }
-
- void
- SetOption(
- int option,
- int value
- ) {
- // intentionally empty
- };
-
-
- void AddInterpolator(KX_IInterpolator* interp);
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:KX_ObColorIpoSGController")
-#endif
-};
-
-#endif /* __KX_OBCOLORIPOSGCONTROLLER_H__ */
diff --git a/source/gameengine/Ketsji/KX_ObjectActuator.cpp b/source/gameengine/Ketsji/KX_ObjectActuator.cpp
deleted file mode 100644
index 8c1dee7940f..00000000000
--- a/source/gameengine/Ketsji/KX_ObjectActuator.cpp
+++ /dev/null
@@ -1,709 +0,0 @@
-/*
- * Do translation/rotation actions
- *
- *
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Ketsji/KX_ObjectActuator.cpp
- * \ingroup ketsji
- */
-
-#include <stdio.h>
-
-#include "KX_ObjectActuator.h"
-#include "KX_GameObject.h"
-#include "KX_PyMath.h" // For PyVecTo - should this include be put in PyObjectPlus?
-#include "PHY_IPhysicsController.h"
-#include "PHY_ICharacter.h"
-#include "PHY_IPhysicsEnvironment.h"
-
-/* ------------------------------------------------------------------------- */
-/* Native functions */
-/* ------------------------------------------------------------------------- */
-
-KX_ObjectActuator::
-KX_ObjectActuator(
- SCA_IObject* gameobj,
- KX_GameObject* refobj,
- const MT_Vector3& force,
- const MT_Vector3& torque,
- const MT_Vector3& dloc,
- const MT_Vector3& drot,
- const MT_Vector3& linV,
- const MT_Vector3& angV,
- const short damping,
- const KX_LocalFlags& flag
-) :
- SCA_IActuator(gameobj, KX_ACT_OBJECT),
- m_force(force),
- m_torque(torque),
- m_dloc(dloc),
- m_drot(drot),
- m_linear_velocity(linV),
- m_angular_velocity(angV),
- m_linear_length2(0.0f),
- m_current_linear_factor(0.0f),
- m_current_angular_factor(0.0f),
- m_damping(damping),
- m_previous_error(0.0f,0.0f,0.0f),
- m_error_accumulator(0.0f,0.0f,0.0f),
- m_bitLocalFlag (flag),
- m_reference(refobj),
- m_active_combined_velocity (false),
- m_linear_damping_active(false),
- m_angular_damping_active(false),
- m_jumping(false)
-{
- if (m_bitLocalFlag.ServoControl)
- {
- // in servo motion, the force is local if the target velocity is local
- m_bitLocalFlag.Force = m_bitLocalFlag.LinearVelocity;
-
- m_pid = m_torque;
- }
- if (m_bitLocalFlag.CharacterMotion)
- {
- KX_GameObject *parent = static_cast<KX_GameObject *>(GetParent());
- PHY_ICharacter *character = parent->GetScene()->GetPhysicsEnvironment()->GetCharacterController(parent);
-
- if (!character)
- {
- printf("Character motion enabled on non-character object (%s), falling back to simple motion.\n", parent->GetName().Ptr());
- m_bitLocalFlag.CharacterMotion = false;
- }
- }
- if (m_reference)
- m_reference->RegisterActuator(this);
- UpdateFuzzyFlags();
-}
-
-KX_ObjectActuator::~KX_ObjectActuator()
-{
- if (m_reference)
- m_reference->UnregisterActuator(this);
-}
-
-bool KX_ObjectActuator::Update()
-{
-
- bool bNegativeEvent = IsNegativeEvent();
- RemoveAllEvents();
-
- KX_GameObject *parent = static_cast<KX_GameObject *>(GetParent());
- PHY_ICharacter *character = parent->GetScene()->GetPhysicsEnvironment()->GetCharacterController(parent);
-
- if (bNegativeEvent) {
- // If we previously set the linear velocity we now have to inform
- // the physics controller that we no longer wish to apply it and that
- // it should reconcile the externally set velocity with it's
- // own velocity.
- if (m_active_combined_velocity) {
- if (parent)
- parent->ResolveCombinedVelocities(
- m_linear_velocity,
- m_angular_velocity,
- (m_bitLocalFlag.LinearVelocity) != 0,
- (m_bitLocalFlag.AngularVelocity) != 0
- );
- m_active_combined_velocity = false;
- }
-
- // Explicitly stop the movement if we're using character motion
- if (m_bitLocalFlag.CharacterMotion) {
- character->SetWalkDirection(MT_Vector3 (0.0f, 0.0f, 0.0f));
- }
-
- m_linear_damping_active = false;
- m_angular_damping_active = false;
- m_error_accumulator.setValue(0.0f,0.0f,0.0f);
- m_previous_error.setValue(0.0f,0.0f,0.0f);
- m_jumping = false;
- return false;
-
- } else if (parent)
- {
- if (m_bitLocalFlag.ServoControl)
- {
- // In this mode, we try to reach a target speed using force
- // As we don't know the friction, we must implement a generic
- // servo control to achieve the speed in a configurable
- // v = current velocity
- // V = target velocity
- // e = V-v = speed error
- // dt = time interval since previous update
- // I = sum(e(t)*dt)
- // dv = e(t) - e(t-1)
- // KP, KD, KI : coefficient
- // F = KP*e+KI*I+KD*dv
- MT_Scalar mass = parent->GetMass();
- if (mass < MT_EPSILON)
- return false;
- MT_Vector3 v = parent->GetLinearVelocity(m_bitLocalFlag.LinearVelocity);
- if (m_reference)
- {
- const MT_Point3& mypos = parent->NodeGetWorldPosition();
- const MT_Point3& refpos = m_reference->NodeGetWorldPosition();
- MT_Point3 relpos;
- relpos = (mypos-refpos);
- MT_Vector3 vel= m_reference->GetVelocity(relpos);
- if (m_bitLocalFlag.LinearVelocity)
- // must convert in local space
- vel = parent->NodeGetWorldOrientation().transposed()*vel;
- v -= vel;
- }
- MT_Vector3 e = m_linear_velocity - v;
- MT_Vector3 dv = e - m_previous_error;
- MT_Vector3 I = m_error_accumulator + e;
-
- m_force = m_pid.x()*e+m_pid.y()*I+m_pid.z()*dv;
- // to automatically adapt the PID coefficient to mass;
- m_force *= mass;
- if (m_bitLocalFlag.Torque)
- {
- if (m_force[0] > m_dloc[0])
- {
- m_force[0] = m_dloc[0];
- I[0] = m_error_accumulator[0];
- } else if (m_force[0] < m_drot[0])
- {
- m_force[0] = m_drot[0];
- I[0] = m_error_accumulator[0];
- }
- }
- if (m_bitLocalFlag.DLoc)
- {
- if (m_force[1] > m_dloc[1])
- {
- m_force[1] = m_dloc[1];
- I[1] = m_error_accumulator[1];
- } else if (m_force[1] < m_drot[1])
- {
- m_force[1] = m_drot[1];
- I[1] = m_error_accumulator[1];
- }
- }
- if (m_bitLocalFlag.DRot)
- {
- if (m_force[2] > m_dloc[2])
- {
- m_force[2] = m_dloc[2];
- I[2] = m_error_accumulator[2];
- } else if (m_force[2] < m_drot[2])
- {
- m_force[2] = m_drot[2];
- I[2] = m_error_accumulator[2];
- }
- }
- m_previous_error = e;
- m_error_accumulator = I;
- parent->ApplyForce(m_force,(m_bitLocalFlag.LinearVelocity) != 0);
- }
- else if (m_bitLocalFlag.CharacterMotion) {
- MT_Vector3 dir = m_dloc;
-
- if (m_bitLocalFlag.DLoc) {
- MT_Matrix3x3 basis = parent->GetPhysicsController()->GetOrientation();
- dir = basis * dir;
- }
-
- if (m_bitLocalFlag.AddOrSetCharLoc) {
- MT_Vector3 old_dir = character->GetWalkDirection();
-
- if (!old_dir.fuzzyZero()) {
- MT_Scalar mag = old_dir.length();
-
- dir = dir + old_dir;
- if (!dir.fuzzyZero())
- dir = dir.normalized() * mag;
- }
- }
-
- // We always want to set the walk direction since a walk direction of (0, 0, 0) should stop the character
- character->SetWalkDirection(dir/parent->GetScene()->GetPhysicsEnvironment()->GetNumTimeSubSteps());
-
- if (!m_bitLocalFlag.ZeroDRot)
- {
- parent->ApplyRotation(m_drot,(m_bitLocalFlag.DRot) != 0);
- }
-
- if (m_bitLocalFlag.CharacterJump) {
- if (!m_jumping) {
- character->Jump();
- m_jumping = true;
- }
- else if (character->OnGround())
- m_jumping = false;
- }
- }
- else {
- if (!m_bitLocalFlag.ZeroForce)
- {
- parent->ApplyForce(m_force,(m_bitLocalFlag.Force) != 0);
- }
- if (!m_bitLocalFlag.ZeroTorque)
- {
- parent->ApplyTorque(m_torque,(m_bitLocalFlag.Torque) != 0);
- }
- if (!m_bitLocalFlag.ZeroDLoc)
- {
- parent->ApplyMovement(m_dloc,(m_bitLocalFlag.DLoc) != 0);
- }
- if (!m_bitLocalFlag.ZeroDRot)
- {
- parent->ApplyRotation(m_drot,(m_bitLocalFlag.DRot) != 0);
- }
- if (!m_bitLocalFlag.ZeroLinearVelocity)
- {
- if (m_bitLocalFlag.AddOrSetLinV) {
- parent->addLinearVelocity(m_linear_velocity,(m_bitLocalFlag.LinearVelocity) != 0);
- } else {
- m_active_combined_velocity = true;
- if (m_damping > 0) {
- MT_Vector3 linV;
- if (!m_linear_damping_active) {
- // delta and the start speed (depends on the existing speed in that direction)
- linV = parent->GetLinearVelocity(m_bitLocalFlag.LinearVelocity);
- // keep only the projection along the desired direction
- m_current_linear_factor = linV.dot(m_linear_velocity)/m_linear_length2;
- m_linear_damping_active = true;
- }
- if (m_current_linear_factor < 1.0f)
- m_current_linear_factor += 1.0f/m_damping;
- if (m_current_linear_factor > 1.0f)
- m_current_linear_factor = 1.0f;
- linV = m_current_linear_factor * m_linear_velocity;
- parent->setLinearVelocity(linV,(m_bitLocalFlag.LinearVelocity) != 0);
- } else {
- parent->setLinearVelocity(m_linear_velocity,(m_bitLocalFlag.LinearVelocity) != 0);
- }
- }
- }
- if (!m_bitLocalFlag.ZeroAngularVelocity)
- {
- m_active_combined_velocity = true;
- if (m_damping > 0) {
- MT_Vector3 angV;
- if (!m_angular_damping_active) {
- // delta and the start speed (depends on the existing speed in that direction)
- angV = parent->GetAngularVelocity(m_bitLocalFlag.AngularVelocity);
- // keep only the projection along the desired direction
- m_current_angular_factor = angV.dot(m_angular_velocity)/m_angular_length2;
- m_angular_damping_active = true;
- }
- if (m_current_angular_factor < 1.0f)
- m_current_angular_factor += 1.0f/m_damping;
- if (m_current_angular_factor > 1.0f)
- m_current_angular_factor = 1.0f;
- angV = m_current_angular_factor * m_angular_velocity;
- parent->setAngularVelocity(angV,(m_bitLocalFlag.AngularVelocity) != 0);
- } else {
- parent->setAngularVelocity(m_angular_velocity,(m_bitLocalFlag.AngularVelocity) != 0);
- }
- }
- }
-
- }
- return true;
-}
-
-
-
-CValue* KX_ObjectActuator::GetReplica()
-{
- KX_ObjectActuator* replica = new KX_ObjectActuator(*this);//m_float,GetName());
- replica->ProcessReplica();
-
- return replica;
-}
-
-void KX_ObjectActuator::ProcessReplica()
-{
- SCA_IActuator::ProcessReplica();
- if (m_reference)
- m_reference->RegisterActuator(this);
-}
-
-bool KX_ObjectActuator::UnlinkObject(SCA_IObject* clientobj)
-{
- if (clientobj == (SCA_IObject*)m_reference)
- {
- // this object is being deleted, we cannot continue to use it as reference.
- m_reference = NULL;
- return true;
- }
- return false;
-}
-
-void KX_ObjectActuator::Relink(CTR_Map<CTR_HashedPtr, void*> *obj_map)
-{
- void **h_obj = (*obj_map)[m_reference];
- if (h_obj) {
- if (m_reference)
- m_reference->UnregisterActuator(this);
- m_reference = (KX_GameObject*)(*h_obj);
- m_reference->RegisterActuator(this);
- }
-}
-
-/* some 'standard' utilities... */
-bool KX_ObjectActuator::isValid(KX_ObjectActuator::KX_OBJECT_ACT_VEC_TYPE type)
-{
- bool res = false;
- res = (type > KX_OBJECT_ACT_NODEF) && (type < KX_OBJECT_ACT_MAX);
- return res;
-}
-
-#ifdef WITH_PYTHON
-
-/* ------------------------------------------------------------------------- */
-/* Python functions */
-/* ------------------------------------------------------------------------- */
-
-/* Integration hooks ------------------------------------------------------- */
-PyTypeObject KX_ObjectActuator::Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "KX_ObjectActuator",
- sizeof(PyObjectPlus_Proxy),
- 0,
- py_base_dealloc,
- 0,
- 0,
- 0,
- 0,
- py_base_repr,
- 0,0,0,0,0,0,0,0,0,
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
- 0,0,0,0,0,0,0,
- Methods,
- 0,
- 0,
- &SCA_IActuator::Type,
- 0,0,0,0,0,0,
- py_base_new
-};
-
-PyMethodDef KX_ObjectActuator::Methods[] = {
- {NULL,NULL} //Sentinel
-};
-
-PyAttributeDef KX_ObjectActuator::Attributes[] = {
- KX_PYATTRIBUTE_VECTOR_RW_CHECK("force", -1000, 1000, false, KX_ObjectActuator, m_force, PyUpdateFuzzyFlags),
- KX_PYATTRIBUTE_BOOL_RW("useLocalForce", KX_ObjectActuator, m_bitLocalFlag.Force),
- KX_PYATTRIBUTE_VECTOR_RW_CHECK("torque", -1000, 1000, false, KX_ObjectActuator, m_torque, PyUpdateFuzzyFlags),
- KX_PYATTRIBUTE_BOOL_RW("useLocalTorque", KX_ObjectActuator, m_bitLocalFlag.Torque),
- KX_PYATTRIBUTE_VECTOR_RW_CHECK("dLoc", -1000, 1000, false, KX_ObjectActuator, m_dloc, PyUpdateFuzzyFlags),
- KX_PYATTRIBUTE_BOOL_RW("useLocalDLoc", KX_ObjectActuator, m_bitLocalFlag.DLoc),
- KX_PYATTRIBUTE_VECTOR_RW_CHECK("dRot", -1000, 1000, false, KX_ObjectActuator, m_drot, PyUpdateFuzzyFlags),
- KX_PYATTRIBUTE_BOOL_RW("useLocalDRot", KX_ObjectActuator, m_bitLocalFlag.DRot),
-#ifdef USE_MATHUTILS
- KX_PYATTRIBUTE_RW_FUNCTION("linV", KX_ObjectActuator, pyattr_get_linV, pyattr_set_linV),
- KX_PYATTRIBUTE_RW_FUNCTION("angV", KX_ObjectActuator, pyattr_get_angV, pyattr_set_angV),
-#else
- KX_PYATTRIBUTE_VECTOR_RW_CHECK("linV", -1000, 1000, false, KX_ObjectActuator, m_linear_velocity, PyUpdateFuzzyFlags),
- KX_PYATTRIBUTE_VECTOR_RW_CHECK("angV", -1000, 1000, false, KX_ObjectActuator, m_angular_velocity, PyUpdateFuzzyFlags),
-#endif
- KX_PYATTRIBUTE_BOOL_RW("useLocalLinV", KX_ObjectActuator, m_bitLocalFlag.LinearVelocity),
- KX_PYATTRIBUTE_BOOL_RW("useLocalAngV", KX_ObjectActuator, m_bitLocalFlag.AngularVelocity),
- KX_PYATTRIBUTE_SHORT_RW("damping", 0, 1000, false, KX_ObjectActuator, m_damping),
- KX_PYATTRIBUTE_RW_FUNCTION("forceLimitX", KX_ObjectActuator, pyattr_get_forceLimitX, pyattr_set_forceLimitX),
- KX_PYATTRIBUTE_RW_FUNCTION("forceLimitY", KX_ObjectActuator, pyattr_get_forceLimitY, pyattr_set_forceLimitY),
- KX_PYATTRIBUTE_RW_FUNCTION("forceLimitZ", KX_ObjectActuator, pyattr_get_forceLimitZ, pyattr_set_forceLimitZ),
- KX_PYATTRIBUTE_VECTOR_RW_CHECK("pid", -100, 200, true, KX_ObjectActuator, m_pid, PyCheckPid),
- KX_PYATTRIBUTE_RW_FUNCTION("reference", KX_ObjectActuator,pyattr_get_reference,pyattr_set_reference),
- { NULL } //Sentinel
-};
-
-/* Attribute get/set functions */
-
-#ifdef USE_MATHUTILS
-
-/* These require an SGNode */
-#define MATHUTILS_VEC_CB_LINV 1
-#define MATHUTILS_VEC_CB_ANGV 2
-
-static unsigned char mathutils_kxobactu_vector_cb_index = -1; /* index for our callbacks */
-
-static int mathutils_obactu_generic_check(BaseMathObject *bmo)
-{
- KX_ObjectActuator* self = static_cast<KX_ObjectActuator*>BGE_PROXY_REF(bmo->cb_user);
- if (self == NULL)
- return -1;
-
- return 0;
-}
-
-static int mathutils_obactu_vector_get(BaseMathObject *bmo, int subtype)
-{
- KX_ObjectActuator* self = static_cast<KX_ObjectActuator*>BGE_PROXY_REF(bmo->cb_user);
- if (self == NULL)
- return -1;
-
- switch (subtype) {
- case MATHUTILS_VEC_CB_LINV:
- self->m_linear_velocity.getValue(bmo->data);
- break;
- case MATHUTILS_VEC_CB_ANGV:
- self->m_angular_velocity.getValue(bmo->data);
- break;
- }
-
- return 0;
-}
-
-static int mathutils_obactu_vector_set(BaseMathObject *bmo, int subtype)
-{
- KX_ObjectActuator* self = static_cast<KX_ObjectActuator*>BGE_PROXY_REF(bmo->cb_user);
- if (self == NULL)
- return -1;
-
- switch (subtype) {
- case MATHUTILS_VEC_CB_LINV:
- self->m_linear_velocity.setValue(bmo->data);
- break;
- case MATHUTILS_VEC_CB_ANGV:
- self->m_angular_velocity.setValue(bmo->data);
- break;
- }
-
- return 0;
-}
-
-static int mathutils_obactu_vector_get_index(BaseMathObject *bmo, int subtype, int index)
-{
- /* lazy, avoid repeteing the case statement */
- if (mathutils_obactu_vector_get(bmo, subtype) == -1)
- return -1;
- return 0;
-}
-
-static int mathutils_obactu_vector_set_index(BaseMathObject *bmo, int subtype, int index)
-{
- float f = bmo->data[index];
-
- /* lazy, avoid repeteing the case statement */
- if (mathutils_obactu_vector_get(bmo, subtype) == -1)
- return -1;
-
- bmo->data[index] = f;
- return mathutils_obactu_vector_set(bmo, subtype);
-}
-
-static Mathutils_Callback mathutils_obactu_vector_cb = {
- mathutils_obactu_generic_check,
- mathutils_obactu_vector_get,
- mathutils_obactu_vector_set,
- mathutils_obactu_vector_get_index,
- mathutils_obactu_vector_set_index
-};
-
-PyObject *KX_ObjectActuator::pyattr_get_linV(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- return Vector_CreatePyObject_cb(
- BGE_PROXY_FROM_REF_BORROW(self_v), 3,
- mathutils_kxobactu_vector_cb_index, MATHUTILS_VEC_CB_LINV);
-}
-
-int KX_ObjectActuator::pyattr_set_linV(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_ObjectActuator* self = static_cast<KX_ObjectActuator*>(self_v);
- if (!PyVecTo(value, self->m_linear_velocity))
- return PY_SET_ATTR_FAIL;
-
- self->UpdateFuzzyFlags();
-
- return PY_SET_ATTR_SUCCESS;
-}
-
-PyObject *KX_ObjectActuator::pyattr_get_angV(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- return Vector_CreatePyObject_cb(
- BGE_PROXY_FROM_REF_BORROW(self_v), 3,
- mathutils_kxobactu_vector_cb_index, MATHUTILS_VEC_CB_ANGV);
-}
-
-int KX_ObjectActuator::pyattr_set_angV(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_ObjectActuator* self = static_cast<KX_ObjectActuator*>(self_v);
- if (!PyVecTo(value, self->m_angular_velocity))
- return PY_SET_ATTR_FAIL;
-
- self->UpdateFuzzyFlags();
-
- return PY_SET_ATTR_SUCCESS;
-}
-
-
-void KX_ObjectActuator_Mathutils_Callback_Init(void)
-{
- // register mathutils callbacks, ok to run more than once.
- mathutils_kxobactu_vector_cb_index = Mathutils_RegisterCallback(&mathutils_obactu_vector_cb);
-}
-
-#endif // USE_MATHUTILS
-
-PyObject *KX_ObjectActuator::pyattr_get_forceLimitX(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_ObjectActuator* self = reinterpret_cast<KX_ObjectActuator*>(self_v);
- PyObject *retVal = PyList_New(3);
-
- PyList_SET_ITEM(retVal, 0, PyFloat_FromDouble(self->m_drot[0]));
- PyList_SET_ITEM(retVal, 1, PyFloat_FromDouble(self->m_dloc[0]));
- PyList_SET_ITEM(retVal, 2, PyBool_FromLong(self->m_bitLocalFlag.Torque));
-
- return retVal;
-}
-
-int KX_ObjectActuator::pyattr_set_forceLimitX(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_ObjectActuator* self = reinterpret_cast<KX_ObjectActuator*>(self_v);
-
- PyObject *seq = PySequence_Fast(value, "");
- if (seq && PySequence_Fast_GET_SIZE(seq) == 3)
- {
- self->m_drot[0] = PyFloat_AsDouble(PySequence_Fast_GET_ITEM(value, 0));
- self->m_dloc[0] = PyFloat_AsDouble(PySequence_Fast_GET_ITEM(value, 1));
- self->m_bitLocalFlag.Torque = (PyLong_AsLong(PySequence_Fast_GET_ITEM(value, 2)) != 0);
-
- if (!PyErr_Occurred())
- {
- Py_DECREF(seq);
- return PY_SET_ATTR_SUCCESS;
- }
- }
-
- Py_XDECREF(seq);
-
- PyErr_SetString(PyExc_ValueError, "expected a sequence of 2 floats and a bool");
- return PY_SET_ATTR_FAIL;
-}
-
-PyObject *KX_ObjectActuator::pyattr_get_forceLimitY(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_ObjectActuator* self = reinterpret_cast<KX_ObjectActuator*>(self_v);
- PyObject *retVal = PyList_New(3);
-
- PyList_SET_ITEM(retVal, 0, PyFloat_FromDouble(self->m_drot[1]));
- PyList_SET_ITEM(retVal, 1, PyFloat_FromDouble(self->m_dloc[1]));
- PyList_SET_ITEM(retVal, 2, PyBool_FromLong(self->m_bitLocalFlag.DLoc));
-
- return retVal;
-}
-
-int KX_ObjectActuator::pyattr_set_forceLimitY(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_ObjectActuator* self = reinterpret_cast<KX_ObjectActuator*>(self_v);
-
- PyObject *seq = PySequence_Fast(value, "");
- if (seq && PySequence_Fast_GET_SIZE(seq) == 3)
- {
- self->m_drot[1] = PyFloat_AsDouble(PySequence_Fast_GET_ITEM(value, 0));
- self->m_dloc[1] = PyFloat_AsDouble(PySequence_Fast_GET_ITEM(value, 1));
- self->m_bitLocalFlag.DLoc = (PyLong_AsLong(PySequence_Fast_GET_ITEM(value, 2)) != 0);
-
- if (!PyErr_Occurred())
- {
- Py_DECREF(seq);
- return PY_SET_ATTR_SUCCESS;
- }
- }
-
- Py_XDECREF(seq);
-
- PyErr_SetString(PyExc_ValueError, "expected a sequence of 2 floats and a bool");
- return PY_SET_ATTR_FAIL;
-}
-
-PyObject *KX_ObjectActuator::pyattr_get_forceLimitZ(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_ObjectActuator* self = reinterpret_cast<KX_ObjectActuator*>(self_v);
- PyObject *retVal = PyList_New(3);
-
- PyList_SET_ITEM(retVal, 0, PyFloat_FromDouble(self->m_drot[2]));
- PyList_SET_ITEM(retVal, 1, PyFloat_FromDouble(self->m_dloc[2]));
- PyList_SET_ITEM(retVal, 2, PyBool_FromLong(self->m_bitLocalFlag.DRot));
-
- return retVal;
-}
-
-int KX_ObjectActuator::pyattr_set_forceLimitZ(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_ObjectActuator* self = reinterpret_cast<KX_ObjectActuator*>(self_v);
-
- PyObject *seq = PySequence_Fast(value, "");
- if (seq && PySequence_Fast_GET_SIZE(seq) == 3)
- {
- self->m_drot[2] = PyFloat_AsDouble(PySequence_Fast_GET_ITEM(value, 0));
- self->m_dloc[2] = PyFloat_AsDouble(PySequence_Fast_GET_ITEM(value, 1));
- self->m_bitLocalFlag.DRot = (PyLong_AsLong(PySequence_Fast_GET_ITEM(value, 2)) != 0);
-
- if (!PyErr_Occurred())
- {
- Py_DECREF(seq);
- return PY_SET_ATTR_SUCCESS;
- }
- }
-
- Py_XDECREF(seq);
-
- PyErr_SetString(PyExc_ValueError, "expected a sequence of 2 floats and a bool");
- return PY_SET_ATTR_FAIL;
-}
-
-PyObject *KX_ObjectActuator::pyattr_get_reference(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_ObjectActuator* actuator = static_cast<KX_ObjectActuator*>(self);
- if (!actuator->m_reference)
- Py_RETURN_NONE;
-
- return actuator->m_reference->GetProxy();
-}
-
-int KX_ObjectActuator::pyattr_set_reference(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_ObjectActuator* actuator = static_cast<KX_ObjectActuator*>(self);
- KX_GameObject *refOb;
-
- if (!ConvertPythonToGameObject(actuator->GetLogicManager(), value, &refOb, true, "actu.reference = value: KX_ObjectActuator"))
- return PY_SET_ATTR_FAIL;
-
- if (actuator->m_reference)
- actuator->m_reference->UnregisterActuator(actuator);
-
- if (refOb==NULL) {
- actuator->m_reference= NULL;
- }
- else {
- actuator->m_reference = refOb;
- actuator->m_reference->RegisterActuator(actuator);
- }
-
- return PY_SET_ATTR_SUCCESS;
-}
-
-#endif // WITH_PYTHON
-
-/* eof */
diff --git a/source/gameengine/Ketsji/KX_ObjectActuator.h b/source/gameengine/Ketsji/KX_ObjectActuator.h
deleted file mode 100644
index 919c6acf03b..00000000000
--- a/source/gameengine/Ketsji/KX_ObjectActuator.h
+++ /dev/null
@@ -1,234 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file KX_ObjectActuator.h
- * \ingroup ketsji
- * \brief Do translation/rotation actions
- */
-
-#ifndef __KX_OBJECTACTUATOR_H__
-#define __KX_OBJECTACTUATOR_H__
-
-#include "SCA_IActuator.h"
-#include "MT_Vector3.h"
-
-#ifdef USE_MATHUTILS
-void KX_ObjectActuator_Mathutils_Callback_Init(void);
-#endif
-
-class KX_GameObject;
-
-//
-// Stores the flags for each CValue derived class
-//
-struct KX_LocalFlags {
- KX_LocalFlags() :
- Force(false),
- Torque(false),
- DRot(false),
- DLoc(false),
- LinearVelocity(false),
- AngularVelocity(false),
- AddOrSetLinV(false),
- AddOrSetCharLoc(false),
- ServoControl(false),
- CharacterMotion(false),
- CharacterJump(false),
- ZeroForce(false),
- ZeroTorque(false),
- ZeroDRot(false),
- ZeroDLoc(false),
- ZeroLinearVelocity(false),
- ZeroAngularVelocity(false)
- {
- }
-
- bool Force;
- bool Torque;
- bool DRot;
- bool DLoc;
- bool LinearVelocity;
- bool AngularVelocity;
- bool AddOrSetLinV;
- bool AddOrSetCharLoc;
- bool ServoControl;
- bool CharacterMotion;
- bool CharacterJump;
- bool ZeroForce;
- bool ZeroTorque;
- bool ZeroDRot;
- bool ZeroDLoc;
- bool ZeroLinearVelocity;
- bool ZeroAngularVelocity;
-};
-
-class KX_ObjectActuator : public SCA_IActuator
-{
- Py_Header
-
- MT_Vector3 m_force;
- MT_Vector3 m_torque;
- MT_Vector3 m_dloc;
- MT_Vector3 m_drot;
- MT_Vector3 m_linear_velocity;
- MT_Vector3 m_angular_velocity;
- MT_Vector3 m_pid;
- MT_Scalar m_linear_length2;
- MT_Scalar m_angular_length2;
- // used in damping
- MT_Scalar m_current_linear_factor;
- MT_Scalar m_current_angular_factor;
- short m_damping;
- // used in servo control
- MT_Vector3 m_previous_error;
- MT_Vector3 m_error_accumulator;
- KX_LocalFlags m_bitLocalFlag;
- KX_GameObject* m_reference;
- // A hack bool -- oh no sorry everyone
- // This bool is used to check if we have informed
- // the physics object that we are no longer
- // setting linear velocity.
-
- bool m_active_combined_velocity;
- bool m_linear_damping_active;
- bool m_angular_damping_active;
- bool m_jumping;
-
-public:
- enum KX_OBJECT_ACT_VEC_TYPE {
- KX_OBJECT_ACT_NODEF = 0,
- KX_OBJECT_ACT_FORCE,
- KX_OBJECT_ACT_TORQUE,
- KX_OBJECT_ACT_DLOC,
- KX_OBJECT_ACT_DROT,
- KX_OBJECT_ACT_LINEAR_VELOCITY,
- KX_OBJECT_ACT_ANGULAR_VELOCITY,
- KX_OBJECT_ACT_MAX
- };
-
- /**
- * Check whether this is a valid vector mode
- */
- bool isValid(KX_OBJECT_ACT_VEC_TYPE type);
-
- KX_ObjectActuator(
- SCA_IObject* gameobj,
- KX_GameObject* refobj,
- const MT_Vector3& force,
- const MT_Vector3& torque,
- const MT_Vector3& dloc,
- const MT_Vector3& drot,
- const MT_Vector3& linV,
- const MT_Vector3& angV,
- const short damping,
- const KX_LocalFlags& flag
- );
- ~KX_ObjectActuator();
- CValue* GetReplica();
- void ProcessReplica();
- bool UnlinkObject(SCA_IObject* clientobj);
- void Relink(CTR_Map<CTR_HashedPtr, void*> *obj_map);
-
- void SetForceLoc(const double force[3]) { /*m_force=force;*/ }
- void UpdateFuzzyFlags()
- {
- m_bitLocalFlag.ZeroForce = MT_fuzzyZero(m_force);
- m_bitLocalFlag.ZeroTorque = MT_fuzzyZero(m_torque);
- m_bitLocalFlag.ZeroDLoc = MT_fuzzyZero(m_dloc);
- m_bitLocalFlag.ZeroDRot = MT_fuzzyZero(m_drot);
- m_bitLocalFlag.ZeroLinearVelocity = MT_fuzzyZero(m_linear_velocity);
- m_linear_length2 = (m_bitLocalFlag.ZeroLinearVelocity) ? 0.0f : m_linear_velocity.length2();
- m_bitLocalFlag.ZeroAngularVelocity = MT_fuzzyZero(m_angular_velocity);
- m_angular_length2 = (m_bitLocalFlag.ZeroAngularVelocity) ? 0.0f : m_angular_velocity.length2();
- }
- virtual bool Update();
-
-#ifdef WITH_PYTHON
-
- /* --------------------------------------------------------------------- */
- /* Python interface ---------------------------------------------------- */
- /* --------------------------------------------------------------------- */
-
- /* Attributes */
- static PyObject* pyattr_get_forceLimitX(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_forceLimitX(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static PyObject* pyattr_get_forceLimitY(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_forceLimitY(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static PyObject* pyattr_get_forceLimitZ(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_forceLimitZ(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static PyObject* pyattr_get_reference(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_reference(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
-
-#ifdef USE_MATHUTILS
- static PyObject* pyattr_get_linV(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_linV(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static PyObject* pyattr_get_angV(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_angV(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
-#endif
-
- // This lets the attribute macros use UpdateFuzzyFlags()
- static int PyUpdateFuzzyFlags(void *self, const PyAttributeDef *attrdef)
- {
- KX_ObjectActuator* act = reinterpret_cast<KX_ObjectActuator*>(self);
- act->UpdateFuzzyFlags();
- return 0;
- }
-
- // This is the keep the PID values in check after they are assigned with Python
- static int PyCheckPid(void *self, const PyAttributeDef *attrdef)
- {
- KX_ObjectActuator* act = reinterpret_cast<KX_ObjectActuator*>(self);
-
- //P 0 to 200
- if (act->m_pid[0] < 0) {
- act->m_pid[0] = 0;
- } else if (act->m_pid[0] > 200) {
- act->m_pid[0] = 200;
- }
-
- //I 0 to 3
- if (act->m_pid[1] < 0) {
- act->m_pid[1] = 0;
- } else if (act->m_pid[1] > 3) {
- act->m_pid[1] = 3;
- }
-
- //D -100 to 100
- if (act->m_pid[2] < -100) {
- act->m_pid[2] = -100;
- } else if (act->m_pid[2] > 100) {
- act->m_pid[2] = 100;
- }
-
- return 0;
- }
-
-#endif /* WITH_PYTHON */
-
-};
-
-#endif /* __KX_OBJECTACTUATOR_H__ */
diff --git a/source/gameengine/Ketsji/KX_ObstacleSimulation.cpp b/source/gameengine/Ketsji/KX_ObstacleSimulation.cpp
deleted file mode 100644
index c84b2474c90..00000000000
--- a/source/gameengine/Ketsji/KX_ObstacleSimulation.cpp
+++ /dev/null
@@ -1,832 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Ketsji/KX_ObstacleSimulation.cpp
- * \ingroup ketsji
- *
- * Simulation for obstacle avoidance behavior
- */
-
-#include "KX_ObstacleSimulation.h"
-#include "KX_NavMeshObject.h"
-#include "KX_PythonInit.h"
-#include "DNA_object_types.h"
-#include "BLI_math.h"
-
-namespace
-{
- inline float perp(const MT_Vector2& a, const MT_Vector2& b) { return a.x()*b.y() - a.y()*b.x(); }
-
- inline float sqr(float x) { return x * x; }
- inline float lerp(float a, float b, float t) { return a + (b - a) * t; }
- inline float clamp(float a, float mn, float mx) { return a < mn ? mn : (a > mx ? mx : a); }
- inline void vset(float v[2], float x, float y) { v[0] = x; v[1] = y; }
-}
-
-/* grr, seems moto provides no nice way to do this */
-#define MT_3D_AS_2D(v) MT_Vector2((v)[0], (v)[1])
-
-static int sweepCircleCircle(
- const MT_Vector2 &pos0, const MT_Scalar r0, const MT_Vector2 &v,
- const MT_Vector2 &pos1, const MT_Scalar r1,
- float& tmin, float& tmax)
-{
- static const float EPS = 0.0001f;
- MT_Vector2 c0(pos0.x(), pos0.y());
- MT_Vector2 c1(pos1.x(), pos1.y());
- MT_Vector2 s = c1 - c0;
- MT_Scalar r = r0+r1;
- float c = s.length2() - r*r;
- float a = v.length2();
- if (a < EPS) return 0; // not moving
-
- // Overlap, calc time to exit.
- float b = MT_dot(v,s);
- float d = b*b - a*c;
- if (d < 0.0f) return 0; // no intersection.
- tmin = (b - sqrtf(d)) / a;
- tmax = (b + sqrtf(d)) / a;
- return 1;
-}
-
-static int sweepCircleSegment(
- const MT_Vector2 &pos0, const MT_Scalar r0, const MT_Vector2 &v,
- const MT_Vector2& pa, const MT_Vector2 &pb, const MT_Scalar sr,
- float& tmin, float &tmax)
-{
- // equation parameters
- MT_Vector2 c0(pos0.x(), pos0.y());
- MT_Vector2 sa(pa.x(), pa.y());
- MT_Vector2 sb(pb.x(), pb.y());
- MT_Vector2 L = sb-sa;
- MT_Vector2 H = c0-sa;
- MT_Scalar radius = r0+sr;
- float l2 = L.length2();
- float r2 = radius * radius;
- float dl = perp(v, L);
- float hl = perp(H, L);
- float a = dl * dl;
- float b = 2.0f * hl * dl;
- float c = hl * hl - (r2 * l2);
- float d = (b*b) - (4.0f * a * c);
-
- // infinite line missed by infinite ray.
- if (d < 0.0f)
- return 0;
-
- d = sqrtf(d);
- tmin = (-b - d) / (2.0f * a);
- tmax = (-b + d) / (2.0f * a);
-
- // line missed by ray range.
- /* if (tmax < 0.0f || tmin > 1.0f)
- return 0;*/
-
- // find what part of the ray was collided.
- MT_Vector2 Pedge;
- Pedge = c0+v*tmin;
- H = Pedge - sa;
- float e0 = MT_dot(H, L) / l2;
- Pedge = c0 + v*tmax;
- H = Pedge - sa;
- float e1 = MT_dot(H, L) / l2;
-
- if (e0 < 0.0f || e1 < 0.0f)
- {
- float ctmin, ctmax;
- if (sweepCircleCircle(pos0, r0, v, pa, sr, ctmin, ctmax))
- {
- if (e0 < 0.0f && ctmin > tmin)
- tmin = ctmin;
- if (e1 < 0.0f && ctmax < tmax)
- tmax = ctmax;
- }
- else
- {
- return 0;
- }
- }
-
- if (e0 > 1.0f || e1 > 1.0f)
- {
- float ctmin, ctmax;
- if (sweepCircleCircle(pos0, r0, v, pb, sr, ctmin, ctmax))
- {
- if (e0 > 1.0f && ctmin > tmin)
- tmin = ctmin;
- if (e1 > 1.0f && ctmax < tmax)
- tmax = ctmax;
- }
- else
- {
- return 0;
- }
- }
-
- return 1;
-}
-
-static bool inBetweenAngle(float a, float amin, float amax, float& t)
-{
- if (amax < amin) amax += (float)M_PI*2;
- if (a < amin-(float)M_PI) a += (float)M_PI*2;
- if (a > amin+(float)M_PI) a -= (float)M_PI*2;
- if (a >= amin && a < amax)
- {
- t = (a-amin) / (amax-amin);
- return true;
- }
- return false;
-}
-
-static float interpolateToi(float a, const float* dir, const float* toi, const int ntoi)
-{
- for (int i = 0; i < ntoi; ++i)
- {
- int next = (i+1) % ntoi;
- float t;
- if (inBetweenAngle(a, dir[i], dir[next], t))
- {
- return lerp(toi[i], toi[next], t);
- }
- }
- return 0;
-}
-
-KX_ObstacleSimulation::KX_ObstacleSimulation(MT_Scalar levelHeight, bool enableVisualization)
-: m_levelHeight(levelHeight)
-, m_enableVisualization(enableVisualization)
-{
-
-}
-
-KX_ObstacleSimulation::~KX_ObstacleSimulation()
-{
- for (size_t i=0; i<m_obstacles.size(); i++)
- {
- KX_Obstacle* obs = m_obstacles[i];
- delete obs;
- }
- m_obstacles.clear();
-}
-KX_Obstacle* KX_ObstacleSimulation::CreateObstacle(KX_GameObject* gameobj)
-{
- KX_Obstacle* obstacle = new KX_Obstacle();
- obstacle->m_gameObj = gameobj;
-
- vset(obstacle->vel, 0,0);
- vset(obstacle->pvel, 0,0);
- vset(obstacle->dvel, 0,0);
- vset(obstacle->nvel, 0,0);
- for (int i = 0; i < VEL_HIST_SIZE; ++i)
- vset(&obstacle->hvel[i*2], 0,0);
- obstacle->hhead = 0;
-
- gameobj->RegisterObstacle(this);
- m_obstacles.push_back(obstacle);
- return obstacle;
-}
-
-void KX_ObstacleSimulation::AddObstacleForObj(KX_GameObject* gameobj)
-{
- KX_Obstacle* obstacle = CreateObstacle(gameobj);
- struct Object* blenderobject = gameobj->GetBlenderObject();
- obstacle->m_type = KX_OBSTACLE_OBJ;
- obstacle->m_shape = KX_OBSTACLE_CIRCLE;
- obstacle->m_rad = blenderobject->obstacleRad;
-}
-
-void KX_ObstacleSimulation::AddObstaclesForNavMesh(KX_NavMeshObject* navmeshobj)
-{
- dtStatNavMesh* navmesh = navmeshobj->GetNavMesh();
- if (navmesh)
- {
- int npoly = navmesh->getPolyCount();
- for (int pi=0; pi<npoly; pi++)
- {
- const dtStatPoly* poly = navmesh->getPoly(pi);
-
- for (int i = 0, j = (int)poly->nv-1; i < (int)poly->nv; j = i++)
- {
- if (poly->n[j]) continue;
- const float* vj = navmesh->getVertex(poly->v[j]);
- const float* vi = navmesh->getVertex(poly->v[i]);
-
- KX_Obstacle* obstacle = CreateObstacle(navmeshobj);
- obstacle->m_type = KX_OBSTACLE_NAV_MESH;
- obstacle->m_shape = KX_OBSTACLE_SEGMENT;
- obstacle->m_pos = MT_Point3(vj[0], vj[2], vj[1]);
- obstacle->m_pos2 = MT_Point3(vi[0], vi[2], vi[1]);
- obstacle->m_rad = 0;
- }
- }
- }
-}
-
-void KX_ObstacleSimulation::DestroyObstacleForObj(KX_GameObject* gameobj)
-{
- for (size_t i=0; i<m_obstacles.size(); )
- {
- if (m_obstacles[i]->m_gameObj == gameobj)
- {
- KX_Obstacle* obstacle = m_obstacles[i];
- obstacle->m_gameObj->UnregisterObstacle();
- m_obstacles[i] = m_obstacles.back();
- m_obstacles.pop_back();
- delete obstacle;
- }
- else
- i++;
- }
-}
-
-void KX_ObstacleSimulation::UpdateObstacles()
-{
- for (size_t i=0; i<m_obstacles.size(); i++)
- {
- if (m_obstacles[i]->m_type==KX_OBSTACLE_NAV_MESH || m_obstacles[i]->m_shape==KX_OBSTACLE_SEGMENT)
- continue;
-
- KX_Obstacle* obs = m_obstacles[i];
- obs->m_pos = obs->m_gameObj->NodeGetWorldPosition();
- obs->vel[0] = obs->m_gameObj->GetLinearVelocity().x();
- obs->vel[1] = obs->m_gameObj->GetLinearVelocity().y();
-
- // Update velocity history and calculate perceived (average) velocity.
- copy_v2_v2(&obs->hvel[obs->hhead * 2], obs->vel);
- obs->hhead = (obs->hhead+1) % VEL_HIST_SIZE;
- vset(obs->pvel,0,0);
- for (int j = 0; j < VEL_HIST_SIZE; ++j)
- add_v2_v2v2(obs->pvel, obs->pvel, &obs->hvel[j * 2]);
- mul_v2_fl(obs->pvel, 1.0f / VEL_HIST_SIZE);
- }
-}
-
-KX_Obstacle* KX_ObstacleSimulation::GetObstacle(KX_GameObject* gameobj)
-{
- for (size_t i=0; i<m_obstacles.size(); i++)
- {
- if (m_obstacles[i]->m_gameObj == gameobj)
- return m_obstacles[i];
- }
-
- return NULL;
-}
-
-void KX_ObstacleSimulation::AdjustObstacleVelocity(KX_Obstacle* activeObst, KX_NavMeshObject* activeNavMeshObj,
- MT_Vector3& velocity, MT_Scalar maxDeltaSpeed,MT_Scalar maxDeltaAngle)
-{
-}
-
-void KX_ObstacleSimulation::DrawObstacles()
-{
- if (!m_enableVisualization)
- return;
- static const MT_Vector3 bluecolor(0,0,1);
- static const MT_Vector3 normal(0.0f, 0.0f, 1.0f);
- static const int SECTORS_NUM = 32;
- for (size_t i=0; i<m_obstacles.size(); i++)
- {
- if (m_obstacles[i]->m_shape==KX_OBSTACLE_SEGMENT)
- {
- MT_Point3 p1 = m_obstacles[i]->m_pos;
- MT_Point3 p2 = m_obstacles[i]->m_pos2;
- //apply world transform
- if (m_obstacles[i]->m_type == KX_OBSTACLE_NAV_MESH)
- {
- KX_NavMeshObject* navmeshobj = static_cast<KX_NavMeshObject*>(m_obstacles[i]->m_gameObj);
- p1 = navmeshobj->TransformToWorldCoords(p1);
- p2 = navmeshobj->TransformToWorldCoords(p2);
- }
-
- KX_RasterizerDrawDebugLine(p1, p2, bluecolor);
- }
- else if (m_obstacles[i]->m_shape==KX_OBSTACLE_CIRCLE)
- {
- KX_RasterizerDrawDebugCircle(m_obstacles[i]->m_pos, m_obstacles[i]->m_rad, bluecolor,
- normal, SECTORS_NUM);
- }
- }
-}
-
-static MT_Point3 nearestPointToObstacle(MT_Point3& pos ,KX_Obstacle* obstacle)
-{
- switch (obstacle->m_shape)
- {
- case KX_OBSTACLE_SEGMENT :
- {
- MT_Vector3 ab = obstacle->m_pos2 - obstacle->m_pos;
- if (!ab.fuzzyZero())
- {
- const MT_Scalar dist = ab.length();
- MT_Vector3 abdir = ab.normalized();
- MT_Vector3 v = pos - obstacle->m_pos;
- MT_Scalar proj = abdir.dot(v);
- CLAMP(proj, 0, dist);
- MT_Point3 res = obstacle->m_pos + abdir*proj;
- return res;
- }
- ATTR_FALLTHROUGH;
- }
- case KX_OBSTACLE_CIRCLE :
- default:
- return obstacle->m_pos;
- }
-}
-
-static bool filterObstacle(KX_Obstacle* activeObst, KX_NavMeshObject* activeNavMeshObj, KX_Obstacle* otherObst,
- float levelHeight)
-{
- //filter obstacles by type
- if ( (otherObst == activeObst) ||
- (otherObst->m_type==KX_OBSTACLE_NAV_MESH && otherObst->m_gameObj!=activeNavMeshObj) )
- return false;
-
- //filter obstacles by position
- MT_Point3 p = nearestPointToObstacle(activeObst->m_pos, otherObst);
- if ( fabsf(activeObst->m_pos.z() - p.z()) > levelHeight)
- return false;
-
- return true;
-}
-
-///////////*********TOI_rays**********/////////////////
-KX_ObstacleSimulationTOI::KX_ObstacleSimulationTOI(MT_Scalar levelHeight, bool enableVisualization)
-: KX_ObstacleSimulation(levelHeight, enableVisualization),
- m_maxSamples(32),
- m_minToi(0.0f),
- m_maxToi(0.0f),
- m_velWeight(1.0f),
- m_curVelWeight(1.0f),
- m_toiWeight(1.0f),
- m_collisionWeight(1.0f)
-{
-}
-
-
-void KX_ObstacleSimulationTOI::AdjustObstacleVelocity(KX_Obstacle* activeObst, KX_NavMeshObject* activeNavMeshObj,
- MT_Vector3& velocity, MT_Scalar maxDeltaSpeed, MT_Scalar maxDeltaAngle)
-{
- int nobs = m_obstacles.size();
- int obstidx = std::find(m_obstacles.begin(), m_obstacles.end(), activeObst) - m_obstacles.begin();
- if (obstidx == nobs)
- return;
-
- vset(activeObst->dvel, velocity.x(), velocity.y());
-
- //apply RVO
- sampleRVO(activeObst, activeNavMeshObj, maxDeltaAngle);
-
- // Fake dynamic constraint.
- float dv[2];
- float vel[2];
- sub_v2_v2v2(dv, activeObst->nvel, activeObst->vel);
- float ds = len_v2(dv);
- if (ds > maxDeltaSpeed || ds<-maxDeltaSpeed)
- mul_v2_fl(dv, fabs(maxDeltaSpeed / ds));
- add_v2_v2v2(vel, activeObst->vel, dv);
-
- velocity.x() = vel[0];
- velocity.y() = vel[1];
-}
-
-///////////*********TOI_rays**********/////////////////
-static const int AVOID_MAX_STEPS = 128;
-struct TOICircle
-{
- TOICircle() : n(0), minToi(0), maxToi(1) {}
- float toi[AVOID_MAX_STEPS]; // Time of impact (seconds)
- float toie[AVOID_MAX_STEPS]; // Time of exit (seconds)
- float dir[AVOID_MAX_STEPS]; // Direction (radians)
- int n; // Number of samples
- float minToi, maxToi; // Min/max TOI (seconds)
-};
-
-KX_ObstacleSimulationTOI_rays::KX_ObstacleSimulationTOI_rays(MT_Scalar levelHeight, bool enableVisualization):
- KX_ObstacleSimulationTOI(levelHeight, enableVisualization)
-{
- m_maxSamples = 32;
- m_minToi = 0.5f;
- m_maxToi = 1.2f;
- m_velWeight = 4.0f;
- m_toiWeight = 1.0f;
- m_collisionWeight = 100.0f;
-}
-
-
-void KX_ObstacleSimulationTOI_rays::sampleRVO(KX_Obstacle* activeObst, KX_NavMeshObject* activeNavMeshObj,
- const float maxDeltaAngle)
-{
- MT_Vector2 vel(activeObst->dvel[0], activeObst->dvel[1]);
- float vmax = (float) vel.length();
- float odir = (float) atan2(vel.y(), vel.x());
-
- MT_Vector2 ddir = vel;
- ddir.normalize();
-
- float bestScore = FLT_MAX;
- float bestDir = odir;
- float bestToi = 0;
-
- TOICircle tc;
- tc.n = m_maxSamples;
- tc.minToi = m_minToi;
- tc.maxToi = m_maxToi;
-
- const int iforw = m_maxSamples/2;
- const float aoff = (float)iforw / (float)m_maxSamples;
-
- size_t nobs = m_obstacles.size();
- for (int iter = 0; iter < m_maxSamples; ++iter)
- {
- // Calculate sample velocity
- const float ndir = ((float)iter/(float)m_maxSamples) - aoff;
- const float dir = odir+ndir*(float)M_PI*2.0f;
- MT_Vector2 svel;
- svel.x() = cosf(dir) * vmax;
- svel.y() = sinf(dir) * vmax;
-
- // Find min time of impact and exit amongst all obstacles.
- float tmin = m_maxToi;
- float tmine = 0.0f;
- for (int i = 0; i < nobs; ++i)
- {
- KX_Obstacle* ob = m_obstacles[i];
- bool res = filterObstacle(activeObst, activeNavMeshObj, ob, m_levelHeight);
- if (!res)
- continue;
-
- float htmin,htmax;
-
- if (ob->m_shape == KX_OBSTACLE_CIRCLE)
- {
- MT_Vector2 vab;
- if (len_v2(ob->vel) < 0.01f * 0.01f) {
- // Stationary, use VO
- vab = svel;
- }
- else
- {
- // Moving, use RVO
- vab = 2*svel - vel - ob->vel;
- }
-
- if (!sweepCircleCircle(MT_3D_AS_2D(activeObst->m_pos), activeObst->m_rad,
- vab, MT_3D_AS_2D(ob->m_pos), ob->m_rad, htmin, htmax))
- {
- continue;
- }
- }
- else if (ob->m_shape == KX_OBSTACLE_SEGMENT)
- {
- MT_Point3 p1 = ob->m_pos;
- MT_Point3 p2 = ob->m_pos2;
- //apply world transform
- if (ob->m_type == KX_OBSTACLE_NAV_MESH)
- {
- KX_NavMeshObject* navmeshobj = static_cast<KX_NavMeshObject*>(ob->m_gameObj);
- p1 = navmeshobj->TransformToWorldCoords(p1);
- p2 = navmeshobj->TransformToWorldCoords(p2);
- }
-
- if (!sweepCircleSegment(MT_3D_AS_2D(activeObst->m_pos), activeObst->m_rad, svel,
- MT_3D_AS_2D(p1), MT_3D_AS_2D(p2), ob->m_rad, htmin, htmax))
- {
- continue;
- }
- }
- else {
- continue;
- }
-
- if (htmin > 0.0f)
- {
- // The closest obstacle is somewhere ahead of us, keep track of nearest obstacle.
- if (htmin < tmin)
- tmin = htmin;
- }
- else if (htmax > 0.0f)
- {
- // The agent overlaps the obstacle, keep track of first safe exit.
- if (htmax > tmine)
- tmine = htmax;
- }
- }
-
- // Calculate sample penalties and final score.
- const float apen = m_velWeight * fabsf(ndir);
- const float tpen = m_toiWeight * (1.0f/(0.0001f+tmin/m_maxToi));
- const float cpen = m_collisionWeight * (tmine/m_minToi)*(tmine/m_minToi);
- const float score = apen + tpen + cpen;
-
- // Update best score.
- if (score < bestScore)
- {
- bestDir = dir;
- bestToi = tmin;
- bestScore = score;
- }
-
- tc.dir[iter] = dir;
- tc.toi[iter] = tmin;
- tc.toie[iter] = tmine;
- }
-
- if (len_v2(activeObst->vel) > 0.1f) {
- // Constrain max turn rate.
- float cura = atan2(activeObst->vel[1],activeObst->vel[0]);
- float da = bestDir - cura;
- if (da < -M_PI) da += (float)M_PI*2;
- if (da > M_PI) da -= (float)M_PI*2;
- if (da < -maxDeltaAngle)
- {
- bestDir = cura - maxDeltaAngle;
- bestToi = min(bestToi, interpolateToi(bestDir, tc.dir, tc.toi, tc.n));
- }
- else if (da > maxDeltaAngle)
- {
- bestDir = cura + maxDeltaAngle;
- bestToi = min(bestToi, interpolateToi(bestDir, tc.dir, tc.toi, tc.n));
- }
- }
-
- // Adjust speed when time of impact is less than min TOI.
- if (bestToi < m_minToi)
- vmax *= bestToi/m_minToi;
-
- // New steering velocity.
- activeObst->nvel[0] = cosf(bestDir) * vmax;
- activeObst->nvel[1] = sinf(bestDir) * vmax;
-}
-
-///////////********* TOI_cells**********/////////////////
-
-static void processSamples(KX_Obstacle* activeObst, KX_NavMeshObject* activeNavMeshObj,
- KX_Obstacles& obstacles, float levelHeight, const float vmax,
- const float* spos, const float cs, const int nspos, float* res,
- float maxToi, float velWeight, float curVelWeight, float sideWeight,
- float toiWeight)
-{
- vset(res, 0,0);
-
- const float ivmax = 1.0f / vmax;
-
- float adir[2] /*, adist */;
- if (normalize_v2_v2(adir, activeObst->pvel) <= 0.01f) {
- zero_v2(adir);
- }
-
- float activeObstPos[2];
- vset(activeObstPos, activeObst->m_pos.x(), activeObst->m_pos.y());
- /* adist = vdot(adir, activeObstPos); */
-
- float minPenalty = FLT_MAX;
-
- for (int n = 0; n < nspos; ++n)
- {
- float vcand[2];
- copy_v2_v2(vcand, &spos[n * 2]);
-
- // Find min time of impact and exit amongst all obstacles.
- float tmin = maxToi;
- float side = 0;
- int nside = 0;
-
- for (int i = 0; i < obstacles.size(); ++i)
- {
- KX_Obstacle* ob = obstacles[i];
- bool res = filterObstacle(activeObst, activeNavMeshObj, ob, levelHeight);
- if (!res)
- continue;
- float htmin, htmax;
-
- if (ob->m_shape==KX_OBSTACLE_CIRCLE)
- {
- float vab[2];
-
- // Moving, use RVO
- mul_v2_v2fl(vab, vcand, 2);
- sub_v2_v2v2(vab, vab, activeObst->vel);
- sub_v2_v2v2(vab, vab, ob->vel);
-
- // Side
- // NOTE: dp, and dv are constant over the whole calculation,
- // they can be precomputed per object.
- const float* pa = activeObstPos;
- float pb[2];
- vset(pb, ob->m_pos.x(), ob->m_pos.y());
-
- const float orig[2] = {0, 0};
- float dp[2], dv[2], np[2];
- sub_v2_v2v2(dp, pb, pa);
- normalize_v2(dp);
- sub_v2_v2v2(dv, ob->dvel, activeObst->dvel);
-
- /* TODO: use line_point_side_v2 */
- if (area_tri_signed_v2(orig, dp, dv) < 0.01f) {
- np[0] = -dp[1];
- np[1] = dp[0];
- }
- else {
- np[0] = dp[1];
- np[1] = -dp[0];
- }
-
- side += clamp(min(dot_v2v2(dp, vab),
- dot_v2v2(np, vab)) * 2.0f, 0.0f, 1.0f);
- nside++;
-
- if (!sweepCircleCircle(MT_3D_AS_2D(activeObst->m_pos), activeObst->m_rad,
- vab, MT_3D_AS_2D(ob->m_pos), ob->m_rad, htmin, htmax))
- {
- continue;
- }
-
- // Handle overlapping obstacles.
- if (htmin < 0.0f && htmax > 0.0f)
- {
- // Avoid more when overlapped.
- htmin = -htmin * 0.5f;
- }
- }
- else if (ob->m_shape == KX_OBSTACLE_SEGMENT)
- {
- MT_Point3 p1 = ob->m_pos;
- MT_Point3 p2 = ob->m_pos2;
- //apply world transform
- if (ob->m_type == KX_OBSTACLE_NAV_MESH)
- {
- KX_NavMeshObject* navmeshobj = static_cast<KX_NavMeshObject*>(ob->m_gameObj);
- p1 = navmeshobj->TransformToWorldCoords(p1);
- p2 = navmeshobj->TransformToWorldCoords(p2);
- }
- float p[2], q[2];
- vset(p, p1.x(), p1.y());
- vset(q, p2.x(), p2.y());
-
- // NOTE: the segments are assumed to come from a navmesh which is shrunken by
- // the agent radius, hence the use of really small radius.
- // This can be handle more efficiently by using seg-seg test instead.
- // If the whole segment is to be treated as obstacle, use agent->rad instead of 0.01f!
- const float r = 0.01f; // agent->rad
- if (dist_squared_to_line_segment_v2(activeObstPos, p, q) < sqr(r + ob->m_rad)) {
- float sdir[2], snorm[2];
- sub_v2_v2v2(sdir, q, p);
- snorm[0] = sdir[1];
- snorm[1] = -sdir[0];
- // If the velocity is pointing towards the segment, no collision.
- if (dot_v2v2(snorm, vcand) < 0.0f)
- continue;
- // Else immediate collision.
- htmin = 0.0f;
- htmax = 10.0f;
- }
- else
- {
- if (!sweepCircleSegment(activeObstPos, r, vcand, p, q, ob->m_rad, htmin, htmax))
- continue;
- }
-
- // Avoid less when facing walls.
- htmin *= 2.0f;
- }
- else {
- continue;
- }
-
- if (htmin >= 0.0f)
- {
- // The closest obstacle is somewhere ahead of us, keep track of nearest obstacle.
- if (htmin < tmin)
- tmin = htmin;
- }
- }
-
- // Normalize side bias, to prevent it dominating too much.
- if (nside)
- side /= nside;
-
- const float vpen = velWeight * (len_v2v2(vcand, activeObst->dvel) * ivmax);
- const float vcpen = curVelWeight * (len_v2v2(vcand, activeObst->vel) * ivmax);
- const float spen = sideWeight * side;
- const float tpen = toiWeight * (1.0f/(0.1f+tmin/maxToi));
-
- const float penalty = vpen + vcpen + spen + tpen;
-
- if (penalty < minPenalty) {
- minPenalty = penalty;
- copy_v2_v2(res, vcand);
- }
- }
-}
-
-void KX_ObstacleSimulationTOI_cells::sampleRVO(KX_Obstacle* activeObst, KX_NavMeshObject* activeNavMeshObj,
- const float maxDeltaAngle)
-{
- vset(activeObst->nvel, 0.f, 0.f);
- float vmax = len_v2(activeObst->dvel);
-
- float* spos = new float[2*m_maxSamples];
- int nspos = 0;
-
- if (!m_adaptive)
- {
- const float cvx = activeObst->dvel[0]*m_bias;
- const float cvy = activeObst->dvel[1]*m_bias;
- float vmax = len_v2(activeObst->dvel);
- const float vrange = vmax*(1-m_bias);
- const float cs = 1.0f / (float)m_sampleRadius*vrange;
-
- for (int y = -m_sampleRadius; y <= m_sampleRadius; ++y)
- {
- for (int x = -m_sampleRadius; x <= m_sampleRadius; ++x)
- {
- if (nspos < m_maxSamples)
- {
- const float vx = cvx + (float)(x+0.5f)*cs;
- const float vy = cvy + (float)(y+0.5f)*cs;
- if (vx*vx+vy*vy > sqr(vmax+cs/2)) continue;
- spos[nspos*2+0] = vx;
- spos[nspos*2+1] = vy;
- nspos++;
- }
- }
- }
- processSamples(activeObst, activeNavMeshObj, m_obstacles, m_levelHeight, vmax, spos, cs/2,
- nspos, activeObst->nvel, m_maxToi, m_velWeight, m_curVelWeight, m_collisionWeight, m_toiWeight);
- }
- else
- {
- int rad;
- float res[2];
- float cs;
- // First sample location.
- rad = 4;
- res[0] = activeObst->dvel[0]*m_bias;
- res[1] = activeObst->dvel[1]*m_bias;
- cs = vmax*(2-m_bias*2) / (float)(rad-1);
-
- for (int k = 0; k < 5; ++k)
- {
- const float half = (rad-1)*cs*0.5f;
-
- nspos = 0;
- for (int y = 0; y < rad; ++y)
- {
- for (int x = 0; x < rad; ++x)
- {
- const float v_xy[2] = {
- res[0] + x * cs - half,
- res[1] + y * cs - half};
-
- if (len_squared_v2(v_xy) > sqr(vmax + cs / 2))
- continue;
-
- copy_v2_v2(&spos[nspos * 2 + 0], v_xy);
- nspos++;
- }
- }
-
- processSamples(activeObst, activeNavMeshObj, m_obstacles, m_levelHeight, vmax, spos, cs/2,
- nspos, res, m_maxToi, m_velWeight, m_curVelWeight, m_collisionWeight, m_toiWeight);
-
- cs *= 0.5f;
- }
- copy_v2_v2(activeObst->nvel, res);
- }
-
- delete [] spos;
-}
-
-KX_ObstacleSimulationTOI_cells::KX_ObstacleSimulationTOI_cells(MT_Scalar levelHeight, bool enableVisualization)
-: KX_ObstacleSimulationTOI(levelHeight, enableVisualization)
-, m_bias(0.4f)
-, m_adaptive(true)
-, m_sampleRadius(15)
-{
- m_maxSamples = (m_sampleRadius*2+1)*(m_sampleRadius*2+1) + 100;
- m_maxToi = 1.5f;
- m_velWeight = 2.0f;
- m_curVelWeight = 0.75f;
- m_toiWeight = 2.5f;
- m_collisionWeight = 0.75f; //side_weight
-}
diff --git a/source/gameengine/Ketsji/KX_ObstacleSimulation.h b/source/gameengine/Ketsji/KX_ObstacleSimulation.h
deleted file mode 100644
index 50589b5bc69..00000000000
--- a/source/gameengine/Ketsji/KX_ObstacleSimulation.h
+++ /dev/null
@@ -1,134 +0,0 @@
-/*
- * Simulation for obstacle avoidance behavior
- * (based on Cane Project - http://code.google.com/p/cane by Mikko Mononen (c) 2009)
- *
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-#ifndef __KX_OBSTACLESIMULATION_H__
-#define __KX_OBSTACLESIMULATION_H__
-
-#include <vector>
-#include "MT_Point2.h"
-#include "MT_Point3.h"
-
-class KX_GameObject;
-class KX_NavMeshObject;
-
-enum KX_OBSTACLE_TYPE
-{
- KX_OBSTACLE_OBJ,
- KX_OBSTACLE_NAV_MESH,
-};
-
-enum KX_OBSTACLE_SHAPE
-{
- KX_OBSTACLE_CIRCLE,
- KX_OBSTACLE_SEGMENT,
-};
-
-#define VEL_HIST_SIZE 6
-struct KX_Obstacle
-{
- KX_OBSTACLE_TYPE m_type;
- KX_OBSTACLE_SHAPE m_shape;
- MT_Point3 m_pos;
- MT_Point3 m_pos2;
- MT_Scalar m_rad;
-
- float vel[2];
- float pvel[2];
- float dvel[2];
- float nvel[2];
- float hvel[VEL_HIST_SIZE*2];
- int hhead;
-
-
- KX_GameObject* m_gameObj;
-};
-typedef std::vector<KX_Obstacle*> KX_Obstacles;
-
-class KX_ObstacleSimulation
-{
-protected:
- KX_Obstacles m_obstacles;
-
- MT_Scalar m_levelHeight;
- bool m_enableVisualization;
-
- KX_Obstacle* CreateObstacle(KX_GameObject* gameobj);
-public:
- KX_ObstacleSimulation(MT_Scalar levelHeight, bool enableVisualization);
- virtual ~KX_ObstacleSimulation();
-
- void DrawObstacles();
- //void DebugDraw();
-
- void AddObstacleForObj(KX_GameObject* gameobj);
- void DestroyObstacleForObj(KX_GameObject* gameobj);
- void AddObstaclesForNavMesh(KX_NavMeshObject* navmesh);
- KX_Obstacle* GetObstacle(KX_GameObject* gameobj);
- void UpdateObstacles();
- virtual void AdjustObstacleVelocity(KX_Obstacle* activeObst, KX_NavMeshObject* activeNavMeshObj,
- MT_Vector3& velocity, MT_Scalar maxDeltaSpeed,MT_Scalar maxDeltaAngle);
-
-};
-class KX_ObstacleSimulationTOI: public KX_ObstacleSimulation
-{
-protected:
- int m_maxSamples; // Number of sample steps
- float m_minToi; // Min TOI
- float m_maxToi; // Max TOI
- float m_velWeight; // Sample selection angle weight
- float m_curVelWeight; // Sample selection current velocity weight
- float m_toiWeight; // Sample selection TOI weight
- float m_collisionWeight; // Sample selection collision weight
-
- virtual void sampleRVO(KX_Obstacle* activeObst, KX_NavMeshObject* activeNavMeshObj,
- const float maxDeltaAngle) = 0;
-public:
- KX_ObstacleSimulationTOI(MT_Scalar levelHeight, bool enableVisualization);
- virtual void AdjustObstacleVelocity(KX_Obstacle* activeObst, KX_NavMeshObject* activeNavMeshObj,
- MT_Vector3& velocity, MT_Scalar maxDeltaSpeed,MT_Scalar maxDeltaAngle);
-};
-
-class KX_ObstacleSimulationTOI_rays: public KX_ObstacleSimulationTOI
-{
-protected:
- virtual void sampleRVO(KX_Obstacle* activeObst, KX_NavMeshObject* activeNavMeshObj,
- const float maxDeltaAngle);
-public:
- KX_ObstacleSimulationTOI_rays(MT_Scalar levelHeight, bool enableVisualization);
-};
-
-class KX_ObstacleSimulationTOI_cells: public KX_ObstacleSimulationTOI
-{
-protected:
- float m_bias;
- bool m_adaptive;
- int m_sampleRadius;
- virtual void sampleRVO(KX_Obstacle* activeObst, KX_NavMeshObject* activeNavMeshObj,
- const float maxDeltaAngle);
-public:
- KX_ObstacleSimulationTOI_cells(MT_Scalar levelHeight, bool enableVisualization);
-};
-
-#endif
diff --git a/source/gameengine/Ketsji/KX_OrientationInterpolator.cpp b/source/gameengine/Ketsji/KX_OrientationInterpolator.cpp
deleted file mode 100644
index bcaa1e60e92..00000000000
--- a/source/gameengine/Ketsji/KX_OrientationInterpolator.cpp
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Ketsji/KX_OrientationInterpolator.cpp
- * \ingroup ketsji
- */
-
-
-#include "KX_OrientationInterpolator.h"
-#include "MT_Matrix3x3.h"
-#include "KX_IScalarInterpolator.h"
-
-void KX_OrientationInterpolator::Execute(float currentTime) const
-{
- MT_Vector3 eul(m_ipos[0]->GetValue(currentTime),
- m_ipos[1]->GetValue(currentTime),
- m_ipos[2]->GetValue(currentTime));
- MT_Scalar ci = cosf(eul[0]);
- MT_Scalar cj = cosf(eul[1]);
- MT_Scalar ch = cosf(eul[2]);
- MT_Scalar si = sinf(eul[0]);
- MT_Scalar sj = sinf(eul[1]);
- MT_Scalar sh = sinf(eul[2]);
- MT_Scalar cc = ci*ch;
- MT_Scalar cs = ci*sh;
- MT_Scalar sc = si*ch;
- MT_Scalar ss = si*sh;
-
- m_target.setValue(cj*ch, sj*sc-cs, sj*cc+ss,
- cj*sh, sj*ss+cc, sj*cs-sc,
- -sj, cj*si, cj*ci);
-}
diff --git a/source/gameengine/Ketsji/KX_OrientationInterpolator.h b/source/gameengine/Ketsji/KX_OrientationInterpolator.h
deleted file mode 100644
index 59014b70174..00000000000
--- a/source/gameengine/Ketsji/KX_OrientationInterpolator.h
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file KX_OrientationInterpolator.h
- * \ingroup ketsji
- */
-
-#ifndef __KX_ORIENTATIONINTERPOLATOR_H__
-#define __KX_ORIENTATIONINTERPOLATOR_H__
-
-#include "KX_IInterpolator.h"
-
-class MT_Matrix3x3;
-class KX_IScalarInterpolator;
-
-class KX_OrientationInterpolator : public KX_IInterpolator {
-public:
- KX_OrientationInterpolator(MT_Matrix3x3& target,
- KX_IScalarInterpolator **ipos)
- : m_target(target)
- {
- m_ipos[0] = ipos[0];
- m_ipos[1] = ipos[1];
- m_ipos[2] = ipos[2];
- }
-
- virtual void Execute(float currentTime) const;
-
-private:
- MT_Matrix3x3& m_target;
- KX_IScalarInterpolator *m_ipos[3];
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:KX_OrientationInterpolator")
-#endif
-};
-
-#endif
-
diff --git a/source/gameengine/Ketsji/KX_ParentActuator.cpp b/source/gameengine/Ketsji/KX_ParentActuator.cpp
deleted file mode 100644
index 0b133400920..00000000000
--- a/source/gameengine/Ketsji/KX_ParentActuator.cpp
+++ /dev/null
@@ -1,205 +0,0 @@
-/*
- * Set or remove an objects parent
- *
- *
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Ketsji/KX_ParentActuator.cpp
- * \ingroup ketsji
- */
-
-
-#include "KX_ParentActuator.h"
-#include "KX_GameObject.h"
-#include "KX_PythonInit.h"
-
-#include "EXP_PyObjectPlus.h"
-
-/* ------------------------------------------------------------------------- */
-/* Native functions */
-/* ------------------------------------------------------------------------- */
-
-KX_ParentActuator::KX_ParentActuator(SCA_IObject *gameobj,
- int mode,
- bool addToCompound,
- bool ghost,
- SCA_IObject *ob)
- : SCA_IActuator(gameobj, KX_ACT_PARENT),
- m_mode(mode),
- m_addToCompound(addToCompound),
- m_ghost(ghost),
- m_ob(ob)
-{
- if (m_ob)
- m_ob->RegisterActuator(this);
-}
-
-
-
-KX_ParentActuator::~KX_ParentActuator()
-{
- if (m_ob)
- m_ob->UnregisterActuator(this);
-}
-
-
-
-CValue* KX_ParentActuator::GetReplica()
-{
- KX_ParentActuator* replica = new KX_ParentActuator(*this);
- // replication just copy the m_base pointer => common random generator
- replica->ProcessReplica();
- return replica;
-}
-
-void KX_ParentActuator::ProcessReplica()
-{
- if (m_ob)
- m_ob->RegisterActuator(this);
- SCA_IActuator::ProcessReplica();
-}
-
-
-bool KX_ParentActuator::UnlinkObject(SCA_IObject* clientobj)
-{
- if (clientobj == m_ob)
- {
- // this object is being deleted, we cannot continue to track it.
- m_ob = NULL;
- return true;
- }
- return false;
-}
-
-void KX_ParentActuator::Relink(CTR_Map<CTR_HashedPtr, void*> *obj_map)
-{
- void **h_obj = (*obj_map)[m_ob];
- if (h_obj) {
- if (m_ob)
- m_ob->UnregisterActuator(this);
- m_ob = (SCA_IObject*)(*h_obj);
- m_ob->RegisterActuator(this);
- }
-}
-
-
-
-bool KX_ParentActuator::Update()
-{
- bool bNegativeEvent = IsNegativeEvent();
- RemoveAllEvents();
-
- if (bNegativeEvent)
- return false; // do nothing on negative events
-
- KX_GameObject *obj = (KX_GameObject*) GetParent();
- KX_Scene *scene = KX_GetActiveScene();
- switch (m_mode) {
- case KX_PARENT_SET:
- if (m_ob)
- obj->SetParent(scene, (KX_GameObject*)m_ob, m_addToCompound, m_ghost);
- break;
- case KX_PARENT_REMOVE:
- obj->RemoveParent(scene);
- break;
- };
-
- return false;
-}
-
-#ifdef WITH_PYTHON
-
-/* ------------------------------------------------------------------------- */
-/* Python functions */
-/* ------------------------------------------------------------------------- */
-
-/* Integration hooks ------------------------------------------------------- */
-PyTypeObject KX_ParentActuator::Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "KX_ParentActuator",
- sizeof(PyObjectPlus_Proxy),
- 0,
- py_base_dealloc,
- 0,
- 0,
- 0,
- 0,
- py_base_repr,
- 0,0,0,0,0,0,0,0,0,
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
- 0,0,0,0,0,0,0,
- Methods,
- 0,
- 0,
- &SCA_IActuator::Type,
- 0,0,0,0,0,0,
- py_base_new
-};
-
-PyMethodDef KX_ParentActuator::Methods[] = {
- {NULL,NULL} //Sentinel
-};
-
-PyAttributeDef KX_ParentActuator::Attributes[] = {
- KX_PYATTRIBUTE_RW_FUNCTION("object", KX_ParentActuator, pyattr_get_object, pyattr_set_object),
- KX_PYATTRIBUTE_INT_RW("mode", KX_PARENT_NODEF+1, KX_PARENT_MAX-1, true, KX_ParentActuator, m_mode),
- KX_PYATTRIBUTE_BOOL_RW("compound", KX_ParentActuator, m_addToCompound),
- KX_PYATTRIBUTE_BOOL_RW("ghost", KX_ParentActuator, m_ghost),
- { NULL } //Sentinel
-};
-
-PyObject *KX_ParentActuator::pyattr_get_object(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_ParentActuator* actuator = static_cast<KX_ParentActuator*>(self);
- if (!actuator->m_ob)
- Py_RETURN_NONE;
- else
- return actuator->m_ob->GetProxy();
-}
-
-int KX_ParentActuator::pyattr_set_object(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_ParentActuator* actuator = static_cast<KX_ParentActuator*>(self);
- KX_GameObject *gameobj;
-
- if (!ConvertPythonToGameObject(actuator->GetLogicManager(), value, &gameobj, true, "actuator.object = value: KX_ParentActuator"))
- return PY_SET_ATTR_FAIL; // ConvertPythonToGameObject sets the error
-
- if (actuator->m_ob != NULL)
- actuator->m_ob->UnregisterActuator(actuator);
-
- actuator->m_ob = (SCA_IObject*) gameobj;
-
- if (actuator->m_ob)
- actuator->m_ob->RegisterActuator(actuator);
-
- return PY_SET_ATTR_SUCCESS;
-}
-
-#endif // WITH_PYTHON
-
-/* eof */
diff --git a/source/gameengine/Ketsji/KX_ParentActuator.h b/source/gameengine/Ketsji/KX_ParentActuator.h
deleted file mode 100644
index 40baac6b2b2..00000000000
--- a/source/gameengine/Ketsji/KX_ParentActuator.h
+++ /dev/null
@@ -1,91 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file KX_ParentActuator.h
- * \ingroup ketsji
- * \brief Set or remove an objects parent
- */
-
-#ifndef __KX_PARENTACTUATOR_H__
-#define __KX_PARENTACTUATOR_H__
-
-#include "SCA_IActuator.h"
-#include "SCA_LogicManager.h"
-
-class KX_ParentActuator : public SCA_IActuator
-{
- Py_Header
-
- /** Mode */
- int m_mode;
-
- /** option */
- bool m_addToCompound;
- bool m_ghost;
- /** Object to set as parent */
- SCA_IObject *m_ob;
-
-
-
-public:
- enum KX_PARENTACT_MODE
- {
- KX_PARENT_NODEF = 0,
- KX_PARENT_SET,
- KX_PARENT_REMOVE,
- KX_PARENT_MAX
-
- };
-
- KX_ParentActuator(class SCA_IObject* gameobj,
- int mode,
- bool addToCompound,
- bool ghost,
- SCA_IObject *ob);
- virtual ~KX_ParentActuator();
- virtual bool Update();
-
- virtual CValue* GetReplica();
- virtual void ProcessReplica();
- virtual void Relink(CTR_Map<CTR_HashedPtr, void*> *obj_map);
- virtual bool UnlinkObject(SCA_IObject* clientobj);
-
-#ifdef WITH_PYTHON
-
- /* --------------------------------------------------------------------- */
- /* Python interface ---------------------------------------------------- */
- /* --------------------------------------------------------------------- */
-
- /* These are used to get and set m_ob */
- static PyObject *pyattr_get_object(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_object(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
-
-#endif /* WITH_PYTHON */
-
-}; /* end of class KX_ParentActuator : public SCA_PropertyActuator */
-
-#endif /* __KX_PARENTACTUATOR_H__ */
diff --git a/source/gameengine/Ketsji/KX_PhysicsEngineEnums.h b/source/gameengine/Ketsji/KX_PhysicsEngineEnums.h
deleted file mode 100644
index ca99c2e7526..00000000000
--- a/source/gameengine/Ketsji/KX_PhysicsEngineEnums.h
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file KX_PhysicsEngineEnums.h
- * \ingroup ketsji
- */
-
-#ifndef __KX_PHYSICSENGINEENUMS_H__
-#define __KX_PHYSICSENGINEENUMS_H__
-
-enum e_PhysicsEngine
-{
- NoSelection = -1,
- UseNone = 0,
- UseBullet = 5,
-};
-
-#endif /* __KX_PHYSICSENGINEENUMS_H__ */
diff --git a/source/gameengine/Ketsji/KX_PolyProxy.cpp b/source/gameengine/Ketsji/KX_PolyProxy.cpp
deleted file mode 100644
index 4454543161b..00000000000
--- a/source/gameengine/Ketsji/KX_PolyProxy.cpp
+++ /dev/null
@@ -1,266 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Ketsji/KX_PolyProxy.cpp
- * \ingroup ketsji
- */
-
-
-#ifdef WITH_PYTHON
-
-#include "KX_PolyProxy.h"
-#include "KX_MeshProxy.h"
-#include "RAS_MeshObject.h"
-#include "RAS_Polygon.h"
-#include "KX_BlenderMaterial.h"
-
-#include "KX_PyMath.h"
-
-PyTypeObject KX_PolyProxy::Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "KX_PolyProxy",
- sizeof(PyObjectPlus_Proxy),
- 0,
- py_base_dealloc,
- 0,
- 0,
- 0,
- 0,
- py_base_repr,
- 0,0,0,0,0,0,0,0,0,
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
- 0,0,0,0,0,0,0,
- Methods,
- 0,
- 0,
- &CValue::Type,
- 0,0,0,0,0,0,
- py_base_new
-};
-
-PyMethodDef KX_PolyProxy::Methods[] = {
- KX_PYMETHODTABLE_NOARGS(KX_PolyProxy,getMaterialIndex),
- KX_PYMETHODTABLE_NOARGS(KX_PolyProxy,getNumVertex),
- KX_PYMETHODTABLE_NOARGS(KX_PolyProxy,isVisible),
- KX_PYMETHODTABLE_NOARGS(KX_PolyProxy,isCollider),
- KX_PYMETHODTABLE_NOARGS(KX_PolyProxy,getMaterialName),
- KX_PYMETHODTABLE_NOARGS(KX_PolyProxy,getTextureName),
- KX_PYMETHODTABLE(KX_PolyProxy,getVertexIndex),
- KX_PYMETHODTABLE_NOARGS(KX_PolyProxy,getMesh),
- KX_PYMETHODTABLE_NOARGS(KX_PolyProxy,getMaterial),
- {NULL,NULL} //Sentinel
-};
-
-PyAttributeDef KX_PolyProxy::Attributes[] = {
- KX_PYATTRIBUTE_RO_FUNCTION("material_name", KX_PolyProxy, pyattr_get_material_name),
- KX_PYATTRIBUTE_RO_FUNCTION("texture_name", KX_PolyProxy, pyattr_get_texture_name),
- KX_PYATTRIBUTE_RO_FUNCTION("material", KX_PolyProxy, pyattr_get_material),
- KX_PYATTRIBUTE_RO_FUNCTION("material_id", KX_PolyProxy, pyattr_get_material_id),
- KX_PYATTRIBUTE_RO_FUNCTION("v1", KX_PolyProxy, pyattr_get_v1),
- KX_PYATTRIBUTE_RO_FUNCTION("v2", KX_PolyProxy, pyattr_get_v2),
- KX_PYATTRIBUTE_RO_FUNCTION("v3", KX_PolyProxy, pyattr_get_v3),
- KX_PYATTRIBUTE_RO_FUNCTION("v4", KX_PolyProxy, pyattr_get_v4),
- KX_PYATTRIBUTE_RO_FUNCTION("visible", KX_PolyProxy, pyattr_get_visible),
- KX_PYATTRIBUTE_RO_FUNCTION("collide", KX_PolyProxy, pyattr_get_collide),
- { NULL } //Sentinel
-};
-
-KX_PolyProxy::KX_PolyProxy(const RAS_MeshObject*mesh, RAS_Polygon* polygon)
-: m_polygon(polygon),
- m_mesh((RAS_MeshObject*)mesh)
-{
-}
-
-KX_PolyProxy::~KX_PolyProxy()
-{
-}
-
-
-// stuff for cvalue related things
-CValue* KX_PolyProxy::Calc(VALUE_OPERATOR, CValue *) { return NULL;}
-CValue* KX_PolyProxy::CalcFinal(VALUE_DATA_TYPE, VALUE_OPERATOR, CValue *) { return NULL;}
-static STR_String sPolyName = "polygone";
-const STR_String & KX_PolyProxy::GetText() {return sPolyName;};
-double KX_PolyProxy::GetNumber() { return -1;}
-STR_String& KX_PolyProxy::GetName() { return sPolyName;}
-void KX_PolyProxy::SetName(const char *) { };
-CValue* KX_PolyProxy::GetReplica() { return NULL;}
-
-// stuff for python integration
-
-PyObject *KX_PolyProxy::pyattr_get_material_name(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_PolyProxy* self = static_cast<KX_PolyProxy*>(self_v);
- return self->PygetMaterialName();
-}
-
-PyObject *KX_PolyProxy::pyattr_get_texture_name(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_PolyProxy* self = static_cast<KX_PolyProxy*>(self_v);
- return self->PygetTextureName();
-}
-
-PyObject *KX_PolyProxy::pyattr_get_material(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_PolyProxy* self = static_cast<KX_PolyProxy*>(self_v);
- return self->PygetMaterial();
-}
-
-PyObject *KX_PolyProxy::pyattr_get_material_id(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_PolyProxy* self = static_cast<KX_PolyProxy*>(self_v);
- return self->PygetMaterialIndex();
-}
-
-PyObject *KX_PolyProxy::pyattr_get_v1(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_PolyProxy* self = static_cast<KX_PolyProxy*>(self_v);
-
- return PyLong_FromLong(self->m_polygon->GetVertexOffsetAbsolute(0));
-}
-
-PyObject *KX_PolyProxy::pyattr_get_v2(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_PolyProxy* self = static_cast<KX_PolyProxy*>(self_v);
-
- return PyLong_FromLong(self->m_polygon->GetVertexOffsetAbsolute(1));
-}
-
-PyObject *KX_PolyProxy::pyattr_get_v3(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_PolyProxy* self = static_cast<KX_PolyProxy*>(self_v);
-
- return PyLong_FromLong(self->m_polygon->GetVertexOffsetAbsolute(2));
-}
-
-PyObject *KX_PolyProxy::pyattr_get_v4(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_PolyProxy* self = static_cast<KX_PolyProxy*>(self_v);
-
- if (3 < self->m_polygon->VertexCount())
- {
- return PyLong_FromLong(self->m_polygon->GetVertexOffsetAbsolute(3));
- }
- return PyLong_FromLong(0);
-}
-
-PyObject *KX_PolyProxy::pyattr_get_visible(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_PolyProxy* self = static_cast<KX_PolyProxy*>(self_v);
- return self->PyisVisible();
-}
-
-PyObject *KX_PolyProxy::pyattr_get_collide(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_PolyProxy* self = static_cast<KX_PolyProxy*>(self_v);
- return self->PyisCollider();
-}
-
-KX_PYMETHODDEF_DOC_NOARGS(KX_PolyProxy, getMaterialIndex,
-"getMaterialIndex() : return the material index of the polygon in the mesh\n")
-{
- RAS_MaterialBucket* polyBucket = m_polygon->GetMaterial();
- unsigned int matid;
- for (matid=0; matid<(unsigned int)m_mesh->NumMaterials(); matid++)
- {
- RAS_MeshMaterial* meshMat = m_mesh->GetMeshMaterial(matid);
- if (meshMat->m_bucket == polyBucket)
- // found it
- break;
- }
- return PyLong_FromLong(matid);
-}
-
-KX_PYMETHODDEF_DOC_NOARGS(KX_PolyProxy, getNumVertex,
-"getNumVertex() : returns the number of vertex of the polygon, 3 or 4\n")
-{
- return PyLong_FromLong(m_polygon->VertexCount());
-}
-
-KX_PYMETHODDEF_DOC_NOARGS(KX_PolyProxy, isVisible,
-"isVisible() : returns whether the polygon is visible or not\n")
-{
- return PyLong_FromLong(m_polygon->IsVisible());
-}
-
-KX_PYMETHODDEF_DOC_NOARGS(KX_PolyProxy, isCollider,
-"isCollider() : returns whether the polygon is receives collision or not\n")
-{
- return PyLong_FromLong(m_polygon->IsCollider());
-}
-
-KX_PYMETHODDEF_DOC_NOARGS(KX_PolyProxy, getMaterialName,
-"getMaterialName() : returns the polygon material name, \"NoMaterial\" if no material\n")
-{
- return PyUnicode_From_STR_String(m_polygon->GetMaterial()->GetPolyMaterial()->GetMaterialName());
-}
-
-KX_PYMETHODDEF_DOC_NOARGS(KX_PolyProxy, getTextureName,
-"getTexturelName() : returns the polygon texture name, \"NULL\" if no texture\n")
-{
- return PyUnicode_From_STR_String(m_polygon->GetMaterial()->GetPolyMaterial()->GetTextureName());
-}
-
-KX_PYMETHODDEF_DOC(KX_PolyProxy, getVertexIndex,
-"getVertexIndex(vertex) : returns the mesh vertex index of a polygon vertex\n"
-"vertex: index of the vertex in the polygon: 0->3\n"
-"return value can be used to retrieve the vertex details through mesh proxy\n"
-"Note: getVertexIndex(3) on a triangle polygon returns 0\n")
-{
- int index;
- if (!PyArg_ParseTuple(args,"i:getVertexIndex",&index))
- {
- return NULL;
- }
- if (index < 0 || index > 3)
- {
- PyErr_SetString(PyExc_AttributeError, "poly.getVertexIndex(int): KX_PolyProxy, expected an index between 0-3");
- return NULL;
- }
- if (index < m_polygon->VertexCount())
- {
- return PyLong_FromLong(m_polygon->GetVertexOffsetAbsolute(index));
- }
- return PyLong_FromLong(0);
-}
-
-KX_PYMETHODDEF_DOC_NOARGS(KX_PolyProxy, getMesh,
-"getMesh() : returns a mesh proxy\n")
-{
- KX_MeshProxy* meshproxy = new KX_MeshProxy((RAS_MeshObject*)m_mesh);
- return meshproxy->NewProxy(true);
-}
-
-KX_PYMETHODDEF_DOC_NOARGS(KX_PolyProxy, getMaterial,
-"getMaterial() : returns a material\n")
-{
- RAS_IPolyMaterial *polymat = m_polygon->GetMaterial()->GetPolyMaterial();
- KX_BlenderMaterial* mat = static_cast<KX_BlenderMaterial*>(polymat);
- return mat->GetProxy();
-}
-
-#endif // WITH_PYTHON
diff --git a/source/gameengine/Ketsji/KX_PolyProxy.h b/source/gameengine/Ketsji/KX_PolyProxy.h
deleted file mode 100644
index 837e7f8354c..00000000000
--- a/source/gameengine/Ketsji/KX_PolyProxy.h
+++ /dev/null
@@ -1,85 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file KX_PolyProxy.h
- * \ingroup ketsji
- */
-
-#ifndef __KX_POLYPROXY_H__
-#define __KX_POLYPROXY_H__
-
-#ifdef WITH_PYTHON
-
-#include "SCA_IObject.h"
-
-class KX_PolyProxy : public CValue
-{
- Py_Header
-protected:
- class RAS_Polygon* m_polygon;
- class RAS_MeshObject* m_mesh;
-public:
- KX_PolyProxy(const class RAS_MeshObject*mesh, class RAS_Polygon* polygon);
- virtual ~KX_PolyProxy();
-
- // stuff for cvalue related things
- CValue* Calc(VALUE_OPERATOR op, CValue *val);
- CValue* CalcFinal(VALUE_DATA_TYPE dtype, VALUE_OPERATOR op, CValue *val);
- const STR_String & GetText();
- double GetNumber();
- STR_String& GetName();
- void SetName(const char *name); // Set the name of the value
- CValue* GetReplica();
-
-
-// stuff for python integration
- static PyObject *pyattr_get_material_name(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject *pyattr_get_texture_name(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject *pyattr_get_material(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject *pyattr_get_material_id(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject *pyattr_get_v1(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject *pyattr_get_v2(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject *pyattr_get_v3(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject *pyattr_get_v4(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject *pyattr_get_visible(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject *pyattr_get_collide(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
-
- KX_PYMETHOD_DOC_NOARGS(KX_PolyProxy,getMaterialIndex)
- KX_PYMETHOD_DOC_NOARGS(KX_PolyProxy,getNumVertex)
- KX_PYMETHOD_DOC_NOARGS(KX_PolyProxy,isVisible)
- KX_PYMETHOD_DOC_NOARGS(KX_PolyProxy,isCollider)
- KX_PYMETHOD_DOC_NOARGS(KX_PolyProxy,getMaterialName)
- KX_PYMETHOD_DOC_NOARGS(KX_PolyProxy,getTextureName)
- KX_PYMETHOD_DOC(KX_PolyProxy,getVertexIndex)
- KX_PYMETHOD_DOC_NOARGS(KX_PolyProxy,getMesh)
- KX_PYMETHOD_DOC_NOARGS(KX_PolyProxy,getMaterial)
-
-};
-
-#endif /* WITH_PYTHON */
-
-#endif /* __KX_POLYPROXY_H__ */
diff --git a/source/gameengine/Ketsji/KX_PositionInterpolator.cpp b/source/gameengine/Ketsji/KX_PositionInterpolator.cpp
deleted file mode 100644
index 1e217ecf616..00000000000
--- a/source/gameengine/Ketsji/KX_PositionInterpolator.cpp
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Ketsji/KX_PositionInterpolator.cpp
- * \ingroup ketsji
- */
-
-
-#include "KX_PositionInterpolator.h"
-#include "MT_Point3.h"
-#include "KX_IScalarInterpolator.h"
-
-void KX_PositionInterpolator::Execute(float currentTime) const
-{
- m_target.setValue(m_ipos[0]->GetValue(currentTime),
- m_ipos[1]->GetValue(currentTime),
- m_ipos[2]->GetValue(currentTime));
-}
diff --git a/source/gameengine/Ketsji/KX_PositionInterpolator.h b/source/gameengine/Ketsji/KX_PositionInterpolator.h
deleted file mode 100644
index b5ab053bb0e..00000000000
--- a/source/gameengine/Ketsji/KX_PositionInterpolator.h
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file KX_PositionInterpolator.h
- * \ingroup ketsji
- */
-
-#ifndef __KX_POSITIONINTERPOLATOR_H__
-#define __KX_POSITIONINTERPOLATOR_H__
-
-#include "KX_IInterpolator.h"
-
-class MT_Point3;
-class KX_IScalarInterpolator;
-
-class KX_PositionInterpolator : public KX_IInterpolator {
-public:
- KX_PositionInterpolator(MT_Point3& target,
- KX_IScalarInterpolator *ipos[]) :
- m_target(target)
- {
- m_ipos[0] = ipos[0];
- m_ipos[1] = ipos[1];
- m_ipos[2] = ipos[2];
- }
-
- virtual void Execute(float currentTime) const;
-
-private:
- MT_Point3& m_target;
- KX_IScalarInterpolator *m_ipos[3];
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:KX_PositionInterpolator")
-#endif
-};
-
-#endif
-
diff --git a/source/gameengine/Ketsji/KX_PyConstraintBinding.cpp b/source/gameengine/Ketsji/KX_PyConstraintBinding.cpp
deleted file mode 100644
index 81fe3be1fcf..00000000000
--- a/source/gameengine/Ketsji/KX_PyConstraintBinding.cpp
+++ /dev/null
@@ -1,750 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Ketsji/KX_PyConstraintBinding.cpp
- * \ingroup ketsji
- */
-
-#include "KX_PyConstraintBinding.h"
-#include "PHY_IPhysicsEnvironment.h"
-#include "KX_ConstraintWrapper.h"
-#include "KX_VehicleWrapper.h"
-#include "KX_CharacterWrapper.h"
-#include "PHY_IPhysicsController.h"
-#include "PHY_IVehicle.h"
-#include "PHY_DynamicTypes.h"
-#include "MT_Matrix3x3.h"
-
-#include "KX_GameObject.h" // ConvertPythonToGameObject()
-#include "KX_PythonInit.h"
-
-#include "EXP_PyObjectPlus.h"
-
-#ifdef WITH_BULLET
-# include "LinearMath/btIDebugDraw.h"
-#endif
-
-#ifdef WITH_PYTHON
-
-// macro copied from KX_PythonInit.cpp
-#define KX_MACRO_addTypesToDict(dict, name, name2) PyDict_SetItemString(dict, #name, item=PyLong_FromLong(name2)); Py_DECREF(item)
-
-// nasty glob variable to connect scripting language
-// if there is a better way (without global), please do so!
-static PHY_IPhysicsEnvironment* g_CurrentActivePhysicsEnvironment = NULL;
-
-
-PyDoc_STRVAR(PhysicsConstraints_module_documentation,
-"This is the Python API for the Physics Constraints"
-);
-
-PyDoc_STRVAR(gPySetGravity__doc__,
-"setGravity(float x,float y,float z)\n"
-""
-);
-PyDoc_STRVAR(gPySetDebugMode__doc__,
-"setDebugMode(int mode)\n"
-""
-);
-
-PyDoc_STRVAR(gPySetNumIterations__doc__,
-"setNumIterations(int numiter)\n"
-"This sets the number of iterations for an iterative constraint solver"
-);
-PyDoc_STRVAR(gPySetNumTimeSubSteps__doc__,
-"setNumTimeSubSteps(int numsubstep)\n"
-"This sets the number of substeps for each physics proceed. Tradeoff quality for performance."
-);
-
-PyDoc_STRVAR(gPySetDeactivationTime__doc__,
-"setDeactivationTime(float time)\n"
-"This sets the time after which a resting rigidbody gets deactived"
-);
-PyDoc_STRVAR(gPySetDeactivationLinearTreshold__doc__,
-"setDeactivationLinearTreshold(float linearTreshold)\n"
-""
-);
-PyDoc_STRVAR(gPySetDeactivationAngularTreshold__doc__,
-"setDeactivationAngularTreshold(float angularTreshold)\n"
-""
-);
-PyDoc_STRVAR(gPySetContactBreakingTreshold__doc__,
-"setContactBreakingTreshold(float breakingTreshold)\n"
-"Reasonable default is 0.02 (if units are meters)"
-);
-
-PyDoc_STRVAR(gPySetCcdMode__doc__,
-"setCcdMode(int ccdMode)\n"
-"Very experimental, not recommended"
-);
-PyDoc_STRVAR(gPySetSorConstant__doc__,
-"setSorConstant(float sor)\n"
-"Very experimental, not recommended"
-);
-PyDoc_STRVAR(gPySetSolverTau__doc__,
-"setTau(float tau)\n"
-"Very experimental, not recommended"
-);
-PyDoc_STRVAR(gPySetSolverDamping__doc__,
-"setDamping(float damping)\n"
-"Very experimental, not recommended"
-);
-PyDoc_STRVAR(gPySetLinearAirDamping__doc__,
-"setLinearAirDamping(float damping)\n"
-"Very experimental, not recommended"
-);
-PyDoc_STRVAR(gPySetUseEpa__doc__,
-"setUseEpa(int epa)\n"
-"Very experimental, not recommended"
-);
-PyDoc_STRVAR(gPySetSolverType__doc__,
-"setSolverType(int solverType)\n"
-"Very experimental, not recommended"
-);
-
-PyDoc_STRVAR(gPyCreateConstraint__doc__,
-"createConstraint(ob1,ob2,float restLength,float restitution,float damping)\n"
-""
-);
-PyDoc_STRVAR(gPyGetVehicleConstraint__doc__,
-"getVehicleConstraint(int constraintId)\n"
-""
-);
-PyDoc_STRVAR(gPyGetCharacter__doc__,
-"getCharacter(KX_GameObject obj)\n"
-""
-);
-PyDoc_STRVAR(gPyRemoveConstraint__doc__,
-"removeConstraint(int constraintId)\n"
-""
-);
-PyDoc_STRVAR(gPyGetAppliedImpulse__doc__,
-"getAppliedImpulse(int constraintId)\n"
-""
-);
-
-
-
-
-static PyObject *gPySetGravity(PyObject *self,
- PyObject *args,
- PyObject *kwds)
-{
- float x,y,z;
- if (PyArg_ParseTuple(args,"fff",&x,&y,&z))
- {
- if (PHY_GetActiveEnvironment())
- PHY_GetActiveEnvironment()->SetGravity(x,y,z);
- }
- else {
- return NULL;
- }
-
- Py_RETURN_NONE;
-}
-
-static PyObject *gPySetDebugMode(PyObject *self,
- PyObject *args,
- PyObject *kwds)
-{
- int mode;
- if (PyArg_ParseTuple(args,"i",&mode))
- {
- if (PHY_GetActiveEnvironment())
- {
- PHY_GetActiveEnvironment()->SetDebugMode(mode);
-
- }
-
- }
- else {
- return NULL;
- }
-
- Py_RETURN_NONE;
-}
-
-
-
-static PyObject *gPySetNumTimeSubSteps(PyObject *self,
- PyObject *args,
- PyObject *kwds)
-{
- int substep;
- if (PyArg_ParseTuple(args,"i",&substep))
- {
- if (PHY_GetActiveEnvironment())
- {
- PHY_GetActiveEnvironment()->SetNumTimeSubSteps(substep);
- }
- }
- else {
- return NULL;
- }
- Py_RETURN_NONE;
-}
-
-
-static PyObject *gPySetNumIterations(PyObject *self,
- PyObject *args,
- PyObject *kwds)
-{
- int iter;
- if (PyArg_ParseTuple(args,"i",&iter))
- {
- if (PHY_GetActiveEnvironment())
- {
- PHY_GetActiveEnvironment()->SetNumIterations(iter);
- }
- }
- else {
- return NULL;
- }
- Py_RETURN_NONE;
-}
-
-
-static PyObject *gPySetDeactivationTime(PyObject *self,
- PyObject *args,
- PyObject *kwds)
-{
- float deactive_time;
- if (PyArg_ParseTuple(args,"f",&deactive_time))
- {
- if (PHY_GetActiveEnvironment())
- {
- PHY_GetActiveEnvironment()->SetDeactivationTime(deactive_time);
- }
- }
- else {
- return NULL;
- }
- Py_RETURN_NONE;
-}
-
-
-static PyObject *gPySetDeactivationLinearTreshold(PyObject *self,
- PyObject *args,
- PyObject *kwds)
-{
- float linearDeactivationTreshold;
- if (PyArg_ParseTuple(args,"f",&linearDeactivationTreshold))
- {
- if (PHY_GetActiveEnvironment())
- {
- PHY_GetActiveEnvironment()->SetDeactivationLinearTreshold( linearDeactivationTreshold);
- }
- }
- else {
- return NULL;
- }
- Py_RETURN_NONE;
-}
-
-
-static PyObject *gPySetDeactivationAngularTreshold(PyObject *self,
- PyObject *args,
- PyObject *kwds)
-{
- float angularDeactivationTreshold;
- if (PyArg_ParseTuple(args,"f",&angularDeactivationTreshold))
- {
- if (PHY_GetActiveEnvironment())
- {
- PHY_GetActiveEnvironment()->SetDeactivationAngularTreshold( angularDeactivationTreshold);
- }
- }
- else {
- return NULL;
- }
- Py_RETURN_NONE;
-}
-
-static PyObject *gPySetContactBreakingTreshold(PyObject *self,
- PyObject *args,
- PyObject *kwds)
-{
- float contactBreakingTreshold;
- if (PyArg_ParseTuple(args,"f",&contactBreakingTreshold))
- {
- if (PHY_GetActiveEnvironment())
- {
- PHY_GetActiveEnvironment()->SetContactBreakingTreshold( contactBreakingTreshold);
- }
- }
- else {
- return NULL;
- }
- Py_RETURN_NONE;
-}
-
-
-static PyObject *gPySetCcdMode(PyObject *self,
- PyObject *args,
- PyObject *kwds)
-{
- float ccdMode;
- if (PyArg_ParseTuple(args,"f",&ccdMode))
- {
- if (PHY_GetActiveEnvironment())
- {
- PHY_GetActiveEnvironment()->SetCcdMode( ccdMode);
- }
- }
- else {
- return NULL;
- }
- Py_RETURN_NONE;
-}
-
-static PyObject *gPySetSorConstant(PyObject *self,
- PyObject *args,
- PyObject *kwds)
-{
- float sor;
- if (PyArg_ParseTuple(args,"f",&sor))
- {
- if (PHY_GetActiveEnvironment())
- {
- PHY_GetActiveEnvironment()->SetSolverSorConstant( sor);
- }
- }
- else {
- return NULL;
- }
- Py_RETURN_NONE;
-}
-
-static PyObject *gPySetSolverTau(PyObject *self,
- PyObject *args,
- PyObject *kwds)
-{
- float tau;
- if (PyArg_ParseTuple(args,"f",&tau))
- {
- if (PHY_GetActiveEnvironment())
- {
- PHY_GetActiveEnvironment()->SetSolverTau( tau);
- }
- }
- else {
- return NULL;
- }
- Py_RETURN_NONE;
-}
-
-
-static PyObject *gPySetSolverDamping(PyObject *self,
- PyObject *args,
- PyObject *kwds)
-{
- float damping;
- if (PyArg_ParseTuple(args,"f",&damping))
- {
- if (PHY_GetActiveEnvironment())
- {
- PHY_GetActiveEnvironment()->SetSolverDamping( damping);
- }
- }
- else {
- return NULL;
- }
- Py_RETURN_NONE;
-}
-
-static PyObject *gPySetLinearAirDamping(PyObject *self,
- PyObject *args,
- PyObject *kwds)
-{
- float damping;
- if (PyArg_ParseTuple(args,"f",&damping))
- {
- if (PHY_GetActiveEnvironment())
- {
- PHY_GetActiveEnvironment()->SetLinearAirDamping( damping);
- }
- }
- else {
- return NULL;
- }
- Py_RETURN_NONE;
-}
-
-
-static PyObject *gPySetUseEpa(PyObject *self,
- PyObject *args,
- PyObject *kwds)
-{
- int epa;
- if (PyArg_ParseTuple(args,"i",&epa))
- {
- if (PHY_GetActiveEnvironment())
- {
- PHY_GetActiveEnvironment()->SetUseEpa(epa);
- }
- }
- else {
- return NULL;
- }
- Py_RETURN_NONE;
-}
-static PyObject *gPySetSolverType(PyObject *self,
- PyObject *args,
- PyObject *kwds)
-{
- int solverType;
- if (PyArg_ParseTuple(args,"i",&solverType))
- {
- if (PHY_GetActiveEnvironment())
- {
- PHY_GetActiveEnvironment()->SetSolverType(solverType);
- }
- }
- else {
- return NULL;
- }
- Py_RETURN_NONE;
-}
-
-
-
-static PyObject *gPyGetVehicleConstraint(PyObject *self,
- PyObject *args,
- PyObject *kwds)
-{
-#if defined(_WIN64)
- __int64 constraintid;
- if (PyArg_ParseTuple(args,"L",&constraintid))
-#else
- long constraintid;
- if (PyArg_ParseTuple(args,"l",&constraintid))
-#endif
- {
- if (PHY_GetActiveEnvironment())
- {
-
- PHY_IVehicle* vehicle = PHY_GetActiveEnvironment()->GetVehicleConstraint(constraintid);
- if (vehicle)
- {
- KX_VehicleWrapper* pyWrapper = new KX_VehicleWrapper(vehicle,PHY_GetActiveEnvironment());
- return pyWrapper->NewProxy(true);
- }
-
- }
- }
- else {
- return NULL;
- }
-
- Py_RETURN_NONE;
-}
-
-static PyObject* gPyGetCharacter(PyObject* self,
- PyObject* args,
- PyObject* kwds)
-{
- PyObject* pyob;
- KX_GameObject *ob;
-
- if (!PyArg_ParseTuple(args,"O", &pyob))
- return NULL;
-
- if (!ConvertPythonToGameObject(KX_GetActiveScene()->GetLogicManager(), pyob, &ob, false, "bge.constraints.getCharacter(value)"))
- return NULL;
-
- if (PHY_GetActiveEnvironment())
- {
-
- PHY_ICharacter* character= PHY_GetActiveEnvironment()->GetCharacterController(ob);
- if (character)
- {
- KX_CharacterWrapper* pyWrapper = new KX_CharacterWrapper(character);
- return pyWrapper->NewProxy(true);
- }
-
- }
-
- Py_RETURN_NONE;
-}
-
-static PyObject *gPyCreateConstraint(PyObject *self,
- PyObject *args,
- PyObject *kwds)
-{
- /* FIXME - physicsid is a long being cast to a pointer, should at least use PyCapsule */
- unsigned long long physicsid = 0, physicsid2 = 0;
- int constrainttype = 0;
- int flag = 0;
- float pivotX = 0.0f, pivotY = 0.0f, pivotZ = 0.0f, axisX = 0.0f, axisY = 0.0f, axisZ = 0.0f;
-
- static const char *kwlist[] = {"physicsid_1", "physicsid_2", "constraint_type", "pivot_x", "pivot_y", "pivot_z",
- "axis_x", "axis_y", "axis_z", "flag", NULL};
-
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "KKi|ffffffi:createConstraint", (char **)kwlist,
- &physicsid, &physicsid2, &constrainttype,
- &pivotX, &pivotY, &pivotZ, &axisX, &axisY, &axisZ, &flag))
- {
- return NULL;
- }
-
- if (PHY_GetActiveEnvironment()) {
- PHY_IPhysicsController *physctrl = (PHY_IPhysicsController*)physicsid;
- PHY_IPhysicsController *physctrl2 = (PHY_IPhysicsController*)physicsid2;
- if (physctrl) { //TODO:check for existence of this pointer!
- //convert from euler angle into axis
- const float deg2rad = 0.017453292f;
-
- //we need to pass a full constraint frame, not just axis
- //localConstraintFrameBasis
- MT_Matrix3x3 localCFrame(MT_Vector3(deg2rad*axisX, deg2rad*axisY, deg2rad*axisZ));
- MT_Vector3 axis0 = localCFrame.getColumn(0);
- MT_Vector3 axis1 = localCFrame.getColumn(1);
- MT_Vector3 axis2 = localCFrame.getColumn(2);
-
- int constraintid = PHY_GetActiveEnvironment()->CreateConstraint(
- physctrl, physctrl2, (enum PHY_ConstraintType)constrainttype, pivotX, pivotY, pivotZ,
- (float)axis0.x(), (float)axis0.y(), (float)axis0.z(),
- (float)axis1.x(), (float)axis1.y(), (float)axis1.z(),
- (float)axis2.x(), (float)axis2.y(), (float)axis2.z(), flag);
-
- KX_ConstraintWrapper *wrap = new KX_ConstraintWrapper(
- (enum PHY_ConstraintType)constrainttype, constraintid, PHY_GetActiveEnvironment());
-
- return wrap->NewProxy(true);
- }
- }
- Py_RETURN_NONE;
-}
-
-
-
-
-static PyObject *gPyGetAppliedImpulse(PyObject *self,
- PyObject *args,
- PyObject *kwds)
-{
- float appliedImpulse = 0.f;
-
-#if defined(_WIN64)
- __int64 constraintid;
- if (PyArg_ParseTuple(args,"L",&constraintid))
-#else
- long constraintid;
- if (PyArg_ParseTuple(args,"l",&constraintid))
-#endif
- {
- if (PHY_GetActiveEnvironment())
- {
- appliedImpulse = PHY_GetActiveEnvironment()->GetAppliedImpulse(constraintid);
- }
- }
- else {
- return NULL;
- }
-
- return PyFloat_FromDouble(appliedImpulse);
-}
-
-
-static PyObject *gPyRemoveConstraint(PyObject *self,
- PyObject *args,
- PyObject *kwds)
-{
-#if defined(_WIN64)
- __int64 constraintid;
- if (PyArg_ParseTuple(args,"L",&constraintid))
-#else
- long constraintid;
- if (PyArg_ParseTuple(args,"l",&constraintid))
-#endif
- {
- if (PHY_GetActiveEnvironment())
- {
- PHY_GetActiveEnvironment()->RemoveConstraintById(constraintid);
- }
- }
- else {
- return NULL;
- }
-
- Py_RETURN_NONE;
-}
-
-static PyObject *gPyExportBulletFile(PyObject *, PyObject *args)
-{
- char* filename;
- if (!PyArg_ParseTuple(args,"s:exportBulletFile",&filename))
- return NULL;
-
- if (PHY_GetActiveEnvironment())
- {
- PHY_GetActiveEnvironment()->ExportFile(filename);
- }
- Py_RETURN_NONE;
-}
-
-static struct PyMethodDef physicsconstraints_methods[] = {
- {"setGravity",(PyCFunction) gPySetGravity,
- METH_VARARGS, (const char*)gPySetGravity__doc__},
- {"setDebugMode",(PyCFunction) gPySetDebugMode,
- METH_VARARGS, (const char *)gPySetDebugMode__doc__},
-
- /// settings that influence quality of the rigidbody dynamics
- {"setNumIterations",(PyCFunction) gPySetNumIterations,
- METH_VARARGS, (const char *)gPySetNumIterations__doc__},
-
- {"setNumTimeSubSteps",(PyCFunction) gPySetNumTimeSubSteps,
- METH_VARARGS, (const char *)gPySetNumTimeSubSteps__doc__},
-
- {"setDeactivationTime",(PyCFunction) gPySetDeactivationTime,
- METH_VARARGS, (const char *)gPySetDeactivationTime__doc__},
-
- {"setDeactivationLinearTreshold",(PyCFunction) gPySetDeactivationLinearTreshold,
- METH_VARARGS, (const char *)gPySetDeactivationLinearTreshold__doc__},
- {"setDeactivationAngularTreshold",(PyCFunction) gPySetDeactivationAngularTreshold,
- METH_VARARGS, (const char *)gPySetDeactivationAngularTreshold__doc__},
-
- {"setContactBreakingTreshold",(PyCFunction) gPySetContactBreakingTreshold,
- METH_VARARGS, (const char *)gPySetContactBreakingTreshold__doc__},
- {"setCcdMode",(PyCFunction) gPySetCcdMode,
- METH_VARARGS, (const char *)gPySetCcdMode__doc__},
- {"setSorConstant",(PyCFunction) gPySetSorConstant,
- METH_VARARGS, (const char *)gPySetSorConstant__doc__},
- {"setSolverTau",(PyCFunction) gPySetSolverTau,
- METH_VARARGS, (const char *)gPySetSolverTau__doc__},
- {"setSolverDamping",(PyCFunction) gPySetSolverDamping,
- METH_VARARGS, (const char *)gPySetSolverDamping__doc__},
-
- {"setLinearAirDamping",(PyCFunction) gPySetLinearAirDamping,
- METH_VARARGS, (const char *)gPySetLinearAirDamping__doc__},
-
- {"setUseEpa",(PyCFunction) gPySetUseEpa,
- METH_VARARGS, (const char *)gPySetUseEpa__doc__},
- {"setSolverType",(PyCFunction) gPySetSolverType,
- METH_VARARGS, (const char *)gPySetSolverType__doc__},
-
-
- {"createConstraint",(PyCFunction) gPyCreateConstraint,
- METH_VARARGS|METH_KEYWORDS, (const char *)gPyCreateConstraint__doc__},
- {"getVehicleConstraint",(PyCFunction) gPyGetVehicleConstraint,
- METH_VARARGS, (const char *)gPyGetVehicleConstraint__doc__},
-
- {"getCharacter",(PyCFunction) gPyGetCharacter,
- METH_VARARGS, (const char *)gPyGetCharacter__doc__},
-
- {"removeConstraint",(PyCFunction) gPyRemoveConstraint,
- METH_VARARGS, (const char *)gPyRemoveConstraint__doc__},
- {"getAppliedImpulse",(PyCFunction) gPyGetAppliedImpulse,
- METH_VARARGS, (const char *)gPyGetAppliedImpulse__doc__},
-
- {"exportBulletFile",(PyCFunction)gPyExportBulletFile,
- METH_VARARGS, "export a .bullet file"},
-
- //sentinel
- { NULL, (PyCFunction) NULL, 0, NULL }
-};
-
-static struct PyModuleDef PhysicsConstraints_module_def = {
- PyModuleDef_HEAD_INIT,
- "PhysicsConstraints", /* m_name */
- PhysicsConstraints_module_documentation, /* m_doc */
- 0, /* m_size */
- physicsconstraints_methods, /* m_methods */
- 0, /* m_reload */
- 0, /* m_traverse */
- 0, /* m_clear */
- 0, /* m_free */
-};
-
-PyMODINIT_FUNC initConstraintPythonBinding()
-{
-
- PyObject *ErrorObject;
- PyObject *m;
- PyObject *d;
- PyObject *item;
-
- m = PyModule_Create(&PhysicsConstraints_module_def);
- PyDict_SetItemString(PySys_GetObject("modules"), PhysicsConstraints_module_def.m_name, m);
-
- // Add some symbolic constants to the module
- d = PyModule_GetDict(m);
- ErrorObject = PyUnicode_FromString("PhysicsConstraints.error");
- PyDict_SetItemString(d, "error", ErrorObject);
- Py_DECREF(ErrorObject);
-
-#ifdef WITH_BULLET
- //Debug Modes constants to be used with setDebugMode() python function
- KX_MACRO_addTypesToDict(d, DBG_NODEBUG, btIDebugDraw::DBG_NoDebug);
- KX_MACRO_addTypesToDict(d, DBG_DRAWWIREFRAME, btIDebugDraw::DBG_DrawWireframe);
- KX_MACRO_addTypesToDict(d, DBG_DRAWAABB, btIDebugDraw::DBG_DrawAabb);
- KX_MACRO_addTypesToDict(d, DBG_DRAWFREATURESTEXT, btIDebugDraw::DBG_DrawFeaturesText);
- KX_MACRO_addTypesToDict(d, DBG_DRAWCONTACTPOINTS, btIDebugDraw::DBG_DrawContactPoints);
- KX_MACRO_addTypesToDict(d, DBG_NOHELPTEXT, btIDebugDraw::DBG_NoHelpText);
- KX_MACRO_addTypesToDict(d, DBG_DRAWTEXT, btIDebugDraw::DBG_DrawText);
- KX_MACRO_addTypesToDict(d, DBG_PROFILETIMINGS, btIDebugDraw::DBG_ProfileTimings);
- KX_MACRO_addTypesToDict(d, DBG_ENABLESATCOMPARISION, btIDebugDraw::DBG_EnableSatComparison);
- KX_MACRO_addTypesToDict(d, DBG_DISABLEBULLETLCP, btIDebugDraw::DBG_DisableBulletLCP);
- KX_MACRO_addTypesToDict(d, DBG_ENABLECCD, btIDebugDraw::DBG_EnableCCD);
- KX_MACRO_addTypesToDict(d, DBG_DRAWCONSTRAINTS, btIDebugDraw::DBG_DrawConstraints);
- KX_MACRO_addTypesToDict(d, DBG_DRAWCONSTRAINTLIMITS, btIDebugDraw::DBG_DrawConstraintLimits);
- KX_MACRO_addTypesToDict(d, DBG_FASTWIREFRAME, btIDebugDraw::DBG_FastWireframe);
-#endif // WITH_BULLET
-
- //Constraint types to be used with createConstraint() python function
- KX_MACRO_addTypesToDict(d, POINTTOPOINT_CONSTRAINT, PHY_POINT2POINT_CONSTRAINT);
- KX_MACRO_addTypesToDict(d, LINEHINGE_CONSTRAINT, PHY_LINEHINGE_CONSTRAINT);
- KX_MACRO_addTypesToDict(d, ANGULAR_CONSTRAINT, PHY_ANGULAR_CONSTRAINT);
- KX_MACRO_addTypesToDict(d, CONETWIST_CONSTRAINT, PHY_CONE_TWIST_CONSTRAINT);
- KX_MACRO_addTypesToDict(d, VEHICLE_CONSTRAINT, PHY_VEHICLE_CONSTRAINT);
- KX_MACRO_addTypesToDict(d, GENERIC_6DOF_CONSTRAINT, PHY_GENERIC_6DOF_CONSTRAINT);
-
- // Check for errors
- if (PyErr_Occurred()) {
- Py_FatalError("can't initialize module PhysicsConstraints");
- }
-
- return m;
-}
-
-#if 0
-static void KX_RemovePythonConstraintBinding()
-{
-}
-#endif
-
-void PHY_SetActiveEnvironment(class PHY_IPhysicsEnvironment* env)
-{
- g_CurrentActivePhysicsEnvironment = env;
-}
-
-PHY_IPhysicsEnvironment* PHY_GetActiveEnvironment()
-{
- return g_CurrentActivePhysicsEnvironment;
-}
-
-#endif // WITH_PYTHON
diff --git a/source/gameengine/Ketsji/KX_PyConstraintBinding.h b/source/gameengine/Ketsji/KX_PyConstraintBinding.h
deleted file mode 100644
index 2bf9f7e197d..00000000000
--- a/source/gameengine/Ketsji/KX_PyConstraintBinding.h
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file KX_PyConstraintBinding.h
- * \ingroup ketsji
- */
-
-#ifndef __KX_PYCONSTRAINTBINDING_H__
-#define __KX_PYCONSTRAINTBINDING_H__
-
-#ifdef WITH_PYTHON
-
-#include <Python.h>
-
-PyMODINIT_FUNC initConstraintPythonBinding();
-
-void PHY_SetActiveEnvironment(class PHY_IPhysicsEnvironment* env);
-PHY_IPhysicsEnvironment* PHY_GetActiveEnvironment();
-#endif /* WITH_PYTHON */
-
-#endif /* __KX_PYCONSTRAINTBINDING_H__ */
diff --git a/source/gameengine/Ketsji/KX_PyMath.cpp b/source/gameengine/Ketsji/KX_PyMath.cpp
deleted file mode 100644
index ee05fd442ab..00000000000
--- a/source/gameengine/Ketsji/KX_PyMath.cpp
+++ /dev/null
@@ -1,215 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- * Initialize Python thingies.
- */
-
-/** \file gameengine/Ketsji/KX_PyMath.cpp
- * \ingroup ketsji
- */
-
-
-#ifdef _MSC_VER
-# pragma warning (disable:4786)
-#endif
-
-#ifdef WITH_PYTHON
-
-#include "MT_Vector3.h"
-#include "MT_Vector4.h"
-#include "MT_Matrix4x4.h"
-#include "MT_Point2.h"
-
-#include "EXP_ListValue.h"
-
-#include "EXP_Python.h"
-#include "KX_PyMath.h"
-
-bool PyOrientationTo(PyObject *pyval, MT_Matrix3x3 &rot, const char *error_prefix)
-{
- int size= PySequence_Size(pyval);
-
- if (size == 4)
- {
- MT_Quaternion qrot;
- if (PyQuatTo(pyval, qrot))
- {
- rot.setRotation(qrot);
- return true;
- }
- }
- else if (size == 3) {
- /* 3x3 matrix or euler */
- MT_Vector3 erot;
- if (PyVecTo(pyval, erot))
- {
- rot.setEuler(erot);
- return true;
- }
- PyErr_Clear();
-
- if (PyMatTo(pyval, rot))
- {
- return true;
- }
- }
-
- PyErr_Format(PyExc_TypeError, "%s, could not set the orientation from a 3x3 matrix, quaternion or euler sequence", error_prefix);
- return false;
-}
-
-bool PyQuatTo(PyObject *pyval, MT_Quaternion &qrot)
-{
- if (!PyVecTo(pyval, qrot))
- return false;
-
- /* annoying!, Blender/Mathutils have the W axis first! */
- MT_Scalar w = qrot[0]; /* from python, this is actually the W */
- qrot[0] = qrot[1];
- qrot[1] = qrot[2];
- qrot[2] = qrot[3];
- qrot[3] = w;
-
- return true;
-}
-
-PyObject *PyObjectFrom(const MT_Matrix4x4 &mat)
-{
-#ifdef USE_MATHUTILS
- float fmat[16];
- mat.getValue(fmat);
- return Matrix_CreatePyObject(fmat, 4, 4, NULL);
-#else
- PyObject *collist = PyList_New(4);
- PyObject *col;
- int i;
-
- for (i=0; i < 4; i++) {
- col = PyList_New(4);
- PyList_SET_ITEM(col, 0, PyFloat_FromDouble(mat[0][i]));
- PyList_SET_ITEM(col, 1, PyFloat_FromDouble(mat[1][i]));
- PyList_SET_ITEM(col, 2, PyFloat_FromDouble(mat[2][i]));
- PyList_SET_ITEM(col, 3, PyFloat_FromDouble(mat[3][i]));
- PyList_SET_ITEM(collist, i, col);
- }
-
- return collist;
-#endif
-}
-
-PyObject *PyObjectFrom(const MT_Matrix3x3 &mat)
-{
-#ifdef USE_MATHUTILS
- float fmat[9];
- mat.getValue3x3(fmat);
- return Matrix_CreatePyObject(fmat, 3, 3, NULL);
-#else
- PyObject *collist = PyList_New(3);
- PyObject *col;
- int i;
-
- for (i=0; i < 3; i++) {
- col = PyList_New(3);
- PyList_SET_ITEM(col, 0, PyFloat_FromDouble(mat[0][i]));
- PyList_SET_ITEM(col, 1, PyFloat_FromDouble(mat[1][i]));
- PyList_SET_ITEM(col, 2, PyFloat_FromDouble(mat[2][i]));
- PyList_SET_ITEM(collist, i, col);
- }
-
- return collist;
-#endif
-}
-
-#ifdef USE_MATHUTILS
-PyObject *PyObjectFrom(const MT_Quaternion &qrot)
-{
- /* NOTE, were re-ordering here for Mathutils compat */
- float fvec[4];
- qrot.getValue(fvec);
- return Quaternion_CreatePyObject(fvec, NULL);
-}
-#endif
-
-PyObject *PyObjectFrom(const MT_Tuple4 &vec)
-{
-#ifdef USE_MATHUTILS
- float fvec[4];
- vec.getValue(fvec);
- return Vector_CreatePyObject(fvec, 4, NULL);
-#else
- PyObject *list = PyList_New(4);
- PyList_SET_ITEM(list, 0, PyFloat_FromDouble(vec[0]));
- PyList_SET_ITEM(list, 1, PyFloat_FromDouble(vec[1]));
- PyList_SET_ITEM(list, 2, PyFloat_FromDouble(vec[2]));
- PyList_SET_ITEM(list, 3, PyFloat_FromDouble(vec[3]));
- return list;
-#endif
-}
-
-PyObject *PyObjectFrom(const MT_Tuple3 &vec)
-{
-#ifdef USE_MATHUTILS
- float fvec[3];
- vec.getValue(fvec);
- return Vector_CreatePyObject(fvec, 3, NULL);
-#else
- PyObject *list = PyList_New(3);
- PyList_SET_ITEM(list, 0, PyFloat_FromDouble(vec[0]));
- PyList_SET_ITEM(list, 1, PyFloat_FromDouble(vec[1]));
- PyList_SET_ITEM(list, 2, PyFloat_FromDouble(vec[2]));
- return list;
-#endif
-}
-
-PyObject *PyObjectFrom(const MT_Tuple2 &vec)
-{
-#ifdef USE_MATHUTILS
- float fvec[2];
- vec.getValue(fvec);
- return Vector_CreatePyObject(fvec, 2, NULL);
-#else
- PyObject *list = PyList_New(2);
- PyList_SET_ITEM(list, 0, PyFloat_FromDouble(vec[0]));
- PyList_SET_ITEM(list, 1, PyFloat_FromDouble(vec[1]));
- return list;
-#endif
-}
-
-PyObject *PyColorFromVector(const MT_Vector3 &vec)
-{
-#ifdef USE_MATHUTILS
- float fvec[3];
- vec.getValue(fvec);
- return Color_CreatePyObject(fvec, NULL);
-#else
- PyObject *list = PyList_New(3);
- PyList_SET_ITEM(list, 0, PyFloat_FromDouble(vec[0]));
- PyList_SET_ITEM(list, 1, PyFloat_FromDouble(vec[1]));
- PyList_SET_ITEM(list, 2, PyFloat_FromDouble(vec[2]));
- return list;
-#endif
-}
-
-#endif // WITH_PYTHON
diff --git a/source/gameengine/Ketsji/KX_PyMath.h b/source/gameengine/Ketsji/KX_PyMath.h
deleted file mode 100644
index 917fd0fcda6..00000000000
--- a/source/gameengine/Ketsji/KX_PyMath.h
+++ /dev/null
@@ -1,281 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file KX_PyMath.h
- * \ingroup ketsji
- * \brief Initialize Python thingies.
- */
-
-#ifndef __KX_PYMATH_H__
-#define __KX_PYMATH_H__
-
-#include "MT_Point2.h"
-#include "MT_Point3.h"
-#include "MT_Vector2.h"
-#include "MT_Vector3.h"
-#include "MT_Vector4.h"
-#include "MT_Matrix3x3.h"
-#include "MT_Matrix4x4.h"
-
-#include "EXP_Python.h"
-#include "EXP_PyObjectPlus.h"
-
-#ifdef WITH_PYTHON
-#ifdef USE_MATHUTILS
-extern "C" {
-#include "../../blender/python/mathutils/mathutils.h" /* so we can have mathutils callbacks */
-}
-#endif
-
-inline unsigned int Size(const MT_Matrix4x4&) { return 4; }
-inline unsigned int Size(const MT_Matrix3x3&) { return 3; }
-inline unsigned int Size(const MT_Tuple2&) { return 2; }
-inline unsigned int Size(const MT_Tuple3&) { return 3; }
-inline unsigned int Size(const MT_Tuple4&) { return 4; }
-
-/**
- * Converts the given python matrix (column-major) to an MT class (row-major).
- */
-template<class T>
-bool PyMatTo(PyObject *pymat, T& mat)
-{
- bool noerror = true;
- mat.setIdentity();
-
-
-#ifdef USE_MATHUTILS
-
- if (MatrixObject_Check(pymat))
- {
- MatrixObject *pymatrix = (MatrixObject *)pymat;
-
- if (BaseMath_ReadCallback(pymatrix) == -1)
- return false;
-
- if (pymatrix->num_col != Size(mat) || pymatrix->num_row != Size(mat))
- return false;
-
- for (unsigned int row = 0; row < Size(mat); row++)
- {
- for (unsigned int col = 0; col < Size(mat); col++)
- {
- mat[row][col] = *(pymatrix->matrix + col * pymatrix->num_row + row);
- }
- }
- }
- else
-
-#endif /* USE_MATHUTILS */
-
-
- if (PySequence_Check(pymat))
- {
- unsigned int rows = PySequence_Size(pymat);
- if (rows != Size(mat))
- return false;
-
- for (unsigned int row = 0; noerror && row < rows; row++)
- {
- PyObject *pyrow = PySequence_GetItem(pymat, row); /* new ref */
- if (!PyErr_Occurred() && PySequence_Check(pyrow))
- {
- unsigned int cols = PySequence_Size(pyrow);
- if (cols != Size(mat)) {
- noerror = false;
- }
- else {
- for (unsigned int col = 0; col < cols; col++) {
- PyObject *item = PySequence_GetItem(pyrow, col); /* new ref */
- mat[row][col] = PyFloat_AsDouble(item);
- Py_DECREF(item);
- }
- }
- }
- else {
- noerror = false;
- }
- Py_DECREF(pyrow);
- }
- } else
- noerror = false;
-
- if (noerror==false)
- PyErr_SetString(PyExc_TypeError, "could not be converted to a matrix (sequence of sequences)");
-
- return noerror;
-}
-
-/**
- * Converts a python sequence to a MT class.
- */
-template<class T>
-bool PyVecTo(PyObject *pyval, T& vec)
-{
-#ifdef USE_MATHUTILS
- /* no need for BaseMath_ReadCallback() here, reading the sequences will do this */
-
- if (VectorObject_Check(pyval)) {
- VectorObject *pyvec= (VectorObject *)pyval;
- if (BaseMath_ReadCallback(pyvec) == -1) {
- return false; /* exception raised */
- }
- if (pyvec->size != Size(vec)) {
- PyErr_Format(PyExc_AttributeError, "error setting vector, %d args, should be %d", pyvec->size, Size(vec));
- return false;
- }
- vec.setValue((float *) pyvec->vec);
- return true;
- }
- else if (QuaternionObject_Check(pyval)) {
- QuaternionObject *pyquat= (QuaternionObject *)pyval;
- if (BaseMath_ReadCallback(pyquat) == -1) {
- return false; /* exception raised */
- }
- if (4 != Size(vec)) {
- PyErr_Format(PyExc_AttributeError, "error setting vector, %d args, should be %d", 4, Size(vec));
- return false;
- }
- /* xyzw -> wxyz reordering is done by PyQuatTo */
- vec.setValue((float *) pyquat->quat);
- return true;
- }
- else if (EulerObject_Check(pyval)) {
- EulerObject *pyeul= (EulerObject *)pyval;
- if (BaseMath_ReadCallback(pyeul) == -1) {
- return false; /* exception raised */
- }
- if (3 != Size(vec)) {
- PyErr_Format(PyExc_AttributeError, "error setting vector, %d args, should be %d", 3, Size(vec));
- return false;
- }
- vec.setValue((float *) pyeul->eul);
- return true;
- }
- else
-#endif
- if (PyTuple_Check(pyval)) {
- unsigned int numitems = PyTuple_GET_SIZE(pyval);
- if (numitems != Size(vec)) {
- PyErr_Format(PyExc_AttributeError, "error setting vector, %d args, should be %d", numitems, Size(vec));
- return false;
- }
-
- for (unsigned int x = 0; x < numitems; x++)
- vec[x] = PyFloat_AsDouble(PyTuple_GET_ITEM(pyval, x)); /* borrow ref */
-
- if (PyErr_Occurred()) {
- PyErr_SetString(PyExc_AttributeError, "one or more of the items in the sequence was not a float");
- return false;
- }
-
- return true;
- }
- else if (PyObject_TypeCheck(pyval, (PyTypeObject *)&PyObjectPlus::Type)) {
- /* note, include this check because PySequence_Check does too much introspection
- * on the PyObject (like getting its __class__, on a BGE type this means searching up
- * the parent list each time only to discover its not a sequence.
- * GameObjects are often used as an alternative to vectors so this is a common case
- * better to do a quick check for it, likely the error below will be ignored.
- *
- * This is not 'correct' since we have proxy type CListValues's which could
- * contain floats/ints but there no cases of CValueLists being this way
- */
- PyErr_Format(PyExc_AttributeError, "expected a sequence type");
- return false;
- }
- else if (PySequence_Check(pyval)) {
- unsigned int numitems = PySequence_Size(pyval);
- if (numitems != Size(vec)) {
- PyErr_Format(PyExc_AttributeError, "error setting vector, %d args, should be %d", numitems, Size(vec));
- return false;
- }
-
- for (unsigned int x = 0; x < numitems; x++) {
- PyObject *item = PySequence_GetItem(pyval, x); /* new ref */
- vec[x] = PyFloat_AsDouble(item);
- Py_DECREF(item);
- }
-
- if (PyErr_Occurred()) {
- PyErr_SetString(PyExc_AttributeError, "one or more of the items in the sequence was not a float");
- return false;
- }
-
- return true;
- }
- else {
- PyErr_Format(PyExc_AttributeError, "not a sequence type, expected a sequence of numbers size %d", Size(vec));
- }
-
- return false;
-}
-
-
-bool PyQuatTo(PyObject *pyval, MT_Quaternion &qrot);
-
-bool PyOrientationTo(PyObject *pyval, MT_Matrix3x3 &mat, const char *error_prefix);
-
-/**
- * Converts an MT_Matrix4x4 to a python object.
- */
-PyObject *PyObjectFrom(const MT_Matrix4x4 &mat);
-
-/**
- * Converts an MT_Matrix3x3 to a python object.
- */
-PyObject *PyObjectFrom(const MT_Matrix3x3 &mat);
-
-/**
- * Converts an MT_Tuple2 to a python object.
- */
-PyObject *PyObjectFrom(const MT_Tuple2 &vec);
-
-/**
- * Converts an MT_Tuple3 to a python object
- */
-PyObject *PyObjectFrom(const MT_Tuple3 &vec);
-
-#ifdef USE_MATHUTILS
-/**
- * Converts an MT_Quaternion to a python object.
- */
-PyObject *PyObjectFrom(const MT_Quaternion &qrot);
-#endif
-
-/**
- * Converts an MT_Tuple4 to a python object.
- */
-PyObject *PyObjectFrom(const MT_Tuple4 &pos);
-
-#endif
-
-/**
- * Converts an MT_Vector3 to a python color object.
- */
-PyObject *PyColorFromVector(const MT_Vector3 &vec);
-
-#endif /* WITH_PYTHON */
diff --git a/source/gameengine/Ketsji/KX_PythonInit.cpp b/source/gameengine/Ketsji/KX_PythonInit.cpp
deleted file mode 100644
index 5540aad7a3f..00000000000
--- a/source/gameengine/Ketsji/KX_PythonInit.cpp
+++ /dev/null
@@ -1,2953 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- * Initialize Python thingies.
- */
-
-/** \file gameengine/Ketsji/KX_PythonInit.cpp
- * \ingroup ketsji
- */
-
-#include "GPU_glew.h"
-
-#ifdef _MSC_VER
-# pragma warning (disable:4786)
-#endif
-
-#ifdef WITH_PYTHON
-# ifdef _XOPEN_SOURCE
-# undef _XOPEN_SOURCE
-# endif
-# include <Python.h>
-
-extern "C" {
- # include "BLI_utildefines.h"
- # include "python_utildefines.h"
- # include "bpy_internal_import.h" /* from the blender python api, but we want to import text too! */
- # include "py_capi_utils.h"
- # include "mathutils.h" // 'mathutils' module copied here so the blenderlayer can use.
- # include "bgl.h"
- # include "blf_py_api.h"
-
- # include "marshal.h" /* python header for loading/saving dicts */
-}
-#include "../../../../intern/audaspace/intern/AUD_PyInit.h"
-
-#endif /* WITH_PYTHON */
-
-#include "KX_PythonInit.h"
-
-// directory header for py function getBlendFileList
-#ifndef WIN32
-# include <dirent.h>
-# include <stdlib.h>
-#else
-# include <io.h>
-# include "BLI_winstuff.h"
-#endif
-
-//python physics binding
-#include "KX_PyConstraintBinding.h"
-
-#include "KX_KetsjiEngine.h"
-#include "KX_RadarSensor.h"
-#include "KX_RaySensor.h"
-#include "KX_ArmatureSensor.h"
-#include "KX_SceneActuator.h"
-#include "KX_GameActuator.h"
-#include "KX_ParentActuator.h"
-#include "KX_SCA_DynamicActuator.h"
-#include "KX_SteeringActuator.h"
-#include "KX_NavMeshObject.h"
-#include "KX_MouseActuator.h"
-#include "KX_TrackToActuator.h"
-
-#include "SCA_IInputDevice.h"
-#include "SCA_PropertySensor.h"
-#include "SCA_RandomActuator.h"
-#include "SCA_KeyboardSensor.h" /* IsPrintable, ToCharacter */
-#include "SCA_JoystickManager.h" /* JOYINDEX_MAX */
-#include "SCA_PythonJoystick.h"
-#include "SCA_PythonKeyboard.h"
-#include "SCA_PythonMouse.h"
-#include "KX_ConstraintActuator.h"
-#include "KX_SoundActuator.h"
-#include "KX_StateActuator.h"
-#include "BL_ActionActuator.h"
-#include "BL_ArmatureObject.h"
-#include "RAS_IRasterizer.h"
-#include "RAS_ICanvas.h"
-#include "RAS_IOffScreen.h"
-#include "RAS_BucketManager.h"
-#include "RAS_2DFilterManager.h"
-#include "MT_Vector3.h"
-#include "MT_Point3.h"
-#include "EXP_ListValue.h"
-#include "EXP_InputParser.h"
-#include "KX_Scene.h"
-
-#include "NG_NetworkScene.h" //Needed for sendMessage()
-
-#include "BL_Shader.h"
-#include "BL_Action.h"
-
-#include "KX_PyMath.h"
-
-#include "EXP_PyObjectPlus.h"
-
-#include "KX_PythonInitTypes.h"
-
-/* we only need this to get a list of libraries from the main struct */
-#include "DNA_ID.h"
-#include "DNA_scene_types.h"
-
-#include "PHY_IPhysicsEnvironment.h"
-
-extern "C" {
-#include "BKE_main.h"
-#include "BKE_global.h"
-#include "BKE_library.h"
-#include "BKE_appdir.h"
-#include "BKE_blender_version.h"
-#include "BLI_blenlib.h"
-#include "GPU_material.h"
-#include "MEM_guardedalloc.h"
-}
-
-/* for converting new scenes */
-#include "KX_BlenderSceneConverter.h"
-#include "KX_LibLoadStatus.h"
-#include "KX_MeshProxy.h" /* for creating a new library of mesh objects */
-extern "C" {
- #include "BKE_idcode.h"
-}
-
-// 'local' copy of canvas ptr, for window height/width python scripts
-
-#ifdef WITH_PYTHON
-
-static RAS_ICanvas* gp_Canvas = NULL;
-static char gp_GamePythonPath[FILE_MAX] = "";
-static char gp_GamePythonPathOrig[FILE_MAX] = ""; // not super happy about this, but we need to remember the first loaded file for the global/dict load save
-
-static SCA_PythonKeyboard* gp_PythonKeyboard = NULL;
-static SCA_PythonMouse* gp_PythonMouse = NULL;
-static SCA_PythonJoystick* gp_PythonJoysticks[JOYINDEX_MAX] = {NULL};
-#endif // WITH_PYTHON
-
-static KX_Scene* gp_KetsjiScene = NULL;
-static KX_KetsjiEngine* gp_KetsjiEngine = NULL;
-static RAS_IRasterizer* gp_Rasterizer = NULL;
-
-
-void KX_SetActiveScene(class KX_Scene* scene)
-{
- gp_KetsjiScene = scene;
-}
-
-class KX_Scene* KX_GetActiveScene()
-{
- return gp_KetsjiScene;
-}
-
-class KX_KetsjiEngine* KX_GetActiveEngine()
-{
- return gp_KetsjiEngine;
-}
-
-/* why is this in python? */
-void KX_RasterizerDrawDebugLine(const MT_Vector3& from,const MT_Vector3& to,const MT_Vector3& color)
-{
- if (gp_Rasterizer)
- gp_Rasterizer->DrawDebugLine(gp_KetsjiScene, from, to, color);
-}
-
-void KX_RasterizerDrawDebugCircle(const MT_Vector3& center, const MT_Scalar radius, const MT_Vector3& color,
- const MT_Vector3& normal, int nsector)
-{
- if (gp_Rasterizer)
- gp_Rasterizer->DrawDebugCircle(gp_KetsjiScene, center, radius, color, normal, nsector);
-}
-
-#ifdef WITH_PYTHON
-
-
-static struct {
- PyObject *path;
- PyObject *meta_path;
- PyObject *modules;
-} gp_sys_backup = {NULL};
-
-/* Macro for building the keyboard translation */
-//#define KX_MACRO_addToDict(dict, name) PyDict_SetItemString(dict, #name, PyLong_FromLong(SCA_IInputDevice::KX_##name))
-//#define KX_MACRO_addToDict(dict, name) PyDict_SetItemString(dict, #name, item=PyLong_FromLong(name)); Py_DECREF(item)
-/* For the defines for types from logic bricks, we do stuff explicitly... */
-#define KX_MACRO_addTypesToDict(dict, name, value) KX_MACRO_addTypesToDict_fn(dict, #name, value)
-static void KX_MACRO_addTypesToDict_fn(PyObject *dict, const char *name, long value)
-{
- PyObject *item;
-
- item = PyLong_FromLong(value);
- PyDict_SetItemString(dict, name, item);
- Py_DECREF(item);
-}
-
-
-
-// temporarily python stuff, will be put in another place later !
-#include "EXP_Python.h"
-#include "SCA_PythonController.h"
-// List of methods defined in the module
-
-static PyObject *ErrorObject;
-
-PyDoc_STRVAR(gPyGetRandomFloat_doc,
-"getRandomFloat()\n"
-"returns a random floating point value in the range [0..1]"
-);
-static PyObject *gPyGetRandomFloat(PyObject *)
-{
- return PyFloat_FromDouble(MT_random());
-}
-
-static PyObject *gPySetGravity(PyObject *, PyObject *value)
-{
- MT_Vector3 vec;
- if (!PyVecTo(value, vec))
- return NULL;
-
- if (gp_KetsjiScene)
- gp_KetsjiScene->SetGravity(vec);
-
- Py_RETURN_NONE;
-}
-
-PyDoc_STRVAR(gPyExpandPath_doc,
-"expandPath(path)\n"
-"Converts a blender internal path into a proper file system path.\n"
-" path - the string path to convert.\n"
-"Use / as directory separator in path\n"
-"You can use '//' at the start of the string to define a relative path."
-"Blender replaces that string by the directory of the current .blend or runtime file to make a full path name.\n"
-"The function also converts the directory separator to the local file system format."
-);
-static PyObject *gPyExpandPath(PyObject *, PyObject *args)
-{
- char expanded[FILE_MAX];
- char* filename;
-
- if (!PyArg_ParseTuple(args,"s:ExpandPath",&filename))
- return NULL;
-
- BLI_strncpy(expanded, filename, FILE_MAX);
- BLI_path_abs(expanded, gp_GamePythonPath);
- return PyC_UnicodeFromByte(expanded);
-}
-
-PyDoc_STRVAR(gPyStartGame_doc,
-"startGame(blend)\n"
-"Loads the blend file"
-);
-static PyObject *gPyStartGame(PyObject *, PyObject *args)
-{
- char* blendfile;
-
- if (!PyArg_ParseTuple(args, "s:startGame", &blendfile))
- return NULL;
-
- gp_KetsjiEngine->RequestExit(KX_EXIT_REQUEST_START_OTHER_GAME);
- gp_KetsjiEngine->SetNameNextGame(blendfile);
-
- Py_RETURN_NONE;
-}
-
-PyDoc_STRVAR(gPyEndGame_doc,
-"endGame()\n"
-"Ends the current game"
-);
-static PyObject *gPyEndGame(PyObject *)
-{
- gp_KetsjiEngine->RequestExit(KX_EXIT_REQUEST_QUIT_GAME);
-
- //printf("%s\n", gp_GamePythonPath);
-
- Py_RETURN_NONE;
-}
-
-PyDoc_STRVAR(gPyRestartGame_doc,
-"restartGame()\n"
-"Restarts the current game by reloading the .blend file"
-);
-static PyObject *gPyRestartGame(PyObject *)
-{
- gp_KetsjiEngine->RequestExit(KX_EXIT_REQUEST_RESTART_GAME);
- gp_KetsjiEngine->SetNameNextGame(gp_GamePythonPath);
-
- Py_RETURN_NONE;
-}
-
-PyDoc_STRVAR(gPySaveGlobalDict_doc,
-"saveGlobalDict()\n"
-"Saves bge.logic.globalDict to a file"
-);
-static PyObject *gPySaveGlobalDict(PyObject *)
-{
- char marshal_path[512];
- char *marshal_buffer = NULL;
- unsigned int marshal_length;
- FILE *fp = NULL;
-
- pathGamePythonConfig(marshal_path);
- marshal_length = saveGamePythonConfig(&marshal_buffer);
-
- if (marshal_length && marshal_buffer)
- {
- fp = fopen(marshal_path, "wb");
-
- if (fp)
- {
- if (fwrite(marshal_buffer, 1, marshal_length, fp) != marshal_length)
- printf("Warning: could not write marshal data\n");
-
- fclose(fp);
- } else {
- printf("Warning: could not open marshal file\n");
- }
- } else {
- printf("Warning: could not create marshal buffer\n");
- }
-
- if (marshal_buffer)
- delete [] marshal_buffer;
-
- Py_RETURN_NONE;
-}
-
-PyDoc_STRVAR(gPyLoadGlobalDict_doc,
-"LoadGlobalDict()\n"
-"Loads bge.logic.globalDict from a file"
-);
-static PyObject *gPyLoadGlobalDict(PyObject *)
-{
- char marshal_path[512];
- char *marshal_buffer = NULL;
- int marshal_length;
- FILE *fp = NULL;
- int result;
-
- pathGamePythonConfig(marshal_path);
-
- fp = fopen(marshal_path, "rb");
-
- if (fp) {
- // obtain file size:
- fseek (fp, 0, SEEK_END);
- marshal_length = ftell(fp);
- if (marshal_length == -1) {
- printf("Warning: could not read position of '%s'\n", marshal_path);
- fclose(fp);
- Py_RETURN_NONE;
- }
- rewind(fp);
-
- marshal_buffer = (char*)malloc (sizeof(char)*marshal_length);
-
- result = fread(marshal_buffer, 1, marshal_length, fp);
-
- if (result == marshal_length) {
- loadGamePythonConfig(marshal_buffer, marshal_length);
- } else {
- printf("Warning: could not read all of '%s'\n", marshal_path);
- }
-
- free(marshal_buffer);
- fclose(fp);
- } else {
- printf("Warning: could not open '%s'\n", marshal_path);
- }
-
- Py_RETURN_NONE;
-}
-
-PyDoc_STRVAR(gPyGetProfileInfo_doc,
-"getProfileInfo()\n"
-"returns a dictionary with profiling information"
-);
-static PyObject *gPyGetProfileInfo(PyObject *)
-{
- return gp_KetsjiEngine->GetPyProfileDict();
-}
-
-PyDoc_STRVAR(gPySendMessage_doc,
-"sendMessage(subject, [body, to, from])\n"
-"sends a message in same manner as a message actuator"
-" subject = Subject of the message"
-" body = Message body"
-" to = Name of object to send the message to"
-" from = Name of object to send the string from"
-);
-static PyObject *gPySendMessage(PyObject *, PyObject *args)
-{
- char* subject;
- char* body = (char *)"";
- char* to = (char *)"";
- char* from = (char *)"";
-
- if (!PyArg_ParseTuple(args, "s|sss:sendMessage", &subject, &body, &to, &from))
- return NULL;
-
- gp_KetsjiScene->GetNetworkScene()->SendMessage(to, from, subject, body);
-
- Py_RETURN_NONE;
-}
-
-// this gets a pointer to an array filled with floats
-static PyObject *gPyGetSpectrum(PyObject *)
-{
- PyObject *resultlist = PyList_New(512);
-
- for (int index = 0; index < 512; index++)
- {
- PyList_SET_ITEM(resultlist, index, PyFloat_FromDouble(0.0));
- }
-
- return resultlist;
-}
-
-static PyObject *gPySetLogicTicRate(PyObject *, PyObject *args)
-{
- float ticrate;
- if (!PyArg_ParseTuple(args, "f:setLogicTicRate", &ticrate))
- return NULL;
-
- KX_KetsjiEngine::SetTicRate(ticrate);
- Py_RETURN_NONE;
-}
-
-static PyObject *gPyGetLogicTicRate(PyObject *)
-{
- return PyFloat_FromDouble(KX_KetsjiEngine::GetTicRate());
-}
-
-static PyObject *gPySetExitKey(PyObject *, PyObject *args)
-{
- short exitkey;
- if (!PyArg_ParseTuple(args, "h:setExitKey", &exitkey))
- return NULL;
- KX_KetsjiEngine::SetExitKey(exitkey);
- Py_RETURN_NONE;
-}
-
-static PyObject *gPyGetExitKey(PyObject *)
-{
- return PyLong_FromLong(KX_KetsjiEngine::GetExitKey());
-}
-
-static PyObject *gPySetRender(PyObject *, PyObject *args)
-{
- int render;
- if (!PyArg_ParseTuple(args, "i:setRender", &render))
- return NULL;
- KX_KetsjiEngine::SetRender(render);
- Py_RETURN_NONE;
-}
-
-static PyObject *gPyGetRender(PyObject *)
-{
- return PyBool_FromLong(KX_KetsjiEngine::GetRender());
-}
-
-
-static PyObject *gPySetMaxLogicFrame(PyObject *, PyObject *args)
-{
- int frame;
- if (!PyArg_ParseTuple(args, "i:setMaxLogicFrame", &frame))
- return NULL;
-
- KX_KetsjiEngine::SetMaxLogicFrame(frame);
- Py_RETURN_NONE;
-}
-
-static PyObject *gPyGetMaxLogicFrame(PyObject *)
-{
- return PyLong_FromLong(KX_KetsjiEngine::GetMaxLogicFrame());
-}
-
-static PyObject *gPySetMaxPhysicsFrame(PyObject *, PyObject *args)
-{
- int frame;
- if (!PyArg_ParseTuple(args, "i:setMaxPhysicsFrame", &frame))
- return NULL;
-
- KX_KetsjiEngine::SetMaxPhysicsFrame(frame);
- Py_RETURN_NONE;
-}
-
-static PyObject *gPyGetMaxPhysicsFrame(PyObject *)
-{
- return PyLong_FromLong(KX_KetsjiEngine::GetMaxPhysicsFrame());
-}
-
-static PyObject *gPySetPhysicsTicRate(PyObject *, PyObject *args)
-{
- float ticrate;
- if (!PyArg_ParseTuple(args, "f:setPhysicsTicRate", &ticrate))
- return NULL;
-
- PHY_GetActiveEnvironment()->SetFixedTimeStep(true,ticrate);
- Py_RETURN_NONE;
-}
-#if 0 // unused
-static PyObject *gPySetPhysicsDebug(PyObject *, PyObject *args)
-{
- int debugMode;
- if (!PyArg_ParseTuple(args, "i:setPhysicsDebug", &debugMode))
- return NULL;
-
- PHY_GetActiveEnvironment()->setDebugMode(debugMode);
- Py_RETURN_NONE;
-}
-#endif
-
-
-static PyObject *gPyGetPhysicsTicRate(PyObject *)
-{
- return PyFloat_FromDouble(PHY_GetActiveEnvironment()->GetFixedTimeStep());
-}
-
-static PyObject *gPySetAnimRecordFrame(PyObject *, PyObject *args)
-{
- int anim_record_frame;
-
- if (!PyArg_ParseTuple(args, "i:setAnimRecordFrame", &anim_record_frame))
- return NULL;
-
- if (anim_record_frame < 0 && (U.flag & USER_NONEGFRAMES)) {
- PyErr_Format(PyExc_ValueError, "Frame number must be non-negative (was %i).", anim_record_frame);
- return NULL;
- }
-
- gp_KetsjiEngine->setAnimRecordFrame(anim_record_frame);
- Py_RETURN_NONE;
-}
-
-static PyObject *gPyGetAnimRecordFrame(PyObject *)
-{
- return PyLong_FromLong(gp_KetsjiEngine->getAnimRecordFrame());
-}
-
-static PyObject *gPyGetAverageFrameRate(PyObject *)
-{
- return PyFloat_FromDouble(KX_KetsjiEngine::GetAverageFrameRate());
-}
-
-static PyObject *gPyGetUseExternalClock(PyObject *)
-{
- return PyBool_FromLong(gp_KetsjiEngine->GetUseExternalClock());
-}
-
-static PyObject *gPySetUseExternalClock(PyObject *, PyObject *args)
-{
- bool bUseExternalClock;
-
- if (!PyArg_ParseTuple(args, "p:setUseExternalClock", &bUseExternalClock))
- return NULL;
-
- gp_KetsjiEngine->SetUseExternalClock(bUseExternalClock);
- Py_RETURN_NONE;
-}
-
-static PyObject *gPyGetClockTime(PyObject *)
-{
- return PyFloat_FromDouble(gp_KetsjiEngine->GetClockTime());
-}
-
-static PyObject *gPySetClockTime(PyObject *, PyObject *args)
-{
- double externalClockTime;
-
- if (!PyArg_ParseTuple(args, "d:setClockTime", &externalClockTime))
- return NULL;
-
- gp_KetsjiEngine->SetClockTime(externalClockTime);
- Py_RETURN_NONE;
-}
-
-static PyObject *gPyGetFrameTime(PyObject *)
-{
- return PyFloat_FromDouble(gp_KetsjiEngine->GetFrameTime());
-}
-
-static PyObject *gPyGetRealTime(PyObject *)
-{
- return PyFloat_FromDouble(gp_KetsjiEngine->GetRealTime());
-}
-
-static PyObject *gPyGetTimeScale(PyObject *)
-{
- return PyFloat_FromDouble(gp_KetsjiEngine->GetTimeScale());
-}
-
-static PyObject *gPySetTimeScale(PyObject *, PyObject *args)
-{
- double time_scale;
-
- if (!PyArg_ParseTuple(args, "d:setTimeScale", &time_scale))
- return NULL;
-
- gp_KetsjiEngine->SetTimeScale(time_scale);
- Py_RETURN_NONE;
-}
-
-static PyObject *gPyGetBlendFileList(PyObject *, PyObject *args)
-{
- char cpath[sizeof(gp_GamePythonPath)];
- char *searchpath = NULL;
- PyObject *list, *value;
-
- DIR *dp;
- struct dirent *dirp;
-
- if (!PyArg_ParseTuple(args, "|s:getBlendFileList", &searchpath))
- return NULL;
-
- list = PyList_New(0);
-
- if (searchpath) {
- BLI_strncpy(cpath, searchpath, FILE_MAX);
- BLI_path_abs(cpath, gp_GamePythonPath);
- } else {
- /* Get the dir only */
- BLI_split_dir_part(gp_GamePythonPath, cpath, sizeof(cpath));
- }
-
- if ((dp = opendir(cpath)) == NULL) {
- /* todo, show the errno, this shouldnt happen anyway if the blendfile is readable */
- fprintf(stderr, "Could not read directory (%s) failed, code %d (%s)\n", cpath, errno, strerror(errno));
- return list;
- }
-
- while ((dirp = readdir(dp)) != NULL) {
- if (BLI_testextensie(dirp->d_name, ".blend")) {
- value = PyC_UnicodeFromByte(dirp->d_name);
- PyList_Append(list, value);
- Py_DECREF(value);
- }
- }
-
- closedir(dp);
- return list;
-}
-
-PyDoc_STRVAR(gPyAddScene_doc,
-"addScene(name, [overlay])\n"
-"Adds a scene to the game engine.\n"
-" name = Name of the scene\n"
-" overlay = Overlay or underlay"
-);
-static PyObject *gPyAddScene(PyObject *, PyObject *args)
-{
- char* name;
- int overlay = 1;
-
- if (!PyArg_ParseTuple(args, "s|i:addScene", &name , &overlay))
- return NULL;
-
- gp_KetsjiEngine->ConvertAndAddScene(name, (overlay != 0));
-
- Py_RETURN_NONE;
-}
-
-PyDoc_STRVAR(gPyGetCurrentScene_doc,
-"getCurrentScene()\n"
-"Gets a reference to the current scene."
-);
-static PyObject *gPyGetCurrentScene(PyObject *self)
-{
- return gp_KetsjiScene->GetProxy();
-}
-
-PyDoc_STRVAR(gPyGetSceneList_doc,
-"getSceneList()\n"
-"Return a list of converted scenes."
-);
-static PyObject *gPyGetSceneList(PyObject *self)
-{
- KX_KetsjiEngine* m_engine = KX_GetActiveEngine();
- PyObject *list;
- KX_SceneList* scenes = m_engine->CurrentScenes();
- int numScenes = scenes->size();
- int i;
-
- list = PyList_New(numScenes);
-
- for (i=0;i<numScenes;i++)
- {
- KX_Scene* scene = scenes->at(i);
- PyList_SET_ITEM(list, i, scene->GetProxy());
- }
-
- return list;
-}
-
-static PyObject *pyPrintStats(PyObject *,PyObject *,PyObject *)
-{
- gp_KetsjiScene->GetSceneConverter()->PrintStats();
- Py_RETURN_NONE;
-}
-
-static PyObject *pyPrintExt(PyObject *,PyObject *,PyObject *)
-{
- if (gp_Rasterizer)
- gp_Rasterizer->PrintHardwareInfo();
- else
- printf("Warning: no rasterizer detected for PrintGLInfo!\n");
-
- Py_RETURN_NONE;
-}
-
-static PyObject *gLibLoad(PyObject *, PyObject *args, PyObject *kwds)
-{
- KX_Scene *kx_scene= gp_KetsjiScene;
- char *path;
- char *group;
- Py_buffer py_buffer;
- py_buffer.buf = NULL;
- char *err_str= NULL;
- KX_LibLoadStatus *status = NULL;
-
- short options=0;
- int load_actions=0, verbose=0, load_scripts=1, async=0;
-
- static const char *kwlist[] = {"path", "group", "buffer", "load_actions", "verbose", "load_scripts", "async", NULL};
-
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "ss|y*iiIi:LibLoad", const_cast<char**>(kwlist),
- &path, &group, &py_buffer, &load_actions, &verbose, &load_scripts, &async))
- return NULL;
-
- /* setup options */
- if (load_actions != 0)
- options |= KX_BlenderSceneConverter::LIB_LOAD_LOAD_ACTIONS;
- if (verbose != 0)
- options |= KX_BlenderSceneConverter::LIB_LOAD_VERBOSE;
- if (load_scripts != 0)
- options |= KX_BlenderSceneConverter::LIB_LOAD_LOAD_SCRIPTS;
- if (async != 0)
- options |= KX_BlenderSceneConverter::LIB_LOAD_ASYNC;
-
- if (!py_buffer.buf)
- {
- char abs_path[FILE_MAX];
- // Make the path absolute
- BLI_strncpy(abs_path, path, sizeof(abs_path));
- BLI_path_abs(abs_path, gp_GamePythonPath);
-
- if ((status=kx_scene->GetSceneConverter()->LinkBlendFilePath(abs_path, group, kx_scene, &err_str, options))) {
- return status->GetProxy();
- }
- }
- else
- {
-
- if ((status=kx_scene->GetSceneConverter()->LinkBlendFileMemory(py_buffer.buf, py_buffer.len, path, group, kx_scene, &err_str, options))) {
- PyBuffer_Release(&py_buffer);
- return status->GetProxy();
- }
-
- PyBuffer_Release(&py_buffer);
- }
-
- if (err_str) {
- PyErr_SetString(PyExc_ValueError, err_str);
- return NULL;
- }
-
- Py_RETURN_FALSE;
-}
-
-static PyObject *gLibNew(PyObject *, PyObject *args)
-{
- KX_Scene *kx_scene= gp_KetsjiScene;
- char *path;
- char *group;
- const char *name;
- PyObject *names;
- int idcode;
-
- if (!PyArg_ParseTuple(args,"ssO!:LibNew",&path, &group, &PyList_Type, &names))
- return NULL;
-
- if (kx_scene->GetSceneConverter()->GetMainDynamicPath(path))
- {
- PyErr_SetString(PyExc_KeyError, "the name of the path given exists");
- return NULL;
- }
-
- idcode= BKE_idcode_from_name(group);
- if (idcode==0) {
- PyErr_Format(PyExc_ValueError, "invalid group given \"%s\"", group);
- return NULL;
- }
-
- Main *maggie=BKE_main_new();
- kx_scene->GetSceneConverter()->GetMainDynamic().push_back(maggie);
- strncpy(maggie->name, path, sizeof(maggie->name)-1);
-
- /* Copy the object into main */
- if (idcode==ID_ME) {
- PyObject *ret= PyList_New(0);
- PyObject *item;
- for (Py_ssize_t i= 0; i < PyList_GET_SIZE(names); i++) {
- name= _PyUnicode_AsString(PyList_GET_ITEM(names, i));
- if (name) {
- RAS_MeshObject *meshobj= kx_scene->GetSceneConverter()->ConvertMeshSpecial(kx_scene, maggie, name);
- if (meshobj) {
- KX_MeshProxy* meshproxy = new KX_MeshProxy(meshobj);
- item= meshproxy->NewProxy(true);
- PyList_Append(ret, item);
- Py_DECREF(item);
- }
- }
- else {
- PyErr_Clear(); /* wasnt a string, ignore for now */
- }
- }
-
- return ret;
- }
- else {
- PyErr_Format(PyExc_ValueError, "only \"Mesh\" group currently supported");
- return NULL;
- }
-
- Py_RETURN_NONE;
-}
-
-static PyObject *gLibFree(PyObject *, PyObject *args)
-{
- KX_Scene *kx_scene= gp_KetsjiScene;
- char *path;
-
- if (!PyArg_ParseTuple(args,"s:LibFree",&path))
- return NULL;
-
- if (kx_scene->GetSceneConverter()->FreeBlendFile(path))
- {
- Py_RETURN_TRUE;
- }
- else {
- Py_RETURN_FALSE;
- }
-}
-
-static PyObject *gLibList(PyObject *, PyObject *args)
-{
- vector<Main*> &dynMaggie = gp_KetsjiScene->GetSceneConverter()->GetMainDynamic();
- int i= 0;
- PyObject *list= PyList_New(dynMaggie.size());
-
- for (vector<Main*>::iterator it=dynMaggie.begin(); !(it==dynMaggie.end()); it++)
- {
- PyList_SET_ITEM(list, i++, PyUnicode_FromString( (*it)->name) );
- }
-
- return list;
-}
-
-struct PyNextFrameState pynextframestate;
-static PyObject *gPyNextFrame(PyObject *)
-{
- if (pynextframestate.func == NULL) Py_RETURN_NONE;
- if (pynextframestate.state == NULL) Py_RETURN_NONE; //should never happen; raise exception instead?
-
- if (pynextframestate.func(pynextframestate.state)) //nonzero = stop
- {
- Py_RETURN_TRUE;
- }
- else // 0 = go on
- {
- Py_RETURN_FALSE;
- }
-}
-
-
-static struct PyMethodDef game_methods[] = {
- {"expandPath", (PyCFunction)gPyExpandPath, METH_VARARGS, (const char *)gPyExpandPath_doc},
- {"startGame", (PyCFunction)gPyStartGame, METH_VARARGS, (const char *)gPyStartGame_doc},
- {"endGame", (PyCFunction)gPyEndGame, METH_NOARGS, (const char *)gPyEndGame_doc},
- {"restartGame", (PyCFunction)gPyRestartGame, METH_NOARGS, (const char *)gPyRestartGame_doc},
- {"saveGlobalDict", (PyCFunction)gPySaveGlobalDict, METH_NOARGS, (const char *)gPySaveGlobalDict_doc},
- {"loadGlobalDict", (PyCFunction)gPyLoadGlobalDict, METH_NOARGS, (const char *)gPyLoadGlobalDict_doc},
- {"sendMessage", (PyCFunction)gPySendMessage, METH_VARARGS, (const char *)gPySendMessage_doc},
- {"getCurrentController", (PyCFunction) SCA_PythonController::sPyGetCurrentController, METH_NOARGS, SCA_PythonController::sPyGetCurrentController__doc__},
- {"getCurrentScene", (PyCFunction) gPyGetCurrentScene, METH_NOARGS, gPyGetCurrentScene_doc},
- {"getSceneList", (PyCFunction) gPyGetSceneList, METH_NOARGS, (const char *)gPyGetSceneList_doc},
- {"addScene", (PyCFunction)gPyAddScene, METH_VARARGS, (const char *)gPyAddScene_doc},
- {"getRandomFloat",(PyCFunction) gPyGetRandomFloat, METH_NOARGS, (const char *)gPyGetRandomFloat_doc},
- {"setGravity",(PyCFunction) gPySetGravity, METH_O, (const char *)"set Gravitation"},
- {"getSpectrum",(PyCFunction) gPyGetSpectrum, METH_NOARGS, (const char *)"get audio spectrum"},
- {"getMaxLogicFrame", (PyCFunction) gPyGetMaxLogicFrame, METH_NOARGS, (const char *)"Gets the max number of logic frame per render frame"},
- {"setMaxLogicFrame", (PyCFunction) gPySetMaxLogicFrame, METH_VARARGS, (const char *)"Sets the max number of logic frame per render frame"},
- {"getMaxPhysicsFrame", (PyCFunction) gPyGetMaxPhysicsFrame, METH_NOARGS, (const char *)"Gets the max number of physics frame per render frame"},
- {"setMaxPhysicsFrame", (PyCFunction) gPySetMaxPhysicsFrame, METH_VARARGS, (const char *)"Sets the max number of physics farme per render frame"},
- {"getLogicTicRate", (PyCFunction) gPyGetLogicTicRate, METH_NOARGS, (const char *)"Gets the logic tic rate"},
- {"setLogicTicRate", (PyCFunction) gPySetLogicTicRate, METH_VARARGS, (const char *)"Sets the logic tic rate"},
- {"getPhysicsTicRate", (PyCFunction) gPyGetPhysicsTicRate, METH_NOARGS, (const char *)"Gets the physics tic rate"},
- {"setPhysicsTicRate", (PyCFunction) gPySetPhysicsTicRate, METH_VARARGS, (const char *)"Sets the physics tic rate"},
- {"getAnimRecordFrame", (PyCFunction) gPyGetAnimRecordFrame, METH_NOARGS, (const char *)"Gets the current frame number used for animation recording"},
- {"setAnimRecordFrame", (PyCFunction) gPySetAnimRecordFrame, METH_VARARGS, (const char *)"Sets the current frame number used for animation recording"},
- {"getExitKey", (PyCFunction) gPyGetExitKey, METH_NOARGS, (const char *)"Gets the key used to exit the game engine"},
- {"setExitKey", (PyCFunction) gPySetExitKey, METH_VARARGS, (const char *)"Sets the key used to exit the game engine"},
- {"setRender", (PyCFunction) gPySetRender, METH_VARARGS, (const char *)"Set the global render flag"},
- {"getRender", (PyCFunction) gPyGetRender, METH_NOARGS, (const char *)"get the global render flag value"},
- {"getUseExternalClock", (PyCFunction) gPyGetUseExternalClock, METH_NOARGS, (const char *)"Get if we use the time provided by an external clock"},
- {"setUseExternalClock", (PyCFunction) gPySetUseExternalClock, METH_VARARGS, (const char *)"Set if we use the time provided by an external clock"},
- {"getClockTime", (PyCFunction) gPyGetClockTime, METH_NOARGS, (const char *)"Get the last BGE render time. "
- "The BGE render time is the simulated time corresponding to the next scene that will be renderered"},
- {"setClockTime", (PyCFunction) gPySetClockTime, METH_VARARGS, (const char *)"Set the BGE render time. "
- "The BGE render time is the simulated time corresponding to the next scene that will be rendered"},
- {"getFrameTime", (PyCFunction) gPyGetFrameTime, METH_NOARGS, (const char *)"Get the BGE last frametime. "
- "The BGE frame time is the simulated time corresponding to the last call of the logic system"},
- {"getRealTime", (PyCFunction) gPyGetRealTime, METH_NOARGS, (const char *)"Get the real system time. "
- "The real-time corresponds to the system time" },
- {"getAverageFrameRate", (PyCFunction) gPyGetAverageFrameRate, METH_NOARGS, (const char *)"Gets the estimated average frame rate"},
- {"getTimeScale", (PyCFunction) gPyGetTimeScale, METH_NOARGS, (const char *)"Get the time multiplier"},
- {"setTimeScale", (PyCFunction) gPySetTimeScale, METH_VARARGS, (const char *)"Set the time multiplier"},
- {"getBlendFileList", (PyCFunction)gPyGetBlendFileList, METH_VARARGS, (const char *)"Gets a list of blend files in the same directory as the current blend file"},
- {"PrintGLInfo", (PyCFunction)pyPrintExt, METH_NOARGS, (const char *)"Prints GL Extension Info"},
- {"PrintMemInfo", (PyCFunction)pyPrintStats, METH_NOARGS, (const char *)"Print engine statistics"},
- {"NextFrame", (PyCFunction)gPyNextFrame, METH_NOARGS, (const char *)"Render next frame (if Python has control)"},
- {"getProfileInfo", (PyCFunction)gPyGetProfileInfo, METH_NOARGS, gPyGetProfileInfo_doc},
- /* library functions */
- {"LibLoad", (PyCFunction)gLibLoad, METH_VARARGS|METH_KEYWORDS, (const char *)""},
- {"LibNew", (PyCFunction)gLibNew, METH_VARARGS, (const char *)""},
- {"LibFree", (PyCFunction)gLibFree, METH_VARARGS, (const char *)""},
- {"LibList", (PyCFunction)gLibList, METH_VARARGS, (const char *)""},
-
- {NULL, (PyCFunction) NULL, 0, NULL }
-};
-
-static PyObject *gPyGetWindowHeight(PyObject *, PyObject *args)
-{
- return PyLong_FromLong((gp_Canvas ? gp_Canvas->GetHeight() : 0));
-}
-
-
-
-static PyObject *gPyGetWindowWidth(PyObject *, PyObject *args)
-{
- return PyLong_FromLong((gp_Canvas ? gp_Canvas->GetWidth() : 0));
-}
-
-
-
-// temporarility visibility thing, will be moved to rasterizer/renderer later
-bool gUseVisibilityTemp = false;
-
-static PyObject *gPyEnableVisibility(PyObject *, PyObject *args)
-{
- int visible;
- if (!PyArg_ParseTuple(args,"i:enableVisibility",&visible))
- return NULL;
-
- gUseVisibilityTemp = (visible != 0);
- Py_RETURN_NONE;
-}
-
-
-
-static PyObject *gPyShowMouse(PyObject *, PyObject *args)
-{
- int visible;
- if (!PyArg_ParseTuple(args,"i:showMouse",&visible))
- return NULL;
-
- if (visible)
- {
- if (gp_Canvas)
- gp_Canvas->SetMouseState(RAS_ICanvas::MOUSE_NORMAL);
- } else
- {
- if (gp_Canvas)
- gp_Canvas->SetMouseState(RAS_ICanvas::MOUSE_INVISIBLE);
- }
-
- Py_RETURN_NONE;
-}
-
-
-
-static PyObject *gPySetMousePosition(PyObject *, PyObject *args)
-{
- int x,y;
- if (!PyArg_ParseTuple(args,"ii:setMousePosition",&x,&y))
- return NULL;
-
- if (gp_Canvas)
- gp_Canvas->SetMousePosition(x,y);
-
- Py_RETURN_NONE;
-}
-
-static PyObject *gPySetEyeSeparation(PyObject *, PyObject *args)
-{
- float sep;
- if (!PyArg_ParseTuple(args, "f:setEyeSeparation", &sep))
- return NULL;
-
- if (!gp_Rasterizer) {
- PyErr_SetString(PyExc_RuntimeError, "Rasterizer.setEyeSeparation(float), Rasterizer not available");
- return NULL;
- }
-
- gp_Rasterizer->SetEyeSeparation(sep);
-
- Py_RETURN_NONE;
-}
-
-static PyObject *gPyGetEyeSeparation(PyObject *)
-{
- if (!gp_Rasterizer) {
- PyErr_SetString(PyExc_RuntimeError, "Rasterizer.getEyeSeparation(), Rasterizer not available");
- return NULL;
- }
-
- return PyFloat_FromDouble(gp_Rasterizer->GetEyeSeparation());
-}
-
-static PyObject *gPySetFocalLength(PyObject *, PyObject *args)
-{
- float focus;
- if (!PyArg_ParseTuple(args, "f:setFocalLength", &focus))
- return NULL;
-
- if (!gp_Rasterizer) {
- PyErr_SetString(PyExc_RuntimeError, "Rasterizer.setFocalLength(float), Rasterizer not available");
- return NULL;
- }
-
- gp_Rasterizer->SetFocalLength(focus);
-
- Py_RETURN_NONE;
-}
-
-static PyObject *gPyGetFocalLength(PyObject *, PyObject *, PyObject *)
-{
- if (!gp_Rasterizer) {
- PyErr_SetString(PyExc_RuntimeError, "Rasterizer.getFocalLength(), Rasterizer not available");
- return NULL;
- }
-
- return PyFloat_FromDouble(gp_Rasterizer->GetFocalLength());
-
- Py_RETURN_NONE;
-}
-
-static PyObject *gPyGetStereoEye(PyObject *, PyObject *, PyObject *)
-{
- int flag = RAS_IRasterizer::RAS_STEREO_LEFTEYE;
-
- if (!gp_Rasterizer) {
- PyErr_SetString(PyExc_RuntimeError, "Rasterizer.getStereoEye(), Rasterizer not available");
- return NULL;
- }
-
- if (gp_Rasterizer->Stereo())
- flag = gp_Rasterizer->GetEye();
-
- return PyLong_FromLong(flag);
-}
-
-static PyObject *gPySetBackgroundColor(PyObject *, PyObject *value)
-{
- MT_Vector4 vec;
- if (!PyVecTo(value, vec))
- return NULL;
-
- KX_WorldInfo *wi = gp_KetsjiScene->GetWorldInfo();
- if (!wi->hasWorld()) {
- PyErr_SetString(PyExc_RuntimeError, "bge.render.SetBackgroundColor(color), World not available");
- return NULL;
- }
-
- ShowDeprecationWarning("setBackgroundColor()", "KX_WorldInfo.background_color");
- wi->setBackColor((float)vec[0], (float)vec[1], (float)vec[2]);
-
- Py_RETURN_NONE;
-}
-
-static PyObject *gPyMakeScreenshot(PyObject *, PyObject *args)
-{
- char* filename;
- if (!PyArg_ParseTuple(args,"s:makeScreenshot",&filename))
- return NULL;
-
- if (gp_Canvas)
- {
- gp_Canvas->MakeScreenShot(filename);
- }
-
- Py_RETURN_NONE;
-}
-
-static PyObject *gPyEnableMotionBlur(PyObject *, PyObject *args)
-{
- float motionblurvalue;
- if (!PyArg_ParseTuple(args,"f:enableMotionBlur",&motionblurvalue))
- return NULL;
-
- if (!gp_Rasterizer) {
- PyErr_SetString(PyExc_RuntimeError, "Rasterizer.enableMotionBlur(float), Rasterizer not available");
- return NULL;
- }
-
- gp_Rasterizer->EnableMotionBlur(motionblurvalue);
-
- Py_RETURN_NONE;
-}
-
-static PyObject *gPyDisableMotionBlur(PyObject *)
-{
- if (!gp_Rasterizer) {
- PyErr_SetString(PyExc_RuntimeError, "Rasterizer.disableMotionBlur(), Rasterizer not available");
- return NULL;
- }
-
- gp_Rasterizer->DisableMotionBlur();
-
- Py_RETURN_NONE;
-}
-
-static int getGLSLSettingFlag(const char *setting)
-{
- if (strcmp(setting, "lights") == 0)
- return GAME_GLSL_NO_LIGHTS;
- else if (strcmp(setting, "shaders") == 0)
- return GAME_GLSL_NO_SHADERS;
- else if (strcmp(setting, "shadows") == 0)
- return GAME_GLSL_NO_SHADOWS;
- else if (strcmp(setting, "ramps") == 0)
- return GAME_GLSL_NO_RAMPS;
- else if (strcmp(setting, "nodes") == 0)
- return GAME_GLSL_NO_NODES;
- else if (strcmp(setting, "extra_textures") == 0)
- return GAME_GLSL_NO_EXTRA_TEX;
- else
- return -1;
-}
-
-static PyObject *gPySetGLSLMaterialSetting(PyObject *,
- PyObject *args,
- PyObject *)
-{
- GlobalSettings *gs= gp_KetsjiEngine->GetGlobalSettings();
- char *setting;
- int enable, flag, sceneflag;
-
- if (!PyArg_ParseTuple(args,"si:setGLSLMaterialSetting",&setting,&enable))
- return NULL;
-
- flag = getGLSLSettingFlag(setting);
-
- if (flag == -1) {
- PyErr_SetString(PyExc_ValueError, "Rasterizer.setGLSLMaterialSetting(string): glsl setting is not known");
- return NULL;
- }
-
- sceneflag= gs->glslflag;
-
- if (enable)
- gs->glslflag &= ~flag;
- else
- gs->glslflag |= flag;
-
- /* display lists and GLSL materials need to be remade */
- if (sceneflag != gs->glslflag) {
- GPU_materials_free();
- if (gp_KetsjiEngine) {
- KX_SceneList *scenes = gp_KetsjiEngine->CurrentScenes();
- KX_SceneList::iterator it;
-
- for (it=scenes->begin(); it!=scenes->end(); it++) {
- // temporarily store the glsl settings in the scene for the GLSL materials
- (*it)->GetBlenderScene()->gm.flag = gs->glslflag;
- if ((*it)->GetBucketManager()) {
- (*it)->GetBucketManager()->ReleaseDisplayLists();
- (*it)->GetBucketManager()->ReleaseMaterials();
- }
- }
- }
- }
-
- Py_RETURN_NONE;
-}
-
-static PyObject *gPyGetGLSLMaterialSetting(PyObject *,
- PyObject *args,
- PyObject *)
-{
- GlobalSettings *gs= gp_KetsjiEngine->GetGlobalSettings();
- char *setting;
- int enabled = 0, flag;
-
- if (!PyArg_ParseTuple(args,"s:getGLSLMaterialSetting",&setting))
- return NULL;
-
- flag = getGLSLSettingFlag(setting);
-
- if (flag == -1) {
- PyErr_SetString(PyExc_ValueError, "Rasterizer.getGLSLMaterialSetting(string): glsl setting is not known");
- return NULL;
- }
-
- enabled = ((gs->glslflag & flag) != 0);
- return PyLong_FromLong(enabled);
-}
-
-#define KX_BLENDER_MULTITEX_MATERIAL 1
-#define KX_BLENDER_GLSL_MATERIAL 2
-
-static PyObject *gPySetMaterialType(PyObject *,
- PyObject *args,
- PyObject *)
-{
- GlobalSettings *gs= gp_KetsjiEngine->GetGlobalSettings();
- int type;
-
- if (!PyArg_ParseTuple(args,"i:setMaterialType",&type))
- return NULL;
-
- if (type == KX_BLENDER_GLSL_MATERIAL)
- gs->matmode= GAME_MAT_GLSL;
- else if (type == KX_BLENDER_MULTITEX_MATERIAL)
- gs->matmode= GAME_MAT_MULTITEX;
- else {
- PyErr_SetString(PyExc_ValueError, "Rasterizer.setMaterialType(int): material type is not known");
- return NULL;
- }
-
- Py_RETURN_NONE;
-}
-
-static PyObject *gPyGetMaterialType(PyObject *)
-{
- GlobalSettings *gs= gp_KetsjiEngine->GetGlobalSettings();
- int flag;
-
- if (gs->matmode == GAME_MAT_GLSL)
- flag = KX_BLENDER_GLSL_MATERIAL;
- else
- flag = KX_BLENDER_MULTITEX_MATERIAL;
-
- return PyLong_FromLong(flag);
-}
-
-static PyObject *gPySetAnisotropicFiltering(PyObject *, PyObject *args)
-{
- short level;
-
- if (!PyArg_ParseTuple(args, "h:setAnisotropicFiltering", &level))
- return NULL;
-
- if (level != 1 && level != 2 && level != 4 && level != 8 && level != 16) {
- PyErr_SetString(PyExc_ValueError, "Rasterizer.setAnisotropicFiltering(level): Expected value of 1, 2, 4, 8, or 16 for value");
- return NULL;
- }
-
- gp_Rasterizer->SetAnisotropicFiltering(level);
-
- Py_RETURN_NONE;
-}
-
-static PyObject *gPyGetAnisotropicFiltering(PyObject *, PyObject *args)
-{
- return PyLong_FromLong(gp_Rasterizer->GetAnisotropicFiltering());
-}
-
-static PyObject *gPyDrawLine(PyObject *, PyObject *args)
-{
- PyObject *ob_from;
- PyObject *ob_to;
- PyObject *ob_color;
-
- if (!gp_Rasterizer) {
- PyErr_SetString(PyExc_RuntimeError, "Rasterizer.drawLine(obFrom, obTo, color): Rasterizer not available");
- return NULL;
- }
-
- if (!PyArg_ParseTuple(args,"OOO:drawLine",&ob_from,&ob_to,&ob_color))
- return NULL;
-
- MT_Vector3 from;
- MT_Vector3 to;
- MT_Vector3 color;
- if (!PyVecTo(ob_from, from))
- return NULL;
- if (!PyVecTo(ob_to, to))
- return NULL;
- if (!PyVecTo(ob_color, color))
- return NULL;
-
- gp_Rasterizer->DrawDebugLine(gp_KetsjiScene, from, to, color);
-
- Py_RETURN_NONE;
-}
-
-static PyObject *gPySetWindowSize(PyObject *, PyObject *args)
-{
- int width, height;
- if (!PyArg_ParseTuple(args, "ii:resize", &width, &height))
- return NULL;
-
- gp_Canvas->ResizeWindow(width, height);
- Py_RETURN_NONE;
-}
-
-static PyObject *gPySetFullScreen(PyObject *, PyObject *value)
-{
- gp_Canvas->SetFullScreen(PyObject_IsTrue(value));
- Py_RETURN_NONE;
-}
-
-static PyObject *gPyGetFullScreen(PyObject *)
-{
- return PyBool_FromLong(gp_Canvas->GetFullScreen());
-}
-
-static PyObject *gPySetMipmapping(PyObject *, PyObject *args)
-{
- int val = 0;
-
- if (!PyArg_ParseTuple(args, "i:setMipmapping", &val))
- return NULL;
-
- if (val < 0 || val > RAS_IRasterizer::RAS_MIPMAP_MAX) {
- PyErr_SetString(PyExc_ValueError, "Rasterizer.setMipmapping(val): invalid mipmaping option");
- return NULL;
- }
-
- if (!gp_Rasterizer) {
- PyErr_SetString(PyExc_RuntimeError, "Rasterizer.setMipmapping(val): Rasterizer not available");
- return NULL;
- }
-
- gp_Rasterizer->SetMipmapping((RAS_IRasterizer::MipmapOption)val);
- Py_RETURN_NONE;
-}
-
-static PyObject *gPyGetMipmapping(PyObject *)
-{
- if (!gp_Rasterizer) {
- PyErr_SetString(PyExc_RuntimeError, "Rasterizer.getMipmapping(): Rasterizer not available");
- return NULL;
- }
- return PyLong_FromLong(gp_Rasterizer->GetMipmapping());
-}
-
-static PyObject *gPySetVsync(PyObject *, PyObject *args)
-{
- int interval;
-
- if (!PyArg_ParseTuple(args, "i:setVsync", &interval))
- return NULL;
-
- if (interval < 0 || interval > VSYNC_ADAPTIVE) {
- PyErr_SetString(PyExc_ValueError, "Rasterizer.setVsync(value): value must be VSYNC_OFF, VSYNC_ON, or VSYNC_ADAPTIVE");
- return NULL;
- }
-
- if (interval == VSYNC_ADAPTIVE)
- interval = -1;
- gp_Canvas->SetSwapInterval((interval == VSYNC_ON) ? 1 : 0);
- Py_RETURN_NONE;
-}
-
-static PyObject *gPyGetVsync(PyObject *)
-{
- int interval = 0;
- gp_Canvas->GetSwapInterval(interval);
- return PyLong_FromLong(interval);
-}
-
-static PyObject *gPyShowFramerate(PyObject *, PyObject *args)
-{
- int visible;
- if (!PyArg_ParseTuple(args,"i:showFramerate",&visible))
- return NULL;
-
- if (visible && gp_KetsjiEngine)
- gp_KetsjiEngine->SetShowFramerate(true);
- else
- gp_KetsjiEngine->SetShowFramerate(false);
-
- Py_RETURN_NONE;
-}
-
-static PyObject *gPyShowProfile(PyObject *, PyObject *args)
-{
- int visible;
- if (!PyArg_ParseTuple(args,"i:showProfile",&visible))
- return NULL;
-
- if (visible && gp_KetsjiEngine)
- gp_KetsjiEngine->SetShowProfile(true);
- else
- gp_KetsjiEngine->SetShowProfile(false);
-
- Py_RETURN_NONE;
-}
-
-static PyObject *gPyShowProperties(PyObject *, PyObject *args)
-{
- int visible;
- if (!PyArg_ParseTuple(args,"i:showProperties",&visible))
- return NULL;
-
- if (visible && gp_KetsjiEngine)
- gp_KetsjiEngine->SetShowProperties(true);
- else
- gp_KetsjiEngine->SetShowProperties(false);
-
- Py_RETURN_NONE;
-}
-
-static PyObject *gPyAutoDebugList(PyObject *, PyObject *args)
-{
- int add;
- if (!PyArg_ParseTuple(args,"i:autoAddProperties",&add))
- return NULL;
-
- if (add && gp_KetsjiEngine)
- gp_KetsjiEngine->SetAutoAddDebugProperties(true);
- else
- gp_KetsjiEngine->SetAutoAddDebugProperties(false);
-
- Py_RETURN_NONE;
-}
-
-static PyObject *gPyClearDebugList(PyObject *)
-{
- if (gp_KetsjiScene)
- gp_KetsjiScene->RemoveAllDebugProperties();
-
- Py_RETURN_NONE;
-}
-
-static PyObject *gPyGetDisplayDimensions(PyObject *)
-{
- PyObject *result;
- int width, height;
-
- gp_Canvas->GetDisplayDimensions(width, height);
-
- result = PyTuple_New(2);
- PyTuple_SET_ITEMS(result,
- PyLong_FromLong(width),
- PyLong_FromLong(height));
-
- return result;
-}
-
-
-/* python wrapper around RAS_IOffScreen
- * Should eventually gets its own file
- */
-
-static void PyRASOffScreen__tp_dealloc(PyRASOffScreen *self)
-{
- if (self->ofs)
- delete self->ofs;
- Py_TYPE(self)->tp_free((PyObject *)self);
-}
-
-PyDoc_STRVAR(py_RASOffScreen_doc,
-"RASOffscreen(width, height) -> new GPU Offscreen object"
-"initialized to hold a framebuffer object of ``width`` x ``height``.\n"
-""
-);
-
-PyDoc_STRVAR(RASOffScreen_width_doc, "Offscreen buffer width.\n\n:type: integer");
-static PyObject *RASOffScreen_width_get(PyRASOffScreen *self, void *UNUSED(type))
-{
- return PyLong_FromLong(self->ofs->GetWidth());
-}
-
-PyDoc_STRVAR(RASOffScreen_height_doc, "Offscreen buffer height.\n\n:type: GLsizei");
-static PyObject *RASOffScreen_height_get(PyRASOffScreen *self, void *UNUSED(type))
-{
- return PyLong_FromLong(self->ofs->GetHeight());
-}
-
-PyDoc_STRVAR(RASOffScreen_color_doc, "Offscreen buffer texture object (if target is RAS_OFS_RENDER_TEXTURE).\n\n:type: GLuint");
-static PyObject *RASOffScreen_color_get(PyRASOffScreen *self, void *UNUSED(type))
-{
- return PyLong_FromLong(self->ofs->GetColor());
-}
-
-static PyGetSetDef RASOffScreen_getseters[] = {
- {(char *)"width", (getter)RASOffScreen_width_get, (setter)NULL, RASOffScreen_width_doc, NULL},
- {(char *)"height", (getter)RASOffScreen_height_get, (setter)NULL, RASOffScreen_height_doc, NULL},
- {(char *)"color", (getter)RASOffScreen_color_get, (setter)NULL, RASOffScreen_color_doc, NULL},
- {NULL, NULL, NULL, NULL, NULL} /* Sentinel */
-};
-
-static int PyRASOffScreen__tp_init(PyRASOffScreen *self, PyObject *args, PyObject *kwargs)
-{
- int width, height, samples, target;
- const char *keywords[] = {"width", "height", "samples", "target", NULL};
-
- samples = 0;
- target = RAS_IOffScreen::RAS_OFS_RENDER_BUFFER;
- if (!PyArg_ParseTupleAndKeywords(args, kwargs, "ii|ii:RASOffscreen", (char **)keywords, &width, &height, &samples, &target)) {
- return -1;
- }
-
- if (width <= 0) {
- PyErr_SetString(PyExc_ValueError, "negative 'width' given");
- return -1;
- }
-
- if (height <= 0) {
- PyErr_SetString(PyExc_ValueError, "negative 'height' given");
- return -1;
- }
-
- if (samples < 0) {
- PyErr_SetString(PyExc_ValueError, "negative 'samples' given");
- return -1;
- }
-
- if (target != RAS_IOffScreen::RAS_OFS_RENDER_BUFFER && target != RAS_IOffScreen::RAS_OFS_RENDER_TEXTURE)
- {
- PyErr_SetString(PyExc_ValueError, "invalid 'target' given, can only be RAS_OFS_RENDER_BUFFER or RAS_OFS_RENDER_TEXTURE");
- return -1;
- }
- if (!gp_Rasterizer)
- {
- PyErr_SetString(PyExc_SystemError, "no rasterizer");
- return -1;
- }
- self->ofs = gp_Rasterizer->CreateOffScreen(width, height, samples, target);
- if (!self->ofs) {
- PyErr_SetString(PyExc_SystemError, "creation failed");
- return -1;
- }
- return 0;
-}
-
-PyTypeObject PyRASOffScreen_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "RASOffScreen", /* tp_name */
- sizeof(PyRASOffScreen), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)PyRASOffScreen__tp_dealloc, /* tp_dealloc */
- NULL, /* tp_print */
- NULL, /* tp_getattr */
- NULL, /* tp_setattr */
- NULL, /* tp_compare */
- NULL, /* tp_repr */
- NULL, /* tp_as_number */
- NULL, /* tp_as_sequence */
- NULL, /* tp_as_mapping */
- NULL, /* tp_hash */
- NULL, /* tp_call */
- NULL, /* tp_str */
- NULL, /* tp_getattro */
- NULL, /* tp_setattro */
- NULL, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT, /* tp_flags */
- py_RASOffScreen_doc, /* Documentation string */
- NULL, /* tp_traverse */
- NULL, /* tp_clear */
- NULL, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- NULL, /* tp_iter */
- NULL, /* tp_iternext */
- NULL, /* tp_methods */
- NULL, /* tp_members */
- RASOffScreen_getseters, /* tp_getset */
- NULL, /* tp_base */
- NULL, /* tp_dict */
- NULL, /* tp_descr_get */
- NULL, /* tp_descr_set */
- 0, /* tp_dictoffset */
- (initproc)PyRASOffScreen__tp_init, /* tp_init */
- (allocfunc)PyType_GenericAlloc, /* tp_alloc */
- (newfunc)PyType_GenericNew, /* tp_new */
- (freefunc)0, /* tp_free */
- NULL, /* tp_is_gc */
- NULL, /* tp_bases */
- NULL, /* tp_mro */
- NULL, /* tp_cache */
- NULL, /* tp_subclasses */
- NULL, /* tp_weaklist */
- (destructor) NULL /* tp_del */
-};
-
-
-static PyObject *gPyOffScreenCreate(PyObject *UNUSED(self), PyObject *args)
-{
- int width;
- int height;
- int samples;
- int target;
-
- samples = 0;
- if (!PyArg_ParseTuple(args, "ii|ii:offScreenCreate", &width, &height, &samples, &target))
- return NULL;
-
- return PyObject_CallObject((PyObject *) &PyRASOffScreen_Type, args);
-}
-
-PyDoc_STRVAR(Rasterizer_module_documentation,
-"This is the Python API for the game engine of Rasterizer"
-);
-
-static struct PyMethodDef rasterizer_methods[] = {
- {"getWindowWidth",(PyCFunction) gPyGetWindowWidth,
- METH_VARARGS, "getWindowWidth doc"},
- {"getWindowHeight",(PyCFunction) gPyGetWindowHeight,
- METH_VARARGS, "getWindowHeight doc"},
- {"makeScreenshot",(PyCFunction)gPyMakeScreenshot,
- METH_VARARGS, "make Screenshot doc"},
- {"enableVisibility",(PyCFunction) gPyEnableVisibility,
- METH_VARARGS, "enableVisibility doc"},
- {"showMouse",(PyCFunction) gPyShowMouse,
- METH_VARARGS, "showMouse(bool visible)"},
- {"setMousePosition",(PyCFunction) gPySetMousePosition,
- METH_VARARGS, "setMousePosition(int x,int y)"},
- {"setBackgroundColor",(PyCFunction)gPySetBackgroundColor,METH_O,"set Background Color (rgb)"},
- {"enableMotionBlur",(PyCFunction)gPyEnableMotionBlur,METH_VARARGS,"enable motion blur"},
- {"disableMotionBlur",(PyCFunction)gPyDisableMotionBlur,METH_NOARGS,"disable motion blur"},
-
- {"setEyeSeparation", (PyCFunction) gPySetEyeSeparation, METH_VARARGS, "set the eye separation for stereo mode"},
- {"getEyeSeparation", (PyCFunction) gPyGetEyeSeparation, METH_NOARGS, "get the eye separation for stereo mode"},
- {"setFocalLength", (PyCFunction) gPySetFocalLength, METH_VARARGS, "set the focal length for stereo mode"},
- {"getFocalLength", (PyCFunction) gPyGetFocalLength, METH_VARARGS, "get the focal length for stereo mode"},
- {"getStereoEye", (PyCFunction) gPyGetStereoEye, METH_VARARGS, "get the current stereoscopy eye being rendered"},
- {"setMaterialMode",(PyCFunction) gPySetMaterialType,
- METH_VARARGS, "set the material mode to use for OpenGL rendering"},
- {"getMaterialMode",(PyCFunction) gPyGetMaterialType,
- METH_NOARGS, "get the material mode being used for OpenGL rendering"},
- {"setGLSLMaterialSetting",(PyCFunction) gPySetGLSLMaterialSetting,
- METH_VARARGS, "set the state of a GLSL material setting"},
- {"getGLSLMaterialSetting",(PyCFunction) gPyGetGLSLMaterialSetting,
- METH_VARARGS, "get the state of a GLSL material setting"},
- {"setAnisotropicFiltering", (PyCFunction) gPySetAnisotropicFiltering,
- METH_VARARGS, "set the anisotropic filtering level (must be one of 1, 2, 4, 8, 16)"},
- {"getAnisotropicFiltering", (PyCFunction) gPyGetAnisotropicFiltering,
- METH_VARARGS, "get the anisotropic filtering level"},
- {"drawLine", (PyCFunction) gPyDrawLine,
- METH_VARARGS, "draw a line on the screen"},
- {"setWindowSize", (PyCFunction) gPySetWindowSize, METH_VARARGS, ""},
- {"setFullScreen", (PyCFunction) gPySetFullScreen, METH_O, ""},
- {"getFullScreen", (PyCFunction) gPyGetFullScreen, METH_NOARGS, ""},
- {"getDisplayDimensions", (PyCFunction) gPyGetDisplayDimensions, METH_NOARGS,
- "Get the actual dimensions, in pixels, of the physical display (e.g., the monitor)."},
- {"setMipmapping", (PyCFunction) gPySetMipmapping, METH_VARARGS, ""},
- {"getMipmapping", (PyCFunction) gPyGetMipmapping, METH_NOARGS, ""},
- {"setVsync", (PyCFunction) gPySetVsync, METH_VARARGS, ""},
- {"getVsync", (PyCFunction) gPyGetVsync, METH_NOARGS, ""},
- {"showFramerate",(PyCFunction) gPyShowFramerate, METH_VARARGS, "show or hide the framerate"},
- {"showProfile",(PyCFunction) gPyShowProfile, METH_VARARGS, "show or hide the profile"},
- {"showProperties",(PyCFunction) gPyShowProperties, METH_VARARGS, "show or hide the debug properties"},
- {"autoDebugList",(PyCFunction) gPyAutoDebugList, METH_VARARGS, "enable or disable auto adding debug properties to the debug list"},
- {"clearDebugList",(PyCFunction) gPyClearDebugList, METH_NOARGS, "clears the debug property list"},
- {"offScreenCreate", (PyCFunction) gPyOffScreenCreate, METH_VARARGS, "create an offscreen buffer object, arguments are width and height in pixels"},
- { NULL, (PyCFunction) NULL, 0, NULL }
-};
-
-
-
-PyDoc_STRVAR(GameLogic_module_documentation,
-"This is the Python API for the game engine of bge.logic"
-);
-
-static struct PyModuleDef GameLogic_module_def = {
- {}, /* m_base */
- "GameLogic", /* m_name */
- GameLogic_module_documentation, /* m_doc */
- 0, /* m_size */
- game_methods, /* m_methods */
- 0, /* m_reload */
- 0, /* m_traverse */
- 0, /* m_clear */
- 0, /* m_free */
-};
-
-PyMODINIT_FUNC initGameLogicPythonBinding()
-{
- PyObject *m;
- PyObject *d;
- PyObject *item; /* temp PyObject *storage */
-
- gUseVisibilityTemp=false;
-
- PyObjectPlus::ClearDeprecationWarning(); /* Not that nice to call here but makes sure warnings are reset between loading scenes */
-
- m = PyModule_Create(&GameLogic_module_def);
- PyDict_SetItemString(PySys_GetObject("modules"), GameLogic_module_def.m_name, m);
-
-
- // Add some symbolic constants to the module
- d = PyModule_GetDict(m);
-
- // can be overwritten later for gameEngine instances that can load new blend files and re-initialize this module
- // for now its safe to make sure it exists for other areas such as the web plugin
-
- PyDict_SetItemString(d, "globalDict", item=PyDict_New()); Py_DECREF(item);
-
- // Add keyboard and mouse attributes to this module
- MT_assert(!gp_PythonKeyboard);
- gp_PythonKeyboard = new SCA_PythonKeyboard(gp_KetsjiEngine->GetKeyboardDevice());
- PyDict_SetItemString(d, "keyboard", gp_PythonKeyboard->NewProxy(true));
-
- MT_assert(!gp_PythonMouse);
- gp_PythonMouse = new SCA_PythonMouse(gp_KetsjiEngine->GetMouseDevice(), gp_Canvas);
- PyDict_SetItemString(d, "mouse", gp_PythonMouse->NewProxy(true));
-
- PyObject* joylist = PyList_New(JOYINDEX_MAX);
- for (int i=0; i<JOYINDEX_MAX; ++i) {
- SCA_Joystick *joy = SCA_Joystick::GetInstance(i);
- PyObject *item;
-
- if (joy && joy->Connected()) {
- gp_PythonJoysticks[i] = new SCA_PythonJoystick(joy);
- item = gp_PythonJoysticks[i]->NewProxy(true);
- }
- else {
- if (joy) {
- joy->ReleaseInstance();
- }
- item = Py_None;
- }
-
- Py_INCREF(item);
- PyList_SET_ITEM(joylist, i, item);
- }
- PyDict_SetItemString(d, "joysticks", joylist);
-
- ErrorObject = PyUnicode_FromString("GameLogic.error");
- PyDict_SetItemString(d, "error", ErrorObject);
- Py_DECREF(ErrorObject);
-
- // XXXX Add constants here
- /* To use logic bricks, we need some sort of constants. Here, we associate */
- /* constants and sumbolic names. Add them to dictionary d. */
-
- /* 1. true and false: needed for everyone */
- KX_MACRO_addTypesToDict(d, KX_TRUE, SCA_ILogicBrick::KX_TRUE);
- KX_MACRO_addTypesToDict(d, KX_FALSE, SCA_ILogicBrick::KX_FALSE);
-
- /* 2. Property sensor */
- KX_MACRO_addTypesToDict(d, KX_PROPSENSOR_EQUAL, SCA_PropertySensor::KX_PROPSENSOR_EQUAL);
- KX_MACRO_addTypesToDict(d, KX_PROPSENSOR_NOTEQUAL, SCA_PropertySensor::KX_PROPSENSOR_NOTEQUAL);
- KX_MACRO_addTypesToDict(d, KX_PROPSENSOR_INTERVAL, SCA_PropertySensor::KX_PROPSENSOR_INTERVAL);
- KX_MACRO_addTypesToDict(d, KX_PROPSENSOR_CHANGED, SCA_PropertySensor::KX_PROPSENSOR_CHANGED);
- KX_MACRO_addTypesToDict(d, KX_PROPSENSOR_EXPRESSION, SCA_PropertySensor::KX_PROPSENSOR_EXPRESSION);
- KX_MACRO_addTypesToDict(d, KX_PROPSENSOR_LESSTHAN, SCA_PropertySensor::KX_PROPSENSOR_LESSTHAN);
- KX_MACRO_addTypesToDict(d, KX_PROPSENSOR_GREATERTHAN, SCA_PropertySensor::KX_PROPSENSOR_GREATERTHAN);
-
- /* 3. Constraint actuator */
- KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_LOCX, KX_ConstraintActuator::KX_ACT_CONSTRAINT_LOCX);
- KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_LOCY, KX_ConstraintActuator::KX_ACT_CONSTRAINT_LOCY);
- KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_LOCZ, KX_ConstraintActuator::KX_ACT_CONSTRAINT_LOCZ);
- KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_ROTX, KX_ConstraintActuator::KX_ACT_CONSTRAINT_ROTX);
- KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_ROTY, KX_ConstraintActuator::KX_ACT_CONSTRAINT_ROTY);
- KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_ROTZ, KX_ConstraintActuator::KX_ACT_CONSTRAINT_ROTZ);
- KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_DIRPX, KX_ConstraintActuator::KX_ACT_CONSTRAINT_DIRPX);
- KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_DIRPY, KX_ConstraintActuator::KX_ACT_CONSTRAINT_DIRPY);
- KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_DIRPZ, KX_ConstraintActuator::KX_ACT_CONSTRAINT_DIRPZ);
- KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_DIRNX, KX_ConstraintActuator::KX_ACT_CONSTRAINT_DIRNX);
- KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_DIRNY, KX_ConstraintActuator::KX_ACT_CONSTRAINT_DIRNY);
- KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_DIRNZ, KX_ConstraintActuator::KX_ACT_CONSTRAINT_DIRNZ);
- KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_ORIX, KX_ConstraintActuator::KX_ACT_CONSTRAINT_ORIX);
- KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_ORIY, KX_ConstraintActuator::KX_ACT_CONSTRAINT_ORIY);
- KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_ORIZ, KX_ConstraintActuator::KX_ACT_CONSTRAINT_ORIZ);
- KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_FHPX, KX_ConstraintActuator::KX_ACT_CONSTRAINT_FHPX);
- KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_FHPY, KX_ConstraintActuator::KX_ACT_CONSTRAINT_FHPY);
- KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_FHPZ, KX_ConstraintActuator::KX_ACT_CONSTRAINT_FHPZ);
- KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_FHNX, KX_ConstraintActuator::KX_ACT_CONSTRAINT_FHNX);
- KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_FHNY, KX_ConstraintActuator::KX_ACT_CONSTRAINT_FHNY);
- KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_FHNZ, KX_ConstraintActuator::KX_ACT_CONSTRAINT_FHNZ);
- KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_NORMAL, KX_ConstraintActuator::KX_ACT_CONSTRAINT_NORMAL);
- KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_MATERIAL, KX_ConstraintActuator::KX_ACT_CONSTRAINT_MATERIAL);
- KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_PERMANENT, KX_ConstraintActuator::KX_ACT_CONSTRAINT_PERMANENT);
- KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_DISTANCE, KX_ConstraintActuator::KX_ACT_CONSTRAINT_DISTANCE);
- KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_LOCAL, KX_ConstraintActuator::KX_ACT_CONSTRAINT_LOCAL);
- KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_DOROTFH, KX_ConstraintActuator::KX_ACT_CONSTRAINT_DOROTFH);
-
- /* 4. Random distribution types */
- KX_MACRO_addTypesToDict(d, KX_RANDOMACT_BOOL_CONST, SCA_RandomActuator::KX_RANDOMACT_BOOL_CONST);
- KX_MACRO_addTypesToDict(d, KX_RANDOMACT_BOOL_UNIFORM, SCA_RandomActuator::KX_RANDOMACT_BOOL_UNIFORM);
- KX_MACRO_addTypesToDict(d, KX_RANDOMACT_BOOL_BERNOUILLI, SCA_RandomActuator::KX_RANDOMACT_BOOL_BERNOUILLI);
- KX_MACRO_addTypesToDict(d, KX_RANDOMACT_INT_CONST, SCA_RandomActuator::KX_RANDOMACT_INT_CONST);
- KX_MACRO_addTypesToDict(d, KX_RANDOMACT_INT_UNIFORM, SCA_RandomActuator::KX_RANDOMACT_INT_UNIFORM);
- KX_MACRO_addTypesToDict(d, KX_RANDOMACT_INT_POISSON, SCA_RandomActuator::KX_RANDOMACT_INT_POISSON);
- KX_MACRO_addTypesToDict(d, KX_RANDOMACT_FLOAT_CONST, SCA_RandomActuator::KX_RANDOMACT_FLOAT_CONST);
- KX_MACRO_addTypesToDict(d, KX_RANDOMACT_FLOAT_UNIFORM, SCA_RandomActuator::KX_RANDOMACT_FLOAT_UNIFORM);
- KX_MACRO_addTypesToDict(d, KX_RANDOMACT_FLOAT_NORMAL, SCA_RandomActuator::KX_RANDOMACT_FLOAT_NORMAL);
- KX_MACRO_addTypesToDict(d, KX_RANDOMACT_FLOAT_NEGATIVE_EXPONENTIAL, SCA_RandomActuator::KX_RANDOMACT_FLOAT_NEGATIVE_EXPONENTIAL);
-
- /* 5. Sound actuator */
- KX_MACRO_addTypesToDict(d, KX_SOUNDACT_PLAYSTOP, KX_SoundActuator::KX_SOUNDACT_PLAYSTOP);
- KX_MACRO_addTypesToDict(d, KX_SOUNDACT_PLAYEND, KX_SoundActuator::KX_SOUNDACT_PLAYEND);
- KX_MACRO_addTypesToDict(d, KX_SOUNDACT_LOOPSTOP, KX_SoundActuator::KX_SOUNDACT_LOOPSTOP);
- KX_MACRO_addTypesToDict(d, KX_SOUNDACT_LOOPEND, KX_SoundActuator::KX_SOUNDACT_LOOPEND);
- KX_MACRO_addTypesToDict(d, KX_SOUNDACT_LOOPBIDIRECTIONAL, KX_SoundActuator::KX_SOUNDACT_LOOPBIDIRECTIONAL);
- KX_MACRO_addTypesToDict(d, KX_SOUNDACT_LOOPBIDIRECTIONAL_STOP, KX_SoundActuator::KX_SOUNDACT_LOOPBIDIRECTIONAL_STOP);
-
- /* 6. Action actuator */
- KX_MACRO_addTypesToDict(d, KX_ACTIONACT_PLAY, ACT_ACTION_PLAY);
- KX_MACRO_addTypesToDict(d, KX_ACTIONACT_PINGPONG, ACT_ACTION_PINGPONG);
- KX_MACRO_addTypesToDict(d, KX_ACTIONACT_FLIPPER, ACT_ACTION_FLIPPER);
- KX_MACRO_addTypesToDict(d, KX_ACTIONACT_LOOPSTOP, ACT_ACTION_LOOP_STOP);
- KX_MACRO_addTypesToDict(d, KX_ACTIONACT_LOOPEND, ACT_ACTION_LOOP_END);
- KX_MACRO_addTypesToDict(d, KX_ACTIONACT_PROPERTY, ACT_ACTION_FROM_PROP);
-
- /* 7. GL_BlendFunc */
- KX_MACRO_addTypesToDict(d, BL_ZERO, GL_ZERO);
- KX_MACRO_addTypesToDict(d, BL_ONE, GL_ONE);
- KX_MACRO_addTypesToDict(d, BL_SRC_COLOR, GL_SRC_COLOR);
- KX_MACRO_addTypesToDict(d, BL_ONE_MINUS_SRC_COLOR, GL_ONE_MINUS_SRC_COLOR);
- KX_MACRO_addTypesToDict(d, BL_DST_COLOR, GL_DST_COLOR);
- KX_MACRO_addTypesToDict(d, BL_ONE_MINUS_DST_COLOR, GL_ONE_MINUS_DST_COLOR);
- KX_MACRO_addTypesToDict(d, BL_SRC_ALPHA, GL_SRC_ALPHA);
- KX_MACRO_addTypesToDict(d, BL_ONE_MINUS_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
- KX_MACRO_addTypesToDict(d, BL_DST_ALPHA, GL_DST_ALPHA);
- KX_MACRO_addTypesToDict(d, BL_ONE_MINUS_DST_ALPHA, GL_ONE_MINUS_DST_ALPHA);
- KX_MACRO_addTypesToDict(d, BL_SRC_ALPHA_SATURATE, GL_SRC_ALPHA_SATURATE);
-
-
- /* 8. UniformTypes */
- KX_MACRO_addTypesToDict(d, SHD_TANGENT, BL_Shader::SHD_TANGENT);
- KX_MACRO_addTypesToDict(d, MODELVIEWMATRIX, BL_Shader::MODELVIEWMATRIX);
- KX_MACRO_addTypesToDict(d, MODELVIEWMATRIX_TRANSPOSE, BL_Shader::MODELVIEWMATRIX_TRANSPOSE);
- KX_MACRO_addTypesToDict(d, MODELVIEWMATRIX_INVERSE, BL_Shader::MODELVIEWMATRIX_INVERSE);
- KX_MACRO_addTypesToDict(d, MODELVIEWMATRIX_INVERSETRANSPOSE, BL_Shader::MODELVIEWMATRIX_INVERSETRANSPOSE);
- KX_MACRO_addTypesToDict(d, MODELMATRIX, BL_Shader::MODELMATRIX);
- KX_MACRO_addTypesToDict(d, MODELMATRIX_TRANSPOSE, BL_Shader::MODELMATRIX_TRANSPOSE);
- KX_MACRO_addTypesToDict(d, MODELMATRIX_INVERSE, BL_Shader::MODELMATRIX_INVERSE);
- KX_MACRO_addTypesToDict(d, MODELMATRIX_INVERSETRANSPOSE, BL_Shader::MODELMATRIX_INVERSETRANSPOSE);
- KX_MACRO_addTypesToDict(d, VIEWMATRIX, BL_Shader::VIEWMATRIX);
- KX_MACRO_addTypesToDict(d, VIEWMATRIX_TRANSPOSE, BL_Shader::VIEWMATRIX_TRANSPOSE);
- KX_MACRO_addTypesToDict(d, VIEWMATRIX_INVERSE, BL_Shader::VIEWMATRIX_INVERSE);
- KX_MACRO_addTypesToDict(d, VIEWMATRIX_INVERSETRANSPOSE, BL_Shader::VIEWMATRIX_INVERSETRANSPOSE);
- KX_MACRO_addTypesToDict(d, CAM_POS, BL_Shader::CAM_POS);
- KX_MACRO_addTypesToDict(d, CONSTANT_TIMER, BL_Shader::CONSTANT_TIMER);
-
- /* 9. state actuator */
- KX_MACRO_addTypesToDict(d, KX_STATE1, (1<<0));
- KX_MACRO_addTypesToDict(d, KX_STATE2, (1<<1));
- KX_MACRO_addTypesToDict(d, KX_STATE3, (1<<2));
- KX_MACRO_addTypesToDict(d, KX_STATE4, (1<<3));
- KX_MACRO_addTypesToDict(d, KX_STATE5, (1<<4));
- KX_MACRO_addTypesToDict(d, KX_STATE6, (1<<5));
- KX_MACRO_addTypesToDict(d, KX_STATE7, (1<<6));
- KX_MACRO_addTypesToDict(d, KX_STATE8, (1<<7));
- KX_MACRO_addTypesToDict(d, KX_STATE9, (1<<8));
- KX_MACRO_addTypesToDict(d, KX_STATE10, (1<<9));
- KX_MACRO_addTypesToDict(d, KX_STATE11, (1<<10));
- KX_MACRO_addTypesToDict(d, KX_STATE12, (1<<11));
- KX_MACRO_addTypesToDict(d, KX_STATE13, (1<<12));
- KX_MACRO_addTypesToDict(d, KX_STATE14, (1<<13));
- KX_MACRO_addTypesToDict(d, KX_STATE15, (1<<14));
- KX_MACRO_addTypesToDict(d, KX_STATE16, (1<<15));
- KX_MACRO_addTypesToDict(d, KX_STATE17, (1<<16));
- KX_MACRO_addTypesToDict(d, KX_STATE18, (1<<17));
- KX_MACRO_addTypesToDict(d, KX_STATE19, (1<<18));
- KX_MACRO_addTypesToDict(d, KX_STATE20, (1<<19));
- KX_MACRO_addTypesToDict(d, KX_STATE21, (1<<20));
- KX_MACRO_addTypesToDict(d, KX_STATE22, (1<<21));
- KX_MACRO_addTypesToDict(d, KX_STATE23, (1<<22));
- KX_MACRO_addTypesToDict(d, KX_STATE24, (1<<23));
- KX_MACRO_addTypesToDict(d, KX_STATE25, (1<<24));
- KX_MACRO_addTypesToDict(d, KX_STATE26, (1<<25));
- KX_MACRO_addTypesToDict(d, KX_STATE27, (1<<26));
- KX_MACRO_addTypesToDict(d, KX_STATE28, (1<<27));
- KX_MACRO_addTypesToDict(d, KX_STATE29, (1<<28));
- KX_MACRO_addTypesToDict(d, KX_STATE30, (1<<29));
-
- /* All Sensors */
- KX_MACRO_addTypesToDict(d, KX_SENSOR_JUST_ACTIVATED, SCA_ISensor::KX_SENSOR_JUST_ACTIVATED);
- KX_MACRO_addTypesToDict(d, KX_SENSOR_ACTIVE, SCA_ISensor::KX_SENSOR_ACTIVE);
- KX_MACRO_addTypesToDict(d, KX_SENSOR_JUST_DEACTIVATED, SCA_ISensor::KX_SENSOR_JUST_DEACTIVATED);
- KX_MACRO_addTypesToDict(d, KX_SENSOR_INACTIVE, SCA_ISensor::KX_SENSOR_INACTIVE);
-
- /* Radar Sensor */
- KX_MACRO_addTypesToDict(d, KX_RADAR_AXIS_POS_X, KX_RadarSensor::KX_RADAR_AXIS_POS_X);
- KX_MACRO_addTypesToDict(d, KX_RADAR_AXIS_POS_Y, KX_RadarSensor::KX_RADAR_AXIS_POS_Y);
- KX_MACRO_addTypesToDict(d, KX_RADAR_AXIS_POS_Z, KX_RadarSensor::KX_RADAR_AXIS_POS_Z);
- KX_MACRO_addTypesToDict(d, KX_RADAR_AXIS_NEG_X, KX_RadarSensor::KX_RADAR_AXIS_NEG_X);
- KX_MACRO_addTypesToDict(d, KX_RADAR_AXIS_NEG_Y, KX_RadarSensor::KX_RADAR_AXIS_NEG_Y);
- KX_MACRO_addTypesToDict(d, KX_RADAR_AXIS_NEG_Z, KX_RadarSensor::KX_RADAR_AXIS_NEG_Z);
-
- /* Ray Sensor */
- KX_MACRO_addTypesToDict(d, KX_RAY_AXIS_POS_X, KX_RaySensor::KX_RAY_AXIS_POS_X);
- KX_MACRO_addTypesToDict(d, KX_RAY_AXIS_POS_Y, KX_RaySensor::KX_RAY_AXIS_POS_Y);
- KX_MACRO_addTypesToDict(d, KX_RAY_AXIS_POS_Z, KX_RaySensor::KX_RAY_AXIS_POS_Z);
- KX_MACRO_addTypesToDict(d, KX_RAY_AXIS_NEG_X, KX_RaySensor::KX_RAY_AXIS_NEG_X);
- KX_MACRO_addTypesToDict(d, KX_RAY_AXIS_NEG_Y, KX_RaySensor::KX_RAY_AXIS_NEG_Y);
- KX_MACRO_addTypesToDict(d, KX_RAY_AXIS_NEG_Z, KX_RaySensor::KX_RAY_AXIS_NEG_Z);
-
- /* TrackTo Actuator */
- KX_MACRO_addTypesToDict(d, KX_TRACK_UPAXIS_POS_X, KX_TrackToActuator::KX_TRACK_UPAXIS_POS_X);
- KX_MACRO_addTypesToDict(d, KX_TRACK_UPAXIS_POS_Y, KX_TrackToActuator::KX_TRACK_UPAXIS_POS_Y);
- KX_MACRO_addTypesToDict(d, KX_TRACK_UPAXIS_POS_Z, KX_TrackToActuator::KX_TRACK_UPAXIS_POS_Z);
- KX_MACRO_addTypesToDict(d, KX_TRACK_TRAXIS_POS_X, KX_TrackToActuator::KX_TRACK_TRAXIS_POS_X);
- KX_MACRO_addTypesToDict(d, KX_TRACK_TRAXIS_POS_Y, KX_TrackToActuator::KX_TRACK_TRAXIS_POS_Y);
- KX_MACRO_addTypesToDict(d, KX_TRACK_TRAXIS_POS_Z, KX_TrackToActuator::KX_TRACK_TRAXIS_POS_Z);
- KX_MACRO_addTypesToDict(d, KX_TRACK_TRAXIS_NEG_X, KX_TrackToActuator::KX_TRACK_TRAXIS_NEG_X);
- KX_MACRO_addTypesToDict(d, KX_TRACK_TRAXIS_NEG_Y, KX_TrackToActuator::KX_TRACK_TRAXIS_NEG_Y);
- KX_MACRO_addTypesToDict(d, KX_TRACK_TRAXIS_NEG_Z, KX_TrackToActuator::KX_TRACK_TRAXIS_NEG_Z);
-
- /* Dynamic actuator */
- KX_MACRO_addTypesToDict(d, KX_DYN_RESTORE_DYNAMICS, KX_SCA_DynamicActuator::KX_DYN_RESTORE_DYNAMICS);
- KX_MACRO_addTypesToDict(d, KX_DYN_DISABLE_DYNAMICS, KX_SCA_DynamicActuator::KX_DYN_DISABLE_DYNAMICS);
- KX_MACRO_addTypesToDict(d, KX_DYN_ENABLE_RIGID_BODY, KX_SCA_DynamicActuator::KX_DYN_ENABLE_RIGID_BODY);
- KX_MACRO_addTypesToDict(d, KX_DYN_DISABLE_RIGID_BODY, KX_SCA_DynamicActuator::KX_DYN_DISABLE_RIGID_BODY);
- KX_MACRO_addTypesToDict(d, KX_DYN_SET_MASS, KX_SCA_DynamicActuator::KX_DYN_SET_MASS);
-
- /* Input & Mouse Sensor */
- KX_MACRO_addTypesToDict(d, KX_INPUT_NONE, SCA_InputEvent::KX_NO_INPUTSTATUS);
- KX_MACRO_addTypesToDict(d, KX_INPUT_JUST_ACTIVATED, SCA_InputEvent::KX_JUSTACTIVATED);
- KX_MACRO_addTypesToDict(d, KX_INPUT_ACTIVE, SCA_InputEvent::KX_ACTIVE);
- KX_MACRO_addTypesToDict(d, KX_INPUT_JUST_RELEASED, SCA_InputEvent::KX_JUSTRELEASED);
-
- KX_MACRO_addTypesToDict(d, KX_MOUSE_BUT_LEFT, SCA_IInputDevice::KX_LEFTMOUSE);
- KX_MACRO_addTypesToDict(d, KX_MOUSE_BUT_MIDDLE, SCA_IInputDevice::KX_MIDDLEMOUSE);
- KX_MACRO_addTypesToDict(d, KX_MOUSE_BUT_RIGHT, SCA_IInputDevice::KX_RIGHTMOUSE);
-
- /* 2D Filter Actuator */
- KX_MACRO_addTypesToDict(d, RAS_2DFILTER_ENABLED, RAS_2DFilterManager::RAS_2DFILTER_ENABLED);
- KX_MACRO_addTypesToDict(d, RAS_2DFILTER_DISABLED, RAS_2DFilterManager::RAS_2DFILTER_DISABLED);
- KX_MACRO_addTypesToDict(d, RAS_2DFILTER_NOFILTER, RAS_2DFilterManager::RAS_2DFILTER_NOFILTER);
- KX_MACRO_addTypesToDict(d, RAS_2DFILTER_MOTIONBLUR, RAS_2DFilterManager::RAS_2DFILTER_MOTIONBLUR);
- KX_MACRO_addTypesToDict(d, RAS_2DFILTER_BLUR, RAS_2DFilterManager::RAS_2DFILTER_BLUR);
- KX_MACRO_addTypesToDict(d, RAS_2DFILTER_SHARPEN, RAS_2DFilterManager::RAS_2DFILTER_SHARPEN);
- KX_MACRO_addTypesToDict(d, RAS_2DFILTER_DILATION, RAS_2DFilterManager::RAS_2DFILTER_DILATION);
- KX_MACRO_addTypesToDict(d, RAS_2DFILTER_EROSION, RAS_2DFilterManager::RAS_2DFILTER_EROSION);
- KX_MACRO_addTypesToDict(d, RAS_2DFILTER_LAPLACIAN, RAS_2DFilterManager::RAS_2DFILTER_LAPLACIAN);
- KX_MACRO_addTypesToDict(d, RAS_2DFILTER_SOBEL, RAS_2DFilterManager::RAS_2DFILTER_SOBEL);
- KX_MACRO_addTypesToDict(d, RAS_2DFILTER_PREWITT, RAS_2DFilterManager::RAS_2DFILTER_PREWITT);
- KX_MACRO_addTypesToDict(d, RAS_2DFILTER_GRAYSCALE, RAS_2DFilterManager::RAS_2DFILTER_GRAYSCALE);
- KX_MACRO_addTypesToDict(d, RAS_2DFILTER_SEPIA, RAS_2DFilterManager::RAS_2DFILTER_SEPIA);
- KX_MACRO_addTypesToDict(d, RAS_2DFILTER_INVERT, RAS_2DFilterManager::RAS_2DFILTER_INVERT);
- KX_MACRO_addTypesToDict(d, RAS_2DFILTER_CUSTOMFILTER, RAS_2DFilterManager::RAS_2DFILTER_CUSTOMFILTER);
-
- /* Sound Actuator */
- KX_MACRO_addTypesToDict(d, KX_SOUNDACT_PLAYSTOP, KX_SoundActuator::KX_SOUNDACT_PLAYSTOP);
- KX_MACRO_addTypesToDict(d, KX_SOUNDACT_PLAYEND, KX_SoundActuator::KX_SOUNDACT_PLAYEND);
- KX_MACRO_addTypesToDict(d, KX_SOUNDACT_LOOPSTOP, KX_SoundActuator::KX_SOUNDACT_LOOPSTOP);
- KX_MACRO_addTypesToDict(d, KX_SOUNDACT_LOOPEND, KX_SoundActuator:: KX_SOUNDACT_LOOPEND);
- KX_MACRO_addTypesToDict(d, KX_SOUNDACT_LOOPBIDIRECTIONAL, KX_SoundActuator::KX_SOUNDACT_LOOPBIDIRECTIONAL);
- KX_MACRO_addTypesToDict(d, KX_SOUNDACT_LOOPBIDIRECTIONAL_STOP, KX_SoundActuator::KX_SOUNDACT_LOOPBIDIRECTIONAL_STOP);
-
- /* State Actuator */
- KX_MACRO_addTypesToDict(d, KX_STATE_OP_CPY, KX_StateActuator::OP_CPY);
- KX_MACRO_addTypesToDict(d, KX_STATE_OP_SET, KX_StateActuator::OP_SET);
- KX_MACRO_addTypesToDict(d, KX_STATE_OP_CLR, KX_StateActuator::OP_CLR);
- KX_MACRO_addTypesToDict(d, KX_STATE_OP_NEG, KX_StateActuator::OP_NEG);
-
- /* Game Actuator Modes */
- KX_MACRO_addTypesToDict(d, KX_GAME_LOAD, KX_GameActuator::KX_GAME_LOAD);
- KX_MACRO_addTypesToDict(d, KX_GAME_START, KX_GameActuator::KX_GAME_START);
- KX_MACRO_addTypesToDict(d, KX_GAME_RESTART, KX_GameActuator::KX_GAME_RESTART);
- KX_MACRO_addTypesToDict(d, KX_GAME_QUIT, KX_GameActuator::KX_GAME_QUIT);
- KX_MACRO_addTypesToDict(d, KX_GAME_SAVECFG, KX_GameActuator::KX_GAME_SAVECFG);
- KX_MACRO_addTypesToDict(d, KX_GAME_LOADCFG, KX_GameActuator::KX_GAME_LOADCFG);
- KX_MACRO_addTypesToDict(d, KX_GAME_SCREENSHOT, KX_GameActuator::KX_GAME_SCREENSHOT);
-
- /* Scene Actuator Modes */
- KX_MACRO_addTypesToDict(d, KX_SCENE_RESTART, KX_SceneActuator::KX_SCENE_RESTART);
- KX_MACRO_addTypesToDict(d, KX_SCENE_SET_SCENE, KX_SceneActuator::KX_SCENE_SET_SCENE);
- KX_MACRO_addTypesToDict(d, KX_SCENE_SET_CAMERA, KX_SceneActuator::KX_SCENE_SET_CAMERA);
- KX_MACRO_addTypesToDict(d, KX_SCENE_ADD_FRONT_SCENE, KX_SceneActuator::KX_SCENE_ADD_FRONT_SCENE);
- KX_MACRO_addTypesToDict(d, KX_SCENE_ADD_BACK_SCENE, KX_SceneActuator::KX_SCENE_ADD_BACK_SCENE);
- KX_MACRO_addTypesToDict(d, KX_SCENE_REMOVE_SCENE, KX_SceneActuator::KX_SCENE_REMOVE_SCENE);
- KX_MACRO_addTypesToDict(d, KX_SCENE_SUSPEND, KX_SceneActuator::KX_SCENE_SUSPEND);
- KX_MACRO_addTypesToDict(d, KX_SCENE_RESUME, KX_SceneActuator::KX_SCENE_RESUME);
-
- /* Parent Actuator Modes */
- KX_MACRO_addTypesToDict(d, KX_PARENT_SET, KX_ParentActuator::KX_PARENT_SET);
- KX_MACRO_addTypesToDict(d, KX_PARENT_REMOVE, KX_ParentActuator::KX_PARENT_REMOVE);
-
- /* BL_ArmatureConstraint type */
- KX_MACRO_addTypesToDict(d, CONSTRAINT_TYPE_TRACKTO, CONSTRAINT_TYPE_TRACKTO);
- KX_MACRO_addTypesToDict(d, CONSTRAINT_TYPE_KINEMATIC, CONSTRAINT_TYPE_KINEMATIC);
- KX_MACRO_addTypesToDict(d, CONSTRAINT_TYPE_ROTLIKE, CONSTRAINT_TYPE_ROTLIKE);
- KX_MACRO_addTypesToDict(d, CONSTRAINT_TYPE_LOCLIKE, CONSTRAINT_TYPE_LOCLIKE);
- KX_MACRO_addTypesToDict(d, CONSTRAINT_TYPE_MINMAX, CONSTRAINT_TYPE_MINMAX);
- KX_MACRO_addTypesToDict(d, CONSTRAINT_TYPE_SIZELIKE, CONSTRAINT_TYPE_SIZELIKE);
- KX_MACRO_addTypesToDict(d, CONSTRAINT_TYPE_LOCKTRACK, CONSTRAINT_TYPE_LOCKTRACK);
- KX_MACRO_addTypesToDict(d, CONSTRAINT_TYPE_STRETCHTO, CONSTRAINT_TYPE_STRETCHTO);
- KX_MACRO_addTypesToDict(d, CONSTRAINT_TYPE_CLAMPTO, CONSTRAINT_TYPE_CLAMPTO);
- KX_MACRO_addTypesToDict(d, CONSTRAINT_TYPE_TRANSFORM, CONSTRAINT_TYPE_TRANSFORM);
- KX_MACRO_addTypesToDict(d, CONSTRAINT_TYPE_DISTLIMIT, CONSTRAINT_TYPE_DISTLIMIT);
- /* BL_ArmatureConstraint ik_type */
- KX_MACRO_addTypesToDict(d, CONSTRAINT_IK_COPYPOSE, CONSTRAINT_IK_COPYPOSE);
- KX_MACRO_addTypesToDict(d, CONSTRAINT_IK_DISTANCE, CONSTRAINT_IK_DISTANCE);
- /* BL_ArmatureConstraint ik_mode */
- KX_MACRO_addTypesToDict(d, CONSTRAINT_IK_MODE_INSIDE, LIMITDIST_INSIDE);
- KX_MACRO_addTypesToDict(d, CONSTRAINT_IK_MODE_OUTSIDE, LIMITDIST_OUTSIDE);
- KX_MACRO_addTypesToDict(d, CONSTRAINT_IK_MODE_ONSURFACE, LIMITDIST_ONSURFACE);
- /* BL_ArmatureConstraint ik_flag */
- KX_MACRO_addTypesToDict(d, CONSTRAINT_IK_FLAG_TIP, CONSTRAINT_IK_TIP);
- KX_MACRO_addTypesToDict(d, CONSTRAINT_IK_FLAG_ROT, CONSTRAINT_IK_ROT);
- KX_MACRO_addTypesToDict(d, CONSTRAINT_IK_FLAG_STRETCH, CONSTRAINT_IK_STRETCH);
- KX_MACRO_addTypesToDict(d, CONSTRAINT_IK_FLAG_POS, CONSTRAINT_IK_POS);
- /* KX_ArmatureSensor type */
- KX_MACRO_addTypesToDict(d, KX_ARMSENSOR_STATE_CHANGED, SENS_ARM_STATE_CHANGED);
- KX_MACRO_addTypesToDict(d, KX_ARMSENSOR_LIN_ERROR_BELOW, SENS_ARM_LIN_ERROR_BELOW);
- KX_MACRO_addTypesToDict(d, KX_ARMSENSOR_LIN_ERROR_ABOVE, SENS_ARM_LIN_ERROR_ABOVE);
- KX_MACRO_addTypesToDict(d, KX_ARMSENSOR_ROT_ERROR_BELOW, SENS_ARM_ROT_ERROR_BELOW);
- KX_MACRO_addTypesToDict(d, KX_ARMSENSOR_ROT_ERROR_ABOVE, SENS_ARM_ROT_ERROR_ABOVE);
-
- /* BL_ArmatureActuator type */
- KX_MACRO_addTypesToDict(d, KX_ACT_ARMATURE_RUN, ACT_ARM_RUN);
- KX_MACRO_addTypesToDict(d, KX_ACT_ARMATURE_ENABLE, ACT_ARM_ENABLE);
- KX_MACRO_addTypesToDict(d, KX_ACT_ARMATURE_DISABLE, ACT_ARM_DISABLE);
- KX_MACRO_addTypesToDict(d, KX_ACT_ARMATURE_SETTARGET, ACT_ARM_SETTARGET);
- KX_MACRO_addTypesToDict(d, KX_ACT_ARMATURE_SETWEIGHT, ACT_ARM_SETWEIGHT);
- KX_MACRO_addTypesToDict(d, KX_ACT_ARMATURE_SETINFLUENCE, ACT_ARM_SETINFLUENCE);
-
- /* BL_Armature Channel rotation_mode */
- KX_MACRO_addTypesToDict(d, ROT_MODE_QUAT, ROT_MODE_QUAT);
- KX_MACRO_addTypesToDict(d, ROT_MODE_XYZ, ROT_MODE_XYZ);
- KX_MACRO_addTypesToDict(d, ROT_MODE_XZY, ROT_MODE_XZY);
- KX_MACRO_addTypesToDict(d, ROT_MODE_YXZ, ROT_MODE_YXZ);
- KX_MACRO_addTypesToDict(d, ROT_MODE_YZX, ROT_MODE_YZX);
- KX_MACRO_addTypesToDict(d, ROT_MODE_ZXY, ROT_MODE_ZXY);
- KX_MACRO_addTypesToDict(d, ROT_MODE_ZYX, ROT_MODE_ZYX);
-
- /* Steering actuator */
- KX_MACRO_addTypesToDict(d, KX_STEERING_SEEK, KX_SteeringActuator::KX_STEERING_SEEK);
- KX_MACRO_addTypesToDict(d, KX_STEERING_FLEE, KX_SteeringActuator::KX_STEERING_FLEE);
- KX_MACRO_addTypesToDict(d, KX_STEERING_PATHFOLLOWING, KX_SteeringActuator::KX_STEERING_PATHFOLLOWING);
-
- /* KX_NavMeshObject render mode */
- KX_MACRO_addTypesToDict(d, RM_WALLS, KX_NavMeshObject::RM_WALLS);
- KX_MACRO_addTypesToDict(d, RM_POLYS, KX_NavMeshObject::RM_POLYS);
- KX_MACRO_addTypesToDict(d, RM_TRIS, KX_NavMeshObject::RM_TRIS);
-
- /* BL_Action play modes */
- KX_MACRO_addTypesToDict(d, KX_ACTION_MODE_PLAY, BL_Action::ACT_MODE_PLAY);
- KX_MACRO_addTypesToDict(d, KX_ACTION_MODE_LOOP, BL_Action::ACT_MODE_LOOP);
- KX_MACRO_addTypesToDict(d, KX_ACTION_MODE_PING_PONG, BL_Action::ACT_MODE_PING_PONG);
-
- /* BL_Action blend modes */
- KX_MACRO_addTypesToDict(d, KX_ACTION_BLEND_BLEND, BL_Action::ACT_BLEND_BLEND);
- KX_MACRO_addTypesToDict(d, KX_ACTION_BLEND_ADD, BL_Action::ACT_BLEND_ADD);
-
- /* Mouse Actuator object axis*/
- KX_MACRO_addTypesToDict(d, KX_ACT_MOUSE_OBJECT_AXIS_X, KX_MouseActuator::KX_ACT_MOUSE_OBJECT_AXIS_X);
- KX_MACRO_addTypesToDict(d, KX_ACT_MOUSE_OBJECT_AXIS_Y, KX_MouseActuator::KX_ACT_MOUSE_OBJECT_AXIS_Y);
- KX_MACRO_addTypesToDict(d, KX_ACT_MOUSE_OBJECT_AXIS_Z, KX_MouseActuator::KX_ACT_MOUSE_OBJECT_AXIS_Z);
-
-
- // Check for errors
- if (PyErr_Occurred())
- {
- Py_FatalError("can't initialize module bge.logic");
- }
-
- return m;
-}
-
-/**
- * Explanation of
- *
- * - backupPySysObjects() : stores sys.path in #gp_sys_backup
- * - initPySysObjects(main) : initializes the blendfile and library paths
- * - restorePySysObjects() : restores sys.path from #gp_sys_backup
- *
- * These exist so the current blend dir "//" can always be used to import modules from.
- * the reason we need a few functions for this is that python is not only used by the game engine
- * so we cant just add to sys.path all the time, it would leave pythons state in a mess.
- * It would also be incorrect since loading blend files for new levels etc would always add to sys.path
- *
- * To play nice with blenders python, the sys.path is backed up and the current blendfile along
- * with all its lib paths are added to the sys path.
- * When loading a new blendfile, the original sys.path is restored and the new paths are added over the top.
- */
-
-/**
- * So we can have external modules mixed with our blend files.
- */
-static void backupPySysObjects(void)
-{
- PyObject *sys_path = PySys_GetObject("path");
- PyObject *sys_meta_path = PySys_GetObject("meta_path");
- PyObject *sys_mods = PySys_GetObject("modules");
-
- /* paths */
- Py_XDECREF(gp_sys_backup.path); /* just in case its set */
- gp_sys_backup.path = PyList_GetSlice(sys_path, 0, INT_MAX); /* copy the list */
-
- /* meta_paths */
- Py_XDECREF(gp_sys_backup.meta_path); /* just in case its set */
- gp_sys_backup.meta_path = PyList_GetSlice(sys_meta_path, 0, INT_MAX); /* copy the list */
-
- /* modules */
- Py_XDECREF(gp_sys_backup.modules); /* just in case its set */
- gp_sys_backup.modules = PyDict_Copy(sys_mods); /* copy the dict */
-
-}
-
-/* for initPySysObjects only,
- * takes a blend path and adds a scripts dir from it
- *
- * "/home/me/foo.blend" -> "/home/me/scripts"
- */
-static void initPySysObjects__append(PyObject *sys_path, const char *filename)
-{
- PyObject *item;
- char expanded[FILE_MAX];
-
- BLI_split_dir_part(filename, expanded, sizeof(expanded)); /* get the dir part of filename only */
- BLI_path_abs(expanded, gp_GamePythonPath); /* filename from lib->filename is (always?) absolute, so this may not be needed but it wont hurt */
- BLI_cleanup_file(gp_GamePythonPath, expanded); /* Don't use BLI_cleanup_dir because it adds a slash - BREAKS WIN32 ONLY */
- item = PyC_UnicodeFromByte(expanded);
-
-// printf("SysPath - '%s', '%s', '%s'\n", expanded, filename, gp_GamePythonPath);
-
- if (PySequence_Index(sys_path, item) == -1) {
- PyErr_Clear(); /* PySequence_Index sets a ValueError */
- PyList_Insert(sys_path, 0, item);
- }
-
- Py_DECREF(item);
-}
-static void initPySysObjects(Main *maggie)
-{
- PyObject *sys_path = PySys_GetObject("path");
- PyObject *sys_meta_path = PySys_GetObject("meta_path");
-
- if (gp_sys_backup.path == NULL) {
- /* backup */
- backupPySysObjects();
- }
- else {
- /* get the original sys path when the BGE started */
- PyList_SetSlice(sys_path, 0, INT_MAX, gp_sys_backup.path);
- PyList_SetSlice(sys_meta_path, 0, INT_MAX, gp_sys_backup.meta_path);
- }
-
- Library *lib= (Library *)maggie->library.first;
-
- while (lib) {
- /* lib->name wont work in some cases (on win32),
- * even when expanding with gp_GamePythonPath, using lib->filename is less trouble */
- initPySysObjects__append(sys_path, lib->filepath);
- lib= (Library *)lib->id.next;
- }
-
- initPySysObjects__append(sys_path, gp_GamePythonPath);
-
-// fprintf(stderr, "\nNew Path: %d ", PyList_GET_SIZE(sys_path));
-// PyObject_Print(sys_path, stderr, 0);
-}
-
-static void restorePySysObjects(void)
-{
- if (gp_sys_backup.path == NULL) {
- return;
- }
-
- /* will never fail */
- PyObject *sys_path = PySys_GetObject("path");
- PyObject *sys_meta_path = PySys_GetObject("meta_path");
- PyObject *sys_mods = PySys_GetObject("modules");
-
- /* paths */
- PyList_SetSlice(sys_path, 0, INT_MAX, gp_sys_backup.path);
- Py_DECREF(gp_sys_backup.path);
- gp_sys_backup.path = NULL;
-
- /* meta_path */
- PyList_SetSlice(sys_meta_path, 0, INT_MAX, gp_sys_backup.meta_path);
- Py_DECREF(gp_sys_backup.meta_path);
- gp_sys_backup.meta_path = NULL;
-
- /* modules */
- PyDict_Clear(sys_mods);
- PyDict_Update(sys_mods, gp_sys_backup.modules);
- Py_DECREF(gp_sys_backup.modules);
- gp_sys_backup.modules = NULL;
-
-
-// fprintf(stderr, "\nRestore Path: %d ", PyList_GET_SIZE(sys_path));
-// PyObject_Print(sys_path, stderr, 0);
-}
-
-void addImportMain(struct Main *maggie)
-{
- bpy_import_main_extra_add(maggie);
-}
-
-void removeImportMain(struct Main *maggie)
-{
- bpy_import_main_extra_remove(maggie);
-}
-
-
-PyDoc_STRVAR(BGE_module_documentation,
- "This module contains submodules for the Blender Game Engine.\n"
-);
-
-static struct PyModuleDef BGE_module_def = {
- PyModuleDef_HEAD_INIT,
- "bge", /* m_name */
- BGE_module_documentation, /* m_doc */
- 0, /* m_size */
- NULL, /* m_methods */
- NULL, /* m_reload */
- NULL, /* m_traverse */
- NULL, /* m_clear */
- NULL, /* m_free */
-};
-
-PyMODINIT_FUNC initBGE(void)
-{
- PyObject *mod;
- PyObject *submodule;
- PyObject *sys_modules = PyThreadState_GET()->interp->modules;
- const char *mod_full;
-
- mod = PyModule_Create(&BGE_module_def);
-
- /* skip "bge." */
-#define SUBMOD (mod_full + 4)
-
- mod_full = "bge.app";
- PyModule_AddObject(mod, SUBMOD, (submodule = initApplicationPythonBinding()));
- PyDict_SetItemString(sys_modules, mod_full, submodule);
- Py_INCREF(submodule);
-
- mod_full = "bge.constraints";
- PyModule_AddObject(mod, SUBMOD, (submodule = initConstraintPythonBinding()));
- PyDict_SetItemString(sys_modules, mod_full, submodule);
- Py_INCREF(submodule);
-
- mod_full = "bge.events";
- PyModule_AddObject(mod, SUBMOD, (submodule = initGameKeysPythonBinding()));
- PyDict_SetItemString(sys_modules, mod_full, submodule);
- Py_INCREF(submodule);
-
- mod_full = "bge.logic";
- PyModule_AddObject(mod, SUBMOD, (submodule = initGameLogicPythonBinding()));
- PyDict_SetItemString(sys_modules, mod_full, submodule);
- Py_INCREF(submodule);
-
- mod_full = "bge.render";
- PyModule_AddObject(mod, SUBMOD, (submodule = initRasterizerPythonBinding()));
- PyDict_SetItemString(sys_modules, mod_full, submodule);
- Py_INCREF(submodule);
-
- mod_full = "bge.texture";
- PyModule_AddObject(mod, SUBMOD, (submodule = initVideoTexturePythonBinding()));
- PyDict_SetItemString(sys_modules, mod_full, submodule);
- Py_INCREF(submodule);
-
- mod_full = "bge.types";
- PyModule_AddObject(mod, SUBMOD, (submodule = initGameTypesPythonBinding()));
- PyDict_SetItemString(sys_modules, mod_full, submodule);
- Py_INCREF(submodule);
-
-#undef SUBMOD
-
- return mod;
-}
-
-
-/* minimal required blender modules to run blenderplayer */
-static struct _inittab bge_internal_modules[] = {
- {"mathutils", PyInit_mathutils},
- {"bgl", BPyInit_bgl},
- {"blf", BPyInit_blf},
- {"aud", AUD_initPython},
- {NULL, NULL}
-};
-
-/**
- * Python is not initialized.
- * see bpy_interface.c's BPY_python_start() which shares the same functionality in blender.
- */
-PyObject *initGamePlayerPythonScripting(Main *maggie, int argc, char** argv)
-{
- /* Yet another gotcha in the py api
- * Cant run PySys_SetArgv more than once because this adds the
- * binary dir to the sys.path each time.
- * Id have thought python being totally restarted would make this ok but
- * somehow it remembers the sys.path - Campbell
- */
- static bool first_time = true;
- const char * const py_path_bundle = BKE_appdir_folder_id(BLENDER_SYSTEM_PYTHON, NULL);
-
- /* not essential but nice to set our name */
- static wchar_t program_path_wchar[FILE_MAX]; /* python holds a reference */
- BLI_strncpy_wchar_from_utf8(program_path_wchar, BKE_appdir_program_path(), ARRAY_SIZE(program_path_wchar));
- Py_SetProgramName(program_path_wchar);
-
- /* Update, Py3.3 resolves attempting to parse non-existing header */
-#if 0
- /* Python 3.2 now looks for '2.xx/python/include/python3.2d/pyconfig.h' to
- * parse from the 'sysconfig' module which is used by 'site',
- * so for now disable site. alternatively we could copy the file. */
- if (py_path_bundle != NULL) {
- Py_NoSiteFlag = 1; /* inhibits the automatic importing of 'site' */
- }
-#endif
-
- Py_FrozenFlag = 1;
-
- /* must run before python initializes */
- PyImport_ExtendInittab(bge_internal_modules);
-
- /* find local python installation */
- PyC_SetHomePath(py_path_bundle);
-
- Py_Initialize();
-
- if (argv && first_time) { /* browser plugins don't currently set this */
- // Until python support ascii again, we use our own.
- // PySys_SetArgv(argc, argv);
- int i;
- PyObject *py_argv= PyList_New(argc);
-
- for (i=0; i<argc; i++)
- PyList_SET_ITEM(py_argv, i, PyC_UnicodeFromByte(argv[i]));
-
- PySys_SetObject("argv", py_argv);
- Py_DECREF(py_argv);
- }
-
- /* Initialize thread support (also acquires lock) */
- PyEval_InitThreads();
-
- bpy_import_init(PyEval_GetBuiltins());
-
- bpy_import_main_set(maggie);
-
- initPySysObjects(maggie);
-
- /* mathutils types are used by the BGE even if we don't import them */
- {
- PyObject *mod = PyImport_ImportModuleLevel("mathutils", NULL, NULL, NULL, 0);
- Py_DECREF(mod);
- }
-
-#ifdef WITH_AUDASPACE
- /* accessing a SoundActuator's sound results in a crash if aud is not initialized... */
- {
- PyObject *mod = PyImport_ImportModuleLevel("aud", NULL, NULL, NULL, 0);
- Py_DECREF(mod);
- }
-#endif
-
- PyDict_SetItemString(PyImport_GetModuleDict(), "bge", initBGE());
-
- first_time = false;
-
- PyObjectPlus::ClearDeprecationWarning();
-
- return PyC_DefaultNameSpace(NULL);
-}
-
-void exitGamePlayerPythonScripting()
-{
- /* Clean up the Python mouse and keyboard */
- delete gp_PythonKeyboard;
- gp_PythonKeyboard = NULL;
-
- delete gp_PythonMouse;
- gp_PythonMouse = NULL;
-
- for (int i=0; i<JOYINDEX_MAX; ++i) {
- if (gp_PythonJoysticks[i]) {
- delete gp_PythonJoysticks[i];
- gp_PythonJoysticks[i] = NULL;
- }
- }
-
- /* since python restarts we cant let the python backup of the sys.path hang around in a global pointer */
- restorePySysObjects(); /* get back the original sys.path and clear the backup */
-
- Py_Finalize();
- bpy_import_main_set(NULL);
- PyObjectPlus::ClearDeprecationWarning();
-}
-
-
-
-/**
- * Python is already initialized.
- */
-PyObject *initGamePythonScripting(Main *maggie)
-{
- /* no need to Py_SetProgramName, it was already taken care of in BPY_python_start */
-
- bpy_import_main_set(maggie);
-
- initPySysObjects(maggie);
-
-#ifdef WITH_AUDASPACE
- /* accessing a SoundActuator's sound results in a crash if aud is not initialized... */
- {
- PyObject *mod= PyImport_ImportModuleLevel("aud", NULL, NULL, NULL, 0);
- Py_DECREF(mod);
- }
-#endif
-
- PyDict_SetItemString(PyImport_GetModuleDict(), "bge", initBGE());
-
- PyObjectPlus::NullDeprecationWarning();
-
- return PyC_DefaultNameSpace(NULL);
-}
-
-void exitGamePythonScripting()
-{
- /* Clean up the Python mouse and keyboard */
- delete gp_PythonKeyboard;
- gp_PythonKeyboard = NULL;
-
- delete gp_PythonMouse;
- gp_PythonMouse = NULL;
-
- for (int i=0; i<JOYINDEX_MAX; ++i) {
- if (gp_PythonJoysticks[i]) {
- delete gp_PythonJoysticks[i];
- gp_PythonJoysticks[i] = NULL;
- }
- }
-
- restorePySysObjects(); /* get back the original sys.path and clear the backup */
- bpy_import_main_set(NULL);
- PyObjectPlus::ClearDeprecationWarning();
-}
-
-/* similar to the above functions except it sets up the namespace
- * and other more general things */
-void setupGamePython(KX_KetsjiEngine* ketsjiengine, KX_Scene *startscene, Main *blenderdata,
- PyObject *pyGlobalDict, PyObject **gameLogic, PyObject **gameLogic_keys, int argc, char** argv)
-{
- PyObject *modules, *dictionaryobject;
-
- gp_Canvas = ketsjiengine->GetCanvas();
- gp_Rasterizer = ketsjiengine->GetRasterizer();
- gp_KetsjiEngine = ketsjiengine;
- gp_KetsjiScene = startscene;
-
- if (argv) /* player only */
- dictionaryobject= initGamePlayerPythonScripting(blenderdata, argc, argv);
- else
- dictionaryobject= initGamePythonScripting(blenderdata);
-
- ketsjiengine->SetPyNamespace(dictionaryobject);
-
- modules = PyImport_GetModuleDict();
-
- *gameLogic = PyDict_GetItemString(modules, "GameLogic");
- /* is set in initGameLogicPythonBinding so only set here if we want it to persist between scenes */
- if (pyGlobalDict)
- PyDict_SetItemString(PyModule_GetDict(*gameLogic), "globalDict", pyGlobalDict); // Same as importing the module.
-
- *gameLogic_keys = PyDict_Keys(PyModule_GetDict(*gameLogic));
-}
-
-static struct PyModuleDef Rasterizer_module_def = {
- PyModuleDef_HEAD_INIT,
- "Rasterizer", /* m_name */
- Rasterizer_module_documentation, /* m_doc */
- 0, /* m_size */
- rasterizer_methods, /* m_methods */
- 0, /* m_reload */
- 0, /* m_traverse */
- 0, /* m_clear */
- 0, /* m_free */
-};
-
-PyMODINIT_FUNC initRasterizerPythonBinding()
-{
- PyObject *m;
- PyObject *d;
-
- PyType_Ready(&PyRASOffScreen_Type);
-
- m = PyModule_Create(&Rasterizer_module_def);
- PyDict_SetItemString(PySys_GetObject("modules"), Rasterizer_module_def.m_name, m);
-
-
- // Add some symbolic constants to the module
- d = PyModule_GetDict(m);
- ErrorObject = PyUnicode_FromString("Rasterizer.error");
- PyDict_SetItemString(d, "error", ErrorObject);
- Py_DECREF(ErrorObject);
-
- /* needed for get/setMaterialType */
- KX_MACRO_addTypesToDict(d, KX_BLENDER_MULTITEX_MATERIAL, KX_BLENDER_MULTITEX_MATERIAL);
- KX_MACRO_addTypesToDict(d, KX_BLENDER_GLSL_MATERIAL, KX_BLENDER_GLSL_MATERIAL);
-
- KX_MACRO_addTypesToDict(d, RAS_MIPMAP_NONE, RAS_IRasterizer::RAS_MIPMAP_NONE);
- KX_MACRO_addTypesToDict(d, RAS_MIPMAP_NEAREST, RAS_IRasterizer::RAS_MIPMAP_NEAREST);
- KX_MACRO_addTypesToDict(d, RAS_MIPMAP_LINEAR, RAS_IRasterizer::RAS_MIPMAP_LINEAR);
-
- /* for get/setVsync */
- KX_MACRO_addTypesToDict(d, VSYNC_OFF, VSYNC_OFF);
- KX_MACRO_addTypesToDict(d, VSYNC_ON, VSYNC_ON);
- KX_MACRO_addTypesToDict(d, VSYNC_ADAPTIVE, VSYNC_ADAPTIVE);
-
- /* stereoscopy */
- KX_MACRO_addTypesToDict(d, LEFT_EYE, RAS_IRasterizer::RAS_STEREO_LEFTEYE);
- KX_MACRO_addTypesToDict(d, RIGHT_EYE, RAS_IRasterizer::RAS_STEREO_RIGHTEYE);
-
- /* offscreen render */
- KX_MACRO_addTypesToDict(d, RAS_OFS_RENDER_BUFFER, RAS_IOffScreen::RAS_OFS_RENDER_BUFFER);
- KX_MACRO_addTypesToDict(d, RAS_OFS_RENDER_TEXTURE, RAS_IOffScreen::RAS_OFS_RENDER_TEXTURE);
-
-
- // XXXX Add constants here
-
- // Check for errors
- if (PyErr_Occurred())
- {
- Py_FatalError("can't initialize module Rasterizer");
- }
-
- return m;
-}
-
-
-
-/* ------------------------------------------------------------------------- */
-/* GameKeys: symbolic constants for key mapping */
-/* ------------------------------------------------------------------------- */
-
-PyDoc_STRVAR(GameKeys_module_documentation,
-"This modules provides defines for key-codes"
-);
-
-PyDoc_STRVAR(gPyEventToString_doc,
-"EventToString(event)\n"
-"Take a valid event from the GameKeys module or Keyboard Sensor and return a name"
-);
-
-static PyObject *gPyEventToString(PyObject *, PyObject *value)
-{
- PyObject *mod, *dict, *key, *val, *ret = NULL;
- Py_ssize_t pos = 0;
-
- mod = PyImport_ImportModule( "GameKeys" );
- if (!mod)
- return NULL;
-
- dict = PyModule_GetDict(mod);
-
- while (PyDict_Next(dict, &pos, &key, &val)) {
- if (PyObject_RichCompareBool(value, val, Py_EQ)) {
- ret = key;
- break;
- }
- }
-
- PyErr_Clear(); // in case there was an error clearing
- Py_DECREF(mod);
- if (!ret) PyErr_SetString(PyExc_ValueError, "GameKeys.EventToString(int): expected a valid int keyboard event");
- else Py_INCREF(ret);
-
- return ret;
-}
-
-
-PyDoc_STRVAR(gPyEventToCharacter_doc,
-"EventToCharacter(event, is_shift)\n"
-"Take a valid event from the GameKeys module or Keyboard Sensor and return a character"
-);
-
-static PyObject *gPyEventToCharacter(PyObject *, PyObject *args)
-{
- int event, shift;
- if (!PyArg_ParseTuple(args,"ii:EventToCharacter", &event, &shift))
- return NULL;
-
- if (IsPrintable(event)) {
- char ch[2] = {'\0', '\0'};
- ch[0] = ToCharacter(event, (bool)shift);
- return PyUnicode_FromString(ch);
- }
- else {
- return PyUnicode_FromString("");
- }
-}
-
-
-static struct PyMethodDef gamekeys_methods[] = {
- {"EventToCharacter", (PyCFunction)gPyEventToCharacter, METH_VARARGS, (const char *)gPyEventToCharacter_doc},
- {"EventToString", (PyCFunction)gPyEventToString, METH_O, (const char *)gPyEventToString_doc},
- { NULL, (PyCFunction) NULL, 0, NULL }
-};
-
-static struct PyModuleDef GameKeys_module_def = {
- PyModuleDef_HEAD_INIT,
- "GameKeys", /* m_name */
- GameKeys_module_documentation, /* m_doc */
- 0, /* m_size */
- gamekeys_methods, /* m_methods */
- 0, /* m_reload */
- 0, /* m_traverse */
- 0, /* m_clear */
- 0, /* m_free */
-};
-
-PyMODINIT_FUNC initGameKeysPythonBinding()
-{
- PyObject *m;
- PyObject *d;
-
- m = PyModule_Create(&GameKeys_module_def);
- PyDict_SetItemString(PySys_GetObject("modules"), GameKeys_module_def.m_name, m);
-
- // Add some symbolic constants to the module
- d = PyModule_GetDict(m);
-
- // XXXX Add constants here
-
- KX_MACRO_addTypesToDict(d, AKEY, SCA_IInputDevice::KX_AKEY);
- KX_MACRO_addTypesToDict(d, BKEY, SCA_IInputDevice::KX_BKEY);
- KX_MACRO_addTypesToDict(d, CKEY, SCA_IInputDevice::KX_CKEY);
- KX_MACRO_addTypesToDict(d, DKEY, SCA_IInputDevice::KX_DKEY);
- KX_MACRO_addTypesToDict(d, EKEY, SCA_IInputDevice::KX_EKEY);
- KX_MACRO_addTypesToDict(d, FKEY, SCA_IInputDevice::KX_FKEY);
- KX_MACRO_addTypesToDict(d, GKEY, SCA_IInputDevice::KX_GKEY);
- KX_MACRO_addTypesToDict(d, HKEY, SCA_IInputDevice::KX_HKEY);
- KX_MACRO_addTypesToDict(d, IKEY, SCA_IInputDevice::KX_IKEY);
- KX_MACRO_addTypesToDict(d, JKEY, SCA_IInputDevice::KX_JKEY);
- KX_MACRO_addTypesToDict(d, KKEY, SCA_IInputDevice::KX_KKEY);
- KX_MACRO_addTypesToDict(d, LKEY, SCA_IInputDevice::KX_LKEY);
- KX_MACRO_addTypesToDict(d, MKEY, SCA_IInputDevice::KX_MKEY);
- KX_MACRO_addTypesToDict(d, NKEY, SCA_IInputDevice::KX_NKEY);
- KX_MACRO_addTypesToDict(d, OKEY, SCA_IInputDevice::KX_OKEY);
- KX_MACRO_addTypesToDict(d, PKEY, SCA_IInputDevice::KX_PKEY);
- KX_MACRO_addTypesToDict(d, QKEY, SCA_IInputDevice::KX_QKEY);
- KX_MACRO_addTypesToDict(d, RKEY, SCA_IInputDevice::KX_RKEY);
- KX_MACRO_addTypesToDict(d, SKEY, SCA_IInputDevice::KX_SKEY);
- KX_MACRO_addTypesToDict(d, TKEY, SCA_IInputDevice::KX_TKEY);
- KX_MACRO_addTypesToDict(d, UKEY, SCA_IInputDevice::KX_UKEY);
- KX_MACRO_addTypesToDict(d, VKEY, SCA_IInputDevice::KX_VKEY);
- KX_MACRO_addTypesToDict(d, WKEY, SCA_IInputDevice::KX_WKEY);
- KX_MACRO_addTypesToDict(d, XKEY, SCA_IInputDevice::KX_XKEY);
- KX_MACRO_addTypesToDict(d, YKEY, SCA_IInputDevice::KX_YKEY);
- KX_MACRO_addTypesToDict(d, ZKEY, SCA_IInputDevice::KX_ZKEY);
-
- KX_MACRO_addTypesToDict(d, ZEROKEY, SCA_IInputDevice::KX_ZEROKEY);
- KX_MACRO_addTypesToDict(d, ONEKEY, SCA_IInputDevice::KX_ONEKEY);
- KX_MACRO_addTypesToDict(d, TWOKEY, SCA_IInputDevice::KX_TWOKEY);
- KX_MACRO_addTypesToDict(d, THREEKEY, SCA_IInputDevice::KX_THREEKEY);
- KX_MACRO_addTypesToDict(d, FOURKEY, SCA_IInputDevice::KX_FOURKEY);
- KX_MACRO_addTypesToDict(d, FIVEKEY, SCA_IInputDevice::KX_FIVEKEY);
- KX_MACRO_addTypesToDict(d, SIXKEY, SCA_IInputDevice::KX_SIXKEY);
- KX_MACRO_addTypesToDict(d, SEVENKEY, SCA_IInputDevice::KX_SEVENKEY);
- KX_MACRO_addTypesToDict(d, EIGHTKEY, SCA_IInputDevice::KX_EIGHTKEY);
- KX_MACRO_addTypesToDict(d, NINEKEY, SCA_IInputDevice::KX_NINEKEY);
-
- KX_MACRO_addTypesToDict(d, CAPSLOCKKEY, SCA_IInputDevice::KX_CAPSLOCKKEY);
-
- KX_MACRO_addTypesToDict(d, LEFTCTRLKEY, SCA_IInputDevice::KX_LEFTCTRLKEY);
- KX_MACRO_addTypesToDict(d, LEFTALTKEY, SCA_IInputDevice::KX_LEFTALTKEY);
- KX_MACRO_addTypesToDict(d, RIGHTALTKEY, SCA_IInputDevice::KX_RIGHTALTKEY);
- KX_MACRO_addTypesToDict(d, RIGHTCTRLKEY, SCA_IInputDevice::KX_RIGHTCTRLKEY);
- KX_MACRO_addTypesToDict(d, RIGHTSHIFTKEY, SCA_IInputDevice::KX_RIGHTSHIFTKEY);
- KX_MACRO_addTypesToDict(d, LEFTSHIFTKEY, SCA_IInputDevice::KX_LEFTSHIFTKEY);
-
- KX_MACRO_addTypesToDict(d, ESCKEY, SCA_IInputDevice::KX_ESCKEY);
- KX_MACRO_addTypesToDict(d, TABKEY, SCA_IInputDevice::KX_TABKEY);
- KX_MACRO_addTypesToDict(d, RETKEY, SCA_IInputDevice::KX_RETKEY);
- KX_MACRO_addTypesToDict(d, ENTERKEY, SCA_IInputDevice::KX_RETKEY);
- KX_MACRO_addTypesToDict(d, SPACEKEY, SCA_IInputDevice::KX_SPACEKEY);
- KX_MACRO_addTypesToDict(d, LINEFEEDKEY, SCA_IInputDevice::KX_LINEFEEDKEY);
- KX_MACRO_addTypesToDict(d, BACKSPACEKEY, SCA_IInputDevice::KX_BACKSPACEKEY);
- KX_MACRO_addTypesToDict(d, DELKEY, SCA_IInputDevice::KX_DELKEY);
- KX_MACRO_addTypesToDict(d, SEMICOLONKEY, SCA_IInputDevice::KX_SEMICOLONKEY);
- KX_MACRO_addTypesToDict(d, PERIODKEY, SCA_IInputDevice::KX_PERIODKEY);
- KX_MACRO_addTypesToDict(d, COMMAKEY, SCA_IInputDevice::KX_COMMAKEY);
- KX_MACRO_addTypesToDict(d, QUOTEKEY, SCA_IInputDevice::KX_QUOTEKEY);
- KX_MACRO_addTypesToDict(d, ACCENTGRAVEKEY, SCA_IInputDevice::KX_ACCENTGRAVEKEY);
- KX_MACRO_addTypesToDict(d, MINUSKEY, SCA_IInputDevice::KX_MINUSKEY);
- KX_MACRO_addTypesToDict(d, SLASHKEY, SCA_IInputDevice::KX_SLASHKEY);
- KX_MACRO_addTypesToDict(d, BACKSLASHKEY, SCA_IInputDevice::KX_BACKSLASHKEY);
- KX_MACRO_addTypesToDict(d, EQUALKEY, SCA_IInputDevice::KX_EQUALKEY);
- KX_MACRO_addTypesToDict(d, LEFTBRACKETKEY, SCA_IInputDevice::KX_LEFTBRACKETKEY);
- KX_MACRO_addTypesToDict(d, RIGHTBRACKETKEY, SCA_IInputDevice::KX_RIGHTBRACKETKEY);
-
- KX_MACRO_addTypesToDict(d, LEFTARROWKEY, SCA_IInputDevice::KX_LEFTARROWKEY);
- KX_MACRO_addTypesToDict(d, DOWNARROWKEY, SCA_IInputDevice::KX_DOWNARROWKEY);
- KX_MACRO_addTypesToDict(d, RIGHTARROWKEY, SCA_IInputDevice::KX_RIGHTARROWKEY);
- KX_MACRO_addTypesToDict(d, UPARROWKEY, SCA_IInputDevice::KX_UPARROWKEY);
-
- KX_MACRO_addTypesToDict(d, PAD2 , SCA_IInputDevice::KX_PAD2);
- KX_MACRO_addTypesToDict(d, PAD4 , SCA_IInputDevice::KX_PAD4);
- KX_MACRO_addTypesToDict(d, PAD6 , SCA_IInputDevice::KX_PAD6);
- KX_MACRO_addTypesToDict(d, PAD8 , SCA_IInputDevice::KX_PAD8);
-
- KX_MACRO_addTypesToDict(d, PAD1 , SCA_IInputDevice::KX_PAD1);
- KX_MACRO_addTypesToDict(d, PAD3 , SCA_IInputDevice::KX_PAD3);
- KX_MACRO_addTypesToDict(d, PAD5 , SCA_IInputDevice::KX_PAD5);
- KX_MACRO_addTypesToDict(d, PAD7 , SCA_IInputDevice::KX_PAD7);
- KX_MACRO_addTypesToDict(d, PAD9 , SCA_IInputDevice::KX_PAD9);
-
- KX_MACRO_addTypesToDict(d, PADPERIOD, SCA_IInputDevice::KX_PADPERIOD);
- KX_MACRO_addTypesToDict(d, PADSLASHKEY, SCA_IInputDevice::KX_PADSLASHKEY);
- KX_MACRO_addTypesToDict(d, PADASTERKEY, SCA_IInputDevice::KX_PADASTERKEY);
-
-
- KX_MACRO_addTypesToDict(d, PAD0, SCA_IInputDevice::KX_PAD0);
- KX_MACRO_addTypesToDict(d, PADMINUS, SCA_IInputDevice::KX_PADMINUS);
- KX_MACRO_addTypesToDict(d, PADENTER, SCA_IInputDevice::KX_PADENTER);
- KX_MACRO_addTypesToDict(d, PADPLUSKEY, SCA_IInputDevice::KX_PADPLUSKEY);
-
-
- KX_MACRO_addTypesToDict(d, F1KEY, SCA_IInputDevice::KX_F1KEY);
- KX_MACRO_addTypesToDict(d, F2KEY, SCA_IInputDevice::KX_F2KEY);
- KX_MACRO_addTypesToDict(d, F3KEY, SCA_IInputDevice::KX_F3KEY);
- KX_MACRO_addTypesToDict(d, F4KEY, SCA_IInputDevice::KX_F4KEY);
- KX_MACRO_addTypesToDict(d, F5KEY, SCA_IInputDevice::KX_F5KEY);
- KX_MACRO_addTypesToDict(d, F6KEY, SCA_IInputDevice::KX_F6KEY);
- KX_MACRO_addTypesToDict(d, F7KEY, SCA_IInputDevice::KX_F7KEY);
- KX_MACRO_addTypesToDict(d, F8KEY, SCA_IInputDevice::KX_F8KEY);
- KX_MACRO_addTypesToDict(d, F9KEY, SCA_IInputDevice::KX_F9KEY);
- KX_MACRO_addTypesToDict(d, F10KEY, SCA_IInputDevice::KX_F10KEY);
- KX_MACRO_addTypesToDict(d, F11KEY, SCA_IInputDevice::KX_F11KEY);
- KX_MACRO_addTypesToDict(d, F12KEY, SCA_IInputDevice::KX_F12KEY);
- KX_MACRO_addTypesToDict(d, F13KEY, SCA_IInputDevice::KX_F13KEY);
- KX_MACRO_addTypesToDict(d, F14KEY, SCA_IInputDevice::KX_F14KEY);
- KX_MACRO_addTypesToDict(d, F15KEY, SCA_IInputDevice::KX_F15KEY);
- KX_MACRO_addTypesToDict(d, F16KEY, SCA_IInputDevice::KX_F16KEY);
- KX_MACRO_addTypesToDict(d, F17KEY, SCA_IInputDevice::KX_F17KEY);
- KX_MACRO_addTypesToDict(d, F18KEY, SCA_IInputDevice::KX_F18KEY);
- KX_MACRO_addTypesToDict(d, F19KEY, SCA_IInputDevice::KX_F19KEY);
-
- KX_MACRO_addTypesToDict(d, OSKEY, SCA_IInputDevice::KX_OSKEY);
-
- KX_MACRO_addTypesToDict(d, PAUSEKEY, SCA_IInputDevice::KX_PAUSEKEY);
- KX_MACRO_addTypesToDict(d, INSERTKEY, SCA_IInputDevice::KX_INSERTKEY);
- KX_MACRO_addTypesToDict(d, HOMEKEY, SCA_IInputDevice::KX_HOMEKEY);
- KX_MACRO_addTypesToDict(d, PAGEUPKEY, SCA_IInputDevice::KX_PAGEUPKEY);
- KX_MACRO_addTypesToDict(d, PAGEDOWNKEY, SCA_IInputDevice::KX_PAGEDOWNKEY);
- KX_MACRO_addTypesToDict(d, ENDKEY, SCA_IInputDevice::KX_ENDKEY);
-
- // MOUSE
- KX_MACRO_addTypesToDict(d, LEFTMOUSE, SCA_IInputDevice::KX_LEFTMOUSE);
- KX_MACRO_addTypesToDict(d, MIDDLEMOUSE, SCA_IInputDevice::KX_MIDDLEMOUSE);
- KX_MACRO_addTypesToDict(d, RIGHTMOUSE, SCA_IInputDevice::KX_RIGHTMOUSE);
- KX_MACRO_addTypesToDict(d, WHEELUPMOUSE, SCA_IInputDevice::KX_WHEELUPMOUSE);
- KX_MACRO_addTypesToDict(d, WHEELDOWNMOUSE, SCA_IInputDevice::KX_WHEELDOWNMOUSE);
- KX_MACRO_addTypesToDict(d, MOUSEX, SCA_IInputDevice::KX_MOUSEX);
- KX_MACRO_addTypesToDict(d, MOUSEY, SCA_IInputDevice::KX_MOUSEY);
-
- // Check for errors
- if (PyErr_Occurred())
- {
- Py_FatalError("can't initialize module GameKeys");
- }
-
- return m;
-}
-
-
-
-/* ------------------------------------------------------------------------- */
-/* Application: application values that remain unchanged during runtime */
-/* ------------------------------------------------------------------------- */
-
-PyDoc_STRVAR(Application_module_documentation,
- "This module contains application values that remain unchanged during runtime."
- );
-
-static struct PyModuleDef Application_module_def = {
- PyModuleDef_HEAD_INIT,
- "bge.app", /* m_name */
- Application_module_documentation, /* m_doc */
- 0, /* m_size */
- NULL, /* m_methods */
- 0, /* m_reload */
- 0, /* m_traverse */
- 0, /* m_clear */
- 0, /* m_free */
-};
-
-PyMODINIT_FUNC initApplicationPythonBinding()
-{
- PyObject *m;
- PyObject *d;
-
- m = PyModule_Create(&Application_module_def);
-
- // Add some symbolic constants to the module
- d = PyModule_GetDict(m);
-
- PyDict_SetItemString(d, "version", Py_BuildValue("(iii)",
- BLENDER_VERSION / 100, BLENDER_VERSION % 100, BLENDER_SUBVERSION));
- PyDict_SetItemString(d, "version_string", PyUnicode_FromFormat("%d.%02d (sub %d)",
- BLENDER_VERSION / 100, BLENDER_VERSION % 100, BLENDER_SUBVERSION));
- PyDict_SetItemString(d, "version_char", PyUnicode_FromString(
- STRINGIFY(BLENDER_VERSION_CHAR)));
-
- PyDict_SetItemString(d, "has_texture_ffmpeg",
-#ifdef WITH_FFMPEG
- Py_True
-#else
- Py_False
-#endif
- );
- PyDict_SetItemString(d, "has_joystick",
-#ifdef WITH_SDL
- Py_True
-#else
- Py_False
-#endif
- );
- PyDict_SetItemString(d, "has_physics",
-#ifdef WITH_BULLET
- Py_True
-#else
- Py_False
-#endif
- );
-
- // Check for errors
- if (PyErr_Occurred()) {
- PyErr_Print();
- PyErr_Clear();
- }
-
- return m;
-}
-
-
-// utility function for loading and saving the globalDict
-int saveGamePythonConfig( char **marshal_buffer)
-{
- int marshal_length = 0;
- PyObject *gameLogic = PyImport_ImportModule("GameLogic");
- if (gameLogic) {
- PyObject *pyGlobalDict = PyDict_GetItemString(PyModule_GetDict(gameLogic), "globalDict"); // Same as importing the module
- if (pyGlobalDict) {
-#ifdef Py_MARSHAL_VERSION
- PyObject *pyGlobalDictMarshal = PyMarshal_WriteObjectToString( pyGlobalDict, 2); // Py_MARSHAL_VERSION == 2 as of Py2.5
-#else
- PyObject *pyGlobalDictMarshal = PyMarshal_WriteObjectToString( pyGlobalDict );
-#endif
- if (pyGlobalDictMarshal) {
- // for testing only
- // PyObject_Print(pyGlobalDictMarshal, stderr, 0);
- char *marshal_cstring;
-
- marshal_cstring = PyBytes_AsString(pyGlobalDictMarshal); // py3 uses byte arrays
- marshal_length= PyBytes_Size(pyGlobalDictMarshal);
- *marshal_buffer = new char[marshal_length + 1];
- memcpy(*marshal_buffer, marshal_cstring, marshal_length);
- Py_DECREF(pyGlobalDictMarshal);
- } else {
- printf("Error, bge.logic.globalDict could not be marshal'd\n");
- }
- } else {
- printf("Error, bge.logic.globalDict was removed\n");
- }
- Py_DECREF(gameLogic);
- } else {
- PyErr_Clear();
- printf("Error, bge.logic failed to import bge.logic.globalDict will be lost\n");
- }
- return marshal_length;
-}
-
-int loadGamePythonConfig(char *marshal_buffer, int marshal_length)
-{
- /* Restore the dict */
- if (marshal_buffer) {
- PyObject *gameLogic = PyImport_ImportModule("GameLogic");
-
- if (gameLogic) {
- PyObject *pyGlobalDict = PyMarshal_ReadObjectFromString(marshal_buffer, marshal_length);
- if (pyGlobalDict) {
- PyObject *pyGlobalDict_orig = PyDict_GetItemString(PyModule_GetDict(gameLogic), "globalDict"); // Same as importing the module.
- if (pyGlobalDict_orig) {
- PyDict_Clear(pyGlobalDict_orig);
- PyDict_Update(pyGlobalDict_orig, pyGlobalDict);
- } else {
- /* this should not happen, but cant find the original globalDict, just assign it then */
- PyDict_SetItemString(PyModule_GetDict(gameLogic), "globalDict", pyGlobalDict); // Same as importing the module.
- }
- Py_DECREF(gameLogic);
- Py_DECREF(pyGlobalDict);
- return 1;
- } else {
- Py_DECREF(gameLogic);
- PyErr_Clear();
- printf("Error could not marshall string\n");
- }
- }
- else {
- PyErr_Clear();
- printf("Error, bge.logic failed to import bge.logic.globalDict will be lost\n");
- }
- }
- return 0;
-}
-
-void pathGamePythonConfig(char *path)
-{
- int len = strlen(gp_GamePythonPathOrig); // Always use the first loaded blend filename
-
- BLI_strncpy(path, gp_GamePythonPathOrig, sizeof(gp_GamePythonPathOrig));
-
- /* replace extension */
- if (BLI_testextensie(path, ".blend")) {
- strcpy(path+(len-6), ".bgeconf");
- } else {
- strcpy(path+len, ".bgeconf");
- }
-}
-
-void setGamePythonPath(const char *path)
-{
- BLI_strncpy(gp_GamePythonPath, path, sizeof(gp_GamePythonPath));
- BLI_cleanup_file(NULL, gp_GamePythonPath); /* not absolutely needed but makes resolving path problems less confusing later */
-
- if (gp_GamePythonPathOrig[0] == '\0')
- BLI_strncpy(gp_GamePythonPathOrig, path, sizeof(gp_GamePythonPathOrig));
-}
-
-// we need this so while blender is open (not blenderplayer)
-// loading new blendfiles will reset this on starting the
-// engine but loading blend files within the BGE wont overwrite gp_GamePythonPathOrig
-void resetGamePythonPath()
-{
- gp_GamePythonPathOrig[0] = '\0';
-}
-
-#endif // WITH_PYTHON
diff --git a/source/gameengine/Ketsji/KX_PythonInit.h b/source/gameengine/Ketsji/KX_PythonInit.h
deleted file mode 100644
index 6550934a916..00000000000
--- a/source/gameengine/Ketsji/KX_PythonInit.h
+++ /dev/null
@@ -1,95 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file KX_PythonInit.h
- * \ingroup ketsji
- */
-
-#ifndef __KX_PYTHONINIT_H__
-#define __KX_PYTHONINIT_H__
-
-#include "EXP_Python.h"
-#include "STR_String.h"
-#include "MT_Vector3.h"
-
-class KX_KetsjiEngine;
-class KX_Scene;
-
-typedef enum {
- psl_Lowest = 0,
- psl_Highest,
-} TPythonSecurityLevel;
-
-extern bool gUseVisibilityTemp;
-
-#ifdef WITH_PYTHON
-PyMODINIT_FUNC initBGE(void);
-PyMODINIT_FUNC initApplicationPythonBinding(void);
-PyMODINIT_FUNC initGameLogicPythonBinding(void);
-PyMODINIT_FUNC initGameKeysPythonBinding(void);
-PyMODINIT_FUNC initRasterizerPythonBinding(void);
-PyMODINIT_FUNC initVideoTexturePythonBinding(void);
-PyObject *initGamePlayerPythonScripting(struct Main *maggie, int argc, char **argv);
-PyObject *initGamePythonScripting(struct Main *maggie);
-
-void exitGamePlayerPythonScripting();
-void exitGamePythonScripting();
-void setupGamePython(KX_KetsjiEngine *ketsjiengine, KX_Scene *startscene, Main *blenderdata,
- PyObject *pyGlobalDict, PyObject **gameLogic, PyObject **gameLogic_keys, int argc, char **argv);
-void setGamePythonPath(const char *path);
-void resetGamePythonPath();
-void pathGamePythonConfig(char *path);
-int saveGamePythonConfig(char **marshal_buffer);
-int loadGamePythonConfig(char *marshal_buffer, int marshal_length);
-#endif
-
-void addImportMain(struct Main *maggie);
-void removeImportMain(struct Main *maggie);
-
-class KX_KetsjiEngine;
-class KX_Scene;
-
-void KX_SetActiveScene(KX_Scene *scene);
-KX_Scene *KX_GetActiveScene();
-KX_KetsjiEngine *KX_GetActiveEngine();
-
-typedef int (*PyNextFrameFunc)(void *);
-
-struct PyNextFrameState {
- /** can be either a GPG_NextFrameState or a BL_KetsjiNextFrameState */
- void *state;
- /** can be either GPG_PyNextFrame or BL_KetsjiPyNextFrame */
- PyNextFrameFunc func;
-};
-extern struct PyNextFrameState pynextframestate;
-
-void KX_RasterizerDrawDebugLine(const MT_Vector3 &from,const MT_Vector3 &to,const MT_Vector3 &color);
-void KX_RasterizerDrawDebugCircle(const MT_Vector3 &center, const MT_Scalar radius, const MT_Vector3 &color,
- const MT_Vector3 &normal, int nsector);
-
-
-#endif /* __KX_PYTHONINIT_H__ */
diff --git a/source/gameengine/Ketsji/KX_PythonInitTypes.cpp b/source/gameengine/Ketsji/KX_PythonInitTypes.cpp
deleted file mode 100644
index 4a999e37f2b..00000000000
--- a/source/gameengine/Ketsji/KX_PythonInitTypes.cpp
+++ /dev/null
@@ -1,286 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): Campbell Barton
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Ketsji/KX_PythonInitTypes.cpp
- * \ingroup ketsji
- */
-
-#ifdef WITH_PYTHON
-
-#include "KX_PythonInitTypes.h"
-
-/* Only for Class::Parents */
-#include "BL_BlenderShader.h"
-#include "BL_ShapeActionActuator.h"
-#include "BL_ArmatureActuator.h"
-#include "BL_ArmatureConstraint.h"
-#include "BL_ArmatureObject.h"
-#include "BL_ArmatureChannel.h"
-#include "KX_WorldInfo.h"
-#include "KX_ArmatureSensor.h"
-#include "KX_BlenderMaterial.h"
-#include "KX_CameraActuator.h"
-#include "KX_CharacterWrapper.h"
-#include "KX_ConstraintActuator.h"
-#include "KX_ConstraintWrapper.h"
-#include "KX_GameActuator.h"
-#include "KX_LibLoadStatus.h"
-#include "KX_Light.h"
-#include "KX_FontObject.h"
-#include "KX_MeshProxy.h"
-#include "KX_MouseFocusSensor.h"
-#include "KX_NetworkMessageActuator.h"
-#include "KX_NetworkMessageSensor.h"
-#include "KX_ObjectActuator.h"
-#include "KX_ParentActuator.h"
-#include "KX_PolyProxy.h"
-#include "KX_SCA_AddObjectActuator.h"
-#include "KX_SCA_EndObjectActuator.h"
-#include "KX_SCA_ReplaceMeshActuator.h"
-#include "KX_SceneActuator.h"
-#include "KX_StateActuator.h"
-#include "KX_SteeringActuator.h"
-#include "KX_TrackToActuator.h"
-#include "KX_VehicleWrapper.h"
-#include "KX_VertexProxy.h"
-#include "SCA_2DFilterActuator.h"
-#include "SCA_ANDController.h"
-#include "SCA_ActuatorSensor.h"
-#include "SCA_AlwaysSensor.h"
-#include "SCA_DelaySensor.h"
-#include "SCA_JoystickSensor.h"
-#include "SCA_KeyboardSensor.h"
-#include "SCA_MouseSensor.h"
-#include "SCA_NANDController.h"
-#include "SCA_NORController.h"
-#include "SCA_ORController.h"
-#include "SCA_RandomSensor.h"
-#include "SCA_XNORController.h"
-#include "SCA_XORController.h"
-#include "SCA_PythonJoystick.h"
-#include "SCA_PythonKeyboard.h"
-#include "SCA_PythonMouse.h"
-#include "KX_NearSensor.h"
-#include "KX_RadarSensor.h"
-#include "KX_RaySensor.h"
-#include "KX_SCA_DynamicActuator.h"
-#include "KX_SoundActuator.h"
-#include "KX_TouchSensor.h"
-#include "KX_VisibilityActuator.h"
-#include "SCA_PropertySensor.h"
-#include "SCA_PythonController.h"
-#include "SCA_RandomActuator.h"
-#include "SCA_IController.h"
-#include "KX_NavMeshObject.h"
-#include "KX_MouseActuator.h"
-#include "EXP_ListWrapper.h"
-
-static void PyType_Attr_Set(PyGetSetDef *attr_getset, PyAttributeDef *attr)
-{
- attr_getset->name= (char *)attr->m_name;
- attr_getset->doc= NULL;
-
- attr_getset->get= reinterpret_cast<getter>(PyObjectPlus::py_get_attrdef);
-
- if (attr->m_access==KX_PYATTRIBUTE_RO)
- attr_getset->set= NULL;
- else
- attr_getset->set= reinterpret_cast<setter>(PyObjectPlus::py_set_attrdef);
-
- attr_getset->closure= reinterpret_cast<void *>(attr);
-}
-
-static void PyType_Ready_ADD(PyObject *dict, PyTypeObject *tp, PyAttributeDef *attributes, PyAttributeDef *attributesPtr, int init_getset)
-{
- PyAttributeDef *attr;
-
- if (init_getset) {
- /* we need to do this for all types before calling PyType_Ready
- * since they will call the parents PyType_Ready and those might not have initialized vars yet */
-
- //if (tp->tp_base==NULL)
- // printf("Debug: No Parents - '%s'\n" , tp->tp_name);
-
- if (tp->tp_getset==NULL && ((attributes && attributes->m_name) || (attributesPtr && attributesPtr->m_name))) {
- PyGetSetDef *attr_getset;
- int attr_tot= 0;
-
- if (attributes) {
- for (attr= attributes; attr->m_name; attr++, attr_tot++)
- attr->m_usePtr = false;
- }
- if (attributesPtr) {
- for (attr= attributesPtr; attr->m_name; attr++, attr_tot++)
- attr->m_usePtr = true;
- }
-
- tp->tp_getset = attr_getset = reinterpret_cast<PyGetSetDef *>(PyMem_Malloc((attr_tot+1) * sizeof(PyGetSetDef))); // XXX - Todo, free
-
- if (attributes) {
- for (attr= attributes; attr->m_name; attr++, attr_getset++) {
- PyType_Attr_Set(attr_getset, attr);
- }
- }
- if (attributesPtr) {
- for (attr= attributesPtr; attr->m_name; attr++, attr_getset++) {
- PyType_Attr_Set(attr_getset, attr);
- }
- }
- memset(attr_getset, 0, sizeof(PyGetSetDef));
- }
- } else {
- PyType_Ready(tp);
- PyDict_SetItemString(dict, tp->tp_name, reinterpret_cast<PyObject *>(tp));
- }
-
-}
-
-
-#define PyType_Ready_Attr(d, n, i) PyType_Ready_ADD(d, &n::Type, n::Attributes, NULL, i)
-#define PyType_Ready_AttrPtr(d, n, i) PyType_Ready_ADD(d, &n::Type, n::Attributes, n::AttributesPtr, i)
-
-
-
-PyDoc_STRVAR(GameTypes_module_documentation,
-"This module provides access to the game engine data types."
-);
-static struct PyModuleDef GameTypes_module_def = {
- PyModuleDef_HEAD_INIT,
- "GameTypes", /* m_name */
- GameTypes_module_documentation, /* m_doc */
- 0, /* m_size */
- NULL, /* m_methods */
- NULL, /* m_reload */
- NULL, /* m_traverse */
- NULL, /* m_clear */
- NULL, /* m_free */
-};
-
-
-PyMODINIT_FUNC initGameTypesPythonBinding(void)
-{
- PyObject *m;
- PyObject *dict;
-
- m = PyModule_Create(&GameTypes_module_def);
- PyDict_SetItemString(PySys_GetObject("modules"), GameTypes_module_def.m_name, m);
-
- dict = PyModule_GetDict(m);
-
- for (int init_getset= 1; init_getset > -1; init_getset--) { /* run twice, once to init the getsets another to run PyType_Ready */
- PyType_Ready_Attr(dict, BL_ActionActuator, init_getset);
- PyType_Ready_Attr(dict, BL_Shader, init_getset);
- PyType_Ready_Attr(dict, BL_ShapeActionActuator, init_getset);
- PyType_Ready_Attr(dict, BL_ArmatureObject, init_getset);
- PyType_Ready_Attr(dict, BL_ArmatureActuator, init_getset);
- PyType_Ready_Attr(dict, BL_ArmatureConstraint, init_getset);
- PyType_Ready_AttrPtr(dict, BL_ArmatureBone, init_getset);
- PyType_Ready_AttrPtr(dict, BL_ArmatureChannel, init_getset);
- // PyType_Ready_Attr(dict, CPropValue, init_getset); // doesn't use Py_Header
- PyType_Ready_Attr(dict, CListValue, init_getset);
- PyType_Ready_Attr(dict, CListWrapper, init_getset);
- PyType_Ready_Attr(dict, CValue, init_getset);
- PyType_Ready_Attr(dict, KX_ArmatureSensor, init_getset);
- PyType_Ready_Attr(dict, KX_BlenderMaterial, init_getset);
- PyType_Ready_Attr(dict, KX_Camera, init_getset);
- PyType_Ready_Attr(dict, KX_CameraActuator, init_getset);
- PyType_Ready_Attr(dict, KX_CharacterWrapper, init_getset);
- PyType_Ready_Attr(dict, KX_ConstraintActuator, init_getset);
- PyType_Ready_Attr(dict, KX_ConstraintWrapper, init_getset);
- PyType_Ready_Attr(dict, KX_GameActuator, init_getset);
- PyType_Ready_Attr(dict, KX_GameObject, init_getset);
- PyType_Ready_Attr(dict, KX_LibLoadStatus, init_getset);
- PyType_Ready_Attr(dict, KX_LightObject, init_getset);
- PyType_Ready_Attr(dict, KX_FontObject, init_getset);
- PyType_Ready_Attr(dict, KX_MeshProxy, init_getset);
- PyType_Ready_Attr(dict, KX_MouseFocusSensor, init_getset);
- PyType_Ready_Attr(dict, KX_NearSensor, init_getset);
- PyType_Ready_Attr(dict, KX_NetworkMessageActuator, init_getset);
- PyType_Ready_Attr(dict, KX_NetworkMessageSensor, init_getset);
- PyType_Ready_Attr(dict, KX_ObjectActuator, init_getset);
- PyType_Ready_Attr(dict, KX_ParentActuator, init_getset);
- PyType_Ready_Attr(dict, KX_PolyProxy, init_getset);
- PyType_Ready_Attr(dict, KX_RadarSensor, init_getset);
- PyType_Ready_Attr(dict, KX_RaySensor, init_getset);
- PyType_Ready_Attr(dict, KX_SCA_AddObjectActuator, init_getset);
- PyType_Ready_Attr(dict, KX_SCA_DynamicActuator, init_getset);
- PyType_Ready_Attr(dict, KX_SCA_EndObjectActuator, init_getset);
- PyType_Ready_Attr(dict, KX_SCA_ReplaceMeshActuator, init_getset);
- PyType_Ready_Attr(dict, KX_Scene, init_getset);
- PyType_Ready_Attr(dict, KX_WorldInfo, init_getset);
- PyType_Ready_Attr(dict, KX_NavMeshObject, init_getset);
- PyType_Ready_Attr(dict, KX_SceneActuator, init_getset);
- PyType_Ready_Attr(dict, KX_SoundActuator, init_getset);
- PyType_Ready_Attr(dict, KX_StateActuator, init_getset);
- PyType_Ready_Attr(dict, KX_SteeringActuator, init_getset);
- PyType_Ready_Attr(dict, KX_TouchSensor, init_getset);
- PyType_Ready_Attr(dict, KX_TrackToActuator, init_getset);
- PyType_Ready_Attr(dict, KX_VehicleWrapper, init_getset);
- PyType_Ready_Attr(dict, KX_VertexProxy, init_getset);
- PyType_Ready_Attr(dict, KX_VisibilityActuator, init_getset);
- PyType_Ready_Attr(dict, KX_MouseActuator, init_getset);
- PyType_Ready_Attr(dict, PyObjectPlus, init_getset);
- PyType_Ready_Attr(dict, SCA_2DFilterActuator, init_getset);
- PyType_Ready_Attr(dict, SCA_ANDController, init_getset);
- // PyType_Ready_Attr(dict, SCA_Actuator, init_getset); // doesn't use Py_Header
- PyType_Ready_Attr(dict, SCA_ActuatorSensor, init_getset);
- PyType_Ready_Attr(dict, SCA_AlwaysSensor, init_getset);
- PyType_Ready_Attr(dict, SCA_DelaySensor, init_getset);
- PyType_Ready_Attr(dict, SCA_ILogicBrick, init_getset);
- PyType_Ready_Attr(dict, SCA_IObject, init_getset);
- PyType_Ready_Attr(dict, SCA_ISensor, init_getset);
- PyType_Ready_Attr(dict, SCA_JoystickSensor, init_getset);
- PyType_Ready_Attr(dict, SCA_KeyboardSensor, init_getset);
- PyType_Ready_Attr(dict, SCA_MouseSensor, init_getset);
- PyType_Ready_Attr(dict, SCA_NANDController, init_getset);
- PyType_Ready_Attr(dict, SCA_NORController, init_getset);
- PyType_Ready_Attr(dict, SCA_ORController, init_getset);
- PyType_Ready_Attr(dict, SCA_PropertyActuator, init_getset);
- PyType_Ready_Attr(dict, SCA_PropertySensor, init_getset);
- PyType_Ready_Attr(dict, SCA_PythonController, init_getset);
- PyType_Ready_Attr(dict, SCA_RandomActuator, init_getset);
- PyType_Ready_Attr(dict, SCA_RandomSensor, init_getset);
- PyType_Ready_Attr(dict, SCA_XNORController, init_getset);
- PyType_Ready_Attr(dict, SCA_XORController, init_getset);
- PyType_Ready_Attr(dict, SCA_IController, init_getset);
- PyType_Ready_Attr(dict, SCA_PythonJoystick, init_getset);
- PyType_Ready_Attr(dict, SCA_PythonKeyboard, init_getset);
- PyType_Ready_Attr(dict, SCA_PythonMouse, init_getset);
- }
-
-#ifdef USE_MATHUTILS
- /* Init mathutils callbacks */
- KX_GameObject_Mathutils_Callback_Init();
- KX_ObjectActuator_Mathutils_Callback_Init();
- KX_WorldInfo_Mathutils_Callback_Init();
- KX_BlenderMaterial_Mathutils_Callback_Init();
-#endif
-
- return m;
-}
-
-#endif // WITH_PYTHON
diff --git a/source/gameengine/Ketsji/KX_PythonInitTypes.h b/source/gameengine/Ketsji/KX_PythonInitTypes.h
deleted file mode 100644
index cfc49a1dc93..00000000000
--- a/source/gameengine/Ketsji/KX_PythonInitTypes.h
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): Campbell Barton
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file KX_PythonInitTypes.h
- * \ingroup ketsji
- */
-
-#ifndef __KX_PYTHON_INIT_TYPES__
-#define __KX_PYTHON_INIT_TYPES__
-
-#ifdef WITH_PYTHON
-#include <Python.h>
-PyMODINIT_FUNC initGameTypesPythonBinding(void);
-#endif
-
-#endif /* __KX_PYTHON_INIT_TYPES__ */
diff --git a/source/gameengine/Ketsji/KX_PythonMain.cpp b/source/gameengine/Ketsji/KX_PythonMain.cpp
deleted file mode 100644
index 740bb102fd9..00000000000
--- a/source/gameengine/Ketsji/KX_PythonMain.cpp
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * Contributor(s): Benoit Bolsee
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Ketsji/KX_PythonMain.cpp
- * \ingroup ketsji
- */
-
-#include "KX_PythonMain.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#include <stddef.h>
-
-#include "MEM_guardedalloc.h"
-
-#include "BLI_string.h"
-#include "BLI_listbase.h"
-
-#include "BKE_text.h"
-#include "BKE_main.h"
-#include "BKE_idprop.h"
-
-
-#ifdef __cplusplus
-}
-#endif
-
-extern "C" char *KX_GetPythonMain(struct Scene *scene)
-{
- /* examine custom scene properties */
- if (scene->id.properties) {
- IDProperty *item = IDP_GetPropertyTypeFromGroup(scene->id.properties, "__main__", IDP_STRING);
- if (item) {
- return BLI_strdup(IDP_String(item));
- }
- }
-
- return NULL;
-}
-
-extern "C" char *KX_GetPythonCode(Main *bmain, char *python_main)
-{
- Text *text;
-
- if ((text = (Text *)BLI_findstring(&bmain->text, python_main, offsetof(ID, name) + 2))) {
- return txt_to_buf(text);
- }
-
- return NULL;
-}
diff --git a/source/gameengine/Ketsji/KX_PythonMain.h b/source/gameengine/Ketsji/KX_PythonMain.h
deleted file mode 100644
index c627a4a147a..00000000000
--- a/source/gameengine/Ketsji/KX_PythonMain.h
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file KX_PythonMain.h
- * \ingroup ketsji
- */
-
-#ifndef __KX_PYTHON_MAIN__
-#define __KX_PYTHON_MAIN__
-
-#include "BLI_sys_types.h"
-#include "BKE_main.h"
-#include "DNA_scene_types.h"
-extern "C" char *KX_GetPythonMain(struct Scene* scene);
-extern "C" char *KX_GetPythonCode(struct Main *main, char *python_main);
-
-#endif /* __KX_PYTHON_MAIN__ */
diff --git a/source/gameengine/Ketsji/KX_RadarSensor.cpp b/source/gameengine/Ketsji/KX_RadarSensor.cpp
deleted file mode 100644
index 861e3f70296..00000000000
--- a/source/gameengine/Ketsji/KX_RadarSensor.cpp
+++ /dev/null
@@ -1,230 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Ketsji/KX_RadarSensor.cpp
- * \ingroup ketsji
- */
-
-
-#include "KX_RadarSensor.h"
-#include "KX_GameObject.h"
-#include "KX_PyMath.h"
-#include "PHY_IPhysicsController.h"
-#include "PHY_IMotionState.h"
-#include "DNA_sensor_types.h"
-
-/**
- * RadarSensor constructor. Creates a near-sensor derived class, with a cone collision shape.
- */
-KX_RadarSensor::KX_RadarSensor(SCA_EventManager* eventmgr,
- KX_GameObject* gameobj,
- PHY_IPhysicsController* physCtrl,
- double coneradius,
- double coneheight,
- int axis,
- double margin,
- double resetmargin,
- bool bFindMaterial,
- const STR_String& touchedpropname)
-
- : KX_NearSensor(
- eventmgr,
- gameobj,
- //DT_NewCone(coneradius,coneheight),
- margin,
- resetmargin,
- bFindMaterial,
- touchedpropname,
- physCtrl),
-
- m_coneradius(coneradius),
- m_coneheight(coneheight),
- m_axis(axis)
-{
- m_client_info->m_type = KX_ClientObjectInfo::SENSOR;
- //m_client_info->m_clientobject = gameobj;
- //m_client_info->m_auxilary_info = NULL;
- //sumoObj->setClientObject(&m_client_info);
-}
-
-KX_RadarSensor::~KX_RadarSensor()
-{
-
-}
-
-CValue* KX_RadarSensor::GetReplica()
-{
- KX_RadarSensor* replica = new KX_RadarSensor(*this);
- replica->ProcessReplica();
- return replica;
-}
-
-/**
- * Transforms the collision object. A cone is not correctly centered
- * for usage. */
-void KX_RadarSensor::SynchronizeTransform()
-{
- // Getting the parent location was commented out. Why?
- MT_Transform trans;
- trans.setOrigin(((KX_GameObject*)GetParent())->NodeGetWorldPosition());
- trans.setBasis(((KX_GameObject*)GetParent())->NodeGetWorldOrientation());
- // What is the default orientation? pointing in the -y direction?
- // is the geometry correctly converted?
-
- // a collision cone is oriented
- // center the cone correctly
- // depends on the radar 'axis'
- switch (m_axis)
- {
- case SENS_RADAR_X_AXIS: // +X Axis
- {
- MT_Quaternion rotquatje(MT_Vector3(0,0,1),MT_radians(90));
- trans.rotate(rotquatje);
- trans.translate(MT_Vector3 (0, -m_coneheight/2.0f, 0));
- break;
- };
- case SENS_RADAR_Y_AXIS: // +Y Axis
- {
- MT_Quaternion rotquatje(MT_Vector3(1,0,0),MT_radians(-180));
- trans.rotate(rotquatje);
- trans.translate(MT_Vector3 (0, -m_coneheight/2.0f, 0));
- break;
- };
- case SENS_RADAR_Z_AXIS: // +Z Axis
- {
- MT_Quaternion rotquatje(MT_Vector3(1,0,0),MT_radians(-90));
- trans.rotate(rotquatje);
- trans.translate(MT_Vector3 (0, -m_coneheight/2.0f, 0));
- break;
- };
- case SENS_RADAR_NEG_X_AXIS: // -X Axis
- {
- MT_Quaternion rotquatje(MT_Vector3(0,0,1),MT_radians(-90));
- trans.rotate(rotquatje);
- trans.translate(MT_Vector3 (0, -m_coneheight/2.0f, 0));
- break;
- };
- case SENS_RADAR_NEG_Y_AXIS: // -Y Axis
- {
- //MT_Quaternion rotquatje(MT_Vector3(1,0,0),MT_radians(-180));
- //trans.rotate(rotquatje);
- trans.translate(MT_Vector3 (0, -m_coneheight/2.0f, 0));
- break;
- };
- case SENS_RADAR_NEG_Z_AXIS: // -Z Axis
- {
- MT_Quaternion rotquatje(MT_Vector3(1,0,0),MT_radians(90));
- trans.rotate(rotquatje);
- trans.translate(MT_Vector3 (0, -m_coneheight/2.0f, 0));
- break;
- };
- default:
- {
- }
- }
-
- //Using a temp variable to translate MT_Point3 to float[3].
- //float[3] works better for the Python interface.
- MT_Point3 temp = trans.getOrigin();
- m_cone_origin[0] = temp[0];
- m_cone_origin[1] = temp[1];
- m_cone_origin[2] = temp[2];
-
- temp = trans(MT_Point3(0, -m_coneheight/2.0f, 0));
- m_cone_target[0] = temp[0];
- m_cone_target[1] = temp[1];
- m_cone_target[2] = temp[2];
-
-
- if (m_physCtrl)
- {
- PHY_IMotionState* motionState = m_physCtrl->GetMotionState();
- const MT_Point3& pos = trans.getOrigin();
- float ori[12];
- trans.getBasis().getValue(ori);
- motionState->SetWorldPosition(pos[0], pos[1], pos[2]);
- motionState->SetWorldOrientation(ori);
- m_physCtrl->WriteMotionStateToDynamics(true);
- }
-
-}
-
-/* ------------------------------------------------------------------------- */
-/* Python Functions */
-/* ------------------------------------------------------------------------- */
-
-#ifdef WITH_PYTHON
-
-/* ------------------------------------------------------------------------- */
-/* Python Integration Hooks */
-/* ------------------------------------------------------------------------- */
-PyTypeObject KX_RadarSensor::Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "KX_RadarSensor",
- sizeof(PyObjectPlus_Proxy),
- 0,
- py_base_dealloc,
- 0,
- 0,
- 0,
- 0,
- py_base_repr,
- 0,0,0,0,0,0,0,0,0,
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
- 0,0,0,0,0,0,0,
- Methods,
- 0,
- 0,
- &KX_NearSensor::Type,
- 0,0,0,0,0,0,
- py_base_new
-};
-
-PyMethodDef KX_RadarSensor::Methods[] = {
- {NULL} //Sentinel
-};
-
-PyAttributeDef KX_RadarSensor::Attributes[] = {
- KX_PYATTRIBUTE_FLOAT_ARRAY_RO("coneOrigin", KX_RadarSensor, m_cone_origin, 3),
- KX_PYATTRIBUTE_FLOAT_ARRAY_RO("coneTarget", KX_RadarSensor, m_cone_target, 3),
- KX_PYATTRIBUTE_FLOAT_RO("distance", KX_RadarSensor, m_coneheight),
- KX_PYATTRIBUTE_RO_FUNCTION("angle", KX_RadarSensor, pyattr_get_angle),
- KX_PYATTRIBUTE_INT_RW("axis", 0, 5, true, KX_RadarSensor, m_axis),
- {NULL} //Sentinel
-};
-
-PyObject *KX_RadarSensor::pyattr_get_angle(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_RadarSensor* self = static_cast<KX_RadarSensor*>(self_v);
-
- // The original angle from the gui was converted, so we recalculate the value here to maintain
- // consistency between Python and the gui
- return PyFloat_FromDouble(MT_degrees(atan(self->m_coneradius / self->m_coneheight)) * 2);
-
-}
-
-#endif // WITH_PYTHON
diff --git a/source/gameengine/Ketsji/KX_RadarSensor.h b/source/gameengine/Ketsji/KX_RadarSensor.h
deleted file mode 100644
index 6a2d50ffa3a..00000000000
--- a/source/gameengine/Ketsji/KX_RadarSensor.h
+++ /dev/null
@@ -1,100 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file KX_RadarSensor.h
- * \ingroup ketsji
- */
-
-#ifndef __KX_RADARSENSOR_H__
-#define __KX_RADARSENSOR_H__
-
-#include "KX_NearSensor.h"
-#include "MT_Point3.h"
-
-/**
- * Radar 'cone' sensor. Very similar to a near-sensor, but instead of a sphere, a cone is used.
- */
-class KX_RadarSensor : public KX_NearSensor
-{
- protected:
- Py_Header
-
- float m_coneradius;
-
- /**
- * Height of the cone.
- */
- float m_coneheight;
- int m_axis;
-
- /**
- * The previous position of the origin of the cone.
- */
- float m_cone_origin[3];
-
- /**
- * The previous direction of the cone (origin to bottom plane).
- */
- float m_cone_target[3];
-
-public:
-
- KX_RadarSensor(SCA_EventManager* eventmgr,
- KX_GameObject* gameobj,
- PHY_IPhysicsController* physCtrl,
- double coneradius,
- double coneheight,
- int axis,
- double margin,
- double resetmargin,
- bool bFindMaterial,
- const STR_String& touchedpropname);
- KX_RadarSensor();
- virtual ~KX_RadarSensor();
- virtual void SynchronizeTransform();
- virtual CValue* GetReplica();
-
- /* --------------------------------------------------------------------- */
- /* Python interface ---------------------------------------------------- */
- /* --------------------------------------------------------------------- */
- enum RadarAxis {
- KX_RADAR_AXIS_POS_X = 0,
- KX_RADAR_AXIS_POS_Y,
- KX_RADAR_AXIS_POS_Z,
- KX_RADAR_AXIS_NEG_X,
- KX_RADAR_AXIS_NEG_Y,
- KX_RADAR_AXIS_NEG_Z
- };
-
- virtual sensortype GetSensorType() { return ST_RADAR; }
- /* python */
-#ifdef WITH_PYTHON
- static PyObject* pyattr_get_angle(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
-#endif
-};
-
-#endif /* __KX_RADARSENSOR_H__ */
diff --git a/source/gameengine/Ketsji/KX_RayCast.cpp b/source/gameengine/Ketsji/KX_RayCast.cpp
deleted file mode 100644
index 478019c6304..00000000000
--- a/source/gameengine/Ketsji/KX_RayCast.cpp
+++ /dev/null
@@ -1,121 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- * KX_MouseFocusSensor determines mouse in/out/over events.
- */
-
-/** \file gameengine/Ketsji/KX_RayCast.cpp
- * \ingroup ketsji
- */
-
-
-#include <stdlib.h>
-#include <stdio.h>
-
-#include "KX_RayCast.h"
-
-#include "MT_Point3.h"
-#include "MT_Vector3.h"
-
-#include "PHY_IPhysicsEnvironment.h"
-#include "PHY_IPhysicsController.h"
-
-KX_RayCast::KX_RayCast(PHY_IPhysicsController* ignoreController, bool faceNormal, bool faceUV)
- :PHY_IRayCastFilterCallback(ignoreController, faceNormal, faceUV)
-{
-}
-
-void KX_RayCast::reportHit(PHY_RayCastResult* result)
-{
- m_hitFound = true;
- m_hitPoint = MT_Vector3(result->m_hitPoint);
- m_hitNormal = MT_Vector3(result->m_hitNormal);
- m_hitUVOK = result->m_hitUVOK;
- m_hitUV = MT_Vector2(result->m_hitUV);
- m_hitMesh = result->m_meshObject;
- m_hitPolygon = result->m_polygon;
-}
-
-bool KX_RayCast::RayTest(PHY_IPhysicsEnvironment* physics_environment, const MT_Point3& _frompoint, const MT_Point3& topoint, KX_RayCast& callback)
-{
- if (physics_environment==NULL) return false; /* prevents crashing in some cases */
-
- // Loops over all physics objects between frompoint and topoint,
- // calling callback.RayHit for each one.
- //
- // callback.RayHit should return true to stop looking, or false to continue.
- //
- // returns true if an object was found, false if not.
-
- MT_Point3 frompoint(_frompoint);
- const MT_Vector3 todir( (topoint - frompoint).safe_normalized() );
- MT_Point3 prevpoint(_frompoint+todir*(-1.f));
-
- PHY_IPhysicsController* hit_controller;
-
- while ((hit_controller = physics_environment->RayTest(callback,
- frompoint.x(),frompoint.y(),frompoint.z(),
- topoint.x(),topoint.y(),topoint.z())) != NULL)
- {
- KX_ClientObjectInfo *info = static_cast<KX_ClientObjectInfo*>(hit_controller->GetNewClientInfo());
-
- if (!info)
- {
- printf("no info!\n");
- MT_assert(info && "Physics controller with no client object info");
- break;
- }
-
- // The biggest danger to endless loop, prevent this by checking that the
- // hit point always progresses along the ray direction..
- prevpoint -= callback.m_hitPoint;
- if (prevpoint.length2() < MT_EPSILON)
- break;
-
- if (callback.RayHit(info))
- // caller may decide to stop the loop and still cancel the hit
- return callback.m_hitFound;
-
- // Skip past the object and keep tracing.
- // Note that retrieving in a single shot multiple hit points would be possible
- // but it would require some change in Bullet.
- prevpoint = callback.m_hitPoint;
- /* We add 0.001 of fudge, so that if the margin && radius == 0.0, we don't endless loop. */
- MT_Scalar marg = 0.001f + hit_controller->GetMargin();
- marg *= 2.f;
- /* Calculate the other side of this object */
- MT_Scalar h = MT_abs(todir.dot(callback.m_hitNormal));
- if (h <= 0.01f)
- // the normal is almost orthogonal to the ray direction, cannot compute the other side
- break;
- marg /= h;
- frompoint = callback.m_hitPoint + marg * todir;
- // verify that we are not passed the to point
- if ((topoint - frompoint).dot(todir) < 0.f)
- break;
- }
- return false;
-}
-
diff --git a/source/gameengine/Ketsji/KX_RayCast.h b/source/gameengine/Ketsji/KX_RayCast.h
deleted file mode 100644
index c977fb8f385..00000000000
--- a/source/gameengine/Ketsji/KX_RayCast.h
+++ /dev/null
@@ -1,149 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file KX_RayCast.h
- * \ingroup ketsji
- */
-
-#ifndef __KX_RAYCAST_H__
-#define __KX_RAYCAST_H__
-
-#include "PHY_IPhysicsEnvironment.h"
-#include "PHY_IPhysicsController.h"
-#include "MT_Vector2.h"
-#include "MT_Point3.h"
-#include "MT_Vector3.h"
-
-class RAS_MeshObject;
-struct KX_ClientObjectInfo;
-
-/**
- * Defines a function for doing a ray cast.
- *
- * eg KX_RayCast::RayTest(ignore_physics_controller, physics_environment, frompoint, topoint, result_point, result_normal, KX_RayCast::Callback<MyClass, MyDataClass>(this, data)
- *
- * Calls myclass->NeedRayCast(client, data) for all client in environment
- * and myclass->RayHit(client, hit_point, hit_normal, data) for all client
- * between frompoint and topoint
- *
- * myclass->NeedRayCast should return true to ray test the current client.
- *
- * myclass->RayHit should return true to end the raycast, false to ignore the current client and to continue.
- *
- * Returns true if a client was accepted, false if nothing found.
- */
-class KX_RayCast : public PHY_IRayCastFilterCallback
-{
-public:
- bool m_hitFound;
- MT_Point3 m_hitPoint;
- MT_Vector3 m_hitNormal;
- const RAS_MeshObject* m_hitMesh;
- int m_hitPolygon;
- int m_hitUVOK; // !=0 if UV coordinate in m_hitUV is valid
- MT_Vector2 m_hitUV;
-
- KX_RayCast(PHY_IPhysicsController* ignoreController, bool faceNormal, bool faceUV);
- virtual ~KX_RayCast() {}
-
- /**
- * The physic environment returns the ray casting result through this function
- */
- virtual void reportHit(PHY_RayCastResult* result);
-
- /** ray test callback.
- * either override this in your class, or use a callback wrapper.
- */
- virtual bool RayHit(KX_ClientObjectInfo* client) = 0;
-
- /**
- * Callback wrapper.
- *
- * Construct with KX_RayCast::Callback<MyClass, MyDataClass>(this, data)
- * and pass to KX_RayCast::RayTest
- */
- template<class T, class dataT> class Callback;
-
- /// Public interface.
- /// Implement bool RayHit in your class to receive ray callbacks.
- static bool RayTest(
- PHY_IPhysicsEnvironment* physics_environment,
- const MT_Point3& frompoint,
- const MT_Point3& topoint,
- KX_RayCast& callback);
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:KX_RayCast")
-#endif
-};
-
-template<class T, class dataT>
-class KX_RayCast::Callback : public KX_RayCast
-{
- T *self;
- /**
- * Some user info passed as argument in constructor.
- * It contains all info needed to check client in NeedRayCast
- * and RayHit.
- */
- dataT *data;
-public:
- Callback(T *_self, PHY_IPhysicsController *controller = NULL, dataT *_data = NULL, bool faceNormal = false, bool faceUV = false)
- : KX_RayCast(controller, faceNormal, faceUV),
- self(_self),
- data(_data)
- {
- }
-
- ~Callback() {}
-
- virtual bool RayHit(KX_ClientObjectInfo* client)
- {
- return self->RayHit(client, this, data);
- }
-
- virtual bool needBroadphaseRayCast(PHY_IPhysicsController* controller)
- {
- KX_ClientObjectInfo* info = static_cast<KX_ClientObjectInfo*>(controller->GetNewClientInfo());
-
- if (!info)
- {
- MT_assert(info && "Physics controller with no client object info");
- return false;
- }
- return self->NeedRayCast(info, data);
- }
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:KX_RayCast::Callback")
-#endif
-};
-
-
-#endif
diff --git a/source/gameengine/Ketsji/KX_RayEventManager.cpp b/source/gameengine/Ketsji/KX_RayEventManager.cpp
deleted file mode 100644
index 661c7eb6f64..00000000000
--- a/source/gameengine/Ketsji/KX_RayEventManager.cpp
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * Manager for ray events
- *
- *
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Ketsji/KX_RayEventManager.cpp
- * \ingroup ketsji
- */
-
-#include "KX_RayEventManager.h"
-#include "SCA_LogicManager.h"
-#include "SCA_ISensor.h"
-#include <vector>
-
-using namespace std;
-
-#include <iostream>
-#include <stdio.h>
-
-void KX_RayEventManager::NextFrame()
-{
- SG_DList::iterator<SCA_ISensor> it(m_sensors);
- for (it.begin();!it.end();++it)
- {
- (*it)->Activate(m_logicmgr);
- }
-}
-
diff --git a/source/gameengine/Ketsji/KX_RayEventManager.h b/source/gameengine/Ketsji/KX_RayEventManager.h
deleted file mode 100644
index 07506b9e32b..00000000000
--- a/source/gameengine/Ketsji/KX_RayEventManager.h
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file KX_RayEventManager.h
- * \ingroup ketsji
- * \brief Manager for ray events
- */
-
-#ifndef __KX_RAYEVENTMANAGER_H__
-#define __KX_RAYEVENTMANAGER_H__
-#include "SCA_EventManager.h"
-#include <vector>
-using namespace std;
-
-class KX_RayEventManager : public SCA_EventManager
-{
-public:
- KX_RayEventManager(class SCA_LogicManager* logicmgr)
- : SCA_EventManager(logicmgr, RAY_EVENTMGR)
- {}
- virtual void NextFrame();
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:KX_RayEventManager")
-#endif
-};
-
-#endif /* __KX_RAYEVENTMANAGER_H__ */
diff --git a/source/gameengine/Ketsji/KX_RaySensor.cpp b/source/gameengine/Ketsji/KX_RaySensor.cpp
deleted file mode 100644
index 4ffb5f332db..00000000000
--- a/source/gameengine/Ketsji/KX_RaySensor.cpp
+++ /dev/null
@@ -1,383 +0,0 @@
-/*
- * Cast a ray and feel for objects
- *
- *
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Ketsji/KX_RaySensor.cpp
- * \ingroup ketsji
- */
-
-
-#include "KX_RaySensor.h"
-#include "SCA_EventManager.h"
-#include "SCA_RandomEventManager.h"
-#include "SCA_LogicManager.h"
-#include "SCA_IObject.h"
-#include "KX_ClientObjectInfo.h"
-#include "KX_GameObject.h"
-#include "KX_Scene.h"
-#include "KX_RayCast.h"
-#include "KX_PyMath.h"
-#include "PHY_IPhysicsEnvironment.h"
-#include "PHY_IPhysicsController.h"
-#include "DNA_sensor_types.h"
-#include "RAS_MeshObject.h"
-
-#include <stdio.h>
-
-
-KX_RaySensor::KX_RaySensor(class SCA_EventManager* eventmgr,
- SCA_IObject* gameobj,
- const STR_String& propname,
- bool bFindMaterial,
- bool bXRay,
- double distance,
- int axis,
- KX_Scene* ketsjiScene)
- : SCA_ISensor(gameobj,eventmgr),
- m_propertyname(propname),
- m_bFindMaterial(bFindMaterial),
- m_bXRay(bXRay),
- m_distance(distance),
- m_scene(ketsjiScene),
- m_axis(axis),
- m_hitMaterial("")
-{
- Init();
-}
-
-void KX_RaySensor::Init()
-{
- m_bTriggered = (m_invert)?true:false;
- m_rayHit = false;
- m_hitObject = NULL;
- m_reset = true;
-}
-
-KX_RaySensor::~KX_RaySensor()
-{
- /* Nothing to be done here. */
-}
-
-
-
-CValue* KX_RaySensor::GetReplica()
-{
- KX_RaySensor* replica = new KX_RaySensor(*this);
- replica->ProcessReplica();
- replica->Init();
-
- return replica;
-}
-
-
-
-bool KX_RaySensor::IsPositiveTrigger()
-{
- bool result = m_rayHit;
-
- if (m_invert)
- result = !result;
-
- return result;
-}
-
-bool KX_RaySensor::RayHit(KX_ClientObjectInfo *client, KX_RayCast *result, void *UNUSED(data))
-{
-
- KX_GameObject* hitKXObj = client->m_gameobject;
- bool bFound = false;
- bool hitMaterial = false;
-
- if (m_propertyname.Length() == 0)
- {
- bFound = true;
- }
- else
- {
- if (m_bFindMaterial) {
- for (unsigned int i = 0; i < hitKXObj->GetMeshCount(); ++i) {
- RAS_MeshObject *meshObj = hitKXObj->GetMesh(i);
- for (unsigned int j = 0; j < meshObj->NumMaterials(); ++j) {
- bFound = strcmp(m_propertyname.ReadPtr(), meshObj->GetMaterialName(j).ReadPtr() + 2) == 0;
- if (bFound) {
- hitMaterial = true;
- break;
- }
- }
- }
- }
- else {
- bFound = hitKXObj->GetProperty(m_propertyname) != NULL;
- }
- }
-
- if (bFound)
- {
- m_rayHit = true;
- m_hitObject = hitKXObj;
- m_hitPosition[0] = result->m_hitPoint[0];
- m_hitPosition[1] = result->m_hitPoint[1];
- m_hitPosition[2] = result->m_hitPoint[2];
-
- m_hitNormal[0] = result->m_hitNormal[0];
- m_hitNormal[1] = result->m_hitNormal[1];
- m_hitNormal[2] = result->m_hitNormal[2];
-
- m_hitMaterial = hitMaterial;
- }
- // no multi-hit search yet
- return true;
-}
-
-/* this function is used to pre-filter the object before casting the ray on them.
- * This is useful for "X-Ray" option when we want to see "through" unwanted object.
- */
-bool KX_RaySensor::NeedRayCast(KX_ClientObjectInfo *client, void *UNUSED(data))
-{
- KX_GameObject *hitKXObj = client->m_gameobject;
-
- if (client->m_type > KX_ClientObjectInfo::ACTOR)
- {
- // Unknown type of object, skip it.
- // Should not occur as the sensor objects are filtered in RayTest()
- printf("Invalid client type %d found ray casting\n", client->m_type);
- return false;
- }
- if (m_bXRay && m_propertyname.Length() != 0)
- {
- if (m_bFindMaterial) {
- bool found = false;
- for (unsigned int i = 0; i < hitKXObj->GetMeshCount(); ++i) {
- RAS_MeshObject *meshObj = hitKXObj->GetMesh(i);
- for (unsigned int j = 0; j < meshObj->NumMaterials(); ++j) {
- found = strcmp(m_propertyname.ReadPtr(), meshObj->GetMaterialName(j).ReadPtr() + 2) == 0;
- if (found)
- break;
- }
- }
- if (!found)
- return false;
- }
- else {
- if (hitKXObj->GetProperty(m_propertyname) == NULL)
- return false;
- }
- }
- return true;
-}
-
-bool KX_RaySensor::Evaluate()
-{
- bool result = false;
- bool reset = m_reset && m_level;
- m_rayHit = false;
- m_hitObject = NULL;
- m_hitPosition[0] = 0;
- m_hitPosition[1] = 0;
- m_hitPosition[2] = 0;
-
- m_hitNormal[0] = 1;
- m_hitNormal[1] = 0;
- m_hitNormal[2] = 0;
-
- KX_GameObject* obj = (KX_GameObject*)GetParent();
- MT_Point3 frompoint = obj->NodeGetWorldPosition();
- MT_Matrix3x3 matje = obj->NodeGetWorldOrientation();
- MT_Matrix3x3 invmat = matje.inverse();
-
- MT_Vector3 todir;
- m_reset = false;
- switch (m_axis)
- {
- case SENS_RAY_X_AXIS: // X
- {
- todir[0] = invmat[0][0];
- todir[1] = invmat[0][1];
- todir[2] = invmat[0][2];
- break;
- }
- case SENS_RAY_Y_AXIS: // Y
- {
- todir[0] = invmat[1][0];
- todir[1] = invmat[1][1];
- todir[2] = invmat[1][2];
- break;
- }
- case SENS_RAY_Z_AXIS: // Z
- {
- todir[0] = invmat[2][0];
- todir[1] = invmat[2][1];
- todir[2] = invmat[2][2];
- break;
- }
- case SENS_RAY_NEG_X_AXIS: // -X
- {
- todir[0] = -invmat[0][0];
- todir[1] = -invmat[0][1];
- todir[2] = -invmat[0][2];
- break;
- }
- case SENS_RAY_NEG_Y_AXIS: // -Y
- {
- todir[0] = -invmat[1][0];
- todir[1] = -invmat[1][1];
- todir[2] = -invmat[1][2];
- break;
- }
- case SENS_RAY_NEG_Z_AXIS: // -Z
- {
- todir[0] = -invmat[2][0];
- todir[1] = -invmat[2][1];
- todir[2] = -invmat[2][2];
- break;
- }
- }
- todir.normalize();
- m_rayDirection[0] = todir[0];
- m_rayDirection[1] = todir[1];
- m_rayDirection[2] = todir[2];
-
- MT_Point3 topoint = frompoint + (m_distance) * todir;
- PHY_IPhysicsEnvironment* pe = m_scene->GetPhysicsEnvironment();
-
- if (!pe)
- {
- std::cout << "WARNING: Ray sensor " << GetName() << ": There is no physics environment!" << std::endl;
- std::cout << " Check universe for malfunction." << std::endl;
- return false;
- }
-
- PHY_IPhysicsController *spc = obj->GetPhysicsController();
- KX_GameObject *parent = obj->GetParent();
- if (!spc && parent)
- spc = parent->GetPhysicsController();
-
-
- PHY_IPhysicsEnvironment* physics_environment = this->m_scene->GetPhysicsEnvironment();
-
-
- KX_RayCast::Callback<KX_RaySensor, void> callback(this, spc);
- KX_RayCast::RayTest(physics_environment, frompoint, topoint, callback);
-
- /* now pass this result to some controller */
-
- if (m_rayHit)
- {
- if (!m_bTriggered)
- {
- // notify logicsystem that ray is now hitting
- result = true;
- m_bTriggered = true;
- }
- else
- {
- // notify logicsystem that ray is STILL hitting ...
- result = false;
-
- }
- }
- else
- {
- if (m_bTriggered)
- {
- m_bTriggered = false;
- // notify logicsystem that ray JUST left the Object
- result = true;
- }
- else
- {
- result = false;
- }
-
- }
- if (reset)
- // force an event
- result = true;
-
- return result;
-}
-
-#ifdef WITH_PYTHON
-
-/* ------------------------------------------------------------------------- */
-/* Python functions */
-/* ------------------------------------------------------------------------- */
-
-/* Integration hooks ------------------------------------------------------- */
-PyTypeObject KX_RaySensor::Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "KX_RaySensor",
- sizeof(PyObjectPlus_Proxy),
- 0,
- py_base_dealloc,
- 0,
- 0,
- 0,
- 0,
- py_base_repr,
- 0,0,0,0,0,0,0,0,0,
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
- 0,0,0,0,0,0,0,
- Methods,
- 0,
- 0,
- &SCA_ISensor::Type,
- 0,0,0,0,0,0,
- py_base_new
-
-};
-
-PyMethodDef KX_RaySensor::Methods[] = {
- {NULL,NULL} //Sentinel
-};
-
-PyAttributeDef KX_RaySensor::Attributes[] = {
- KX_PYATTRIBUTE_BOOL_RW("useMaterial", KX_RaySensor, m_bFindMaterial),
- KX_PYATTRIBUTE_BOOL_RW("useXRay", KX_RaySensor, m_bXRay),
- KX_PYATTRIBUTE_FLOAT_RW("range", 0, 10000, KX_RaySensor, m_distance),
- KX_PYATTRIBUTE_STRING_RW("propName", 0, MAX_PROP_NAME, false, KX_RaySensor, m_propertyname),
- KX_PYATTRIBUTE_INT_RW("axis", 0, 5, true, KX_RaySensor, m_axis),
- KX_PYATTRIBUTE_FLOAT_ARRAY_RO("hitPosition", KX_RaySensor, m_hitPosition, 3),
- KX_PYATTRIBUTE_FLOAT_ARRAY_RO("rayDirection", KX_RaySensor, m_rayDirection, 3),
- KX_PYATTRIBUTE_FLOAT_ARRAY_RO("hitNormal", KX_RaySensor, m_hitNormal, 3),
- KX_PYATTRIBUTE_STRING_RO("hitMaterial", KX_RaySensor, m_hitMaterial),
- KX_PYATTRIBUTE_RO_FUNCTION("hitObject", KX_RaySensor, pyattr_get_hitobject),
- { NULL } //Sentinel
-};
-
-PyObject *KX_RaySensor::pyattr_get_hitobject(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_RaySensor* self = static_cast<KX_RaySensor*>(self_v);
- if (self->m_hitObject)
- return self->m_hitObject->GetProxy();
-
- Py_RETURN_NONE;
-}
-
-#endif // WITH_PYTHON
diff --git a/source/gameengine/Ketsji/KX_RaySensor.h b/source/gameengine/Ketsji/KX_RaySensor.h
deleted file mode 100644
index 1901bb04f86..00000000000
--- a/source/gameengine/Ketsji/KX_RaySensor.h
+++ /dev/null
@@ -1,109 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file KX_RaySensor.h
- * \ingroup ketsji
- * \brief Cast a ray and feel for objects
- */
-
-#ifndef __KX_RAYSENSOR_H__
-#define __KX_RAYSENSOR_H__
-
-#include "SCA_ISensor.h"
-#include "MT_Point3.h"
-#include "SCA_IScene.h" /* only for scene replace */
-#include "KX_Scene.h" /* only for scene replace */
-
-#include "BLI_utildefines.h"
-
-struct KX_ClientObjectInfo;
-class KX_RayCast;
-
-class KX_RaySensor : public SCA_ISensor
-{
- Py_Header
- STR_String m_propertyname;
- bool m_bFindMaterial;
- bool m_bXRay;
- float m_distance;
- class KX_Scene* m_scene;
- bool m_bTriggered;
- int m_axis;
- bool m_rayHit;
- float m_hitPosition[3];
- SCA_IObject* m_hitObject;
- float m_hitNormal[3];
- float m_rayDirection[3];
- STR_String m_hitMaterial;
-
-public:
- KX_RaySensor(class SCA_EventManager* eventmgr,
- SCA_IObject* gameobj,
- const STR_String& propname,
- bool bFindMaterial,
- bool bXRay,
- double distance,
- int axis,
- class KX_Scene* ketsjiScene);
- virtual ~KX_RaySensor();
- virtual CValue* GetReplica();
-
- virtual bool Evaluate();
- virtual bool IsPositiveTrigger();
- virtual void Init();
-
- /// \see KX_RayCast
- bool RayHit(KX_ClientObjectInfo *client, KX_RayCast *result, void *UNUSED(data));
- /// \see KX_RayCast
- bool NeedRayCast(KX_ClientObjectInfo *client, void *UNUSED(data));
-
- virtual void Replace_IScene(SCA_IScene *val)
- {
- m_scene= static_cast<KX_Scene *>(val);
- }
-
- //Python Interface
- // odd order, see: SENS_RAY_X_AXIS
- enum RayAxis {
- KX_RAY_AXIS_POS_X = 1,
- KX_RAY_AXIS_POS_Y = 0,
- KX_RAY_AXIS_POS_Z = 2,
- KX_RAY_AXIS_NEG_X = 3,
- KX_RAY_AXIS_NEG_Y = 4,
- KX_RAY_AXIS_NEG_Z = 5,
- };
-
-#ifdef WITH_PYTHON
-
- /* Attributes */
- static PyObject *pyattr_get_hitobject(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
-
-#endif /* WITH_PYTHON */
-
-};
-
-#endif /* __KX_RAYSENSOR_H__ */
diff --git a/source/gameengine/Ketsji/KX_SCA_AddObjectActuator.cpp b/source/gameengine/Ketsji/KX_SCA_AddObjectActuator.cpp
deleted file mode 100644
index bb38d8269b7..00000000000
--- a/source/gameengine/Ketsji/KX_SCA_AddObjectActuator.cpp
+++ /dev/null
@@ -1,284 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Ketsji/KX_SCA_AddObjectActuator.cpp
- * \ingroup ketsji
- *
- * Add an object when this actuator is triggered
- */
-
-/* Previously existed as:
- * \source\gameengine\GameLogic\SCA_AddObjectActuator.cpp
- * Please look here for revision history. */
-
-#include "KX_SCA_AddObjectActuator.h"
-#include "SCA_IScene.h"
-#include "KX_GameObject.h"
-#include "EXP_PyObjectPlus.h"
-
-/* ------------------------------------------------------------------------- */
-/* Native functions */
-/* ------------------------------------------------------------------------- */
-
-KX_SCA_AddObjectActuator::KX_SCA_AddObjectActuator(SCA_IObject *gameobj,
- SCA_IObject *original,
- int time,
- SCA_IScene* scene,
- const float *linvel,
- bool linv_local,
- const float *angvel,
- bool angv_local)
- :
- SCA_IActuator(gameobj, KX_ACT_ADD_OBJECT),
- m_OriginalObject(original),
- m_scene(scene),
-
- m_localLinvFlag(linv_local),
- m_localAngvFlag(angv_local)
-{
- m_linear_velocity[0] = linvel[0];
- m_linear_velocity[1] = linvel[1];
- m_linear_velocity[2] = linvel[2];
- m_angular_velocity[0] = angvel[0];
- m_angular_velocity[1] = angvel[1];
- m_angular_velocity[2] = angvel[2];
-
- if (m_OriginalObject)
- m_OriginalObject->RegisterActuator(this);
-
- m_lastCreatedObject = NULL;
- m_timeProp = time;
-}
-
-
-
-KX_SCA_AddObjectActuator::~KX_SCA_AddObjectActuator()
-{
- if (m_OriginalObject)
- m_OriginalObject->UnregisterActuator(this);
- if (m_lastCreatedObject)
- m_lastCreatedObject->UnregisterActuator(this);
-}
-
-
-
-bool KX_SCA_AddObjectActuator::Update()
-{
- //bool result = false; /*unused*/
- bool bNegativeEvent = IsNegativeEvent();
- RemoveAllEvents();
-
- if (bNegativeEvent) return false; // do nothing on negative events
-
- InstantAddObject();
-
-
- return false;
-}
-
-
-
-
-SCA_IObject* KX_SCA_AddObjectActuator::GetLastCreatedObject() const
-{
- return m_lastCreatedObject;
-}
-
-
-
-CValue* KX_SCA_AddObjectActuator::GetReplica()
-{
- KX_SCA_AddObjectActuator* replica = new KX_SCA_AddObjectActuator(*this);
-
- if (replica == NULL)
- return NULL;
-
- // this will copy properties and so on...
- replica->ProcessReplica();
-
- return replica;
-}
-
-void KX_SCA_AddObjectActuator::ProcessReplica()
-{
- if (m_OriginalObject)
- m_OriginalObject->RegisterActuator(this);
- m_lastCreatedObject=NULL;
- SCA_IActuator::ProcessReplica();
-}
-
-bool KX_SCA_AddObjectActuator::UnlinkObject(SCA_IObject* clientobj)
-{
- if (clientobj == m_OriginalObject)
- {
- // this object is being deleted, we cannot continue to track it.
- m_OriginalObject = NULL;
- return true;
- }
- if (clientobj == m_lastCreatedObject)
- {
- // this object is being deleted, we cannot continue to track it.
- m_lastCreatedObject = NULL;
- return true;
- }
- return false;
-}
-
-void KX_SCA_AddObjectActuator::Relink(CTR_Map<CTR_HashedPtr, void*> *obj_map)
-{
- void **h_obj = (*obj_map)[m_OriginalObject];
- if (h_obj) {
- if (m_OriginalObject)
- m_OriginalObject->UnregisterActuator(this);
- m_OriginalObject = (SCA_IObject*)(*h_obj);
- m_OriginalObject->RegisterActuator(this);
- }
-}
-
-#ifdef WITH_PYTHON
-
-/* ------------------------------------------------------------------------- */
-/* Python functions */
-/* ------------------------------------------------------------------------- */
-
-/* Integration hooks ------------------------------------------------------- */
-PyTypeObject KX_SCA_AddObjectActuator::Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "KX_SCA_AddObjectActuator",
- sizeof(PyObjectPlus_Proxy),
- 0,
- py_base_dealloc,
- 0,
- 0,
- 0,
- 0,
- py_base_repr,
- 0,0,0,0,0,0,0,0,0,
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
- 0,0,0,0,0,0,0,
- Methods,
- 0,
- 0,
- &SCA_IActuator::Type,
- 0,0,0,0,0,0,
- py_base_new
-};
-
-PyMethodDef KX_SCA_AddObjectActuator::Methods[] = {
- {"instantAddObject", (PyCFunction) KX_SCA_AddObjectActuator::sPyInstantAddObject, METH_NOARGS, NULL},
- {NULL,NULL} //Sentinel
-};
-
-PyAttributeDef KX_SCA_AddObjectActuator::Attributes[] = {
- KX_PYATTRIBUTE_RW_FUNCTION("object",KX_SCA_AddObjectActuator,pyattr_get_object,pyattr_set_object),
- KX_PYATTRIBUTE_RO_FUNCTION("objectLastCreated",KX_SCA_AddObjectActuator,pyattr_get_objectLastCreated),
- KX_PYATTRIBUTE_INT_RW("time",0,2000,true,KX_SCA_AddObjectActuator,m_timeProp),
- KX_PYATTRIBUTE_FLOAT_ARRAY_RW("linearVelocity",-FLT_MAX,FLT_MAX,KX_SCA_AddObjectActuator,m_linear_velocity,3),
- KX_PYATTRIBUTE_FLOAT_ARRAY_RW("angularVelocity",-FLT_MAX,FLT_MAX,KX_SCA_AddObjectActuator,m_angular_velocity,3),
- { NULL } //Sentinel
-};
-
-PyObject *KX_SCA_AddObjectActuator::pyattr_get_object(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_SCA_AddObjectActuator* actuator = static_cast<KX_SCA_AddObjectActuator*>(self);
- if (!actuator->m_OriginalObject)
- Py_RETURN_NONE;
- else
- return actuator->m_OriginalObject->GetProxy();
-}
-
-int KX_SCA_AddObjectActuator::pyattr_set_object(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_SCA_AddObjectActuator* actuator = static_cast<KX_SCA_AddObjectActuator*>(self);
- KX_GameObject *gameobj;
-
- if (!ConvertPythonToGameObject(actuator->GetLogicManager(), value, &gameobj, true, "actuator.object = value: KX_SCA_AddObjectActuator"))
- return PY_SET_ATTR_FAIL; // ConvertPythonToGameObject sets the error
-
- if (actuator->m_OriginalObject != NULL)
- actuator->m_OriginalObject->UnregisterActuator(actuator);
-
- actuator->m_OriginalObject = (SCA_IObject*)gameobj;
-
- if (actuator->m_OriginalObject)
- actuator->m_OriginalObject->RegisterActuator(actuator);
-
- return PY_SET_ATTR_SUCCESS;
-}
-
-PyObject *KX_SCA_AddObjectActuator::pyattr_get_objectLastCreated(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_SCA_AddObjectActuator* actuator = static_cast<KX_SCA_AddObjectActuator*>(self);
- if (!actuator->m_lastCreatedObject)
- Py_RETURN_NONE;
- else
- return actuator->m_lastCreatedObject->GetProxy();
-}
-
-PyObject *KX_SCA_AddObjectActuator::PyInstantAddObject()
-{
- InstantAddObject();
-
- Py_RETURN_NONE;
-}
-
-#endif // WITH_PYTHON
-
-void KX_SCA_AddObjectActuator::InstantAddObject()
-{
- if (m_OriginalObject)
- {
- // Add an identical object, with properties inherited from the original object
- // Now it needs to be added to the current scene.
- SCA_IObject* replica = m_scene->AddReplicaObject(m_OriginalObject,GetParent(),m_timeProp );
- KX_GameObject * game_obj = static_cast<KX_GameObject *>(replica);
- game_obj->setLinearVelocity(m_linear_velocity, m_localLinvFlag);
- game_obj->setAngularVelocity(m_angular_velocity,m_localAngvFlag);
- game_obj->ResolveCombinedVelocities(m_linear_velocity, m_angular_velocity, m_localLinvFlag, m_localAngvFlag);
-
- // keep a copy of the last object, to allow python scripters to change it
- if (m_lastCreatedObject)
- {
- //Let's not keep a reference to the object: it's bad, if the object is deleted
- //this will force to keep a "zombie" in the game for no good reason.
- //m_scene->DelayedReleaseObject(m_lastCreatedObject);
- //m_lastCreatedObject->Release();
-
- //Instead we use the registration mechanism
- m_lastCreatedObject->UnregisterActuator(this);
- m_lastCreatedObject = NULL;
- }
-
- m_lastCreatedObject = replica;
- // no reference
- //m_lastCreatedObject->AddRef();
- // but registration
- m_lastCreatedObject->RegisterActuator(this);
- // finished using replica? then release it
- replica->Release();
- }
-}
diff --git a/source/gameengine/Ketsji/KX_SCA_AddObjectActuator.h b/source/gameengine/Ketsji/KX_SCA_AddObjectActuator.h
deleted file mode 100644
index 976f3c58d68..00000000000
--- a/source/gameengine/Ketsji/KX_SCA_AddObjectActuator.h
+++ /dev/null
@@ -1,133 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file KX_SCA_AddObjectActuator.h
- * \ingroup ketsji
- * \attention Previously existed as: source/gameengine/GameLogic/SCA_AddObjectActuator.h
- * Please look here for revision history.
- */
-
-#ifndef __KX_SCA_ADDOBJECTACTUATOR_H__
-#define __KX_SCA_ADDOBJECTACTUATOR_H__
-
-/* Actuator tree */
-#include "SCA_IActuator.h"
-#include "SCA_LogicManager.h"
-
-#include "MT_Vector3.h"
-
-
-class SCA_IScene;
-
-class KX_SCA_AddObjectActuator : public SCA_IActuator
-{
- Py_Header
-
- /// Time field: lifetime of the new object
- int m_timeProp;
-
- /// Original object reference (object to replicate)
- SCA_IObject* m_OriginalObject;
-
- /// Object will be added to the following scene
- SCA_IScene* m_scene;
-
- /// Linear velocity upon creation of the object.
- float m_linear_velocity[3];
- /// Apply the velocity locally
- bool m_localLinvFlag;
-
- /// Angular velocity upon creation of the object.
- float m_angular_velocity[3];
- /// Apply the velocity locally
- bool m_localAngvFlag;
-
-
-
-
- SCA_IObject* m_lastCreatedObject;
-
-public:
-
- /**
- * This class also has the default constructors
- * available. Use with care!
- */
-
- KX_SCA_AddObjectActuator(
- SCA_IObject *gameobj,
- SCA_IObject *original,
- int time,
- SCA_IScene* scene,
- const float *linvel,
- bool linv_local,
- const float *angvel,
- bool angv_local
- );
-
- ~KX_SCA_AddObjectActuator(void);
-
- CValue*
- GetReplica(
- );
-
- virtual void
- ProcessReplica();
-
- virtual void Replace_IScene(SCA_IScene *val)
- {
- m_scene= val;
- };
-
- virtual bool
- UnlinkObject(SCA_IObject* clientobj);
-
- virtual void
- Relink(CTR_Map<CTR_HashedPtr, void*> *obj_map);
-
- virtual bool
- Update();
-
- SCA_IObject *
- GetLastCreatedObject(
- ) const;
-
- void InstantAddObject();
-
-#ifdef WITH_PYTHON
-
- KX_PYMETHOD_DOC_NOARGS(KX_SCA_AddObjectActuator,InstantAddObject);
-
- static PyObject *pyattr_get_object(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_object(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static PyObject *pyattr_get_objectLastCreated(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef);
-
-#endif /* WITH_PYTHON */
-
-}; /* end of class KX_SCA_AddObjectActuator : public KX_EditObjectActuator */
-
-#endif /* __KX_SCA_ADDOBJECTACTUATOR_H__ */
diff --git a/source/gameengine/Ketsji/KX_SCA_DynamicActuator.cpp b/source/gameengine/Ketsji/KX_SCA_DynamicActuator.cpp
deleted file mode 100644
index a4220424c6f..00000000000
--- a/source/gameengine/Ketsji/KX_SCA_DynamicActuator.cpp
+++ /dev/null
@@ -1,160 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Ketsji/KX_SCA_DynamicActuator.cpp
- * \ingroup ketsji
- * Adjust dynamics settings for this object
- */
-
-/* Previously existed as:
- * \source\gameengine\GameLogic\SCA_DynamicActuator.cpp
- * Please look here for revision history. */
-
-#include "KX_SCA_DynamicActuator.h"
-#include "PHY_IPhysicsController.h"
-
-#ifdef WITH_PYTHON
-
-/* ------------------------------------------------------------------------- */
-/* Python functions */
-/* ------------------------------------------------------------------------- */
-
-/* Integration hooks ------------------------------------------------------- */
-
-PyTypeObject KX_SCA_DynamicActuator::Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "KX_SCA_DynamicActuator",
- sizeof(PyObjectPlus_Proxy),
- 0,
- py_base_dealloc,
- 0,
- 0,
- 0,
- 0,
- py_base_repr,
- 0,0,0,0,0,0,0,0,0,
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
- 0,0,0,0,0,0,0,
- Methods,
- 0,
- 0,
- &SCA_IActuator::Type,
- 0,0,0,0,0,0,
- py_base_new
-};
-
-PyMethodDef KX_SCA_DynamicActuator::Methods[] = {
- {NULL,NULL} //Sentinel
-};
-
-PyAttributeDef KX_SCA_DynamicActuator::Attributes[] = {
- KX_PYATTRIBUTE_SHORT_RW("mode",0,4,false,KX_SCA_DynamicActuator,m_dyn_operation),
- KX_PYATTRIBUTE_FLOAT_RW("mass",0.0f,FLT_MAX,KX_SCA_DynamicActuator,m_setmass),
- { NULL } //Sentinel
-};
-
-#endif // WITH_PYTHON
-
-/* ------------------------------------------------------------------------- */
-/* Native functions */
-/* ------------------------------------------------------------------------- */
-
-KX_SCA_DynamicActuator::KX_SCA_DynamicActuator(SCA_IObject *gameobj,
- short dyn_operation,
- float setmass) :
-
- SCA_IActuator(gameobj, KX_ACT_DYNAMIC),
- m_dyn_operation(dyn_operation),
- m_setmass(setmass)
-{
-} /* End of constructor */
-
-
-KX_SCA_DynamicActuator::~KX_SCA_DynamicActuator()
-{
- // there's nothing to be done here, really....
-} /* end of destructor */
-
-
-
-bool KX_SCA_DynamicActuator::Update()
-{
- // bool result = false; /*unused*/
- KX_GameObject *obj = (KX_GameObject*) GetParent();
- bool bNegativeEvent = IsNegativeEvent();
- PHY_IPhysicsController* controller;
- RemoveAllEvents();
-
- if (bNegativeEvent)
- return false; // do nothing on negative events
-
- if (!obj)
- return false; // object not accessible, shouldnt happen
- controller = obj->GetPhysicsController();
- if (!controller)
- return false; // no physic object
-
- switch (m_dyn_operation)
- {
- case 0:
- // Child objects must be static, so we block changing to dynamic
- if (!obj->GetParent())
- controller->RestoreDynamics();
- break;
- case 1:
- controller->SuspendDynamics();
- break;
- case 2:
- controller->SetRigidBody(true);
- break;
- case 3:
- controller->SetRigidBody(false);
- break;
- case 4:
- controller->SetMass(m_setmass);
- break;
- }
-
- return false;
-}
-
-
-
-CValue* KX_SCA_DynamicActuator::GetReplica()
-{
- KX_SCA_DynamicActuator* replica =
- new KX_SCA_DynamicActuator(*this);
-
- if (replica == NULL)
- return NULL;
-
- replica->ProcessReplica();
- return replica;
-};
-
-
-/* eof */
diff --git a/source/gameengine/Ketsji/KX_SCA_DynamicActuator.h b/source/gameengine/Ketsji/KX_SCA_DynamicActuator.h
deleted file mode 100644
index 4eb337c54f5..00000000000
--- a/source/gameengine/Ketsji/KX_SCA_DynamicActuator.h
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): Campbell Barton
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file KX_SCA_DynamicActuator.h
- * \ingroup ketsji
- * \brief Add object to the game world on action of this actuator
- */
-
-#ifndef __KX_SCA_DYNAMICACTUATOR_H__
-#define __KX_SCA_DYNAMICACTUATOR_H__
-
-#include "SCA_IActuator.h"
-#include "SCA_PropertyActuator.h"
-#include "SCA_LogicManager.h"
-
-#include "KX_GameObject.h"
-
-class KX_SCA_DynamicActuator : public SCA_IActuator
-{
- Py_Header
-
- // dynamics operation to apply to the game object
- short m_dyn_operation;
- float m_setmass;
- public:
- KX_SCA_DynamicActuator(
- SCA_IObject* gameobj,
- short dyn_operation,
- float setmass
- );
-
- ~KX_SCA_DynamicActuator(
- );
-
- CValue*
- GetReplica(
- );
-
- virtual bool
- Update();
-
- //Python Interface
- enum DynamicOperation {
- KX_DYN_RESTORE_DYNAMICS = 0,
- KX_DYN_DISABLE_DYNAMICS,
- KX_DYN_ENABLE_RIGID_BODY,
- KX_DYN_DISABLE_RIGID_BODY,
- KX_DYN_SET_MASS,
- };
-};
-
-#endif
diff --git a/source/gameengine/Ketsji/KX_SCA_EndObjectActuator.cpp b/source/gameengine/Ketsji/KX_SCA_EndObjectActuator.cpp
deleted file mode 100644
index 81c9dc91603..00000000000
--- a/source/gameengine/Ketsji/KX_SCA_EndObjectActuator.cpp
+++ /dev/null
@@ -1,125 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Ketsji/KX_SCA_EndObjectActuator.cpp
- * \ingroup ketsji
- */
-
-
-//
-
-// Remove the actuator's parent when triggered
-//
-// Previously existed as:
-// \source\gameengine\GameLogic\SCA_EndObjectActuator.cpp
-// Please look here for revision history.
-
-#include "SCA_IActuator.h"
-#include "KX_SCA_EndObjectActuator.h"
-#include "SCA_IScene.h"
-
-KX_SCA_EndObjectActuator::KX_SCA_EndObjectActuator(SCA_IObject *gameobj,
- SCA_IScene* scene):
- SCA_IActuator(gameobj, KX_ACT_END_OBJECT),
- m_scene(scene)
-{
- // intentionally empty
-} /* End of constructor */
-
-
-
-KX_SCA_EndObjectActuator::~KX_SCA_EndObjectActuator()
-{
- // there's nothing to be done here, really....
-} /* end of destructor */
-
-
-
-bool KX_SCA_EndObjectActuator::Update()
-{
- // bool result = false; /*unused*/
- bool bNegativeEvent = IsNegativeEvent();
- RemoveAllEvents();
-
- if (bNegativeEvent)
- return false; // do nothing on negative events
- m_scene->DelayedRemoveObject(GetParent());
-
- return false;
-}
-
-
-
-CValue* KX_SCA_EndObjectActuator::GetReplica()
-{
- KX_SCA_EndObjectActuator* replica =
- new KX_SCA_EndObjectActuator(*this);
- if (replica == NULL) return NULL;
-
- replica->ProcessReplica();
- return replica;
-};
-
-#ifdef WITH_PYTHON
-
-/* ------------------------------------------------------------------------- */
-/* Python functions : integration hooks */
-/* ------------------------------------------------------------------------- */
-
-PyTypeObject KX_SCA_EndObjectActuator::Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "KX_SCA_EndObjectActuator",
- sizeof(PyObjectPlus_Proxy),
- 0,
- py_base_dealloc,
- 0,
- 0,
- 0,
- 0,
- py_base_repr,
- 0,0,0,0,0,0,0,0,0,
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
- 0,0,0,0,0,0,0,
- Methods,
- 0,
- 0,
- &SCA_IActuator::Type,
- 0,0,0,0,0,0,
- py_base_new
-};
-
-PyMethodDef KX_SCA_EndObjectActuator::Methods[] = {
- {NULL,NULL} //Sentinel
-};
-
-PyAttributeDef KX_SCA_EndObjectActuator::Attributes[] = {
- { NULL } //Sentinel
-};
-
-#endif // WITH_PYTHON
-
-/* eof */
diff --git a/source/gameengine/Ketsji/KX_SCA_EndObjectActuator.h b/source/gameengine/Ketsji/KX_SCA_EndObjectActuator.h
deleted file mode 100644
index 3399ed90667..00000000000
--- a/source/gameengine/Ketsji/KX_SCA_EndObjectActuator.h
+++ /dev/null
@@ -1,74 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file KX_SCA_EndObjectActuator.h
- * \ingroup ketsji
- * \brief Add object to the game world on action of this actuator
- * \attention Previously existed as: source/gameengine/GameLogic/SCA_EndObjectActuator.h
- * Please look here for revision history.
- */
-
-#ifndef __KX_SCA_ENDOBJECTACTUATOR_H__
-#define __KX_SCA_ENDOBJECTACTUATOR_H__
-
-#include "SCA_IActuator.h"
-
-class SCA_IScene;
-
-class KX_SCA_EndObjectActuator : public SCA_IActuator
-{
- Py_Header
- SCA_IScene* m_scene;
-
- public:
- KX_SCA_EndObjectActuator(
- SCA_IObject* gameobj,
- SCA_IScene* scene
- );
-
- ~KX_SCA_EndObjectActuator();
-
- CValue*
- GetReplica(
- );
-
- virtual bool
- Update();
-
- virtual void Replace_IScene(SCA_IScene *val)
- {
- m_scene= val;
- };
-
- /* --------------------------------------------------------------------- */
- /* Python interface ---------------------------------------------------- */
- /* --------------------------------------------------------------------- */
-
-}; /* end of class KX_EditObjectActuator : public SCA_PropertyActuator */
-
-#endif
-
diff --git a/source/gameengine/Ketsji/KX_SCA_ReplaceMeshActuator.cpp b/source/gameengine/Ketsji/KX_SCA_ReplaceMeshActuator.cpp
deleted file mode 100644
index 1bf76de0b40..00000000000
--- a/source/gameengine/Ketsji/KX_SCA_ReplaceMeshActuator.cpp
+++ /dev/null
@@ -1,182 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Ketsji/KX_SCA_ReplaceMeshActuator.cpp
- * \ingroup ketsji
- *
- * Replace the mesh for this actuator's parent
- */
-
-//
-// Previously existed as:
-
-// \source\gameengine\GameLogic\SCA_ReplaceMeshActuator.cpp
-
-// Please look here for revision history.
-
-#include <stddef.h>
-
-#include "KX_SCA_ReplaceMeshActuator.h"
-#include "KX_MeshProxy.h"
-
-#include "EXP_PyObjectPlus.h"
-
-#ifdef WITH_PYTHON
-
-/* ------------------------------------------------------------------------- */
-/* Python functions */
-/* ------------------------------------------------------------------------- */
-
-/* Integration hooks ------------------------------------------------------- */
-
-PyTypeObject KX_SCA_ReplaceMeshActuator::Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "KX_SCA_ReplaceMeshActuator",
- sizeof(PyObjectPlus_Proxy),
- 0,
- py_base_dealloc,
- 0,
- 0,
- 0,
- 0,
- py_base_repr,
- 0,0,0,0,0,0,0,0,0,
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
- 0,0,0,0,0,0,0,
- Methods,
- 0,
- 0,
- &SCA_IActuator::Type,
- 0,0,0,0,0,0,
- py_base_new
-};
-
-PyMethodDef KX_SCA_ReplaceMeshActuator::Methods[] = {
- KX_PYMETHODTABLE(KX_SCA_ReplaceMeshActuator, instantReplaceMesh),
- {NULL,NULL} //Sentinel
-};
-
-PyAttributeDef KX_SCA_ReplaceMeshActuator::Attributes[] = {
- KX_PYATTRIBUTE_RW_FUNCTION("mesh", KX_SCA_ReplaceMeshActuator, pyattr_get_mesh, pyattr_set_mesh),
- KX_PYATTRIBUTE_BOOL_RW ("useDisplayMesh", KX_SCA_ReplaceMeshActuator, m_use_gfx),
- KX_PYATTRIBUTE_BOOL_RW ("usePhysicsMesh", KX_SCA_ReplaceMeshActuator, m_use_phys),
- { NULL } //Sentinel
-};
-
-PyObject *KX_SCA_ReplaceMeshActuator::pyattr_get_mesh(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_SCA_ReplaceMeshActuator* actuator = static_cast<KX_SCA_ReplaceMeshActuator*>(self);
- if (!actuator->m_mesh)
- Py_RETURN_NONE;
- KX_MeshProxy* meshproxy = new KX_MeshProxy(actuator->m_mesh);
- return meshproxy->NewProxy(true);
-}
-
-int KX_SCA_ReplaceMeshActuator::pyattr_set_mesh(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_SCA_ReplaceMeshActuator* actuator = static_cast<KX_SCA_ReplaceMeshActuator*>(self);
- RAS_MeshObject* new_mesh;
-
- if (!ConvertPythonToMesh(actuator->GetLogicManager(), value, &new_mesh, true, "actuator.mesh = value: KX_SCA_ReplaceMeshActuator"))
- return PY_SET_ATTR_FAIL;
-
- actuator->m_mesh = new_mesh;
- return PY_SET_ATTR_SUCCESS;
-}
-
-KX_PYMETHODDEF_DOC(KX_SCA_ReplaceMeshActuator, instantReplaceMesh,
-"instantReplaceMesh() : immediately replace mesh without delay\n")
-{
- InstantReplaceMesh();
- Py_RETURN_NONE;
-}
-
-#endif // WITH_PYTHON
-
-/* ------------------------------------------------------------------------- */
-/* Native functions */
-/* ------------------------------------------------------------------------- */
-
-KX_SCA_ReplaceMeshActuator::KX_SCA_ReplaceMeshActuator(SCA_IObject *gameobj,
- class RAS_MeshObject *mesh,
- SCA_IScene* scene,
- bool use_gfx,
- bool use_phys) :
-
- SCA_IActuator(gameobj, KX_ACT_REPLACE_MESH),
- m_mesh(mesh),
- m_scene(scene),
- m_use_gfx(use_gfx),
- m_use_phys(use_phys)
-{
-} /* End of constructor */
-
-
-
-KX_SCA_ReplaceMeshActuator::~KX_SCA_ReplaceMeshActuator()
-{
- // there's nothing to be done here, really....
-} /* end of destructor */
-
-
-
-bool KX_SCA_ReplaceMeshActuator::Update()
-{
- // bool result = false; /*unused*/
- bool bNegativeEvent = IsNegativeEvent();
- RemoveAllEvents();
-
- if (bNegativeEvent)
- return false; // do nothing on negative events
-
- if (m_mesh || m_use_phys) /* NULL mesh is ok if were updating physics */
- m_scene->ReplaceMesh(GetParent(),m_mesh, m_use_gfx, m_use_phys);
-
- return false;
-}
-
-
-
-CValue* KX_SCA_ReplaceMeshActuator::GetReplica()
-{
- KX_SCA_ReplaceMeshActuator* replica =
- new KX_SCA_ReplaceMeshActuator(*this);
-
- if (replica == NULL)
- return NULL;
-
- replica->ProcessReplica();
-
- return replica;
-};
-
-void KX_SCA_ReplaceMeshActuator::InstantReplaceMesh()
-{
- if (m_mesh) m_scene->ReplaceMesh(GetParent(),m_mesh, m_use_gfx, m_use_phys);
-}
-
-/* eof */
diff --git a/source/gameengine/Ketsji/KX_SCA_ReplaceMeshActuator.h b/source/gameengine/Ketsji/KX_SCA_ReplaceMeshActuator.h
deleted file mode 100644
index 4370b5d4a4f..00000000000
--- a/source/gameengine/Ketsji/KX_SCA_ReplaceMeshActuator.h
+++ /dev/null
@@ -1,96 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file KX_SCA_ReplaceMeshActuator.h
- * \ingroup ketsji
- * \brief Add object to the game world on action of this actuator
- * \attention Previously existed as: source/gameengine/GameLogic/SCA_ReplaceMeshActuator.h
- * Please look here for revision history.
- */
-
-#ifndef __KX_SCA_REPLACEMESHACTUATOR_H__
-#define __KX_SCA_REPLACEMESHACTUATOR_H__
-
-#include "SCA_IActuator.h"
-#include "SCA_PropertyActuator.h"
-#include "SCA_LogicManager.h"
-#include "SCA_IScene.h"
-
-#include "RAS_MeshObject.h"
-
-class KX_SCA_ReplaceMeshActuator : public SCA_IActuator
-{
- Py_Header
-
- // mesh reference (mesh to replace)
- RAS_MeshObject* m_mesh;
- SCA_IScene* m_scene;
- bool m_use_gfx;
- bool m_use_phys;
-
- public:
- KX_SCA_ReplaceMeshActuator(
- SCA_IObject* gameobj,
- RAS_MeshObject *mesh,
- SCA_IScene* scene,
- bool use_gfx,
- bool use_phys
- );
-
- ~KX_SCA_ReplaceMeshActuator(
- );
-
- CValue*
- GetReplica(
- );
-
- virtual bool
- Update();
-
- void InstantReplaceMesh();
-
-#ifdef WITH_PYTHON
-
- /* --------------------------------------------------------------------- */
- /* Python interface ---------------------------------------------------- */
- /* --------------------------------------------------------------------- */
-
- virtual void Replace_IScene(SCA_IScene *val)
- {
- m_scene= val;
- };
-
- static PyObject *pyattr_get_mesh(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_mesh(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
-
- KX_PYMETHOD_DOC(KX_SCA_ReplaceMeshActuator,instantReplaceMesh);
-
-#endif /* WITH_PYTHON */
-
-};
-
-#endif /* __KX_SCA_REPLACEMESHACTUATOR_H__ */
diff --git a/source/gameengine/Ketsji/KX_SG_BoneParentNodeRelationship.cpp b/source/gameengine/Ketsji/KX_SG_BoneParentNodeRelationship.cpp
deleted file mode 100644
index 5a13cf5440d..00000000000
--- a/source/gameengine/Ketsji/KX_SG_BoneParentNodeRelationship.cpp
+++ /dev/null
@@ -1,155 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Ketsji/KX_SG_BoneParentNodeRelationship.cpp
- * \ingroup ketsji
- */
-
-
-#include <iostream>
-
-#include "KX_SG_BoneParentNodeRelationship.h"
-
-#include "MT_Matrix4x4.h"
-#include "BL_ArmatureObject.h"
-
-
-/**
- * Implementation of classes defined in KX_SG_BoneParentNodeRelationship.h
- */
-
-/**
- * first of all KX_SG_BoneParentRelation
- */
-
- KX_BoneParentRelation *
-KX_BoneParentRelation::
-New(Bone* bone
-) {
- return new KX_BoneParentRelation(bone);
-}
-
- bool
-KX_BoneParentRelation::
-UpdateChildCoordinates(
- SG_Spatial * child,
- const SG_Spatial * parent,
- bool& parentUpdated
-) {
- MT_assert(child != NULL);
-
- // This way of accessing child coordinates is a bit cumbersome
- // be nice to have non constant reference access to these values.
-
- const MT_Vector3 & child_scale = child->GetLocalScale();
- const MT_Point3 & child_pos = child->GetLocalPosition();
- const MT_Matrix3x3 & child_rotation = child->GetLocalOrientation();
- // we don't know if the armature has been updated or not, assume yes
- parentUpdated = true;
-
- // the childs world locations which we will update.
-
- MT_Vector3 child_w_scale;
- MT_Point3 child_w_pos;
- MT_Matrix3x3 child_w_rotation;
-
- bool valid_parent_transform = false;
-
- if (parent)
- {
- BL_ArmatureObject *armature = (BL_ArmatureObject*)(parent->GetSGClientObject());
- if (armature)
- {
- MT_Matrix4x4 parent_matrix;
- if (armature->GetBoneMatrix(m_bone, parent_matrix))
- {
- // Get the child's transform, and the bone matrix.
- MT_Matrix4x4 child_transform (
- MT_Transform(child_pos + MT_Vector3(0.0f, armature->GetBoneLength(m_bone), 0.0f),
- child_rotation.scaled(
- child_scale[0],
- child_scale[1],
- child_scale[2])));
-
- // The child's world transform is parent * child
- parent_matrix = parent->GetWorldTransform() * parent_matrix;
- child_transform = parent_matrix * child_transform;
-
- // Recompute the child transform components from the transform.
- child_w_scale.setValue(
- MT_Vector3(child_transform[0][0], child_transform[0][1], child_transform[0][2]).length(),
- MT_Vector3(child_transform[1][0], child_transform[1][1], child_transform[1][2]).length(),
- MT_Vector3(child_transform[2][0], child_transform[2][1], child_transform[2][2]).length());
- child_w_rotation.setValue(child_transform[0][0], child_transform[0][1], child_transform[0][2],
- child_transform[1][0], child_transform[1][1], child_transform[1][2],
- child_transform[2][0], child_transform[2][1], child_transform[2][2]);
- child_w_rotation.scale(1.0f/child_w_scale[0], 1.0f/child_w_scale[1], 1.0f/child_w_scale[2]);
-
- child_w_pos = MT_Point3(child_transform[0][3], child_transform[1][3], child_transform[2][3]);
-
- valid_parent_transform = true;
- }
- }
- }
-
- if (valid_parent_transform)
- {
- child->SetWorldScale(child_w_scale);
- child->SetWorldPosition(child_w_pos);
- child->SetWorldOrientation(child_w_rotation);
- }
- else {
- child->SetWorldFromLocalTransform();
- }
- child->ClearModified();
- // this node must always be updated, so reschedule it for next time
- child->ActivateRecheduleUpdateCallback();
- return valid_parent_transform;
-}
-
- SG_ParentRelation *
-KX_BoneParentRelation::
-NewCopy(
-) {
- KX_BoneParentRelation* bone_parent = new KX_BoneParentRelation(m_bone);
- return bone_parent;
-}
-
-KX_BoneParentRelation::
-~KX_BoneParentRelation(
-) {
- //nothing to do
-}
-
-
-KX_BoneParentRelation::
-KX_BoneParentRelation(Bone* bone
-)
-: m_bone(bone)
-{
- // nothing to do
-}
diff --git a/source/gameengine/Ketsji/KX_SG_BoneParentNodeRelationship.h b/source/gameengine/Ketsji/KX_SG_BoneParentNodeRelationship.h
deleted file mode 100644
index 6f4fd482198..00000000000
--- a/source/gameengine/Ketsji/KX_SG_BoneParentNodeRelationship.h
+++ /dev/null
@@ -1,96 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- *
- */
-
-/** \file KX_SG_BoneParentNodeRelationship.h
- * \ingroup ketsji
- */
-
-#ifndef __KX_SG_BONEPARENTNODERELATIONSHIP_H__
-#define __KX_SG_BONEPARENTNODERELATIONSHIP_H__
-
-#include "SG_Spatial.h"
-#include "SG_ParentRelation.h"
-
-struct Bone;
-
-/**
- * Bone parent relationship parents a child SG_Spatial frame to a
- * bone in an armature object.
- */
-class KX_BoneParentRelation : public SG_ParentRelation
-{
-
-public :
- /**
- * Allocate and construct a new KX_SG_BoneParentRelation
- * on the heap.
- *
- * bone is the bone id to use. Currently it is a pointer
- * to a Blender struct Bone - this should be fixed if
- */
-
- static
- KX_BoneParentRelation *
- New(Bone* bone
- );
-
- /**
- * Updates the childs world coordinates relative to the parent's
- * world coordinates.
- *
- * Parent should be a BL_ArmatureObject.
- */
- bool
- UpdateChildCoordinates(
- SG_Spatial * child,
- const SG_Spatial * parent,
- bool& parentUpdated
- );
-
- /**
- * Create a copy of this relationship
- */
- SG_ParentRelation *
- NewCopy(
- );
-
- ~KX_BoneParentRelation(
- );
-
-private :
- Bone* m_bone;
- KX_BoneParentRelation(Bone* bone
- );
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:KX_BoneParentRelation")
-#endif
-};
-
-#endif
diff --git a/source/gameengine/Ketsji/KX_SG_NodeRelationships.cpp b/source/gameengine/Ketsji/KX_SG_NodeRelationships.cpp
deleted file mode 100644
index e80de76861e..00000000000
--- a/source/gameengine/Ketsji/KX_SG_NodeRelationships.cpp
+++ /dev/null
@@ -1,298 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Ketsji/KX_SG_NodeRelationships.cpp
- * \ingroup ketsji
- */
-
-
-#include "KX_SG_NodeRelationships.h"
-
-/**
- * Implementation of classes defined in KX_SG_NodeRelationships.h
- */
-
-/**
- * first of all KX_NormalParentRelation
- */
-
- KX_NormalParentRelation *
-KX_NormalParentRelation::
-New(
-) {
- return new KX_NormalParentRelation();
-}
-
- bool
-KX_NormalParentRelation::
-UpdateChildCoordinates(
- SG_Spatial * child,
- const SG_Spatial * parent,
- bool& parentUpdated
-) {
- MT_assert(child != NULL);
-
- if (!parentUpdated && !child->IsModified())
- return false;
-
- parentUpdated = true;
-
- if (parent==NULL) { /* Simple case */
- child->SetWorldFromLocalTransform();
- child->ClearModified();
- return true; //false;
- }
- else {
- // the childs world locations which we will update.
- const MT_Vector3 & p_world_scale = parent->GetWorldScaling();
- const MT_Point3 & p_world_pos = parent->GetWorldPosition();
- const MT_Matrix3x3 & p_world_rotation = parent->GetWorldOrientation();
-
- child->SetWorldScale(p_world_scale * child->GetLocalScale());
- child->SetWorldOrientation(p_world_rotation * child->GetLocalOrientation());
- child->SetWorldPosition(p_world_pos + p_world_scale * (p_world_rotation * child->GetLocalPosition()));
- child->ClearModified();
- return true;
- }
-}
-
- SG_ParentRelation *
-KX_NormalParentRelation::
-NewCopy(
-) {
- return new KX_NormalParentRelation();
-}
-
-KX_NormalParentRelation::
-~KX_NormalParentRelation(
-) {
- //nothing to do
-}
-
-
-KX_NormalParentRelation::
-KX_NormalParentRelation(
-) {
- // nothing to do
-}
-
-/**
- * Next KX_VertexParentRelation
- */
-
-
- KX_VertexParentRelation *
-KX_VertexParentRelation::
-New(
-) {
- return new KX_VertexParentRelation();
-}
-
-/**
- * Method inherited from KX_ParentRelation
- */
-
- bool
-KX_VertexParentRelation::
-UpdateChildCoordinates(
- SG_Spatial * child,
- const SG_Spatial * parent,
- bool& parentUpdated
-) {
-
- MT_assert(child != NULL);
-
- if (!parentUpdated && !child->IsModified())
- return false;
-
- child->SetWorldScale(child->GetLocalScale());
-
- if (parent)
- child->SetWorldPosition(child->GetLocalPosition()+parent->GetWorldPosition());
- else
- child->SetWorldPosition(child->GetLocalPosition());
-
- child->SetWorldOrientation(child->GetLocalOrientation());
- child->ClearModified();
- return true; //parent != NULL;
-}
-
-/**
- * Method inherited from KX_ParentRelation
- */
-
- SG_ParentRelation *
-KX_VertexParentRelation::
-NewCopy(
-) {
- return new KX_VertexParentRelation();
-};
-
-KX_VertexParentRelation::
-~KX_VertexParentRelation(
-) {
- //nothing to do
-}
-
-
-KX_VertexParentRelation::
-KX_VertexParentRelation(
-) {
- //nothing to do
-}
-
-
-/**
- * Slow parent relationship
- */
-
- KX_SlowParentRelation *
-KX_SlowParentRelation::
-New(
- MT_Scalar relaxation
-) {
- return new KX_SlowParentRelation(relaxation);
-}
-
-/**
- * Method inherited from KX_ParentRelation
- */
-
- bool
-KX_SlowParentRelation::
-UpdateChildCoordinates(
- SG_Spatial * child,
- const SG_Spatial * parent,
- bool& parentUpdated
-) {
- MT_assert(child != NULL);
-
- // the child will move even if the parent is not
- parentUpdated = true;
-
- const MT_Vector3 & child_scale = child->GetLocalScale();
- const MT_Point3 & child_pos = child->GetLocalPosition();
- const MT_Matrix3x3 & child_rotation = child->GetLocalOrientation();
-
- // the childs world locations which we will update.
-
- MT_Vector3 child_w_scale;
- MT_Point3 child_w_pos;
- MT_Matrix3x3 child_w_rotation;
-
- if (parent) {
-
- // This is a slow parent relation
- // first compute the normal child world coordinates.
-
- MT_Vector3 child_n_scale;
- MT_Point3 child_n_pos;
- MT_Matrix3x3 child_n_rotation;
-
- const MT_Vector3 & p_world_scale = parent->GetWorldScaling();
- const MT_Point3 & p_world_pos = parent->GetWorldPosition();
- const MT_Matrix3x3 & p_world_rotation = parent->GetWorldOrientation();
-
- child_n_scale = p_world_scale * child_scale;
- child_n_rotation = p_world_rotation * child_rotation;
-
- child_n_pos = p_world_pos + p_world_scale *
- (p_world_rotation * child_pos);
-
-
- if (m_initialized) {
-
- // get the current world positions
-
- child_w_scale = child->GetWorldScaling();
- child_w_pos = child->GetWorldPosition();
- child_w_rotation = child->GetWorldOrientation();
-
- // now 'interpolate' the normal coordinates with the last
- // world coordinates to get the new world coordinates.
-
- MT_Scalar weight = MT_Scalar(1)/(m_relax + 1);
- child_w_scale = (m_relax * child_w_scale + child_n_scale) * weight;
- child_w_pos = (m_relax * child_w_pos + child_n_pos) * weight;
- // for rotation we must go through quaternion
- MT_Quaternion child_w_quat = child_w_rotation.getRotation().slerp(child_n_rotation.getRotation(), weight);
- child_w_rotation.setRotation(child_w_quat);
- //FIXME: update physics controller.
- } else {
- child_w_scale = child_n_scale;
- child_w_pos = child_n_pos;
- child_w_rotation = child_n_rotation;
- m_initialized = true;
- }
-
- } else {
-
- child_w_scale = child_scale;
- child_w_pos = child_pos;
- child_w_rotation = child_rotation;
- }
-
- child->SetWorldScale(child_w_scale);
- child->SetWorldPosition(child_w_pos);
- child->SetWorldOrientation(child_w_rotation);
- child->ClearModified();
- // this node must always be updated, so reschedule it for next time
- child->ActivateRecheduleUpdateCallback();
-
- return true; //parent != NULL;
-}
-
-/**
- * Method inherited from KX_ParentRelation
- */
-
- SG_ParentRelation *
-KX_SlowParentRelation::
-NewCopy(
-) {
- return new KX_SlowParentRelation(m_relax);
-}
-
-KX_SlowParentRelation::
-KX_SlowParentRelation(
- MT_Scalar relaxation
-):
- m_relax(relaxation),
- m_initialized(false)
-{
- //nothing to do
-}
-
-KX_SlowParentRelation::
-~KX_SlowParentRelation(
-) {
- //nothing to do
-}
-
-
-
-
diff --git a/source/gameengine/Ketsji/KX_SG_NodeRelationships.h b/source/gameengine/Ketsji/KX_SG_NodeRelationships.h
deleted file mode 100644
index 5d777f5028f..00000000000
--- a/source/gameengine/Ketsji/KX_SG_NodeRelationships.h
+++ /dev/null
@@ -1,231 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- *
- */
-
-/** \file KX_SG_NodeRelationships.h
- * \ingroup ketsji
- * \section KX_SG_NodeRelationships
- * This file provides common concrete implementations of
- * SG_ParentRelation used by the game engine. These are
- * KX_SlowParentRelation a slow parent relationship.
- * KX_NormalParentRelation a normal parent relationship where
- * orientation and position are inherited from the parent by
- * the child.
- * KX_VertexParentRelation only location information is
- * inherited by the child.
- */
-
-#ifndef __KX_SG_NODERELATIONSHIPS_H__
-#define __KX_SG_NODERELATIONSHIPS_H__
-
-#include "SG_Spatial.h"
-#include "SG_ParentRelation.h"
-
-class KX_NormalParentRelation : public SG_ParentRelation
-{
-
-public :
- /**
- * Allocate and construct a new KX_NormalParentRelation
- * on the heap.
- */
-
- static
- KX_NormalParentRelation *
- New(
- );
-
- /**
- * Method inherited from KX_ParentRelation
- */
-
- bool
- UpdateChildCoordinates(
- SG_Spatial * child,
- const SG_Spatial * parent,
- bool& parentUpdated
- );
-
- /**
- * Method inherited from KX_ParentRelation
- */
-
- SG_ParentRelation *
- NewCopy(
- );
-
- ~KX_NormalParentRelation(
- );
-
-private :
-
- KX_NormalParentRelation(
- );
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:KX_NormalParentRelation")
-#endif
-};
-
-
-class KX_VertexParentRelation : public SG_ParentRelation
-{
-
-public :
-
- /**
- * Allocate and construct a new KX_VertexParentRelation
- * on the heap.
- */
-
- static
- KX_VertexParentRelation *
- New(
- );
-
- /**
- * Method inherited from KX_ParentRelation
- */
-
- bool
- UpdateChildCoordinates(
- SG_Spatial * child,
- const SG_Spatial * parent,
- bool& parentUpdated
- );
-
- /**
- * Method inherited from KX_ParentRelation
- */
-
- SG_ParentRelation *
- NewCopy(
- );
-
- ~KX_VertexParentRelation(
- );
-
- bool
- IsVertexRelation(
- ) {
- return true;
- }
-
-private :
-
- KX_VertexParentRelation(
- );
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:KX_VertexParentRelation")
-#endif
-};
-
-
-class KX_SlowParentRelation : public SG_ParentRelation
-{
-
-public :
-
- /**
- * Allocate and construct a new KX_VertexParentRelation
- * on the heap.
- */
-
- static
- KX_SlowParentRelation *
- New(
- MT_Scalar relaxation
- );
-
- /**
- * Method inherited from KX_ParentRelation
- */
-
- bool
- UpdateChildCoordinates(
- SG_Spatial * child,
- const SG_Spatial * parent,
- bool& parentUpdated
- );
-
- /**
- * Method inherited from KX_ParentRelation
- */
-
- SG_ParentRelation *
- NewCopy(
- );
-
- MT_Scalar
- GetTimeOffset(
- ) { return m_relax; }
-
- void
- SetTimeOffset(
- MT_Scalar relaxation
- ) { m_relax = relaxation; }
-
- ~KX_SlowParentRelation(
- );
-
- bool
- IsSlowRelation(
- ) {
- return true;
- }
-
-private :
-
- KX_SlowParentRelation(
- MT_Scalar relaxation
- );
-
- // the relaxation coefficient.
-
- MT_Scalar m_relax;
-
- /**
- * Looks like a hack flag to me.
- * We need to compute valid world coordinates the first
- * time we update spatial data of the child. This is done
- * by just doing a normal parent relation the first time
- * UpdateChildCoordinates is called and then doing the
- * slow parent relation
- */
-
- bool m_initialized;
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:KX_SlowParentRelation")
-#endif
-};
-
-#endif
diff --git a/source/gameengine/Ketsji/KX_ScalarInterpolator.cpp b/source/gameengine/Ketsji/KX_ScalarInterpolator.cpp
deleted file mode 100644
index e234a9621b8..00000000000
--- a/source/gameengine/Ketsji/KX_ScalarInterpolator.cpp
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Ketsji/KX_ScalarInterpolator.cpp
- * \ingroup ketsji
- */
-
-
-#include "KX_ScalarInterpolator.h"
-#include "KX_IScalarInterpolator.h"
-
-void KX_ScalarInterpolator::Execute(float currentTime) const
-{
- *m_target = m_ipo->GetValue(currentTime);
-}
diff --git a/source/gameengine/Ketsji/KX_ScalarInterpolator.h b/source/gameengine/Ketsji/KX_ScalarInterpolator.h
deleted file mode 100644
index 5d8c3163376..00000000000
--- a/source/gameengine/Ketsji/KX_ScalarInterpolator.h
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file KX_ScalarInterpolator.h
- * \ingroup ketsji
- */
-
-#ifndef __KX_SCALARINTERPOLATOR_H__
-#define __KX_SCALARINTERPOLATOR_H__
-
-#include "MT_Scalar.h"
-#include "KX_IInterpolator.h"
-
-class KX_IScalarInterpolator;
-
-class KX_ScalarInterpolator : public KX_IInterpolator {
-public:
- KX_ScalarInterpolator(MT_Scalar* target,
- KX_IScalarInterpolator *ipo) :
- m_target(target),
- m_ipo(ipo)
- {}
-
- virtual ~KX_ScalarInterpolator() {}
- virtual void Execute(float currentTime) const;
- void SetNewTarget(MT_Scalar* newtarget)
- {
- m_target=newtarget;
- }
- MT_Scalar* GetTarget()
- {
- return m_target;
- }
-private:
- MT_Scalar* m_target;
- KX_IScalarInterpolator *m_ipo;
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:KX_ScalarInterpolator")
-#endif
-};
-
-#endif
-
diff --git a/source/gameengine/Ketsji/KX_ScalingInterpolator.cpp b/source/gameengine/Ketsji/KX_ScalingInterpolator.cpp
deleted file mode 100644
index dd40cbd22fd..00000000000
--- a/source/gameengine/Ketsji/KX_ScalingInterpolator.cpp
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Ketsji/KX_ScalingInterpolator.cpp
- * \ingroup ketsji
- */
-
-
-#include "KX_ScalingInterpolator.h"
-#include "MT_Vector3.h"
-#include "KX_IScalarInterpolator.h"
-
-void KX_ScalingInterpolator::Execute(float currentTime) const
-{
- m_target.setValue(m_ipos[0]->GetValue(currentTime),
- m_ipos[1]->GetValue(currentTime),
- m_ipos[2]->GetValue(currentTime));
-}
diff --git a/source/gameengine/Ketsji/KX_ScalingInterpolator.h b/source/gameengine/Ketsji/KX_ScalingInterpolator.h
deleted file mode 100644
index 52b6d0cf8cc..00000000000
--- a/source/gameengine/Ketsji/KX_ScalingInterpolator.h
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file KX_ScalingInterpolator.h
- * \ingroup ketsji
- */
-
-#ifndef __KX_SCALINGINTERPOLATOR_H__
-#define __KX_SCALINGINTERPOLATOR_H__
-
-#include "KX_IInterpolator.h"
-
-class MT_Vector3;
-class KX_IScalarInterpolator;
-
-class KX_ScalingInterpolator : public KX_IInterpolator {
-public:
- KX_ScalingInterpolator(MT_Vector3& target,
- KX_IScalarInterpolator *ipos[])
- : m_target(target)
- {
- m_ipos[0] = ipos[0];
- m_ipos[1] = ipos[1];
- m_ipos[2] = ipos[2];
- }
-
- virtual void Execute(float currentTime) const;
-
-private:
- MT_Vector3& m_target;
- KX_IScalarInterpolator *m_ipos[3];
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:KX_ScalingInterpolator")
-#endif
-};
-
-#endif
-
diff --git a/source/gameengine/Ketsji/KX_Scene.cpp b/source/gameengine/Ketsji/KX_Scene.cpp
deleted file mode 100644
index 0e6b04c6df5..00000000000
--- a/source/gameengine/Ketsji/KX_Scene.cpp
+++ /dev/null
@@ -1,2644 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- * Ketsji scene. Holds references to all scene data.
- */
-
-/** \file gameengine/Ketsji/KX_Scene.cpp
- * \ingroup ketsji
- */
-
-
-#ifdef _MSC_VER
-# pragma warning (disable:4786)
-#endif
-
-#include <stdio.h>
-
-#include "KX_Scene.h"
-#include "KX_PythonInit.h"
-#include "MT_assert.h"
-#include "KX_KetsjiEngine.h"
-#include "KX_BlenderMaterial.h"
-#include "KX_FontObject.h"
-#include "RAS_IPolygonMaterial.h"
-#include "EXP_ListValue.h"
-#include "SCA_LogicManager.h"
-#include "SCA_TimeEventManager.h"
-//#include "SCA_AlwaysEventManager.h"
-//#include "SCA_RandomEventManager.h"
-//#include "KX_RayEventManager.h"
-#include "SCA_2DFilterActuator.h"
-#include "SCA_PythonController.h"
-#include "KX_TouchEventManager.h"
-#include "SCA_KeyboardManager.h"
-#include "SCA_MouseManager.h"
-//#include "SCA_PropertyEventManager.h"
-#include "SCA_ActuatorEventManager.h"
-#include "SCA_BasicEventManager.h"
-#include "KX_Camera.h"
-#include "SCA_JoystickManager.h"
-#include "KX_PyMath.h"
-#include "RAS_MeshObject.h"
-#include "SCA_IScene.h"
-
-#include "RAS_IRasterizer.h"
-#include "RAS_ICanvas.h"
-#include "RAS_BucketManager.h"
-
-#include "EXP_FloatValue.h"
-#include "SCA_IController.h"
-#include "SCA_IActuator.h"
-#include "SG_Node.h"
-#include "BL_System.h"
-#include "SG_Controller.h"
-#include "SG_IObject.h"
-#include "SG_Tree.h"
-#include "DNA_group_types.h"
-#include "DNA_scene_types.h"
-#include "DNA_property_types.h"
-
-#include "KX_SG_NodeRelationships.h"
-
-#include "KX_NetworkEventManager.h"
-#include "NG_NetworkScene.h"
-#include "PHY_IPhysicsEnvironment.h"
-#include "PHY_IGraphicController.h"
-#include "PHY_IPhysicsController.h"
-#include "KX_BlenderSceneConverter.h"
-#include "KX_MotionState.h"
-
-#include "BL_ModifierDeformer.h"
-#include "BL_ShapeDeformer.h"
-#include "BL_DeformableGameObject.h"
-#include "KX_ObstacleSimulation.h"
-
-#ifdef WITH_BULLET
-# include "KX_SoftBodyDeformer.h"
-#endif
-
-#ifdef WITH_PYTHON
-# include "EXP_PythonCallBack.h"
-#endif
-
-#include "KX_Light.h"
-
-#include "BKE_group.h"
-#include "BLI_task.h"
-
-static void *KX_SceneReplicationFunc(SG_IObject* node,void* gameobj,void* scene)
-{
- KX_GameObject* replica = ((KX_Scene*)scene)->AddNodeReplicaObject(node,(KX_GameObject*)gameobj);
-
- if (replica)
- replica->Release();
-
- return (void*)replica;
-}
-
-static void *KX_SceneDestructionFunc(SG_IObject* node,void* gameobj,void* scene)
-{
- ((KX_Scene*)scene)->RemoveNodeDestructObject(node,(KX_GameObject*)gameobj);
-
- return NULL;
-};
-
-bool KX_Scene::KX_ScenegraphUpdateFunc(SG_IObject* node,void* gameobj,void* scene)
-{
- return ((SG_Node*)node)->Schedule(((KX_Scene*)scene)->m_sghead);
-}
-
-bool KX_Scene::KX_ScenegraphRescheduleFunc(SG_IObject* node,void* gameobj,void* scene)
-{
- return ((SG_Node*)node)->Reschedule(((KX_Scene*)scene)->m_sghead);
-}
-
-SG_Callbacks KX_Scene::m_callbacks = SG_Callbacks(
- KX_SceneReplicationFunc,
- KX_SceneDestructionFunc,
- KX_GameObject::UpdateTransformFunc,
- KX_Scene::KX_ScenegraphUpdateFunc,
- KX_Scene::KX_ScenegraphRescheduleFunc);
-
-// temporarily var until there is a button in the userinterface
-// (defined in KX_PythonInit.cpp)
-extern bool gUseVisibilityTemp;
-
-KX_Scene::KX_Scene(class SCA_IInputDevice* keyboarddevice,
- class SCA_IInputDevice* mousedevice,
- class NG_NetworkDeviceInterface *ndi,
- const STR_String& sceneName,
- Scene *scene,
- class RAS_ICanvas* canvas):
- PyObjectPlus(),
- m_keyboardmgr(NULL),
- m_mousemgr(NULL),
- m_sceneConverter(NULL),
- m_physicsEnvironment(0),
- m_sceneName(sceneName),
- m_networkDeviceInterface(ndi),
- m_active_camera(NULL),
- m_ueberExecutionPriority(0),
- m_blenderScene(scene),
- m_isActivedHysteresis(false),
- m_lodHysteresisValue(0)
-{
- m_suspendedtime = 0.0;
- m_suspendeddelta = 0.0;
-
- m_dbvt_culling = false;
- m_dbvt_occlusion_res = 0;
- m_activity_culling = false;
- m_suspend = false;
- m_isclearingZbuffer = true;
- m_isShadowDone = false;
- m_tempObjectList = new CListValue();
- m_objectlist = new CListValue();
- m_parentlist = new CListValue();
- m_lightlist= new CListValue();
- m_inactivelist = new CListValue();
- m_euthanasyobjects = new CListValue();
- m_animatedlist = new CListValue();
-
- m_logicmgr = new SCA_LogicManager();
-
- m_timemgr = new SCA_TimeEventManager(m_logicmgr);
- m_keyboardmgr = new SCA_KeyboardManager(m_logicmgr,keyboarddevice);
- m_mousemgr = new SCA_MouseManager(m_logicmgr,mousedevice, canvas);
-
- //SCA_AlwaysEventManager* alwaysmgr = new SCA_AlwaysEventManager(m_logicmgr);
- //SCA_PropertyEventManager* propmgr = new SCA_PropertyEventManager(m_logicmgr);
- SCA_ActuatorEventManager* actmgr = new SCA_ActuatorEventManager(m_logicmgr);
- //SCA_RandomEventManager* rndmgr = new SCA_RandomEventManager(m_logicmgr);
- SCA_BasicEventManager* basicmgr = new SCA_BasicEventManager(m_logicmgr);
- //KX_RayEventManager* raymgr = new KX_RayEventManager(m_logicmgr);
-
- KX_NetworkEventManager* netmgr = new KX_NetworkEventManager(m_logicmgr, ndi);
-
-
-
- //m_logicmgr->RegisterEventManager(alwaysmgr);
- //m_logicmgr->RegisterEventManager(propmgr);
- m_logicmgr->RegisterEventManager(actmgr);
- m_logicmgr->RegisterEventManager(m_keyboardmgr);
- m_logicmgr->RegisterEventManager(m_mousemgr);
- m_logicmgr->RegisterEventManager(m_timemgr);
- //m_logicmgr->RegisterEventManager(rndmgr);
- //m_logicmgr->RegisterEventManager(raymgr);
- m_logicmgr->RegisterEventManager(netmgr);
- m_logicmgr->RegisterEventManager(basicmgr);
-
-
- SYS_SystemHandle hSystem = SYS_GetSystem();
- bool nojoystick= SYS_GetCommandLineInt(hSystem,"nojoystick",0);
- if (!nojoystick)
- {
- SCA_JoystickManager *joymgr = new SCA_JoystickManager(m_logicmgr);
- m_logicmgr->RegisterEventManager(joymgr);
- }
-
- MT_assert (m_networkDeviceInterface != NULL);
- m_networkScene = new NG_NetworkScene(m_networkDeviceInterface);
-
- m_rootnode = NULL;
-
- m_bucketmanager=new RAS_BucketManager();
-
- bool showObstacleSimulation = (scene->gm.flag & GAME_SHOW_OBSTACLE_SIMULATION) != 0;
- switch (scene->gm.obstacleSimulation)
- {
- case OBSTSIMULATION_TOI_rays:
- m_obstacleSimulation = new KX_ObstacleSimulationTOI_rays((MT_Scalar)scene->gm.levelHeight, showObstacleSimulation);
- break;
- case OBSTSIMULATION_TOI_cells:
- m_obstacleSimulation = new KX_ObstacleSimulationTOI_cells((MT_Scalar)scene->gm.levelHeight, showObstacleSimulation);
- break;
- default:
- m_obstacleSimulation = NULL;
- }
-
-#ifdef WITH_PYTHON
- m_attr_dict = NULL;
- m_draw_call_pre = NULL;
- m_draw_call_post = NULL;
- m_draw_setup_call_pre = NULL;
-#endif
-}
-
-
-
-KX_Scene::~KX_Scene()
-{
- // The release of debug properties used to be in SCA_IScene::~SCA_IScene
- // It's still there but we remove all properties here otherwise some
- // reference might be hanging and causing late release of objects
- RemoveAllDebugProperties();
-
- while (GetRootParentList()->GetCount() > 0)
- {
- KX_GameObject* parentobj = (KX_GameObject*) GetRootParentList()->GetValue(0);
- this->RemoveObject(parentobj);
- }
-
- if (m_obstacleSimulation)
- delete m_obstacleSimulation;
-
- if (m_objectlist)
- m_objectlist->Release();
-
- if (m_parentlist)
- m_parentlist->Release();
-
- if (m_inactivelist)
- m_inactivelist->Release();
-
- if (m_lightlist)
- m_lightlist->Release();
-
- if (m_tempObjectList)
- m_tempObjectList->Release();
-
- if (m_euthanasyobjects)
- m_euthanasyobjects->Release();
-
- if (m_animatedlist)
- m_animatedlist->Release();
-
- if (m_logicmgr)
- delete m_logicmgr;
-
- if (m_physicsEnvironment)
- delete m_physicsEnvironment;
-
- if (m_networkScene)
- delete m_networkScene;
-
- if (m_bucketmanager)
- {
- delete m_bucketmanager;
- }
-
-#ifdef WITH_PYTHON
- if (m_attr_dict) {
- PyDict_Clear(m_attr_dict);
- /* Py_CLEAR: Py_DECREF's and NULL's */
- Py_CLEAR(m_attr_dict);
- }
-
- /* these may be NULL but the macro checks */
- Py_CLEAR(m_draw_call_pre);
- Py_CLEAR(m_draw_call_post);
-#endif
-}
-
-RAS_BucketManager* KX_Scene::GetBucketManager()
-{
- return m_bucketmanager;
-}
-
-
-CListValue* KX_Scene::GetTempObjectList()
-{
- return m_tempObjectList;
-}
-
-CListValue* KX_Scene::GetObjectList()
-{
- return m_objectlist;
-}
-
-
-CListValue* KX_Scene::GetRootParentList()
-{
- return m_parentlist;
-}
-
-CListValue* KX_Scene::GetInactiveList()
-{
- return m_inactivelist;
-}
-
-
-
-CListValue* KX_Scene::GetLightList()
-{
- return m_lightlist;
-}
-
-SCA_LogicManager* KX_Scene::GetLogicManager()
-{
- return m_logicmgr;
-}
-
-SCA_TimeEventManager* KX_Scene::GetTimeEventManager()
-{
- return m_timemgr;
-}
-
-
-
-
-list<class KX_Camera*>* KX_Scene::GetCameras()
-{
- return &m_cameras;
-}
-
-void KX_Scene::SetFramingType(RAS_FrameSettings & frame_settings)
-{
- m_frame_settings = frame_settings;
-};
-
-/**
- * Return a const reference to the framing
- * type set by the above call.
- * The contents are not guaranteed to be sensible
- * if you don't call the above function.
- */
-const RAS_FrameSettings& KX_Scene::GetFramingType() const
-{
- return m_frame_settings;
-};
-
-
-
-/**
- * Store the current scene's viewport on the
- * game engine canvas.
- */
-void KX_Scene::SetSceneViewport(const RAS_Rect &viewport)
-{
- m_viewport = viewport;
-}
-
-
-
-const RAS_Rect& KX_Scene::GetSceneViewport() const
-{
- return m_viewport;
-}
-
-
-
-void KX_Scene::SetWorldInfo(class KX_WorldInfo* worldinfo)
-{
- m_worldinfo = worldinfo;
-}
-
-
-
-class KX_WorldInfo* KX_Scene::GetWorldInfo()
-{
- return m_worldinfo;
-}
-
-
-const STR_String& KX_Scene::GetName()
-{
- return m_sceneName;
-}
-
-
-void KX_Scene::Suspend()
-{
- m_suspend = true;
-}
-
-void KX_Scene::Resume()
-{
- m_suspend = false;
-}
-
-void KX_Scene::SetActivityCulling(bool b)
-{
- m_activity_culling = b;
-}
-
-bool KX_Scene::IsSuspended()
-{
- return m_suspend;
-}
-
-bool KX_Scene::IsClearingZBuffer()
-{
- return m_isclearingZbuffer;
-}
-
-void KX_Scene::EnableZBufferClearing(bool isclearingZbuffer)
-{
- m_isclearingZbuffer = isclearingZbuffer;
-}
-
-void KX_Scene::AddObjectDebugProperties(class KX_GameObject* gameobj)
-{
- Object* blenderobject = gameobj->GetBlenderObject();
- bProperty* prop = (bProperty*)blenderobject->prop.first;
-
- while (prop) {
- if (prop->flag & PROP_DEBUG)
- AddDebugProperty(gameobj,STR_String(prop->name));
- prop = prop->next;
- }
-
- if (blenderobject->scaflag & OB_DEBUGSTATE)
- AddDebugProperty(gameobj,STR_String("__state__"));
-}
-
-void KX_Scene::RemoveNodeDestructObject(class SG_IObject* node,class CValue* gameobj)
-{
- KX_GameObject* orgobj = (KX_GameObject*)gameobj;
- if (NewRemoveObject(orgobj) != 0)
- {
- // object is not yet deleted because a reference is hanging somewhere.
- // This should not happen anymore since we use proxy object for Python
- // confident enough to put an assert?
- //assert(false);
- printf("Zombie object! name=%s\n", orgobj->GetName().ReadPtr());
- orgobj->SetSGNode(NULL);
- PHY_IGraphicController* ctrl = orgobj->GetGraphicController();
- if (ctrl)
- {
- // a graphic controller is set, we must delete it as the node will be deleted
- delete ctrl;
- orgobj->SetGraphicController(NULL);
- }
- }
- if (node)
- delete node;
-}
-
-KX_GameObject* KX_Scene::AddNodeReplicaObject(class SG_IObject* node, class CValue* gameobj)
-{
- // for group duplication, limit the duplication of the hierarchy to the
- // objects that are part of the group.
- if (!IsObjectInGroup(gameobj))
- return NULL;
-
- KX_GameObject* orgobj = (KX_GameObject*)gameobj;
- KX_GameObject* newobj = (KX_GameObject*)orgobj->GetReplica();
- m_map_gameobject_to_replica.insert(orgobj, newobj);
-
- // also register 'timers' (time properties) of the replica
- int numprops = newobj->GetPropertyCount();
-
- for (int i = 0; i < numprops; i++)
- {
- CValue* prop = newobj->GetProperty(i);
-
- if (prop->GetProperty("timer"))
- this->m_timemgr->AddTimeProperty(prop);
- }
-
- if (node)
- {
- newobj->SetSGNode((SG_Node*)node);
- }
- else
- {
- m_rootnode = new SG_Node(newobj,this,KX_Scene::m_callbacks);
-
- // this fixes part of the scaling-added object bug
- SG_Node* orgnode = orgobj->GetSGNode();
- m_rootnode->SetLocalScale(orgnode->GetLocalScale());
- m_rootnode->SetLocalPosition(orgnode->GetLocalPosition());
- m_rootnode->SetLocalOrientation(orgnode->GetLocalOrientation());
-
- // define the relationship between this node and it's parent.
- KX_NormalParentRelation * parent_relation =
- KX_NormalParentRelation::New();
- m_rootnode->SetParentRelation(parent_relation);
-
- newobj->SetSGNode(m_rootnode);
- }
-
- SG_IObject* replicanode = newobj->GetSGNode();
-// SG_Node* rootnode = (replicanode == m_rootnode ? NULL : m_rootnode);
-
- replicanode->SetSGClientObject(newobj);
-
- // this is the list of object that are send to the graphics pipeline
- m_objectlist->Add(newobj->AddRef());
- if (newobj->GetGameObjectType()==SCA_IObject::OBJ_LIGHT)
- m_lightlist->Add(newobj->AddRef());
- else if (newobj->GetGameObjectType()==SCA_IObject::OBJ_TEXT)
- AddFont((KX_FontObject*)newobj);
- newobj->AddMeshUser();
-
- // logic cannot be replicated, until the whole hierarchy is replicated.
- m_logicHierarchicalGameObjects.push_back(newobj);
- //replicate controllers of this node
- SGControllerList scenegraphcontrollers = orgobj->GetSGNode()->GetSGControllerList();
- replicanode->RemoveAllControllers();
- SGControllerList::iterator cit;
- //int numcont = scenegraphcontrollers.size();
-
- for (cit = scenegraphcontrollers.begin();!(cit==scenegraphcontrollers.end());++cit)
- {
- // controller replication is quite complicated
- // only replicate ipo controller for now
-
- SG_Controller* replicacontroller = (*cit)->GetReplica((SG_Node*) replicanode);
- if (replicacontroller)
- {
- replicacontroller->SetObject(replicanode);
- replicanode->AddSGController(replicacontroller);
- }
- }
- // replicate graphic controller
- if (orgobj->GetGraphicController())
- {
- PHY_IMotionState* motionstate = new KX_MotionState(newobj->GetSGNode());
- PHY_IGraphicController* newctrl = orgobj->GetGraphicController()->GetReplica(motionstate);
- newctrl->SetNewClientInfo(newobj->getClientInfo());
- newobj->SetGraphicController(newctrl);
- }
-
- // replicate physics controller
- if (orgobj->GetPhysicsController())
- {
- PHY_IMotionState* motionstate = new KX_MotionState(newobj->GetSGNode());
- PHY_IPhysicsController* newctrl = orgobj->GetPhysicsController()->GetReplica();
-
- KX_GameObject *parent = newobj->GetParent();
- PHY_IPhysicsController* parentctrl = (parent) ? parent->GetPhysicsController() : NULL;
-
- newctrl->SetNewClientInfo(newobj->getClientInfo());
- newobj->SetPhysicsController(newctrl, newobj->IsDynamic());
- newctrl->PostProcessReplica(motionstate, parentctrl);
-
- // Child objects must be static
- if (parent)
- newctrl->SuspendDynamics();
- }
-
- return newobj;
-}
-
-
-
-// before calling this method KX_Scene::ReplicateLogic(), make sure to
-// have called 'GameObject::ReParentLogic' for each object this
-// hierarchy that's because first ALL bricks must exist in the new
-// replica of the hierarchy in order to make cross-links work properly
-// !
-// It is VERY important that the order of sensors and actuators in
-// the replicated object is preserved: it is used to reconnect the logic.
-// This method is more robust then using the bricks name in case of complex
-// group replication. The replication of logic bricks is done in
-// SCA_IObject::ReParentLogic(), make sure it preserves the order of the bricks.
-void KX_Scene::ReplicateLogic(KX_GameObject* newobj)
-{
- /* add properties to debug list, for added objects and DupliGroups */
- if (KX_GetActiveEngine()->GetAutoAddDebugProperties()) {
- AddObjectDebugProperties(newobj);
- }
- // also relink the controller to sensors/actuators
- SCA_ControllerList& controllers = newobj->GetControllers();
- //SCA_SensorList& sensors = newobj->GetSensors();
- //SCA_ActuatorList& actuators = newobj->GetActuators();
-
- for (SCA_ControllerList::iterator itc = controllers.begin(); !(itc==controllers.end());itc++)
- {
- SCA_IController* cont = (*itc);
- cont->SetUeberExecutePriority(m_ueberExecutionPriority);
- vector<SCA_ISensor*> linkedsensors = cont->GetLinkedSensors();
- vector<SCA_IActuator*> linkedactuators = cont->GetLinkedActuators();
-
- // disconnect the sensors and actuators
- // do it directly on the list at this controller is not connected to anything at this stage
- cont->GetLinkedSensors().clear();
- cont->GetLinkedActuators().clear();
-
- // now relink each sensor
- for (vector<SCA_ISensor*>::iterator its = linkedsensors.begin();!(its==linkedsensors.end());its++)
- {
- SCA_ISensor* oldsensor = (*its);
- SCA_IObject* oldsensorobj = oldsensor->GetParent();
- SCA_IObject* newsensorobj = NULL;
-
- // the original owner of the sensor has been replicated?
- void **h_obj = m_map_gameobject_to_replica[oldsensorobj];
- if (h_obj)
- newsensorobj = (SCA_IObject*)(*h_obj);
- if (!newsensorobj)
- {
- // no, then the sensor points outside the hierarchy, keep it the same
- if (m_objectlist->SearchValue(oldsensorobj))
- // only replicate links that points to active objects
- m_logicmgr->RegisterToSensor(cont,oldsensor);
- }
- else
- {
- // yes, then the new sensor has the same position
- SCA_SensorList& sensorlist = oldsensorobj->GetSensors();
- SCA_SensorList::iterator sit;
- SCA_ISensor* newsensor = NULL;
- int sensorpos;
-
- for (sensorpos=0, sit=sensorlist.begin(); sit!=sensorlist.end(); sit++, sensorpos++)
- {
- if ((*sit) == oldsensor)
- {
- newsensor = newsensorobj->GetSensors().at(sensorpos);
- break;
- }
- }
- assert(newsensor != NULL);
- m_logicmgr->RegisterToSensor(cont,newsensor);
- }
- }
-
- // now relink each actuator
- for (vector<SCA_IActuator*>::iterator ita = linkedactuators.begin();!(ita==linkedactuators.end());ita++)
- {
- SCA_IActuator* oldactuator = (*ita);
- SCA_IObject* oldactuatorobj = oldactuator->GetParent();
- SCA_IObject* newactuatorobj = NULL;
-
- // the original owner of the sensor has been replicated?
- void **h_obj = m_map_gameobject_to_replica[oldactuatorobj];
- if (h_obj)
- newactuatorobj = (SCA_IObject*)(*h_obj);
-
- if (!newactuatorobj)
- {
- // no, then the sensor points outside the hierarchy, keep it the same
- if (m_objectlist->SearchValue(oldactuatorobj))
- // only replicate links that points to active objects
- m_logicmgr->RegisterToActuator(cont,oldactuator);
- }
- else
- {
- // yes, then the new sensor has the same position
- SCA_ActuatorList& actuatorlist = oldactuatorobj->GetActuators();
- SCA_ActuatorList::iterator ait;
- SCA_IActuator* newactuator = NULL;
- int actuatorpos;
-
- for (actuatorpos=0, ait=actuatorlist.begin(); ait!=actuatorlist.end(); ait++, actuatorpos++)
- {
- if ((*ait) == oldactuator)
- {
- newactuator = newactuatorobj->GetActuators().at(actuatorpos);
- break;
- }
- }
- assert(newactuator != NULL);
- m_logicmgr->RegisterToActuator(cont,newactuator);
- newactuator->SetUeberExecutePriority(m_ueberExecutionPriority);
- }
- }
- }
- // ready to set initial state
- newobj->ResetState();
-}
-
-void KX_Scene::DupliGroupRecurse(CValue* obj, int level)
-{
- KX_GameObject* groupobj = (KX_GameObject*) obj;
- KX_GameObject* replica;
- KX_GameObject* gameobj;
- Object* blgroupobj = groupobj->GetBlenderObject();
- Group* group;
- vector<KX_GameObject*> duplilist;
-
- if (!groupobj->GetSGNode() ||
- !groupobj->IsDupliGroup() ||
- level>MAX_DUPLI_RECUR)
- return;
-
- // we will add one group at a time
- m_logicHierarchicalGameObjects.clear();
- m_map_gameobject_to_replica.clear();
- m_ueberExecutionPriority++;
- // for groups will do something special:
- // we will force the creation of objects to those in the group only
- // Again, this is match what Blender is doing (it doesn't care of parent relationship)
- m_groupGameObjects.clear();
-
- group = blgroupobj->dup_group;
- FOREACH_GROUP_BASE_BEGIN(group, base)
- {
- Object *blenderobj = base->object;
- if (blgroupobj == blenderobj)
- // this check is also in group_duplilist()
- continue;
-
- gameobj = (KX_GameObject*)m_logicmgr->FindGameObjByBlendObj(blenderobj);
- if (gameobj == NULL)
- {
- // this object has not been converted!!!
- // Should not happen as dupli group are created automatically
- continue;
- }
-
- gameobj->SetBlenderGroupObject(blgroupobj);
-
- if ((base->flag & BASE_VISIBLED) == 0) {
- // object is not visible in the 3D view, will not be instantiated
- continue;
- }
- m_groupGameObjects.insert(gameobj);
- }
- FOREACH_GROUP_BASE_END;
-
- set<CValue*>::iterator oit;
- for (oit=m_groupGameObjects.begin(); oit != m_groupGameObjects.end(); oit++)
- {
- gameobj = (KX_GameObject*)(*oit);
-
- KX_GameObject *parent = gameobj->GetParent();
- if (parent != NULL)
- {
- // this object is not a top parent. Either it is the child of another
- // object in the group and it will be added automatically when the parent
- // is added. Or it is the child of an object outside the group and the group
- // is inconsistent, skip it anyway
- continue;
- }
- replica = (KX_GameObject*) AddNodeReplicaObject(NULL,gameobj);
- // add to 'rootparent' list (this is the list of top hierarchy objects, updated each frame)
- m_parentlist->Add(replica->AddRef());
-
- // recurse replication into children nodes
- NodeList& children = gameobj->GetSGNode()->GetSGChildren();
-
- replica->GetSGNode()->ClearSGChildren();
- for (NodeList::iterator childit = children.begin();!(childit==children.end());++childit)
- {
- SG_Node* orgnode = (*childit);
- SG_Node* childreplicanode = orgnode->GetSGReplica();
- if (childreplicanode)
- replica->GetSGNode()->AddChild(childreplicanode);
- }
- // don't replicate logic now: we assume that the objects in the group can have
- // logic relationship, even outside parent relationship
- // In order to match 3D view, the position of groupobj is used as a
- // transformation matrix instead of the new position. This means that
- // the group reference point is 0,0,0
-
- // get the rootnode's scale
- MT_Vector3 newscale = groupobj->NodeGetWorldScaling();
- // set the replica's relative scale with the rootnode's scale
- replica->NodeSetRelativeScale(newscale);
-
- MT_Point3 offset(group->dupli_ofs);
- MT_Point3 newpos = groupobj->NodeGetWorldPosition() +
- newscale*(groupobj->NodeGetWorldOrientation() * (gameobj->NodeGetWorldPosition()-offset));
- replica->NodeSetLocalPosition(newpos);
- // set the orientation after position for softbody!
- MT_Matrix3x3 newori = groupobj->NodeGetWorldOrientation() * gameobj->NodeGetWorldOrientation();
- replica->NodeSetLocalOrientation(newori);
- // update scenegraph for entire tree of children
- replica->GetSGNode()->UpdateWorldData(0);
- replica->GetSGNode()->SetBBox(gameobj->GetSGNode()->BBox());
- replica->GetSGNode()->SetRadius(gameobj->GetSGNode()->Radius());
- // we can now add the graphic controller to the physic engine
- replica->ActivateGraphicController(true);
-
- // done with replica
- replica->Release();
- }
-
- // the logic must be replicated first because we need
- // the new logic bricks before relinking
- vector<KX_GameObject*>::iterator git;
- for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
- {
- (*git)->ReParentLogic();
- }
-
- // relink any pointers as necessary, sort of a temporary solution
- for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
- {
- // this will also relink the actuator to objects within the hierarchy
- (*git)->Relink(&m_map_gameobject_to_replica);
- // add the object in the layer of the parent
- (*git)->SetLayer(groupobj->GetLayer());
- }
-
- // replicate crosslinks etc. between logic bricks
- for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
- {
- ReplicateLogic((*git));
- }
-
- // now look if object in the hierarchy have dupli group and recurse
- for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
- {
- /* Replicate all constraints. */
- if ((*git)->GetPhysicsController()) {
- (*git)->GetPhysicsController()->ReplicateConstraints((*git), m_logicHierarchicalGameObjects);
- (*git)->ClearConstraints();
- }
-
- if ((*git) != groupobj && (*git)->IsDupliGroup())
- // can't instantiate group immediately as it destroys m_logicHierarchicalGameObjects
- duplilist.push_back((*git));
-
- if ((*git)->GetBlenderGroupObject() == blgroupobj) {
- // set references for dupli-group
- // groupobj holds a list of all objects, that belongs to this group
- groupobj->AddInstanceObjects((*git));
-
- // every object gets the reference to its dupli-group object
- (*git)->SetDupliGroupObject(groupobj);
- }
- }
-
- for (git = duplilist.begin(); !(git == duplilist.end()); ++git)
- {
- DupliGroupRecurse((*git), level+1);
- }
-}
-
-
-SCA_IObject* KX_Scene::AddReplicaObject(class CValue* originalobject,
- class CValue* referenceobject,
- int lifespan)
-{
-
- m_logicHierarchicalGameObjects.clear();
- m_map_gameobject_to_replica.clear();
- m_groupGameObjects.clear();
-
- KX_GameObject* originalobj = (KX_GameObject*) originalobject;
- KX_GameObject* referenceobj = (KX_GameObject*) referenceobject;
-
- m_ueberExecutionPriority++;
-
- // lets create a replica
- KX_GameObject* replica = (KX_GameObject*) AddNodeReplicaObject(NULL,originalobj);
-
- // add a timebomb to this object
- // lifespan of zero means 'this object lives forever'
- if (lifespan > 0)
- {
- // for now, convert between so called frames and realtime
- m_tempObjectList->Add(replica->AddRef());
- // this convert the life from frames to sort-of seconds, hard coded 0.02 that assumes we have 50 frames per second
- // if you change this value, make sure you change it in KX_GameObject::pyattr_get_life property too
- CValue *fval = new CFloatValue(lifespan*0.02f);
- replica->SetProperty("::timebomb",fval);
- fval->Release();
- }
-
- // add to 'rootparent' list (this is the list of top hierarchy objects, updated each frame)
- m_parentlist->Add(replica->AddRef());
-
- // recurse replication into children nodes
-
- NodeList& children = originalobj->GetSGNode()->GetSGChildren();
-
- replica->GetSGNode()->ClearSGChildren();
- for (NodeList::iterator childit = children.begin();!(childit==children.end());++childit)
- {
- SG_Node* orgnode = (*childit);
- SG_Node* childreplicanode = orgnode->GetSGReplica();
- if (childreplicanode)
- replica->GetSGNode()->AddChild(childreplicanode);
- }
-
- if (referenceobj) {
- // At this stage all the objects in the hierarchy have been duplicated,
- // we can update the scenegraph, we need it for the duplication of logic
- MT_Point3 newpos = referenceobj->NodeGetWorldPosition();
- replica->NodeSetLocalPosition(newpos);
-
- MT_Matrix3x3 newori = referenceobj->NodeGetWorldOrientation();
- replica->NodeSetLocalOrientation(newori);
-
- // get the rootnode's scale
- MT_Vector3 newscale = referenceobj->GetSGNode()->GetRootSGParent()->GetLocalScale();
- // set the replica's relative scale with the rootnode's scale
- replica->NodeSetRelativeScale(newscale);
- }
-
- replica->GetSGNode()->UpdateWorldData(0);
- replica->GetSGNode()->SetBBox(originalobj->GetSGNode()->BBox());
- replica->GetSGNode()->SetRadius(originalobj->GetSGNode()->Radius());
- // the size is correct, we can add the graphic controller to the physic engine
- replica->ActivateGraphicController(true);
-
- // now replicate logic
- vector<KX_GameObject*>::iterator git;
- for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
- {
- (*git)->ReParentLogic();
- }
-
- // relink any pointers as necessary, sort of a temporary solution
- for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
- {
- // this will also relink the actuators in the hierarchy
- (*git)->Relink(&m_map_gameobject_to_replica);
- if (referenceobj) {
- // add the object in the layer of the reference object
- (*git)->SetLayer(referenceobj->GetLayer());
- }
- else {
- // We don't know what layer set, so we set all visible layers in the blender scene.
- (*git)->SetLayer(m_blenderScene->lay);
- }
- }
-
- // replicate crosslinks etc. between logic bricks
- for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
- {
- ReplicateLogic((*git));
- }
-
- // check if there are objects with dupligroup in the hierarchy
- vector<KX_GameObject*> duplilist;
- for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
- {
- if ((*git)->IsDupliGroup())
- {
- // separate list as m_logicHierarchicalGameObjects is also used by DupliGroupRecurse()
- duplilist.push_back(*git);
- }
- }
- for (git = duplilist.begin();!(git==duplilist.end());++git)
- {
- DupliGroupRecurse(*git, 0);
- }
- // don't release replica here because we are returning it, not done with it...
- return replica;
-}
-
-
-
-void KX_Scene::RemoveObject(class CValue* gameobj)
-{
- KX_GameObject* newobj = (KX_GameObject*) gameobj;
-
- // disconnect child from parent
- SG_Node* node = newobj->GetSGNode();
-
- if (node)
- {
- node->DisconnectFromParent();
-
- // recursively destruct
- node->Destruct();
- }
- //no need to do that: the object is destroyed and memory released
- //newobj->SetSGNode(0);
-}
-
-void KX_Scene::RemoveDupliGroup(class CValue *gameobj)
-{
- KX_GameObject *newobj = (KX_GameObject *) gameobj;
-
- if (newobj->IsDupliGroup()) {
- for (int i = 0; i < newobj->GetInstanceObjects()->GetCount(); i++) {
- CValue *obj = newobj->GetInstanceObjects()->GetValue(i);
- DelayedRemoveObject(obj);
- }
- }
-}
-
-void KX_Scene::DelayedRemoveObject(class CValue* gameobj)
-{
- RemoveDupliGroup(gameobj);
-
- if (!m_euthanasyobjects->SearchValue(gameobj))
- {
- m_euthanasyobjects->Add(gameobj->AddRef());
- }
-}
-
-int KX_Scene::NewRemoveObject(class CValue* gameobj)
-{
- int ret;
- KX_GameObject* newobj = (KX_GameObject*) gameobj;
-
- /* remove property from debug list */
- RemoveObjectDebugProperties(newobj);
-
- /* Invalidate the python reference, since the object may exist in script lists
- * its possible that it wont be automatically invalidated, so do it manually here,
- *
- * if for some reason the object is added back into the scene python can always get a new Proxy
- */
- newobj->InvalidateProxy();
-
- // keep the blender->game object association up to date
- // note that all the replicas of an object will have the same
- // blender object, that's why we need to check the game object
- // as only the deletion of the original object must be recorded
- m_logicmgr->UnregisterGameObj(newobj->GetBlenderObject(), gameobj);
-
- //todo: look at this
- //GetPhysicsEnvironment()->RemovePhysicsController(gameobj->getPhysicsController());
-
- // remove all sensors/controllers/actuators from logicsystem...
-
- SCA_SensorList& sensors = newobj->GetSensors();
- for (SCA_SensorList::iterator its = sensors.begin();
- !(its==sensors.end());its++)
- {
- m_logicmgr->RemoveSensor(*its);
- }
-
- SCA_ControllerList& controllers = newobj->GetControllers();
- for (SCA_ControllerList::iterator itc = controllers.begin();
- !(itc==controllers.end());itc++)
- {
- m_logicmgr->RemoveController(*itc);
- (*itc)->ReParent(NULL);
- }
-
- SCA_ActuatorList& actuators = newobj->GetActuators();
- for (SCA_ActuatorList::iterator ita = actuators.begin();
- !(ita==actuators.end());ita++)
- {
- m_logicmgr->RemoveActuator(*ita);
- }
- // the sensors/controllers/actuators must also be released, this is done in ~SCA_IObject
-
- // now remove the timer properties from the time manager
- int numprops = newobj->GetPropertyCount();
-
- for (int i = 0; i < numprops; i++)
- {
- CValue* propval = newobj->GetProperty(i);
- if (propval->GetProperty("timer"))
- {
- m_timemgr->RemoveTimeProperty(propval);
- }
- }
-
- // if the object is the dupligroup proxy, you have to cleanup all m_pDupliGroupObject's in all
- // instances refering to this group
- if (newobj->GetInstanceObjects()) {
- for (int i = 0; i < newobj->GetInstanceObjects()->GetCount(); i++) {
- KX_GameObject* instance = (KX_GameObject*)newobj->GetInstanceObjects()->GetValue(i);
- instance->RemoveDupliGroupObject();
- }
- }
-
- // if this object was part of a group, make sure to remove it from that group's instance list
- KX_GameObject* group = newobj->GetDupliGroupObject();
- if (group)
- group->RemoveInstanceObject(newobj);
-
- newobj->RemoveMeshes();
-
- switch (newobj->GetGameObjectType()) {
- case SCA_IObject::OBJ_CAMERA:
- m_cameras.remove((KX_Camera *)newobj);
- break;
- case SCA_IObject::OBJ_TEXT:
- m_fonts.remove((KX_FontObject *)newobj);
- break;
- }
-
- ret = 1;
- if (newobj->GetGameObjectType()==SCA_IObject::OBJ_LIGHT && m_lightlist->RemoveValue(newobj))
- ret = newobj->Release();
- if (m_objectlist->RemoveValue(newobj))
- ret = newobj->Release();
- if (m_tempObjectList->RemoveValue(newobj))
- ret = newobj->Release();
- if (m_parentlist->RemoveValue(newobj))
- ret = newobj->Release();
- if (m_inactivelist->RemoveValue(newobj))
- ret = newobj->Release();
- if (m_euthanasyobjects->RemoveValue(newobj))
- ret = newobj->Release();
- if (m_animatedlist->RemoveValue(newobj))
- ret = newobj->Release();
-
- /* Warning 'newobj' maye be freed now, only compare, don't access */
-
-
- if (newobj == m_active_camera)
- {
- //no AddRef done on m_active_camera so no Release
- //m_active_camera->Release();
- m_active_camera = NULL;
- }
-
- /* currently does nothing, keep in case we need to Unregister something */
-#if 0
- if (m_sceneConverter)
- m_sceneConverter->UnregisterGameObject(newobj);
-#endif
-
- // return value will be 0 if the object is actually deleted (all reference gone)
-
- return ret;
-}
-
-
-
-void KX_Scene::ReplaceMesh(class CValue* obj,void* meshobj, bool use_gfx, bool use_phys)
-{
- KX_GameObject* gameobj = static_cast<KX_GameObject*>(obj);
- RAS_MeshObject* mesh = static_cast<RAS_MeshObject*>(meshobj);
-
- if (!gameobj) {
- std::cout << "KX_Scene::ReplaceMesh Warning: invalid object, doing nothing" << std::endl;
- return;
- }
-
- if (use_gfx && mesh != NULL)
- {
- gameobj->RemoveMeshes();
- gameobj->AddMesh(mesh);
-
- if (gameobj->m_isDeformable)
- {
- BL_DeformableGameObject* newobj = static_cast<BL_DeformableGameObject*>( gameobj );
-
- if (newobj->GetDeformer())
- {
- delete newobj->GetDeformer();
- newobj->SetDeformer(NULL);
- }
-
- if (mesh->GetMesh())
- {
- // we must create a new deformer but which one?
- KX_GameObject* parentobj = newobj->GetParent();
- // this always return the original game object (also for replicate)
- Object* blendobj = newobj->GetBlenderObject();
- // object that owns the new mesh
- Object* oldblendobj = static_cast<struct Object*>(m_logicmgr->FindBlendObjByGameMeshName(mesh->GetName()));
- Mesh* blendmesh = mesh->GetMesh();
-
- bool bHasModifier = BL_ModifierDeformer::HasCompatibleDeformer(blendobj);
- bool bHasShapeKey = blendmesh->key != NULL && blendmesh->key->type==KEY_RELATIVE;
- bool bHasDvert = blendmesh->dvert != NULL;
- bool bHasArmature =
- BL_ModifierDeformer::HasArmatureDeformer(blendobj) &&
- parentobj && // current parent is armature
- parentobj->GetGameObjectType() == SCA_IObject::OBJ_ARMATURE &&
- oldblendobj && // needed for mesh deform
- blendobj->parent && // original object had armature (not sure this test is needed)
- blendobj->parent->type == OB_ARMATURE &&
- blendmesh->dvert!=NULL; // mesh has vertex group
-#ifdef WITH_BULLET
- bool bHasSoftBody = (!parentobj && (blendobj->gameflag & OB_SOFT_BODY));
-#endif
-
- if (oldblendobj==NULL) {
- if (bHasModifier || bHasShapeKey || bHasDvert || bHasArmature) {
- std::cout << "warning: ReplaceMesh() new mesh is not used in an object from the current scene, you will get incorrect behavior" << std::endl;
- bHasShapeKey= bHasDvert= bHasArmature=bHasModifier= false;
- }
- }
-
- if (bHasModifier)
- {
- BL_ModifierDeformer* modifierDeformer;
- if (bHasShapeKey || bHasArmature)
- {
- modifierDeformer = new BL_ModifierDeformer(
- newobj,
- m_blenderScene,
- oldblendobj, blendobj,
- mesh,
- true,
- static_cast<BL_ArmatureObject*>( parentobj->AddRef() )
- );
- modifierDeformer->LoadShapeDrivers(parentobj);
- }
- else
- {
- modifierDeformer = new BL_ModifierDeformer(
- newobj,
- m_blenderScene,
- oldblendobj, blendobj,
- mesh,
- false,
- NULL
- );
- }
- newobj->SetDeformer(modifierDeformer);
- }
- else if (bHasShapeKey) {
- BL_ShapeDeformer* shapeDeformer;
- if (bHasArmature)
- {
- shapeDeformer = new BL_ShapeDeformer(
- newobj,
- oldblendobj, blendobj,
- mesh,
- true,
- true,
- static_cast<BL_ArmatureObject*>( parentobj->AddRef() )
- );
- shapeDeformer->LoadShapeDrivers(parentobj);
- }
- else
- {
- shapeDeformer = new BL_ShapeDeformer(
- newobj,
- oldblendobj, blendobj,
- mesh,
- false,
- true,
- NULL
- );
- }
- newobj->SetDeformer( shapeDeformer);
- }
- else if (bHasArmature)
- {
- BL_SkinDeformer* skinDeformer = new BL_SkinDeformer(
- newobj,
- oldblendobj, blendobj,
- mesh,
- true,
- true,
- static_cast<BL_ArmatureObject*>( parentobj->AddRef() )
- );
- newobj->SetDeformer(skinDeformer);
- }
- else if (bHasDvert)
- {
- BL_MeshDeformer* meshdeformer = new BL_MeshDeformer(
- newobj, oldblendobj, mesh
- );
- newobj->SetDeformer(meshdeformer);
- }
-#ifdef WITH_BULLET
- else if (bHasSoftBody)
- {
- KX_SoftBodyDeformer *softdeformer = new KX_SoftBodyDeformer(mesh, newobj);
- newobj->SetDeformer(softdeformer);
- }
-#endif
- }
- }
-
- gameobj->AddMeshUser();
- }
-
- if (use_phys) { /* update the new assigned mesh with the physics mesh */
- if (gameobj->GetPhysicsController())
- gameobj->GetPhysicsController()->ReinstancePhysicsShape(NULL, use_gfx?NULL:mesh);
- }
-}
-
-/* Font Object routines */
-void KX_Scene::AddFont(KX_FontObject* font)
-{
- if (!FindFont(font))
- m_fonts.push_back(font);
-}
-
-KX_FontObject* KX_Scene::FindFont(KX_FontObject* font)
-{
- list<KX_FontObject*>::iterator it = m_fonts.begin();
-
- while ((it != m_fonts.end()) && ((*it) != font))
- {
- ++it;
- }
-
- return ((it == m_fonts.end()) ? NULL : (*it));
-}
-
-
-/* Camera Object routines */
-KX_Camera* KX_Scene::FindCamera(KX_Camera* cam)
-{
- list<KX_Camera*>::iterator it = m_cameras.begin();
-
- while ((it != m_cameras.end()) && ((*it) != cam)) {
- it++;
- }
-
- return ((it == m_cameras.end()) ? NULL : (*it));
-}
-
-
-KX_Camera* KX_Scene::FindCamera(STR_String& name)
-{
- list<KX_Camera*>::iterator it = m_cameras.begin();
-
- while ((it != m_cameras.end()) && ((*it)->GetName() != name)) {
- it++;
- }
-
- return ((it == m_cameras.end()) ? NULL : (*it));
-}
-
-void KX_Scene::AddCamera(KX_Camera* cam)
-{
- if (!FindCamera(cam))
- m_cameras.push_back(cam);
-}
-
-
-KX_Camera* KX_Scene::GetActiveCamera()
-{
- // NULL if not defined
- return m_active_camera;
-}
-
-
-void KX_Scene::SetActiveCamera(KX_Camera* cam)
-{
- // only set if the cam is in the active list? Or add it otherwise?
- if (!FindCamera(cam)) {
- AddCamera(cam);
- if (cam) std::cout << "Added cam " << cam->GetName() << std::endl;
- }
-
- m_active_camera = cam;
-}
-
-void KX_Scene::SetCameraOnTop(KX_Camera* cam)
-{
- if (!FindCamera(cam)) {
- // adding is always done at the back, so that's all that needs to be done
- AddCamera(cam);
- if (cam) std::cout << "Added cam " << cam->GetName() << std::endl;
- } else {
- m_cameras.remove(cam);
- m_cameras.push_back(cam);
- }
-}
-
-void KX_Scene::MarkVisible(SG_Tree *node, RAS_IRasterizer* rasty, KX_Camera* cam, int layer)
-{
- int intersect = KX_Camera::INTERSECT;
- KX_GameObject *gameobj = node->Client()?(KX_GameObject*) node->Client()->GetSGClientObject():NULL;
- bool visible = (gameobj && gameobj->GetVisible() && (!layer || (gameobj->GetLayer() & layer)));
- bool dotest = visible || node->Left() || node->Right();
-
- /* If the camera is inside the box, assume intersect. */
- if (dotest && !node->inside( cam->NodeGetWorldPosition()))
- {
- MT_Scalar radius = node->Radius();
- MT_Point3 center = node->Center();
-
- intersect = cam->SphereInsideFrustum(center, radius);
-
- if (intersect == KX_Camera::INTERSECT)
- {
- MT_Point3 box[8];
- node->get(box);
- intersect = cam->BoxInsideFrustum(box);
- }
- }
-
- switch (intersect)
- {
- case KX_Camera::OUTSIDE:
- MarkSubTreeVisible(node, rasty, false, cam);
- break;
- case KX_Camera::INTERSECT:
- if (gameobj)
- MarkVisible(rasty, gameobj, cam, layer);
- if (node->Left())
- MarkVisible(node->Left(), rasty, cam, layer);
- if (node->Right())
- MarkVisible(node->Right(), rasty, cam, layer);
- break;
- case KX_Camera::INSIDE:
- MarkSubTreeVisible(node, rasty, true, cam, layer);
- break;
- }
-}
-
-void KX_Scene::MarkSubTreeVisible(SG_Tree *node, RAS_IRasterizer* rasty, bool visible, KX_Camera* cam, int layer)
-{
- if (node->Client())
- {
- KX_GameObject *gameobj = (KX_GameObject*) node->Client()->GetSGClientObject();
- if (gameobj->GetVisible())
- {
- if (visible)
- {
- int nummeshes = gameobj->GetMeshCount();
-
- // this adds the vertices to the display list
- for (int m=0;m<nummeshes;m++)
- (gameobj->GetMesh(m))->SchedulePolygons(rasty->GetDrawingMode());
- }
-
- gameobj->SetCulled(!visible);
- gameobj->UpdateBuckets(false);
- }
- }
- if (node->Left())
- MarkSubTreeVisible(node->Left(), rasty, visible, cam, layer);
- if (node->Right())
- MarkSubTreeVisible(node->Right(), rasty, visible, cam, layer);
-}
-
-void KX_Scene::MarkVisible(RAS_IRasterizer* rasty, KX_GameObject* gameobj,KX_Camera* cam,int layer)
-{
- // User (Python/Actuator) has forced object invisible...
- if (!gameobj->GetSGNode() || !gameobj->GetVisible())
- return;
-
- // Shadow lamp layers
- if (layer && !(gameobj->GetLayer() & layer)) {
- gameobj->SetCulled(true);
- gameobj->UpdateBuckets(false);
- return;
- }
-
- // If Frustum culling is off, the object is always visible.
- bool vis = !cam->GetFrustumCulling();
-
- // If the camera is inside this node, then the object is visible.
- if (!vis)
- {
- vis = gameobj->GetSGNode()->inside( cam->GetCameraLocation() );
- }
-
- // Test the object's bound sphere against the view frustum.
- if (!vis)
- {
- MT_Vector3 scale = gameobj->GetSGNode()->GetWorldScaling();
- MT_Scalar radius = fabs(scale[scale.closestAxis()] * gameobj->GetSGNode()->Radius());
- switch (cam->SphereInsideFrustum(gameobj->NodeGetWorldPosition(), radius))
- {
- case KX_Camera::INSIDE:
- vis = true;
- break;
- case KX_Camera::OUTSIDE:
- vis = false;
- break;
- case KX_Camera::INTERSECT:
- // Test the object's bound box against the view frustum.
- MT_Point3 box[8];
- gameobj->GetSGNode()->getBBox(box);
- vis = cam->BoxInsideFrustum(box) != KX_Camera::OUTSIDE;
- break;
- }
- }
-
- if (vis)
- {
- int nummeshes = gameobj->GetMeshCount();
-
- for (int m=0;m<nummeshes;m++)
- {
- // this adds the vertices to the display list
- (gameobj->GetMesh(m))->SchedulePolygons(rasty->GetDrawingMode());
- }
- // Visibility/ non-visibility are marked
- // elsewhere now.
- gameobj->SetCulled(false);
- gameobj->UpdateBuckets(false);
- } else {
- gameobj->SetCulled(true);
- gameobj->UpdateBuckets(false);
- }
-}
-
-void KX_Scene::PhysicsCullingCallback(KX_ClientObjectInfo *objectInfo, void* cullingInfo)
-{
- KX_GameObject* gameobj = objectInfo->m_gameobject;
- if (!gameobj->GetVisible())
- // ideally, invisible objects should be removed from the culling tree temporarily
- return;
- if (((CullingInfo*)cullingInfo)->m_layer && !(gameobj->GetLayer() & ((CullingInfo*)cullingInfo)->m_layer))
- // used for shadow: object is not in shadow layer
- return;
-
- // make object visible
- gameobj->SetCulled(false);
- gameobj->UpdateBuckets(false);
-}
-
-void KX_Scene::CalculateVisibleMeshes(RAS_IRasterizer* rasty,KX_Camera* cam, int layer)
-{
- bool dbvt_culling = false;
- if (m_dbvt_culling)
- {
- /* Reset KX_GameObject m_bCulled to true before doing culling
- * since DBVT culling will only set it to false.
- * This is similar to what RAS_BucketManager does for RAS_MeshSlot culling.
- */
- for (int i = 0; i < m_objectlist->GetCount(); i++) {
- KX_GameObject *gameobj = static_cast<KX_GameObject*>(m_objectlist->GetValue(i));
- gameobj->SetCulled(true);
- }
-
- // test culling through Bullet
- MT_Vector4 planes[6];
- // get the clip planes
- MT_Vector4* cplanes = cam->GetNormalizedClipPlanes();
- // and convert
- planes[0].setValue(cplanes[4].getValue()); // near
- planes[1].setValue(cplanes[5].getValue()); // far
- planes[2].setValue(cplanes[0].getValue()); // left
- planes[3].setValue(cplanes[1].getValue()); // right
- planes[4].setValue(cplanes[2].getValue()); // top
- planes[5].setValue(cplanes[3].getValue()); // bottom
- CullingInfo info(layer);
-
- float mvmat[16] = {0};
- cam->GetModelviewMatrix().getValue(mvmat);
- float pmat[16] = {0};
- cam->GetProjectionMatrix().getValue(pmat);
-
- dbvt_culling = m_physicsEnvironment->CullingTest(PhysicsCullingCallback,&info,planes,5,m_dbvt_occlusion_res,
- KX_GetActiveEngine()->GetCanvas()->GetViewPort(),
- mvmat, pmat);
- }
- if (!dbvt_culling) {
- // the physics engine couldn't help us, do it the hard way
- for (int i = 0; i < m_objectlist->GetCount(); i++)
- {
- MarkVisible(rasty, static_cast<KX_GameObject*>(m_objectlist->GetValue(i)), cam, layer);
- }
- }
-}
-
-// logic stuff
-void KX_Scene::LogicBeginFrame(double curtime)
-{
- // have a look at temp objects ...
- int lastobj = m_tempObjectList->GetCount() - 1;
-
- for (int i = lastobj; i >= 0; i--)
- {
- CValue* objval = m_tempObjectList->GetValue(i);
- CFloatValue* propval = (CFloatValue*) objval->GetProperty("::timebomb");
-
- if (propval)
- {
- float timeleft = (float)(propval->GetNumber() - 1.0/KX_KetsjiEngine::GetTicRate());
-
- if (timeleft > 0)
- {
- propval->SetFloat(timeleft);
- }
- else
- {
- DelayedRemoveObject(objval);
- // remove obj
- }
- }
- else
- {
- // all object is the tempObjectList should have a clock
- }
- }
- m_logicmgr->BeginFrame(curtime, 1.0/KX_KetsjiEngine::GetTicRate());
-}
-
-void KX_Scene::AddAnimatedObject(CValue* gameobj)
-{
- gameobj->AddRef();
- m_animatedlist->Add(gameobj);
-}
-
-static void update_anim_thread_func(TaskPool *pool, void *taskdata, int UNUSED(threadid))
-{
- KX_GameObject *gameobj, *child, *parent;
- CListValue *children;
- bool needs_update;
- double curtime = *(double*)BLI_task_pool_userdata(pool);
-
- gameobj = (KX_GameObject*)taskdata;
-
- // Non-armature updates are fast enough, so just update them
- needs_update = gameobj->GetGameObjectType() != SCA_IObject::OBJ_ARMATURE;
-
- if (!needs_update) {
- // If we got here, we're looking to update an armature, so check its children meshes
- // to see if we need to bother with a more expensive pose update
- children = gameobj->GetChildren();
-
- bool has_mesh = false, has_non_mesh = false;
-
- // Check for meshes that haven't been culled
- for (int j=0; j<children->GetCount(); ++j) {
- child = (KX_GameObject*)children->GetValue(j);
-
- if (!child->GetCulled()) {
- needs_update = true;
- break;
- }
-
- if (child->GetMeshCount() == 0)
- has_non_mesh = true;
- else
- has_mesh = true;
- }
-
- // If we didn't find a non-culled mesh, check to see
- // if we even have any meshes, and update if this
- // armature has only non-mesh children.
- if (!needs_update && !has_mesh && has_non_mesh)
- needs_update = true;
-
- children->Release();
- }
-
- if (needs_update) {
- gameobj->UpdateActionManager(curtime);
- children = gameobj->GetChildren();
- parent = gameobj->GetParent();
-
- // Only do deformers here if they are not parented to an armature, otherwise the armature will
- // handle updating its children
- if (gameobj->GetDeformer() && (!parent || parent->GetGameObjectType() != SCA_IObject::OBJ_ARMATURE))
- gameobj->GetDeformer()->Update();
-
- for (int j=0; j<children->GetCount(); ++j) {
- child = (KX_GameObject*)children->GetValue(j);
-
- if (child->GetDeformer()) {
- child->GetDeformer()->Update();
- }
- }
-
- children->Release();
- }
-}
-
-void KX_Scene::UpdateAnimations(double curtime)
-{
- TaskPool *pool = BLI_task_pool_create(KX_GetActiveEngine()->GetTaskScheduler(), &curtime);
-
- for (int i=0; i<m_animatedlist->GetCount(); ++i) {
- BLI_task_pool_push(pool, update_anim_thread_func, m_animatedlist->GetValue(i), false, TASK_PRIORITY_LOW);
- }
-
- BLI_task_pool_work_and_wait(pool);
- BLI_task_pool_free(pool);
-}
-
-void KX_Scene::LogicUpdateFrame(double curtime, bool frame)
-{
- m_logicmgr->UpdateFrame(curtime, frame);
-}
-
-
-
-void KX_Scene::LogicEndFrame()
-{
- m_logicmgr->EndFrame();
- int numobj;
-
- KX_GameObject* obj;
-
- while ((numobj = m_euthanasyobjects->GetCount()) > 0)
- {
- // remove the object from this list to make sure we will not hit it again
- obj = (KX_GameObject*)m_euthanasyobjects->GetValue(numobj-1);
- m_euthanasyobjects->Remove(numobj-1);
- obj->Release();
- RemoveObject(obj);
- }
-
- //prepare obstacle simulation for new frame
- if (m_obstacleSimulation)
- m_obstacleSimulation->UpdateObstacles();
-}
-
-
-
-/**
- * UpdateParents: SceneGraph transformation update.
- */
-void KX_Scene::UpdateParents(double curtime)
-{
- // we use the SG dynamic list
- SG_Node* node;
-
- while ((node = SG_Node::GetNextScheduled(m_sghead)) != NULL)
- {
- node->UpdateWorldData(curtime);
- }
-
- //for (int i=0; i<GetRootParentList()->GetCount(); i++)
- //{
- // KX_GameObject* parentobj = (KX_GameObject*)GetRootParentList()->GetValue(i);
- // parentobj->NodeUpdateGS(curtime);
- //}
-
- // the list must be empty here
- assert(m_sghead.Empty());
- // some nodes may be ready for reschedule, move them to schedule list for next time
- while ((node = SG_Node::GetNextRescheduled(m_sghead)) != NULL)
- {
- node->Schedule(m_sghead);
- }
-}
-
-
-RAS_MaterialBucket* KX_Scene::FindBucket(class RAS_IPolyMaterial* polymat, bool &bucketCreated)
-{
- return m_bucketmanager->FindBucket(polymat, bucketCreated);
-}
-
-
-
-void KX_Scene::RenderBuckets(const MT_Transform & cameratransform,
- class RAS_IRasterizer* rasty)
-{
- m_bucketmanager->Renderbuckets(cameratransform,rasty);
- KX_BlenderMaterial::EndFrame();
-}
-
-void KX_Scene::RenderFonts()
-{
- list<KX_FontObject*>::iterator it = m_fonts.begin();
- while (it != m_fonts.end()) {
- (*it)->DrawFontText();
- ++it;
- }
-}
-
-void KX_Scene::UpdateObjectLods(void)
-{
- KX_GameObject* gameobj;
-
- if (!this->m_active_camera)
- return;
-
- MT_Vector3 cam_pos = this->m_active_camera->NodeGetWorldPosition();
-
- for (int i = 0; i < this->GetObjectList()->GetCount(); i++) {
- gameobj = (KX_GameObject*) GetObjectList()->GetValue(i);
- if (!gameobj->GetCulled()) {
- gameobj->UpdateLod(cam_pos);
- }
- }
-}
-
-void KX_Scene::SetLodHysteresis(bool active)
-{
- m_isActivedHysteresis = active;
-}
-
-bool KX_Scene::IsActivedLodHysteresis(void)
-{
- return m_isActivedHysteresis;
-}
-
-void KX_Scene::SetLodHysteresisValue(int hysteresisvalue)
-{
- m_lodHysteresisValue = hysteresisvalue;
-}
-
-int KX_Scene::GetLodHysteresisValue(void)
-{
- return m_lodHysteresisValue;
-}
-
-void KX_Scene::UpdateObjectActivity(void)
-{
- if (m_activity_culling) {
- /* determine the activity criterium and set objects accordingly */
- int i=0;
-
- MT_Point3 camloc = GetActiveCamera()->NodeGetWorldPosition(); //GetCameraLocation();
-
- for (i=0;i<GetObjectList()->GetCount();i++)
- {
- KX_GameObject* ob = (KX_GameObject*) GetObjectList()->GetValue(i);
-
- if (!ob->GetIgnoreActivityCulling()) {
- /* Simple test: more than 10 away from the camera, count
- * Manhattan distance. */
- MT_Point3 obpos = ob->NodeGetWorldPosition();
-
- if ((fabsf(camloc[0] - obpos[0]) > m_activity_box_radius) ||
- (fabsf(camloc[1] - obpos[1]) > m_activity_box_radius) ||
- (fabsf(camloc[2] - obpos[2]) > m_activity_box_radius) )
- {
- ob->Suspend();
- }
- else {
- ob->Resume();
- }
- }
- }
- }
-}
-
-void KX_Scene::SetActivityCullingRadius(float f)
-{
- if (f < 0.5f)
- f = 0.5f;
- m_activity_box_radius = f;
-}
-
-NG_NetworkDeviceInterface* KX_Scene::GetNetworkDeviceInterface()
-{
- return m_networkDeviceInterface;
-}
-
-NG_NetworkScene* KX_Scene::GetNetworkScene()
-{
- return m_networkScene;
-}
-
-void KX_Scene::SetNetworkDeviceInterface(NG_NetworkDeviceInterface* newInterface)
-{
- m_networkDeviceInterface = newInterface;
-}
-
-void KX_Scene::SetNetworkScene(NG_NetworkScene *newScene)
-{
- m_networkScene = newScene;
-}
-
-
-void KX_Scene::SetGravity(const MT_Vector3& gravity)
-{
- GetPhysicsEnvironment()->SetGravity(gravity[0],gravity[1],gravity[2]);
-}
-
-MT_Vector3 KX_Scene::GetGravity()
-{
- MT_Vector3 gravity;
-
- GetPhysicsEnvironment()->GetGravity(gravity);
-
- return gravity;
-}
-
-void KX_Scene::SetSceneConverter(class KX_BlenderSceneConverter* sceneConverter)
-{
- m_sceneConverter = sceneConverter;
-}
-
-void KX_Scene::SetPhysicsEnvironment(class PHY_IPhysicsEnvironment* physEnv)
-{
- m_physicsEnvironment = physEnv;
- if (m_physicsEnvironment) {
- KX_TouchEventManager* touchmgr = new KX_TouchEventManager(m_logicmgr, physEnv);
- m_logicmgr->RegisterEventManager(touchmgr);
- }
-}
-
-void KX_Scene::setSuspendedTime(double suspendedtime)
-{
- m_suspendedtime = suspendedtime;
-}
-double KX_Scene::getSuspendedTime()
-{
- return m_suspendedtime;
-}
-void KX_Scene::setSuspendedDelta(double suspendeddelta)
-{
- m_suspendeddelta = suspendeddelta;
-}
-double KX_Scene::getSuspendedDelta()
-{
- return m_suspendeddelta;
-}
-
-short KX_Scene::GetAnimationFPS()
-{
- return m_blenderScene->r.frs_sec;
-}
-
-static void MergeScene_LogicBrick(SCA_ILogicBrick* brick, KX_Scene *from, KX_Scene *to)
-{
- SCA_LogicManager *logicmgr= to->GetLogicManager();
-
- brick->Replace_IScene(to);
- brick->Replace_NetworkScene(to->GetNetworkScene());
- brick->SetLogicManager(to->GetLogicManager());
-
- // If we end up replacing a KX_TouchEventManager, we need to make sure
- // physics controllers are properly in place. In other words, do this
- // after merging physics controllers!
- SCA_ISensor *sensor= dynamic_cast<class SCA_ISensor *>(brick);
- if (sensor) {
- sensor->Replace_EventManager(logicmgr);
- }
-
- SCA_2DFilterActuator *filter_actuator = dynamic_cast<class SCA_2DFilterActuator*>(brick);
- if (filter_actuator) {
- filter_actuator->SetScene(to);
- }
-
-#ifdef WITH_PYTHON
- // Python must be called from the main thread unless we want to deal
- // with GIL issues. So, this is delayed until here in case of async
- // libload (originally in KX_ConvertControllers)
- SCA_PythonController *pyctrl = dynamic_cast<SCA_PythonController*>(brick);
- if (pyctrl) {
- pyctrl->SetNamespace(KX_GetActiveEngine()->GetPyNamespace());
-
- if (pyctrl->m_mode==SCA_PythonController::SCA_PYEXEC_SCRIPT)
- pyctrl->Compile();
- }
-#endif
-}
-
-static void MergeScene_GameObject(KX_GameObject* gameobj, KX_Scene *to, KX_Scene *from)
-{
- {
- SCA_ActuatorList& actuators= gameobj->GetActuators();
- SCA_ActuatorList::iterator ita;
-
- for (ita = actuators.begin(); !(ita==actuators.end()); ++ita)
- {
- MergeScene_LogicBrick(*ita, from, to);
- }
- }
-
-
- {
- SCA_SensorList& sensors= gameobj->GetSensors();
- SCA_SensorList::iterator its;
-
- for (its = sensors.begin(); !(its==sensors.end()); ++its)
- {
- MergeScene_LogicBrick(*its, from, to);
- }
- }
-
- {
- SCA_ControllerList& controllers= gameobj->GetControllers();
- SCA_ControllerList::iterator itc;
-
- for (itc = controllers.begin(); !(itc==controllers.end()); ++itc)
- {
- SCA_IController *cont= *itc;
- MergeScene_LogicBrick(cont, from, to);
- }
- }
-
- /* graphics controller */
- PHY_IController *ctrl = gameobj->GetGraphicController();
- if (ctrl) {
- /* SHOULD update the m_cullingTree */
- ctrl->SetPhysicsEnvironment(to->GetPhysicsEnvironment());
- }
-
- ctrl = gameobj->GetPhysicsController();
- if (ctrl) {
- ctrl->SetPhysicsEnvironment(to->GetPhysicsEnvironment());
- }
-
- /* SG_Node can hold a scene reference */
- SG_Node *sg= gameobj->GetSGNode();
- if (sg) {
- if (sg->GetSGClientInfo() == from) {
- sg->SetSGClientInfo(to);
-
- /* Make sure to grab the children too since they might not be tied to a game object */
- NodeList children = sg->GetSGChildren();
- for (int i=0; i<children.size(); i++)
- children[i]->SetSGClientInfo(to);
- }
- }
- /* If the object is a light, update it's scene */
- if (gameobj->GetGameObjectType() == SCA_IObject::OBJ_LIGHT)
- ((KX_LightObject*)gameobj)->UpdateScene(to);
-
- if (gameobj->GetGameObjectType() == SCA_IObject::OBJ_CAMERA)
- to->AddCamera((KX_Camera*)gameobj);
-
- // All armatures should be in the animated object list to be umpdated.
- if (gameobj->GetGameObjectType() == SCA_IObject::OBJ_ARMATURE)
- to->AddAnimatedObject(gameobj);
-
- /* Add the object to the scene's logic manager */
- to->GetLogicManager()->RegisterGameObjectName(gameobj->GetName(), gameobj);
- to->GetLogicManager()->RegisterGameObj(gameobj->GetBlenderObject(), gameobj);
-
- for (int i = 0; i < gameobj->GetMeshCount(); ++i) {
- RAS_MeshObject *meshobj = gameobj->GetMesh(i);
- // Register the mesh object by name and blender object.
- to->GetLogicManager()->RegisterGameMeshName(meshobj->GetName(), gameobj->GetBlenderObject());
- to->GetLogicManager()->RegisterMeshName(meshobj->GetName(), meshobj);
- }
-}
-
-bool KX_Scene::MergeScene(KX_Scene *other)
-{
- PHY_IPhysicsEnvironment *env = this->GetPhysicsEnvironment();
- PHY_IPhysicsEnvironment *env_other = other->GetPhysicsEnvironment();
-
- if ((env==NULL) != (env_other==NULL)) /* TODO - even when both scenes have NONE physics, the other is loaded with bullet enabled, ??? */
- {
- printf("KX_Scene::MergeScene: physics scenes type differ, aborting\n");
- printf("\tsource %d, terget %d\n", (int)(env!=NULL), (int)(env_other!=NULL));
- return false;
- }
-
- if (GetSceneConverter() != other->GetSceneConverter()) {
- printf("KX_Scene::MergeScene: converters differ, aborting\n");
- return false;
- }
-
-
- GetBucketManager()->MergeBucketManager(other->GetBucketManager(), this);
-
-
- /* active + inactive == all ??? - lets hope so */
- for (int i = 0; i < other->GetObjectList()->GetCount(); i++)
- {
- KX_GameObject* gameobj = (KX_GameObject*)other->GetObjectList()->GetValue(i);
- MergeScene_GameObject(gameobj, this, other);
-
- /* add properties to debug list for LibLoad objects */
- if (KX_GetActiveEngine()->GetAutoAddDebugProperties()) {
- AddObjectDebugProperties(gameobj);
- }
-
- gameobj->UpdateBuckets(false); /* only for active objects */
- }
-
- for (int i = 0; i < other->GetInactiveList()->GetCount(); i++)
- {
- KX_GameObject* gameobj = (KX_GameObject*)other->GetInactiveList()->GetValue(i);
- MergeScene_GameObject(gameobj, this, other);
- }
-
- if (env) {
- env->MergeEnvironment(env_other);
- CListValue *otherObjects = other->GetObjectList();
-
- // List of all physics objects to merge (needed by ReplicateConstraints).
- std::vector<KX_GameObject *> physicsObjects;
- for (unsigned int i = 0; i < otherObjects->GetCount(); ++i) {
- KX_GameObject *gameobj = (KX_GameObject *)otherObjects->GetValue(i);
- if (gameobj->GetPhysicsController()) {
- physicsObjects.push_back(gameobj);
- }
- }
-
- for (unsigned int i = 0; i < physicsObjects.size(); ++i) {
- KX_GameObject *gameobj = physicsObjects[i];
- // Replicate all constraints in the right physics environment.
- gameobj->GetPhysicsController()->ReplicateConstraints(gameobj, physicsObjects);
- gameobj->ClearConstraints();
- }
- }
-
-
- GetTempObjectList()->MergeList(other->GetTempObjectList());
- other->GetTempObjectList()->ReleaseAndRemoveAll();
-
- GetObjectList()->MergeList(other->GetObjectList());
- other->GetObjectList()->ReleaseAndRemoveAll();
-
- GetInactiveList()->MergeList(other->GetInactiveList());
- other->GetInactiveList()->ReleaseAndRemoveAll();
-
- GetRootParentList()->MergeList(other->GetRootParentList());
- other->GetRootParentList()->ReleaseAndRemoveAll();
-
- GetLightList()->MergeList(other->GetLightList());
- other->GetLightList()->ReleaseAndRemoveAll();
-
- /* move materials across, assume they both use the same scene-converters
- * Do this after lights are merged so materials can use the lights in shaders
- */
- GetSceneConverter()->MergeScene(this, other);
-
- /* merge logic */
- {
- SCA_LogicManager *logicmgr= GetLogicManager();
- SCA_LogicManager *logicmgr_other= other->GetLogicManager();
-
- vector<class SCA_EventManager*>evtmgrs= logicmgr->GetEventManagers();
- //vector<class SCA_EventManager*>evtmgrs_others= logicmgr_other->GetEventManagers();
-
- //SCA_EventManager *evtmgr;
- SCA_EventManager *evtmgr_other;
-
- for (unsigned int i= 0; i < evtmgrs.size(); i++) {
- evtmgr_other= logicmgr_other->FindEventManager(evtmgrs[i]->GetType());
-
- if (evtmgr_other) /* unlikely but possible one scene has a joystick and not the other */
- evtmgr_other->Replace_LogicManager(logicmgr);
-
- /* when merging objects sensors are moved across into the new manager, don't need to do this here */
- }
-
- /* grab any timer properties from the other scene */
- SCA_TimeEventManager *timemgr= GetTimeEventManager();
- SCA_TimeEventManager *timemgr_other= other->GetTimeEventManager();
- vector<CValue*> times = timemgr_other->GetTimeValues();
-
- for (unsigned int i= 0; i < times.size(); i++) {
- timemgr->AddTimeProperty(times[i]);
- }
-
- }
- return true;
-}
-
-void KX_Scene::Update2DFilter(vector<STR_String>& propNames, void* gameObj, RAS_2DFilterManager::RAS_2DFILTER_MODE filtermode, int pass, STR_String& text)
-{
- m_filtermanager.EnableFilter(propNames, gameObj, filtermode, pass, text);
-}
-
-void KX_Scene::Render2DFilters(RAS_ICanvas* canvas)
-{
- m_filtermanager.RenderFilters(canvas);
-}
-
-#ifdef WITH_PYTHON
-
-void KX_Scene::RunDrawingCallbacks(PyObject *cb_list)
-{
- if (!cb_list || PyList_GET_SIZE(cb_list) == 0)
- return;
-
- RunPythonCallBackList(cb_list, NULL, 0, 0);
-}
-
-//----------------------------------------------------------------------------
-//Python
-
-PyTypeObject KX_Scene::Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "KX_Scene",
- sizeof(PyObjectPlus_Proxy),
- 0,
- py_base_dealloc,
- 0,
- 0,
- 0,
- 0,
- py_base_repr,
- 0,
- &Sequence,
- &Mapping,
- 0,0,0,0,0,0,
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
- 0,0,0,0,0,0,0,
- Methods,
- 0,
- 0,
- &CValue::Type,
- 0,0,0,0,0,0,
- py_base_new
-};
-
-PyMethodDef KX_Scene::Methods[] = {
- KX_PYMETHODTABLE(KX_Scene, addObject),
- KX_PYMETHODTABLE(KX_Scene, end),
- KX_PYMETHODTABLE(KX_Scene, restart),
- KX_PYMETHODTABLE(KX_Scene, replace),
- KX_PYMETHODTABLE(KX_Scene, suspend),
- KX_PYMETHODTABLE(KX_Scene, resume),
- KX_PYMETHODTABLE(KX_Scene, drawObstacleSimulation),
-
-
- /* dict style access */
- KX_PYMETHODTABLE(KX_Scene, get),
-
- {NULL,NULL} //Sentinel
-};
-static PyObject *Map_GetItem(PyObject *self_v, PyObject *item)
-{
- KX_Scene* self = static_cast<KX_Scene*>BGE_PROXY_REF(self_v);
- const char *attr_str= _PyUnicode_AsString(item);
- PyObject *pyconvert;
-
- if (self == NULL) {
- PyErr_SetString(PyExc_SystemError, "val = scene[key]: KX_Scene, " BGE_PROXY_ERROR_MSG);
- return NULL;
- }
-
- if (!self->m_attr_dict)
- self->m_attr_dict = PyDict_New();
-
- if (self->m_attr_dict && (pyconvert=PyDict_GetItem(self->m_attr_dict, item))) {
-
- if (attr_str)
- PyErr_Clear();
- Py_INCREF(pyconvert);
- return pyconvert;
- }
- else {
- if (attr_str) PyErr_Format(PyExc_KeyError, "value = scene[key]: KX_Scene, key \"%s\" does not exist", attr_str);
- else PyErr_SetString(PyExc_KeyError, "value = scene[key]: KX_Scene, key does not exist");
- return NULL;
- }
-
-}
-
-static int Map_SetItem(PyObject *self_v, PyObject *key, PyObject *val)
-{
- KX_Scene* self = static_cast<KX_Scene*>BGE_PROXY_REF(self_v);
- const char *attr_str= _PyUnicode_AsString(key);
- if (attr_str==NULL)
- PyErr_Clear();
-
- if (self == NULL) {
- PyErr_SetString(PyExc_SystemError, "scene[key] = value: KX_Scene, " BGE_PROXY_ERROR_MSG);
- return -1;
- }
-
- if (!self->m_attr_dict)
- self->m_attr_dict = PyDict_New();
-
- if (val==NULL) { /* del ob["key"] */
- int del= 0;
-
- if (self->m_attr_dict)
- del |= (PyDict_DelItem(self->m_attr_dict, key)==0) ? 1:0;
-
- if (del==0) {
- if (attr_str) PyErr_Format(PyExc_KeyError, "scene[key] = value: KX_Scene, key \"%s\" could not be set", attr_str);
- else PyErr_SetString(PyExc_KeyError, "del scene[key]: KX_Scene, key could not be deleted");
- return -1;
- }
- else if (self->m_attr_dict) {
- PyErr_Clear(); /* PyDict_DelItem sets an error when it fails */
- }
- }
- else { /* ob["key"] = value */
- int set = 0;
-
- if (self->m_attr_dict==NULL) /* lazy init */
- self->m_attr_dict= PyDict_New();
-
-
- if (PyDict_SetItem(self->m_attr_dict, key, val)==0)
- set= 1;
- else
- PyErr_SetString(PyExc_KeyError, "scene[key] = value: KX_Scene, key not be added to internal dictionary");
-
- if (set==0)
- return -1; /* pythons error value */
-
- }
-
- return 0; /* success */
-}
-
-static int Seq_Contains(PyObject *self_v, PyObject *value)
-{
- KX_Scene* self = static_cast<KX_Scene*>BGE_PROXY_REF(self_v);
-
- if (self == NULL) {
- PyErr_SetString(PyExc_SystemError, "val in scene: KX_Scene, " BGE_PROXY_ERROR_MSG);
- return -1;
- }
-
- if (!self->m_attr_dict)
- self->m_attr_dict = PyDict_New();
-
- if (self->m_attr_dict && PyDict_GetItem(self->m_attr_dict, value))
- return 1;
-
- return 0;
-}
-
-PyMappingMethods KX_Scene::Mapping = {
- (lenfunc)NULL, /* inquiry mp_length */
- (binaryfunc)Map_GetItem, /* binaryfunc mp_subscript */
- (objobjargproc)Map_SetItem, /* objobjargproc mp_ass_subscript */
-};
-
-PySequenceMethods KX_Scene::Sequence = {
- NULL, /* Cant set the len otherwise it can evaluate as false */
- NULL, /* sq_concat */
- NULL, /* sq_repeat */
- NULL, /* sq_item */
- NULL, /* sq_slice */
- NULL, /* sq_ass_item */
- NULL, /* sq_ass_slice */
- (objobjproc)Seq_Contains, /* sq_contains */
- (binaryfunc) NULL, /* sq_inplace_concat */
- (ssizeargfunc) NULL, /* sq_inplace_repeat */
-};
-
-PyObject *KX_Scene::pyattr_get_name(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_Scene* self = static_cast<KX_Scene*>(self_v);
- return PyUnicode_From_STR_String(self->GetName());
-}
-
-PyObject *KX_Scene::pyattr_get_objects(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_Scene* self = static_cast<KX_Scene*>(self_v);
- return self->GetObjectList()->GetProxy();
-}
-
-PyObject *KX_Scene::pyattr_get_objects_inactive(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_Scene* self = static_cast<KX_Scene*>(self_v);
- return self->GetInactiveList()->GetProxy();
-}
-
-PyObject *KX_Scene::pyattr_get_lights(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_Scene* self = static_cast<KX_Scene*>(self_v);
- return self->GetLightList()->GetProxy();
-}
-
-PyObject *KX_Scene::pyattr_get_world(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_Scene* self = static_cast<KX_Scene*>(self_v);
- KX_WorldInfo *world = self->GetWorldInfo();
-
- if (world->GetName() != "") {
- return world->GetProxy();
- }
- else {
- Py_RETURN_NONE;
- }
-}
-
-PyObject *KX_Scene::pyattr_get_cameras(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- /* With refcounts in this case...
- * the new CListValue is owned by python, so its possible python holds onto it longer then the BGE
- * however this is the same with "scene.objects + []", when you make a copy by adding lists.
- */
-
- KX_Scene* self = static_cast<KX_Scene*>(self_v);
- CListValue* clist = new CListValue();
-
- /* return self->GetCameras()->GetProxy(); */
-
- list<KX_Camera*>::iterator it = self->GetCameras()->begin();
- while (it != self->GetCameras()->end()) {
- clist->Add((*it)->AddRef());
- it++;
- }
-
- return clist->NewProxy(true);
-}
-
-PyObject *KX_Scene::pyattr_get_active_camera(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_Scene* self = static_cast<KX_Scene*>(self_v);
- KX_Camera* cam= self->GetActiveCamera();
- if (cam)
- return self->GetActiveCamera()->GetProxy();
- else
- Py_RETURN_NONE;
-}
-
-
-int KX_Scene::pyattr_set_active_camera(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_Scene* self = static_cast<KX_Scene*>(self_v);
- KX_Camera *camOb;
-
- if (!ConvertPythonToCamera(value, &camOb, false, "scene.active_camera = value: KX_Scene"))
- return PY_SET_ATTR_FAIL;
-
- self->SetActiveCamera(camOb);
- return PY_SET_ATTR_SUCCESS;
-}
-
-PyObject *KX_Scene::pyattr_get_drawing_callback_pre(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_Scene* self = static_cast<KX_Scene*>(self_v);
-
- if (self->m_draw_call_pre==NULL)
- self->m_draw_call_pre= PyList_New(0);
- Py_INCREF(self->m_draw_call_pre);
- return self->m_draw_call_pre;
-}
-
-PyObject *KX_Scene::pyattr_get_drawing_callback_post(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_Scene* self = static_cast<KX_Scene*>(self_v);
-
- if (self->m_draw_call_post==NULL)
- self->m_draw_call_post= PyList_New(0);
- Py_INCREF(self->m_draw_call_post);
- return self->m_draw_call_post;
-}
-
-PyObject *KX_Scene::pyattr_get_drawing_setup_callback_pre(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_Scene* self = static_cast<KX_Scene*>(self_v);
-
- if (self->m_draw_setup_call_pre == NULL)
- self->m_draw_setup_call_pre = PyList_New(0);
-
- Py_INCREF(self->m_draw_setup_call_pre);
- return self->m_draw_setup_call_pre;
-}
-
-int KX_Scene::pyattr_set_drawing_callback_pre(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_Scene* self = static_cast<KX_Scene*>(self_v);
-
- if (!PyList_CheckExact(value))
- {
- PyErr_SetString(PyExc_ValueError, "Expected a list");
- return PY_SET_ATTR_FAIL;
- }
- Py_XDECREF(self->m_draw_call_pre);
-
- Py_INCREF(value);
- self->m_draw_call_pre = value;
-
- return PY_SET_ATTR_SUCCESS;
-}
-
-int KX_Scene::pyattr_set_drawing_callback_post(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_Scene* self = static_cast<KX_Scene*>(self_v);
-
- if (!PyList_CheckExact(value))
- {
- PyErr_SetString(PyExc_ValueError, "Expected a list");
- return PY_SET_ATTR_FAIL;
- }
- Py_XDECREF(self->m_draw_call_post);
-
- Py_INCREF(value);
- self->m_draw_call_post = value;
-
- return PY_SET_ATTR_SUCCESS;
-}
-
-int KX_Scene::pyattr_set_drawing_setup_callback_pre(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_Scene* self = static_cast<KX_Scene*>(self_v);
-
- if (!PyList_CheckExact(value)) {
- PyErr_SetString(PyExc_ValueError, "Expected a list");
- return PY_SET_ATTR_FAIL;
- }
-
- Py_XDECREF(self->m_draw_setup_call_pre);
- Py_INCREF(value);
-
- self->m_draw_setup_call_pre = value;
- return PY_SET_ATTR_SUCCESS;
-}
-
-PyObject *KX_Scene::pyattr_get_gravity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_Scene* self = static_cast<KX_Scene*>(self_v);
-
- return PyObjectFrom(self->GetGravity());
-}
-
-int KX_Scene::pyattr_set_gravity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_Scene* self = static_cast<KX_Scene*>(self_v);
-
- MT_Vector3 vec;
- if (!PyVecTo(value, vec))
- return PY_SET_ATTR_FAIL;
-
- self->SetGravity(vec);
- return PY_SET_ATTR_SUCCESS;
-}
-
-PyAttributeDef KX_Scene::Attributes[] = {
- KX_PYATTRIBUTE_RO_FUNCTION("name", KX_Scene, pyattr_get_name),
- KX_PYATTRIBUTE_RO_FUNCTION("objects", KX_Scene, pyattr_get_objects),
- KX_PYATTRIBUTE_RO_FUNCTION("objectsInactive", KX_Scene, pyattr_get_objects_inactive),
- KX_PYATTRIBUTE_RO_FUNCTION("lights", KX_Scene, pyattr_get_lights),
- KX_PYATTRIBUTE_RO_FUNCTION("cameras", KX_Scene, pyattr_get_cameras),
- KX_PYATTRIBUTE_RO_FUNCTION("world", KX_Scene, pyattr_get_world),
- KX_PYATTRIBUTE_RW_FUNCTION("active_camera", KX_Scene, pyattr_get_active_camera, pyattr_set_active_camera),
- KX_PYATTRIBUTE_RW_FUNCTION("pre_draw", KX_Scene, pyattr_get_drawing_callback_pre, pyattr_set_drawing_callback_pre),
- KX_PYATTRIBUTE_RW_FUNCTION("post_draw", KX_Scene, pyattr_get_drawing_callback_post, pyattr_set_drawing_callback_post),
- KX_PYATTRIBUTE_RW_FUNCTION("pre_draw_setup", KX_Scene, pyattr_get_drawing_setup_callback_pre, pyattr_set_drawing_setup_callback_pre),
- KX_PYATTRIBUTE_RW_FUNCTION("gravity", KX_Scene, pyattr_get_gravity, pyattr_set_gravity),
- KX_PYATTRIBUTE_BOOL_RO("suspended", KX_Scene, m_suspend),
- KX_PYATTRIBUTE_BOOL_RO("activity_culling", KX_Scene, m_activity_culling),
- KX_PYATTRIBUTE_FLOAT_RW("activity_culling_radius", 0.5f, FLT_MAX, KX_Scene, m_activity_box_radius),
- KX_PYATTRIBUTE_BOOL_RO("dbvt_culling", KX_Scene, m_dbvt_culling),
- { NULL } //Sentinel
-};
-
-KX_PYMETHODDEF_DOC(KX_Scene, addObject,
-"addObject(object, other, time=0)\n"
-"Returns the added object.\n")
-{
- PyObject *pyob, *pyreference = Py_None;
- KX_GameObject *ob, *reference;
-
- int time = 0;
-
- if (!PyArg_ParseTuple(args, "O|Oi:addObject", &pyob, &pyreference, &time))
- return NULL;
-
- if (!ConvertPythonToGameObject(m_logicmgr, pyob, &ob, false, "scene.addObject(object, reference, time): KX_Scene (first argument)") ||
- !ConvertPythonToGameObject(m_logicmgr, pyreference, &reference, true, "scene.addObject(object, reference, time): KX_Scene (second argument)"))
- return NULL;
-
- if (!m_inactivelist->SearchValue(ob)) {
- PyErr_Format(PyExc_ValueError, "scene.addObject(object, reference, time): KX_Scene (first argument): object must be in an inactive layer");
- return NULL;
- }
- SCA_IObject *replica = AddReplicaObject((SCA_IObject*)ob, reference, time);
-
- // release here because AddReplicaObject AddRef's
- // the object is added to the scene so we don't want python to own a reference
- replica->Release();
- return replica->GetProxy();
-}
-
-KX_PYMETHODDEF_DOC(KX_Scene, end,
-"end()\n"
-"Removes this scene from the game.\n")
-{
-
- KX_GetActiveEngine()->RemoveScene(m_sceneName);
-
- Py_RETURN_NONE;
-}
-
-KX_PYMETHODDEF_DOC(KX_Scene, restart,
- "restart()\n"
- "Restarts this scene.\n")
-{
- KX_GetActiveEngine()->ReplaceScene(m_sceneName, m_sceneName);
-
- Py_RETURN_NONE;
-}
-
-KX_PYMETHODDEF_DOC(KX_Scene, replace,
- "replace(newScene)\n"
- "Replaces this scene with another one.\n"
- "Return True if the new scene exists and scheduled for replacement, False otherwise.\n")
-{
- char* name;
-
- if (!PyArg_ParseTuple(args, "s:replace", &name))
- return NULL;
-
- if (KX_GetActiveEngine()->ReplaceScene(m_sceneName, name))
- Py_RETURN_TRUE;
-
- Py_RETURN_FALSE;
-}
-
-KX_PYMETHODDEF_DOC(KX_Scene, suspend,
- "suspend()\n"
- "Suspends this scene.\n")
-{
- Suspend();
-
- Py_RETURN_NONE;
-}
-
-KX_PYMETHODDEF_DOC(KX_Scene, resume,
- "resume()\n"
- "Resumes this scene.\n")
-{
- Resume();
-
- Py_RETURN_NONE;
-}
-
-KX_PYMETHODDEF_DOC(KX_Scene, drawObstacleSimulation,
- "drawObstacleSimulation()\n"
- "Draw debug visualization of obstacle simulation.\n")
-{
- if (GetObstacleSimulation())
- GetObstacleSimulation()->DrawObstacles();
-
- Py_RETURN_NONE;
-}
-
-/* Matches python dict.get(key, [default]) */
-KX_PYMETHODDEF_DOC(KX_Scene, get, "")
-{
- PyObject *key;
- PyObject *def = Py_None;
- PyObject *ret;
-
- if (!PyArg_ParseTuple(args, "O|O:get", &key, &def))
- return NULL;
-
- if (m_attr_dict && (ret=PyDict_GetItem(m_attr_dict, key))) {
- Py_INCREF(ret);
- return ret;
- }
-
- Py_INCREF(def);
- return def;
-}
-
-#endif // WITH_PYTHON
diff --git a/source/gameengine/Ketsji/KX_Scene.h b/source/gameengine/Ketsji/KX_Scene.h
deleted file mode 100644
index 6d8ae8a321b..00000000000
--- a/source/gameengine/Ketsji/KX_Scene.h
+++ /dev/null
@@ -1,697 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file KX_Scene.h
- * \ingroup ketsji
- */
-
-#ifndef __KX_SCENE_H__
-#define __KX_SCENE_H__
-
-
-#include "KX_PhysicsEngineEnums.h"
-
-#include <vector>
-#include <set>
-#include <list>
-
-#include "CTR_Map.h"
-#include "CTR_HashedPtr.h"
-#include "SG_IObject.h"
-#include "SCA_IScene.h"
-#include "MT_Transform.h"
-
-#include "RAS_FramingManager.h"
-#include "RAS_Rect.h"
-
-
-#include "EXP_PyObjectPlus.h"
-#include "RAS_2DFilterManager.h"
-
-/**
- * \section Forward declarations
- */
-struct SM_MaterialProps;
-struct SM_ShapeProps;
-struct Scene;
-
-class CTR_HashedPtr;
-class CListValue;
-class CValue;
-class SCA_LogicManager;
-class SCA_KeyboardManager;
-class SCA_TimeEventManager;
-class SCA_MouseManager;
-class SCA_ISystem;
-class SCA_IInputDevice;
-class NG_NetworkDeviceInterface;
-class NG_NetworkScene;
-class SG_IObject;
-class SG_Node;
-class SG_Tree;
-class KX_WorldInfo;
-class KX_Camera;
-class KX_GameObject;
-class KX_LightObject;
-class RAS_BucketManager;
-class RAS_MaterialBucket;
-class RAS_IPolyMaterial;
-class RAS_IRasterizer;
-class RAS_IRenderTools;
-class SCA_JoystickManager;
-class btCollisionShape;
-class KX_BlenderSceneConverter;
-struct KX_ClientObjectInfo;
-class KX_ObstacleSimulation;
-
-#ifdef WITH_CXX_GUARDEDALLOC
-#include "MEM_guardedalloc.h"
-#endif
-
-/* for ID freeing */
-#define IS_TAGGED(_id) ((_id) && (((ID *)_id)->tag & LIB_TAG_DOIT))
-
-/**
- * The KX_Scene holds all data for an independent scene. It relates
- * KX_Objects to the specific objects in the modules.
- * */
-class KX_Scene : public PyObjectPlus, public SCA_IScene
-{
- Py_Header
-
-#ifdef WITH_PYTHON
- PyObject* m_attr_dict;
- PyObject* m_draw_call_pre;
- PyObject* m_draw_call_post;
- PyObject* m_draw_setup_call_pre;
-#endif
-
- struct CullingInfo {
- int m_layer;
- CullingInfo(int layer) : m_layer(layer) {}
- };
-
-protected:
- RAS_BucketManager* m_bucketmanager;
- CListValue* m_tempObjectList;
-
- /**
- * The list of objects which have been removed during the
- * course of one frame. They are actually destroyed in
- * LogicEndFrame() via a call to RemoveObject().
- */
- CListValue* m_euthanasyobjects;
-
- CListValue* m_objectlist;
- CListValue* m_parentlist; // all 'root' parents
- CListValue* m_lightlist;
- CListValue* m_inactivelist; // all objects that are not in the active layer
- CListValue* m_animatedlist; // all animated objects
-
- SG_QList m_sghead; // list of nodes that needs scenegraph update
- // the Dlist is not object that must be updated
- // the Qlist is for objects that needs to be rescheduled
- // for updates after udpate is over (slow parent, bone parent)
-
-
- /**
- * The set of cameras for this scene
- */
- std::list<class KX_Camera*> m_cameras;
-
- /**
- * The set of fonts for this scene
- */
- std::list<class KX_FontObject*> m_fonts;
-
-
- /**
- * Various SCA managers used by the scene
- */
- SCA_LogicManager* m_logicmgr;
- SCA_KeyboardManager* m_keyboardmgr;
- SCA_MouseManager* m_mousemgr;
- SCA_TimeEventManager* m_timemgr;
-
- // Scene converter where many scene entities are registered
- // Used to deregister objects that are deleted
- class KX_BlenderSceneConverter* m_sceneConverter;
- /**
- * physics engine abstraction
- */
- //e_PhysicsEngine m_physicsEngine; //who needs this ?
- class PHY_IPhysicsEnvironment* m_physicsEnvironment;
-
- /**
- * Does this scene clear the z-buffer?
- */
- bool m_isclearingZbuffer;
-
- /**
- * Does the shadow buffer needs calculing
- */
- bool m_isShadowDone;
-
- /**
- * The name of the scene
- */
- STR_String m_sceneName;
-
- /**
- * stores the world-settings for a scene
- */
- KX_WorldInfo* m_worldinfo;
-
- /**
- * \section Different scenes, linked to ketsji scene
- */
-
- /**
- * Network scene.
- */
- NG_NetworkDeviceInterface* m_networkDeviceInterface;
- NG_NetworkScene* m_networkScene;
-
- /**
- * A temporary variable used to parent objects together on
- * replication. Don't get confused by the name it is not
- * the scene's root node!
- */
- SG_Node* m_rootnode;
-
- /**
- * The active camera for the scene
- */
- KX_Camera* m_active_camera;
-
- /**
- * Another temporary variable outstaying its welcome
- * used in AddReplicaObject to map game objects to their
- * replicas so pointers can be updated.
- */
- CTR_Map <CTR_HashedPtr, void*> m_map_gameobject_to_replica;
-
- /**
- * Another temporary variable outstaying its welcome
- * used in AddReplicaObject to keep a record of all added
- * objects. Logic can only be updated when all objects
- * have been updated. This stores a list of the new objects.
- */
- std::vector<KX_GameObject*> m_logicHierarchicalGameObjects;
-
- /**
- * This temporary variable will contain the list of
- * object that can be added during group instantiation.
- * objects outside this list will not be added (can
- * happen with children that are outside the group).
- * Used in AddReplicaObject. If the list is empty, it
- * means don't care.
- */
- std::set<CValue*> m_groupGameObjects;
-
- /**
- * Pointer to system variable passed in in constructor
- * only used in constructor so we do not need to keep it
- * around in this class.
- */
-
- SCA_ISystem* m_kxsystem;
-
- /**
- * The execution priority of replicated object actuators?
- */
- int m_ueberExecutionPriority;
-
- /**
- * Activity 'bubble' settings :
- * Suspend (freeze) the entire scene.
- */
- bool m_suspend;
-
- /**
- * Radius in Manhattan distance of the box for activity culling.
- */
- float m_activity_box_radius;
-
- /**
- * Toggle to enable or disable activity culling.
- */
- bool m_activity_culling;
-
- /**
- * Toggle to enable or disable culling via DBVT broadphase of Bullet.
- */
- bool m_dbvt_culling;
-
- /**
- * Occlusion culling resolution
- */
- int m_dbvt_occlusion_res;
-
- /**
- * The framing settings used by this scene
- */
-
- RAS_FrameSettings m_frame_settings;
-
- /**
- * This scenes viewport into the game engine
- * canvas.Maintained externally, initially [0,0] -> [0,0]
- */
- RAS_Rect m_viewport;
-
- /**
- * Visibility testing functions.
- */
- void MarkVisible(SG_Tree *node, RAS_IRasterizer* rasty, KX_Camera*cam,int layer=0);
- void MarkSubTreeVisible(SG_Tree *node, RAS_IRasterizer* rasty, bool visible, KX_Camera*cam,int layer=0);
- void MarkVisible(RAS_IRasterizer* rasty, KX_GameObject* gameobj, KX_Camera*cam, int layer=0);
- static void PhysicsCullingCallback(KX_ClientObjectInfo* objectInfo, void* cullingInfo);
-
- double m_suspendedtime;
- double m_suspendeddelta;
-
- struct Scene* m_blenderScene;
-
- RAS_2DFilterManager m_filtermanager;
-
- KX_ObstacleSimulation* m_obstacleSimulation;
-
- /**
- * LOD Hysteresis settings
- */
- bool m_isActivedHysteresis;
- int m_lodHysteresisValue;
-
-public:
- KX_Scene(class SCA_IInputDevice* keyboarddevice,
- class SCA_IInputDevice* mousedevice,
- class NG_NetworkDeviceInterface* ndi,
- const STR_String& scenename,
- struct Scene* scene,
- class RAS_ICanvas* canvas);
-
- virtual
- ~KX_Scene();
-
- RAS_BucketManager* GetBucketManager();
- RAS_MaterialBucket* FindBucket(RAS_IPolyMaterial* polymat, bool &bucketCreated);
- void RenderBuckets(const MT_Transform& cameratransform,
- RAS_IRasterizer* rasty);
-
- /**
- * Update all transforms according to the scenegraph.
- */
- static bool KX_ScenegraphUpdateFunc(SG_IObject* node,void* gameobj,void* scene);
- static bool KX_ScenegraphRescheduleFunc(SG_IObject* node,void* gameobj,void* scene);
- void UpdateParents(double curtime);
- void DupliGroupRecurse(CValue* gameobj, int level);
- bool IsObjectInGroup(CValue* gameobj)
- {
- return (m_groupGameObjects.empty() ||
- m_groupGameObjects.find(gameobj) != m_groupGameObjects.end());
- }
- void AddObjectDebugProperties(class KX_GameObject* gameobj);
- SCA_IObject* AddReplicaObject(CValue* gameobj,
- CValue* locationobj,
- int lifespan=0);
- KX_GameObject* AddNodeReplicaObject(SG_IObject* node,
- CValue* gameobj);
- void RemoveNodeDestructObject(SG_IObject* node,
- CValue* gameobj);
- void RemoveObject(CValue* gameobj);
- void RemoveDupliGroup(CValue *gameobj);
- void DelayedRemoveObject(CValue* gameobj);
-
- int NewRemoveObject(CValue* gameobj);
- void ReplaceMesh(CValue* gameobj,
- void* meshob, bool use_gfx, bool use_phys);
-
- void AddAnimatedObject(CValue* gameobj);
-
- /**
- * \section Logic stuff
- * Initiate an update of the logic system.
- */
- void LogicBeginFrame(double curtime);
- void LogicUpdateFrame(double curtime, bool frame);
- void UpdateAnimations(double curtime);
-
- void
- LogicEndFrame(
- );
-
- CListValue*
- GetTempObjectList(
- );
-
- CListValue*
- GetObjectList(
- );
-
- CListValue*
- GetInactiveList(
- );
-
- CListValue*
- GetRootParentList(
- );
-
- CListValue*
- GetLightList(
- );
-
- SCA_LogicManager *
- GetLogicManager(
- );
-
- SCA_TimeEventManager *
- GetTimeEventManager(
- );
-
- /** Font Routines */
-
- /** Find a font in the scene by pointer. */
- KX_FontObject*
- FindFont(
- KX_FontObject*
- );
-
- /** Add a camera to this scene. */
- void
- AddFont(
- KX_FontObject*
- );
-
- /** Render the fonts in this scene. */
- void
- RenderFonts(
- );
-
- /** Camera Routines */
-
- std::list<class KX_Camera*>*
- GetCameras(
- );
-
-
- /** Find a camera in the scene by pointer. */
- KX_Camera*
- FindCamera(
- KX_Camera*
- );
-
- /** Find a scene in the scene by name. */
- KX_Camera*
- FindCamera(
- STR_String&
- );
-
- /** Add a camera to this scene. */
- void
- AddCamera(
- KX_Camera*
- );
-
- /** Find the currently active camera. */
- KX_Camera*
- GetActiveCamera(
- );
-
- /**
- * Set this camera to be the active camera in the scene. If the
- * camera is not present in the camera list, it will be added
- */
-
- void
- SetActiveCamera(
- class KX_Camera*
- );
-
- /**
- * Move this camera to the end of the list so that it is rendered last.
- * If the camera is not on the list, it will be added
- */
- void
- SetCameraOnTop(
- class KX_Camera*
- );
-
- /**
- * Activates new desired canvas width set at design time.
- * \param width The new desired width.
- */
- void
- SetCanvasDesignWidth(
- unsigned int width
- );
- /**
- * Activates new desired canvas height set at design time.
- * \param width The new desired height.
- */
- void
- SetCanvasDesignHeight(
- unsigned int height
- );
- /**
- * Returns the current desired canvas width set at design time.
- * \return The desired width.
- */
- unsigned int
- GetCanvasDesignWidth(
- void
- ) const;
-
- /**
- * Returns the current desired canvas height set at design time.
- * \return The desired height.
- */
- unsigned int
- GetCanvasDesignHeight(
- void
- ) const;
-
- /**
- * Set the framing options for this scene
- */
-
- void
- SetFramingType(
- RAS_FrameSettings & frame_settings
- );
-
- /**
- * Return a const reference to the framing
- * type set by the above call.
- * The contents are not guaranteed to be sensible
- * if you don't call the above function.
- */
-
- const
- RAS_FrameSettings &
- GetFramingType(
- ) const;
-
- /**
- * Store the current scene's viewport on the
- * game engine canvas.
- */
- void SetSceneViewport(const RAS_Rect &viewport);
-
- /**
- * Get the current scene's viewport on the
- * game engine canvas. This maintained
- * externally in KX_GameEngine
- */
- const RAS_Rect& GetSceneViewport() const;
-
- /**
- * \section Accessors to different scenes of this scene
- */
- void SetNetworkDeviceInterface(NG_NetworkDeviceInterface* newInterface);
- void SetNetworkScene(NG_NetworkScene *newScene);
- void SetWorldInfo(class KX_WorldInfo* wi);
- KX_WorldInfo* GetWorldInfo();
- void CalculateVisibleMeshes(RAS_IRasterizer* rasty, KX_Camera *cam, int layer=0);
- KX_Camera* GetpCamera();
- NG_NetworkDeviceInterface* GetNetworkDeviceInterface();
- NG_NetworkScene* GetNetworkScene();
- KX_BlenderSceneConverter *GetSceneConverter() { return m_sceneConverter; }
-
- /**
- * Replicate the logic bricks associated to this object.
- */
-
- void ReplicateLogic(class KX_GameObject* newobj);
- static SG_Callbacks m_callbacks;
-
- const STR_String& GetName();
-
- // Suspend the entire scene.
- void Suspend();
-
- // Resume a suspended scene.
- void Resume();
-
- // Update the mesh for objects based on level of detail settings
- void UpdateObjectLods(void);
-
- // LoD Hysteresis functions
- void SetLodHysteresis(bool active);
- bool IsActivedLodHysteresis();
- void SetLodHysteresisValue(int hysteresisvalue);
- int GetLodHysteresisValue();
-
- // Update the activity box settings for objects in this scene, if needed.
- void UpdateObjectActivity(void);
-
- // Enable/disable activity culling.
- void SetActivityCulling(bool b);
-
- // Set the radius of the activity culling box.
- void SetActivityCullingRadius(float f);
- bool IsSuspended();
- bool IsClearingZBuffer();
- void EnableZBufferClearing(bool isclearingZbuffer);
- bool IsShadowDone() { return m_isShadowDone; }
- void SetShadowDone(bool b) { m_isShadowDone = b; }
- // use of DBVT tree for camera culling
- void SetDbvtCulling(bool b) { m_dbvt_culling = b; }
- bool GetDbvtCulling() { return m_dbvt_culling; }
- void SetDbvtOcclusionRes(int i) { m_dbvt_occlusion_res = i; }
- int GetDbvtOcclusionRes() { return m_dbvt_occlusion_res; }
-
- void SetSceneConverter(class KX_BlenderSceneConverter* sceneConverter);
-
- class PHY_IPhysicsEnvironment* GetPhysicsEnvironment()
- {
- return m_physicsEnvironment;
- }
-
- void SetPhysicsEnvironment(class PHY_IPhysicsEnvironment* physEnv);
-
- void SetGravity(const MT_Vector3& gravity);
- MT_Vector3 GetGravity();
-
- short GetAnimationFPS();
-
- /**
- * Sets the node tree for this scene.
- */
- void SetNodeTree(SG_Tree* root);
-
- /**
- * 2D Filters
- */
- void Update2DFilter(std::vector<STR_String>& propNames, void* gameObj, RAS_2DFilterManager::RAS_2DFILTER_MODE filtermode, int pass, STR_String& text);
- void Render2DFilters(RAS_ICanvas* canvas);
-
- KX_ObstacleSimulation* GetObstacleSimulation() { return m_obstacleSimulation; }
-
-#ifdef WITH_PYTHON
- /* --------------------------------------------------------------------- */
- /* Python interface ---------------------------------------------------- */
- /* --------------------------------------------------------------------- */
-
- KX_PYMETHOD_DOC(KX_Scene, addObject);
- KX_PYMETHOD_DOC(KX_Scene, end);
- KX_PYMETHOD_DOC(KX_Scene, restart);
- KX_PYMETHOD_DOC(KX_Scene, replace);
- KX_PYMETHOD_DOC(KX_Scene, suspend);
- KX_PYMETHOD_DOC(KX_Scene, resume);
- KX_PYMETHOD_DOC(KX_Scene, get);
- KX_PYMETHOD_DOC(KX_Scene, drawObstacleSimulation);
-
-
- /* attributes */
- static PyObject* pyattr_get_name(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_objects(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_objects_inactive(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_lights(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_cameras(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_world(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_active_camera(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_active_camera(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static PyObject* pyattr_get_drawing_callback_pre(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_drawing_callback_pre(void *selv_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static PyObject* pyattr_get_drawing_callback_post(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_drawing_callback_post(void *selv_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static PyObject* pyattr_get_drawing_setup_callback_pre(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_drawing_setup_callback_pre(void *selv_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static PyObject* pyattr_get_gravity(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_gravity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
-
- virtual PyObject *py_repr(void) { return PyUnicode_From_STR_String(GetName()); }
-
- /* getitem/setitem */
- static PyMappingMethods Mapping;
- static PySequenceMethods Sequence;
-
- /**
- * Run the registered python drawing functions.
- */
- void RunDrawingCallbacks(PyObject *cb_list);
-
- PyObject *GetPreDrawCB() { return m_draw_call_pre; }
- PyObject *GetPostDrawCB() { return m_draw_call_post; }
- PyObject *GetPreDrawSetupCB() { return m_draw_setup_call_pre; }
-#endif
-
- /**
- * Sets the time the scene was suspended
- */
- void setSuspendedTime(double suspendedtime);
- /**
- * Returns the "curtime" the scene was suspended
- */
- double getSuspendedTime();
- /**
- * Sets the difference between the local time of the scene (when it
- * was running and not suspended) and the "curtime"
- */
- void setSuspendedDelta(double suspendeddelta);
- /**
- * Returns the difference between the local time of the scene (when it
- * was running and not suspended) and the "curtime"
- */
- double getSuspendedDelta();
- /**
- * Returns the Blender scene this was made from
- */
- struct Scene *GetBlenderScene() { return m_blenderScene; }
-
- bool MergeScene(KX_Scene *other);
-
-
- //void PrintStats(int verbose_level) {
- // m_bucketmanager->PrintStats(verbose_level)
- //}
-};
-
-typedef std::vector<KX_Scene*> KX_SceneList;
-
-#endif /* __KX_SCENE_H__ */
diff --git a/source/gameengine/Ketsji/KX_SceneActuator.cpp b/source/gameengine/Ketsji/KX_SceneActuator.cpp
deleted file mode 100644
index 6fe33fd2f63..00000000000
--- a/source/gameengine/Ketsji/KX_SceneActuator.cpp
+++ /dev/null
@@ -1,292 +0,0 @@
-/*
- * Set scene/camera stuff
- *
- *
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Ketsji/KX_SceneActuator.cpp
- * \ingroup ketsji
- */
-
-
-#include "SCA_IActuator.h"
-#include "KX_SceneActuator.h"
-#include <iostream>
-#include "KX_Scene.h"
-#include "KX_Camera.h"
-#include "KX_KetsjiEngine.h"
-
-/* ------------------------------------------------------------------------- */
-/* Native functions */
-/* ------------------------------------------------------------------------- */
-
-KX_SceneActuator::KX_SceneActuator(SCA_IObject *gameobj,
- int mode,
- KX_Scene *scene,
- KX_KetsjiEngine* ketsjiEngine,
- const STR_String& nextSceneName,
- KX_Camera* camera)
- : SCA_IActuator(gameobj, KX_ACT_SCENE)
-{
- m_mode = mode;
- m_scene = scene;
- m_KetsjiEngine=ketsjiEngine;
- m_camera = camera;
- m_nextSceneName = nextSceneName;
- if (m_camera)
- m_camera->RegisterActuator(this);
-} /* End of constructor */
-
-
-
-KX_SceneActuator::~KX_SceneActuator()
-{
- if (m_camera)
- m_camera->UnregisterActuator(this);
-} /* end of destructor */
-
-
-
-CValue* KX_SceneActuator::GetReplica()
-{
- KX_SceneActuator* replica = new KX_SceneActuator(*this);
- replica->ProcessReplica();
- return replica;
-}
-
-void KX_SceneActuator::ProcessReplica()
-{
- if (m_camera)
- m_camera->RegisterActuator(this);
- SCA_IActuator::ProcessReplica();
-}
-
-bool KX_SceneActuator::UnlinkObject(SCA_IObject* clientobj)
-{
- if (clientobj == (SCA_IObject*)m_camera)
- {
- // this object is being deleted, we cannot continue to track it.
- m_camera = NULL;
- return true;
- }
- return false;
-}
-
-void KX_SceneActuator::Relink(CTR_Map<CTR_HashedPtr, void*> *obj_map)
-{
- void **h_obj = (*obj_map)[m_camera];
- if (h_obj) {
- if (m_camera)
- m_camera->UnregisterActuator(this);
- m_camera = (KX_Camera*)(*h_obj);
- m_camera->RegisterActuator(this);
- }
-}
-
-
-bool KX_SceneActuator::Update()
-{
- // bool result = false; /*unused*/
- bool bNegativeEvent = IsNegativeEvent();
- RemoveAllEvents();
-
- if (bNegativeEvent)
- return false; // do nothing on negative events
-
- switch (m_mode)
- {
- case KX_SCENE_RESTART:
- {
- m_KetsjiEngine->ReplaceScene(m_scene->GetName(),m_scene->GetName());
- break;
- }
- case KX_SCENE_SET_CAMERA:
- if (m_camera)
- {
- m_scene->SetActiveCamera(m_camera);
- }
- else
- {
- // if no camera is set and the parent object is a camera, use it as the camera
- SCA_IObject* parent = GetParent();
- if (parent->GetGameObjectType()==SCA_IObject::OBJ_CAMERA)
- {
- m_scene->SetActiveCamera((KX_Camera*)parent);
- }
- }
- break;
- default:
- break;
- }
-
- if (!m_nextSceneName.Length())
- return false;
-
- switch (m_mode)
- {
- case KX_SCENE_SET_SCENE:
- {
- m_KetsjiEngine->ReplaceScene(m_scene->GetName(),m_nextSceneName);
- break;
- }
- case KX_SCENE_ADD_FRONT_SCENE:
- {
- bool overlay=true;
- m_KetsjiEngine->ConvertAndAddScene(m_nextSceneName,overlay);
- break;
- }
- case KX_SCENE_ADD_BACK_SCENE:
- {
- bool overlay=false;
- m_KetsjiEngine->ConvertAndAddScene(m_nextSceneName,overlay);
- break;
- }
- case KX_SCENE_REMOVE_SCENE:
- {
- m_KetsjiEngine->RemoveScene(m_nextSceneName);
- break;
- }
- case KX_SCENE_SUSPEND:
- {
- m_KetsjiEngine->SuspendScene(m_nextSceneName);
- break;
- }
- case KX_SCENE_RESUME:
- {
- m_KetsjiEngine->ResumeScene(m_nextSceneName);
- break;
- }
- default:
- ; /* do nothing? this is an internal error !!! */
- }
-
- return false;
-}
-
-
-
-/* returns a camera if the name is valid */
-KX_Camera* KX_SceneActuator::FindCamera(const char *camName)
-{
- KX_SceneList* sl = m_KetsjiEngine->CurrentScenes();
- STR_String name = STR_String(camName);
- KX_SceneList::iterator it = sl->begin();
- KX_Camera* cam = NULL;
-
- while ((it != sl->end()) && (!cam))
- {
- cam = (*it)->FindCamera(name);
- it++;
- }
-
- return cam;
-}
-
-
-
-KX_Scene* KX_SceneActuator::FindScene(const char *sceneName)
-{
- return m_KetsjiEngine->FindScene(sceneName);
-}
-
-
-#ifdef WITH_PYTHON
-
-/* ------------------------------------------------------------------------- */
-/* Python functions */
-/* ------------------------------------------------------------------------- */
-
-/* Integration hooks ------------------------------------------------------- */
-PyTypeObject KX_SceneActuator::Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "KX_SceneActuator",
- sizeof(PyObjectPlus_Proxy),
- 0,
- py_base_dealloc,
- 0,
- 0,
- 0,
- 0,
- py_base_repr,
- 0,0,0,0,0,0,0,0,0,
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
- 0,0,0,0,0,0,0,
- Methods,
- 0,
- 0,
- &SCA_IActuator::Type,
- 0,0,0,0,0,0,
- py_base_new
-};
-
-PyMethodDef KX_SceneActuator::Methods[] =
-{
- {NULL,NULL} //Sentinel
-};
-
-PyAttributeDef KX_SceneActuator::Attributes[] = {
- KX_PYATTRIBUTE_STRING_RW("scene",0,MAX_ID_NAME-2,true,KX_SceneActuator,m_nextSceneName),
- KX_PYATTRIBUTE_RW_FUNCTION("camera",KX_SceneActuator,pyattr_get_camera,pyattr_set_camera),
- KX_PYATTRIBUTE_BOOL_RW("useRestart", KX_SceneActuator, m_restart),
- KX_PYATTRIBUTE_INT_RW("mode", KX_SCENE_NODEF+1, KX_SCENE_MAX-1, true, KX_SceneActuator, m_mode),
- { NULL } //Sentinel
-};
-
-PyObject *KX_SceneActuator::pyattr_get_camera(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_SceneActuator* actuator = static_cast<KX_SceneActuator*>(self);
- if (!actuator->m_camera)
- Py_RETURN_NONE;
-
- return actuator->m_camera->GetProxy();
-}
-
-int KX_SceneActuator::pyattr_set_camera(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_SceneActuator* actuator = static_cast<KX_SceneActuator*>(self);
- KX_Camera *camOb;
-
- if (!ConvertPythonToCamera(value, &camOb, true, "actu.camera = value: KX_SceneActuator"))
- return PY_SET_ATTR_FAIL;
-
- if (actuator->m_camera)
- actuator->m_camera->UnregisterActuator(actuator);
-
- if (camOb==NULL) {
- actuator->m_camera= NULL;
- }
- else {
- actuator->m_camera = camOb;
- actuator->m_camera->RegisterActuator(actuator);
- }
-
- return PY_SET_ATTR_SUCCESS;
-}
-
-#endif // WITH_PYTHON
-
-/* eof */
diff --git a/source/gameengine/Ketsji/KX_SceneActuator.h b/source/gameengine/Ketsji/KX_SceneActuator.h
deleted file mode 100644
index 389e9208ef3..00000000000
--- a/source/gameengine/Ketsji/KX_SceneActuator.h
+++ /dev/null
@@ -1,109 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file KX_SceneActuator.h
- * \ingroup ketsji
- */
-
-#ifndef __KX_SCENEACTUATOR_H__
-#define __KX_SCENEACTUATOR_H__
-
-#include "SCA_IActuator.h"
-#include "SCA_IScene.h" /* Replace_IScene only */
-#include "KX_Scene.h" /* Replace_IScene only */
-
-class KX_SceneActuator : public SCA_IActuator
-{
- Py_Header
-
- int m_mode;
- // (restart) has become a toggle internally... not in the interface though
- bool m_restart;
- // (set Scene) Scene
- /** The current scene. */
- class KX_Scene* m_scene;
- class KX_KetsjiEngine* m_KetsjiEngine;
- /** The scene to switch to. */
- STR_String m_nextSceneName;
-
- // (Set Camera) Object
- class KX_Camera* m_camera;
-
- /** Is this a valid scene? */
- class KX_Scene* FindScene(const char* sceneName);
- /** Is this a valid camera? */
- class KX_Camera* FindCamera(const char* cameraName);
-
- public:
- enum SCA_SceneActuatorMode
- {
- KX_SCENE_NODEF = 0,
- KX_SCENE_RESTART,
- KX_SCENE_SET_SCENE,
- KX_SCENE_SET_CAMERA,
- KX_SCENE_ADD_FRONT_SCENE,
- KX_SCENE_ADD_BACK_SCENE,
- KX_SCENE_REMOVE_SCENE,
- KX_SCENE_SUSPEND,
- KX_SCENE_RESUME,
- KX_SCENE_MAX
- };
-
- KX_SceneActuator(SCA_IObject* gameobj,
- int mode,
- KX_Scene* scene,
- KX_KetsjiEngine* ketsjiEngine,
- const STR_String& nextSceneName,
- KX_Camera* camera);
- virtual ~KX_SceneActuator();
-
- virtual CValue* GetReplica();
- virtual void ProcessReplica();
- virtual bool UnlinkObject(SCA_IObject* clientobj);
- virtual void Relink(CTR_Map<CTR_HashedPtr, void*> *obj_map);
-
- virtual bool Update();
-
-#ifdef WITH_PYTHON
-
- virtual void Replace_IScene(SCA_IScene *val)
- {
- m_scene= static_cast<KX_Scene *>(val);
- };
-
- /* --------------------------------------------------------------------- */
- /* Python interface ---------------------------------------------------- */
- /* --------------------------------------------------------------------- */
-
- static PyObject *pyattr_get_camera(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_camera(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
-
-#endif /* WITH_PYTHON */
-
-}; /* end of class KXSceneActuator */
-
-#endif
diff --git a/source/gameengine/Ketsji/KX_SoundActuator.cpp b/source/gameengine/Ketsji/KX_SoundActuator.cpp
deleted file mode 100644
index a09429450cb..00000000000
--- a/source/gameengine/Ketsji/KX_SoundActuator.cpp
+++ /dev/null
@@ -1,571 +0,0 @@
-/*
- * KX_SoundActuator.cpp
- *
- *
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- *
- */
-
-/** \file gameengine/Ketsji/KX_SoundActuator.cpp
- * \ingroup ketsji
- */
-
-
-#include "KX_SoundActuator.h"
-
-#ifdef WITH_AUDASPACE
-typedef float sample_t;
-# include <python/PyAPI.h>
-# include <AUD_Sound.h>
-# include <AUD_Special.h>
-# include <AUD_Device.h>
-# include <AUD_Handle.h>
-#endif
-
-#include "KX_GameObject.h"
-#include "KX_PyMath.h" // needed for PyObjectFrom()
-#include "KX_PythonInit.h"
-#include "KX_Camera.h"
-#include <iostream>
-
-/* ------------------------------------------------------------------------- */
-/* Native functions */
-/* ------------------------------------------------------------------------- */
-KX_SoundActuator::KX_SoundActuator(SCA_IObject* gameobj,
- AUD_Sound* sound,
- float volume,
- float pitch,
- bool is3d,
- KX_3DSoundSettings settings,
- KX_SOUNDACT_TYPE type)//,
- : SCA_IActuator(gameobj, KX_ACT_SOUND)
-{
- m_sound = sound ? AUD_Sound_copy(sound) : NULL;
- m_handle = NULL;
- m_volume = volume;
- m_pitch = pitch;
- m_is3d = is3d;
- m_3d = settings;
- m_type = type;
- m_isplaying = false;
-}
-
-
-
-KX_SoundActuator::~KX_SoundActuator()
-{
- if (m_handle) {
- AUD_Handle_stop(m_handle);
- }
-
- if (m_sound) {
- AUD_Sound_free(m_sound);
- }
-}
-
-void KX_SoundActuator::play()
-{
- if (m_handle) {
- AUD_Handle_stop(m_handle);
- m_handle = NULL;
- }
-
- if (!m_sound)
- return;
-
- // this is the sound that will be played and not deleted afterwards
- AUD_Sound* sound = m_sound;
-
- bool loop = false;
-
- switch (m_type)
- {
- case KX_SOUNDACT_LOOPBIDIRECTIONAL:
- case KX_SOUNDACT_LOOPBIDIRECTIONAL_STOP:
- sound = AUD_Sound_pingpong(sound);
- ATTR_FALLTHROUGH;
- case KX_SOUNDACT_LOOPEND:
- case KX_SOUNDACT_LOOPSTOP:
- loop = true;
- break;
- case KX_SOUNDACT_PLAYSTOP:
- case KX_SOUNDACT_PLAYEND:
- default:
- break;
- }
-
- AUD_Device* device = AUD_Device_getCurrent();
- m_handle = AUD_Device_play(device, sound, false);
- AUD_Device_free(device);
-
- // in case of pingpong, we have to free the sound
- if (sound != m_sound)
- AUD_Sound_free(sound);
-
- if (m_handle != NULL) {
- if (m_is3d) {
- AUD_Handle_setRelative(m_handle, true);
- AUD_Handle_setVolumeMaximum(m_handle, m_3d.max_gain);
- AUD_Handle_setVolumeMinimum(m_handle, m_3d.min_gain);
- AUD_Handle_setDistanceReference(m_handle, m_3d.reference_distance);
- AUD_Handle_setDistanceMaximum(m_handle, m_3d.max_distance);
- AUD_Handle_setAttenuation(m_handle, m_3d.rolloff_factor);
- AUD_Handle_setConeAngleInner(m_handle, m_3d.cone_inner_angle);
- AUD_Handle_setConeAngleOuter(m_handle, m_3d.cone_outer_angle);
- AUD_Handle_setConeVolumeOuter(m_handle, m_3d.cone_outer_gain);
- }
-
- if (loop)
- AUD_Handle_setLoopCount(m_handle, -1);
- AUD_Handle_setPitch(m_handle, m_pitch);
- AUD_Handle_setVolume(m_handle, m_volume);
- }
-
- m_isplaying = true;
-}
-
-CValue* KX_SoundActuator::GetReplica()
-{
- KX_SoundActuator* replica = new KX_SoundActuator(*this);
- replica->ProcessReplica();
- return replica;
-}
-
-void KX_SoundActuator::ProcessReplica()
-{
- SCA_IActuator::ProcessReplica();
- m_handle = NULL;
- m_sound = AUD_Sound_copy(m_sound);
-}
-
-bool KX_SoundActuator::Update(double curtime, bool frame)
-{
- if (!frame)
- return true;
- bool result = false;
-
- // do nothing on negative events, otherwise sounds are played twice!
- bool bNegativeEvent = IsNegativeEvent();
- bool bPositiveEvent = m_posevent;
-
- RemoveAllEvents();
-
- if (!m_sound)
- return false;
-
- // actual audio device playing state
- bool isplaying = m_handle ? (AUD_Handle_getStatus(m_handle) == AUD_STATUS_PLAYING) : false;
-
- if (bNegativeEvent)
- {
- // here must be a check if it is still playing
- if (m_isplaying && isplaying)
- {
- switch (m_type)
- {
- case KX_SOUNDACT_PLAYSTOP:
- case KX_SOUNDACT_LOOPSTOP:
- case KX_SOUNDACT_LOOPBIDIRECTIONAL_STOP:
- {
- // stop immediately
- if (m_handle)
- {
- AUD_Handle_stop(m_handle);
- m_handle = NULL;
- }
- break;
- }
- case KX_SOUNDACT_PLAYEND:
- {
- // do nothing, sound will stop anyway when it's finished
- break;
- }
- case KX_SOUNDACT_LOOPEND:
- case KX_SOUNDACT_LOOPBIDIRECTIONAL:
- {
- // stop the looping so that the sound stops when it finished
- if (m_handle)
- AUD_Handle_setLoopCount(m_handle, 0);
- break;
- }
- default:
- // implement me !!
- break;
- }
- }
- // remember that we tried to stop the actuator
- m_isplaying = false;
- }
-
-#if 1
- // Warning: when de-activating the actuator, after a single negative event this runs again with...
- // m_posevent==false && m_posevent==false, in this case IsNegativeEvent() returns false
- // and assumes this is a positive event.
- // check that we actually have a positive event so as not to play sounds when being disabled.
- else if (bPositiveEvent) /* <- added since 2.49 */
-#else
- else // <- works in most cases except a loop-end sound will never stop unless
- // the negative pulse is done continuesly
-#endif
- {
- if (!m_isplaying)
- play();
- }
- // verify that the sound is still playing
- isplaying = m_handle ? (AUD_Handle_getStatus(m_handle) == AUD_STATUS_PLAYING) : false;
-
- if (isplaying)
- {
- if (m_is3d)
- {
- KX_Camera* cam = KX_GetActiveScene()->GetActiveCamera();
- if (cam)
- {
- KX_GameObject* obj = (KX_GameObject*)this->GetParent();
- MT_Point3 p;
- MT_Matrix3x3 Mo;
- float data[4];
-
- Mo = cam->NodeGetWorldOrientation().inverse();
- p = (obj->NodeGetWorldPosition() - cam->NodeGetWorldPosition());
- p = Mo * p;
- p.getValue(data);
- AUD_Handle_setLocation(m_handle, data);
- p = (obj->GetLinearVelocity() - cam->GetLinearVelocity());
- p = Mo * p;
- p.getValue(data);
- AUD_Handle_setVelocity(m_handle, data);
- (Mo * obj->NodeGetWorldOrientation()).getRotation().getValue(data);
- AUD_Handle_setOrientation(m_handle, data);
- }
- }
- result = true;
- }
- else
- {
- m_isplaying = false;
- result = false;
- }
- return result;
-}
-
-#ifdef WITH_PYTHON
-
-/* ------------------------------------------------------------------------- */
-/* Python functions */
-/* ------------------------------------------------------------------------- */
-
-
-
-/* Integration hooks ------------------------------------------------------- */
-PyTypeObject KX_SoundActuator::Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "KX_SoundActuator",
- sizeof(PyObjectPlus_Proxy),
- 0,
- py_base_dealloc,
- 0,
- 0,
- 0,
- 0,
- py_base_repr,
- 0,0,0,0,0,0,0,0,0,
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
- 0,0,0,0,0,0,0,
- Methods,
- 0,
- 0,
- &SCA_IActuator::Type,
- 0,0,0,0,0,0,
- py_base_new
-};
-
-PyMethodDef KX_SoundActuator::Methods[] = {
- KX_PYMETHODTABLE_NOARGS(KX_SoundActuator, startSound),
- KX_PYMETHODTABLE_NOARGS(KX_SoundActuator, pauseSound),
- KX_PYMETHODTABLE_NOARGS(KX_SoundActuator, stopSound),
- {NULL, NULL} //Sentinel
-};
-
-PyAttributeDef KX_SoundActuator::Attributes[] = {
- KX_PYATTRIBUTE_BOOL_RO("is3D", KX_SoundActuator, m_is3d),
- KX_PYATTRIBUTE_RW_FUNCTION("volume_maximum", KX_SoundActuator, pyattr_get_3d_property, pyattr_set_3d_property),
- KX_PYATTRIBUTE_RW_FUNCTION("volume_minimum", KX_SoundActuator, pyattr_get_3d_property, pyattr_set_3d_property),
- KX_PYATTRIBUTE_RW_FUNCTION("distance_reference", KX_SoundActuator, pyattr_get_3d_property, pyattr_set_3d_property),
- KX_PYATTRIBUTE_RW_FUNCTION("distance_maximum", KX_SoundActuator, pyattr_get_3d_property, pyattr_set_3d_property),
- KX_PYATTRIBUTE_RW_FUNCTION("attenuation", KX_SoundActuator, pyattr_get_3d_property, pyattr_set_3d_property),
- KX_PYATTRIBUTE_RW_FUNCTION("cone_angle_inner", KX_SoundActuator, pyattr_get_3d_property, pyattr_set_3d_property),
- KX_PYATTRIBUTE_RW_FUNCTION("cone_angle_outer", KX_SoundActuator, pyattr_get_3d_property, pyattr_set_3d_property),
- KX_PYATTRIBUTE_RW_FUNCTION("cone_volume_outer", KX_SoundActuator, pyattr_get_3d_property, pyattr_set_3d_property),
- KX_PYATTRIBUTE_RW_FUNCTION("sound", KX_SoundActuator, pyattr_get_sound, pyattr_set_sound),
-
- KX_PYATTRIBUTE_RW_FUNCTION("time", KX_SoundActuator, pyattr_get_audposition, pyattr_set_audposition),
- KX_PYATTRIBUTE_RW_FUNCTION("volume", KX_SoundActuator, pyattr_get_gain, pyattr_set_gain),
- KX_PYATTRIBUTE_RW_FUNCTION("pitch", KX_SoundActuator, pyattr_get_pitch, pyattr_set_pitch),
- KX_PYATTRIBUTE_ENUM_RW("mode",KX_SoundActuator::KX_SOUNDACT_NODEF+1,KX_SoundActuator::KX_SOUNDACT_MAX-1,false,KX_SoundActuator,m_type),
- { NULL } //Sentinel
-};
-
-/* Methods ----------------------------------------------------------------- */
-KX_PYMETHODDEF_DOC_NOARGS(KX_SoundActuator, startSound,
-"startSound()\n"
-"\tStarts the sound.\n")
-{
- switch (m_handle ? AUD_Handle_getStatus(m_handle) : AUD_STATUS_INVALID) {
- case AUD_STATUS_PLAYING:
- break;
- case AUD_STATUS_PAUSED:
- AUD_Handle_resume(m_handle);
- break;
- default:
- play();
- }
- Py_RETURN_NONE;
-}
-
-KX_PYMETHODDEF_DOC_NOARGS(KX_SoundActuator, pauseSound,
-"pauseSound()\n"
-"\tPauses the sound.\n")
-{
- if (m_handle)
- AUD_Handle_pause(m_handle);
- Py_RETURN_NONE;
-}
-
-KX_PYMETHODDEF_DOC_NOARGS(KX_SoundActuator, stopSound,
-"stopSound()\n"
-"\tStops the sound.\n")
-{
- if (m_handle)
- {
- AUD_Handle_stop(m_handle);
- m_handle = NULL;
- }
- Py_RETURN_NONE;
-}
-
-/* Atribute setting and getting -------------------------------------------- */
-PyObject *KX_SoundActuator::pyattr_get_3d_property(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_SoundActuator * actuator = static_cast<KX_SoundActuator *> (self);
- const char* prop = attrdef->m_name;
- float result_value = 0.0f;
-
- if (!strcmp(prop, "volume_maximum")) {
- result_value = actuator->m_3d.max_gain;
-
- } else if (!strcmp(prop, "volume_minimum")) {
- result_value = actuator->m_3d.min_gain;
-
- } else if (!strcmp(prop, "distance_reference")) {
- result_value = actuator->m_3d.reference_distance;
-
- } else if (!strcmp(prop, "distance_maximum")) {
- result_value = actuator->m_3d.max_distance;
-
- } else if (!strcmp(prop, "attenuation")) {
- result_value = actuator->m_3d.rolloff_factor;
-
- } else if (!strcmp(prop, "cone_angle_inner")) {
- result_value = actuator->m_3d.cone_inner_angle;
-
- } else if (!strcmp(prop, "cone_angle_outer")) {
- result_value = actuator->m_3d.cone_outer_angle;
-
- } else if (!strcmp(prop, "cone_volume_outer")) {
- result_value = actuator->m_3d.cone_outer_gain;
-
- } else {
- Py_RETURN_NONE;
- }
-
- PyObject *result = PyFloat_FromDouble(result_value);
- return result;
-}
-
-PyObject *KX_SoundActuator::pyattr_get_audposition(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_SoundActuator * actuator = static_cast<KX_SoundActuator *> (self);
- float position = 0.0f;
-
- if (actuator->m_handle)
- position = AUD_Handle_getPosition(actuator->m_handle);
-
- PyObject *result = PyFloat_FromDouble(position);
-
- return result;
-}
-
-PyObject *KX_SoundActuator::pyattr_get_gain(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_SoundActuator * actuator = static_cast<KX_SoundActuator *> (self);
- float gain = actuator->m_volume;
-
- PyObject *result = PyFloat_FromDouble(gain);
-
- return result;
-}
-
-PyObject *KX_SoundActuator::pyattr_get_pitch(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_SoundActuator * actuator = static_cast<KX_SoundActuator *> (self);
- float pitch = actuator->m_pitch;
-
- PyObject *result = PyFloat_FromDouble(pitch);
-
- return result;
-}
-
-PyObject *KX_SoundActuator::pyattr_get_sound(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_SoundActuator * actuator = static_cast<KX_SoundActuator *> (self);
- if (actuator->m_sound)
- return (PyObject *)AUD_getPythonSound(actuator->m_sound);
- else
- Py_RETURN_NONE;
-}
-
-int KX_SoundActuator::pyattr_set_3d_property(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_SoundActuator * actuator = static_cast<KX_SoundActuator *> (self);
- const char* prop = attrdef->m_name;
- float prop_value = 0.0f;
-
- if (!PyArg_Parse(value, "f", &prop_value))
- return PY_SET_ATTR_FAIL;
-
- // if sound is working and 3D, set the new setting
- if (!actuator->m_is3d)
- return PY_SET_ATTR_FAIL;
-
- if (!strcmp(prop, "volume_maximum")) {
- actuator->m_3d.max_gain = prop_value;
- if (actuator->m_handle)
- AUD_Handle_setVolumeMaximum(actuator->m_handle, prop_value);
-
- } else if (!strcmp(prop, "volume_minimum")) {
- actuator->m_3d.min_gain = prop_value;
- if (actuator->m_handle)
- AUD_Handle_setVolumeMinimum(actuator->m_handle, prop_value);
-
- } else if (!strcmp(prop, "distance_reference")) {
- actuator->m_3d.reference_distance = prop_value;
- if (actuator->m_handle)
- AUD_Handle_setDistanceReference(actuator->m_handle, prop_value);
-
- } else if (!strcmp(prop, "distance_maximum")) {
- actuator->m_3d.max_distance = prop_value;
- if (actuator->m_handle)
- AUD_Handle_setDistanceMaximum(actuator->m_handle, prop_value);
-
- } else if (!strcmp(prop, "attenuation")) {
- actuator->m_3d.rolloff_factor = prop_value;
- if (actuator->m_handle)
- AUD_Handle_setAttenuation(actuator->m_handle, prop_value);
-
- } else if (!strcmp(prop, "cone_angle_inner")) {
- actuator->m_3d.cone_inner_angle = prop_value;
- if (actuator->m_handle)
- AUD_Handle_setConeAngleInner(actuator->m_handle, prop_value);
-
- } else if (!strcmp(prop, "cone_angle_outer")) {
- actuator->m_3d.cone_outer_angle = prop_value;
- if (actuator->m_handle)
- AUD_Handle_setConeAngleOuter(actuator->m_handle, prop_value);
-
- } else if (!strcmp(prop, "cone_volume_outer")) {
- actuator->m_3d.cone_outer_gain = prop_value;
- if (actuator->m_handle)
- AUD_Handle_setConeVolumeOuter(actuator->m_handle, prop_value);
-
- } else {
- return PY_SET_ATTR_FAIL;
- }
-
- return PY_SET_ATTR_SUCCESS;
-}
-
-int KX_SoundActuator::pyattr_set_audposition(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_SoundActuator * actuator = static_cast<KX_SoundActuator *> (self);
-
- float position = 1.0f;
- if (!PyArg_Parse(value, "f", &position))
- return PY_SET_ATTR_FAIL;
-
- if (actuator->m_handle)
- AUD_Handle_setPosition(actuator->m_handle, position);
- return PY_SET_ATTR_SUCCESS;
-}
-
-int KX_SoundActuator::pyattr_set_gain(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- float gain = 1.0f;
- KX_SoundActuator * actuator = static_cast<KX_SoundActuator *> (self);
- if (!PyArg_Parse(value, "f", &gain))
- return PY_SET_ATTR_FAIL;
-
- actuator->m_volume = gain;
- if (actuator->m_handle)
- AUD_Handle_setVolume(actuator->m_handle, gain);
-
- return PY_SET_ATTR_SUCCESS;
-}
-
-int KX_SoundActuator::pyattr_set_pitch(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- float pitch = 1.0f;
- KX_SoundActuator * actuator = static_cast<KX_SoundActuator *> (self);
- if (!PyArg_Parse(value, "f", &pitch))
- return PY_SET_ATTR_FAIL;
-
- actuator->m_pitch = pitch;
- if (actuator->m_handle)
- AUD_Handle_setPitch(actuator->m_handle, pitch);
-
- return PY_SET_ATTR_SUCCESS;
-}
-
-int KX_SoundActuator::pyattr_set_sound(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- PyObject *sound = NULL;
- KX_SoundActuator * actuator = static_cast<KX_SoundActuator *> (self);
- if (!PyArg_Parse(value, "O", &sound))
- return PY_SET_ATTR_FAIL;
-
- AUD_Sound *snd = AUD_getSoundFromPython(sound);
-
- if (snd)
- {
- AUD_Sound_free(actuator->m_sound);
- actuator->m_sound = snd;
- return PY_SET_ATTR_SUCCESS;
- }
-
- return PY_SET_ATTR_FAIL;
-}
-
-#endif // WITH_PYTHON
diff --git a/source/gameengine/Ketsji/KX_SoundActuator.h b/source/gameengine/Ketsji/KX_SoundActuator.h
deleted file mode 100644
index 4f3e6f707e0..00000000000
--- a/source/gameengine/Ketsji/KX_SoundActuator.h
+++ /dev/null
@@ -1,127 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file KX_SoundActuator.h
- * \ingroup ketsji
- */
-
-#ifndef __KX_SOUNDACTUATOR_H__
-#define __KX_SOUNDACTUATOR_H__
-
-#include "SCA_IActuator.h"
-
-#ifdef WITH_AUDASPACE
-# include <AUD_Sound.h>
-# include <AUD_Handle.h>
-#endif
-
-#include "BKE_sound.h"
-
-typedef struct KX_3DSoundSettings {
- float min_gain;
- float max_gain;
- float reference_distance;
- float max_distance;
- float rolloff_factor;
- float cone_inner_angle;
- float cone_outer_angle;
- float cone_outer_gain;
-} KX_3DSoundSettings;
-
-class KX_SoundActuator : public SCA_IActuator
-{
- Py_Header
- bool m_isplaying;
- AUD_Sound* m_sound;
- float m_volume;
- float m_pitch;
- bool m_is3d;
- KX_3DSoundSettings m_3d;
- AUD_Handle* m_handle;
-
- void play();
-
-public:
-
- enum KX_SOUNDACT_TYPE
- {
- KX_SOUNDACT_NODEF = 0,
- KX_SOUNDACT_PLAYSTOP,
- KX_SOUNDACT_PLAYEND,
- KX_SOUNDACT_LOOPSTOP,
- KX_SOUNDACT_LOOPEND,
- KX_SOUNDACT_LOOPBIDIRECTIONAL,
- KX_SOUNDACT_LOOPBIDIRECTIONAL_STOP,
- KX_SOUNDACT_MAX
- };
-
- KX_SOUNDACT_TYPE m_type;
-
- KX_SoundActuator(SCA_IObject* gameobj,
- AUD_Sound *sound,
- float volume,
- float pitch,
- bool is3d,
- KX_3DSoundSettings settings,
- KX_SOUNDACT_TYPE type);
-
- ~KX_SoundActuator();
-
- virtual bool Update(double curtime, bool frame);
-
- CValue* GetReplica();
- void ProcessReplica();
-
-#ifdef WITH_PYTHON
-
- /* -------------------------------------------------------------------- */
- /* Python interface --------------------------------------------------- */
- /* -------------------------------------------------------------------- */
-
- KX_PYMETHOD_DOC_NOARGS(KX_SoundActuator, startSound);
- KX_PYMETHOD_DOC_NOARGS(KX_SoundActuator, pauseSound);
- KX_PYMETHOD_DOC_NOARGS(KX_SoundActuator, stopSound);
-
- static int pyattr_set_3d_property(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static int pyattr_set_audposition(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static int pyattr_set_gain(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static int pyattr_set_pitch(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static int pyattr_set_type(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static int pyattr_set_sound(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
-
- static PyObject *pyattr_get_3d_property(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject *pyattr_get_audposition(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject *pyattr_get_gain(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject *pyattr_get_pitch(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject *pyattr_get_type(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject *pyattr_get_sound(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef);
-
-#endif /* WITH_PYTHON */
-
-};
-
-#endif /* __KX_SOUNDACTUATOR_H__ */
diff --git a/source/gameengine/Ketsji/KX_StateActuator.cpp b/source/gameengine/Ketsji/KX_StateActuator.cpp
deleted file mode 100644
index d918f87c4bf..00000000000
--- a/source/gameengine/Ketsji/KX_StateActuator.cpp
+++ /dev/null
@@ -1,171 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- * Actuator to toggle visibility/invisibility of objects
- */
-
-/** \file gameengine/Ketsji/KX_StateActuator.cpp
- * \ingroup ketsji
- */
-
-
-#include "KX_StateActuator.h"
-#include "KX_GameObject.h"
-
-KX_StateActuator::KX_StateActuator(
- SCA_IObject* gameobj,
- int operation,
- unsigned int mask
- )
- : SCA_IActuator(gameobj, KX_ACT_STATE),
- m_operation(operation),
- m_mask(mask)
-{
- // intentionally empty
-}
-
-KX_StateActuator::~KX_StateActuator(
- void
- )
-{
- // intentionally empty
-}
-
-// used to put state actuator to be executed before any other actuators
-SG_QList KX_StateActuator::m_stateActuatorHead;
-
-CValue*
-KX_StateActuator::GetReplica(
- void
- )
-{
- KX_StateActuator* replica = new KX_StateActuator(*this);
- replica->ProcessReplica();
- return replica;
-}
-
-bool
-KX_StateActuator::Update()
-{
- bool bNegativeEvent = IsNegativeEvent();
- unsigned int objMask;
-
- // execution of state actuator means that we are in the execution phase, reset this pointer
- // because all the active actuator of this object will be removed for sure.
- m_gameobj->m_firstState = NULL;
- RemoveAllEvents();
- if (bNegativeEvent) return false;
-
- KX_GameObject *obj = (KX_GameObject*) GetParent();
-
- objMask = obj->GetState();
- switch (m_operation)
- {
- case OP_CPY:
- objMask = m_mask;
- break;
- case OP_SET:
- objMask |= m_mask;
- break;
- case OP_CLR:
- objMask &= ~m_mask;
- break;
- case OP_NEG:
- objMask ^= m_mask;
- break;
- default:
- // unsupported operation, no nothing
- return false;
- }
- obj->SetState(objMask);
- return false;
-}
-
-// this function is only used to deactivate actuators outside the logic loop
-// e.g. when an object is deleted.
-void KX_StateActuator::Deactivate()
-{
- if (QDelink())
- {
- // the actuator was in the active list
- if (m_stateActuatorHead.QEmpty())
- // no more state object active
- m_stateActuatorHead.Delink();
- }
-}
-
-void KX_StateActuator::Activate(SG_DList& head)
-{
- // sort the state actuators per object on the global list
- if (QEmpty())
- {
- InsertSelfActiveQList(m_stateActuatorHead, &m_gameobj->m_firstState);
- // add front to make sure it runs before other actuators
- head.AddFront(&m_stateActuatorHead);
- }
-}
-
-#ifdef WITH_PYTHON
-
-/* ------------------------------------------------------------------------- */
-/* Python functions */
-/* ------------------------------------------------------------------------- */
-
-
-
-/* Integration hooks ------------------------------------------------------- */
-PyTypeObject KX_StateActuator::Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "KX_StateActuator",
- sizeof(PyObjectPlus_Proxy),
- 0,
- py_base_dealloc,
- 0,
- 0,
- 0,
- 0,
- py_base_repr,
- 0,0,0,0,0,0,0,0,0,
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
- 0,0,0,0,0,0,0,
- Methods,
- 0,
- 0,
- &SCA_IActuator::Type,
- 0,0,0,0,0,0,
- py_base_new
-};
-
-PyMethodDef KX_StateActuator::Methods[] = {
- {NULL,NULL} //Sentinel
-};
-
-PyAttributeDef KX_StateActuator::Attributes[] = {
- KX_PYATTRIBUTE_INT_RW("operation",KX_StateActuator::OP_NOP+1,KX_StateActuator::OP_COUNT-1,false,KX_StateActuator,m_operation),
- KX_PYATTRIBUTE_INT_RW("mask",0,0x3FFFFFFF,false,KX_StateActuator,m_mask),
- { NULL } //Sentinel
-};
-
-#endif // WITH_PYTHON
diff --git a/source/gameengine/Ketsji/KX_StateActuator.h b/source/gameengine/Ketsji/KX_StateActuator.h
deleted file mode 100644
index 5ed065d3604..00000000000
--- a/source/gameengine/Ketsji/KX_StateActuator.h
+++ /dev/null
@@ -1,97 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file KX_StateActuator.h
- * \ingroup ketsji
- * \brief Actuator to toggle visibility/invisibility of objects
- */
-
-#ifndef __KX_STATEACTUATOR_H__
-#define __KX_STATEACTUATOR_H__
-
-#include "SCA_IActuator.h"
-
-
-/*
- * Use of SG_DList : element of actuator being deactivated
- * Head: SCA_LogicManager::m_removedActuators
- * Use of SG_QList : element of global activated state actuator list
- * Head: KX_StateActuator::m_stateActuatorHead
- */
-class KX_StateActuator : public SCA_IActuator
-{
- Py_Header
-
- /** Make visible? */
- enum {
- OP_NOP = -1,
- OP_CPY = 0,
- OP_SET,
- OP_CLR,
- OP_NEG,
- OP_COUNT
- };
- // SG_Dlist: element of objects with active actuators, always put in front of the list
- // Head: SCA_LogicManager::m_activeActuators
- // SG_QList: Head of active state actuators list globally
- // Elements: KX_StateActuator
- static SG_QList m_stateActuatorHead;
- int m_operation;
- int m_mask;
-
- public:
-
- KX_StateActuator(
- SCA_IObject* gameobj,
- int operation,
- unsigned int mask
- );
-
- virtual
- ~KX_StateActuator(
- void
- );
-
- virtual CValue*
- GetReplica(
- void
- );
-
- virtual bool
- Update();
-
- virtual void Deactivate();
- virtual void Activate(SG_DList& head);
-
- /* --------------------------------------------------------------------- */
- /* Python interface ---------------------------------------------------- */
- /* --------------------------------------------------------------------- */
-
-};
-
-#endif
-
diff --git a/source/gameengine/Ketsji/KX_SteeringActuator.cpp b/source/gameengine/Ketsji/KX_SteeringActuator.cpp
deleted file mode 100644
index d3a7b665e61..00000000000
--- a/source/gameengine/Ketsji/KX_SteeringActuator.cpp
+++ /dev/null
@@ -1,639 +0,0 @@
-/*
- * Add steering behaviors
- *
- *
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-#include "BLI_math.h"
-#include "KX_SteeringActuator.h"
-#include "KX_GameObject.h"
-#include "KX_NavMeshObject.h"
-#include "KX_ObstacleSimulation.h"
-#include "KX_PythonInit.h"
-#include "KX_PyMath.h"
-#include "Recast.h"
-
-/* ------------------------------------------------------------------------- */
-/* Native functions */
-/* ------------------------------------------------------------------------- */
-
-KX_SteeringActuator::KX_SteeringActuator(SCA_IObject *gameobj,
- int mode,
- KX_GameObject *target,
- KX_GameObject *navmesh,
- float distance,
- float velocity,
- float acceleration,
- float turnspeed,
- bool isSelfTerminated,
- int pathUpdatePeriod,
- KX_ObstacleSimulation* simulation,
- short facingmode,
- bool normalup,
- bool enableVisualization,
- bool lockzvel)
- : SCA_IActuator(gameobj, KX_ACT_STEERING),
- m_target(target),
- m_mode(mode),
- m_distance(distance),
- m_velocity(velocity),
- m_acceleration(acceleration),
- m_turnspeed(turnspeed),
- m_simulation(simulation),
- m_updateTime(0),
- m_obstacle(NULL),
- m_isActive(false),
- m_isSelfTerminated(isSelfTerminated),
- m_enableVisualization(enableVisualization),
- m_facingMode(facingmode),
- m_normalUp(normalup),
- m_pathLen(0),
- m_pathUpdatePeriod(pathUpdatePeriod),
- m_lockzvel(lockzvel),
- m_wayPointIdx(-1),
- m_steerVec(MT_Vector3(0, 0, 0))
-{
- m_navmesh = static_cast<KX_NavMeshObject*>(navmesh);
- if (m_navmesh)
- m_navmesh->RegisterActuator(this);
- if (m_target)
- m_target->RegisterActuator(this);
-
- if (m_simulation)
- m_obstacle = m_simulation->GetObstacle((KX_GameObject*)gameobj);
- KX_GameObject* parent = ((KX_GameObject*)gameobj)->GetParent();
- if (m_facingMode>0 && parent)
- {
- m_parentlocalmat = parent->GetSGNode()->GetLocalOrientation();
- }
- else
- m_parentlocalmat.setIdentity();
-}
-
-KX_SteeringActuator::~KX_SteeringActuator()
-{
- if (m_navmesh)
- m_navmesh->UnregisterActuator(this);
- if (m_target)
- m_target->UnregisterActuator(this);
-}
-
-CValue* KX_SteeringActuator::GetReplica()
-{
- KX_SteeringActuator* replica = new KX_SteeringActuator(*this);
- // replication just copy the m_base pointer => common random generator
- replica->ProcessReplica();
- return replica;
-}
-
-void KX_SteeringActuator::ProcessReplica()
-{
- if (m_target)
- m_target->RegisterActuator(this);
- if (m_navmesh)
- m_navmesh->RegisterActuator(this);
- SCA_IActuator::ProcessReplica();
-}
-
-void KX_SteeringActuator::ReParent(SCA_IObject* parent)
-{
- SCA_IActuator::ReParent(parent);
- if (m_simulation)
- m_obstacle = m_simulation->GetObstacle((KX_GameObject*)m_gameobj);
-}
-
-bool KX_SteeringActuator::UnlinkObject(SCA_IObject* clientobj)
-{
- if (clientobj == m_target)
- {
- m_target = NULL;
- return true;
- }
- else if (clientobj == m_navmesh)
- {
- m_navmesh = NULL;
- return true;
- }
- return false;
-}
-
-void KX_SteeringActuator::Relink(CTR_Map<CTR_HashedPtr, void*> *obj_map)
-{
- void **h_obj = (*obj_map)[m_target];
- if (h_obj) {
- if (m_target)
- m_target->UnregisterActuator(this);
- m_target = (KX_GameObject*)(*h_obj);
- m_target->RegisterActuator(this);
- }
-
- h_obj = (*obj_map)[m_navmesh];
- if (h_obj) {
- if (m_navmesh)
- m_navmesh->UnregisterActuator(this);
- m_navmesh = (KX_NavMeshObject*)(*h_obj);
- m_navmesh->RegisterActuator(this);
- }
-}
-
-bool KX_SteeringActuator::Update(double curtime, bool frame)
-{
- if (frame)
- {
- double delta = curtime - m_updateTime;
- m_updateTime = curtime;
-
- if (m_posevent && !m_isActive)
- {
- delta = 0.0;
- m_pathUpdateTime = -1.0;
- m_updateTime = curtime;
- m_isActive = true;
- }
- bool bNegativeEvent = IsNegativeEvent();
- if (bNegativeEvent)
- m_isActive = false;
-
- RemoveAllEvents();
-
- if (!delta)
- return true;
-
- if (bNegativeEvent || !m_target)
- return false; // do nothing on negative events
-
- KX_GameObject *obj = (KX_GameObject*) GetParent();
- const MT_Point3& mypos = obj->NodeGetWorldPosition();
- const MT_Point3& targpos = m_target->NodeGetWorldPosition();
- MT_Vector3 vectotarg = targpos - mypos;
- MT_Vector3 vectotarg2d = vectotarg;
- vectotarg2d.z() = 0.0f;
- m_steerVec = MT_Vector3(0.0f, 0.0f, 0.0f);
- bool apply_steerforce = false;
- bool terminate = true;
-
- switch (m_mode) {
- case KX_STEERING_SEEK:
- if (vectotarg2d.length2()>m_distance*m_distance)
- {
- terminate = false;
- m_steerVec = vectotarg;
- m_steerVec.normalize();
- apply_steerforce = true;
- }
- break;
- case KX_STEERING_FLEE:
- if (vectotarg2d.length2()<m_distance*m_distance)
- {
- terminate = false;
- m_steerVec = -vectotarg;
- m_steerVec.normalize();
- apply_steerforce = true;
- }
- break;
- case KX_STEERING_PATHFOLLOWING:
- if (m_navmesh && vectotarg.length2()>m_distance*m_distance)
- {
- terminate = false;
-
- static const MT_Scalar WAYPOINT_RADIUS(0.25f);
-
- if (m_pathUpdateTime<0 || (m_pathUpdatePeriod>=0 &&
- curtime - m_pathUpdateTime>((double)m_pathUpdatePeriod/1000.0)))
- {
- m_pathUpdateTime = curtime;
- m_pathLen = m_navmesh->FindPath(mypos, targpos, m_path, MAX_PATH_LENGTH);
- m_wayPointIdx = m_pathLen > 1 ? 1 : -1;
- }
-
- if (m_wayPointIdx>0)
- {
- MT_Vector3 waypoint(&m_path[3*m_wayPointIdx]);
- if ((waypoint-mypos).length2()<WAYPOINT_RADIUS*WAYPOINT_RADIUS)
- {
- m_wayPointIdx++;
- if (m_wayPointIdx>=m_pathLen)
- {
- m_wayPointIdx = -1;
- terminate = true;
- }
- else
- waypoint.setValue(&m_path[3*m_wayPointIdx]);
- }
-
- m_steerVec = waypoint - mypos;
- apply_steerforce = true;
-
-
- if (m_enableVisualization)
- {
- //debug draw
- static const MT_Vector3 PATH_COLOR(1.0f,0.0f,0.0f);
- m_navmesh->DrawPath(m_path, m_pathLen, PATH_COLOR);
- }
- }
-
- }
- break;
- }
-
- if (apply_steerforce)
- {
- bool isdyna = obj->IsDynamic();
- if (isdyna)
- m_steerVec.z() = 0;
- if (!m_steerVec.fuzzyZero())
- m_steerVec.normalize();
- MT_Vector3 newvel = m_velocity * m_steerVec;
-
- //adjust velocity to avoid obstacles
- if (m_simulation && m_obstacle /*&& !newvel.fuzzyZero()*/)
- {
- if (m_enableVisualization)
- KX_RasterizerDrawDebugLine(mypos, mypos + newvel, MT_Vector3(1.0f, 0.0f, 0.0f));
- m_simulation->AdjustObstacleVelocity(m_obstacle, m_mode!=KX_STEERING_PATHFOLLOWING ? m_navmesh : NULL,
- newvel, m_acceleration*(float)delta, m_turnspeed/(180.0f*(float)(M_PI*delta)));
- if (m_enableVisualization)
- KX_RasterizerDrawDebugLine(mypos, mypos + newvel, MT_Vector3(0.0f, 1.0f, 0.0f));
- }
-
- HandleActorFace(newvel);
- if (isdyna)
- {
- //temporary solution: set 2D steering velocity directly to obj
- //correct way is to apply physical force
- MT_Vector3 curvel = obj->GetLinearVelocity();
-
- if (m_lockzvel)
- newvel.z() = 0.0f;
- else
- newvel.z() = curvel.z();
-
- obj->setLinearVelocity(newvel, false);
- }
- else
- {
- MT_Vector3 movement = delta*newvel;
- obj->ApplyMovement(movement, false);
- }
- }
- else
- {
- if (m_simulation && m_obstacle)
- {
- m_obstacle->dvel[0] = 0.f;
- m_obstacle->dvel[1] = 0.f;
- }
-
- }
-
- if (terminate && m_isSelfTerminated)
- return false;
- }
-
- return true;
-}
-
-const MT_Vector3& KX_SteeringActuator::GetSteeringVec()
-{
- static MT_Vector3 ZERO_VECTOR(0, 0, 0);
- if (m_isActive)
- return m_steerVec;
- else
- return ZERO_VECTOR;
-}
-
-inline float vdot2(const float* a, const float* b)
-{
- return a[0]*b[0] + a[2]*b[2];
-}
-static bool barDistSqPointToTri(const float* p, const float* a, const float* b, const float* c)
-{
- float v0[3], v1[3], v2[3];
- rcVsub(v0, c,a);
- rcVsub(v1, b,a);
- rcVsub(v2, p,a);
-
- const float dot00 = vdot2(v0, v0);
- const float dot01 = vdot2(v0, v1);
- const float dot02 = vdot2(v0, v2);
- const float dot11 = vdot2(v1, v1);
- const float dot12 = vdot2(v1, v2);
-
- // Compute barycentric coordinates
- float invDenom = 1.0f / (dot00 * dot11 - dot01 * dot01);
- float u = (dot11 * dot02 - dot01 * dot12) * invDenom;
- float v = (dot00 * dot12 - dot01 * dot02) * invDenom;
-
- float ud = u<0.f ? -u : (u>1.f ? u-1.f : 0.f);
- float vd = v<0.f ? -v : (v>1.f ? v-1.f : 0.f);
- return ud * ud + vd * vd;
-}
-
-inline void flipAxes(float* vec)
-{
- std::swap(vec[1],vec[2]);
-}
-
-static bool getNavmeshNormal(dtStatNavMesh* navmesh, const MT_Vector3& pos, MT_Vector3& normal)
-{
- static const float polyPickExt[3] = {2, 4, 2};
- float spos[3];
- pos.getValue(spos);
- flipAxes(spos);
- dtStatPolyRef sPolyRef = navmesh->findNearestPoly(spos, polyPickExt);
- if (sPolyRef == 0)
- return false;
- const dtStatPoly* p = navmesh->getPoly(sPolyRef-1);
- const dtStatPolyDetail* pd = navmesh->getPolyDetail(sPolyRef-1);
-
- float distMin = FLT_MAX;
- int idxMin = -1;
- for (int i = 0; i < pd->ntris; ++i)
- {
- const unsigned char* t = navmesh->getDetailTri(pd->tbase+i);
- const float* v[3];
- for (int j = 0; j < 3; ++j)
- {
- if (t[j] < p->nv)
- v[j] = navmesh->getVertex(p->v[t[j]]);
- else
- v[j] = navmesh->getDetailVertex(pd->vbase+(t[j]-p->nv));
- }
- float dist = barDistSqPointToTri(spos, v[0], v[1], v[2]);
- if (dist<distMin)
- {
- distMin = dist;
- idxMin = i;
- }
- }
-
- if (idxMin>=0)
- {
- const unsigned char* t = navmesh->getDetailTri(pd->tbase+idxMin);
- const float* v[3];
- for (int j = 0; j < 3; ++j)
- {
- if (t[j] < p->nv)
- v[j] = navmesh->getVertex(p->v[t[j]]);
- else
- v[j] = navmesh->getDetailVertex(pd->vbase+(t[j]-p->nv));
- }
- MT_Vector3 tri[3];
- for (size_t j=0; j<3; j++)
- tri[j].setValue(v[j][0],v[j][2],v[j][1]);
- MT_Vector3 a,b;
- a = tri[1]-tri[0];
- b = tri[2]-tri[0];
- normal = b.cross(a).safe_normalized();
- return true;
- }
-
- return false;
-}
-
-void KX_SteeringActuator::HandleActorFace(MT_Vector3& velocity)
-{
- if (m_facingMode==0 && (!m_navmesh || !m_normalUp))
- return;
- KX_GameObject* curobj = (KX_GameObject*) GetParent();
- MT_Vector3 dir = m_facingMode==0 ? curobj->NodeGetLocalOrientation().getColumn(1) : velocity;
- if (dir.fuzzyZero())
- return;
- dir.normalize();
- MT_Vector3 up(0,0,1);
- MT_Vector3 left;
- MT_Matrix3x3 mat;
-
- if (m_navmesh && m_normalUp)
- {
- dtStatNavMesh* navmesh = m_navmesh->GetNavMesh();
- MT_Vector3 normal;
- MT_Vector3 trpos = m_navmesh->TransformToLocalCoords(curobj->NodeGetWorldPosition());
- if (getNavmeshNormal(navmesh, trpos, normal))
- {
-
- left = (dir.cross(up)).safe_normalized();
- dir = (-left.cross(normal)).safe_normalized();
- up = normal;
- }
- }
-
- switch (m_facingMode)
- {
- case 1: // TRACK X
- {
- left = dir.safe_normalized();
- dir = -(left.cross(up)).safe_normalized();
- break;
- };
- case 2: // TRACK Y
- {
- left = (dir.cross(up)).safe_normalized();
- break;
- }
-
- case 3: // track Z
- {
- left = up.safe_normalized();
- up = dir.safe_normalized();
- dir = left;
- left = (dir.cross(up)).safe_normalized();
- break;
- }
-
- case 4: // TRACK -X
- {
- left = -dir.safe_normalized();
- dir = -(left.cross(up)).safe_normalized();
- break;
- };
- case 5: // TRACK -Y
- {
- left = (-dir.cross(up)).safe_normalized();
- dir = -dir;
- break;
- }
- case 6: // track -Z
- {
- left = up.safe_normalized();
- up = -dir.safe_normalized();
- dir = left;
- left = (dir.cross(up)).safe_normalized();
- break;
- }
- }
-
- mat.setValue (
- left[0], dir[0],up[0],
- left[1], dir[1],up[1],
- left[2], dir[2],up[2]
- );
-
-
-
- KX_GameObject* parentObject = curobj->GetParent();
- if (parentObject)
- {
- MT_Point3 localpos;
- localpos = curobj->GetSGNode()->GetLocalPosition();
- MT_Matrix3x3 parentmatinv;
- parentmatinv = parentObject->NodeGetWorldOrientation ().inverse ();
- mat = parentmatinv * mat;
- mat = m_parentlocalmat * mat;
- curobj->NodeSetLocalOrientation(mat);
- curobj->NodeSetLocalPosition(localpos);
- }
- else
- {
- curobj->NodeSetLocalOrientation(mat);
- }
-
-}
-
-#ifdef WITH_PYTHON
-
-/* ------------------------------------------------------------------------- */
-/* Python functions */
-/* ------------------------------------------------------------------------- */
-
-/* Integration hooks ------------------------------------------------------- */
-PyTypeObject KX_SteeringActuator::Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "KX_SteeringActuator",
- sizeof(PyObjectPlus_Proxy),
- 0,
- py_base_dealloc,
- 0,
- 0,
- 0,
- 0,
- py_base_repr,
- 0,0,0,0,0,0,0,0,0,
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
- 0,0,0,0,0,0,0,
- Methods,
- 0,
- 0,
- &SCA_IActuator::Type,
- 0,0,0,0,0,0,
- py_base_new
-};
-
-PyMethodDef KX_SteeringActuator::Methods[] = {
- {NULL,NULL} //Sentinel
-};
-
-PyAttributeDef KX_SteeringActuator::Attributes[] = {
- KX_PYATTRIBUTE_INT_RW("behavior", KX_STEERING_NODEF+1, KX_STEERING_MAX-1, true, KX_SteeringActuator, m_mode),
- KX_PYATTRIBUTE_RW_FUNCTION("target", KX_SteeringActuator, pyattr_get_target, pyattr_set_target),
- KX_PYATTRIBUTE_RW_FUNCTION("navmesh", KX_SteeringActuator, pyattr_get_navmesh, pyattr_set_navmesh),
- KX_PYATTRIBUTE_FLOAT_RW("distance", 0.0f, 1000.0f, KX_SteeringActuator, m_distance),
- KX_PYATTRIBUTE_FLOAT_RW("velocity", 0.0f, 1000.0f, KX_SteeringActuator, m_velocity),
- KX_PYATTRIBUTE_FLOAT_RW("acceleration", 0.0f, 1000.0f, KX_SteeringActuator, m_acceleration),
- KX_PYATTRIBUTE_FLOAT_RW("turnspeed", 0.0f, 720.0f, KX_SteeringActuator, m_turnspeed),
- KX_PYATTRIBUTE_BOOL_RW("selfterminated", KX_SteeringActuator, m_isSelfTerminated),
- KX_PYATTRIBUTE_BOOL_RW("enableVisualization", KX_SteeringActuator, m_enableVisualization),
- KX_PYATTRIBUTE_RO_FUNCTION("steeringVec", KX_SteeringActuator, pyattr_get_steeringVec),
- KX_PYATTRIBUTE_SHORT_RW("facingMode", 0, 6, true, KX_SteeringActuator, m_facingMode),
- KX_PYATTRIBUTE_INT_RW("pathUpdatePeriod", -1, 100000, true, KX_SteeringActuator, m_pathUpdatePeriod),
- KX_PYATTRIBUTE_BOOL_RW("lockZVelocity", KX_SteeringActuator, m_lockzvel),
- { NULL } //Sentinel
-};
-
-PyObject *KX_SteeringActuator::pyattr_get_target(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_SteeringActuator* actuator = static_cast<KX_SteeringActuator*>(self);
- if (!actuator->m_target)
- Py_RETURN_NONE;
- else
- return actuator->m_target->GetProxy();
-}
-
-int KX_SteeringActuator::pyattr_set_target(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_SteeringActuator* actuator = static_cast<KX_SteeringActuator*>(self);
- KX_GameObject *gameobj;
-
- if (!ConvertPythonToGameObject(actuator->GetLogicManager(), value, &gameobj, true, "actuator.object = value: KX_SteeringActuator"))
- return PY_SET_ATTR_FAIL; // ConvertPythonToGameObject sets the error
-
- if (actuator->m_target != NULL)
- actuator->m_target->UnregisterActuator(actuator);
-
- actuator->m_target = (KX_GameObject*) gameobj;
-
- if (actuator->m_target)
- actuator->m_target->RegisterActuator(actuator);
-
- return PY_SET_ATTR_SUCCESS;
-}
-
-PyObject *KX_SteeringActuator::pyattr_get_navmesh(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_SteeringActuator* actuator = static_cast<KX_SteeringActuator*>(self);
- if (!actuator->m_navmesh)
- Py_RETURN_NONE;
- else
- return actuator->m_navmesh->GetProxy();
-}
-
-int KX_SteeringActuator::pyattr_set_navmesh(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_SteeringActuator* actuator = static_cast<KX_SteeringActuator*>(self);
- KX_GameObject *gameobj;
-
- if (!ConvertPythonToGameObject(actuator->GetLogicManager(), value, &gameobj, true, "actuator.object = value: KX_SteeringActuator"))
- return PY_SET_ATTR_FAIL; // ConvertPythonToGameObject sets the error
-
- if (dynamic_cast<KX_NavMeshObject *>(gameobj) == NULL) {
- PyErr_Format(PyExc_TypeError, "KX_NavMeshObject is expected");
- return PY_SET_ATTR_FAIL;
- }
-
- if (actuator->m_navmesh != NULL)
- actuator->m_navmesh->UnregisterActuator(actuator);
-
- actuator->m_navmesh = static_cast<KX_NavMeshObject*>(gameobj);
-
- if (actuator->m_navmesh)
- actuator->m_navmesh->RegisterActuator(actuator);
-
- return PY_SET_ATTR_SUCCESS;
-}
-
-PyObject *KX_SteeringActuator::pyattr_get_steeringVec(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_SteeringActuator* actuator = static_cast<KX_SteeringActuator*>(self);
- const MT_Vector3& steeringVec = actuator->GetSteeringVec();
- return PyObjectFrom(steeringVec);
-}
-
-#endif // WITH_PYTHON
-
-/* eof */
-
diff --git a/source/gameengine/Ketsji/KX_SteeringActuator.h b/source/gameengine/Ketsji/KX_SteeringActuator.h
deleted file mode 100644
index 3273471c166..00000000000
--- a/source/gameengine/Ketsji/KX_SteeringActuator.h
+++ /dev/null
@@ -1,123 +0,0 @@
-/*
- * Add steering behaviors
- *
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-#ifndef __KX_STEERINGACTUATOR_H__
-#define __KX_STEERINGACTUATOR_H__
-
-#include "SCA_IActuator.h"
-#include "SCA_LogicManager.h"
-#include "MT_Matrix3x3.h"
-
-class KX_GameObject;
-class KX_NavMeshObject;
-struct KX_Obstacle;
-class KX_ObstacleSimulation;
-const int MAX_PATH_LENGTH = 128;
-
-class KX_SteeringActuator : public SCA_IActuator
-{
- Py_Header
-
- /** Target object */
- KX_GameObject *m_target;
- KX_NavMeshObject *m_navmesh;
- int m_mode;
- float m_distance;
- float m_velocity;
- float m_acceleration;
- float m_turnspeed;
- KX_ObstacleSimulation* m_simulation;
-
- double m_updateTime;
- KX_Obstacle* m_obstacle;
- bool m_isActive;
- bool m_isSelfTerminated;
- bool m_enableVisualization;
- short m_facingMode;
- bool m_normalUp;
- float m_path[MAX_PATH_LENGTH*3];
- int m_pathLen;
- int m_pathUpdatePeriod;
- double m_pathUpdateTime;
- bool m_lockzvel;
- int m_wayPointIdx;
- MT_Matrix3x3 m_parentlocalmat;
- MT_Vector3 m_steerVec;
- void HandleActorFace(MT_Vector3& velocity);
-public:
- enum KX_STEERINGACT_MODE
- {
- KX_STEERING_NODEF = 0,
- KX_STEERING_SEEK,
- KX_STEERING_FLEE,
- KX_STEERING_PATHFOLLOWING,
- KX_STEERING_MAX
- };
-
- KX_SteeringActuator(class SCA_IObject* gameobj,
- int mode,
- KX_GameObject *target,
- KX_GameObject *navmesh,
- float distance,
- float velocity,
- float acceleration,
- float turnspeed,
- bool isSelfTerminated,
- int pathUpdatePeriod,
- KX_ObstacleSimulation* simulation,
- short facingmode,
- bool normalup,
- bool enableVisualization,
- bool lockzvel);
- virtual ~KX_SteeringActuator();
- virtual bool Update(double curtime, bool frame);
-
- virtual CValue* GetReplica();
- virtual void ProcessReplica();
- virtual void ReParent(SCA_IObject* parent);
- virtual void Relink(CTR_Map<CTR_HashedPtr, void*> *obj_map);
- virtual bool UnlinkObject(SCA_IObject* clientobj);
- const MT_Vector3& GetSteeringVec();
-
-#ifdef WITH_PYTHON
-
- /* --------------------------------------------------------------------- */
- /* Python interface ---------------------------------------------------- */
- /* --------------------------------------------------------------------- */
-
- /* These are used to get and set m_target */
- static PyObject *pyattr_get_target(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_target(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static PyObject *pyattr_get_navmesh(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_navmesh(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static PyObject *pyattr_get_steeringVec(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef);
-
-
-#endif /* WITH_PYTHON */
-
-}; /* end of class KX_SteeringActuator : public SCA_PropertyActuator */
-
-#endif /* __KX_STEERINGACTUATOR_H__ */
diff --git a/source/gameengine/Ketsji/KX_TimeCategoryLogger.cpp b/source/gameengine/Ketsji/KX_TimeCategoryLogger.cpp
deleted file mode 100644
index 13717993c4c..00000000000
--- a/source/gameengine/Ketsji/KX_TimeCategoryLogger.cpp
+++ /dev/null
@@ -1,141 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Ketsji/KX_TimeCategoryLogger.cpp
- * \ingroup ketsji
- */
-
-
-#include "KX_TimeCategoryLogger.h"
-
-KX_TimeCategoryLogger::KX_TimeCategoryLogger(unsigned int maxNumMeasurements)
-: m_maxNumMeasurements(maxNumMeasurements)
-{
-}
-
-
-KX_TimeCategoryLogger::~KX_TimeCategoryLogger(void)
-{
- DisposeLoggers();
-}
-
-
-void KX_TimeCategoryLogger::SetMaxNumMeasurements(unsigned int maxNumMeasurements)
-{
- KX_TimeLoggerMap::iterator it;
- for (it = m_loggers.begin(); it != m_loggers.end(); it++) {
- it->second->SetMaxNumMeasurements(maxNumMeasurements);
- }
- m_maxNumMeasurements = maxNumMeasurements;
-}
-
-
-unsigned int KX_TimeCategoryLogger::GetMaxNumMeasurements(void) const
-{
- return m_maxNumMeasurements;
-}
-
-
-void KX_TimeCategoryLogger::AddCategory(TimeCategory tc)
-{
- // Only add if not already present
- if (m_loggers.find(tc) == m_loggers.end()) {
- KX_TimeLogger* logger = new KX_TimeLogger(m_maxNumMeasurements);
- //assert(logger);
- m_loggers.insert(KX_TimeLoggerMap::value_type(tc, logger));
- }
-}
-
-
-void KX_TimeCategoryLogger::StartLog(TimeCategory tc, double now, bool endOtherCategories)
-{
- if (endOtherCategories) {
- KX_TimeLoggerMap::iterator it;
- for (it = m_loggers.begin(); it != m_loggers.end(); it++) {
- if (it->first != tc) {
- it->second->EndLog(now);
- }
- }
- }
- //assert(m_loggers[tc] != m_loggers.end());
- m_loggers[tc]->StartLog(now);
-}
-
-
-void KX_TimeCategoryLogger::EndLog(TimeCategory tc, double now)
-{
- //assert(m_loggers[tc] != m_loggers.end());
- m_loggers[tc]->EndLog(now);
-}
-
-
-void KX_TimeCategoryLogger::EndLog(double now)
-{
- KX_TimeLoggerMap::iterator it;
- for (it = m_loggers.begin(); it != m_loggers.end(); it++) {
- it->second->EndLog(now);
- }
-}
-
-
-void KX_TimeCategoryLogger::NextMeasurement(double now)
-{
- KX_TimeLoggerMap::iterator it;
- for (it = m_loggers.begin(); it != m_loggers.end(); it++) {
- it->second->NextMeasurement(now);
- }
-}
-
-
-double KX_TimeCategoryLogger::GetAverage(TimeCategory tc)
-{
- //assert(m_loggers[tc] != m_loggers.end());
- return m_loggers[tc]->GetAverage();
-}
-
-
-double KX_TimeCategoryLogger::GetAverage(void)
-{
- double time = 0.0;
-
- KX_TimeLoggerMap::iterator it;
- for (it = m_loggers.begin(); it != m_loggers.end(); it++) {
- time += it->second->GetAverage();
- }
-
- return time;
-}
-
-
-void KX_TimeCategoryLogger::DisposeLoggers(void)
-{
- KX_TimeLoggerMap::iterator it;
- for (it = m_loggers.begin(); it != m_loggers.end(); it++) {
- delete it->second;
- }
-}
-
diff --git a/source/gameengine/Ketsji/KX_TimeCategoryLogger.h b/source/gameengine/Ketsji/KX_TimeCategoryLogger.h
deleted file mode 100644
index e097454fca7..00000000000
--- a/source/gameengine/Ketsji/KX_TimeCategoryLogger.h
+++ /dev/null
@@ -1,136 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file KX_TimeCategoryLogger.h
- * \ingroup ketsji
- */
-
-#ifndef __KX_TIMECATEGORYLOGGER_H__
-#define __KX_TIMECATEGORYLOGGER_H__
-
-#ifdef _MSC_VER
-# pragma warning (disable:4786) /* suppress stl-MSVC debug info warning */
-#endif
-
-#include <map>
-
-#include "KX_TimeLogger.h"
-
-/**
- * Stores and manages time measurements by category.
- * Categories can be added dynamically.
- * Average measurements can be established for each separate category
- * or for all categories together.
- */
-class KX_TimeCategoryLogger {
-public:
- typedef int TimeCategory;
-
- /**
- * Constructor.
- * \param maxNumMesasurements Maximum number of measurements stored (> 1).
- */
- KX_TimeCategoryLogger(unsigned int maxNumMeasurements = 10);
-
- /**
- * Destructor.
- */
- virtual ~KX_TimeCategoryLogger(void);
-
- /**
- * Changes the maximum number of measurements that can be stored.
- */
- virtual void SetMaxNumMeasurements(unsigned int maxNumMeasurements);
-
- /**
- * Changes the maximum number of measurements that can be stored.
- */
- virtual unsigned int GetMaxNumMeasurements(void) const;
-
- /**
- * Adds a category.
- * \param category The new category.
- */
- virtual void AddCategory(TimeCategory tc);
-
- /**
- * Starts logging in current measurement for the given category.
- * \param tc The category to log to.
- * \param now The current time.
- * \param endOtherCategories Whether to stop logging to other categories.
- */
- virtual void StartLog(TimeCategory tc, double now, bool endOtherCategories = true);
-
- /**
- * End logging in current measurement for the given category.
- * \param tc The category to log to.
- * \param now The current time.
- */
- virtual void EndLog(TimeCategory tc, double now);
-
- /**
- * End logging in current measurement for all categories.
- * \param now The current time.
- */
- virtual void EndLog(double now);
-
- /**
- * Logs time in next measurement.
- * \param now The current time.
- */
- virtual void NextMeasurement(double now);
-
- /**
- * Returns average of all but the current measurement time.
- * \return The average of all but the current measurement.
- */
- virtual double GetAverage(TimeCategory tc);
-
- /**
- * Returns average for grand total.
- */
- virtual double GetAverage(void);
-
-protected:
- /**
- * Disposes loggers.
- */
- virtual void DisposeLoggers(void);
-
- /** Storage for the loggers. */
- typedef std::map<TimeCategory, KX_TimeLogger*> KX_TimeLoggerMap;
- KX_TimeLoggerMap m_loggers;
- /** Maximum number of measurements. */
- unsigned int m_maxNumMeasurements;
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:KX_TimeCategoryLogger")
-#endif
-};
-
-#endif /* __KX_TIMECATEGORYLOGGER_H__ */
diff --git a/source/gameengine/Ketsji/KX_TimeLogger.cpp b/source/gameengine/Ketsji/KX_TimeLogger.cpp
deleted file mode 100644
index 12106245c4d..00000000000
--- a/source/gameengine/Ketsji/KX_TimeLogger.cpp
+++ /dev/null
@@ -1,117 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Ketsji/KX_TimeLogger.cpp
- * \ingroup ketsji
- */
-
-
-#include "KX_TimeLogger.h"
-
-KX_TimeLogger::KX_TimeLogger(unsigned int maxNumMeasurements) :
- m_maxNumMeasurements(maxNumMeasurements),
- m_logStart(0),
- m_logging(false)
-{
-}
-
-
-KX_TimeLogger::~KX_TimeLogger(void)
-{
-}
-
-
-void KX_TimeLogger::SetMaxNumMeasurements(unsigned int maxNumMeasurements)
-{
- if ((m_maxNumMeasurements != maxNumMeasurements) && maxNumMeasurements) {
- // Actual removing is done in NextMeasurement()
- m_maxNumMeasurements = maxNumMeasurements;
- }
-}
-
-
-unsigned int KX_TimeLogger::GetMaxNumMeasurements(void) const
-{
- return m_maxNumMeasurements;
-}
-
-
-void KX_TimeLogger::StartLog(double now)
-{
- if (!m_logging) {
- m_logging = true;
- m_logStart = now;
- }
-}
-
-
-void KX_TimeLogger::EndLog(double now)
-{
- if (m_logging) {
- m_logging = false;
- double time = now - m_logStart;
- if (m_measurements.size() > 0) {
- m_measurements[0] += time;
- }
- }
-}
-
-
-void KX_TimeLogger::NextMeasurement(double now)
-{
- // End logging to current measurement
- EndLog(now);
-
- // Add a new measurement at the front
- double m = 0.0;
- m_measurements.push_front(m);
-
- // Remove measurement if we grow beyond the maximum size
- if ((m_measurements.size()) > m_maxNumMeasurements) {
- while (m_measurements.size() > m_maxNumMeasurements) {
- m_measurements.pop_back();
- }
- }
-}
-
-
-
-double KX_TimeLogger::GetAverage(void) const
-{
- double avg = 0.0;
-
- unsigned int numMeasurements = m_measurements.size();
- if (numMeasurements > 1) {
- for (unsigned int i = 1; i < numMeasurements; i++) {
- avg += m_measurements[i];
- }
- avg /= (double)numMeasurements - 1.0;
- }
-
- return avg;
-}
-
diff --git a/source/gameengine/Ketsji/KX_TimeLogger.h b/source/gameengine/Ketsji/KX_TimeLogger.h
deleted file mode 100644
index 59d7bdc84e3..00000000000
--- a/source/gameengine/Ketsji/KX_TimeLogger.h
+++ /dev/null
@@ -1,114 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file KX_TimeLogger.h
- * \ingroup ketsji
- */
-
-#ifndef __KX_TIMELOGGER_H__
-#define __KX_TIMELOGGER_H__
-
-#ifdef _MSC_VER
-# pragma warning (disable:4786) /* suppress stl-MSVC debug info warning */
-#endif
-
-#include <deque>
-
-#ifdef WITH_CXX_GUARDEDALLOC
-# include "MEM_guardedalloc.h"
-#endif
-
-/**
- * Stores and manages time measurements.
- */
-class KX_TimeLogger {
-public:
- /**
- * Constructor.
- * \param maxNumMesasurements Maximum number of measurements stored (>1).
- */
- KX_TimeLogger(unsigned int maxNumMeasurements = 10);
-
- /**
- * Destructor.
- */
- virtual ~KX_TimeLogger(void);
-
- /**
- * Changes the maximum number of measurements that can be stored.
- */
- virtual void SetMaxNumMeasurements(unsigned int maxNumMeasurements);
-
- /**
- * Changes the maximum number of measurements that can be stored.
- */
- virtual unsigned int GetMaxNumMeasurements(void) const;
-
- /**
- * Starts logging in current measurement.
- * \param now The current time.
- */
- virtual void StartLog(double now);
-
- /**
- * End logging in current measurement.
- * \param now The current time.
- */
- virtual void EndLog(double now);
-
- /**
- * Logs time in next measurement.
- * \param now The current time.
- */
- virtual void NextMeasurement(double now);
-
- /**
- * Returns average of all but the current measurement.
- * \return The average of all but the current measurement.
- */
- virtual double GetAverage(void) const;
-
-protected:
- /** Storage for the measurements. */
- std::deque<double> m_measurements;
-
- /** Maximum number of measurements. */
- unsigned int m_maxNumMeasurements;
-
- /** Time at start of logging. */
- double m_logStart;
-
- /** State of logging. */
- bool m_logging;
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:KX_TimeLogger")
-#endif
-};
-
-#endif /* __KX_TIMELOGGER_H__ */
diff --git a/source/gameengine/Ketsji/KX_TouchEventManager.cpp b/source/gameengine/Ketsji/KX_TouchEventManager.cpp
deleted file mode 100644
index 7f167652464..00000000000
--- a/source/gameengine/Ketsji/KX_TouchEventManager.cpp
+++ /dev/null
@@ -1,246 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Ketsji/KX_TouchEventManager.cpp
- * \ingroup ketsji
- */
-
-
-#include "KX_TouchEventManager.h"
-#include "SCA_ISensor.h"
-#include "KX_TouchSensor.h"
-#include "KX_GameObject.h"
-#include "PHY_IPhysicsEnvironment.h"
-#include "PHY_IPhysicsController.h"
-
-
-KX_TouchEventManager::KX_TouchEventManager(class SCA_LogicManager* logicmgr,
- PHY_IPhysicsEnvironment* physEnv)
- : SCA_EventManager(logicmgr, TOUCH_EVENTMGR),
- m_physEnv(physEnv)
-{
- //notm_scene->addTouchCallback(STATIC_RESPONSE, KX_TouchEventManager::collisionResponse, this);
-
- //m_scene->addTouchCallback(OBJECT_RESPONSE, KX_TouchEventManager::collisionResponse, this);
- //m_scene->addTouchCallback(SENSOR_RESPONSE, KX_TouchEventManager::collisionResponse, this);
-
- m_physEnv->AddTouchCallback(PHY_OBJECT_RESPONSE, KX_TouchEventManager::newCollisionResponse, this);
- m_physEnv->AddTouchCallback(PHY_SENSOR_RESPONSE, KX_TouchEventManager::newCollisionResponse, this);
- m_physEnv->AddTouchCallback(PHY_BROADPH_RESPONSE, KX_TouchEventManager::newBroadphaseResponse, this);
-
-}
-
-bool KX_TouchEventManager::NewHandleCollision(void* object1, void* object2, const PHY_CollData *coll_data)
-{
-
- PHY_IPhysicsController* obj1 = static_cast<PHY_IPhysicsController*>(object1);
- PHY_IPhysicsController* obj2 = static_cast<PHY_IPhysicsController*>(object2);
-
- m_newCollisions.insert(NewCollision(obj1, obj2, coll_data));
-
- return false;
-}
-
-
-bool KX_TouchEventManager::newCollisionResponse(void *client_data,
- void *object1,
- void *object2,
- const PHY_CollData *coll_data)
-{
- KX_TouchEventManager *touchmgr = (KX_TouchEventManager *) client_data;
- touchmgr->NewHandleCollision(object1, object2, coll_data);
- return false;
-}
-
-bool KX_TouchEventManager::newBroadphaseResponse(void *client_data,
- void *object1,
- void *object2,
- const PHY_CollData *coll_data)
-{
- PHY_IPhysicsController* ctrl1 = static_cast<PHY_IPhysicsController*>(object1);
- PHY_IPhysicsController* ctrl2 = static_cast<PHY_IPhysicsController*>(object2);
-
- KX_ClientObjectInfo *info1 = (ctrl1) ? static_cast<KX_ClientObjectInfo*>(ctrl1->GetNewClientInfo()) : NULL;
- KX_ClientObjectInfo *info2 = (ctrl2) ? static_cast<KX_ClientObjectInfo*>(ctrl2->GetNewClientInfo()) : NULL;
-
- // This call back should only be called for controllers of Near and Radar sensor
- if (!info1)
- return true;
-
- // Get KX_GameObjects for callbacks
- KX_GameObject* gobj1 = info1->m_gameobject;
- KX_GameObject* gobj2 = (info2) ? info2->m_gameobject : NULL;
-
- bool has_py_callbacks = false;
-
-#ifdef WITH_PYTHON
- // Consider callbacks for broadphase inclusion if it's a sensor object type
- if (gobj1 && gobj2)
- has_py_callbacks = gobj1->m_collisionCallbacks || gobj2->m_collisionCallbacks;
-#else
- (void)gobj1;
- (void)gobj2;
-#endif
-
- switch (info1->m_type)
- {
- case KX_ClientObjectInfo::SENSOR:
- if (info1->m_sensors.size() == 1)
- {
- // only one sensor for this type of object
- KX_TouchSensor* touchsensor = static_cast<KX_TouchSensor*>(*info1->m_sensors.begin());
- return touchsensor->BroadPhaseFilterCollision(object1, object2);
- }
- break;
- case KX_ClientObjectInfo::OBSENSOR:
- case KX_ClientObjectInfo::OBACTORSENSOR:
- // this object may have multiple collision sensors,
- // check is any of them is interested in this object
- for (std::list<SCA_ISensor*>::iterator it = info1->m_sensors.begin();
- it != info1->m_sensors.end();
- ++it)
- {
- if ((*it)->GetSensorType() == SCA_ISensor::ST_TOUCH)
- {
- KX_TouchSensor* touchsensor = static_cast<KX_TouchSensor*>(*it);
- if (touchsensor->BroadPhaseSensorFilterCollision(object1, object2))
- return true;
- }
- }
-
- return has_py_callbacks;
-
- // quiet the compiler
- case KX_ClientObjectInfo::STATIC:
- case KX_ClientObjectInfo::ACTOR:
- case KX_ClientObjectInfo::RESERVED1:
- /* do nothing*/
- break;
- }
- return true;
-}
-
-void KX_TouchEventManager::RegisterSensor(SCA_ISensor* sensor)
-{
- KX_TouchSensor* touchsensor = static_cast<KX_TouchSensor*>(sensor);
- if (m_sensors.AddBack(touchsensor))
- // the sensor was effectively inserted, register it
- touchsensor->RegisterSumo(this);
-}
-
-void KX_TouchEventManager::RemoveSensor(SCA_ISensor* sensor)
-{
- KX_TouchSensor* touchsensor = static_cast<KX_TouchSensor*>(sensor);
- if (touchsensor->Delink())
- // the sensor was effectively removed, unregister it
- touchsensor->UnregisterSumo(this);
-}
-
-
-
-void KX_TouchEventManager::EndFrame()
-{
- SG_DList::iterator<KX_TouchSensor> it(m_sensors);
- for (it.begin();!it.end();++it)
- {
- (*it)->EndFrame();
- }
-}
-
-
-
-void KX_TouchEventManager::NextFrame()
-{
- SG_DList::iterator<KX_TouchSensor> it(m_sensors);
- for (it.begin();!it.end();++it)
- (*it)->SynchronizeTransform();
-
- for (std::set<NewCollision>::iterator cit = m_newCollisions.begin(); cit != m_newCollisions.end(); ++cit)
- {
- // Controllers
- PHY_IPhysicsController* ctrl1 = (*cit).first;
- PHY_IPhysicsController* ctrl2 = (*cit).second;
-
- // Sensor iterator
- list<SCA_ISensor*>::iterator sit;
-
- // First client info
- KX_ClientObjectInfo *client_info = static_cast<KX_ClientObjectInfo*>(ctrl1->GetNewClientInfo());
- // First gameobject
- KX_GameObject *kxObj1 = KX_GameObject::GetClientObject(client_info);
- // Invoke sensor response for each object
- if (client_info) {
- for ( sit = client_info->m_sensors.begin(); sit != client_info->m_sensors.end(); ++sit) {
- static_cast<KX_TouchSensor*>(*sit)->NewHandleCollision(ctrl1, ctrl2, NULL);
- }
- }
-
- // Second client info
- client_info = static_cast<KX_ClientObjectInfo *>(ctrl2->GetNewClientInfo());
- // Second gameobject
- KX_GameObject *kxObj2 = KX_GameObject::GetClientObject(client_info);
- if (client_info) {
- for ( sit = client_info->m_sensors.begin(); sit != client_info->m_sensors.end(); ++sit) {
- static_cast<KX_TouchSensor*>(*sit)->NewHandleCollision(ctrl2, ctrl1, NULL);
- }
- }
- // Run python callbacks
- PHY_CollData *colldata = cit->colldata;
- kxObj1->RunCollisionCallbacks(kxObj2, colldata->m_point1, colldata->m_normal);
- kxObj2->RunCollisionCallbacks(kxObj1, colldata->m_point2, -colldata->m_normal);
-
- delete cit->colldata;
- }
-
- m_newCollisions.clear();
-
- for (it.begin();!it.end();++it)
- (*it)->Activate(m_logicmgr);
- }
-
-
-KX_TouchEventManager::NewCollision::NewCollision(PHY_IPhysicsController *first,
- PHY_IPhysicsController *second,
- const PHY_CollData *colldata)
- : first(first), second(second), colldata(new PHY_CollData(*colldata))
-{}
-
-KX_TouchEventManager::NewCollision::NewCollision(const NewCollision &to_copy)
- : first(to_copy.first), second(to_copy.second), colldata(to_copy.colldata)
-{}
-
-bool KX_TouchEventManager::NewCollision::operator<(const NewCollision &other) const
-{
- //see strict weak ordering: https://support.microsoft.com/en-us/kb/949171
- if (first == other.first) {
- if (second == other.second) {
- return colldata < other.colldata;
- }
- return second < other.second;
- }
- return first < other.first;
-}
diff --git a/source/gameengine/Ketsji/KX_TouchEventManager.h b/source/gameengine/Ketsji/KX_TouchEventManager.h
deleted file mode 100644
index d9c6fdad307..00000000000
--- a/source/gameengine/Ketsji/KX_TouchEventManager.h
+++ /dev/null
@@ -1,109 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file KX_TouchEventManager.h
- * \ingroup ketsji
- */
-
-#ifndef __KX_TOUCHEVENTMANAGER_H__
-#define __KX_TOUCHEVENTMANAGER_H__
-
-
-#include "SCA_EventManager.h"
-#include "KX_TouchSensor.h"
-#include "KX_GameObject.h"
-
-#include <vector>
-#include <set>
-
-class SCA_ISensor;
-class PHY_IPhysicsEnvironment;
-
-class KX_TouchEventManager : public SCA_EventManager
-{
- /**
- * Contains two colliding objects and the first contact point.
- */
- class NewCollision {
- public:
- PHY_IPhysicsController *first;
- PHY_IPhysicsController *second;
- PHY_CollData *colldata;
-
- /**
- * Creates a copy of the given PHY_CollData; freeing that copy should be done by the owner of
- * the NewCollision object.
- *
- * This allows us to efficiently store NewCollision objects in a std::set without creating more
- * copies of colldata, as the NewCollision copy constructor reuses the pointer and doesn't clone
- * it again. */
- NewCollision(PHY_IPhysicsController *first,
- PHY_IPhysicsController *second,
- const PHY_CollData *colldata);
- NewCollision(const NewCollision &to_copy);
- bool operator<(const NewCollision &other) const;
- };
-
- PHY_IPhysicsEnvironment* m_physEnv;
-
- std::set<NewCollision> m_newCollisions;
-
-
- static bool newCollisionResponse(void *client_data,
- void *object1,
- void *object2,
- const PHY_CollData *coll_data);
-
- static bool newBroadphaseResponse(void *client_data,
- void *object1,
- void *object2,
- const PHY_CollData *coll_data);
-
- virtual bool NewHandleCollision(void* obj1,void* obj2,
- const PHY_CollData * coll_data);
-
-
-
-
-
-public:
- KX_TouchEventManager(class SCA_LogicManager* logicmgr,
- PHY_IPhysicsEnvironment* physEnv);
- virtual void NextFrame();
- virtual void EndFrame();
- virtual void RegisterSensor(SCA_ISensor* sensor);
- virtual void RemoveSensor(SCA_ISensor* sensor);
- SCA_LogicManager* GetLogicManager() { return m_logicmgr;}
- PHY_IPhysicsEnvironment *GetPhysicsEnvironment() { return m_physEnv; }
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:KX_TouchEventManager")
-#endif
-};
-
-#endif /* __KX_TOUCHEVENTMANAGER_H__ */
diff --git a/source/gameengine/Ketsji/KX_TouchSensor.cpp b/source/gameengine/Ketsji/KX_TouchSensor.cpp
deleted file mode 100644
index 593d3e844e8..00000000000
--- a/source/gameengine/Ketsji/KX_TouchSensor.cpp
+++ /dev/null
@@ -1,362 +0,0 @@
-/*
- * Senses touch and collision events
- *
- *
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Ketsji/KX_TouchSensor.cpp
- * \ingroup ketsji
- */
-
-
-#include "KX_TouchSensor.h"
-#include "SCA_EventManager.h"
-#include "SCA_LogicManager.h"
-#include "KX_GameObject.h"
-#include "KX_TouchEventManager.h"
-
-#include "PHY_IPhysicsController.h"
-
-#include "RAS_MeshObject.h"
-
-#include <iostream>
-#include "PHY_IPhysicsEnvironment.h"
-
-/* ------------------------------------------------------------------------- */
-/* Native functions */
-/* ------------------------------------------------------------------------- */
-
-void KX_TouchSensor::SynchronizeTransform()
-{
- // the touch sensor does not require any synchronization: it uses
- // the same physical object which is already synchronized by Blender
-}
-
-
-void KX_TouchSensor::EndFrame()
-{
- m_colliders->ReleaseAndRemoveAll();
- m_hitObject = NULL;
- m_bTriggered = false;
- m_bColliderHash = 0;
-}
-
-void KX_TouchSensor::UnregisterToManager()
-{
- // before unregistering the sensor, make sure we release all references
- EndFrame();
- SCA_ISensor::UnregisterToManager();
-}
-
-bool KX_TouchSensor::Evaluate()
-{
- bool result = false;
- bool reset = m_reset && m_level;
- m_reset = false;
- if (m_bTriggered != m_bLastTriggered)
- {
- m_bLastTriggered = m_bTriggered;
- if (!m_bTriggered)
- m_hitObject = NULL;
- result = true;
- }
- if (reset)
- // force an event
- result = true;
-
- if (m_bTouchPulse) { /* pulse on changes to the colliders */
- int count = m_colliders->GetCount();
-
- if (m_bLastCount!=count || m_bColliderHash!=m_bLastColliderHash) {
- m_bLastCount = count;
- m_bLastColliderHash= m_bColliderHash;
- result = true;
- }
- }
- return result;
-}
-
-KX_TouchSensor::KX_TouchSensor(SCA_EventManager* eventmgr,KX_GameObject* gameobj,bool bFindMaterial,bool bTouchPulse,const STR_String& touchedpropname)
-:SCA_ISensor(gameobj,eventmgr),
-m_touchedpropname(touchedpropname),
-m_bFindMaterial(bFindMaterial),
-m_bTouchPulse(bTouchPulse),
-m_hitMaterial("")
-/*m_sumoObj(sumoObj),*/
-{
-// KX_TouchEventManager* touchmgr = (KX_TouchEventManager*) eventmgr;
-// m_resptable = touchmgr->GetResponseTable();
-
-// m_solidHandle = m_sumoObj->getObjectHandle();
-
- m_colliders = new CListValue();
-
- KX_ClientObjectInfo *client_info = gameobj->getClientInfo();
- //client_info->m_gameobject = gameobj;
- //client_info->m_auxilary_info = NULL;
- client_info->m_sensors.push_back(this);
-
- m_physCtrl = gameobj->GetPhysicsController();
- MT_assert( !gameobj->GetPhysicsController() || m_physCtrl );
- Init();
-}
-
-void KX_TouchSensor::Init()
-{
- m_bCollision = false;
- m_bTriggered = false;
- m_bLastTriggered = (m_invert)?true:false;
- m_bLastCount = 0;
- m_bColliderHash = m_bLastColliderHash = 0;
- m_hitObject = NULL;
- m_reset = true;
-}
-
-KX_TouchSensor::~KX_TouchSensor()
-{
- //DT_ClearObjectResponse(m_resptable,m_solidHandle);
- m_colliders->Release();
-}
-
-CValue* KX_TouchSensor::GetReplica()
-{
- KX_TouchSensor* replica = new KX_TouchSensor(*this);
- replica->ProcessReplica();
- return replica;
-}
-
-void KX_TouchSensor::ProcessReplica()
-{
- SCA_ISensor::ProcessReplica();
- m_colliders = new CListValue();
- Init();
-}
-
-void KX_TouchSensor::ReParent(SCA_IObject* parent)
-{
- KX_GameObject *gameobj = static_cast<KX_GameObject *>(parent);
- PHY_IPhysicsController *sphy = ((KX_GameObject*)parent)->GetPhysicsController();
- if (sphy)
- m_physCtrl = sphy;
-
-// m_solidHandle = m_sumoObj->getObjectHandle();
- KX_ClientObjectInfo *client_info = gameobj->getClientInfo();
- //client_info->m_gameobject = gameobj;
- //client_info->m_auxilary_info = NULL;
-
- client_info->m_sensors.push_back(this);
- SCA_ISensor::ReParent(parent);
-}
-
-void KX_TouchSensor::RegisterSumo(KX_TouchEventManager *touchman)
-{
- if (m_physCtrl)
- {
- if (touchman->GetPhysicsEnvironment()->RequestCollisionCallback(m_physCtrl))
- {
- KX_ClientObjectInfo *client_info = static_cast<KX_ClientObjectInfo*>(m_physCtrl->GetNewClientInfo());
- if (client_info->isSensor())
- touchman->GetPhysicsEnvironment()->AddSensor(m_physCtrl);
- }
- }
-}
-void KX_TouchSensor::UnregisterSumo(KX_TouchEventManager* touchman)
-{
- if (m_physCtrl)
- {
- if (touchman->GetPhysicsEnvironment()->RemoveCollisionCallback(m_physCtrl))
- {
- // no more sensor on the controller, can remove it if it is a sensor object
- KX_ClientObjectInfo *client_info = static_cast<KX_ClientObjectInfo*>(m_physCtrl->GetNewClientInfo());
- if (client_info->isSensor())
- touchman->GetPhysicsEnvironment()->RemoveSensor(m_physCtrl);
- }
- }
-}
-
-// this function is called only for sensor objects
-// return true if the controller can collide with the object
-bool KX_TouchSensor::BroadPhaseSensorFilterCollision(void*obj1,void*obj2)
-{
- assert(obj1==m_physCtrl && obj2);
-
- KX_GameObject* myobj = (KX_GameObject*)GetParent();
- KX_GameObject* myparent = myobj->GetParent();
- KX_ClientObjectInfo *client_info = static_cast<KX_ClientObjectInfo*>(((PHY_IPhysicsController*)obj2)->GetNewClientInfo());
- KX_ClientObjectInfo *my_client_info = static_cast<KX_ClientObjectInfo*>(m_physCtrl->GetNewClientInfo());
- KX_GameObject* otherobj = ( client_info ? client_info->m_gameobject : NULL);
-
- // we can only check on persistent characteristic: m_link and m_suspended are not
- // good candidate because they are transient. That must be handled at another level
- if (!otherobj ||
- otherobj == myparent || // don't interact with our parent
- (my_client_info->m_type == KX_ClientObjectInfo::OBACTORSENSOR &&
- client_info->m_type != KX_ClientObjectInfo::ACTOR)) // only with actor objects
- return false;
-
- bool found = m_touchedpropname.IsEmpty();
- if (!found)
- {
- if (m_bFindMaterial) {
- for (unsigned int i = 0; i < otherobj->GetMeshCount(); ++i) {
- RAS_MeshObject *meshObj = otherobj->GetMesh(i);
- for (unsigned int j = 0; j < meshObj->NumMaterials(); ++j) {
- found = strcmp(m_touchedpropname.ReadPtr(), meshObj->GetMaterialName(j).ReadPtr() + 2) == 0;
- if (found)
- break;
- }
- }
- }
- else {
- found = (otherobj->GetProperty(m_touchedpropname) != NULL);
- }
- }
- return found;
-}
-
-bool KX_TouchSensor::NewHandleCollision(void*object1,void*object2,const PHY_CollData* colldata)
-{
-// KX_TouchEventManager* toucheventmgr = (KX_TouchEventManager*)m_eventmgr;
- KX_GameObject* parent = (KX_GameObject*)GetParent();
-
- // need the mapping from PHY_IPhysicsController to gameobjects now
-
- KX_ClientObjectInfo *client_info = static_cast<KX_ClientObjectInfo*> (object1 == m_physCtrl?
- ((PHY_IPhysicsController*)object2)->GetNewClientInfo():
- ((PHY_IPhysicsController*)object1)->GetNewClientInfo());
-
- KX_GameObject* gameobj = ( client_info ?
- client_info->m_gameobject :
- NULL);
-
- // add the same check as in SCA_ISensor::Activate(),
- // we don't want to record collision when the sensor is not active.
- if (m_links && !m_suspended &&
- gameobj && (gameobj != parent) && client_info->isActor())
- {
-
- bool found = m_touchedpropname.IsEmpty();
- bool hitMaterial = false;
- if (!found)
- {
- if (m_bFindMaterial) {
- for (unsigned int i = 0; i < gameobj->GetMeshCount(); ++i) {
- RAS_MeshObject *meshObj = gameobj->GetMesh(i);
- for (unsigned int j = 0; j < meshObj->NumMaterials(); ++j) {
- found = strcmp(m_touchedpropname.ReadPtr(), meshObj->GetMaterialName(j).ReadPtr() + 2) == 0;
- if (found) {
- hitMaterial = true;
- break;
- }
- }
- }
- }
- else {
- found = (gameobj->GetProperty(m_touchedpropname) != NULL);
- }
- }
- if (found)
- {
- if (!m_colliders->SearchValue(gameobj)) {
- m_colliders->Add(gameobj->AddRef());
-
- if (m_bTouchPulse)
- m_bColliderHash += (uint_ptr)(static_cast<void *>(&gameobj));
- }
- m_bTriggered = true;
- m_hitObject = gameobj;
- m_hitMaterial = hitMaterial;
- //printf("KX_TouchSensor::HandleCollision\n");
- }
-
- }
- return false; // was DT_CONTINUE but this was defined in sumo as false.
-}
-
-#ifdef WITH_PYTHON
-
-/* ------------------------------------------------------------------------- */
-/* Python functions */
-/* ------------------------------------------------------------------------- */
-/* Integration hooks ------------------------------------------------------- */
-PyTypeObject KX_TouchSensor::Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "KX_TouchSensor",
- sizeof(PyObjectPlus_Proxy),
- 0,
- py_base_dealloc,
- 0,
- 0,
- 0,
- 0,
- py_base_repr,
- 0,0,0,0,0,0,0,0,0,
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
- 0,0,0,0,0,0,0,
- Methods,
- 0,
- 0,
- &SCA_ISensor::Type,
- 0,0,0,0,0,0,
- py_base_new
-};
-
-PyMethodDef KX_TouchSensor::Methods[] = {
- {NULL,NULL} //Sentinel
-};
-
-PyAttributeDef KX_TouchSensor::Attributes[] = {
- KX_PYATTRIBUTE_STRING_RW("propName",0,MAX_PROP_NAME,false,KX_TouchSensor,m_touchedpropname),
- KX_PYATTRIBUTE_BOOL_RW("useMaterial",KX_TouchSensor,m_bFindMaterial),
- KX_PYATTRIBUTE_BOOL_RW("usePulseCollision",KX_TouchSensor,m_bTouchPulse),
- KX_PYATTRIBUTE_STRING_RO("hitMaterial", KX_TouchSensor, m_hitMaterial),
- KX_PYATTRIBUTE_RO_FUNCTION("hitObject", KX_TouchSensor, pyattr_get_object_hit),
- KX_PYATTRIBUTE_RO_FUNCTION("hitObjectList", KX_TouchSensor, pyattr_get_object_hit_list),
- { NULL } //Sentinel
-};
-
-/* Python API */
-
-PyObject *KX_TouchSensor::pyattr_get_object_hit(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_TouchSensor* self = static_cast<KX_TouchSensor*>(self_v);
-
- if (self->m_hitObject)
- return self->m_hitObject->GetProxy();
- else
- Py_RETURN_NONE;
-}
-
-PyObject *KX_TouchSensor::pyattr_get_object_hit_list(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_TouchSensor* self = static_cast<KX_TouchSensor*>(self_v);
- return self->m_colliders->GetProxy();
-}
-
-#endif
-
-/* eof */
diff --git a/source/gameengine/Ketsji/KX_TouchSensor.h b/source/gameengine/Ketsji/KX_TouchSensor.h
deleted file mode 100644
index e1b5725a32b..00000000000
--- a/source/gameengine/Ketsji/KX_TouchSensor.h
+++ /dev/null
@@ -1,138 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file KX_TouchSensor.h
- * \ingroup ketsji
- * \brief Senses touch and collision events
- */
-
-#ifndef __KX_TOUCHSENSOR_H__
-#define __KX_TOUCHSENSOR_H__
-
-#include "SCA_ISensor.h"
-#include "EXP_ListValue.h"
-
-struct PHY_CollData;
-
-#include "KX_ClientObjectInfo.h"
-
-#if defined(_WIN64)
-typedef unsigned __int64 uint_ptr;
-#else
-typedef unsigned long uint_ptr;
-#endif
-
-class KX_TouchEventManager;
-
-class KX_TouchSensor : public SCA_ISensor
-{
-protected:
- Py_Header
-
- /**
- * The sensor should only look for objects with this property.
- */
- STR_String m_touchedpropname;
- bool m_bFindMaterial;
- bool m_bTouchPulse; /* changes in the colliding objects trigger pulses */
-
- class PHY_IPhysicsController* m_physCtrl;
-
- bool m_bCollision;
- bool m_bTriggered;
- bool m_bLastTriggered;
-
- // Use with m_bTouchPulse to detect changes
- int m_bLastCount; /* size of m_colliders last tick */
- uint_ptr m_bColliderHash; /* hash collision objects pointers to trigger in case one object collides and another takes its place */
- uint_ptr m_bLastColliderHash;
-
- SCA_IObject* m_hitObject;
- class CListValue* m_colliders;
- STR_String m_hitMaterial;
-
-public:
- KX_TouchSensor(class SCA_EventManager* eventmgr,
- class KX_GameObject* gameobj,
- bool bFindMaterial,
- bool bTouchPulse,
- const STR_String& touchedpropname);
- virtual ~KX_TouchSensor();
-
- virtual CValue* GetReplica();
- virtual void ProcessReplica();
- virtual void SynchronizeTransform();
- virtual bool Evaluate();
- virtual void Init();
- virtual void ReParent(SCA_IObject* parent);
-
- virtual void RegisterSumo(KX_TouchEventManager* touchman);
- virtual void UnregisterSumo(KX_TouchEventManager* touchman);
- virtual void UnregisterToManager();
-
-#if 0
- virtual DT_Bool HandleCollision(void* obj1,void* obj2,
- const DT_CollData * coll_data);
-#endif
-
- virtual bool NewHandleCollision(void*obj1,void*obj2,const PHY_CollData* colldata);
-
- // Allows to do pre-filtering and save computation time
- // obj1 = sensor physical controller, obj2 = physical controller of second object
- // return value = true if collision should be checked on pair of object
- virtual bool BroadPhaseFilterCollision(void*obj1,void*obj2) { return true; }
- virtual bool BroadPhaseSensorFilterCollision(void*obj1,void*obj2);
- virtual sensortype GetSensorType() { return ST_TOUCH; }
-
-
- virtual bool IsPositiveTrigger() {
- bool result = m_bTriggered;
- if (m_invert) result = !result;
- return result;
- }
-
- virtual void EndFrame();
-
- class PHY_IPhysicsController* GetPhysicsController() { return m_physCtrl; }
-
-
- // todo: put some info for collision maybe
-
-#ifdef WITH_PYTHON
-
- /* --------------------------------------------------------------------- */
- /* Python interface ---------------------------------------------------- */
- /* --------------------------------------------------------------------- */
-
- static PyObject* pyattr_get_object_hit(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject* pyattr_get_object_hit_list(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
-
-#endif
-
-};
-
-#endif /* __KX_TOUCHSENSOR_H__ */
diff --git a/source/gameengine/Ketsji/KX_TrackToActuator.cpp b/source/gameengine/Ketsji/KX_TrackToActuator.cpp
deleted file mode 100644
index a8fa9b0815d..00000000000
--- a/source/gameengine/Ketsji/KX_TrackToActuator.cpp
+++ /dev/null
@@ -1,430 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Ketsji/KX_TrackToActuator.cpp
- * \ingroup ketsji
- *
- * Replace the mesh for this actuator's parent
- */
-
-/* m_trackflag is used to determine the forward tracking direction
- * m_upflag for the up direction
- * normal situation is +y for forward, +z for up */
-
-#include "MT_Scalar.h"
-#include "SCA_IActuator.h"
-#include "KX_TrackToActuator.h"
-#include "SCA_IScene.h"
-#include "SCA_LogicManager.h"
-#include <math.h>
-#include <iostream>
-#include "KX_GameObject.h"
-
-#include "EXP_PyObjectPlus.h"
-
-/* ------------------------------------------------------------------------- */
-/* Native functions */
-/* ------------------------------------------------------------------------- */
-
-KX_TrackToActuator::KX_TrackToActuator(SCA_IObject *gameobj,
- SCA_IObject *ob,
- int time,
- bool allow3D,
- int trackflag,
- int upflag)
- : SCA_IActuator(gameobj, KX_ACT_TRACKTO)
-{
- m_time = time;
- m_allow3D = allow3D;
- m_object = ob;
- m_trackflag = trackflag;
- m_upflag = upflag;
- m_parentobj = 0;
-
- if (m_object)
- m_object->RegisterActuator(this);
-
- {
- // if the object is vertex parented, don't check parent orientation as the link is broken
- if (!((KX_GameObject*)gameobj)->IsVertexParent()) {
- m_parentobj = ((KX_GameObject*)gameobj)->GetParent(); // check if the object is parented
- if (m_parentobj) {
- // if so, store the initial local rotation
- // this is needed to revert the effect of the parent inverse node (TBC)
- m_parentlocalmat = m_parentobj->GetSGNode()->GetLocalOrientation();
- // use registration mechanism rather than AddRef, it creates zombie objects
- m_parentobj->RegisterActuator(this);
- }
- }
- }
-
-} /* End of constructor */
-
-
-
-/* old function from Blender */
-static MT_Matrix3x3 EulToMat3(float eul[3])
-{
- MT_Matrix3x3 mat;
- float ci, cj, ch, si, sj, sh, cc, cs, sc, ss;
-
- ci = cosf(eul[0]);
- cj = cosf(eul[1]);
- ch = cosf(eul[2]);
- si = sinf(eul[0]);
- sj = sinf(eul[1]);
- sh = sinf(eul[2]);
- cc = ci*ch;
- cs = ci*sh;
- sc = si*ch;
- ss = si*sh;
-
- mat[0][0] = cj*ch;
- mat[1][0] = sj*sc-cs;
- mat[2][0] = sj*cc+ss;
- mat[0][1] = cj*sh;
- mat[1][1] = sj*ss+cc;
- mat[2][1] = sj*cs-sc;
- mat[0][2] = -sj;
- mat[1][2] = cj*si;
- mat[2][2] = cj*ci;
-
- return mat;
-}
-
-
-
-/* old function from Blender */
-static void Mat3ToEulOld(MT_Matrix3x3 mat, float eul[3])
-{
- const float cy = sqrtf(mat[0][0] * mat[0][0] + mat[0][1] * mat[0][1]);
-
- if (cy > (float)(16.0f * FLT_EPSILON)) {
- eul[0] = atan2f( mat[1][2], mat[2][2]);
- eul[1] = atan2f(-mat[0][2], cy);
- eul[2] = atan2f( mat[0][1], mat[0][0]);
- }
- else {
- eul[0] = atan2f(-mat[2][1], mat[1][1]);
- eul[1] = atan2f(-mat[0][2], cy);
- eul[2] = 0.0f;
- }
-}
-
-
-
-/* old function from Blender */
-static void compatible_eulFast(float *eul, float *oldrot)
-{
- float dx, dy, dz;
-
- /* angular difference of 360 degrees */
-
- dx = eul[0] - oldrot[0];
- dy = eul[1] - oldrot[1];
- dz = eul[2] - oldrot[2];
-
- if (fabsf(dx) > (float)MT_PI) {
- if (dx > 0.0f) eul[0] -= (float)MT_2_PI; else eul[0] += (float)MT_2_PI;
- }
- if (fabsf(dy) > (float)MT_PI) {
- if (dy > 0.0f) eul[1] -= (float)MT_2_PI; else eul[1] += (float)MT_2_PI;
- }
- if (fabsf(dz) > (float)MT_PI) {
- if (dz > 0.0f) eul[2] -= (float)MT_2_PI; else eul[2] += (float)MT_2_PI;
- }
-}
-
-
-
-static MT_Matrix3x3 matrix3x3_interpol(MT_Matrix3x3 oldmat, MT_Matrix3x3 mat, int m_time)
-{
- float eul[3], oldeul[3];
-
- Mat3ToEulOld(oldmat, oldeul);
- Mat3ToEulOld(mat, eul);
- compatible_eulFast(eul, oldeul);
-
- eul[0] = (m_time * oldeul[0] + eul[0]) / (1.0f + m_time);
- eul[1] = (m_time * oldeul[1] + eul[1]) / (1.0f + m_time);
- eul[2] = (m_time * oldeul[2] + eul[2]) / (1.0f + m_time);
-
- return EulToMat3(eul);
-}
-
-static float basis_cross(int n, int m)
-{
- switch (n - m) {
- case 1:
- case -2:
- return 1.0f;
-
- case -1:
- case 2:
- return -1.0f;
-
- default:
- return 0.0f;
- }
-}
-
-/* vectomat function obtained from constrain.c and modified to work with MOTO library */
-static MT_Matrix3x3 vectomat(MT_Vector3 vec, short axis, short upflag, short threedimup)
-{
- MT_Matrix3x3 mat;
- MT_Vector3 y(MT_Scalar(0.0f), MT_Scalar(1.0f), MT_Scalar(0.0f));
- MT_Vector3 z(MT_Scalar(0.0f), MT_Scalar(0.0f), MT_Scalar(1.0f)); /* world Z axis is the global up axis */
- MT_Vector3 proj;
- MT_Vector3 right;
- MT_Scalar mul;
- int right_index;
-
- /* Normalized Vec vector*/
- vec = vec.safe_normalized_vec(z);
-
- /* if 2D doesn't move the up vector */
- if (!threedimup) {
- vec.setValue(MT_Scalar(vec[0]), MT_Scalar(vec[1]), MT_Scalar(0.0f));
- vec = (vec - z.dot(vec)*z).safe_normalized_vec(z);
- }
-
- if (axis > 2)
- axis -= 3;
- else
- vec = -vec;
-
- /* project the up vector onto the plane specified by vec */
- /* first z onto vec... */
- mul = z.dot(vec) / vec.dot(vec);
- proj = vec * mul;
- /* then onto the plane */
- proj = z - proj;
- /* proj specifies the transformation of the up axis */
- proj = proj.safe_normalized_vec(y);
-
- /* Normalized cross product of vec and proj specifies transformation of the right axis */
- right = proj.cross(vec);
- right.normalize();
-
- if (axis != upflag) {
- right_index = 3 - axis - upflag;
-
- /* account for up direction, track direction */
- right = right * basis_cross(axis, upflag);
- mat.setRow(right_index, right);
- mat.setRow(upflag, proj);
- mat.setRow(axis, vec);
- mat = mat.inverse();
- }
- /* identity matrix - don't do anything if the two axes are the same */
- else {
- mat.setIdentity();
- }
-
- return mat;
-}
-
-KX_TrackToActuator::~KX_TrackToActuator()
-{
- if (m_object)
- m_object->UnregisterActuator(this);
- if (m_parentobj)
- m_parentobj->UnregisterActuator(this);
-} /* end of destructor */
-
-void KX_TrackToActuator::ProcessReplica()
-{
- // the replica is tracking the same object => register it
- if (m_object)
- m_object->RegisterActuator(this);
- if (m_parentobj)
- m_parentobj->RegisterActuator(this);
- SCA_IActuator::ProcessReplica();
-}
-
-
-bool KX_TrackToActuator::UnlinkObject(SCA_IObject* clientobj)
-{
- if (clientobj == m_object)
- {
- // this object is being deleted, we cannot continue to track it.
- m_object = NULL;
- return true;
- }
- if (clientobj == m_parentobj)
- {
- m_parentobj = NULL;
- return true;
- }
- return false;
-}
-
-void KX_TrackToActuator::Relink(CTR_Map<CTR_HashedPtr, void*> *obj_map)
-{
- void **h_obj = (*obj_map)[m_object];
- if (h_obj) {
- if (m_object)
- m_object->UnregisterActuator(this);
- m_object = (SCA_IObject*)(*h_obj);
- m_object->RegisterActuator(this);
- }
-
- void **h_parobj = (*obj_map)[m_parentobj];
- if (h_parobj) {
- if (m_parentobj)
- m_parentobj->UnregisterActuator(this);
- m_parentobj= (KX_GameObject*)(*h_parobj);
- m_parentobj->RegisterActuator(this);
- }
-}
-
-
-bool KX_TrackToActuator::Update(double curtime, bool frame)
-{
- bool result = false;
- bool bNegativeEvent = IsNegativeEvent();
- RemoveAllEvents();
-
- if (bNegativeEvent)
- {
- // do nothing on negative events
- }
- else if (m_object)
- {
- KX_GameObject* curobj = (KX_GameObject*) GetParent();
- MT_Vector3 dir = curobj->NodeGetWorldPosition() - ((KX_GameObject*)m_object)->NodeGetWorldPosition();
- MT_Matrix3x3 mat;
- MT_Matrix3x3 oldmat;
-
- mat = vectomat(dir, m_trackflag, m_upflag, m_allow3D);
- oldmat = curobj->NodeGetWorldOrientation();
-
- /* erwin should rewrite this! */
- mat = matrix3x3_interpol(oldmat, mat, m_time);
-
- /* check if the model is parented and calculate the child transform */
- if (m_parentobj) {
-
- MT_Point3 localpos;
- localpos = curobj->GetSGNode()->GetLocalPosition();
- // Get the inverse of the parent matrix
- MT_Matrix3x3 parentmatinv;
- parentmatinv = m_parentobj->NodeGetWorldOrientation().inverse();
- // transform the local coordinate system into the parents system
- mat = parentmatinv * mat;
- // append the initial parent local rotation matrix
- mat = m_parentlocalmat * mat;
-
- // set the models tranformation properties
- curobj->NodeSetLocalOrientation(mat);
- curobj->NodeSetLocalPosition(localpos);
- //curobj->UpdateTransform();
- }
- else {
- curobj->NodeSetLocalOrientation(mat);
- }
-
- result = true;
- }
-
- return result;
-}
-
-#ifdef WITH_PYTHON
-
-/* ------------------------------------------------------------------------- */
-/* Python functions */
-/* ------------------------------------------------------------------------- */
-
-/* Integration hooks ------------------------------------------------------- */
-PyTypeObject KX_TrackToActuator::Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "KX_TrackToActuator",
- sizeof(PyObjectPlus_Proxy),
- 0,
- py_base_dealloc,
- 0,
- 0,
- 0,
- 0,
- py_base_repr,
- 0,0,0,0,0,0,0,0,0,
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
- 0,0,0,0,0,0,0,
- Methods,
- 0,
- 0,
- &SCA_IActuator::Type,
- 0,0,0,0,0,0,
- py_base_new
-};
-
-PyMethodDef KX_TrackToActuator::Methods[] = {
- {NULL,NULL} //Sentinel
-};
-
-PyAttributeDef KX_TrackToActuator::Attributes[] = {
- KX_PYATTRIBUTE_INT_RW("time",0,1000,true,KX_TrackToActuator,m_time),
- KX_PYATTRIBUTE_BOOL_RW("use3D",KX_TrackToActuator,m_allow3D),
- KX_PYATTRIBUTE_INT_RW("upAxis", 0, 2, true, KX_TrackToActuator,m_upflag),
- KX_PYATTRIBUTE_INT_RW("trackAxis", 0, 5, true, KX_TrackToActuator,m_trackflag),
- KX_PYATTRIBUTE_RW_FUNCTION("object", KX_TrackToActuator, pyattr_get_object, pyattr_set_object),
-
- { NULL } //Sentinel
-};
-
-PyObject *KX_TrackToActuator::pyattr_get_object(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_TrackToActuator* actuator = static_cast<KX_TrackToActuator*>(self);
- if (!actuator->m_object)
- Py_RETURN_NONE;
- else
- return actuator->m_object->GetProxy();
-}
-
-int KX_TrackToActuator::pyattr_set_object(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_TrackToActuator* actuator = static_cast<KX_TrackToActuator*>(self);
- KX_GameObject *gameobj;
-
- if (!ConvertPythonToGameObject(actuator->GetLogicManager(), value, &gameobj, true, "actuator.object = value: KX_TrackToActuator"))
- return PY_SET_ATTR_FAIL; // ConvertPythonToGameObject sets the error
-
- if (actuator->m_object != NULL)
- actuator->m_object->UnregisterActuator(actuator);
-
- actuator->m_object = (SCA_IObject*) gameobj;
-
- if (actuator->m_object)
- actuator->m_object->RegisterActuator(actuator);
-
- return PY_SET_ATTR_SUCCESS;
-}
-
-#endif // WITH_PYTHON
-
-/* eof */
diff --git a/source/gameengine/Ketsji/KX_TrackToActuator.h b/source/gameengine/Ketsji/KX_TrackToActuator.h
deleted file mode 100644
index 124014eede2..00000000000
--- a/source/gameengine/Ketsji/KX_TrackToActuator.h
+++ /dev/null
@@ -1,98 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file KX_TrackToActuator.h
- * \ingroup ketsji
- */
-
-#ifndef __KX_TRACKTOACTUATOR_H__
-#define __KX_TRACKTOACTUATOR_H__
-
-#include "SCA_IActuator.h"
-#include "SCA_IObject.h"
-#include "MT_Matrix3x3.h"
-#include "KX_GameObject.h"
-
-
-class KX_TrackToActuator : public SCA_IActuator
-{
- Py_Header
- // Object reference. Actually, we use the object's 'life'
- SCA_IObject* m_object;
- // 3d toggle
- bool m_allow3D;
- // time field
- int m_time;
- int m_trackflag;
- int m_upflag;
-
- MT_Matrix3x3 m_parentlocalmat;
- KX_GameObject* m_parentobj;
-
- public:
- KX_TrackToActuator(SCA_IObject* gameobj, SCA_IObject *ob, int time,
- bool threedee,int trackflag,int upflag);
- virtual ~KX_TrackToActuator();
- virtual CValue* GetReplica() {
- KX_TrackToActuator* replica = new KX_TrackToActuator(*this);
- replica->ProcessReplica();
- return replica;
- };
-
- virtual void ProcessReplica();
- virtual bool UnlinkObject(SCA_IObject* clientobj);
- virtual void Relink(CTR_Map<CTR_HashedPtr, void*> *obj_map);
- virtual bool Update(double curtime, bool frame);
-
- //Python Interface
- enum UpAxis {
- KX_TRACK_UPAXIS_POS_X = 0,
- KX_TRACK_UPAXIS_POS_Y,
- KX_TRACK_UPAXIS_POS_Z
- };
- enum TrackAxis {
- KX_TRACK_TRAXIS_POS_X = 0,
- KX_TRACK_TRAXIS_POS_Y,
- KX_TRACK_TRAXIS_POS_Z,
- KX_TRACK_TRAXIS_NEG_X,
- KX_TRACK_TRAXIS_NEG_Y,
- KX_TRACK_TRAXIS_NEG_Z
- };
-
-#ifdef WITH_PYTHON
-
- /* Python part */
-
- /* These are used to get and set m_ob */
- static PyObject *pyattr_get_object(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_object(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
-
-#endif /* WITH_PYTHON */
-
-}; /* end of class KX_TrackToActuator : public KX_EditObjectActuator */
-
-#endif /* __KX_TRACKTOACTUATOR_H__ */
diff --git a/source/gameengine/Ketsji/KX_VehicleWrapper.cpp b/source/gameengine/Ketsji/KX_VehicleWrapper.cpp
deleted file mode 100644
index ddae645802c..00000000000
--- a/source/gameengine/Ketsji/KX_VehicleWrapper.cpp
+++ /dev/null
@@ -1,380 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Ketsji/KX_VehicleWrapper.cpp
- * \ingroup ketsji
- */
-
-#include "EXP_PyObjectPlus.h"
-
-#include "KX_VehicleWrapper.h"
-#include "PHY_IPhysicsEnvironment.h"
-#include "PHY_IVehicle.h"
-#include "KX_PyMath.h"
-#include "KX_GameObject.h"
-#include "KX_MotionState.h"
-#include "KX_PythonInit.h"
-
-KX_VehicleWrapper::KX_VehicleWrapper(
- PHY_IVehicle* vehicle,
- PHY_IPhysicsEnvironment* physenv) :
- PyObjectPlus(),
- m_vehicle(vehicle),
- m_physenv(physenv)
-{
-}
-
-KX_VehicleWrapper::~KX_VehicleWrapper()
-{
- int numMotion = m_motionStates.size();
- for (int i=0;i<numMotion;i++)
- {
- PHY_IMotionState* motionState = m_motionStates[i];
- delete motionState;
- }
- m_motionStates.clear();
-}
-
-#ifdef WITH_PYTHON
-
-
-static bool raise_exc_wheel(PHY_IVehicle *vehicle, int i, const char *method)
-{
- if (i < 0 || i >= vehicle->GetNumWheels()) {
- PyErr_Format(PyExc_ValueError,
- "%s(...): wheel index %d out of range (0 to %d).", method, i, vehicle->GetNumWheels() - 1);
- return true;
- }
- else {
- return false;
- }
-}
-
-#define WHEEL_INDEX_CHECK_OR_RETURN(i, method) \
- if (raise_exc_wheel(m_vehicle, i, method)) {return NULL;} (void)0
-
-
-PyObject *KX_VehicleWrapper::PyAddWheel(PyObject *args)
-{
-
- PyObject *pylistPos,*pylistDir,*pylistAxleDir;
- PyObject *wheelGameObject;
- float suspensionRestLength,wheelRadius;
- int hasSteering;
-
-
- if (PyArg_ParseTuple(args,"OOOOffi:addWheel",&wheelGameObject,&pylistPos,&pylistDir,&pylistAxleDir,&suspensionRestLength,&wheelRadius,&hasSteering))
- {
- KX_GameObject *gameOb;
- if (!ConvertPythonToGameObject(KX_GetActiveScene()->GetLogicManager(), wheelGameObject, &gameOb, false, "vehicle.addWheel(...): KX_VehicleWrapper (first argument)"))
- return NULL;
-
- if (gameOb->GetSGNode())
- {
- MT_Vector3 attachPos,attachDir,attachAxle;
- if (!PyVecTo(pylistPos,attachPos)) {
- PyErr_SetString(PyExc_AttributeError,
- "addWheel(...) Unable to add wheel. attachPos must be a vector with 3 elements.");
- return NULL;
- }
- if (!PyVecTo(pylistDir,attachDir)) {
- PyErr_SetString(PyExc_AttributeError,
- "addWheel(...) Unable to add wheel. downDir must be a vector with 3 elements.");
- return NULL;
- }
- if (!PyVecTo(pylistAxleDir,attachAxle)) {
- PyErr_SetString(PyExc_AttributeError,
- "addWheel(...) Unable to add wheel. axleDir must be a vector with 3 elements.");
- return NULL;
- }
-
- //someone reverse some conventions inside Bullet (axle winding)
- attachAxle = -attachAxle;
-
- if (wheelRadius <= 0) {
- PyErr_SetString(PyExc_AttributeError,
- "addWheel(...) Unable to add wheel. wheelRadius must be positive.");
- return NULL;
- }
-
- PHY_IMotionState *motionState = new KX_MotionState(gameOb->GetSGNode());
- m_vehicle->AddWheel(motionState,attachPos,attachDir,attachAxle,suspensionRestLength,wheelRadius,hasSteering);
- }
-
- } else {
- return NULL;
- }
- Py_RETURN_NONE;
-}
-
-
-PyObject *KX_VehicleWrapper::PyGetWheelPosition(PyObject *args)
-{
-
- int wheelIndex;
-
- if (PyArg_ParseTuple(args,"i:getWheelPosition",&wheelIndex))
- {
- float position[3];
- WHEEL_INDEX_CHECK_OR_RETURN(wheelIndex, "getWheelPosition");
-
- m_vehicle->GetWheelPosition(wheelIndex,position[0],position[1],position[2]);
- MT_Vector3 pos(position[0],position[1],position[2]);
- return PyObjectFrom(pos);
- }
- return NULL;
-}
-
-PyObject *KX_VehicleWrapper::PyGetWheelRotation(PyObject *args)
-{
- int wheelIndex;
- if (PyArg_ParseTuple(args,"i:getWheelRotation",&wheelIndex))
- {
- WHEEL_INDEX_CHECK_OR_RETURN(wheelIndex, "getWheelRotation");
-
- return PyFloat_FromDouble(m_vehicle->GetWheelRotation(wheelIndex));
- }
- return NULL;
-}
-
-PyObject *KX_VehicleWrapper::PyGetWheelOrientationQuaternion(PyObject *args)
-{
- int wheelIndex;
- if (PyArg_ParseTuple(args,"i:getWheelOrientationQuaternion",&wheelIndex))
- {
- float orn[4];
- WHEEL_INDEX_CHECK_OR_RETURN(wheelIndex, "getWheelOrientationQuaternion");
-
- m_vehicle->GetWheelOrientationQuaternion(wheelIndex,orn[0],orn[1],orn[2],orn[3]);
- MT_Quaternion quatorn(orn[0],orn[1],orn[2],orn[3]);
- MT_Matrix3x3 ornmat(quatorn);
- return PyObjectFrom(ornmat);
- }
- return NULL;
-
-}
-
-
-PyObject *KX_VehicleWrapper::PyGetNumWheels(PyObject *args)
-{
- return PyLong_FromLong(m_vehicle->GetNumWheels());
-}
-
-
-PyObject *KX_VehicleWrapper::PyGetConstraintId(PyObject *args)
-{
- return PyLong_FromLong(m_vehicle->GetUserConstraintId());
-}
-
-
-PyObject *KX_VehicleWrapper::PyApplyEngineForce(PyObject *args)
-{
- float force;
- int wheelIndex;
-
- if (PyArg_ParseTuple(args,"fi:applyEngineForce",&force,&wheelIndex))
- {
- WHEEL_INDEX_CHECK_OR_RETURN(wheelIndex, "applyEngineForce");
-
- force *= -1.f;//someone reverse some conventions inside Bullet (axle winding)
- m_vehicle->ApplyEngineForce(force,wheelIndex);
- }
- else {
- return NULL;
- }
- Py_RETURN_NONE;
-}
-
-PyObject *KX_VehicleWrapper::PySetTyreFriction(PyObject *args)
-{
- float wheelFriction;
- int wheelIndex;
-
- if (PyArg_ParseTuple(args,"fi:setTyreFriction",&wheelFriction,&wheelIndex))
- {
- WHEEL_INDEX_CHECK_OR_RETURN(wheelIndex, "setTyreFriction");
-
- m_vehicle->SetWheelFriction(wheelFriction,wheelIndex);
- }
- else {
- return NULL;
- }
- Py_RETURN_NONE;
-}
-
-PyObject *KX_VehicleWrapper::PySetSuspensionStiffness(PyObject *args)
-{
- float suspensionStiffness;
- int wheelIndex;
-
- if (PyArg_ParseTuple(args,"fi:setSuspensionStiffness",&suspensionStiffness,&wheelIndex))
- {
- WHEEL_INDEX_CHECK_OR_RETURN(wheelIndex, "setSuspensionStiffness");
-
- m_vehicle->SetSuspensionStiffness(suspensionStiffness,wheelIndex);
- }
- else {
- return NULL;
- }
- Py_RETURN_NONE;
-}
-
-PyObject *KX_VehicleWrapper::PySetSuspensionDamping(PyObject *args)
-{
- float suspensionDamping;
- int wheelIndex;
-
- if (PyArg_ParseTuple(args,"fi:setSuspensionDamping",&suspensionDamping,&wheelIndex))
- {
- WHEEL_INDEX_CHECK_OR_RETURN(wheelIndex, "setSuspensionDamping");
-
- m_vehicle->SetSuspensionDamping(suspensionDamping,wheelIndex);
- } else {
- return NULL;
- }
- Py_RETURN_NONE;
-}
-
-PyObject *KX_VehicleWrapper::PySetSuspensionCompression(PyObject *args)
-{
- float suspensionCompression;
- int wheelIndex;
-
- if (PyArg_ParseTuple(args,"fi:setSuspensionCompression",&suspensionCompression,&wheelIndex))
- {
- WHEEL_INDEX_CHECK_OR_RETURN(wheelIndex, "setSuspensionCompression");
-
- m_vehicle->SetSuspensionCompression(suspensionCompression,wheelIndex);
- } else {
- return NULL;
- }
- Py_RETURN_NONE;
-}
-
-PyObject *KX_VehicleWrapper::PySetRollInfluence(PyObject *args)
-{
- float rollInfluence;
- int wheelIndex;
-
- if (PyArg_ParseTuple(args,"fi:setRollInfluence",&rollInfluence,&wheelIndex))
- {
- WHEEL_INDEX_CHECK_OR_RETURN(wheelIndex, "setRollInfluence");
-
- m_vehicle->SetRollInfluence(rollInfluence,wheelIndex);
- }
- else {
- return NULL;
- }
- Py_RETURN_NONE;
-}
-
-
-PyObject *KX_VehicleWrapper::PyApplyBraking(PyObject *args)
-{
- float braking;
- int wheelIndex;
-
- if (PyArg_ParseTuple(args,"fi:applyBraking",&braking,&wheelIndex))
- {
- WHEEL_INDEX_CHECK_OR_RETURN(wheelIndex, "applyBraking");
-
- m_vehicle->ApplyBraking(braking,wheelIndex);
- }
- else {
- return NULL;
- }
- Py_RETURN_NONE;
-}
-
-
-PyObject *KX_VehicleWrapper::PySetSteeringValue(PyObject *args)
-{
- float steeringValue;
- int wheelIndex;
-
- if (PyArg_ParseTuple(args,"fi:setSteeringValue",&steeringValue,&wheelIndex))
- {
- WHEEL_INDEX_CHECK_OR_RETURN(wheelIndex, "setSteeringValue");
-
- m_vehicle->SetSteeringValue(steeringValue,wheelIndex);
- }
- else {
- return NULL;
- }
- Py_RETURN_NONE;
-}
-
-
-PyObject *KX_VehicleWrapper::PyGetConstraintType(PyObject *args)
-{
- return PyLong_FromLong(m_vehicle->GetUserConstraintType());
-}
-
-
-
-
-
-//python specific stuff
-PyTypeObject KX_VehicleWrapper::Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "KX_VehicleWrapper",
- sizeof(PyObjectPlus_Proxy),
- 0,
- py_base_dealloc,
- 0,
- 0,
- 0,
- 0,
- py_base_repr,
- 0,0,0,0,0,0,0,0,0,
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
- 0,0,0,0,0,0,0,
- Methods,
- 0,
- 0,
- &PyObjectPlus::Type,
- 0,0,0,0,0,0,
- py_base_new
-};
-
-PyMethodDef KX_VehicleWrapper::Methods[] = {
- {"addWheel",(PyCFunction) KX_VehicleWrapper::sPyAddWheel, METH_VARARGS},
- {"getNumWheels",(PyCFunction) KX_VehicleWrapper::sPyGetNumWheels, METH_VARARGS},
- {"getWheelOrientationQuaternion",(PyCFunction) KX_VehicleWrapper::sPyGetWheelOrientationQuaternion, METH_VARARGS},
- {"getWheelRotation",(PyCFunction) KX_VehicleWrapper::sPyGetWheelRotation, METH_VARARGS},
- {"getWheelPosition",(PyCFunction) KX_VehicleWrapper::sPyGetWheelPosition, METH_VARARGS},
- {"getConstraintId",(PyCFunction) KX_VehicleWrapper::sPyGetConstraintId, METH_VARARGS},
- {"getConstraintType",(PyCFunction) KX_VehicleWrapper::sPyGetConstraintType, METH_VARARGS},
- {"setSteeringValue",(PyCFunction) KX_VehicleWrapper::sPySetSteeringValue, METH_VARARGS},
- {"applyEngineForce",(PyCFunction) KX_VehicleWrapper::sPyApplyEngineForce, METH_VARARGS},
- {"applyBraking",(PyCFunction) KX_VehicleWrapper::sPyApplyBraking, METH_VARARGS},
- {"setTyreFriction",(PyCFunction) KX_VehicleWrapper::sPySetTyreFriction, METH_VARARGS},
- {"setSuspensionStiffness",(PyCFunction) KX_VehicleWrapper::sPySetSuspensionStiffness, METH_VARARGS},
- {"setSuspensionDamping",(PyCFunction) KX_VehicleWrapper::sPySetSuspensionDamping, METH_VARARGS},
- {"setSuspensionCompression",(PyCFunction) KX_VehicleWrapper::sPySetSuspensionCompression, METH_VARARGS},
- {"setRollInfluence",(PyCFunction) KX_VehicleWrapper::sPySetRollInfluence, METH_VARARGS},
- {NULL,NULL} //Sentinel
-};
-
-PyAttributeDef KX_VehicleWrapper::Attributes[] = {
- { NULL } //Sentinel
-};
-
-#endif // WITH_PYTHON
diff --git a/source/gameengine/Ketsji/KX_VehicleWrapper.h b/source/gameengine/Ketsji/KX_VehicleWrapper.h
deleted file mode 100644
index 22b9591f48b..00000000000
--- a/source/gameengine/Ketsji/KX_VehicleWrapper.h
+++ /dev/null
@@ -1,61 +0,0 @@
-
-/** \file KX_VehicleWrapper.h
- * \ingroup ketsji
- */
-
-#ifndef __KX_VEHICLEWRAPPER_H__
-#define __KX_VEHICLEWRAPPER_H__
-
-#include "EXP_Value.h"
-class PHY_IVehicle;
-class PHY_IMotionState;
-
-#include <vector>
-
-///Python interface to physics vehicles (primarily 4-wheel cars and 2wheel bikes)
-class KX_VehicleWrapper : public PyObjectPlus
-{
- Py_Header
-
- std::vector<PHY_IMotionState*> m_motionStates;
-
-public:
- KX_VehicleWrapper(PHY_IVehicle* vehicle,class PHY_IPhysicsEnvironment* physenv);
- virtual ~KX_VehicleWrapper ();
- int getConstraintId();
-
-#ifdef WITH_PYTHON
-
- KX_PYMETHOD_VARARGS(KX_VehicleWrapper,AddWheel);
- KX_PYMETHOD_VARARGS(KX_VehicleWrapper,GetNumWheels);
- KX_PYMETHOD_VARARGS(KX_VehicleWrapper,GetWheelOrientationQuaternion);
- KX_PYMETHOD_VARARGS(KX_VehicleWrapper,GetWheelRotation);
-
- KX_PYMETHOD_VARARGS(KX_VehicleWrapper,GetWheelPosition);
-
- KX_PYMETHOD_VARARGS(KX_VehicleWrapper,GetConstraintId);
- KX_PYMETHOD_VARARGS(KX_VehicleWrapper,GetConstraintType);
-
- KX_PYMETHOD_VARARGS(KX_VehicleWrapper,SetSteeringValue);
-
- KX_PYMETHOD_VARARGS(KX_VehicleWrapper,ApplyEngineForce);
-
- KX_PYMETHOD_VARARGS(KX_VehicleWrapper,ApplyBraking);
-
- KX_PYMETHOD_VARARGS(KX_VehicleWrapper,SetTyreFriction);
-
- KX_PYMETHOD_VARARGS(KX_VehicleWrapper,SetSuspensionStiffness);
-
- KX_PYMETHOD_VARARGS(KX_VehicleWrapper,SetSuspensionDamping);
-
- KX_PYMETHOD_VARARGS(KX_VehicleWrapper,SetSuspensionCompression);
-
- KX_PYMETHOD_VARARGS(KX_VehicleWrapper,SetRollInfluence);
-#endif /* WITH_PYTHON */
-
-private:
- PHY_IVehicle* m_vehicle;
- PHY_IPhysicsEnvironment* m_physenv;
-};
-
-#endif /* __KX_VEHICLEWRAPPER_H__ */
diff --git a/source/gameengine/Ketsji/KX_VertexProxy.cpp b/source/gameengine/Ketsji/KX_VertexProxy.cpp
deleted file mode 100644
index 40f4c462801..00000000000
--- a/source/gameengine/Ketsji/KX_VertexProxy.cpp
+++ /dev/null
@@ -1,595 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Ketsji/KX_VertexProxy.cpp
- * \ingroup ketsji
- */
-
-
-#ifdef WITH_PYTHON
-
-#include "KX_VertexProxy.h"
-#include "KX_MeshProxy.h"
-#include "RAS_TexVert.h"
-
-#include "KX_PyMath.h"
-
-PyTypeObject KX_VertexProxy::Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "KX_VertexProxy",
- sizeof(PyObjectPlus_Proxy),
- 0,
- py_base_dealloc,
- 0,
- 0,
- 0,
- 0,
- py_base_repr,
- 0,0,0,0,0,0,0,0,0,
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
- 0,0,0,0,0,0,0,
- Methods,
- 0,
- 0,
- &CValue::Type,
- 0,0,0,0,0,0,
- py_base_new
-};
-
-PyMethodDef KX_VertexProxy::Methods[] = {
- {"getXYZ", (PyCFunction)KX_VertexProxy::sPyGetXYZ,METH_NOARGS},
- {"setXYZ", (PyCFunction)KX_VertexProxy::sPySetXYZ,METH_O},
- {"getUV", (PyCFunction)KX_VertexProxy::sPyGetUV1, METH_NOARGS},
- {"setUV", (PyCFunction)KX_VertexProxy::sPySetUV1, METH_O},
-
- {"getUV2", (PyCFunction)KX_VertexProxy::sPyGetUV2,METH_NOARGS},
- {"setUV2", (PyCFunction)KX_VertexProxy::sPySetUV2,METH_VARARGS},
-
- {"getRGBA", (PyCFunction)KX_VertexProxy::sPyGetRGBA,METH_NOARGS},
- {"setRGBA", (PyCFunction)KX_VertexProxy::sPySetRGBA,METH_O},
- {"getNormal", (PyCFunction)KX_VertexProxy::sPyGetNormal,METH_NOARGS},
- {"setNormal", (PyCFunction)KX_VertexProxy::sPySetNormal,METH_O},
- {NULL,NULL} //Sentinel
-};
-
-PyAttributeDef KX_VertexProxy::Attributes[] = {
- KX_PYATTRIBUTE_RW_FUNCTION("x", KX_VertexProxy, pyattr_get_x, pyattr_set_x),
- KX_PYATTRIBUTE_RW_FUNCTION("y", KX_VertexProxy, pyattr_get_y, pyattr_set_y),
- KX_PYATTRIBUTE_RW_FUNCTION("z", KX_VertexProxy, pyattr_get_z, pyattr_set_z),
-
- KX_PYATTRIBUTE_RW_FUNCTION("r", KX_VertexProxy, pyattr_get_r, pyattr_set_r),
- KX_PYATTRIBUTE_RW_FUNCTION("g", KX_VertexProxy, pyattr_get_g, pyattr_set_g),
- KX_PYATTRIBUTE_RW_FUNCTION("b", KX_VertexProxy, pyattr_get_b, pyattr_set_b),
- KX_PYATTRIBUTE_RW_FUNCTION("a", KX_VertexProxy, pyattr_get_a, pyattr_set_a),
-
- KX_PYATTRIBUTE_RW_FUNCTION("u", KX_VertexProxy, pyattr_get_u, pyattr_set_u),
- KX_PYATTRIBUTE_RW_FUNCTION("v", KX_VertexProxy, pyattr_get_v, pyattr_set_v),
-
- KX_PYATTRIBUTE_RW_FUNCTION("u2", KX_VertexProxy, pyattr_get_u2, pyattr_set_u2),
- KX_PYATTRIBUTE_RW_FUNCTION("v2", KX_VertexProxy, pyattr_get_v2, pyattr_set_v2),
-
- KX_PYATTRIBUTE_RW_FUNCTION("XYZ", KX_VertexProxy, pyattr_get_XYZ, pyattr_set_XYZ),
- KX_PYATTRIBUTE_RW_FUNCTION("UV", KX_VertexProxy, pyattr_get_UV, pyattr_set_UV),
- KX_PYATTRIBUTE_RW_FUNCTION("uvs", KX_VertexProxy, pyattr_get_uvs, pyattr_set_uvs),
-
- KX_PYATTRIBUTE_RW_FUNCTION("color", KX_VertexProxy, pyattr_get_color, pyattr_set_color),
- KX_PYATTRIBUTE_RW_FUNCTION("normal", KX_VertexProxy, pyattr_get_normal, pyattr_set_normal),
-
- { NULL } //Sentinel
-};
-
-PyObject *KX_VertexProxy::pyattr_get_x(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_VertexProxy* self = static_cast<KX_VertexProxy*>(self_v);
- return PyFloat_FromDouble(self->m_vertex->getXYZ()[0]);
-}
-
-PyObject *KX_VertexProxy::pyattr_get_y(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_VertexProxy* self = static_cast<KX_VertexProxy*>(self_v);
- return PyFloat_FromDouble(self->m_vertex->getXYZ()[1]);
-}
-
-PyObject *KX_VertexProxy::pyattr_get_z(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_VertexProxy* self = static_cast<KX_VertexProxy*>(self_v);
- return PyFloat_FromDouble(self->m_vertex->getXYZ()[2]);
-}
-
-PyObject *KX_VertexProxy::pyattr_get_r(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_VertexProxy* self = static_cast<KX_VertexProxy*>(self_v);
- return PyFloat_FromDouble(self->m_vertex->getRGBA()[0]/255.0);
-}
-
-PyObject *KX_VertexProxy::pyattr_get_g(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_VertexProxy* self = static_cast<KX_VertexProxy*>(self_v);
- return PyFloat_FromDouble(self->m_vertex->getRGBA()[1]/255.0);
-}
-
-PyObject *KX_VertexProxy::pyattr_get_b(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_VertexProxy* self = static_cast<KX_VertexProxy*>(self_v);
- return PyFloat_FromDouble(self->m_vertex->getRGBA()[2]/255.0);
-}
-
-PyObject *KX_VertexProxy::pyattr_get_a(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_VertexProxy* self = static_cast<KX_VertexProxy*>(self_v);
- return PyFloat_FromDouble(self->m_vertex->getRGBA()[3]/255.0);
-}
-
-PyObject *KX_VertexProxy::pyattr_get_u(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_VertexProxy* self = static_cast<KX_VertexProxy*>(self_v);
- return PyFloat_FromDouble(self->m_vertex->getUV(0)[0]);
-}
-
-PyObject *KX_VertexProxy::pyattr_get_v(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_VertexProxy* self = static_cast<KX_VertexProxy*>(self_v);
- return PyFloat_FromDouble(self->m_vertex->getUV(0)[1]);
-}
-
-PyObject *KX_VertexProxy::pyattr_get_u2(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_VertexProxy* self = static_cast<KX_VertexProxy*>(self_v);
- return PyFloat_FromDouble(self->m_vertex->getUV(1)[0]);
-}
-
-PyObject *KX_VertexProxy::pyattr_get_v2(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_VertexProxy* self = static_cast<KX_VertexProxy*>(self_v);
- return PyFloat_FromDouble(self->m_vertex->getUV(1)[1]);
-}
-
-PyObject *KX_VertexProxy::pyattr_get_XYZ(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_VertexProxy* self = static_cast<KX_VertexProxy*>(self_v);
- return PyObjectFrom(MT_Vector3(self->m_vertex->getXYZ()));
-}
-
-PyObject *KX_VertexProxy::pyattr_get_UV(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_VertexProxy* self = static_cast<KX_VertexProxy*>(self_v);
- return PyObjectFrom(MT_Point2(self->m_vertex->getUV(0)));
-}
-
-PyObject *KX_VertexProxy::pyattr_get_uvs(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_VertexProxy* self= static_cast<KX_VertexProxy*>(self_v);
-
- PyObject* uvlist = PyList_New(RAS_TexVert::MAX_UNIT);
- for (int i=0; i<RAS_TexVert::MAX_UNIT; ++i)
- {
- PyList_SET_ITEM(uvlist, i, PyObjectFrom(MT_Point2(self->m_vertex->getUV(i))));
- }
-
- return uvlist;
-}
-
-PyObject *KX_VertexProxy::pyattr_get_color(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_VertexProxy* self = static_cast<KX_VertexProxy*>(self_v);
- const unsigned char *colp = self->m_vertex->getRGBA();
- MT_Vector4 color(colp[0], colp[1], colp[2], colp[3]);
- color /= 255.0f;
- return PyObjectFrom(color);
-}
-
-PyObject *KX_VertexProxy::pyattr_get_normal(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- KX_VertexProxy* self = static_cast<KX_VertexProxy*>(self_v);
- return PyObjectFrom(MT_Vector3(self->m_vertex->getNormal()));
-}
-
-int KX_VertexProxy::pyattr_set_x(void *self_v, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_VertexProxy* self = static_cast<KX_VertexProxy*>(self_v);
- if (PyFloat_Check(value))
- {
- float val = PyFloat_AsDouble(value);
- MT_Point3 pos(self->m_vertex->getXYZ());
- pos.x() = val;
- self->m_vertex->SetXYZ(pos);
- self->m_mesh->SetMeshModified(true);
- return PY_SET_ATTR_SUCCESS;
- }
- return PY_SET_ATTR_FAIL;
-}
-
-int KX_VertexProxy::pyattr_set_y(void *self_v, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_VertexProxy* self = static_cast<KX_VertexProxy*>(self_v);
- if (PyFloat_Check(value))
- {
- float val = PyFloat_AsDouble(value);
- MT_Point3 pos(self->m_vertex->getXYZ());
- pos.y() = val;
- self->m_vertex->SetXYZ(pos);
- self->m_mesh->SetMeshModified(true);
- return PY_SET_ATTR_SUCCESS;
- }
- return PY_SET_ATTR_FAIL;
-}
-
-int KX_VertexProxy::pyattr_set_z(void *self_v, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_VertexProxy* self = static_cast<KX_VertexProxy*>(self_v);
- if (PyFloat_Check(value))
- {
- float val = PyFloat_AsDouble(value);
- MT_Point3 pos(self->m_vertex->getXYZ());
- pos.z() = val;
- self->m_vertex->SetXYZ(pos);
- self->m_mesh->SetMeshModified(true);
- return PY_SET_ATTR_SUCCESS;
- }
- return PY_SET_ATTR_FAIL;
-}
-
-int KX_VertexProxy::pyattr_set_u(void *self_v, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_VertexProxy* self = static_cast<KX_VertexProxy*>(self_v);
- if (PyFloat_Check(value))
- {
- float val = PyFloat_AsDouble(value);
- MT_Point2 uv = self->m_vertex->getUV(0);
- uv[0] = val;
- self->m_vertex->SetUV(0, uv);
- self->m_mesh->SetMeshModified(true);
- return PY_SET_ATTR_SUCCESS;
- }
- return PY_SET_ATTR_FAIL;
-}
-
-int KX_VertexProxy::pyattr_set_v(void *self_v, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_VertexProxy* self = static_cast<KX_VertexProxy*>(self_v);
- if (PyFloat_Check(value))
- {
- float val = PyFloat_AsDouble(value);
- MT_Point2 uv = self->m_vertex->getUV(0);
- uv[1] = val;
- self->m_vertex->SetUV(0, uv);
- self->m_mesh->SetMeshModified(true);
- return PY_SET_ATTR_SUCCESS;
- }
- return PY_SET_ATTR_FAIL;
-}
-
-int KX_VertexProxy::pyattr_set_u2(void *self_v, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_VertexProxy* self = static_cast<KX_VertexProxy*>(self_v);
- if (PyFloat_Check(value))
- {
- float val = PyFloat_AsDouble(value);
- MT_Point2 uv = self->m_vertex->getUV(1);
- uv[0] = val;
- self->m_vertex->SetUV(1, uv);
- self->m_mesh->SetMeshModified(true);
- return PY_SET_ATTR_SUCCESS;
- }
- return PY_SET_ATTR_FAIL;
-}
-
-int KX_VertexProxy::pyattr_set_v2(void *self_v, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_VertexProxy* self = static_cast<KX_VertexProxy*>(self_v);
- if (PyFloat_Check(value))
- {
- float val = PyFloat_AsDouble(value);
- MT_Point2 uv = self->m_vertex->getUV(1);
- uv[1] = val;
- self->m_vertex->SetUV(1, uv);
- self->m_mesh->SetMeshModified(true);
- return PY_SET_ATTR_SUCCESS;
- }
- return PY_SET_ATTR_FAIL;
-}
-
-int KX_VertexProxy::pyattr_set_r(void *self_v, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_VertexProxy* self = static_cast<KX_VertexProxy*>(self_v);
- if (PyFloat_Check(value))
- {
- float val = PyFloat_AsDouble(value);
- unsigned int icol = *((const unsigned int *)self->m_vertex->getRGBA());
- unsigned char *cp = (unsigned char*) &icol;
- val *= 255.0f;
- cp[0] = (unsigned char) val;
- self->m_vertex->SetRGBA(icol);
- self->m_mesh->SetMeshModified(true);
- return PY_SET_ATTR_SUCCESS;
- }
- return PY_SET_ATTR_FAIL;
-}
-
-int KX_VertexProxy::pyattr_set_g(void *self_v, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_VertexProxy* self = static_cast<KX_VertexProxy*>(self_v);
- if (PyFloat_Check(value))
- {
- float val = PyFloat_AsDouble(value);
- unsigned int icol = *((const unsigned int *)self->m_vertex->getRGBA());
- unsigned char *cp = (unsigned char*) &icol;
- val *= 255.0f;
- cp[1] = (unsigned char) val;
- self->m_vertex->SetRGBA(icol);
- self->m_mesh->SetMeshModified(true);
- return PY_SET_ATTR_SUCCESS;
- }
- return PY_SET_ATTR_FAIL;
-}
-
-int KX_VertexProxy::pyattr_set_b(void *self_v, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_VertexProxy* self = static_cast<KX_VertexProxy*>(self_v);
- if (PyFloat_Check(value))
- {
- float val = PyFloat_AsDouble(value);
- unsigned int icol = *((const unsigned int *)self->m_vertex->getRGBA());
- unsigned char *cp = (unsigned char*) &icol;
- val *= 255.0f;
- cp[2] = (unsigned char) val;
- self->m_vertex->SetRGBA(icol);
- self->m_mesh->SetMeshModified(true);
- return PY_SET_ATTR_SUCCESS;
- }
- return PY_SET_ATTR_FAIL;
-}
-
-int KX_VertexProxy::pyattr_set_a(void *self_v, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_VertexProxy* self = static_cast<KX_VertexProxy*>(self_v);
- if (PyFloat_Check(value))
- {
- float val = PyFloat_AsDouble(value);
- unsigned int icol = *((const unsigned int *)self->m_vertex->getRGBA());
- unsigned char *cp = (unsigned char*) &icol;
- val *= 255.0f;
- cp[3] = (unsigned char) val;
- self->m_vertex->SetRGBA(icol);
- self->m_mesh->SetMeshModified(true);
- return PY_SET_ATTR_SUCCESS;
- }
- return PY_SET_ATTR_FAIL;
-}
-
-int KX_VertexProxy::pyattr_set_XYZ(void *self_v, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_VertexProxy* self = static_cast<KX_VertexProxy*>(self_v);
- if (PySequence_Check(value))
- {
- MT_Point3 vec;
- if (PyVecTo(value, vec))
- {
- self->m_vertex->SetXYZ(vec);
- self->m_mesh->SetMeshModified(true);
- return PY_SET_ATTR_SUCCESS;
- }
- }
- return PY_SET_ATTR_FAIL;
-}
-
-int KX_VertexProxy::pyattr_set_UV(void *self_v, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_VertexProxy* self = static_cast<KX_VertexProxy*>(self_v);
- if (PySequence_Check(value))
- {
- MT_Point2 vec;
- if (PyVecTo(value, vec)) {
- self->m_vertex->SetUV(0, vec);
- self->m_mesh->SetMeshModified(true);
- return PY_SET_ATTR_SUCCESS;
- }
- }
- return PY_SET_ATTR_FAIL;
-}
-
-int KX_VertexProxy::pyattr_set_uvs(void *self_v, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_VertexProxy* self= static_cast<KX_VertexProxy*>(self_v);
- if (PySequence_Check(value))
- {
- MT_Point2 vec;
- for (int i=0; i<PySequence_Size(value) && i<RAS_TexVert::MAX_UNIT; ++i)
- {
- if (PyVecTo(PySequence_GetItem(value, i), vec))
- {
- self->m_vertex->SetUV(i, vec);
- self->m_mesh->SetMeshModified(true);
- }
- else
- {
- PyErr_SetString(PyExc_AttributeError, STR_String().Format("list[%d] was not a vector", i).ReadPtr());
- return PY_SET_ATTR_FAIL;
- }
- }
-
- self->m_mesh->SetMeshModified(true);
- return PY_SET_ATTR_SUCCESS;
- }
- return PY_SET_ATTR_FAIL;
-}
-
-int KX_VertexProxy::pyattr_set_color(void *self_v, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_VertexProxy* self = static_cast<KX_VertexProxy*>(self_v);
- if (PySequence_Check(value))
- {
- MT_Vector4 vec;
- if (PyVecTo(value, vec))
- {
- self->m_vertex->SetRGBA(vec);
- self->m_mesh->SetMeshModified(true);
- return PY_SET_ATTR_SUCCESS;
- }
- }
- return PY_SET_ATTR_FAIL;
-}
-
-int KX_VertexProxy::pyattr_set_normal(void *self_v, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_VertexProxy* self = static_cast<KX_VertexProxy*>(self_v);
- if (PySequence_Check(value))
- {
- MT_Vector3 vec;
- if (PyVecTo(value, vec))
- {
- self->m_vertex->SetNormal(vec);
- self->m_mesh->SetMeshModified(true);
- return PY_SET_ATTR_SUCCESS;
- }
- }
- return PY_SET_ATTR_FAIL;
-}
-
-KX_VertexProxy::KX_VertexProxy(KX_MeshProxy*mesh, RAS_TexVert* vertex)
-: m_vertex(vertex),
- m_mesh(mesh)
-{
- /* see bug [#27071] */
- Py_INCREF(m_mesh->GetProxy());
-}
-
-KX_VertexProxy::~KX_VertexProxy()
-{
- /* see bug [#27071] */
- Py_DECREF(m_mesh->GetProxy());
-}
-
-
-
-// stuff for cvalue related things
-CValue* KX_VertexProxy::Calc(VALUE_OPERATOR, CValue *) { return NULL;}
-CValue* KX_VertexProxy::CalcFinal(VALUE_DATA_TYPE, VALUE_OPERATOR, CValue *) { return NULL;}
-static STR_String sVertexName = "vertex";
-const STR_String & KX_VertexProxy::GetText() {return sVertexName;};
-double KX_VertexProxy::GetNumber() { return -1;}
-STR_String& KX_VertexProxy::GetName() { return sVertexName;}
-void KX_VertexProxy::SetName(const char *) { };
-CValue* KX_VertexProxy::GetReplica() { return NULL;}
-
-// stuff for python integration
-
-PyObject *KX_VertexProxy::PyGetXYZ()
-{
- return PyObjectFrom(MT_Point3(m_vertex->getXYZ()));
-}
-
-PyObject *KX_VertexProxy::PySetXYZ(PyObject *value)
-{
- MT_Point3 vec;
- if (!PyVecTo(value, vec))
- return NULL;
-
- m_vertex->SetXYZ(vec);
- m_mesh->SetMeshModified(true);
- Py_RETURN_NONE;
-}
-
-PyObject *KX_VertexProxy::PyGetNormal()
-{
- return PyObjectFrom(MT_Vector3(m_vertex->getNormal()));
-}
-
-PyObject *KX_VertexProxy::PySetNormal(PyObject *value)
-{
- MT_Vector3 vec;
- if (!PyVecTo(value, vec))
- return NULL;
-
- m_vertex->SetNormal(vec);
- m_mesh->SetMeshModified(true);
- Py_RETURN_NONE;
-}
-
-
-PyObject *KX_VertexProxy::PyGetRGBA()
-{
- int *rgba = (int *) m_vertex->getRGBA();
- return PyLong_FromLong(*rgba);
-}
-
-PyObject *KX_VertexProxy::PySetRGBA(PyObject *value)
-{
- if (PyLong_Check(value)) {
- int rgba = PyLong_AsLong(value);
- m_vertex->SetRGBA(rgba);
- m_mesh->SetMeshModified(true);
- Py_RETURN_NONE;
- }
- else {
- MT_Vector4 vec;
- if (PyVecTo(value, vec))
- {
- m_vertex->SetRGBA(vec);
- m_mesh->SetMeshModified(true);
- Py_RETURN_NONE;
- }
- }
-
- PyErr_SetString(PyExc_TypeError, "vert.setRGBA(value): KX_VertexProxy, expected a 4D vector or an int");
- return NULL;
-}
-
-
-PyObject *KX_VertexProxy::PyGetUV1()
-{
- return PyObjectFrom(MT_Vector2(m_vertex->getUV(0)));
-}
-
-PyObject *KX_VertexProxy::PySetUV1(PyObject *value)
-{
- MT_Point2 vec;
- if (!PyVecTo(value, vec))
- return NULL;
-
- m_vertex->SetUV(0, vec);
- m_mesh->SetMeshModified(true);
- Py_RETURN_NONE;
-}
-
-PyObject *KX_VertexProxy::PyGetUV2()
-{
- return PyObjectFrom(MT_Vector2(m_vertex->getUV(1)));
-}
-
-PyObject *KX_VertexProxy::PySetUV2(PyObject *args)
-{
- MT_Point2 vec;
- if (!PyVecTo(args, vec))
- return NULL;
-
- m_vertex->SetUV(1, vec);
- m_mesh->SetMeshModified(true);
- Py_RETURN_NONE;
-}
-
-#endif // WITH_PYTHON
diff --git a/source/gameengine/Ketsji/KX_VertexProxy.h b/source/gameengine/Ketsji/KX_VertexProxy.h
deleted file mode 100644
index 8070825ad11..00000000000
--- a/source/gameengine/Ketsji/KX_VertexProxy.h
+++ /dev/null
@@ -1,112 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file KX_VertexProxy.h
- * \ingroup ketsji
- */
-
-#ifndef __KX_VERTEXPROXY_H__
-#define __KX_VERTEXPROXY_H__
-
-#ifdef WITH_PYTHON
-
-#include "SCA_IObject.h"
-
-class KX_VertexProxy : public CValue
-{
- Py_Header
-protected:
-
- class RAS_TexVert* m_vertex;
- class KX_MeshProxy* m_mesh;
-public:
- KX_VertexProxy(class KX_MeshProxy*mesh, class RAS_TexVert* vertex);
- virtual ~KX_VertexProxy();
-
- // stuff for cvalue related things
- CValue* Calc(VALUE_OPERATOR op, CValue *val);
- CValue* CalcFinal(VALUE_DATA_TYPE dtype, VALUE_OPERATOR op, CValue *val);
- const STR_String & GetText();
- double GetNumber();
- STR_String& GetName();
- void SetName(const char *name); // Set the name of the value
- CValue* GetReplica();
-
-
-// stuff for python integration
-
- static PyObject *pyattr_get_x(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject *pyattr_get_y(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject *pyattr_get_z(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject *pyattr_get_r(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject *pyattr_get_g(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject *pyattr_get_b(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject *pyattr_get_a(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject *pyattr_get_u(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject *pyattr_get_v(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject *pyattr_get_u2(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject *pyattr_get_v2(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject *pyattr_get_XYZ(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject *pyattr_get_UV(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject *pyattr_get_color(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject *pyattr_get_normal(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject *pyattr_get_uvs(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_x(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static int pyattr_set_y(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static int pyattr_set_z(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static int pyattr_set_u(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static int pyattr_set_v(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static int pyattr_set_u2(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static int pyattr_set_v2(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static int pyattr_set_r(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static int pyattr_set_g(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static int pyattr_set_b(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static int pyattr_set_a(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static int pyattr_set_XYZ(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static int pyattr_set_UV(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static int pyattr_set_color(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static int pyattr_set_normal(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static int pyattr_set_uvs(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
-
- KX_PYMETHOD_NOARGS(KX_VertexProxy,GetXYZ);
- KX_PYMETHOD_O(KX_VertexProxy,SetXYZ);
- KX_PYMETHOD_NOARGS(KX_VertexProxy,GetUV1);
- KX_PYMETHOD_O(KX_VertexProxy,SetUV1);
-
- KX_PYMETHOD_NOARGS(KX_VertexProxy,GetUV2);
- KX_PYMETHOD_VARARGS(KX_VertexProxy,SetUV2);
-
- KX_PYMETHOD_NOARGS(KX_VertexProxy,GetRGBA);
- KX_PYMETHOD_O(KX_VertexProxy,SetRGBA);
- KX_PYMETHOD_NOARGS(KX_VertexProxy,GetNormal);
- KX_PYMETHOD_O(KX_VertexProxy,SetNormal);
-
-};
-
-#endif /* WITH_PYTHON */
-
-#endif /* __KX_VERTEXPROXY_H__ */
diff --git a/source/gameengine/Ketsji/KX_VisibilityActuator.cpp b/source/gameengine/Ketsji/KX_VisibilityActuator.cpp
deleted file mode 100644
index 6f689e228b9..00000000000
--- a/source/gameengine/Ketsji/KX_VisibilityActuator.cpp
+++ /dev/null
@@ -1,127 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- * Actuator to toggle visibility/invisibility of objects
- */
-
-/** \file gameengine/Ketsji/KX_VisibilityActuator.cpp
- * \ingroup ketsji
- */
-
-
-#include "KX_VisibilityActuator.h"
-#include "KX_GameObject.h"
-
-KX_VisibilityActuator::KX_VisibilityActuator(
- SCA_IObject* gameobj,
- bool visible,
- bool occlusion,
- bool recursive
- )
- : SCA_IActuator(gameobj, KX_ACT_VISIBILITY),
- m_visible(visible),
- m_occlusion(occlusion),
- m_recursive(recursive)
-{
- // intentionally empty
-}
-
-KX_VisibilityActuator::~KX_VisibilityActuator(
- void
- )
-{
- // intentionally empty
-}
-
-CValue*
-KX_VisibilityActuator::GetReplica(
- void
- )
-{
- KX_VisibilityActuator* replica = new KX_VisibilityActuator(*this);
- replica->ProcessReplica();
- return replica;
-}
-
-bool
-KX_VisibilityActuator::Update()
-{
- bool bNegativeEvent = IsNegativeEvent();
-
- RemoveAllEvents();
- if (bNegativeEvent) return false;
-
- KX_GameObject *obj = (KX_GameObject*) GetParent();
-
- obj->SetVisible(m_visible, m_recursive);
- obj->SetOccluder(m_occlusion, m_recursive);
- obj->UpdateBuckets(m_recursive);
-
- return false;
-}
-
-#ifdef WITH_PYTHON
-
-/* ------------------------------------------------------------------------- */
-/* Python functions */
-/* ------------------------------------------------------------------------- */
-
-
-
-/* Integration hooks ------------------------------------------------------- */
-PyTypeObject KX_VisibilityActuator::Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "KX_VisibilityActuator",
- sizeof(PyObjectPlus_Proxy),
- 0,
- py_base_dealloc,
- 0,
- 0,
- 0,
- 0,
- py_base_repr,
- 0,0,0,0,0,0,0,0,0,
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
- 0,0,0,0,0,0,0,
- Methods,
- 0,
- 0,
- &SCA_IActuator::Type,
- 0,0,0,0,0,0,
- py_base_new
-};
-
-PyMethodDef KX_VisibilityActuator::Methods[] = {
- {NULL,NULL} //Sentinel
-};
-
-PyAttributeDef KX_VisibilityActuator::Attributes[] = {
- KX_PYATTRIBUTE_BOOL_RW("visibility", KX_VisibilityActuator, m_visible),
- KX_PYATTRIBUTE_BOOL_RW("useOcclusion", KX_VisibilityActuator, m_occlusion),
- KX_PYATTRIBUTE_BOOL_RW("useRecursion", KX_VisibilityActuator, m_recursive),
- { NULL } //Sentinel
-};
-
-#endif // WITH_PYTHON
diff --git a/source/gameengine/Ketsji/KX_VisibilityActuator.h b/source/gameengine/Ketsji/KX_VisibilityActuator.h
deleted file mode 100644
index a207844db74..00000000000
--- a/source/gameengine/Ketsji/KX_VisibilityActuator.h
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file KX_VisibilityActuator.h
- * \ingroup ketsji
- * \brief Actuator to toggle visibility/invisibility of objects
- */
-
-#ifndef __KX_VISIBILITYACTUATOR_H__
-#define __KX_VISIBILITYACTUATOR_H__
-
-#include "SCA_IActuator.h"
-
-class KX_VisibilityActuator : public SCA_IActuator
-{
- Py_Header
-
- /** Make visible? */
- bool m_visible;
- bool m_occlusion;
- bool m_recursive;
-
- public:
-
- KX_VisibilityActuator(
- SCA_IObject* gameobj,
- bool visible,
- bool occlusion,
- bool recursive);
-
- virtual
- ~KX_VisibilityActuator(
- void
- );
-
- virtual CValue*
- GetReplica(
- void
- );
-
- virtual bool
- Update();
-
- /* --------------------------------------------------------------------- */
- /* Python interface ---------------------------------------------------- */
- /* --------------------------------------------------------------------- */
-
-};
-
-#endif
-
diff --git a/source/gameengine/Ketsji/KX_WorldInfo.cpp b/source/gameengine/Ketsji/KX_WorldInfo.cpp
deleted file mode 100644
index be8b1ce92fc..00000000000
--- a/source/gameengine/Ketsji/KX_WorldInfo.cpp
+++ /dev/null
@@ -1,494 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Ketsji/KX_WorldInfo.cpp
- * \ingroup ketsji
- */
-
-
-#include "KX_WorldInfo.h"
-#include "KX_PythonInit.h"
-#include "KX_PyMath.h"
-#include "RAS_IRasterizer.h"
-#include "GPU_material.h"
-
-/* This little block needed for linking to Blender... */
-#ifdef WIN32
-#include "BLI_winstuff.h"
-#endif
-
-/* This list includes only data type definitions */
-#include "DNA_scene_types.h"
-#include "DNA_world_types.h"
-
-#include "BLI_math.h"
-
-#include "BKE_global.h"
-#include "BKE_scene.h"
-/* end of blender include block */
-
-
-KX_WorldInfo::KX_WorldInfo(Scene *blenderscene, World *blenderworld)
-{
- if (blenderworld) {
- m_name = blenderworld->id.name + 2;
- m_do_color_management = BKE_scene_check_color_management_enabled(blenderscene);
- m_hasworld = true;
- m_hasmist = ((blenderworld->mode) & WO_MIST ? true : false);
- m_misttype = blenderworld->mistype;
- m_miststart = blenderworld->miststa;
- m_mistdistance = blenderworld->mistdist;
- m_mistintensity = blenderworld->misi;
- setMistColor(blenderworld->horr, blenderworld->horg, blenderworld->horb);
- setBackColor(blenderworld->horr, blenderworld->horg, blenderworld->horb);
- setAmbientColor(blenderworld->ambr, blenderworld->ambg, blenderworld->ambb);
- }
- else {
- m_hasworld = false;
- }
-}
-
-KX_WorldInfo::~KX_WorldInfo()
-{
-}
-
-const STR_String& KX_WorldInfo::GetName()
-{
- return m_name;
-}
-
-bool KX_WorldInfo::hasWorld()
-{
- return m_hasworld;
-}
-
-void KX_WorldInfo::setBackColor(float r, float g, float b)
-{
- m_backgroundcolor[0] = r;
- m_backgroundcolor[1] = g;
- m_backgroundcolor[2] = b;
-
- if (m_do_color_management) {
- linearrgb_to_srgb_v3_v3(m_con_backgroundcolor, m_backgroundcolor);
- }
- else {
- copy_v3_v3(m_con_backgroundcolor, m_backgroundcolor);
- }
-}
-
-const float *KX_WorldInfo::getBackColorConverted() const
-{
- return m_con_backgroundcolor;
-}
-
-void KX_WorldInfo::setMistType(short type)
-{
- m_misttype = type;
-}
-
-void KX_WorldInfo::setUseMist(bool enable)
-{
- m_hasmist = enable;
-}
-
-void KX_WorldInfo::setMistStart(float d)
-{
- m_miststart = d;
-}
-
-void KX_WorldInfo::setMistDistance(float d)
-{
- m_mistdistance = d;
-}
-
-void KX_WorldInfo::setMistIntensity(float intensity)
-{
- m_mistintensity = intensity;
-}
-void KX_WorldInfo::setMistColor(float r, float g, float b)
-{
- m_mistcolor[0] = r;
- m_mistcolor[1] = g;
- m_mistcolor[2] = b;
-
- if (m_do_color_management) {
- linearrgb_to_srgb_v3_v3(m_con_mistcolor, m_mistcolor);
- }
- else {
- copy_v3_v3(m_con_mistcolor, m_mistcolor);
- }
-}
-
-void KX_WorldInfo::setAmbientColor(float r, float g, float b)
-{
- m_ambientcolor[0] = r;
- m_ambientcolor[1] = g;
- m_ambientcolor[2] = b;
-
- if (m_do_color_management) {
- linearrgb_to_srgb_v3_v3(m_con_ambientcolor, m_ambientcolor);
- }
- else {
- copy_v3_v3(m_con_ambientcolor, m_ambientcolor);
- }
-}
-
-void KX_WorldInfo::UpdateBackGround()
-{
- if (m_hasworld) {
- RAS_IRasterizer *m_rasterizer = KX_GetActiveEngine()->GetRasterizer();
-
- if (m_rasterizer->GetDrawingMode() >= RAS_IRasterizer::KX_SOLID) {
- m_rasterizer->SetBackColor(m_con_backgroundcolor);
- GPU_horizon_update_color(m_backgroundcolor);
- }
- }
-}
-
-void KX_WorldInfo::UpdateWorldSettings()
-{
- if (m_hasworld) {
- RAS_IRasterizer *m_rasterizer = KX_GetActiveEngine()->GetRasterizer();
-
- if (m_rasterizer->GetDrawingMode() >= RAS_IRasterizer::KX_SOLID) {
- m_rasterizer->SetAmbientColor(m_con_ambientcolor);
- GPU_ambient_update_color(m_ambientcolor);
-
- if (m_hasmist) {
- m_rasterizer->SetFog(m_misttype, m_miststart, m_mistdistance, m_mistintensity, m_con_mistcolor);
- GPU_mist_update_values(m_misttype, m_miststart, m_mistdistance, m_mistintensity, m_mistcolor);
- m_rasterizer->EnableFog(true);
- GPU_mist_update_enable(true);
- }
- else {
- m_rasterizer->EnableFog(false);
- GPU_mist_update_enable(false);
- }
- }
- }
-}
-
-#ifdef WITH_PYTHON
-
-/* -------------------------------------------------------------------------
- * Python functions
- * ------------------------------------------------------------------------- */
-PyObject *KX_WorldInfo::py_repr(void)
-{
- return PyUnicode_From_STR_String(GetName());
-}
-
-/* -------------------------------------------------------------------------
- * Python Integration Hooks
- * ------------------------------------------------------------------------- */
-PyTypeObject KX_WorldInfo::Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "KX_WorldInfo",
- sizeof(PyObjectPlus_Proxy),
- 0,
- py_base_dealloc,
- 0,
- 0,
- 0,
- 0,
- py_base_repr,
- 0,0,0,0,0,0,0,0,0,
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
- 0,0,0,0,0,0,0,
- Methods,
- 0,
- 0,
- &PyObjectPlus::Type,
- 0,0,0,0,0,0,
- py_base_new
-};
-
-PyMethodDef KX_WorldInfo::Methods[] = {
- {NULL,NULL} /* Sentinel */
-};
-
-PyAttributeDef KX_WorldInfo::Attributes[] = {
- KX_PYATTRIBUTE_BOOL_RW("mistEnable", KX_WorldInfo, m_hasmist),
- KX_PYATTRIBUTE_FLOAT_RW("mistStart", 0.0f, 10000.0f, KX_WorldInfo, m_miststart),
- KX_PYATTRIBUTE_FLOAT_RW("mistDistance", 0.001f, 10000.0f, KX_WorldInfo, m_mistdistance),
- KX_PYATTRIBUTE_FLOAT_RW("mistIntensity", 0.0f, 1.0f, KX_WorldInfo, m_mistintensity),
- KX_PYATTRIBUTE_SHORT_RW("mistType", 0, 2, true, KX_WorldInfo, m_misttype),
- KX_PYATTRIBUTE_RO_FUNCTION("KX_MIST_QUADRATIC", KX_WorldInfo, pyattr_get_mist_typeconst),
- KX_PYATTRIBUTE_RO_FUNCTION("KX_MIST_LINEAR", KX_WorldInfo, pyattr_get_mist_typeconst),
- KX_PYATTRIBUTE_RO_FUNCTION("KX_MIST_INV_QUADRATIC", KX_WorldInfo, pyattr_get_mist_typeconst),
- KX_PYATTRIBUTE_RW_FUNCTION("mistColor", KX_WorldInfo, pyattr_get_mist_color, pyattr_set_mist_color),
- KX_PYATTRIBUTE_RW_FUNCTION("backgroundColor", KX_WorldInfo, pyattr_get_back_color, pyattr_set_back_color),
- KX_PYATTRIBUTE_RW_FUNCTION("ambientColor", KX_WorldInfo, pyattr_get_ambient_color, pyattr_set_ambient_color),
- { NULL } /* Sentinel */
-};
-
-/* Attribute get/set functions */
-
-#ifdef USE_MATHUTILS
-
-/*----------------------mathutils callbacks ----------------------------*/
-
-/* subtype */
-#define MATHUTILS_COL_CB_MIST_COLOR 1
-#define MATHUTILS_COL_CB_BACK_COLOR 2
-#define MATHUTILS_COL_CB_AMBIENT_COLOR 3
-
-static unsigned char mathutils_world_color_cb_index = -1; /* index for our callbacks */
-
-static int mathutils_world_generic_check(BaseMathObject *bmo)
-{
- KX_WorldInfo *self = static_cast<KX_WorldInfo*>BGE_PROXY_REF(bmo->cb_user);
- if (self == NULL)
- return -1;
-
- return 0;
-}
-
-static int mathutils_world_color_get(BaseMathObject *bmo, int subtype)
-{
- KX_WorldInfo *self = static_cast<KX_WorldInfo*>BGE_PROXY_REF(bmo->cb_user);
- if (self == NULL)
- return -1;
-
- switch (subtype) {
- case MATHUTILS_COL_CB_MIST_COLOR:
- copy_v3_v3(bmo->data, self->m_mistcolor);
- break;
- case MATHUTILS_COL_CB_BACK_COLOR:
- copy_v3_v3(bmo->data, self->m_backgroundcolor);
- break;
- case MATHUTILS_COL_CB_AMBIENT_COLOR:
- copy_v3_v3(bmo->data, self->m_ambientcolor);
- break;
- default:
- return -1;
- }
- return 0;
-}
-
-static int mathutils_world_color_set(BaseMathObject *bmo, int subtype)
-{
- KX_WorldInfo *self = static_cast<KX_WorldInfo*>BGE_PROXY_REF(bmo->cb_user);
-
- if (self == NULL)
- return -1;
-
- switch (subtype) {
- case MATHUTILS_COL_CB_MIST_COLOR:
- self->setMistColor(bmo->data[0], bmo->data[1], bmo->data[2]);
- break;
- case MATHUTILS_COL_CB_BACK_COLOR:
- self->setBackColor(bmo->data[0], bmo->data[1], bmo->data[2]);
- break;
- case MATHUTILS_COL_CB_AMBIENT_COLOR:
- self->setAmbientColor(bmo->data[0], bmo->data[1], bmo->data[2]);
- break;
- default:
- return -1;
- }
- return 0;
-}
-
-static int mathutils_world_color_get_index(BaseMathObject *bmo, int subtype, int index)
-{
- KX_WorldInfo *self = static_cast<KX_WorldInfo*>BGE_PROXY_REF(bmo->cb_user);
-
- if (self == NULL)
- return -1;
-
- switch (subtype) {
- case MATHUTILS_COL_CB_MIST_COLOR:
- {
- const float *color = self->m_mistcolor;
- bmo->data[index] = color[index];
- }
- break;
- case MATHUTILS_COL_CB_BACK_COLOR:
- {
- const float *color = self->m_backgroundcolor;
- bmo->data[index] = color[index];
- }
- break;
- case MATHUTILS_COL_CB_AMBIENT_COLOR:
- {
- const float *color = self->m_ambientcolor;
- bmo->data[index] = color[index];
- }
- break;
- default:
- return -1;
- }
- return 0;
-}
-
-static int mathutils_world_color_set_index(BaseMathObject *bmo, int subtype, int index)
-{
- KX_WorldInfo *self = static_cast<KX_WorldInfo*>BGE_PROXY_REF(bmo->cb_user);
-
- if (self == NULL)
- return -1;
-
- float color[4];
- switch (subtype) {
- case MATHUTILS_COL_CB_MIST_COLOR:
- copy_v3_v3(color, self->m_mistcolor);
- color[index] = bmo->data[index];
- self->setMistColor(color[0], color[1], color[2]);
- break;
- case MATHUTILS_COL_CB_BACK_COLOR:
- copy_v3_v3(color, self->m_backgroundcolor);
- color[index] = bmo->data[index];
- self->setBackColor(color[0], color[1], color[2]);
- break;
- case MATHUTILS_COL_CB_AMBIENT_COLOR:
- copy_v3_v3(color, self->m_ambientcolor);
- color[index] = bmo->data[index];
- self->setAmbientColor(color[0], color[1], color[2]);
- break;
- default:
- return -1;
- }
- return 0;
-}
-
-static Mathutils_Callback mathutils_world_color_cb = {
- mathutils_world_generic_check,
- mathutils_world_color_get,
- mathutils_world_color_set,
- mathutils_world_color_get_index,
- mathutils_world_color_set_index
-};
-
-void KX_WorldInfo_Mathutils_Callback_Init()
-{
- // register mathutils callbacks, ok to run more than once.
- mathutils_world_color_cb_index = Mathutils_RegisterCallback(&mathutils_world_color_cb);
-}
-#endif // USE_MATHUTILS
-
-
-PyObject *KX_WorldInfo::pyattr_get_mist_typeconst(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
- PyObject *retvalue;
-
- const char* type = attrdef->m_name;
-
- if (!strcmp(type, "KX_MIST_QUADRATIC")) {
- retvalue = PyLong_FromLong(KX_MIST_QUADRATIC);
- }
- else if (!strcmp(type, "KX_MIST_LINEAR")) {
- retvalue = PyLong_FromLong(KX_MIST_LINEAR);
- }
- else if (!strcmp(type, "KX_MIST_INV_QUADRATIC")) {
- retvalue = PyLong_FromLong(KX_MIST_INV_QUADRATIC);
- }
- else {
- /* should never happen */
- PyErr_SetString(PyExc_TypeError, "invalid mist type");
- retvalue = NULL;
- }
-
- return retvalue;
-}
-
-PyObject *KX_WorldInfo::pyattr_get_mist_color(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
-#ifdef USE_MATHUTILS
- return Color_CreatePyObject_cb(
- BGE_PROXY_FROM_REF_BORROW(self_v),
- mathutils_world_color_cb_index, MATHUTILS_COL_CB_MIST_COLOR);
-#else
- KX_WorldInfo *self = static_cast<KX_WorldInfo*>(self_v);
- return PyObjectFrom(MT_Vector3(self->m_mistcolor));
-#endif
-}
-
-int KX_WorldInfo::pyattr_set_mist_color(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_WorldInfo *self = static_cast<KX_WorldInfo*>(self_v);
-
- MT_Vector3 color;
- if (PyVecTo(value, color))
- {
- self->setMistColor(color[0], color[1], color[2]);
- return PY_SET_ATTR_SUCCESS;
- }
- return PY_SET_ATTR_FAIL;
-}
-
-PyObject *KX_WorldInfo::pyattr_get_back_color(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
-
-#ifdef USE_MATHUTILS
- return Color_CreatePyObject_cb(
- BGE_PROXY_FROM_REF_BORROW(self_v),
- mathutils_world_color_cb_index, MATHUTILS_COL_CB_BACK_COLOR);
-#else
- KX_WorldInfo *self = static_cast<KX_WorldInfo*>(self_v);
- return PyObjectFrom(MT_Vector3(self->m_backgroundcolor));
-#endif
-}
-
-int KX_WorldInfo::pyattr_set_back_color(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_WorldInfo *self = static_cast<KX_WorldInfo*>(self_v);
-
- MT_Vector3 color;
- if (PyVecTo(value, color))
- {
- self->setBackColor(color[0], color[1], color[2]);
- return PY_SET_ATTR_SUCCESS;
- }
- return PY_SET_ATTR_FAIL;
-}
-
-PyObject *KX_WorldInfo::pyattr_get_ambient_color(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
-{
-#ifdef USE_MATHUTILS
- return Color_CreatePyObject_cb(
- BGE_PROXY_FROM_REF_BORROW(self_v),
- mathutils_world_color_cb_index, MATHUTILS_COL_CB_AMBIENT_COLOR);
-#else
- KX_WorldInfo *self = static_cast<KX_WorldInfo*>(self_v);
- return PyObjectFrom(MT_Vector3(self->m_ambientcolor));
-#endif
-}
-
-int KX_WorldInfo::pyattr_set_ambient_color(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
-{
- KX_WorldInfo *self = static_cast<KX_WorldInfo*>(self_v);
-
- MT_Vector3 color;
- if (PyVecTo(value, color))
- {
- self->setAmbientColor(color[0], color[1], color[2]);
- return PY_SET_ATTR_SUCCESS;
- }
- return PY_SET_ATTR_FAIL;
-}
-
-#endif /* WITH_PYTHON */
diff --git a/source/gameengine/Ketsji/KX_WorldInfo.h b/source/gameengine/Ketsji/KX_WorldInfo.h
deleted file mode 100644
index b155faf2837..00000000000
--- a/source/gameengine/Ketsji/KX_WorldInfo.h
+++ /dev/null
@@ -1,105 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file KX_WorldInfo.h
- * \ingroup ketsji
- */
-
-#ifndef __KX_WORLDINFO_H__
-#define __KX_WORLDINFO_H__
-
-#include "MT_Scalar.h"
-#include "KX_KetsjiEngine.h"
-#include "EXP_PyObjectPlus.h"
-
-#ifdef USE_MATHUTILS
-void KX_WorldInfo_Mathutils_Callback_Init(void);
-#endif
-
-struct Scene;
-struct World;
-
-class KX_WorldInfo : public PyObjectPlus
-{
- Py_Header
-
- STR_String m_name;
- bool m_do_color_management;
- bool m_hasworld;
- bool m_hasmist;
- short m_misttype;
- float m_miststart;
- float m_mistdistance;
- float m_mistintensity;
- float m_mistcolor[3];
- float m_backgroundcolor[3];
- float m_ambientcolor[3];
- float m_con_mistcolor[3];
- float m_con_backgroundcolor[3];
- float m_con_ambientcolor[3];
-
-public:
- /**
- * Mist options
- */
- enum MistType {
- KX_MIST_QUADRATIC,
- KX_MIST_LINEAR,
- KX_MIST_INV_QUADRATIC,
- };
-
- KX_WorldInfo(Scene *blenderscene, World *blenderworld);
- ~KX_WorldInfo();
-
- const STR_String &GetName();
- bool hasWorld();
- void setUseMist(bool enable);
- void setMistType(short type);
- void setMistStart(float d);
- void setMistDistance(float d);
- void setMistIntensity(float intensity);
- void setMistColor(float r, float g, float b);
- void setBackColor(float r, float g, float b);
- const float *getBackColorConverted() const;
- void setAmbientColor(float r, float g, float b);
- void UpdateBackGround();
- void UpdateWorldSettings();
-
-#ifdef WITH_PYTHON
- /* attributes */
- static PyObject *pyattr_get_mist_typeconst(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static PyObject *pyattr_get_mist_color(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_mist_color(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static PyObject *pyattr_get_back_color(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_back_color(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- static PyObject *pyattr_get_ambient_color(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef);
- static int pyattr_set_ambient_color(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value);
- virtual PyObject *py_repr(void);
-#endif
-};
-
-#endif /* __KX_WORLDINFO_H__ */
diff --git a/source/gameengine/Ketsji/KX_WorldIpoController.cpp b/source/gameengine/Ketsji/KX_WorldIpoController.cpp
deleted file mode 100644
index 1123e07ebcc..00000000000
--- a/source/gameengine/Ketsji/KX_WorldIpoController.cpp
+++ /dev/null
@@ -1,125 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Ketsji/KX_WorldIpoController.cpp
- * \ingroup ketsji
- */
-
-
-#include "KX_WorldIpoController.h"
-#include "KX_ScalarInterpolator.h"
-#include "KX_WorldInfo.h"
-#include "KX_PythonInit.h"
-#include "KX_Scene.h"
-
-#if defined(_WIN64)
-typedef unsigned __int64 uint_ptr;
-#else
-typedef unsigned long uint_ptr;
-#endif
-
-bool KX_WorldIpoController::Update(double currentTime)
-{
- if (m_modified) {
- T_InterpolatorList::iterator i;
- for (i = m_interpolators.begin(); !(i == m_interpolators.end()); ++i) {
- (*i)->Execute(m_ipotime);
- }
-
- KX_WorldInfo *world = KX_GetActiveScene()->GetWorldInfo();
-
- if (m_modify_mist_start) {
- world->setMistStart(m_mist_start);
- }
-
- if (m_modify_mist_dist) {
- world->setMistDistance(m_mist_dist);
- }
-
- if (m_modify_mist_intensity) {
- world->setMistIntensity(m_mist_intensity);
- }
-
- if (m_modify_horizon_color) {
- world->setBackColor(m_hori_rgb[0], m_hori_rgb[1], m_hori_rgb[2]);
- world->setMistColor(m_hori_rgb[0], m_hori_rgb[1], m_hori_rgb[2]);
- }
-
- if (m_modify_ambient_color) {
- world->setAmbientColor(m_ambi_rgb[0], m_ambi_rgb[1], m_ambi_rgb[2]);
- }
-
- m_modified = false;
- }
- return false;
-}
-
-
-void KX_WorldIpoController::AddInterpolator(KX_IInterpolator* interp)
-{
- this->m_interpolators.push_back(interp);
-}
-
-
-SG_Controller* KX_WorldIpoController::GetReplica(class SG_Node* destnode)
-{
- KX_WorldIpoController* iporeplica = new KX_WorldIpoController(*this);
- // clear object that ipo acts on
- iporeplica->ClearObject();
-
- // dirty hack, ask Gino for a better solution in the ipo implementation
- // hacken en zagen, in what we call datahiding, not written for replication :(
-
- T_InterpolatorList oldlist = m_interpolators;
- iporeplica->m_interpolators.clear();
-
- T_InterpolatorList::iterator i;
- for (i = oldlist.begin(); !(i == oldlist.end()); ++i) {
- KX_ScalarInterpolator* copyipo = new KX_ScalarInterpolator(*((KX_ScalarInterpolator*)*i));
- iporeplica->AddInterpolator(copyipo);
-
- MT_Scalar* scaal = ((KX_ScalarInterpolator*)*i)->GetTarget();
- uint_ptr orgbase = (uint_ptr)this;
- uint_ptr orgloc = (uint_ptr)scaal;
- uint_ptr offset = orgloc-orgbase;
- uint_ptr newaddrbase = (uint_ptr)iporeplica + offset;
- MT_Scalar* blaptr = (MT_Scalar*) newaddrbase;
- copyipo->SetNewTarget((MT_Scalar*)blaptr);
- }
-
- return iporeplica;
-}
-
-KX_WorldIpoController::~KX_WorldIpoController()
-{
-
- T_InterpolatorList::iterator i;
- for (i = m_interpolators.begin(); !(i == m_interpolators.end()); ++i) {
- delete (*i);
- }
-
-}
diff --git a/source/gameengine/Ketsji/KX_WorldIpoController.h b/source/gameengine/Ketsji/KX_WorldIpoController.h
deleted file mode 100644
index 704f421573e..00000000000
--- a/source/gameengine/Ketsji/KX_WorldIpoController.h
+++ /dev/null
@@ -1,117 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file KX_WorldIpoController.h
- * \ingroup ketsji
- */
-
-#ifndef __KX_WORLDIPOCONTROLLER_H__
-#define __KX_WORLDIPOCONTROLLER_H__
-
-#include "SG_Controller.h"
-#include "SG_Spatial.h"
-#include "KX_IInterpolator.h"
-
-class KX_WorldIpoController : public SG_Controller
-{
-public:
- MT_Scalar m_mist_start;
- MT_Scalar m_mist_dist;
- MT_Scalar m_mist_intensity;
- MT_Scalar m_hori_rgb[3];
- MT_Scalar m_ambi_rgb[3];
-
-private:
- T_InterpolatorList m_interpolators;
- unsigned short m_modify_mist_start : 1;
- unsigned short m_modify_mist_dist : 1;
- unsigned short m_modify_mist_intensity : 1;
- unsigned short m_modify_horizon_color : 1;
- unsigned short m_modify_ambient_color : 1;
- bool m_modified;
-
- double m_ipotime;
-
-public:
- KX_WorldIpoController() :
- m_modify_mist_start(false),
- m_modify_mist_dist(false),
- m_modify_mist_intensity(false),
- m_modify_horizon_color(false),
- m_modify_ambient_color(false),
- m_modified(true),
- m_ipotime(0.0)
- {}
-
- virtual ~KX_WorldIpoController();
-
- virtual SG_Controller* GetReplica(class SG_Node* destnode);
-
- virtual bool Update(double time);
-
- virtual void SetSimulatedTime(double time) {
- m_ipotime = time;
- m_modified = true;
- }
-
- void SetModifyMistStart(bool modify) {
- m_modify_mist_start = modify;
- }
-
- void SetModifyMistDist(bool modify) {
- m_modify_mist_dist = modify;
- }
-
- void SetModifyMistIntensity(bool modify) {
- m_modify_mist_intensity = modify;
- }
-
- void SetModifyHorizonColor(bool modify) {
- m_modify_horizon_color = modify;
- }
-
- void SetModifyAmbientColor(bool modify) {
- m_modify_ambient_color = modify;
- }
-
- void
- SetOption(
- int option,
- int value
- ) {
- // intentionally empty
- };
-
- void AddInterpolator(KX_IInterpolator* interp);
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:KX_WorldIpoController")
-#endif
-};
-
-#endif /* __KX_WORLDIPOCONTROLLER_H__ */
diff --git a/source/gameengine/Network/CMakeLists.txt b/source/gameengine/Network/CMakeLists.txt
deleted file mode 100644
index 019fc3e6032..00000000000
--- a/source/gameengine/Network/CMakeLists.txt
+++ /dev/null
@@ -1,48 +0,0 @@
-# ***** BEGIN GPL LICENSE BLOCK *****
-#
-# This program is free software; you can redistribute it and/or
-# modify it under the terms of the GNU General Public License
-# as published by the Free Software Foundation; either version 2
-# of the License, or (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software Foundation,
-# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
-#
-# The Original Code is Copyright (C) 2006, Blender Foundation
-# All rights reserved.
-#
-# The Original Code is: all of this file.
-#
-# Contributor(s): Jacques Beaurain.
-#
-# ***** END GPL LICENSE BLOCK *****
-
-set(INC
- .
- ../../../intern/container
- ../../../intern/string
- ../../blender/blenlib
-)
-
-set(INC_SYS
- ../../../intern/moto/include
-)
-
-set(SRC
- NG_NetworkMessage.cpp
- NG_NetworkObject.cpp
- NG_NetworkScene.cpp
-
- NG_NetworkDeviceInterface.h
- NG_NetworkMessage.h
- NG_NetworkObject.h
- NG_NetworkScene.h
-)
-
-blender_add_lib(ge_logic_ngnetwork "${SRC}" "${INC}" "${INC_SYS}")
diff --git a/source/gameengine/Network/LoopBackNetwork/CMakeLists.txt b/source/gameengine/Network/LoopBackNetwork/CMakeLists.txt
deleted file mode 100644
index 75877575614..00000000000
--- a/source/gameengine/Network/LoopBackNetwork/CMakeLists.txt
+++ /dev/null
@@ -1,43 +0,0 @@
-# ***** BEGIN GPL LICENSE BLOCK *****
-#
-# This program is free software; you can redistribute it and/or
-# modify it under the terms of the GNU General Public License
-# as published by the Free Software Foundation; either version 2
-# of the License, or (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software Foundation,
-# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
-#
-# The Original Code is Copyright (C) 2006, Blender Foundation
-# All rights reserved.
-#
-# The Original Code is: all of this file.
-#
-# Contributor(s): Jacques Beaurain.
-#
-# ***** END GPL LICENSE BLOCK *****
-
-set(INC
- .
- ..
- ../../../../intern/container
- ../../../../intern/string
-)
-
-set(INC_SYS
-
-)
-
-set(SRC
- NG_LoopBackNetworkDeviceInterface.cpp
-
- NG_LoopBackNetworkDeviceInterface.h
-)
-
-blender_add_lib(ge_logic_loopbacknetwork "${SRC}" "${INC}" "${INC_SYS}")
diff --git a/source/gameengine/Network/LoopBackNetwork/NG_LoopBackNetworkDeviceInterface.cpp b/source/gameengine/Network/LoopBackNetwork/NG_LoopBackNetworkDeviceInterface.cpp
deleted file mode 100644
index c57bd304ca2..00000000000
--- a/source/gameengine/Network/LoopBackNetwork/NG_LoopBackNetworkDeviceInterface.cpp
+++ /dev/null
@@ -1,112 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- * LoopbackNetworkDeviceInterface derived from NG_NetworkDeviceInterface
- */
-
-/** \file gameengine/Network/LoopBackNetwork/NG_LoopBackNetworkDeviceInterface.cpp
- * \ingroup bgenetlb
- */
-
-
-#include "NG_LoopBackNetworkDeviceInterface.h"
-#include "NG_NetworkMessage.h"
-
-using namespace std;
-
-// temporary debugging printf's
-#ifdef NAN_NET_DEBUG
- #include <stdio.h>
-#endif
-
-NG_LoopBackNetworkDeviceInterface::NG_LoopBackNetworkDeviceInterface()
-{
- m_currentQueue=0;
- Online(); // LoopBackdevices are 'online' immediately
-}
-
-NG_LoopBackNetworkDeviceInterface::~NG_LoopBackNetworkDeviceInterface()
-{
-}
-
-// perhaps this should go to the shared/common implementation too
-void NG_LoopBackNetworkDeviceInterface::NextFrame()
-{
- // Release reference to the messages while emptying the queue
- while (m_messages[m_currentQueue].size() > 0) {
-#ifdef NAN_NET_DEBUG
- printf("NG_LBNDI::NextFrame %d '%s'\n", m_currentQueue, m_messages[m_currentQueue][0]->GetSubject().ReadPtr());
-#endif
- // Should do assert(m_events[0]);
- m_messages[m_currentQueue][0]->Release();
- m_messages[m_currentQueue].pop_front();
- }
- //m_messages[m_currentQueue].clear();
-
- m_currentQueue=1-m_currentQueue;
-}
-
-void NG_LoopBackNetworkDeviceInterface::SendNetworkMessage(NG_NetworkMessage* nwmsg)
-{
-#ifdef NAN_NET_DEBUG
- printf("NG_LBNDI::SendNetworkMessage %d, '%s'->'%s' '%s' '%s'\n",
- 1-m_currentQueue,
- nwmsg->GetDestinationName().ReadPtr(),
- nwmsg->GetSenderName().ReadPtr(),
- nwmsg->GetSubject().ReadPtr(),
- nwmsg->GetMessageText().ReadPtr());
-#endif
- int backqueue = 1-m_currentQueue;
-
- nwmsg->AddRef();
- m_messages[backqueue].push_back(nwmsg);
-}
-
-vector<NG_NetworkMessage*> NG_LoopBackNetworkDeviceInterface::RetrieveNetworkMessages()
-{
- vector<NG_NetworkMessage*> messages;
-
- std::deque<NG_NetworkMessage*>::iterator mesit=m_messages[m_currentQueue].begin();
- for (; !(mesit == m_messages[m_currentQueue].end()); ++mesit)
- {
-
- // We don't increase the reference count for these messages. We
- // are passing a vector of messages in the interface and not
- // explicitily storing the messgaes for long term usage
-
- messages.push_back(*mesit);
-
-#ifdef NAN_NET_DEBUG
- printf("NG_LBNDI::RetrieveNetworkMessages %d '%s'->'%s' '%s' '%s'\n",
- m_currentQueue,
- (*mesit)->GetDestinationName().ReadPtr(),
- (*mesit)->GetSenderName().ReadPtr(),
- (*mesit)->GetSubject().ReadPtr(),
- (*mesit)->GetMessageText().ReadPtr());
-#endif
- }
- return messages;
-}
-
diff --git a/source/gameengine/Network/LoopBackNetwork/NG_LoopBackNetworkDeviceInterface.h b/source/gameengine/Network/LoopBackNetwork/NG_LoopBackNetworkDeviceInterface.h
deleted file mode 100644
index 8bbb1e91e35..00000000000
--- a/source/gameengine/Network/LoopBackNetwork/NG_LoopBackNetworkDeviceInterface.h
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file NG_LoopBackNetworkDeviceInterface.h
- * \ingroup bgenetlb
- * \brief LoopbackNetworkDeviceInterface derived from NG_NetworkDeviceInterface
- */
-#ifndef __NG_LOOPBACKNETWORKDEVICEINTERFACE_H__
-#define __NG_LOOPBACKNETWORKDEVICEINTERFACE_H__
-
-#include <deque>
-#include "NG_NetworkDeviceInterface.h"
-
-class NG_LoopBackNetworkDeviceInterface : public NG_NetworkDeviceInterface
-{
- std::deque<NG_NetworkMessage*> m_messages[2];
- int m_currentQueue;
-
-public:
- NG_LoopBackNetworkDeviceInterface();
- virtual ~NG_LoopBackNetworkDeviceInterface();
-
- /**
- * Clear message buffer
- */
- virtual void NextFrame();
-
- bool Connect(char *address, unsigned int port, char *password,
- unsigned int localport, unsigned int timeout)
- {
- return true;
- }
- bool Disconnect(void) {return true;}
-
- virtual void SendNetworkMessage(class NG_NetworkMessage* msg);
- virtual std::vector<NG_NetworkMessage*> RetrieveNetworkMessages();
-};
-
-#endif /* __NG_LOOPBACKNETWORKDEVICEINTERFACE_H__ */
diff --git a/source/gameengine/Network/NG_NetworkDeviceInterface.h b/source/gameengine/Network/NG_NetworkDeviceInterface.h
deleted file mode 100644
index 7fcf799db31..00000000000
--- a/source/gameengine/Network/NG_NetworkDeviceInterface.h
+++ /dev/null
@@ -1,82 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file NG_NetworkDeviceInterface.h
- * \ingroup bgenet
- * \brief Functions like (de)initialize network, get library version
- * To be derived by loopback and network libraries
- */
-
-#ifndef __NG_NETWORKDEVICEINTERFACE_H__
-#define __NG_NETWORKDEVICEINTERFACE_H__
-
-#include "NG_NetworkMessage.h"
-#include <vector>
-
-class NG_NetworkDeviceInterface
-{
-private:
- // candidates for shared/common implementation class
- bool m_online;
-public:
- NG_NetworkDeviceInterface() {}
- virtual ~NG_NetworkDeviceInterface() {}
-
- virtual void NextFrame()=0;
-
- /**
- * Mark network connection online
- */
- void Online(void) { m_online = true; }
- /**
- * Mark network connection offline
- */
- void Offline(void) { m_online = false; }
- /**
- * Is the network connection established ?
- */
- bool IsOnline(void) { return m_online; }
-
- virtual bool Connect(char *address, unsigned int port, char *password,
- unsigned int localport, unsigned int timeout)=0;
- virtual bool Disconnect(void)=0;
-
- virtual void SendNetworkMessage(NG_NetworkMessage* msg)=0;
- /**
- * read NG_NetworkMessage from library buffer, may be
- * irrelevant for loopbackdevices
- */
-
- virtual std::vector<NG_NetworkMessage*> RetrieveNetworkMessages()=0;
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:NG_NetworkDeviceInterface")
-#endif
-};
-
-#endif /* __NG_NETWORKDEVICEINTERFACE_H__ */
diff --git a/source/gameengine/Network/NG_NetworkMessage.cpp b/source/gameengine/Network/NG_NetworkMessage.cpp
deleted file mode 100644
index 23ae2529b7a..00000000000
--- a/source/gameengine/Network/NG_NetworkMessage.cpp
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- * generic Network Message implementation
- */
-
-/** \file gameengine/Network/NG_NetworkMessage.cpp
- * \ingroup bgenet
- */
-
-#include "NG_NetworkMessage.h"
-#include <assert.h>
-
-int NG_NetworkMessage::s_nextID = 3; // just some number to start with
-
-NG_NetworkMessage::NG_NetworkMessage(
- const STR_String& to,
- const STR_String& from,
- const STR_String& subject,
- const STR_String& body) :
- m_uniqueMessageID(s_nextID++),
- m_refcount(1),
- m_to(to),
- m_from(from),
- m_subject(subject),
- m_message(body)
-{
-}
-
-NG_NetworkMessage::~NG_NetworkMessage()
-{
- assert(m_refcount==0);
-}
diff --git a/source/gameengine/Network/NG_NetworkMessage.h b/source/gameengine/Network/NG_NetworkMessage.h
deleted file mode 100644
index 6ed266557fc..00000000000
--- a/source/gameengine/Network/NG_NetworkMessage.h
+++ /dev/null
@@ -1,138 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file NG_NetworkMessage.h
- * \ingroup bgenet
- * \brief generic Network Message class
- */
-#ifndef __NG_NETWORKMESSAGE_H__
-#define __NG_NETWORKMESSAGE_H__
-
-#include "STR_HashedString.h"
-
-#ifdef WITH_CXX_GUARDEDALLOC
-#include "MEM_guardedalloc.h"
-#endif
-
-class NG_NetworkMessage
-{
- static int s_nextID;
- int m_uniqueMessageID; // intern counting MessageID
- unsigned int m_ClientId;
- int m_refcount;
-
- STR_String m_to; // receiver
- STR_String m_from; // sender
- STR_String m_subject; // empty or propName
- STR_String m_message; // message or propValue
-
-protected:
- ~NG_NetworkMessage();
-
-public:
- NG_NetworkMessage(
- const STR_String& to,
- const STR_String& from,
- const STR_String& subject,
- const STR_String& body);
-
- void AddRef() {
- m_refcount++;
- }
-
- // This is not nice code you should'nt need to resort to
- // delete this.
- void Release()
- {
- if (! --m_refcount)
- {
- delete this;
- }
- }
-
- /**
- * set the content of this message
- */
- void SetMessageText(const STR_String& msgtext) {
- m_message = msgtext;
- }
-
- /**
- * get the (read-only) To part of this message
- */
- const STR_String& GetDestinationName() { return m_to; }
-
- /**
- * get the (read-only) From part of this message
- */
- const STR_String& GetSenderName() { return m_from; }
-
- /**
- * get the (read-only) Subject part of this message
- */
- const STR_String& GetSubject() { return m_subject; }
-
- /**
- * get the (read-only) Body part of this message
- */
- const STR_String& GetMessageText() {
-//cout << "GetMessageText " << m_message << "\n";
- return m_message;
- }
- const STR_String& GetMessageText() const {
-//cout << "GetMessageText " << m_message << "\n";
- return m_message;
- }
-
- /**
- * Set the NetworkMessage sender identifier
- */
- void SetSender(unsigned int ClientId) {
- m_ClientId = ClientId;
- }
-
- /**
- * Get the NetworkMessage sender identifier
- */
- unsigned int GetSender(void) {
- return m_ClientId;
- }
-
- /**
- * get the unique Network Message ID
- */
- int GetMessageID() {
- return m_uniqueMessageID;
- }
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:NG_NetworkMessage")
-#endif
-};
-
-#endif /* __NG_NETWORKMESSAGE_H__ */
diff --git a/source/gameengine/Network/NG_NetworkObject.cpp b/source/gameengine/Network/NG_NetworkObject.cpp
deleted file mode 100644
index 5cd42a2e45a..00000000000
--- a/source/gameengine/Network/NG_NetworkObject.cpp
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- * NetworkGame_NetworkObject generic Network Object implementation
- */
-
-/** \file gameengine/Network/NG_NetworkObject.cpp
- * \ingroup bgenet
- */
-
-#include "NG_NetworkObject.h"
-
-NG_NetworkObject::NG_NetworkObject()
-{
-}
-
-NG_NetworkObject::~NG_NetworkObject()
-{
-}
-
-const STR_String& NG_NetworkObject::GetName()
-{
- return m_name;
-}
diff --git a/source/gameengine/Network/NG_NetworkObject.h b/source/gameengine/Network/NG_NetworkObject.h
deleted file mode 100644
index 54459cad55d..00000000000
--- a/source/gameengine/Network/NG_NetworkObject.h
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file NG_NetworkObject.h
- * \ingroup bgenet
- * \brief generic Network Object class
- */
-#ifndef __NG_NETWORKOBJECT_H__
-#define __NG_NETWORKOBJECT_H__
-
-#include "STR_String.h"
-
-#ifdef WITH_CXX_GUARDEDALLOC
-#include "MEM_guardedalloc.h"
-#endif
-
-class NG_NetworkObject
-{
- STR_String m_name;
-public:
- NG_NetworkObject();
- ~NG_NetworkObject();
- const STR_String& GetName();
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:NG_NetworkObject")
-#endif
-};
-
-#endif /* __NG_NETWORKOBJECT_H__ */
diff --git a/source/gameengine/Network/NG_NetworkScene.cpp b/source/gameengine/Network/NG_NetworkScene.cpp
deleted file mode 100644
index 3dbfb53d03d..00000000000
--- a/source/gameengine/Network/NG_NetworkScene.cpp
+++ /dev/null
@@ -1,272 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- * NetworkSceneManagement generic implementation
- */
-
-/** \file gameengine/Network/NG_NetworkScene.cpp
- * \ingroup bgenet
- */
-
-#include <stdio.h>
-#include <MT_assert.h>
-#include <algorithm>
-
-#include "NG_NetworkScene.h"
-#include "NG_NetworkDeviceInterface.h"
-#include "NG_NetworkMessage.h"
-#include "NG_NetworkObject.h"
-
-NG_NetworkScene::NG_NetworkScene(NG_NetworkDeviceInterface* nic)
-{
- m_networkdevice = nic;
-}
-
-NG_NetworkScene::~NG_NetworkScene()
-{
- ClearAllMessageMaps();
-}
-
-/**
- * progress one frame, handle all network traffic
- */
-void NG_NetworkScene::proceed(double curtime)
-{
- if (!m_networkdevice) return;
- if (!m_networkdevice->IsOnline()) return;
-
- ClearAllMessageMaps();
-
- // read all NetworkMessages from the device
- vector<NG_NetworkMessage*> messages =
- m_networkdevice->RetrieveNetworkMessages();
-
- vector<NG_NetworkMessage*>::iterator mesit = messages.begin();
- for (; !(mesit == messages.end()); mesit++) {
- NG_NetworkMessage* message = (*mesit);
- vector<NG_NetworkMessage*>* tmplist=NULL;
-
- vector<NG_NetworkMessage*>** tmplistptr =
- m_messagesByDestinationName[message->GetDestinationName()];
- // if there is already a vector of messages, append, else create
- // a new vector and insert into map
- if (!tmplistptr) {
- tmplist = new vector<NG_NetworkMessage*>;
- m_messagesByDestinationName.insert(message->GetDestinationName(),
- tmplist);
- } else {
- tmplist = *tmplistptr;
- }
- message->AddRef();
- tmplist->push_back(message);
- tmplist = NULL;
-
- tmplistptr = m_messagesBySenderName[message->GetSenderName()];
- // if there is already a vector of messages, append, else create
- // a new vector and insert into map
- if (!tmplistptr) {
- tmplist = new vector<NG_NetworkMessage*>;
- m_messagesBySenderName.insert(message->GetSenderName(), tmplist);
- } else {
- tmplist = *tmplistptr;
- }
- message->AddRef();
- tmplist->push_back(message);
- tmplist = NULL;
-
- tmplistptr = m_messagesBySubject[message->GetSubject()];
- // if there is already a vector of messages, append, else create
- // a new vector and insert into map
- if (!tmplistptr) {
- tmplist = new vector<NG_NetworkMessage*>;
- m_messagesBySubject.insert(message->GetSubject(), tmplist);
- } else {
- tmplist = *tmplistptr;
- }
- message->AddRef();
- tmplist->push_back(message);
- tmplist = NULL;
- }
-}
-
-/**
- * add a network object to the network scene
- */
-void NG_NetworkScene::AddObject(NG_NetworkObject* object)
-{
- if (! m_networkdevice->IsOnline()) return;
-
- const STR_String& name = object->GetName();
- m_networkObjects.insert(name, object);
-}
-
-/**
- * remove a network object from the network scene
- */
-void NG_NetworkScene::RemoveObject(NG_NetworkObject* object)
-{
- if (! m_networkdevice->IsOnline()) return;
-
- const STR_String& name = object->GetName();
- m_networkObjects.remove(name);
-}
-
-/**
- * remove all network scene objects at once
- */
-void NG_NetworkScene::RemoveAllObjects()
-{
- m_networkObjects.clear();
-}
-
-/**
- * get a single network object given its name
- */
-NG_NetworkObject* NG_NetworkScene::FindNetworkObject(const STR_String& objname)
-{
- NG_NetworkObject *nwobj = NULL;
- if (! m_networkdevice->IsOnline()) return nwobj;
-
- NG_NetworkObject **nwobjptr = m_networkObjects[objname];
- if (nwobjptr) {
- nwobj = *nwobjptr;
- }
-
- return nwobj;
-}
-
-bool NG_NetworkScene::ConstraintsAreValid(
- const STR_String& from,
- const STR_String& subject,
- NG_NetworkMessage* message)
-{
- vector<NG_NetworkMessage*>** fromlistptr = m_messagesBySenderName[from];
- vector<NG_NetworkMessage*>** subjectlistptr = m_messagesBySubject[subject];
-
- vector<NG_NetworkMessage*>* fromlist = (fromlistptr ? *fromlistptr : NULL);
- vector<NG_NetworkMessage*>* subjectlist = (subjectlistptr ? *subjectlistptr : NULL);
-
- return (
- ( from.IsEmpty() || (!fromlist ? false : (!(std::find(fromlist->begin(), fromlist->end(), message) == fromlist->end())))
- ) &&
- ( subject.IsEmpty() || (!subjectlist ? false : (!(std::find(subjectlist->begin(), subjectlist->end(), message) == subjectlist->end())))
- ));
-}
-
-vector<NG_NetworkMessage*> NG_NetworkScene::FindMessages(
- const STR_String& to,
- const STR_String& from,
- const STR_String& subject,
- bool spamallowed)
-{
- vector<NG_NetworkMessage*> foundmessages;
- bool notfound = false;
-
- // broad phase
- notfound = ((to.IsEmpty() || spamallowed) ? notfound : m_messagesByDestinationName[to] == NULL);
- if (!notfound)
- notfound = (from.IsEmpty() ? notfound : m_messagesBySenderName[from] == NULL);
- if (!notfound)
- notfound = (subject.IsEmpty() ? notfound : m_messagesBySubject[subject] == NULL);
- if (notfound) {
- // it's definitely NOT in the scene, so stop looking
- } else { // narrow phase
- // possibly it's there, but maybe not (false hit)
- if (to.IsEmpty()) {
- // take all messages, and check other fields
- MT_assert(!"objectnames that are empty are not valid, so make it a hobby project :)\n");
- } else {
- //todo: find intersection of messages (that are in other 2 maps)
- vector<NG_NetworkMessage*>** tolistptr = m_messagesByDestinationName[to];
- if (tolistptr) {
- vector<NG_NetworkMessage*>* tolist = *tolistptr;
- vector<NG_NetworkMessage*>::iterator listit;
- for (listit=tolist->begin();!(listit==tolist->end());listit++) {
- NG_NetworkMessage* message = *listit;
- if (ConstraintsAreValid(from, subject, message)) {
- message->AddRef();
- foundmessages.push_back(message);
- }
- }
- }
- // TODO find intersection of messages (that are in other 2 maps)
- if (spamallowed) {
- tolistptr = m_messagesByDestinationName[""];
- if (tolistptr) {
- vector<NG_NetworkMessage*>* tolist = *tolistptr;
- vector<NG_NetworkMessage*>::iterator listit;
- for (listit=tolist->begin();!(listit==tolist->end());listit++) {
- NG_NetworkMessage* message = *listit;
- if (ConstraintsAreValid(from, subject, message)) {
- message->AddRef();
- foundmessages.push_back(message);
- }
- }
- }
- }
- }
- }
- return foundmessages;
-}
-
-void NG_NetworkScene::SendMessage(
- const STR_String& to,
- const STR_String& from,
- const STR_String& subject,
- const STR_String& message)
-{
- NG_NetworkMessage* msg = new NG_NetworkMessage(to, from, subject, message);
- m_networkdevice->SendNetworkMessage(msg);
- msg->Release();
-}
-
-void NG_NetworkScene::ClearAllMessageMaps(void)
-{
- ClearMessageMap(m_messagesByDestinationName);
- ClearMessageMap(m_messagesBySenderName);
- ClearMessageMap(m_messagesBySubject);
-}
-
-void NG_NetworkScene::ClearMessageMap(TMessageMap& map)
-{
- // Release the messages in the map
- for (int i = 0; i < map.size(); i++) {
- vector<NG_NetworkMessage*>* msglist;
- msglist = *(map.at(i));
-
- // Iterate through the current vector and release all it's messages
- vector<NG_NetworkMessage*>::iterator msgit;
- for (msgit = msglist->begin(); msgit != msglist->end(); msgit++) {
- (*msgit)->Release();
- }
-
- // Delete the actual vector
- delete (msglist);
- }
-
- // Empty the map
- map.clear();
-}
-
diff --git a/source/gameengine/Network/NG_NetworkScene.h b/source/gameengine/Network/NG_NetworkScene.h
deleted file mode 100644
index e6233852ee2..00000000000
--- a/source/gameengine/Network/NG_NetworkScene.h
+++ /dev/null
@@ -1,118 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file NG_NetworkScene.h
- * \ingroup bgenet
- * \brief NetworkSceneManagement generic class
- */
-#ifndef __NG_NETWORKSCENE_H__
-#define __NG_NETWORKSCENE_H__
-
-#include "CTR_Map.h"
-#include "STR_HashedString.h"
-#include <vector>
-
-#ifdef WITH_CXX_GUARDEDALLOC
-#include "MEM_guardedalloc.h"
-#endif
-
-//MSVC defines SendMessage as a win api function, even though we aren't using it
-#ifdef SendMessage
-# undef SendMessage
-#endif
-
-using namespace std;
-
-class NG_NetworkDeviceInterface;
-
-class NG_NetworkScene
-{
- class NG_NetworkDeviceInterface *m_networkdevice;
- CTR_Map<STR_HashedString, class NG_NetworkObject *> m_networkObjects;
-
- // CTR_Maps used as a 'Bloom' filter
- typedef CTR_Map<STR_HashedString, std::vector<class NG_NetworkMessage*>* > TMessageMap;
- TMessageMap m_messagesByDestinationName;
- TMessageMap m_messagesBySenderName;
- TMessageMap m_messagesBySubject;
-
-public:
- NG_NetworkScene(NG_NetworkDeviceInterface *nic);
- ~NG_NetworkScene();
-
- /**
- * progress one frame, handle all network traffic
- */
- void proceed(double curtime);
-
- /**
- * add a networkobject to the scene
- */
- void AddObject(NG_NetworkObject* object);
-
- /**
- * remove a networkobject to the scene
- */
- void RemoveObject(NG_NetworkObject* object);
-
- /**
- * remove all objects at once
- */
- void RemoveAllObjects();
-
- /**
- * send a message (ascii text) over the network
- */
- void SendMessage(const STR_String& to,const STR_String& from,const STR_String& subject,const STR_String& message);
-
- /**
- * find an object by name
- */
- NG_NetworkObject* FindNetworkObject(const STR_String& objname);
-
- bool ConstraintsAreValid(const STR_String& from,const STR_String& subject,class NG_NetworkMessage* message);
- vector<NG_NetworkMessage*> FindMessages(const STR_String& to,const STR_String& from,const STR_String& subject,bool spamallowed);
-
-protected:
- /**
- * Releases messages in message map members.
- */
- void ClearAllMessageMaps(void);
-
- /**
- * Releases messages for the given message map.
- * \param map Message map with messages.
- */
- void ClearMessageMap(TMessageMap& map);
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:NG_NetworkScene")
-#endif
-};
-
-#endif /* __NG_NETWORKSCENE_H__ */
diff --git a/source/gameengine/Physics/Bullet/CMakeLists.txt b/source/gameengine/Physics/Bullet/CMakeLists.txt
deleted file mode 100644
index 8b00f1b47fa..00000000000
--- a/source/gameengine/Physics/Bullet/CMakeLists.txt
+++ /dev/null
@@ -1,73 +0,0 @@
-# ***** BEGIN GPL LICENSE BLOCK *****
-#
-# This program is free software; you can redistribute it and/or
-# modify it under the terms of the GNU General Public License
-# as published by the Free Software Foundation; either version 2
-# of the License, or (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software Foundation,
-# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
-#
-# The Original Code is Copyright (C) 2006, Blender Foundation
-# All rights reserved.
-#
-# The Original Code is: all of this file.
-#
-# Contributor(s): Jacques Beaurain.
-#
-# ***** END GPL LICENSE BLOCK *****
-
-# since this includes bullet we get errors from the headers too
-remove_strict_flags()
-
-set(INC
- .
- ../common
- ../../Converter
- ../../Expressions
- ../../GameLogic
- ../../Ketsji
- ../../Rasterizer
- ../../SceneGraph
- ../../../blender/blenkernel
- ../../../blender/blenlib
- ../../../blender/gpu
- ../../../blender/makesdna
- ../../../../intern/container
- ../../../../intern/guardedalloc
- ../../../../intern/glew-mx
- ../../../../intern/string
-)
-
-set(INC_SYS
- ../../../../intern/moto/include
- ${GLEW_INCLUDE_PATH}
- ${PYTHON_INCLUDE_DIRS}
-)
-
-set(SRC
- CcdPhysicsEnvironment.cpp
- CcdPhysicsController.cpp
- CcdGraphicController.cpp
-
- CcdGraphicController.h
- CcdPhysicsController.h
- CcdPhysicsEnvironment.h
-)
-
-if(WITH_BULLET)
- list(APPEND INC_SYS
- ${BULLET_INCLUDE_DIRS}
- )
- add_definitions(-DWITH_BULLET)
-endif()
-
-add_definitions(${GL_DEFINITIONS})
-
-blender_add_lib(ge_phys_bullet "${SRC}" "${INC}" "${INC_SYS}")
diff --git a/source/gameengine/Physics/Bullet/CcdGraphicController.cpp b/source/gameengine/Physics/Bullet/CcdGraphicController.cpp
deleted file mode 100644
index 470a5431843..00000000000
--- a/source/gameengine/Physics/Bullet/CcdGraphicController.cpp
+++ /dev/null
@@ -1,152 +0,0 @@
-/** \file gameengine/Physics/Bullet/CcdGraphicController.cpp
- * \ingroup physbullet
- */
-/*
-Bullet Continuous Collision Detection and Physics Library
-Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
-
-This software is provided 'as-is', without any express or implied warranty.
-In no event will the authors be held liable for any damages arising from the use of this software.
-Permission is granted to anyone to use this software for any purpose,
-including commercial applications, and to alter it and redistribute it freely,
-subject to the following restrictions:
-
-1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
-2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
-3. This notice may not be removed or altered from any source distribution.
-*/
-
-#include "CcdPhysicsEnvironment.h"
-#include "CcdGraphicController.h"
-#include "btBulletDynamicsCommon.h"
-#include "MT_Point3.h"
-
-
-CcdGraphicController::CcdGraphicController (CcdPhysicsEnvironment* phyEnv, PHY_IMotionState* motionState) :
- m_localAabbMin(0.f, 0.f, 0.f),
- m_localAabbMax(0.f, 0.f, 0.f),
- m_motionState(motionState),
- m_phyEnv(phyEnv),
- m_handle(NULL),
- m_newClientInfo(NULL)
-{
-}
-
-CcdGraphicController::~CcdGraphicController()
-{
- if (m_phyEnv)
- m_phyEnv->RemoveCcdGraphicController(this);
-
- if (m_motionState)
- delete m_motionState;
-}
-
-void CcdGraphicController::SetLocalAabb(const btVector3& aabbMin,const btVector3& aabbMax)
-{
- m_localAabbMin = aabbMin;
- m_localAabbMax = aabbMax;
- SetGraphicTransform();
-}
-
-void CcdGraphicController::SetLocalAabb(const MT_Point3& aabbMin,const MT_Point3& aabbMax)
-{
- m_localAabbMin.setValue(aabbMin[0],aabbMin[1],aabbMin[2]);
- m_localAabbMax.setValue(aabbMax[0],aabbMax[1],aabbMax[2]);
- SetGraphicTransform();
-}
-
-void CcdGraphicController::SetLocalAabb(const MT_Vector3& aabbMin,const MT_Vector3& aabbMax)
-{
- m_localAabbMin.setValue(aabbMin[0],aabbMin[1],aabbMin[2]);
- m_localAabbMax.setValue(aabbMax[0],aabbMax[1],aabbMax[2]);
- SetGraphicTransform();
-}
-
-void CcdGraphicController::SetLocalAabb(const float* aabbMin,const float* aabbMax)
-{
- m_localAabbMin.setValue(aabbMin[0],aabbMin[1],aabbMin[2]);
- m_localAabbMax.setValue(aabbMax[0],aabbMax[1],aabbMax[2]);
- SetGraphicTransform();
-}
-
-void CcdGraphicController::GetAabb(btVector3& aabbMin, btVector3& aabbMax)
-{
- btVector3 pos;
- btVector3 scale;
- float ori[12];
- m_motionState->GetWorldPosition(pos.m_floats[0],pos.m_floats[1],pos.m_floats[2]);
- m_motionState->GetWorldScaling(scale.m_floats[0],scale.m_floats[1],scale.m_floats[2]);
- m_motionState->GetWorldOrientation(ori);
- btMatrix3x3 rot(ori[0], ori[4], ori[8],
- ori[1], ori[5], ori[9],
- ori[2], ori[6], ori[10]);
-
- btVector3 localAabbMin = m_localAabbMin;
- btVector3 localAabbMax = m_localAabbMax;
- btVector3 tmpAabbMin = m_localAabbMin * scale;
- btVector3 tmpAabbMax = m_localAabbMax * scale;
-
- localAabbMin[0] = (scale.getX() >= 0.0f) ? tmpAabbMin[0] : tmpAabbMax[0];
- localAabbMin[1] = (scale.getY() >= 0.0f) ? tmpAabbMin[1] : tmpAabbMax[1];
- localAabbMin[2] = (scale.getZ() >= 0.0f) ? tmpAabbMin[2] : tmpAabbMax[2];
- localAabbMax[0] = (scale.getX() <= 0.0f) ? tmpAabbMin[0] : tmpAabbMax[0];
- localAabbMax[1] = (scale.getY() <= 0.0f) ? tmpAabbMin[1] : tmpAabbMax[1];
- localAabbMax[2] = (scale.getZ() <= 0.0f) ? tmpAabbMin[2] : tmpAabbMax[2];
-
- btVector3 localHalfExtents = btScalar(0.5f)*(localAabbMax-localAabbMin);
- btVector3 localCenter = btScalar(0.5f)*(localAabbMax+localAabbMin);
-
- btMatrix3x3 abs_b = rot.absolute();
- btVector3 center = rot*localCenter + pos;
- btVector3 extent = abs_b*localHalfExtents;
- aabbMin = center - extent;
- aabbMax = center + extent;
-}
-
-bool CcdGraphicController::SetGraphicTransform()
-{
- if (!m_handle)
- return false;
- btVector3 aabbMin;
- btVector3 aabbMax;
- GetAabb(aabbMin, aabbMax);
- // update Aabb in broadphase
- m_phyEnv->GetCullingTree()->setAabb(m_handle,aabbMin,aabbMax,NULL);
- return true;
-}
-
-PHY_IGraphicController* CcdGraphicController::GetReplica(class PHY_IMotionState* motionState)
-{
- CcdGraphicController* replica = new CcdGraphicController(*this);
- replica->m_motionState = motionState;
- replica->m_newClientInfo = NULL;
- replica->m_handle = NULL;
- // don't add the graphic controller now: work around a bug in Bullet with rescaling,
- // (the scale of the controller is not yet defined).
- //m_phyEnv->addCcdGraphicController(replica);
- return replica;
-}
-
-void CcdGraphicController::SetPhysicsEnvironment(class PHY_IPhysicsEnvironment* env)
-{
- CcdPhysicsEnvironment* phyEnv = static_cast<CcdPhysicsEnvironment*>(env);
- /* Updates the m_phyEnv's m_cullingTree & m_cullingCache */
- if (GetBroadphaseHandle()) {
- /* insert into the new physics scene */
- Activate(false);
- m_phyEnv= phyEnv;
- Activate(true);
- }
- else {
- m_phyEnv= phyEnv;
- }
-}
-
-void CcdGraphicController::Activate(bool active)
-{
- if (active)
- m_phyEnv->AddCcdGraphicController(this);
- else
- m_phyEnv->RemoveCcdGraphicController(this);
-
-}
diff --git a/source/gameengine/Physics/Bullet/CcdGraphicController.h b/source/gameengine/Physics/Bullet/CcdGraphicController.h
deleted file mode 100644
index e76ad86301e..00000000000
--- a/source/gameengine/Physics/Bullet/CcdGraphicController.h
+++ /dev/null
@@ -1,90 +0,0 @@
-/*
-Bullet Continuous Collision Detection and Physics Library
-Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
-
-This software is provided 'as-is', without any express or implied warranty.
-In no event will the authors be held liable for any damages arising from the use of this software.
-Permission is granted to anyone to use this software for any purpose,
-including commercial applications, and to alter it and redistribute it freely,
-subject to the following restrictions:
-
-1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
-2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
-3. This notice may not be removed or altered from any source distribution.
-*/
-
-/** \file CcdGraphicController.h
- * \ingroup physbullet
- */
-
-
-#ifndef __CCDGRAPHICCONTROLLER_H__
-#define __CCDGRAPHICCONTROLLER_H__
-
-#include "PHY_IGraphicController.h"
-
-#include "btBulletDynamicsCommon.h"
-#include "LinearMath/btTransform.h"
-
-#include "PHY_IMotionState.h"
-#include "MT_Point3.h"
-
-class CcdPhysicsEnvironment;
-class btCollisionObject;
-
-///CcdGraphicController is a graphic object that supports view frustrum culling and occlusion
-class CcdGraphicController : public PHY_IGraphicController
-{
-public:
- CcdGraphicController(CcdPhysicsEnvironment* phyEnv, PHY_IMotionState* motionState);
-
- virtual ~CcdGraphicController();
-
- void SetLocalAabb(const btVector3& aabbMin,const btVector3& aabbMax);
- void SetLocalAabb(const MT_Point3& aabbMin,const MT_Point3& aabbMax);
- virtual void SetLocalAabb(const MT_Vector3& aabbMin,const MT_Vector3& aabbMax);
- virtual void SetLocalAabb(const float aabbMin[3],const float aabbMax[3]);
-
- PHY_IMotionState* GetMotionState() { return m_motionState; }
- void GetAabb(btVector3& aabbMin, btVector3& aabbMax);
-
- virtual void SetBroadphaseHandle(btBroadphaseProxy* handle) { m_handle = handle; }
- virtual btBroadphaseProxy* GetBroadphaseHandle() { return m_handle; }
-
- virtual void SetPhysicsEnvironment(class PHY_IPhysicsEnvironment* env);
-
- ////////////////////////////////////
- // PHY_IGraphicController interface
- ////////////////////////////////////
-
- /**
- * Updates the Aabb based on the motion state
- */
- virtual bool SetGraphicTransform();
- /**
- * Add/remove to environment
- */
- virtual void Activate(bool active);
-
- // client info for culling
- virtual void* GetNewClientInfo() { return m_newClientInfo; }
- virtual void SetNewClientInfo(void* clientinfo) { m_newClientInfo = clientinfo; }
- virtual PHY_IGraphicController* GetReplica(class PHY_IMotionState* motionstate);
-
-private:
- // unscaled aabb corner
- btVector3 m_localAabbMin;
- btVector3 m_localAabbMax;
-
- PHY_IMotionState* m_motionState;
- CcdPhysicsEnvironment* m_phyEnv;
- btBroadphaseProxy* m_handle;
- void* m_newClientInfo;
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:CcdGraphicController")
-#endif
-};
-
-#endif /* BULLET2_PHYSICSCONTROLLER_H */
diff --git a/source/gameengine/Physics/Bullet/CcdPhysicsController.cpp b/source/gameengine/Physics/Bullet/CcdPhysicsController.cpp
deleted file mode 100644
index b3cee944880..00000000000
--- a/source/gameengine/Physics/Bullet/CcdPhysicsController.cpp
+++ /dev/null
@@ -1,2668 +0,0 @@
-/** \file gameengine/Physics/Bullet/CcdPhysicsController.cpp
- * \ingroup physbullet
- */
-/*
-Bullet Continuous Collision Detection and Physics Library
-Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
-
-This software is provided 'as-is', without any express or implied warranty.
-In no event will the authors be held liable for any damages arising from the use of this software.
-Permission is granted to anyone to use this software for any purpose,
-including commercial applications, and to alter it and redistribute it freely,
-subject to the following restrictions:
-
-1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
-2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
-3. This notice may not be removed or altered from any source distribution.
-*/
-
-#ifndef WIN32
-#include <stdint.h>
-#endif
-
-#include "CcdPhysicsController.h"
-#include "btBulletDynamicsCommon.h"
-#include "BulletCollision/CollisionDispatch/btGhostObject.h"
-#include "BulletCollision/CollisionShapes/btScaledBvhTriangleMeshShape.h"
-#include "BulletCollision/CollisionShapes/btTriangleIndexVertexArray.h"
-
-#include "PHY_IMotionState.h"
-#include "CcdPhysicsEnvironment.h"
-#include "RAS_MeshObject.h"
-#include "RAS_Polygon.h"
-#include "RAS_Deformer.h"
-#include "KX_GameObject.h"
-
-#include "BulletSoftBody/btSoftBody.h"
-#include "BulletSoftBody/btSoftBodyInternals.h"
-#include "BulletSoftBody/btSoftBodyHelpers.h"
-#include "LinearMath/btConvexHull.h"
-#include "BulletCollision/Gimpact/btGImpactShape.h"
-
-#include "BulletSoftBody/btSoftRigidDynamicsWorld.h"
-
-#include "DNA_mesh_types.h"
-#include "DNA_meshdata_types.h"
-
-extern "C"{
- #include "BLI_utildefines.h"
- #include "BKE_cdderivedmesh.h"
-}
-
-
-class BP_Proxy;
-
-///todo: fill all the empty CcdPhysicsController methods, hook them up to the btRigidBody class
-
-//'temporarily' global variables
-//float gDeactivationTime = 2.f;
-//bool gDisableDeactivation = false;
-extern float gDeactivationTime;
-extern bool gDisableDeactivation;
-
-
-float gLinearSleepingTreshold;
-float gAngularSleepingTreshold;
-
-BlenderBulletCharacterController::BlenderBulletCharacterController(btMotionState *motionState, btPairCachingGhostObject *ghost, btConvexShape* shape, float stepHeight)
- : btKinematicCharacterController(ghost,shape,stepHeight,2),
- m_motionState(motionState),
- m_jumps(0),
- m_maxJumps(1)
-{
-}
-
-void BlenderBulletCharacterController::updateAction(btCollisionWorld *collisionWorld, btScalar dt)
-{
- if (onGround())
- m_jumps = 0;
-
- btKinematicCharacterController::updateAction(collisionWorld,dt);
- m_motionState->setWorldTransform(getGhostObject()->getWorldTransform());
-}
-
-unsigned char BlenderBulletCharacterController::getMaxJumps() const
-{
- return m_maxJumps;
-}
-
-void BlenderBulletCharacterController::setMaxJumps(unsigned char maxJumps)
-{
- m_maxJumps = maxJumps;
-}
-
-unsigned char BlenderBulletCharacterController::getJumpCount() const
-{
- return m_jumps;
-}
-
-bool BlenderBulletCharacterController::canJump() const
-{
- return (onGround() && m_maxJumps > 0) || m_jumps < m_maxJumps;
-}
-
-void BlenderBulletCharacterController::jump()
-{
- if (!canJump())
- return;
-
- m_verticalVelocity = m_jumpSpeed;
- m_wasJumping = true;
- m_jumps++;
-}
-
-const btVector3& BlenderBulletCharacterController::getWalkDirection()
-{
- return m_walkDirection;
-}
-
-bool CleanPairCallback::processOverlap(btBroadphasePair &pair)
-{
- if ((pair.m_pProxy0 == m_cleanProxy) || (pair.m_pProxy1 == m_cleanProxy)) {
- m_pairCache->cleanOverlappingPair(pair, m_dispatcher);
- CcdPhysicsController *ctrl0 = (CcdPhysicsController*)(((btCollisionObject*)pair.m_pProxy0->m_clientObject)->getUserPointer());
- CcdPhysicsController *ctrl1 = (CcdPhysicsController*)(((btCollisionObject*)pair.m_pProxy1->m_clientObject)->getUserPointer());
- ctrl0->GetCollisionObject()->activate(false);
- ctrl1->GetCollisionObject()->activate(false);
- }
- return false;
-}
-
-CcdPhysicsController::CcdPhysicsController (const CcdConstructionInfo& ci)
-:m_cci(ci)
-{
- m_prototypeTransformInitialized = false;
- m_softbodyMappingDone = false;
- m_collisionDelay = 0;
- m_newClientInfo = 0;
- m_registerCount = 0;
- m_softBodyTransformInitialized = false;
- m_parentCtrl = 0;
- // copy pointers locally to allow smart release
- m_MotionState = ci.m_MotionState;
- m_collisionShape = ci.m_collisionShape;
- // apply scaling before creating rigid body
- m_collisionShape->setLocalScaling(m_cci.m_scaling);
- if (m_cci.m_mass)
- m_collisionShape->calculateLocalInertia(m_cci.m_mass, m_cci.m_localInertiaTensor);
- // shape info is shared, increment ref count
- m_shapeInfo = ci.m_shapeInfo;
- if (m_shapeInfo)
- m_shapeInfo->AddRef();
-
- m_bulletChildShape = NULL;
-
- m_bulletMotionState = 0;
- m_characterController = 0;
- m_savedCollisionFlags = 0;
- m_savedCollisionFilterGroup = 0;
- m_savedCollisionFilterMask = 0;
- m_savedMass = 0.0f;
- m_savedDyna = false;
- m_suspended = false;
-
- CreateRigidbody();
-}
-
-void CcdPhysicsController::addCcdConstraintRef(btTypedConstraint* c)
-{
- int index = m_ccdConstraintRefs.findLinearSearch(c);
- if (index == m_ccdConstraintRefs.size())
- m_ccdConstraintRefs.push_back(c);
-}
-
-void CcdPhysicsController::removeCcdConstraintRef(btTypedConstraint* c)
-{
- m_ccdConstraintRefs.remove(c);
-}
-
-btTypedConstraint* CcdPhysicsController::getCcdConstraintRef(int index)
-{
- return m_ccdConstraintRefs[index];
-}
-
-int CcdPhysicsController::getNumCcdConstraintRefs() const
-{
- return m_ccdConstraintRefs.size();
-}
-
-btTransform& CcdPhysicsController::GetTransformFromMotionState(PHY_IMotionState* motionState)
-{
- static btTransform trans;
- btVector3 tmp;
- motionState->GetWorldPosition(tmp.m_floats[0], tmp.m_floats[1], tmp.m_floats[2]);
- trans.setOrigin(tmp);
-
- float ori[12];
- motionState->GetWorldOrientation(ori);
- trans.getBasis().setFromOpenGLSubMatrix(ori);
- //btQuaternion orn;
- //motionState->getWorldOrientation(orn[0],orn[1],orn[2],orn[3]);
- //trans.setRotation(orn);
- return trans;
-
-}
-
-class BlenderBulletMotionState : public btMotionState
-{
- PHY_IMotionState* m_blenderMotionState;
-
-public:
-
- BlenderBulletMotionState(PHY_IMotionState* bms)
- :m_blenderMotionState(bms)
- {
-
- }
-
- void getWorldTransform(btTransform& worldTrans ) const
- {
- btVector3 pos;
- float ori[12];
-
- m_blenderMotionState->GetWorldPosition(pos.m_floats[0],pos.m_floats[1],pos.m_floats[2]);
- m_blenderMotionState->GetWorldOrientation(ori);
- worldTrans.setOrigin(pos);
- worldTrans.getBasis().setFromOpenGLSubMatrix(ori);
- }
-
- void setWorldTransform(const btTransform& worldTrans)
- {
- m_blenderMotionState->SetWorldPosition(worldTrans.getOrigin().getX(),worldTrans.getOrigin().getY(),worldTrans.getOrigin().getZ());
- btQuaternion rotQuat = worldTrans.getRotation();
- m_blenderMotionState->SetWorldOrientation(rotQuat[0],rotQuat[1],rotQuat[2],rotQuat[3]);
- m_blenderMotionState->CalculateWorldTransformations();
- }
-
-};
-
-btRigidBody* CcdPhysicsController::GetRigidBody()
-{
- return btRigidBody::upcast(m_object);
-}
-const btRigidBody* CcdPhysicsController::GetRigidBody() const
-{
- return btRigidBody::upcast(m_object);
-}
-
-btCollisionObject* CcdPhysicsController::GetCollisionObject()
-{
- return m_object;
-}
-btSoftBody* CcdPhysicsController::GetSoftBody()
-{
- return btSoftBody::upcast(m_object);
-}
-btKinematicCharacterController* CcdPhysicsController::GetCharacterController()
-{
- return m_characterController;
-}
-
-#include "BulletSoftBody/btSoftBodyHelpers.h"
-
-
-bool CcdPhysicsController::CreateSoftbody()
-{
- int shapeType = m_cci.m_collisionShape ? m_cci.m_collisionShape->getShapeType() : 0;
-
- //disable soft body until first sneak preview is ready
- if (!m_cci.m_bSoft || !m_cci.m_collisionShape ||
- ((shapeType != CONVEX_HULL_SHAPE_PROXYTYPE)&&
- (shapeType != TRIANGLE_MESH_SHAPE_PROXYTYPE) &&
- (shapeType != SCALED_TRIANGLE_MESH_SHAPE_PROXYTYPE)))
- {
- return false;
- }
-
- btRigidBody::btRigidBodyConstructionInfo rbci(m_cci.m_mass,m_bulletMotionState,m_collisionShape,m_cci.m_localInertiaTensor * m_cci.m_inertiaFactor);
- rbci.m_linearDamping = m_cci.m_linearDamping;
- rbci.m_angularDamping = m_cci.m_angularDamping;
- rbci.m_friction = m_cci.m_friction;
- rbci.m_restitution = m_cci.m_restitution;
-
- btVector3 p(0.0f,0.0f,0.0f);// = getOrigin();
- //btSoftBody* psb=btSoftBodyHelpers::CreateRope(worldInfo, btVector3(-10,0,i*0.25),btVector3(10,0,i*0.25), 16,1+2);
- btSoftBody* psb = 0;
- btSoftBodyWorldInfo& worldInfo = m_cci.m_physicsEnv->GetDynamicsWorld()->getWorldInfo();
-
- if (m_cci.m_collisionShape->getShapeType() == CONVEX_HULL_SHAPE_PROXYTYPE) {
- btConvexHullShape* convexHull = (btConvexHullShape* )m_cci.m_collisionShape;
- {
- int nvertices = convexHull->getNumPoints();
- const btVector3* vertices = convexHull->getPoints();
-
- HullDesc hdsc(QF_TRIANGLES,nvertices,vertices);
- HullResult hres;
- HullLibrary hlib; /*??*/
- hdsc.mMaxVertices=nvertices;
- hlib.CreateConvexHull(hdsc,hres);
-
- psb = new btSoftBody(&worldInfo, (int)hres.mNumOutputVertices,
- &hres.m_OutputVertices[0], 0);
- for (int i = 0; i < (int)hres.mNumFaces; ++i) {
- const unsigned int idx[3] = {hres.m_Indices[i * 3 + 0],
- hres.m_Indices[i * 3 + 1],
- hres.m_Indices[i * 3 + 2]};
- if (idx[0] < idx[1]) psb->appendLink(idx[0], idx[1]);
- if (idx[1] < idx[2]) psb->appendLink(idx[1], idx[2]);
- if (idx[2] < idx[0]) psb->appendLink(idx[2], idx[0]);
- psb->appendFace(idx[0], idx[1], idx[2]);
- }
- hlib.ReleaseResult(hres);
- }
- }
- else {
- int numtris = 0;
- if (m_cci.m_collisionShape->getShapeType() ==SCALED_TRIANGLE_MESH_SHAPE_PROXYTYPE)
- {
- btScaledBvhTriangleMeshShape* scaledtrimeshshape = (btScaledBvhTriangleMeshShape*) m_cci.m_collisionShape;
- btBvhTriangleMeshShape* trimeshshape = scaledtrimeshshape->getChildShape();
-
- ///only deal with meshes that have 1 sub part/component, for now
- if (trimeshshape->getMeshInterface()->getNumSubParts()==1)
- {
- unsigned char* vertexBase;
- btScalar* scaledVertexBase;
- btVector3 localScaling;
- PHY_ScalarType vertexType;
- int numverts;
- int vertexstride;
- unsigned char* indexbase;
- int indexstride;
- PHY_ScalarType indexType;
- trimeshshape->getMeshInterface()->getLockedVertexIndexBase(&vertexBase,numverts,vertexType,vertexstride,&indexbase,indexstride,numtris,indexType);
- localScaling = scaledtrimeshshape->getLocalScaling();
- scaledVertexBase = new btScalar[numverts*3];
- for (int i=0; i<numverts*3; i+=3)
- {
- scaledVertexBase[i] = ((const btScalar*)vertexBase)[i] * localScaling.getX();
- scaledVertexBase[i+1] = ((const btScalar*)vertexBase)[i+1] * localScaling.getY();
- scaledVertexBase[i+2] = ((const btScalar*)vertexBase)[i+2] * localScaling.getZ();
- }
- psb = btSoftBodyHelpers::CreateFromTriMesh(worldInfo,scaledVertexBase,(const int*)indexbase,numtris,false);
- delete [] scaledVertexBase;
- }
- } else
- {
- btTriangleMeshShape* trimeshshape = (btTriangleMeshShape*) m_cci.m_collisionShape;
- ///only deal with meshes that have 1 sub part/component, for now
- if (trimeshshape->getMeshInterface()->getNumSubParts()==1)
- {
- unsigned char* vertexBase;
- PHY_ScalarType vertexType;
- int numverts;
- int vertexstride;
- unsigned char* indexbase;
- int indexstride;
- PHY_ScalarType indexType;
- trimeshshape->getMeshInterface()->getLockedVertexIndexBase(&vertexBase,numverts,vertexType,vertexstride,&indexbase,indexstride,numtris,indexType);
-
- psb = btSoftBodyHelpers::CreateFromTriMesh(worldInfo,(const btScalar*)vertexBase,(const int*)indexbase,numtris,false);
- }
- }
- // store face tag so that we can find our original face when doing ray casting
- btSoftBody::Face* ft;
- int i;
- for (i=0, ft=&psb->m_faces[0]; i<numtris; ++i, ++ft)
- {
- // Hack!! use m_tag to store the face number, normally it is a pointer
- // add 1 to make sure it is never 0
- ft->m_tag = (void*)((uintptr_t)(i+1));
- }
- }
- if (m_cci.m_margin > 0.f)
- {
- psb->getCollisionShape()->setMargin(m_cci.m_margin);
- psb->updateBounds();
- }
- m_object = psb;
-
- //btSoftBody::Material* pm=psb->appendMaterial();
- btSoftBody::Material* pm=psb->m_materials[0];
- pm->m_kLST = m_cci.m_soft_linStiff;
- pm->m_kAST = m_cci.m_soft_angStiff;
- pm->m_kVST = m_cci.m_soft_volume;
- psb->m_cfg.collisions = 0;
-
- if (m_cci.m_soft_collisionflags & CCD_BSB_COL_CL_RS)
- {
- psb->m_cfg.collisions += btSoftBody::fCollision::CL_RS;
- } else
- {
- psb->m_cfg.collisions += btSoftBody::fCollision::SDF_RS;
- }
- if (m_cci.m_soft_collisionflags & CCD_BSB_COL_CL_SS)
- {
- psb->m_cfg.collisions += btSoftBody::fCollision::CL_SS;
- } else
- {
- psb->m_cfg.collisions += btSoftBody::fCollision::VF_SS;
- }
-
-
- psb->m_cfg.kSRHR_CL = m_cci.m_soft_kSRHR_CL; /* Soft vs rigid hardness [0,1] (cluster only) */
- psb->m_cfg.kSKHR_CL = m_cci.m_soft_kSKHR_CL; /* Soft vs kinetic hardness [0,1] (cluster only) */
- psb->m_cfg.kSSHR_CL = m_cci.m_soft_kSSHR_CL; /* Soft vs soft hardness [0,1] (cluster only) */
- psb->m_cfg.kSR_SPLT_CL = m_cci.m_soft_kSR_SPLT_CL; /* Soft vs rigid impulse split [0,1] (cluster only) */
-
- psb->m_cfg.kSK_SPLT_CL = m_cci.m_soft_kSK_SPLT_CL; /* Soft vs rigid impulse split [0,1] (cluster only) */
- psb->m_cfg.kSS_SPLT_CL = m_cci.m_soft_kSS_SPLT_CL; /* Soft vs rigid impulse split [0,1] (cluster only) */
- psb->m_cfg.kVCF = m_cci.m_soft_kVCF; /* Velocities correction factor (Baumgarte) */
- psb->m_cfg.kDP = m_cci.m_soft_kDP; /* Damping coefficient [0,1] */
-
- psb->m_cfg.kDG = m_cci.m_soft_kDG; /* Drag coefficient [0,+inf] */
- psb->m_cfg.kLF = m_cci.m_soft_kLF; /* Lift coefficient [0,+inf] */
- psb->m_cfg.kPR = m_cci.m_soft_kPR; /* Pressure coefficient [-inf,+inf] */
- psb->m_cfg.kVC = m_cci.m_soft_kVC; /* Volume conversation coefficient [0,+inf] */
-
- psb->m_cfg.kDF = m_cci.m_soft_kDF; /* Dynamic friction coefficient [0,1] */
- psb->m_cfg.kMT = m_cci.m_soft_kMT; /* Pose matching coefficient [0,1] */
- psb->m_cfg.kCHR = m_cci.m_soft_kCHR; /* Rigid contacts hardness [0,1] */
- psb->m_cfg.kKHR = m_cci.m_soft_kKHR; /* Kinetic contacts hardness [0,1] */
-
- psb->m_cfg.kSHR = m_cci.m_soft_kSHR; /* Soft contacts hardness [0,1] */
- psb->m_cfg.kAHR = m_cci.m_soft_kAHR; /* Anchors hardness [0,1] */
-
- if (m_cci.m_gamesoftFlag & CCD_BSB_BENDING_CONSTRAINTS)//OB_SB_GOAL)
- {
- psb->generateBendingConstraints(2,pm);
- }
-
- psb->m_cfg.piterations = m_cci.m_soft_piterations;
- psb->m_cfg.viterations = m_cci.m_soft_viterations;
- psb->m_cfg.diterations = m_cci.m_soft_diterations;
- psb->m_cfg.citerations = m_cci.m_soft_citerations;
-
- if (m_cci.m_gamesoftFlag & CCD_BSB_SHAPE_MATCHING)//OB_SB_GOAL)
- {
- psb->setPose(false,true);//
- } else
- {
- psb->setPose(true,false);
- }
-
- psb->randomizeConstraints();
-
- if (m_cci.m_soft_collisionflags & (CCD_BSB_COL_CL_RS+CCD_BSB_COL_CL_SS))
- {
- psb->generateClusters(m_cci.m_soft_numclusteriterations);
- }
-
- psb->setTotalMass(m_cci.m_mass);
-
- psb->setCollisionFlags(0);
-
- ///create a mapping between graphics mesh vertices and soft body vertices
- {
- RAS_MeshObject* rasMesh= GetShapeInfo()->GetMesh();
-
- if (rasMesh && !m_softbodyMappingDone)
- {
- //printf("apply\n");
- RAS_MeshSlot::iterator it;
- RAS_MeshMaterial *mmat;
- RAS_MeshSlot *slot;
- size_t i;
-
- //for each material
- for (int m=0;m<rasMesh->NumMaterials();m++)
- {
- mmat = rasMesh->GetMeshMaterial(m);
-
- slot = mmat->m_baseslot;
- for (slot->begin(it); !slot->end(it); slot->next(it))
- {
- int index = 0;
- for (i=it.startvertex; i<it.endvertex; i++,index++)
- {
- RAS_TexVert* vertex = &it.vertex[i];
- //search closest index, and store it in vertex
- vertex->setSoftBodyIndex(0);
- btScalar maxDistSqr = 1e30;
- btSoftBody::tNodeArray& nodes(psb->m_nodes);
- btVector3 xyz = btVector3(vertex->getXYZ()[0],vertex->getXYZ()[1],vertex->getXYZ()[2]);
- for (int n=0;n<nodes.size();n++)
- {
- btScalar distSqr = (nodes[n].m_x - xyz).length2();
- if (distSqr<maxDistSqr)
- {
- maxDistSqr = distSqr;
-
- vertex->setSoftBodyIndex(n);
- }
- }
- }
- }
- }
- }
- }
- m_softbodyMappingDone = true;
-
- btTransform startTrans;
- rbci.m_motionState->getWorldTransform(startTrans);
-
- m_MotionState->SetWorldPosition(startTrans.getOrigin().getX(),startTrans.getOrigin().getY(),startTrans.getOrigin().getZ());
- m_MotionState->SetWorldOrientation(0,0,0,1);
-
- if (!m_prototypeTransformInitialized)
- {
- m_prototypeTransformInitialized = true;
- m_softBodyTransformInitialized = true;
- psb->transform(startTrans);
- }
- m_object->setCollisionFlags(m_object->getCollisionFlags() | m_cci.m_collisionFlags);
- if (m_cci.m_do_anisotropic)
- m_object->setAnisotropicFriction(m_cci.m_anisotropicFriction);
- return true;
-}
-
-bool CcdPhysicsController::CreateCharacterController()
-{
- if (!m_cci.m_bCharacter)
- return false;
-
- m_object = new btPairCachingGhostObject();
- m_object->setCollisionShape(m_collisionShape);
- m_object->setCollisionFlags(btCollisionObject::CF_CHARACTER_OBJECT);
-
- btTransform trans;
- m_bulletMotionState->getWorldTransform(trans);
- m_object->setWorldTransform(trans);
-
- m_characterController = new BlenderBulletCharacterController(m_bulletMotionState,(btPairCachingGhostObject*)m_object,(btConvexShape*)m_collisionShape,m_cci.m_stepHeight);
-
- m_characterController->setJumpSpeed(m_cci.m_jumpSpeed);
- m_characterController->setFallSpeed(m_cci.m_fallSpeed);
- m_characterController->setMaxJumps(m_cci.m_maxJumps);
-
- return true;
-}
-
-void CcdPhysicsController::CreateRigidbody()
-{
-
- //btTransform trans = GetTransformFromMotionState(m_MotionState);
- m_bulletMotionState = new BlenderBulletMotionState(m_MotionState);
-
- ///either create a btCollisionObject, btRigidBody or btSoftBody
- if (CreateSoftbody() || CreateCharacterController())
- // soft body created, done
- return;
-
- //create a rgid collision object
- btRigidBody::btRigidBodyConstructionInfo rbci(m_cci.m_mass,m_bulletMotionState,m_collisionShape,m_cci.m_localInertiaTensor * m_cci.m_inertiaFactor);
- rbci.m_linearDamping = m_cci.m_linearDamping;
- rbci.m_angularDamping = m_cci.m_angularDamping;
- rbci.m_friction = m_cci.m_friction;
- rbci.m_restitution = m_cci.m_restitution;
- m_object = new btRigidBody(rbci);
-
- //
- // init the rigidbody properly
- //
-
- //setMassProps this also sets collisionFlags
- //convert collision flags!
- //special case: a near/radar sensor controller should not be defined static or it will
- //generate loads of static-static collision messages on the console
- if (m_cci.m_bSensor)
- {
- // reset the flags that have been set so far
- GetCollisionObject()->setCollisionFlags(0);
- // sensor must never go to sleep: they need to detect continously
- GetCollisionObject()->setActivationState(DISABLE_DEACTIVATION);
- }
- GetCollisionObject()->setCollisionFlags(m_object->getCollisionFlags() | m_cci.m_collisionFlags);
- btRigidBody* body = GetRigidBody();
-
- if (body)
- {
- body->setGravity( m_cci.m_gravity);
- body->setDamping(m_cci.m_linearDamping, m_cci.m_angularDamping);
-
- if (!m_cci.m_bRigid)
- {
- body->setAngularFactor(0.f);
- }
- // use bullet's default contact processing theshold, blender's old default of 1 is too small here.
- // if there's really a need to change this, it should be exposed in the ui first.
-// body->setContactProcessingThreshold(m_cci.m_contactProcessingThreshold);
- body->setSleepingThresholds(gLinearSleepingTreshold, gAngularSleepingTreshold);
-
- }
- if (m_object && m_cci.m_do_anisotropic)
- {
- m_object->setAnisotropicFriction(m_cci.m_anisotropicFriction);
- }
-
-}
-
-static void DeleteBulletShape(btCollisionShape* shape, bool free)
-{
- if (shape->getShapeType() == SCALED_TRIANGLE_MESH_SHAPE_PROXYTYPE) {
- /* If we use Bullet scaled shape (btScaledBvhTriangleMeshShape) we have to
- * free the child of the unscaled shape (btTriangleMeshShape) here.
- */
- btTriangleMeshShape *meshShape = ((btScaledBvhTriangleMeshShape *)shape)->getChildShape();
- if (meshShape)
- delete meshShape;
- }
- if (free) {
- delete shape;
- }
-}
-
-bool CcdPhysicsController::DeleteControllerShape( )
-{
- if (m_collisionShape)
- {
- // collision shape is always unique to the controller, can delete it here
- if (m_collisionShape->isCompound())
- {
- // bullet does not delete the child shape, must do it here
- btCompoundShape* compoundShape = (btCompoundShape*)m_collisionShape;
- int numChild = compoundShape->getNumChildShapes();
- for (int i=numChild-1 ; i >= 0; i--)
- {
- btCollisionShape* childShape = compoundShape->getChildShape(i);
- DeleteBulletShape(childShape, true);
- }
- }
- DeleteBulletShape(m_collisionShape, true);
-
- return true;
- }
-
- return false;
-}
-
-bool CcdPhysicsController::ReplaceControllerShape(btCollisionShape *newShape)
-{
- if (m_collisionShape)
- DeleteControllerShape();
-
- // If newShape is NULL it means to create a new Bullet shape.
- if (!newShape)
- newShape = m_shapeInfo->CreateBulletShape(m_cci.m_margin, m_cci.m_bGimpact, !m_cci.m_bSoft);
-
- m_object->setCollisionShape(newShape);
- m_collisionShape = newShape;
- m_cci.m_collisionShape = newShape;
-
- btSoftBody *softBody = GetSoftBody();
- if (softBody) {
- btSoftRigidDynamicsWorld *world = GetPhysicsEnvironment()->GetDynamicsWorld();
- // remove the old softBody
- world->removeSoftBody(softBody);
-
- // soft body must be recreated
- delete m_object;
- m_object = NULL;
- // force complete reinitialization
- m_softbodyMappingDone = false;
- m_prototypeTransformInitialized = false;
- m_softBodyTransformInitialized = false;
-
- CreateSoftbody();
- assert(m_object);
-
- btSoftBody *newSoftBody = GetSoftBody();
- // set the user
- newSoftBody->setUserPointer(this);
- // add the new softbody
- world->addSoftBody(newSoftBody);
- }
-
- return true;
-}
-
-CcdPhysicsController::~CcdPhysicsController()
-{
- //will be reference counted, due to sharing
- if (m_cci.m_physicsEnv)
- m_cci.m_physicsEnv->RemoveCcdPhysicsController(this);
-
- if (m_MotionState)
- delete m_MotionState;
- if (m_bulletMotionState)
- delete m_bulletMotionState;
- if (m_characterController)
- delete m_characterController;
- delete m_object;
-
- DeleteControllerShape();
-
- if (m_shapeInfo)
- {
- m_shapeInfo->Release();
- }
-}
-
-void CcdPhysicsController::SimulationTick(float timestep)
-{
- btRigidBody *body = GetRigidBody();
- if (!body || body->isStaticObject())
- return;
-
- // Clamp linear velocity
- if (m_cci.m_clamp_vel_max > 0.0f || m_cci.m_clamp_vel_min > 0.0f) {
- const btVector3 &linvel = body->getLinearVelocity();
- btScalar len = linvel.length();
-
- if (m_cci.m_clamp_vel_max > 0.0f && len > m_cci.m_clamp_vel_max)
- body->setLinearVelocity(linvel * (m_cci.m_clamp_vel_max / len));
- else if (m_cci.m_clamp_vel_min > 0.0f && !btFuzzyZero(len) && len < m_cci.m_clamp_vel_min)
- body->setLinearVelocity(linvel * (m_cci.m_clamp_vel_min / len));
- }
-
- // Clamp angular velocity
- if (m_cci.m_clamp_angvel_max > 0.0f || m_cci.m_clamp_angvel_min > 0.0f) {
- const btVector3 &angvel = body->getAngularVelocity();
- btScalar len = angvel.length();
-
- if (m_cci.m_clamp_angvel_max > 0.0f && len > m_cci.m_clamp_angvel_max)
- body->setAngularVelocity(angvel * (m_cci.m_clamp_angvel_max / len));
- else if (m_cci.m_clamp_angvel_min > 0.0f && !btFuzzyZero(len) && len < m_cci.m_clamp_angvel_min)
- body->setAngularVelocity(angvel * (m_cci.m_clamp_angvel_min / len));
- }
-}
-
-
-/**
- * SynchronizeMotionStates ynchronizes dynas, kinematic and deformable entities (and do 'late binding')
- */
-bool CcdPhysicsController::SynchronizeMotionStates(float time)
-{
- //sync non-static to motionstate, and static from motionstate (todo: add kinematic etc.)
-
- btSoftBody* sb = GetSoftBody();
- if (sb)
- {
- if (sb->m_pose.m_bframe)
- {
- btVector3 worldPos = sb->m_pose.m_com;
- btQuaternion worldquat;
- btMatrix3x3 trs = sb->m_pose.m_rot*sb->m_pose.m_scl;
- trs.getRotation(worldquat);
- m_MotionState->SetWorldPosition(worldPos[0],worldPos[1],worldPos[2]);
- m_MotionState->SetWorldOrientation(worldquat[0],worldquat[1],worldquat[2],worldquat[3]);
- }
- else
- {
- btVector3 aabbMin,aabbMax;
- sb->getAabb(aabbMin,aabbMax);
- btVector3 worldPos = (aabbMax+aabbMin)*0.5f;
- m_MotionState->SetWorldPosition(worldPos[0],worldPos[1],worldPos[2]);
- }
- m_MotionState->CalculateWorldTransformations();
- return true;
- }
-
- btRigidBody* body = GetRigidBody();
-
- if (body && !body->isStaticObject())
- {
- const btTransform& xform = body->getCenterOfMassTransform();
- const btMatrix3x3& worldOri = xform.getBasis();
- const btVector3& worldPos = xform.getOrigin();
- float ori[12];
- worldOri.getOpenGLSubMatrix(ori);
- m_MotionState->SetWorldOrientation(ori);
- m_MotionState->SetWorldPosition(worldPos[0],worldPos[1],worldPos[2]);
- m_MotionState->CalculateWorldTransformations();
-
- float scale[3];
- m_MotionState->GetWorldScaling(scale[0],scale[1],scale[2]);
- btVector3 scaling(scale[0],scale[1],scale[2]);
- GetCollisionShape()->setLocalScaling(scaling);
- } else
- {
- btVector3 worldPos;
- btQuaternion worldquat;
-
-/* m_MotionState->getWorldPosition(worldPos[0],worldPos[1],worldPos[2]);
- m_MotionState->getWorldOrientation(worldquat[0],worldquat[1],worldquat[2],worldquat[3]);
- btTransform oldTrans = m_body->getCenterOfMassTransform();
- btTransform newTrans(worldquat,worldPos);
-
- SetCenterOfMassTransform(newTrans);
- //need to keep track of previous position for friction effects...
-
- m_MotionState->calculateWorldTransformations();
-*/
- float scale[3];
- m_MotionState->GetWorldScaling(scale[0],scale[1],scale[2]);
- btVector3 scaling(scale[0],scale[1],scale[2]);
- GetCollisionShape()->setLocalScaling(scaling);
- }
- return true;
-
-}
-
- /**
- * WriteMotionStateToDynamics synchronizes dynas, kinematic and deformable entities (and do 'late binding')
- */
-
-void CcdPhysicsController::WriteMotionStateToDynamics(bool nondynaonly)
-{
- btTransform& xform = CcdPhysicsController::GetTransformFromMotionState(m_MotionState);
- SetCenterOfMassTransform(xform);
-}
-
-void CcdPhysicsController::WriteDynamicsToMotionState()
-{
-}
- // controller replication
-void CcdPhysicsController::PostProcessReplica(class PHY_IMotionState* motionstate,class PHY_IPhysicsController* parentctrl)
-{
- SetParentCtrl((CcdPhysicsController*)parentctrl);
- m_softBodyTransformInitialized=false;
- m_MotionState = motionstate;
- m_registerCount = 0;
- m_collisionShape = NULL;
-
- // Clear all old constraints.
- m_ccdConstraintRefs.clear();
-
- // always create a new shape to avoid scaling bug
- if (m_shapeInfo)
- {
- m_shapeInfo->AddRef();
- m_collisionShape = m_shapeInfo->CreateBulletShape(m_cci.m_margin, m_cci.m_bGimpact, !m_cci.m_bSoft);
-
- if (m_collisionShape)
- {
- // new shape has no scaling, apply initial scaling
- //m_collisionShape->setMargin(m_cci.m_margin);
- m_collisionShape->setLocalScaling(m_cci.m_scaling);
-
- if (m_cci.m_mass)
- m_collisionShape->calculateLocalInertia(m_cci.m_mass, m_cci.m_localInertiaTensor);
- }
- }
-
- // load some characterists that are not
- btRigidBody* oldbody = GetRigidBody();
- m_object = 0;
- CreateRigidbody();
- btRigidBody* body = GetRigidBody();
- if (body)
- {
- if (m_cci.m_mass)
- {
- body->setMassProps(m_cci.m_mass, m_cci.m_localInertiaTensor * m_cci.m_inertiaFactor);
- }
-
- if (oldbody)
- {
- body->setLinearFactor(oldbody->getLinearFactor());
- body->setAngularFactor(oldbody->getAngularFactor());
- if (oldbody->getActivationState() == DISABLE_DEACTIVATION)
- body->setActivationState(DISABLE_DEACTIVATION);
- }
- }
- // sensor object are added when needed
- if (!m_cci.m_bSensor)
- m_cci.m_physicsEnv->AddCcdPhysicsController(this);
-
-
-}
-
-void CcdPhysicsController::SetPhysicsEnvironment(class PHY_IPhysicsEnvironment *env)
-{
- // can safely assume CCD environment
- CcdPhysicsEnvironment *physicsEnv = static_cast<CcdPhysicsEnvironment*>(env);
-
- if (m_cci.m_physicsEnv != physicsEnv)
- {
- // since the environment is changing, we must also move the controler to the
- // new environment. Note that we don't handle sensor explicitly: this
- // function can be called on sensor but only when they are not registered
- if (m_cci.m_physicsEnv->RemoveCcdPhysicsController(this))
- {
- physicsEnv->AddCcdPhysicsController(this);
-
- // Set the object to be active so it can at least by evaluated once.
- // This fixes issues with static objects not having their physics meshes
- // in the right spot when lib loading.
- this->GetCollisionObject()->setActivationState(ACTIVE_TAG);
- }
- m_cci.m_physicsEnv = physicsEnv;
- }
-}
-
-void CcdPhysicsController::SetCenterOfMassTransform(btTransform& xform)
-{
- btRigidBody* body = GetRigidBody();
- if (body)
- {
- body->setCenterOfMassTransform(xform);
- } else
- {
- //either collision object or soft body?
- if (GetSoftBody())
- {
-
- } else
- {
-
- if (m_object->isStaticOrKinematicObject())
- {
- m_object->setInterpolationWorldTransform(m_object->getWorldTransform());
- } else
- {
- m_object->setInterpolationWorldTransform(xform);
- }
- m_object->setWorldTransform(xform);
- }
- }
-}
-
- // kinematic methods
-void CcdPhysicsController::RelativeTranslate(const MT_Vector3& dlocin,bool local)
-{
- if (m_object)
- {
- m_object->activate(true);
- if (m_object->isStaticObject())
- {
- if (!m_cci.m_bSensor)
- m_object->setCollisionFlags(m_object->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT);
- // kinematic object should not set the transform, it disturbs the velocity interpolation
- return;
- }
-
- btVector3 dloc(dlocin.x(), dlocin.y(), dlocin.z());
- btTransform xform = m_object->getWorldTransform();
-
- if (local)
- dloc = xform.getBasis()*dloc;
-
- xform.setOrigin(xform.getOrigin() + dloc);
- SetCenterOfMassTransform(xform);
- }
-
-}
-
-void CcdPhysicsController::RelativeRotate(const MT_Matrix3x3& rotval,bool local)
-{
- if (m_object)
- {
- m_object->activate(true);
- if (m_object->isStaticObject())
- {
- if (!m_cci.m_bSensor)
- m_object->setCollisionFlags(m_object->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT);
- // kinematic object should not set the transform, it disturbs the velocity interpolation
- return;
- }
-
- btMatrix3x3 drotmat(rotval[0].x(), rotval[0].y(), rotval[0].z(),
- rotval[1].x(), rotval[1].y(), rotval[1].z(),
- rotval[2].x(), rotval[2].y(), rotval[2].z());
-
-
- btMatrix3x3 currentOrn;
- GetWorldOrientation(currentOrn);
-
- btTransform xform = m_object->getWorldTransform();
-
- xform.setBasis(xform.getBasis()*(local ?
- drotmat : (currentOrn.inverse() * drotmat * currentOrn)));
-
- SetCenterOfMassTransform(xform);
- }
-}
-
-
-void CcdPhysicsController::GetWorldOrientation(btMatrix3x3& mat)
-{
- float ori[12];
- m_MotionState->GetWorldOrientation(ori);
- mat.setFromOpenGLSubMatrix(ori);
-}
-
-MT_Matrix3x3 CcdPhysicsController::GetOrientation()
-{
- btMatrix3x3 orn = m_object->getWorldTransform().getBasis();
- return MT_Matrix3x3(orn[0][0], orn[0][1], orn[0][2], orn[1][0], orn[1][1], orn[1][2], orn[2][0], orn[2][1], orn[2][2]);
-}
-
-void CcdPhysicsController::SetOrientation(const MT_Matrix3x3& orn)
-{
- btMatrix3x3 btmat(orn[0][0], orn[0][1], orn[0][2], orn[1][0], orn[1][1], orn[1][2], orn[2][0], orn[2][1], orn[2][2]);
- SetWorldOrientation(btmat);
-}
-
-void CcdPhysicsController::SetWorldOrientation(const btMatrix3x3& orn)
-{
- if (m_object)
- {
- m_object->activate(true);
- if (m_object->isStaticObject() && !m_cci.m_bSensor)
- {
- m_object->setCollisionFlags(m_object->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT);
- }
- // not required
- //m_MotionState->setWorldOrientation(quatImag0,quatImag1,quatImag2,quatReal);
- btTransform xform = m_object->getWorldTransform();
- xform.setBasis(orn);
- SetCenterOfMassTransform(xform);
- // not required
- //m_bulletMotionState->setWorldTransform(xform);
- //only once!
- if (!m_softBodyTransformInitialized && GetSoftBody())
- {
- m_softbodyStartTrans.setBasis(orn);
- xform.setOrigin(m_softbodyStartTrans.getOrigin());
- GetSoftBody()->transform(xform);
- m_softBodyTransformInitialized = true;
- }
-
- }
-
-}
-
-void CcdPhysicsController::SetPosition(const MT_Vector3& pos)
-{
- if (m_object)
- {
- m_object->activate(true);
- if (m_object->isStaticObject())
- {
- if (!m_cci.m_bSensor)
- m_object->setCollisionFlags(m_object->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT);
- // kinematic object should not set the transform, it disturbs the velocity interpolation
- return;
- }
- // not required, this function is only used to update the physic controller
- //m_MotionState->setWorldPosition(posX,posY,posZ);
- btTransform xform = m_object->getWorldTransform();
- xform.setOrigin(btVector3(pos.x(), pos.y(), pos.z()));
- SetCenterOfMassTransform(xform);
- if (!m_softBodyTransformInitialized)
- m_softbodyStartTrans.setOrigin(xform.getOrigin());
- // not required
- //m_bulletMotionState->setWorldTransform(xform);
- }
-}
-
-void CcdPhysicsController::ForceWorldTransform(const btMatrix3x3& mat, const btVector3& pos)
-{
- if (m_object)
- {
- btTransform& xform = m_object->getWorldTransform();
- xform.setBasis(mat);
- xform.setOrigin(pos);
- }
-}
-
-
-void CcdPhysicsController::ResolveCombinedVelocities(float linvelX,float linvelY,float linvelZ,float angVelX,float angVelY,float angVelZ)
-{
-}
-
-void CcdPhysicsController::RefreshCollisions()
-{
- // the object is in an inactive layer so it's useless to update it and can cause problems
- if (!GetPhysicsEnvironment()->IsActiveCcdPhysicsController(this))
- return;
-
- btSoftRigidDynamicsWorld *dw = GetPhysicsEnvironment()->GetDynamicsWorld();
- btBroadphaseProxy *proxy = m_object->getBroadphaseHandle();
- btDispatcher *dispatcher = dw->getDispatcher();
- btOverlappingPairCache *pairCache = dw->getPairCache();
-
- CleanPairCallback cleanPairs(proxy, pairCache, dispatcher);
- pairCache->processAllOverlappingPairs(&cleanPairs, dispatcher);
-
- // Forcibly recreate the physics object
- btBroadphaseProxy* handle = m_object->getBroadphaseHandle();
- GetPhysicsEnvironment()->UpdateCcdPhysicsController(this, GetMass(), m_object->getCollisionFlags(), handle->m_collisionFilterGroup, handle->m_collisionFilterMask);
-}
-
-void CcdPhysicsController::SuspendDynamics(bool ghost)
-{
- btRigidBody *body = GetRigidBody();
- if (body && !m_suspended && !GetConstructionInfo().m_bSensor && GetPhysicsEnvironment()->IsActiveCcdPhysicsController(this))
- {
- btBroadphaseProxy* handle = body->getBroadphaseHandle();
-
- m_savedCollisionFlags = body->getCollisionFlags();
- m_savedMass = GetMass();
- m_savedDyna = m_cci.m_bDyna;
- m_savedCollisionFilterGroup = handle->m_collisionFilterGroup;
- m_savedCollisionFilterMask = handle->m_collisionFilterMask;
- m_suspended = true;
- GetPhysicsEnvironment()->UpdateCcdPhysicsController(this,
- 0.0f,
- btCollisionObject::CF_STATIC_OBJECT|((ghost)?btCollisionObject::CF_NO_CONTACT_RESPONSE:(m_savedCollisionFlags&btCollisionObject::CF_NO_CONTACT_RESPONSE)),
- btBroadphaseProxy::StaticFilter,
- btBroadphaseProxy::AllFilter ^ btBroadphaseProxy::StaticFilter);
- m_cci.m_bDyna = false;
- }
-}
-
-void CcdPhysicsController::RestoreDynamics()
-{
- btRigidBody *body = GetRigidBody();
- if (body && m_suspended && GetPhysicsEnvironment()->IsActiveCcdPhysicsController(this))
- {
- // before make sure any position change that was done in this logic frame are accounted for
- SetTransform();
- GetPhysicsEnvironment()->UpdateCcdPhysicsController(this,
- m_savedMass,
- m_savedCollisionFlags,
- m_savedCollisionFilterGroup,
- m_savedCollisionFilterMask);
- body->activate();
- m_cci.m_bDyna = m_savedDyna;
- m_suspended = false;
- }
-}
-
-void CcdPhysicsController::GetPosition(MT_Vector3& pos) const
-{
- const btTransform& xform = m_object->getWorldTransform();
- pos[0] = xform.getOrigin().x();
- pos[1] = xform.getOrigin().y();
- pos[2] = xform.getOrigin().z();
-}
-
-void CcdPhysicsController::SetScaling(const MT_Vector3& scale)
-{
- if (!btFuzzyZero(m_cci.m_scaling.x()-scale.x()) ||
- !btFuzzyZero(m_cci.m_scaling.y()-scale.y()) ||
- !btFuzzyZero(m_cci.m_scaling.z()-scale.z()))
- {
- m_cci.m_scaling = btVector3(scale.x(),scale.y(),scale.z());
-
- if (m_object && m_object->getCollisionShape())
- {
- m_object->activate(true); // without this, sleeping objects scale wont be applied in bullet if python changes the scale - Campbell.
- m_object->getCollisionShape()->setLocalScaling(m_cci.m_scaling);
-
- //printf("no inertia recalc for fixed objects with mass=0\n");
- btRigidBody* body = GetRigidBody();
- if (body && m_cci.m_mass)
- {
- body->getCollisionShape()->calculateLocalInertia(m_cci.m_mass, m_cci.m_localInertiaTensor);
- body->setMassProps(m_cci.m_mass, m_cci.m_localInertiaTensor * m_cci.m_inertiaFactor);
- }
-
- }
- }
-}
-
-void CcdPhysicsController::SetTransform()
-{
- btVector3 pos;
- btVector3 scale;
- float ori[12];
- m_MotionState->GetWorldPosition(pos.m_floats[0],pos.m_floats[1],pos.m_floats[2]);
- m_MotionState->GetWorldScaling(scale.m_floats[0],scale.m_floats[1],scale.m_floats[2]);
- m_MotionState->GetWorldOrientation(ori);
- btMatrix3x3 rot(ori[0], ori[4], ori[8],
- ori[1], ori[5], ori[9],
- ori[2], ori[6], ori[10]);
- ForceWorldTransform(rot, pos);
-
- if (!IsDynamic() && !GetConstructionInfo().m_bSensor && !GetCharacterController())
- {
- btCollisionObject* object = GetRigidBody();
- object->setActivationState(ACTIVE_TAG);
- object->setCollisionFlags(object->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT);
- }
-}
-
-MT_Scalar CcdPhysicsController::GetMass()
-{
- if (GetSoftBody())
- return GetSoftBody()->getTotalMass();
-
- MT_Scalar invmass = 0.f;
- if (GetRigidBody())
- invmass = GetRigidBody()->getInvMass();
- if (invmass)
- return 1.f/invmass;
- return 0.f;
-
-}
-
-void CcdPhysicsController::SetMass(MT_Scalar newmass)
-{
- btRigidBody *body = GetRigidBody();
- if (body && !m_suspended && newmass>MT_EPSILON && GetMass()>MT_EPSILON)
- {
- btBroadphaseProxy* handle = body->getBroadphaseHandle();
- GetPhysicsEnvironment()->UpdateCcdPhysicsController(this,
- newmass,
- body->getCollisionFlags(),
- handle->m_collisionFilterGroup,
- handle->m_collisionFilterMask);
- }
-}
-
- // physics methods
-void CcdPhysicsController::ApplyTorque(const MT_Vector3& torquein,bool local)
-{
- btVector3 torque(torquein.x(),torquein.y(),torquein.z());
- btTransform xform = m_object->getWorldTransform();
-
-
- if (m_object && torque.length2() > (SIMD_EPSILON*SIMD_EPSILON))
- {
- btRigidBody* body = GetRigidBody();
- m_object->activate();
- if (m_object->isStaticObject())
- {
- if (!m_cci.m_bSensor)
- m_object->setCollisionFlags(m_object->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT);
- return;
- }
- if (local)
- {
- torque = xform.getBasis()*torque;
- }
- if (body)
- {
- if (m_cci.m_bRigid)
- {
- body->applyTorque(torque);
- }
- else
- {
- //workaround for incompatibility between 'DYNAMIC' game object, and angular factor
- //a DYNAMIC object has some inconsistency: it has no angular effect due to collisions, but still has torque
- const btVector3 angFac = body->getAngularFactor();
- btVector3 tmpFac(1,1,1);
- body->setAngularFactor(tmpFac);
- body->applyTorque(torque);
- body->setAngularFactor(angFac);
- }
- }
- }
-}
-
-void CcdPhysicsController::ApplyForce(const MT_Vector3& forcein,bool local)
-{
- btVector3 force(forcein.x(),forcein.y(),forcein.z());
-
-
- if (m_object && force.length2() > (SIMD_EPSILON*SIMD_EPSILON))
- {
- m_object->activate();
- if (m_object->isStaticObject())
- {
- if (!m_cci.m_bSensor)
- m_object->setCollisionFlags(m_object->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT);
- return;
- }
- btTransform xform = m_object->getWorldTransform();
-
- if (local)
- {
- force = xform.getBasis()*force;
- }
- btRigidBody* body = GetRigidBody();
- if (body)
- body->applyCentralForce(force);
- btSoftBody* soft = GetSoftBody();
- if (soft)
- {
- // the force is applied on each node, must reduce it in the same extend
- if (soft->m_nodes.size() > 0)
- force /= soft->m_nodes.size();
- soft->addForce(force);
- }
- }
-}
-void CcdPhysicsController::SetAngularVelocity(const MT_Vector3& ang_vel,bool local)
-{
- btVector3 angvel(ang_vel.x(),ang_vel.y(),ang_vel.z());
-
- /* Refuse tiny tiny velocities, as they might cause instabilities. */
- float vel_squared = angvel.length2();
- if (vel_squared > 0 && vel_squared <= (SIMD_EPSILON*SIMD_EPSILON))
- angvel = btVector3(0, 0, 0);
-
- if (m_object)
- {
- m_object->activate(true);
- if (m_object->isStaticObject())
- {
- if (!m_cci.m_bSensor)
- m_object->setCollisionFlags(m_object->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT);
- return;
- }
- btTransform xform = m_object->getWorldTransform();
- if (local)
- {
- angvel = xform.getBasis()*angvel;
- }
- btRigidBody* body = GetRigidBody();
- if (body)
- body->setAngularVelocity(angvel);
- }
-
-}
-void CcdPhysicsController::SetLinearVelocity(const MT_Vector3& lin_vel,bool local)
-{
- btVector3 linVel(lin_vel.x(),lin_vel.y(),lin_vel.z());
-
- /* Refuse tiny tiny velocities, as they might cause instabilities. */
- float vel_squared = linVel.length2();
- if (vel_squared > 0 && vel_squared <= (SIMD_EPSILON*SIMD_EPSILON))
- linVel = btVector3(0, 0, 0);
-
- if (m_object)
- {
- m_object->activate(true);
- if (m_object->isStaticObject())
- {
- if (!m_cci.m_bSensor)
- m_object->setCollisionFlags(m_object->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT);
- return;
- }
-
- btSoftBody* soft = GetSoftBody();
- if (soft)
- {
- if (local)
- {
- linVel = m_softbodyStartTrans.getBasis()*linVel;
- }
- soft->setVelocity(linVel);
- } else
- {
- btTransform xform = m_object->getWorldTransform();
- if (local)
- {
- linVel = xform.getBasis()*linVel;
- }
- btRigidBody* body = GetRigidBody();
- if (body)
- body->setLinearVelocity(linVel);
- }
- }
-}
-void CcdPhysicsController::ApplyImpulse(const MT_Point3& attach, const MT_Vector3& impulsein, bool local)
-{
- btVector3 pos;
- btVector3 impulse(impulsein.x(), impulsein.y(), impulsein.z());
-
- if (m_object && impulse.length2() > (SIMD_EPSILON*SIMD_EPSILON))
- {
- m_object->activate();
- if (m_object->isStaticObject())
- {
- if (!m_cci.m_bSensor)
- m_object->setCollisionFlags(m_object->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT);
- return;
- }
-
- btTransform xform = m_object->getWorldTransform();
-
- if (local)
- {
- pos = btVector3(attach.x(), attach.y(), attach.z());
- impulse = xform.getBasis() * impulse;
- }
- else {
- /* If the point of impulse application is not equal to the object position
- * then an angular momentum is generated in the object*/
- pos = btVector3(attach.x()-xform.getOrigin().x(), attach.y()-xform.getOrigin().y(), attach.z()-xform.getOrigin().z());
- }
-
- btRigidBody* body = GetRigidBody();
- if (body)
- body->applyImpulse(impulse,pos);
-
- }
-
-}
-
-void CcdPhysicsController::Jump()
-{
- if (m_object && m_characterController)
- m_characterController->jump();
-}
-
-void CcdPhysicsController::SetActive(bool active)
-{
-}
-
-float CcdPhysicsController::GetLinearDamping() const
-{
- const btRigidBody* body = GetRigidBody();
- if (body)
- return body->getLinearDamping();
- return 0;
-}
-
-float CcdPhysicsController::GetAngularDamping() const
-{
- const btRigidBody* body = GetRigidBody();
- if (body)
- return body->getAngularDamping();
- return 0;
-}
-
-void CcdPhysicsController::SetLinearDamping(float damping)
-{
- SetDamping(damping, GetAngularDamping());
-}
-
-void CcdPhysicsController::SetAngularDamping(float damping)
-{
- SetDamping(GetLinearDamping(), damping);
-}
-
-void CcdPhysicsController::SetDamping(float linear, float angular)
-{
- btRigidBody* body = GetRigidBody();
- if (!body) return;
-
- body->setDamping(linear, angular);
-}
-
-
- // reading out information from physics
-MT_Vector3 CcdPhysicsController::GetLinearVelocity()
-{
- btRigidBody* body = GetRigidBody();
- if (body)
- {
- const btVector3& linvel = body->getLinearVelocity();
- return MT_Vector3(linvel.x(), linvel.y(), linvel.z());
- }
-
- return MT_Vector3(0.f, 0.f, 0.f);
-}
-
-MT_Vector3 CcdPhysicsController::GetAngularVelocity()
-{
- btRigidBody* body = GetRigidBody();
- if (body)
- {
- const btVector3& angvel= body->getAngularVelocity();
- return MT_Vector3(angvel.x(), angvel.y(), angvel.z());
- }
-
- return MT_Vector3(0.f, 0.f, 0.f);
-}
-
-MT_Vector3 CcdPhysicsController::GetVelocity(const MT_Point3 &posin)
-{
- btVector3 pos(posin.x(), posin.y(), posin.z());
- btRigidBody* body = GetRigidBody();
- if (body)
- {
- btVector3 linvel = body->getVelocityInLocalPoint(pos);
- return MT_Vector3(linvel.x(), linvel.y(), linvel.z());
- }
-
- return MT_Vector3(0.f, 0.f, 0.f);
-}
-
-MT_Vector3 CcdPhysicsController::GetLocalInertia()
-{
- MT_Vector3 inertia(0.f, 0.f, 0.f);
- btVector3 inv_inertia;
- if (GetRigidBody()) {
- inv_inertia = GetRigidBody()->getInvInertiaDiagLocal();
- if (!btFuzzyZero(inv_inertia.getX()) &&
- !btFuzzyZero(inv_inertia.getY()) &&
- !btFuzzyZero(inv_inertia.getZ()))
- inertia = MT_Vector3(1.f/inv_inertia.getX(), 1.f/inv_inertia.getY(), 1.f/inv_inertia.getZ());
- }
- return inertia;
-}
-
- // dyna's that are rigidbody are free in orientation, dyna's with non-rigidbody are restricted
-void CcdPhysicsController::SetRigidBody(bool rigid)
-{
- btRigidBody* body = GetRigidBody();
- if (body)
- {
- m_cci.m_bRigid = rigid;
- if (!rigid) {
- body->setAngularFactor(0.f);
- body->setAngularVelocity(btVector3(0.f, 0.f, 0.f));
- }
- else
- body->setAngularFactor(m_cci.m_angularFactor);
- }
-}
-
- // clientinfo for raycasts for example
-void* CcdPhysicsController::GetNewClientInfo()
-{
- return m_newClientInfo;
-}
-void CcdPhysicsController::SetNewClientInfo(void* clientinfo)
-{
- m_newClientInfo = clientinfo;
-
- if (m_cci.m_bSensor)
- {
- // use a different callback function for sensor object,
- // bullet will not synchronize, we must do it explicitly
- SG_Callbacks& callbacks = KX_GameObject::GetClientObject((KX_ClientObjectInfo*)clientinfo)->GetSGNode()->GetCallBackFunctions();
- callbacks.m_updatefunc = KX_GameObject::SynchronizeTransformFunc;
- }
-}
-
-
-void CcdPhysicsController::UpdateDeactivation(float timeStep)
-{
- btRigidBody* body = GetRigidBody();
- if (body)
- {
- body->updateDeactivation( timeStep);
- }
-}
-
-bool CcdPhysicsController::WantsSleeping()
-{
- btRigidBody* body = GetRigidBody();
- if (body)
- {
- return body->wantsSleeping();
- }
- //check it out
- return true;
-}
-/* This function dynamically adds the collision shape of another controller to
- * the current controller shape provided it is a compound shape.
- * The idea is that dynamic parenting on a compound object will dynamically extend the shape
- */
-void CcdPhysicsController::AddCompoundChild(PHY_IPhysicsController* child)
-{
- if (child == NULL || !IsCompound())
- return;
- // other controller must be a bullet controller too
- // verify that body and shape exist and match
- CcdPhysicsController* childCtrl = dynamic_cast<CcdPhysicsController*>(child);
- btRigidBody* rootBody = GetRigidBody();
- btRigidBody* childBody = childCtrl->GetRigidBody();
- if (!rootBody || !childBody)
- return;
- const btCollisionShape* rootShape = rootBody->getCollisionShape();
- const btCollisionShape* childShape = childBody->getCollisionShape();
- if (!rootShape ||
- !childShape ||
- rootShape->getShapeType() != COMPOUND_SHAPE_PROXYTYPE)
- return;
- btCompoundShape* compoundShape = (btCompoundShape*)rootShape;
- // compute relative transformation between parent and child
- btTransform rootTrans;
- btTransform childTrans;
- rootBody->getMotionState()->getWorldTransform(rootTrans);
- childBody->getMotionState()->getWorldTransform(childTrans);
- btVector3 rootScale = rootShape->getLocalScaling();
- rootScale[0] = 1.0f/rootScale[0];
- rootScale[1] = 1.0f/rootScale[1];
- rootScale[2] = 1.0f/rootScale[2];
- // relative scale = child_scale/parent_scale
- btVector3 relativeScale = childShape->getLocalScaling()*rootScale;
- btMatrix3x3 rootRotInverse = rootTrans.getBasis().transpose();
- // relative pos = parent_rot^-1 * ((parent_pos-child_pos)/parent_scale)
- btVector3 relativePos = rootRotInverse*((childTrans.getOrigin()-rootTrans.getOrigin())*rootScale);
- // relative rot = parent_rot^-1 * child_rot
- btMatrix3x3 relativeRot = rootRotInverse*childTrans.getBasis();
- // create a proxy shape info to store the transformation
- CcdShapeConstructionInfo* proxyShapeInfo = new CcdShapeConstructionInfo();
- // store the transformation to this object shapeinfo
- proxyShapeInfo->m_childTrans.setOrigin(relativePos);
- proxyShapeInfo->m_childTrans.setBasis(relativeRot);
- proxyShapeInfo->m_childScale.setValue(relativeScale[0], relativeScale[1], relativeScale[2]);
- // we will need this to make sure that we remove the right proxy later when unparenting
- proxyShapeInfo->m_userData = childCtrl;
- proxyShapeInfo->SetProxy(childCtrl->GetShapeInfo()->AddRef());
- // add to parent compound shapeinfo (increments ref count)
- GetShapeInfo()->AddShape(proxyShapeInfo);
- // create new bullet collision shape from the object shapeinfo and set scaling
- btCollisionShape* newChildShape = proxyShapeInfo->CreateBulletShape(childCtrl->GetMargin(), childCtrl->GetConstructionInfo().m_bGimpact, true);
- newChildShape->setLocalScaling(relativeScale);
- // add bullet collision shape to parent compound collision shape
- compoundShape->addChildShape(proxyShapeInfo->m_childTrans,newChildShape);
- // proxyShapeInfo is not needed anymore, release it
- proxyShapeInfo->Release();
- // remember we created this shape
- childCtrl->m_bulletChildShape = newChildShape;
- // recompute inertia of parent
- if (!rootBody->isStaticOrKinematicObject())
- {
- btVector3 localInertia;
- float mass = 1.f/rootBody->getInvMass();
- compoundShape->calculateLocalInertia(mass,localInertia);
- rootBody->setMassProps(mass,localInertia);
- }
- // must update the broadphase cache,
- GetPhysicsEnvironment()->RefreshCcdPhysicsController(this);
- // remove the children
- GetPhysicsEnvironment()->RemoveCcdPhysicsController(childCtrl);
-}
-
-/* Reverse function of the above, it will remove a shape from a compound shape
- * provided that the former was added to the later using AddCompoundChild()
- */
-void CcdPhysicsController::RemoveCompoundChild(PHY_IPhysicsController* child)
-{
- if (child == NULL || !IsCompound())
- return;
- // other controller must be a bullet controller too
- // verify that body and shape exist and match
- CcdPhysicsController* childCtrl = dynamic_cast<CcdPhysicsController*>(child);
- btRigidBody* rootBody = GetRigidBody();
- btRigidBody* childBody = childCtrl->GetRigidBody();
- if (!rootBody || !childBody)
- return;
- const btCollisionShape* rootShape = rootBody->getCollisionShape();
- if (!rootShape ||
- rootShape->getShapeType() != COMPOUND_SHAPE_PROXYTYPE)
- return;
- btCompoundShape* compoundShape = (btCompoundShape*)rootShape;
- // retrieve the shapeInfo
- CcdShapeConstructionInfo* childShapeInfo = childCtrl->GetShapeInfo();
- CcdShapeConstructionInfo* rootShapeInfo = GetShapeInfo();
- // and verify that the child is part of the parent
- int i = rootShapeInfo->FindChildShape(childShapeInfo, childCtrl);
- if (i < 0)
- return;
- rootShapeInfo->RemoveChildShape(i);
- if (childCtrl->m_bulletChildShape)
- {
- int numChildren = compoundShape->getNumChildShapes();
- for (i=0; i<numChildren; i++)
- {
- if (compoundShape->getChildShape(i) == childCtrl->m_bulletChildShape)
- {
- compoundShape->removeChildShapeByIndex(i);
- compoundShape->recalculateLocalAabb();
- break;
- }
- }
- delete childCtrl->m_bulletChildShape;
- childCtrl->m_bulletChildShape = NULL;
- }
- // recompute inertia of parent
- if (!rootBody->isStaticOrKinematicObject())
- {
- btVector3 localInertia;
- float mass = 1.f/rootBody->getInvMass();
- compoundShape->calculateLocalInertia(mass,localInertia);
- rootBody->setMassProps(mass,localInertia);
- }
- // must update the broadphase cache,
- GetPhysicsEnvironment()->RefreshCcdPhysicsController(this);
- // reactivate the children
- GetPhysicsEnvironment()->AddCcdPhysicsController(childCtrl);
-}
-
-PHY_IPhysicsController* CcdPhysicsController::GetReplica()
-{
- CcdPhysicsController* replica = new CcdPhysicsController(*this);
- return replica;
-}
-
-// Keeping this separate for now, maybe we can combine it with GetReplica()...
-PHY_IPhysicsController* CcdPhysicsController::GetReplicaForSensors()
-{
- // This is used only to replicate Near and Radar sensor controllers
- // The replication of object physics controller is done in KX_BulletPhysicsController::GetReplica()
- CcdConstructionInfo cinfo = m_cci;
- if (m_shapeInfo)
- {
- // This situation does not normally happen
- cinfo.m_collisionShape = m_shapeInfo->CreateBulletShape(m_cci.m_margin, m_cci.m_bGimpact, !m_cci.m_bSoft);
- }
- else if (m_collisionShape)
- {
- switch (m_collisionShape->getShapeType())
- {
- case SPHERE_SHAPE_PROXYTYPE:
- {
- btSphereShape* orgShape = (btSphereShape*)m_collisionShape;
- cinfo.m_collisionShape = new btSphereShape(*orgShape);
- break;
- }
-
- case CONE_SHAPE_PROXYTYPE:
- {
- btConeShape* orgShape = (btConeShape*)m_collisionShape;
- cinfo.m_collisionShape = new btConeShape(*orgShape);
- break;
- }
-
- default:
- {
- return 0;
- }
- }
- }
-
- cinfo.m_MotionState = new DefaultMotionState();
- cinfo.m_shapeInfo = m_shapeInfo;
-
- CcdPhysicsController* replica = new CcdPhysicsController(cinfo);
- return replica;
-}
-
-/* Refresh the physics object from either an object or a mesh.
- * from_gameobj and from_meshobj can be NULL
- *
- * when setting the mesh, the following vars get priority
- * 1) from_meshobj - creates the phys mesh from RAS_MeshObject
- * 2) from_gameobj - creates the phys mesh from the DerivedMesh where possible, else the RAS_MeshObject
- * 3) this - update the phys mesh from DerivedMesh or RAS_MeshObject
- *
- * Most of the logic behind this is in m_shapeInfo->UpdateMesh(...)
- */
-bool CcdPhysicsController::ReinstancePhysicsShape(KX_GameObject *from_gameobj, RAS_MeshObject *from_meshobj)
-{
- if (m_shapeInfo->m_shapeType != PHY_SHAPE_MESH)
- return false;
-
- if (!from_gameobj && !from_meshobj)
- from_gameobj = KX_GameObject::GetClientObject((KX_ClientObjectInfo*)GetNewClientInfo());
-
- /* updates the arrays used for making the new bullet mesh */
- m_shapeInfo->UpdateMesh(from_gameobj, from_meshobj);
-
- /* create the new bullet mesh */
- GetPhysicsEnvironment()->UpdateCcdPhysicsControllerShape(m_shapeInfo);
-
- return true;
-}
-
-void CcdPhysicsController::ReplicateConstraints(KX_GameObject *replica, std::vector<KX_GameObject*> constobj)
-{
- if (replica->GetConstraints().size() == 0 || !replica->GetPhysicsController())
- return;
-
- PHY_IPhysicsEnvironment *physEnv = GetPhysicsEnvironment();
-
- vector<bRigidBodyJointConstraint*> constraints = replica->GetConstraints();
- vector<bRigidBodyJointConstraint*>::iterator consit;
-
- /* Object could have some constraints, iterate over all of theme to ensure that every constraint is recreated. */
- for (consit = constraints.begin(); consit != constraints.end(); ++consit) {
- /* Try to find the constraint targets in the list of group objects. */
- bRigidBodyJointConstraint *dat = (*consit);
- vector<KX_GameObject*>::iterator memit;
- for (memit = constobj.begin(); memit != constobj.end(); ++memit) {
- KX_GameObject *member = (*memit);
- /* If the group member is the actual target for the constraint. */
- if (dat->tar->id.name + 2 == member->GetName() && member->GetPhysicsController())
- physEnv->SetupObjectConstraints(replica, member, dat);
- }
- }
-
-}
-
-///////////////////////////////////////////////////////////
-///A small utility class, DefaultMotionState
-///
-///////////////////////////////////////////////////////////
-
-DefaultMotionState::DefaultMotionState()
-{
- m_worldTransform.setIdentity();
- m_localScaling.setValue(1.f,1.f,1.f);
-}
-
-
-DefaultMotionState::~DefaultMotionState()
-{
-
-}
-
-void DefaultMotionState::GetWorldPosition(float& posX,float& posY,float& posZ)
-{
- posX = m_worldTransform.getOrigin().x();
- posY = m_worldTransform.getOrigin().y();
- posZ = m_worldTransform.getOrigin().z();
-}
-
-void DefaultMotionState::GetWorldScaling(float& scaleX,float& scaleY,float& scaleZ)
-{
- scaleX = m_localScaling.getX();
- scaleY = m_localScaling.getY();
- scaleZ = m_localScaling.getZ();
-}
-
-void DefaultMotionState::GetWorldOrientation(float& quatIma0,float& quatIma1,float& quatIma2,float& quatReal)
-{
- btQuaternion quat = m_worldTransform.getRotation();
- quatIma0 = quat.x();
- quatIma1 = quat.y();
- quatIma2 = quat.z();
- quatReal = quat[3];
-}
-
-void DefaultMotionState::GetWorldOrientation(float* ori)
-{
- m_worldTransform.getBasis().getOpenGLSubMatrix(ori);
-}
-
-void DefaultMotionState::SetWorldOrientation(const float* ori)
-{
- m_worldTransform.getBasis().setFromOpenGLSubMatrix(ori);
-}
-void DefaultMotionState::SetWorldPosition(float posX,float posY,float posZ)
-{
- btVector3 pos(posX,posY,posZ);
- m_worldTransform.setOrigin( pos );
-}
-
-void DefaultMotionState::SetWorldOrientation(float quatIma0,float quatIma1,float quatIma2,float quatReal)
-{
- btQuaternion orn(quatIma0,quatIma1,quatIma2,quatReal);
- m_worldTransform.setRotation( orn );
-}
-
-void DefaultMotionState::CalculateWorldTransformations()
-{
-
-}
-
-// Shape constructor
-std::map<RAS_MeshObject*, CcdShapeConstructionInfo*> CcdShapeConstructionInfo::m_meshShapeMap;
-
-CcdShapeConstructionInfo* CcdShapeConstructionInfo::FindMesh(RAS_MeshObject* mesh, struct DerivedMesh* dm, bool polytope)
-{
- if (polytope || dm)
- // not yet supported
- return NULL;
-
- std::map<RAS_MeshObject*,CcdShapeConstructionInfo*>::const_iterator mit = m_meshShapeMap.find(mesh);
- if (mit != m_meshShapeMap.end())
- return mit->second;
- return NULL;
-}
-
-bool CcdShapeConstructionInfo::SetMesh(RAS_MeshObject *meshobj, DerivedMesh *dm, bool polytope)
-{
- int numpolys, numverts;
-
- // assume no shape information
- // no support for dynamic change of shape yet
- assert(IsUnused());
- m_shapeType = PHY_SHAPE_NONE;
- m_meshObject = NULL;
- bool free_dm = false;
-
- // No mesh object or mesh has no polys
- if (!meshobj || !meshobj->HasColliderPolygon()) {
- m_vertexArray.clear();
- m_polygonIndexArray.clear();
- m_triFaceArray.clear();
- m_triFaceUVcoArray.clear();
- return false;
- }
-
- if (!dm) {
- free_dm = true;
- dm = CDDM_from_mesh(meshobj->GetMesh());
- }
-
- // Some meshes with modifiers returns 0 polys, call DM_ensure_tessface avoid this.
- DM_ensure_tessface(dm);
-
- MVert *mvert = dm->getVertArray(dm);
- MFace *mface = dm->getTessFaceArray(dm);
- numpolys = dm->getNumTessFaces(dm);
- numverts = dm->getNumVerts(dm);
- MTFace *tface = (MTFace *)dm->getTessFaceDataArray(dm, CD_MTFACE);
-
- /* double lookup */
- const int *index_mf_to_mpoly = (const int *)dm->getTessFaceDataArray(dm, CD_ORIGINDEX);
- const int *index_mp_to_orig = (const int *)dm->getPolyDataArray(dm, CD_ORIGINDEX);
- if (!index_mf_to_mpoly) {
- index_mp_to_orig = NULL;
- }
-
- m_shapeType = (polytope) ? PHY_SHAPE_POLYTOPE : PHY_SHAPE_MESH;
-
- /* Convert blender geometry into bullet mesh, need these vars for mapping */
- std::vector<bool> vert_tag_array(numverts, false);
- unsigned int tot_bt_verts = 0;
-
- if (polytope) {
- // Tag verts we're using
- for (int p2 = 0; p2 < numpolys; p2++) {
- MFace *mf = &mface[p2];
- const int origi = index_mf_to_mpoly ? DM_origindex_mface_mpoly(index_mf_to_mpoly, index_mp_to_orig, p2) : p2;
- RAS_Polygon *poly = (origi != ORIGINDEX_NONE) ? meshobj->GetPolygon(origi) : NULL;
-
- // only add polygons that have the collision flag set
- if (poly && poly->IsCollider()) {
- if (!vert_tag_array[mf->v1]) {
- vert_tag_array[mf->v1] = true;
- tot_bt_verts++;
- }
- if (!vert_tag_array[mf->v2]) {
- vert_tag_array[mf->v2] = true;
- tot_bt_verts++;
- }
- if (!vert_tag_array[mf->v3]) {
- vert_tag_array[mf->v3] = true;
- tot_bt_verts++;
- }
- if (mf->v4 && !vert_tag_array[mf->v4]) {
- vert_tag_array[mf->v4] = true;
- tot_bt_verts++;
- }
- }
- }
-
- /* Can happen with ngons */
- if (!tot_bt_verts) {
- goto cleanup_empty_mesh;
- }
-
- m_vertexArray.resize(tot_bt_verts * 3);
-
- btScalar *bt = &m_vertexArray[0];
-
- for (int p2 = 0; p2 < numpolys; p2++) {
- MFace *mf = &mface[p2];
- const int origi = index_mf_to_mpoly ? DM_origindex_mface_mpoly(index_mf_to_mpoly, index_mp_to_orig, p2) : p2;
- RAS_Polygon *poly = (origi != ORIGINDEX_NONE) ? meshobj->GetPolygon(origi) : NULL;
-
- // only add polygons that have the collisionflag set
- if (poly->IsCollider()) {
- if (vert_tag_array[mf->v1]) {
- const float *vtx = mvert[mf->v1].co;
- vert_tag_array[mf->v1] = false;
- *bt++ = vtx[0];
- *bt++ = vtx[1];
- *bt++ = vtx[2];
- }
- if (vert_tag_array[mf->v2]) {
- const float *vtx = mvert[mf->v2].co;
- vert_tag_array[mf->v2] = false;
- *bt++ = vtx[0];
- *bt++ = vtx[1];
- *bt++ = vtx[2];
- }
- if (vert_tag_array[mf->v3]) {
- const float *vtx = mvert[mf->v3].co;
- vert_tag_array[mf->v3] = false;
- *bt++ = vtx[0];
- *bt++ = vtx[1];
- *bt++ = vtx[2];
- }
- if (mf->v4 && vert_tag_array[mf->v4]) {
- const float *vtx = mvert[mf->v4].co;
- vert_tag_array[mf->v4] = false;
- *bt++ = vtx[0];
- *bt++ = vtx[1];
- *bt++ = vtx[2];
- }
- }
- }
- }
- else {
- unsigned int tot_bt_tris = 0;
- std::vector<int> vert_remap_array(numverts, 0);
-
- // Tag verts we're using
- for (int p2 = 0; p2 < numpolys; p2++) {
- MFace *mf = &mface[p2];
- const int origi = index_mf_to_mpoly ? DM_origindex_mface_mpoly(index_mf_to_mpoly, index_mp_to_orig, p2) : p2;
- RAS_Polygon *poly = (origi != ORIGINDEX_NONE) ? meshobj->GetPolygon(origi) : NULL;
-
- // only add polygons that have the collision flag set
- if (poly && poly->IsCollider()) {
- if (!vert_tag_array[mf->v1]) {
- vert_tag_array[mf->v1] = true;
- vert_remap_array[mf->v1] = tot_bt_verts;
- tot_bt_verts++;
- }
- if (!vert_tag_array[mf->v2]) {
- vert_tag_array[mf->v2] = true;
- vert_remap_array[mf->v2] = tot_bt_verts;
- tot_bt_verts++;
- }
- if (!vert_tag_array[mf->v3]) {
- vert_tag_array[mf->v3] = true;
- vert_remap_array[mf->v3] = tot_bt_verts;
- tot_bt_verts++;
- }
- if (mf->v4 && !vert_tag_array[mf->v4]) {
- vert_tag_array[mf->v4] = true;
- vert_remap_array[mf->v4] = tot_bt_verts;
- tot_bt_verts++;
- }
- tot_bt_tris += (mf->v4 ? 2 : 1); /* a quad or a tri */
- }
- }
-
- /* Can happen with ngons */
- if (!tot_bt_verts) {
- goto cleanup_empty_mesh;
- }
-
- m_vertexArray.resize(tot_bt_verts * 3);
- m_polygonIndexArray.resize(tot_bt_tris);
- m_triFaceArray.resize(tot_bt_tris * 3);
- btScalar *bt = &m_vertexArray[0];
- int *poly_index_pt = &m_polygonIndexArray[0];
- int *tri_pt = &m_triFaceArray[0];
-
- UVco *uv_pt = NULL;
- if (tface) {
- m_triFaceUVcoArray.resize(tot_bt_tris * 3);
- uv_pt = &m_triFaceUVcoArray[0];
- }
- else
- m_triFaceUVcoArray.clear();
-
- for (int p2 = 0; p2 < numpolys; p2++) {
- MFace *mf = &mface[p2];
- MTFace *tf = (tface) ? &tface[p2] : NULL;
- const int origi = index_mf_to_mpoly ? DM_origindex_mface_mpoly(index_mf_to_mpoly, index_mp_to_orig, p2) : p2;
- RAS_Polygon *poly = (origi != ORIGINDEX_NONE) ? meshobj->GetPolygon(origi) : NULL;
-
- // only add polygons that have the collisionflag set
- if (poly && poly->IsCollider()) {
- MVert *v1 = &mvert[mf->v1];
- MVert *v2 = &mvert[mf->v2];
- MVert *v3 = &mvert[mf->v3];
-
- // the face indices
- tri_pt[0] = vert_remap_array[mf->v1];
- tri_pt[1] = vert_remap_array[mf->v2];
- tri_pt[2] = vert_remap_array[mf->v3];
- tri_pt = tri_pt + 3;
- if (tf) {
- uv_pt[0].uv[0] = tf->uv[0][0];
- uv_pt[0].uv[1] = tf->uv[0][1];
- uv_pt[1].uv[0] = tf->uv[1][0];
- uv_pt[1].uv[1] = tf->uv[1][1];
- uv_pt[2].uv[0] = tf->uv[2][0];
- uv_pt[2].uv[1] = tf->uv[2][1];
- uv_pt += 3;
- }
-
- // m_polygonIndexArray
- *poly_index_pt = origi;
- poly_index_pt++;
-
- // the vertex location
- if (vert_tag_array[mf->v1]) { /* *** v1 *** */
- vert_tag_array[mf->v1] = false;
- *bt++ = v1->co[0];
- *bt++ = v1->co[1];
- *bt++ = v1->co[2];
- }
- if (vert_tag_array[mf->v2]) { /* *** v2 *** */
- vert_tag_array[mf->v2] = false;
- *bt++ = v2->co[0];
- *bt++ = v2->co[1];
- *bt++ = v2->co[2];
- }
- if (vert_tag_array[mf->v3]) { /* *** v3 *** */
- vert_tag_array[mf->v3] = false;
- *bt++ = v3->co[0];
- *bt++ = v3->co[1];
- *bt++ = v3->co[2];
- }
-
- if (mf->v4)
- {
- MVert *v4 = &mvert[mf->v4];
-
- tri_pt[0] = vert_remap_array[mf->v1];
- tri_pt[1] = vert_remap_array[mf->v3];
- tri_pt[2] = vert_remap_array[mf->v4];
- tri_pt = tri_pt + 3;
- if (tf)
- {
- uv_pt[0].uv[0] = tf->uv[0][0];
- uv_pt[0].uv[1] = tf->uv[0][1];
- uv_pt[1].uv[0] = tf->uv[2][0];
- uv_pt[1].uv[1] = tf->uv[2][1];
- uv_pt[2].uv[0] = tf->uv[3][0];
- uv_pt[2].uv[1] = tf->uv[3][1];
- uv_pt += 3;
- }
-
- // m_polygonIndexArray
- *poly_index_pt = origi;
- poly_index_pt++;
-
- // the vertex location
- if (vert_tag_array[mf->v4]) { /* *** v4 *** */
- vert_tag_array[mf->v4] = false;
- *bt++ = v4->co[0];
- *bt++ = v4->co[1];
- *bt++ = v4->co[2];
- }
- }
- }
- }
-
-
- /* If this ever gets confusing, print out an OBJ file for debugging */
-#if 0
- printf("# vert count %d\n", m_vertexArray.size());
- for (i = 0; i < m_vertexArray.size(); i += 1) {
- printf("v %.6f %.6f %.6f\n", m_vertexArray[i].x(), m_vertexArray[i].y(), m_vertexArray[i].z());
- }
-
- printf("# face count %d\n", m_triFaceArray.size());
- for (i = 0; i < m_triFaceArray.size(); i += 3) {
- printf("f %d %d %d\n", m_triFaceArray[i] + 1, m_triFaceArray[i + 1] + 1, m_triFaceArray[i + 2] + 1);
- }
-#endif
-
- }
-
-#if 0
- if (validpolys == false)
- {
- // should not happen
- m_shapeType = PHY_SHAPE_NONE;
- return false;
- }
-#endif
-
- m_meshObject = meshobj;
- if (free_dm) {
- dm->release(dm);
- dm = NULL;
- }
-
- // sharing only on static mesh at present, if you change that, you must also change in FindMesh
- if (!polytope && !dm) {
- // triangle shape can be shared, store the mesh object in the map
- m_meshShapeMap.insert(std::pair<RAS_MeshObject *, CcdShapeConstructionInfo *>(meshobj, this));
- }
- return true;
-
-
-cleanup_empty_mesh:
- m_shapeType = PHY_SHAPE_NONE;
- m_meshObject = NULL;
- m_vertexArray.clear();
- m_polygonIndexArray.clear();
- m_triFaceArray.clear();
- m_triFaceUVcoArray.clear();
- if (free_dm) {
- dm->release(dm);
- }
- return false;
-}
-
-#include <cstdio>
-
-/* Updates the arrays used by CreateBulletShape(),
- * take care that recalcLocalAabb() runs after CreateBulletShape is called.
- * */
-bool CcdShapeConstructionInfo::UpdateMesh(class KX_GameObject *gameobj, class RAS_MeshObject *meshobj)
-{
- int numpolys;
- int numverts;
-
- unsigned int tot_bt_tris = 0;
- unsigned int tot_bt_verts = 0;
-
- int i, j;
- int v_orig;
-
- /* Use for looping over verts in a face as a try or 2 tris */
- const int quad_verts[7] = {0, 1, 2, 0, 2, 3, -1};
- const int tri_verts[4] = {0, 1, 2, -1};
- const int *fv_pt;
-
- if (!gameobj && !meshobj)
- return false;
-
- if (m_shapeType != PHY_SHAPE_MESH)
- return false;
-
- RAS_Deformer *deformer = gameobj ? gameobj->GetDeformer() : NULL;
- DerivedMesh *dm = NULL;
-
- if (deformer)
- dm = deformer->GetPhysicsMesh();
-
- /* get the mesh from the object if not defined */
- if (!meshobj) {
- /* modifier mesh */
- if (dm)
- meshobj = deformer->GetRasMesh();
-
- /* game object first mesh */
- if (!meshobj) {
- if (gameobj->GetMeshCount() > 0) {
- meshobj = gameobj->GetMesh(0);
- }
- }
- }
-
- if (dm && deformer->GetRasMesh() == meshobj) {
- /*
- * Derived Mesh Update
- *
- * */
-
- MVert *mvert = dm->getVertArray(dm);
- MFace *mface = dm->getTessFaceArray(dm);
- numpolys = dm->getNumTessFaces(dm);
- numverts = dm->getNumVerts(dm);
-
- /* double lookup */
- const int *index_mf_to_mpoly = (const int *)dm->getTessFaceDataArray(dm, CD_ORIGINDEX);
- const int *index_mp_to_orig = (const int *)dm->getPolyDataArray(dm, CD_ORIGINDEX);
- if (!index_mf_to_mpoly) {
- index_mp_to_orig = NULL;
- }
-
- MFace *mf;
- MVert *mv;
-
- if (CustomData_has_layer(&dm->faceData, CD_MTFACE)) {
- MTFace *tface = (MTFace *)dm->getTessFaceDataArray(dm, CD_MTFACE);
- MTFace *tf;
-
- std::vector<bool> vert_tag_array(numverts, false);
- std::vector<int> vert_remap_array(numverts, 0);
-
- for (mf = mface, tf = tface, i = 0; i < numpolys; mf++, tf++, i++) {
- // 2.8x TODO: use GEMAT_NOPHYSICS.
- // if (tf->mode & TF_DYNAMIC)
- {
- int flen;
-
- if (mf->v4) {
- tot_bt_tris += 2;
- flen = 4;
- }
- else {
- tot_bt_tris++;
- flen = 3;
- }
-
- for (j = 0; j < flen; j++) {
- v_orig = (*(&mf->v1 + j));
-
- if (!vert_tag_array[v_orig]) {
- vert_tag_array[v_orig] = true;
- vert_remap_array[v_orig] = tot_bt_verts;
- tot_bt_verts++;
- }
- }
- }
- }
-
- m_vertexArray.resize(tot_bt_verts * 3);
- btScalar *bt = &m_vertexArray[0];
-
- m_triFaceArray.resize(tot_bt_tris * 3);
- int *tri_pt = &m_triFaceArray[0];
-
- m_triFaceUVcoArray.resize(tot_bt_tris * 3);
- UVco *uv_pt = &m_triFaceUVcoArray[0];
-
- m_polygonIndexArray.resize(tot_bt_tris);
- int *poly_index_pt = &m_polygonIndexArray[0];
-
- for (mf = mface, tf = tface, i = 0; i < numpolys; mf++, tf++, i++) {
- // 2.8x TODO: use GEMAT_NOPHYSICS.
- // if (tf->mode & TF_DYNAMIC)
- {
- int origi = index_mf_to_mpoly ? DM_origindex_mface_mpoly(index_mf_to_mpoly, index_mp_to_orig, i) : i;
-
- if (mf->v4) {
- fv_pt = quad_verts;
- *poly_index_pt++ = origi;
- *poly_index_pt++ = origi;
- }
- else {
- fv_pt = tri_verts;
- *poly_index_pt++ = origi;
- }
-
- for (; *fv_pt > -1; fv_pt++) {
- v_orig = (*(&mf->v1 + (*fv_pt)));
-
- if (vert_tag_array[v_orig])
- {
- mv = mvert + v_orig;
- *bt++ = mv->co[0];
- *bt++ = mv->co[1];
- *bt++ = mv->co[2];
-
- vert_tag_array[v_orig] = false;
- }
- *tri_pt++ = vert_remap_array[v_orig];
- uv_pt->uv[0] = tf->uv[*fv_pt][0];
- uv_pt->uv[1] = tf->uv[*fv_pt][1];
- uv_pt++;
- }
- }
- }
- }
- else {
- /* no need for a vertex mapping. simple/fast */
-
- tot_bt_verts = numverts;
-
- for (mf = mface, i = 0; i < numpolys; mf++, i++) {
- tot_bt_tris += (mf->v4 ? 2 : 1);
- }
-
- m_vertexArray.resize(tot_bt_verts * 3);
- btScalar *bt = &m_vertexArray[0];
-
- m_triFaceArray.resize(tot_bt_tris * 3);
- int *tri_pt = &m_triFaceArray[0];
-
- m_polygonIndexArray.resize(tot_bt_tris);
- int *poly_index_pt = &m_polygonIndexArray[0];
-
- m_triFaceUVcoArray.clear();
-
- for (mv = mvert, i = 0; i < numverts; mv++, i++) {
- *bt++ = mv->co[0]; *bt++ = mv->co[1]; *bt++ = mv->co[2];
- }
-
- for (mf = mface, i = 0; i < numpolys; mf++, i++) {
- int origi = index_mf_to_mpoly ? DM_origindex_mface_mpoly(index_mf_to_mpoly, index_mp_to_orig, i) : i;
-
- if (mf->v4) {
- fv_pt = quad_verts;
- *poly_index_pt++ = origi;
- *poly_index_pt++ = origi;
- }
- else {
- fv_pt = tri_verts;
- *poly_index_pt++ = origi;
- }
-
- for (; *fv_pt > -1; fv_pt++)
- *tri_pt++ = (*(&mf->v1 + (*fv_pt)));
- }
- }
- }
- else { /*
- * RAS Mesh Update
- *
- * */
- /* Note!, gameobj can be NULL here */
-
- /* transverts are only used for deformed RAS_Meshes, the RAS_TexVert data
- * is too hard to get at, see below for details */
- float(*transverts)[3] = NULL;
- int transverts_tot = 0; /* with deformed meshes - should always be greater than the max orginal index, or we get crashes */
-
- if (deformer) {
- /* map locations from the deformed array
- *
- * Could call deformer->Update(); but rely on redraw updating.
- * */
- transverts = deformer->GetTransVerts(&transverts_tot);
- }
-
- // Tag verts we're using
- numpolys = meshobj->NumPolygons();
- numverts = meshobj->m_sharedvertex_map.size();
- const float *xyz;
-
-
- std::vector<bool> vert_tag_array(numverts, false);
- std::vector<int> vert_remap_array(numverts, 0);
-
- for (int p = 0; p < numpolys; p++) {
- RAS_Polygon *poly = meshobj->GetPolygon(p);
- if (poly->IsCollider()) {
- for (i = 0; i < poly->VertexCount(); i++) {
- v_orig = poly->GetVertex(i)->getOrigIndex();
- if (!vert_tag_array[v_orig]) {
- vert_tag_array[v_orig] = true;
- vert_remap_array[v_orig] = tot_bt_verts;
- tot_bt_verts++;
- }
- }
- tot_bt_tris += (poly->VertexCount() == 4 ? 2 : 1);
- }
- }
-
- // This case happens when none of the polys are colliders
- if (tot_bt_tris == 0 || tot_bt_verts == 0)
- return false;
-
- m_vertexArray.resize(tot_bt_verts * 3);
- btScalar *bt = &m_vertexArray[0];
-
- m_triFaceArray.resize(tot_bt_tris * 3);
- int *tri_pt = &m_triFaceArray[0];
-
- /* cant be used for anything useful in this case, since we don't rely on the original mesh
- * will just be an array like pythons range(tot_bt_tris) */
- m_polygonIndexArray.resize(tot_bt_tris);
-
-
- int p = 0;
- int t = 0;
- while (t < tot_bt_tris) {
- RAS_Polygon *poly = meshobj->GetPolygon(p);
-
- if (poly->IsCollider()) {
- /* quad or tri loop */
- fv_pt = (poly->VertexCount() == 3 ? tri_verts : quad_verts);
-
- for (; *fv_pt > -1; fv_pt++) {
- v_orig = poly->GetVertex(*fv_pt)->getOrigIndex();
- if (vert_tag_array[v_orig]) {
- if (transverts) {
- /* deformed mesh, using RAS_TexVert locations would be too troublesome
- * because they are use the gameob as a hash in the material slot */
- *bt++ = transverts[v_orig][0];
- *bt++ = transverts[v_orig][1];
- *bt++ = transverts[v_orig][2];
- }
- else {
- /* static mesh python may have modified */
- xyz = meshobj->GetVertexLocation(v_orig);
- *bt++ = xyz[0];
- *bt++ = xyz[1];
- *bt++ = xyz[2];
- }
- vert_tag_array[v_orig] = false;
- }
- *tri_pt++ = vert_remap_array[v_orig];
- }
- }
- // first triangle
- m_polygonIndexArray[t] = p;
-
- // if the poly is a quad we transform it in two triangles
- if (poly->VertexCount() == 4) {
- t++;
- // second triangle
- m_polygonIndexArray[t] = p;
- }
- t++;
- p++;
- }
- }
-
-#if 0
- /* needs #include <cstdio> */
- printf("# vert count %d\n", m_vertexArray.size());
- for (int i = 0; i < m_vertexArray.size(); i += 3) {
- printf("v %.6f %.6f %.6f\n", m_vertexArray[i], m_vertexArray[i + 1], m_vertexArray[i + 2]);
- }
-
- printf("# face count %d\n", m_triFaceArray.size());
- for (int i = 0; i < m_triFaceArray.size(); i += 3) {
- printf("f %d %d %d\n", m_triFaceArray[i] + 1, m_triFaceArray[i + 1] + 1, m_triFaceArray[i + 2] + 1);
- }
-#endif
-
- /* force recreation of the m_triangleIndexVertexArray.
- * If this has multiple users we cant delete */
- if (m_triangleIndexVertexArray) {
- m_forceReInstance = true;
- }
-
- // Make sure to also replace the mesh in the shape map! Otherwise we leave dangling references when we free.
- // Note, this whole business could cause issues with shared meshes. If we update one mesh, do we replace
- // them all?
- std::map<RAS_MeshObject *, CcdShapeConstructionInfo *>::iterator mit = m_meshShapeMap.find(m_meshObject);
- if (mit != m_meshShapeMap.end()) {
- m_meshShapeMap.erase(mit);
- m_meshShapeMap[meshobj] = this;
- }
-
- m_meshObject = meshobj;
-
- if (dm) {
- dm->needsFree = 1;
- dm->release(dm);
- }
- return true;
-}
-
-bool CcdShapeConstructionInfo::SetProxy(CcdShapeConstructionInfo* shapeInfo)
-{
- if (shapeInfo == NULL)
- return false;
- // no support for dynamic change
- assert(IsUnused());
- m_shapeType = PHY_SHAPE_PROXY;
- m_shapeProxy = shapeInfo;
- return true;
-}
-
-btCollisionShape* CcdShapeConstructionInfo::CreateBulletShape(btScalar margin, bool useGimpact, bool useBvh)
-{
- btCollisionShape* collisionShape = 0;
- btCompoundShape* compoundShape = 0;
-
- if (m_shapeType == PHY_SHAPE_PROXY && m_shapeProxy != NULL)
- return m_shapeProxy->CreateBulletShape(margin, useGimpact, useBvh);
-
- switch (m_shapeType)
- {
- default:
- break;
-
- case PHY_SHAPE_BOX:
- collisionShape = new btBoxShape(m_halfExtend);
- collisionShape->setMargin(margin);
- break;
-
- case PHY_SHAPE_SPHERE:
- collisionShape = new btSphereShape(m_radius);
- collisionShape->setMargin(margin);
- break;
-
- case PHY_SHAPE_CYLINDER:
- collisionShape = new btCylinderShapeZ(m_halfExtend);
- collisionShape->setMargin(margin);
- break;
-
- case PHY_SHAPE_CONE:
- collisionShape = new btConeShapeZ(m_radius, m_height);
- collisionShape->setMargin(margin);
- break;
-
- case PHY_SHAPE_POLYTOPE:
- collisionShape = new btConvexHullShape(&m_vertexArray[0], m_vertexArray.size()/3, 3*sizeof(btScalar));
- collisionShape->setMargin(margin);
- break;
-
- case PHY_SHAPE_CAPSULE:
- collisionShape = new btCapsuleShapeZ(m_radius, m_height);
- collisionShape->setMargin(margin);
- break;
-
- case PHY_SHAPE_MESH:
- // Let's use the latest btScaledBvhTriangleMeshShape: it allows true sharing of
- // triangle mesh information between duplicates => drastic performance increase when
- // duplicating complex mesh objects.
- // BUT it causes a small performance decrease when sharing is not required:
- // 9 multiplications/additions and one function call for each triangle that passes the mid phase filtering
- // One possible optimization is to use directly the btBvhTriangleMeshShape when the scale is 1,1,1
- // and btScaledBvhTriangleMeshShape otherwise.
- if (useGimpact) {
- if (!m_triangleIndexVertexArray || m_forceReInstance) {
- if (m_triangleIndexVertexArray)
- delete m_triangleIndexVertexArray;
-
- m_triangleIndexVertexArray = new btTriangleIndexVertexArray(
- m_polygonIndexArray.size(),
- m_triFaceArray.data(),
- 3 * sizeof(int),
- m_vertexArray.size() / 3,
- &m_vertexArray[0],
- 3 * sizeof(btScalar));
- m_forceReInstance = false;
- }
-
- btGImpactMeshShape *gimpactShape = new btGImpactMeshShape(m_triangleIndexVertexArray);
- gimpactShape->setMargin(margin);
- gimpactShape->updateBound();
- collisionShape = gimpactShape;
- }
- else {
- if (!m_triangleIndexVertexArray || m_forceReInstance) {
- ///enable welding, only for the objects that need it (such as soft bodies)
- if (0.0f != m_weldingThreshold1) {
- btTriangleMesh *collisionMeshData = new btTriangleMesh(true, false);
- collisionMeshData->m_weldingThreshold = m_weldingThreshold1;
- bool removeDuplicateVertices = true;
- // m_vertexArray not in multiple of 3 anymore, use m_triFaceArray
- for (unsigned int i = 0; i < m_triFaceArray.size(); i += 3) {
- btScalar *bt = &m_vertexArray[3 * m_triFaceArray[i]];
- btVector3 v1(bt[0], bt[1], bt[2]);
- bt = &m_vertexArray[3 * m_triFaceArray[i + 1]];
- btVector3 v2(bt[0], bt[1], bt[2]);
- bt = &m_vertexArray[3 * m_triFaceArray[i + 2]];
- btVector3 v3(bt[0], bt[1], bt[2]);
- collisionMeshData->addTriangle(v1, v2, v3, removeDuplicateVertices);
- }
- m_triangleIndexVertexArray = collisionMeshData;
- }
- else {
- m_triangleIndexVertexArray = new btTriangleIndexVertexArray(
- m_polygonIndexArray.size(),
- m_triFaceArray.data(),
- 3 * sizeof(int),
- m_vertexArray.size() / 3,
- &m_vertexArray[0],
- 3 * sizeof(btScalar));
- }
-
- m_forceReInstance = false;
- }
-
- btBvhTriangleMeshShape *unscaledShape = new btBvhTriangleMeshShape(m_triangleIndexVertexArray, true, useBvh);
- unscaledShape->setMargin(margin);
- collisionShape = new btScaledBvhTriangleMeshShape(unscaledShape, btVector3(1.0f, 1.0f, 1.0f));
- collisionShape->setMargin(margin);
- }
- break;
-
- case PHY_SHAPE_COMPOUND:
- if (m_shapeArray.size() > 0)
- {
- compoundShape = new btCompoundShape();
- for (std::vector<CcdShapeConstructionInfo*>::iterator sit = m_shapeArray.begin();
- sit != m_shapeArray.end();
- sit++)
- {
- collisionShape = (*sit)->CreateBulletShape(margin, useGimpact, useBvh);
- if (collisionShape)
- {
- collisionShape->setLocalScaling((*sit)->m_childScale);
- compoundShape->addChildShape((*sit)->m_childTrans, collisionShape);
- }
- }
- collisionShape = compoundShape;
- }
- break;
- }
- return collisionShape;
-}
-
-void CcdShapeConstructionInfo::AddShape(CcdShapeConstructionInfo* shapeInfo)
-{
- m_shapeArray.push_back(shapeInfo);
- shapeInfo->AddRef();
-}
-
-CcdShapeConstructionInfo::~CcdShapeConstructionInfo()
-{
- for (std::vector<CcdShapeConstructionInfo*>::iterator sit = m_shapeArray.begin();
- sit != m_shapeArray.end();
- sit++)
- {
- (*sit)->Release();
- }
- m_shapeArray.clear();
-
- if (m_triangleIndexVertexArray)
- delete m_triangleIndexVertexArray;
- m_vertexArray.clear();
- if (m_shapeType == PHY_SHAPE_MESH && m_meshObject != NULL)
- {
- std::map<RAS_MeshObject*,CcdShapeConstructionInfo*>::iterator mit = m_meshShapeMap.find(m_meshObject);
- if (mit != m_meshShapeMap.end() && mit->second == this)
- {
- m_meshShapeMap.erase(mit);
- }
- }
- if (m_shapeType == PHY_SHAPE_PROXY && m_shapeProxy != NULL)
- {
- m_shapeProxy->Release();
- }
-}
-
diff --git a/source/gameengine/Physics/Bullet/CcdPhysicsController.h b/source/gameengine/Physics/Bullet/CcdPhysicsController.h
deleted file mode 100644
index 831e7346df7..00000000000
--- a/source/gameengine/Physics/Bullet/CcdPhysicsController.h
+++ /dev/null
@@ -1,832 +0,0 @@
-/*
-Bullet Continuous Collision Detection and Physics Library
-Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
-
-This software is provided 'as-is', without any express or implied warranty.
-In no event will the authors be held liable for any damages arising from the use of this software.
-Permission is granted to anyone to use this software for any purpose,
-including commercial applications, and to alter it and redistribute it freely,
-subject to the following restrictions:
-
-1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
-2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
-3. This notice may not be removed or altered from any source distribution.
-*/
-
-/** \file CcdPhysicsController.h
- * \ingroup physbullet
- */
-
-
-#ifndef __CCDPHYSICSCONTROLLER_H__
-#define __CCDPHYSICSCONTROLLER_H__
-
-#include <vector>
-#include <map>
-
-#include "PHY_IPhysicsController.h"
-
-/// PHY_IPhysicsController is the abstract simplified Interface to a physical object.
-/// It contains the IMotionState and IDeformableMesh Interfaces.
-#include "btBulletDynamicsCommon.h"
-#include "BulletDynamics/Character/btKinematicCharacterController.h"
-#include "LinearMath/btTransform.h"
-
-#include "PHY_IMotionState.h"
-#include "PHY_ICharacter.h"
-
-extern float gDeactivationTime;
-extern float gLinearSleepingTreshold;
-extern float gAngularSleepingTreshold;
-extern bool gDisableDeactivation;
-class CcdPhysicsEnvironment;
-class btMotionState;
-class RAS_MeshObject;
-struct DerivedMesh;
-class btCollisionShape;
-
-
-#define CCD_BSB_SHAPE_MATCHING 2
-#define CCD_BSB_BENDING_CONSTRAINTS 8
-#define CCD_BSB_AERO_VPOINT 16 /* aero model, Vertex normals are oriented toward velocity*/
-#define CCD_BSB_AERO_VTWOSIDE 32 /* aero model, Vertex normals are flipped to match velocity */
-
-/* BulletSoftBody.collisionflags */
-#define CCD_BSB_COL_SDF_RS 2 /* SDF based rigid vs soft */
-#define CCD_BSB_COL_CL_RS 4 /* Cluster based rigid vs soft */
-#define CCD_BSB_COL_CL_SS 8 /* Cluster based soft vs soft */
-#define CCD_BSB_COL_VF_SS 16 /* Vertex/Face based soft vs soft */
-
-
-// Shape contructor
-// It contains all the information needed to create a simple bullet shape at runtime
-class CcdShapeConstructionInfo
-{
-public:
- struct UVco
- {
- float uv[2];
- };
-
- static CcdShapeConstructionInfo* FindMesh(class RAS_MeshObject* mesh, struct DerivedMesh* dm, bool polytope);
-
- CcdShapeConstructionInfo() :
- m_shapeType(PHY_SHAPE_NONE),
- m_radius(1.0f),
- m_height(1.0f),
- m_halfExtend(0.f,0.f,0.f),
- m_childScale(1.0f,1.0f,1.0f),
- m_userData(NULL),
- m_refCount(1),
- m_meshObject(NULL),
- m_triangleIndexVertexArray(NULL),
- m_forceReInstance(false),
- m_weldingThreshold1(0.f),
- m_shapeProxy(NULL)
- {
- m_childTrans.setIdentity();
- }
-
- ~CcdShapeConstructionInfo();
-
- CcdShapeConstructionInfo* AddRef()
- {
- m_refCount++;
- return this;
- }
-
- int Release()
- {
- if (--m_refCount > 0)
- return m_refCount;
- delete this;
- return 0;
- }
-
- bool IsUnused(void)
- {
- return (m_meshObject==NULL && m_shapeArray.size() == 0 && m_shapeProxy == NULL);
- }
-
- void AddShape(CcdShapeConstructionInfo* shapeInfo);
-
- btStridingMeshInterface *GetMeshInterface()
- {
- return m_triangleIndexVertexArray;
- }
-
- CcdShapeConstructionInfo* GetChildShape(int i)
- {
- if (i < 0 || i >= (int)m_shapeArray.size())
- return NULL;
-
- return m_shapeArray.at(i);
- }
- int FindChildShape(CcdShapeConstructionInfo* shapeInfo, void* userData)
- {
- if (shapeInfo == NULL)
- return -1;
- for (int i=0; i<(int)m_shapeArray.size(); i++)
- {
- CcdShapeConstructionInfo* childInfo = m_shapeArray.at(i);
- if ((userData == NULL || userData == childInfo->m_userData) &&
- (childInfo == shapeInfo ||
- (childInfo->m_shapeType == PHY_SHAPE_PROXY &&
- childInfo->m_shapeProxy == shapeInfo)))
- return i;
- }
- return -1;
- }
-
- bool RemoveChildShape(int i)
- {
- if (i < 0 || i >= (int)m_shapeArray.size())
- return false;
- m_shapeArray.at(i)->Release();
- if (i < (int)m_shapeArray.size()-1)
- m_shapeArray[i] = m_shapeArray.back();
- m_shapeArray.pop_back();
- return true;
- }
-
- bool SetMesh(class RAS_MeshObject* mesh, struct DerivedMesh* dm, bool polytope);
- RAS_MeshObject* GetMesh(void)
- {
- return m_meshObject;
- }
-
- bool UpdateMesh(class KX_GameObject* gameobj, class RAS_MeshObject* mesh);
-
-
- bool SetProxy(CcdShapeConstructionInfo* shapeInfo);
- CcdShapeConstructionInfo* GetProxy(void)
- {
- return m_shapeProxy;
- }
-
- btCollisionShape* CreateBulletShape(btScalar margin, bool useGimpact=false, bool useBvh=true);
-
- // member variables
- PHY_ShapeType m_shapeType;
- btScalar m_radius;
- btScalar m_height;
- btVector3 m_halfExtend;
- btTransform m_childTrans;
- btVector3 m_childScale;
- void* m_userData;
- btAlignedObjectArray<btScalar> m_vertexArray; // Contains both vertex array for polytope shape and
- // triangle array for concave mesh shape. Each vertex is 3 consecutive values
- // In this case a triangle is made of 3 consecutive points
- std::vector<int> m_polygonIndexArray; // Contains the array of polygon index in the
- // original mesh that correspond to shape triangles.
- // only set for concave mesh shape.
-
- std::vector<int> m_triFaceArray; // Contains an array of triplets of face indices
- // quads turn into 2 tris
-
- std::vector<UVco> m_triFaceUVcoArray; // Contains an array of pair of UV coordinate for each vertex of faces
- // quads turn into 2 tris
-
- void setVertexWeldingThreshold1(float threshold)
- {
- m_weldingThreshold1 = threshold*threshold;
- }
-protected:
- static std::map<RAS_MeshObject*, CcdShapeConstructionInfo*> m_meshShapeMap;
- int m_refCount; // this class is shared between replicas
- // keep track of users so that we can release it
- RAS_MeshObject* m_meshObject; // Keep a pointer to the original mesh
- // The list of vertexes and indexes for the triangle mesh, shared between Bullet shape.
- btTriangleIndexVertexArray *m_triangleIndexVertexArray;
- std::vector<CcdShapeConstructionInfo*> m_shapeArray; // for compound shapes
- bool m_forceReInstance; //use gimpact for concave dynamic/moving collision detection
- float m_weldingThreshold1; //welding closeby vertices together can improve softbody stability etc.
- CcdShapeConstructionInfo* m_shapeProxy; // only used for PHY_SHAPE_PROXY, pointer to actual shape info
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:CcdShapeConstructionInfo")
-#endif
-};
-
-struct CcdConstructionInfo
-{
-
- ///CollisionFilterGroups provides some optional usage of basic collision filtering
- ///this is done during broadphase, so very early in the pipeline
- ///more advanced collision filtering should be done in btCollisionDispatcher::NeedsCollision
- enum CollisionFilterGroups
- {
- DefaultFilter = 1,
- StaticFilter = 2,
- KinematicFilter = 4,
- DebrisFilter = 8,
- SensorFilter = 16,
- CharacterFilter = 32,
- AllFilter = DefaultFilter | StaticFilter | KinematicFilter | DebrisFilter | SensorFilter | CharacterFilter,
- };
-
-
- CcdConstructionInfo()
- :m_localInertiaTensor(1.f, 1.f, 1.f),
- m_gravity(0,0,0),
- m_scaling(1.f,1.f,1.f),
- m_linearFactor(0.f, 0.f, 0.f),
- m_angularFactor(0.f, 0.f, 0.f),
- m_mass(0.f),
- m_clamp_vel_min(-1.f),
- m_clamp_vel_max(-1.f),
- m_clamp_angvel_min(0.0f),
- m_clamp_angvel_max(0.0f),
- m_restitution(0.1f),
- m_friction(0.5f),
- m_linearDamping(0.1f),
- m_angularDamping(0.1f),
- m_margin(0.06f),
- m_gamesoftFlag(0),
- m_soft_linStiff(1.f),
- m_soft_angStiff(1.f),
- m_soft_volume(1.f),
- m_soft_viterations(0),
- m_soft_piterations(1),
- m_soft_diterations(0),
- m_soft_citerations(4),
- m_soft_kSRHR_CL(0.1f),
- m_soft_kSKHR_CL(1.f),
- m_soft_kSSHR_CL(0.5f),
- m_soft_kSR_SPLT_CL(0.5f),
- m_soft_kSK_SPLT_CL(0.5f),
- m_soft_kSS_SPLT_CL(0.5f),
- m_soft_kVCF(1.f),
- m_soft_kDP(0.f),
- m_soft_kDG(0.f),
- m_soft_kLF(0.f),
- m_soft_kPR(0.f),
- m_soft_kVC(0.f),
- m_soft_kDF(0.2f),
- m_soft_kMT(0),
- m_soft_kCHR(1.0f),
- m_soft_kKHR(0.1f),
- m_soft_kSHR(1.0f),
- m_soft_kAHR(0.7f),
- m_collisionFlags(0),
- m_bDyna(false),
- m_bRigid(false),
- m_bSoft(false),
- m_bSensor(false),
- m_bCharacter(false),
- m_bGimpact(false),
- m_collisionFilterGroup(DefaultFilter),
- m_collisionFilterMask(AllFilter),
- m_collisionShape(0),
- m_MotionState(0),
- m_shapeInfo(0),
- m_physicsEnv(0),
- m_inertiaFactor(1.f),
- m_do_anisotropic(false),
- m_anisotropicFriction(1.f,1.f,1.f),
- m_do_fh(false),
- m_do_rot_fh(false),
- m_fh_spring(0.f),
- m_fh_damping(0.f),
- m_fh_distance(1.f),
- m_fh_normal(false)
- // m_contactProcessingThreshold(1e10f)
- {
-
- }
-
- btVector3 m_localInertiaTensor;
- btVector3 m_gravity;
- btVector3 m_scaling;
- btVector3 m_linearFactor;
- btVector3 m_angularFactor;
- btScalar m_mass;
- btScalar m_clamp_vel_min;
- btScalar m_clamp_vel_max;
- btScalar m_clamp_angvel_min; // Minimum angular velocity, in radians/sec.
- btScalar m_clamp_angvel_max; // Maximum angular velocity, in radians/sec.
- btScalar m_restitution;
- btScalar m_friction;
- btScalar m_linearDamping;
- btScalar m_angularDamping;
- btScalar m_margin;
-
- ////////////////////
- float m_stepHeight;
- float m_jumpSpeed;
- float m_fallSpeed;
- unsigned char m_maxJumps;
-
- int m_gamesoftFlag;
- float m_soft_linStiff; /* linear stiffness 0..1 */
- float m_soft_angStiff; /* angular stiffness 0..1 */
- float m_soft_volume; /* volume preservation 0..1 */
-
- int m_soft_viterations; /* Velocities solver iterations */
- int m_soft_piterations; /* Positions solver iterations */
- int m_soft_diterations; /* Drift solver iterations */
- int m_soft_citerations; /* Cluster solver iterations */
-
- float m_soft_kSRHR_CL; /* Soft vs rigid hardness [0,1] (cluster only) */
- float m_soft_kSKHR_CL; /* Soft vs kinetic hardness [0,1] (cluster only) */
- float m_soft_kSSHR_CL; /* Soft vs soft hardness [0,1] (cluster only) */
- float m_soft_kSR_SPLT_CL; /* Soft vs rigid impulse split [0,1] (cluster only) */
-
- float m_soft_kSK_SPLT_CL; /* Soft vs rigid impulse split [0,1] (cluster only) */
- float m_soft_kSS_SPLT_CL; /* Soft vs rigid impulse split [0,1] (cluster only) */
- float m_soft_kVCF; /* Velocities correction factor (Baumgarte) */
- float m_soft_kDP; /* Damping coefficient [0,1] */
-
- float m_soft_kDG; /* Drag coefficient [0,+inf] */
- float m_soft_kLF; /* Lift coefficient [0,+inf] */
- float m_soft_kPR; /* Pressure coefficient [-inf,+inf] */
- float m_soft_kVC; /* Volume conversation coefficient [0,+inf] */
-
- float m_soft_kDF; /* Dynamic friction coefficient [0,1] */
- float m_soft_kMT; /* Pose matching coefficient [0,1] */
- float m_soft_kCHR; /* Rigid contacts hardness [0,1] */
- float m_soft_kKHR; /* Kinetic contacts hardness [0,1] */
-
- float m_soft_kSHR; /* Soft contacts hardness [0,1] */
- float m_soft_kAHR; /* Anchors hardness [0,1] */
- int m_soft_collisionflags; /* Vertex/Face or Signed Distance Field(SDF) or Clusters, Soft versus Soft or Rigid */
- int m_soft_numclusteriterations; /* number of iterations to refine collision clusters*/
-///////////////////
-
-
-
- int m_collisionFlags;
- bool m_bDyna;
- bool m_bRigid;
- bool m_bSoft;
- bool m_bSensor;
- bool m_bCharacter;
- bool m_bGimpact; // use Gimpact for mesh body
-
- ///optional use of collision group/mask:
- ///only collision with object goups that match the collision mask.
- ///this is very basic early out. advanced collision filtering should be
- ///done in the btCollisionDispatcher::NeedsCollision and NeedsResponse
- ///both values default to 1
- short int m_collisionFilterGroup;
- short int m_collisionFilterMask;
-
- ///these pointers are used as argument passing for the CcdPhysicsController constructor
- ///and not anymore after that
- class btCollisionShape* m_collisionShape;
- class PHY_IMotionState* m_MotionState;
- class CcdShapeConstructionInfo* m_shapeInfo;
-
- CcdPhysicsEnvironment* m_physicsEnv; //needed for self-replication
- float m_inertiaFactor;//tweak the inertia (hooked up to Blender 'formfactor'
- bool m_do_anisotropic;
- btVector3 m_anisotropicFriction;
-
- bool m_do_fh; ///< Should the object have a linear Fh spring?
- bool m_do_rot_fh; ///< Should the object have an angular Fh spring?
- btScalar m_fh_spring; ///< Spring constant (both linear and angular)
- btScalar m_fh_damping; ///< Damping factor (linear and angular) in range [0, 1]
- btScalar m_fh_distance; ///< The range above the surface where Fh is active.
- bool m_fh_normal; ///< Should the object slide off slopes?
- float m_radius;//for fh backwards compatibility
-
- ///m_contactProcessingThreshold allows to process contact points with positive distance
- ///normally only contacts with negative distance (penetration) are solved
- ///however, rigid body stacking is more stable when positive contacts are still passed into the constraint solver
- ///this might sometimes lead to collisions with 'internal edges' such as a sliding character controller
- ///so disable/set m_contactProcessingThreshold to zero for sliding characters etc.
- // float m_contactProcessingThreshold;///< Process contacts with positive distance in range [0..INF]
-};
-
-class btRigidBody;
-class btCollisionObject;
-class btSoftBody;
-class btPairCachingGhostObject;
-
-class BlenderBulletCharacterController : public btKinematicCharacterController, public PHY_ICharacter
-{
-private:
- btMotionState* m_motionState;
- unsigned char m_jumps;
- unsigned char m_maxJumps;
-
-public:
- BlenderBulletCharacterController(btMotionState *motionState, btPairCachingGhostObject *ghost, btConvexShape* shape, float stepHeight);
-
- virtual void updateAction(btCollisionWorld *collisionWorld, btScalar dt);
-
- unsigned char getMaxJumps() const;
-
- void setMaxJumps(unsigned char maxJumps);
-
- unsigned char getJumpCount() const;
-
- virtual bool canJump() const;
-
- virtual void jump();
-
- const btVector3& getWalkDirection();
-
- // PHY_ICharacter interface
- virtual void Jump() { jump(); }
- virtual bool OnGround() { return onGround(); }
- virtual float GetGravity() { return getGravity(); }
- virtual void SetGravity(float gravity) { setGravity(gravity); }
- virtual unsigned char GetMaxJumps() { return getMaxJumps(); }
- virtual void SetMaxJumps(unsigned char maxJumps) { setMaxJumps(maxJumps); }
- virtual unsigned char GetJumpCount() { return getJumpCount(); }
- virtual void SetWalkDirection(const MT_Vector3& dir)
- {
- btVector3 vec = btVector3(dir[0], dir[1], dir[2]);
- setWalkDirection(vec);
- }
- virtual MT_Vector3 GetWalkDirection()
- {
- btVector3 vec = getWalkDirection();
- return MT_Vector3(vec[0], vec[1], vec[2]);
- }
-
-#ifdef WITH_CXX_GUARDEDALLOC
- using PHY_ICharacter::operator new;
- using PHY_ICharacter::operator delete;
-#endif
-};
-
-class CleanPairCallback : public btOverlapCallback
-{
- btBroadphaseProxy *m_cleanProxy;
- btOverlappingPairCache *m_pairCache;
- btDispatcher *m_dispatcher;
-
-public:
- CleanPairCallback(btBroadphaseProxy *cleanProxy, btOverlappingPairCache *pairCache, btDispatcher *dispatcher)
- :m_cleanProxy(cleanProxy),
- m_pairCache(pairCache),
- m_dispatcher(dispatcher)
- {
- }
-
- virtual bool processOverlap(btBroadphasePair &pair);
-};
-
-///CcdPhysicsController is a physics object that supports continuous collision detection and time of impact based physics resolution.
-class CcdPhysicsController : public PHY_IPhysicsController
-{
-protected:
- btCollisionObject* m_object;
- BlenderBulletCharacterController* m_characterController;
-
-
- class PHY_IMotionState* m_MotionState;
- btMotionState* m_bulletMotionState;
- class btCollisionShape* m_collisionShape;
- class CcdShapeConstructionInfo* m_shapeInfo;
- btCollisionShape* m_bulletChildShape;
-
- btAlignedObjectArray<btTypedConstraint*> m_ccdConstraintRefs; // keep track of typed constraints referencing this rigid body
- friend class CcdPhysicsEnvironment; // needed when updating the controller
-
- //some book keeping for replication
- bool m_softbodyMappingDone;
- bool m_softBodyTransformInitialized;
- bool m_prototypeTransformInitialized;
- btTransform m_softbodyStartTrans;
-
-
- void* m_newClientInfo;
- int m_registerCount; // needed when multiple sensors use the same controller
- CcdConstructionInfo m_cci;//needed for replication
-
- CcdPhysicsController* m_parentCtrl;
-
- int m_savedCollisionFlags;
- short m_savedCollisionFilterGroup;
- short m_savedCollisionFilterMask;
- MT_Scalar m_savedMass;
- bool m_savedDyna;
- bool m_suspended;
-
-
- void GetWorldOrientation(btMatrix3x3& mat);
-
- void CreateRigidbody();
- bool CreateSoftbody();
- bool CreateCharacterController();
-
- bool Register() {
- return (m_registerCount++ == 0) ? true : false;
- }
- bool Unregister() {
- return (--m_registerCount == 0) ? true : false;
- }
-
- bool Registered() const
- {
- return (m_registerCount != 0);
- }
-
- void addCcdConstraintRef(btTypedConstraint* c);
- void removeCcdConstraintRef(btTypedConstraint* c);
- btTypedConstraint* getCcdConstraintRef(int index);
- int getNumCcdConstraintRefs() const;
-
- void SetWorldOrientation(const btMatrix3x3& mat);
- void ForceWorldTransform(const btMatrix3x3& mat, const btVector3& pos);
-
- public:
-
- int m_collisionDelay;
-
-
- CcdPhysicsController (const CcdConstructionInfo& ci);
-
- /**
- * Delete the current Bullet shape used in the rigid body.
- */
- bool DeleteControllerShape();
-
- /**
- * Delete the old Bullet shape and set the new Bullet shape : newShape
- * \param newShape The new Bullet shape to set, if is NULL we create a new Bullet shape
- */
- bool ReplaceControllerShape(btCollisionShape *newShape);
-
- virtual ~CcdPhysicsController();
-
- CcdConstructionInfo& GetConstructionInfo()
- {
- return m_cci;
- }
- const CcdConstructionInfo& GetConstructionInfo() const
- {
- return m_cci;
- }
-
-
- btRigidBody* GetRigidBody();
- const btRigidBody* GetRigidBody() const;
- btCollisionObject* GetCollisionObject();
- btSoftBody* GetSoftBody();
- btKinematicCharacterController* GetCharacterController();
-
- CcdShapeConstructionInfo* GetShapeInfo() { return m_shapeInfo; }
-
- btCollisionShape* GetCollisionShape() {
- return m_object->getCollisionShape();
- }
- ////////////////////////////////////
- // PHY_IPhysicsController interface
- ////////////////////////////////////
-
-
- /**
- * SynchronizeMotionStates ynchronizes dynas, kinematic and deformable entities (and do 'late binding')
- */
- virtual bool SynchronizeMotionStates(float time);
-
- /**
- * Called for every physics simulation step. Use this method for
- * things like limiting linear and angular velocity.
- */
- void SimulationTick(float timestep);
-
- /**
- * WriteMotionStateToDynamics ynchronizes dynas, kinematic and deformable entities (and do 'late binding')
- */
-
- virtual void WriteMotionStateToDynamics(bool nondynaonly);
- virtual void WriteDynamicsToMotionState();
-
- // controller replication
- virtual void PostProcessReplica(class PHY_IMotionState* motionstate,class PHY_IPhysicsController* parentctrl);
- virtual void SetPhysicsEnvironment(class PHY_IPhysicsEnvironment *env);
-
- // kinematic methods
- virtual void RelativeTranslate(const MT_Vector3& dloc,bool local);
- virtual void RelativeRotate(const MT_Matrix3x3&rotval, bool local);
- virtual MT_Matrix3x3 GetOrientation();
- virtual void SetOrientation(const MT_Matrix3x3& orn);
- virtual void SetPosition(const MT_Vector3& pos);
- virtual void GetPosition(MT_Vector3& pos) const;
- virtual void SetScaling(const MT_Vector3& scale);
- virtual void SetTransform();
-
- virtual MT_Scalar GetMass();
- virtual void SetMass(MT_Scalar newmass);
-
- // physics methods
- virtual void ApplyImpulse(const MT_Point3& attach, const MT_Vector3& impulsein, bool local);
- virtual void ApplyTorque(const MT_Vector3& torque,bool local);
- virtual void ApplyForce(const MT_Vector3& force,bool local);
- virtual void SetAngularVelocity(const MT_Vector3& ang_vel,bool local);
- virtual void SetLinearVelocity(const MT_Vector3& lin_vel,bool local);
- virtual void Jump();
- virtual void SetActive(bool active);
-
- virtual float GetLinearDamping() const;
- virtual float GetAngularDamping() const;
- virtual void SetLinearDamping(float damping);
- virtual void SetAngularDamping(float damping);
- virtual void SetDamping(float linear, float angular);
-
- // reading out information from physics
- virtual MT_Vector3 GetLinearVelocity();
- virtual MT_Vector3 GetAngularVelocity();
- virtual MT_Vector3 GetVelocity(const MT_Point3& posin);
- virtual MT_Vector3 GetLocalInertia();
-
- // dyna's that are rigidbody are free in orientation, dyna's with non-rigidbody are restricted
- virtual void SetRigidBody(bool rigid);
-
-
- virtual void ResolveCombinedVelocities(float linvelX,float linvelY,float linvelZ,float angVelX,float angVelY,float angVelZ);
- virtual void RefreshCollisions();
- virtual void SuspendDynamics(bool ghost);
- virtual void RestoreDynamics();
-
- // Shape control
- virtual void AddCompoundChild(PHY_IPhysicsController* child);
- virtual void RemoveCompoundChild(PHY_IPhysicsController* child);
-
- // clientinfo for raycasts for example
- virtual void* GetNewClientInfo();
- virtual void SetNewClientInfo(void* clientinfo);
- virtual PHY_IPhysicsController* GetReplica();
- virtual PHY_IPhysicsController* GetReplicaForSensors();
-
- ///There should be no 'SetCollisionFilterGroup' method, as changing this during run-time is will result in errors
- short int GetCollisionFilterGroup() const
- {
- return m_cci.m_collisionFilterGroup;
- }
- ///There should be no 'SetCollisionFilterGroup' method, as changing this during run-time is will result in errors
- short int GetCollisionFilterMask() const
- {
- return m_cci.m_collisionFilterMask;
- }
-
- virtual void CalcXform() {}
- virtual void SetMargin(float margin)
- {
- if (m_collisionShape) {
- m_collisionShape->setMargin(margin);
- // if the shape use a unscaled shape we have also to set the correct margin in it
- if (m_collisionShape->getShapeType() == SCALED_TRIANGLE_MESH_SHAPE_PROXYTYPE)
- ((btScaledBvhTriangleMeshShape *)m_collisionShape)->getChildShape()->setMargin(margin);
- }
- }
- virtual float GetMargin() const
- {
- return (m_collisionShape) ? m_collisionShape->getMargin() : 0.f;
- }
- virtual float GetRadius() const
- {
- // this is not the actual shape radius, it's only used for Fh support
- return m_cci.m_radius;
- }
- virtual void SetRadius(float margin)
- {
- if (m_collisionShape && m_collisionShape->getShapeType() == SPHERE_SHAPE_PROXYTYPE)
- {
- btSphereShape* sphereShape = static_cast<btSphereShape*>(m_collisionShape);
- sphereShape->setUnscaledRadius(margin);
- }
- m_cci.m_radius = margin;
- }
-
- // velocity clamping
- virtual void SetLinVelocityMin(float val)
- {
- m_cci.m_clamp_vel_min= val;
- }
- virtual float GetLinVelocityMin() const
- {
- return m_cci.m_clamp_vel_min;
- }
- virtual void SetLinVelocityMax(float val)
- {
- m_cci.m_clamp_vel_max= val;
- }
- virtual float GetLinVelocityMax() const
- {
- return m_cci.m_clamp_vel_max;
- }
-
- virtual void SetAngularVelocityMin(float val)
- {
- m_cci.m_clamp_angvel_min = val;
- }
- virtual float GetAngularVelocityMin() const
- {
- return m_cci.m_clamp_angvel_min;
- }
- virtual void SetAngularVelocityMax(float val)
- {
- m_cci.m_clamp_angvel_max = val;
- }
- virtual float GetAngularVelocityMax() const
- {
- return m_cci.m_clamp_angvel_max;
- }
-
- bool WantsSleeping();
-
- void UpdateDeactivation(float timeStep);
-
- void SetCenterOfMassTransform(btTransform& xform);
-
- static btTransform& GetTransformFromMotionState(PHY_IMotionState* motionState);
-
- void setAabb(const btVector3& aabbMin,const btVector3& aabbMax);
-
-
- class PHY_IMotionState* GetMotionState()
- {
- return m_MotionState;
- }
-
- const class PHY_IMotionState* GetMotionState() const
- {
- return m_MotionState;
- }
-
- class CcdPhysicsEnvironment* GetPhysicsEnvironment()
- {
- return m_cci.m_physicsEnv;
- }
-
- void SetParentCtrl(CcdPhysicsController* parentCtrl)
- {
- m_parentCtrl = parentCtrl;
- }
-
- CcdPhysicsController* GetParentCtrl()
- {
- return m_parentCtrl;
- }
-
- const CcdPhysicsController* GetParentCtrl() const
- {
- return m_parentCtrl;
- }
-
- virtual bool IsDynamic()
- {
- return GetConstructionInfo().m_bDyna;
- }
-
- virtual bool IsSuspended() const
- {
- return m_suspended;
- }
-
- virtual bool IsCompound()
- {
- return GetConstructionInfo().m_shapeInfo->m_shapeType == PHY_SHAPE_COMPOUND;
- }
-
- virtual bool ReinstancePhysicsShape(KX_GameObject *from_gameobj, RAS_MeshObject* from_meshobj);
-
- /* Method to replicate rigid body joint contraints for group instances. */
- virtual void ReplicateConstraints(KX_GameObject *gameobj, std::vector<KX_GameObject*> constobj);
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:CcdPhysicsController")
-#endif
-};
-
-
-
-
-///DefaultMotionState implements standard motionstate, using btTransform
-class DefaultMotionState : public PHY_IMotionState
-
-{
- public:
- DefaultMotionState();
-
- virtual ~DefaultMotionState();
-
- virtual void GetWorldPosition(float& posX,float& posY,float& posZ);
- virtual void GetWorldScaling(float& scaleX,float& scaleY,float& scaleZ);
- virtual void GetWorldOrientation(float& quatIma0,float& quatIma1,float& quatIma2,float& quatReal);
-
- virtual void SetWorldPosition(float posX,float posY,float posZ);
- virtual void SetWorldOrientation(float quatIma0,float quatIma1,float quatIma2,float quatReal);
- virtual void GetWorldOrientation(float* ori);
- virtual void SetWorldOrientation(const float* ori);
-
- virtual void CalculateWorldTransformations();
-
- btTransform m_worldTransform;
- btVector3 m_localScaling;
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:DefaultMotionState")
-#endif
-};
-
-
-#endif /* __CCDPHYSICSCONTROLLER_H__ */
diff --git a/source/gameengine/Physics/Bullet/CcdPhysicsEnvironment.cpp b/source/gameengine/Physics/Bullet/CcdPhysicsEnvironment.cpp
deleted file mode 100644
index 78d2d88cc65..00000000000
--- a/source/gameengine/Physics/Bullet/CcdPhysicsEnvironment.cpp
+++ /dev/null
@@ -1,3795 +0,0 @@
-/** \file gameengine/Physics/Bullet/CcdPhysicsEnvironment.cpp
- * \ingroup physbullet
- */
-/*
-Bullet Continuous Collision Detection and Physics Library
-Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
-
-This software is provided 'as-is', without any express or implied warranty.
-In no event will the authors be held liable for any damages arising from the use of this software.
-Permission is granted to anyone to use this software for any purpose,
-including commercial applications, and to alter it and redistribute it freely,
-subject to the following restrictions:
-
-1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
-2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
-3. This notice may not be removed or altered from any source distribution.
-*/
-
-
-
-
-#include "CcdPhysicsEnvironment.h"
-#include "CcdPhysicsController.h"
-#include "CcdGraphicController.h"
-
-#include <algorithm>
-#include "btBulletDynamicsCommon.h"
-#include "LinearMath/btIDebugDraw.h"
-#include "BulletCollision/CollisionDispatch/btGhostObject.h"
-#include "BulletCollision/CollisionDispatch/btSimulationIslandManager.h"
-#include "BulletSoftBody/btSoftRigidDynamicsWorld.h"
-#include "BulletSoftBody/btSoftBodyRigidBodyCollisionConfiguration.h"
-#include "BulletCollision/Gimpact/btGImpactCollisionAlgorithm.h"
-#include "BulletCollision/NarrowPhaseCollision/btRaycastCallback.h"
-
-//profiling/timings
-#include "LinearMath/btQuickprof.h"
-
-
-#include "PHY_IMotionState.h"
-#include "PHY_ICharacter.h"
-#include "PHY_Pro.h"
-#include "KX_GameObject.h"
-#include "KX_PythonInit.h" // for KX_RasterizerDrawDebugLine
-#include "KX_BlenderSceneConverter.h"
-#include "RAS_MeshObject.h"
-#include "RAS_Polygon.h"
-#include "RAS_TexVert.h"
-
-#include "DNA_scene_types.h"
-#include "DNA_world_types.h"
-#include "DNA_object_force_types.h"
-
-extern "C" {
- #include "BLI_utildefines.h"
- #include "BKE_object.h"
-}
-
-#define CCD_CONSTRAINT_DISABLE_LINKED_COLLISION 0x80
-
-#ifdef NEW_BULLET_VEHICLE_SUPPORT
-#include "BulletDynamics/Vehicle/btRaycastVehicle.h"
-#include "BulletDynamics/Vehicle/btVehicleRaycaster.h"
-#include "BulletDynamics/Vehicle/btWheelInfo.h"
-#include "PHY_IVehicle.h"
-static btRaycastVehicle::btVehicleTuning gTuning;
-
-#endif //NEW_BULLET_VEHICLE_SUPPORT
-#include "LinearMath/btAabbUtil2.h"
-#include "MT_Matrix4x4.h"
-#include "MT_Vector3.h"
-#include "MT_MinMax.h"
-
-#ifdef WIN32
-void DrawRasterizerLine(const float* from,const float* to,int color);
-#endif
-
-
-#include "BulletDynamics/ConstraintSolver/btContactConstraint.h"
-
-
-#include <stdio.h>
-#include <string.h> // for memset
-
-// This was copied from the old KX_ConvertPhysicsObjects
-#ifdef WIN32
-#ifdef _MSC_VER
-//only use SIMD Hull code under Win32
-//#define TEST_HULL 1
-#ifdef TEST_HULL
-#define USE_HULL 1
-//#define TEST_SIMD_HULL 1
-
-#include "NarrowPhaseCollision/Hull.h"
-#endif //#ifdef TEST_HULL
-
-#endif //_MSC_VER
-#endif //WIN32
-
-#ifdef NEW_BULLET_VEHICLE_SUPPORT
-class WrapperVehicle : public PHY_IVehicle
-{
-
- btRaycastVehicle* m_vehicle;
- PHY_IPhysicsController* m_chassis;
-
-public:
-
- WrapperVehicle(btRaycastVehicle* vehicle,PHY_IPhysicsController* chassis)
- :m_vehicle(vehicle),
- m_chassis(chassis)
- {
- }
-
- ~WrapperVehicle()
- {
- delete m_vehicle;
- }
-
- btRaycastVehicle* GetVehicle()
- {
- return m_vehicle;
- }
-
- PHY_IPhysicsController* GetChassis()
- {
- return m_chassis;
- }
-
- virtual void AddWheel(
- PHY_IMotionState* motionState,
- MT_Vector3 connectionPoint,
- MT_Vector3 downDirection,
- MT_Vector3 axleDirection,
- float suspensionRestLength,
- float wheelRadius,
- bool hasSteering
- )
- {
- btVector3 connectionPointCS0(connectionPoint[0],connectionPoint[1],connectionPoint[2]);
- btVector3 wheelDirectionCS0(downDirection[0],downDirection[1],downDirection[2]);
- btVector3 wheelAxle(axleDirection[0],axleDirection[1],axleDirection[2]);
-
-
- btWheelInfo& info = m_vehicle->addWheel(connectionPointCS0,wheelDirectionCS0,wheelAxle,
- suspensionRestLength,wheelRadius,gTuning,hasSteering);
- info.m_clientInfo = motionState;
-
- }
-
- void SyncWheels()
- {
- int numWheels = GetNumWheels();
- int i;
- for (i=0;i<numWheels;i++)
- {
- btWheelInfo& info = m_vehicle->getWheelInfo(i);
- PHY_IMotionState* motionState = (PHY_IMotionState*)info.m_clientInfo;
- // m_vehicle->updateWheelTransformsWS(info,false);
- m_vehicle->updateWheelTransform(i,false);
- btTransform trans = m_vehicle->getWheelInfo(i).m_worldTransform;
- btQuaternion orn = trans.getRotation();
- const btVector3& pos = trans.getOrigin();
- motionState->SetWorldOrientation(orn.x(),orn.y(),orn.z(),orn[3]);
- motionState->SetWorldPosition(pos.x(),pos.y(),pos.z());
-
- }
- }
-
- virtual int GetNumWheels() const
- {
- return m_vehicle->getNumWheels();
- }
-
- virtual void GetWheelPosition(int wheelIndex,float& posX,float& posY,float& posZ) const
- {
- if ((wheelIndex>=0) && (wheelIndex< m_vehicle->getNumWheels()))
- {
- btVector3 origin = m_vehicle->getWheelTransformWS(wheelIndex).getOrigin();
-
- posX = origin.x();
- posY = origin.y();
- posZ = origin.z();
- }
- }
-
- virtual void GetWheelOrientationQuaternion(int wheelIndex,float& quatX,float& quatY,float& quatZ,float& quatW) const
- {
- if ((wheelIndex>=0) && (wheelIndex< m_vehicle->getNumWheels()))
- {
- btQuaternion quat = m_vehicle->getWheelTransformWS(wheelIndex).getRotation();
-
- quatX = quat.x();
- quatY = quat.y();
- quatZ = quat.z();
- quatW = quat.w();
- }
- }
-
- virtual float GetWheelRotation(int wheelIndex) const
- {
- float rotation = 0.f;
-
- if ((wheelIndex>=0) && (wheelIndex< m_vehicle->getNumWheels()))
- {
- btWheelInfo& info = m_vehicle->getWheelInfo(wheelIndex);
- rotation = info.m_rotation;
- }
-
- return rotation;
- }
-
-
-
- virtual int GetUserConstraintId() const
- {
- return m_vehicle->getUserConstraintId();
- }
-
- virtual int GetUserConstraintType() const
- {
- return m_vehicle->getUserConstraintType();
- }
-
- virtual void SetSteeringValue(float steering,int wheelIndex)
- {
- if ((wheelIndex>=0) && (wheelIndex< m_vehicle->getNumWheels())) {
- m_vehicle->setSteeringValue(steering,wheelIndex);
- }
- }
-
- virtual void ApplyEngineForce(float force,int wheelIndex)
- {
- if ((wheelIndex>=0) && (wheelIndex< m_vehicle->getNumWheels())) {
- m_vehicle->applyEngineForce(force,wheelIndex);
- }
- }
-
- virtual void ApplyBraking(float braking,int wheelIndex)
- {
- if ((wheelIndex>=0) && (wheelIndex< m_vehicle->getNumWheels()))
- {
- btWheelInfo& info = m_vehicle->getWheelInfo(wheelIndex);
- info.m_brake = braking;
- }
- }
-
- virtual void SetWheelFriction(float friction,int wheelIndex)
- {
- if ((wheelIndex>=0) && (wheelIndex< m_vehicle->getNumWheels()))
- {
- btWheelInfo& info = m_vehicle->getWheelInfo(wheelIndex);
- info.m_frictionSlip = friction;
- }
-
- }
-
- virtual void SetSuspensionStiffness(float suspensionStiffness,int wheelIndex)
- {
- if ((wheelIndex>=0) && (wheelIndex< m_vehicle->getNumWheels()))
- {
- btWheelInfo& info = m_vehicle->getWheelInfo(wheelIndex);
- info.m_suspensionStiffness = suspensionStiffness;
-
- }
- }
-
- virtual void SetSuspensionDamping(float suspensionDamping,int wheelIndex)
- {
- if ((wheelIndex>=0) && (wheelIndex< m_vehicle->getNumWheels()))
- {
- btWheelInfo& info = m_vehicle->getWheelInfo(wheelIndex);
- info.m_wheelsDampingRelaxation = suspensionDamping;
- }
- }
-
- virtual void SetSuspensionCompression(float suspensionCompression,int wheelIndex)
- {
- if ((wheelIndex>=0) && (wheelIndex< m_vehicle->getNumWheels()))
- {
- btWheelInfo& info = m_vehicle->getWheelInfo(wheelIndex);
- info.m_wheelsDampingCompression = suspensionCompression;
- }
- }
-
-
-
- virtual void SetRollInfluence(float rollInfluence,int wheelIndex)
- {
- if ((wheelIndex>=0) && (wheelIndex< m_vehicle->getNumWheels()))
- {
- btWheelInfo& info = m_vehicle->getWheelInfo(wheelIndex);
- info.m_rollInfluence = rollInfluence;
- }
- }
-
- virtual void SetCoordinateSystem(int rightIndex,int upIndex,int forwardIndex)
- {
- m_vehicle->setCoordinateSystem(rightIndex,upIndex,forwardIndex);
- }
-
-
-
-};
-
-class BlenderVehicleRaycaster: public btDefaultVehicleRaycaster
-{
- btDynamicsWorld* m_dynamicsWorld;
-public:
- BlenderVehicleRaycaster(btDynamicsWorld* world)
- :btDefaultVehicleRaycaster(world), m_dynamicsWorld(world)
- {
- }
-
- virtual void* castRay(const btVector3& from,const btVector3& to, btVehicleRaycasterResult& result)
- {
- // RayResultCallback& resultCallback;
-
- btCollisionWorld::ClosestRayResultCallback rayCallback(from,to);
-
- // We override btDefaultVehicleRaycaster so we can set this flag, otherwise our
- // vehicles go crazy (http://bulletphysics.org/Bullet/phpBB3/viewtopic.php?t=9662)
- rayCallback.m_flags |= btTriangleRaycastCallback::kF_UseSubSimplexConvexCastRaytest;
-
- m_dynamicsWorld->rayTest(from, to, rayCallback);
-
- if (rayCallback.hasHit())
- {
-
- const btRigidBody* body = btRigidBody::upcast(rayCallback.m_collisionObject);
- if (body && body->hasContactResponse())
- {
- result.m_hitPointInWorld = rayCallback.m_hitPointWorld;
- result.m_hitNormalInWorld = rayCallback.m_hitNormalWorld;
- result.m_hitNormalInWorld.normalize();
- result.m_distFraction = rayCallback.m_closestHitFraction;
- return (void*)body;
- }
- }
- return 0;
- }
-};
-#endif //NEW_BULLET_VEHICLE_SUPPORT
-
-class CcdOverlapFilterCallBack : public btOverlapFilterCallback
-{
-private:
- class CcdPhysicsEnvironment* m_physEnv;
-public:
- CcdOverlapFilterCallBack(CcdPhysicsEnvironment* env) :
- m_physEnv(env)
- {
- }
- virtual ~CcdOverlapFilterCallBack()
- {
- }
- // return true when pairs need collision
- virtual bool needBroadphaseCollision(btBroadphaseProxy* proxy0,btBroadphaseProxy* proxy1) const;
-};
-
-
-void CcdPhysicsEnvironment::SetDebugDrawer(btIDebugDraw* debugDrawer)
-{
- if (debugDrawer && m_dynamicsWorld)
- m_dynamicsWorld->setDebugDrawer(debugDrawer);
- m_debugDrawer = debugDrawer;
-}
-
-#if 0
-static void DrawAabb(btIDebugDraw* debugDrawer,const btVector3& from,const btVector3& to,const btVector3& color)
-{
- btVector3 halfExtents = (to-from)* 0.5f;
- btVector3 center = (to+from) *0.5f;
- int i,j;
-
- btVector3 edgecoord(1.f,1.f,1.f),pa,pb;
- for (i=0;i<4;i++)
- {
- for (j=0;j<3;j++)
- {
- pa = btVector3(edgecoord[0]*halfExtents[0], edgecoord[1]*halfExtents[1],
- edgecoord[2]*halfExtents[2]);
- pa+=center;
-
- int othercoord = j%3;
- edgecoord[othercoord]*=-1.f;
- pb = btVector3(edgecoord[0]*halfExtents[0], edgecoord[1]*halfExtents[1],
- edgecoord[2]*halfExtents[2]);
- pb+=center;
-
- debugDrawer->drawLine(pa,pb,color);
- }
- edgecoord = btVector3(-1.f,-1.f,-1.f);
- if (i<3)
- edgecoord[i]*=-1.f;
- }
-}
-#endif
-
-
-
-
-
-CcdPhysicsEnvironment::CcdPhysicsEnvironment(bool useDbvtCulling,btDispatcher* dispatcher,btOverlappingPairCache* pairCache)
-:m_cullingCache(NULL),
-m_cullingTree(NULL),
-m_numIterations(10),
-m_numTimeSubSteps(1),
-m_ccdMode(0),
-m_solverType(-1),
-m_profileTimings(0),
-m_enableSatCollisionDetection(false),
-m_deactivationTime(2.0f),
-m_linearDeactivationThreshold(0.8f),
-m_angularDeactivationThreshold(1.0f),
-m_contactBreakingThreshold(0.02f),
-m_solver(NULL),
-m_ownPairCache(NULL),
-m_filterCallback(NULL),
-m_ghostPairCallback(NULL),
-m_ownDispatcher(NULL),
-m_scalingPropagated(false)
-{
-
- for (int i=0;i<PHY_NUM_RESPONSE;i++)
- {
- m_triggerCallbacks[i] = 0;
- }
-
-// m_collisionConfiguration = new btDefaultCollisionConfiguration();
- m_collisionConfiguration = new btSoftBodyRigidBodyCollisionConfiguration();
- //m_collisionConfiguration->setConvexConvexMultipointIterations();
-
- if (!dispatcher)
- {
- btCollisionDispatcher* disp = new btCollisionDispatcher(m_collisionConfiguration);
- dispatcher = disp;
- btGImpactCollisionAlgorithm::registerAlgorithm(disp);
- m_ownDispatcher = dispatcher;
- }
-
- //m_broadphase = new btAxisSweep3(btVector3(-1000,-1000,-1000),btVector3(1000,1000,1000));
- //m_broadphase = new btSimpleBroadphase();
- m_broadphase = new btDbvtBroadphase();
- // avoid any collision in the culling tree
- if (useDbvtCulling) {
- m_cullingCache = new btNullPairCache();
- m_cullingTree = new btDbvtBroadphase(m_cullingCache);
- }
-
- m_filterCallback = new CcdOverlapFilterCallBack(this);
- m_ghostPairCallback = new btGhostPairCallback();
- m_broadphase->getOverlappingPairCache()->setOverlapFilterCallback(m_filterCallback);
- m_broadphase->getOverlappingPairCache()->setInternalGhostPairCallback(m_ghostPairCallback);
-
- SetSolverType(1);//issues with quickstep and memory allocations
-// m_dynamicsWorld = new btDiscreteDynamicsWorld(dispatcher,m_broadphase,m_solver,m_collisionConfiguration);
- m_dynamicsWorld = new btSoftRigidDynamicsWorld(dispatcher,m_broadphase,m_solver,m_collisionConfiguration);
- m_dynamicsWorld->setInternalTickCallback(&CcdPhysicsEnvironment::StaticSimulationSubtickCallback, this);
- //m_dynamicsWorld->getSolverInfo().m_linearSlop = 0.01f;
- //m_dynamicsWorld->getSolverInfo().m_solverMode= SOLVER_USE_WARMSTARTING + SOLVER_USE_2_FRICTION_DIRECTIONS + SOLVER_RANDMIZE_ORDER + SOLVER_USE_FRICTION_WARMSTARTING;
-
- m_debugDrawer = 0;
- SetGravity(0.f,0.f,-9.81f);
-}
-
-void CcdPhysicsEnvironment::AddCcdPhysicsController(CcdPhysicsController* ctrl)
-{
- // the controller is already added we do nothing
- if (!m_controllers.insert(ctrl).second) {
- return;
- }
-
- btRigidBody* body = ctrl->GetRigidBody();
- btCollisionObject* obj = ctrl->GetCollisionObject();
-
- //this m_userPointer is just used for triggers, see CallbackTriggers
- obj->setUserPointer(ctrl);
- if (body) {
- body->setGravity(m_gravity);
- body->setSleepingThresholds(m_linearDeactivationThreshold, m_angularDeactivationThreshold);
- }
-
- if (body)
- {
- //use explicit group/filter for finer control over collision in bullet => near/radar sensor
- m_dynamicsWorld->addRigidBody(body, ctrl->GetCollisionFilterGroup(), ctrl->GetCollisionFilterMask());
- } else
- {
- if (ctrl->GetSoftBody())
- {
- btSoftBody* softBody = ctrl->GetSoftBody();
- m_dynamicsWorld->addSoftBody(softBody);
- } else
- {
- if (obj->getCollisionShape())
- {
- m_dynamicsWorld->addCollisionObject(obj, ctrl->GetCollisionFilterGroup(), ctrl->GetCollisionFilterMask());
- }
- if (ctrl->GetCharacterController())
- {
- m_dynamicsWorld->addAction(ctrl->GetCharacterController());
- }
- }
- }
- if (obj->isStaticOrKinematicObject())
- {
- obj->setActivationState(ISLAND_SLEEPING);
- }
-
- assert(obj->getBroadphaseHandle());
-}
-
-void CcdPhysicsEnvironment::RemoveConstraint(btTypedConstraint *con)
-{
- btRigidBody &rbA = con->getRigidBodyA();
- btRigidBody &rbB = con->getRigidBodyB();
- rbA.activate();
- rbB.activate();
- m_dynamicsWorld->removeConstraint(con);
-
- if (rbA.getUserPointer()) {
- ((CcdPhysicsController *)rbA.getUserPointer())->removeCcdConstraintRef(con);
- }
-
- if (rbB.getUserPointer()) {
- ((CcdPhysicsController *)rbB.getUserPointer())->removeCcdConstraintRef(con);
- }
-
- /* Since we remove the constraint in the onwer and the target, we can delete it,
- * KX_ConstraintWrapper keep the constraint id not the pointer, so no problems. */
- delete con;
-}
-
-bool CcdPhysicsEnvironment::RemoveCcdPhysicsController(CcdPhysicsController* ctrl)
-{
- // if the physics controller is already removed we do nothing
- if (!m_controllers.erase(ctrl)) {
- return false;
- }
-
- //also remove constraint
- btRigidBody* body = ctrl->GetRigidBody();
- if (body)
- {
- btBroadphaseProxy *proxy = ctrl->GetCollisionObject()->getBroadphaseHandle();
- btDispatcher *dispatcher = m_dynamicsWorld->getDispatcher();
- btOverlappingPairCache *pairCache = m_dynamicsWorld->getPairCache();
-
- CleanPairCallback cleanPairs(proxy, pairCache, dispatcher);
- pairCache->processAllOverlappingPairs(&cleanPairs, dispatcher);
-
- for (int i = ctrl->getNumCcdConstraintRefs() - 1; i >= 0; i--)
- {
- btTypedConstraint* con = ctrl->getCcdConstraintRef(i);
- RemoveConstraint(con);
- }
- m_dynamicsWorld->removeRigidBody(ctrl->GetRigidBody());
-
- // Handle potential vehicle constraints
- int numVehicles = m_wrapperVehicles.size();
- int vehicle_constraint = 0;
- for (int i=0;i<numVehicles;i++)
- {
- WrapperVehicle* wrapperVehicle = m_wrapperVehicles[i];
- if (wrapperVehicle->GetChassis() == ctrl)
- vehicle_constraint = wrapperVehicle->GetVehicle()->getUserConstraintId();
- }
-
- if (vehicle_constraint > 0)
- RemoveConstraintById(vehicle_constraint);
- } else
- {
- //if a softbody
- if (ctrl->GetSoftBody())
- {
- m_dynamicsWorld->removeSoftBody(ctrl->GetSoftBody());
- } else
- {
- m_dynamicsWorld->removeCollisionObject(ctrl->GetCollisionObject());
-
- if (ctrl->GetCharacterController())
- {
- m_dynamicsWorld->removeAction(ctrl->GetCharacterController());
- }
- }
- }
-
- return true;
-}
-
-void CcdPhysicsEnvironment::UpdateCcdPhysicsController(CcdPhysicsController* ctrl, btScalar newMass, int newCollisionFlags, short int newCollisionGroup, short int newCollisionMask)
-{
- // this function is used when the collisionning group of a controller is changed
- // remove and add the collistioning object
- btRigidBody* body = ctrl->GetRigidBody();
- btSoftBody *softBody = ctrl->GetSoftBody();
- btCollisionObject* obj = ctrl->GetCollisionObject();
- if (obj)
- {
- btVector3 inertia(0.0f,0.0f,0.0f);
- m_dynamicsWorld->removeCollisionObject(obj);
- obj->setCollisionFlags(newCollisionFlags);
- if (body)
- {
- if (newMass)
- body->getCollisionShape()->calculateLocalInertia(newMass, inertia);
- body->setMassProps(newMass, inertia);
- m_dynamicsWorld->addRigidBody(body, newCollisionGroup, newCollisionMask);
- }
- else if (softBody) {
- m_dynamicsWorld->addSoftBody(softBody);
- }
- else {
- m_dynamicsWorld->addCollisionObject(obj, newCollisionGroup, newCollisionMask);
- }
- }
- // to avoid nasty interaction, we must update the property of the controller as well
- ctrl->m_cci.m_mass = newMass;
- ctrl->m_cci.m_collisionFilterGroup = newCollisionGroup;
- ctrl->m_cci.m_collisionFilterMask = newCollisionMask;
- ctrl->m_cci.m_collisionFlags = newCollisionFlags;
-}
-
-void CcdPhysicsEnvironment::RefreshCcdPhysicsController(CcdPhysicsController* ctrl)
-{
- btCollisionObject* obj = ctrl->GetCollisionObject();
- if (obj)
- {
- btBroadphaseProxy* proxy = obj->getBroadphaseHandle();
- if (proxy)
- {
- m_dynamicsWorld->getPairCache()->cleanProxyFromPairs(proxy,m_dynamicsWorld->getDispatcher());
- }
- }
-}
-
-bool CcdPhysicsEnvironment::IsActiveCcdPhysicsController(CcdPhysicsController *ctrl)
-{
- return (m_controllers.find(ctrl) != m_controllers.end());
-}
-
-void CcdPhysicsEnvironment::AddCcdGraphicController(CcdGraphicController* ctrl)
-{
- if (m_cullingTree && !ctrl->GetBroadphaseHandle())
- {
- btVector3 minAabb;
- btVector3 maxAabb;
- ctrl->GetAabb(minAabb, maxAabb);
-
- ctrl->SetBroadphaseHandle(m_cullingTree->createProxy(
- minAabb,
- maxAabb,
- INVALID_SHAPE_PROXYTYPE, // this parameter is not used
- ctrl,
- 0, // this object does not collision with anything
- 0,
- NULL, // dispatcher => this parameter is not used
- 0));
-
- assert(ctrl->GetBroadphaseHandle());
- }
-}
-
-void CcdPhysicsEnvironment::RemoveCcdGraphicController(CcdGraphicController* ctrl)
-{
- if (m_cullingTree)
- {
- btBroadphaseProxy* bp = ctrl->GetBroadphaseHandle();
- if (bp)
- {
- m_cullingTree->destroyProxy(bp,NULL);
- ctrl->SetBroadphaseHandle(0);
- }
- }
-}
-
-void CcdPhysicsEnvironment::UpdateCcdPhysicsControllerShape(CcdShapeConstructionInfo *shapeInfo)
-{
- for (std::set<CcdPhysicsController *>::iterator it = m_controllers.begin(); it != m_controllers.end(); ++it) {
- CcdPhysicsController *ctrl = *it;
-
- if (ctrl->GetShapeInfo() != shapeInfo)
- continue;
-
- ctrl->ReplaceControllerShape(NULL);
- RefreshCcdPhysicsController(ctrl);
- }
-}
-
-void CcdPhysicsEnvironment::BeginFrame()
-{
-
-}
-
-void CcdPhysicsEnvironment::DebugDrawWorld()
-{
- if (m_dynamicsWorld->getDebugDrawer() && m_dynamicsWorld->getDebugDrawer()->getDebugMode() >0)
- m_dynamicsWorld->debugDrawWorld();
-}
-
-void CcdPhysicsEnvironment::StaticSimulationSubtickCallback(btDynamicsWorld *world, btScalar timeStep)
-{
- // Get the pointer to the CcdPhysicsEnvironment associated with this Bullet world.
- CcdPhysicsEnvironment *this_ = static_cast<CcdPhysicsEnvironment*>(world->getWorldUserInfo());
- this_->SimulationSubtickCallback(timeStep);
-}
-
-void CcdPhysicsEnvironment::SimulationSubtickCallback(btScalar timeStep)
-{
- std::set<CcdPhysicsController*>::iterator it;
-
- for (it = m_controllers.begin(); it != m_controllers.end(); it++) {
- (*it)->SimulationTick(timeStep);
- }
-}
-
-bool CcdPhysicsEnvironment::ProceedDeltaTime(double curTime,float timeStep,float interval)
-{
- std::set<CcdPhysicsController*>::iterator it;
- int i;
-
- // Update Bullet global variables.
- gDeactivationTime = m_deactivationTime;
- gContactBreakingThreshold = m_contactBreakingThreshold;
-
- for (it=m_controllers.begin(); it!=m_controllers.end(); it++)
- {
- (*it)->SynchronizeMotionStates(timeStep);
- }
-
- float subStep = timeStep / float(m_numTimeSubSteps);
- i = m_dynamicsWorld->stepSimulation(interval,25,subStep);//perform always a full simulation step
-//uncomment next line to see where Bullet spend its time (printf in console)
-//CProfileManager::dumpAll();
-
- ProcessFhSprings(curTime,i*subStep);
-
- for (it=m_controllers.begin(); it!=m_controllers.end(); it++)
- {
- (*it)->SynchronizeMotionStates(timeStep);
- }
-
- //for (it=m_controllers.begin(); it!=m_controllers.end(); it++)
- //{
- // (*it)->SynchronizeMotionStates(timeStep);
- //}
-
- for (i=0;i<m_wrapperVehicles.size();i++)
- {
- WrapperVehicle* veh = m_wrapperVehicles[i];
- veh->SyncWheels();
- }
-
-
- CallbackTriggers();
-
- return true;
-}
-
-class ClosestRayResultCallbackNotMe : public btCollisionWorld::ClosestRayResultCallback
-{
- btCollisionObject* m_owner;
- btCollisionObject* m_parent;
-
-public:
- ClosestRayResultCallbackNotMe(const btVector3& rayFromWorld,const btVector3& rayToWorld,btCollisionObject* owner,btCollisionObject* parent)
- :btCollisionWorld::ClosestRayResultCallback(rayFromWorld,rayToWorld),
- m_owner(owner),
- m_parent(parent)
- {
-
- }
-
- virtual bool needsCollision(btBroadphaseProxy* proxy0) const
- {
- //don't collide with self
- if (proxy0->m_clientObject == m_owner)
- return false;
-
- if (proxy0->m_clientObject == m_parent)
- return false;
-
- return btCollisionWorld::ClosestRayResultCallback::needsCollision(proxy0);
- }
-
-};
-
-void CcdPhysicsEnvironment::ProcessFhSprings(double curTime,float interval)
-{
- std::set<CcdPhysicsController*>::iterator it;
- // Add epsilon to the tick rate for numerical stability
- int numIter = (int)(interval*(KX_KetsjiEngine::GetTicRate() + 0.001f));
-
- for (it=m_controllers.begin(); it!=m_controllers.end(); it++)
- {
- CcdPhysicsController* ctrl = (*it);
- btRigidBody* body = ctrl->GetRigidBody();
-
- if (body && (ctrl->GetConstructionInfo().m_do_fh || ctrl->GetConstructionInfo().m_do_rot_fh))
- {
- //printf("has Fh or RotFh\n");
- //re-implement SM_FhObject.cpp using btCollisionWorld::rayTest and info from ctrl->getConstructionInfo()
- //send a ray from {0.0, 0.0, 0.0} towards {0.0, 0.0, -10.0}, in local coordinates
- CcdPhysicsController* parentCtrl = ctrl->GetParentCtrl();
- btRigidBody* parentBody = parentCtrl?parentCtrl->GetRigidBody() : 0;
- btRigidBody* cl_object = parentBody ? parentBody : body;
-
- if (body->isStaticOrKinematicObject())
- continue;
-
- btVector3 rayDirLocal(0,0,-10);
-
- //m_dynamicsWorld
- //ctrl->GetRigidBody();
- btVector3 rayFromWorld = body->getCenterOfMassPosition();
- //btVector3 rayToWorld = rayFromWorld + body->getCenterOfMassTransform().getBasis() * rayDirLocal;
- //ray always points down the z axis in world space...
- btVector3 rayToWorld = rayFromWorld + rayDirLocal;
-
- ClosestRayResultCallbackNotMe resultCallback(rayFromWorld,rayToWorld,body,parentBody);
-
- m_dynamicsWorld->rayTest(rayFromWorld,rayToWorld,resultCallback);
- if (resultCallback.hasHit())
- {
- //we hit this one: resultCallback.m_collisionObject;
- CcdPhysicsController* controller = static_cast<CcdPhysicsController*>(resultCallback.m_collisionObject->getUserPointer());
-
- if (controller)
- {
- if (controller->GetConstructionInfo().m_fh_distance < SIMD_EPSILON)
- continue;
-
- btRigidBody* hit_object = controller->GetRigidBody();
- if (!hit_object)
- continue;
-
- CcdConstructionInfo& hitObjShapeProps = controller->GetConstructionInfo();
-
- float distance = resultCallback.m_closestHitFraction*rayDirLocal.length()-ctrl->GetConstructionInfo().m_radius;
- if (distance >= hitObjShapeProps.m_fh_distance)
- continue;
-
-
-
- //btVector3 ray_dir = cl_object->getCenterOfMassTransform().getBasis()* rayDirLocal.normalized();
- btVector3 ray_dir = rayDirLocal.normalized();
- btVector3 normal = resultCallback.m_hitNormalWorld;
- normal.normalize();
-
- for (int i=0; i<numIter; i++)
- {
- if (ctrl->GetConstructionInfo().m_do_fh)
- {
- btVector3 lspot = cl_object->getCenterOfMassPosition() +
- rayDirLocal * resultCallback.m_closestHitFraction;
-
-
-
-
- lspot -= hit_object->getCenterOfMassPosition();
- btVector3 rel_vel = cl_object->getLinearVelocity() - hit_object->getVelocityInLocalPoint(lspot);
- btScalar rel_vel_ray = ray_dir.dot(rel_vel);
- btScalar spring_extent = 1.0f - distance / hitObjShapeProps.m_fh_distance;
-
- btScalar i_spring = spring_extent * hitObjShapeProps.m_fh_spring;
- btScalar i_damp = rel_vel_ray * hitObjShapeProps.m_fh_damping;
-
- cl_object->setLinearVelocity(cl_object->getLinearVelocity() + (-(i_spring + i_damp) * ray_dir));
- if (hitObjShapeProps.m_fh_normal)
- {
- cl_object->setLinearVelocity(cl_object->getLinearVelocity()+(i_spring + i_damp) *(normal - normal.dot(ray_dir) * ray_dir));
- }
-
- btVector3 lateral = rel_vel - rel_vel_ray * ray_dir;
-
-
- if (ctrl->GetConstructionInfo().m_do_anisotropic) {
- //Bullet basis contains no scaling/shear etc.
- const btMatrix3x3& lcs = cl_object->getCenterOfMassTransform().getBasis();
- btVector3 loc_lateral = lateral * lcs;
- const btVector3& friction_scaling = cl_object->getAnisotropicFriction();
- loc_lateral *= friction_scaling;
- lateral = lcs * loc_lateral;
- }
-
- btScalar rel_vel_lateral = lateral.length();
-
- if (rel_vel_lateral > SIMD_EPSILON) {
- btScalar friction_factor = hit_object->getFriction();//cl_object->getFriction();
-
- btScalar max_friction = friction_factor * btMax(btScalar(0.0f), i_spring);
-
- btScalar rel_mom_lateral = rel_vel_lateral / cl_object->getInvMass();
-
- btVector3 friction = (rel_mom_lateral > max_friction) ?
- -lateral * (max_friction / rel_vel_lateral) :
- -lateral;
-
- cl_object->applyCentralImpulse(friction);
- }
- }
-
-
- if (ctrl->GetConstructionInfo().m_do_rot_fh) {
- btVector3 up2 = cl_object->getWorldTransform().getBasis().getColumn(2);
-
- btVector3 t_spring = up2.cross(normal) * hitObjShapeProps.m_fh_spring;
- btVector3 ang_vel = cl_object->getAngularVelocity();
-
- // only rotations that tilt relative to the normal are damped
- ang_vel -= ang_vel.dot(normal) * normal;
-
- btVector3 t_damp = ang_vel * hitObjShapeProps.m_fh_damping;
-
- cl_object->setAngularVelocity(cl_object->getAngularVelocity() + (t_spring - t_damp));
- }
- }
- }
- }
- }
- }
-}
-
-int CcdPhysicsEnvironment::GetDebugMode() const
-{
- if (m_debugDrawer) {
- return m_debugDrawer->getDebugMode();
- }
- return 0;
-}
-
-void CcdPhysicsEnvironment::SetDebugMode(int debugMode)
-{
- if (m_debugDrawer) {
- m_debugDrawer->setDebugMode(debugMode);
- }
-}
-
-void CcdPhysicsEnvironment::SetNumIterations(int numIter)
-{
- m_numIterations = numIter;
-}
-void CcdPhysicsEnvironment::SetDeactivationTime(float dTime)
-{
- m_deactivationTime = dTime;
-}
-void CcdPhysicsEnvironment::SetDeactivationLinearTreshold(float linTresh)
-{
- m_linearDeactivationThreshold = linTresh;
-
- // Update from all controllers.
- for (std::set<CcdPhysicsController*>::iterator it = m_controllers.begin(); it != m_controllers.end(); it++) {
- if ((*it)->GetRigidBody())
- (*it)->GetRigidBody()->setSleepingThresholds(m_linearDeactivationThreshold, m_angularDeactivationThreshold);
- }
-}
-void CcdPhysicsEnvironment::SetDeactivationAngularTreshold(float angTresh)
-{
- m_angularDeactivationThreshold = angTresh;
-
- // Update from all controllers.
- for (std::set<CcdPhysicsController*>::iterator it = m_controllers.begin(); it != m_controllers.end(); it++) {
- if ((*it)->GetRigidBody())
- (*it)->GetRigidBody()->setSleepingThresholds(m_linearDeactivationThreshold, m_angularDeactivationThreshold);
- }
-}
-
-void CcdPhysicsEnvironment::SetContactBreakingTreshold(float contactBreakingTreshold)
-{
- m_contactBreakingThreshold = contactBreakingTreshold;
-}
-
-
-void CcdPhysicsEnvironment::SetCcdMode(int ccdMode)
-{
- m_ccdMode = ccdMode;
-}
-
-
-void CcdPhysicsEnvironment::SetSolverSorConstant(float sor)
-{
- m_dynamicsWorld->getSolverInfo().m_sor = sor;
-}
-
-void CcdPhysicsEnvironment::SetSolverTau(float tau)
-{
- m_dynamicsWorld->getSolverInfo().m_tau = tau;
-}
-void CcdPhysicsEnvironment::SetSolverDamping(float damping)
-{
- m_dynamicsWorld->getSolverInfo().m_damping = damping;
-}
-
-
-void CcdPhysicsEnvironment::SetLinearAirDamping(float damping)
-{
- //gLinearAirDamping = damping;
-}
-
-void CcdPhysicsEnvironment::SetUseEpa(bool epa)
-{
- //gUseEpa = epa;
-}
-
-void CcdPhysicsEnvironment::SetSolverType(int solverType)
-{
-
- switch (solverType)
- {
- case 1:
- {
- if (m_solverType != solverType)
- {
-
- m_solver = new btSequentialImpulseConstraintSolver();
-
-
- break;
- }
- }
-
- case 0:
- default:
- if (m_solverType != solverType)
- {
-// m_solver = new OdeConstraintSolver();
-
- break;
- }
-
- };
-
- m_solverType = solverType;
-}
-
-
-
-void CcdPhysicsEnvironment::GetGravity(MT_Vector3& grav)
-{
- const btVector3& gravity = m_dynamicsWorld->getGravity();
- grav[0] = gravity.getX();
- grav[1] = gravity.getY();
- grav[2] = gravity.getZ();
-}
-
-
-void CcdPhysicsEnvironment::SetGravity(float x,float y,float z)
-{
- m_gravity = btVector3(x,y,z);
- m_dynamicsWorld->setGravity(m_gravity);
- m_dynamicsWorld->getWorldInfo().m_gravity.setValue(x,y,z);
-}
-
-
-
-
-static int gConstraintUid = 1;
-
-//Following the COLLADA physics specification for constraints
-int CcdPhysicsEnvironment::CreateUniversalD6Constraint(
- class PHY_IPhysicsController* ctrlRef,class PHY_IPhysicsController* ctrlOther,
- btTransform& frameInA,
- btTransform& frameInB,
- const btVector3& linearMinLimits,
- const btVector3& linearMaxLimits,
- const btVector3& angularMinLimits,
- const btVector3& angularMaxLimits,int flags
-)
-{
-
- bool disableCollisionBetweenLinkedBodies = (0!=(flags & CCD_CONSTRAINT_DISABLE_LINKED_COLLISION));
-
- //we could either add some logic to recognize ball-socket and hinge, or let that up to the user
- //perhaps some warning or hint that hinge/ball-socket is more efficient?
-
-
- btGeneric6DofConstraint* genericConstraint = 0;
- CcdPhysicsController* ctrl0 = (CcdPhysicsController*) ctrlRef;
- CcdPhysicsController* ctrl1 = (CcdPhysicsController*) ctrlOther;
-
- btRigidBody* rb0 = ctrl0->GetRigidBody();
- btRigidBody* rb1 = ctrl1->GetRigidBody();
-
- if (rb1)
- {
-
-
- bool useReferenceFrameA = true;
- genericConstraint = new btGeneric6DofSpringConstraint(
- *rb0,*rb1,
- frameInA,frameInB,useReferenceFrameA);
- genericConstraint->setLinearLowerLimit(linearMinLimits);
- genericConstraint->setLinearUpperLimit(linearMaxLimits);
- genericConstraint->setAngularLowerLimit(angularMinLimits);
- genericConstraint->setAngularUpperLimit(angularMaxLimits);
- } else
- {
- // TODO: Implement single body case...
- //No, we can use a fixed rigidbody in above code, rather than unnecessary duplation of code
-
- }
-
- if (genericConstraint)
- {
- // m_constraints.push_back(genericConstraint);
- m_dynamicsWorld->addConstraint(genericConstraint,disableCollisionBetweenLinkedBodies);
-
- genericConstraint->setUserConstraintId(gConstraintUid++);
- genericConstraint->setUserConstraintType(PHY_GENERIC_6DOF_CONSTRAINT);
- //64 bit systems can't cast pointer to int. could use size_t instead.
- return genericConstraint->getUserConstraintId();
- }
- return 0;
-}
-
-void CcdPhysicsEnvironment::RemoveConstraintById(int constraintId)
-{
- // For soft body constraints
- if (constraintId == 0)
- return;
-
- int i;
- int numConstraints = m_dynamicsWorld->getNumConstraints();
- for (i=0;i<numConstraints;i++)
- {
- btTypedConstraint* constraint = m_dynamicsWorld->getConstraint(i);
- if (constraint->getUserConstraintId() == constraintId)
- {
- RemoveConstraint(constraint);
- break;
- }
- }
-
- WrapperVehicle *vehicle;
- if ((vehicle = (WrapperVehicle*)GetVehicleConstraint(constraintId)))
- {
- m_dynamicsWorld->removeVehicle(vehicle->GetVehicle());
- m_wrapperVehicles.erase(std::remove(m_wrapperVehicles.begin(), m_wrapperVehicles.end(), vehicle));
- delete vehicle;
- }
-}
-
-
-struct FilterClosestRayResultCallback : public btCollisionWorld::ClosestRayResultCallback
-{
- PHY_IRayCastFilterCallback& m_phyRayFilter;
- const btCollisionShape* m_hitTriangleShape;
- int m_hitTriangleIndex;
-
-
- FilterClosestRayResultCallback (PHY_IRayCastFilterCallback& phyRayFilter,const btVector3& rayFrom,const btVector3& rayTo)
- : btCollisionWorld::ClosestRayResultCallback(rayFrom,rayTo),
- m_phyRayFilter(phyRayFilter),
- m_hitTriangleShape(NULL),
- m_hitTriangleIndex(0)
- {
- }
-
- virtual ~FilterClosestRayResultCallback()
- {
- }
-
- virtual bool needsCollision(btBroadphaseProxy* proxy0) const
- {
- if (!(proxy0->m_collisionFilterGroup & m_collisionFilterMask))
- return false;
- if (!(m_collisionFilterGroup & proxy0->m_collisionFilterMask))
- return false;
- btCollisionObject* object = (btCollisionObject*)proxy0->m_clientObject;
- CcdPhysicsController* phyCtrl = static_cast<CcdPhysicsController*>(object->getUserPointer());
- if (phyCtrl == m_phyRayFilter.m_ignoreController)
- return false;
- return m_phyRayFilter.needBroadphaseRayCast(phyCtrl);
- }
-
- virtual btScalar addSingleResult(btCollisionWorld::LocalRayResult& rayResult,bool normalInWorldSpace)
- {
- //CcdPhysicsController* curHit = static_cast<CcdPhysicsController*>(rayResult.m_collisionObject->getUserPointer());
- // save shape information as ClosestRayResultCallback::AddSingleResult() does not do it
- if (rayResult.m_localShapeInfo)
- {
- m_hitTriangleShape = rayResult.m_collisionObject->getCollisionShape();
- m_hitTriangleIndex = rayResult.m_localShapeInfo->m_triangleIndex;
- } else
- {
- m_hitTriangleShape = NULL;
- m_hitTriangleIndex = 0;
- }
- return ClosestRayResultCallback::addSingleResult(rayResult,normalInWorldSpace);
- }
-
-};
-
-static bool GetHitTriangle(btCollisionShape* shape, CcdShapeConstructionInfo* shapeInfo, int hitTriangleIndex, btVector3 triangle[])
-{
- // this code is copied from Bullet
- const unsigned char *vertexbase;
- int numverts;
- PHY_ScalarType type;
- int stride;
- const unsigned char *indexbase;
- int indexstride;
- int numfaces;
- PHY_ScalarType indicestype;
- btStridingMeshInterface* meshInterface = shapeInfo->GetMeshInterface();
-
- if (!meshInterface)
- return false;
-
- meshInterface->getLockedReadOnlyVertexIndexBase(
- &vertexbase,
- numverts,
- type,
- stride,
- &indexbase,
- indexstride,
- numfaces,
- indicestype,
- 0);
-
- unsigned int* gfxbase = (unsigned int*)(indexbase+hitTriangleIndex*indexstride);
- const btVector3& meshScaling = shape->getLocalScaling();
- for (int j=2;j>=0;j--)
- {
- int graphicsindex = (indicestype == PHY_SHORT) ? ((unsigned short *)gfxbase)[j] : gfxbase[j];
-
- btScalar* graphicsbase = (btScalar*)(vertexbase+graphicsindex*stride);
-
- triangle[j] = btVector3(graphicsbase[0]*meshScaling.getX(),graphicsbase[1]*meshScaling.getY(),graphicsbase[2]*meshScaling.getZ());
- }
- meshInterface->unLockReadOnlyVertexBase(0);
- return true;
-}
-
-PHY_IPhysicsController* CcdPhysicsEnvironment::RayTest(PHY_IRayCastFilterCallback &filterCallback, float fromX,float fromY,float fromZ, float toX,float toY,float toZ)
-{
- btVector3 rayFrom(fromX,fromY,fromZ);
- btVector3 rayTo(toX,toY,toZ);
-
- btVector3 hitPointWorld,normalWorld;
-
- //Either Ray Cast with or without filtering
-
- //btCollisionWorld::ClosestRayResultCallback rayCallback(rayFrom,rayTo);
- FilterClosestRayResultCallback rayCallback(filterCallback,rayFrom,rayTo);
-
-
- PHY_RayCastResult result;
- memset(&result, 0, sizeof(result));
-
- // don't collision with sensor object
- rayCallback.m_collisionFilterMask = CcdConstructionInfo::AllFilter ^ CcdConstructionInfo::SensorFilter;
- // use faster (less accurate) ray callback, works better with 0 collision margins
- rayCallback.m_flags |= btTriangleRaycastCallback::kF_UseSubSimplexConvexCastRaytest;
- //, ,filterCallback.m_faceNormal);
-
- m_dynamicsWorld->rayTest(rayFrom,rayTo,rayCallback);
- if (rayCallback.hasHit())
- {
- CcdPhysicsController* controller = static_cast<CcdPhysicsController*>(rayCallback.m_collisionObject->getUserPointer());
- result.m_controller = controller;
- result.m_hitPoint[0] = rayCallback.m_hitPointWorld.getX();
- result.m_hitPoint[1] = rayCallback.m_hitPointWorld.getY();
- result.m_hitPoint[2] = rayCallback.m_hitPointWorld.getZ();
-
- if (rayCallback.m_hitTriangleShape != NULL)
- {
- // identify the mesh polygon
- CcdShapeConstructionInfo* shapeInfo = controller->m_shapeInfo;
- if (shapeInfo)
- {
- btCollisionShape* shape = controller->GetCollisionObject()->getCollisionShape();
- if (shape->isCompound())
- {
- btCompoundShape* compoundShape = (btCompoundShape*)shape;
- CcdShapeConstructionInfo* compoundShapeInfo = shapeInfo;
- // need to search which sub-shape has been hit
- for (int i=0; i<compoundShape->getNumChildShapes(); i++)
- {
- shapeInfo = compoundShapeInfo->GetChildShape(i);
- shape=compoundShape->getChildShape(i);
- if (shape == rayCallback.m_hitTriangleShape)
- break;
- }
- }
- if (shape == rayCallback.m_hitTriangleShape &&
- rayCallback.m_hitTriangleIndex < shapeInfo->m_polygonIndexArray.size())
- {
- // save original collision shape triangle for soft body
- int hitTriangleIndex = rayCallback.m_hitTriangleIndex;
-
- result.m_meshObject = shapeInfo->GetMesh();
- if (shape->isSoftBody())
- {
- // soft body using different face numbering because of randomization
- // hopefully we have stored the original face number in m_tag
- const btSoftBody* softBody = static_cast<const btSoftBody*>(rayCallback.m_collisionObject);
- if (softBody->m_faces[hitTriangleIndex].m_tag != 0)
- {
- rayCallback.m_hitTriangleIndex = (int)((uintptr_t)(softBody->m_faces[hitTriangleIndex].m_tag)-1);
- }
- }
- // retrieve the original mesh polygon (in case of quad->tri conversion)
- result.m_polygon = shapeInfo->m_polygonIndexArray.at(rayCallback.m_hitTriangleIndex);
- // hit triangle in world coordinate, for face normal and UV coordinate
- btVector3 triangle[3];
- bool triangleOK = false;
- if (filterCallback.m_faceUV && (3*rayCallback.m_hitTriangleIndex) < shapeInfo->m_triFaceUVcoArray.size())
- {
- // interpolate the UV coordinate of the hit point
- CcdShapeConstructionInfo::UVco* uvCo = &shapeInfo->m_triFaceUVcoArray[3*rayCallback.m_hitTriangleIndex];
- // 1. get the 3 coordinate of the triangle in world space
- btVector3 v1, v2, v3;
- if (shape->isSoftBody())
- {
- // soft body give points directly in world coordinate
- const btSoftBody* softBody = static_cast<const btSoftBody*>(rayCallback.m_collisionObject);
- v1 = softBody->m_faces[hitTriangleIndex].m_n[0]->m_x;
- v2 = softBody->m_faces[hitTriangleIndex].m_n[1]->m_x;
- v3 = softBody->m_faces[hitTriangleIndex].m_n[2]->m_x;
- } else
- {
- // for rigid body we must apply the world transform
- triangleOK = GetHitTriangle(shape, shapeInfo, hitTriangleIndex, triangle);
- if (!triangleOK)
- // if we cannot get the triangle, no use to continue
- goto SKIP_UV_NORMAL;
- v1 = rayCallback.m_collisionObject->getWorldTransform()(triangle[0]);
- v2 = rayCallback.m_collisionObject->getWorldTransform()(triangle[1]);
- v3 = rayCallback.m_collisionObject->getWorldTransform()(triangle[2]);
- }
- // 2. compute barycentric coordinate of the hit point
- btVector3 v = v2-v1;
- btVector3 w = v3-v1;
- btVector3 u = v.cross(w);
- btScalar A = u.length();
-
- v = v2-rayCallback.m_hitPointWorld;
- w = v3-rayCallback.m_hitPointWorld;
- u = v.cross(w);
- btScalar A1 = u.length();
-
- v = rayCallback.m_hitPointWorld-v1;
- w = v3-v1;
- u = v.cross(w);
- btScalar A2 = u.length();
-
- btVector3 baryCo;
- baryCo.setX(A1/A);
- baryCo.setY(A2/A);
- baryCo.setZ(1.0f-baryCo.getX()-baryCo.getY());
- // 3. compute UV coordinate
- result.m_hitUV[0] = baryCo.getX()*uvCo[0].uv[0] + baryCo.getY()*uvCo[1].uv[0] + baryCo.getZ()*uvCo[2].uv[0];
- result.m_hitUV[1] = baryCo.getX()*uvCo[0].uv[1] + baryCo.getY()*uvCo[1].uv[1] + baryCo.getZ()*uvCo[2].uv[1];
- result.m_hitUVOK = 1;
- }
-
- // Bullet returns the normal from "outside".
- // If the user requests the real normal, compute it now
- if (filterCallback.m_faceNormal)
- {
- if (shape->isSoftBody())
- {
- // we can get the real normal directly from the body
- const btSoftBody* softBody = static_cast<const btSoftBody*>(rayCallback.m_collisionObject);
- rayCallback.m_hitNormalWorld = softBody->m_faces[hitTriangleIndex].m_normal;
- } else
- {
- if (!triangleOK)
- triangleOK = GetHitTriangle(shape, shapeInfo, hitTriangleIndex, triangle);
- if (triangleOK)
- {
- btVector3 triangleNormal;
- triangleNormal = (triangle[1]-triangle[0]).cross(triangle[2]-triangle[0]);
- rayCallback.m_hitNormalWorld = rayCallback.m_collisionObject->getWorldTransform().getBasis()*triangleNormal;
- }
- }
- }
- SKIP_UV_NORMAL:
- ;
- }
- }
- }
- if (rayCallback.m_hitNormalWorld.length2() > (SIMD_EPSILON*SIMD_EPSILON))
- {
- rayCallback.m_hitNormalWorld.normalize();
- } else
- {
- rayCallback.m_hitNormalWorld.setValue(1,0,0);
- }
- result.m_hitNormal[0] = rayCallback.m_hitNormalWorld.getX();
- result.m_hitNormal[1] = rayCallback.m_hitNormalWorld.getY();
- result.m_hitNormal[2] = rayCallback.m_hitNormalWorld.getZ();
- filterCallback.reportHit(&result);
- }
-
-
- return result.m_controller;
-}
-
-// Handles occlusion culling.
-// The implementation is based on the CDTestFramework
-struct OcclusionBuffer
-{
- struct WriteOCL
- {
- static inline bool Process(btScalar &q, btScalar v)
- {
- if (q < v) {
- q = v;
- }
- return false;
- }
- static inline void Occlusion(bool &flag)
- {
- flag = true;
- }
- };
-
- struct QueryOCL
- {
- static inline bool Process(btScalar &q, btScalar v)
- {
- return (q <= v);
- }
- static inline void Occlusion(bool &flag)
- {
- }
- };
-
- btScalar *m_buffer;
- size_t m_bufferSize;
- bool m_initialized;
- bool m_occlusion;
- int m_sizes[2];
- btScalar m_scales[2];
- btScalar m_offsets[2];
- btScalar m_wtc[16]; // world to clip transform
- btScalar m_mtc[16]; // model to clip transform
- // constructor: size=largest dimension of the buffer.
- // Buffer size depends on aspect ratio
- OcclusionBuffer()
- {
- m_initialized = false;
- m_occlusion = false;
- m_buffer = NULL;
- m_bufferSize = 0;
- }
- // multiplication of column major matrices: m = m1 * m2
- template<typename T1, typename T2>
- void CMmat4mul(btScalar *m, const T1 *m1, const T2 *m2)
- {
- m[0] = btScalar(m1[0] * m2[0] + m1[4] * m2[1] + m1[8] * m2[2] + m1[12] * m2[3]);
- m[1] = btScalar(m1[1] * m2[0] + m1[5] * m2[1] + m1[9] * m2[2] + m1[13] * m2[3]);
- m[2] = btScalar(m1[2] * m2[0] + m1[6] * m2[1] + m1[10] * m2[2] + m1[14] * m2[3]);
- m[3] = btScalar(m1[3] * m2[0] + m1[7] * m2[1] + m1[11] * m2[2] + m1[15] * m2[3]);
-
- m[4] = btScalar(m1[0] * m2[4] + m1[4] * m2[5] + m1[8] * m2[6] + m1[12] * m2[7]);
- m[5] = btScalar(m1[1] * m2[4] + m1[5] * m2[5] + m1[9] * m2[6] + m1[13] * m2[7]);
- m[6] = btScalar(m1[2] * m2[4] + m1[6] * m2[5] + m1[10] * m2[6] + m1[14] * m2[7]);
- m[7] = btScalar(m1[3] * m2[4] + m1[7] * m2[5] + m1[11] * m2[6] + m1[15] * m2[7]);
-
- m[8] = btScalar(m1[0] * m2[8] + m1[4] * m2[9] + m1[8] * m2[10] + m1[12] * m2[11]);
- m[9] = btScalar(m1[1] * m2[8] + m1[5] * m2[9] + m1[9] * m2[10] + m1[13] * m2[11]);
- m[10] = btScalar(m1[2] * m2[8] + m1[6] * m2[9] + m1[10] * m2[10] + m1[14] * m2[11]);
- m[11] = btScalar(m1[3] * m2[8] + m1[7] * m2[9] + m1[11] * m2[10] + m1[15] * m2[11]);
-
- m[12] = btScalar(m1[0] * m2[12] + m1[4] * m2[13] + m1[8] * m2[14] + m1[12] * m2[15]);
- m[13] = btScalar(m1[1] * m2[12] + m1[5] * m2[13] + m1[9] * m2[14] + m1[13] * m2[15]);
- m[14] = btScalar(m1[2] * m2[12] + m1[6] * m2[13] + m1[10] * m2[14] + m1[14] * m2[15]);
- m[15] = btScalar(m1[3] * m2[12] + m1[7] * m2[13] + m1[11] * m2[14] + m1[15] * m2[15]);
- }
-
- void setup(int size, const int *view, float modelview[16], float projection[16])
- {
- m_initialized = false;
- m_occlusion = false;
- // compute the size of the buffer
- int maxsize = (view[2] > view[3]) ? view[2] : view[3];
- assert(maxsize > 0);
- double ratio = 1.0 / (2 * maxsize);
- // ensure even number
- m_sizes[0] = 2 * ((int)(size * view[2] * ratio + 0.5));
- m_sizes[1] = 2 * ((int)(size * view[3] * ratio + 0.5));
- m_scales[0] = btScalar(m_sizes[0] / 2);
- m_scales[1] = btScalar(m_sizes[1] / 2);
- m_offsets[0] = m_scales[0] + 0.5f;
- m_offsets[1] = m_scales[1] + 0.5f;
- // prepare matrix
- // at this time of the rendering, the modelview matrix is the
- // world to camera transformation and the projection matrix is
- // camera to clip transformation. combine both so that
- CMmat4mul(m_wtc, projection, modelview);
- }
-
- void initialize()
- {
- size_t newsize = (m_sizes[0] * m_sizes[1]) * sizeof(btScalar);
- if (m_buffer) {
- // see if we can reuse
- if (newsize > m_bufferSize) {
- free(m_buffer);
- m_buffer = NULL;
- m_bufferSize = 0;
- }
- }
- if (!m_buffer) {
- m_buffer = (btScalar *)calloc(1, newsize);
- m_bufferSize = newsize;
- }
- else {
- // buffer exists already, just clears it
- memset(m_buffer, 0, newsize);
- }
- // memory allocate must succeed
- assert(m_buffer != NULL);
- m_initialized = true;
- m_occlusion = false;
- }
-
- void SetModelMatrix(float *fl)
- {
- CMmat4mul(m_mtc,m_wtc,fl);
- if (!m_initialized) {
- initialize();
- }
- }
-
- // transform a segment in world coordinate to clip coordinate
- void transformW(const btVector3 &x, btVector4 &t)
- {
- t[0] = x[0] * m_wtc[0] + x[1] * m_wtc[4] + x[2] * m_wtc[8] + m_wtc[12];
- t[1] = x[0] * m_wtc[1] + x[1] * m_wtc[5] + x[2] * m_wtc[9] + m_wtc[13];
- t[2] = x[0] * m_wtc[2] + x[1] * m_wtc[6] + x[2] * m_wtc[10] + m_wtc[14];
- t[3] = x[0] * m_wtc[3] + x[1] * m_wtc[7] + x[2] * m_wtc[11] + m_wtc[15];
- }
-
- void transformM(const float *x, btVector4 &t)
- {
- t[0] = x[0] * m_mtc[0] + x[1] * m_mtc[4] + x[2] * m_mtc[8] + m_mtc[12];
- t[1] = x[0] * m_mtc[1] + x[1] * m_mtc[5] + x[2] * m_mtc[9] + m_mtc[13];
- t[2] = x[0] * m_mtc[2] + x[1] * m_mtc[6] + x[2] * m_mtc[10] + m_mtc[14];
- t[3] = x[0] * m_mtc[3] + x[1] * m_mtc[7] + x[2] * m_mtc[11] + m_mtc[15];
- }
- // convert polygon to device coordinates
- static bool project(btVector4 *p, int n)
- {
- for (int i = 0; i < n; ++i) {
- p[i][2] = 1 / p[i][3];
- p[i][0] *= p[i][2];
- p[i][1] *= p[i][2];
- }
- return true;
- }
- // pi: closed polygon in clip coordinate, NP = number of segments
- // po: same polygon with clipped segments removed
- template <const int NP>
- static int clip(const btVector4 *pi, btVector4 *po)
- {
- btScalar s[2 * NP];
- btVector4 pn[2 * NP];
- int i, j, m, n, ni;
- // deal with near clipping
- for (i = 0, m = 0; i < NP; ++i) {
- s[i] = pi[i][2] + pi[i][3];
- if (s[i] < 0) {
- m += 1 << i;
- }
- }
- if (m == ((1 << NP) - 1)) {
- return 0;
- }
- if (m != 0) {
- for (i = NP - 1, j = 0, n = 0; j < NP; i = j++) {
- const btVector4 &a = pi[i];
- const btVector4 &b = pi[j];
- const btScalar t = s[i] / (a[3] + a[2] - b[3] - b[2]);
- if ((t > 0) && (t < 1)) {
- pn[n][0] = a[0] + (b[0] - a[0]) * t;
- pn[n][1] = a[1] + (b[1] - a[1]) * t;
- pn[n][2] = a[2] + (b[2] - a[2]) * t;
- pn[n][3] = a[3] + (b[3] - a[3]) * t;
- ++n;
- }
- if (s[j] > 0) {
- pn[n++] = b;
- }
- }
- // ready to test far clipping, start from the modified polygon
- pi = pn;
- ni = n;
- }
- else {
- // no clipping on the near plane, keep same vector
- ni = NP;
- }
- // now deal with far clipping
- for (i = 0, m = 0; i < ni; ++i) {
- s[i] = pi[i][2] - pi[i][3];
- if (s[i] > 0) {
- m += 1 << i;
- }
- }
- if (m == ((1 << ni) - 1)) {
- return 0;
- }
- if (m != 0) {
- for (i = ni - 1, j = 0, n = 0;j < ni; i = j++) {
- const btVector4 &a = pi[i];
- const btVector4 &b = pi[j];
- const btScalar t = s[i] / (a[2] - a[3] - b[2] + b[3]);
- if ((t > 0) && (t < 1)) {
- po[n][0] = a[0] + (b[0] - a[0]) * t;
- po[n][1] = a[1] + (b[1] - a[1]) * t;
- po[n][2] = a[2] + (b[2] - a[2]) * t;
- po[n][3] = a[3] + (b[3] - a[3]) * t;
- ++n;
- }
- if (s[j] < 0) {
- po[n++] = b;
- }
- }
- return n;
- }
- for (int i = 0; i < ni; ++i) {
- po[i] = pi[i];
- }
- return ni;
- }
- // write or check a triangle to buffer. a,b,c in device coordinates (-1,+1)
- template <typename POLICY>
- inline bool draw(const btVector4 &a,
- const btVector4 &b,
- const btVector4 &c,
- const float face,
- const btScalar minarea)
- {
- const btScalar a2 = btCross(b - a, c - a)[2];
- if ((face * a2) < 0.0f || btFabs(a2) < minarea) {
- return false;
- }
- // further down we are normally going to write to the Zbuffer, mark it so
- POLICY::Occlusion(m_occlusion);
-
- int x[3], y[3], ib = 1, ic = 2;
- btScalar z[3];
- x[0] = (int)(a.x() * m_scales[0] + m_offsets[0]);
- y[0] = (int)(a.y() * m_scales[1] + m_offsets[1]);
- z[0] = a.z();
- if (a2 < 0.f) {
- // negative aire is possible with double face => must
- // change the order of b and c otherwise the algorithm doesn't work
- ib = 2;
- ic = 1;
- }
- x[ib] = (int)(b.x() * m_scales[0] + m_offsets[0]);
- x[ic] = (int)(c.x() * m_scales[0] + m_offsets[0]);
- y[ib] = (int)(b.y() * m_scales[1] + m_offsets[1]);
- y[ic] = (int)(c.y() * m_scales[1] + m_offsets[1]);
- z[ib] = b.z();
- z[ic] = c.z();
- const int mix = btMax(0, btMin(x[0], btMin(x[1], x[2])));
- const int mxx = btMin(m_sizes[0], 1 + btMax(x[0], btMax(x[1], x[2])));
- const int miy = btMax(0, btMin(y[0], btMin(y[1], y[2])));
- const int mxy = btMin(m_sizes[1], 1 + btMax(y[0], btMax(y[1], y[2])));
- const int width = mxx - mix;
- const int height = mxy - miy;
- if ((width * height) <= 1) {
- // degenerated in at most one single pixel
- btScalar *scan = &m_buffer[miy * m_sizes[0] + mix];
- // use for loop to detect the case where width or height == 0
- for (int iy = miy; iy < mxy; ++iy) {
- for (int ix = mix; ix < mxx; ++ix) {
- if (POLICY::Process(*scan, z[0])) {
- return true;
- }
- if (POLICY::Process(*scan, z[1])) {
- return true;
- }
- if (POLICY::Process(*scan, z[2])) {
- return true;
- }
- }
- }
- }
- else if (width == 1) {
- // Degenerated in at least 2 vertical lines
- // The algorithm below doesn't work when face has a single pixel width
- // We cannot use general formulas because the plane is degenerated.
- // We have to interpolate along the 3 edges that overlaps and process each pixel.
- // sort the y coord to make formula simpler
- int ytmp;
- btScalar ztmp;
- if (y[0] > y[1]) {
- ytmp = y[1];
- y[1] = y[0];
- y[0] = ytmp;
- ztmp = z[1];
- z[1] = z[0];
- z[0] = ztmp;
- }
- if (y[0] > y[2]) {
- ytmp = y[2];
- y[2] = y[0];
- y[0] = ytmp;
- ztmp = z[2];
- z[2] = z[0];
- z[0] = ztmp;
- }
- if (y[1] > y[2]) {
- ytmp = y[2];
- y[2] = y[1];
- y[1] = ytmp;
- ztmp = z[2];
- z[2] = z[1];
- z[1] = ztmp;
- }
- int dy[] = {y[0] - y[1],
- y[1] - y[2],
- y[2] - y[0]};
- btScalar dzy[3];
- dzy[0] = (dy[0]) ? (z[0] - z[1]) / dy[0] : btScalar(0.0f);
- dzy[1] = (dy[1]) ? (z[1] - z[2]) / dy[1] : btScalar(0.0f);
- dzy[2] = (dy[2]) ? (z[2] - z[0]) / dy[2] : btScalar(0.0f);
- btScalar v[3] = {dzy[0] * (miy - y[0]) + z[0],
- dzy[1] * (miy - y[1]) + z[1],
- dzy[2] * (miy - y[2]) + z[2]};
- dy[0] = y[1] - y[0];
- dy[1] = y[0] - y[1];
- dy[2] = y[2] - y[0];
- btScalar *scan = &m_buffer[miy * m_sizes[0] + mix];
- for (int iy = miy; iy < mxy; ++iy) {
- if (dy[0] >= 0 && POLICY::Process(*scan, v[0])) {
- return true;
- }
- if (dy[1] >= 0 && POLICY::Process(*scan, v[1])) {
- return true;
- }
- if (dy[2] >= 0 && POLICY::Process(*scan, v[2])) {
- return true;
- }
- scan += m_sizes[0];
- v[0] += dzy[0];
- v[1] += dzy[1];
- v[2] += dzy[2];
- dy[0]--;
- dy[1]++;
- dy[2]--;
- }
- }
- else if (height == 1) {
- // Degenerated in at least 2 horizontal lines
- // The algorithm below doesn't work when face has a single pixel width
- // We cannot use general formulas because the plane is degenerated.
- // We have to interpolate along the 3 edges that overlaps and process each pixel.
- int xtmp;
- btScalar ztmp;
- if (x[0] > x[1]) {
- xtmp = x[1];
- x[1] = x[0];
- x[0] = xtmp;
- ztmp = z[1];
- z[1] = z[0];
- z[0] = ztmp;
- }
- if (x[0] > x[2]) {
- xtmp = x[2];
- x[2] = x[0];
- x[0] = xtmp;
- ztmp = z[2];
- z[2] = z[0];
- z[0] = ztmp;
- }
- if (x[1] > x[2]) {
- xtmp = x[2];
- x[2] = x[1];
- x[1] = xtmp;
- ztmp = z[2];
- z[2] = z[1];
- z[1] = ztmp;
- }
- int dx[] = {x[0] - x[1],
- x[1] - x[2],
- x[2] - x[0]};
- btScalar dzx[3];
- dzx[0] = (dx[0]) ? (z[0]-z[1]) / dx[0] : btScalar(0.0f);
- dzx[1] = (dx[1]) ? (z[1]-z[2]) / dx[1] : btScalar(0.0f);
- dzx[2] = (dx[2]) ? (z[2]-z[0]) / dx[2] : btScalar(0.0f);
- btScalar v[3] = {dzx[0] * (mix - x[0]) + z[0],
- dzx[1] * (mix - x[1]) + z[1],
- dzx[2] * (mix - x[2]) + z[2]};
- dx[0] = x[1] - x[0];
- dx[1] = x[0] - x[1];
- dx[2] = x[2] - x[0];
- btScalar *scan = &m_buffer[miy * m_sizes[0] + mix];
- for (int ix = mix; ix < mxx; ++ix) {
- if (dx[0] >= 0 && POLICY::Process(*scan, v[0])) {
- return true;
- }
- if (dx[1] >= 0 && POLICY::Process(*scan, v[1])) {
- return true;
- }
- if (dx[2] >= 0 && POLICY::Process(*scan, v[2])) {
- return true;
- }
- scan++;
- v[0] += dzx[0];
- v[1] += dzx[1];
- v[2] += dzx[2];
- dx[0]--;
- dx[1]++;
- dx[2]--;
- }
- }
- else {
- // general case
- const int dx[] = {y[0] - y[1],
- y[1] - y[2],
- y[2] - y[0]};
- const int dy[] = {x[1] - x[0] - dx[0] * width,
- x[2] - x[1] - dx[1] * width,
- x[0] - x[2] - dx[2] * width};
- const int a = x[2] * y[0] + x[0] * y[1] - x[2] * y[1] - x[0] * y[2] + x[1] * y[2] - x[1] * y[0];
- const btScalar ia = 1 / (btScalar)a;
- const btScalar dzx = ia * (y[2] * (z[1] - z[0]) + y[1] * (z[0] - z[2]) + y[0] * (z[2] - z[1]));
- const btScalar dzy = ia * (x[2] * (z[0] - z[1]) + x[0] * (z[1] - z[2]) + x[1] * (z[2] - z[0])) - (dzx * width);
- int c[] = {miy * x[1] + mix * y[0] - x[1] * y[0] - mix * y[1] + x[0] * y[1] - miy * x[0],
- miy * x[2] + mix * y[1] - x[2] * y[1] - mix * y[2] + x[1] * y[2] - miy * x[1],
- miy * x[0] + mix * y[2] - x[0] * y[2] - mix * y[0] + x[2] * y[0] - miy * x[2]};
- btScalar v = ia * ((z[2] * c[0]) + (z[0] * c[1]) + (z[1] * c[2]));
- btScalar *scan = &m_buffer[miy * m_sizes[0]];
-
- for (int iy = miy; iy < mxy; ++iy) {
- for (int ix = mix; ix < mxx; ++ix) {
- if ((c[0] >= 0) && (c[1] >= 0) && (c[2] >= 0)) {
- if (POLICY::Process(scan[ix], v)) {
- return true;
- }
- }
- c[0] += dx[0]; c[1] += dx[1]; c[2] += dx[2]; v += dzx;
- }
- c[0] += dy[0]; c[1] += dy[1]; c[2] += dy[2]; v += dzy;
- scan += m_sizes[0];
- }
- }
- return false;
- }
- // clip than write or check a polygon
- template <const int NP, typename POLICY>
- inline bool clipDraw(const btVector4 *p,
- const float face,
- btScalar minarea)
- {
- btVector4 o[NP * 2];
- int n = clip<NP>(p, o);
- bool earlyexit = false;
- if (n) {
- project(o, n);
- for (int i = 2; i < n && !earlyexit; ++i) {
- earlyexit |= draw<POLICY>(o[0], o[i - 1], o[i], face, minarea);
- }
- }
- return earlyexit;
- }
- // add a triangle (in model coordinate)
- // face = 0.f if face is double side,
- // = 1.f if face is single sided and scale is positive
- // = -1.f if face is single sided and scale is negative
- void appendOccluderM(const float *a,
- const float *b,
- const float *c,
- const float face)
- {
- btVector4 p[3];
- transformM(a, p[0]);
- transformM(b, p[1]);
- transformM(c, p[2]);
- clipDraw<3, WriteOCL>(p, face, btScalar(0.0f));
- }
- // add a quad (in model coordinate)
- void appendOccluderM(const float *a,
- const float *b,
- const float *c,
- const float *d,
- const float face)
- {
- btVector4 p[4];
- transformM(a, p[0]);
- transformM(b, p[1]);
- transformM(c, p[2]);
- transformM(d, p[3]);
- clipDraw<4, WriteOCL>(p, face, btScalar(0.0f));
- }
- // query occluder for a box (c=center, e=extend) in world coordinate
- inline bool queryOccluderW(const btVector3 &c,
- const btVector3 &e)
- {
- if (!m_occlusion) {
- // no occlusion yet, no need to check
- return true;
- }
- btVector4 x[8];
- transformW(btVector3(c[0] - e[0], c[1] - e[1], c[2] - e[2]), x[0]);
- transformW(btVector3(c[0] + e[0], c[1] - e[1], c[2] - e[2]), x[1]);
- transformW(btVector3(c[0] + e[0], c[1] + e[1], c[2] - e[2]), x[2]);
- transformW(btVector3(c[0] - e[0], c[1] + e[1], c[2] - e[2]), x[3]);
- transformW(btVector3(c[0] - e[0], c[1] - e[1], c[2] + e[2]), x[4]);
- transformW(btVector3(c[0] + e[0], c[1] - e[1], c[2] + e[2]), x[5]);
- transformW(btVector3(c[0] + e[0], c[1] + e[1], c[2] + e[2]), x[6]);
- transformW(btVector3(c[0] - e[0], c[1] + e[1], c[2] + e[2]), x[7]);
-
- for (int i = 0; i < 8; ++i) {
- // the box is clipped, it's probably a large box, don't waste our time to check
- if ((x[i][2] + x[i][3]) <= 0) {
- return true;
- }
- }
- static const int d[] = {1, 0, 3, 2,
- 4, 5, 6, 7,
- 4, 7, 3, 0,
- 6, 5, 1, 2,
- 7, 6, 2, 3,
- 5, 4, 0, 1};
- for (unsigned int i = 0; i < (sizeof(d) / sizeof(d[0]));) {
- const btVector4 p[] = {x[d[i + 0]],
- x[d[i + 1]],
- x[d[i + 2]],
- x[d[i + 3]]};
- i += 4;
- if (clipDraw<4, QueryOCL>(p, 1.0f, 0.0f)) {
- return true;
- }
- }
- return false;
- }
-};
-
-
-struct DbvtCullingCallback : btDbvt::ICollide
-{
- PHY_CullingCallback m_clientCallback;
- void* m_userData;
- OcclusionBuffer *m_ocb;
-
- DbvtCullingCallback(PHY_CullingCallback clientCallback, void* userData)
- {
- m_clientCallback = clientCallback;
- m_userData = userData;
- m_ocb = NULL;
- }
- bool Descent(const btDbvtNode* node)
- {
- return(m_ocb->queryOccluderW(node->volume.Center(),node->volume.Extents()));
- }
- void Process(const btDbvtNode* node,btScalar depth)
- {
- Process(node);
- }
- void Process(const btDbvtNode* leaf)
- {
- btBroadphaseProxy* proxy=(btBroadphaseProxy*)leaf->data;
- // the client object is a graphic controller
- CcdGraphicController* ctrl = static_cast<CcdGraphicController*>(proxy->m_clientObject);
- KX_ClientObjectInfo *info = (KX_ClientObjectInfo*)ctrl->GetNewClientInfo();
- if (m_ocb)
- {
- // means we are doing occlusion culling. Check if this object is an occluders
- KX_GameObject* gameobj = KX_GameObject::GetClientObject(info);
- if (gameobj && gameobj->GetOccluder())
- {
- float *fl = gameobj->GetOpenGLMatrixPtr()->getPointer();
- // this will create the occlusion buffer if not already done
- // and compute the transformation from model local space to clip space
- m_ocb->SetModelMatrix(fl);
- float face = (gameobj->IsNegativeScaling()) ? -1.0f : 1.0f;
- // walk through the meshes and for each add to buffer
- for (int i=0; i<gameobj->GetMeshCount(); i++)
- {
- RAS_MeshObject* meshobj = gameobj->GetMesh(i);
- const float *v1, *v2, *v3, *v4;
-
- int polycount = meshobj->NumPolygons();
- for (int j=0; j<polycount; j++)
- {
- RAS_Polygon* poly = meshobj->GetPolygon(j);
- switch (poly->VertexCount())
- {
- case 3:
- v1 = poly->GetVertex(0)->getXYZ();
- v2 = poly->GetVertex(1)->getXYZ();
- v3 = poly->GetVertex(2)->getXYZ();
- m_ocb->appendOccluderM(v1,v2,v3,((poly->IsTwoside())?0.f:face));
- break;
- case 4:
- v1 = poly->GetVertex(0)->getXYZ();
- v2 = poly->GetVertex(1)->getXYZ();
- v3 = poly->GetVertex(2)->getXYZ();
- v4 = poly->GetVertex(3)->getXYZ();
- m_ocb->appendOccluderM(v1,v2,v3,v4,((poly->IsTwoside())?0.f:face));
- break;
- }
- }
- }
- }
- }
- if (info)
- (*m_clientCallback)(info, m_userData);
- }
-};
-
-static OcclusionBuffer gOcb;
-bool CcdPhysicsEnvironment::CullingTest(PHY_CullingCallback callback, void* userData, MT_Vector4 *planes, int nplanes, int occlusionRes, const int *viewport, float modelview[16], float projection[16])
-{
- if (!m_cullingTree)
- return false;
- DbvtCullingCallback dispatcher(callback, userData);
- btVector3 planes_n[6];
- btScalar planes_o[6];
- if (nplanes > 6)
- nplanes = 6;
- for (int i=0; i<nplanes; i++)
- {
- planes_n[i].setValue(planes[i][0], planes[i][1], planes[i][2]);
- planes_o[i] = planes[i][3];
- }
- // if occlusionRes != 0 => occlusion culling
- if (occlusionRes)
- {
- gOcb.setup(occlusionRes, viewport, modelview, projection);
- dispatcher.m_ocb = &gOcb;
- // occlusion culling, the direction of the view is taken from the first plan which MUST be the near plane
- btDbvt::collideOCL(m_cullingTree->m_sets[1].m_root,planes_n,planes_o,planes_n[0],nplanes,dispatcher);
- btDbvt::collideOCL(m_cullingTree->m_sets[0].m_root,planes_n,planes_o,planes_n[0],nplanes,dispatcher);
- }
- else {
- btDbvt::collideKDOP(m_cullingTree->m_sets[1].m_root,planes_n,planes_o,nplanes,dispatcher);
- btDbvt::collideKDOP(m_cullingTree->m_sets[0].m_root,planes_n,planes_o,nplanes,dispatcher);
- }
- return true;
-}
-
-int CcdPhysicsEnvironment::GetNumContactPoints()
-{
- return 0;
-}
-
-void CcdPhysicsEnvironment::GetContactPoint(int i,float& hitX,float& hitY,float& hitZ,float& normalX,float& normalY,float& normalZ)
-{
-
-}
-
-
-
-
-btBroadphaseInterface* CcdPhysicsEnvironment::GetBroadphase()
-{
- return m_dynamicsWorld->getBroadphase();
-}
-
-btDispatcher* CcdPhysicsEnvironment::GetDispatcher()
-{
- return m_dynamicsWorld->getDispatcher();
-}
-
-void CcdPhysicsEnvironment::MergeEnvironment(PHY_IPhysicsEnvironment *other_env)
-{
- CcdPhysicsEnvironment *other = dynamic_cast<CcdPhysicsEnvironment*>(other_env);
- if (other == NULL) {
- printf("KX_Scene::MergeScene: Other scene is not using Bullet physics, not merging physics.\n");
- return;
- }
-
- std::set<CcdPhysicsController*>::iterator it;
-
- while (other->m_controllers.begin() != other->m_controllers.end())
- {
- it= other->m_controllers.begin();
- CcdPhysicsController* ctrl= (*it);
-
- other->RemoveCcdPhysicsController(ctrl);
- this->AddCcdPhysicsController(ctrl);
- }
-}
-
-CcdPhysicsEnvironment::~CcdPhysicsEnvironment()
-{
-
-#ifdef NEW_BULLET_VEHICLE_SUPPORT
- m_wrapperVehicles.clear();
-#endif //NEW_BULLET_VEHICLE_SUPPORT
-
- //m_broadphase->DestroyScene();
- //delete broadphase ? release reference on broadphase ?
-
- //first delete scene, then dispatcher, because pairs have to release manifolds on the dispatcher
- //delete m_dispatcher;
- delete m_dynamicsWorld;
-
-
- if (NULL != m_ownPairCache)
- delete m_ownPairCache;
-
- if (NULL != m_ownDispatcher)
- delete m_ownDispatcher;
-
- if (NULL != m_solver)
- delete m_solver;
-
- if (NULL != m_debugDrawer)
- delete m_debugDrawer;
-
- if (NULL != m_filterCallback)
- delete m_filterCallback;
-
- if (NULL != m_ghostPairCallback)
- delete m_ghostPairCallback;
-
- if (NULL != m_collisionConfiguration)
- delete m_collisionConfiguration;
-
- if (NULL != m_broadphase)
- delete m_broadphase;
-
- if (NULL != m_cullingTree)
- delete m_cullingTree;
-
- if (NULL != m_cullingCache)
- delete m_cullingCache;
-
-}
-
-
-float CcdPhysicsEnvironment::GetConstraintParam(int constraintId,int param)
-{
- btTypedConstraint* typedConstraint = GetConstraintById(constraintId);
- if (!typedConstraint)
- return 0.0f;
-
- switch (typedConstraint->getUserConstraintType())
- {
- case PHY_GENERIC_6DOF_CONSTRAINT:
- {
-
- switch (param)
- {
- case 0: case 1: case 2:
- {
- //param = 0..2 are linear constraint values
- btGeneric6DofConstraint* genCons = (btGeneric6DofConstraint*)typedConstraint;
- genCons->calculateTransforms();
- return genCons->getRelativePivotPosition(param);
- break;
- }
- case 3: case 4: case 5:
- {
- //param = 3..5 are relative constraint (Euler) angles
- btGeneric6DofConstraint* genCons = (btGeneric6DofConstraint*)typedConstraint;
- genCons->calculateTransforms();
- return genCons->getAngle(param-3);
- break;
- }
- default:
- {
- }
- }
- break;
- };
- default:
- {
- };
- };
- return 0.f;
-}
-
-void CcdPhysicsEnvironment::SetConstraintParam(int constraintId,int param,float value0,float value1)
-{
- btTypedConstraint* typedConstraint = GetConstraintById(constraintId);
- if (!typedConstraint)
- return;
-
- switch (typedConstraint->getUserConstraintType())
- {
- case PHY_GENERIC_6DOF_CONSTRAINT:
- {
-
- switch (param)
- {
- case 0: case 1: case 2: case 3: case 4: case 5:
- {
- //param = 0..5 are constraint limits, with low/high limit value
- btGeneric6DofConstraint* genCons = (btGeneric6DofConstraint*)typedConstraint;
- genCons->setLimit(param,value0,value1);
- break;
- }
- case 6: case 7: case 8:
- {
- //param = 6,7,8 are translational motors, with value0=target velocity, value1 = max motor force
- btGeneric6DofConstraint* genCons = (btGeneric6DofConstraint*)typedConstraint;
- int transMotorIndex = param-6;
- btTranslationalLimitMotor* transMotor = genCons->getTranslationalLimitMotor();
- transMotor->m_targetVelocity[transMotorIndex] = value0;
- transMotor->m_maxMotorForce[transMotorIndex] = value1;
- transMotor->m_enableMotor[transMotorIndex] = (value1>0.f);
- break;
- }
- case 9: case 10: case 11:
- {
- //param = 9,10,11 are rotational motors, with value0=target velocity, value1 = max motor force
- btGeneric6DofConstraint* genCons = (btGeneric6DofConstraint*)typedConstraint;
- int angMotorIndex = param-9;
- btRotationalLimitMotor* rotMotor = genCons->getRotationalLimitMotor(angMotorIndex);
- rotMotor->m_enableMotor = (value1 > 0.f);
- rotMotor->m_targetVelocity = value0;
- rotMotor->m_maxMotorForce = value1;
- break;
- }
-
- case 12: case 13: case 14: case 15: case 16: case 17:
- {
- //param 12-17 are for motorized springs on each of the degrees of freedom
- btGeneric6DofSpringConstraint* genCons = (btGeneric6DofSpringConstraint*)typedConstraint;
- int springIndex = param-12;
- if (value0!=0.f)
- {
- bool springEnabled = true;
- genCons->setStiffness(springIndex,value0);
- genCons->setDamping(springIndex,value1);
- genCons->enableSpring(springIndex,springEnabled);
- genCons->setEquilibriumPoint(springIndex);
- } else
- {
- bool springEnabled = false;
- genCons->enableSpring(springIndex,springEnabled);
- }
- break;
- }
-
- default:
- {
- }
- };
- break;
- };
- case PHY_CONE_TWIST_CONSTRAINT:
- {
- switch (param)
- {
- case 3: case 4: case 5:
- {
- //param = 3,4,5 are constraint limits, high limit values
- btConeTwistConstraint* coneTwist = (btConeTwistConstraint*)typedConstraint;
- if (value1<0.0f)
- coneTwist->setLimit(param,btScalar(BT_LARGE_FLOAT));
- else
- coneTwist->setLimit(param,value1);
- break;
- }
- default:
- {
- }
- };
- break;
- };
- case PHY_ANGULAR_CONSTRAINT:
- case PHY_LINEHINGE_CONSTRAINT:
- {
- switch (param)
- {
- case 3:
- {
- //param = 3 is a constraint limit, with low/high limit value
- btHingeConstraint* hingeCons = (btHingeConstraint*)typedConstraint;
- hingeCons->setLimit(value0,value1);
- break;
- }
- default:
- {
- }
- }
- break;
- };
- default:
- {
- };
- };
-}
-
-btTypedConstraint* CcdPhysicsEnvironment::GetConstraintById(int constraintId)
-{
- // For soft body constraints
- if (constraintId == 0)
- return NULL;
-
- int numConstraints = m_dynamicsWorld->getNumConstraints();
- int i;
- for (i=0;i<numConstraints;i++)
- {
- btTypedConstraint* constraint = m_dynamicsWorld->getConstraint(i);
- if (constraint->getUserConstraintId()==constraintId)
- {
- return constraint;
- }
- }
- return 0;
-}
-
-
-void CcdPhysicsEnvironment::AddSensor(PHY_IPhysicsController* ctrl)
-{
- CcdPhysicsController* ctrl1 = (CcdPhysicsController* )ctrl;
- AddCcdPhysicsController(ctrl1);
-}
-
-bool CcdPhysicsEnvironment::RemoveCollisionCallback(PHY_IPhysicsController* ctrl)
-{
- CcdPhysicsController* ccdCtrl = (CcdPhysicsController*)ctrl;
- return ccdCtrl->Unregister();
-}
-
-
-void CcdPhysicsEnvironment::RemoveSensor(PHY_IPhysicsController* ctrl)
-{
- RemoveCcdPhysicsController((CcdPhysicsController*)ctrl);
-}
-
-void CcdPhysicsEnvironment::AddTouchCallback(int response_class, PHY_ResponseCallback callback, void *user)
-{
- /* printf("addTouchCallback\n(response class = %i)\n",response_class);
-
- //map PHY_ convention into SM_ convention
- switch (response_class)
- {
- case PHY_FH_RESPONSE:
- printf("PHY_FH_RESPONSE\n");
- break;
- case PHY_SENSOR_RESPONSE:
- printf("PHY_SENSOR_RESPONSE\n");
- break;
- case PHY_CAMERA_RESPONSE:
- printf("PHY_CAMERA_RESPONSE\n");
- break;
- case PHY_OBJECT_RESPONSE:
- printf("PHY_OBJECT_RESPONSE\n");
- break;
- case PHY_STATIC_RESPONSE:
- printf("PHY_STATIC_RESPONSE\n");
- break;
- default:
- assert(0);
- return;
- }
- */
-
- m_triggerCallbacks[response_class] = callback;
- m_triggerCallbacksUserPtrs[response_class] = user;
-
-}
-bool CcdPhysicsEnvironment::RequestCollisionCallback(PHY_IPhysicsController* ctrl)
-{
- CcdPhysicsController* ccdCtrl = static_cast<CcdPhysicsController*>(ctrl);
- return ccdCtrl->Register();
-}
-
-void CcdPhysicsEnvironment::CallbackTriggers()
-{
- bool draw_contact_points = m_debugDrawer && (m_debugDrawer->getDebugMode() & btIDebugDraw::DBG_DrawContactPoints);
-
- if (!m_triggerCallbacks[PHY_OBJECT_RESPONSE] && !draw_contact_points)
- return;
-
- //walk over all overlapping pairs, and if one of the involved bodies is registered for trigger callback, perform callback
- btDispatcher* dispatcher = m_dynamicsWorld->getDispatcher();
- int numManifolds = dispatcher->getNumManifolds();
- for (int i=0;i<numManifolds;i++)
- {
- bool colliding_ctrl0 = true;
- btPersistentManifold* manifold = dispatcher->getManifoldByIndexInternal(i);
- int numContacts = manifold->getNumContacts();
- if (!numContacts) continue;
-
- const btRigidBody* rb0 = static_cast<const btRigidBody*>(manifold->getBody0());
- const btRigidBody* rb1 = static_cast<const btRigidBody*>(manifold->getBody1());
- if (draw_contact_points)
- {
- for (int j=0;j<numContacts;j++)
- {
- btVector3 color(1,1,0);
- const btManifoldPoint& cp = manifold->getContactPoint(j);
- m_debugDrawer->drawContactPoint(cp.m_positionWorldOnB,
- cp.m_normalWorldOnB,
- cp.getDistance(),
- cp.getLifeTime(),
- color);
- }
- }
-
- //m_internalOwner is set in 'addPhysicsController'
- CcdPhysicsController* ctrl0 = static_cast<CcdPhysicsController*>(rb0->getUserPointer());
- CcdPhysicsController* ctrl1 = static_cast<CcdPhysicsController*>(rb1->getUserPointer());
- bool usecallback = false;
-
- // Test if one of the controller is registered and use collision callback.
- if (ctrl0->Registered())
- usecallback = true;
- else if (ctrl1->Registered()) {
- colliding_ctrl0 = false;
- usecallback = true;
- }
-
- if (usecallback) {
- static PHY_CollData coll_data;
- const btManifoldPoint &cp = manifold->getContactPoint(0);
-
- /* Make sure that "point1" is always on the object we report on, and
- * "point2" on the other object. Also ensure the normal is oriented
- * correctly. */
- btVector3 point1 = colliding_ctrl0 ? cp.m_positionWorldOnA : cp.m_positionWorldOnB;
- btVector3 point2 = colliding_ctrl0 ? cp.m_positionWorldOnB : cp.m_positionWorldOnA;
- btVector3 normal = colliding_ctrl0 ? -cp.m_normalWorldOnB : cp.m_normalWorldOnB;
-
- coll_data.m_point1 = MT_Vector3(point1.m_floats);
- coll_data.m_point2 = MT_Vector3(point2.m_floats);
- coll_data.m_normal = MT_Vector3(normal.m_floats);
-
- m_triggerCallbacks[PHY_OBJECT_RESPONSE](m_triggerCallbacksUserPtrs[PHY_OBJECT_RESPONSE],
- ctrl0, ctrl1, &coll_data);
- }
- // Bullet does not refresh the manifold contact point for object without contact response
- // may need to remove this when a newer Bullet version is integrated
- if (!dispatcher->needsResponse(rb0, rb1))
- {
- // Refresh algorithm fails sometimes when there is penetration
- // (usuall the case with ghost and sensor objects)
- // Let's just clear the manifold, in any case, it is recomputed on each frame.
- manifold->clearManifold(); //refreshContactPoints(rb0->getCenterOfMassTransform(),rb1->getCenterOfMassTransform());
- }
- }
-}
-
-// This call back is called before a pair is added in the cache
-// Handy to remove objects that must be ignored by sensors
-bool CcdOverlapFilterCallBack::needBroadphaseCollision(btBroadphaseProxy* proxy0,btBroadphaseProxy* proxy1) const
-{
- btCollisionObject *colObj0, *colObj1;
- CcdPhysicsController *sensorCtrl, *objCtrl;
-
- KX_GameObject *kxObj0 = KX_GameObject::GetClientObject(
- (KX_ClientObjectInfo*)
- ((CcdPhysicsController*)
- (((btCollisionObject*)proxy0->m_clientObject)->getUserPointer()))
- ->GetNewClientInfo());
- KX_GameObject *kxObj1 = KX_GameObject::GetClientObject(
- (KX_ClientObjectInfo*)
- ((CcdPhysicsController*)
- (((btCollisionObject*)proxy1->m_clientObject)->getUserPointer()))
- ->GetNewClientInfo());
-
- // First check the filters. Note that this is called during scene
- // conversion, so we can't assume the KX_GameObject instances exist. This
- // may make some objects erroneously collide on the first frame, but the
- // alternative is to have them erroneously miss.
- bool collides;
- collides = (proxy0->m_collisionFilterGroup & proxy1->m_collisionFilterMask) != 0;
- collides = collides && (proxy1->m_collisionFilterGroup & proxy0->m_collisionFilterMask);
- if (kxObj0 && kxObj1) {
- collides = collides && kxObj0->CheckCollision(kxObj1);
- collides = collides && kxObj1->CheckCollision(kxObj0);
- }
- if (!collides)
- return false;
-
- // additional check for sensor object
- if (proxy0->m_collisionFilterGroup & btBroadphaseProxy::SensorTrigger)
- {
- // this is a sensor object, the other one can't be a sensor object because
- // they exclude each other in the above test
- assert(!(proxy1->m_collisionFilterGroup & btBroadphaseProxy::SensorTrigger));
- colObj0 = (btCollisionObject*)proxy0->m_clientObject;
- colObj1 = (btCollisionObject*)proxy1->m_clientObject;
- }
- else if (proxy1->m_collisionFilterGroup & btBroadphaseProxy::SensorTrigger)
- {
- colObj0 = (btCollisionObject*)proxy1->m_clientObject;
- colObj1 = (btCollisionObject*)proxy0->m_clientObject;
- }
- else
- {
- return true;
- }
- if (!colObj0 || !colObj1)
- return false;
- sensorCtrl = static_cast<CcdPhysicsController*>(colObj0->getUserPointer());
- objCtrl = static_cast<CcdPhysicsController*>(colObj1->getUserPointer());
- if (m_physEnv->m_triggerCallbacks[PHY_BROADPH_RESPONSE])
- {
- return m_physEnv->m_triggerCallbacks[PHY_BROADPH_RESPONSE](m_physEnv->m_triggerCallbacksUserPtrs[PHY_BROADPH_RESPONSE], sensorCtrl, objCtrl, 0);
- }
- return true;
-}
-
-
-#ifdef NEW_BULLET_VEHICLE_SUPPORT
-
-//complex constraint for vehicles
-PHY_IVehicle* CcdPhysicsEnvironment::GetVehicleConstraint(int constraintId)
-{
- int i;
-
- int numVehicles = m_wrapperVehicles.size();
- for (i=0;i<numVehicles;i++)
- {
- WrapperVehicle* wrapperVehicle = m_wrapperVehicles[i];
- if (wrapperVehicle->GetVehicle()->getUserConstraintId() == constraintId)
- return wrapperVehicle;
- }
-
- return 0;
-}
-
-#endif //NEW_BULLET_VEHICLE_SUPPORT
-
-
-PHY_ICharacter* CcdPhysicsEnvironment::GetCharacterController(KX_GameObject *ob)
-{
- CcdPhysicsController* controller = (CcdPhysicsController*)ob->GetPhysicsController();
- return (controller) ? dynamic_cast<BlenderBulletCharacterController*>(controller->GetCharacterController()) : NULL;
-}
-
-
-PHY_IPhysicsController* CcdPhysicsEnvironment::CreateSphereController(float radius,const MT_Vector3& position)
-{
-
- CcdConstructionInfo cinfo;
- memset(&cinfo, 0, sizeof(cinfo)); /* avoid uninitialized values */
- cinfo.m_collisionShape = new btSphereShape(radius); // memory leak! The shape is not deleted by Bullet and we cannot add it to the KX_Scene.m_shapes list
- cinfo.m_MotionState = 0;
- cinfo.m_physicsEnv = this;
- // declare this object as Dyamic rather than static!!
- // The reason as it is designed to detect all type of object, including static object
- // It would cause static-static message to be printed on the console otherwise
- cinfo.m_collisionFlags |= btCollisionObject::CF_NO_CONTACT_RESPONSE | btCollisionObject::CF_STATIC_OBJECT;
- DefaultMotionState* motionState = new DefaultMotionState();
- cinfo.m_MotionState = motionState;
- // we will add later the possibility to select the filter from option
- cinfo.m_collisionFilterMask = CcdConstructionInfo::AllFilter ^ CcdConstructionInfo::SensorFilter;
- cinfo.m_collisionFilterGroup = CcdConstructionInfo::SensorFilter;
- cinfo.m_bSensor = true;
- motionState->m_worldTransform.setIdentity();
- motionState->m_worldTransform.setOrigin(btVector3(position[0],position[1],position[2]));
-
- CcdPhysicsController* sphereController = new CcdPhysicsController(cinfo);
-
- return sphereController;
-}
-
-int findClosestNode(btSoftBody* sb,const btVector3& worldPoint);
-int findClosestNode(btSoftBody* sb,const btVector3& worldPoint)
-{
- int node = -1;
-
- btSoftBody::tNodeArray& nodes(sb->m_nodes);
- float maxDistSqr = 1e30f;
-
- for (int n=0;n<nodes.size();n++)
- {
- btScalar distSqr = (nodes[n].m_x - worldPoint).length2();
- if (distSqr<maxDistSqr)
- {
- maxDistSqr = distSqr;
- node = n;
- }
- }
- return node;
-}
-
-int CcdPhysicsEnvironment::CreateConstraint(class PHY_IPhysicsController* ctrl0,class PHY_IPhysicsController* ctrl1,PHY_ConstraintType type,
- float pivotX,float pivotY,float pivotZ,
- float axisX,float axisY,float axisZ,
- float axis1X,float axis1Y,float axis1Z,
- float axis2X,float axis2Y,float axis2Z,int flags
- )
-{
-
- bool disableCollisionBetweenLinkedBodies = (0!=(flags & CCD_CONSTRAINT_DISABLE_LINKED_COLLISION));
-
-
-
- CcdPhysicsController* c0 = (CcdPhysicsController*)ctrl0;
- CcdPhysicsController* c1 = (CcdPhysicsController*)ctrl1;
-
- btRigidBody* rb0 = c0 ? c0->GetRigidBody() : 0;
- btRigidBody* rb1 = c1 ? c1->GetRigidBody() : 0;
-
-
-
-
- bool rb0static = rb0 ? rb0->isStaticOrKinematicObject() : true;
- bool rb1static = rb1 ? rb1->isStaticOrKinematicObject() : true;
-
- btCollisionObject* colObj0 = c0->GetCollisionObject();
- if (!colObj0)
- {
- return 0;
- }
-
- btVector3 pivotInA(pivotX,pivotY,pivotZ);
-
-
-
- //it might be a soft body, let's try
- btSoftBody* sb0 = c0 ? c0->GetSoftBody() : 0;
- btSoftBody* sb1 = c1 ? c1->GetSoftBody() : 0;
- if (sb0 && sb1)
- {
- //not between two soft bodies?
- return 0;
- }
-
- if (sb0)
- {
- //either cluster or node attach, let's find closest node first
- //the soft body doesn't have a 'real' world transform, so get its initial world transform for now
- btVector3 pivotPointSoftWorld = sb0->m_initialWorldTransform(pivotInA);
- int node=findClosestNode(sb0,pivotPointSoftWorld);
- if (node >=0)
- {
- bool clusterconstaint = false;
-/*
- switch (type)
- {
- case PHY_LINEHINGE_CONSTRAINT:
- {
- if (sb0->clusterCount() && rb1)
- {
- btSoftBody::LJoint::Specs ls;
- ls.erp=0.5f;
- ls.position=sb0->clusterCom(0);
- sb0->appendLinearJoint(ls,rb1);
- clusterconstaint = true;
- break;
- }
- }
- case PHY_GENERIC_6DOF_CONSTRAINT:
- {
- if (sb0->clusterCount() && rb1)
- {
- btSoftBody::AJoint::Specs as;
- as.erp = 1;
- as.cfm = 1;
- as.axis.setValue(axisX,axisY,axisZ);
- sb0->appendAngularJoint(as,rb1);
- clusterconstaint = true;
- break;
- }
-
- break;
- }
- default:
- {
-
- }
- };
- */
-
- if (!clusterconstaint)
- {
- if (rb1)
- {
- sb0->appendAnchor(node,rb1,disableCollisionBetweenLinkedBodies);
- } else
- {
- sb0->setMass(node,0.f);
- }
- }
-
-
- }
- return 0;//can't remove soft body anchors yet
- }
-
- if (sb1)
- {
- btVector3 pivotPointAWorld = colObj0->getWorldTransform()(pivotInA);
- int node=findClosestNode(sb1,pivotPointAWorld);
- if (node >=0)
- {
- bool clusterconstaint = false;
-
- /*
- switch (type)
- {
- case PHY_LINEHINGE_CONSTRAINT:
- {
- if (sb1->clusterCount() && rb0)
- {
- btSoftBody::LJoint::Specs ls;
- ls.erp=0.5f;
- ls.position=sb1->clusterCom(0);
- sb1->appendLinearJoint(ls,rb0);
- clusterconstaint = true;
- break;
- }
- }
- case PHY_GENERIC_6DOF_CONSTRAINT:
- {
- if (sb1->clusterCount() && rb0)
- {
- btSoftBody::AJoint::Specs as;
- as.erp = 1;
- as.cfm = 1;
- as.axis.setValue(axisX,axisY,axisZ);
- sb1->appendAngularJoint(as,rb0);
- clusterconstaint = true;
- break;
- }
-
- break;
- }
- default:
- {
-
-
- }
- };*/
-
-
- if (!clusterconstaint)
- {
- if (rb0)
- {
- sb1->appendAnchor(node,rb0,disableCollisionBetweenLinkedBodies);
- } else
- {
- sb1->setMass(node,0.f);
- }
- }
-
-
- }
- return 0;//can't remove soft body anchors yet
- }
-
- if (rb0static && rb1static)
- {
-
- return 0;
- }
-
-
- if (!rb0)
- return 0;
-
- btVector3 pivotInB = rb1 ? rb1->getCenterOfMassTransform().inverse()(rb0->getCenterOfMassTransform()(pivotInA)) :
- rb0->getCenterOfMassTransform() * pivotInA;
- btVector3 axisInA(axisX,axisY,axisZ);
-
-
- bool angularOnly = false;
-
- switch (type)
- {
- case PHY_POINT2POINT_CONSTRAINT:
- {
- // If either of the controllers is missing, we can't do anything.
- if (!c0 || !c1) return 0;
-
- btPoint2PointConstraint* p2p = 0;
-
- if (rb1)
- {
- p2p = new btPoint2PointConstraint(*rb0,
- *rb1,pivotInA,pivotInB);
- } else
- {
- p2p = new btPoint2PointConstraint(*rb0,
- pivotInA);
- }
-
- c0->addCcdConstraintRef(p2p);
- c1->addCcdConstraintRef(p2p);
- m_dynamicsWorld->addConstraint(p2p,disableCollisionBetweenLinkedBodies);
-// m_constraints.push_back(p2p);
-
- p2p->setUserConstraintId(gConstraintUid++);
- p2p->setUserConstraintType(type);
- //64 bit systems can't cast pointer to int. could use size_t instead.
- return p2p->getUserConstraintId();
-
- break;
- }
-
- case PHY_GENERIC_6DOF_CONSTRAINT:
- {
- // If either of the controllers is missing, we can't do anything.
- if (!c0 || !c1) return 0;
-
- btGeneric6DofConstraint* genericConstraint = 0;
-
- if (rb1)
- {
- btTransform frameInA;
- btTransform frameInB;
-
- btVector3 axis1(axis1X,axis1Y,axis1Z), axis2(axis2X,axis2Y,axis2Z);
- if (axis1.length() == 0.0f)
- {
- btPlaneSpace1( axisInA, axis1, axis2 );
- }
-
- frameInA.getBasis().setValue( axisInA.x(), axis1.x(), axis2.x(),
- axisInA.y(), axis1.y(), axis2.y(),
- axisInA.z(), axis1.z(), axis2.z() );
- frameInA.setOrigin( pivotInA );
-
- btTransform inv = rb1->getCenterOfMassTransform().inverse();
-
- btTransform globalFrameA = rb0->getCenterOfMassTransform() * frameInA;
-
- frameInB = inv * globalFrameA;
- bool useReferenceFrameA = true;
-
- genericConstraint = new btGeneric6DofSpringConstraint(
- *rb0,*rb1,
- frameInA,frameInB,useReferenceFrameA);
-
-
- } else
- {
- static btRigidBody s_fixedObject2( 0,0,0);
- btTransform frameInA;
- btTransform frameInB;
-
- btVector3 axis1, axis2;
- btPlaneSpace1( axisInA, axis1, axis2 );
-
- frameInA.getBasis().setValue( axisInA.x(), axis1.x(), axis2.x(),
- axisInA.y(), axis1.y(), axis2.y(),
- axisInA.z(), axis1.z(), axis2.z() );
-
- frameInA.setOrigin( pivotInA );
-
- ///frameInB in worldspace
- frameInB = rb0->getCenterOfMassTransform() * frameInA;
-
- bool useReferenceFrameA = true;
- genericConstraint = new btGeneric6DofSpringConstraint(
- *rb0,s_fixedObject2,
- frameInA,frameInB,useReferenceFrameA);
- }
-
- if (genericConstraint)
- {
- //m_constraints.push_back(genericConstraint);
- c0->addCcdConstraintRef(genericConstraint);
- c1->addCcdConstraintRef(genericConstraint);
- m_dynamicsWorld->addConstraint(genericConstraint,disableCollisionBetweenLinkedBodies);
- genericConstraint->setUserConstraintId(gConstraintUid++);
- genericConstraint->setUserConstraintType(type);
- //64 bit systems can't cast pointer to int. could use size_t instead.
- return genericConstraint->getUserConstraintId();
- }
-
- break;
- }
- case PHY_CONE_TWIST_CONSTRAINT:
- {
- // If either of the controllers is missing, we can't do anything.
- if (!c0 || !c1) return 0;
-
- btConeTwistConstraint* coneTwistContraint = 0;
-
-
- if (rb1)
- {
- btTransform frameInA;
- btTransform frameInB;
-
- btVector3 axis1(axis1X,axis1Y,axis1Z), axis2(axis2X,axis2Y,axis2Z);
- if (axis1.length() == 0.0f)
- {
- btPlaneSpace1( axisInA, axis1, axis2 );
- }
-
- frameInA.getBasis().setValue( axisInA.x(), axis1.x(), axis2.x(),
- axisInA.y(), axis1.y(), axis2.y(),
- axisInA.z(), axis1.z(), axis2.z() );
- frameInA.setOrigin( pivotInA );
-
- btTransform inv = rb1->getCenterOfMassTransform().inverse();
-
- btTransform globalFrameA = rb0->getCenterOfMassTransform() * frameInA;
-
- frameInB = inv * globalFrameA;
-
- coneTwistContraint = new btConeTwistConstraint( *rb0,*rb1,
- frameInA,frameInB);
-
-
- } else
- {
- static btRigidBody s_fixedObject2( 0,0,0);
- btTransform frameInA;
- btTransform frameInB;
-
- btVector3 axis1, axis2;
- btPlaneSpace1( axisInA, axis1, axis2 );
-
- frameInA.getBasis().setValue( axisInA.x(), axis1.x(), axis2.x(),
- axisInA.y(), axis1.y(), axis2.y(),
- axisInA.z(), axis1.z(), axis2.z() );
-
- frameInA.setOrigin( pivotInA );
-
- ///frameInB in worldspace
- frameInB = rb0->getCenterOfMassTransform() * frameInA;
-
- coneTwistContraint = new btConeTwistConstraint(
- *rb0,s_fixedObject2,
- frameInA,frameInB);
- }
-
- if (coneTwistContraint)
- {
- //m_constraints.push_back(genericConstraint);
- c0->addCcdConstraintRef(coneTwistContraint);
- c1->addCcdConstraintRef(coneTwistContraint);
- m_dynamicsWorld->addConstraint(coneTwistContraint,disableCollisionBetweenLinkedBodies);
- coneTwistContraint->setUserConstraintId(gConstraintUid++);
- coneTwistContraint->setUserConstraintType(type);
- //64 bit systems can't cast pointer to int. could use size_t instead.
- return coneTwistContraint->getUserConstraintId();
- }
-
-
-
- break;
- }
- case PHY_ANGULAR_CONSTRAINT:
- angularOnly = true;
-
-
- case PHY_LINEHINGE_CONSTRAINT:
- {
- // If either of the controllers is missing, we can't do anything.
- if (!c0 || !c1) return 0;
-
- btHingeConstraint* hinge = 0;
-
- if (rb1)
- {
- // We know the orientations so we should use them instead of
- // having btHingeConstraint fill in the blanks any way it wants to.
- btTransform frameInA;
- btTransform frameInB;
-
- btVector3 axis1(axis1X,axis1Y,axis1Z), axis2(axis2X,axis2Y,axis2Z);
- if (axis1.length() == 0.0f)
- {
- btPlaneSpace1( axisInA, axis1, axis2 );
- }
-
- // Internally btHingeConstraint's hinge-axis is z
- frameInA.getBasis().setValue( axis1.x(), axis2.x(), axisInA.x(),
- axis1.y(), axis2.y(), axisInA.y(),
- axis1.z(), axis2.z(), axisInA.z() );
-
- frameInA.setOrigin( pivotInA );
-
- btTransform inv = rb1->getCenterOfMassTransform().inverse();
-
- btTransform globalFrameA = rb0->getCenterOfMassTransform() * frameInA;
-
- frameInB = inv * globalFrameA;
-
- hinge = new btHingeConstraint(*rb0,*rb1,frameInA,frameInB);
-
-
- } else
- {
- static btRigidBody s_fixedObject2( 0,0,0);
-
- btTransform frameInA;
- btTransform frameInB;
-
- btVector3 axis1(axis1X,axis1Y,axis1Z), axis2(axis2X,axis2Y,axis2Z);
- if (axis1.length() == 0.0f)
- {
- btPlaneSpace1( axisInA, axis1, axis2 );
- }
-
- // Internally btHingeConstraint's hinge-axis is z
- frameInA.getBasis().setValue( axis1.x(), axis2.x(), axisInA.x(),
- axis1.y(), axis2.y(), axisInA.y(),
- axis1.z(), axis2.z(), axisInA.z() );
- frameInA.setOrigin( pivotInA );
- frameInB = rb0->getCenterOfMassTransform() * frameInA;
-
- hinge = new btHingeConstraint(*rb0, s_fixedObject2, frameInA, frameInB);
- }
- hinge->setAngularOnly(angularOnly);
-
- //m_constraints.push_back(hinge);
- c0->addCcdConstraintRef(hinge);
- c1->addCcdConstraintRef(hinge);
- m_dynamicsWorld->addConstraint(hinge,disableCollisionBetweenLinkedBodies);
- hinge->setUserConstraintId(gConstraintUid++);
- hinge->setUserConstraintType(type);
- //64 bit systems can't cast pointer to int. could use size_t instead.
- return hinge->getUserConstraintId();
- break;
- }
-#ifdef NEW_BULLET_VEHICLE_SUPPORT
-
- case PHY_VEHICLE_CONSTRAINT:
- {
- btRaycastVehicle::btVehicleTuning* tuning = new btRaycastVehicle::btVehicleTuning();
- btRigidBody* chassis = rb0;
- btDefaultVehicleRaycaster* raycaster = new BlenderVehicleRaycaster(m_dynamicsWorld);
- btRaycastVehicle* vehicle = new btRaycastVehicle(*tuning,chassis,raycaster);
- WrapperVehicle* wrapperVehicle = new WrapperVehicle(vehicle,ctrl0);
- m_wrapperVehicles.push_back(wrapperVehicle);
- m_dynamicsWorld->addVehicle(vehicle);
- vehicle->setUserConstraintId(gConstraintUid++);
- vehicle->setUserConstraintType(type);
- return vehicle->getUserConstraintId();
-
- break;
- };
-#endif //NEW_BULLET_VEHICLE_SUPPORT
-
- default:
- {
- }
- };
-
- //btRigidBody& rbA,btRigidBody& rbB, const btVector3& pivotInA,const btVector3& pivotInB
-
- return 0;
-
-}
-
-
-
-PHY_IPhysicsController* CcdPhysicsEnvironment::CreateConeController(float coneradius,float coneheight)
-{
- CcdConstructionInfo cinfo;
-//don't memset cinfo: this is C++ and values should be set in the constructor!
-
- // we don't need a CcdShapeConstructionInfo for this shape:
- // it is simple enough for the standard copy constructor (see CcdPhysicsController::GetReplica)
- cinfo.m_collisionShape = new btConeShape(coneradius,coneheight);
- cinfo.m_MotionState = 0;
- cinfo.m_physicsEnv = this;
- cinfo.m_collisionFlags |= btCollisionObject::CF_NO_CONTACT_RESPONSE | btCollisionObject::CF_STATIC_OBJECT;
- DefaultMotionState* motionState = new DefaultMotionState();
- cinfo.m_MotionState = motionState;
-
- // we will add later the possibility to select the filter from option
- cinfo.m_collisionFilterMask = CcdConstructionInfo::AllFilter ^ CcdConstructionInfo::SensorFilter;
- cinfo.m_collisionFilterGroup = CcdConstructionInfo::SensorFilter;
- cinfo.m_bSensor = true;
- motionState->m_worldTransform.setIdentity();
-// motionState->m_worldTransform.setOrigin(btVector3(position[0],position[1],position[2]));
-
- CcdPhysicsController* sphereController = new CcdPhysicsController(cinfo);
-
-
- return sphereController;
-}
-
-float CcdPhysicsEnvironment::getAppliedImpulse(int constraintid)
-{
- // For soft body constraints
- if (constraintid == 0)
- return 0.0f;
-
- int i;
- int numConstraints = m_dynamicsWorld->getNumConstraints();
- for (i=0;i<numConstraints;i++)
- {
- btTypedConstraint* constraint = m_dynamicsWorld->getConstraint(i);
- if (constraint->getUserConstraintId() == constraintid)
- {
- return constraint->getAppliedImpulse();
- }
- }
-
- return 0.f;
-}
-
-void CcdPhysicsEnvironment::ExportFile(const char* filename)
-{
- btDefaultSerializer* serializer = new btDefaultSerializer();
-
-
- for (int i=0;i<m_dynamicsWorld->getNumCollisionObjects();i++)
- {
-
- btCollisionObject* colObj = m_dynamicsWorld->getCollisionObjectArray()[i];
-
- CcdPhysicsController* controller = static_cast<CcdPhysicsController*>(colObj->getUserPointer());
- if (controller)
- {
- const char* name = KX_GameObject::GetClientObject((KX_ClientObjectInfo*)controller->GetNewClientInfo())->GetName();
- if (name)
- {
- serializer->registerNameForPointer(colObj,name);
- }
- }
- }
-
- m_dynamicsWorld->serialize(serializer);
-
- FILE* file = fopen(filename,"wb");
- if (file)
- {
- fwrite(serializer->getBufferPointer(),serializer->getCurrentBufferSize(),1, file);
- fclose(file);
- }
-}
-
-struct BlenderDebugDraw : public btIDebugDraw
-{
- BlenderDebugDraw () :
- m_debugMode(0)
- {
- }
-
- int m_debugMode;
-
- virtual void drawLine(const btVector3& from,const btVector3& to,const btVector3& color)
- {
- if (m_debugMode >0)
- {
- MT_Vector3 kxfrom(from[0],from[1],from[2]);
- MT_Vector3 kxto(to[0],to[1],to[2]);
- MT_Vector3 kxcolor(color[0],color[1],color[2]);
-
- KX_RasterizerDrawDebugLine(kxfrom,kxto,kxcolor);
- }
- }
-
- virtual void reportErrorWarning(const char* warningString)
- {
-
- }
-
- virtual void drawContactPoint(const btVector3& PointOnB,const btVector3& normalOnB,float distance,int lifeTime,const btVector3& color)
- {
- drawLine(PointOnB, PointOnB + normalOnB, color);
- drawSphere(PointOnB, 0.1f, color);
- }
-
- virtual void setDebugMode(int debugMode)
- {
- m_debugMode = debugMode;
- }
- virtual int getDebugMode() const
- {
- return m_debugMode;
- }
- ///todo: find out if Blender can do this
- virtual void draw3dText(const btVector3& location,const char* textString)
- {
-
- }
-
-};
-
-CcdPhysicsEnvironment *CcdPhysicsEnvironment::Create(Scene *blenderscene, bool visualizePhysics)
-{
- CcdPhysicsEnvironment* ccdPhysEnv = new CcdPhysicsEnvironment((blenderscene->gm.mode & WO_DBVT_CULLING) != 0);
- ccdPhysEnv->SetDebugDrawer(new BlenderDebugDraw());
- ccdPhysEnv->SetDeactivationLinearTreshold(blenderscene->gm.lineardeactthreshold);
- ccdPhysEnv->SetDeactivationAngularTreshold(blenderscene->gm.angulardeactthreshold);
- ccdPhysEnv->SetDeactivationTime(blenderscene->gm.deactivationtime);
-
- if (visualizePhysics)
- ccdPhysEnv->SetDebugMode(btIDebugDraw::DBG_DrawWireframe|btIDebugDraw::DBG_DrawAabb|btIDebugDraw::DBG_DrawContactPoints|btIDebugDraw::DBG_DrawText|btIDebugDraw::DBG_DrawConstraintLimits|btIDebugDraw::DBG_DrawConstraints);
-
- return ccdPhysEnv;
-}
-
-void CcdPhysicsEnvironment::ConvertObject(KX_GameObject *gameobj, RAS_MeshObject *meshobj, DerivedMesh *dm, KX_Scene *kxscene, PHY_ShapeProps *shapeprops, PHY_MaterialProps *smmaterial, PHY_IMotionState *motionstate, int activeLayerBitInfo, bool isCompoundChild, bool hasCompoundChildren)
-{
- Object* blenderobject = gameobj->GetBlenderObject();
-
- bool isbulletdyna = (blenderobject->gameflag & OB_DYNAMIC) != 0;
- bool isbulletsensor = (blenderobject->gameflag & OB_SENSOR) != 0;
- bool isbulletchar = (blenderobject->gameflag & OB_CHARACTER) != 0;
- bool isbulletsoftbody = (blenderobject->gameflag & OB_SOFT_BODY) != 0;
- bool isbulletrigidbody = (blenderobject->gameflag & OB_RIGID_BODY) != 0;
- bool useGimpact = false;
- CcdConstructionInfo ci;
- class CcdShapeConstructionInfo *shapeInfo = new CcdShapeConstructionInfo();
-
- // get Root Parent of blenderobject
- Object *blenderparent = blenderobject->parent;
- while (blenderparent && blenderparent->parent) {
- blenderparent = blenderparent->parent;
- }
-
- KX_GameObject *parent = NULL;
- if (blenderparent)
- {
- KX_BlenderSceneConverter *converter = (KX_BlenderSceneConverter*)KX_GetActiveEngine()->GetSceneConverter();
- parent = converter->FindGameObject(blenderparent);
- isbulletsoftbody = false;
- }
-
- if (!isbulletdyna)
- {
- ci.m_collisionFlags |= btCollisionObject::CF_STATIC_OBJECT;
- }
- if ((blenderobject->gameflag & (OB_GHOST | OB_SENSOR | OB_CHARACTER)) != 0)
- {
- ci.m_collisionFlags |= btCollisionObject::CF_NO_CONTACT_RESPONSE;
- }
-
- ci.m_MotionState = motionstate;
- ci.m_gravity = btVector3(0,0,0);
- ci.m_linearFactor = btVector3(((blenderobject->gameflag2 & OB_LOCK_RIGID_BODY_X_AXIS) !=0)? 0 : 1,
- ((blenderobject->gameflag2 & OB_LOCK_RIGID_BODY_Y_AXIS) !=0)? 0 : 1,
- ((blenderobject->gameflag2 & OB_LOCK_RIGID_BODY_Z_AXIS) !=0)? 0 : 1);
- ci.m_angularFactor = btVector3(((blenderobject->gameflag2 & OB_LOCK_RIGID_BODY_X_ROT_AXIS) !=0)? 0 : 1,
- ((blenderobject->gameflag2 & OB_LOCK_RIGID_BODY_Y_ROT_AXIS) !=0)? 0 : 1,
- ((blenderobject->gameflag2 & OB_LOCK_RIGID_BODY_Z_ROT_AXIS) !=0)? 0 : 1);
- ci.m_localInertiaTensor =btVector3(0,0,0);
- ci.m_mass = isbulletdyna ? shapeprops->m_mass : 0.f;
- ci.m_clamp_vel_min = shapeprops->m_clamp_vel_min;
- ci.m_clamp_vel_max = shapeprops->m_clamp_vel_max;
- ci.m_clamp_angvel_min = shapeprops->m_clamp_angvel_min;
- ci.m_clamp_angvel_max = shapeprops->m_clamp_angvel_max;
- ci.m_stepHeight = isbulletchar ? shapeprops->m_step_height : 0.f;
- ci.m_jumpSpeed = isbulletchar ? shapeprops->m_jump_speed : 0.f;
- ci.m_fallSpeed = isbulletchar ? shapeprops->m_fall_speed : 0.f;
- ci.m_maxJumps = isbulletchar ? shapeprops->m_max_jumps : 0;
-
- //mmm, for now, take this for the size of the dynamicobject
- // Blender uses inertia for radius of dynamic object
- shapeInfo->m_radius = ci.m_radius = blenderobject->inertia;
- useGimpact = ((isbulletdyna || isbulletsensor) && !isbulletsoftbody);
-
- if (isbulletsoftbody)
- {
- if (blenderobject->bsoft)
- {
- ci.m_margin = blenderobject->bsoft->margin;
- ci.m_gamesoftFlag = blenderobject->bsoft->flag;
-
- ci.m_soft_linStiff = blenderobject->bsoft->linStiff;
- ci.m_soft_angStiff = blenderobject->bsoft->angStiff; /* angular stiffness 0..1 */
- ci.m_soft_volume = blenderobject->bsoft->volume; /* volume preservation 0..1 */
-
- ci.m_soft_viterations = blenderobject->bsoft->viterations; /* Velocities solver iterations */
- ci.m_soft_piterations = blenderobject->bsoft->piterations; /* Positions solver iterations */
- ci.m_soft_diterations = blenderobject->bsoft->diterations; /* Drift solver iterations */
- ci.m_soft_citerations = blenderobject->bsoft->citerations; /* Cluster solver iterations */
-
- ci.m_soft_kSRHR_CL = blenderobject->bsoft->kSRHR_CL; /* Soft vs rigid hardness [0,1] (cluster only) */
- ci.m_soft_kSKHR_CL = blenderobject->bsoft->kSKHR_CL; /* Soft vs kinetic hardness [0,1] (cluster only) */
- ci.m_soft_kSSHR_CL = blenderobject->bsoft->kSSHR_CL; /* Soft vs soft hardness [0,1] (cluster only) */
- ci.m_soft_kSR_SPLT_CL = blenderobject->bsoft->kSR_SPLT_CL; /* Soft vs rigid impulse split [0,1] (cluster only) */
-
- ci.m_soft_kSK_SPLT_CL = blenderobject->bsoft->kSK_SPLT_CL; /* Soft vs rigid impulse split [0,1] (cluster only) */
- ci.m_soft_kSS_SPLT_CL = blenderobject->bsoft->kSS_SPLT_CL; /* Soft vs rigid impulse split [0,1] (cluster only) */
- ci.m_soft_kVCF = blenderobject->bsoft->kVCF; /* Velocities correction factor (Baumgarte) */
- ci.m_soft_kDP = blenderobject->bsoft->kDP; /* Damping coefficient [0,1] */
-
- ci.m_soft_kDG = blenderobject->bsoft->kDG; /* Drag coefficient [0,+inf] */
- ci.m_soft_kLF = blenderobject->bsoft->kLF; /* Lift coefficient [0,+inf] */
- ci.m_soft_kPR = blenderobject->bsoft->kPR; /* Pressure coefficient [-inf,+inf] */
- ci.m_soft_kVC = blenderobject->bsoft->kVC; /* Volume conversation coefficient [0,+inf] */
-
- ci.m_soft_kDF = blenderobject->bsoft->kDF; /* Dynamic friction coefficient [0,1] */
- ci.m_soft_kMT = blenderobject->bsoft->kMT; /* Pose matching coefficient [0,1] */
- ci.m_soft_kCHR = blenderobject->bsoft->kCHR; /* Rigid contacts hardness [0,1] */
- ci.m_soft_kKHR = blenderobject->bsoft->kKHR; /* Kinetic contacts hardness [0,1] */
-
- ci.m_soft_kSHR = blenderobject->bsoft->kSHR; /* Soft contacts hardness [0,1] */
- ci.m_soft_kAHR = blenderobject->bsoft->kAHR; /* Anchors hardness [0,1] */
- ci.m_soft_collisionflags = blenderobject->bsoft->collisionflags; /* Vertex/Face or Signed Distance Field(SDF) or Clusters, Soft versus Soft or Rigid */
- ci.m_soft_numclusteriterations = blenderobject->bsoft->numclusteriterations; /* number of iterations to refine collision clusters*/
-
- }
- else
- {
- ci.m_margin = 0.f;
- ci.m_gamesoftFlag = OB_BSB_BENDING_CONSTRAINTS | OB_BSB_SHAPE_MATCHING | OB_BSB_AERO_VPOINT;
-
- ci.m_soft_linStiff = 0.5f;
- ci.m_soft_angStiff = 1.f; /* angular stiffness 0..1 */
- ci.m_soft_volume = 1.f; /* volume preservation 0..1 */
-
- ci.m_soft_viterations = 0;
- ci.m_soft_piterations = 1;
- ci.m_soft_diterations = 0;
- ci.m_soft_citerations = 4;
-
- ci.m_soft_kSRHR_CL = 0.1f;
- ci.m_soft_kSKHR_CL = 1.f;
- ci.m_soft_kSSHR_CL = 0.5f;
- ci.m_soft_kSR_SPLT_CL = 0.5f;
-
- ci.m_soft_kSK_SPLT_CL = 0.5f;
- ci.m_soft_kSS_SPLT_CL = 0.5f;
- ci.m_soft_kVCF = 1;
- ci.m_soft_kDP = 0;
-
- ci.m_soft_kDG = 0;
- ci.m_soft_kLF = 0;
- ci.m_soft_kPR = 0;
- ci.m_soft_kVC = 0;
-
- ci.m_soft_kDF = 0.2f;
- ci.m_soft_kMT = 0.05f;
- ci.m_soft_kCHR = 1.0f;
- ci.m_soft_kKHR = 0.1f;
-
- ci.m_soft_kSHR = 1.f;
- ci.m_soft_kAHR = 0.7f;
- ci.m_soft_collisionflags = OB_BSB_COL_SDF_RS + OB_BSB_COL_VF_SS;
- ci.m_soft_numclusteriterations = 16;
- }
- }
- else
- {
- ci.m_margin = blenderobject->margin;
- }
-
- ci.m_localInertiaTensor = btVector3(ci.m_mass/3.f,ci.m_mass/3.f,ci.m_mass/3.f);
-
- btCollisionShape* bm = 0;
-
- char bounds = isbulletdyna ? OB_BOUND_SPHERE : OB_BOUND_TRIANGLE_MESH;
- if (!(blenderobject->gameflag & OB_BOUNDS))
- {
- if (blenderobject->gameflag & OB_SOFT_BODY)
- bounds = OB_BOUND_TRIANGLE_MESH;
- else if (blenderobject->gameflag & OB_CHARACTER)
- bounds = OB_BOUND_SPHERE;
- }
- else
- {
- if (ELEM(blenderobject->collision_boundtype, OB_BOUND_CONVEX_HULL, OB_BOUND_TRIANGLE_MESH)
- && blenderobject->type != OB_MESH)
- {
- // Can't use triangle mesh or convex hull on a non-mesh object, fall-back to sphere
- bounds = OB_BOUND_SPHERE;
- }
- else
- bounds = blenderobject->collision_boundtype;
- }
-
- // Get bounds information
- float bounds_center[3], bounds_extends[3];
- BoundBox *bb= BKE_object_boundbox_get(blenderobject);
- if (bb==NULL)
- {
- bounds_center[0] = bounds_center[1] = bounds_center[2] = 0.0f;
- bounds_extends[0] = bounds_extends[1] = bounds_extends[2] = 1.0f;
- }
- else
- {
- bounds_extends[0] = 0.5f * fabsf(bb->vec[0][0] - bb->vec[4][0]);
- bounds_extends[1] = 0.5f * fabsf(bb->vec[0][1] - bb->vec[2][1]);
- bounds_extends[2] = 0.5f * fabsf(bb->vec[0][2] - bb->vec[1][2]);
-
- bounds_center[0] = 0.5f * (bb->vec[0][0] + bb->vec[4][0]);
- bounds_center[1] = 0.5f * (bb->vec[0][1] + bb->vec[2][1]);
- bounds_center[2] = 0.5f * (bb->vec[0][2] + bb->vec[1][2]);
- }
-
- switch (bounds)
- {
- case OB_BOUND_SPHERE:
- {
- //float radius = objprop->m_radius;
- //btVector3 inertiaHalfExtents (
- // radius,
- // radius,
- // radius);
-
- //blender doesn't support multisphere, but for testing:
-
- //bm = new MultiSphereShape(inertiaHalfExtents,,&trans.getOrigin(),&radius,1);
- shapeInfo->m_shapeType = PHY_SHAPE_SPHERE;
- // XXX We calculated the radius but didn't use it?
- // objprop.m_boundobject.c.m_radius = MT_max(bb.m_extends[0], MT_max(bb.m_extends[1], bb.m_extends[2]));
- bm = shapeInfo->CreateBulletShape(ci.m_margin);
- break;
- };
- case OB_BOUND_BOX:
- {
- shapeInfo->m_halfExtend.setValue(
- 2.f * bounds_extends[0],
- 2.f * bounds_extends[1],
- 2.f * bounds_extends[2]);
-
- shapeInfo->m_halfExtend /= 2.0f;
- shapeInfo->m_halfExtend = shapeInfo->m_halfExtend.absolute();
- shapeInfo->m_shapeType = PHY_SHAPE_BOX;
- bm = shapeInfo->CreateBulletShape(ci.m_margin);
- break;
- };
- case OB_BOUND_CYLINDER:
- {
- float radius = MT_max(bounds_extends[0], bounds_extends[1]);
- shapeInfo->m_halfExtend.setValue(
- radius,
- radius,
- bounds_extends[2]
- );
- shapeInfo->m_shapeType = PHY_SHAPE_CYLINDER;
- bm = shapeInfo->CreateBulletShape(ci.m_margin);
- break;
- }
-
- case OB_BOUND_CONE:
- {
- shapeInfo->m_radius = MT_max(bounds_extends[0], bounds_extends[1]);
- shapeInfo->m_height = 2.f * bounds_extends[2];
- shapeInfo->m_shapeType = PHY_SHAPE_CONE;
- bm = shapeInfo->CreateBulletShape(ci.m_margin);
- break;
- }
- case OB_BOUND_CONVEX_HULL:
- {
- shapeInfo->SetMesh(meshobj, dm,true);
- bm = shapeInfo->CreateBulletShape(ci.m_margin);
- break;
- }
- case OB_BOUND_CAPSULE:
- {
- shapeInfo->m_radius = MT_max(bounds_extends[0], bounds_extends[1]);
- shapeInfo->m_height = 2.f * (bounds_extends[2] - shapeInfo->m_radius);
- if (shapeInfo->m_height < 0.f)
- shapeInfo->m_height = 0.f;
- shapeInfo->m_shapeType = PHY_SHAPE_CAPSULE;
- bm = shapeInfo->CreateBulletShape(ci.m_margin);
- break;
- }
- case OB_BOUND_TRIANGLE_MESH:
- {
- // mesh shapes can be shared, check first if we already have a shape on that mesh
- class CcdShapeConstructionInfo *sharedShapeInfo = CcdShapeConstructionInfo::FindMesh(meshobj, dm, false);
- if (sharedShapeInfo != NULL)
- {
- shapeInfo->Release();
- shapeInfo = sharedShapeInfo;
- shapeInfo->AddRef();
- } else
- {
- shapeInfo->SetMesh(meshobj, dm, false);
- }
-
- // Soft bodies can benefit from welding, don't do it on non-soft bodies
- if (isbulletsoftbody)
- {
- // disable welding: it doesn't bring any additional stability and it breaks the relation between soft body collision shape and graphic mesh
- // shapeInfo->setVertexWeldingThreshold1((blenderobject->bsoft) ? blenderobject->bsoft->welding ? 0.f);
- shapeInfo->setVertexWeldingThreshold1(0.f); //todo: expose this to the UI
- }
-
- bm = shapeInfo->CreateBulletShape(ci.m_margin, useGimpact, !isbulletsoftbody);
- //should we compute inertia for dynamic shape?
- //bm->calculateLocalInertia(ci.m_mass,ci.m_localInertiaTensor);
-
- break;
- }
- }
-
-
-// ci.m_localInertiaTensor.setValue(0.1f,0.1f,0.1f);
-
- if (!bm)
- {
- delete motionstate;
- shapeInfo->Release();
- return;
- }
-
- //bm->setMargin(ci.m_margin);
-
-
- if (isCompoundChild)
- {
- //find parent, compound shape and add to it
- //take relative transform into account!
- CcdPhysicsController* parentCtrl = (CcdPhysicsController*)parent->GetPhysicsController();
- assert(parentCtrl);
-
- // only makes compound shape if parent has a physics controller (i.e not an empty, etc)
- if (parentCtrl) {
- CcdShapeConstructionInfo* parentShapeInfo = parentCtrl->GetShapeInfo();
- btRigidBody* rigidbody = parentCtrl->GetRigidBody();
- btCollisionShape* colShape = rigidbody->getCollisionShape();
- assert(colShape->isCompound());
- btCompoundShape* compoundShape = (btCompoundShape*)colShape;
-
- // compute the local transform from parent, this may include several node in the chain
- SG_Node* gameNode = gameobj->GetSGNode();
- SG_Node* parentNode = parent->GetSGNode();
- // relative transform
- MT_Vector3 parentScale = parentNode->GetWorldScaling();
- parentScale[0] = MT_Scalar(1.0f)/parentScale[0];
- parentScale[1] = MT_Scalar(1.0f)/parentScale[1];
- parentScale[2] = MT_Scalar(1.0f)/parentScale[2];
- MT_Vector3 relativeScale = gameNode->GetWorldScaling() * parentScale;
- MT_Matrix3x3 parentInvRot = parentNode->GetWorldOrientation().transposed();
- MT_Vector3 relativePos = parentInvRot*((gameNode->GetWorldPosition()-parentNode->GetWorldPosition())*parentScale);
- MT_Matrix3x3 relativeRot = parentInvRot*gameNode->GetWorldOrientation();
-
- shapeInfo->m_childScale.setValue(relativeScale[0],relativeScale[1],relativeScale[2]);
- bm->setLocalScaling(shapeInfo->m_childScale);
- shapeInfo->m_childTrans.getOrigin().setValue(relativePos[0],relativePos[1],relativePos[2]);
- float rot[12];
- relativeRot.getValue(rot);
- shapeInfo->m_childTrans.getBasis().setFromOpenGLSubMatrix(rot);
-
- parentShapeInfo->AddShape(shapeInfo);
- compoundShape->addChildShape(shapeInfo->m_childTrans,bm);
- //do some recalc?
- //recalc inertia for rigidbody
- if (!rigidbody->isStaticOrKinematicObject())
- {
- btVector3 localInertia;
- float mass = 1.f/rigidbody->getInvMass();
- compoundShape->calculateLocalInertia(mass,localInertia);
- rigidbody->setMassProps(mass,localInertia);
- }
- shapeInfo->Release();
- // delete motionstate as it's not used
- delete motionstate;
- }
- return;
- }
-
- if (hasCompoundChildren)
- {
- // create a compound shape info
- CcdShapeConstructionInfo *compoundShapeInfo = new CcdShapeConstructionInfo();
- compoundShapeInfo->m_shapeType = PHY_SHAPE_COMPOUND;
- compoundShapeInfo->AddShape(shapeInfo);
- // create the compound shape manually as we already have the child shape
- btCompoundShape* compoundShape = new btCompoundShape();
- compoundShape->addChildShape(shapeInfo->m_childTrans,bm);
- // now replace the shape
- bm = compoundShape;
- shapeInfo->Release();
- shapeInfo = compoundShapeInfo;
- }
-
-
-
-
-
-
-#ifdef TEST_SIMD_HULL
- if (bm->IsPolyhedral())
- {
- PolyhedralConvexShape* polyhedron = static_cast<PolyhedralConvexShape*>(bm);
- if (!polyhedron->m_optionalHull)
- {
- //first convert vertices in 'Point3' format
- int numPoints = polyhedron->GetNumVertices();
- Point3* points = new Point3[numPoints+1];
- //first 4 points should not be co-planar, so add central point to satisfy MakeHull
- points[0] = Point3(0.f,0.f,0.f);
-
- btVector3 vertex;
- for (int p=0;p<numPoints;p++)
- {
- polyhedron->GetVertex(p,vertex);
- points[p+1] = Point3(vertex.getX(),vertex.getY(),vertex.getZ());
- }
-
- Hull* hull = Hull::MakeHull(numPoints+1,points);
- polyhedron->m_optionalHull = hull;
- }
-
- }
-#endif //TEST_SIMD_HULL
-
-
- ci.m_collisionShape = bm;
- ci.m_shapeInfo = shapeInfo;
- ci.m_friction = smmaterial->m_friction;//tweak the friction a bit, so the default 0.5 works nice
- ci.m_restitution = smmaterial->m_restitution;
- ci.m_physicsEnv = this;
- // drag / damping is inverted
- ci.m_linearDamping = 1.f - shapeprops->m_lin_drag;
- ci.m_angularDamping = 1.f - shapeprops->m_ang_drag;
- //need a bit of damping, else system doesn't behave well
- ci.m_inertiaFactor = shapeprops->m_inertia/0.4f;//defaults to 0.4, don't want to change behavior
-
- ci.m_do_anisotropic = shapeprops->m_do_anisotropic;
- ci.m_anisotropicFriction.setValue(shapeprops->m_friction_scaling[0],shapeprops->m_friction_scaling[1],shapeprops->m_friction_scaling[2]);
-
-
-//////////
- //do Fh, do Rot Fh
- ci.m_do_fh = shapeprops->m_do_fh;
- ci.m_do_rot_fh = shapeprops->m_do_rot_fh;
- ci.m_fh_damping = smmaterial->m_fh_damping;
- ci.m_fh_distance = smmaterial->m_fh_distance;
- ci.m_fh_normal = smmaterial->m_fh_normal;
- ci.m_fh_spring = smmaterial->m_fh_spring;
-
- ci.m_collisionFilterGroup =
- (isbulletsensor) ? short(CcdConstructionInfo::SensorFilter) :
- (isbulletdyna) ? short(CcdConstructionInfo::DefaultFilter) :
- (isbulletchar) ? short(CcdConstructionInfo::CharacterFilter) :
- short(CcdConstructionInfo::StaticFilter);
- ci.m_collisionFilterMask =
- (isbulletsensor) ? short(CcdConstructionInfo::AllFilter ^ CcdConstructionInfo::SensorFilter) :
- (isbulletdyna) ? short(CcdConstructionInfo::AllFilter) :
- (isbulletchar) ? short(CcdConstructionInfo::AllFilter) :
- short(CcdConstructionInfo::AllFilter ^ CcdConstructionInfo::StaticFilter);
- ci.m_bRigid = isbulletdyna && isbulletrigidbody;
- ci.m_bSoft = isbulletsoftbody;
- ci.m_bDyna = isbulletdyna;
- ci.m_bSensor = isbulletsensor;
- ci.m_bCharacter = isbulletchar;
- ci.m_bGimpact = useGimpact;
- MT_Vector3 scaling = gameobj->NodeGetWorldScaling();
- ci.m_scaling.setValue(scaling[0], scaling[1], scaling[2]);
- CcdPhysicsController* physicscontroller = new CcdPhysicsController(ci);
- // shapeInfo is reference counted, decrement now as we don't use it anymore
- if (shapeInfo)
- shapeInfo->Release();
-
- gameobj->SetPhysicsController(physicscontroller,isbulletdyna);
-
- // record animation for dynamic objects
- if (isbulletdyna)
- gameobj->SetRecordAnimation(true);
-
- physicscontroller->SetNewClientInfo(gameobj->getClientInfo());
-
- // don't add automatically sensor object, they are added when a collision sensor is registered
- if (!isbulletsensor && (blenderobject->lay & activeLayerBitInfo) != 0)
- {
- this->AddCcdPhysicsController( physicscontroller);
- }
-
- {
- btRigidBody* rbody = physicscontroller->GetRigidBody();
-
- if (rbody)
- {
- rbody->setLinearFactor(ci.m_linearFactor);
-
- if (isbulletrigidbody)
- {
- rbody->setAngularFactor(ci.m_angularFactor);
- }
-
- if (rbody && (blenderobject->gameflag & OB_COLLISION_RESPONSE) != 0)
- {
- rbody->setActivationState(DISABLE_DEACTIVATION);
- }
- }
- }
-
- if (parent)
- physicscontroller->SuspendDynamics(false);
-
- CcdPhysicsController* parentCtrl = parent ? (CcdPhysicsController*)parent->GetPhysicsController() : 0;
- physicscontroller->SetParentCtrl(parentCtrl);
-
-
- //Now done directly in ci.m_collisionFlags so that it propagates to replica
- //if (objprop->m_ghost)
- //{
- // rbody->setCollisionFlags(rbody->getCollisionFlags() | btCollisionObject::CF_NO_CONTACT_RESPONSE);
- //}
-
- if (isbulletdyna && !isbulletrigidbody)
- {
-#if 0
- //setting the inertia could achieve similar results to constraint the up
- //but it is prone to instability, so use special 'Angular' constraint
- btVector3 inertia = physicscontroller->GetRigidBody()->getInvInertiaDiagLocal();
- inertia.setX(0.f);
- inertia.setZ(0.f);
-
- physicscontroller->GetRigidBody()->setInvInertiaDiagLocal(inertia);
- physicscontroller->GetRigidBody()->updateInertiaTensor();
-#endif
-
- //this->createConstraint(physicscontroller,0,PHY_ANGULAR_CONSTRAINT,0,0,0,0,0,1);
-
- //Now done directly in ci.m_bRigid so that it propagates to replica
- //physicscontroller->GetRigidBody()->setAngularFactor(0.f);
- ;
- }
-
-
- STR_String materialname;
- if (meshobj)
- materialname = meshobj->GetMaterialName(0);
-
-
-#if 0
- ///test for soft bodies
- if (objprop->m_softbody && physicscontroller)
- {
- btSoftBody* softBody = physicscontroller->GetSoftBody();
- if (softBody && gameobj->GetMesh(0))//only the first mesh, if any
- {
- //should be a mesh then, so add a soft body deformer
- KX_SoftBodyDeformer* softbodyDeformer = new KX_SoftBodyDeformer( gameobj->GetMesh(0),(BL_DeformableGameObject*)gameobj);
- gameobj->SetDeformer(softbodyDeformer);
- }
- }
-#endif
-}
-
-
-void CcdPhysicsEnvironment::SetupObjectConstraints(KX_GameObject *obj_src, KX_GameObject *obj_dest,
- bRigidBodyJointConstraint *dat)
-{
- PHY_IPhysicsController *phy_src = obj_src->GetPhysicsController();
- PHY_IPhysicsController *phy_dest = obj_dest->GetPhysicsController();
- PHY_IPhysicsEnvironment *phys_env = obj_src->GetScene()->GetPhysicsEnvironment();
-
- /* We need to pass a full constraint frame, not just axis. */
- MT_Matrix3x3 localCFrame(MT_Vector3(dat->axX,dat->axY,dat->axZ));
- MT_Vector3 axis0 = localCFrame.getColumn(0);
- MT_Vector3 axis1 = localCFrame.getColumn(1);
- MT_Vector3 axis2 = localCFrame.getColumn(2);
- MT_Vector3 scale = obj_src->NodeGetWorldScaling();
-
- /* Apply not only the pivot and axis values, but also take scale into count
- * this is not working well, if only one or two axis are scaled, but works ok on
- * homogeneous scaling. */
- int constraintId = phys_env->CreateConstraint(
- phy_src, phy_dest, (PHY_ConstraintType)dat->type,
- (float)(dat->pivX * scale.x()), (float)(dat->pivY * scale.y()), (float)(dat->pivZ * scale.z()),
- (float)(axis0.x() * scale.x()), (float)(axis0.y() * scale.y()), (float)(axis0.z() * scale.z()),
- (float)(axis1.x() * scale.x()), (float)(axis1.y() * scale.y()), (float)(axis1.z() * scale.z()),
- (float)(axis2.x() * scale.x()), (float)(axis2.y() * scale.y()), (float)(axis2.z() * scale.z()),
- dat->flag);
-
- /* PHY_POINT2POINT_CONSTRAINT = 1,
- * PHY_LINEHINGE_CONSTRAINT = 2,
- * PHY_ANGULAR_CONSTRAINT = 3,
- * PHY_CONE_TWIST_CONSTRAINT = 4,
- * PHY_VEHICLE_CONSTRAINT = 11,
- * PHY_GENERIC_6DOF_CONSTRAINT = 12 */
-
- if (!constraintId)
- return;
-
- int dof = 0;
- int dof_max = 0;
- int dofbit = 0;
-
- switch (dat->type) {
- /* Set all the limits for generic 6DOF constraint. */
- case PHY_GENERIC_6DOF_CONSTRAINT:
- dof_max = 6;
- dofbit = 1;
- break;
- /* Set XYZ angular limits for cone twist constraint. */
- case PHY_CONE_TWIST_CONSTRAINT:
- dof = 3;
- dof_max = 6;
- dofbit = 1 << 3;
- break;
- /* Set only X angular limits for line hinge and angular constraint. */
- case PHY_LINEHINGE_CONSTRAINT:
- case PHY_ANGULAR_CONSTRAINT:
- dof = 3;
- dof_max = 4;
- dofbit = 1 << 3;
- break;
- default:
- break;
- }
-
- for (; dof < dof_max; dof++) {
- if (dat->flag & dofbit) {
- phys_env->SetConstraintParam(constraintId, dof, dat->minLimit[dof], dat->maxLimit[dof]);
- }
- else {
- /* minLimit > maxLimit means free (no limit) for this degree of freedom. */
- phys_env->SetConstraintParam(constraintId, dof, 1.0f, -1.0f);
- }
- dofbit <<= 1;
- }
-
-}
diff --git a/source/gameengine/Physics/Bullet/CcdPhysicsEnvironment.h b/source/gameengine/Physics/Bullet/CcdPhysicsEnvironment.h
deleted file mode 100644
index a64d2c8f15f..00000000000
--- a/source/gameengine/Physics/Bullet/CcdPhysicsEnvironment.h
+++ /dev/null
@@ -1,345 +0,0 @@
-/*
-Bullet Continuous Collision Detection and Physics Library
-Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
-
-This software is provided 'as-is', without any express or implied warranty.
-In no event will the authors be held liable for any damages arising from the use of this software.
-Permission is granted to anyone to use this software for any purpose,
-including commercial applications, and to alter it and redistribute it freely,
-subject to the following restrictions:
-
-1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
-2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
-3. This notice may not be removed or altered from any source distribution.
-*/
-
-/** \file CcdPhysicsEnvironment.h
- * \ingroup physbullet
- * See also \ref bulletdoc
- */
-
-#ifndef __CCDPHYSICSENVIRONMENT_H__
-#define __CCDPHYSICSENVIRONMENT_H__
-
-#include "PHY_IPhysicsEnvironment.h"
-#include "KX_KetsjiEngine.h"
-
-#include <vector>
-#include <set>
-#include <map>
-class CcdPhysicsController;
-class CcdGraphicController;
-#include "LinearMath/btVector3.h"
-#include "LinearMath/btTransform.h"
-
-
-
-
-class btTypedConstraint;
-class btSimulationIslandManager;
-class btCollisionDispatcher;
-class btDispatcher;
-//#include "btBroadphaseInterface.h"
-
-//switch on/off new vehicle support
-#define NEW_BULLET_VEHICLE_SUPPORT 1
-
-#include "BulletDynamics/ConstraintSolver/btContactSolverInfo.h"
-
-class WrapperVehicle;
-class btPersistentManifold;
-class btBroadphaseInterface;
-struct btDbvtBroadphase;
-class btOverlappingPairCache;
-class btIDebugDraw;
-class btDynamicsWorld;
-class PHY_IVehicle;
-class CcdOverlapFilterCallBack;
-class CcdShapeConstructionInfo;
-
-/** CcdPhysicsEnvironment is an experimental mainloop for physics simulation using optional continuous collision detection.
- * Physics Environment takes care of stepping the simulation and is a container for physics entities.
- * It stores rigidbodies,constraints, materials etc.
- * A derived class may be able to 'construct' entities by loading and/or converting
- */
-class CcdPhysicsEnvironment : public PHY_IPhysicsEnvironment
-{
- friend class CcdOverlapFilterCallBack;
- btVector3 m_gravity;
-
- // Removes the constraint and his references from the owner and the target.
- void RemoveConstraint(btTypedConstraint *con);
-
-protected:
- btIDebugDraw* m_debugDrawer;
-
- class btDefaultCollisionConfiguration* m_collisionConfiguration;
- class btBroadphaseInterface* m_broadphase; // broadphase for dynamic world
- // for culling only
- btOverlappingPairCache* m_cullingCache;
- struct btDbvtBroadphase* m_cullingTree; // broadphase for culling
-
- //solver iterations
- int m_numIterations;
-
- //timestep subdivisions
- int m_numTimeSubSteps;
-
-
- int m_ccdMode;
- int m_solverType;
- int m_profileTimings;
- bool m_enableSatCollisionDetection;
-
- float m_deactivationTime;
- float m_linearDeactivationThreshold;
- float m_angularDeactivationThreshold;
- float m_contactBreakingThreshold;
-
- void ProcessFhSprings(double curTime,float timeStep);
-
- public:
- CcdPhysicsEnvironment(bool useDbvtCulling, btDispatcher* dispatcher=0, btOverlappingPairCache* pairCache=0);
-
- virtual ~CcdPhysicsEnvironment();
-
- /////////////////////////////////////
- //PHY_IPhysicsEnvironment interface
- /////////////////////////////////////
-
- /// Perform an integration step of duration 'timeStep'.
-
- virtual void SetDebugDrawer(btIDebugDraw* debugDrawer);
-
- virtual void SetNumIterations(int numIter);
- virtual void SetNumTimeSubSteps(int numTimeSubSteps)
- {
- m_numTimeSubSteps = numTimeSubSteps;
- }
- virtual void SetDeactivationTime(float dTime);
- virtual void SetDeactivationLinearTreshold(float linTresh);
- virtual void SetDeactivationAngularTreshold(float angTresh);
- virtual void SetContactBreakingTreshold(float contactBreakingTreshold);
- virtual void SetCcdMode(int ccdMode);
- virtual void SetSolverType(int solverType);
- virtual void SetSolverSorConstant(float sor);
- virtual void SetSolverTau(float tau);
- virtual void SetSolverDamping(float damping);
- virtual void SetLinearAirDamping(float damping);
- virtual void SetUseEpa(bool epa);
-
- virtual int GetNumTimeSubSteps()
- {
- return m_numTimeSubSteps;
- }
-
- virtual void BeginFrame();
- virtual void EndFrame() {}
- /// Perform an integration step of duration 'timeStep'.
- virtual bool ProceedDeltaTime(double curTime,float timeStep,float interval);
-
- /**
- * Called by Bullet for every physical simulation (sub)tick.
- * Our constructor registers this callback to Bullet, which stores a pointer to 'this' in
- * the btDynamicsWorld::getWorldUserInfo() pointer.
- */
- static void StaticSimulationSubtickCallback(btDynamicsWorld *world, btScalar timeStep);
- void SimulationSubtickCallback(btScalar timeStep);
-
- virtual void DebugDrawWorld();
-// virtual bool proceedDeltaTimeOneStep(float timeStep);
-
- virtual void SetFixedTimeStep(bool useFixedTimeStep,float fixedTimeStep)
- {
- SetNumTimeSubSteps((int)(fixedTimeStep / KX_KetsjiEngine::GetTicRate()));
- }
- //returns 0.f if no fixed timestep is used
-
- virtual float GetFixedTimeStep() { return 0.f; }
-
- virtual void SetDebugMode(int debugMode);
- virtual int GetDebugMode()const;
-
- virtual void SetGravity(float x,float y,float z);
- virtual void GetGravity(MT_Vector3& grav);
-
-
- virtual int CreateConstraint(class PHY_IPhysicsController* ctrl,class PHY_IPhysicsController* ctrl2,PHY_ConstraintType type,
- float pivotX,float pivotY,float pivotZ,
- float axisX,float axisY,float axisZ,
- float axis1X=0,float axis1Y=0,float axis1Z=0,
- float axis2X=0,float axis2Y=0,float axis2Z=0,int flag=0
- );
-
-
- //Following the COLLADA physics specification for constraints
- virtual int CreateUniversalD6Constraint(
- class PHY_IPhysicsController* ctrlRef,class PHY_IPhysicsController* ctrlOther,
- btTransform& localAttachmentFrameRef,
- btTransform& localAttachmentOther,
- const btVector3& linearMinLimits,
- const btVector3& linearMaxLimits,
- const btVector3& angularMinLimits,
- const btVector3& angularMaxLimits,int flags
- );
-
-
- virtual void SetConstraintParam(int constraintId,int param,float value,float value1);
-
- virtual float GetConstraintParam(int constraintId,int param);
-
- virtual void RemoveConstraintById(int constraintid);
-
- virtual float getAppliedImpulse(int constraintid);
-
-
- virtual void CallbackTriggers();
-
-
-#ifdef NEW_BULLET_VEHICLE_SUPPORT
- //complex constraint for vehicles
- virtual PHY_IVehicle* GetVehicleConstraint(int constraintId);
-#else
- virtual class PHY_IVehicle* GetVehicleConstraint(int constraintId)
- {
- return 0;
- }
-#endif /* NEW_BULLET_VEHICLE_SUPPORT */
- // Character physics wrapper
- virtual PHY_ICharacter* GetCharacterController(class KX_GameObject* ob);
-
- btTypedConstraint* GetConstraintById(int constraintId);
-
- virtual PHY_IPhysicsController* RayTest(PHY_IRayCastFilterCallback &filterCallback, float fromX,float fromY,float fromZ, float toX,float toY,float toZ);
- virtual bool CullingTest(PHY_CullingCallback callback, void* userData, MT_Vector4* planes, int nplanes, int occlusionRes, const int *viewport, float modelview[16], float projection[16]);
-
-
- //Methods for gamelogic collision/physics callbacks
- virtual void AddSensor(PHY_IPhysicsController* ctrl);
- virtual void RemoveSensor(PHY_IPhysicsController* ctrl);
- virtual void AddTouchCallback(int response_class, PHY_ResponseCallback callback, void *user);
- virtual bool RequestCollisionCallback(PHY_IPhysicsController* ctrl);
- virtual bool RemoveCollisionCallback(PHY_IPhysicsController* ctrl);
- //These two methods are used *solely* to create controllers for Near/Radar sensor! Don't use for anything else
- virtual PHY_IPhysicsController* CreateSphereController(float radius,const MT_Vector3& position);
- virtual PHY_IPhysicsController* CreateConeController(float coneradius,float coneheight);
-
-
- virtual int GetNumContactPoints();
-
- virtual void GetContactPoint(int i,float& hitX,float& hitY,float& hitZ,float& normalX,float& normalY,float& normalZ);
-
- //////////////////////
- //CcdPhysicsEnvironment interface
- ////////////////////////
-
- void AddCcdPhysicsController(CcdPhysicsController* ctrl);
-
- bool RemoveCcdPhysicsController(CcdPhysicsController* ctrl);
-
- void UpdateCcdPhysicsController(CcdPhysicsController* ctrl, btScalar newMass, int newCollisionFlags, short int newCollisionGroup, short int newCollisionMask);
-
- void RefreshCcdPhysicsController(CcdPhysicsController* ctrl);
-
- bool IsActiveCcdPhysicsController(CcdPhysicsController *ctrl);
-
- void AddCcdGraphicController(CcdGraphicController* ctrl);
-
- void RemoveCcdGraphicController(CcdGraphicController* ctrl);
-
- /**
- * Update all physics controllers shape which use the same shape construction info.
- * Call RecreateControllerShape on controllers which use the same shape
- * construction info that argument shapeInfo.
- * You need to call this function when the shape construction info changed.
- */
- void UpdateCcdPhysicsControllerShape(CcdShapeConstructionInfo *shapeInfo);
-
- btBroadphaseInterface* GetBroadphase();
- btDbvtBroadphase* GetCullingTree() { return m_cullingTree; }
-
- btDispatcher* GetDispatcher();
-
-
- bool IsSatCollisionDetectionEnabled() const
- {
- return m_enableSatCollisionDetection;
- }
-
- void EnableSatCollisionDetection(bool enableSat)
- {
- m_enableSatCollisionDetection = enableSat;
- }
-
-
- const btPersistentManifold* GetManifold(int index) const;
-
-
- void SyncMotionStates(float timeStep);
-
- class btSoftRigidDynamicsWorld* GetDynamicsWorld()
- {
- return m_dynamicsWorld;
- }
-
- class btConstraintSolver* GetConstraintSolver();
-
- void MergeEnvironment(PHY_IPhysicsEnvironment *other_env);
-
- static CcdPhysicsEnvironment *Create(struct Scene *blenderscene, bool visualizePhysics);
-
- virtual void ConvertObject(KX_GameObject* gameobj,
- RAS_MeshObject* meshobj,
- DerivedMesh* dm,
- KX_Scene* kxscene,
- PHY_ShapeProps* shapeprops,
- PHY_MaterialProps* smmaterial,
- PHY_IMotionState *motionstate,
- int activeLayerBitInfo,
- bool isCompoundChild,
- bool hasCompoundChildren);
-
- /* Set the rigid body joints constraints values for converted objects and replicated group instances. */
- virtual void SetupObjectConstraints(KX_GameObject *obj_src, KX_GameObject *obj_dest,
- bRigidBodyJointConstraint *dat);
-
- protected:
-
-
-
- std::set<CcdPhysicsController*> m_controllers;
-
- PHY_ResponseCallback m_triggerCallbacks[PHY_NUM_RESPONSE];
- void* m_triggerCallbacksUserPtrs[PHY_NUM_RESPONSE];
-
- std::vector<WrapperVehicle*> m_wrapperVehicles;
-
- //use explicit btSoftRigidDynamicsWorld/btDiscreteDynamicsWorld* so that we have access to
- //btDiscreteDynamicsWorld::addRigidBody(body,filter,group)
- //so that we can set the body collision filter/group at the time of creation
- //and not afterwards (breaks the collision system for radar/near sensor)
- //Ideally we would like to have access to this function from the btDynamicsWorld interface
- //class btDynamicsWorld* m_dynamicsWorld;
- class btSoftRigidDynamicsWorld* m_dynamicsWorld;
-
- class btConstraintSolver* m_solver;
-
- class btOverlappingPairCache* m_ownPairCache;
-
- class CcdOverlapFilterCallBack* m_filterCallback;
-
- class btGhostPairCallback* m_ghostPairCallback;
-
- class btDispatcher* m_ownDispatcher;
-
- bool m_scalingPropagated;
-
- virtual void ExportFile(const char* filename);
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:CcdPhysicsEnvironment")
-#endif
-};
-
-#endif /* __CCDPHYSICSENVIRONMENT_H__ */
diff --git a/source/gameengine/Physics/Dummy/CMakeLists.txt b/source/gameengine/Physics/Dummy/CMakeLists.txt
deleted file mode 100644
index 692331f1ce4..00000000000
--- a/source/gameengine/Physics/Dummy/CMakeLists.txt
+++ /dev/null
@@ -1,41 +0,0 @@
-# ***** BEGIN GPL LICENSE BLOCK *****
-#
-# This program is free software; you can redistribute it and/or
-# modify it under the terms of the GNU General Public License
-# as published by the Free Software Foundation; either version 2
-# of the License, or (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software Foundation,
-# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
-#
-# The Original Code is Copyright (C) 2006, Blender Foundation
-# All rights reserved.
-#
-# The Original Code is: all of this file.
-#
-# Contributor(s): Jacques Beaurain.
-#
-# ***** END GPL LICENSE BLOCK *****
-
-set(INC
- .
- ../common
-)
-
-set(INC_SYS
- ../../../../intern/moto/include
-)
-
-set(SRC
- DummyPhysicsEnvironment.cpp
-
- DummyPhysicsEnvironment.h
-)
-
-blender_add_lib(ge_phys_dummy "${SRC}" "${INC}" "${INC_SYS}")
diff --git a/source/gameengine/Physics/Dummy/DummyPhysicsEnvironment.cpp b/source/gameengine/Physics/Dummy/DummyPhysicsEnvironment.cpp
deleted file mode 100644
index 99db56bfcef..00000000000
--- a/source/gameengine/Physics/Dummy/DummyPhysicsEnvironment.cpp
+++ /dev/null
@@ -1,121 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Physics/Dummy/DummyPhysicsEnvironment.cpp
- * \ingroup physdummy
- */
-
-
-#include <stddef.h>
-
-#include "DummyPhysicsEnvironment.h"
-#include "PHY_IMotionState.h"
-
-DummyPhysicsEnvironment::DummyPhysicsEnvironment()
-{
- // create physicsengine data
-}
-
-
-
-DummyPhysicsEnvironment::~DummyPhysicsEnvironment()
-{
- //destroy physicsengine data
-}
-
-void DummyPhysicsEnvironment::BeginFrame()
-{
- // beginning of logic frame: apply forces
-}
-
-void DummyPhysicsEnvironment::EndFrame()
-{
- // end of logic frame: clear forces
-}
-
-
-
-bool DummyPhysicsEnvironment::ProceedDeltaTime(double curTime,float timeStep,float interval)
-{
- //step physics simulation, typically perform
-
- //collision detection
- //solve constraints
- //integrate solution
- // return true if an update was done.
- return true;
-}
-void DummyPhysicsEnvironment::SetFixedTimeStep(bool useFixedTimeStep,float fixedTimeStep)
-{
-}
-
-float DummyPhysicsEnvironment::GetFixedTimeStep()
-{
- return 0.f;
-}
-
-int DummyPhysicsEnvironment::GetDebugMode() const
-{
- return 0;
-}
-
-void DummyPhysicsEnvironment::SetGravity(float x,float y,float z)
-{
-}
-
-void DummyPhysicsEnvironment::GetGravity(class MT_Vector3& grav)
-{
-}
-
-
-
-
-int DummyPhysicsEnvironment::CreateConstraint(class PHY_IPhysicsController* ctrl,class PHY_IPhysicsController* ctrl2,PHY_ConstraintType type,
- float pivotX,float pivotY,float pivotZ,float axisX,float axisY,float axisZ,
- float axis1X,float axis1Y,float axis1Z,
- float axis2X,float axis2Y,float axis2Z,int flag
- )
-{
-
- int constraintid = 0;
- return constraintid;
-
-}
-
-void DummyPhysicsEnvironment::RemoveConstraintById(int constraintid)
-{
- if (constraintid)
- {
- }
-}
-
-PHY_IPhysicsController* DummyPhysicsEnvironment::RayTest(PHY_IRayCastFilterCallback &filterCallback,float fromX,float fromY,float fromZ, float toX,float toY,float toZ)
-{
- //collision detection / raytesting
- return NULL;
-}
-
diff --git a/source/gameengine/Physics/Dummy/DummyPhysicsEnvironment.h b/source/gameengine/Physics/Dummy/DummyPhysicsEnvironment.h
deleted file mode 100644
index 3e9379dd60d..00000000000
--- a/source/gameengine/Physics/Dummy/DummyPhysicsEnvironment.h
+++ /dev/null
@@ -1,134 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file DummyPhysicsEnvironment.h
- * \ingroup physdummy
- */
-
-#ifndef __DUMMYPHYSICSENVIRONMENT_H__
-#define __DUMMYPHYSICSENVIRONMENT_H__
-
-#include "PHY_IPhysicsEnvironment.h"
-#include "PHY_IMotionState.h"
-
-/**
- * DummyPhysicsEnvironment is an empty placeholder
- * Alternatives are ODE,Sumo and Dynamo PhysicsEnvironments
- * Use DummyPhysicsEnvironment as a base to integrate your own physics engine
- * Physics Environment takes care of stepping the simulation and is a container for physics entities (rigidbodies,constraints, materials etc.)
- *
- * A derived class may be able to 'construct' entities by loading and/or converting
- */
-class DummyPhysicsEnvironment : public PHY_IPhysicsEnvironment
-{
-
-public:
- DummyPhysicsEnvironment ();
- virtual ~DummyPhysicsEnvironment ();
- virtual void BeginFrame();
- virtual void EndFrame();
-// Perform an integration step of duration 'timeStep'.
- virtual bool ProceedDeltaTime(double curTime,float timeStep,float interval);
- virtual void SetFixedTimeStep(bool useFixedTimeStep,float fixedTimeStep);
- virtual float GetFixedTimeStep();
-
- virtual int GetDebugMode() const;
-
- virtual void SetGravity(float x,float y,float z);
- virtual void GetGravity(class MT_Vector3& grav);
-
- virtual int CreateConstraint(class PHY_IPhysicsController* ctrl,class PHY_IPhysicsController* ctrl2,PHY_ConstraintType type,
- float pivotX,float pivotY,float pivotZ,
- float axisX,float axisY,float axisZ,
- float axis1X=0,float axis1Y=0,float axis1Z=0,
- float axis2X=0,float axis2Y=0,float axis2Z=0,int flag=0
- );
-
- virtual void RemoveConstraintById(int constraintid);
-
- //complex constraint for vehicles
- virtual PHY_IVehicle* GetVehicleConstraint(int constraintId)
- {
- return 0;
- }
-
- // Character physics wrapper
- virtual PHY_ICharacter* GetCharacterController(class KX_GameObject* ob)
- {
- return 0;
- }
-
- virtual PHY_IPhysicsController* RayTest(PHY_IRayCastFilterCallback &filterCallback, float fromX,float fromY,float fromZ, float toX,float toY,float toZ);
- virtual bool CullingTest(PHY_CullingCallback callback, void* userData, class MT_Vector4* planes, int nplanes, int occlusionRes, const int *viewport, float modelview[16], float projection[16]) { return false; }
-
-
- //gamelogic callbacks
- virtual void AddSensor(PHY_IPhysicsController* ctrl) {}
- virtual void RemoveSensor(PHY_IPhysicsController* ctrl) {}
- virtual void AddTouchCallback(int response_class, PHY_ResponseCallback callback, void *user)
- {
- }
- virtual bool RequestCollisionCallback(PHY_IPhysicsController* ctrl) { return false; }
- virtual bool RemoveCollisionCallback(PHY_IPhysicsController* ctrl) { return false;}
- virtual PHY_IPhysicsController* CreateSphereController(float radius,const class MT_Vector3& position) {return 0;}
- virtual PHY_IPhysicsController* CreateConeController(float coneradius,float coneheight) { return 0;}
-
- virtual void SetConstraintParam(int constraintId,int param,float value,float value1)
- {
- }
-
- virtual float GetConstraintParam(int constraintId,int param)
- {
- return 0.f;
- }
-
- virtual void MergeEnvironment(PHY_IPhysicsEnvironment *other_env)
- {
- // Dummy, nothing to do here
- }
-
- virtual void ConvertObject(KX_GameObject* gameobj,
- RAS_MeshObject* meshobj,
- DerivedMesh* dm,
- KX_Scene* kxscene,
- PHY_ShapeProps* shapeprops,
- PHY_MaterialProps* smmaterial,
- PHY_IMotionState *motionstate,
- int activeLayerBitInfo,
- bool isCompoundChild,
- bool hasCompoundChildren)
- {
- // All we need to do is handle the motionstate (we're supposed to own it)
- delete motionstate;
- }
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:DummyPhysicsEnvironment")
-#endif
-};
-
-#endif /* __DUMMYPHYSICSENVIRONMENT_H__ */
diff --git a/source/gameengine/Physics/common/PHY_DynamicTypes.h b/source/gameengine/Physics/common/PHY_DynamicTypes.h
deleted file mode 100644
index d10f48ad7a4..00000000000
--- a/source/gameengine/Physics/common/PHY_DynamicTypes.h
+++ /dev/null
@@ -1,91 +0,0 @@
-/*
-Bullet Continuous Collision Detection and Physics Library
-Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
-
-This software is provided 'as-is', without any express or implied warranty.
-In no event will the authors be held liable for any damages arising from the use of this software.
-Permission is granted to anyone to use this software for any purpose,
-including commercial applications, and to alter it and redistribute it freely,
-subject to the following restrictions:
-
-1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
-2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
-3. This notice may not be removed or altered from any source distribution.
-*/
-
-/** \file PHY_DynamicTypes.h
- * \ingroup phys
- */
-
-#ifndef __PHY_DYNAMICTYPES_H__
-#define __PHY_DYNAMICTYPES_H__
-
-#include "MT_Vector3.h"
-
-struct KX_ClientObjectInfo;
-
-enum
-{
- PHY_FH_RESPONSE,
- PHY_SENSOR_RESPONSE, /* Touch Sensors */
- PHY_CAMERA_RESPONSE, /* Visibility Culling */
- PHY_OBJECT_RESPONSE, /* Object Dynamic Geometry Response */
- PHY_STATIC_RESPONSE, /* Static Geometry Response */
- PHY_BROADPH_RESPONSE, /* broadphase Response */
-
- PHY_NUM_RESPONSE
-};
-
-typedef struct PHY_CollData {
- MT_Vector3 m_point1; /* Point in object1 in world coordinates */
- MT_Vector3 m_point2; /* Point in object2 in world coordinates */
- MT_Vector3 m_normal; /* point2 - point1 */
-} PHY_CollData;
-
-
-typedef bool (*PHY_ResponseCallback)(void *client_data,
- void *client_object1,
- void *client_object2,
- const PHY_CollData *coll_data);
-typedef void (*PHY_CullingCallback)(KX_ClientObjectInfo* info, void* param);
-
-
-/// PHY_PhysicsType enumerates all possible Physics Entities.
-/// It is mainly used to create/add Physics Objects
-
-typedef enum PHY_PhysicsType {
- PHY_CONVEX_RIGIDBODY=16386,
- PHY_CONCAVE_RIGIDBODY=16399,
- PHY_CONVEX_FIXEDBODY=16388,//'collision object'
- PHY_CONCAVE_FIXEDBODY=16401,
- PHY_CONVEX_KINEMATICBODY=16387,//
- PHY_CONCAVE_KINEMATICBODY=16400,
- PHY_CONVEX_PHANTOMBODY=16398,
- PHY_CONCAVE_PHANTOMBODY=16402
-} PHY_PhysicsType;
-
-/// PHY_ConstraintType enumerates all supported Constraint Types
-typedef enum PHY_ConstraintType {
- PHY_POINT2POINT_CONSTRAINT=1,
- PHY_LINEHINGE_CONSTRAINT=2,
- PHY_ANGULAR_CONSTRAINT = 3,//hinge without ball socket
- PHY_CONE_TWIST_CONSTRAINT = 4,
- PHY_VEHICLE_CONSTRAINT=11,//complex 'constraint' that turns a rigidbody into a vehicle
- PHY_GENERIC_6DOF_CONSTRAINT=12,//can leave any of the 6 degree of freedom 'free' or 'locked'
-
-} PHY_ConstraintType;
-
-typedef enum PHY_ShapeType {
- PHY_SHAPE_NONE,
- PHY_SHAPE_BOX,
- PHY_SHAPE_SPHERE,
- PHY_SHAPE_CYLINDER,
- PHY_SHAPE_CONE,
- PHY_SHAPE_CAPSULE,
- PHY_SHAPE_MESH,
- PHY_SHAPE_POLYTOPE,
- PHY_SHAPE_COMPOUND,
- PHY_SHAPE_PROXY
-} PHY_ShapeType;
-
-#endif /* __PHY_DYNAMICTYPES_H__ */
diff --git a/source/gameengine/Physics/common/PHY_ICharacter.h b/source/gameengine/Physics/common/PHY_ICharacter.h
deleted file mode 100644
index 1a924904b7d..00000000000
--- a/source/gameengine/Physics/common/PHY_ICharacter.h
+++ /dev/null
@@ -1,39 +0,0 @@
-
-/** \file PHY_ICharacter.h
- * \ingroup phys
- */
-
-#ifndef __PHY_ICHARACTER_H__
-#define __PHY_ICHARACTER_H__
-
-//PHY_ICharacter provides a generic interface for "character" controllers
-
-#ifdef WITH_CXX_GUARDEDALLOC
-#include "MEM_guardedalloc.h"
-#endif
-
-class PHY_ICharacter
-{
-public:
- virtual ~PHY_ICharacter() {};
-
- virtual void Jump()= 0;
- virtual bool OnGround()= 0;
-
- virtual float GetGravity()= 0;
- virtual void SetGravity(float gravity)= 0;
-
- virtual unsigned char GetMaxJumps() = 0;
- virtual void SetMaxJumps(unsigned char maxJumps) = 0;
-
- virtual unsigned char GetJumpCount() = 0;
-
- virtual void SetWalkDirection(const class MT_Vector3& dir)=0;
- virtual MT_Vector3 GetWalkDirection()=0;
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:PHY_ICharacter")
-#endif
-};
-
-#endif //__PHY_ICHARACTER_H__
diff --git a/source/gameengine/Physics/common/PHY_IController.h b/source/gameengine/Physics/common/PHY_IController.h
deleted file mode 100644
index 741fae8d2ad..00000000000
--- a/source/gameengine/Physics/common/PHY_IController.h
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file PHY_IController.h
- * \ingroup phys
- */
-
-#ifndef __PHY_ICONTROLLER_H__
-#define __PHY_ICONTROLLER_H__
-
-#include "PHY_DynamicTypes.h"
-
-class PHY_IPhysicsEnvironment;
-
-#ifdef WITH_CXX_GUARDEDALLOC
-#include "MEM_guardedalloc.h"
-#endif
-
-/**
- * PHY_IController is the abstract simplified Interface to objects
- * controlled by the physics engine. This includes the physics objects
- * and the graphics object for view frustrum and occlusion culling.
- */
-class PHY_IController
-{
- public:
- virtual ~PHY_IController() {};
- // clientinfo for raycasts for example
- virtual void* GetNewClientInfo()=0;
- virtual void SetNewClientInfo(void* clientinfo)=0;
- virtual void SetPhysicsEnvironment(class PHY_IPhysicsEnvironment *env)=0;
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:PHY_IController")
-#endif
-};
-
-#endif /* __PHY_ICONTROLLER_H__ */
diff --git a/source/gameengine/Physics/common/PHY_IGraphicController.h b/source/gameengine/Physics/common/PHY_IGraphicController.h
deleted file mode 100644
index b047edd93eb..00000000000
--- a/source/gameengine/Physics/common/PHY_IGraphicController.h
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file PHY_IGraphicController.h
- * \ingroup phys
- */
-
-#ifndef __PHY_IGRAPHICCONTROLLER_H__
-#define __PHY_IGRAPHICCONTROLLER_H__
-
-#include "PHY_IController.h"
-
-
-/**
- * PHY_IPhysicsController is the abstract simplified Interface to a physical object.
- * It contains the IMotionState and IDeformableMesh Interfaces.
- */
-class PHY_IGraphicController : public PHY_IController
-{
- public:
- /**
- * SynchronizeMotionStates ynchronizes dynas, kinematic and deformable entities (and do 'late binding')
- */
- virtual bool SetGraphicTransform()=0;
- virtual void Activate(bool active=true)=0;
- virtual void SetLocalAabb(const class MT_Vector3& aabbMin,const class MT_Vector3& aabbMax)=0;
- virtual void SetLocalAabb(const float* aabbMin,const float* aabbMax)=0;
-
- virtual PHY_IGraphicController* GetReplica(class PHY_IMotionState* motionstate) {return 0;}
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:PHY_IController")
-#endif
-};
-
-#endif /* __PHY_IGRAPHICCONTROLLER_H__ */
diff --git a/source/gameengine/Physics/common/PHY_IMotionState.h b/source/gameengine/Physics/common/PHY_IMotionState.h
deleted file mode 100644
index e803d658713..00000000000
--- a/source/gameengine/Physics/common/PHY_IMotionState.h
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file PHY_IMotionState.h
- * \ingroup phys
- */
-
-#ifndef __PHY_IMOTIONSTATE_H__
-#define __PHY_IMOTIONSTATE_H__
-
-#ifdef WITH_CXX_GUARDEDALLOC
-#include "MEM_guardedalloc.h"
-#endif
-
-/**
- * PHY_IMotionState is the Interface to explicitly synchronize the world transformation.
- * Default implementations for mayor graphics libraries like OpenGL and DirectX can be provided.
- */
-class PHY_IMotionState
-
-{
- public:
- virtual ~PHY_IMotionState() {};
-
- virtual void GetWorldPosition(float& posX,float& posY,float& posZ)=0;
- virtual void GetWorldScaling(float& scaleX,float& scaleY,float& scaleZ)=0;
- virtual void GetWorldOrientation(float& quatIma0,float& quatIma1,float& quatIma2,float& quatReal)=0;
- // ori = array 12 floats, [0..3] = first column + 0, [4..7] = second column, [8..11] = third column
- virtual void GetWorldOrientation(float* ori)=0;
- virtual void SetWorldOrientation(const float* ori)=0;
-
- virtual void SetWorldPosition(float posX,float posY,float posZ)=0;
- virtual void SetWorldOrientation(float quatIma0,float quatIma1,float quatIma2,float quatReal)=0;
-
-
- virtual void CalculateWorldTransformations()=0;
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:PHY_IMotionState")
-#endif
-};
-
-#endif /* __PHY_IMOTIONSTATE_H__ */
diff --git a/source/gameengine/Physics/common/PHY_IPhysicsController.h b/source/gameengine/Physics/common/PHY_IPhysicsController.h
deleted file mode 100644
index 4c6e8c71ef7..00000000000
--- a/source/gameengine/Physics/common/PHY_IPhysicsController.h
+++ /dev/null
@@ -1,154 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file PHY_IPhysicsController.h
- * \ingroup phys
- */
-
-#ifndef __PHY_IPHYSICSCONTROLLER_H__
-#define __PHY_IPHYSICSCONTROLLER_H__
-
-#include <vector>
-#include "PHY_IController.h"
-
-class PHY_IMotionState;
-class PHY_IPhysicsEnvironment;
-
-class MT_Vector3;
-class MT_Point3;
-class MT_Matrix3x3;
-
-class KX_GameObject;
-class RAS_MeshObject;
-
-/**
- * PHY_IPhysicsController is the abstract simplified Interface to a physical object.
- * It contains the IMotionState and IDeformableMesh Interfaces.
- */
-class PHY_IPhysicsController : public PHY_IController
-{
-
- public:
- virtual ~PHY_IPhysicsController() {};
- /**
- * SynchronizeMotionStates ynchronizes dynas, kinematic and deformable entities (and do 'late binding')
- */
- virtual bool SynchronizeMotionStates(float time)=0;
- /**
- * WriteMotionStateToDynamics ynchronizes dynas, kinematic and deformable entities (and do 'late binding')
- */
-
- virtual void WriteMotionStateToDynamics(bool nondynaonly)=0;
- virtual void WriteDynamicsToMotionState()=0;
- virtual class PHY_IMotionState* GetMotionState() = 0;
- // controller replication
- virtual void PostProcessReplica(class PHY_IMotionState* motionstate,class PHY_IPhysicsController* parentctrl)=0;
- virtual void SetPhysicsEnvironment(class PHY_IPhysicsEnvironment *env)=0;
-
- // kinematic methods
- virtual void RelativeTranslate(const MT_Vector3& dloc,bool local)=0;
- virtual void RelativeRotate(const MT_Matrix3x3&,bool local)=0;
- virtual MT_Matrix3x3 GetOrientation()=0;
- virtual void SetOrientation(const MT_Matrix3x3& orn)=0;
- virtual void SetPosition(const MT_Vector3& pos)=0;
- virtual void GetPosition(MT_Vector3& pos) const=0;
- virtual void SetScaling(const MT_Vector3& scale)=0;
- virtual void SetTransform()=0;
-
- virtual MT_Scalar GetMass()=0;
- virtual void SetMass(MT_Scalar newmass)=0;
-
- // physics methods
- virtual void ApplyImpulse(const MT_Point3& attach, const MT_Vector3& impulse,bool local)=0;
- virtual void ApplyTorque(const MT_Vector3& torque,bool local)=0;
- virtual void ApplyForce(const MT_Vector3& force,bool local)=0;
- virtual void SetAngularVelocity(const MT_Vector3& ang_vel,bool local)=0;
- virtual void SetLinearVelocity(const MT_Vector3& lin_vel,bool local)=0;
- virtual void ResolveCombinedVelocities(float linvelX,float linvelY,float linvelZ,float angVelX,float angVelY,float angVelZ) = 0;
-
- virtual float GetLinearDamping() const=0;
- virtual float GetAngularDamping() const=0;
- virtual void SetLinearDamping(float damping)=0;
- virtual void SetAngularDamping(float damping)=0;
- virtual void SetDamping(float linear, float angular)=0;
-
- virtual void RefreshCollisions() = 0;
- virtual void SuspendDynamics(bool ghost=false)=0;
- virtual void RestoreDynamics()=0;
-
- virtual void SetActive(bool active)=0;
-
- // reading out information from physics
- virtual MT_Vector3 GetLinearVelocity()=0;
- virtual MT_Vector3 GetAngularVelocity()=0;
- virtual MT_Vector3 GetVelocity(const MT_Point3& pos)=0;
- virtual MT_Vector3 GetLocalInertia()=0;
-
- // dyna's that are rigidbody are free in orientation, dyna's with non-rigidbody are restricted
- virtual void SetRigidBody(bool rigid)=0;
-
- virtual PHY_IPhysicsController* GetReplica() {return 0;}
- virtual PHY_IPhysicsController* GetReplicaForSensors() {return 0;}
-
- virtual void CalcXform() =0;
- virtual void SetMargin(float margin) =0;
- virtual float GetMargin() const=0;
- virtual float GetRadius() const=0;
- virtual void SetRadius(float margin) = 0;
-
- virtual float GetLinVelocityMin() const=0;
- virtual void SetLinVelocityMin(float val) = 0;
- virtual float GetLinVelocityMax() const=0;
- virtual void SetLinVelocityMax(float val) = 0;
-
- virtual void SetAngularVelocityMin(float val) = 0;
- virtual float GetAngularVelocityMin() const = 0;
- virtual void SetAngularVelocityMax(float val) = 0;
- virtual float GetAngularVelocityMax() const = 0;
-
- MT_Vector3 GetWorldPosition(MT_Vector3& localpos);
-
- // Shape control
- virtual void AddCompoundChild(PHY_IPhysicsController* child) = 0;
- virtual void RemoveCompoundChild(PHY_IPhysicsController* child) = 0;
-
-
- virtual bool IsDynamic() = 0;
- virtual bool IsCompound() = 0;
- virtual bool IsSuspended() const = 0;
-
- virtual bool ReinstancePhysicsShape(KX_GameObject *from_gameobj, RAS_MeshObject* from_meshobj) = 0;
-
- /* Method to replicate rigid body joint contraints for group instances. */
- virtual void ReplicateConstraints(KX_GameObject *gameobj, std::vector<KX_GameObject*> constobj) = 0;
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:PHY_IPhysicsController")
-#endif
-};
-
-#endif /* __PHY_IPHYSICSCONTROLLER_H__ */
diff --git a/source/gameengine/Physics/common/PHY_IPhysicsEnvironment.h b/source/gameengine/Physics/common/PHY_IPhysicsEnvironment.h
deleted file mode 100644
index 72ec7b1edd0..00000000000
--- a/source/gameengine/Physics/common/PHY_IPhysicsEnvironment.h
+++ /dev/null
@@ -1,226 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file PHY_IPhysicsEnvironment.h
- * \ingroup phys
- */
-
-#ifndef __PHY_IPHYSICSENVIRONMENT_H__
-#define __PHY_IPHYSICSENVIRONMENT_H__
-
-#include "PHY_DynamicTypes.h"
-#include "MT_Vector2.h"
-#include "MT_Vector3.h"
-#include "MT_Vector4.h"
-
-#ifdef WITH_CXX_GUARDEDALLOC
-#include "MEM_guardedalloc.h"
-#endif
-
-class PHY_IVehicle;
-class PHY_ICharacter;
-class RAS_MeshObject;
-class PHY_IPhysicsController;
-
-
-class RAS_MeshObject;
-struct DerivedMesh;
-class KX_GameObject;
-class KX_Scene;
-
-struct PHY_ShapeProps;
-struct PHY_MaterialProps;
-class PHY_IMotionState;
-struct bRigidBodyJointConstraint;
-
-/**
- * pass back information from rayTest
- */
-struct PHY_RayCastResult
-{
- PHY_IPhysicsController* m_controller;
- MT_Vector3 m_hitPoint;
- MT_Vector3 m_hitNormal;
- const RAS_MeshObject* m_meshObject; // !=NULL for mesh object (only for Bullet controllers)
- int m_polygon; // index of the polygon hit by the ray,
- // only if m_meshObject != NULL
- int m_hitUVOK; // !=0 if UV coordinate in m_hitUV is valid
- MT_Vector2 m_hitUV; // UV coordinates of hit point
-};
-
-/**
- * This class replaces the ignoreController parameter of rayTest function.
- * It allows more sophisticated filtering on the physics controller before computing the ray intersection to save CPU.
- * It is only used to its full extend by the Ccd physics environment (Bullet).
- */
-class PHY_IRayCastFilterCallback
-{
-public:
- PHY_IPhysicsController* m_ignoreController;
- bool m_faceNormal;
- bool m_faceUV;
-
- virtual ~PHY_IRayCastFilterCallback()
- {
- }
-
- virtual bool needBroadphaseRayCast(PHY_IPhysicsController* controller)
- {
- return true;
- }
-
- virtual void reportHit(PHY_RayCastResult* result) = 0;
-
- PHY_IRayCastFilterCallback(PHY_IPhysicsController* ignoreController, bool faceNormal=false, bool faceUV=false)
- :m_ignoreController(ignoreController),
- m_faceNormal(faceNormal),
- m_faceUV(faceUV)
- {
- }
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:PHY_IRayCastFilterCallback")
-#endif
-};
-
-/**
- * Physics Environment takes care of stepping the simulation and is a container for physics entities
- * (rigidbodies,constraints, materials etc.)
- * A derived class may be able to 'construct' entities by loading and/or converting
- */
-class PHY_IPhysicsEnvironment
-{
- public:
- virtual ~PHY_IPhysicsEnvironment() {}
- virtual void BeginFrame() = 0;
- virtual void EndFrame() = 0;
- /// Perform an integration step of duration 'timeStep'.
- virtual bool ProceedDeltaTime(double curTime,float timeStep,float interval)=0;
- ///draw debug lines (make sure to call this during the render phase, otherwise lines are not drawn properly)
- virtual void DebugDrawWorld() {}
- virtual void SetFixedTimeStep(bool useFixedTimeStep,float fixedTimeStep)=0;
- //returns 0.f if no fixed timestep is used
- virtual float GetFixedTimeStep()=0;
-
- ///getDebugMode return the actual debug visualization state
- virtual int GetDebugMode()const=0;
- ///setDebugMode is used to support several ways of debug lines, contact point visualization
- virtual void SetDebugMode(int debugMode) {}
- ///setNumIterations set the number of iterations for iterative solvers
- virtual void SetNumIterations(int numIter) {}
- ///setNumTimeSubSteps set the number of divisions of the timestep. Tradeoff quality versus performance.
- virtual void SetNumTimeSubSteps(int numTimeSubSteps) {}
- virtual int GetNumTimeSubSteps() {return 0; }
- ///setDeactivationTime sets the minimum time that an objects has to stay within the velocity tresholds until it gets fully deactivated
- virtual void SetDeactivationTime(float dTime) {}
- ///setDeactivationLinearTreshold sets the linear velocity treshold, see setDeactivationTime
- virtual void SetDeactivationLinearTreshold(float linTresh) {}
- ///setDeactivationAngularTreshold sets the angular velocity treshold, see setDeactivationTime
- virtual void SetDeactivationAngularTreshold(float angTresh) {}
- ///setContactBreakingTreshold sets tresholds to do with contact point management
- virtual void SetContactBreakingTreshold(float contactBreakingTreshold) {}
- ///continuous collision detection mode, very experimental for Bullet
- virtual void SetCcdMode(int ccdMode) {}
- ///successive overrelaxation constant, in case PSOR is used, values in between 1 and 2 guarantee converging behavior
- virtual void SetSolverSorConstant(float sor) {}
- ///setSolverType, internal setting, chooses solvertype, PSOR, Dantzig, impulse based, penalty based
- virtual void SetSolverType(int solverType) {}
- ///setTau sets the spring constant of a penalty based solver
- virtual void SetSolverTau(float tau) {}
- ///setDamping sets the damper constant of a penalty based solver
- virtual void SetSolverDamping(float damping) {}
- ///linear air damping for rigidbodies
- virtual void SetLinearAirDamping(float damping) {}
- /// penetrationdepth setting
- virtual void SetUseEpa(bool epa) {}
-
- virtual void SetGravity(float x,float y,float z)=0;
- virtual void GetGravity(MT_Vector3& grav) = 0;
-
- virtual int CreateConstraint(class PHY_IPhysicsController* ctrl,class PHY_IPhysicsController* ctrl2,PHY_ConstraintType type,
- float pivotX,float pivotY,float pivotZ,
- float axis0X,float axis0Y,float axis0Z,
- float axis1X=0,float axis1Y=0,float axis1Z=0,
- float axis2X=0,float axis2Y=0,float axis2Z=0,int flag=0
- )=0;
- virtual void RemoveConstraintById(int constraintid) = 0;
- virtual float GetAppliedImpulse(int constraintid) { return 0.0f; }
-
-
- //complex constraint for vehicles
- virtual PHY_IVehicle* GetVehicleConstraint(int constraintId) =0;
-
- // Character physics wrapper
- virtual PHY_ICharacter* GetCharacterController(class KX_GameObject* ob) =0;
-
- virtual PHY_IPhysicsController* RayTest(PHY_IRayCastFilterCallback &filterCallback, float fromX,float fromY,float fromZ, float toX,float toY,float toZ)=0;
-
- //culling based on physical broad phase
- // the plane number must be set as follow: near, far, left, right, top, botton
- // the near plane must be the first one and must always be present, it is used to get the direction of the view
- virtual bool CullingTest(PHY_CullingCallback callback, void *userData, MT_Vector4* planeNormals, int planeNumber, int occlusionRes, const int *viewport, float modelview[16], float projection[16]) = 0;
-
- //Methods for gamelogic collision/physics callbacks
- //todo:
- virtual void AddSensor(PHY_IPhysicsController* ctrl)=0;
- virtual void RemoveSensor(PHY_IPhysicsController* ctrl)=0;
- virtual void AddTouchCallback(int response_class, PHY_ResponseCallback callback, void *user)=0;
- virtual bool RequestCollisionCallback(PHY_IPhysicsController* ctrl)=0;
- virtual bool RemoveCollisionCallback(PHY_IPhysicsController* ctrl)=0;
- //These two methods are *solely* used to create controllers for sensor! Don't use for anything else
- virtual PHY_IPhysicsController* CreateSphereController(float radius,const MT_Vector3& position) =0;
- virtual PHY_IPhysicsController* CreateConeController(float coneradius,float coneheight)=0;
-
- virtual void SetConstraintParam(int constraintId,int param,float value,float value1) = 0;
- virtual float GetConstraintParam(int constraintId,int param) = 0;
-
- virtual void ExportFile(const char* filename) {};
-
- virtual void MergeEnvironment(PHY_IPhysicsEnvironment *other_env) = 0;
-
- virtual void ConvertObject(KX_GameObject* gameobj,
- RAS_MeshObject* meshobj,
- DerivedMesh* dm,
- KX_Scene* kxscene,
- PHY_ShapeProps* shapeprops,
- PHY_MaterialProps* smmaterial,
- PHY_IMotionState *motionstate,
- int activeLayerBitInfo,
- bool isCompoundChild,
- bool hasCompoundChildren) = 0;
-
- /* Set the rigid body joints constraints values for converted objects and replicated group instances. */
- virtual void SetupObjectConstraints(KX_GameObject *obj_src, KX_GameObject *obj_dest,
- bRigidBodyJointConstraint *dat) {}
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:PHY_IPhysicsEnvironment")
-#endif
-};
-
-#endif /* __PHY_IPHYSICSENVIRONMENT_H__ */
diff --git a/source/gameengine/Physics/common/PHY_IVehicle.h b/source/gameengine/Physics/common/PHY_IVehicle.h
deleted file mode 100644
index 7e4a49e923e..00000000000
--- a/source/gameengine/Physics/common/PHY_IVehicle.h
+++ /dev/null
@@ -1,69 +0,0 @@
-
-/** \file PHY_IVehicle.h
- * \ingroup phys
- */
-
-#ifndef __PHY_IVEHICLE_H__
-#define __PHY_IVEHICLE_H__
-
-//PHY_IVehicle provides a generic interface for (raycast based) vehicles. Mostly targetting 4 wheel cars and 2 wheel motorbikes.
-
-class PHY_IMotionState;
-#include "PHY_DynamicTypes.h"
-
-#ifdef WITH_CXX_GUARDEDALLOC
-#include "MEM_guardedalloc.h"
-#endif
-
-class PHY_IVehicle
-{
-public:
- virtual ~PHY_IVehicle() {};
-
- virtual void AddWheel(
- PHY_IMotionState* motionState,
- MT_Vector3 connectionPoint,
- MT_Vector3 downDirection,
- MT_Vector3 axleDirection,
- float suspensionRestLength,
- float wheelRadius,
- bool hasSteering
- ) = 0;
-
-
- virtual int GetNumWheels() const = 0;
-
- virtual void GetWheelPosition(int wheelIndex,float& posX,float& posY,float& posZ) const = 0;
- virtual void GetWheelOrientationQuaternion(int wheelIndex,float& quatX,float& quatY,float& quatZ,float& quatW) const = 0;
- virtual float GetWheelRotation(int wheelIndex) const = 0;
-
- virtual int GetUserConstraintId() const =0;
- virtual int GetUserConstraintType() const =0;
-
- //some basic steering/braking/tuning/balancing (bikes)
-
- virtual void SetSteeringValue(float steering,int wheelIndex) = 0;
-
- virtual void ApplyEngineForce(float force,int wheelIndex) = 0;
-
- virtual void ApplyBraking(float braking,int wheelIndex) = 0;
-
- virtual void SetWheelFriction(float friction,int wheelIndex) = 0;
-
- virtual void SetSuspensionStiffness(float suspensionStiffness,int wheelIndex) = 0;
-
- virtual void SetSuspensionDamping(float suspensionStiffness,int wheelIndex) = 0;
-
- virtual void SetSuspensionCompression(float suspensionStiffness,int wheelIndex) = 0;
-
- virtual void SetRollInfluence(float rollInfluence,int wheelIndex) = 0;
-
- virtual void SetCoordinateSystem(int rightIndex,int upIndex,int forwardIndex) =0;
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:PHY_IVehicle")
-#endif
-};
-
-#endif /* __PHY_IVEHICLE_H__ */
diff --git a/source/gameengine/Physics/common/PHY_Pro.h b/source/gameengine/Physics/common/PHY_Pro.h
deleted file mode 100644
index bfe574e73cb..00000000000
--- a/source/gameengine/Physics/common/PHY_Pro.h
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file PHY_Pro.h
- * \ingroup phys
- */
-
-#ifndef __PHY_PRO_H__
-#define __PHY_PRO_H__
-
-#include <MT_Scalar.h>
-
-// Properties of dynamic objects
-struct PHY_ShapeProps {
- MT_Scalar m_mass; // Total mass
- MT_Scalar m_inertia; // Inertia, should be a tensor some time
- MT_Scalar m_lin_drag; // Linear drag (air, water) 0 = concrete, 1 = vacuum, inverted and called dampening in blenders UI
- MT_Scalar m_ang_drag; // Angular drag, inverted and called dampening in blenders UI
- MT_Scalar m_friction_scaling[3]; // Scaling for anisotropic friction. Component in range [0, 1]
- MT_Scalar m_clamp_vel_min; // Clamp the minimum velocity, this ensures an object moves at a minimum speed unless its stationary
- MT_Scalar m_clamp_vel_max; // Clamp max velocity
- MT_Scalar m_clamp_angvel_min; // Clamp the minimum angular velocity.
- MT_Scalar m_clamp_angvel_max; // Clamp the maximum angular velocity.
- bool m_do_anisotropic; // Should I do anisotropic friction?
- bool m_do_fh; // Should the object have a linear Fh spring?
- bool m_do_rot_fh; // Should the object have an angular Fh spring?
- MT_Scalar m_step_height; // Max height of climbable steps (Character)
- MT_Scalar m_jump_speed; // Velocity of jumps (Character)
- MT_Scalar m_fall_speed; // Max velocity of falling (Character)
- unsigned char m_max_jumps; // Max ammount of jumps (Character)
-};
-
-
-// Properties of collidable objects (non-ghost objects)
-struct PHY_MaterialProps {
- MT_Scalar m_restitution; // restitution of energie after a collision 0 = inelastic, 1 = elastic
- MT_Scalar m_friction; // Coulomb friction (= ratio between the normal en maximum friction force)
- MT_Scalar m_fh_spring; // Spring constant (both linear and angular)
- MT_Scalar m_fh_damping; // Damping factor (linear and angular) in range [0, 1]
- MT_Scalar m_fh_distance; // The range above the surface where Fh is active.
- bool m_fh_normal; // Should the object slide off slopes?
-};
-
-#endif /* __PHY_PRO_H__ */
diff --git a/source/gameengine/Rasterizer/CMakeLists.txt b/source/gameengine/Rasterizer/CMakeLists.txt
deleted file mode 100644
index fc7dc90e03b..00000000000
--- a/source/gameengine/Rasterizer/CMakeLists.txt
+++ /dev/null
@@ -1,92 +0,0 @@
-# ***** BEGIN GPL LICENSE BLOCK *****
-#
-# This program is free software; you can redistribute it and/or
-# modify it under the terms of the GNU General Public License
-# as published by the Free Software Foundation; either version 2
-# of the License, or (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software Foundation,
-# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
-#
-# The Original Code is Copyright (C) 2006, Blender Foundation
-# All rights reserved.
-#
-# The Original Code is: all of this file.
-#
-# Contributor(s): Jacques Beaurain.
-#
-# ***** END GPL LICENSE BLOCK *****
-
-set(INC
- .
- ../Expressions
- ../Ketsji
- ../SceneGraph
- ../../blender/makesdna
- ../../blender/blenlib
- ../../blender/blenkernel
- ../../blender/gpu
- ../../blender/imbuf
- ../../../intern/container
- ../../../intern/glew-mx
- ../../../intern/guardedalloc
- ../../../intern/string
-)
-
-set(INC_SYS
- ../../../intern/moto/include
- ${GLEW_INCLUDE_PATH}
- ${PYTHON_INCLUDE_DIRS}
-)
-
-set(SRC
- RAS_2DFilterManager.cpp
- RAS_BucketManager.cpp
- RAS_FramingManager.cpp
- RAS_IPolygonMaterial.cpp
- RAS_MaterialBucket.cpp
- RAS_MeshObject.cpp
- RAS_Polygon.cpp
- RAS_TexVert.cpp
- RAS_texmatrix.cpp
- RAS_ICanvas.cpp
-
- RAS_2DFilterManager.h
- RAS_BucketManager.h
- RAS_CameraData.h
- RAS_Deformer.h
- RAS_FramingManager.h
- RAS_ICanvas.h
- RAS_IPolygonMaterial.h
- RAS_IRasterizer.h
- RAS_ILightObject.h
- RAS_IOffScreen.h
- RAS_ISync.h
- RAS_MaterialBucket.h
- RAS_MeshObject.h
- RAS_ObjectColor.h
- RAS_Polygon.h
- RAS_Rect.h
- RAS_TexMatrix.h
- RAS_TexVert.h
- RAS_OpenGLFilters/RAS_Blur2DFilter.h
- RAS_OpenGLFilters/RAS_Dilation2DFilter.h
- RAS_OpenGLFilters/RAS_Erosion2DFilter.h
- RAS_OpenGLFilters/RAS_GrayScale2DFilter.h
- RAS_OpenGLFilters/RAS_Invert2DFilter.h
- RAS_OpenGLFilters/RAS_Laplacian2DFilter.h
- RAS_OpenGLFilters/RAS_Prewitt2DFilter.h
- RAS_OpenGLFilters/RAS_Sepia2DFilter.h
- RAS_OpenGLFilters/RAS_Sharpen2DFilter.h
- RAS_OpenGLFilters/RAS_Sobel2DFilter.h
-)
-
-add_definitions(${GL_DEFINITIONS})
-
-blender_add_lib(ge_rasterizer "${SRC}" "${INC}" "${INC_SYS}")
diff --git a/source/gameengine/Rasterizer/RAS_2DFilterManager.cpp b/source/gameengine/Rasterizer/RAS_2DFilterManager.cpp
deleted file mode 100644
index f379e2eb486..00000000000
--- a/source/gameengine/Rasterizer/RAS_2DFilterManager.cpp
+++ /dev/null
@@ -1,562 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Rasterizer/RAS_2DFilterManager.cpp
- * \ingroup bgerast
- */
-
-#include "BLI_utildefines.h"
-
-#include "RAS_OpenGLFilters/RAS_Blur2DFilter.h"
-#include "RAS_OpenGLFilters/RAS_Sharpen2DFilter.h"
-#include "RAS_OpenGLFilters/RAS_Dilation2DFilter.h"
-#include "RAS_OpenGLFilters/RAS_Erosion2DFilter.h"
-#include "RAS_OpenGLFilters/RAS_Laplacian2DFilter.h"
-#include "RAS_OpenGLFilters/RAS_Sobel2DFilter.h"
-#include "RAS_OpenGLFilters/RAS_Prewitt2DFilter.h"
-#include "RAS_OpenGLFilters/RAS_GrayScale2DFilter.h"
-#include "RAS_OpenGLFilters/RAS_Sepia2DFilter.h"
-#include "RAS_OpenGLFilters/RAS_Invert2DFilter.h"
-
-#include "STR_String.h"
-#include "RAS_ICanvas.h"
-#include "RAS_Rect.h"
-#include "RAS_2DFilterManager.h"
-#include <iostream>
-
-#include "GPU_glew.h"
-
-#include <stdio.h>
-
-#include "EXP_Value.h"
-
-RAS_2DFilterManager::RAS_2DFilterManager():
-texturewidth(-1), textureheight(-1),
-/* numberoffilters(0), */ /* UNUSED */ need_tex_update(true)
-{
- isshadersupported = GLEW_ARB_shader_objects &&
- GLEW_ARB_fragment_shader && GLEW_ARB_multitexture;
-
- /* used to return before 2.49 but need to initialize values so don't */
- if (!isshadersupported)
- std::cout<<"shaders not supported!" << std::endl;
-
- int passindex;
- for (passindex =0; passindex<MAX_RENDER_PASS; passindex++)
- {
- m_filters[passindex] = 0;
- m_enabled[passindex] = 0;
- texflag[passindex] = 0;
- m_gameObjects[passindex] = NULL;
- }
- texname[0] = texname[1] = texname[2] = -1;
- errorprinted= false;
-}
-
-RAS_2DFilterManager::~RAS_2DFilterManager()
-{
- FreeTextures();
-
- for (int passindex = 0; passindex < MAX_RENDER_PASS; passindex++) {
- if (m_filters[passindex]) {
- glDeleteObjectARB(m_filters[passindex]);
- }
- }
-}
-
-void RAS_2DFilterManager::PrintShaderErrors(unsigned int shader, const char *task, const char *code)
-{
- GLcharARB log[5000];
- GLsizei length = 0;
- const char *c, *pos, *end;
- int line = 1;
-
- if (errorprinted)
- return;
-
- errorprinted= true;
-
- glGetInfoLogARB(shader, sizeof(log), &length, log);
- end = code + strlen(code);
-
- printf("2D Filter GLSL Shader: %s error:\n", task);
-
- c = code;
- while ((c < end) && (pos = strchr(c, '\n'))) {
- printf("%2d ", line);
- fwrite(c, (pos+1)-c, 1, stdout);
- c = pos+1;
- line++;
- }
-
- puts(c);
- puts(log);
- puts("\n");
-}
-
-unsigned int RAS_2DFilterManager::CreateShaderProgram(const char* shadersource)
-{
- GLuint program = 0;
- GLuint fShader = glCreateShaderObjectARB(GL_FRAGMENT_SHADER);
- GLint success;
-
- glShaderSourceARB(fShader, 1, (const char**)&shadersource, NULL);
-
- glCompileShaderARB(fShader);
-
-
- glGetObjectParameterivARB(fShader, GL_COMPILE_STATUS, &success);
- if (!success) {
- /*Shader Comile Error*/
- PrintShaderErrors(fShader, "compile", shadersource);
- goto fail;
- }
-
- program = glCreateProgramObjectARB();
- glAttachObjectARB(program, fShader);
-
- glLinkProgramARB(program);
- glGetObjectParameterivARB(program, GL_LINK_STATUS, &success);
- if (!success) {
- /*Program Link Error*/
- PrintShaderErrors(fShader, "link", shadersource);
- goto fail;
- }
-
- glValidateProgramARB(program);
- glGetObjectParameterivARB(program, GL_VALIDATE_STATUS, &success);
- if (!success) {
- /*Program Validation Error*/
- PrintShaderErrors(fShader, "validate", shadersource);
- goto fail;
- }
-
- /* owned by 'program' */
- if (fShader) {
- glDeleteObjectARB(fShader);
- }
-
- return program;
-
-
-fail:
- if (fShader) {
- glDeleteObjectARB(fShader);
- }
-
- if (program) {
- glDeleteObjectARB(program);
- }
- return 0;
-}
-
-unsigned int RAS_2DFilterManager::CreateShaderProgram(int filtermode)
-{
- switch (filtermode) {
- case RAS_2DFILTER_BLUR:
- return CreateShaderProgram(BlurFragmentShader);
- case RAS_2DFILTER_SHARPEN:
- return CreateShaderProgram(SharpenFragmentShader);
- case RAS_2DFILTER_DILATION:
- return CreateShaderProgram(DilationFragmentShader);
- case RAS_2DFILTER_EROSION:
- return CreateShaderProgram(ErosionFragmentShader);
- case RAS_2DFILTER_LAPLACIAN:
- return CreateShaderProgram(LaplacionFragmentShader);
- case RAS_2DFILTER_SOBEL:
- return CreateShaderProgram(SobelFragmentShader);
- case RAS_2DFILTER_PREWITT:
- return CreateShaderProgram(PrewittFragmentShader);
- case RAS_2DFILTER_GRAYSCALE:
- return CreateShaderProgram(GrayScaleFragmentShader);
- case RAS_2DFILTER_SEPIA:
- return CreateShaderProgram(SepiaFragmentShader);
- case RAS_2DFILTER_INVERT:
- return CreateShaderProgram(InvertFragmentShader);
- }
- return 0;
-}
-
-void RAS_2DFilterManager::AnalyseShader(int passindex, vector<STR_String>& propNames)
-{
- texflag[passindex] = 0;
- if (glGetUniformLocationARB(m_filters[passindex], "bgl_DepthTexture") != -1)
- {
- if (GLEW_ARB_depth_texture)
- texflag[passindex] |= 0x1;
- }
- if (glGetUniformLocationARB(m_filters[passindex], "bgl_LuminanceTexture") != -1)
- {
- texflag[passindex] |= 0x2;
- }
-
- if (m_gameObjects[passindex])
- {
- int objProperties = propNames.size();
- int i;
- for (i=0; i<objProperties; i++)
- if (glGetUniformLocationARB(m_filters[passindex], propNames[i]) != -1)
- m_properties[passindex].push_back(propNames[i]);
- }
-}
-
-void RAS_2DFilterManager::StartShaderProgram(int passindex)
-{
- GLint uniformLoc;
- glUseProgramObjectARB(m_filters[passindex]);
- uniformLoc = glGetUniformLocationARB(m_filters[passindex], "bgl_RenderedTexture");
- glActiveTextureARB(GL_TEXTURE0);
- glBindTexture(GL_TEXTURE_2D, texname[0]);
-
- if (uniformLoc != -1)
- {
- glUniform1iARB(uniformLoc, 0);
- }
-
- /* send depth texture to glsl program if it needs */
- if (texflag[passindex] & 0x1) {
- uniformLoc = glGetUniformLocationARB(m_filters[passindex], "bgl_DepthTexture");
- glActiveTextureARB(GL_TEXTURE1);
- glBindTexture(GL_TEXTURE_2D, texname[1]);
-
- if (uniformLoc != -1)
- {
- glUniform1iARB(uniformLoc, 1);
- }
- }
-
- /* send luminance texture to glsl program if it needs */
- if (texflag[passindex] & 0x2) {
- uniformLoc = glGetUniformLocationARB(m_filters[passindex], "bgl_LuminanceTexture");
- glActiveTextureARB(GL_TEXTURE2);
- glBindTexture(GL_TEXTURE_2D, texname[2]);
-
- if (uniformLoc != -1)
- {
- glUniform1iARB(uniformLoc, 2);
- }
- }
-
- uniformLoc = glGetUniformLocationARB(m_filters[passindex], "bgl_TextureCoordinateOffset");
- if (uniformLoc != -1)
- {
- glUniform2fvARB(uniformLoc, 9, textureoffsets);
- }
- uniformLoc = glGetUniformLocationARB(m_filters[passindex], "bgl_RenderedTextureWidth");
- if (uniformLoc != -1)
- {
- glUniform1fARB(uniformLoc,texturewidth);
- }
- uniformLoc = glGetUniformLocationARB(m_filters[passindex], "bgl_RenderedTextureHeight");
- if (uniformLoc != -1)
- {
- glUniform1fARB(uniformLoc,textureheight);
- }
-
- int i, objProperties = m_properties[passindex].size();
- for (i=0; i<objProperties; i++)
- {
- uniformLoc = glGetUniformLocationARB(m_filters[passindex], m_properties[passindex][i]);
-
- if (uniformLoc == -1)
- continue;
-
- CValue *property = ((CValue *)m_gameObjects[passindex])->GetProperty(m_properties[passindex][i]);
-
- if (!property)
- continue;
-
- switch (property->GetValueType()) {
- case VALUE_INT_TYPE:
- glUniform1iARB(uniformLoc, property->GetNumber());
- break;
- case VALUE_FLOAT_TYPE:
- glUniform1fARB(uniformLoc, property->GetNumber());
- break;
- default:
- break;
- }
- }
-}
-
-void RAS_2DFilterManager::EndShaderProgram()
-{
- glUseProgramObjectARB(0);
-}
-
-void RAS_2DFilterManager::FreeTextures()
-{
- if (texname[0]!=(unsigned int)-1)
- glDeleteTextures(1, (GLuint*)&texname[0]);
- if (texname[1]!=(unsigned int)-1)
- glDeleteTextures(1, (GLuint*)&texname[1]);
- if (texname[2]!=(unsigned int)-1)
- glDeleteTextures(1, (GLuint*)&texname[2]);
-}
-
-void RAS_2DFilterManager::SetupTextures(bool depth, bool luminance)
-{
- FreeTextures();
-
- glGenTextures(1, (GLuint*)&texname[0]);
- glBindTexture(GL_TEXTURE_2D, texname[0]);
- glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, texturewidth, textureheight, 0, GL_RGBA,
- GL_UNSIGNED_BYTE, 0);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
-
- if (depth) {
- glGenTextures(1, (GLuint*)&texname[1]);
- glBindTexture(GL_TEXTURE_2D, texname[1]);
- glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT32, texturewidth,textureheight,
- 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE,NULL);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE,
- GL_NONE);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
- }
-
- if (luminance) {
- glGenTextures(1, (GLuint*)&texname[2]);
- glBindTexture(GL_TEXTURE_2D, texname[2]);
- glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE16, texturewidth, textureheight,
- 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, 0);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
- }
-}
-
-void RAS_2DFilterManager::UpdateOffsetMatrix(RAS_ICanvas* canvas)
-{
- /* RAS_Rect canvas_rect = canvas->GetWindowArea(); */ /* UNUSED */
- texturewidth = canvas->GetWidth()+1;
- textureheight = canvas->GetHeight()+1;
- GLint i,j;
-
- if (!GL_ARB_texture_non_power_of_two)
- {
- i = 0;
- while ((1 << i) <= texturewidth)
- i++;
- texturewidth = (1 << (i));
-
- // Now for height
- i = 0;
- while ((1 << i) <= textureheight)
- i++;
- textureheight = (1 << (i));
- }
-
- GLfloat xInc = 1.0f / (GLfloat)texturewidth;
- GLfloat yInc = 1.0f / (GLfloat)textureheight;
-
- for (i = 0; i < 3; i++)
- {
- for (j = 0; j < 3; j++)
- {
- textureoffsets[(((i*3)+j)*2)+0] = (-1.0f * xInc) + ((GLfloat)i * xInc);
- textureoffsets[(((i*3)+j)*2)+1] = (-1.0f * yInc) + ((GLfloat)j * yInc);
- }
- }
-}
-
-void RAS_2DFilterManager::UpdateCanvasTextureCoord(const int viewport[4])
-{
- /*
- * This function update canvascoord[].
- * These parameters are used to create texcoord[1]
- * That way we can access the texcoord relative to the canvas:
- * (0.0,0.0) bottom left, (1.0,1.0) top right, (0.5,0.5) center
- */
- canvascoord[0] = (GLfloat) viewport[0] / -viewport[2];
- canvascoord[1] = (GLfloat) (texturewidth - viewport[0]) / viewport[2];
-
- canvascoord[2] = (GLfloat) viewport[1] / -viewport[3];
- canvascoord[3] = (GLfloat)(textureheight - viewport[1]) / viewport[3];
-}
-
-void RAS_2DFilterManager::RenderFilters(RAS_ICanvas* canvas)
-{
- bool need_depth=false;
- bool need_luminance=false;
- int num_filters = 0;
-
- int passindex;
-
- if (!isshadersupported)
- return;
-
- for (passindex =0; passindex<MAX_RENDER_PASS; passindex++)
- {
- if (m_filters[passindex] && m_enabled[passindex]) {
- num_filters ++;
- if (texflag[passindex] & 0x1)
- need_depth = true;
- if (texflag[passindex] & 0x2)
- need_luminance = true;
- if (need_depth && need_luminance)
- break;
- }
- }
-
- if (num_filters <= 0)
- return;
-
- const int *viewport = canvas->GetViewPort();
-
- if (texturewidth != viewport[2] || textureheight != viewport[3])
- {
- UpdateOffsetMatrix(canvas);
- UpdateCanvasTextureCoord(viewport);
- need_tex_update = true;
- }
-
- if (need_tex_update)
- {
- SetupTextures(need_depth, need_luminance);
- need_tex_update = false;
- }
-
- if (need_depth) {
- glActiveTextureARB(GL_TEXTURE1);
- glBindTexture(GL_TEXTURE_2D, texname[1]);
- glCopyTexImage2D(GL_TEXTURE_2D,0,GL_DEPTH_COMPONENT, viewport[0], viewport[1], viewport[2], viewport[3], 0);
- }
-
- if (need_luminance) {
- glActiveTextureARB(GL_TEXTURE2);
- glBindTexture(GL_TEXTURE_2D, texname[2]);
- glCopyTexImage2D(GL_TEXTURE_2D,0,GL_LUMINANCE16, viewport[0], viewport[1], viewport[2], viewport[3], 0);
- }
-
- // reverting to texunit 0, without this we get bug [#28462]
- glActiveTextureARB(GL_TEXTURE0);
-
- // We do this to make side-by-side stereo rendering work correctly with 2D filters. It would probably be nicer to just set the viewport,
- // but it can be easier for writing shaders to have the coordinates for the whole screen instead of just part of the screen.
- RAS_Rect scissor_rect = canvas->GetDisplayArea();
-
- glScissor(scissor_rect.GetLeft() + viewport[0],
- scissor_rect.GetBottom() + viewport[1],
- scissor_rect.GetWidth() + 1,
- scissor_rect.GetHeight() + 1);
-
- glDisable(GL_DEPTH_TEST);
- // in case the previous material was wire
- glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
- // if the last rendered face had alpha add it would messes with the color of the plane we apply 2DFilter to
- glDisable(GL_BLEND);
- // fix for [#34523] alpha buffer is now available for all OSs
- glDisable(GL_ALPHA_TEST);
-
- glPushMatrix(); //GL_MODELVIEW
- glLoadIdentity(); // GL_MODELVIEW
- glMatrixMode(GL_TEXTURE);
- glLoadIdentity();
- glMatrixMode(GL_PROJECTION);
- glPushMatrix();
- glLoadIdentity();
-
- for (passindex =0; passindex<MAX_RENDER_PASS; passindex++)
- {
- if (m_filters[passindex] && m_enabled[passindex])
- {
- StartShaderProgram(passindex);
-
- glActiveTextureARB(GL_TEXTURE0);
- glBindTexture(GL_TEXTURE_2D, texname[0]);
- glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, viewport[0], viewport[1], viewport[2], viewport[3], 0); // Don't use texturewidth and textureheight in case we don't have NPOT support
- glClear(GL_COLOR_BUFFER_BIT);
-
- glBegin(GL_QUADS);
- glColor4f(1.f, 1.f, 1.f, 1.f);
- glTexCoord2f(1.0f, 1.0f); glMultiTexCoord2fARB(GL_TEXTURE3_ARB, canvascoord[1], canvascoord[3]); glVertex2f(1.0f,1.0f);
- glTexCoord2f(0.0f, 1.0f); glMultiTexCoord2fARB(GL_TEXTURE3_ARB, canvascoord[0], canvascoord[3]); glVertex2f(-1.0f,1.0f);
- glTexCoord2f(0.0f, 0.0f); glMultiTexCoord2fARB(GL_TEXTURE3_ARB, canvascoord[0], canvascoord[2]); glVertex2f(-1.0f,-1.0f);
- glTexCoord2f(1.0f, 0.0f); glMultiTexCoord2fARB(GL_TEXTURE3_ARB, canvascoord[1], canvascoord[2]); glVertex2f(1.0f,-1.0f);
- glEnd();
- }
- }
-
- glEnable(GL_DEPTH_TEST);
- EndShaderProgram();
- glPopMatrix();
- glMatrixMode(GL_MODELVIEW);
- glPopMatrix();
-}
-
-void RAS_2DFilterManager::EnableFilter(vector<STR_String>& propNames, void* gameObj, RAS_2DFILTER_MODE mode, int pass, STR_String& text)
-{
- if (!isshadersupported)
- return;
- if (pass<0 || pass>=MAX_RENDER_PASS)
- return;
- need_tex_update = true;
- if (mode == RAS_2DFILTER_DISABLED)
- {
- m_enabled[pass] = 0;
- return;
- }
-
- if (mode == RAS_2DFILTER_ENABLED)
- {
- m_enabled[pass] = 1;
- return;
- }
-
- if (mode == RAS_2DFILTER_NOFILTER)
- {
- if (m_filters[pass])
- glDeleteObjectARB(m_filters[pass]);
- m_enabled[pass] = 0;
- m_filters[pass] = 0;
- m_gameObjects[pass] = NULL;
- m_properties[pass].clear();
- texflag[pass] = 0;
- return;
- }
-
- if (mode == RAS_2DFILTER_CUSTOMFILTER)
- {
- if (m_filters[pass])
- glDeleteObjectARB(m_filters[pass]);
- m_filters[pass] = CreateShaderProgram(text.Ptr());
- m_gameObjects[pass] = gameObj;
- AnalyseShader(pass, propNames);
- m_enabled[pass] = 1;
- return;
- }
-
- // We've checked all other cases, which means we must be dealing with a builtin filter
- if (m_filters[pass])
- glDeleteObjectARB(m_filters[pass]);
- m_filters[pass] = CreateShaderProgram(mode);
- m_gameObjects[pass] = NULL;
- AnalyseShader(pass, propNames);
- m_enabled[pass] = 1;
-}
diff --git a/source/gameengine/Rasterizer/RAS_2DFilterManager.h b/source/gameengine/Rasterizer/RAS_2DFilterManager.h
deleted file mode 100644
index bb727fe3b29..00000000000
--- a/source/gameengine/Rasterizer/RAS_2DFilterManager.h
+++ /dev/null
@@ -1,114 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file RAS_2DFilterManager.h
- * \ingroup bgerast
- */
-
-#ifndef __RAS_2DFILTERMANAGER_H__
-#define __RAS_2DFILTERMANAGER_H__
-
-#define MAX_RENDER_PASS 100
-
-#ifdef WITH_CXX_GUARDEDALLOC
-#include "MEM_guardedalloc.h"
-#endif
-
-class RAS_ICanvas;
-
-class RAS_2DFilterManager
-{
-private:
- unsigned int CreateShaderProgram(const char* shadersource);
- unsigned int CreateShaderProgram(int filtermode);
- void AnalyseShader(int passindex, std::vector<STR_String>& propNames);
- void StartShaderProgram(int passindex);
- void EndShaderProgram();
- void PrintShaderErrors(unsigned int shader, const char *task, const char *code);
-
- void SetupTextures(bool depth, bool luminance);
- void FreeTextures();
-
- void UpdateOffsetMatrix(RAS_ICanvas* canvas);
- void UpdateCanvasTextureCoord(const int viewport[4]);
-
- float canvascoord[4];
- float textureoffsets[18];
- /* float view[4]; */ /* UNUSED */
- /* texname[0] contains render to texture, texname[1] contains depth texture, texname[2] contains luminance texture*/
- unsigned int texname[3];
- int texturewidth;
- int textureheight;
- /* int numberoffilters; */ /* UNUSED */
- /* bit 0: enable/disable depth texture
- * bit 1: enable/disable luminance texture*/
- short texflag[MAX_RENDER_PASS];
-
- bool isshadersupported;
- bool errorprinted;
- bool need_tex_update;
-
- unsigned int m_filters[MAX_RENDER_PASS];
- short m_enabled[MAX_RENDER_PASS];
-
- // stores object properties to send to shaders in each pass
- std::vector<STR_String> m_properties[MAX_RENDER_PASS];
- void* m_gameObjects[MAX_RENDER_PASS];
-public:
- enum RAS_2DFILTER_MODE {
- RAS_2DFILTER_ENABLED = -2,
- RAS_2DFILTER_DISABLED = -1,
- RAS_2DFILTER_NOFILTER = 0,
- RAS_2DFILTER_MOTIONBLUR,
- RAS_2DFILTER_BLUR,
- RAS_2DFILTER_SHARPEN,
- RAS_2DFILTER_DILATION,
- RAS_2DFILTER_EROSION,
- RAS_2DFILTER_LAPLACIAN,
- RAS_2DFILTER_SOBEL,
- RAS_2DFILTER_PREWITT,
- RAS_2DFILTER_GRAYSCALE,
- RAS_2DFILTER_SEPIA,
- RAS_2DFILTER_INVERT,
- RAS_2DFILTER_CUSTOMFILTER,
- RAS_2DFILTER_NUMBER_OF_FILTERS
- };
-
- RAS_2DFilterManager();
-
- ~RAS_2DFilterManager();
-
- void RenderFilters(RAS_ICanvas* canvas);
-
- void EnableFilter(std::vector<STR_String>& propNames, void* gameObj, RAS_2DFILTER_MODE mode, int pass, STR_String& text);
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:RAS_2DFilterManager")
-#endif
-};
-#endif
diff --git a/source/gameengine/Rasterizer/RAS_BucketManager.cpp b/source/gameengine/Rasterizer/RAS_BucketManager.cpp
deleted file mode 100644
index deca7cbed9f..00000000000
--- a/source/gameengine/Rasterizer/RAS_BucketManager.cpp
+++ /dev/null
@@ -1,380 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Rasterizer/RAS_BucketManager.cpp
- * \ingroup bgerast
- */
-
-#ifdef _MSC_VER
- /* don't show these anoying STL warnings */
-# pragma warning (disable:4786)
-#endif
-
-#include "RAS_MaterialBucket.h"
-#include "RAS_MeshObject.h"
-#include "RAS_Polygon.h"
-#include "RAS_IPolygonMaterial.h"
-#include "RAS_IRasterizer.h"
-
-#include "RAS_BucketManager.h"
-
-#include <algorithm>
-/* sorting */
-
-struct RAS_BucketManager::sortedmeshslot
-{
-public:
- MT_Scalar m_z; /* depth */
- RAS_MeshSlot *m_ms; /* mesh slot */
- RAS_MaterialBucket *m_bucket; /* buck mesh slot came from */
-
- sortedmeshslot() {}
-
- void set(RAS_MeshSlot *ms, RAS_MaterialBucket *bucket, const MT_Vector3& pnorm)
- {
- // would be good to use the actual bounding box center instead
- MT_Point3 pos(ms->m_OpenGLMatrix[12], ms->m_OpenGLMatrix[13], ms->m_OpenGLMatrix[14]);
-
- m_z = MT_dot(pnorm, pos);
- m_ms = ms;
- m_bucket = bucket;
- }
-};
-
-struct RAS_BucketManager::backtofront
-{
- bool operator()(const sortedmeshslot &a, const sortedmeshslot &b)
- {
- return (a.m_z < b.m_z) || (a.m_z == b.m_z && a.m_ms < b.m_ms);
- }
-};
-
-struct RAS_BucketManager::fronttoback
-{
- bool operator()(const sortedmeshslot &a, const sortedmeshslot &b)
- {
- return (a.m_z > b.m_z) || (a.m_z == b.m_z && a.m_ms > b.m_ms);
- }
-};
-
-/* bucket manager */
-
-RAS_BucketManager::RAS_BucketManager()
-{
-
-}
-
-RAS_BucketManager::~RAS_BucketManager()
-{
- BucketList::iterator it;
-
- for (it = m_SolidBuckets.begin(); it != m_SolidBuckets.end(); it++)
- delete (*it);
-
- for (it = m_AlphaBuckets.begin(); it != m_AlphaBuckets.end(); it++)
- delete(*it);
-
- m_SolidBuckets.clear();
- m_AlphaBuckets.clear();
-}
-
-void RAS_BucketManager::OrderBuckets(const MT_Transform& cameratrans, BucketList& buckets, vector<sortedmeshslot>& slots, bool alpha)
-{
- BucketList::iterator bit;
- list<RAS_MeshSlot>::iterator mit;
- size_t size = 0, i = 0;
-
- /* Camera's near plane equation: pnorm.dot(point) + pval,
- * but we leave out pval since it's constant anyway */
- const MT_Vector3 pnorm(cameratrans.getBasis()[2]);
-
- for (bit = buckets.begin(); bit != buckets.end(); ++bit)
- {
- SG_DList::iterator<RAS_MeshSlot> mit((*bit)->GetActiveMeshSlots());
- for (mit.begin(); !mit.end(); ++mit)
- size++;
- }
-
- slots.resize(size);
-
- for (bit = buckets.begin(); bit != buckets.end(); ++bit)
- {
- RAS_MaterialBucket* bucket = *bit;
- RAS_MeshSlot* ms;
- // remove the mesh slot from the list, it culls them automatically for next frame
- while ((ms = bucket->GetNextActiveMeshSlot())) {
- slots[i++].set(ms, bucket, pnorm);
- }
- }
-
- if (alpha)
- sort(slots.begin(), slots.end(), backtofront());
- else
- sort(slots.begin(), slots.end(), fronttoback());
-}
-
-void RAS_BucketManager::RenderAlphaBuckets(const MT_Transform& cameratrans, RAS_IRasterizer* rasty)
-{
- vector<sortedmeshslot> slots;
- vector<sortedmeshslot>::iterator sit;
-
- // Having depth masks disabled/enabled gives different artifacts in
- // case no sorting is done or is done inexact. For compatibility, we
- // disable it.
- if (rasty->GetDrawingMode() != RAS_IRasterizer::KX_SHADOW)
- rasty->SetDepthMask(RAS_IRasterizer::KX_DEPTHMASK_DISABLED);
-
- OrderBuckets(cameratrans, m_AlphaBuckets, slots, true);
-
- for (sit=slots.begin(); sit!=slots.end(); ++sit) {
- rasty->SetClientObject(sit->m_ms->m_clientObj);
-
- while (sit->m_bucket->ActivateMaterial(cameratrans, rasty))
- sit->m_bucket->RenderMeshSlot(cameratrans, rasty, *(sit->m_ms));
-
- // make this mesh slot culled automatically for next frame
- // it will be culled out by frustum culling
- sit->m_ms->SetCulled(true);
- }
-
- rasty->SetDepthMask(RAS_IRasterizer::KX_DEPTHMASK_ENABLED);
-}
-
-void RAS_BucketManager::RenderSolidBuckets(const MT_Transform& cameratrans, RAS_IRasterizer* rasty)
-{
- BucketList::iterator bit;
-
- rasty->SetDepthMask(RAS_IRasterizer::KX_DEPTHMASK_ENABLED);
-
- for (bit = m_SolidBuckets.begin(); bit != m_SolidBuckets.end(); ++bit) {
-#if 1
- RAS_MaterialBucket* bucket = *bit;
- RAS_MeshSlot* ms;
- // remove the mesh slot from the list, it culls them automatically for next frame
- while ((ms = bucket->GetNextActiveMeshSlot())) {
- rasty->SetClientObject(ms->m_clientObj);
- while (bucket->ActivateMaterial(cameratrans, rasty))
- bucket->RenderMeshSlot(cameratrans, rasty, *ms);
-
- // make this mesh slot culled automatically for next frame
- // it will be culled out by frustum culling
- ms->SetCulled(true);
- }
-#else
- list<RAS_MeshSlot>::iterator mit;
- for (mit = (*bit)->msBegin(); mit != (*bit)->msEnd(); ++mit) {
- if (mit->IsCulled())
- continue;
-
- rasty->SetClientObject(rasty, mit->m_clientObj);
-
- while ((*bit)->ActivateMaterial(cameratrans, rasty))
- (*bit)->RenderMeshSlot(cameratrans, rasty, *mit);
-
- // make this mesh slot culled automatically for next frame
- // it will be culled out by frustum culling
- mit->SetCulled(true);
- }
-#endif
- }
-
- /* this code draws meshes order front-to-back instead to reduce overdraw.
- * it turned out slower due to much material state switching, a more clever
- * algorithm might do better. */
-#if 0
- vector<sortedmeshslot> slots;
- vector<sortedmeshslot>::iterator sit;
-
- OrderBuckets(cameratrans, m_SolidBuckets, slots, false);
-
- for (sit=slots.begin(); sit!=slots.end(); ++sit) {
- rendertools->SetClientObject(rasty, sit->m_ms->m_clientObj);
-
- while (sit->m_bucket->ActivateMaterial(cameratrans, rasty))
- sit->m_bucket->RenderMeshSlot(cameratrans, rasty, *(sit->m_ms));
- }
-#endif
-}
-
-void RAS_BucketManager::Renderbuckets(const MT_Transform& cameratrans, RAS_IRasterizer* rasty)
-{
- /* beginning each frame, clear (texture/material) caching information */
- rasty->ClearCachingInfo();
-
- RenderSolidBuckets(cameratrans, rasty);
- RenderAlphaBuckets(cameratrans, rasty);
-
- /* If we're drawing shadows and bucket wasn't rendered (outside of the lamp frustum or doesn't cast shadows)
- * then the mesh is still modified, so we don't want to set MeshModified to false yet (it will mess up
- * updating display lists). Just leave this step for the main render pass.
- */
- if (rasty->GetDrawingMode() != RAS_IRasterizer::KX_SHADOW) {
- /* All meshes should be up to date now */
- /* Don't do this while processing buckets because some meshes are split between buckets */
- BucketList::iterator bit;
- list<RAS_MeshSlot>::iterator mit;
- for (bit = m_SolidBuckets.begin(); bit != m_SolidBuckets.end(); ++bit) {
- for (mit = (*bit)->msBegin(); mit != (*bit)->msEnd(); ++mit) {
- mit->m_mesh->SetMeshModified(false);
- }
- }
- for (bit = m_AlphaBuckets.begin(); bit != m_AlphaBuckets.end(); ++bit) {
- for (mit = (*bit)->msBegin(); mit != (*bit)->msEnd(); ++mit) {
- mit->m_mesh->SetMeshModified(false);
- }
- }
- }
-
-
- rasty->SetClientObject(NULL);
-}
-
-RAS_MaterialBucket *RAS_BucketManager::FindBucket(RAS_IPolyMaterial *material, bool &bucketCreated)
-{
- BucketList::iterator it;
-
- bucketCreated = false;
-
- for (it = m_SolidBuckets.begin(); it != m_SolidBuckets.end(); it++)
- if (*(*it)->GetPolyMaterial() == *material)
- return *it;
-
- for (it = m_AlphaBuckets.begin(); it != m_AlphaBuckets.end(); it++)
- if (*(*it)->GetPolyMaterial() == *material)
- return *it;
-
- RAS_MaterialBucket *bucket = new RAS_MaterialBucket(material);
- bucketCreated = true;
-
- if (bucket->IsAlpha())
- m_AlphaBuckets.push_back(bucket);
- else
- m_SolidBuckets.push_back(bucket);
-
- return bucket;
-}
-
-void RAS_BucketManager::OptimizeBuckets(MT_Scalar distance)
-{
- BucketList::iterator bit;
-
- distance = 10.0f;
-
- for (bit = m_SolidBuckets.begin(); bit != m_SolidBuckets.end(); ++bit)
- (*bit)->Optimize(distance);
- for (bit = m_AlphaBuckets.begin(); bit != m_AlphaBuckets.end(); ++bit)
- (*bit)->Optimize(distance);
-}
-
-void RAS_BucketManager::ReleaseDisplayLists(RAS_IPolyMaterial *mat)
-{
- BucketList::iterator bit;
- list<RAS_MeshSlot>::iterator mit;
-
- for (bit = m_SolidBuckets.begin(); bit != m_SolidBuckets.end(); ++bit) {
- if (mat == NULL || (mat == (*bit)->GetPolyMaterial())) {
- for (mit = (*bit)->msBegin(); mit != (*bit)->msEnd(); ++mit) {
- if (mit->m_DisplayList) {
- mit->m_DisplayList->Release();
- mit->m_DisplayList = NULL;
- }
- }
- }
- }
-
- for (bit = m_AlphaBuckets.begin(); bit != m_AlphaBuckets.end(); ++bit) {
- if (mat == NULL || (mat == (*bit)->GetPolyMaterial())) {
- for (mit = (*bit)->msBegin(); mit != (*bit)->msEnd(); ++mit) {
- if (mit->m_DisplayList) {
- mit->m_DisplayList->Release();
- mit->m_DisplayList = NULL;
- }
- }
- }
- }
-}
-
-void RAS_BucketManager::ReleaseMaterials(RAS_IPolyMaterial * mat)
-{
- BucketList::iterator bit;
- list<RAS_MeshSlot>::iterator mit;
-
- for (bit = m_SolidBuckets.begin(); bit != m_SolidBuckets.end(); ++bit) {
- if (mat == NULL || (mat == (*bit)->GetPolyMaterial())) {
- (*bit)->GetPolyMaterial()->ReleaseMaterial();
- }
- }
-
- for (bit = m_AlphaBuckets.begin(); bit != m_AlphaBuckets.end(); ++bit) {
- if (mat == NULL || (mat == (*bit)->GetPolyMaterial())) {
- (*bit)->GetPolyMaterial()->ReleaseMaterial();
- }
- }
-}
-
-/* frees the bucket, only used when freeing scenes */
-void RAS_BucketManager::RemoveMaterial(RAS_IPolyMaterial * mat)
-{
- BucketList::iterator bit, bitp;
- list<RAS_MeshSlot>::iterator mit;
- int i;
-
-
- for (i=0; i<m_SolidBuckets.size(); i++) {
- RAS_MaterialBucket *bucket = m_SolidBuckets[i];
- if (mat == bucket->GetPolyMaterial()) {
- m_SolidBuckets.erase(m_SolidBuckets.begin()+i);
- delete bucket;
- i--;
- }
- }
-
- for (int i=0; i<m_AlphaBuckets.size(); i++) {
- RAS_MaterialBucket *bucket = m_AlphaBuckets[i];
- if (mat == bucket->GetPolyMaterial()) {
- m_AlphaBuckets.erase(m_AlphaBuckets.begin()+i);
- delete bucket;
- i--;
- }
- }
-}
-
-//#include <stdio.h>
-
-void RAS_BucketManager::MergeBucketManager(RAS_BucketManager *other, SCA_IScene *scene)
-{
- /* concatenate lists */
- // printf("BEFORE %d %d\n", GetSolidBuckets().size(), GetAlphaBuckets().size());
-
- GetSolidBuckets().insert( GetSolidBuckets().end(), other->GetSolidBuckets().begin(), other->GetSolidBuckets().end() );
- other->GetSolidBuckets().clear();
-
- GetAlphaBuckets().insert( GetAlphaBuckets().end(), other->GetAlphaBuckets().begin(), other->GetAlphaBuckets().end() );
- other->GetAlphaBuckets().clear();
- //printf("AFTER %d %d\n", GetSolidBuckets().size(), GetAlphaBuckets().size());
-}
-
diff --git a/source/gameengine/Rasterizer/RAS_BucketManager.h b/source/gameengine/Rasterizer/RAS_BucketManager.h
deleted file mode 100644
index 5ed212ebee0..00000000000
--- a/source/gameengine/Rasterizer/RAS_BucketManager.h
+++ /dev/null
@@ -1,93 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file RAS_BucketManager.h
- * \ingroup bgerast
- */
-
-#ifndef __RAS_BUCKETMANAGER_H__
-#define __RAS_BUCKETMANAGER_H__
-
-#include "MT_Transform.h"
-#include "RAS_MaterialBucket.h"
-
-#include <vector>
-
-class RAS_BucketManager
-{
-public:
- typedef std::vector<class RAS_MaterialBucket*> BucketList;
-private:
- BucketList m_SolidBuckets;
- BucketList m_AlphaBuckets;
-
- struct sortedmeshslot;
- struct backtofront;
- struct fronttoback;
-
-public:
- RAS_BucketManager();
- virtual ~RAS_BucketManager();
-
- void Renderbuckets(const MT_Transform & cameratrans, RAS_IRasterizer* rasty);
-
- RAS_MaterialBucket* FindBucket(RAS_IPolyMaterial *material, bool &bucketCreated);
- void OptimizeBuckets(MT_Scalar distance);
-
- void ReleaseDisplayLists(RAS_IPolyMaterial *material = NULL);
- void ReleaseMaterials(RAS_IPolyMaterial *material = NULL);
-
- void RemoveMaterial(RAS_IPolyMaterial *mat); // freeing scenes only
-
- /* for merging */
- void MergeBucketManager(RAS_BucketManager *other, SCA_IScene *scene);
- BucketList & GetSolidBuckets() {return m_SolidBuckets;}
- BucketList & GetAlphaBuckets() {return m_AlphaBuckets;}
-
- /*void PrintStats(int verbose_level) {
- printf("\nMappings...\n");
- printf("\t m_SolidBuckets: %d\n", m_SolidBuckets.size());
- printf("\t\t m_SolidBuckets: %d\n", m_SolidBuckets.size());
- printf("\t m_AlphaBuckets: %d\n", m_AlphaBuckets.size());
- }*/
-
-
-private:
- void OrderBuckets(const MT_Transform& cameratrans, BucketList& buckets, vector<sortedmeshslot>& slots, bool alpha);
-
- void RenderSolidBuckets(const MT_Transform& cameratrans,
- RAS_IRasterizer* rasty);
- void RenderAlphaBuckets(const MT_Transform& cameratrans,
- RAS_IRasterizer* rasty);
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:RAS_BucketManager")
-#endif
-};
-
-#endif /* __RAS_BUCKETMANAGER_H__ */
diff --git a/source/gameengine/Rasterizer/RAS_CameraData.h b/source/gameengine/Rasterizer/RAS_CameraData.h
deleted file mode 100644
index bc8433afd05..00000000000
--- a/source/gameengine/Rasterizer/RAS_CameraData.h
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file RAS_CameraData.h
- * \ingroup bgerast
- */
-
-#ifndef __RAS_CAMERADATA_H__
-#define __RAS_CAMERADATA_H__
-
-struct RAS_CameraData
-{
- float m_lens;
- float m_scale;
- float m_sensor_x;
- float m_sensor_y;
- short m_sensor_fit;
- float m_shift_x;
- float m_shift_y;
- float m_clipstart;
- float m_clipend;
- bool m_perspective;
- bool m_viewport;
- int m_viewportleft;
- int m_viewportbottom;
- int m_viewportright;
- int m_viewporttop;
- float m_focallength;
-
- RAS_CameraData(float lens = 35.0f, float scale = 6.0f, float sensor_x = 32.0f, float sensor_y = 18.0f, short sensor_fit = 0,
- float shift_x = 0.0f, float shift_y = 0.0f,
- float clipstart = 0.1f, float clipend = 5000.0f, bool perspective = true,
- float focallength = 3.0f, bool viewport = false, int viewportleft = 0, int viewportbottom = 0,
- int viewportright = 0, int viewporttop = 0) :
- m_lens(lens),
- m_scale(scale),
- m_sensor_x(sensor_x),
- m_sensor_y(sensor_y),
- m_sensor_fit(sensor_fit),
- m_shift_x(shift_x),
- m_shift_y(shift_y),
- m_clipstart(clipstart),
- m_clipend(clipend),
- m_perspective(perspective),
- m_viewport(viewport),
- m_viewportleft(viewportleft),
- m_viewportbottom(viewportbottom),
- m_viewportright(viewportright),
- m_viewporttop(viewporttop),
- m_focallength(focallength)
- {
- }
-};
-
-#endif /* __RAS_CAMERADATA_H__ */
diff --git a/source/gameengine/Rasterizer/RAS_Deformer.h b/source/gameengine/Rasterizer/RAS_Deformer.h
deleted file mode 100644
index 058f2304f3d..00000000000
--- a/source/gameengine/Rasterizer/RAS_Deformer.h
+++ /dev/null
@@ -1,103 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file RAS_Deformer.h
- * \ingroup bgerast
- */
-
-#ifndef __RAS_DEFORMER_H__
-#define __RAS_DEFORMER_H__
-
-#ifdef _MSC_VER
-# pragma warning (disable:4786) /* get rid of stupid stl-visual compiler debug warning */
-#endif
-
-#include <stdlib.h>
-#include "CTR_Map.h"
-
-#ifdef WITH_CXX_GUARDEDALLOC
-#include "MEM_guardedalloc.h"
-#endif
-
-struct DerivedMesh;
-class RAS_MeshObject;
-
-class RAS_Deformer
-{
-public:
- RAS_Deformer() : m_pMesh(NULL), m_bDynamic(false) {}
- virtual ~RAS_Deformer() {}
- virtual void Relink(CTR_Map<class CTR_HashedPtr, void*>*map)=0;
- virtual bool Apply(class RAS_IPolyMaterial *polymat)=0;
- virtual bool Update(void)=0;
- virtual bool UpdateBuckets(void)=0;
- virtual RAS_Deformer *GetReplica()=0;
- virtual void ProcessReplica()=0;
- virtual bool SkipVertexTransform()
- {
- return false;
- }
- virtual bool ShareVertexArray()
- {
- return true;
- }
- virtual bool UseVertexArray()
- {
- return true;
- }
- // true when deformer produces varying vertex (shape or armature)
- bool IsDynamic()
- {
- return m_bDynamic;
- }
- virtual struct DerivedMesh* GetFinalMesh()
- {
- return NULL;
- }
- virtual struct DerivedMesh* GetPhysicsMesh()
- {
- return NULL;
- }
- virtual class RAS_MeshObject* GetRasMesh()
- {
- /* m_pMesh does not seem to be being used?? */
- return NULL;
- }
- virtual float (* GetTransVerts(int *tot))[3] { *tot= 0; return NULL; }
-
-protected:
- class RAS_MeshObject *m_pMesh;
- bool m_bDynamic;
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:RAS_Deformer")
-#endif
-};
-
-#endif
-
diff --git a/source/gameengine/Rasterizer/RAS_FramingManager.cpp b/source/gameengine/Rasterizer/RAS_FramingManager.cpp
deleted file mode 100644
index 8b0ec22fde3..00000000000
--- a/source/gameengine/Rasterizer/RAS_FramingManager.cpp
+++ /dev/null
@@ -1,425 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Rasterizer/RAS_FramingManager.cpp
- * \ingroup bgerast
- */
-
-
-#include "RAS_FramingManager.h"
-#include "RAS_Rect.h"
-
- void
-RAS_FramingManager::
-ComputeDefaultFrustum(
- const float camnear,
- const float camfar,
- const float lens,
- const float sensor_x, const float sensor_y,
- const short sensor_fit,
- const float shift_x,
- const float shift_y,
- const float design_aspect_ratio,
- RAS_FrameFrustum & frustum
-) {
- float size;
- float halfSize;
- float sizeX;
- float sizeY;
- float offsetX;
- float offsetY;
-
- if (sensor_fit==RAS_SENSORFIT_AUTO) {
- size = sensor_x * camnear / lens;
- halfSize = size * 0.5f;
-
- if (design_aspect_ratio > 1.f) {
- // halfsize defines the width
- sizeX = halfSize;
- sizeY = halfSize/design_aspect_ratio;
- } else {
- // halfsize defines the height
- sizeX = halfSize * design_aspect_ratio;
- sizeY = halfSize;
- }
- }
- else if (sensor_fit==RAS_SENSORFIT_HOR) {
- size = sensor_x * camnear / lens;
- halfSize = size * 0.5f;
- sizeX = halfSize;
- sizeY = halfSize/design_aspect_ratio;
- }
- else {
- size = sensor_y * camnear / lens;
- halfSize = size * 0.5f;
- sizeX = halfSize * design_aspect_ratio;
- sizeY = halfSize;
- }
-
- offsetX = size * shift_x;
- offsetY = size * shift_y;
-
- frustum.x2 = sizeX + offsetX;
- frustum.x1 = -sizeX + offsetX;
- frustum.y2 = sizeY + offsetY;
- frustum.y1 = -sizeY + offsetY;
- frustum.camnear = camnear;
- frustum.camfar = camfar;
-}
-
- void
-RAS_FramingManager::
-ComputeDefaultOrtho(
- const float camnear,
- const float camfar,
- const float scale,
- const float design_aspect_ratio,
- const short sensor_fit,
- const float shift_x,
- const float shift_y,
- RAS_FrameFrustum & frustum
-)
-{
- float halfSize = scale*0.5f;
- float sizeX;
- float sizeY;
- float offsetX;
- float offsetY;
-
- if (sensor_fit==RAS_SENSORFIT_AUTO) {
- if (design_aspect_ratio > 1.f) {
- // halfsize defines the width
- sizeX = halfSize;
- sizeY = halfSize/design_aspect_ratio;
- } else {
- // halfsize defines the height
- sizeX = halfSize * design_aspect_ratio;
- sizeY = halfSize;
- }
- }
- else if (sensor_fit==RAS_SENSORFIT_HOR) {
- sizeX = halfSize;
- sizeY = halfSize/design_aspect_ratio;
- }
- else {
- sizeX = halfSize * design_aspect_ratio;
- sizeY = halfSize;
- }
-
- offsetX = scale * shift_x;
- offsetY = scale * shift_y;
-
- frustum.x2 = sizeX + offsetX;
- frustum.x1 = -sizeX + offsetX;
- frustum.y2 = sizeY + offsetY;
- frustum.y1 = -sizeY + offsetY;
- frustum.camnear = camnear;
- frustum.camfar = camfar;
-}
-
-
- void
-RAS_FramingManager::
-ComputeBestFitViewRect(
- const RAS_Rect &availableViewport,
- const float design_aspect_ratio,
- RAS_Rect &viewport
-) {
- // try and honour the aspect ratio when setting the
- // drawable area. If we don't do this we are liable
- // to get a lot of distortion in the rendered image.
-
- int width = availableViewport.GetWidth();
- int height = availableViewport.GetHeight();
- float window_aspect = float(width)/float(height);
-
- if (window_aspect < design_aspect_ratio) {
- int v_height = (int)(width / design_aspect_ratio);
- int left_over = (height - v_height) / 2;
-
- viewport.SetLeft(availableViewport.GetLeft());
- viewport.SetBottom(availableViewport.GetBottom() + left_over);
- viewport.SetRight(availableViewport.GetLeft() + width);
- viewport.SetTop(availableViewport.GetBottom() + left_over + v_height);
-
- } else {
- int v_width = (int)(height * design_aspect_ratio);
- int left_over = (width - v_width) / 2;
-
- viewport.SetLeft(availableViewport.GetLeft() + left_over);
- viewport.SetBottom(availableViewport.GetBottom());
- viewport.SetRight(availableViewport.GetLeft() + v_width + left_over);
- viewport.SetTop(availableViewport.GetBottom() + height);
- }
-}
-
- void
-RAS_FramingManager::
-ComputeViewport(
- const RAS_FrameSettings &settings,
- const RAS_Rect &availableViewport,
- RAS_Rect &viewport
-) {
-
- RAS_FrameSettings::RAS_FrameType type = settings.FrameType();
- const int winx = availableViewport.GetWidth();
- const int winy = availableViewport.GetHeight();
-
- const float design_width = float(settings.DesignAspectWidth());
- const float design_height = float(settings.DesignAspectHeight());
-
- float design_aspect_ratio = float(1);
-
- if (design_height == float(0)) {
- // well this is ill defined
- // lets just scale the thing
-
- type = RAS_FrameSettings::e_frame_scale;
- } else {
- design_aspect_ratio = design_width/design_height;
- }
-
- switch (type) {
-
- case RAS_FrameSettings::e_frame_scale :
- case RAS_FrameSettings::e_frame_extend:
- {
- viewport.SetLeft(availableViewport.GetLeft());
- viewport.SetBottom(availableViewport.GetBottom());
- viewport.SetRight(availableViewport.GetLeft() + int(winx));
- viewport.SetTop(availableViewport.GetBottom() + int(winy));
-
- break;
- }
-
- case RAS_FrameSettings::e_frame_bars:
- {
- ComputeBestFitViewRect(
- availableViewport,
- design_aspect_ratio,
- viewport
- );
-
- break;
- }
- default :
- break;
- }
-}
-
- void
-RAS_FramingManager::
-ComputeFrustum(
- const RAS_FrameSettings &settings,
- const RAS_Rect &availableViewport,
- const RAS_Rect &viewport,
- const float lens,
- const float sensor_x, const float sensor_y, const short sensor_fit,
- const float shift_x,
- const float shift_y,
- const float camnear,
- const float camfar,
- RAS_FrameFrustum &frustum
-) {
-
- RAS_FrameSettings::RAS_FrameType type = settings.FrameType();
-
- const float design_width = float(settings.DesignAspectWidth());
- const float design_height = float(settings.DesignAspectHeight());
-
- float design_aspect_ratio = float(1);
-
- if (design_height == float(0)) {
- // well this is ill defined
- // lets just scale the thing
-
- type = RAS_FrameSettings::e_frame_scale;
- } else {
- design_aspect_ratio = design_width/design_height;
- }
-
- ComputeDefaultFrustum(
- camnear,
- camfar,
- lens,
- sensor_x,
- sensor_y,
- sensor_fit,
- shift_x,
- shift_y,
- design_aspect_ratio,
- frustum
- );
-
- switch (type) {
-
- case RAS_FrameSettings::e_frame_extend:
- {
- float x_scale, y_scale;
- switch (sensor_fit) {
- case RAS_SENSORFIT_HOR:
- {
- x_scale = 1.0f;
- y_scale = float(viewport.GetHeight()) / float(viewport.GetWidth());
- break;
- }
- case RAS_SENSORFIT_VERT:
- {
- x_scale = float(viewport.GetWidth()) / float(viewport.GetHeight());
- y_scale = 1.0f;
- break;
- }
- case RAS_SENSORFIT_AUTO:
- default:
- {
- RAS_Rect vt;
- ComputeBestFitViewRect(
- availableViewport,
- design_aspect_ratio,
- vt
- );
-
- // now scale the calculated frustum by the difference
- // between vt and the viewport in each axis.
- // These are always > 1
-
- x_scale = float(viewport.GetWidth())/float(vt.GetWidth());
- y_scale = float(viewport.GetHeight())/float(vt.GetHeight());
- break;
- }
- }
-
- frustum.x1 *= x_scale;
- frustum.x2 *= x_scale;
- frustum.y1 *= y_scale;
- frustum.y2 *= y_scale;
-
- break;
- }
- case RAS_FrameSettings::e_frame_scale :
- case RAS_FrameSettings::e_frame_bars:
- default :
- break;
- }
-}
-
- void
-RAS_FramingManager::
- ComputeOrtho(
- const RAS_FrameSettings &settings,
- const RAS_Rect &availableViewport,
- const RAS_Rect &viewport,
- const float scale,
- const float camnear,
- const float camfar,
- const short sensor_fit,
- const float shift_x,
- const float shift_y,
- RAS_FrameFrustum &frustum
- )
-{
- RAS_FrameSettings::RAS_FrameType type = settings.FrameType();
-
- const float design_width = float(settings.DesignAspectWidth());
- const float design_height = float(settings.DesignAspectHeight());
-
- float design_aspect_ratio = float(1);
-
- if (design_height == float(0)) {
- // well this is ill defined
- // lets just scale the thing
- type = RAS_FrameSettings::e_frame_scale;
- } else {
- design_aspect_ratio = design_width/design_height;
- }
-
-
- ComputeDefaultOrtho(
- camnear,
- camfar,
- scale,
- design_aspect_ratio,
- sensor_fit,
- shift_x,
- shift_y,
- frustum
- );
-
- switch (type) {
-
- case RAS_FrameSettings::e_frame_extend:
- {
- float x_scale, y_scale;
- switch (sensor_fit) {
- case RAS_SENSORFIT_HOR:
- {
- x_scale = 1.0f;
- y_scale = float(viewport.GetHeight()) / float(viewport.GetWidth());
- break;
- }
- case RAS_SENSORFIT_VERT:
- {
- x_scale = float(viewport.GetWidth()) / float(viewport.GetHeight());
- y_scale = 1.0f;
- break;
- }
- case RAS_SENSORFIT_AUTO:
- default:
- {
- RAS_Rect vt;
- ComputeBestFitViewRect(
- availableViewport,
- design_aspect_ratio,
- vt
- );
-
- // now scale the calculated frustum by the difference
- // between vt and the viewport in each axis.
- // These are always > 1
-
- x_scale = float(viewport.GetWidth())/float(vt.GetWidth());
- y_scale = float(viewport.GetHeight())/float(vt.GetHeight());
- break;
- }
- }
-
- frustum.x1 *= x_scale;
- frustum.x2 *= x_scale;
- frustum.y1 *= y_scale;
- frustum.y2 *= y_scale;
-
- break;
- }
- case RAS_FrameSettings::e_frame_scale :
- case RAS_FrameSettings::e_frame_bars:
- default :
- break;
- }
-
-}
-
-
diff --git a/source/gameengine/Rasterizer/RAS_FramingManager.h b/source/gameengine/Rasterizer/RAS_FramingManager.h
deleted file mode 100644
index cb86a7a4484..00000000000
--- a/source/gameengine/Rasterizer/RAS_FramingManager.h
+++ /dev/null
@@ -1,316 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file RAS_FramingManager.h
- * \ingroup bgerast
- */
-
-#ifndef __RAS_FRAMINGMANAGER_H__
-#define __RAS_FRAMINGMANAGER_H__
-
-#ifdef WITH_CXX_GUARDEDALLOC
-#include "MEM_guardedalloc.h"
-#endif
-
-class RAS_Rect;
-
-/**
- * \section RAS_FrameSettings
- * This is a value type describing the framing used
- * by a particular scene in the game engine.
- * Each KX_Scene contains a RAS_FrameSetting describing
- * how the frustum and viewport are to be modified
- * depending on the canvas size.
- *
- * e_frame_scale means that the viewport is set to the current
- * canvas size. If the view frustum aspect ratio is different
- * to the canvas aspect this will lead to stretching.
- *
- * e_frame_extend means that the best fit viewport will be
- * computed based upon the design aspect ratio
- * and the view frustum will be adjusted so that
- * more of the scene is visible.
- *
- * e_frame_bars means that the best fit viewport will be
- * be computed based upon the design aspect ratio.
- */
-
-class RAS_FrameSettings
-{
-public :
- /**
- * enum defining the policy to use
- * in each axis.
- */
- enum RAS_FrameType {
- e_frame_scale,
- e_frame_extend,
- e_frame_bars
- };
-
- /**
- * Constructor
- */
-
- RAS_FrameSettings(
- RAS_FrameType frame_type,
- float bar_r,
- float bar_g,
- float bar_b,
- unsigned int design_aspect_width,
- unsigned int design_aspect_height
- ):
- m_frame_type(frame_type),
- m_bar_r(bar_r),
- m_bar_g(bar_g),
- m_bar_b(bar_b),
- m_design_aspect_width(design_aspect_width),
- m_design_aspect_height(design_aspect_height)
- {
- };
-
- RAS_FrameSettings(
- ):
- m_frame_type(e_frame_scale),
- m_bar_r(0),
- m_bar_g(0),
- m_bar_b(0),
- m_design_aspect_width(1),
- m_design_aspect_height(1)
- {
- };
-
- /**
- * Accessors
- */
-
- const
- RAS_FrameType &
- FrameType(
- ) const {
- return m_frame_type;
- };
-
- void
- SetFrameType(
- RAS_FrameType type
- ) {
- m_frame_type = type;
- };
-
- float
- BarRed(
- ) const {
- return m_bar_r;
- };
-
- float
- BarGreen(
- ) const {
- return m_bar_g;
- };
-
- float
- BarBlue(
- ) const {
- return m_bar_b;
- };
-
- unsigned int
- DesignAspectWidth(
- ) const {
- return m_design_aspect_width;
- };
-
- unsigned int
- DesignAspectHeight(
- ) const {
- return m_design_aspect_height;
- };
-
-private :
-
- RAS_FrameType m_frame_type;
- float m_bar_r;
- float m_bar_g;
- float m_bar_b;
- unsigned int m_design_aspect_width;
- unsigned int m_design_aspect_height;
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:RAS_FrameSettings")
-#endif
-};
-
-struct RAS_FrameFrustum
-{
- float camnear,camfar;
- float x1,y1;
- float x2,y2;
-};
-
-/* must match R_CULLING_... from DNA_scene_types.h */
-enum RAS_CullingMode
-{
- RAS_CULLING_DBVT = 0,
- RAS_CULLING_NORMAL,
- RAS_CULLING_NONE
-};
-
-/* Should match CAMERA_SENSOR_FIT... from DNA_camera_types.h */
-enum RAS_SensorFit
-{
- RAS_SENSORFIT_AUTO = 0,
- RAS_SENSORFIT_HOR,
- RAS_SENSORFIT_VERT
-};
-
-/**
- * \section RAS_FramingManager
- * This class helps to compute a view frustum
- * and a viewport rectangle given the
- * above settings and a description of the
- * current canvas dimensions.
- *
- * You do not have to instantiate this class
- * directly, it only contains static helper functions
- */
-
-class RAS_FramingManager
-{
-public :
-
- /**
- * Compute a viewport given
- * a RAS_FrameSettings and a description of the
- * canvas.
- */
-
- static
- void
- ComputeViewport(
- const RAS_FrameSettings &settings,
- const RAS_Rect &availableViewport,
- RAS_Rect &viewport
- );
-
-
- /**
- * compute a frustum given a valid viewport,
- * RAS_FrameSettings, canvas description
- * and camera description
- */
-
- static
- void
- ComputeOrtho(
- const RAS_FrameSettings &settings,
- const RAS_Rect &availableViewport,
- const RAS_Rect &viewport,
- const float scale,
- const float camnear,
- const float camfar,
- const short sensor_fit,
- const float shift_x,
- const float shift_y,
- RAS_FrameFrustum &frustum
- );
-
- static
- void
- ComputeFrustum(
- const RAS_FrameSettings &settings,
- const RAS_Rect &availableViewport,
- const RAS_Rect &viewport,
- const float lens,
- const float sensor_x, const float sensor_y, const short sensor_fit,
- const float shift_x,
- const float shift_y,
- const float camnear,
- const float camfar,
- RAS_FrameFrustum &frustum
- );
-
- static
- void
- ComputeDefaultFrustum(
- const float camnear,
- const float camfar,
- const float lens,
- const float sensor_x, const float sensor_y,
- const short sensor_fit,
- const float shift_x,
- const float shift_y,
- const float design_aspect_ratio,
- RAS_FrameFrustum & frustum
- );
-
- static
- void
- ComputeDefaultOrtho(
- const float camnear,
- const float camfar,
- const float scale,
- const float design_aspect_ratio,
- const short sensor_fit,
- const float shift_x,
- const float shift_y,
- RAS_FrameFrustum & frustum
- );
-
-private :
-
- static
- void
- ComputeBestFitViewRect(
- const RAS_Rect &availableViewport,
- const float design_aspect_ratio,
- RAS_Rect &viewport
- );
-
-
-
- /**
- * Private constructor - this class is not meant
- * for instantiation.
- */
-
- RAS_FramingManager(
- );
-
- RAS_FramingManager(
- const RAS_FramingManager &
- );
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:RAS_FramingManager")
-#endif
-};
-
-#endif
diff --git a/source/gameengine/Rasterizer/RAS_ICanvas.cpp b/source/gameengine/Rasterizer/RAS_ICanvas.cpp
deleted file mode 100644
index 808d257f8f0..00000000000
--- a/source/gameengine/Rasterizer/RAS_ICanvas.cpp
+++ /dev/null
@@ -1,128 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Rasterizer/RAS_ICanvas.cpp
- * \ingroup bgerast
- */
-
-#include "RAS_ICanvas.h"
-#include "DNA_scene_types.h"
-
-#include "BKE_image.h"
-#include "BKE_global.h"
-#include "BKE_main.h"
-
-#include "BLI_task.h"
-#include "BLI_path_util.h"
-#include "BLI_string.h"
-
-#include "MEM_guardedalloc.h"
-
-extern "C" {
-#include "IMB_imbuf.h"
-#include "IMB_imbuf_types.h"
-}
-
-
-// Task data for saving screenshots in a different thread.
-struct ScreenshotTaskData
-{
- unsigned int *dumprect;
- int dumpsx;
- int dumpsy;
- char *path;
- ImageFormatData *im_format;
-};
-
-/**
- * Function that actually performs the image compression and saving to disk of a screenshot.
- * Run in a separate thread by RAS_ICanvas::save_screenshot().
- *
- * @param taskdata Must point to a ScreenshotTaskData object. This function takes ownership
- * of all pointers in the ScreenshotTaskData, and frees them.
- */
-void save_screenshot_thread_func(TaskPool *__restrict pool, void *taskdata, int threadid);
-
-
-RAS_ICanvas::RAS_ICanvas()
-{
- m_taskscheduler = BLI_task_scheduler_create(TASK_SCHEDULER_AUTO_THREADS);
- m_taskpool = BLI_task_pool_create(m_taskscheduler, NULL);
-}
-
-RAS_ICanvas::~RAS_ICanvas()
-{
- if (m_taskpool) {
- BLI_task_pool_work_and_wait(m_taskpool);
- BLI_task_pool_free(m_taskpool);
- m_taskpool = NULL;
- }
-
- if (m_taskscheduler) {
- BLI_task_scheduler_free(m_taskscheduler);
- m_taskscheduler = NULL;
- }
-}
-
-
-void save_screenshot_thread_func(TaskPool *__restrict UNUSED(pool), void *taskdata, int UNUSED(threadid))
-{
- ScreenshotTaskData *task = static_cast<ScreenshotTaskData *>(taskdata);
-
- /* create and save imbuf */
- ImBuf *ibuf = IMB_allocImBuf(task->dumpsx, task->dumpsy, 24, 0);
- ibuf->rect = task->dumprect;
-
- BKE_imbuf_write_as(ibuf, task->path, task->im_format, false);
-
- ibuf->rect = NULL;
- IMB_freeImBuf(ibuf);
- MEM_freeN(task->dumprect);
- MEM_freeN(task->path);
- MEM_freeN(task->im_format);
-}
-
-
-void RAS_ICanvas::save_screenshot(const char *filename, int dumpsx, int dumpsy, unsigned int *dumprect,
- ImageFormatData * im_format)
-{
- /* create file path */
- char *path = (char *)MEM_mallocN(FILE_MAX, "screenshot-path");
- BLI_strncpy(path, filename, FILE_MAX);
- BLI_path_abs(path, G.main->name);
- BLI_path_frame(path, m_frame, 0);
- m_frame++;
- BKE_image_path_ensure_ext_from_imtype(path, im_format->imtype);
-
- /* Save the actual file in a different thread, so that the
- * game engine can keep running at full speed. */
- ScreenshotTaskData *task = (ScreenshotTaskData *)MEM_mallocN(sizeof(ScreenshotTaskData), "screenshot-data");
- task->dumprect = dumprect;
- task->dumpsx = dumpsx;
- task->dumpsy = dumpsy;
- task->path = path;
- task->im_format = im_format;
-
- BLI_task_pool_push(m_taskpool,
- save_screenshot_thread_func,
- task,
- true, // free task data
- TASK_PRIORITY_LOW);
-}
diff --git a/source/gameengine/Rasterizer/RAS_ICanvas.h b/source/gameengine/Rasterizer/RAS_ICanvas.h
deleted file mode 100644
index 91cc13c8f85..00000000000
--- a/source/gameengine/Rasterizer/RAS_ICanvas.h
+++ /dev/null
@@ -1,287 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file RAS_ICanvas.h
- * \ingroup bgerast
- */
-
-#ifndef __RAS_ICANVAS_H__
-#define __RAS_ICANVAS_H__
-
-#ifdef WITH_CXX_GUARDEDALLOC
-#include "MEM_guardedalloc.h"
-#endif
-
-class RAS_Rect;
-struct TaskScheduler;
-struct TaskPool;
-struct ImageFormatData;
-
-/**
- * 2D rendering device context. The connection from 3d rendercontext to 2d surface.
- */
-class RAS_ICanvas
-{
-public:
- enum BufferType {
- COLOR_BUFFER=1,
- DEPTH_BUFFER=2
- };
-
- enum RAS_MouseState
- {
- MOUSE_INVISIBLE=1,
- MOUSE_WAIT,
- MOUSE_NORMAL
- };
-
- RAS_ICanvas();
- virtual ~RAS_ICanvas();
-
- virtual
- void
- Init(
- ) = 0;
-
- virtual
- void
- BeginFrame(
- )=0;
-
- virtual
- void
- EndFrame(
- )=0;
-
- /**
- * Initializes the canvas for drawing. Drawing to the canvas is
- * only allowed between BeginDraw() and EndDraw().
- *
- * \retval false Acquiring the canvas failed.
- * \retval true Acquiring the canvas succeeded.
- *
- */
-
- virtual
- bool
- BeginDraw(
- )=0;
-
- /**
- * Unitializes the canvas for drawing.
- */
-
- virtual
- void
- EndDraw(
- )=0;
-
-
- /// probably needs some arguments for PS2 in future
- virtual
- void
- SwapBuffers(
- )=0;
-
- virtual
- void
- SetSwapInterval(
- int interval
- )=0;
-
- virtual
- bool
- GetSwapInterval(
- int& intervalOut
- )=0;
-
- virtual
- void
- ClearBuffer(
- int type
- )=0;
-
- virtual
- void
- ClearColor(
- float r,
- float g,
- float b,
- float a
- )=0;
-
- virtual
- int
- GetWidth(
- ) const = 0;
-
- virtual
- int
- GetHeight(
- ) const = 0;
-
- virtual
- int
- GetMouseX(int x
- )=0;
-
- virtual
- int
- GetMouseY(int y
- )= 0;
-
- virtual
- float
- GetMouseNormalizedX(int x
- )=0;
-
- virtual
- float
- GetMouseNormalizedY(int y
- )= 0;
-
- virtual
- const RAS_Rect &
- GetDisplayArea(
- ) const = 0;
-
- virtual
- void
- SetDisplayArea(RAS_Rect *rect
- ) = 0;
-
- /**
- * Used to get canvas area within blender.
- */
- virtual
- RAS_Rect &
- GetWindowArea(
- ) = 0;
-
- /**
- * Set the visible view-port
- */
-
- virtual
- void
- SetViewPort(
- int x1, int y1,
- int x2, int y2
- ) = 0;
-
- /**
- * Update the Canvas' viewport (used when the viewport changes without using SetViewPort()
- * eg: Shadow buffers and FBOs
- */
-
- virtual
- void
- UpdateViewPort(
- int x1, int y1,
- int x2, int y2
- ) = 0;
-
- /**
- * Get the visible viewport
- */
- virtual
- const int*
- GetViewPort() = 0;
-
- virtual
- void
- SetMouseState(
- RAS_MouseState mousestate
- )=0;
-
- virtual
- void
- SetMousePosition(
- int x,
- int y
- )=0;
-
- virtual
- RAS_MouseState
- GetMouseState()
- {
- return m_mousestate;
- }
-
- virtual
- void
- MakeScreenShot(
- const char* filename
- )=0;
-
- virtual void GetDisplayDimensions(int &width, int &height) = 0;
-
- virtual
- void
- ResizeWindow(
- int width,
- int height
- )=0;
-
- virtual
- void
- SetFullScreen(
- bool enable
- )=0;
-
- virtual
- bool
- GetFullScreen()=0;
-
-
-
-protected:
- RAS_MouseState m_mousestate;
- int m_frame; /// frame number for screenshots.
- TaskScheduler *m_taskscheduler;
- TaskPool *m_taskpool;
-
- /**
- * Saves screenshot data to a file. The actual compression and disk I/O is performed in
- * a separate thread.
- *
- * @param filename name of the file, can contain "###" for sequential numbering. A copy of the string
- * is made, so the pointer can be freed by the caller.
- * @param dumpsx width in pixels.
- * @param dumpsy height in pixels.
- * @param dumprect pixel data; ownership is passed to this function, which also frees the data.
- * @param im_format image format for the file; ownership is passed to this function, which also frees the data.
- */
- void save_screenshot(const char *filename, int dumpsx, int dumpsy, unsigned int *dumprect,
- ImageFormatData * im_format);
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:RAS_ICanvas")
-#endif
-};
-
-#endif /* __RAS_ICANVAS_H__ */
diff --git a/source/gameengine/Rasterizer/RAS_ILightObject.h b/source/gameengine/Rasterizer/RAS_ILightObject.h
deleted file mode 100644
index a3d55c925d6..00000000000
--- a/source/gameengine/Rasterizer/RAS_ILightObject.h
+++ /dev/null
@@ -1,95 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): Mitchell Stokes
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file RAS_ILightObject.h
- * \ingroup bgerast
- */
-
-#ifndef __RAS_LIGHTOBJECT_H__
-#define __RAS_LIGHTOBJECT_H__
-
-class RAS_ICanvas;
-
-class KX_Camera;
-class KX_Scene;
-
-class MT_Transform;
-class MT_Matrix4x4;
-
-struct Image;
-
-class RAS_ILightObject
-{
-public:
- enum LightType {
- LIGHT_SPOT,
- LIGHT_SUN,
- LIGHT_NORMAL
- };
- bool m_modified;
- int m_layer;
- void *m_scene;
- void *m_light;
-
- float m_energy;
- float m_distance;
- float m_shadowclipstart;
- float m_shadowfrustumsize;
- float m_shadowclipend;
- float m_shadowbias;
- float m_shadowbleedbias;
- short m_shadowmaptype;
- float m_shadowcolor[3];
-
- float m_color[3];
-
- float m_att1;
- float m_att2;
- float m_coeff_const, m_coeff_lin, m_coeff_quad;
- float m_spotsize;
- float m_spotblend;
-
- LightType m_type;
-
- bool m_nodiffuse;
- bool m_nospecular;
- bool m_glsl;
-
- virtual ~RAS_ILightObject() {}
- virtual RAS_ILightObject* Clone() = 0;
-
- virtual bool HasShadowBuffer() = 0;
- virtual int GetShadowBindCode() = 0;
- virtual MT_Matrix4x4 GetShadowMatrix() = 0;
- virtual int GetShadowLayer() = 0;
- virtual void BindShadowBuffer(RAS_ICanvas *canvas, KX_Camera *cam, MT_Transform& camtrans) = 0;
- virtual void UnbindShadowBuffer() = 0;
- virtual Image *GetTextureImage(short texslot) = 0;
- virtual void Update() = 0;
-};
-
-#endif /* __RAS_LIGHTOBJECT_H__ */
diff --git a/source/gameengine/Rasterizer/RAS_IOffScreen.h b/source/gameengine/Rasterizer/RAS_IOffScreen.h
deleted file mode 100644
index d61a31504b8..00000000000
--- a/source/gameengine/Rasterizer/RAS_IOffScreen.h
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2015, Blender Foundation
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): Blender Foundation.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file RAS_IOffScreen.h
- * \ingroup bgerast
- */
-
-#ifndef __RAS_OFFSCREEN_H__
-#define __RAS_OFFSCREEN_H__
-
-#include "EXP_Python.h"
-
-class RAS_ICanvas;
-
-class MT_Transform;
-
-struct Image;
-
-class RAS_IOffScreen
-{
-public:
- enum RAS_OFS_BIND_MODE {
- RAS_OFS_BIND_RENDER = 0,
- RAS_OFS_BIND_READ,
- };
- enum RAS_OFS_RENDER_TARGET {
- RAS_OFS_RENDER_BUFFER = 0, // use render buffer as render target
- RAS_OFS_RENDER_TEXTURE, // use texture as render target
- };
-
- int m_width;
- int m_height;
- int m_samples;
- int m_color; // if used, holds the texture object, 0 if not used
-
- virtual ~RAS_IOffScreen() {}
-
- virtual bool Create(int width, int height, int samples, RAS_OFS_RENDER_TARGET target) = 0;
- virtual void Destroy() = 0;
- virtual void Bind(RAS_OFS_BIND_MODE mode) = 0;
- virtual void Blit() = 0;
- virtual void Unbind() = 0;
- virtual void MipMap() = 0;
-
- virtual int GetWidth() { return m_width; }
- virtual int GetHeight() { return m_height; }
- virtual int GetSamples() { return m_samples; }
- virtual int GetColor() { return m_color; }
-};
-
-#ifdef WITH_PYTHON
-typedef struct {
- PyObject_HEAD
- RAS_IOffScreen *ofs;
-} PyRASOffScreen;
-
-extern PyTypeObject PyRASOffScreen_Type;
-#endif
-
-#endif /* __RAS_OFFSCREEN_H__ */
diff --git a/source/gameengine/Rasterizer/RAS_IPolygonMaterial.cpp b/source/gameengine/Rasterizer/RAS_IPolygonMaterial.cpp
deleted file mode 100644
index 1d22d2debf9..00000000000
--- a/source/gameengine/Rasterizer/RAS_IPolygonMaterial.cpp
+++ /dev/null
@@ -1,292 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Rasterizer/RAS_IPolygonMaterial.cpp
- * \ingroup bgerast
- */
-
-
-#include "RAS_IPolygonMaterial.h"
-#include "RAS_IRasterizer.h"
-
-#include "DNA_material_types.h"
-
-void RAS_IPolyMaterial::Initialize(
- const STR_String& texname,
- const STR_String& matname,
- int materialindex,
- int tile,
- int tilexrep,
- int tileyrep,
- int alphablend,
- bool alpha,
- bool zsort,
- bool light,
- bool image,
- struct GameSettings* game)
-{
- m_texturename = texname;
- m_materialname = matname;
- m_materialindex = materialindex;
- m_tile = tile;
- m_tilexrep = tilexrep;
- m_tileyrep = tileyrep;
- m_alphablend = alphablend;
- m_alpha = alpha;
- m_zsort = zsort;
- m_light = light;
- m_polymatid = m_newpolymatid++;
- m_flag = 0;
- m_multimode = 0;
- m_shininess = 35.0f;
- m_specular.setValue(0.5f,0.5f,0.5f);
- m_specularity = 1.0f;
- m_diffuse.setValue(0.5f,0.5f,0.5f);
- m_drawingmode = ConvertFaceMode(game, image);
-}
-
-RAS_IPolyMaterial::RAS_IPolyMaterial()
- : m_texturename("__Dummy_Texture_Name__"),
- m_materialname("__Dummy_Material_Name__"),
- m_tile(0),
- m_tilexrep(0),
- m_tileyrep(0),
- m_drawingmode (0),
- m_alphablend(0),
- m_alpha(false),
- m_zsort(false),
- m_light(false),
- m_materialindex(0),
- m_polymatid(0),
- m_flag(0),
- m_multimode(0)
-{
- m_shininess = 35.0f;
- m_specular = MT_Vector3(0.5f,0.5f,0.5f);
- m_specularity = 1.0f;
- m_diffuse = MT_Vector3(0.5f,0.5f,0.5f);
-}
-
-RAS_IPolyMaterial::RAS_IPolyMaterial(const STR_String& texname,
- const STR_String& matname,
- int materialindex,
- int tile,
- int tilexrep,
- int tileyrep,
- int alphablend,
- bool alpha,
- bool zsort)
- : m_texturename(texname),
- m_materialname(matname),
- m_tile(tile),
- m_tilexrep(tilexrep),
- m_tileyrep(tileyrep),
- m_alphablend(alphablend),
- m_alpha(alpha),
- m_zsort(zsort),
- m_materialindex(materialindex),
- m_polymatid(m_newpolymatid++),
- m_flag(0),
- m_multimode(0)
-{
- m_shininess = 35.0f;
- m_specular = MT_Vector3(0.5f,0.5f,0.5f);
- m_specularity = 1.0f;
- m_diffuse = MT_Vector3(0.5f,0.5f,0.5f);
-}
-
-
-bool RAS_IPolyMaterial::Equals(const RAS_IPolyMaterial& lhs) const
-{
- if (m_flag &RAS_BLENDERMAT)
- {
- bool test = (
- this->m_multimode == lhs.m_multimode &&
- this->m_flag == lhs.m_flag &&
- this->m_drawingmode == lhs.m_drawingmode &&
- this->m_alphablend == lhs.m_alphablend &&
- this->m_texturename.hash() == lhs.m_texturename.hash() &&
- this->m_materialname.hash() == lhs.m_materialname.hash()
- );
-
- return test;
- }
- else
- {
- return (
- this->m_tile == lhs.m_tile &&
- this->m_tilexrep == lhs.m_tilexrep &&
- this->m_tileyrep == lhs.m_tileyrep &&
- this->m_alphablend == lhs.m_alphablend &&
- this->m_alpha == lhs.m_alpha &&
- this->m_zsort == lhs.m_zsort &&
- this->m_light == lhs.m_light &&
- this->m_drawingmode == lhs.m_drawingmode &&
- this->m_texturename.hash() == lhs.m_texturename.hash() &&
- this->m_materialname.hash() == lhs.m_materialname.hash()
- );
- }
-}
-
-int RAS_IPolyMaterial::ConvertFaceMode(struct GameSettings *game, bool image) const
-{
- if (!game) return (image?GEMAT_TEX:0);
-
- int modefinal = 0;
-
- int orimode = game->face_orientation;
- int alpha_blend = game->alpha_blend;
- int flags = game->flag & (GEMAT_TEXT | GEMAT_BACKCULL);
-
- modefinal = orimode | alpha_blend | flags;
- modefinal |= (image ? GEMAT_TEX : 0);
-
- return modefinal;
-}
-
-void RAS_IPolyMaterial::GetMaterialRGBAColor(unsigned char *rgba) const
-{
- *rgba++ = 0xFF;
- *rgba++ = 0xFF;
- *rgba++ = 0xFF;
- *rgba++ = 0xFF;
-}
-
-bool RAS_IPolyMaterial::Less(const RAS_IPolyMaterial& rhs) const
-{
- if (Equals(rhs))
- return false;
-
- return m_polymatid < rhs.m_polymatid;
-}
-
-bool RAS_IPolyMaterial::IsAlpha() const
-{
- return m_alpha || m_zsort;
-}
-
-bool RAS_IPolyMaterial::IsZSort() const
-{
- return m_zsort;
-}
-
-unsigned int RAS_IPolyMaterial::hash() const
-{
- return m_texturename.hash();
-}
-
-int RAS_IPolyMaterial::GetDrawingMode() const
-{
- return m_drawingmode;
-}
-
-const STR_String& RAS_IPolyMaterial::GetMaterialName() const
-{
- return m_materialname;
-}
-
-dword RAS_IPolyMaterial::GetMaterialNameHash() const
-{
- return m_materialname.hash();
-}
-
-const STR_String& RAS_IPolyMaterial::GetTextureName() const
-{
- return m_texturename;
-}
-
-int RAS_IPolyMaterial::GetMaterialIndex() const
-{
- return m_materialindex;
-}
-
-Material *RAS_IPolyMaterial::GetBlenderMaterial() const
-{
- return NULL;
-}
-
-Image *RAS_IPolyMaterial::GetBlenderImage() const
-{
- return NULL;
-}
-
-unsigned int *RAS_IPolyMaterial::GetMCol() const
-{
- return NULL;
-}
-
-Scene* RAS_IPolyMaterial::GetBlenderScene() const
-{
- return NULL;
-}
-
-void RAS_IPolyMaterial::ReleaseMaterial()
-{
-}
-
-unsigned int RAS_IPolyMaterial::GetFlag() const
-{
- return m_flag;
-}
-
-bool RAS_IPolyMaterial::UsesLighting(RAS_IRasterizer *rasty) const
-{
- bool dolights = false;
-
- if (m_flag & RAS_BLENDERMAT) {
- dolights = (m_flag & RAS_MULTILIGHT) != 0;
- }
- else if (rasty->GetDrawingMode() < RAS_IRasterizer::KX_SOLID) {
- /* pass */
- }
- else if (rasty->GetDrawingMode() == RAS_IRasterizer::KX_SHADOW) {
- /* pass */
- }
- else {
- dolights = m_light;
- }
-
- return dolights;
-}
-
-bool RAS_IPolyMaterial::CastsShadows() const
-{
- return (m_flag & RAS_CASTSHADOW) != 0;
-}
-
-bool RAS_IPolyMaterial::OnlyShadow() const
-{
- return (m_flag & RAS_ONLYSHADOW) != 0;
-}
-
-bool RAS_IPolyMaterial::UsesObjectColor() const
-{
- return !(m_flag & RAS_BLENDERGLSL);
-}
-
-unsigned int RAS_IPolyMaterial::m_newpolymatid = 0;
-
diff --git a/source/gameengine/Rasterizer/RAS_IPolygonMaterial.h b/source/gameengine/Rasterizer/RAS_IPolygonMaterial.h
deleted file mode 100644
index 7023d305510..00000000000
--- a/source/gameengine/Rasterizer/RAS_IPolygonMaterial.h
+++ /dev/null
@@ -1,206 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file RAS_IPolygonMaterial.h
- * \ingroup bgerast
- */
-
-#ifndef __RAS_IPOLYGONMATERIAL_H__
-#define __RAS_IPOLYGONMATERIAL_H__
-
-#include "STR_HashedString.h"
-
-#include "MT_Vector3.h"
-
-#ifdef WITH_CXX_GUARDEDALLOC
-#include "MEM_guardedalloc.h"
-#endif
-
-class RAS_IRasterizer;
-struct Material;
-struct Image;
-struct Scene;
-class SCA_IScene;
-struct GameSettings;
-
-enum MaterialProps
-{
- RAS_ZSORT =1,
- RAS_TRANSPARENT =2,
- RAS_TRIANGLE =4,
- RAS_MULTITEX =8,
- RAS_MULTILIGHT =16,
- RAS_BLENDERMAT =32,
- RAS_GLSHADER =64,
- RAS_AUTOGEN =128,
- RAS_NORMAL =256,
- RAS_DEFMULTI =512,
- RAS_BLENDERGLSL =1024,
- RAS_CASTSHADOW =2048,
- RAS_ONLYSHADOW =4096,
-};
-
-/**
- * Polygon Material on which the material buckets are sorted
- *
- */
-class RAS_IPolyMaterial
-{
- //todo: remove these variables from this interface/protocol class
-protected:
- STR_HashedString m_texturename;
- STR_HashedString m_materialname; //also needed for touchsensor
- int m_tile;
- int m_tilexrep,m_tileyrep;
- int m_drawingmode;
- int m_alphablend;
- bool m_alpha;
- bool m_zsort;
- bool m_light;
- int m_materialindex;
-
- unsigned int m_polymatid;
- static unsigned int m_newpolymatid;
-
- // will move...
- unsigned int m_flag;//MaterialProps
- int m_multimode; // sum of values
-public:
- MT_Vector3 m_diffuse;
- float m_shininess;
- MT_Vector3 m_specular;
- float m_specularity;
-
- /** Used to store caching information for materials. */
- typedef void* TCachingInfo;
-
- // care! these are taken from blender polygonflags, see file DNA_mesh_types.h for #define TF_BILLBOARD etc.
- enum MaterialFlags
- {
- BILLBOARD_SCREENALIGNED = 512, /* GEMAT_HALO */
- BILLBOARD_AXISALIGNED = 1024, /* GEMAT_BILLBOARD */
- SHADOW =2048 /* GEMAT_SHADOW */
- };
-
- RAS_IPolyMaterial();
- RAS_IPolyMaterial(const STR_String& texname,
- const STR_String& matname,
- int materialindex,
- int tile,
- int tilexrep,
- int tileyrep,
- int transp,
- bool alpha,
- bool zsort);
- void Initialize(const STR_String& texname,
- const STR_String& matname,
- int materialindex,
- int tile,
- int tilexrep,
- int tileyrep,
- int transp,
- bool alpha,
- bool zsort,
- bool light,
- bool image,
- struct GameSettings* game);
-
- virtual ~RAS_IPolyMaterial() {}
-
- /**
- * Returns the caching information for this material,
- * This can be used to speed up the rasterizing process.
- * \return The caching information.
- */
- virtual TCachingInfo GetCachingInfo(void) const { return 0; }
-
- /**
- * Activates the material in the rasterizer.
- * On entry, the cachingInfo contains info about the last activated material.
- * On exit, the cachingInfo should contain updated info about this material.
- * \param rasty The rasterizer in which the material should be active.
- * \param cachingInfo The information about the material used to speed up rasterizing.
- */
- virtual bool Activate(RAS_IRasterizer* rasty, TCachingInfo& cachingInfo) const
- {
- return false;
- }
- virtual void ActivateMeshSlot(const class RAS_MeshSlot & ms, RAS_IRasterizer* rasty) const {}
-
- virtual bool Equals(const RAS_IPolyMaterial& lhs) const;
- bool Less(const RAS_IPolyMaterial& rhs) const;
- //int GetLightLayer() const;
- bool IsAlpha() const;
- bool IsZSort() const;
- unsigned int hash() const;
- int GetDrawingMode() const;
- const STR_String& GetMaterialName() const;
- dword GetMaterialNameHash() const;
- const STR_String& GetTextureName() const;
- unsigned int GetFlag() const;
- int GetMaterialIndex() const;
-
- virtual Material* GetBlenderMaterial() const;
- virtual Image* GetBlenderImage() const;
- virtual unsigned int* GetMCol() const;
- virtual Scene* GetBlenderScene() const;
- virtual void ReleaseMaterial();
- virtual void GetMaterialRGBAColor(unsigned char *rgba) const;
- virtual bool UsesLighting(RAS_IRasterizer *rasty) const;
- virtual bool UsesObjectColor() const;
- virtual bool CastsShadows() const;
- virtual bool OnlyShadow() const;
-
- virtual void Replace_IScene(SCA_IScene *val) {} /* overridden by KX_BlenderMaterial */
-
- /**
- * \return the equivalent drawing mode for the material settings (equivalent to old TexFace tface->mode).
- */
- int ConvertFaceMode(struct GameSettings *game, bool image) const;
-
- /*
- * PreCalculate texture gen
- */
- virtual void OnConstruction() {}
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:RAS_IPolyMaterial")
-#endif
-};
-
-inline bool operator ==( const RAS_IPolyMaterial & rhs,const RAS_IPolyMaterial & lhs)
-{
- return ( rhs.Equals(lhs));
-}
-
-inline bool operator < ( const RAS_IPolyMaterial & lhs, const RAS_IPolyMaterial & rhs)
-{
- return lhs.Less(rhs);
-}
-
-#endif /* __RAS_IPOLYGONMATERIAL_H__ */
diff --git a/source/gameengine/Rasterizer/RAS_IRasterizer.h b/source/gameengine/Rasterizer/RAS_IRasterizer.h
deleted file mode 100644
index dc92408915b..00000000000
--- a/source/gameengine/Rasterizer/RAS_IRasterizer.h
+++ /dev/null
@@ -1,506 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file RAS_IRasterizer.h
- * \ingroup bgerast
- */
-
-#ifndef __RAS_IRASTERIZER_H__
-#define __RAS_IRASTERIZER_H__
-
-#ifdef _MSC_VER
-# pragma warning (disable:4786)
-#endif
-
-#include "STR_HashedString.h"
-
-#include "MT_CmMatrix4x4.h"
-#include "MT_Matrix4x4.h"
-
-#include "RAS_TexVert.h"
-
-#include <vector>
-using namespace std;
-
-#ifdef WITH_CXX_GUARDEDALLOC
-#include "MEM_guardedalloc.h"
-#endif
-
-class RAS_ICanvas;
-class RAS_IPolyMaterial;
-class RAS_MeshSlot;
-class RAS_ILightObject;
-class SCA_IScene;
-class RAS_IOffScreen;
-class RAS_ISync;
-
-typedef vector<unsigned short> KX_IndexArray;
-typedef vector<RAS_TexVert> KX_VertexArray;
-typedef vector<KX_VertexArray *> vecVertexArray;
-typedef vector<KX_IndexArray *> vecIndexArrays;
-
-/**
- * 3D rendering device context interface.
- */
-class RAS_IRasterizer
-{
-public:
- enum RAS_TEXT_RENDER_MODE {
- RAS_TEXT_RENDER_NODEF = 0,
- RAS_TEXT_NORMAL,
- RAS_TEXT_PADDED,
- RAS_TEXT_MAX,
- };
-
- RAS_IRasterizer(RAS_ICanvas* canv) {};
- virtual ~RAS_IRasterizer() {};
-
- /**
- * Drawing types
- */
- enum DrawType {
- KX_BOUNDINGBOX = 1,
- KX_WIREFRAME,
- KX_SOLID,
- KX_SHADED,
- KX_TEXTURED,
- KX_SHADOW,
- };
-
- /**
- * Drawing modes
- */
-
- enum DrawMode {
- KX_MODE_LINES = 1,
- KX_MODE_TRIANGLES,
- KX_MODE_QUADS,
- };
-
- /**
- * Valid SetDepthMask parameters
- */
- enum DepthMask {
- KX_DEPTHMASK_ENABLED = 1,
- KX_DEPTHMASK_DISABLED,
- };
-
- /**
- */
- enum {
- RAS_RENDER_3DPOLYGON_TEXT = 64, /* GEMAT_TEXT */
- KX_BACKCULL = 16, /* GEMAT_BACKCULL */
- KX_TEX = 4096, /* GEMAT_TEX */
- KX_LINES = 32768,
- };
-
- /**
- * Stereo mode types
- */
- enum StereoMode {
- RAS_STEREO_NOSTEREO = 1,
- RAS_STEREO_QUADBUFFERED,
- RAS_STEREO_ABOVEBELOW,
- RAS_STEREO_INTERLACED,
- RAS_STEREO_ANAGLYPH,
- RAS_STEREO_SIDEBYSIDE,
- RAS_STEREO_VINTERLACE,
- RAS_STEREO_DOME,
- RAS_STEREO_3DTVTOPBOTTOM,
-
- RAS_STEREO_MAXSTEREO
- };
-
- /**
- * Texture gen modes.
- */
- enum TexCoGen {
- RAS_TEXCO_GEN, /* < GPU will generate texture coordinates */
- RAS_TEXCO_ORCO, /* < Vertex coordinates (object space) */
- RAS_TEXCO_GLOB, /* < Vertex coordinates (world space) */
- RAS_TEXCO_UV, /* < UV coordinates */
- RAS_TEXCO_OBJECT, /* < Use another object's position as coordinates */
- RAS_TEXCO_LAVECTOR, /* < Light vector as coordinates */
- RAS_TEXCO_VIEW, /* < View vector as coordinates */
- RAS_TEXCO_STICKY, /* < Sticky coordinates */
- RAS_TEXCO_WINDOW, /* < Window coordinates */
- RAS_TEXCO_NORM, /* < Normal coordinates */
- RAS_TEXTANGENT, /* < */
- RAS_TEXCO_VCOL, /* < Vertex Color */
- RAS_TEXCO_DISABLE, /* < Disable this texture unit (cached) */
- };
-
- /**
- * Render pass identifiers for stereo.
- */
- enum StereoEye {
- RAS_STEREO_LEFTEYE = 1,
- RAS_STEREO_RIGHTEYE,
- };
-
- /**
- * Mipmap options
- */
- enum MipmapOption {
- RAS_MIPMAP_NONE,
- RAS_MIPMAP_NEAREST,
- RAS_MIPMAP_LINEAR,
-
- RAS_MIPMAP_MAX, /* Should always be last */
- };
-
- /**
- * SetDepthMask enables or disables writing a fragment's depth value
- * to the Z buffer.
- */
- virtual void SetDepthMask(DepthMask depthmask) = 0;
-
- /**
- * SetMaterial sets the material settings for subsequent primitives
- * to be rendered with.
- * The material will be cached.
- */
- virtual bool SetMaterial(const RAS_IPolyMaterial &mat) = 0;
-
- /**
- * Init initializes the renderer.
- */
- virtual bool Init() = 0;
-
- /**
- * Exit cleans up the renderer.
- */
- virtual void Exit() = 0;
-
- /**
- * BeginFrame is called at the start of each frame.
- */
- virtual bool BeginFrame(double time) = 0;
-
- /**
- * ClearColorBuffer clears the color buffer.
- */
- virtual void ClearColorBuffer() = 0;
-
- /**
- * ClearDepthBuffer clears the depth buffer.
- */
- virtual void ClearDepthBuffer() = 0;
-
- /**
- * ClearCachingInfo clears the currently cached material.
- */
- virtual void ClearCachingInfo(void) = 0;
-
- /**
- * EndFrame is called at the end of each frame.
- */
- virtual void EndFrame() = 0;
-
- /**
- * SetRenderArea sets the render area from the 2d canvas.
- * Returns true if only of subset of the canvas is used.
- */
- virtual void SetRenderArea() = 0;
-
- // Stereo Functions
- /**
- * SetStereoMode will set the stereo mode
- */
- virtual void SetStereoMode(const StereoMode stereomode) = 0;
-
- /**
- * Stereo can be used to query if the rasterizer is in stereo mode.
- * \return true if stereo mode is enabled.
- */
- virtual bool Stereo() = 0;
- virtual StereoMode GetStereoMode() = 0;
- virtual bool InterlacedStereo() = 0;
-
- /**
- * Sets which eye buffer subsequent primitives will be rendered to.
- */
- virtual void SetEye(const StereoEye eye) = 0;
- virtual StereoEye GetEye() = 0;
-
- /**
- * Sets the distance between eyes for stereo mode.
- */
- virtual void SetEyeSeparation(const float eyeseparation) = 0;
- virtual float GetEyeSeparation() = 0;
-
- /**
- * Sets the focal length for stereo mode.
- */
- virtual void SetFocalLength(const float focallength) = 0;
- virtual float GetFocalLength() = 0;
-
- /**
- * Create an offscreen render buffer that can be used as target for render.
- * For the time being, it is only used in VideoTexture for custom render.
- */
- virtual RAS_IOffScreen *CreateOffScreen(int width, int height, int samples, int target) = 0;
-
- /**
- * Create a sync object
- * For use with offscreen render
- */
- virtual RAS_ISync *CreateSync(int type) = 0;
-
- /**
- * SwapBuffers swaps the back buffer with the front buffer.
- */
- virtual void SwapBuffers() = 0;
-
- // Drawing Functions
- /**
- * IndexPrimitives: Renders primitives from mesh slot.
- */
- virtual void IndexPrimitives(class RAS_MeshSlot &ms) = 0;
-
- /**
- * IndexPrimitives_3DText will render text into the polygons.
- */
- virtual void IndexPrimitives_3DText(class RAS_MeshSlot &ms, class RAS_IPolyMaterial *polymat) = 0;
-
- virtual void SetProjectionMatrix(MT_CmMatrix4x4 &mat) = 0;
-
- /* This one should become our final version, methinks. */
- /**
- * Set the projection matrix for the rasterizer. This projects
- * from camera coordinates to window coordinates.
- * \param mat The projection matrix.
- */
- virtual void SetProjectionMatrix(const MT_Matrix4x4 &mat) = 0;
-
- /**
- * Sets the modelview matrix.
- */
- virtual void SetViewMatrix(const MT_Matrix4x4 &mat, const MT_Matrix3x3 &ori,
- const MT_Point3 &pos, const MT_Vector3 &scale, bool perspective) = 0;
-
- /**
- */
- virtual const MT_Point3& GetCameraPosition() = 0;
- virtual bool GetCameraOrtho() = 0;
-
- /**
- * Fog
- */
- virtual void SetFog(short type, float start, float dist, float intensity, float color[3]) = 0;
- virtual void DisplayFog() = 0;
- virtual void EnableFog(bool enable) = 0;
-
- virtual void SetBackColor(float color[3]) = 0;
-
- /**
- * \param drawingmode = KX_BOUNDINGBOX, KX_WIREFRAME, KX_SOLID, KX_SHADED or KX_TEXTURED.
- */
- virtual void SetDrawingMode(int drawingmode) = 0;
-
- /**
- * \return the current drawing mode: KX_BOUNDINGBOX, KX_WIREFRAME, KX_SOLID, KX_SHADED or KX_TEXTURED.
- */
- virtual int GetDrawingMode() = 0;
-
- /**
- * Sets face culling
- */
- virtual void SetCullFace(bool enable) = 0;
-
- /**
- * Sets wireframe mode.
- */
- virtual void SetLines(bool enable) = 0;
-
- /**
- */
- virtual double GetTime() = 0;
-
- /**
- * Generates a projection matrix from the specified frustum.
- * \param left the left clipping plane
- * \param right the right clipping plane
- * \param bottom the bottom clipping plane
- * \param top the top clipping plane
- * \param frustnear the near clipping plane
- * \param frustfar the far clipping plane
- * \return a 4x4 matrix representing the projection transform.
- */
- virtual MT_Matrix4x4 GetFrustumMatrix(
- float left, float right, float bottom, float top,
- float frustnear, float frustfar,
- float focallength = 0.0f, bool perspective = true) = 0;
-
- /**
- * Generates a orthographic projection matrix from the specified frustum.
- * \param left the left clipping plane
- * \param right the right clipping plane
- * \param bottom the bottom clipping plane
- * \param top the top clipping plane
- * \param frustnear the near clipping plane
- * \param frustfar the far clipping plane
- * \return a 4x4 matrix representing the projection transform.
- */
- virtual MT_Matrix4x4 GetOrthoMatrix(
- float left, float right, float bottom, float top,
- float frustnear, float frustfar) = 0;
-
- /**
- * Sets the specular color component of the lighting equation.
- */
- virtual void SetSpecularity(float specX, float specY, float specZ, float specval) = 0;
-
- /**
- * Sets the specular exponent component of the lighting equation.
- */
- virtual void SetShinyness(float shiny) = 0;
-
- /**
- * Sets the diffuse color component of the lighting equation.
- */
- virtual void SetDiffuse(float difX,float difY, float difZ, float diffuse) = 0;
-
- /**
- * Sets the emissive color component of the lighting equation.
- */
- virtual void SetEmissive(float eX, float eY, float eZ, float e) = 0;
-
- virtual void SetAmbientColor(float color[3]) = 0;
- virtual void SetAmbient(float factor) = 0;
-
- /**
- * Sets a polygon offset. z depth will be: z1 = mult*z0 + add
- */
- virtual void SetPolygonOffset(float mult, float add) = 0;
-
- virtual void DrawDebugLine(SCA_IScene *scene, const MT_Vector3 &from, const MT_Vector3 &to, const MT_Vector3& color) = 0;
- virtual void DrawDebugCircle(SCA_IScene *scene, const MT_Vector3 &center, const MT_Scalar radius,
- const MT_Vector3 &color, const MT_Vector3 &normal, int nsector) = 0;
- virtual void FlushDebugShapes(SCA_IScene *scene) = 0;
-
- virtual void SetTexCoordNum(int num) = 0;
- virtual void SetAttribNum(int num) = 0;
- virtual void SetTexCoord(TexCoGen coords, int unit) = 0;
- virtual void SetAttrib(TexCoGen coords, int unit, int layer = 0) = 0;
-
- virtual const MT_Matrix4x4 &GetViewMatrix() const = 0;
- virtual const MT_Matrix4x4 &GetViewInvMatrix() const = 0;
-
- virtual bool QueryLists() { return false; }
- virtual bool QueryArrays() { return false; }
-
- virtual void EnableMotionBlur(float motionblurvalue) = 0;
- virtual void DisableMotionBlur() = 0;
-
- virtual float GetMotionBlurValue() = 0;
- virtual int GetMotionBlurState() = 0;
- virtual void SetMotionBlurState(int newstate) = 0;
-
- virtual void SetAlphaBlend(int alphablend) = 0;
- virtual void SetFrontFace(bool ccw) = 0;
-
- virtual void SetAnisotropicFiltering(short level) = 0;
- virtual short GetAnisotropicFiltering() = 0;
-
- virtual void SetMipmapping(MipmapOption val) = 0;
- virtual MipmapOption GetMipmapping() = 0;
-
- virtual void SetUsingOverrideShader(bool val) = 0;
- virtual bool GetUsingOverrideShader() = 0;
-
- /**
- * Render Tools
- */
- virtual void applyTransform(float *oglmatrix, int drawingmode) = 0;
-
- /**
- * Renders 2D boxes.
- * \param xco Position on the screen (origin in lower left corner).
- * \param yco Position on the screen (origin in lower left corner).
- * \param width Width of the canvas to draw to.
- * \param height Height of the canvas to draw to.
- * \param percentage Percentage of bar.
- */
- virtual void RenderBox2D(int xco, int yco, int width, int height, float percentage) = 0;
-
- /**
- * Renders 3D text string using BFL.
- * \param fontid The id of the font.
- * \param text The string to render.
- * \param size The size of the text.
- * \param dpi The resolution of the text.
- * \param color The color of the object.
- * \param mat The Matrix of the text object.
- * \param aspect A scaling factor to compensate for the size.
- */
- virtual void RenderText3D(
- int fontid, const char *text, int size, int dpi,
- const float color[4], const float mat[16], float aspect) = 0;
-
- /**
- * Renders 2D text string.
- * \param mode The type of text
- * \param text The string to render.
- * \param xco Position on the screen (origin in lower left corner).
- * \param yco Position on the screen (origin in lower left corner).
- * \param width Width of the canvas to draw to.
- * \param height Height of the canvas to draw to.
- */
- virtual void RenderText2D(
- RAS_TEXT_RENDER_MODE mode, const char *text,
- int xco, int yco, int width, int height) = 0;
-
- virtual void ProcessLighting(bool uselights, const MT_Transform &trans) = 0;
-
- virtual void PushMatrix() = 0;
-
- virtual void PopMatrix() = 0;
-
- virtual RAS_ILightObject *CreateLight() = 0;
-
- virtual void AddLight(RAS_ILightObject *lightobject) = 0;
-
- virtual void RemoveLight(RAS_ILightObject *lightobject) = 0;
-
- virtual void MotionBlur() = 0;
-
- virtual void SetClientObject(void *obj) = 0;
-
- virtual void SetAuxilaryClientInfo(void *inf) = 0;
-
- /**
- * Prints information about what the hardware supports.
- */
- virtual void PrintHardwareInfo() = 0;
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:RAS_IRasterizer")
-#endif
-};
-
-#endif /* __RAS_IRASTERIZER_H__ */
diff --git a/source/gameengine/Rasterizer/RAS_ISync.h b/source/gameengine/Rasterizer/RAS_ISync.h
deleted file mode 100644
index 7e34172c2a3..00000000000
--- a/source/gameengine/Rasterizer/RAS_ISync.h
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2015, Blender Foundation
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): Blender Foundation.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file RAS_ISync.h
- * \ingroup bgerast
- */
-
-#ifndef __RAS_ISYNC_H__
-#define __RAS_ISYNC_H__
-
-class RAS_ISync
-{
-public:
- enum RAS_SYNC_TYPE {
- RAS_SYNC_TYPE_FENCE = 0,
- };
- virtual ~RAS_ISync() {}
-
- virtual bool Create(RAS_SYNC_TYPE type) = 0;
- virtual void Destroy() = 0;
- virtual void Wait() = 0;
-};
-
-#endif /* __RAS_ISYNC_H__ */
diff --git a/source/gameengine/Rasterizer/RAS_MaterialBucket.cpp b/source/gameengine/Rasterizer/RAS_MaterialBucket.cpp
deleted file mode 100644
index 9cd8f77adfd..00000000000
--- a/source/gameengine/Rasterizer/RAS_MaterialBucket.cpp
+++ /dev/null
@@ -1,679 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Rasterizer/RAS_MaterialBucket.cpp
- * \ingroup bgerast
- */
-
-
-#include "RAS_MaterialBucket.h"
-
-#ifdef _MSC_VER
-# pragma warning (disable:4786)
-#endif
-
-#ifdef WIN32
-#include <windows.h>
-#endif // WIN32
-
-#include "RAS_IPolygonMaterial.h"
-#include "RAS_TexVert.h"
-#include "RAS_IRasterizer.h"
-#include "RAS_MeshObject.h"
-#include "RAS_Deformer.h" // __NLA
-
-/* mesh slot */
-
-RAS_MeshSlot::RAS_MeshSlot() : SG_QList()
-{
- m_clientObj = NULL;
- m_pDeformer = NULL;
- m_OpenGLMatrix = NULL;
- m_mesh = NULL;
- m_bucket = NULL;
- m_bVisible = false;
- m_bCulled = true;
- m_bObjectColor = false;
- m_RGBAcolor = MT_Vector4(0.0f, 0.0f, 0.0f, 0.0f);
- m_DisplayList = NULL;
- m_bDisplayList = true;
- m_joinSlot = NULL;
- m_pDerivedMesh = NULL;
-}
-
-RAS_MeshSlot::~RAS_MeshSlot()
-{
- RAS_DisplayArrayList::iterator it;
-
-#ifdef USE_SPLIT
- Split(true);
-
- while (m_joinedSlots.size())
- m_joinedSlots.front()->Split(true);
-#endif
-
- for (it=m_displayArrays.begin(); it!=m_displayArrays.end(); it++) {
- (*it)->m_users--;
- if ((*it)->m_users == 0)
- delete *it;
- }
-
- if (m_DisplayList) {
- m_DisplayList->Release();
- m_DisplayList = NULL;
- }
-}
-
-RAS_MeshSlot::RAS_MeshSlot(const RAS_MeshSlot& slot) : SG_QList()
-{
- RAS_DisplayArrayList::iterator it;
-
- m_clientObj = NULL;
- m_pDeformer = NULL;
- m_pDerivedMesh = NULL;
- m_OpenGLMatrix = NULL;
- m_mesh = slot.m_mesh;
- m_bucket = slot.m_bucket;
- m_bVisible = slot.m_bVisible;
- m_bCulled = slot.m_bCulled;
- m_bObjectColor = slot.m_bObjectColor;
- m_RGBAcolor = slot.m_RGBAcolor;
- m_DisplayList = NULL;
- m_bDisplayList = slot.m_bDisplayList;
- m_joinSlot = NULL;
- m_currentArray = slot.m_currentArray;
- m_displayArrays = slot.m_displayArrays;
- m_joinedSlots = slot.m_joinedSlots;
-
- m_startarray = slot.m_startarray;
- m_startvertex = slot.m_startvertex;
- m_startindex = slot.m_startindex;
- m_endarray = slot.m_endarray;
- m_endvertex = slot.m_endvertex;
- m_endindex = slot.m_endindex;
-
- for (it=m_displayArrays.begin(); it!=m_displayArrays.end(); it++) {
- // don't copy display arrays for now because it breaks python
- // access to vertices, but we'll need a solution if we want to
- // join display arrays for reducing draw calls.
- //*it = new RAS_DisplayArray(**it);
- //(*it)->m_users = 1;
-
- (*it)->m_users++;
- }
-}
-
-void RAS_MeshSlot::init(RAS_MaterialBucket *bucket, int numverts)
-{
- m_bucket = bucket;
-
- SetDisplayArray(numverts);
-
- m_startarray = 0;
- m_startvertex = 0;
- m_startindex = 0;
- m_endarray = 0;
- m_endvertex = 0;
- m_endindex = 0;
-}
-
-void RAS_MeshSlot::begin(RAS_MeshSlot::iterator& it)
-{
- int startvertex, endvertex;
- int startindex, endindex;
-
- it.array = m_displayArrays.empty() ? NULL : m_displayArrays[m_startarray];
-
- if (it.array == NULL || it.array->m_index.size() == 0 || it.array->m_vertex.size() == 0) {
- it.array = NULL;
- it.vertex = NULL;
- it.index = NULL;
- it.startvertex = 0;
- it.endvertex = 0;
- it.totindex = 0;
- }
- else {
- startvertex = m_startvertex;
- endvertex = (m_startarray == m_endarray)? m_endvertex: it.array->m_vertex.size();
- startindex = m_startindex;
- endindex = (m_startarray == m_endarray)? m_endindex: it.array->m_index.size();
-
- it.vertex = &it.array->m_vertex[0];
- it.index = &it.array->m_index[startindex];
- it.startvertex = startvertex;
- it.endvertex = endvertex;
- it.totindex = endindex-startindex;
- it.arraynum = m_startarray;
- }
-}
-
-void RAS_MeshSlot::next(RAS_MeshSlot::iterator& it)
-{
- int startvertex, endvertex;
- int startindex, endindex;
-
- if (it.arraynum == (size_t)m_endarray) {
- it.array = NULL;
- it.vertex = NULL;
- it.index = NULL;
- it.startvertex = 0;
- it.endvertex = 0;
- it.totindex = 0;
- }
- else {
- it.arraynum++;
- it.array = m_displayArrays[it.arraynum];
-
- startindex = 0;
- endindex = (it.arraynum == (size_t)m_endarray)? m_endindex: it.array->m_index.size();
- startvertex = 0;
- endvertex = (it.arraynum == (size_t)m_endarray)? m_endvertex: it.array->m_vertex.size();
-
- it.vertex = &it.array->m_vertex[0];
- it.index = &it.array->m_index[startindex];
- it.startvertex = startvertex;
- it.endvertex = endvertex;
- it.totindex = endindex-startindex;
- }
-}
-
-bool RAS_MeshSlot::end(RAS_MeshSlot::iterator& it)
-{
- return (it.array == NULL);
-}
-
-RAS_DisplayArray *RAS_MeshSlot::CurrentDisplayArray()
-{
- return m_currentArray;
-}
-
-void RAS_MeshSlot::SetDisplayArray(int numverts)
-{
- RAS_DisplayArrayList::iterator it;
- RAS_DisplayArray *darray = NULL;
-
- for (it=m_displayArrays.begin(); it!=m_displayArrays.end(); it++) {
- darray = *it;
-
- if (darray->m_type == numverts) {
- if (darray->m_index.size()+numverts >= RAS_DisplayArray::BUCKET_MAX_INDEX)
- darray = NULL;
- else if (darray->m_vertex.size()+numverts >= RAS_DisplayArray::BUCKET_MAX_VERTEX)
- darray = NULL;
- else
- break;
- }
- else
- darray = NULL;
- }
-
- if (!darray) {
- darray = new RAS_DisplayArray();
- darray->m_users = 1;
-
- if (numverts == 2) darray->m_type = RAS_DisplayArray::LINE;
- else if (numverts == 3) darray->m_type = RAS_DisplayArray::TRIANGLE;
- else darray->m_type = RAS_DisplayArray::QUAD;
-
- m_displayArrays.push_back(darray);
-
- if (numverts == 2)
- darray->m_type = RAS_DisplayArray::LINE;
- else if (numverts == 3)
- darray->m_type = RAS_DisplayArray::TRIANGLE;
- else if (numverts == 4)
- darray->m_type = RAS_DisplayArray::QUAD;
-
- m_endarray = m_displayArrays.size()-1;
- m_endvertex = 0;
- m_endindex = 0;
- }
-
- m_currentArray = darray;
-}
-
-void RAS_MeshSlot::AddPolygon(int numverts)
-{
- SetDisplayArray(numverts);
-}
-
-int RAS_MeshSlot::AddVertex(const RAS_TexVert& tv)
-{
- RAS_DisplayArray *darray;
- int offset;
-
- darray = m_currentArray;
- darray->m_vertex.push_back(tv);
- offset = darray->m_vertex.size()-1;
-
- if (darray == m_displayArrays[m_endarray])
- m_endvertex++;
-
- return offset;
-}
-
-void RAS_MeshSlot::AddPolygonVertex(int offset)
-{
- RAS_DisplayArray *darray;
-
- darray = m_currentArray;
- darray->m_index.push_back(offset);
-
- if (darray == m_displayArrays[m_endarray])
- m_endindex++;
-}
-
-void RAS_MeshSlot::UpdateDisplayArraysOffset()
-{
- unsigned int offset = 0;
- for (unsigned short i = 0; i < m_displayArrays.size(); ++i) {
- RAS_DisplayArray *darray = m_displayArrays[i];
- darray->m_offset = offset;
- offset += darray->m_vertex.size();
- }
-}
-
-void RAS_MeshSlot::SetDeformer(RAS_Deformer* deformer)
-{
- if (deformer && m_pDeformer != deformer) {
- RAS_DisplayArrayList::iterator it;
- if (deformer->ShareVertexArray()) {
- // this deformer uses the base vertex array, first release the current ones
- for (it=m_displayArrays.begin(); it!=m_displayArrays.end(); it++) {
- (*it)->m_users--;
- if ((*it)->m_users == 0)
- delete *it;
- }
- m_displayArrays.clear();
- // then hook to the base ones
- RAS_MeshMaterial *mmat = m_mesh->GetMeshMaterial(m_bucket->GetPolyMaterial());
- if (mmat && mmat->m_baseslot) {
- m_displayArrays = mmat->m_baseslot->m_displayArrays;
- for (it=m_displayArrays.begin(); it!=m_displayArrays.end(); it++) {
- (*it)->m_users++;
- }
- }
- }
- else {
- // no sharing
- // we create local copy of RAS_DisplayArray when we have a deformer:
- // this way we can avoid conflict between the vertex cache of duplicates
- for (it=m_displayArrays.begin(); it!=m_displayArrays.end(); it++) {
- if (deformer->UseVertexArray()) {
- // the deformer makes use of vertex array, make sure we have our local copy
- if ((*it)->m_users > 1) {
- // only need to copy if there are other users
- // note that this is the usual case as vertex arrays are held by the material base slot
- RAS_DisplayArray *newarray = new RAS_DisplayArray(*(*it));
- newarray->m_users = 1;
- (*it)->m_users--;
- *it = newarray;
- }
- } else {
- // the deformer is not using vertex array (Modifier), release them
- (*it)->m_users--;
- if ((*it)->m_users == 0)
- delete *it;
- }
- }
- if (!deformer->UseVertexArray()) {
- m_displayArrays.clear();
- m_startarray = 0;
- m_startvertex = 0;
- m_startindex = 0;
- m_endarray = 0;
- m_endvertex = 0;
- m_endindex = 0;
- }
- }
- }
- m_pDeformer = deformer;
-}
-
-bool RAS_MeshSlot::Equals(RAS_MeshSlot *target)
-{
- if (!m_OpenGLMatrix || !target->m_OpenGLMatrix)
- return false;
- if (m_pDeformer || target->m_pDeformer)
- return false;
- if (m_bVisible != target->m_bVisible)
- return false;
- if (m_bObjectColor != target->m_bObjectColor)
- return false;
- if (m_bObjectColor && !(m_RGBAcolor == target->m_RGBAcolor))
- return false;
-
- return true;
-}
-
-bool RAS_MeshSlot::Join(RAS_MeshSlot *target, MT_Scalar distance)
-{
- RAS_DisplayArrayList::iterator it;
- iterator mit;
- size_t i;
-
- // verify if we can join
- if (m_joinSlot || (m_joinedSlots.empty() == false) || target->m_joinSlot)
- return false;
-
- if (!Equals(target))
- return false;
-
- MT_Vector3 co(&m_OpenGLMatrix[12]);
- MT_Vector3 targetco(&target->m_OpenGLMatrix[12]);
-
- if ((co - targetco).length() > distance)
- return false;
-
- MT_Matrix4x4 mat(m_OpenGLMatrix);
- MT_Matrix4x4 targetmat(target->m_OpenGLMatrix);
- targetmat.invert();
-
- MT_Matrix4x4 transform = targetmat*mat;
-
- // m_mesh, clientobj
- m_joinSlot = target;
- m_joinInvTransform = transform;
- m_joinInvTransform.invert();
- target->m_joinedSlots.push_back(this);
-
- MT_Matrix4x4 ntransform = m_joinInvTransform.transposed();
- ntransform[0][3] = ntransform[1][3] = ntransform[2][3] = 0.0f;
-
- for (begin(mit); !end(mit); next(mit))
- for (i=mit.startvertex; i<mit.endvertex; i++)
- mit.vertex[i].Transform(transform, ntransform);
-
- /* We know we'll need a list at least this big, reserve in advance */
- target->m_displayArrays.reserve(target->m_displayArrays.size() + m_displayArrays.size());
-
- for (it=m_displayArrays.begin(); it!=m_displayArrays.end(); it++) {
- target->m_displayArrays.push_back(*it);
- target->m_endarray++;
- target->m_endvertex = target->m_displayArrays.back()->m_vertex.size();
- target->m_endindex = target->m_displayArrays.back()->m_index.size();
- }
-
- if (m_DisplayList) {
- m_DisplayList->Release();
- m_DisplayList = NULL;
- }
- if (target->m_DisplayList) {
- target->m_DisplayList->Release();
- target->m_DisplayList = NULL;
- }
-
- return true;
-#if 0
- return false;
-#endif
-}
-
-bool RAS_MeshSlot::Split(bool force)
-{
- list<RAS_MeshSlot*>::iterator jit;
- RAS_MeshSlot *target = m_joinSlot;
- RAS_DisplayArrayList::iterator it, jt;
- iterator mit;
- size_t i, found0 = 0, found1 = 0;
-
- if (target && (force || !Equals(target))) {
- m_joinSlot = NULL;
-
- for (jit=target->m_joinedSlots.begin(); jit!=target->m_joinedSlots.end(); jit++) {
- if (*jit == this) {
- target->m_joinedSlots.erase(jit);
- found0 = 1;
- break;
- }
- }
-
- if (!found0)
- abort();
-
- for (it=m_displayArrays.begin(); it!=m_displayArrays.end(); it++) {
- found1 = 0;
- for (jt=target->m_displayArrays.begin(); jt!=target->m_displayArrays.end(); jt++) {
- if (*jt == *it) {
- target->m_displayArrays.erase(jt);
- target->m_endarray--;
- found1 = 1;
- break;
- }
- }
-
- if (!found1)
- abort();
- }
-
- if (target->m_displayArrays.empty() == false) {
- target->m_endvertex = target->m_displayArrays.back()->m_vertex.size();
- target->m_endindex = target->m_displayArrays.back()->m_index.size();
- }
- else {
- target->m_endvertex = 0;
- target->m_endindex = 0;
- }
-
- MT_Matrix4x4 ntransform = m_joinInvTransform.inverse().transposed();
- ntransform[0][3] = ntransform[1][3] = ntransform[2][3] = 0.0f;
-
- for (begin(mit); !end(mit); next(mit))
- for (i=mit.startvertex; i<mit.endvertex; i++)
- mit.vertex[i].Transform(m_joinInvTransform, ntransform);
-
- if (target->m_DisplayList) {
- target->m_DisplayList->Release();
- target->m_DisplayList = NULL;
- }
-
- return true;
- }
-
- return false;
-}
-
-
-#ifdef USE_SPLIT
-bool RAS_MeshSlot::IsCulled()
-{
- if (m_joinSlot)
- return true;
- if (!m_bCulled)
- return false;
- list<RAS_MeshSlot*>::iterator it;
- for (it=m_joinedSlots.begin(); it!=m_joinedSlots.end(); it++)
- if (!(*it)->m_bCulled)
- return false;
- return true;
-}
-#endif
-
-/* material bucket sorting */
-
-struct RAS_MaterialBucket::less
-{
- bool operator()(const RAS_MaterialBucket* x, const RAS_MaterialBucket* y) const
- {
- return *x->GetPolyMaterial() < *y->GetPolyMaterial();
- }
-};
-
-/* material bucket */
-
-RAS_MaterialBucket::RAS_MaterialBucket(RAS_IPolyMaterial* mat)
-{
- m_material = mat;
-}
-
-RAS_MaterialBucket::~RAS_MaterialBucket()
-{
-}
-
-RAS_IPolyMaterial* RAS_MaterialBucket::GetPolyMaterial() const
-{
- return m_material;
-}
-
-bool RAS_MaterialBucket::IsAlpha() const
-{
- return (m_material->IsAlpha());
-}
-
-bool RAS_MaterialBucket::IsZSort() const
-{
- return (m_material->IsZSort());
-}
-
-RAS_MeshSlot* RAS_MaterialBucket::AddMesh(int numverts)
-{
- RAS_MeshSlot *ms;
-
- m_meshSlots.push_back(RAS_MeshSlot());
-
- ms = &m_meshSlots.back();
- ms->init(this, numverts);
-
- return ms;
-}
-
-RAS_MeshSlot* RAS_MaterialBucket::CopyMesh(RAS_MeshSlot *ms)
-{
- m_meshSlots.push_back(RAS_MeshSlot(*ms));
-
- return &m_meshSlots.back();
-}
-
-void RAS_MaterialBucket::RemoveMesh(RAS_MeshSlot* ms)
-{
- list<RAS_MeshSlot>::iterator it;
-
- for (it=m_meshSlots.begin(); it!=m_meshSlots.end(); it++) {
- if (&*it == ms) {
- m_meshSlots.erase(it);
- return;
- }
- }
-}
-
-list<RAS_MeshSlot>::iterator RAS_MaterialBucket::msBegin()
-{
- return m_meshSlots.begin();
-}
-
-list<RAS_MeshSlot>::iterator RAS_MaterialBucket::msEnd()
-{
- return m_meshSlots.end();
-}
-
-bool RAS_MaterialBucket::ActivateMaterial(const MT_Transform& cameratrans, RAS_IRasterizer* rasty)
-{
- bool uselights;
-
- if (rasty->GetDrawingMode() == RAS_IRasterizer::KX_SHADOW && !m_material->CastsShadows())
- return false;
-
- if (rasty->GetDrawingMode() != RAS_IRasterizer::KX_SHADOW && m_material->OnlyShadow())
- return false;
-
- if (!rasty->SetMaterial(*m_material))
- return false;
-
- uselights= m_material->UsesLighting(rasty);
- rasty->ProcessLighting(uselights, cameratrans);
-
- return true;
-}
-
-void RAS_MaterialBucket::RenderMeshSlot(const MT_Transform& cameratrans, RAS_IRasterizer* rasty, RAS_MeshSlot &ms)
-{
- m_material->ActivateMeshSlot(ms, rasty);
-
- if (ms.m_pDeformer)
- {
- if (ms.m_pDeformer->Apply(m_material))
- ms.m_mesh->SetMeshModified(true);
- // KX_ReInstanceShapeFromMesh(ms.m_mesh); // Recompute the physics mesh. (Can't call KX_* from RAS_)
- }
-
- if (IsZSort() && rasty->GetDrawingMode() >= RAS_IRasterizer::KX_SOLID)
- ms.m_mesh->SortPolygons(ms, cameratrans*MT_Transform(ms.m_OpenGLMatrix));
-
- rasty->PushMatrix();
- if (!ms.m_pDeformer || !ms.m_pDeformer->SkipVertexTransform())
- {
- rasty->applyTransform(ms.m_OpenGLMatrix,m_material->GetDrawingMode());
- }
-
- if (rasty->QueryLists())
- if (ms.m_DisplayList)
- ms.m_DisplayList->SetModified(ms.m_mesh->MeshModified());
-
- // verify if we can use display list, not for deformed object, and
- // also don't create a new display list when drawing shadow buffers,
- // then it won't have texture coordinates for actual drawing. also
- // for zsort we can't make a display list, since the polygon order
- // changes all the time.
- if (ms.m_pDeformer && ms.m_pDeformer->IsDynamic())
- ms.m_bDisplayList = false;
- else if (!ms.m_DisplayList && rasty->GetDrawingMode() == RAS_IRasterizer::KX_SHADOW)
- ms.m_bDisplayList = false;
- else if (IsZSort())
- ms.m_bDisplayList = false;
- else if (m_material->UsesObjectColor() && ms.m_bObjectColor)
- ms.m_bDisplayList = false;
- else
- ms.m_bDisplayList = true;
-
- if (m_material->GetDrawingMode() & RAS_IRasterizer::RAS_RENDER_3DPOLYGON_TEXT) {
- // for text drawing using faces
- rasty->IndexPrimitives_3DText(ms, m_material);
- }
- else {
- rasty->IndexPrimitives(ms);
- }
-
- rasty->PopMatrix();
-}
-
-void RAS_MaterialBucket::Optimize(MT_Scalar distance)
-{
- /* TODO: still have to check before this works correct:
- * - lightlayer, frontface, text, billboard
- * - make it work with physics */
-
-#if 0
- list<RAS_MeshSlot>::iterator it;
- list<RAS_MeshSlot>::iterator jt;
-
- // greed joining on all following buckets
- for (it=m_meshSlots.begin(); it!=m_meshSlots.end(); it++)
- for (jt=it, jt++; jt!=m_meshSlots.end(); jt++)
- jt->Join(&*it, distance);
-#endif
-}
-
diff --git a/source/gameengine/Rasterizer/RAS_MaterialBucket.h b/source/gameengine/Rasterizer/RAS_MaterialBucket.h
deleted file mode 100644
index 75cc382c78c..00000000000
--- a/source/gameengine/Rasterizer/RAS_MaterialBucket.h
+++ /dev/null
@@ -1,267 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file RAS_MaterialBucket.h
- * \ingroup bgerast
- */
-
-#ifndef __RAS_MATERIALBUCKET_H__
-#define __RAS_MATERIALBUCKET_H__
-
-#include "RAS_TexVert.h"
-#include "CTR_Map.h"
-#include "SG_QList.h"
-
-#include "MT_Transform.h"
-#include "MT_Matrix4x4.h"
-
-#include <vector>
-#include <set>
-#include <list>
-
-class RAS_MaterialBucket;
-struct DerivedMesh;
-class CTR_HashedPtr;
-class RAS_Deformer;
-class RAS_IPolyMaterial;
-class RAS_IRasterizer;
-class RAS_MeshObject;
-
-using namespace std;
-
-/* Display List Slot */
-
-class KX_ListSlot
-{
-protected:
- int m_refcount;
-public:
- KX_ListSlot() { m_refcount = 1; }
- virtual ~KX_ListSlot() {}
- virtual int Release() {
- if (--m_refcount > 0)
- return m_refcount;
- delete this;
- return 0;
- }
- virtual KX_ListSlot* AddRef() {
- m_refcount++;
- return this;
- }
- virtual void SetModified(bool mod)=0;
-};
-
-/* An array with data used for OpenGL drawing */
-
-class RAS_DisplayArray
-{
-public:
- /** The offset relation to the previous RAS_DisplayArray.
- * For the user vertex are one big list but in C++ source
- * it's two different lists if we use quads and triangles.
- * So to fix that we add an offset.
- * This value is set in UpdateDisplayArraysOffset().
- */
- unsigned int m_offset;
- vector<RAS_TexVert> m_vertex;
- vector<unsigned short> m_index;
- /* LINE currently isn't used */
- enum { LINE = 2, TRIANGLE = 3, QUAD = 4 } m_type;
- //RAS_MeshSlot *m_origSlot;
-
- /* Number of RAS_MeshSlot using this array */
- int m_users;
-
- enum { BUCKET_MAX_INDEX = 65535 };
- enum { BUCKET_MAX_VERTEX = 65535 };
-};
-
-/* Entry of a RAS_MeshObject into RAS_MaterialBucket */
-typedef std::vector<RAS_DisplayArray*> RAS_DisplayArrayList;
-
-// The QList is used to link the mesh slots to the object
-// The DList is used to link the visible mesh slots to the material bucket
-class RAS_MeshSlot : public SG_QList
-{
- friend class RAS_ListRasterizer;
-private:
- // indices into display arrays
- int m_startarray;
- int m_endarray;
- int m_startindex;
- int m_endindex;
- int m_startvertex;
- int m_endvertex;
- RAS_DisplayArrayList m_displayArrays;
-
- // for construction only
- RAS_DisplayArray* m_currentArray;
-
-public:
- // for rendering
- RAS_MaterialBucket* m_bucket;
- RAS_MeshObject* m_mesh;
- void* m_clientObj;
- RAS_Deformer* m_pDeformer;
- DerivedMesh* m_pDerivedMesh;
- float* m_OpenGLMatrix;
- // visibility
- bool m_bVisible;
- bool m_bCulled;
- // object color
- bool m_bObjectColor;
- MT_Vector4 m_RGBAcolor;
- // display lists
- KX_ListSlot* m_DisplayList;
- bool m_bDisplayList;
- // joined mesh slots
- RAS_MeshSlot* m_joinSlot;
- MT_Matrix4x4 m_joinInvTransform;
- list<RAS_MeshSlot*> m_joinedSlots;
-
- RAS_MeshSlot();
- RAS_MeshSlot(const RAS_MeshSlot& slot);
- virtual ~RAS_MeshSlot();
-
- void init(RAS_MaterialBucket *bucket, int numverts);
-
- struct iterator {
- RAS_DisplayArray *array;
- RAS_TexVert *vertex;
- unsigned short *index;
- size_t startvertex;
- size_t endvertex;
- size_t totindex;
- size_t arraynum;
- };
-
- void begin(iterator& it);
- void next(iterator& it);
- bool end(iterator& it);
-
- /* used during construction */
- void SetDisplayArray(int numverts);
- RAS_DisplayArray *CurrentDisplayArray();
- void SetDeformer(RAS_Deformer* deformer);
-
- void AddPolygon(int numverts);
- int AddVertex(const RAS_TexVert& tv);
- void AddPolygonVertex(int offset);
-
- /// Update offset of each display array
- void UpdateDisplayArraysOffset();
-
- /* optimization */
- bool Split(bool force=false);
- bool Join(RAS_MeshSlot *target, MT_Scalar distance);
- bool Equals(RAS_MeshSlot *target);
-#ifdef USE_SPLIT
- bool IsCulled();
-#else
- bool IsCulled() { return m_bCulled; }
-#endif
- void SetCulled(bool culled) { m_bCulled = culled; }
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:RAS_MeshSlot")
-#endif
-};
-
-/* Used by RAS_MeshObject, to point to it's slots in a bucket */
-
-class RAS_MeshMaterial
-{
-public:
- RAS_MeshSlot *m_baseslot;
- class RAS_MaterialBucket *m_bucket;
-
- /* the KX_GameObject is used as a key here */
- CTR_Map<CTR_HashedPtr,RAS_MeshSlot*> m_slots;
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:RAS_MeshMaterial")
-#endif
-};
-
-/* Contains a list of display arrays with the same material,
- * and a mesh slot for each mesh that uses display arrays in
- * this bucket */
-
-class RAS_MaterialBucket
-{
-public:
- RAS_MaterialBucket(RAS_IPolyMaterial* mat);
- virtual ~RAS_MaterialBucket();
-
- /* Bucket Sorting */
- struct less;
- typedef set<RAS_MaterialBucket*, less> Set;
-
- /* Material Properties */
- RAS_IPolyMaterial* GetPolyMaterial() const;
- bool IsAlpha() const;
- bool IsZSort() const;
-
- /* Rendering */
- bool ActivateMaterial(const MT_Transform& cameratrans, RAS_IRasterizer* rasty);
- void RenderMeshSlot(const MT_Transform& cameratrans, RAS_IRasterizer* rasty, RAS_MeshSlot &ms);
-
- /* Mesh Slot Access */
- list<RAS_MeshSlot>::iterator msBegin();
- list<RAS_MeshSlot>::iterator msEnd();
-
- class RAS_MeshSlot* AddMesh(int numverts);
- class RAS_MeshSlot* CopyMesh(class RAS_MeshSlot *ms);
- void RemoveMesh(class RAS_MeshSlot* ms);
- void Optimize(MT_Scalar distance);
- void ActivateMesh(RAS_MeshSlot* slot)
- {
- m_activeMeshSlotsHead.AddBack(slot);
- }
- SG_DList& GetActiveMeshSlots()
- {
- return m_activeMeshSlotsHead;
- }
- RAS_MeshSlot* GetNextActiveMeshSlot()
- {
- return (RAS_MeshSlot*)m_activeMeshSlotsHead.Remove();
- }
-
-private:
- list<RAS_MeshSlot> m_meshSlots; // all the mesh slots
- RAS_IPolyMaterial* m_material;
- SG_DList m_activeMeshSlotsHead; // only those which must be rendered
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:RAS_MaterialBucket")
-#endif
-};
-
-#endif /* __RAS_MATERIAL_BUCKET */
diff --git a/source/gameengine/Rasterizer/RAS_MeshObject.cpp b/source/gameengine/Rasterizer/RAS_MeshObject.cpp
deleted file mode 100644
index 4360464ed32..00000000000
--- a/source/gameengine/Rasterizer/RAS_MeshObject.cpp
+++ /dev/null
@@ -1,573 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Rasterizer/RAS_MeshObject.cpp
- * \ingroup bgerast
- */
-
-#include "DNA_key_types.h"
-#include "DNA_mesh_types.h"
-
-#include "CTR_HashedPtr.h"
-
-#include "RAS_MeshObject.h"
-#include "RAS_Polygon.h"
-#include "RAS_IPolygonMaterial.h"
-#include "RAS_Deformer.h"
-#include "MT_Point3.h"
-
-#include <algorithm>
-
-
-/* polygon sorting */
-
-struct RAS_MeshObject::polygonSlot
-{
- float m_z;
- int m_index[4];
-
- polygonSlot() {}
-
- /* pnorm is the normal from the plane equation that the distance from is
- * used to sort again. */
- void get(const RAS_TexVert *vertexarray, const unsigned short *indexarray,
- int offset, int nvert, const MT_Vector3& pnorm)
- {
- MT_Vector3 center(0, 0, 0);
- int i;
-
- for (i=0; i<nvert; i++) {
- m_index[i] = indexarray[offset+i];
- center += vertexarray[m_index[i]].getXYZ();
- }
-
- /* note we don't divide center by the number of vertices, since all
- * polygons have the same number of vertices, and that we leave out
- * the 4-th component of the plane equation since it is constant. */
- m_z = MT_dot(pnorm, center);
- }
-
- void set(unsigned short *indexarray, int offset, int nvert)
- {
- int i;
-
- for (i=0; i<nvert; i++)
- indexarray[offset+i] = m_index[i];
- }
-};
-
-struct RAS_MeshObject::backtofront
-{
- bool operator()(const polygonSlot &a, const polygonSlot &b) const
- {
- return a.m_z < b.m_z;
- }
-};
-
-struct RAS_MeshObject::fronttoback
-{
- bool operator()(const polygonSlot &a, const polygonSlot &b) const
- {
- return a.m_z > b.m_z;
- }
-};
-
-/* mesh object */
-
-STR_String RAS_MeshObject::s_emptyname = "";
-
-RAS_MeshObject::RAS_MeshObject(Mesh* mesh)
- : m_bModified(true),
- m_bMeshModified(true),
- m_mesh(mesh)
-{
- if (m_mesh && m_mesh->key)
- {
- KeyBlock *kb;
- int count=0;
- // initialize weight cache for shape objects
- // count how many keys in this mesh
- for (kb= (KeyBlock *)m_mesh->key->block.first; kb; kb= (KeyBlock *)kb->next)
- count++;
- m_cacheWeightIndex.resize(count,-1);
- }
-}
-
-RAS_MeshObject::~RAS_MeshObject()
-{
- vector<RAS_Polygon*>::iterator it;
-
- for (it=m_Polygons.begin(); it!=m_Polygons.end(); it++)
- delete (*it);
-
- m_sharedvertex_map.clear();
- m_Polygons.clear();
- m_materials.clear();
-}
-
-bool RAS_MeshObject::MeshModified()
-{
- return m_bMeshModified;
-}
-
-//unsigned int RAS_MeshObject::GetLightLayer()
-//{
-// return m_lightlayer;
-//}
-
-
-
-int RAS_MeshObject::NumMaterials()
-{
- return m_materials.size();
-}
-
-const STR_String& RAS_MeshObject::GetMaterialName(unsigned int matid)
-{
- RAS_MeshMaterial* mmat = GetMeshMaterial(matid);
-
- if (mmat)
- return mmat->m_bucket->GetPolyMaterial()->GetMaterialName();
-
- return s_emptyname;
-}
-
-RAS_MeshMaterial* RAS_MeshObject::GetMeshMaterial(unsigned int matid)
-{
- if ((m_materials.empty() == false) && (matid < m_materials.size()))
- {
- list<RAS_MeshMaterial>::iterator it = m_materials.begin();
- while (matid--) ++it;
- return &*it;
- }
-
- return NULL;
-}
-
-
-
-int RAS_MeshObject::NumPolygons()
-{
- return m_Polygons.size();
-}
-
-
-
-RAS_Polygon* RAS_MeshObject::GetPolygon(int num) const
-{
- return m_Polygons[num];
-}
-
-
-
-
- list<RAS_MeshMaterial>::iterator GetFirstMaterial();
- list<RAS_MeshMaterial>::iterator GetLastMaterial();
-list<RAS_MeshMaterial>::iterator RAS_MeshObject::GetFirstMaterial()
-{
- return m_materials.begin();
-}
-
-
-
-list<RAS_MeshMaterial>::iterator RAS_MeshObject::GetLastMaterial()
-{
- return m_materials.end();
-}
-
-
-
-void RAS_MeshObject::SetName(const char *name)
-{
- m_name = name;
-}
-
-
-
-STR_String& RAS_MeshObject::GetName()
-{
- return m_name;
-}
-
-
-
-const STR_String& RAS_MeshObject::GetTextureName(unsigned int matid)
-{
- RAS_MeshMaterial* mmat = GetMeshMaterial(matid);
-
- if (mmat)
- return mmat->m_bucket->GetPolyMaterial()->GetTextureName();
-
- return s_emptyname;
-}
-
-RAS_MeshMaterial *RAS_MeshObject::GetMeshMaterial(RAS_IPolyMaterial *mat)
-{
- list<RAS_MeshMaterial>::iterator mit;
-
- /* find a mesh material */
- for (mit = m_materials.begin(); mit != m_materials.end(); mit++)
- if (mit->m_bucket->GetPolyMaterial() == mat)
- return &*mit;
-
- return NULL;
-}
-
-int RAS_MeshObject::GetMaterialId(RAS_IPolyMaterial *mat)
-{
- list<RAS_MeshMaterial>::iterator mit;
- int imat;
-
- /* find a mesh material */
- for (imat=0, mit = m_materials.begin(); mit != m_materials.end(); mit++, imat++)
- if (mit->m_bucket->GetPolyMaterial() == mat)
- return imat;
-
- return -1;
-}
-
-RAS_Polygon* RAS_MeshObject::AddPolygon(RAS_MaterialBucket *bucket, int numverts)
-{
- RAS_MeshMaterial *mmat;
- RAS_Polygon *poly;
- RAS_MeshSlot *slot;
-
- /* find a mesh material */
- mmat = GetMeshMaterial(bucket->GetPolyMaterial());
-
- /* none found, create a new one */
- if (!mmat) {
- RAS_MeshMaterial meshmat;
- meshmat.m_bucket = bucket;
- meshmat.m_baseslot = meshmat.m_bucket->AddMesh(numverts);
- meshmat.m_baseslot->m_mesh = this;
- m_materials.push_back(meshmat);
- mmat = &m_materials.back();
- }
-
- /* add it to the bucket, this also adds new display arrays */
- slot = mmat->m_baseslot;
- slot->AddPolygon(numverts);
-
- /* create a new polygon */
- RAS_DisplayArray *darray = slot->CurrentDisplayArray();
- poly = new RAS_Polygon(bucket, darray, numverts);
- m_Polygons.push_back(poly);
-
- return poly;
-}
-
-void RAS_MeshObject::DebugColor(unsigned int abgr)
-{
- /*int numpolys = NumPolygons();
-
- for (int i=0;i<numpolys;i++) {
- RAS_Polygon* poly = m_polygons[i];
- for (int v=0;v<poly->VertexCount();v++)
- RAS_TexVert* vtx = poly->GetVertex(v)->setDebugRGBA(abgr);
- }
- */
-
- /* m_debugcolor = abgr; */
-}
-
-void RAS_MeshObject::SetVertexColor(RAS_IPolyMaterial* mat,MT_Vector4 rgba)
-{
- RAS_MeshMaterial *mmat = GetMeshMaterial(mat);
- RAS_MeshSlot *slot = mmat->m_baseslot;
- RAS_MeshSlot::iterator it;
- size_t i;
-
- for (slot->begin(it); !slot->end(it); slot->next(it))
- for (i=it.startvertex; i<it.endvertex; i++)
- it.vertex[i].SetRGBA(rgba);
-}
-
-void RAS_MeshObject::AddVertex(RAS_Polygon *poly, int i,
- const MT_Point3& xyz,
- const MT_Point2 uvs[RAS_TexVert::MAX_UNIT],
- const MT_Vector4& tangent,
- const unsigned int rgba,
- const MT_Vector3& normal,
- bool flat,
- int origindex)
-{
- RAS_TexVert texvert(xyz, uvs, tangent, rgba, normal, flat, origindex);
- RAS_MeshMaterial *mmat;
- RAS_DisplayArray *darray;
- RAS_MeshSlot *slot;
- int offset;
-
- mmat = GetMeshMaterial(poly->GetMaterial()->GetPolyMaterial());
- slot = mmat->m_baseslot;
- darray = slot->CurrentDisplayArray();
-
- { /* Shared Vertex! */
- /* find vertices shared between faces, with the restriction
- * that they exist in the same display array, and have the
- * same uv coordinate etc */
- vector<SharedVertex>& sharedmap = m_sharedvertex_map[origindex];
- vector<SharedVertex>::iterator it;
-
- for (it = sharedmap.begin(); it != sharedmap.end(); it++)
- {
- if (it->m_darray != darray)
- continue;
- if (!it->m_darray->m_vertex[it->m_offset].closeTo(&texvert))
- continue;
-
- /* found one, add it and we're done */
- if (poly->IsVisible())
- slot->AddPolygonVertex(it->m_offset);
- poly->SetVertexOffset(i, it->m_offset);
- return;
- }
- }
-
- /* no shared vertex found, add a new one */
- offset = slot->AddVertex(texvert);
- if (poly->IsVisible())
- slot->AddPolygonVertex(offset);
- poly->SetVertexOffset(i, offset);
-
- { /* Shared Vertex! */
- SharedVertex shared;
- shared.m_darray = darray;
- shared.m_offset = offset;
- m_sharedvertex_map[origindex].push_back(shared);
- }
-}
-
-int RAS_MeshObject::NumVertices(RAS_IPolyMaterial* mat)
-{
- RAS_MeshMaterial *mmat;
- RAS_MeshSlot *slot;
- RAS_MeshSlot::iterator it;
- size_t len = 0;
-
- mmat = GetMeshMaterial(mat);
- slot = mmat->m_baseslot;
- for (slot->begin(it); !slot->end(it); slot->next(it))
- len += it.endvertex - it.startvertex;
-
- return len;
-}
-
-
-RAS_TexVert* RAS_MeshObject::GetVertex(unsigned int matid,
- unsigned int index)
-{
- RAS_MeshMaterial *mmat;
- RAS_MeshSlot *slot;
- RAS_MeshSlot::iterator it;
- size_t len;
-
- mmat = GetMeshMaterial(matid);
-
- if (!mmat)
- return NULL;
-
- slot = mmat->m_baseslot;
- len = 0;
- for (slot->begin(it); !slot->end(it); slot->next(it)) {
- if (index >= len + it.endvertex - it.startvertex)
- len += it.endvertex - it.startvertex;
- else
- return &it.vertex[index - len];
- }
-
- return NULL;
-}
-
-const float* RAS_MeshObject::GetVertexLocation(unsigned int orig_index)
-{
- vector<SharedVertex>& sharedmap = m_sharedvertex_map[orig_index];
- vector<SharedVertex>::iterator it= sharedmap.begin();
- return it->m_darray->m_vertex[it->m_offset].getXYZ();
-}
-
-void RAS_MeshObject::AddMeshUser(void *clientobj, SG_QList *head, RAS_Deformer* deformer)
-{
- list<RAS_MeshMaterial>::iterator it;
- list<RAS_MeshMaterial>::iterator mit;
-
- for (it = m_materials.begin();it!=m_materials.end();++it) {
- /* always copy from the base slot, which is never removed
- * since new objects can be created with the same mesh data */
- if (deformer && !deformer->UseVertexArray())
- {
- // HACK!
- // this deformer doesn't use vertex array => derive mesh
- // we must keep only the mesh slots that have unique material id
- // this is to match the derived mesh drawing function
- // Need a better solution in the future: scan the derive mesh and create vertex array
- RAS_IPolyMaterial* curmat = it->m_bucket->GetPolyMaterial();
- if (curmat->GetFlag() & RAS_BLENDERGLSL)
- {
- for (mit = m_materials.begin(); mit != it; ++mit)
- {
- RAS_IPolyMaterial* mat = mit->m_bucket->GetPolyMaterial();
- if ((mat->GetFlag() & RAS_BLENDERGLSL) &&
- mat->GetMaterialIndex() == curmat->GetMaterialIndex())
- // no need to convert current mesh slot
- break;
- }
- if (mit != it)
- continue;
- }
- }
- RAS_MeshSlot *ms = it->m_bucket->CopyMesh(it->m_baseslot);
- ms->m_clientObj = clientobj;
- ms->SetDeformer(deformer);
- it->m_slots.insert(clientobj, ms);
- head->QAddBack(ms);
- }
-}
-
-void RAS_MeshObject::RemoveFromBuckets(void *clientobj)
-{
- list<RAS_MeshMaterial>::iterator it;
-
- for (it = m_materials.begin();it!=m_materials.end();++it) {
- RAS_MeshSlot **msp = it->m_slots[clientobj];
-
- if (!msp)
- continue;
-
- RAS_MeshSlot *ms = *msp;
-
- it->m_bucket->RemoveMesh(ms);
- it->m_slots.remove(clientobj);
- }
-}
-
-void RAS_MeshObject::EndConversion()
-{
-#if 0
- m_sharedvertex_map.clear(); // SharedVertex
- vector<vector<SharedVertex> > shared_null(0);
- shared_null.swap( m_sharedvertex_map ); /* really free the memory */
-#endif
-
- for (std::list<RAS_MeshMaterial>::iterator it = m_materials.begin();
- it != m_materials.end();
- ++it)
- {
- RAS_MeshSlot *ms = it->m_baseslot;
- ms->UpdateDisplayArraysOffset();
- }
-}
-
-//void RAS_MeshObject::Transform(const MT_Transform& trans)
-//{
- //m_trans.translate(MT_Vector3(0,0,1));//.operator *=(trans);
-
-// for (int i=0;i<m_Polygons.size();i++)
-// {
-// m_Polygons[i]->Transform(trans);
-// }
-//}
-
-
-/*
-void RAS_MeshObject::RelativeTransform(const MT_Vector3& vec)
-{
- for (int i=0;i<m_Polygons.size();i++)
- {
- m_Polygons[i]->RelativeTransform(vec);
- }
-}
-*/
-
-void RAS_MeshObject::SortPolygons(RAS_MeshSlot& ms, const MT_Transform &transform)
-{
- // Limitations: sorting is quite simple, and handles many
- // cases wrong, partially due to polygons being sorted per
- // bucket.
- //
- // a) mixed triangles/quads are sorted wrong
- // b) mixed materials are sorted wrong
- // c) more than 65k faces are sorted wrong
- // d) intersecting objects are sorted wrong
- // e) intersecting polygons are sorted wrong
- //
- // a) can be solved by making all faces either triangles or quads
- // if they need to be z-sorted. c) could be solved by allowing
- // larger buckets, b) and d) cannot be solved easily if we want
- // to avoid excessive state changes while drawing. e) would
- // require splitting polygons.
-
- RAS_MeshSlot::iterator it;
- size_t j;
-
- for (ms.begin(it); !ms.end(it); ms.next(it)) {
- unsigned int nvert = (int)it.array->m_type;
- unsigned int totpoly = it.totindex/nvert;
-
- if (totpoly <= 1)
- continue;
- if (it.array->m_type == RAS_DisplayArray::LINE)
- continue;
-
- // Extract camera Z plane...
- const MT_Vector3 pnorm(transform.getBasis()[2]);
- // unneeded: const MT_Scalar pval = transform.getOrigin()[2];
-
- vector<polygonSlot> poly_slots(totpoly);
-
- /* get indices and z into temporary array */
- for (j=0; j<totpoly; j++)
- poly_slots[j].get(it.vertex, it.index, j*nvert, nvert, pnorm);
-
- /* sort (stable_sort might be better, if flickering happens?) */
- std::sort(poly_slots.begin(), poly_slots.end(), backtofront());
-
- /* get indices from temporary array again */
- for (j=0; j<totpoly; j++)
- poly_slots[j].set(it.index, j*nvert, nvert);
- }
-}
-
-
-bool RAS_MeshObject::HasColliderPolygon()
-{
- int numpolys= NumPolygons();
- for (int p=0; p<numpolys; p++)
- if (m_Polygons[p]->IsCollider())
- return true;
-
- return false;
-}
-
-void RAS_MeshObject::SchedulePolygons(int drawingmode)
-{
- if (m_bModified)
- {
- m_bModified = false;
- m_bMeshModified = true;
- }
-}
diff --git a/source/gameengine/Rasterizer/RAS_MeshObject.h b/source/gameengine/Rasterizer/RAS_MeshObject.h
deleted file mode 100644
index a6f1a1cafc6..00000000000
--- a/source/gameengine/Rasterizer/RAS_MeshObject.h
+++ /dev/null
@@ -1,161 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file RAS_MeshObject.h
- * \ingroup bgerast
- */
-
-#ifndef __RAS_MESHOBJECT_H__
-#define __RAS_MESHOBJECT_H__
-
-#ifdef _MSC_VER
- /* disable the STL warnings ("debug information length > 255") */
-# pragma warning (disable:4786)
-#endif
-
-#include <vector>
-#include <list>
-
-#include "RAS_MaterialBucket.h"
-#include "MT_Transform.h"
-#include "STR_String.h"
-
-struct Mesh;
-class RAS_Deformer;
-class RAS_Polygon;
-
-/* RAS_MeshObject is a mesh used for rendering. It stores polygons,
- * but the actual vertices and index arrays are stored in material
- * buckets, referenced by the list of RAS_MeshMaterials. */
-
-class RAS_MeshObject
-{
-private:
- /* unsigned int m_debugcolor; */ /* UNUSED */
-
- bool m_bModified;
- bool m_bMeshModified;
-
- STR_String m_name;
- static STR_String s_emptyname;
-
- vector<RAS_Polygon*> m_Polygons;
-
- /* polygon sorting */
- struct polygonSlot;
- struct backtofront;
- struct fronttoback;
-
-protected:
- vector<int> m_cacheWeightIndex;
- list<RAS_MeshMaterial> m_materials;
- Mesh* m_mesh;
-
-public:
- // for now, meshes need to be in a certain layer (to avoid sorting on lights in realtime)
- RAS_MeshObject(Mesh* mesh);
- virtual ~RAS_MeshObject();
-
-
- /* materials */
- int NumMaterials();
- const STR_String& GetMaterialName(unsigned int matid);
- const STR_String& GetTextureName(unsigned int matid);
-
- RAS_MeshMaterial* GetMeshMaterial(unsigned int matid);
- RAS_MeshMaterial* GetMeshMaterial(RAS_IPolyMaterial *mat);
- int GetMaterialId(RAS_IPolyMaterial *mat);
-
- list<RAS_MeshMaterial>::iterator GetFirstMaterial();
- list<RAS_MeshMaterial>::iterator GetLastMaterial();
-
- //unsigned int GetLightLayer();
-
- /* name */
- void SetName(const char *name);
- STR_String& GetName();
-
- /* modification state */
- bool MeshModified();
- void SetMeshModified(bool v) { m_bMeshModified = v; }
-
- /* original blender mesh */
- Mesh* GetMesh() { return m_mesh; }
-
- /* mesh construction */
-
- virtual RAS_Polygon* AddPolygon(RAS_MaterialBucket *bucket, int numverts);
- virtual void AddVertex(RAS_Polygon *poly, int i,
- const MT_Point3& xyz,
- const MT_Point2 uvs[RAS_TexVert::MAX_UNIT],
- const MT_Vector4& tangent,
- const unsigned int rgbacolor,
- const MT_Vector3& normal,
- bool flat,
- int origindex);
-
- void SchedulePolygons(int drawingmode);
-
- /* vertex and polygon acces */
- int NumVertices(RAS_IPolyMaterial* mat);
- RAS_TexVert* GetVertex(unsigned int matid, unsigned int index);
- const float* GetVertexLocation(unsigned int orig_index);
-
- int NumPolygons();
- RAS_Polygon* GetPolygon(int num) const;
-
- /* buckets */
- virtual void AddMeshUser(void *clientobj, SG_QList *head, RAS_Deformer* deformer);
-
- void RemoveFromBuckets(void *clientobj);
- void EndConversion();
-
- /* colors */
- void DebugColor(unsigned int abgr);
- void SetVertexColor(RAS_IPolyMaterial* mat,MT_Vector4 rgba);
-
- /* polygon sorting by Z for alpha */
- void SortPolygons(RAS_MeshSlot& ms, const MT_Transform &transform);
-
-
- bool HasColliderPolygon();
-
- /* for construction to find shared vertices */
- struct SharedVertex {
- RAS_DisplayArray *m_darray;
- int m_offset;
- };
-
- vector<vector<SharedVertex> > m_sharedvertex_map;
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:RAS_MeshObject")
-#endif
-};
-
-#endif /* __RAS_MESHOBJECT_H__ */
diff --git a/source/gameengine/Rasterizer/RAS_ObjectColor.h b/source/gameengine/Rasterizer/RAS_ObjectColor.h
deleted file mode 100644
index 77feffccffc..00000000000
--- a/source/gameengine/Rasterizer/RAS_ObjectColor.h
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file RAS_ObjectColor.h
- * \ingroup bgerast
- */
-
-#ifndef __RAS_OBJECTCOLOR_H__
-#define __RAS_OBJECTCOLOR_H__
-
-struct RAS_ObjectColor {
- float m_red;
- float m_green;
- float m_blue;
-};
-
-#endif /* __RAS_OBJECTCOLOR_H__ */
diff --git a/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Blur2DFilter.h b/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Blur2DFilter.h
deleted file mode 100644
index 3f1644a5c60..00000000000
--- a/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Blur2DFilter.h
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file RAS_Blur2DFilter.h
- * \ingroup bgerastoglfilters
- */
-
-#ifndef __RAS_BLUR2DFILTER_H__
-#define __RAS_BLUR2DFILTER_H__
-
-static const char *BlurFragmentShader = STRINGIFY(
-uniform sampler2D bgl_RenderedTexture;
-uniform vec2 bgl_TextureCoordinateOffset[9];
-
-void main(void)
-{
- vec4 sample[9];
-
- for (int i = 0; i < 9; i++)
- {
- sample[i] = texture2D(bgl_RenderedTexture,
- gl_TexCoord[0].st + bgl_TextureCoordinateOffset[i]);
- }
-
- gl_FragColor = (sample[0] + (2.0*sample[1]) + sample[2] +
- (2.0*sample[3]) + sample[4] + (2.0*sample[5]) +
- sample[6] + (2.0*sample[7]) + sample[8]) / 13.0;
-}
-);
-#endif
-
diff --git a/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Dilation2DFilter.h b/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Dilation2DFilter.h
deleted file mode 100644
index 4e863cb6f8d..00000000000
--- a/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Dilation2DFilter.h
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file RAS_Dilation2DFilter.h
- * \ingroup bgerastoglfilters
- */
-
-#ifndef __RAS_DILATION2DFILTER_H__
-#define __RAS_DILATION2DFILTER_H__
-
-static const char *DilationFragmentShader = STRINGIFY(
-uniform sampler2D bgl_RenderedTexture;
-uniform vec2 bgl_TextureCoordinateOffset[9];
-
-void main(void)
-{
- vec4 sample[9];
- vec4 maxValue = vec4(0.0);
-
- for (int i = 0; i < 9; i++)
- {
- sample[i] = texture2D(bgl_RenderedTexture,
- gl_TexCoord[0].st + bgl_TextureCoordinateOffset[i]);
- maxValue = max(sample[i], maxValue);
- }
-
- gl_FragColor = maxValue;
-}
-);
-#endif
-
diff --git a/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Erosion2DFilter.h b/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Erosion2DFilter.h
deleted file mode 100644
index 56e2c22fe2e..00000000000
--- a/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Erosion2DFilter.h
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file RAS_Erosion2DFilter.h
- * \ingroup bgerastoglfilters
- */
-
-#ifndef __RAS_EROSION2DFILTER_H__
-#define __RAS_EROSION2DFILTER_H__
-
-static const char *ErosionFragmentShader = STRINGIFY(
-uniform sampler2D bgl_RenderedTexture;
-uniform vec2 bgl_TextureCoordinateOffset[9];
-
-void main(void)
-{
- vec4 sample[9];
- vec4 minValue = vec4(1.0);
-
- for (int i = 0; i < 9; i++)
- {
- sample[i] = texture2D(bgl_RenderedTexture,
- gl_TexCoord[0].st + bgl_TextureCoordinateOffset[i]);
- minValue = min(sample[i], minValue);
- }
-
- gl_FragColor = minValue;
-}
-);
-#endif
diff --git a/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_GrayScale2DFilter.h b/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_GrayScale2DFilter.h
deleted file mode 100644
index 932d5b16fed..00000000000
--- a/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_GrayScale2DFilter.h
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file RAS_GrayScale2DFilter.h
- * \ingroup bgerastoglfilters
- */
-
-#ifndef __RAS_GRAYSCALE2DFILTER_H__
-#define __RAS_GRAYSCALE2DFILTER_H__
-
-static const char *GrayScaleFragmentShader = STRINGIFY(
-uniform sampler2D bgl_RenderedTexture;
-
-void main(void)
-{
- vec4 texcolor = texture2D(bgl_RenderedTexture, gl_TexCoord[0].st);
- float gray = dot(texcolor.rgb, vec3(0.299, 0.587, 0.114));
- gl_FragColor = vec4(gray, gray, gray, texcolor.a);
-}
-);
-#endif
diff --git a/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Invert2DFilter.h b/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Invert2DFilter.h
deleted file mode 100644
index dce303916ea..00000000000
--- a/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Invert2DFilter.h
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file RAS_Invert2DFilter.h
- * \ingroup bgerastoglfilters
- */
-
-#ifndef __RAS_INVERT2DFILTER_H__
-#define __RAS_INVERT2DFILTER_H__
-
-static const char *InvertFragmentShader = STRINGIFY(
-uniform sampler2D bgl_RenderedTexture;
-
-void main(void)
-{
- vec4 texcolor = texture2D(bgl_RenderedTexture, gl_TexCoord[0].st);
- gl_FragColor.rgb = 1.0 - texcolor.rgb;
- gl_FragColor.a = texcolor.a;
-}
-);
-#endif
diff --git a/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Laplacian2DFilter.h b/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Laplacian2DFilter.h
deleted file mode 100644
index 9ec5092817d..00000000000
--- a/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Laplacian2DFilter.h
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file RAS_Laplacian2DFilter.h
- * \ingroup bgerastoglfilters
- */
-
-#ifndef __RAS_LAPLACIAN2DFILTER_H__
-#define __RAS_LAPLACIAN2DFILTER_H__
-
-static const char *LaplacionFragmentShader = STRINGIFY(
-uniform sampler2D bgl_RenderedTexture;
-uniform vec2 bgl_TextureCoordinateOffset[9];
-
-void main(void)
-{
- vec4 sample[9];
-
- for (int i = 0; i < 9; i++)
- {
- sample[i] = texture2D(bgl_RenderedTexture,
- gl_TexCoord[0].st + bgl_TextureCoordinateOffset[i]);
- }
-
- gl_FragColor = (sample[4] * 8.0) -
- (sample[0] + sample[1] + sample[2] +
- sample[3] + sample[5] +
- sample[6] + sample[7] + sample[8]);
- gl_FragColor = vec4(gl_FragColor.rgb, 1.0);
-}
-);
-#endif
-
diff --git a/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Prewitt2DFilter.h b/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Prewitt2DFilter.h
deleted file mode 100644
index 4ae6009fdeb..00000000000
--- a/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Prewitt2DFilter.h
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file RAS_Prewitt2DFilter.h
- * \ingroup bgerastoglfilters
- */
-
-#ifndef __RAS_PREWITT2DFILTER_H__
-#define __RAS_PREWITT2DFILTER_H__
-
-static const char *PrewittFragmentShader = STRINGIFY(
-uniform sampler2D bgl_RenderedTexture;
-uniform vec2 bgl_TextureCoordinateOffset[9];
-
-void main(void)
-{
- vec4 sample[9];
-
- for (int i = 0; i < 9; i++)
- {
- sample[i] = texture2D(bgl_RenderedTexture,
- gl_TexCoord[0].st + bgl_TextureCoordinateOffset[i]);
- }
-
- vec4 horizEdge = sample[2] + sample[5] + sample[8] -
- (sample[0] + sample[3] + sample[6]);
-
- vec4 vertEdge = sample[0] + sample[1] + sample[2] -
- (sample[6] + sample[7] + sample[8]);
-
- gl_FragColor.rgb = sqrt((horizEdge.rgb * horizEdge.rgb) +
- (vertEdge.rgb * vertEdge.rgb));
- gl_FragColor.a = 1.0;
-}
-
-);
-#endif
-
diff --git a/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Sepia2DFilter.h b/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Sepia2DFilter.h
deleted file mode 100644
index 16b4e71dfdb..00000000000
--- a/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Sepia2DFilter.h
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file RAS_Sepia2DFilter.h
- * \ingroup bgerastoglfilters
- */
-
-#ifndef __RAS_SEPIA2DFILTER_H__
-#define __RAS_SEPIA2DFILTER_H__
-
-static const char *SepiaFragmentShader = STRINGIFY(
-uniform sampler2D bgl_RenderedTexture;
-
-void main(void)
-{
- vec4 texcolor = texture2D(bgl_RenderedTexture, gl_TexCoord[0].st);
- float gray = dot(texcolor.rgb, vec3(0.299, 0.587, 0.114));
- gl_FragColor = vec4(gray * vec3(1.2, 1.0, 0.8), texcolor.a);
-}
-);
-#endif
diff --git a/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Sharpen2DFilter.h b/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Sharpen2DFilter.h
deleted file mode 100644
index 7512393815b..00000000000
--- a/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Sharpen2DFilter.h
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file RAS_Sharpen2DFilter.h
- * \ingroup bgerastoglfilters
- */
-
-#ifndef __RAS_SHARPEN2DFILTER_H__
-#define __RAS_SHARPEN2DFILTER_H__
-
-static const char *SharpenFragmentShader = STRINGIFY(
-uniform sampler2D bgl_RenderedTexture;
-uniform vec2 bgl_TextureCoordinateOffset[9];
-
-void main(void)
-{
- vec4 sample[9];
-
- for (int i = 0; i < 9; i++)
- {
- sample[i] = texture2D(bgl_RenderedTexture,
- gl_TexCoord[0].st + bgl_TextureCoordinateOffset[i]);
- }
-
- gl_FragColor = (sample[4] * 9.0) -
- (sample[0] + sample[1] + sample[2] +
- sample[3] + sample[5] +
- sample[6] + sample[7] + sample[8]);
-}
-);
-#endif
diff --git a/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Sobel2DFilter.h b/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Sobel2DFilter.h
deleted file mode 100644
index 088ac10a56a..00000000000
--- a/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Sobel2DFilter.h
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file RAS_Sobel2DFilter.h
- * \ingroup bgerastoglfilters
- */
-
-#ifndef __RAS_SOBEL2DFILTER_H__
-#define __RAS_SOBEL2DFILTER_H__
-
-static const char *SobelFragmentShader = STRINGIFY(
-uniform sampler2D bgl_RenderedTexture;
-uniform vec2 bgl_TextureCoordinateOffset[9];
-
-void main(void)
-{
- vec4 sample[9];
-
- for (int i = 0; i < 9; i++)
- {
- sample[i] = texture2D(bgl_RenderedTexture,
- gl_TexCoord[0].st + bgl_TextureCoordinateOffset[i]);
- }
-
- vec4 horizEdge = sample[2] + (2.0*sample[5]) + sample[8] -
- (sample[0] + (2.0*sample[3]) + sample[6]);
-
- vec4 vertEdge = sample[0] + (2.0*sample[1]) + sample[2] -
- (sample[6] + (2.0*sample[7]) + sample[8]);
-
- gl_FragColor.rgb = sqrt((horizEdge.rgb * horizEdge.rgb) +
- (vertEdge.rgb * vertEdge.rgb));
- gl_FragColor.a = 1.0;
-}
-);
-#endif
-
diff --git a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/CMakeLists.txt b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/CMakeLists.txt
deleted file mode 100644
index 89e31b62b41..00000000000
--- a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/CMakeLists.txt
+++ /dev/null
@@ -1,72 +0,0 @@
-# ***** BEGIN GPL LICENSE BLOCK *****
-#
-# This program is free software; you can redistribute it and/or
-# modify it under the terms of the GNU General Public License
-# as published by the Free Software Foundation; either version 2
-# of the License, or (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software Foundation,
-# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
-#
-# The Original Code is Copyright (C) 2006, Blender Foundation
-# All rights reserved.
-#
-# The Original Code is: all of this file.
-#
-# Contributor(s): Jacques Beaurain.
-#
-# ***** END GPL LICENSE BLOCK *****
-
-set(INC
- ..
- # XXX Remove these <<<
- ../../BlenderRoutines
- ../../Expressions
- ../../GameLogic
- ../../Ketsji
- ../../Physics/common
- # >>>
- ../../SceneGraph
- ../../../blender/blenfont
- ../../../blender/blenkernel
- ../../../blender/blenlib
- ../../../blender/gpu
- ../../../blender/makesdna
- ../../../../intern/container
- ../../../../intern/glew-mx
- ../../../../intern/string
-)
-
-set(INC_SYS
- ../../../../intern/moto/include
- ${GLEW_INCLUDE_PATH}
-)
-
-set(SRC
- RAS_ListRasterizer.cpp
- RAS_OpenGLLight.cpp
- RAS_OpenGLOffScreen.cpp
- RAS_OpenGLSync.cpp
- RAS_OpenGLRasterizer.cpp
- RAS_StorageVA.cpp
- RAS_StorageVBO.cpp
-
- RAS_IStorage.h
- RAS_ListRasterizer.h
- RAS_OpenGLLight.h
- RAS_OpenGLOffScreen.h
- RAS_OpenGLSync.h
- RAS_OpenGLRasterizer.h
- RAS_StorageVA.h
- RAS_StorageVBO.h
-)
-
-add_definitions(${GL_DEFINITIONS})
-
-blender_add_lib(ge_oglrasterizer "${SRC}" "${INC}" "${INC_SYS}")
diff --git a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_IStorage.h b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_IStorage.h
deleted file mode 100644
index ae0cdcd84af..00000000000
--- a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_IStorage.h
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-#ifndef __KX_STORAGE
-#define __KX_STORAGE
-
-#ifdef WITH_CXX_GUARDEDALLOC
- #include "MEM_guardedalloc.h"
-#endif
-
-class RAS_MeshSlot;
-
-class RAS_IStorage
-{
-
-public:
- virtual ~RAS_IStorage() {};
-
- virtual bool Init()=0;
- virtual void Exit()=0;
-
- virtual void IndexPrimitives(RAS_MeshSlot& ms)=0;
-
- virtual void SetDrawingMode(int drawingmode)=0;
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:RAS_IStorage")
-#endif
-};
-
-#endif //__KX_STORAGE
diff --git a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_ListRasterizer.cpp b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_ListRasterizer.cpp
deleted file mode 100644
index 71c8cfe745f..00000000000
--- a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_ListRasterizer.cpp
+++ /dev/null
@@ -1,278 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_ListRasterizer.cpp
- * \ingroup bgerastogl
- */
-
-#include <iostream>
-
-#include "RAS_ListRasterizer.h"
-
-#ifdef WIN32
-#include <windows.h>
-#endif // WIN32
-
-#include "GPU_glew.h"
-
-#include "RAS_MaterialBucket.h"
-#include "RAS_TexVert.h"
-#include "MT_assert.h"
-
-//#if defined(DEBUG)
-//#ifdef WIN32
-//#define spit(x) std::cout << x << std::endl;
-//#endif //WIN32
-//#else
-#define spit(x)
-//#endif
-
-RAS_ListSlot::RAS_ListSlot(RAS_ListRasterizer* rasty)
-: KX_ListSlot(),
- m_list(0),
- m_flag(LIST_MODIFY|LIST_CREATE),
- m_matnr(0),
- m_rasty(rasty)
-{
-}
-
-int RAS_ListSlot::Release()
-{
- if (--m_refcount > 0)
- return m_refcount;
- m_rasty->RemoveListSlot(this);
- delete this;
- return 0;
-}
-
-RAS_ListSlot::~RAS_ListSlot()
-{
- RemoveList();
-}
-
-
-void RAS_ListSlot::RemoveList()
-{
- if (m_list != 0) {
- spit("Releasing display list (" << m_list << ")");
- glDeleteLists((GLuint)m_list, 1);
- m_list =0;
- }
-}
-
-void RAS_ListSlot::DrawList()
-{
- if (m_flag &LIST_MODIFY) {
- if (m_flag &LIST_CREATE) {
- if (m_list == 0) {
- m_list = (unsigned int)glGenLists(1);
- m_flag = m_flag &~ LIST_CREATE;
- spit("Created display list (" << m_list << ")");
- }
- }
- if (m_list != 0)
- glNewList((GLuint)m_list, GL_COMPILE);
-
- m_flag |= LIST_BEGIN;
- return;
- }
- glCallList(m_list);
-}
-
-void RAS_ListSlot::EndList()
-{
- if (m_flag & LIST_BEGIN) {
- glEndList();
- m_flag = m_flag &~(LIST_BEGIN|LIST_MODIFY);
- m_flag |= LIST_END;
- glCallList(m_list);
- }
-}
-
-void RAS_ListSlot::SetModified(bool mod)
-{
- if (mod && !(m_flag & LIST_MODIFY)) {
- spit("Modifying list (" << m_list << ")");
- m_flag = m_flag &~ LIST_END;
- m_flag |= LIST_MODIFY;
- }
-}
-
-bool RAS_ListSlot::End()
-{
- return (m_flag &LIST_END)!=0;
-}
-
-
-
-RAS_ListRasterizer::RAS_ListRasterizer(RAS_ICanvas* canvas, bool lock, RAS_STORAGE_TYPE storage)
-: RAS_OpenGLRasterizer(canvas, storage)
-{
-}
-
-RAS_ListRasterizer::~RAS_ListRasterizer()
-{
- ReleaseAlloc();
-}
-
-void RAS_ListRasterizer::RemoveListSlot(RAS_ListSlot* list)
-{
- if (list->m_flag & LIST_DERIVEDMESH) {
- RAS_DerivedMeshLists::iterator it = mDerivedMeshLists.begin();
- while (it != mDerivedMeshLists.end()) {
- RAS_ListSlots *slots = it->second;
- if (slots->size() > list->m_matnr && slots->at(list->m_matnr) == list) {
- (*slots)[list->m_matnr] = NULL;
- // check if all slots are NULL and if yes, delete the entry
- int i;
- for (i=slots->size(); i-- > 0; ) {
- if (slots->at(i) != NULL)
- break;
- }
- if (i < 0) {
- slots->clear();
- delete slots;
- mDerivedMeshLists.erase(it);
- }
- break;
- }
- ++it;
- }
- } else {
- RAS_ArrayLists::iterator it = mArrayLists.begin();
- while (it != mArrayLists.end()) {
- if (it->second == list) {
- mArrayLists.erase(it);
- break;
- }
- it++;
- }
- }
-}
-
-RAS_ListSlot* RAS_ListRasterizer::FindOrAdd(RAS_MeshSlot& ms)
-{
- /*
- * Keep a copy of constant lists submitted for rendering,
- * this guards against (replicated)new...delete every frame,
- * and we can reuse lists!
- * :: sorted by mesh slot
- */
- RAS_ListSlot* localSlot = (RAS_ListSlot*)ms.m_DisplayList;
- if (!localSlot) {
- if (ms.m_pDerivedMesh) {
- // that means that we draw based on derived mesh, a display list is possible
- // Note that we come here only for static derived mesh
- int matnr = ms.m_bucket->GetPolyMaterial()->GetMaterialIndex();
- RAS_ListSlot* nullSlot = NULL;
- RAS_ListSlots *listVector;
- RAS_DerivedMeshLists::iterator it = mDerivedMeshLists.find(ms.m_pDerivedMesh);
- if (it == mDerivedMeshLists.end()) {
- listVector = new RAS_ListSlots(matnr+4, nullSlot);
- localSlot = new RAS_ListSlot(this);
- localSlot->m_flag |= LIST_DERIVEDMESH;
- localSlot->m_matnr = matnr;
- listVector->at(matnr) = localSlot;
- mDerivedMeshLists.insert(std::pair<DerivedMesh*, RAS_ListSlots*>(ms.m_pDerivedMesh, listVector));
- } else {
- listVector = it->second;
- if (listVector->size() <= matnr)
- listVector->resize(matnr+4, nullSlot);
- if ((localSlot = listVector->at(matnr)) == NULL) {
- localSlot = new RAS_ListSlot(this);
- localSlot->m_flag |= LIST_DERIVEDMESH;
- localSlot->m_matnr = matnr;
- listVector->at(matnr) = localSlot;
- } else {
- localSlot->AddRef();
- }
- }
- } else {
- RAS_ArrayLists::iterator it = mArrayLists.find(ms.m_displayArrays);
- if (it == mArrayLists.end()) {
- localSlot = new RAS_ListSlot(this);
- mArrayLists.insert(std::pair<RAS_DisplayArrayList, RAS_ListSlot*>(ms.m_displayArrays, localSlot));
- } else {
- localSlot = static_cast<RAS_ListSlot*>(it->second->AddRef());
- }
- }
- }
- MT_assert(localSlot);
- return localSlot;
-}
-
-void RAS_ListRasterizer::ReleaseAlloc()
-{
- for (RAS_ArrayLists::iterator it = mArrayLists.begin();it != mArrayLists.end();++it)
- delete it->second;
- mArrayLists.clear();
- for (RAS_DerivedMeshLists::iterator it = mDerivedMeshLists.begin();it != mDerivedMeshLists.end();++it) {
- RAS_ListSlots* slots = it->second;
- for (int i=slots->size(); i-- > 0; ) {
- RAS_ListSlot* slot = slots->at(i);
- if (slot)
- delete slot;
- }
- slots->clear();
- delete slots;
- }
- mDerivedMeshLists.clear();
-}
-
-void RAS_ListRasterizer::IndexPrimitives(RAS_MeshSlot& ms)
-{
- RAS_ListSlot* localSlot =0;
-
- if (ms.m_bDisplayList) {
- localSlot = FindOrAdd(ms);
- localSlot->DrawList();
-
- if (localSlot->End()) {
- // save slot here too, needed for replicas and object using same mesh
- // => they have the same vertexarray but different mesh slot
- ms.m_DisplayList = localSlot;
- return;
- }
- }
-
- RAS_OpenGLRasterizer::IndexPrimitives(ms);
-
- if (ms.m_bDisplayList) {
- localSlot->EndList();
- ms.m_DisplayList = localSlot;
- }
-}
-
-bool RAS_ListRasterizer::Init(void)
-{
- return RAS_OpenGLRasterizer::Init();
-}
-
-void RAS_ListRasterizer::SetDrawingMode(int drawingmode)
-{
- RAS_OpenGLRasterizer::SetDrawingMode(drawingmode);
-}
-
-void RAS_ListRasterizer::Exit()
-{
- RAS_OpenGLRasterizer::Exit();
-}
-
-// eof
diff --git a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_ListRasterizer.h b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_ListRasterizer.h
deleted file mode 100644
index e3e6931311b..00000000000
--- a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_ListRasterizer.h
+++ /dev/null
@@ -1,77 +0,0 @@
-
-/** \file RAS_ListRasterizer.h
- * \ingroup bgerastogl
- */
-
-#ifndef __RAS_LISTRASTERIZER_H__
-#define __RAS_LISTRASTERIZER_H__
-
-#include "RAS_MaterialBucket.h"
-#include "RAS_OpenGLRasterizer.h"
-#include <vector>
-#include <map>
-
-class RAS_ListRasterizer;
-class RAS_ListSlot : public KX_ListSlot
-{
- friend class RAS_ListRasterizer;
- unsigned int m_list;
- unsigned int m_flag;
- unsigned int m_matnr;
- RAS_ListRasterizer* m_rasty;
-public:
- RAS_ListSlot(RAS_ListRasterizer* rasty);
- virtual ~RAS_ListSlot();
- virtual void SetModified(bool mod);
- virtual int Release();
-
- void RemoveList();
- void DrawList();
- void EndList();
- bool End();
-
-};
-
-enum RAS_ListSlotFlags {
- LIST_CREATE =1,
- LIST_MODIFY =2,
- LIST_BEGIN =4,
- LIST_END =8,
- LIST_DERIVEDMESH=16,
-};
-
-struct DerivedMesh;
-
-typedef std::map<RAS_DisplayArrayList, RAS_ListSlot*> RAS_ArrayLists;
-typedef std::vector<RAS_ListSlot*> RAS_ListSlots; // indexed by material slot number
-typedef std::map<DerivedMesh*, RAS_ListSlots*> RAS_DerivedMeshLists;
-
-class RAS_ListRasterizer : public RAS_OpenGLRasterizer
-{
- RAS_ArrayLists mArrayLists;
- RAS_DerivedMeshLists mDerivedMeshLists;
-
- RAS_ListSlot* FindOrAdd(class RAS_MeshSlot& ms);
- void ReleaseAlloc();
-
-public:
- void RemoveListSlot(RAS_ListSlot* list);
- RAS_ListRasterizer(RAS_ICanvas* canvas, bool lock, RAS_STORAGE_TYPE storage);
- virtual ~RAS_ListRasterizer();
-
- virtual void IndexPrimitives(class RAS_MeshSlot& ms);
-
- virtual bool Init();
- virtual void Exit();
-
- virtual void SetDrawingMode(int drawingmode);
-
- virtual bool QueryLists() {return true;}
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:RAS_ListRasterizer")
-#endif
-};
-
-#endif
diff --git a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLLight.cpp b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLLight.cpp
deleted file mode 100644
index 18254357f85..00000000000
--- a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLLight.cpp
+++ /dev/null
@@ -1,300 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): Mitchell Stokes
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-#include "GPU_glew.h"
-
-#include <stdio.h>
-
-
-#include "RAS_OpenGLLight.h"
-#include "RAS_OpenGLRasterizer.h"
-#include "RAS_ICanvas.h"
-
-#include "MT_CmMatrix4x4.h"
-
-#include "KX_Camera.h"
-#include "KX_Light.h"
-#include "KX_Scene.h"
-
-#include "DNA_lamp_types.h"
-#include "DNA_scene_types.h"
-
-#include "GPU_lamp.h"
-#include "GPU_material.h"
-
-RAS_OpenGLLight::RAS_OpenGLLight(RAS_OpenGLRasterizer *ras)
- :m_rasterizer(ras)
-{
-}
-
-RAS_OpenGLLight::~RAS_OpenGLLight()
-{
- GPULamp *lamp;
- KX_LightObject* kxlight = (KX_LightObject*)m_light;
- Lamp *la = (Lamp*)kxlight->GetBlenderObject()->data;
-
- if ((lamp = GetGPULamp())) {
- float obmat[4][4] = {{0}};
- GPU_lamp_update(lamp, 0, 0, obmat);
- GPU_lamp_update_distance(lamp, la->dist, la->att1, la->att2, la->coeff_const, la->coeff_lin, la->coeff_quad);
- GPU_lamp_update_spot(lamp, la->spotsize, la->spotblend);
- }
-}
-
-bool RAS_OpenGLLight::ApplyFixedFunctionLighting(KX_Scene *kxscene, int oblayer, int slot)
-{
- KX_Scene* lightscene = (KX_Scene*)m_scene;
- KX_LightObject* kxlight = (KX_LightObject*)m_light;
- float vec[4];
- int scenelayer = ~0;
-
- if (kxscene && kxscene->GetBlenderScene())
- scenelayer = kxscene->GetBlenderScene()->lay;
-
- /* only use lights in the same layer as the object */
- if (!(m_layer & oblayer))
- return false;
- /* only use lights in the same scene, and in a visible layer */
- if (kxscene != lightscene || !(m_layer & scenelayer))
- return false;
-
- // lights don't get their openGL matrix updated, do it now
- if (kxlight->GetSGNode()->IsDirty())
- kxlight->GetOpenGLMatrix();
-
- MT_CmMatrix4x4& worldmatrix= *kxlight->GetOpenGLMatrixPtr();
-
- vec[0] = worldmatrix(0,3);
- vec[1] = worldmatrix(1,3);
- vec[2] = worldmatrix(2,3);
- vec[3] = 1.0f;
-
- if (m_type==RAS_ILightObject::LIGHT_SUN) {
-
- vec[0] = worldmatrix(0,2);
- vec[1] = worldmatrix(1,2);
- vec[2] = worldmatrix(2,2);
- //vec[0] = base->object->obmat[2][0];
- //vec[1] = base->object->obmat[2][1];
- //vec[2] = base->object->obmat[2][2];
- vec[3] = 0.0f;
- glLightfv((GLenum)(GL_LIGHT0+slot), GL_POSITION, vec);
- }
- else {
- //vec[3] = 1.0f;
- glLightfv((GLenum)(GL_LIGHT0+slot), GL_POSITION, vec);
- glLightf((GLenum)(GL_LIGHT0+slot), GL_CONSTANT_ATTENUATION, 1.0f);
- glLightf((GLenum)(GL_LIGHT0+slot), GL_LINEAR_ATTENUATION, m_att1/m_distance);
- // without this next line it looks backward compatible.
- //attennuation still is acceptable
- glLightf((GLenum)(GL_LIGHT0+slot), GL_QUADRATIC_ATTENUATION, m_att2/(m_distance*m_distance));
-
- if (m_type==RAS_ILightObject::LIGHT_SPOT) {
- vec[0] = -worldmatrix(0,2);
- vec[1] = -worldmatrix(1,2);
- vec[2] = -worldmatrix(2,2);
- //vec[0] = -base->object->obmat[2][0];
- //vec[1] = -base->object->obmat[2][1];
- //vec[2] = -base->object->obmat[2][2];
- glLightfv((GLenum)(GL_LIGHT0+slot), GL_SPOT_DIRECTION, vec);
- glLightf((GLenum)(GL_LIGHT0+slot), GL_SPOT_CUTOFF, m_spotsize / 2.0f);
- glLightf((GLenum)(GL_LIGHT0+slot), GL_SPOT_EXPONENT, 128.0f * m_spotblend);
- }
- else {
- glLightf((GLenum)(GL_LIGHT0+slot), GL_SPOT_CUTOFF, 180.0f);
- }
- }
-
- if (m_nodiffuse) {
- vec[0] = vec[1] = vec[2] = vec[3] = 0.0f;
- }
- else {
- vec[0] = m_energy*m_color[0];
- vec[1] = m_energy*m_color[1];
- vec[2] = m_energy*m_color[2];
- vec[3] = 1.0f;
- }
-
- glLightfv((GLenum)(GL_LIGHT0+slot), GL_DIFFUSE, vec);
- if (m_nospecular)
- {
- vec[0] = vec[1] = vec[2] = vec[3] = 0.0f;
- }
- else if (m_nodiffuse) {
- vec[0] = m_energy*m_color[0];
- vec[1] = m_energy*m_color[1];
- vec[2] = m_energy*m_color[2];
- vec[3] = 1.0f;
- }
-
- glLightfv((GLenum)(GL_LIGHT0+slot), GL_SPECULAR, vec);
- glEnable((GLenum)(GL_LIGHT0+slot));
-
- return true;
-}
-
-GPULamp *RAS_OpenGLLight::GetGPULamp()
-{
- KX_LightObject* kxlight = (KX_LightObject*)m_light;
-
- if (m_glsl)
- return GPU_lamp_from_blender(kxlight->GetScene()->GetBlenderScene(), kxlight->GetBlenderObject(), kxlight->GetBlenderGroupObject());
- else
- return NULL;
-}
-
-
-bool RAS_OpenGLLight::HasShadowBuffer()
-{
- GPULamp *lamp;
-
- if ((lamp = GetGPULamp()))
- return GPU_lamp_has_shadow_buffer(lamp);
- else
- return false;
-}
-
-int RAS_OpenGLLight::GetShadowBindCode()
-{
- GPULamp *lamp;
-
- if ((lamp = GetGPULamp()))
- return GPU_lamp_shadow_bind_code(lamp);
- return -1;
-}
-
-MT_Matrix4x4 RAS_OpenGLLight::GetShadowMatrix()
-{
- GPULamp *lamp;
-
- if ((lamp = GetGPULamp()))
- return MT_Matrix4x4(GPU_lamp_dynpersmat(lamp));
- MT_Matrix4x4 mat;
- mat.setIdentity();
- return mat;
-}
-
-int RAS_OpenGLLight::GetShadowLayer()
-{
- GPULamp *lamp;
-
- if ((lamp = GetGPULamp()))
- return GPU_lamp_shadow_layer(lamp);
- else
- return 0;
-}
-
-void RAS_OpenGLLight::BindShadowBuffer(RAS_ICanvas *canvas, KX_Camera *cam, MT_Transform& camtrans)
-{
- GPULamp *lamp;
- float viewmat[4][4], winmat[4][4];
- int winsize;
-
- /* bind framebuffer */
- lamp = GetGPULamp();
- GPU_lamp_shadow_buffer_bind(lamp, viewmat, &winsize, winmat);
-
- if (GPU_lamp_shadow_buffer_type(lamp) == LA_SHADMAP_VARIANCE)
- m_rasterizer->SetUsingOverrideShader(true);
-
- /* GPU_lamp_shadow_buffer_bind() changes the viewport, so update the canvas */
- canvas->UpdateViewPort(0, 0, winsize, winsize);
-
- /* setup camera transformation */
- MT_Matrix4x4 modelviewmat((float*)viewmat);
- MT_Matrix4x4 projectionmat((float*)winmat);
-
- MT_Transform trans = MT_Transform((float*)viewmat);
- camtrans.invert(trans);
-
- cam->SetModelviewMatrix(modelviewmat);
- cam->SetProjectionMatrix(projectionmat);
-
- cam->NodeSetLocalPosition(camtrans.getOrigin());
- cam->NodeSetLocalOrientation(camtrans.getBasis());
- cam->NodeUpdateGS(0);
-
- /* setup rasterizer transformations */
- /* SetViewMatrix may use stereomode which we temporarily disable here */
- RAS_IRasterizer::StereoMode stereomode = m_rasterizer->GetStereoMode();
- m_rasterizer->SetStereoMode(RAS_IRasterizer::RAS_STEREO_NOSTEREO);
- m_rasterizer->SetProjectionMatrix(projectionmat);
- m_rasterizer->SetViewMatrix(modelviewmat, cam->NodeGetWorldOrientation(), cam->NodeGetWorldPosition(), cam->NodeGetLocalScaling(), cam->GetCameraData()->m_perspective);
- m_rasterizer->SetStereoMode(stereomode);
-}
-
-void RAS_OpenGLLight::UnbindShadowBuffer()
-{
- GPULamp *lamp = GetGPULamp();
- GPU_lamp_shadow_buffer_unbind(lamp);
-
- if (GPU_lamp_shadow_buffer_type(lamp) == LA_SHADMAP_VARIANCE)
- m_rasterizer->SetUsingOverrideShader(false);
-}
-
-Image *RAS_OpenGLLight::GetTextureImage(short texslot)
-{
- KX_LightObject* kxlight = (KX_LightObject*)m_light;
- Lamp *la = (Lamp*)kxlight->GetBlenderObject()->data;
-
- if (texslot >= MAX_MTEX || texslot < 0)
- {
- printf("KX_LightObject::GetTextureImage(): texslot exceeds slot bounds (0-%d)\n", MAX_MTEX-1);
- return NULL;
- }
-
- if (la->mtex[texslot])
- return la->mtex[texslot]->tex->ima;
-
- return NULL;
-}
-
-void RAS_OpenGLLight::Update()
-{
- GPULamp *lamp;
- KX_LightObject* kxlight = (KX_LightObject*)m_light;
-
- if ((lamp = GetGPULamp()) != NULL && kxlight->GetSGNode()) {
- float obmat[4][4];
- // lights don't get their openGL matrix updated, do it now
- if (kxlight->GetSGNode()->IsDirty())
- kxlight->GetOpenGLMatrix();
- float *dobmat = kxlight->GetOpenGLMatrixPtr()->getPointer();
-
- for (int i=0; i<4; i++)
- for (int j=0; j<4; j++, dobmat++)
- obmat[i][j] = (float)*dobmat;
- int hide = kxlight->GetVisible() ? 0 : 1;
- GPU_lamp_update(lamp, m_layer, hide, obmat);
- GPU_lamp_update_colors(lamp, m_color[0], m_color[1],
- m_color[2], m_energy);
- GPU_lamp_update_distance(lamp, m_distance, m_att1, m_att2, m_coeff_const, m_coeff_lin, m_coeff_quad);
- GPU_lamp_update_spot(lamp, m_spotsize, m_spotblend);
- }
-}
-
-
diff --git a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLLight.h b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLLight.h
deleted file mode 100644
index a520b18c434..00000000000
--- a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLLight.h
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): Mitchell Stokes
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-#include "RAS_ILightObject.h"
-
-class RAS_OpenGLRasterizer;
-struct GPULamp;
-struct Image;
-
-class RAS_OpenGLLight : public RAS_ILightObject
-{
-
- RAS_OpenGLRasterizer *m_rasterizer;
-
- GPULamp *GetGPULamp();
-public:
- RAS_OpenGLLight(RAS_OpenGLRasterizer *ras);
- ~RAS_OpenGLLight();
-
- bool ApplyFixedFunctionLighting(KX_Scene *kxscene, int oblayer, int slot);
-
- RAS_OpenGLLight* Clone() { return new RAS_OpenGLLight(*this); }
-
- bool HasShadowBuffer();
- int GetShadowBindCode();
- MT_Matrix4x4 GetShadowMatrix();
- int GetShadowLayer();
- void BindShadowBuffer(RAS_ICanvas *canvas, KX_Camera *cam, MT_Transform& camtrans);
- void UnbindShadowBuffer();
- Image *GetTextureImage(short texslot);
- void Update();
-};
diff --git a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLOffScreen.cpp b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLOffScreen.cpp
deleted file mode 100644
index 58b3c61bd05..00000000000
--- a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLOffScreen.cpp
+++ /dev/null
@@ -1,347 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2015, Blender Foundation
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): Blender Foundation.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-#include "GPU_glew.h"
-
-#include <stdio.h>
-
-#include "RAS_OpenGLOffScreen.h"
-#include "RAS_ICanvas.h"
-
-RAS_OpenGLOffScreen::RAS_OpenGLOffScreen(RAS_ICanvas *canvas)
- :m_canvas(canvas), m_depthrb(0), m_colorrb(0), m_depthtx(0), m_colortx(0),
- m_fbo(0), m_blitfbo(0), m_blitrbo(0), m_blittex(0), m_target(RAS_OFS_RENDER_BUFFER), m_bound(false)
-{
- m_width = 0;
- m_height = 0;
- m_samples = 0;
- m_color = 0;
-}
-
-RAS_OpenGLOffScreen::~RAS_OpenGLOffScreen()
-{
- Destroy();
-}
-
-bool RAS_OpenGLOffScreen::Create(int width, int height, int samples, RAS_OFS_RENDER_TARGET target)
-{
- GLenum status;
- GLuint glo[2], fbo;
- GLint max_samples;
- GLenum textarget;
-
- if (m_fbo) {
- printf("RAS_OpenGLOffScreen::Create(): buffer exists already, destroy first\n");
- return false;
- }
- if (target != RAS_IOffScreen::RAS_OFS_RENDER_BUFFER &&
- target != RAS_IOffScreen::RAS_OFS_RENDER_TEXTURE)
- {
- printf("RAS_OpenGLOffScreen::Create(): invalid offscren target\n");
- return false;
- }
- if (!GLEW_EXT_framebuffer_object) {
- printf("RAS_OpenGLOffScreen::Create(): frame buffer not supported\n");
- return false;
- }
- if (samples) {
- if (!GLEW_EXT_framebuffer_multisample ||
- !GLEW_EXT_framebuffer_blit)
- {
- samples = 0;
- }
- }
- if (samples && target == RAS_OFS_RENDER_TEXTURE) {
- // we need this in addition if we use multisample textures
- if (!GLEW_ARB_texture_multisample ||
- !GLEW_EXT_framebuffer_multisample_blit_scaled)
- {
- samples = 0;
- }
- }
- if (samples) {
- max_samples = 0;
- glGetIntegerv(GL_MAX_SAMPLES_EXT , &max_samples);
- if (samples > max_samples)
- samples = max_samples;
- }
- m_target = target;
- fbo = 0;
- glGenFramebuffersEXT(1, &fbo);
- if (fbo == 0) {
- printf("RAS_OpenGLOffScreen::Create(): frame buffer creation failed: %d\n", (int)glGetError());
- return false;
- }
- m_fbo = fbo;
- glo[0] = glo[1] = 0;
- if (target == RAS_OFS_RENDER_TEXTURE) {
- glGenTextures(2, glo);
- if (glo[0] == 0 || glo[1] == 0) {
- printf("RAS_OpenGLOffScreen::Create(): texture creation failed: %d\n", (int)glGetError());
- goto L_ERROR;
- }
- m_depthtx = glo[0];
- m_color = m_colortx = glo[1];
- if (samples) {
- textarget = GL_TEXTURE_2D_MULTISAMPLE;
- glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, m_depthtx);
- glTexImage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, samples, GL_DEPTH_COMPONENT, width, height, true);
- glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, m_colortx);
- glTexImage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, samples, GL_RGBA8, width, height, true);
- glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
- glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, 0);
- }
- else {
- textarget = GL_TEXTURE_2D;
- glBindTexture(GL_TEXTURE_2D, m_depthtx);
- glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, width, height, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE, NULL);
- glBindTexture(GL_TEXTURE_2D, m_colortx);
- glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
- glBindTexture(GL_TEXTURE_2D, 0);
- }
- glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, m_fbo);
- glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, textarget, m_depthtx, 0);
- glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, textarget, m_colortx, 0);
- }
- else {
- glGenRenderbuffersEXT(2, glo);
- if (glo[0] == 0 || glo[1] == 0) {
- printf("RAS_OpenGLOffScreen::Create(): render buffer creation failed: %d\n", (int)glGetError());
- goto L_ERROR;
- }
- m_depthrb = glo[0];
- m_colorrb = glo[1];
- glBindRenderbufferEXT(GL_RENDERBUFFER, m_depthrb);
- glRenderbufferStorageMultisampleEXT(GL_RENDERBUFFER, samples, GL_DEPTH_COMPONENT, width, height);
- glBindRenderbufferEXT(GL_RENDERBUFFER, m_colorrb);
- glRenderbufferStorageMultisampleEXT(GL_RENDERBUFFER, samples, GL_RGBA8, width, height);
- glBindRenderbufferEXT(GL_RENDERBUFFER, 0);
-
- glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, m_fbo);
- glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER, m_depthrb);
- glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_RENDERBUFFER, m_colorrb);
- }
- status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
- glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
-
- if (status != GL_FRAMEBUFFER_COMPLETE_EXT) {
- printf("RAS_OpenGLOffScreen::Create(): frame buffer incomplete: %d\n", (int)status);
- goto L_ERROR;
- }
- m_width = width;
- m_height = height;
-
- if (samples > 0) {
- GLuint blit_tex;
- GLuint blit_fbo;
- // create a secondary FBO to blit to before the pixel can be read
-
- /* write into new single-sample buffer */
- glGenFramebuffersEXT(1, &blit_fbo);
- if (!blit_fbo) {
- printf("RAS_OpenGLOffScreen::Create(): failed creating a FBO for multi-sample offscreen buffer\n");
- goto L_ERROR;
- }
- m_blitfbo = blit_fbo;
- blit_tex = 0;
- if (target == RAS_OFS_RENDER_TEXTURE) {
- glGenTextures(1, &blit_tex);
- if (!blit_tex) {
- printf("RAS_OpenGLOffScreen::Create(): failed creating a texture for multi-sample offscreen buffer\n");
- goto L_ERROR;
- }
- // m_color is the texture where the final render goes, the blit texture in this case
- m_color = m_blittex = blit_tex;
- glBindTexture(GL_TEXTURE_2D, m_blittex);
- glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
- glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
- glBindTexture(GL_TEXTURE_2D, 0);
- glBindFramebufferEXT(GL_DRAW_FRAMEBUFFER_EXT, m_blitfbo);
- glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, m_blittex, 0);
- }
- else {
- /* create render buffer for new 'fbo_blit' */
- glGenRenderbuffersEXT(1, &blit_tex);
- if (!blit_tex) {
- printf("RAS_OpenGLOffScreen::Create(): failed creating a render buffer for multi-sample offscreen buffer\n");
- goto L_ERROR;
- }
- m_blitrbo = blit_tex;
- glBindRenderbufferEXT(GL_RENDERBUFFER, m_blitrbo);
- glRenderbufferStorageMultisampleEXT(GL_RENDERBUFFER, 0, GL_RGBA8, width, height);
- glBindRenderbufferEXT(GL_RENDERBUFFER, 0);
- glBindFramebufferEXT(GL_DRAW_FRAMEBUFFER_EXT, m_blitfbo);
- glFramebufferRenderbufferEXT(GL_DRAW_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_RENDERBUFFER, m_blitrbo);
- }
- status = glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER_EXT);
- glBindFramebuffer(GL_DRAW_FRAMEBUFFER_EXT, 0);
- if (status != GL_FRAMEBUFFER_COMPLETE) {
- printf("RAS_OpenGLOffScreen::Create(): frame buffer for multi-sample offscreen buffer incomplete: %d\n", (int)status);
- goto L_ERROR;
- }
- // remember that multisample is enabled
- m_samples = 1;
- }
- return true;
-
-L_ERROR:
- Destroy();
- return false;
-}
-
-void RAS_OpenGLOffScreen::Destroy()
-{
- GLuint globj;
- Unbind();
- if (m_fbo) {
- globj = m_fbo;
- glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, m_fbo);
- if (m_target == RAS_OFS_RENDER_TEXTURE) {
- GLenum textarget = (m_samples) ? GL_TEXTURE_2D_MULTISAMPLE : GL_TEXTURE_2D;
- glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, textarget, 0, 0);
- glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, textarget, 0, 0);
- }
- else {
- glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, 0);
- glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_RENDERBUFFER_EXT, 0);
- }
- glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
- glDeleteFramebuffersEXT(1, &globj);
- m_fbo = 0;
- }
- if (m_depthrb) {
- globj = m_depthrb;
- glDeleteRenderbuffers(1, &globj);
- m_depthrb = 0;
- }
- if (m_colorrb) {
- globj = m_colorrb;
- glDeleteRenderbuffers(1, &globj);
- m_colorrb = 0;
- }
- if (m_depthtx) {
- globj = m_depthtx;
- glDeleteTextures(1, &globj);
- m_depthtx = 0;
- }
- if (m_colortx) {
- globj = m_colortx;
- glDeleteTextures(1, &globj);
- m_colortx = 0;
- }
- if (m_blitfbo) {
- globj = m_blitfbo;
- glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, m_blitfbo);
- if (m_target == RAS_OFS_RENDER_TEXTURE) {
- glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, 0, 0);
- }
- else {
- glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_RENDERBUFFER_EXT, 0);
- }
- glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
- glDeleteFramebuffersEXT(1, &globj);
- m_blitfbo = 0;
- }
- if (m_blitrbo) {
- globj = m_blitrbo;
- glDeleteRenderbuffers(1, &globj);
- m_blitrbo = 0;
- }
- if (m_blittex) {
- globj = m_blittex;
- glDeleteTextures(1, &globj);
- m_blittex = 0;
- }
- m_width = 0;
- m_height = 0;
- m_samples = 0;
- m_color = 0;
- m_target = RAS_OFS_RENDER_BUFFER;
-}
-
-void RAS_OpenGLOffScreen::Bind(RAS_OFS_BIND_MODE mode)
-{
- if (m_fbo) {
- if (mode == RAS_OFS_BIND_RENDER) {
- glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, m_fbo);
- glReadBuffer(GL_COLOR_ATTACHMENT0_EXT);
- glDrawBuffer(GL_COLOR_ATTACHMENT0_EXT);
- glViewport(0, 0, m_width, m_height);
- glDisable(GL_SCISSOR_TEST);
- }
- else if (!m_blitfbo) {
- glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, m_fbo);
- glReadBuffer(GL_COLOR_ATTACHMENT0_EXT);
- }
- else {
- glBindFramebufferEXT(GL_READ_FRAMEBUFFER_EXT, m_blitfbo);
- glReadBuffer(GL_COLOR_ATTACHMENT0_EXT);
- }
- m_bound = true;
- }
-}
-
-void RAS_OpenGLOffScreen::Unbind()
-{
- if (!m_bound)
- return;
-
- glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
- glEnable(GL_SCISSOR_TEST);
- glReadBuffer(GL_BACK);
- glDrawBuffer(GL_BACK);
- m_bound = false;
-}
-
-void RAS_OpenGLOffScreen::MipMap()
-{
- if (m_color) {
- glBindTexture(GL_TEXTURE_2D, m_color);
- glGenerateMipmap(GL_TEXTURE_2D);
- glBindTexture(GL_TEXTURE_2D, 0);
- }
-}
-
-void RAS_OpenGLOffScreen::Blit()
-{
- if (m_bound && m_blitfbo) {
- // set the draw target to the secondary FBO, the read target is still the multisample FBO
- glBindFramebufferEXT(GL_DRAW_FRAMEBUFFER, m_blitfbo);
-
- // sample the primary
- glBlitFramebufferEXT(0, 0, m_width, m_height, 0, 0, m_width, m_height, GL_COLOR_BUFFER_BIT, GL_NEAREST);
-
- // make sure the next glReadPixels will read from the secondary buffer
- glBindFramebufferEXT(GL_READ_FRAMEBUFFER, m_blitfbo);
- }
-}
diff --git a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLOffScreen.h b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLOffScreen.h
deleted file mode 100644
index 3f6845f1e21..00000000000
--- a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLOffScreen.h
+++ /dev/null
@@ -1,65 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2015, Blender Foundation
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): Blender Foundation.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-#ifndef __RAS_OPENGLOFFSCREEN__
-#define __RAS_OPENGLOFFSCREEN__
-
-#include "RAS_IOffScreen.h"
-#include "GPU_extensions.h"
-
-class RAS_ICanvas;
-
-class RAS_OpenGLOffScreen : public RAS_IOffScreen
-{
- RAS_ICanvas *m_canvas;
- // these are GL objects
- unsigned int m_depthrb;
- unsigned int m_colorrb;
- unsigned int m_depthtx;
- unsigned int m_colortx;
- unsigned int m_fbo;
- unsigned int m_blitfbo;
- unsigned int m_blitrbo;
- unsigned int m_blittex;
- RAS_OFS_RENDER_TARGET m_target;
- bool m_bound;
-
-
-public:
- RAS_OpenGLOffScreen(RAS_ICanvas *canvas);
- ~RAS_OpenGLOffScreen();
-
- bool Create(int width, int height, int samples, RAS_OFS_RENDER_TARGET target);
- void Destroy();
- void Bind(RAS_OFS_BIND_MODE mode);
- void Blit();
- void Unbind();
- void MipMap();
-};
-
-#endif /* __RAS_OPENGLOFFSCREEN__ */
-
diff --git a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLRasterizer.cpp b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLRasterizer.cpp
deleted file mode 100644
index d1c3162f752..00000000000
--- a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLRasterizer.cpp
+++ /dev/null
@@ -1,1694 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLRasterizer.cpp
- * \ingroup bgerastogl
- */
-
-
-#include <math.h>
-#include <stdlib.h>
-
-#include "RAS_OpenGLRasterizer.h"
-
-#include "GPU_glew.h"
-
-#include "RAS_ICanvas.h"
-#include "RAS_Rect.h"
-#include "RAS_TexVert.h"
-#include "RAS_MeshObject.h"
-#include "RAS_Polygon.h"
-#include "RAS_ILightObject.h"
-#include "MT_CmMatrix4x4.h"
-
-#include "RAS_OpenGLLight.h"
-#include "RAS_OpenGLOffScreen.h"
-#include "RAS_OpenGLSync.h"
-
-#include "RAS_StorageVA.h"
-#include "RAS_StorageVBO.h"
-
-#include "GPU_draw.h"
-#include "GPU_extensions.h"
-#include "GPU_material.h"
-#include "GPU_shader.h"
-
-extern "C"{
- #include "BLF_api.h"
- #include "BKE_DerivedMesh.h"
- #include "DNA_material_types.h"
-}
-
-
-// XXX Clean these up <<<
-#include "EXP_Value.h"
-#include "KX_Scene.h"
-#include "KX_RayCast.h"
-#include "KX_GameObject.h"
-// >>>
-
-#ifndef M_PI
-#define M_PI 3.14159265358979323846
-#endif
-
-/**
- * 32x32 bit masks for vinterlace stereo mode
- */
-static GLuint left_eye_vinterlace_mask[32];
-static GLuint right_eye_vinterlace_mask[32];
-
-/**
- * 32x32 bit masks for hinterlace stereo mode.
- * Left eye = &hinterlace_mask[0]
- * Right eye = &hinterlace_mask[1]
- */
-static GLuint hinterlace_mask[33];
-
-RAS_OpenGLRasterizer::RAS_OpenGLRasterizer(RAS_ICanvas* canvas, RAS_STORAGE_TYPE storage)
- :RAS_IRasterizer(canvas),
- m_2DCanvas(canvas),
- m_fogenabled(false),
- m_time(0.0f),
- m_campos(0.0f, 0.0f, 0.0f),
- m_camortho(false),
- m_camnegscale(false),
- m_stereomode(RAS_STEREO_NOSTEREO),
- m_curreye(RAS_STEREO_LEFTEYE),
- m_eyeseparation(0.0f),
- m_focallength(0.0f),
- m_setfocallength(false),
- m_noOfScanlines(32),
- m_motionblur(0),
- m_motionblurvalue(-1.0f),
- m_usingoverrideshader(false),
- m_clientobject(NULL),
- m_auxilaryClientInfo(NULL),
- m_drawingmode(KX_TEXTURED),
- m_texco_num(0),
- m_attrib_num(0),
- //m_last_alphablend(GPU_BLEND_SOLID),
- m_last_frontface(true),
- m_materialCachingInfo(0),
- m_storage_type(storage)
-{
- m_viewmatrix.setIdentity();
- m_viewinvmatrix.setIdentity();
-
- for (int i = 0; i < 32; i++)
- {
- left_eye_vinterlace_mask[i] = 0x55555555;
- right_eye_vinterlace_mask[i] = 0xAAAAAAAA;
- hinterlace_mask[i] = (i&1)*0xFFFFFFFF;
- }
- hinterlace_mask[32] = 0;
-
- m_prevafvalue = GPU_get_anisotropic();
-
- if (m_storage_type == RAS_VBO /*|| m_storage_type == RAS_AUTO_STORAGE && GLEW_ARB_vertex_buffer_object*/) {
- m_storage = new RAS_StorageVBO(&m_texco_num, m_texco, &m_attrib_num, m_attrib, m_attrib_layer);
- }
- else if ((m_storage_type == RAS_VA) || (m_storage_type == RAS_AUTO_STORAGE)) {
- m_storage = new RAS_StorageVA(&m_texco_num, m_texco, &m_attrib_num, m_attrib, m_attrib_layer);
- }
- else {
- printf("Unknown rasterizer storage type, falling back to vertex arrays\n");
- m_storage = new RAS_StorageVA(&m_texco_num, m_texco, &m_attrib_num, m_attrib, m_attrib_layer);
- }
-
- glGetIntegerv(GL_MAX_LIGHTS, (GLint *) &m_numgllights);
- if (m_numgllights < 8)
- m_numgllights = 8;
-}
-
-
-
-RAS_OpenGLRasterizer::~RAS_OpenGLRasterizer()
-{
- // Restore the previous AF value
- GPU_set_anisotropic(m_prevafvalue);
-
- if (m_storage)
- delete m_storage;
-}
-
-bool RAS_OpenGLRasterizer::Init()
-{
- bool storage_init;
- GPU_state_init();
-
-
- m_ambr = 0.0f;
- m_ambg = 0.0f;
- m_ambb = 0.0f;
-
- glDisable(GL_BLEND);
- glDisable(GL_ALPHA_TEST);
- //m_last_alphablend = GPU_BLEND_SOLID;
- GPU_set_material_alpha_blend(GPU_BLEND_SOLID);
-
- glFrontFace(GL_CCW);
- m_last_frontface = true;
-
- m_redback = 0.4375f;
- m_greenback = 0.4375f;
- m_blueback = 0.4375f;
- m_alphaback = 0.0f;
-
- glClearColor(m_redback,m_greenback,m_blueback,m_alphaback);
- glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
- glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
-
-
- glShadeModel(GL_SMOOTH);
-
- storage_init = m_storage->Init();
-
- return true && storage_init;
-}
-
-
-void RAS_OpenGLRasterizer::SetAmbientColor(float color[3])
-{
- m_ambr = color[0];
- m_ambg = color[1];
- m_ambb = color[2];
-}
-
-void RAS_OpenGLRasterizer::SetAmbient(float factor)
-{
- float ambient[] = {m_ambr * factor, m_ambg * factor, m_ambb * factor, 1.0f};
- glLightModelfv(GL_LIGHT_MODEL_AMBIENT, ambient);
-}
-
-void RAS_OpenGLRasterizer::SetBackColor(float color[3])
-{
- m_redback = color[0];
- m_greenback = color[1];
- m_blueback = color[2];
- m_alphaback = 0.0f;
-}
-
-void RAS_OpenGLRasterizer::SetFog(short type, float start, float dist, float intensity, float color[3])
-{
- float params[4] = {color[0], color[1], color[2], 1.0f};
- glFogi(GL_FOG_MODE, GL_LINEAR);
- glFogf(GL_FOG_DENSITY, intensity / 10.0f);
- glFogf(GL_FOG_START, start);
- glFogf(GL_FOG_END, start + dist);
- glFogfv(GL_FOG_COLOR, params);
-}
-
-void RAS_OpenGLRasterizer::EnableFog(bool enable)
-{
- m_fogenabled = enable;
-}
-
-void RAS_OpenGLRasterizer::DisplayFog()
-{
- if ((m_drawingmode >= KX_SOLID) && m_fogenabled) {
- glEnable(GL_FOG);
- }
- else {
- glDisable(GL_FOG);
- }
-}
-
-bool RAS_OpenGLRasterizer::SetMaterial(const RAS_IPolyMaterial& mat)
-{
- return mat.Activate(this, m_materialCachingInfo);
-}
-
-
-
-void RAS_OpenGLRasterizer::Exit()
-{
- m_storage->Exit();
-
- glEnable(GL_CULL_FACE);
- glEnable(GL_DEPTH_TEST);
- glClearDepth(1.0f);
- glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
- glClearColor(m_redback, m_greenback, m_blueback, m_alphaback);
- glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
- glDepthMask (GL_TRUE);
- glDepthFunc(GL_LEQUAL);
- glBlendFunc(GL_ONE, GL_ZERO);
-
- glDisable(GL_POLYGON_STIPPLE);
-
- glDisable(GL_LIGHTING);
- if (GLEW_EXT_separate_specular_color || GLEW_VERSION_1_2)
- glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SINGLE_COLOR);
-
- EndFrame();
-}
-
-bool RAS_OpenGLRasterizer::BeginFrame(double time)
-{
- m_time = time;
-
- // Blender camera routine destroys the settings
- if (m_drawingmode < KX_SOLID)
- {
- glDisable(GL_CULL_FACE);
- glDisable(GL_DEPTH_TEST);
- }
- else
- {
- glEnable(GL_DEPTH_TEST);
- glEnable(GL_CULL_FACE);
- }
-
- glDisable(GL_BLEND);
- glDisable(GL_ALPHA_TEST);
- //m_last_alphablend = GPU_BLEND_SOLID;
- GPU_set_material_alpha_blend(GPU_BLEND_SOLID);
-
- glFrontFace(GL_CCW);
- m_last_frontface = true;
-
- glShadeModel(GL_SMOOTH);
-
- glEnable(GL_MULTISAMPLE_ARB);
-
- m_2DCanvas->BeginFrame();
-
- // Render Tools
- m_clientobject = NULL;
- m_lastlightlayer = -1;
- m_lastauxinfo = NULL;
- m_lastlighting = true; /* force disable in DisableOpenGLLights() */
- DisableOpenGLLights();
-
- return true;
-}
-
-
-
-void RAS_OpenGLRasterizer::SetDrawingMode(int drawingmode)
-{
- m_drawingmode = drawingmode;
-
- if (m_drawingmode == KX_WIREFRAME)
- glDisable(GL_CULL_FACE);
-
- m_storage->SetDrawingMode(drawingmode);
-}
-
-int RAS_OpenGLRasterizer::GetDrawingMode()
-{
- return m_drawingmode;
-}
-
-
-void RAS_OpenGLRasterizer::SetDepthMask(DepthMask depthmask)
-{
- glDepthMask(depthmask == KX_DEPTHMASK_DISABLED ? GL_FALSE : GL_TRUE);
-}
-
-
-void RAS_OpenGLRasterizer::ClearColorBuffer()
-{
- m_2DCanvas->ClearColor(m_redback,m_greenback,m_blueback,m_alphaback);
- m_2DCanvas->ClearBuffer(RAS_ICanvas::COLOR_BUFFER);
-}
-
-
-void RAS_OpenGLRasterizer::ClearDepthBuffer()
-{
- m_2DCanvas->ClearBuffer(RAS_ICanvas::DEPTH_BUFFER);
-}
-
-
-void RAS_OpenGLRasterizer::ClearCachingInfo(void)
-{
- m_materialCachingInfo = 0;
-}
-
-void RAS_OpenGLRasterizer::FlushDebugShapes(SCA_IScene *scene)
-{
- std::vector<OglDebugShape> &debugShapes = m_debugShapes[scene];
- if (debugShapes.empty())
- return;
-
- // DrawDebugLines
- GLboolean light, tex;
-
- light= glIsEnabled(GL_LIGHTING);
- tex= glIsEnabled(GL_TEXTURE_2D);
-
- if (light) glDisable(GL_LIGHTING);
- if (tex) glDisable(GL_TEXTURE_2D);
-
- // draw lines
- glBegin(GL_LINES);
- for (unsigned int i = 0; i < debugShapes.size(); i++) {
- if (debugShapes[i].m_type != OglDebugShape::LINE)
- continue;
- glColor4f(debugShapes[i].m_color[0], debugShapes[i].m_color[1], debugShapes[i].m_color[2], 1.0f);
- const MT_Scalar *fromPtr = &debugShapes[i].m_pos.x();
- const MT_Scalar *toPtr= &debugShapes[i].m_param.x();
- glVertex3fv(fromPtr);
- glVertex3fv(toPtr);
- }
- glEnd();
-
- // draw circles
- for (unsigned int i = 0; i < debugShapes.size(); i++) {
- if (debugShapes[i].m_type != OglDebugShape::CIRCLE)
- continue;
- glBegin(GL_LINE_LOOP);
- glColor4f(debugShapes[i].m_color[0], debugShapes[i].m_color[1], debugShapes[i].m_color[2], 1.0f);
-
- static const MT_Vector3 worldUp(0.0f, 0.0f, 1.0f);
- MT_Vector3 norm = debugShapes[i].m_param;
- MT_Matrix3x3 tr;
- if (norm.fuzzyZero() || norm == worldUp)
- {
- tr.setIdentity();
- }
- else
- {
- MT_Vector3 xaxis, yaxis;
- xaxis = MT_cross(norm, worldUp);
- yaxis = MT_cross(xaxis, norm);
- tr.setValue(xaxis.x(), xaxis.y(), xaxis.z(),
- yaxis.x(), yaxis.y(), yaxis.z(),
- norm.x(), norm.y(), norm.z());
- }
- MT_Scalar rad = debugShapes[i].m_param2.x();
- int n = (int)debugShapes[i].m_param2.y();
- for (int j = 0; j<n; j++)
- {
- MT_Scalar theta = j*(float)M_PI*2/n;
- MT_Vector3 pos(cosf(theta) * rad, sinf(theta) * rad, 0.0f);
- pos = pos*tr;
- pos += debugShapes[i].m_pos;
- const MT_Scalar* posPtr = &pos.x();
- glVertex3fv(posPtr);
- }
- glEnd();
- }
-
- if (light) glEnable(GL_LIGHTING);
- if (tex) glEnable(GL_TEXTURE_2D);
-
- debugShapes.clear();
-}
-
-void RAS_OpenGLRasterizer::EndFrame()
-{
- glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
-
- glDisable(GL_MULTISAMPLE_ARB);
-
- m_2DCanvas->EndFrame();
-}
-
-void RAS_OpenGLRasterizer::SetRenderArea()
-{
- RAS_Rect area;
- // only above/below stereo method needs viewport adjustment
- switch (m_stereomode)
- {
- case RAS_STEREO_ABOVEBELOW:
- switch (m_curreye) {
- case RAS_STEREO_LEFTEYE:
- // upper half of window
- area.SetLeft(0);
- area.SetBottom(m_2DCanvas->GetHeight() -
- int(m_2DCanvas->GetHeight() - m_noOfScanlines) / 2);
-
- area.SetRight(int(m_2DCanvas->GetWidth()));
- area.SetTop(int(m_2DCanvas->GetHeight()));
- m_2DCanvas->SetDisplayArea(&area);
- break;
- case RAS_STEREO_RIGHTEYE:
- // lower half of window
- area.SetLeft(0);
- area.SetBottom(0);
- area.SetRight(int(m_2DCanvas->GetWidth()));
- area.SetTop(int(m_2DCanvas->GetHeight() - m_noOfScanlines) / 2);
- m_2DCanvas->SetDisplayArea(&area);
- break;
- }
- break;
- case RAS_STEREO_3DTVTOPBOTTOM:
- switch (m_curreye) {
- case RAS_STEREO_LEFTEYE:
- // upper half of window
- area.SetLeft(0);
- area.SetBottom(m_2DCanvas->GetHeight() -
- m_2DCanvas->GetHeight() / 2);
-
- area.SetRight(m_2DCanvas->GetWidth());
- area.SetTop(m_2DCanvas->GetHeight());
- m_2DCanvas->SetDisplayArea(&area);
- break;
- case RAS_STEREO_RIGHTEYE:
- // lower half of window
- area.SetLeft(0);
- area.SetBottom(0);
- area.SetRight(m_2DCanvas->GetWidth());
- area.SetTop(m_2DCanvas->GetHeight() / 2);
- m_2DCanvas->SetDisplayArea(&area);
- break;
- }
- break;
- case RAS_STEREO_SIDEBYSIDE:
- switch (m_curreye)
- {
- case RAS_STEREO_LEFTEYE:
- // Left half of window
- area.SetLeft(0);
- area.SetBottom(0);
- area.SetRight(m_2DCanvas->GetWidth()/2);
- area.SetTop(m_2DCanvas->GetHeight());
- m_2DCanvas->SetDisplayArea(&area);
- break;
- case RAS_STEREO_RIGHTEYE:
- // Right half of window
- area.SetLeft(m_2DCanvas->GetWidth()/2);
- area.SetBottom(0);
- area.SetRight(m_2DCanvas->GetWidth());
- area.SetTop(m_2DCanvas->GetHeight());
- m_2DCanvas->SetDisplayArea(&area);
- break;
- }
- break;
- default:
- // every available pixel
- area.SetLeft(0);
- area.SetBottom(0);
- area.SetRight(int(m_2DCanvas->GetWidth()));
- area.SetTop(int(m_2DCanvas->GetHeight()));
- m_2DCanvas->SetDisplayArea(&area);
- break;
- }
-}
-
-void RAS_OpenGLRasterizer::SetStereoMode(const StereoMode stereomode)
-{
- m_stereomode = stereomode;
-}
-
-RAS_IRasterizer::StereoMode RAS_OpenGLRasterizer::GetStereoMode()
-{
- return m_stereomode;
-}
-
-bool RAS_OpenGLRasterizer::Stereo()
-{
- if (m_stereomode > RAS_STEREO_NOSTEREO) // > 0
- return true;
- else
- return false;
-}
-
-bool RAS_OpenGLRasterizer::InterlacedStereo()
-{
- return m_stereomode == RAS_STEREO_VINTERLACE || m_stereomode == RAS_STEREO_INTERLACED;
-}
-
-void RAS_OpenGLRasterizer::SetEye(const StereoEye eye)
-{
- m_curreye = eye;
- switch (m_stereomode)
- {
- case RAS_STEREO_QUADBUFFERED:
- glDrawBuffer(m_curreye == RAS_STEREO_LEFTEYE ? GL_BACK_LEFT : GL_BACK_RIGHT);
- break;
- case RAS_STEREO_ANAGLYPH:
- if (m_curreye == RAS_STEREO_LEFTEYE) {
- glColorMask(GL_TRUE, GL_FALSE, GL_FALSE, GL_FALSE);
- }
- else {
- //glAccum(GL_LOAD, 1.0f);
- glColorMask(GL_FALSE, GL_TRUE, GL_TRUE, GL_FALSE);
- ClearDepthBuffer();
- }
- break;
- case RAS_STEREO_VINTERLACE:
- {
- // OpenGL stippling is deprecated, it is no longer possible to affect all shaders
- // this way, offscreen rendering and then compositing may be the better solution
- glEnable(GL_POLYGON_STIPPLE);
- glPolygonStipple((const GLubyte*) ((m_curreye == RAS_STEREO_LEFTEYE) ? left_eye_vinterlace_mask : right_eye_vinterlace_mask));
- if (m_curreye == RAS_STEREO_RIGHTEYE)
- ClearDepthBuffer();
- break;
- }
- case RAS_STEREO_INTERLACED:
- {
- glEnable(GL_POLYGON_STIPPLE);
- glPolygonStipple((const GLubyte*) &hinterlace_mask[m_curreye == RAS_STEREO_LEFTEYE?0:1]);
- if (m_curreye == RAS_STEREO_RIGHTEYE)
- ClearDepthBuffer();
- break;
- }
- default:
- break;
- }
-}
-
-RAS_IRasterizer::StereoEye RAS_OpenGLRasterizer::GetEye()
-{
- return m_curreye;
-}
-
-
-void RAS_OpenGLRasterizer::SetEyeSeparation(const float eyeseparation)
-{
- m_eyeseparation = eyeseparation;
-}
-
-float RAS_OpenGLRasterizer::GetEyeSeparation()
-{
- return m_eyeseparation;
-}
-
-void RAS_OpenGLRasterizer::SetFocalLength(const float focallength)
-{
- m_focallength = focallength;
- m_setfocallength = true;
-}
-
-float RAS_OpenGLRasterizer::GetFocalLength()
-{
- return m_focallength;
-}
-
-RAS_IOffScreen *RAS_OpenGLRasterizer::CreateOffScreen(int width, int height, int samples, int target)
-{
- RAS_IOffScreen *ofs;
-
- ofs = new RAS_OpenGLOffScreen(m_2DCanvas);
-
- if (!ofs->Create(width, height, samples, (RAS_IOffScreen::RAS_OFS_RENDER_TARGET)target)) {
- delete ofs;
- return NULL;
- }
- return ofs;
-}
-
-RAS_ISync *RAS_OpenGLRasterizer::CreateSync(int type)
-{
- RAS_ISync *sync;
-
- sync = new RAS_OpenGLSync();
-
- if (!sync->Create((RAS_ISync::RAS_SYNC_TYPE)type)) {
- delete sync;
- return NULL;
- }
- return sync;
-}
-
-void RAS_OpenGLRasterizer::SwapBuffers()
-{
- m_2DCanvas->SwapBuffers();
-}
-
-
-
-const MT_Matrix4x4& RAS_OpenGLRasterizer::GetViewMatrix() const
-{
- return m_viewmatrix;
-}
-
-const MT_Matrix4x4& RAS_OpenGLRasterizer::GetViewInvMatrix() const
-{
- return m_viewinvmatrix;
-}
-
-void RAS_OpenGLRasterizer::IndexPrimitives_3DText(RAS_MeshSlot& ms,
- class RAS_IPolyMaterial* polymat)
-{
- bool obcolor = ms.m_bObjectColor;
- MT_Vector4& rgba = ms.m_RGBAcolor;
- RAS_MeshSlot::iterator it;
-
- const STR_String& mytext = ((CValue*)m_clientobject)->GetPropertyText("Text");
-
- // handle object color
- if (obcolor) {
- glDisableClientState(GL_COLOR_ARRAY);
- glColor4d(rgba[0], rgba[1], rgba[2], rgba[3]);
- }
- else
- glEnableClientState(GL_COLOR_ARRAY);
-
- for (ms.begin(it); !ms.end(it); ms.next(it)) {
- RAS_TexVert *vertex;
- size_t i, j, numvert;
-
- numvert = it.array->m_type;
-
- if (it.array->m_type == RAS_DisplayArray::LINE) {
- // line drawing, no text
- glBegin(GL_LINES);
-
- for (i=0; i<it.totindex; i+=2)
- {
- vertex = &it.vertex[it.index[i]];
- glVertex3fv(vertex->getXYZ());
-
- vertex = &it.vertex[it.index[i+1]];
- glVertex3fv(vertex->getXYZ());
- }
-
- glEnd();
- }
- else {
- // triangle and quad text drawing
- for (i=0; i<it.totindex; i+=numvert)
- {
- float v[4][3];
- const float *v_ptr[4] = {NULL};
- const float *uv_ptr[4] = {NULL};
- int glattrib, unit;
-
- for (j=0; j<numvert; j++) {
- vertex = &it.vertex[it.index[i+j]];
-
- v[j][0] = vertex->getXYZ()[0];
- v[j][1] = vertex->getXYZ()[1];
- v[j][2] = vertex->getXYZ()[2];
- v_ptr[j] = v[j];
-
- uv_ptr[j] = vertex->getUV(0);
- }
-
- // find the right opengl attribute
- glattrib = -1;
- if (GLEW_ARB_vertex_program)
- for (unit=0; unit<m_attrib_num; unit++)
- if (m_attrib[unit] == RAS_TEXCO_UV)
- glattrib = unit;
-
- GPU_render_text(
- polymat->GetDrawingMode(), mytext, mytext.Length(), polymat->GetMCol(),
- v_ptr, uv_ptr, glattrib);
-
- ClearCachingInfo();
- }
- }
- }
-
- glDisableClientState(GL_COLOR_ARRAY);
-}
-
-void RAS_OpenGLRasterizer::SetTexCoordNum(int num)
-{
- m_texco_num = num;
- if (m_texco_num > RAS_MAX_TEXCO)
- m_texco_num = RAS_MAX_TEXCO;
-}
-
-void RAS_OpenGLRasterizer::SetAttribNum(int num)
-{
- m_attrib_num = num;
- if (m_attrib_num > RAS_MAX_ATTRIB)
- m_attrib_num = RAS_MAX_ATTRIB;
-}
-
-void RAS_OpenGLRasterizer::SetTexCoord(TexCoGen coords, int unit)
-{
- // this changes from material to material
- if (unit < RAS_MAX_TEXCO)
- m_texco[unit] = coords;
-}
-
-void RAS_OpenGLRasterizer::SetAttrib(TexCoGen coords, int unit, int layer)
-{
- // this changes from material to material
- if (unit < RAS_MAX_ATTRIB) {
- m_attrib[unit] = coords;
- m_attrib_layer[unit] = layer;
- }
-}
-
-void RAS_OpenGLRasterizer::IndexPrimitives(RAS_MeshSlot& ms)
-{
- if (ms.m_pDerivedMesh)
- DrawDerivedMesh(ms);
- else
- m_storage->IndexPrimitives(ms);
-}
-
-// Code for hooking into Blender's mesh drawing for derived meshes.
-// If/when we use more of Blender's drawing code, we may be able to
-// clean this up
-static bool current_wireframe;
-static RAS_MaterialBucket *current_bucket;
-static RAS_IPolyMaterial *current_polymat;
-static RAS_MeshSlot *current_ms;
-static RAS_MeshObject *current_mesh;
-static int current_blmat_nr;
-static GPUVertexAttribs current_gpu_attribs;
-static int CheckMaterialDM(int matnr, void *attribs)
-{
- // only draw the current material
- if (matnr != current_blmat_nr)
- return 0;
- GPUVertexAttribs *gattribs = (GPUVertexAttribs *)attribs;
- if (gattribs)
- memcpy(gattribs, &current_gpu_attribs, sizeof(GPUVertexAttribs));
- return 1;
-}
-
-void RAS_OpenGLRasterizer::DrawDerivedMesh(class RAS_MeshSlot &ms)
-{
- // mesh data is in derived mesh
- current_bucket = ms.m_bucket;
- current_polymat = current_bucket->GetPolyMaterial();
- current_ms = &ms;
- current_mesh = ms.m_mesh;
- current_wireframe = m_drawingmode <= RAS_IRasterizer::KX_WIREFRAME;
- // MCol *mcol = (MCol*)ms.m_pDerivedMesh->getFaceDataArray(ms.m_pDerivedMesh, CD_MCOL); /* UNUSED */
-
- // handle two-side
- if (current_polymat->GetDrawingMode() & RAS_IRasterizer::KX_BACKCULL)
- this->SetCullFace(true);
- else
- this->SetCullFace(false);
-
-#if 0
- if (current_polymat->GetFlag() & RAS_BLENDERGLSL)
-#endif
- {
- // GetMaterialIndex return the original mface material index,
- // increment by 1 to match what derived mesh is doing
- current_blmat_nr = current_polymat->GetMaterialIndex()+1;
- // For GLSL we need to retrieve the GPU material attribute
- Material* blmat = current_polymat->GetBlenderMaterial();
- Scene* blscene = current_polymat->GetBlenderScene();
- if (!current_wireframe && blscene && blmat)
- GPU_material_vertex_attributes(GPU_material_from_blender(blscene, blmat, false), &current_gpu_attribs);
- else
- memset(&current_gpu_attribs, 0, sizeof(current_gpu_attribs));
- // DM draw can mess up blending mode, restore at the end
- int current_blend_mode = GPU_get_material_alpha_blend();
- ms.m_pDerivedMesh->drawFacesGLSL(ms.m_pDerivedMesh, CheckMaterialDM);
- GPU_set_material_alpha_blend(current_blend_mode);
- }
-}
-
-void RAS_OpenGLRasterizer::SetProjectionMatrix(MT_CmMatrix4x4 &mat)
-{
- glMatrixMode(GL_PROJECTION);
- float* matrix = &mat(0, 0);
- glLoadMatrixf(matrix);
-
- m_camortho = (mat(3, 3) != 0.0f);
-}
-
-void RAS_OpenGLRasterizer::SetProjectionMatrix(const MT_Matrix4x4 & mat)
-{
- glMatrixMode(GL_PROJECTION);
- float matrix[16];
- /* Get into argument. Looks a bit dodgy, but it's ok. */
- mat.getValue(matrix);
- glLoadMatrixf(matrix);
-
- m_camortho = (mat[3][3] != 0.0f);
-}
-
-MT_Matrix4x4 RAS_OpenGLRasterizer::GetFrustumMatrix(
- float left,
- float right,
- float bottom,
- float top,
- float frustnear,
- float frustfar,
- float focallength,
- bool
-) {
- MT_Matrix4x4 result;
- float mat[16];
-
- // correction for stereo
- if (Stereo())
- {
- float near_div_focallength;
- float offset;
-
- // if Rasterizer.setFocalLength is not called we use the camera focallength
- if (!m_setfocallength)
- // if focallength is null we use a value known to be reasonable
- m_focallength = (focallength == 0.f) ? m_eyeseparation * 30.0f
- : focallength;
-
- near_div_focallength = frustnear / m_focallength;
- offset = 0.5f * m_eyeseparation * near_div_focallength;
- switch (m_curreye) {
- case RAS_STEREO_LEFTEYE:
- left += offset;
- right += offset;
- break;
- case RAS_STEREO_RIGHTEYE:
- left -= offset;
- right -= offset;
- break;
- }
- // leave bottom and top untouched
- if (m_stereomode == RAS_STEREO_3DTVTOPBOTTOM) {
- // restore the vertical frustum because the 3DTV will
- // expand the top and bottom part to the full size of the screen
- bottom *= 2.0f;
- top *= 2.0f;
- }
- }
-
- glMatrixMode(GL_PROJECTION);
- glLoadIdentity();
- glFrustum(left, right, bottom, top, frustnear, frustfar);
-
- glGetFloatv(GL_PROJECTION_MATRIX, mat);
- result.setValue(mat);
-
- return result;
-}
-
-MT_Matrix4x4 RAS_OpenGLRasterizer::GetOrthoMatrix(
- float left,
- float right,
- float bottom,
- float top,
- float frustnear,
- float frustfar
-) {
- MT_Matrix4x4 result;
- float mat[16];
-
- // stereo is meaningless for orthographic, disable it
- glMatrixMode(GL_PROJECTION);
- glLoadIdentity();
- glOrtho(left, right, bottom, top, frustnear, frustfar);
-
- glGetFloatv(GL_PROJECTION_MATRIX, mat);
- result.setValue(mat);
-
- return result;
-}
-
-
-// next arguments probably contain redundant info, for later...
-void RAS_OpenGLRasterizer::SetViewMatrix(const MT_Matrix4x4 &mat,
- const MT_Matrix3x3 & camOrientMat3x3,
- const MT_Point3 & pos,
- const MT_Vector3 &scale,
- bool perspective)
-{
- m_viewmatrix = mat;
-
- // correction for stereo
- if (Stereo() && perspective)
- {
- MT_Vector3 unitViewDir(0.0f, -1.0f, 0.0f); // minus y direction, Blender convention
- MT_Vector3 unitViewupVec(0.0f, 0.0f, 1.0f);
- MT_Vector3 viewDir, viewupVec;
- MT_Vector3 eyeline;
-
- // actual viewDir
- viewDir = camOrientMat3x3 * unitViewDir; // this is the moto convention, vector on right hand side
- // actual viewup vec
- viewupVec = camOrientMat3x3 * unitViewupVec;
-
- // vector between eyes
- eyeline = viewDir.cross(viewupVec);
-
- switch (m_curreye) {
- case RAS_STEREO_LEFTEYE:
- {
- // translate to left by half the eye distance
- MT_Transform transform;
- transform.setIdentity();
- transform.translate(-(eyeline * m_eyeseparation / 2.0f));
- m_viewmatrix *= transform;
- }
- break;
- case RAS_STEREO_RIGHTEYE:
- {
- // translate to right by half the eye distance
- MT_Transform transform;
- transform.setIdentity();
- transform.translate(eyeline * m_eyeseparation / 2.0f);
- m_viewmatrix *= transform;
- }
- break;
- }
- }
-
- bool negX = (scale[0] < 0.0f);
- bool negY = (scale[1] < 0.0f);
- bool negZ = (scale[2] < 0.0f);
- if (negX || negY || negZ) {
- m_viewmatrix.tscale((negX)?-1.0f:1.0f, (negY)?-1.0f:1.0f, (negZ)?-1.0f:1.0f, 1.0);
- }
- m_viewinvmatrix = m_viewmatrix;
- m_viewinvmatrix.invert();
-
- // note: getValue gives back column major as needed by OpenGL
- MT_Scalar glviewmat[16];
- m_viewmatrix.getValue(glviewmat);
-
- glMatrixMode(GL_MODELVIEW);
- glLoadMatrixf(glviewmat);
- m_campos = pos;
- m_camnegscale = negX ^ negY ^ negZ;
-}
-
-
-const MT_Point3& RAS_OpenGLRasterizer::GetCameraPosition()
-{
- return m_campos;
-}
-
-bool RAS_OpenGLRasterizer::GetCameraOrtho()
-{
- return m_camortho;
-}
-
-void RAS_OpenGLRasterizer::SetCullFace(bool enable)
-{
- if (enable)
- glEnable(GL_CULL_FACE);
- else
- glDisable(GL_CULL_FACE);
-}
-
-void RAS_OpenGLRasterizer::SetLines(bool enable)
-{
- if (enable)
- glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
- else
- glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
-}
-
-void RAS_OpenGLRasterizer::SetSpecularity(float specX,
- float specY,
- float specZ,
- float specval)
-{
- GLfloat mat_specular[] = {specX, specY, specZ, specval};
- glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, mat_specular);
-}
-
-
-
-void RAS_OpenGLRasterizer::SetShinyness(float shiny)
-{
- GLfloat mat_shininess[] = { shiny };
- glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, mat_shininess);
-}
-
-
-
-void RAS_OpenGLRasterizer::SetDiffuse(float difX,float difY,float difZ,float diffuse)
-{
- GLfloat mat_diffuse [] = {difX, difY,difZ, diffuse};
- glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, mat_diffuse);
-}
-
-void RAS_OpenGLRasterizer::SetEmissive(float eX, float eY, float eZ, float e)
-{
- GLfloat mat_emit [] = {eX,eY,eZ,e};
- glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, mat_emit);
-}
-
-
-double RAS_OpenGLRasterizer::GetTime()
-{
- return m_time;
-}
-
-void RAS_OpenGLRasterizer::SetPolygonOffset(float mult, float add)
-{
- glPolygonOffset(mult, add);
- GLint mode = GL_POLYGON_OFFSET_FILL;
- if (m_drawingmode < KX_SHADED)
- mode = GL_POLYGON_OFFSET_LINE;
- if (mult != 0.0f || add != 0.0f)
- glEnable(mode);
- else
- glDisable(mode);
-}
-
-void RAS_OpenGLRasterizer::EnableMotionBlur(float motionblurvalue)
-{
- /* don't just set m_motionblur to 1, but check if it is 0 so
- * we don't reset a motion blur that is already enabled */
- if (m_motionblur == 0)
- m_motionblur = 1;
- m_motionblurvalue = motionblurvalue;
-}
-
-void RAS_OpenGLRasterizer::DisableMotionBlur()
-{
- m_motionblur = 0;
- m_motionblurvalue = -1.0f;
-}
-
-void RAS_OpenGLRasterizer::SetAlphaBlend(int alphablend)
-{
- /* Variance shadow maps don't handle alpha well, best to not allow it for now */
- if (m_drawingmode == KX_SHADOW && m_usingoverrideshader)
- GPU_set_material_alpha_blend(GPU_BLEND_SOLID);
- else
- GPU_set_material_alpha_blend(alphablend);
-/*
- if (alphablend == m_last_alphablend)
- return;
-
- if (alphablend == GPU_BLEND_SOLID) {
- glDisable(GL_BLEND);
- glDisable(GL_ALPHA_TEST);
- glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
- }
- else if (alphablend == GPU_BLEND_ADD) {
- glBlendFunc(GL_ONE, GL_ONE);
- glEnable(GL_BLEND);
- glDisable(GL_ALPHA_TEST);
- }
- else if (alphablend == GPU_BLEND_ALPHA) {
- glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
- glEnable(GL_BLEND);
- glEnable(GL_ALPHA_TEST);
- glAlphaFunc(GL_GREATER, 0.0f);
- }
- else if (alphablend == GPU_BLEND_CLIP) {
- glDisable(GL_BLEND);
- glEnable(GL_ALPHA_TEST);
- glAlphaFunc(GL_GREATER, 0.5f);
- }
-
- m_last_alphablend = alphablend;
-*/
-}
-
-void RAS_OpenGLRasterizer::SetFrontFace(bool ccw)
-{
- if (m_camnegscale)
- ccw = !ccw;
-
- if (m_last_frontface == ccw)
- return;
-
- if (ccw)
- glFrontFace(GL_CCW);
- else
- glFrontFace(GL_CW);
-
- m_last_frontface = ccw;
-}
-
-void RAS_OpenGLRasterizer::SetAnisotropicFiltering(short level)
-{
- GPU_set_anisotropic((float)level);
-}
-
-short RAS_OpenGLRasterizer::GetAnisotropicFiltering()
-{
- return (short)GPU_get_anisotropic();
-}
-
-void RAS_OpenGLRasterizer::SetMipmapping(MipmapOption val)
-{
- if (val == RAS_IRasterizer::RAS_MIPMAP_LINEAR)
- {
- GPU_set_linear_mipmap(1);
- GPU_set_mipmap(1);
- }
- else if (val == RAS_IRasterizer::RAS_MIPMAP_NEAREST)
- {
- GPU_set_linear_mipmap(0);
- GPU_set_mipmap(1);
- }
- else
- {
- GPU_set_linear_mipmap(0);
- GPU_set_mipmap(0);
- }
-}
-
-RAS_IRasterizer::MipmapOption RAS_OpenGLRasterizer::GetMipmapping()
-{
- if (GPU_get_mipmap()) {
- if (GPU_get_linear_mipmap()) {
- return RAS_IRasterizer::RAS_MIPMAP_LINEAR;
- }
- else {
- return RAS_IRasterizer::RAS_MIPMAP_NEAREST;
- }
- }
- else {
- return RAS_IRasterizer::RAS_MIPMAP_NONE;
- }
-}
-
-void RAS_OpenGLRasterizer::SetUsingOverrideShader(bool val)
-{
- m_usingoverrideshader = val;
-}
-
-bool RAS_OpenGLRasterizer::GetUsingOverrideShader()
-{
- return m_usingoverrideshader;
-}
-
-/**
- * Render Tools
- */
-
-/* ProcessLighting performs lighting on objects. the layer is a bitfield that
- * contains layer information. There are 20 'official' layers in blender. A
- * light is applied on an object only when they are in the same layer. OpenGL
- * has a maximum of 8 lights (simultaneous), so 20 * 8 lights are possible in
- * a scene. */
-
-void RAS_OpenGLRasterizer::ProcessLighting(bool uselights, const MT_Transform& viewmat)
-{
- bool enable = false;
- int layer= -1;
-
- /* find the layer */
- if (uselights) {
- if (m_clientobject)
- layer = static_cast<KX_GameObject*>(m_clientobject)->GetLayer();
- }
-
- /* avoid state switching */
- if (m_lastlightlayer == layer && m_lastauxinfo == m_auxilaryClientInfo)
- return;
-
- m_lastlightlayer = layer;
- m_lastauxinfo = m_auxilaryClientInfo;
-
- /* enable/disable lights as needed */
- if (layer >= 0) {
- //enable = ApplyLights(layer, viewmat);
- // taken from blender source, incompatibility between Blender Object / GameObject
- KX_Scene* kxscene = (KX_Scene*)m_auxilaryClientInfo;
- float glviewmat[16];
- unsigned int count;
- std::vector<RAS_OpenGLLight*>::iterator lit = m_lights.begin();
-
- for (count=0; count<m_numgllights; count++)
- glDisable((GLenum)(GL_LIGHT0+count));
-
- viewmat.getValue(glviewmat);
-
- glPushMatrix();
- glLoadMatrixf(glviewmat);
- for (lit = m_lights.begin(), count = 0; !(lit==m_lights.end()) && count < m_numgllights; ++lit)
- {
- RAS_OpenGLLight* light = (*lit);
-
- if (light->ApplyFixedFunctionLighting(kxscene, layer, count))
- count++;
- }
- glPopMatrix();
-
- enable = count > 0;
- }
-
- if (enable)
- EnableOpenGLLights();
- else
- DisableOpenGLLights();
-}
-
-void RAS_OpenGLRasterizer::EnableOpenGLLights()
-{
- if (m_lastlighting == true)
- return;
-
- glEnable(GL_LIGHTING);
- glEnable(GL_COLOR_MATERIAL);
-
- glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
- glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE);
- glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, (GetCameraOrtho())? GL_FALSE: GL_TRUE);
- if (GLEW_EXT_separate_specular_color || GLEW_VERSION_1_2)
- glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
-
- m_lastlighting = true;
-}
-
-void RAS_OpenGLRasterizer::DisableOpenGLLights()
-{
- if (m_lastlighting == false)
- return;
-
- glDisable(GL_LIGHTING);
- glDisable(GL_COLOR_MATERIAL);
-
- m_lastlighting = false;
-}
-
-RAS_ILightObject *RAS_OpenGLRasterizer::CreateLight()
-{
- return new RAS_OpenGLLight(this);
-}
-
-void RAS_OpenGLRasterizer::AddLight(RAS_ILightObject* lightobject)
-{
- RAS_OpenGLLight* gllight = dynamic_cast<RAS_OpenGLLight*>(lightobject);
- assert(gllight);
- m_lights.push_back(gllight);
-}
-
-void RAS_OpenGLRasterizer::RemoveLight(RAS_ILightObject* lightobject)
-{
- RAS_OpenGLLight* gllight = dynamic_cast<RAS_OpenGLLight*>(lightobject);
- assert(gllight);
-
- std::vector<RAS_OpenGLLight*>::iterator lit =
- std::find(m_lights.begin(),m_lights.end(),gllight);
-
- if (!(lit==m_lights.end()))
- m_lights.erase(lit);
-}
-
-bool RAS_OpenGLRasterizer::RayHit(struct KX_ClientObjectInfo *client, KX_RayCast *result, float *oglmatrix)
-{
- if (result->m_hitMesh) {
-
- RAS_Polygon* poly = result->m_hitMesh->GetPolygon(result->m_hitPolygon);
- if (!poly->IsVisible())
- return false;
-
- MT_Vector3 resultnormal(result->m_hitNormal);
- MT_Vector3 left(oglmatrix[0],oglmatrix[1],oglmatrix[2]);
- MT_Vector3 dir = -(left.cross(resultnormal)).safe_normalized();
- left = (dir.cross(resultnormal)).safe_normalized();
- // for the up vector, we take the 'resultnormal' returned by the physics
-
- float maat[16] = {left[0], left[1], left[2], 0,
- dir[0], dir[1], dir[2], 0,
- resultnormal[0], resultnormal[1], resultnormal[2], 0,
- 0, 0, 0, 1};
-
- glTranslatef(oglmatrix[12],oglmatrix[13],oglmatrix[14]);
- //glMultMatrixd(oglmatrix);
- glMultMatrixf(maat);
- return true;
- }
- else {
- return false;
- }
-}
-
-void RAS_OpenGLRasterizer::applyTransform(float* oglmatrix,int objectdrawmode )
-{
- /* FIXME:
- blender: intern/moto/include/MT_Vector3.inl:42: MT_Vector3 operator/(const
- MT_Vector3&, double): Assertion `!MT_fuzzyZero(s)' failed.
-
- Program received signal SIGABRT, Aborted.
- [Switching to Thread 16384 (LWP 1519)]
- 0x40477571 in kill () from /lib/libc.so.6
- (gdb) bt
- #7 0x08334368 in MT_Vector3::normalized() const ()
- #8 0x0833e6ec in RAS_OpenGLRasterizer::applyTransform(RAS_IRasterizer*, double*, int) ()
- */
-
- if (objectdrawmode & RAS_IPolyMaterial::BILLBOARD_SCREENALIGNED ||
- objectdrawmode & RAS_IPolyMaterial::BILLBOARD_AXISALIGNED)
- {
- // rotate the billboard/halo
- //page 360/361 3D Game Engine Design, David Eberly for a discussion
- // on screen aligned and axis aligned billboards
- // assumed is that the preprocessor transformed all billboard polygons
- // so that their normal points into the positive x direction (1.0f, 0.0f, 0.0f)
- // when new parenting for objects is done, this rotation
- // will be moved into the object
-
- MT_Point3 objpos (oglmatrix[12],oglmatrix[13],oglmatrix[14]);
- MT_Point3 campos = GetCameraPosition();
- MT_Vector3 dir = (campos - objpos).safe_normalized();
- MT_Vector3 up(0,0,1.0f);
-
- KX_GameObject* gameobj = (KX_GameObject*)m_clientobject;
- // get scaling of halo object
- MT_Vector3 size = gameobj->GetSGNode()->GetWorldScaling();
-
- bool screenaligned = (objectdrawmode & RAS_IPolyMaterial::BILLBOARD_SCREENALIGNED)!=0;//false; //either screen or axisaligned
- if (screenaligned)
- {
- up = (up - up.dot(dir) * dir).safe_normalized();
- } else
- {
- dir = (dir - up.dot(dir)*up).safe_normalized();
- }
-
- MT_Vector3 left = dir.normalized();
- dir = (up.cross(left)).normalized();
-
- // we have calculated the row vectors, now we keep
- // local scaling into account:
-
- left *= size[0];
- dir *= size[1];
- up *= size[2];
-
- float maat[16] = {left[0], left[1], left[2], 0,
- dir[0], dir[1], dir[2], 0,
- up[0], up[1], up[2], 0,
- 0, 0, 0, 1};
-
- glTranslatef(objpos[0],objpos[1],objpos[2]);
- glMultMatrixf(maat);
-
- }
- else {
- if (objectdrawmode & RAS_IPolyMaterial::SHADOW)
- {
- // shadow must be cast to the ground, physics system needed here!
- MT_Point3 frompoint(oglmatrix[12],oglmatrix[13],oglmatrix[14]);
- KX_GameObject *gameobj = (KX_GameObject*)m_clientobject;
- MT_Vector3 direction = MT_Vector3(0,0,-1);
-
- direction.normalize();
- direction *= 100000;
-
- MT_Point3 topoint = frompoint + direction;
-
- KX_Scene* kxscene = (KX_Scene*) m_auxilaryClientInfo;
- PHY_IPhysicsEnvironment* physics_environment = kxscene->GetPhysicsEnvironment();
- PHY_IPhysicsController* physics_controller = gameobj->GetPhysicsController();
-
- KX_GameObject *parent = gameobj->GetParent();
- if (!physics_controller && parent)
- physics_controller = parent->GetPhysicsController();
-
- KX_RayCast::Callback<RAS_OpenGLRasterizer, float> callback(this, physics_controller, oglmatrix);
- if (!KX_RayCast::RayTest(physics_environment, frompoint, topoint, callback))
- {
- // couldn't find something to cast the shadow on...
- glMultMatrixf(oglmatrix);
- }
- else
- { // we found the "ground", but the cast matrix doesn't take
- // scaling in consideration, so we must apply the object scale
- MT_Vector3 size = gameobj->GetSGNode()->GetLocalScale();
- glScalef(size[0], size[1], size[2]);
- }
- } else
- {
-
- // 'normal' object
- glMultMatrixf(oglmatrix);
- }
- }
-}
-
-static void DisableForText()
-{
- glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); /* needed for texture fonts otherwise they render as wireframe */
-
- glDisable(GL_BLEND);
- glDisable(GL_ALPHA_TEST);
-
- glDisable(GL_LIGHTING);
- glDisable(GL_COLOR_MATERIAL);
-
- if (GLEW_ARB_multitexture) {
- for (int i=0; i<RAS_MAX_TEXCO; i++) {
- glActiveTextureARB(GL_TEXTURE0_ARB+i);
-
- if (GLEW_ARB_texture_cube_map) {
- glDisable(GL_TEXTURE_CUBE_MAP_ARB);
- glDisable(GL_TEXTURE_GEN_S);
- glDisable(GL_TEXTURE_GEN_T);
- glDisable(GL_TEXTURE_GEN_Q);
- glDisable(GL_TEXTURE_GEN_R);
- }
- glDisable(GL_TEXTURE_2D);
- }
-
- glActiveTextureARB(GL_TEXTURE0_ARB);
- }
- else {
- if (GLEW_ARB_texture_cube_map)
- glDisable(GL_TEXTURE_CUBE_MAP_ARB);
-
- glDisable(GL_TEXTURE_2D);
- }
-}
-
-void RAS_OpenGLRasterizer::RenderBox2D(int xco,
- int yco,
- int width,
- int height,
- float percentage)
-{
- /* This is a rather important line :( The gl-mode hasn't been left
- * behind quite as neatly as we'd have wanted to. I don't know
- * what cause it, though :/ .*/
- glDisable(GL_DEPTH_TEST);
-
- glMatrixMode(GL_PROJECTION);
- glPushMatrix();
- glLoadIdentity();
-
- glOrtho(0, width, 0, height, -100, 100);
-
- glMatrixMode(GL_MODELVIEW);
- glPushMatrix();
- glLoadIdentity();
-
- yco = height - yco;
- int barsize = 50;
-
- /* draw in black first */
- glColor3ub(0, 0, 0);
- glBegin(GL_QUADS);
- glVertex2f(xco + 1 + 1 + barsize * percentage, yco - 1 + 10);
- glVertex2f(xco + 1, yco - 1 + 10);
- glVertex2f(xco + 1, yco - 1);
- glVertex2f(xco + 1 + 1 + barsize * percentage, yco - 1);
- glEnd();
-
- glColor3ub(255, 255, 255);
- glBegin(GL_QUADS);
- glVertex2f(xco + 1 + barsize * percentage, yco + 10);
- glVertex2f(xco, yco + 10);
- glVertex2f(xco, yco);
- glVertex2f(xco + 1 + barsize * percentage, yco);
- glEnd();
-
- glMatrixMode(GL_PROJECTION);
- glPopMatrix();
- glMatrixMode(GL_MODELVIEW);
- glPopMatrix();
- glEnable(GL_DEPTH_TEST);
-}
-
-void RAS_OpenGLRasterizer::RenderText3D(
- int fontid, const char *text, int size, int dpi,
- const float color[4], const float mat[16], float aspect)
-{
- /* gl prepping */
- DisableForText();
-
- /* the actual drawing */
- glColor4fv(color);
-
- /* multiply the text matrix by the object matrix */
- BLF_enable(fontid, BLF_MATRIX|BLF_ASPECT);
- BLF_matrix(fontid, mat);
-
- /* aspect is the inverse scale that allows you to increase
- * your resolution without sizing the final text size
- * the bigger the size, the smaller the aspect */
- BLF_aspect(fontid, aspect, aspect, aspect);
-
- BLF_size(fontid, size, dpi);
- BLF_position(fontid, 0, 0, 0);
- BLF_draw(fontid, text, 65535);
-
- BLF_disable(fontid, BLF_MATRIX|BLF_ASPECT);
-}
-
-void RAS_OpenGLRasterizer::RenderText2D(
- RAS_TEXT_RENDER_MODE mode,
- const char* text,
- int xco, int yco,
- int width, int height)
-{
- /* This is a rather important line :( The gl-mode hasn't been left
- * behind quite as neatly as we'd have wanted to. I don't know
- * what cause it, though :/ .*/
- DisableForText();
- glDisable(GL_DEPTH_TEST);
-
- glMatrixMode(GL_PROJECTION);
- glPushMatrix();
- glLoadIdentity();
-
- glOrtho(0, width, 0, height, -100, 100);
-
- glMatrixMode(GL_MODELVIEW);
- glPushMatrix();
- glLoadIdentity();
-
- if (mode == RAS_TEXT_PADDED) {
- /* draw in black first */
- glColor3ub(0, 0, 0);
- BLF_size(blf_mono_font, 11, 72);
- BLF_position(blf_mono_font, (float)xco+1, (float)(height-yco-1), 0.0f);
- BLF_draw(blf_mono_font, text, 65535); /* XXX, use real len */
- }
-
- /* the actual drawing */
- glColor3ub(255, 255, 255);
- BLF_size(blf_mono_font, 11, 72);
- BLF_position(blf_mono_font, (float)xco, (float)(height-yco), 0.0f);
- BLF_draw(blf_mono_font, text, 65535); /* XXX, use real len */
-
- glMatrixMode(GL_PROJECTION);
- glPopMatrix();
- glMatrixMode(GL_MODELVIEW);
- glPopMatrix();
- glEnable(GL_DEPTH_TEST);
-}
-
-void RAS_OpenGLRasterizer::PushMatrix()
-{
- glPushMatrix();
-}
-
-void RAS_OpenGLRasterizer::PopMatrix()
-{
- glPopMatrix();
-}
-
-void RAS_OpenGLRasterizer::MotionBlur()
-{
- int state = GetMotionBlurState();
- float motionblurvalue;
- if (state)
- {
- motionblurvalue = GetMotionBlurValue();
- if (state==1)
- {
- // bugfix:load color buffer into accum buffer for the first time(state=1)
- glAccum(GL_LOAD, 1.0f);
- SetMotionBlurState(2);
- }
- else if (motionblurvalue >= 0.0f && motionblurvalue <= 1.0f) {
- glAccum(GL_MULT, motionblurvalue);
- glAccum(GL_ACCUM, 1-motionblurvalue);
- glAccum(GL_RETURN, 1.0f);
- glFlush();
- }
- }
-}
-
-void RAS_OpenGLRasterizer::SetClientObject(void* obj)
-{
- if (m_clientobject != obj)
- {
- bool ccw = (obj == NULL || !((KX_GameObject*)obj)->IsNegativeScaling());
- SetFrontFace(ccw);
-
- m_clientobject = obj;
- }
-}
-
-void RAS_OpenGLRasterizer::SetAuxilaryClientInfo(void* inf)
-{
- m_auxilaryClientInfo = inf;
-}
-
-void RAS_OpenGLRasterizer::PrintHardwareInfo()
-{
- #define pprint(x) std::cout << x << std::endl;
-
- pprint("GL_VENDOR: " << glGetString(GL_VENDOR));
- pprint("GL_RENDERER: " << glGetString(GL_RENDERER));
- pprint("GL_VERSION: " << glGetString(GL_VERSION));
- bool support=0;
- pprint("Supported Extensions...");
- pprint(" GL_ARB_shader_objects supported? "<< (GLEW_ARB_shader_objects?"yes.":"no."));
-
- support= GLEW_ARB_vertex_shader;
- pprint(" GL_ARB_vertex_shader supported? "<< (support?"yes.":"no."));
- if (support) {
- pprint(" ----------Details----------");
- int max=0;
- glGetIntegerv(GL_MAX_VERTEX_UNIFORM_COMPONENTS_ARB, (GLint*)&max);
- pprint(" Max uniform components." << max);
-
- glGetIntegerv(GL_MAX_VARYING_FLOATS_ARB, (GLint*)&max);
- pprint(" Max varying floats." << max);
-
- glGetIntegerv(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS_ARB, (GLint*)&max);
- pprint(" Max vertex texture units." << max);
-
- glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS_ARB, (GLint*)&max);
- pprint(" Max combined texture units." << max);
- pprint("");
- }
-
- support=GLEW_ARB_fragment_shader;
- pprint(" GL_ARB_fragment_shader supported? "<< (support?"yes.":"no."));
- if (support) {
- pprint(" ----------Details----------");
- int max=0;
- glGetIntegerv(GL_MAX_FRAGMENT_UNIFORM_COMPONENTS_ARB, (GLint*)&max);
- pprint(" Max uniform components." << max);
- pprint("");
- }
-
- support = GLEW_ARB_texture_cube_map;
- pprint(" GL_ARB_texture_cube_map supported? "<< (support?"yes.":"no."));
- if (support) {
- pprint(" ----------Details----------");
- int size=0;
- glGetIntegerv(GL_MAX_CUBE_MAP_TEXTURE_SIZE_ARB, (GLint*)&size);
- pprint(" Max cubemap size." << size);
- pprint("");
- }
-
- support = GLEW_ARB_multitexture;
- pprint(" GL_ARB_multitexture supported? "<< (support?"yes.":"no."));
- if (support) {
- pprint(" ----------Details----------");
- int units=0;
- glGetIntegerv(GL_MAX_TEXTURE_UNITS_ARB, (GLint*)&units);
- pprint(" Max texture units available. " << units);
- pprint("");
- }
-
- pprint(" GL_ARB_texture_env_combine supported? "<< (GLEW_ARB_texture_env_combine?"yes.":"no."));
-
- pprint(" GL_ARB_texture_non_power_of_two supported " << (GPU_full_non_power_of_two_support()?"yes.":"no."));
-}
-
diff --git a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLRasterizer.h b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLRasterizer.h
deleted file mode 100644
index 9561e207dba..00000000000
--- a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLRasterizer.h
+++ /dev/null
@@ -1,343 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file RAS_OpenGLRasterizer.h
- * \ingroup bgerastogl
- */
-
-#ifndef __RAS_OPENGLRASTERIZER_H__
-#define __RAS_OPENGLRASTERIZER_H__
-
-#ifdef _MSC_VER
-# pragma warning (disable:4786)
-#endif
-
-#include "MT_CmMatrix4x4.h"
-#include <vector>
-#include <map>
-using namespace std;
-
-#include "RAS_IRasterizer.h"
-#include "RAS_MaterialBucket.h"
-#include "RAS_IPolygonMaterial.h"
-
-#include "BLI_utildefines.h"
-
-class RAS_IStorage;
-class RAS_ICanvas;
-class RAS_OpenGLLight;
-
-#define RAS_MAX_TEXCO 8 /* match in BL_Material */
-#define RAS_MAX_ATTRIB 16 /* match in BL_BlenderShader */
-
-enum RAS_STORAGE_TYPE {
- RAS_AUTO_STORAGE,
- RAS_VA,
- RAS_VBO,
-};
-
-struct OglDebugShape
-{
- enum SHAPE_TYPE{
- LINE,
- CIRCLE,
- };
- SHAPE_TYPE m_type;
- MT_Vector3 m_pos;
- MT_Vector3 m_param;
- MT_Vector3 m_param2;
- MT_Vector3 m_color;
-};
-
-/**
- * 3D rendering device context.
- */
-class RAS_OpenGLRasterizer : public RAS_IRasterizer
-{
- RAS_ICanvas *m_2DCanvas;
-
- /* fogging vars */
- bool m_fogenabled;
-
- float m_redback;
- float m_greenback;
- float m_blueback;
- float m_alphaback;
-
- float m_ambr;
- float m_ambg;
- float m_ambb;
- double m_time;
- MT_Matrix4x4 m_viewmatrix;
- MT_Matrix4x4 m_viewinvmatrix;
- MT_Point3 m_campos;
- bool m_camortho;
- bool m_camnegscale;
-
- StereoMode m_stereomode;
- StereoEye m_curreye;
- float m_eyeseparation;
- float m_focallength;
- bool m_setfocallength;
- int m_noOfScanlines;
-
- short m_prevafvalue;
-
- /* motion blur */
- int m_motionblur;
- float m_motionblurvalue;
-
- bool m_usingoverrideshader;
-
- /* Render tools */
- void *m_clientobject;
- void *m_auxilaryClientInfo;
- std::vector<RAS_OpenGLLight *> m_lights;
- int m_lastlightlayer;
- bool m_lastlighting;
- void *m_lastauxinfo;
- unsigned int m_numgllights;
-
-protected:
- int m_drawingmode;
- TexCoGen m_texco[RAS_MAX_TEXCO];
- TexCoGen m_attrib[RAS_MAX_ATTRIB];
- int m_attrib_layer[RAS_MAX_ATTRIB];
- int m_texco_num;
- int m_attrib_num;
- /* int m_last_alphablend; */
- bool m_last_frontface;
-
- /* Stores the caching information for the last material activated. */
- RAS_IPolyMaterial::TCachingInfo m_materialCachingInfo;
-
- /* Making use of a Strategy design pattern for storage behavior.
- * Examples of concrete strategies: Vertex Arrays, VBOs, Immediate Mode*/
- int m_storage_type;
- RAS_IStorage *m_storage;
-
-public:
- double GetTime();
- RAS_OpenGLRasterizer(RAS_ICanvas *canv, RAS_STORAGE_TYPE storage);
- virtual ~RAS_OpenGLRasterizer();
-
- /*enum DrawType
- {
- KX_BOUNDINGBOX = 1,
- KX_WIREFRAME,
- KX_SOLID,
- KX_SHADED,
- KX_TEXTURED
- };
-
- enum DepthMask
- {
- KX_DEPTHMASK_ENABLED =1,
- KX_DEPTHMASK_DISABLED,
- };*/
- virtual void SetDepthMask(DepthMask depthmask);
-
- virtual bool SetMaterial(const RAS_IPolyMaterial &mat);
- virtual bool Init();
- virtual void Exit();
- virtual bool BeginFrame(double time);
- virtual void ClearColorBuffer();
- virtual void ClearDepthBuffer();
- virtual void ClearCachingInfo(void);
- virtual void EndFrame();
- virtual void SetRenderArea();
-
- virtual void SetStereoMode(const StereoMode stereomode);
- virtual RAS_IRasterizer::StereoMode GetStereoMode();
- virtual bool Stereo();
- virtual bool InterlacedStereo();
- virtual void SetEye(const StereoEye eye);
- virtual StereoEye GetEye();
- virtual void SetEyeSeparation(const float eyeseparation);
- virtual float GetEyeSeparation();
- virtual void SetFocalLength(const float focallength);
- virtual float GetFocalLength();
- virtual RAS_IOffScreen *CreateOffScreen(int width, int height, int samples, int target);
- virtual RAS_ISync *CreateSync(int type);
- virtual void SwapBuffers();
-
- virtual void IndexPrimitives(class RAS_MeshSlot &ms);
- virtual void IndexPrimitives_3DText(class RAS_MeshSlot &ms, class RAS_IPolyMaterial *polymat);
- virtual void DrawDerivedMesh(class RAS_MeshSlot &ms);
-
- virtual void SetProjectionMatrix(MT_CmMatrix4x4 &mat);
- virtual void SetProjectionMatrix(const MT_Matrix4x4 &mat);
- virtual void SetViewMatrix(
- const MT_Matrix4x4 &mat,
- const MT_Matrix3x3 &ori,
- const MT_Point3 &pos,
- const MT_Vector3 &scale,
- bool perspective);
-
- virtual const MT_Point3& GetCameraPosition();
- virtual bool GetCameraOrtho();
-
- virtual void SetFog(short type, float start, float dist, float intensity, float color[3]);
- virtual void EnableFog(bool enable);
- virtual void DisplayFog();
-
- virtual void SetBackColor(float color[3]);
-
- virtual void SetDrawingMode(int drawingmode);
- virtual int GetDrawingMode();
-
- virtual void SetCullFace(bool enable);
- virtual void SetLines(bool enable);
-
- virtual MT_Matrix4x4 GetFrustumMatrix(
- float left, float right, float bottom, float top,
- float frustnear, float frustfar,
- float focallength, bool perspective);
- virtual MT_Matrix4x4 GetOrthoMatrix(
- float left, float right, float bottom, float top,
- float frustnear, float frustfar);
-
- virtual void SetSpecularity(float specX, float specY, float specZ, float specval);
- virtual void SetShinyness(float shiny);
- virtual void SetDiffuse(float difX, float difY, float difZ, float diffuse);
- virtual void SetEmissive(float eX, float eY, float eZ, float e);
-
- virtual void SetAmbientColor(float color[3]);
- virtual void SetAmbient(float factor);
-
- virtual void SetPolygonOffset(float mult, float add);
-
- virtual void FlushDebugShapes(SCA_IScene *scene);
-
- virtual void DrawDebugLine(SCA_IScene *scene, const MT_Vector3 &from,const MT_Vector3 &to, const MT_Vector3 &color)
- {
- OglDebugShape line;
- line.m_type = OglDebugShape::LINE;
- line.m_pos= from;
- line.m_param = to;
- line.m_color = color;
- m_debugShapes[scene].push_back(line);
- }
-
- virtual void DrawDebugCircle(SCA_IScene *scene, const MT_Vector3 &center, const MT_Scalar radius,
- const MT_Vector3 &color, const MT_Vector3 &normal, int nsector)
- {
- OglDebugShape line;
- line.m_type = OglDebugShape::CIRCLE;
- line.m_pos= center;
- line.m_param = normal;
- line.m_color = color;
- line.m_param2.x() = radius;
- line.m_param2.y() = (float) nsector;
- m_debugShapes[scene].push_back(line);
- }
-
- // We store each debug shape by scene.
- std::map<SCA_IScene *, std::vector<OglDebugShape> > m_debugShapes;
-
- virtual void SetTexCoordNum(int num);
- virtual void SetAttribNum(int num);
- virtual void SetTexCoord(TexCoGen coords, int unit);
- virtual void SetAttrib(TexCoGen coords, int unit, int layer = 0);
-
- void TexCoord(const RAS_TexVert &tv);
-
- const MT_Matrix4x4 &GetViewMatrix() const;
- const MT_Matrix4x4 &GetViewInvMatrix() const;
-
- virtual void EnableMotionBlur(float motionblurvalue);
- virtual void DisableMotionBlur();
- virtual float GetMotionBlurValue() { return m_motionblurvalue; }
- virtual int GetMotionBlurState() { return m_motionblur; }
- virtual void SetMotionBlurState(int newstate)
- {
- if (newstate < 0)
- m_motionblur = 0;
- else if (newstate > 2)
- m_motionblur = 2;
- else
- m_motionblur = newstate;
- }
-
- virtual void SetAlphaBlend(int alphablend);
- virtual void SetFrontFace(bool ccw);
-
- virtual void SetAnisotropicFiltering(short level);
- virtual short GetAnisotropicFiltering();
-
- virtual void SetMipmapping(MipmapOption val);
- virtual MipmapOption GetMipmapping();
-
- virtual void SetUsingOverrideShader(bool val);
- virtual bool GetUsingOverrideShader();
-
- /**
- * Render Tools
- */
- void EnableOpenGLLights();
- void DisableOpenGLLights();
- void ProcessLighting(bool uselights, const MT_Transform &viewmat);
-
- void RenderBox2D(int xco, int yco, int width, int height, float percentage);
- void RenderText3D(int fontid, const char *text, int size, int dpi,
- const float color[4], const float mat[16], float aspect);
- void RenderText2D(RAS_TEXT_RENDER_MODE mode, const char *text,
- int xco, int yco, int width, int height);
-
- void applyTransform(float *oglmatrix, int objectdrawmode);
-
- void PushMatrix();
- void PopMatrix();
-
- /// \see KX_RayCast
- bool RayHit(struct KX_ClientObjectInfo *client, class KX_RayCast *result, float *oglmatrix);
- /// \see KX_RayCast
- bool NeedRayCast(struct KX_ClientObjectInfo *, void *UNUSED(data)) { return true; }
-
- RAS_ILightObject* CreateLight();
- void AddLight(RAS_ILightObject* lightobject);
-
- void RemoveLight(RAS_ILightObject* lightobject);
- int ApplyLights(int objectlayer, const MT_Transform& viewmat);
-
- void MotionBlur();
-
- void SetClientObject(void *obj);
-
- void SetAuxilaryClientInfo(void *inf);
-
- /**
- * Prints information about what the hardware supports.
- */
- virtual void PrintHardwareInfo();
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:RAS_OpenGLRasterizer")
-#endif
-};
-
-#endif /* __RAS_OPENGLRASTERIZER_H__ */
diff --git a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLSync.cpp b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLSync.cpp
deleted file mode 100644
index 26b956cd74e..00000000000
--- a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLSync.cpp
+++ /dev/null
@@ -1,82 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2015, Blender Foundation
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): Blender Foundation.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-#include "GPU_glew.h"
-
-#include <stdio.h>
-
-#include "RAS_OpenGLSync.h"
-
-RAS_OpenGLSync::RAS_OpenGLSync()
- :m_sync(NULL)
-{
-}
-
-RAS_OpenGLSync::~RAS_OpenGLSync()
-{
- Destroy();
-}
-
-bool RAS_OpenGLSync::Create(RAS_SYNC_TYPE type)
-{
- if (m_sync) {
- printf("RAS_OpenGLSync::Create(): sync already exists, destroy first\n");
- return false;
- }
- if (type != RAS_SYNC_TYPE_FENCE) {
- printf("RAS_OpenGLSync::Create(): only RAS_SYNC_TYPE_FENCE are currently supported\n");
- return false;
- }
- if (!GLEW_ARB_sync) {
- printf("RAS_OpenGLSync::Create(): ARB_sync extension is needed to create sync object\n");
- return false;
- }
- m_sync = glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0);
- if (!m_sync) {
- printf("RAS_OpenGLSync::Create(): glFenceSync() failed");
- return false;
- }
- return true;
-}
-
-void RAS_OpenGLSync::Destroy()
-{
- if (m_sync) {
- glDeleteSync(m_sync);
- m_sync = NULL;
- }
-}
-
-void RAS_OpenGLSync::Wait()
-{
- if (m_sync) {
- // this is needed to ensure that the sync is in the GPU
- glFlush();
- // block until the operation have completed
- glWaitSync(m_sync, 0, GL_TIMEOUT_IGNORED);
- }
-}
diff --git a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLSync.h b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLSync.h
deleted file mode 100644
index 4ba96903856..00000000000
--- a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLSync.h
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2015, Blender Foundation
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): Blender Foundation.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-#ifndef __RAS_OPENGLSYNC__
-#define __RAS_OPENGLSYNC__
-
-
-#include "RAS_ISync.h"
-
-struct __GLsync;
-
-class RAS_OpenGLSync : public RAS_ISync
-{
-private:
- struct __GLsync *m_sync;
-
-public:
- RAS_OpenGLSync();
- ~RAS_OpenGLSync();
-
- virtual bool Create(RAS_SYNC_TYPE type);
- virtual void Destroy();
- virtual void Wait();
-};
-
-#endif /* __RAS_OPENGLSYNC__ */
diff --git a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_StorageVA.cpp b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_StorageVA.cpp
deleted file mode 100644
index f980116f5f8..00000000000
--- a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_StorageVA.cpp
+++ /dev/null
@@ -1,260 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-#include "RAS_StorageVA.h"
-
-#include "GPU_glew.h"
-
-RAS_StorageVA::RAS_StorageVA(int *texco_num, RAS_IRasterizer::TexCoGen *texco, int *attrib_num, RAS_IRasterizer::TexCoGen *attrib, int *attrib_layer) :
- m_drawingmode(RAS_IRasterizer::KX_TEXTURED),
- m_texco_num(texco_num),
- m_attrib_num(attrib_num),
- m_last_texco_num(0),
- m_last_attrib_num(0),
- m_texco(texco),
- m_attrib(attrib),
- m_attrib_layer(attrib_layer)
-{
-}
-
-RAS_StorageVA::~RAS_StorageVA()
-{
-}
-
-bool RAS_StorageVA::Init()
-{
- glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
-
- return true;
-}
-
-void RAS_StorageVA::Exit()
-{
-}
-
-void RAS_StorageVA::IndexPrimitives(class RAS_MeshSlot& ms)
-{
- static const GLsizei stride = sizeof(RAS_TexVert);
- bool wireframe = m_drawingmode <= RAS_IRasterizer::KX_WIREFRAME, use_color_array = true;
- RAS_MeshSlot::iterator it;
- GLenum drawmode;
-
- if (!wireframe)
- EnableTextures(true);
- glEnableClientState(GL_VERTEX_ARRAY);
- glEnableClientState(GL_NORMAL_ARRAY);
-
- // use glDrawElements to draw each vertexarray
- for (ms.begin(it); !ms.end(it); ms.next(it)) {
- if (it.totindex == 0)
- continue;
-
- // drawing mode
- if (it.array->m_type == RAS_DisplayArray::TRIANGLE)
- drawmode = GL_TRIANGLES;
- else if (it.array->m_type == RAS_DisplayArray::QUAD)
- drawmode = GL_QUADS;
- else
- drawmode = GL_LINES;
-
- // colors
- if (drawmode != GL_LINES && !wireframe) {
- if (ms.m_bObjectColor) {
- const MT_Vector4& rgba = ms.m_RGBAcolor;
-
- glDisableClientState(GL_COLOR_ARRAY);
- glColor4d(rgba[0], rgba[1], rgba[2], rgba[3]);
- use_color_array = false;
- }
- else {
- glColor4f(0.0f, 0.0f, 0.0f, 1.0f);
- glEnableClientState(GL_COLOR_ARRAY);
- use_color_array = true;
- }
- }
- else
- glColor4f(0.0f, 0.0f, 0.0f, 1.0f);
-
- glVertexPointer(3, GL_FLOAT, stride, it.vertex->getXYZ());
- glNormalPointer(GL_FLOAT, stride, it.vertex->getNormal());
-
- if (!wireframe) {
- TexCoordPtr(it.vertex);
- if (use_color_array)
- glColorPointer(4, GL_UNSIGNED_BYTE, stride, it.vertex->getRGBA());
- }
-
- // here the actual drawing takes places
- glDrawElements(drawmode, it.totindex, GL_UNSIGNED_SHORT, it.index);
- }
-
- glDisableClientState(GL_VERTEX_ARRAY);
- glDisableClientState(GL_NORMAL_ARRAY);
- if (!wireframe) {
- glDisableClientState(GL_COLOR_ARRAY);
- EnableTextures(false);
- }
-}
-
-void RAS_StorageVA::TexCoordPtr(const RAS_TexVert *tv)
-{
- /* note: this function must closely match EnableTextures to enable/disable
- * the right arrays, otherwise coordinate and attribute pointers from other
- * materials can still be used and cause crashes */
- int unit;
-
- if (GLEW_ARB_multitexture)
- {
- for (unit = 0; unit < *m_texco_num; unit++)
- {
- glClientActiveTextureARB(GL_TEXTURE0_ARB+unit);
- switch (m_texco[unit]) {
- case RAS_IRasterizer::RAS_TEXCO_ORCO:
- case RAS_IRasterizer::RAS_TEXCO_GLOB:
- glTexCoordPointer(3, GL_FLOAT, sizeof(RAS_TexVert),tv->getXYZ());
- break;
- case RAS_IRasterizer::RAS_TEXCO_UV:
- glTexCoordPointer(2, GL_FLOAT, sizeof(RAS_TexVert),tv->getUV(unit));
- break;
- case RAS_IRasterizer::RAS_TEXCO_NORM:
- glTexCoordPointer(3, GL_FLOAT, sizeof(RAS_TexVert),tv->getNormal());
- break;
- case RAS_IRasterizer::RAS_TEXTANGENT:
- glTexCoordPointer(4, GL_FLOAT, sizeof(RAS_TexVert),tv->getTangent());
- break;
- default:
- break;
- }
- }
-
- glClientActiveTextureARB(GL_TEXTURE0_ARB);
- }
-
- if (GLEW_ARB_vertex_program) {
- for (unit = 0; unit < *m_attrib_num; unit++) {
- switch (m_attrib[unit]) {
- case RAS_IRasterizer::RAS_TEXCO_ORCO:
- case RAS_IRasterizer::RAS_TEXCO_GLOB:
- glVertexAttribPointerARB(unit, 3, GL_FLOAT, GL_FALSE, sizeof(RAS_TexVert), tv->getXYZ());
- break;
- case RAS_IRasterizer::RAS_TEXCO_UV:
- glVertexAttribPointerARB(unit, 2, GL_FLOAT, GL_FALSE, sizeof(RAS_TexVert), tv->getUV(m_attrib_layer[unit]));
- break;
- case RAS_IRasterizer::RAS_TEXCO_NORM:
- glVertexAttribPointerARB(unit, 3, GL_FLOAT, GL_FALSE, sizeof(RAS_TexVert), tv->getNormal());
- break;
- case RAS_IRasterizer::RAS_TEXTANGENT:
- glVertexAttribPointerARB(unit, 4, GL_FLOAT, GL_FALSE, sizeof(RAS_TexVert), tv->getTangent());
- break;
- case RAS_IRasterizer::RAS_TEXCO_VCOL:
- glVertexAttribPointerARB(unit, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(RAS_TexVert), tv->getRGBA());
- break;
- default:
- break;
- }
- }
- }
-}
-
-void RAS_StorageVA::EnableTextures(bool enable)
-{
- RAS_IRasterizer::TexCoGen *texco, *attrib;
- int unit, texco_num, attrib_num;
-
- /* we cache last texcoords and attribs to ensure we disable the ones that
- * were actually last set */
- if (enable) {
- texco = m_texco;
- texco_num = *m_texco_num;
- attrib = m_attrib;
- attrib_num = *m_attrib_num;
-
- memcpy(m_last_texco, m_texco, sizeof(RAS_IRasterizer::TexCoGen)*(*m_texco_num));
- m_last_texco_num = *m_texco_num;
- memcpy(m_last_attrib, m_attrib, sizeof(RAS_IRasterizer::TexCoGen)*(*m_attrib_num));
- m_last_attrib_num = *m_attrib_num;
- }
- else {
- texco = m_last_texco;
- texco_num = m_last_texco_num;
- attrib = m_last_attrib;
- attrib_num = m_last_attrib_num;
- }
-
- if (GLEW_ARB_multitexture) {
- for (unit = 0; unit < texco_num; unit++) {
- glClientActiveTextureARB(GL_TEXTURE0_ARB + unit);
-
- switch (texco[unit]) {
- case RAS_IRasterizer::RAS_TEXCO_ORCO:
- case RAS_IRasterizer::RAS_TEXCO_GLOB:
- case RAS_IRasterizer::RAS_TEXCO_UV:
- case RAS_IRasterizer::RAS_TEXCO_NORM:
- case RAS_IRasterizer::RAS_TEXTANGENT:
- if (enable) glEnableClientState(GL_TEXTURE_COORD_ARRAY);
- else glDisableClientState(GL_TEXTURE_COORD_ARRAY);
- break;
- default:
- glDisableClientState(GL_TEXTURE_COORD_ARRAY);
- break;
- }
- }
-
- glClientActiveTextureARB(GL_TEXTURE0_ARB);
- }
- else {
- if (texco_num) {
- if (enable) glEnableClientState(GL_TEXTURE_COORD_ARRAY);
- else glDisableClientState(GL_TEXTURE_COORD_ARRAY);
- }
- }
-
- if (GLEW_ARB_vertex_program) {
- for (unit = 0; unit < attrib_num; unit++) {
- switch (attrib[unit]) {
- case RAS_IRasterizer::RAS_TEXCO_ORCO:
- case RAS_IRasterizer::RAS_TEXCO_GLOB:
- case RAS_IRasterizer::RAS_TEXCO_UV:
- case RAS_IRasterizer::RAS_TEXCO_NORM:
- case RAS_IRasterizer::RAS_TEXTANGENT:
- case RAS_IRasterizer::RAS_TEXCO_VCOL:
- if (enable) glEnableVertexAttribArrayARB(unit);
- else glDisableVertexAttribArrayARB(unit);
- break;
- default:
- glDisableVertexAttribArrayARB(unit);
- break;
- }
- }
- }
-
- if (!enable) {
- m_last_texco_num = 0;
- m_last_attrib_num = 0;
- }
-}
-
diff --git a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_StorageVA.h b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_StorageVA.h
deleted file mode 100644
index a5a3170ed77..00000000000
--- a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_StorageVA.h
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-#ifndef __KX_VERTEXARRAYSTORAGE
-#define __KX_VERTEXARRAYSTORAGE
-
-#include "RAS_IStorage.h"
-#include "RAS_IRasterizer.h"
-
-#include "RAS_OpenGLRasterizer.h"
-
-class RAS_StorageVA : public RAS_IStorage
-{
-
-public:
- RAS_StorageVA(int *texco_num, RAS_IRasterizer::TexCoGen *texco, int *attrib_num, RAS_IRasterizer::TexCoGen *attrib, int *attrib_layer);
- virtual ~RAS_StorageVA();
-
- virtual bool Init();
- virtual void Exit();
-
- virtual void IndexPrimitives(RAS_MeshSlot& ms);
-
- virtual void SetDrawingMode(int drawingmode) {m_drawingmode = drawingmode;};
-
-protected:
- int m_drawingmode;
-
- int* m_texco_num;
- int* m_attrib_num;
-
- int m_last_texco_num;
- int m_last_attrib_num;
-
- RAS_IRasterizer::TexCoGen* m_texco;
- RAS_IRasterizer::TexCoGen* m_attrib;
- int* m_attrib_layer;
-
- RAS_IRasterizer::TexCoGen m_last_texco[RAS_MAX_TEXCO];
- RAS_IRasterizer::TexCoGen m_last_attrib[RAS_MAX_ATTRIB];
-
- virtual void EnableTextures(bool enable);
- virtual void TexCoordPtr(const RAS_TexVert *tv);
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
-public:
- void *operator new(size_t num_bytes) { return MEM_mallocN(num_bytes, "GE:RAS_StorageVA"); }
- void operator delete( void *mem ) { MEM_freeN(mem); }
-#endif
-};
-
-#endif //__KX_VERTEXARRAYSTORAGE
diff --git a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_StorageVBO.cpp b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_StorageVBO.cpp
deleted file mode 100644
index 4ba5882a46e..00000000000
--- a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_StorageVBO.cpp
+++ /dev/null
@@ -1,227 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-#include "RAS_StorageVBO.h"
-#include "RAS_MeshObject.h"
-
-#include "GPU_glew.h"
-
-VBO::VBO(RAS_DisplayArray *data, unsigned int indices)
-{
- this->data = data;
- this->size = data->m_vertex.size();
- this->indices = indices;
- this->stride = sizeof(RAS_TexVert);
-
- // Determine drawmode
- if (data->m_type == data->QUAD)
- this->mode = GL_QUADS;
- else if (data->m_type == data->TRIANGLE)
- this->mode = GL_TRIANGLES;
- else
- this->mode = GL_LINE;
-
- // Generate Buffers
- glGenBuffersARB(1, &this->ibo);
- glGenBuffersARB(1, &this->vbo_id);
-
- // Fill the buffers with initial data
- UpdateIndices();
- UpdateData();
-
- // Establish offsets
- this->vertex_offset = (void*)(((RAS_TexVert*)0)->getXYZ());
- this->normal_offset = (void*)(((RAS_TexVert*)0)->getNormal());
- this->tangent_offset = (void*)(((RAS_TexVert*)0)->getTangent());
- this->color_offset = (void*)(((RAS_TexVert*)0)->getRGBA());
- this->uv_offset = (void*)(((RAS_TexVert*)0)->getUV(0));
-}
-
-VBO::~VBO()
-{
- glDeleteBuffersARB(1, &this->ibo);
- glDeleteBuffersARB(1, &this->vbo_id);
-}
-
-void VBO::UpdateData()
-{
- glBindBufferARB(GL_ARRAY_BUFFER_ARB, this->vbo_id);
- glBufferData(GL_ARRAY_BUFFER, this->stride*this->size, &this->data->m_vertex[0], GL_STATIC_DRAW);
-}
-
-void VBO::UpdateIndices()
-{
- glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, this->ibo);
- glBufferData(GL_ELEMENT_ARRAY_BUFFER, data->m_index.size() * sizeof(GLushort),
- &data->m_index[0], GL_STATIC_DRAW);
-}
-
-void VBO::Draw(int texco_num, RAS_IRasterizer::TexCoGen* texco, int attrib_num, RAS_IRasterizer::TexCoGen* attrib, int *attrib_layer)
-{
- int unit;
-
- // Bind buffers
- glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, this->ibo);
- glBindBufferARB(GL_ARRAY_BUFFER_ARB, this->vbo_id);
-
- // Vertexes
- glEnableClientState(GL_VERTEX_ARRAY);
- glVertexPointer(3, GL_FLOAT, this->stride, this->vertex_offset);
-
- // Normals
- glEnableClientState(GL_NORMAL_ARRAY);
- glNormalPointer(GL_FLOAT, this->stride, this->normal_offset);
-
- // Colors
- glEnableClientState(GL_COLOR_ARRAY);
- glColorPointer(4, GL_UNSIGNED_BYTE, this->stride, this->color_offset);
-
- for (unit = 0; unit < texco_num; ++unit)
- {
- glClientActiveTexture(GL_TEXTURE0_ARB + unit);
- switch (texco[unit]) {
- case RAS_IRasterizer::RAS_TEXCO_ORCO:
- case RAS_IRasterizer::RAS_TEXCO_GLOB:
- glEnableClientState(GL_TEXTURE_COORD_ARRAY);
- glTexCoordPointer(3, GL_FLOAT, this->stride, this->vertex_offset);
- break;
- case RAS_IRasterizer::RAS_TEXCO_UV:
- glEnableClientState(GL_TEXTURE_COORD_ARRAY);
- glTexCoordPointer(2, GL_FLOAT, this->stride, (void*)((intptr_t)this->uv_offset+(sizeof(GLfloat)*2*unit)));
- break;
- case RAS_IRasterizer::RAS_TEXCO_NORM:
- glEnableClientState(GL_TEXTURE_COORD_ARRAY);
- glTexCoordPointer(3, GL_FLOAT, this->stride, this->normal_offset);
- break;
- case RAS_IRasterizer::RAS_TEXTANGENT:
- glEnableClientState(GL_TEXTURE_COORD_ARRAY);
- glTexCoordPointer(4, GL_FLOAT, this->stride, this->tangent_offset);
- break;
- default:
- break;
- }
- }
- glClientActiveTextureARB(GL_TEXTURE0_ARB);
-
- if (GLEW_ARB_vertex_program)
- {
- for (unit = 0; unit < attrib_num; ++unit)
- {
- switch (attrib[unit]) {
- case RAS_IRasterizer::RAS_TEXCO_ORCO:
- case RAS_IRasterizer::RAS_TEXCO_GLOB:
- glVertexAttribPointerARB(unit, 3, GL_FLOAT, GL_FALSE, this->stride, this->vertex_offset);
- glEnableVertexAttribArrayARB(unit);
- break;
- case RAS_IRasterizer::RAS_TEXCO_UV:
- glVertexAttribPointerARB(unit, 2, GL_FLOAT, GL_FALSE, this->stride, (void*)((intptr_t)this->uv_offset+attrib_layer[unit]*sizeof(GLfloat)*2));
- glEnableVertexAttribArrayARB(unit);
- break;
- case RAS_IRasterizer::RAS_TEXCO_NORM:
- glVertexAttribPointerARB(unit, 2, GL_FLOAT, GL_FALSE, stride, this->normal_offset);
- glEnableVertexAttribArrayARB(unit);
- break;
- case RAS_IRasterizer::RAS_TEXTANGENT:
- glVertexAttribPointerARB(unit, 4, GL_FLOAT, GL_FALSE, this->stride, this->tangent_offset);
- glEnableVertexAttribArrayARB(unit);
- break;
- case RAS_IRasterizer::RAS_TEXCO_VCOL:
- glVertexAttribPointerARB(unit, 4, GL_UNSIGNED_BYTE, GL_TRUE, this->stride, this->color_offset);
- glEnableVertexAttribArrayARB(unit);
- default:
- break;
- }
- }
- }
-
- glDrawElements(this->mode, this->indices, GL_UNSIGNED_SHORT, 0);
-
- glDisableClientState(GL_VERTEX_ARRAY);
- glDisableClientState(GL_NORMAL_ARRAY);
- glDisableClientState(GL_COLOR_ARRAY);
- glDisableClientState(GL_TEXTURE_COORD_ARRAY);
-
- if (GLEW_ARB_vertex_program)
- {
- for (int i = 0; i < attrib_num; ++i)
- glDisableVertexAttribArrayARB(i);
- }
-
- glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0);
- glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, 0);
-}
-
-RAS_StorageVBO::RAS_StorageVBO(int *texco_num, RAS_IRasterizer::TexCoGen *texco, int *attrib_num, RAS_IRasterizer::TexCoGen *attrib, int *attrib_layer):
- m_drawingmode(RAS_IRasterizer::KX_TEXTURED),
- m_texco_num(texco_num),
- m_attrib_num(attrib_num),
- m_texco(texco),
- m_attrib(attrib),
- m_attrib_layer(attrib_layer)
-{
-}
-
-RAS_StorageVBO::~RAS_StorageVBO()
-{
-}
-
-bool RAS_StorageVBO::Init()
-{
- return true;
-}
-
-void RAS_StorageVBO::Exit()
-{
- VBOMap::iterator it = m_vbo_lookup.begin();
- while (it != m_vbo_lookup.end()) {
- delete it->second;
- ++it;
- }
- m_vbo_lookup.clear();
-}
-
-void RAS_StorageVBO::IndexPrimitives(RAS_MeshSlot& ms)
-{
- RAS_MeshSlot::iterator it;
- VBO *vbo;
-
- for (ms.begin(it); !ms.end(it); ms.next(it))
- {
- vbo = m_vbo_lookup[it.array];
-
- if (vbo == 0)
- m_vbo_lookup[it.array] = vbo = new VBO(it.array, it.totindex);
-
- // Update the vbo
- if (ms.m_mesh->MeshModified())
- {
- vbo->UpdateData();
- }
-
- vbo->Draw(*m_texco_num, m_texco, *m_attrib_num, m_attrib, m_attrib_layer);
- }
-}
diff --git a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_StorageVBO.h b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_StorageVBO.h
deleted file mode 100644
index c82b6a3206d..00000000000
--- a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_StorageVBO.h
+++ /dev/null
@@ -1,100 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-#ifndef __KX_VERTEXBUFFEROBJECTSTORAGE
-#define __KX_VERTEXBUFFEROBJECTSTORAGE
-
-#include <map>
-#include "GPU_glew.h"
-
-#include "RAS_IStorage.h"
-#include "RAS_IRasterizer.h"
-
-#include "RAS_OpenGLRasterizer.h"
-
-class VBO
-{
-public:
- VBO(RAS_DisplayArray *data, unsigned int indices);
- ~VBO();
-
- void Draw(int texco_num, RAS_IRasterizer::TexCoGen* texco, int attrib_num, RAS_IRasterizer::TexCoGen* attrib, int *attrib_layer);
-
- void UpdateData();
- void UpdateIndices();
-private:
- RAS_DisplayArray* data;
- GLuint size;
- GLuint stride;
- GLuint indices;
- GLenum mode;
- GLuint ibo;
- GLuint vbo_id;
-
- void* vertex_offset;
- void* normal_offset;
- void* color_offset;
- void* tangent_offset;
- void* uv_offset;
-};
-
-typedef std::map<RAS_DisplayArray*, VBO*> VBOMap;
-
-class RAS_StorageVBO : public RAS_IStorage
-{
-
-public:
- RAS_StorageVBO(int *texco_num, RAS_IRasterizer::TexCoGen *texco, int *attrib_num, RAS_IRasterizer::TexCoGen *attrib, int *attrib_layer);
- virtual ~RAS_StorageVBO();
-
- virtual bool Init();
- virtual void Exit();
-
- virtual void IndexPrimitives(RAS_MeshSlot& ms);
-
- virtual void SetDrawingMode(int drawingmode) {m_drawingmode = drawingmode;};
-
-protected:
- int m_drawingmode;
-
- int* m_texco_num;
- int* m_attrib_num;
-
- RAS_IRasterizer::TexCoGen* m_texco;
- RAS_IRasterizer::TexCoGen* m_attrib;
- int* m_attrib_layer;
-
- VBOMap m_vbo_lookup;
-
-#ifdef WITH_CXX_GUARDEDALLOC
-public:
- void *operator new(size_t num_bytes) { return MEM_mallocN(num_bytes, "GE:RAS_StorageVA"); }
- void operator delete( void *mem ) { MEM_freeN(mem); }
-#endif
-};
-
-#endif //__KX_VERTEXBUFFEROBJECTSTORAGE
diff --git a/source/gameengine/Rasterizer/RAS_Polygon.cpp b/source/gameengine/Rasterizer/RAS_Polygon.cpp
deleted file mode 100644
index 3274ded4406..00000000000
--- a/source/gameengine/Rasterizer/RAS_Polygon.cpp
+++ /dev/null
@@ -1,123 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Rasterizer/RAS_Polygon.cpp
- * \ingroup bgerast
- */
-
-#ifdef _MSC_VER
-# pragma warning (disable:4786)
-#endif
-
-#include "RAS_Polygon.h"
-#include "RAS_MaterialBucket.h"
-
-RAS_Polygon::RAS_Polygon(RAS_MaterialBucket* bucket, RAS_DisplayArray *darray, int numvert)
-{
- m_bucket = bucket;
- m_darray = darray;
- m_offset[0] = m_offset[1] = m_offset[2] = m_offset[3] = 0;
- m_numvert = numvert;
-
-// m_edgecode = 255;
- m_polyflags = 0;
-}
-
-int RAS_Polygon::VertexCount()
-{
- return m_numvert;
-}
-
-void RAS_Polygon::SetVertexOffset(int i, unsigned short offset)
-{
- m_offset[i] = offset;
-}
-
-RAS_TexVert *RAS_Polygon::GetVertex(int i)
-{
- return &m_darray->m_vertex[m_offset[i]];
-}
-
-unsigned int RAS_Polygon::GetVertexOffsetAbsolute(unsigned short i)
-{
- return m_offset[i] + m_darray->m_offset;
-}
-
-/*
-int RAS_Polygon::GetEdgeCode()
-{
- return m_edgecode;
-}
-
-void RAS_Polygon::SetEdgeCode(int edgecode)
-{
- m_edgecode = edgecode;
-}*/
-
-
-bool RAS_Polygon::IsVisible()
-{
- return (m_polyflags & VISIBLE) != 0;
-}
-
-void RAS_Polygon::SetVisible(bool visible)
-{
- if (visible) m_polyflags |= VISIBLE;
- else m_polyflags &= ~VISIBLE;
-}
-
-bool RAS_Polygon::IsCollider()
-{
- return (m_polyflags & COLLIDER) != 0;
-}
-
-void RAS_Polygon::SetCollider(bool visible)
-{
- if (visible) m_polyflags |= COLLIDER;
- else m_polyflags &= ~COLLIDER;
-}
-
-bool RAS_Polygon::IsTwoside()
-{
- return (m_polyflags & TWOSIDE) != 0;
-}
-
-void RAS_Polygon::SetTwoside(bool twoside)
-{
- if (twoside) m_polyflags |= TWOSIDE;
- else m_polyflags &= ~TWOSIDE;
-}
-
-RAS_MaterialBucket* RAS_Polygon::GetMaterial()
-{
- return m_bucket;
-}
-
-RAS_DisplayArray* RAS_Polygon::GetDisplayArray()
-{
- return m_darray;
-}
diff --git a/source/gameengine/Rasterizer/RAS_Polygon.h b/source/gameengine/Rasterizer/RAS_Polygon.h
deleted file mode 100644
index 597e80ffdfb..00000000000
--- a/source/gameengine/Rasterizer/RAS_Polygon.h
+++ /dev/null
@@ -1,101 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file RAS_Polygon.h
- * \ingroup bgerast
- */
-
-#ifndef __RAS_POLYGON_H__
-#define __RAS_POLYGON_H__
-
-class RAS_DisplayArray;
-class RAS_MaterialBucket;
-class RAS_TexVert;
-
-#ifdef WITH_CXX_GUARDEDALLOC
-#include "MEM_guardedalloc.h"
-#endif
-
-/* polygon flags */
-
-class RAS_Polygon
-{
- /* location */
- RAS_MaterialBucket* m_bucket;
- RAS_DisplayArray* m_darray;
- unsigned short m_offset[4];
- unsigned short m_numvert;
-
- /* flags */
-#if 1
- unsigned short m_polyflags;
-#else
- unsigned char m_edgecode;
- unsigned char m_polyflags;
-#endif
-
-public:
- enum {
- VISIBLE = 1,
- COLLIDER = 2,
- TWOSIDE = 4
- };
-
- RAS_Polygon(RAS_MaterialBucket* bucket, RAS_DisplayArray* darray, int numvert);
- virtual ~RAS_Polygon() {};
-
- int VertexCount();
- RAS_TexVert* GetVertex(int i);
-
- void SetVertexOffset(int i, unsigned short offset);
- unsigned int GetVertexOffsetAbsolute(unsigned short i);
-
- // each bit is for a visible edge, starting with bit 1 for the first edge, bit 2 for second etc.
- // - Not used yet!
-/* int GetEdgeCode();
- void SetEdgeCode(int edgecode); */
-
- bool IsVisible();
- void SetVisible(bool visible);
-
- bool IsCollider();
- void SetCollider(bool collider);
-
- bool IsTwoside();
- void SetTwoside(bool twoside);
-
- RAS_MaterialBucket* GetMaterial();
- RAS_DisplayArray* GetDisplayArray();
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:RAS_Polygon")
-#endif
-};
-
-#endif
-
diff --git a/source/gameengine/Rasterizer/RAS_Rect.h b/source/gameengine/Rasterizer/RAS_Rect.h
deleted file mode 100644
index fc99c9159db..00000000000
--- a/source/gameengine/Rasterizer/RAS_Rect.h
+++ /dev/null
@@ -1,104 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file RAS_Rect.h
- * \ingroup bgerast
- */
-
-#ifndef __RAS_RECT_H__
-#define __RAS_RECT_H__
-
-#ifdef WITH_CXX_GUARDEDALLOC
-#include "MEM_guardedalloc.h"
-#endif
-
-/**
- * \section interface class.
- * RAS_Rect just encodes a simple rectangle.
- * \note Should be part of a generic library
- */
-class RAS_Rect
-{
-public: // todo: make a decent class, and make private
- int m_x1, m_y1;
- int m_x2, m_y2;
-
-public:
- RAS_Rect() : m_x1(0), m_y1(0), m_x2(0), m_y2(0) {}
- int GetWidth(
- ) const {
- return m_x2 - m_x1;
- }
- int GetHeight(
- ) const {
- return m_y2 - m_y1;
- }
- int GetLeft(
- ) const {
- return m_x1;
- }
- int GetRight(
- ) const {
- return m_x2;
- }
- int GetBottom(
- ) const {
- return m_y1;
- }
- int GetTop(
- ) const {
- return m_y2;
- }
-
- void SetLeft(
- int x1)
- {
- m_x1 = x1;
- }
- void SetBottom(
- int y1)
- {
- m_y1 = y1;
- }
- void SetRight(
- int x2)
- {
- m_x2 = x2;
- }
- void SetTop(
- int y2)
- {
- m_y2 = y2;
- }
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:RAS_Rect")
-#endif
-};
-
-#endif /* __RAS_RECT_H__ */
diff --git a/source/gameengine/Rasterizer/RAS_TexMatrix.h b/source/gameengine/Rasterizer/RAS_TexMatrix.h
deleted file mode 100644
index a2dd291d016..00000000000
--- a/source/gameengine/Rasterizer/RAS_TexMatrix.h
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file RAS_TexMatrix.h
- * \ingroup bgerast
- */
-
-#ifndef __RAS_TEXMATRIX_H__
-#define __RAS_TEXMATRIX_H__
-
-#include "MT_Matrix3x3.h"
-#include "MT_Point3.h"
-#include "MT_Point2.h"
-#include "RAS_TexVert.h"
-
-void RAS_CalcTexMatrix(RAS_TexVert p[3],MT_Point3& origin,MT_Vector3& udir,MT_Vector3& vdir);
-
-#endif /* __RAS_TEXMATRIX_H__ */
diff --git a/source/gameengine/Rasterizer/RAS_TexVert.cpp b/source/gameengine/Rasterizer/RAS_TexVert.cpp
deleted file mode 100644
index 2e176360d61..00000000000
--- a/source/gameengine/Rasterizer/RAS_TexVert.cpp
+++ /dev/null
@@ -1,164 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Rasterizer/RAS_TexVert.cpp
- * \ingroup bgerast
- */
-
-
-#include "RAS_TexVert.h"
-#include "MT_Matrix4x4.h"
-#include "BLI_math.h"
-
-RAS_TexVert::RAS_TexVert(const MT_Point3& xyz,
- const MT_Point2 uvs[MAX_UNIT],
- const MT_Vector4& tangent,
- const unsigned int rgba,
- const MT_Vector3& normal,
- const bool flat,
- const unsigned int origindex)
-{
- xyz.getValue(m_localxyz);
- SetRGBA(rgba);
- SetNormal(normal);
- tangent.getValue(m_tangent);
- m_flag = (flat) ? FLAT: 0;
- m_origindex = origindex;
- m_unit = 2;
- m_softBodyIndex = -1;
-
- for (int i = 0; i < MAX_UNIT; ++i)
- {
- uvs[i].getValue(m_uvs[i]);
- }
-}
-
-const MT_Point3& RAS_TexVert::xyz()
-{
- g_pt3.setValue(m_localxyz);
- return g_pt3;
-}
-
-void RAS_TexVert::SetRGBA(const MT_Vector4& rgba)
-{
- unsigned char *colp = (unsigned char*) &m_rgba;
- colp[0] = (unsigned char) (rgba[0] * 255.0f);
- colp[1] = (unsigned char) (rgba[1] * 255.0f);
- colp[2] = (unsigned char) (rgba[2] * 255.0f);
- colp[3] = (unsigned char) (rgba[3] * 255.0f);
-}
-
-
-void RAS_TexVert::SetXYZ(const MT_Point3& xyz)
-{
- xyz.getValue(m_localxyz);
-}
-
-void RAS_TexVert::SetXYZ(const float xyz[3])
-{
- copy_v3_v3(m_localxyz, xyz);
-}
-
-void RAS_TexVert::SetUV(int index, const MT_Point2& uv)
-{
- uv.getValue(m_uvs[index]);
-}
-
-void RAS_TexVert::SetUV(int index, const float uv[2])
-{
- copy_v2_v2(m_uvs[index], uv);
-}
-
-void RAS_TexVert::SetRGBA(const unsigned int rgba)
-{
- m_rgba = rgba;
-}
-
-
-void RAS_TexVert::SetFlag(const short flag)
-{
- m_flag = flag;
-}
-
-void RAS_TexVert::SetUnit(const unsigned int u)
-{
- m_unit = (u <= (unsigned int) MAX_UNIT) ? u: (unsigned int)MAX_UNIT;
-}
-
-void RAS_TexVert::SetNormal(const MT_Vector3& normal)
-{
- normal.getValue(m_normal);
-}
-
-void RAS_TexVert::SetTangent(const MT_Vector3& tangent)
-{
- tangent.getValue(m_tangent);
-}
-
-
-// compare two vertices, and return true if both are almost identical (they can be shared)
-bool RAS_TexVert::closeTo(const RAS_TexVert* other)
-{
- const float eps = FLT_EPSILON;
- for (int i = 0; i < MAX_UNIT; i++) {
- if (!compare_v2v2(m_uvs[i], other->m_uvs[i], eps)) {
- return false;
- }
- }
-
- return (/* m_flag == other->m_flag && */
- /* at the moment the face only stores the smooth/flat setting so don't bother comparing it */
- (m_rgba == other->m_rgba) &&
- compare_v3v3(m_normal, other->m_normal, eps) &&
- compare_v3v3(m_tangent, other->m_tangent, eps)
- /* don't bother comparing m_localxyz since we know there from the same vert */
- /* && compare_v3v3(m_localxyz, other->m_localxyz, eps))*/
- );
-}
-
-short RAS_TexVert::getFlag() const
-{
- return m_flag;
-}
-
-
-unsigned int RAS_TexVert::getUnit() const
-{
- return m_unit;
-}
-
-void RAS_TexVert::Transform(const MT_Matrix4x4& mat, const MT_Matrix4x4& nmat)
-{
- SetXYZ((mat * MT_Vector4(m_localxyz[0], m_localxyz[1], m_localxyz[2], 1.0f)).getValue());
- SetNormal((nmat * MT_Vector4(m_normal[0], m_normal[1], m_normal[2], 1.0f)).getValue());
- SetTangent((nmat * MT_Vector4(m_tangent[0], m_tangent[1], m_tangent[2], 1.0f)).getValue());
-}
-
-void RAS_TexVert::TransformUV(int index, const MT_Matrix4x4& mat)
-{
- SetUV(index, (mat * MT_Vector4(m_uvs[index][0], m_uvs[index][1], 0.0f, 1.0f)).getValue());
-}
diff --git a/source/gameengine/Rasterizer/RAS_TexVert.h b/source/gameengine/Rasterizer/RAS_TexVert.h
deleted file mode 100644
index 8d08549d97e..00000000000
--- a/source/gameengine/Rasterizer/RAS_TexVert.h
+++ /dev/null
@@ -1,146 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file RAS_TexVert.h
- * \ingroup bgerast
- */
-
-#ifndef __RAS_TEXVERT_H__
-#define __RAS_TEXVERT_H__
-
-
-#include "MT_Point3.h"
-#include "MT_Point2.h"
-#include "MT_Transform.h"
-
-#ifdef WITH_CXX_GUARDEDALLOC
-#include "MEM_guardedalloc.h"
-#endif
-
-static MT_Point3 g_pt3;
-static MT_Point2 g_pt2;
-
-class RAS_TexVert
-{
-
- float m_localxyz[3]; // 3*4 = 12
- float m_uvs[8][2]; // 8*2*4=64 //8 = MAX_UNIT
- unsigned int m_rgba; // 4
- float m_tangent[4]; // 4*4 = 16
- float m_normal[3]; // 3*4 = 12
- short m_flag; // 2
- short m_softBodyIndex; //2
- unsigned int m_unit; // 4
- unsigned int m_origindex; // 4
- char m_padding[8]; // 8
- //---------
- // 128
- // 32 bytes alignment improves performance on ATI cards.
-
-public:
- enum {
- FLAT = 1,
- MAX_UNIT = 8
- };
-
- short getFlag() const;
- unsigned int getUnit() const;
-
- RAS_TexVert()// :m_xyz(0,0,0),m_uv(0,0),m_rgba(0)
- {}
- RAS_TexVert(const MT_Point3& xyz,
- const MT_Point2 uvs[MAX_UNIT],
- const MT_Vector4& tangent,
- const unsigned int rgba,
- const MT_Vector3& normal,
- const bool flat,
- const unsigned int origindex);
- ~RAS_TexVert() {};
-
- const float* getUV (int unit) const {
- return m_uvs[unit];
- };
-
- const float* getXYZ() const {
- return m_localxyz;
- };
-
- const float* getNormal() const {
- return m_normal;
- }
-
- short int getSoftBodyIndex() const
- {
- return m_softBodyIndex;
- }
-
- void setSoftBodyIndex(short int sbIndex)
- {
- m_softBodyIndex = sbIndex;
- }
-
- const float* getTangent() const {
- return m_tangent;
- }
-
- const unsigned char* getRGBA() const {
- return (unsigned char *) &m_rgba;
- }
-
- unsigned int getOrigIndex() const {
- return m_origindex;
- }
-
- void SetXYZ(const MT_Point3& xyz);
- void SetXYZ(const float xyz[3]);
- void SetUV(int index, const MT_Point2& uv);
- void SetUV(int index, const float uv[2]);
-
- void SetRGBA(const unsigned int rgba);
- void SetNormal(const MT_Vector3& normal);
- void SetTangent(const MT_Vector3& tangent);
- void SetFlag(const short flag);
- void SetUnit(const unsigned u);
-
- void SetRGBA(const MT_Vector4& rgba);
- const MT_Point3& xyz();
-
- void Transform(const class MT_Matrix4x4& mat,
- const class MT_Matrix4x4& nmat);
- void TransformUV(int index, const MT_Matrix4x4& mat);
-
- // compare two vertices, to test if they can be shared, used for
- // splitting up based on uv's, colors, etc
- bool closeTo(const RAS_TexVert* other);
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:RAS_TexVert")
-#endif
-};
-
-#endif /* __RAS_TEXVERT_H__ */
diff --git a/source/gameengine/Rasterizer/RAS_texmatrix.cpp b/source/gameengine/Rasterizer/RAS_texmatrix.cpp
deleted file mode 100644
index d30a3d3a75d..00000000000
--- a/source/gameengine/Rasterizer/RAS_texmatrix.cpp
+++ /dev/null
@@ -1,131 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/Rasterizer/RAS_texmatrix.cpp
- * \ingroup bgerast
- */
-
-
-#include "RAS_TexMatrix.h"
-
-void RAS_CalcTexMatrix(RAS_TexVert p[3],MT_Point3& origin,MT_Vector3& udir,MT_Vector3& vdir)
-{
-// precondition: 3 vertices are non-collinear
-
- MT_Vector3 vec1 = p[1].xyz()-p[0].xyz();
- MT_Vector3 vec2 = p[2].xyz()-p[0].xyz();
- MT_Vector3 normal = vec1.cross(vec2);
- normal.normalize();
-
- // determine which coordinate we drop, ie. max coordinate in the normal
-
-
- int ZCOORD = normal.closestAxis();
- int XCOORD = (ZCOORD+1)%3;
- int YCOORD = (ZCOORD+2)%3;
-
- // ax+by+cz+d=0
- MT_Scalar d = -p[0].xyz().dot(normal);
-
-
- MT_Matrix3x3 mat3( p[0].getUV(0)[0],p[0].getUV(0)[1], 1,
- p[1].getUV(0)[0],p[1].getUV(0)[1], 1,
- p[2].getUV(0)[0],p[2].getUV(0)[1], 1);
-
-
- MT_Matrix3x3 mat3inv = mat3.inverse();
-
- MT_Vector3 p123x(p[0].xyz()[XCOORD],p[1].xyz()[XCOORD],p[2].xyz()[XCOORD]);
- MT_Vector3 resultx = mat3inv*p123x;
- MT_Vector3 p123y(p[0].xyz()[YCOORD],p[1].xyz()[YCOORD],p[2].xyz()[YCOORD]);
- MT_Vector3 resulty = mat3inv*p123y;
-
- // normal[ZCOORD] is not zero, because it's chosen to be maximal (absolute), and normal has length 1,
- // so at least on of the coords is <> 0
-
- //droppedvalue udir.dot(normal) =0
- MT_Scalar droppedu = -(resultx.x()*normal[XCOORD]+resulty.x()*normal[YCOORD])/normal[ZCOORD];
- udir[XCOORD] = resultx.x();
- udir[YCOORD] = resulty.x();
- udir[ZCOORD] = droppedu;
- MT_Scalar droppedv = -(resultx.y()*normal[XCOORD]+resulty.y()*normal[YCOORD])/normal[ZCOORD];
- vdir[XCOORD] = resultx.y();
- vdir[YCOORD] = resulty.y();
- vdir[ZCOORD] = droppedv;
- // droppedvalue b = -(ax+cz+d)/y;
- MT_Scalar droppedvalue = -((resultx.z()*normal[XCOORD] + resulty.z()*normal[YCOORD]+d))/normal[ZCOORD];
- origin[XCOORD] = resultx.z();
- origin[YCOORD] = resulty.z();
- origin[ZCOORD] = droppedvalue;
-
-
-}
-
-#ifdef _TEXOWNMAIN
-
-int main()
-{
-
- MT_Point2 puv0={0,0};
- MT_Point3 pxyz0 (0,0,128);
-
- MT_Scalar puv1[2] = {1,0};
- MT_Point3 pxyz1(128,0,128);
-
- MT_Scalar puv2[2] = {1,1};
- MT_Point3 pxyz2(128,0,0);
-
- RAS_TexVert p0(pxyz0,puv0);
- RAS_TexVert p1(pxyz1,puv1);
- RAS_TexVert p2(pxyz2,puv2);
-
- RAS_TexVert vertices[3] =
- {
- p0,
- p1,
- p2
- };
-
- MT_Vector3 udir,vdir;
- MT_Point3 origin;
- CalcTexMatrix(vertices,origin,udir,vdir);
-
- MT_Point3 testpoint(128,32,64);
-
- MT_Scalar lenu = udir.length2();
- MT_Scalar lenv = vdir.length2();
-
- MT_Scalar testu=((pxyz2-origin).dot(udir))/lenu;
- MT_Scalar testv=((pxyz2-origin).dot(vdir))/lenv;
-
-
-
-
- return 0;
-}
-
-#endif // _TEXOWNMAIN
diff --git a/source/gameengine/SceneGraph/CMakeLists.txt b/source/gameengine/SceneGraph/CMakeLists.txt
deleted file mode 100644
index bbad429bbcd..00000000000
--- a/source/gameengine/SceneGraph/CMakeLists.txt
+++ /dev/null
@@ -1,53 +0,0 @@
-# ***** BEGIN GPL LICENSE BLOCK *****
-#
-# This program is free software; you can redistribute it and/or
-# modify it under the terms of the GNU General Public License
-# as published by the Free Software Foundation; either version 2
-# of the License, or (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software Foundation,
-# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
-#
-# The Original Code is Copyright (C) 2006, Blender Foundation
-# All rights reserved.
-#
-# The Original Code is: all of this file.
-#
-# Contributor(s): Jacques Beaurain.
-#
-# ***** END GPL LICENSE BLOCK *****
-
-set(INC
- .
-)
-
-set(INC_SYS
- ../../../intern/moto/include
-)
-
-set(SRC
- SG_BBox.cpp
- SG_Controller.cpp
- SG_IObject.cpp
- SG_Node.cpp
- SG_Spatial.cpp
- SG_Tree.cpp
-
- SG_BBox.h
- SG_Controller.h
- SG_DList.h
- SG_IObject.h
- SG_Node.h
- SG_ParentRelation.h
- SG_QList.h
- SG_Spatial.h
- SG_Tree.h
-)
-
-blender_add_lib(ge_scenegraph "${SRC}" "${INC}" "${INC_SYS}")
diff --git a/source/gameengine/SceneGraph/SG_BBox.cpp b/source/gameengine/SceneGraph/SG_BBox.cpp
deleted file mode 100644
index f9d83d37384..00000000000
--- a/source/gameengine/SceneGraph/SG_BBox.cpp
+++ /dev/null
@@ -1,262 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- * Bounding Box
- */
-
-/** \file gameengine/SceneGraph/SG_BBox.cpp
- * \ingroup bgesg
- */
-
-
-#include <math.h>
-
-#include "SG_BBox.h"
-#include "SG_Node.h"
-
-SG_BBox::SG_BBox() :
- m_min(0.0f, 0.0f, 0.0f),
- m_max(0.0f, 0.0f, 0.0f)
-{
-}
-
-SG_BBox::SG_BBox(const MT_Point3 &min, const MT_Point3 &max) :
- m_min(min),
- m_max(max)
-{
-}
-
-SG_BBox::SG_BBox(const SG_BBox &other, const MT_Transform &world) :
- m_min(world(other.m_min)),
- m_max(world(other.m_max))
-{
- *this += world(MT_Point3(m_min[0], m_min[1], m_max[2]));
- *this += world(MT_Point3(m_min[0], m_max[1], m_min[2]));
- *this += world(MT_Point3(m_min[0], m_max[1], m_max[2]));
- *this += world(MT_Point3(m_max[0], m_min[1], m_min[2]));
- *this += world(MT_Point3(m_max[0], m_min[1], m_max[2]));
- *this += world(MT_Point3(m_max[0], m_max[1], m_min[2]));
-}
-
-SG_BBox::SG_BBox(const SG_BBox &other) :
- m_min(other.m_min),
- m_max(other.m_max)
-{
-}
-
-SG_BBox::~ SG_BBox()
-{
-}
-
-SG_BBox& SG_BBox::operator +=(const MT_Point3 &point)
-{
- if (point[0] < m_min[0])
- m_min[0] = point[0];
- else if (point[0] > m_max[0])
- m_max[0] = point[0];
-
- if (point[1] < m_min[1])
- m_min[1] = point[1];
- else if (point[1] > m_max[1])
- m_max[1] = point[1];
-
- if (point[2] < m_min[2])
- m_min[2] = point[2];
- else if (point[2] > m_max[2])
- m_max[2] = point[2];
-
- return *this;
-}
-
-SG_BBox& SG_BBox::operator += (const SG_BBox &bbox)
-{
- *this += bbox.m_min;
- *this += bbox.m_max;
-
- return *this;
-}
-
-SG_BBox SG_BBox::operator +(const SG_BBox &bbox2) const
-{
- SG_BBox ret = *this;
- ret += bbox2;
- return ret;
-}
-
-MT_Scalar SG_BBox::volume() const
-{
- MT_Vector3 size = m_max - m_min;
- return size[0]*size[1]*size[2];
-}
-#if 0
-void SG_BBox::translate(const MT_Vector3& dx)
-{
- m_min += dx;
- m_max += dx;
-}
-
-void SG_BBox::scale(const MT_Vector3& size, const MT_Point3& point)
-{
- MT_Vector3 center = (m_max - m_min)/2. + point;
- m_max = (m_max - center)*size;
- m_min = (m_min - center)*size;
-}
-#endif
-
-SG_BBox SG_BBox::transform(const MT_Transform &world) const
-{
- SG_BBox bbox(world(m_min), world(m_max));
- bbox += world(MT_Point3(m_min[0], m_min[1], m_max[2]));
- bbox += world(MT_Point3(m_min[0], m_max[1], m_min[2]));
- bbox += world(MT_Point3(m_min[0], m_max[1], m_max[2]));
- bbox += world(MT_Point3(m_max[0], m_min[1], m_min[2]));
- bbox += world(MT_Point3(m_max[0], m_min[1], m_max[2]));
- bbox += world(MT_Point3(m_max[0], m_max[1], m_min[2]));
- return bbox;
-}
-
-bool SG_BBox::inside(const MT_Point3 &point) const
-{
- return point[0] >= m_min[0] && point[0] <= m_max[0] &&
- point[1] >= m_min[1] && point[1] <= m_max[1] &&
- point[2] >= m_min[2] && point[2] <= m_max[2];
-}
-
-bool SG_BBox::inside(const SG_BBox& other) const
-{
- return inside(other.m_min) && inside(other.m_max);
-}
-
-bool SG_BBox::intersects(const SG_BBox& other) const
-{
- return inside(other.m_min) != inside(other.m_max);
-}
-
-bool SG_BBox::outside(const SG_BBox& other) const
-{
- return !inside(other.m_min) && !inside(other.m_max);
-}
-
-SG_BBox::intersect SG_BBox::test(const SG_BBox& other) const
-{
- bool point1(inside(other.m_min)), point2(inside(other.m_max));
-
- return point1?(point2?INSIDE:INTERSECT):(point2?INTERSECT:OUTSIDE);
-}
-
-void SG_BBox::get(MT_Point3 *box, const MT_Transform &world) const
-{
- *box++ = world(m_min);
- *box++ = world(MT_Point3(m_min[0], m_min[1], m_max[2]));
- *box++ = world(MT_Point3(m_min[0], m_max[1], m_min[2]));
- *box++ = world(MT_Point3(m_min[0], m_max[1], m_max[2]));
- *box++ = world(MT_Point3(m_max[0], m_min[1], m_min[2]));
- *box++ = world(MT_Point3(m_max[0], m_min[1], m_max[2]));
- *box++ = world(MT_Point3(m_max[0], m_max[1], m_min[2]));
- *box++ = world(m_max);
-}
-
-void SG_BBox::getaa(MT_Point3 *box, const MT_Transform &world) const
-{
- const MT_Point3 min(world(m_min)), max(world(m_max));
- *box++ = min;
- *box++ = MT_Point3(min[0], min[1], max[2]);
- *box++ = MT_Point3(min[0], max[1], min[2]);
- *box++ = MT_Point3(min[0], max[1], max[2]);
- *box++ = MT_Point3(max[0], min[1], min[2]);
- *box++ = MT_Point3(max[0], min[1], max[2]);
- *box++ = MT_Point3(max[0], max[1], min[2]);
- *box++ = max;
-}
-
-void SG_BBox::getmm(MT_Point3 *box, const MT_Transform &world) const
-{
- const MT_Point3 min(world(m_min)), max(world(m_max));
- *box++ = min;
- *box++ = max;
-}
-
-void SG_BBox::split(SG_BBox &left, SG_BBox &right) const
-{
- MT_Scalar sizex = m_max[0] - m_min[0];
- MT_Scalar sizey = m_max[1] - m_min[1];
- MT_Scalar sizez = m_max[2] - m_min[2];
- if (sizex < sizey)
- {
- if (sizey > sizez)
- {
- left.m_min = m_min;
- left.m_max[0] = m_max[0];
- left.m_max[1] = m_min[1] + sizey/2.0f;
- left.m_max[2] = m_max[2];
-
- right.m_min[0] = m_min[0];
- right.m_min[1] = m_min[1] + sizey/2.0f;
- right.m_min[2] = m_min[2];
- right.m_max = m_max;
- std::cout << "splity" << std::endl;
- }
- else {
- left.m_min = m_min;
- left.m_max[0] = m_max[0];
- left.m_max[1] = m_max[1];
- left.m_max[2] = m_min[2] + sizez/2.0f;
-
- right.m_min[0] = m_min[0];
- right.m_min[1] = m_min[1];
- right.m_min[2] = m_min[2] + sizez/2.0f;
- right.m_max = m_max;
- std::cout << "splitz" << std::endl;
- }
- }
- else {
- if (sizex > sizez) {
- left.m_min = m_min;
- left.m_max[0] = m_min[0] + sizex/2.0f;
- left.m_max[1] = m_max[1];
- left.m_max[2] = m_max[2];
-
- right.m_min[0] = m_min[0] + sizex/2.0f;
- right.m_min[1] = m_min[1];
- right.m_min[2] = m_min[2];
- right.m_max = m_max;
- std::cout << "splitx" << std::endl;
- }
- else {
- left.m_min = m_min;
- left.m_max[0] = m_max[0];
- left.m_max[1] = m_max[1];
- left.m_max[2] = m_min[2] + sizez/2.0f;
-
- right.m_min[0] = m_min[0];
- right.m_min[1] = m_min[1];
- right.m_min[2] = m_min[2] + sizez/2.0f;
- right.m_max = m_max;
- std::cout << "splitz" << std::endl;
- }
- }
-
- //std::cout << "Left: " << left.m_min << " -> " << left.m_max << " Right: " << right.m_min << " -> " << right.m_max << std::endl;
-}
diff --git a/source/gameengine/SceneGraph/SG_BBox.h b/source/gameengine/SceneGraph/SG_BBox.h
deleted file mode 100644
index 3c524dc7f18..00000000000
--- a/source/gameengine/SceneGraph/SG_BBox.h
+++ /dev/null
@@ -1,143 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file SG_BBox.h
- * \ingroup bgesg
- * \brief Bounding Box
- */
-
-#ifndef __SG_BBOX_H__
-#define __SG_BBOX_H__
-
-#include "MT_Scalar.h"
-#include "MT_Point3.h"
-#include "MT_Vector3.h"
-#include "MT_Transform.h"
-
-#include <vector>
-
-#ifdef WITH_CXX_GUARDEDALLOC
-#include "MEM_guardedalloc.h"
-#endif
-
-class SG_Node;
-
-/**
- * Bounding box class.
- * Holds the minimum and maximum axis aligned points of a node's bounding box,
- * in world coordinates.
- */
-class SG_BBox
-{
- MT_Point3 m_min;
- MT_Point3 m_max;
-public:
- typedef enum { INSIDE, INTERSECT, OUTSIDE } intersect;
- SG_BBox();
- SG_BBox(const MT_Point3 &min, const MT_Point3 &max);
- SG_BBox(const SG_BBox &other, const MT_Transform &world);
- SG_BBox(const SG_BBox &other);
- ~SG_BBox();
-
- /**
- * Enlarges the bounding box to contain the specified point.
- */
- SG_BBox& operator +=(const MT_Point3 &point);
- /**
- * Enlarges the bounding box to contain the specified bound box.
- */
- SG_BBox& operator +=(const SG_BBox &bbox);
-
- SG_BBox operator + (const SG_BBox &bbox2) const;
-#if 0
- /**
- * Translates the bounding box.
- */
- void translate(const MT_Vector3 &dx);
- /**
- * Scales the bounding box about the optional point.
- */
- void scale(const MT_Vector3 &size, const MT_Point3 &point = MT_Point3(0.0f, 0.0f, 0.0f));
-#endif
- SG_BBox transform(const MT_Transform &world) const;
- /**
- * Computes the volume of the bounding box.
- */
- MT_Scalar volume() const;
-
- /**
- * Test if the given point is inside this bounding box.
- */
- bool inside(const MT_Point3 &point) const;
-
- /**
- * Test if the given bounding box is inside this bounding box.
- */
- bool inside(const SG_BBox &other) const;
-
- /**
- * Test if the given bounding box is outside this bounding box.
- */
- bool outside(const SG_BBox &other) const;
-
- /**
- * Test if the given bounding box intersects this bounding box.
- */
- bool intersects(const SG_BBox &other) const;
-
- /**
- * Test the given bounding box with this bounding box.
- */
- intersect test(const SG_BBox &other) const;
-
- /**
- * Get the eight points that define this bounding box.
- *
- * \param world a world transform to apply to the produced points bounding box.
- */
- void get(MT_Point3 *box, const MT_Transform &world) const;
- /**
- * Get the eight points that define this axis aligned bounding box.
- * This differs from SG_BBox::get() in that the produced box will be world axis aligned.
- * The maximum & minimum local points will be transformed *before* splitting to 8 points.
- * \param world a world transform to be applied.
- */
- void getaa(MT_Point3 *box, const MT_Transform &world) const;
-
- void getmm(MT_Point3 *box, const MT_Transform &world) const;
-
- void split(SG_BBox &left, SG_BBox &right) const;
-
- friend class SG_Tree;
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:SG_BBox")
-#endif
-};
-
-#endif /* __SG_BBOX_H__ */
diff --git a/source/gameengine/SceneGraph/SG_Controller.cpp b/source/gameengine/SceneGraph/SG_Controller.cpp
deleted file mode 100644
index 264942415c9..00000000000
--- a/source/gameengine/SceneGraph/SG_Controller.cpp
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/SceneGraph/SG_Controller.cpp
- * \ingroup bgesg
- */
-
-#include "SG_Controller.h"
-
- void
-SG_Controller::
-SetObject(SG_IObject* obj)
-{
- m_pObject = obj; // no checks yet ?
-}
-
- void
-SG_Controller::
-ClearObject(
-) {
- m_pObject = NULL;
-}
diff --git a/source/gameengine/SceneGraph/SG_Controller.h b/source/gameengine/SceneGraph/SG_Controller.h
deleted file mode 100644
index a173633e13c..00000000000
--- a/source/gameengine/SceneGraph/SG_Controller.h
+++ /dev/null
@@ -1,124 +0,0 @@
-/*
- * Implementationclass to derive controllers from
- *
- *
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file SG_Controller.h
- * \ingroup bgesg
- */
-
-#ifndef __SG_CONTROLLER_H__
-#define __SG_CONTROLLER_H__
-
-#include "SG_IObject.h"
-
-/**
- * A scenegraph controller
- */
-class SG_Controller
-{
-public:
- SG_Controller(
- ) :
- m_pObject(NULL) {
- }
-
- virtual
- ~SG_Controller(
- ) {};
-
- virtual
- bool
- Update(
- double time
- )=0;
-
- virtual
- void
- SetObject (
- SG_IObject* object
- );
-
- void
- ClearObject(
- );
-
- virtual
- void
- SetSimulatedTime(
- double time
- )=0;
-
- virtual
- SG_Controller*
- GetReplica(
- class SG_Node* destnode
- )=0;
-
- /**
- * Hacky way of passing options to specific controllers
- * \param option An integer identifying the option.
- * \param value The value of this option.
- * \attention This has been placed here to give sca-elements
- * \attention some control over the controllers. This is
- * \attention necessary because the identity of the controller
- * \attention is lost on the way here.
- */
- virtual
- void
- SetOption(
- int option,
- int value
- )=0;
-
- /**
- * Option-identifiers: SG_CONTR_<controller-type>_<option>.
- * Options only apply to a specific controller type. The
- * semantics are defined by whoever uses the setting.
- */
- enum SG_Controller_option {
- SG_CONTR_NODEF = 0,
- SG_CONTR_IPO_IPO_AS_FORCE,
- SG_CONTR_IPO_IPO_ADD,
- SG_CONTR_IPO_LOCAL,
- SG_CONTR_IPO_RESET,
- SG_CONTR_CAMIPO_LENS,
- SG_CONTR_CAMIPO_CLIPEND,
- SG_CONTR_CAMIPO_CLIPSTART,
- SG_CONTR_MAX
- };
-
-protected:
- SG_IObject* m_pObject;
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:SG_Controller")
-#endif
-};
-
-#endif /* __SG_CONTROLLER_H__ */
diff --git a/source/gameengine/SceneGraph/SG_DList.h b/source/gameengine/SceneGraph/SG_DList.h
deleted file mode 100644
index 90153f14c07..00000000000
--- a/source/gameengine/SceneGraph/SG_DList.h
+++ /dev/null
@@ -1,251 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file SG_DList.h
- * \ingroup bgesg
- */
-
-#ifndef __SG_DLIST_H__
-#define __SG_DLIST_H__
-
-#include <stdlib.h>
-
-#ifdef WITH_CXX_GUARDEDALLOC
-#include "MEM_guardedalloc.h"
-#endif
-
-/**
- * Double circular linked list
- */
-class SG_DList
-{
-protected :
- SG_DList* m_flink;
- SG_DList* m_blink;
-
-public:
- template<typename T> class iterator
- {
- private:
- SG_DList& m_head;
- T* m_current;
- public:
- typedef iterator<T> _myT;
- iterator(SG_DList& head) : m_head(head), m_current(NULL) {}
- ~iterator() {}
-
- void begin()
- {
- m_current = (T*)m_head.Peek();
- }
- void back()
- {
- m_current = (T*)m_head.Back();
- }
- bool end()
- {
- return (m_current == (T*)m_head.Self());
- }
- bool add_back(T* item)
- {
- return m_current->AddBack(item);
- }
- T* operator*()
- {
- return m_current;
- }
- _myT& operator++()
- {
- // no check of NULL! make sure you don't try to increment beyond end
- m_current = (T*)m_current->Peek();
- return *this;
- }
- _myT& operator--()
- {
- // no check of NULL! make sure you don't try to increment beyond end
- m_current = (T*)m_current->Back();
- return *this;
- }
- };
-
- template<typename T> class const_iterator
- {
- private:
- const SG_DList& m_head;
- const T* m_current;
- public:
- typedef const_iterator<T> _myT;
- const_iterator(const SG_DList& head) : m_head(head), m_current(NULL) {}
- ~const_iterator() {}
-
- void begin()
- {
- m_current = (const T*)m_head.Peek();
- }
- void back()
- {
- m_current = (const T*)m_head.Back();
- }
- bool end()
- {
- return (m_current == (const T*)m_head.Self());
- }
- const T* operator*()
- {
- return m_current;
- }
- _myT& operator++()
- {
- // no check of NULL! make sure you don't try to increment beyond end
- m_current = (const T*)m_current->Peek();
- return *this;
- }
- _myT& operator--()
- {
- // no check of NULL! make sure you don't try to increment beyond end
- m_current = (const T*)m_current->Back();
- return *this;
- }
- };
-
- SG_DList()
- {
- m_flink = m_blink = this;
- }
- SG_DList(const SG_DList& other)
- {
- m_flink = m_blink = this;
- }
- virtual ~SG_DList()
- {
- Delink();
- }
-
- inline bool Empty() // Check for empty queue
- {
- return ( m_flink == this );
- }
- bool AddBack( SG_DList *item ) // Add to the back
- {
- if (!item->Empty())
- return false;
- item->m_blink = m_blink;
- item->m_flink = this;
- m_blink->m_flink = item;
- m_blink = item;
- return true;
- }
- bool AddFront( SG_DList *item ) // Add to the back
- {
- if (!item->Empty())
- return false;
- item->m_flink = m_flink;
- item->m_blink = this;
- m_flink->m_blink = item;
- m_flink = item;
- return true;
- }
- SG_DList *Remove() // Remove from the front
- {
- if (Empty())
- {
- return NULL;
- }
- SG_DList* item = m_flink;
- m_flink = item->m_flink;
- m_flink->m_blink = this;
- item->m_flink = item->m_blink = item;
- return item;
- }
- bool Delink() // Remove from the middle
- {
- if (Empty())
- return false;
- m_blink->m_flink = m_flink;
- m_flink->m_blink = m_blink;
- m_flink = m_blink = this;
- return true;
- }
- inline SG_DList *Peek() // Look at front without removing
- {
- return m_flink;
- }
- inline SG_DList *Back() // Look at front without removing
- {
- return m_blink;
- }
- inline SG_DList *Self()
- {
- return this;
- }
- inline const SG_DList *Peek() const // Look at front without removing
- {
- return (const SG_DList*)m_flink;
- }
- inline const SG_DList *Back() const // Look at front without removing
- {
- return (const SG_DList*)m_blink;
- }
- inline const SG_DList *Self() const
- {
- return this;
- }
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:SG_DList")
-#endif
-};
-
-/**
- * SG_DListHead : Template class that implements copy constructor to duplicate list automatically
- * The elements of the list must have themselves a copy constructor.
- */
-template<typename T> class SG_DListHead : public SG_DList
-{
-public:
- typedef SG_DListHead<T> _myT;
- SG_DListHead() : SG_DList() {}
- SG_DListHead(const _myT& other) : SG_DList()
- {
- // copy the list, assuming objects of type T
- const_iterator<T> eit(other);
- T* elem;
- for (eit.begin(); !eit.end(); ++eit) {
- elem = (*eit)->GetReplica();
- AddBack(elem);
- }
- }
- virtual ~SG_DListHead() {}
- T* Remove()
- {
- return static_cast<T*>(SG_DList::Remove());
- }
-
-};
-
-#endif /* __SG_DLIST_H__ */
diff --git a/source/gameengine/SceneGraph/SG_IObject.cpp b/source/gameengine/SceneGraph/SG_IObject.cpp
deleted file mode 100644
index 9ae32a89ff8..00000000000
--- a/source/gameengine/SceneGraph/SG_IObject.cpp
+++ /dev/null
@@ -1,111 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/SceneGraph/SG_IObject.cpp
- * \ingroup bgesg
- */
-
-
-#include "SG_IObject.h"
-#include "SG_Controller.h"
-
-#include <algorithm>
-
-SG_Stage gSG_Stage = SG_STAGE_UNKNOWN;
-
-SG_IObject::
-SG_IObject(
- void* clientobj,
- void* clientinfo,
- SG_Callbacks& callbacks
-):
- SG_QList(),
- m_SGclientObject(clientobj),
- m_SGclientInfo(clientinfo)
-{
- m_callbacks = callbacks;
-}
-
-SG_IObject::
-SG_IObject(
- const SG_IObject &other
-) :
- SG_QList(),
- m_SGclientObject(other.m_SGclientObject),
- m_SGclientInfo(other.m_SGclientInfo),
- m_callbacks(other.m_callbacks)
-{
- //nothing to do
-}
-
- void
-SG_IObject::
-AddSGController(
- SG_Controller* cont
-) {
- m_SGcontrollers.push_back(cont);
-}
-
- void
-SG_IObject::
-RemoveSGController(
- SG_Controller* cont
-) {
- SGControllerList::iterator contit;
-
- m_SGcontrollers.erase(std::remove(m_SGcontrollers.begin(), m_SGcontrollers.end(), cont));
-}
-
- void
-SG_IObject::
-RemoveAllControllers(
-) {
- m_SGcontrollers.clear();
-}
-
-void SG_IObject::SetControllerTime(double time)
-{
- SGControllerList::iterator contit;
- for (contit = m_SGcontrollers.begin();contit!=m_SGcontrollers.end();++contit)
- {
- (*contit)->SetSimulatedTime(time);
- }
-}
-
-/// Needed for replication
-
-
-SG_IObject::
-~SG_IObject()
-{
- SGControllerList::iterator contit;
-
- for (contit = m_SGcontrollers.begin();contit!=m_SGcontrollers.end();++contit)
- {
- delete (*contit);
- }
-}
diff --git a/source/gameengine/SceneGraph/SG_IObject.h b/source/gameengine/SceneGraph/SG_IObject.h
deleted file mode 100644
index 2dcf3c6492e..00000000000
--- a/source/gameengine/SceneGraph/SG_IObject.h
+++ /dev/null
@@ -1,374 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file SG_IObject.h
- * \ingroup bgesg
- */
-
-#ifndef __SG_IOBJECT_H__
-#define __SG_IOBJECT_H__
-
-#include "SG_QList.h"
-#include <vector>
-
-// used for debugging: stage of the game engine main loop at which a Scenegraph modification is done
-enum SG_Stage
-{
- SG_STAGE_UNKNOWN = 0,
- SG_STAGE_NETWORK,
- SG_STAGE_NETWORK_UPDATE,
- SG_STAGE_PHYSICS1,
- SG_STAGE_PHYSICS1_UPDATE,
- SG_STAGE_CONTROLLER,
- SG_STAGE_CONTROLLER_UPDATE,
- SG_STAGE_ACTUATOR,
- SG_STAGE_ACTUATOR_UPDATE,
- SG_STAGE_ANIMATION_UPDATE,
- SG_STAGE_PHYSICS2,
- SG_STAGE_PHYSICS2_UPDATE,
- SG_STAGE_SCENE,
- SG_STAGE_RENDER,
- SG_STAGE_CONVERTER,
- SG_STAGE_CULLING,
- SG_STAGE_MAX
-};
-
-extern SG_Stage gSG_Stage;
-
-inline void SG_SetActiveStage(SG_Stage stage)
-{
- gSG_Stage = stage;
-}
-
-
-
-class SG_Controller;
-class SG_IObject;
-
-typedef std::vector<SG_Controller*> SGControllerList;
-
-typedef void* (*SG_ReplicationNewCallback)(
- SG_IObject* sgobject,
- void* clientobj,
- void* clientinfo
-);
-
-typedef void* (*SG_DestructionNewCallback)(
- SG_IObject* sgobject,
- void* clientobj,
- void* clientinfo
-);
-
-typedef void (*SG_UpdateTransformCallback)(
- SG_IObject* sgobject,
- void* clientobj,
- void* clientinfo
-);
-
-typedef bool (*SG_ScheduleUpdateCallback)(
- SG_IObject* sgobject,
- void* clientobj,
- void* clientinfo
-);
-
-typedef bool (*SG_RescheduleUpdateCallback)(
- SG_IObject* sgobject,
- void* clientobj,
- void* clientinfo
-);
-
-
-/**
- * SG_Callbacks hold 2 call backs to the outside world.
- * The first is meant to be called when objects are replicated.
- * And allows the outside world to synchronize external objects
- * with replicated nodes and their children.
- * The second is called when a node is destroyed and again
- * is their for synchronization purposes
- * These callbacks may both be NULL.
- * The efficacy of this approach has not been proved some
- * alternatives might be to perform all replication and destruction
- * externally.
- * To define a class interface rather than a simple function
- * call back so that replication information can be transmitted from
- * parent->child.
- */
-struct SG_Callbacks
-{
- SG_Callbacks(
- ):
- m_replicafunc(NULL),
- m_destructionfunc(NULL),
- m_updatefunc(NULL),
- m_schedulefunc(NULL),
- m_reschedulefunc(NULL)
- {
- }
-
- SG_Callbacks(
- SG_ReplicationNewCallback repfunc,
- SG_DestructionNewCallback destructfunc,
- SG_UpdateTransformCallback updatefunc,
- SG_ScheduleUpdateCallback schedulefunc,
- SG_RescheduleUpdateCallback reschedulefunc
- ):
- m_replicafunc(repfunc),
- m_destructionfunc(destructfunc),
- m_updatefunc(updatefunc),
- m_schedulefunc(schedulefunc),
- m_reschedulefunc(reschedulefunc)
- {
- }
-
- SG_ReplicationNewCallback m_replicafunc;
- SG_DestructionNewCallback m_destructionfunc;
- SG_UpdateTransformCallback m_updatefunc;
- SG_ScheduleUpdateCallback m_schedulefunc;
- SG_RescheduleUpdateCallback m_reschedulefunc;
-};
-
-/**
- * base object that can be part of the scenegraph.
- */
-class SG_IObject : public SG_QList
-{
-private :
-
- void* m_SGclientObject;
- void* m_SGclientInfo;
- SG_Callbacks m_callbacks;
- SGControllerList m_SGcontrollers;
-
-public:
- virtual ~SG_IObject();
-
-
- /**
- * Add a pointer to a controller allocated on the heap, to
- * this node. This memory for this controller becomes the
- * responsibility of this class. It will be deleted when
- * this object is deleted.
- */
-
- void
- AddSGController(
- SG_Controller* cont
- );
-
- /**
- * Remove a pointer to a controller from this node.
- * This does not delete the controller itself! Be careful to
- * avoid memory leaks.
- */
- void
- RemoveSGController(
- SG_Controller* cont
- );
-
- /**
- * Clear the array of pointers to controllers associated with
- * this node. This does not delete the controllers themselves!
- * This should be used very carefully to avoid memory
- * leaks.
- */
-
- void
- RemoveAllControllers(
- );
-
- /// Needed for replication
-
- /**
- * Return a reference to this node's controller list.
- * Whilst we don't wish to expose full control of the container
- * to the user we do allow them to call non_const methods
- * on pointers in the container. C++ topic: how to do this in
- * using STL?
- */
-
- SGControllerList& GetSGControllerList()
- {
- return m_SGcontrollers;
- }
-
- /**
- *
- */
- SG_Callbacks& GetCallBackFunctions()
- {
- return m_callbacks;
- }
-
- /**
- * Get the client object associated with this
- * node. This interface allows you to associate
- * arbitrary external objects with this node. They are
- * passed to the callback functions when they are
- * activated so you can synchronize these external objects
- * upon replication and destruction
- * This may be NULL.
- */
-
- inline const void* GetSGClientObject() const
- {
- return m_SGclientObject;
- }
-
- inline void* GetSGClientObject()
- {
- return m_SGclientObject;
- }
-
- /**
- * Set the client object for this node. This is just a
- * pointer to an object allocated that should exist for
- * the duration of the lifetime of this object, or until
- * this function is called again.
- */
-
- void SetSGClientObject(void* clientObject)
- {
- m_SGclientObject = clientObject;
- }
-
-
- /* needed for scene switching */
- inline const void* GetSGClientInfo() const
- {
- return m_SGclientInfo;
- }
- inline void* GetSGClientInfo()
- {
- return m_SGclientInfo;
- }
- void SetSGClientInfo(void* clientInfo)
- {
- m_SGclientInfo = clientInfo;
- }
-
-
- /**
- * Set the current simulation time for this node.
- * The implementation of this function runs through
- * the nodes list of controllers and calls their SetSimulatedTime methods
- */
-
- void SetControllerTime(double time);
-
- virtual
- void
- Destruct(
- ) = 0;
-
-protected :
-
- bool
- ActivateReplicationCallback(
- SG_IObject *replica
- )
- {
- if (m_callbacks.m_replicafunc)
- {
- // Call client provided replication func
- if (m_callbacks.m_replicafunc(replica,m_SGclientObject,m_SGclientInfo) == NULL)
- return false;
- }
- return true;
- }
-
-
- void
- ActivateDestructionCallback(
- )
- {
- if (m_callbacks.m_destructionfunc)
- {
- // Call client provided destruction function on this!
- m_callbacks.m_destructionfunc(this,m_SGclientObject,m_SGclientInfo);
- }
- else
- {
- // no callback but must still destroy the node to avoid memory leak
- delete this;
- }
- }
-
- void
- ActivateUpdateTransformCallback(
- )
- {
- if (m_callbacks.m_updatefunc)
- {
- // Call client provided update func.
- m_callbacks.m_updatefunc(this, m_SGclientObject, m_SGclientInfo);
- }
- }
-
- bool
- ActivateScheduleUpdateCallback(
- )
- {
- // HACK, this check assumes that the scheduled nodes are put on a DList (see SG_Node.h)
- // The early check on Empty() allows up to avoid calling the callback function
- // when the node is already scheduled for update.
- if (Empty() && m_callbacks.m_schedulefunc)
- {
- // Call client provided update func.
- return m_callbacks.m_schedulefunc(this, m_SGclientObject, m_SGclientInfo);
- }
- return false;
- }
-
- void
- ActivateRecheduleUpdateCallback(
- )
- {
- if (m_callbacks.m_reschedulefunc)
- {
- // Call client provided update func.
- m_callbacks.m_reschedulefunc(this, m_SGclientObject, m_SGclientInfo);
- }
- }
-
-
- SG_IObject(
- void* clientobj,
- void* clientinfo,
- SG_Callbacks& callbacks
- );
-
- SG_IObject(
- const SG_IObject &other
- );
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:SG_IObject")
-#endif
-};
-
-#endif /* __SG_IOBJECT_H__ */
diff --git a/source/gameengine/SceneGraph/SG_Node.cpp b/source/gameengine/SceneGraph/SG_Node.cpp
deleted file mode 100644
index 04d9a306fc4..00000000000
--- a/source/gameengine/SceneGraph/SG_Node.cpp
+++ /dev/null
@@ -1,227 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/SceneGraph/SG_Node.cpp
- * \ingroup bgesg
- */
-
-
-#include "SG_Node.h"
-#include "SG_ParentRelation.h"
-#include <algorithm>
-
-using namespace std;
-
-
-SG_Node::SG_Node(
- void* clientobj,
- void* clientinfo,
- SG_Callbacks& callbacks
-
-)
- : SG_Spatial(clientobj,clientinfo,callbacks),
- m_SGparent(NULL)
-{
- m_modified = true;
-}
-
-SG_Node::SG_Node(
- const SG_Node & other
-) :
- SG_Spatial(other),
- m_children(other.m_children),
- m_SGparent(other.m_SGparent)
-{
- m_modified = true;
-}
-
-SG_Node::~SG_Node()
-{
-}
-
-
-SG_Node* SG_Node::GetSGReplica()
-{
- SG_Node* replica = new SG_Node(*this);
- if (replica == NULL) return NULL;
-
- ProcessSGReplica(&replica);
-
- return replica;
-}
-
- void
-SG_Node::
-ProcessSGReplica(
- SG_Node** replica
-) {
- // Apply the replication call back function.
- if (!ActivateReplicationCallback(*replica))
- {
- delete (*replica);
- *replica = NULL;
- return;
- }
-
- // clear the replica node of it's parent.
- static_cast<SG_Node*>(*replica)->m_SGparent = NULL;
-
- if (m_children.begin() != m_children.end())
- {
- // if this node has children, the replica has too, so clear and clone children
- (*replica)->ClearSGChildren();
-
- NodeList::iterator childit;
- for (childit = m_children.begin();childit!=m_children.end();++childit)
- {
- SG_Node* childnode = (*childit)->GetSGReplica();
- if (childnode)
- (*replica)->AddChild(childnode);
- }
- }
- // Nodes without children and without client object are
- // not worth to keep, they will just take up CPU
- // This can happen in partial replication of hierarchy
- // during group duplication.
- if ((*replica)->m_children.empty() &&
- (*replica)->GetSGClientObject() == NULL)
- {
- delete (*replica);
- *replica = NULL;
- }
-}
-
-
- void
-SG_Node::
-Destruct()
-{
- // Not entirely sure what Destruct() expects to happen.
- // I think it probably means just to call the DestructionCallback
- // in the right order on all the children - rather than free any memory
-
- // We'll delete m_parent_relation now anyway.
-
- delete(m_parent_relation);
- m_parent_relation = NULL;
-
- if (m_children.begin() != m_children.end())
- {
- NodeList::iterator childit;
- for (childit = m_children.begin();childit!=m_children.end();++childit)
- {
- // call the SG_Node destruct method on each of our children }-)
- (*childit)->Destruct();
- }
- }
-
- ActivateDestructionCallback();
-}
-
-const
- SG_Node *
-SG_Node::
-GetRootSGParent(
-) const {
- return (m_SGparent ? (const SG_Node*) m_SGparent->GetRootSGParent() : (const SG_Node*) this);
-}
-
-bool SG_Node::IsAncessor(const SG_Node* child) const
-{
- return (!child->m_SGparent) ? false :
- (child->m_SGparent == this) ? true : IsAncessor(child->m_SGparent);
-}
-
- void
-SG_Node::
-DisconnectFromParent(
-) {
- if (m_SGparent)
- {
- m_SGparent->RemoveChild(this);
- m_SGparent = NULL;
- }
-
-}
-
-void SG_Node::AddChild(SG_Node* child)
-{
- m_children.push_back(child);
- child->SetSGParent(this); // this way ?
-}
-
-void SG_Node::RemoveChild(SG_Node* child)
-{
- NodeList::iterator childfound = find(m_children.begin(),m_children.end(),child);
-
- if (childfound != m_children.end())
- {
- m_children.erase(childfound);
- }
-}
-
-
-
-void SG_Node::UpdateWorldData(double time, bool parentUpdated)
-{
- //if (!GetSGParent())
- // return;
-
- if (UpdateSpatialData(GetSGParent(),time,parentUpdated))
- // to update the
- ActivateUpdateTransformCallback();
-
- // The node is updated, remove it from the update list
- Delink();
-
- // update children's worlddata
- for (NodeList::iterator it = m_children.begin();it!=m_children.end();++it)
- {
- (*it)->UpdateWorldData(time, parentUpdated);
- }
-}
-
-
-
-void SG_Node::SetSimulatedTime(double time,bool recurse)
-{
-
- // update the controllers of this node.
- SetControllerTime(time);
-
- // update children's simulate time.
- if (recurse)
- {
- for (NodeList::iterator it = m_children.begin();it!=m_children.end();++it)
- {
- (*it)->SetSimulatedTime(time,recurse);
- }
- }
-}
-
-
-
diff --git a/source/gameengine/SceneGraph/SG_Node.h b/source/gameengine/SceneGraph/SG_Node.h
deleted file mode 100644
index bde64f21305..00000000000
--- a/source/gameengine/SceneGraph/SG_Node.h
+++ /dev/null
@@ -1,278 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file SG_Node.h
- * \ingroup bgesg
- */
-
-#ifndef __SG_NODE_H__
-#define __SG_NODE_H__
-
-#include "SG_Spatial.h"
-#include <vector>
-
-typedef std::vector<SG_Node*> NodeList;
-
-/**
- * Scenegraph node.
- */
-class SG_Node : public SG_Spatial
-{
-public:
- SG_Node(
- void* clientobj,
- void* clientinfo,
- SG_Callbacks& callbacks
- );
-
- SG_Node(
- const SG_Node & other
- );
-
- virtual ~SG_Node();
-
-
- /**
- * Add a child to this object. This also informs the child of
- * it's parent.
- * This just stores a pointer to the child and does not
- * make a deep copy.
- */
-
- void
- AddChild(
- SG_Node* child
- );
-
- /**
- * Remove a child node from this object. This just removes the child
- * pointer from the list of children - it does not destroy the child.
- * This does not inform the child that this node is no longer it's parent.
- * If the node was not a child of this object no action is performed.
- */
-
- void
- RemoveChild(
- SG_Node* child
- );
-
- /**
- * Return true if the node is the ancestor of child
- */
- bool
- IsAncessor(
- const SG_Node* child
- ) const;
- /**
- * Get the current list of children. Do not use this interface for
- * adding or removing children please use the methods of this class for
- * that.
- * \return a reference to the list of children of this node.
- */
-
- NodeList& GetSGChildren()
- {
- return this->m_children;
- }
-
- /**
- * Get the current list of children.
- * \return a const reference to the current list of children of this node.
- */
-
- const NodeList& GetSGChildren() const
- {
- return this->m_children;
- }
-
- /**
- * Clear the list of children associated with this node
- */
-
- void ClearSGChildren()
- {
- m_children.clear();
- }
-
- /**
- * return the parent of this node if it exists.
- */
-
- SG_Node* GetSGParent() const
- {
- return m_SGparent;
- }
-
- /**
- * Set the parent of this node.
- */
-
- void SetSGParent(SG_Node* parent)
- {
- m_SGparent = parent;
- }
-
- /**
- * Return the top node in this node's Scene graph hierarchy
- */
-
- const
- SG_Node*
- GetRootSGParent(
- ) const;
-
- /**
- * Disconnect this node from it's parent
- */
-
- void
- DisconnectFromParent(
- );
-
- /**
- * Return vertex parent status.
- */
- bool IsVertexParent()
- {
- if (m_parent_relation)
- {
- return m_parent_relation->IsVertexRelation();
- }
- return false;
- }
-
-
- /**
- * Return slow parent status.
- */
-
- bool IsSlowParent()
- {
- if (m_parent_relation)
- {
- return m_parent_relation->IsSlowRelation();
- }
- return false;
- }
-
-
-
-
- /**
- * Update the spatial data of this node. Iterate through
- * the children of this node and update their world data.
- */
-
- void
- UpdateWorldData(
- double time,
- bool parentUpdated=false
- );
-
- /**
- * Update the simulation time of this node. Iterate through
- * the children nodes and update their simulated time.
- */
-
- void
- SetSimulatedTime(
- double time,
- bool recurse
- );
-
- /**
- * Schedule this node for update by placing it in head queue
- */
- bool Schedule(SG_QList& head)
- {
- // Put top parent in front of list to make sure they are updated before their
- // children => the children will be udpated and removed from the list before
- // we get to them, should they be in the list too.
- return (m_SGparent)?head.AddBack(this):head.AddFront(this);
- }
-
- /**
- * Used during Scenegraph update
- */
- static SG_Node* GetNextScheduled(SG_QList& head)
- {
- return static_cast<SG_Node*>(head.Remove());
- }
-
- /**
- * Make this node ready for schedule on next update. This is needed for nodes
- * that must always be updated (slow parent, bone parent)
- */
- bool Reschedule(SG_QList& head)
- {
- return head.QAddBack(this);
- }
-
- /**
- * Used during Scenegraph update
- */
- static SG_Node* GetNextRescheduled(SG_QList& head)
- {
- return static_cast<SG_Node*>(head.QRemove());
- }
-
- /**
- * Node replication functions.
- */
-
- SG_Node*
- GetSGReplica(
- );
-
- void
- Destruct(
- );
-
-private:
-
- void
- ProcessSGReplica(
- SG_Node** replica
- );
-
- /**
- * The list of children of this node.
- */
- NodeList m_children;
-
- /**
- * The parent of this node may be NULL
- */
- SG_Node* m_SGparent;
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:SG_Node")
-#endif
-};
-
-#endif /* __SG_NODE_H__ */
diff --git a/source/gameengine/SceneGraph/SG_ParentRelation.h b/source/gameengine/SceneGraph/SG_ParentRelation.h
deleted file mode 100644
index ce45b42c148..00000000000
--- a/source/gameengine/SceneGraph/SG_ParentRelation.h
+++ /dev/null
@@ -1,139 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- *
- */
-
-/** \file SG_ParentRelation.h
- * \ingroup bgesg
- * \page SG_ParentRelationPage SG_ParentRelation
- *
- * \section SG_ParentRelationSection SG_ParentRelation
- *
- * This is an abstract interface class to the Scene Graph library.
- * It allows you to specify how child nodes react to parent nodes.
- * Normally a child will use it's parent's transforms to compute
- * it's own global transforms. How this is performed depends on
- * the type of relation. For example if the parent is a vertex
- * parent to this child then the child should not inherit any
- * rotation information from the parent. Or if the parent is a
- * 'slow parent' to this child then the child should react
- * slowly to changes in the parent's position. The exact relation
- * is left for you to implement by filling out this interface
- * with concrete examples.
- *
- * There is exactly one SG_ParentRelation per SG_Node. Subclasses
- * should not be value types and should be allocated on the heap.
- *
- */
-
-#ifndef __SG_PARENTRELATION_H__
-#define __SG_PARENTRELATION_H__
-
-class SG_Spatial;
-
-class SG_ParentRelation {
-
-public :
- /**
- * Update the childs local and global coordinates
- * based upon the parents global coordinates.
- * You must also handle the case when this node has no
- * parent (parent == NULL). Usually you should just
- * copy the local coordinates of the child to the
- * world coordinates.
- */
-
- virtual
- bool
- UpdateChildCoordinates(
- SG_Spatial * child,
- const SG_Spatial * parent,
- bool& parentUpdated
- ) = 0;
-
- virtual
- ~SG_ParentRelation(
- ) {};
-
- /**
- * You must provide a way of duplicating an
- * instance of an SG_ParentRelation. This should
- * return a pointer to a new duplicate allocated
- * on the heap. Responsibility for deleting the
- * duplicate resides with the caller of this method.
- */
-
- virtual
- SG_ParentRelation *
- NewCopy(
- ) = 0;
-
- /**
- * Vertex Parent Relation are special: they don't propagate rotation
- */
- virtual
- bool
- IsVertexRelation(
- ) {
- return false;
- }
-
- /**
- * Need this to see if we are able to adjust time-offset from the python api
- */
- virtual
- bool
- IsSlowRelation(
- ) {
- return false;
- }
-protected :
-
- /**
- * Protected constructors
- * this class is not meant to be instantiated.
- */
-
- SG_ParentRelation(
- ) {
- };
-
- /**
- * Copy construction should not be implemented
- */
-
- SG_ParentRelation(
- const SG_ParentRelation &
- );
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:SG_ParentRelation")
-#endif
-};
-
-#endif
-
diff --git a/source/gameengine/SceneGraph/SG_QList.h b/source/gameengine/SceneGraph/SG_QList.h
deleted file mode 100644
index 663f29ebd88..00000000000
--- a/source/gameengine/SceneGraph/SG_QList.h
+++ /dev/null
@@ -1,164 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file SG_QList.h
- * \ingroup bgesg
- */
-
-#ifndef __SG_QLIST_H__
-#define __SG_QLIST_H__
-
-#include "SG_DList.h"
-
-/**
- * Double-Double circular linked list
- * For storing an object is two lists simultaneously
- */
-class SG_QList : public SG_DList
-{
-protected :
- SG_QList* m_fqlink;
- SG_QList* m_bqlink;
-
-public:
- template<typename T> class iterator
- {
- private:
- SG_QList& m_head;
- T* m_current;
- public:
- typedef iterator<T> _myT;
- iterator(SG_QList& head, SG_QList* current=NULL) : m_head(head) { m_current = (T*)current; }
- ~iterator() {}
-
- void begin()
- {
- m_current = (T*)m_head.QPeek();
- }
- void back()
- {
- m_current = (T*)m_head.QBack();
- }
- bool end()
- {
- return (m_current == (T*)m_head.Self());
- }
- bool add_back(T* item)
- {
- return m_current->QAddBack(item);
- }
- T* operator*()
- {
- return m_current;
- }
- _myT& operator++()
- {
- m_current = (T*)m_current->QPeek();
- return *this;
- }
- _myT& operator--()
- {
- // no check on NULL! make sure you don't try to increment beyond end
- m_current = (T*)m_current->QBack();
- return *this;
- }
- };
-
- SG_QList() : SG_DList()
- {
- m_fqlink = m_bqlink = this;
- }
- SG_QList(const SG_QList& other) : SG_DList()
- {
- m_fqlink = m_bqlink = this;
- }
- virtual ~SG_QList()
- {
- QDelink();
- }
-
- inline bool QEmpty() // Check for empty queue
- {
- return ( m_fqlink == this );
- }
- bool QAddBack( SG_QList *item ) // Add to the back
- {
- if (!item->QEmpty())
- return false;
- item->m_bqlink = m_bqlink;
- item->m_fqlink = this;
- m_bqlink->m_fqlink = item;
- m_bqlink = item;
- return true;
- }
- bool QAddFront( SG_QList *item ) // Add to the back
- {
- if (!item->Empty())
- return false;
- item->m_fqlink = m_fqlink;
- item->m_bqlink = this;
- m_fqlink->m_bqlink = item;
- m_fqlink = item;
- return true;
- }
- SG_QList *QRemove() // Remove from the front
- {
- if (QEmpty())
- {
- return NULL;
- }
- SG_QList* item = m_fqlink;
- m_fqlink = item->m_fqlink;
- m_fqlink->m_bqlink = this;
- item->m_fqlink = item->m_bqlink = item;
- return item;
- }
- bool QDelink() // Remove from the middle
- {
- if (QEmpty())
- return false;
- m_bqlink->m_fqlink = m_fqlink;
- m_fqlink->m_bqlink = m_bqlink;
- m_fqlink = m_bqlink = this;
- return true;
- }
- inline SG_QList *QPeek() // Look at front without removing
- {
- return m_fqlink;
- }
- inline SG_QList *QBack() // Look at front without removing
- {
- return m_bqlink;
- }
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:SG_QList")
-#endif
-};
-
-#endif /* __SG_QLIST_H__ */
diff --git a/source/gameengine/SceneGraph/SG_Spatial.cpp b/source/gameengine/SceneGraph/SG_Spatial.cpp
deleted file mode 100644
index 5cb75873237..00000000000
--- a/source/gameengine/SceneGraph/SG_Spatial.cpp
+++ /dev/null
@@ -1,217 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/SceneGraph/SG_Spatial.cpp
- * \ingroup bgesg
- */
-
-
-#include "SG_Node.h"
-#include "SG_Spatial.h"
-#include "SG_Controller.h"
-#include "SG_ParentRelation.h"
-
-SG_Spatial::
-SG_Spatial(
- void* clientobj,
- void* clientinfo,
- SG_Callbacks& callbacks
-):
-
- SG_IObject(clientobj,clientinfo,callbacks),
- m_localPosition(0.0f,0.0f,0.0f),
- m_localRotation(1.0f,0.0f,0.0f,0.0f,1.0f,0.0f,0.0f,0.0f,1.0f),
- m_localScaling(1.0f,1.0f,1.0f),
-
- m_worldPosition(0.0f,0.0f,0.0f),
- m_worldRotation(1.0f,0.0f,0.0f,0.0f,1.0f,0.0f,0.0f,0.0f,1.0f),
- m_worldScaling(1.0f,1.0f,1.0f),
-
- m_parent_relation (NULL),
-
- m_bbox(MT_Point3(-1.0f, -1.0f, -1.0f), MT_Point3(1.0f, 1.0f, 1.0f)),
- m_radius(1.0f),
- m_modified(false),
- m_ogldirty(false)
-{
-}
-
-SG_Spatial::
-SG_Spatial(
- const SG_Spatial& other
-) :
- SG_IObject(other),
- m_localPosition(other.m_localPosition),
- m_localRotation(other.m_localRotation),
- m_localScaling(other.m_localScaling),
-
- m_worldPosition(other.m_worldPosition),
- m_worldRotation(other.m_worldRotation),
- m_worldScaling(other.m_worldScaling),
-
- m_parent_relation(NULL),
-
- m_bbox(other.m_bbox),
- m_radius(other.m_radius),
- m_modified(false),
- m_ogldirty(false)
-{
- // duplicate the parent relation for this object
- m_parent_relation = other.m_parent_relation->NewCopy();
-}
-
-SG_Spatial::
-~SG_Spatial()
-{
- delete (m_parent_relation);
-}
-
- void
-SG_Spatial::
-SetParentRelation(
- SG_ParentRelation *relation
-) {
- delete (m_parent_relation);
- m_parent_relation = relation;
- SetModified();
-}
-
-
-/**
- * Update Spatial Data.
- * Calculates WorldTransform., (either doing its self or using the linked SGControllers)
- */
-
-
- bool
-SG_Spatial::
-UpdateSpatialData(
- const SG_Spatial *parent,
- double time,
- bool& parentUpdated)
-{
- bool bComputesWorldTransform = false;
-
- // update spatial controllers
-
- SGControllerList::iterator cit = GetSGControllerList().begin();
- SGControllerList::const_iterator c_end = GetSGControllerList().end();
-
- for (;cit!=c_end;++cit)
- {
- if ((*cit)->Update(time))
- bComputesWorldTransform = true;
- }
-
- // If none of the objects updated our values then we ask the
- // parent_relation object owned by this class to update
- // our world coordinates.
-
- if (!bComputesWorldTransform)
- bComputesWorldTransform = ComputeWorldTransforms(parent, parentUpdated);
-
- return bComputesWorldTransform;
-}
-
-/**
- * Position and translation methods
- */
-
-
- void
-SG_Spatial::
-RelativeTranslate(
- const MT_Vector3& trans,
- const SG_Spatial *parent,
- bool local
-) {
- if (local) {
- m_localPosition += m_localRotation * trans;
- }
- else {
- if (parent) {
- m_localPosition += trans * parent->GetWorldOrientation();
- }
- else {
- m_localPosition += trans;
- }
- }
- SetModified();
-}
-
-
-/**
- * Scaling methods.
- */
-
-
-/**
- * Orientation and rotation methods.
- */
-
-
- void
-SG_Spatial::
-RelativeRotate(
- const MT_Matrix3x3& rot,
- bool local
-) {
- m_localRotation = m_localRotation * (
- local ?
- rot
- :
- (GetWorldOrientation().inverse() * rot * GetWorldOrientation()));
- SetModified();
-}
-
-
-
-MT_Transform SG_Spatial::GetWorldTransform() const
-{
- return MT_Transform(m_worldPosition,
- m_worldRotation.scaled(
- m_worldScaling[0], m_worldScaling[1], m_worldScaling[2]));
-}
-
-bool SG_Spatial::inside(const MT_Point3 &point) const
-{
- MT_Scalar radius = m_worldScaling[m_worldScaling.closestAxis()]*m_radius;
- return (m_worldPosition.distance2(point) <= radius*radius) ?
- m_bbox.transform(GetWorldTransform()).inside(point) :
- false;
-}
-
-void SG_Spatial::getBBox(MT_Point3 *box) const
-{
- m_bbox.get(box, GetWorldTransform());
-}
-
-void SG_Spatial::getAABBox(MT_Point3 *box) const
-{
- m_bbox.getaa(box, GetWorldTransform());
-}
-
diff --git a/source/gameengine/SceneGraph/SG_Spatial.h b/source/gameengine/SceneGraph/SG_Spatial.h
deleted file mode 100644
index aa917fa70db..00000000000
--- a/source/gameengine/SceneGraph/SG_Spatial.h
+++ /dev/null
@@ -1,294 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file SG_Spatial.h
- * \ingroup bgesg
- */
-
-#ifndef __SG_SPATIAL_H__
-#define __SG_SPATIAL_H__
-
-#include <MT_Vector3.h>
-#include <MT_Point3.h>
-#include <MT_Matrix3x3.h> // or Quaternion later ?
-#include "SG_IObject.h"
-#include "SG_BBox.h"
-#include "SG_ParentRelation.h"
-
-
-class SG_Node;
-class SG_ParentRelation;
-
-/**
- * SG_Spatial contains spatial information (local & world position, rotation
- * and scaling) for a Scene graph node.
- * It also contains a link to the node's parent.
- */
-class SG_Spatial : public SG_IObject
-{
-
-protected:
- MT_Point3 m_localPosition;
- MT_Matrix3x3 m_localRotation;
- MT_Vector3 m_localScaling;
-
- MT_Point3 m_worldPosition;
- MT_Matrix3x3 m_worldRotation;
- MT_Vector3 m_worldScaling;
-
- SG_ParentRelation * m_parent_relation;
-
- SG_BBox m_bbox;
- MT_Scalar m_radius;
- bool m_modified;
- bool m_ogldirty; // true if the openGL matrix for this object must be recomputed
-
-public:
- inline void ClearModified()
- {
- m_modified = false;
- m_ogldirty = true;
- }
- inline void SetModified()
- {
- m_modified = true;
- ActivateScheduleUpdateCallback();
- }
- inline void ClearDirty()
- {
- m_ogldirty = false;
- }
- /**
- * Define the relationship this node has with it's parent
- * node. You should pass an unshared instance of an SG_ParentRelation
- * allocated on the heap to this method. Ownership of this
- * instance is assumed by this class.
- * You may call this function several times in the lifetime
- * of a node to change the relationship dynamically.
- * You must call this method before the first call to UpdateSpatialData().
- * An assertion will be fired at run-time in debug if this is not
- * the case.
- * The relation is activated only if no controllers of this object
- * updated the coordinates of the child.
- */
-
- void
- SetParentRelation(
- SG_ParentRelation *relation
- );
-
- SG_ParentRelation * GetParentRelation()
- {
- return m_parent_relation;
- }
-
-
-
-
- /**
- * Apply a translation relative to the current position.
- * if local then the translation is assumed to be in the
- * local coordinates of this object. If not then the translation
- * is assumed to be in global coordinates. In this case
- * you must provide a pointer to the parent of this object if it
- * exists otherwise if there is no parent set it to NULL
- */
-
- void
- RelativeTranslate(
- const MT_Vector3& trans,
- const SG_Spatial *parent,
- bool local
- );
-
- void SetLocalPosition(const MT_Point3& trans)
- {
- m_localPosition = trans;
- SetModified();
- }
-
- void SetWorldPosition(const MT_Point3& trans)
- {
- m_worldPosition = trans;
- }
-
-
- void
- RelativeRotate(
- const MT_Matrix3x3& rot,
- bool local
- );
-
- void SetLocalOrientation(const MT_Matrix3x3& rot)
- {
- m_localRotation = rot;
- SetModified();
- }
-
- // rot is arrange like openGL matrix
- void SetLocalOrientation(const float* rot)
- {
- m_localRotation.setValue(rot);
- SetModified();
- }
-
- void SetWorldOrientation(const MT_Matrix3x3& rot)
- {
- m_worldRotation = rot;
- }
-
- void RelativeScale(const MT_Vector3& scale)
- {
- m_localScaling = m_localScaling * scale;
- SetModified();
- }
-
- void SetLocalScale(const MT_Vector3& scale)
- {
- m_localScaling = scale;
- SetModified();
- }
-
- void SetWorldScale(const MT_Vector3& scale)
- {
- m_worldScaling = scale;
- }
-
- const MT_Point3& GetLocalPosition() const
- {
- return m_localPosition;
- }
-
- const MT_Matrix3x3& GetLocalOrientation() const
- {
- return m_localRotation;
- }
-
- const MT_Vector3& GetLocalScale() const
- {
- return m_localScaling;
- }
-
- const MT_Point3& GetWorldPosition() const
- {
- return m_worldPosition;
- }
-
- const MT_Matrix3x3& GetWorldOrientation() const
- {
- return m_worldRotation;
- }
-
- const MT_Vector3& GetWorldScaling() const
- {
- return m_worldScaling;
- }
-
- void SetWorldFromLocalTransform()
- {
- m_worldPosition= m_localPosition;
- m_worldScaling= m_localScaling;
- m_worldRotation= m_localRotation;
- }
-
-
-
- MT_Transform GetWorldTransform() const;
-
- bool ComputeWorldTransforms(const SG_Spatial *parent, bool& parentUpdated)
- {
- return m_parent_relation->UpdateChildCoordinates(this,parent,parentUpdated);
- }
-
-
- /**
- * Bounding box functions.
- */
- SG_BBox& BBox()
- {
- return m_bbox;
- }
-
- void SetBBox(SG_BBox& bbox)
- {
- m_bbox = bbox;
- }
-
-
- bool inside(const MT_Point3 &point) const;
- void getBBox(MT_Point3 *box) const;
- void getAABBox(MT_Point3 *box) const;
-
- MT_Scalar Radius() const { return m_radius; }
- void SetRadius(MT_Scalar radius) { m_radius = radius; }
- bool IsModified() { return m_modified; }
- bool IsDirty() { return m_ogldirty; }
-
-protected:
- friend class SG_Controller;
- friend class KX_BoneParentRelation;
- friend class KX_VertexParentRelation;
- friend class KX_SlowParentRelation;
- friend class KX_NormalParentRelation;
-
- /**
- * Protected constructor this class is not
- * designed for direct instantiation
- */
-
- SG_Spatial(
- void* clientobj,
- void* clientinfo,
- SG_Callbacks& callbacks
- );
-
- SG_Spatial(
- const SG_Spatial& other
- );
-
-
- virtual ~SG_Spatial();
-
- /**
- * Update the world coordinates of this spatial node. This also informs
- * any controllers to update this object.
- */
-
- bool
- UpdateSpatialData(
- const SG_Spatial *parent,
- double time,
- bool& parentUpdated
- );
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:SG_Spatial")
-#endif
-};
-
-#endif /* __SG_SPATIAL_H__ */
diff --git a/source/gameengine/SceneGraph/SG_Tree.cpp b/source/gameengine/SceneGraph/SG_Tree.cpp
deleted file mode 100644
index 87feb2c012a..00000000000
--- a/source/gameengine/SceneGraph/SG_Tree.cpp
+++ /dev/null
@@ -1,422 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- * Bounding Box
- */
-
-/** \file gameengine/SceneGraph/SG_Tree.cpp
- * \ingroup bgesg
- */
-
-
-#include <math.h>
-
-#include "SG_BBox.h"
-#include "SG_Tree.h"
-#include "SG_Node.h"
-
-SG_Tree::SG_Tree() :
- m_left(NULL),
- m_right(NULL),
- m_parent(NULL),
- m_radius(0.0f),
- m_client_object(NULL)
-{
-}
-
-SG_Tree::SG_Tree(SG_Tree* left, SG_Tree* right) :
- m_left(left),
- m_right(right),
- m_parent(NULL),
- m_client_object(NULL)
-{
- if (m_left)
- {
- m_bbox = m_left->m_bbox;
- m_left->m_parent = this;
- }
- if (m_right)
- {
- m_bbox += m_right->m_bbox;
- m_right->m_parent = this;
- }
- m_center = (m_bbox.m_min + m_bbox.m_max)/2.0f;
- m_radius = (m_bbox.m_max - m_bbox.m_min).length();
-}
-
-SG_Tree::SG_Tree(SG_Node* client) :
- m_left(NULL),
- m_right(NULL),
- m_parent(NULL),
- m_client_object(client)
-{
- m_bbox = SG_BBox(client->BBox(), client->GetWorldTransform());
- m_center = (m_bbox.m_min + m_bbox.m_max)/2.0f;
- m_radius = (m_bbox.m_max - m_bbox.m_min).length();
-}
-
-SG_Tree::~SG_Tree()
-{
-}
-
-MT_Scalar SG_Tree::volume() const
-{
- return m_bbox.volume();
-}
-
-void SG_Tree::dump() const
-{
- if (m_left)
- m_left->dump();
- if (m_client_object)
- std::cout << m_client_object << std::endl;
- else
- std::cout << this << " ";
- if (m_right)
- m_right->dump();
-}
-
-SG_Tree* SG_Tree::Left() const
-{
- return m_left;
-}
-
-SG_Tree* SG_Tree::Right() const
-{
- return m_right;
-}
-
-SG_Node* SG_Tree::Client() const
-{
- return m_client_object;
-}
-
-SG_Tree* SG_Tree::Find(SG_Node *node)
-{
- if (m_client_object == node)
- return this;
-
- SG_Tree *left = m_left, *right = m_right;
-
- if (left && right)
- {
- if (right->m_bbox.intersects(node->BBox()))
- std::swap(left, right);
- }
-
- if (left)
- {
- SG_Tree* ret = left->Find(node);
- if (ret) return ret;
- }
-
- if (right)
- {
- SG_Tree* ret = right->Find(node);
- if (ret) return ret;
- }
-
- return NULL;
-}
-
-void SG_Tree::get(MT_Point3 *box) const
-{
- MT_Transform identity;
- identity.setIdentity();
- m_bbox.get(box, identity);
-}
-
-bool SG_Tree::inside(const MT_Point3 &point) const
-{
- return m_bbox.inside(point);
-}
-
-const SG_BBox& SG_Tree::BBox() const
-{
- return m_bbox;
-}
-
-void SG_Tree::SetLeft(SG_Tree *left)
-{
- m_left = left;
- m_bbox += left->m_bbox;
- m_center = (m_bbox.m_min + m_bbox.m_max)/2.0f;
- m_radius = (m_bbox.m_max - m_bbox.m_min).length();
-}
-
-void SG_Tree::SetRight(SG_Tree *right)
-{
- m_right = right;
- m_bbox += right->m_bbox;
- m_center = (m_bbox.m_min + m_bbox.m_max)/2.0f;
- m_radius = (m_bbox.m_max - m_bbox.m_min).length();
-}
-
-/**
- * A Half array is a square 2d array where cell(x, y) is undefined
- * if x < y.
- */
-template<typename T>
-class HalfArray
-{
- std::vector<std::vector<T> > m_array;
-public:
- HalfArray() {}
- ~HalfArray() {}
-
- void resize(unsigned int size)
- {
- m_array.resize(size);
- for ( unsigned int i = 0; i < size; i++)
- {
- m_array[i].resize(size - i);
- }
- }
-
- T& operator() (unsigned int x, unsigned int y)
- {
- assert(x >= y);
- return m_array[y][x - y];
- }
-
- void erase_column (unsigned int x)
- {
- for (unsigned int y = 0; y <= x; y++)
- m_array[y].erase(m_array[y].begin() + x - y);
- }
-
- void delete_column (unsigned int x)
- {
- for (unsigned int y = 0; y < x; y++)
- {
- delete m_array[y][x - y];
- m_array[y].erase(m_array[y].begin() + x - y);
- }
- }
-
- void erase_row (unsigned int y)
- {
- m_array.erase(m_array.begin() + y);
- }
-};
-
-SG_TreeFactory::SG_TreeFactory()
-{
-}
-
-SG_TreeFactory::~SG_TreeFactory()
-{
-}
-
-void SG_TreeFactory::Add(SG_Node* client)
-{
- if (client)
- m_objects.insert(new SG_Tree(client));
-}
-
-void SG_TreeFactory::Add(SG_Tree* tree)
-{
- m_objects.insert(tree);
-}
-
-SG_Tree* SG_TreeFactory::MakeTreeDown(SG_BBox &bbox)
-{
- if (m_objects.empty())
- return NULL;
- if (m_objects.size() == 1)
- return *m_objects.begin();
-
- TreeSet::iterator it = m_objects.begin();
- SG_Tree *root = *it;
- if (m_objects.size() == 2)
- {
- root->SetRight(*(++it));
- return root;
- }
-
- if (m_objects.size() == 3)
- {
- root->SetLeft(*(++it));
- root->SetRight(*(++it));
- return root;
- }
-
- if (bbox.volume() < 1.0f)
- return MakeTreeUp();
-
- SG_TreeFactory lefttree;
- SG_TreeFactory righttree;
-
- SG_BBox left, right;
- int hasleft = 0, hasright = 0;
- bbox.split(left, right);
-
- if (left.test(root->BBox()) == SG_BBox::INSIDE)
- {
- lefttree.Add(root);
- root = NULL;
- }
-
- if (root && right.test(root->BBox()) == SG_BBox::INSIDE)
- {
- righttree.Add(root);
- root = NULL;
- }
-
- for (++it; it != m_objects.end(); ++it)
- {
- switch (left.test((*it)->BBox()))
- {
- case SG_BBox::INSIDE:
- // Object is inside left tree;
- lefttree.Add(*it);
- hasleft++;
- break;
- case SG_BBox::OUTSIDE:
- righttree.Add(*it);
- hasright++;
- break;
- case SG_BBox::INTERSECT:
- if (left.inside((*it)->Client()->GetWorldPosition()))
- {
- lefttree.Add(*it);
- hasleft++;
- }
- else {
- righttree.Add(*it);
- hasright++;
- }
- break;
- }
- }
- std::cout << "Left: " << hasleft << " Right: " << hasright << " Count: " << m_objects.size() << std::endl;
-
- SG_Tree *leftnode = NULL;
- if (hasleft)
- leftnode = lefttree.MakeTreeDown(left);
-
- SG_Tree *rightnode = NULL;
- if (hasright)
- rightnode = righttree.MakeTreeDown(right);
-
- if (!root)
- root = new SG_Tree(leftnode, rightnode);
- else
- {
- if (leftnode)
- root->SetLeft(leftnode);
- if (rightnode)
- root->SetRight(rightnode);
- }
-
- return root;
-}
-
-SG_Tree* SG_TreeFactory::MakeTree()
-{
- if (m_objects.size() < 8)
- return MakeTreeUp();
-
- TreeSet::iterator it = m_objects.begin();
- SG_BBox bbox((*it)->BBox());
- for (++it; it != m_objects.end(); ++it)
- bbox += (*it)->BBox();
-
- return MakeTreeDown(bbox);
-}
-
-SG_Tree* SG_TreeFactory::MakeTreeUp()
-{
- unsigned int num_objects = m_objects.size();
-
- if (num_objects < 1)
- return NULL;
- if (num_objects < 2)
- return *m_objects.begin();
-
- HalfArray<SG_Tree*> sizes;
- sizes.resize(num_objects);
-
- unsigned int x, y;
- TreeSet::iterator xit, yit;
- for ( y = 0, yit = m_objects.begin(); y < num_objects; y++, ++yit)
- {
- sizes(y, y) = *yit;
- xit = yit;
- for ( x = y+1, ++xit; x < num_objects; x++, ++xit)
- {
- sizes(x, y) = new SG_Tree(*xit, *yit);
-
- }
- }
- while (num_objects > 2)
- {
- /* Find the pair of bboxes that produce the smallest combined bbox. */
- unsigned int minx = UINT_MAX, miny = UINT_MAX;
- MT_Scalar min_volume = FLT_MAX;
- SG_Tree *min = NULL;
- //char temp[16];
- for ( y = 0; y < num_objects; y++)
- {
- for ( x = y+1; x < num_objects; x++)
- {
- if (sizes(x, y)->volume() < min_volume)
- {
- min = sizes(x, y);
- minx = x;
- miny = y;
- min_volume = sizes(x, y)->volume();
- }
- }
- }
-
- /* Remove other bboxes that contain the two bboxes */
- sizes.delete_column(miny);
-
- for ( x = miny + 1; x < num_objects; x++)
- {
- if (x == minx)
- continue;
- delete sizes(x, miny);
- }
- sizes.erase_row(miny);
-
- num_objects--;
- minx--;
- sizes(minx, minx) = min;
- for ( x = minx + 1; x < num_objects; x++)
- {
- delete sizes(x, minx);
- sizes(x, minx) = new SG_Tree(min, sizes(x, x));
- }
- for ( y = 0; y < minx; y++)
- {
- delete sizes(minx, y);
- sizes(minx, y) = new SG_Tree(sizes(y, y), min);
- }
- }
- return sizes(1, 0);
-}
-
diff --git a/source/gameengine/SceneGraph/SG_Tree.h b/source/gameengine/SceneGraph/SG_Tree.h
deleted file mode 100644
index 339862c652f..00000000000
--- a/source/gameengine/SceneGraph/SG_Tree.h
+++ /dev/null
@@ -1,163 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file SG_Tree.h
- * \ingroup bgesg
- */
-
-#ifndef __SG_TREE_H__
-#define __SG_TREE_H__
-
-#include "MT_Point3.h"
-#include "SG_BBox.h"
-
-#include <set>
-
-class SG_Node;
-
-
-/**
- * SG_Tree.
- * Holds a binary tree of SG_Nodes.
- */
-class SG_Tree
-{
- SG_Tree* m_left;
- SG_Tree* m_right;
- SG_Tree* m_parent;
- SG_BBox m_bbox;
- MT_Point3 m_center;
- MT_Scalar m_radius;
- SG_Node* m_client_object;
-public:
- SG_Tree();
- SG_Tree(SG_Tree* left, SG_Tree* right);
-
- SG_Tree(SG_Node* client);
- ~SG_Tree();
-
- /**
- * Computes the volume of the bounding box.
- */
- MT_Scalar volume() const;
-
- /**
- * Prints the tree (for debugging.)
- */
- void dump() const;
-
- /**
- * Returns the left node.
- */
- SG_Tree *Left() const;
- SG_Tree *Right() const;
- SG_Node *Client() const;
-
- SG_Tree* Find(SG_Node *node);
- /**
- * Gets the eight corners of this treenode's bounding box,
- * in world coordinates.
- * \param box: an array of 8 MT_Point3
- * \example MT_Point3 box[8];
- * treenode->get(box);
- */
- void get(MT_Point3 *box) const;
- /**
- * Get the tree node's bounding box.
- */
- const SG_BBox& BBox() const;
-
- /**
- * Test if the given bounding box is inside this bounding box.
- */
- bool inside(const MT_Point3 &point) const;
-
- void SetLeft(SG_Tree *left);
- void SetRight(SG_Tree *right);
-
- MT_Point3 Center() const { return m_center; }
- MT_Scalar Radius() { return m_radius; }
-
- //friend class SG_TreeFactory;
-
- struct greater
- {
- bool operator()(const SG_Tree *a, const SG_Tree *b)
- {
- return a->volume() > b->volume();
- }
- };
-
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:SG_Tree")
-#endif
-};
-
-
-/**
- * SG_TreeFactory generates an SG_Tree from a list of SG_Nodes.
- * It joins pairs of SG_Nodes to minimize the size of the resultant
- * bounding box.
- * cf building an optimized Huffman tree.
- * \warning O(n^3)!!!
- */
-class SG_TreeFactory
-{
- typedef std::multiset<SG_Tree*, SG_Tree::greater> TreeSet;
- TreeSet m_objects;
-public:
- SG_TreeFactory();
- ~SG_TreeFactory();
-
- /**
- * Add a node to be added to the tree.
- */
- void Add(SG_Node* client);
- void Add(SG_Tree* tree);
-
- /**
- * Build the tree from the set of nodes added by
- * the Add method.
- */
- SG_Tree* MakeTreeUp();
-
- /**
- * Build the tree from the set of nodes top down.
- */
- SG_Tree* MakeTreeDown(SG_BBox &bbox);
-
- SG_Tree* MakeTree();
-
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:SG_TreeFactory")
-#endif
-};
-
-#endif /* __SG_BBOX_H__ */
diff --git a/source/gameengine/VideoTexture/BlendType.h b/source/gameengine/VideoTexture/BlendType.h
deleted file mode 100644
index 561c6e8768f..00000000000
--- a/source/gameengine/VideoTexture/BlendType.h
+++ /dev/null
@@ -1,86 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * Copyright (c) 2006 The Zdeno Ash Miklas
- *
- * This source file is part of VideoTexture library
- *
- * Contributor(s):
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file BlendType.h
- * \ingroup bgevideotex
- */
-
-#ifndef __BLENDTYPE_H__
-#define __BLENDTYPE_H__
-
-
-/// class allows check type of blender python object and access its contained object
-/// MUST ONLY BE USED FOR KX classes that are descendent of PyObjectPlus
-template <class PyObj> class BlendType
-{
-public:
- /// constructor
- BlendType (const char * name) : m_name(name), m_objType(NULL) {}
-
- /// check blender type and return pointer to contained object or NULL (if type is not valid)
- PyObj *checkType(PyObject *obj)
- {
- // if pointer to type isn't set
- if (m_objType == NULL)
- {
- // compare names of type
- if (strcmp(Py_TYPE(obj)->tp_name, m_name) == 0)
- // if name of type match, save pointer to type
- m_objType = Py_TYPE(obj);
- else
- // if names of type don't match, return NULL
- return NULL;
- }
- // if pointer to type is set and don't match to type of provided object, return NULL
- else if (Py_TYPE(obj) != m_objType)
- return NULL;
- // return pointer to object, this class can only be used for KX object =>
- // the Py object is actually a proxy
- return (PyObj *)BGE_PROXY_REF(obj);
- }
-
- /// parse arguments to get object
- PyObj *parseArg(PyObject *args)
- {
- // parse arguments
- PyObject *obj;
- if (PyArg_ParseTuple(args, "O", &obj)) {
- // if successfully parsed, return pointer to object
- return checkType(obj);
- }
- // otherwise return NULL
- return NULL;
- }
-
-protected:
- /// name of Python type
- const char * m_name;
- /// pointer to Python type
- PyTypeObject *m_objType;
-};
-
-
-#endif
diff --git a/source/gameengine/VideoTexture/CMakeLists.txt b/source/gameengine/VideoTexture/CMakeLists.txt
deleted file mode 100644
index 1eb09b02e05..00000000000
--- a/source/gameengine/VideoTexture/CMakeLists.txt
+++ /dev/null
@@ -1,119 +0,0 @@
-# ***** BEGIN GPL LICENSE BLOCK *****
-#
-# This program is free software; you can redistribute it and/or
-# modify it under the terms of the GNU General Public License
-# as published by the Free Software Foundation; either version 2
-# of the License, or (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software Foundation,
-# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
-#
-# The Original Code is Copyright (C) 2006, Blender Foundation
-# All rights reserved.
-#
-# The Original Code is: all of this file.
-#
-# Contributor(s): Jacques Beaurain.
-#
-# ***** END GPL LICENSE BLOCK *****
-
-set(INC
- .
- ../BlenderRoutines
- ../Expressions
- ../GameLogic
- ../Ketsji
- ../Rasterizer
- ../Rasterizer/RAS_OpenGLRasterizer
- ../SceneGraph
- ../../blender/blenkernel
- ../../blender/blenlib
- ../../blender/editors/include
- ../../blender/gpu
- ../../blender/imbuf
- ../../blender/makesdna
- ../../blender/python
- ../../blender/python/generic
- ../../../intern/container
- ../../../intern/ffmpeg
- ../../../intern/glew-mx
- ../../../intern/guardedalloc
- ../../../intern/string
- ../../../intern/decklink
- ../../../intern/gpudirect
- ../../../intern/atomic
-)
-
-set(INC_SYS
- ../../../intern/moto/include
- ${GLEW_INCLUDE_PATH}
-)
-
-add_definitions(${GL_DEFINITIONS})
-
-set(SRC
- Exception.cpp
- FilterBase.cpp
- FilterBlueScreen.cpp
- FilterColor.cpp
- FilterNormal.cpp
- FilterSource.cpp
- ImageBase.cpp
- ImageBuff.cpp
- ImageMix.cpp
- ImageRender.cpp
- ImageViewport.cpp
- PyTypeList.cpp
- Texture.cpp
- DeckLink.cpp
- VideoBase.cpp
- VideoFFmpeg.cpp
- VideoDeckLink.cpp
- blendVideoTex.cpp
-
- BlendType.h
- Common.h
- Exception.h
- FilterBase.h
- FilterBlueScreen.h
- FilterColor.h
- FilterNormal.h
- FilterSource.h
- ImageBase.h
- ImageBuff.h
- ImageMix.h
- ImageRender.h
- ImageViewport.h
- PyTypeList.h
- Texture.h
- DeckLink.h
- VideoBase.h
- VideoFFmpeg.h
- VideoDeckLink.h
-)
-
-if(WITH_CODEC_FFMPEG)
- list(APPEND INC_SYS
- ${FFMPEG_INCLUDE_DIRS}
- ${PTHREADS_INCLUDE_DIRS}
- )
- add_definitions(-DWITH_FFMPEG)
-
- remove_strict_flags_file(
- VideoFFmpeg.cpp
- VideoDeckLink
- DeckLink
- )
-endif()
-
-if(WITH_GAMEENGINE_DECKLINK)
- add_definitions(-DWITH_GAMEENGINE_DECKLINK)
-endif()
-
-blender_add_lib(ge_videotex "${SRC}" "${INC}" "${INC_SYS}")
diff --git a/source/gameengine/VideoTexture/Common.h b/source/gameengine/VideoTexture/Common.h
deleted file mode 100644
index 22ea177addc..00000000000
--- a/source/gameengine/VideoTexture/Common.h
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * Copyright (c) 2006 The Zdeno Ash Miklas
- *
- * This source file is part of VideoTexture library
- *
- * Contributor(s):
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file VideoTexture/Common.h
- * \ingroup bgevideotex
- */
-
-#if defined WIN32
-#define WINDOWS_LEAN_AND_MEAN
-#endif
-
-#ifndef NULL
-#define NULL 0
-#endif
-
-#ifndef _HRESULT_DEFINED
-#define _HRESULT_DEFINED
-#define HRESULT long
-#endif
-
-#ifndef DWORD
-#define DWORD unsigned long
-#endif
-
-#ifndef S_OK
-#define S_OK ((HRESULT)0L)
-#endif
-
-#ifndef BYTE
-#define BYTE unsigned char
-#endif
-
-#ifndef WIN32
-#define Sleep(time) sleep(time)
-#endif
-
-#ifndef FAILED
-#define FAILED(Status) ((HRESULT)(Status)<0)
-#endif
-
-#include <iostream>
diff --git a/source/gameengine/VideoTexture/DeckLink.cpp b/source/gameengine/VideoTexture/DeckLink.cpp
deleted file mode 100644
index fa8ab8c641c..00000000000
--- a/source/gameengine/VideoTexture/DeckLink.cpp
+++ /dev/null
@@ -1,813 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2015, Blender Foundation
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): Blender Foundation.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/VideoTexture/Texture.cpp
- * \ingroup bgevideotex
- */
-
-#ifdef WITH_GAMEENGINE_DECKLINK
-
-// implementation
-
-// FFmpeg defines its own version of stdint.h on Windows.
-// Decklink needs FFmpeg, so it uses its version of stdint.h
-// this is necessary for INT64_C macro
-#ifndef __STDC_CONSTANT_MACROS
-#define __STDC_CONSTANT_MACROS
-#endif
-// this is necessary for UINTPTR_MAX (used by atomic-ops)
-#ifndef __STDC_LIMIT_MACROS
-#define __STDC_LIMIT_MACROS
-#endif
-
-#include "atomic_ops.h"
-
-#include "EXP_PyObjectPlus.h"
-#include "KX_KetsjiEngine.h"
-#include "KX_PythonInit.h"
-#include "DeckLink.h"
-
-#include <memory.h>
-
-// macro for exception handling and logging
-#define CATCH_EXCP catch (Exception & exp) \
-{ exp.report(); return NULL; }
-
-static struct
-{
- const char *name;
- BMDDisplayMode mode;
-} sModeStringTab[] = {
- { "NTSC", bmdModeNTSC },
- { "NTSC2398", bmdModeNTSC2398 },
- { "PAL", bmdModePAL },
- { "NTSCp", bmdModeNTSCp },
- { "PALp", bmdModePALp },
-
- /* HD 1080 Modes */
-
- { "HD1080p2398", bmdModeHD1080p2398 },
- { "HD1080p24", bmdModeHD1080p24 },
- { "HD1080p25", bmdModeHD1080p25 },
- { "HD1080p2997", bmdModeHD1080p2997 },
- { "HD1080p30", bmdModeHD1080p30 },
- { "HD1080i50", bmdModeHD1080i50 },
- { "HD1080i5994", bmdModeHD1080i5994 },
- { "HD1080i6000", bmdModeHD1080i6000 },
- { "HD1080p50", bmdModeHD1080p50 },
- { "HD1080p5994", bmdModeHD1080p5994 },
- { "HD1080p6000", bmdModeHD1080p6000 },
-
- /* HD 720 Modes */
-
- { "HD720p50", bmdModeHD720p50 },
- { "HD720p5994", bmdModeHD720p5994 },
- { "HD720p60", bmdModeHD720p60 },
-
- /* 2k Modes */
-
- { "2k2398", bmdMode2k2398 },
- { "2k24", bmdMode2k24 },
- { "2k25", bmdMode2k25 },
-
- /* DCI Modes (output only) */
-
- { "2kDCI2398", bmdMode2kDCI2398 },
- { "2kDCI24", bmdMode2kDCI24 },
- { "2kDCI25", bmdMode2kDCI25 },
-
- /* 4k Modes */
-
- { "4K2160p2398", bmdMode4K2160p2398 },
- { "4K2160p24", bmdMode4K2160p24 },
- { "4K2160p25", bmdMode4K2160p25 },
- { "4K2160p2997", bmdMode4K2160p2997 },
- { "4K2160p30", bmdMode4K2160p30 },
- { "4K2160p50", bmdMode4K2160p50 },
- { "4K2160p5994", bmdMode4K2160p5994 },
- { "4K2160p60", bmdMode4K2160p60 },
- // sentinel
- { NULL }
-};
-
-static struct
-{
- const char *name;
- BMDPixelFormat format;
-} sFormatStringTab[] = {
- { "8BitYUV", bmdFormat8BitYUV },
- { "10BitYUV", bmdFormat10BitYUV },
- { "8BitARGB", bmdFormat8BitARGB },
- { "8BitBGRA", bmdFormat8BitBGRA },
- { "10BitRGB", bmdFormat10BitRGB },
- { "12BitRGB", bmdFormat12BitRGB },
- { "12BitRGBLE", bmdFormat12BitRGBLE },
- { "10BitRGBXLE", bmdFormat10BitRGBXLE },
- { "10BitRGBX", bmdFormat10BitRGBX },
- // sentinel
- { NULL }
-};
-
-ExceptionID DeckLinkBadDisplayMode, DeckLinkBadPixelFormat;
-ExpDesc DeckLinkBadDisplayModeDesc(DeckLinkBadDisplayMode, "Invalid or unsupported display mode");
-ExpDesc DeckLinkBadPixelFormatDesc(DeckLinkBadPixelFormat, "Invalid or unsupported pixel format");
-
-HRESULT decklink_ReadDisplayMode(const char *format, size_t len, BMDDisplayMode *displayMode)
-{
- int i;
-
- if (len == 0)
- len = strlen(format);
- for (i = 0; sModeStringTab[i].name != NULL; i++) {
- if (strlen(sModeStringTab[i].name) == len &&
- !strncmp(sModeStringTab[i].name, format, len))
- {
- *displayMode = sModeStringTab[i].mode;
- return S_OK;
- }
- }
- if (len != 4)
- THRWEXCP(DeckLinkBadDisplayMode, S_OK);
- // assume the user entered directly the mode value as a 4 char string
- *displayMode = (BMDDisplayMode)((((uint32_t)format[0]) << 24) + (((uint32_t)format[1]) << 16) + (((uint32_t)format[2]) << 8) + ((uint32_t)format[3]));
- return S_OK;
-}
-
-HRESULT decklink_ReadPixelFormat(const char *format, size_t len, BMDPixelFormat *pixelFormat)
-{
- int i;
-
- if (!len)
- len = strlen(format);
- for (i = 0; sFormatStringTab[i].name != NULL; i++) {
- if (strlen(sFormatStringTab[i].name) == len &&
- !strncmp(sFormatStringTab[i].name, format, len))
- {
- *pixelFormat = sFormatStringTab[i].format;
- return S_OK;
- }
- }
- if (len != 4)
- THRWEXCP(DeckLinkBadPixelFormat, S_OK);
- // assume the user entered directly the mode value as a 4 char string
- *pixelFormat = (BMDPixelFormat)((((uint32_t)format[0]) << 24) + (((uint32_t)format[1]) << 16) + (((uint32_t)format[2]) << 8) + ((uint32_t)format[3]));
- return S_OK;
-}
-
-class DeckLink3DFrameWrapper : public IDeckLinkVideoFrame, IDeckLinkVideoFrame3DExtensions
-{
-public:
- // IUnknown
- virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, LPVOID *ppv)
- {
- if (!memcmp(&iid, &IID_IDeckLinkVideoFrame3DExtensions, sizeof(iid))) {
- if (mpRightEye) {
- *ppv = (IDeckLinkVideoFrame3DExtensions*)this;
- return S_OK;
- }
- }
- return E_NOTIMPL;
- }
- virtual ULONG STDMETHODCALLTYPE AddRef(void) { return 1U; }
- virtual ULONG STDMETHODCALLTYPE Release(void) { return 1U; }
- // IDeckLinkVideoFrame
- virtual long STDMETHODCALLTYPE GetWidth(void) { return mpLeftEye->GetWidth(); }
- virtual long STDMETHODCALLTYPE GetHeight(void) { return mpLeftEye->GetHeight(); }
- virtual long STDMETHODCALLTYPE GetRowBytes(void) { return mpLeftEye->GetRowBytes(); }
- virtual BMDPixelFormat STDMETHODCALLTYPE GetPixelFormat(void) { return mpLeftEye->GetPixelFormat(); }
- virtual BMDFrameFlags STDMETHODCALLTYPE GetFlags(void) { return mpLeftEye->GetFlags(); }
- virtual HRESULT STDMETHODCALLTYPE GetBytes(void **buffer) { return mpLeftEye->GetBytes(buffer); }
- virtual HRESULT STDMETHODCALLTYPE GetTimecode(BMDTimecodeFormat format,IDeckLinkTimecode **timecode)
- { return mpLeftEye->GetTimecode(format, timecode); }
- virtual HRESULT STDMETHODCALLTYPE GetAncillaryData(IDeckLinkVideoFrameAncillary **ancillary)
- { return mpLeftEye->GetAncillaryData(ancillary); }
- // IDeckLinkVideoFrame3DExtensions
- virtual BMDVideo3DPackingFormat STDMETHODCALLTYPE Get3DPackingFormat(void)
- {
- return bmdVideo3DPackingLeftOnly;
- }
- virtual HRESULT STDMETHODCALLTYPE GetFrameForRightEye(
- /* [out] */ IDeckLinkVideoFrame **rightEyeFrame)
- {
- mpRightEye->AddRef();
- *rightEyeFrame = mpRightEye;
- return S_OK;
- }
- // Constructor
- DeckLink3DFrameWrapper(IDeckLinkVideoFrame *leftEye, IDeckLinkVideoFrame *rightEye)
- {
- mpLeftEye = leftEye;
- mpRightEye = rightEye;
- }
- // no need for a destructor, it's just a wrapper
-private:
- IDeckLinkVideoFrame *mpLeftEye;
- IDeckLinkVideoFrame *mpRightEye;
-};
-
-static void decklink_Reset(DeckLink *self)
-{
- self->m_lastClock = 0.0;
- self->mDLOutput = NULL;
- self->mUse3D = false;
- self->mDisplayMode = bmdModeUnknown;
- self->mKeyingSupported = false;
- self->mHDKeyingSupported = false;
- self->mSize[0] = 0;
- self->mSize[1] = 0;
- self->mFrameSize = 0;
- self->mLeftFrame = NULL;
- self->mRightFrame = NULL;
- self->mKeyer = NULL;
- self->mUseKeying = false;
- self->mKeyingLevel = 255;
- self->mUseExtend = false;
-}
-
-#ifdef __BIG_ENDIAN__
-#define CONV_PIXEL(i) ((((i)>>16)&0xFF00)+(((i)&0xFF00)<<16)+((i)&0xFF00FF))
-#else
-#define CONV_PIXEL(i) ((((i)&0xFF)<<16)+(((i)>>16)&0xFF)+((i)&0xFF00FF00))
-#endif
-
-// adapt the pixel format and picture size from VideoTexture (RGBA) to DeckLink (BGRA)
-static void decklink_ConvImage(uint32_t *dest, const short *destSize, const uint32_t *source, const short *srcSize, bool extend)
-{
- short w, h, x, y;
- const uint32_t *s;
- uint32_t *d, p;
- bool sameSize = (destSize[0] == srcSize[0] && destSize[1] == srcSize[1]);
-
- if (sameSize || !extend) {
- // here we convert pixel by pixel
- w = (destSize[0] < srcSize[0]) ? destSize[0] : srcSize[0];
- h = (destSize[1] < srcSize[1]) ? destSize[1] : srcSize[1];
- for (y = 0; y < h; ++y) {
- s = source + y*srcSize[0];
- d = dest + y*destSize[0];
- for (x = 0; x < w; ++x, ++s, ++d) {
- *d = CONV_PIXEL(*s);
- }
- }
- }
- else {
- // here we scale
- // interpolation accumulator
- int accHeight = srcSize[1] >> 1;
- d = dest;
- s = source;
- // process image rows
- for (y = 0; y < srcSize[1]; ++y) {
- // increase height accum
- accHeight += destSize[1];
- // if pixel row has to be drawn
- if (accHeight >= srcSize[1]) {
- // decrease accum
- accHeight -= srcSize[1];
- // width accum
- int accWidth = srcSize[0] >> 1;
- // process row
- for (x = 0; x < srcSize[0]; ++x, ++s) {
- // increase width accum
- accWidth += destSize[0];
- // convert pixel
- p = CONV_PIXEL(*s);
- // if pixel has to be drown one or more times
- while (accWidth >= srcSize[0]) {
- // decrease accum
- accWidth -= srcSize[0];
- *d++ = p;
- }
- }
- // if there should be more identical lines
- while (accHeight >= srcSize[1]) {
- accHeight -= srcSize[1];
- // copy previous line
- memcpy(d, d - destSize[0], 4 * destSize[0]);
- d += destSize[0];
- }
- }
- else {
- // if we skip a source line
- s += srcSize[0];
- }
- }
- }
-}
-
-// DeckLink object allocation
-static PyObject *DeckLink_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
-{
- // allocate object
- DeckLink * self = reinterpret_cast<DeckLink*>(type->tp_alloc(type, 0));
- // initialize object structure
- decklink_Reset(self);
- // m_leftEye is a python object, it's handled by python
- self->m_leftEye = NULL;
- self->m_rightEye = NULL;
- // return allocated object
- return reinterpret_cast<PyObject*>(self);
-}
-
-
-// forward declaration
-PyObject *DeckLink_close(DeckLink *self);
-int DeckLink_setSource(DeckLink *self, PyObject *value, void *closure);
-
-
-// DeckLink object deallocation
-static void DeckLink_dealloc(DeckLink *self)
-{
- // release renderer
- Py_XDECREF(self->m_leftEye);
- // close decklink
- PyObject *ret = DeckLink_close(self);
- Py_DECREF(ret);
- // release object
- Py_TYPE((PyObject *)self)->tp_free((PyObject *)self);
-}
-
-
-ExceptionID AutoDetectionNotAvail, DeckLinkOpenCard, DeckLinkBadFormat, DeckLinkInternalError;
-ExpDesc AutoDetectionNotAvailDesc(AutoDetectionNotAvail, "Auto detection not yet available");
-ExpDesc DeckLinkOpenCardDesc(DeckLinkOpenCard, "Cannot open card for output");
-ExpDesc DeckLinkBadFormatDesc(DeckLinkBadFormat, "Invalid or unsupported output format, use <mode>[/3D]");
-ExpDesc DeckLinkInternalErrorDesc(DeckLinkInternalError, "DeckLink API internal error, please report");
-
-// DeckLink object initialization
-static int DeckLink_init(DeckLink *self, PyObject *args, PyObject *kwds)
-{
- IDeckLinkIterator* pIterator;
- IDeckLinkAttributes* pAttributes;
- IDeckLinkDisplayModeIterator* pDisplayModeIterator;
- IDeckLinkDisplayMode* pDisplayMode;
- IDeckLink* pDL;
- char* p3D;
- BOOL flag;
- size_t len;
- int i;
- uint32_t displayFlags;
- BMDVideoOutputFlags outputFlags;
- BMDDisplayModeSupport support;
- uint32_t* bytes;
-
-
- // material ID
- short cardIdx = 0;
- // texture ID
- char *format = NULL;
-
- static const char *kwlist[] = {"cardIdx", "format", NULL};
- // get parameters
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "|hs",
- const_cast<char**>(kwlist), &cardIdx, &format))
- return -1;
-
- try {
- if (format == NULL) {
- THRWEXCP(AutoDetectionNotAvail, S_OK);
- }
-
- if ((p3D = strchr(format, '/')) != NULL && strcmp(p3D, "/3D"))
- THRWEXCP(DeckLinkBadFormat, S_OK);
- self->mUse3D = (p3D) ? true : false;
- // read the mode
- len = (p3D) ? (size_t)(p3D - format) : strlen(format);
- // throws if bad mode
- decklink_ReadDisplayMode(format, len, &self->mDisplayMode);
-
- pIterator = BMD_CreateDeckLinkIterator();
- pDL = NULL;
- if (pIterator) {
- i = 0;
- while (pIterator->Next(&pDL) == S_OK) {
- if (i == cardIdx) {
- break;
- }
- i++;
- pDL->Release();
- pDL = NULL;
- }
- pIterator->Release();
- }
-
- if (!pDL) {
- THRWEXCP(DeckLinkOpenCard, S_OK);
- }
- // detect the capabilities
- if (pDL->QueryInterface(IID_IDeckLinkAttributes, (void**)&pAttributes) == S_OK) {
- if (pAttributes->GetFlag(BMDDeckLinkSupportsInternalKeying, &flag) == S_OK && flag) {
- self->mKeyingSupported = true;
- if (pAttributes->GetFlag(BMDDeckLinkSupportsHDKeying, &flag) == S_OK && flag) {
- self->mHDKeyingSupported = true;
- }
- }
- pAttributes->Release();
- }
-
- if (pDL->QueryInterface(IID_IDeckLinkOutput, (void**)&self->mDLOutput) != S_OK) {
- self->mDLOutput = NULL;
- }
- if (self->mKeyingSupported) {
- pDL->QueryInterface(IID_IDeckLinkKeyer, (void **)&self->mKeyer);
- }
- // we don't need the device anymore, release to avoid leaking
- pDL->Release();
-
- if (!self->mDLOutput)
- THRWEXCP(DeckLinkOpenCard, S_OK);
-
- if (self->mDLOutput->GetDisplayModeIterator(&pDisplayModeIterator) != S_OK)
- THRWEXCP(DeckLinkInternalError, S_OK);
-
- displayFlags = (self->mUse3D) ? bmdDisplayModeSupports3D : 0;
- outputFlags = (self->mUse3D) ? bmdVideoOutputDualStream3D : bmdVideoOutputFlagDefault;
- pDisplayMode = NULL;
- i = 0;
- while (pDisplayModeIterator->Next(&pDisplayMode) == S_OK) {
- if (pDisplayMode->GetDisplayMode() == self->mDisplayMode
- && (pDisplayMode->GetFlags() & displayFlags) == displayFlags) {
- if (self->mDLOutput->DoesSupportVideoMode(self->mDisplayMode, bmdFormat8BitBGRA, outputFlags, &support, NULL) != S_OK ||
- support == bmdDisplayModeNotSupported)
- {
- printf("Warning: DeckLink card %d reports no BGRA support, proceed anyway\n", cardIdx);
- }
- break;
- }
- pDisplayMode->Release();
- pDisplayMode = NULL;
- i++;
- }
- pDisplayModeIterator->Release();
-
- if (!pDisplayMode)
- THRWEXCP(DeckLinkBadFormat, S_OK);
- self->mSize[0] = pDisplayMode->GetWidth();
- self->mSize[1] = pDisplayMode->GetHeight();
- self->mFrameSize = 4*self->mSize[0]*self->mSize[1];
- pDisplayMode->Release();
- if (self->mDLOutput->EnableVideoOutput(self->mDisplayMode, outputFlags) != S_OK)
- // this shouldn't fail
- THRWEXCP(DeckLinkOpenCard, S_OK);
-
- if (self->mDLOutput->CreateVideoFrame(self->mSize[0], self->mSize[1], self->mSize[0] * 4, bmdFormat8BitBGRA, bmdFrameFlagFlipVertical, &self->mLeftFrame) != S_OK)
- THRWEXCP(DeckLinkInternalError, S_OK);
- // clear alpha channel in the frame buffer
- self->mLeftFrame->GetBytes((void **)&bytes);
- memset(bytes, 0, self->mFrameSize);
- if (self->mUse3D) {
- if (self->mDLOutput->CreateVideoFrame(self->mSize[0], self->mSize[1], self->mSize[0] * 4, bmdFormat8BitBGRA, bmdFrameFlagFlipVertical, &self->mRightFrame) != S_OK)
- THRWEXCP(DeckLinkInternalError, S_OK);
- // clear alpha channel in the frame buffer
- self->mRightFrame->GetBytes((void **)&bytes);
- memset(bytes, 0, self->mFrameSize);
- }
- }
- catch (Exception & exp)
- {
- printf("DeckLink: exception when opening card %d: %s\n", cardIdx, exp.what());
- exp.report();
- // normally, the object should be deallocated
- return -1;
- }
- // initialization succeeded
- return 0;
-}
-
-
-// close added decklink
-PyObject *DeckLink_close(DeckLink * self)
-{
- if (self->mLeftFrame)
- self->mLeftFrame->Release();
- if (self->mRightFrame)
- self->mRightFrame->Release();
- if (self->mKeyer)
- self->mKeyer->Release();
- if (self->mDLOutput)
- self->mDLOutput->Release();
- decklink_Reset(self);
- Py_RETURN_NONE;
-}
-
-
-// refresh decklink key frame
-static PyObject *DeckLink_refresh(DeckLink *self, PyObject *args)
-{
- // get parameter - refresh source
- PyObject *param;
- double ts = -1.0;
-
- if (!PyArg_ParseTuple(args, "O|d:refresh", &param, &ts) || !PyBool_Check(param)) {
- // report error
- PyErr_SetString(PyExc_TypeError, "The value must be a bool");
- return NULL;
- }
- // some trick here: we are in the business of loading a key frame in decklink,
- // no use to do it if we are still in the same rendering frame.
- // We find this out by looking at the engine current clock time
- KX_KetsjiEngine* engine = KX_GetActiveEngine();
- if (engine->GetClockTime() != self->m_lastClock)
- {
- self->m_lastClock = engine->GetClockTime();
- // set source refresh
- bool refreshSource = (param == Py_True);
- uint32_t *leftEye = NULL;
- uint32_t *rightEye = NULL;
- // try to process key frame from source
- try {
- // check if optimization is possible
- if (self->m_leftEye != NULL) {
- ImageBase *leftImage = self->m_leftEye->m_image;
- short * srcSize = leftImage->getSize();
- self->mLeftFrame->GetBytes((void **)&leftEye);
- if (srcSize[0] == self->mSize[0] && srcSize[1] == self->mSize[1])
- {
- // buffer has same size, can load directly
- if (!leftImage->loadImage(leftEye, self->mFrameSize, GL_BGRA, ts))
- leftEye = NULL;
- }
- else {
- // scaling is required, go the hard way
- unsigned int *src = leftImage->getImage(0, ts);
- if (src != NULL)
- decklink_ConvImage(leftEye, self->mSize, src, srcSize, self->mUseExtend);
- else
- leftEye = NULL;
- }
- }
- if (leftEye) {
- if (self->mUse3D && self->m_rightEye != NULL) {
- ImageBase *rightImage = self->m_rightEye->m_image;
- short * srcSize = rightImage->getSize();
- self->mRightFrame->GetBytes((void **)&rightEye);
- if (srcSize[0] == self->mSize[0] && srcSize[1] == self->mSize[1])
- {
- // buffer has same size, can load directly
- rightImage->loadImage(rightEye, self->mFrameSize, GL_BGRA, ts);
- }
- else {
- // scaling is required, go the hard way
- unsigned int *src = rightImage->getImage(0, ts);
- if (src != NULL)
- decklink_ConvImage(rightEye, self->mSize, src, srcSize, self->mUseExtend);
- }
- }
- if (self->mUse3D) {
- DeckLink3DFrameWrapper frame3D(
- (IDeckLinkVideoFrame*)self->mLeftFrame,
- (IDeckLinkVideoFrame*)self->mRightFrame);
- self->mDLOutput->DisplayVideoFrameSync(&frame3D);
- }
- else {
- self->mDLOutput->DisplayVideoFrameSync((IDeckLinkVideoFrame*)self->mLeftFrame);
- }
- }
- // refresh texture source, if required
- if (refreshSource) {
- if (self->m_leftEye)
- self->m_leftEye->m_image->refresh();
- if (self->m_rightEye)
- self->m_rightEye->m_image->refresh();
- }
- }
- CATCH_EXCP;
- }
- Py_RETURN_NONE;
-}
-
-// get source object
-static PyObject *DeckLink_getSource(DeckLink *self, PyObject *value, void *closure)
-{
- // if source exists
- if (self->m_leftEye != NULL) {
- Py_INCREF(self->m_leftEye);
- return reinterpret_cast<PyObject*>(self->m_leftEye);
- }
- // otherwise return None
- Py_RETURN_NONE;
-}
-
-
-// set source object
-int DeckLink_setSource(DeckLink *self, PyObject *value, void *closure)
-{
- // check new value
- if (value == NULL || !pyImageTypes.in(Py_TYPE(value))) {
- // report value error
- PyErr_SetString(PyExc_TypeError, "Invalid type of value");
- return -1;
- }
- // increase ref count for new value
- Py_INCREF(value);
- // release previous
- Py_XDECREF(self->m_leftEye);
- // set new value
- self->m_leftEye = reinterpret_cast<PyImage*>(value);
- // return success
- return 0;
-}
-
-// get source object
-static PyObject *DeckLink_getRight(DeckLink *self, PyObject *value, void *closure)
-{
- // if source exists
- if (self->m_rightEye != NULL)
- {
- Py_INCREF(self->m_rightEye);
- return reinterpret_cast<PyObject*>(self->m_rightEye);
- }
- // otherwise return None
- Py_RETURN_NONE;
-}
-
-
-// set source object
-static int DeckLink_setRight(DeckLink *self, PyObject *value, void *closure)
-{
- // check new value
- if (value == NULL || !pyImageTypes.in(Py_TYPE(value)))
- {
- // report value error
- PyErr_SetString(PyExc_TypeError, "Invalid type of value");
- return -1;
- }
- // increase ref count for new value
- Py_INCREF(value);
- // release previous
- Py_XDECREF(self->m_rightEye);
- // set new value
- self->m_rightEye = reinterpret_cast<PyImage*>(value);
- // return success
- return 0;
-}
-
-
-static PyObject *DeckLink_getKeying(DeckLink *self, PyObject *value, void *closure)
-{
- if (self->mUseKeying) Py_RETURN_TRUE;
- else Py_RETURN_FALSE;
-}
-
-static int DeckLink_setKeying(DeckLink *self, PyObject *value, void *closure)
-{
- if (value == NULL || !PyBool_Check(value))
- {
- PyErr_SetString(PyExc_TypeError, "The value must be a bool");
- return -1;
- }
- if (self->mKeyer != NULL)
- {
- if (value == Py_True)
- {
- if (self->mKeyer->Enable(false) != S_OK)
- {
- PyErr_SetString(PyExc_RuntimeError, "Error enabling keyer");
- return -1;
- }
- self->mUseKeying = true;
- self->mKeyer->SetLevel(self->mKeyingLevel);
- }
- else
- {
- self->mKeyer->Disable();
- self->mUseKeying = false;
- }
- }
- // success
- return 0;
-}
-
-static PyObject *DeckLink_getLevel(DeckLink *self, PyObject *value, void *closure)
-{
- return Py_BuildValue("h", self->mKeyingLevel);
-}
-
-static int DeckLink_setLevel(DeckLink *self, PyObject *value, void *closure)
-{
- long level;
- if (value == NULL || !PyLong_Check(value)) {
- PyErr_SetString(PyExc_TypeError, "The value must be an integer from 0 to 255");
- return -1;
- }
- level = PyLong_AsLong(value);
- if (level > 255)
- level = 255;
- else if (level < 0)
- level = 0;
- self->mKeyingLevel = (uint8_t)level;
- if (self->mUseKeying) {
- if (self->mKeyer->SetLevel(self->mKeyingLevel) != S_OK) {
- PyErr_SetString(PyExc_RuntimeError, "Error changin level of keyer");
- return -1;
- }
- }
- // success
- return 0;
-}
-
-static PyObject *DeckLink_getExtend(DeckLink *self, PyObject *value, void *closure)
-{
- if (self->mUseExtend) Py_RETURN_TRUE;
- else Py_RETURN_FALSE;
-}
-
-static int DeckLink_setExtend(DeckLink *self, PyObject *value, void *closure)
-{
- if (value == NULL || !PyBool_Check(value))
- {
- PyErr_SetString(PyExc_TypeError, "The value must be a bool");
- return -1;
- }
- self->mUseExtend = (value == Py_True);
- return 0;
-}
-
-// class DeckLink methods
-static PyMethodDef decklinkMethods[] =
-{
- { "close", (PyCFunction)DeckLink_close, METH_NOARGS, "Close dynamic decklink and restore original"},
- { "refresh", (PyCFunction)DeckLink_refresh, METH_VARARGS, "Refresh decklink from source"},
- {NULL} /* Sentinel */
-};
-
-// class DeckLink attributes
-static PyGetSetDef decklinkGetSets[] =
-{
- { (char*)"source", (getter)DeckLink_getSource, (setter)DeckLink_setSource, (char*)"source of decklink (left eye)", NULL},
- { (char*)"right", (getter)DeckLink_getRight, (setter)DeckLink_setRight, (char*)"source of decklink (right eye)", NULL },
- { (char*)"keying", (getter)DeckLink_getKeying, (setter)DeckLink_setKeying, (char*)"whether keying is enabled (frame is alpha-composited with passthrough output)", NULL },
- { (char*)"level", (getter)DeckLink_getLevel, (setter)DeckLink_setLevel, (char*)"change the level of keying (overall alpha level of key frame, 0 to 255)", NULL },
- { (char*)"extend", (getter)DeckLink_getExtend, (setter)DeckLink_setExtend, (char*)"whether image should stretched to fit frame", NULL },
- { NULL }
-};
-
-
-// class DeckLink declaration
-PyTypeObject DeckLinkType =
-{
- PyVarObject_HEAD_INIT(NULL, 0)
- "VideoTexture.DeckLink", /*tp_name*/
- sizeof(DeckLink), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- (destructor)DeckLink_dealloc,/*tp_dealloc*/
- 0, /*tp_print*/
- 0, /*tp_getattr*/
- 0, /*tp_setattr*/
- 0, /*tp_compare*/
- 0, /*tp_repr*/
- 0, /*tp_as_number*/
- 0, /*tp_as_sequence*/
- 0, /*tp_as_mapping*/
- 0, /*tp_hash */
- 0, /*tp_call*/
- 0, /*tp_str*/
- 0, /*tp_getattro*/
- 0, /*tp_setattro*/
- &imageBufferProcs, /*tp_as_buffer*/
- Py_TPFLAGS_DEFAULT, /*tp_flags*/
- "DeckLink objects", /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- decklinkMethods, /* tp_methods */
- 0, /* tp_members */
- decklinkGetSets, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- (initproc)DeckLink_init, /* tp_init */
- 0, /* tp_alloc */
- DeckLink_new, /* tp_new */
-};
-
-#endif /* WITH_GAMEENGINE_DECKLINK */
diff --git a/source/gameengine/VideoTexture/DeckLink.h b/source/gameengine/VideoTexture/DeckLink.h
deleted file mode 100644
index 4528fe7cec0..00000000000
--- a/source/gameengine/VideoTexture/DeckLink.h
+++ /dev/null
@@ -1,86 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2015, Blender Foundation
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): Blender Foundation.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file VideoTexture/DeckLink.h
- * \ingroup bgevideotex
- */
-
-#ifndef __DECKLINK_H__
-#define __DECKLINK_H__
-
-#ifdef WITH_GAMEENGINE_DECKLINK
-
-#include "EXP_PyObjectPlus.h"
-#include <structmember.h>
-
-#include "DNA_image_types.h"
-
-#include "DeckLinkAPI.h"
-
-#include "ImageBase.h"
-#include "BlendType.h"
-#include "Exception.h"
-
-
-// type DeckLink declaration
-struct DeckLink
-{
- PyObject_HEAD
-
- // last refresh
- double m_lastClock;
- // decklink card to which we output
- IDeckLinkOutput * mDLOutput;
- IDeckLinkKeyer * mKeyer;
- IDeckLinkMutableVideoFrame *mLeftFrame;
- IDeckLinkMutableVideoFrame *mRightFrame;
- bool mUse3D;
- bool mUseKeying;
- bool mUseExtend;
- bool mKeyingSupported;
- bool mHDKeyingSupported;
- uint8_t mKeyingLevel;
- BMDDisplayMode mDisplayMode;
- short mSize[2];
- uint32_t mFrameSize;
-
- // image source
- PyImage * m_leftEye;
- PyImage * m_rightEye;
-};
-
-
-// DeckLink type description
-extern PyTypeObject DeckLinkType;
-
-// helper function
-HRESULT decklink_ReadDisplayMode(const char *format, size_t len, BMDDisplayMode *displayMode);
-HRESULT decklink_ReadPixelFormat(const char *format, size_t len, BMDPixelFormat *displayMode);
-
-#endif /* WITH_GAMEENGINE_DECKLINK */
-
-#endif /* __DECKLINK_H__ */
diff --git a/source/gameengine/VideoTexture/Exception.cpp b/source/gameengine/VideoTexture/Exception.cpp
deleted file mode 100644
index 9f82987ea62..00000000000
--- a/source/gameengine/VideoTexture/Exception.cpp
+++ /dev/null
@@ -1,241 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * Copyright (c) 2006 The Zdeno Ash Miklas
- *
- * This source file is part of VideoTexture library
- *
- * Contributor(s):
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/VideoTexture/Exception.cpp
- * \ingroup bgevideotex
- */
-
-#include <sstream>
-#include <fstream>
-
-#include "EXP_PyObjectPlus.h"
-
-#include "Exception.h"
-
-
-// exception identificators
-ExceptionID ErrGeneral, ErrNotFound;
-
-// exception descriptions
-ExpDesc errGenerDesc(ErrGeneral, "General Error");
-ExpDesc errNFoundDesc(ErrNotFound, "Error description not found");
-
-
-
-// implementation of ExpDesc
-
-// constructor
-ExpDesc::ExpDesc (ExceptionID & exp, const char *desc, RESULT hres)
-: m_expID(exp), m_hRslt(hres), m_description(desc)
-{
-}
-
-// destructor
-ExpDesc::~ExpDesc (void) {}
-
-// list of descriptions
-std::vector<ExpDesc*> ExpDesc::m_expDescs;
-
-
-// class Exception
-
-
-// last exception description
-std::string Exception::m_lastError;
-
-// log file name
-const char * Exception::m_logFile = NULL;
-
-
-// basic constructor
-Exception::Exception ()
-{
- // default values
- m_expID = &ErrNotFound;
- m_hRslt = S_OK;
- m_line = 0;
-}
-
-
-// destructor
-Exception::~Exception () throw() { }
-
-
-// copy constructor
-Exception::Exception (const Exception & xpt)
-{ copy (xpt); }
-
-
-// assignment operator
-Exception & Exception::operator= (const Exception & xpt)
-{ copy (xpt); return *this; }
-
-
-// get exception description
-const char * Exception::what()
-{
- // set exception description
- setXptDesc();
- // return c string
- return m_desc.c_str();
-}
-
-
-// debug version - with file and line of exception
-Exception::Exception (ExceptionID & expID, RESULT rslt, const char *fil, int lin)
-: m_expID (&expID), m_hRslt (rslt)
-{
- // set file and line
- if (fil[0] != '\0' || lin > 0)
- setFileLine (fil, lin);
- else
- m_line = -1;
-}
-
-
-// set file and line
-void Exception::setFileLine (const char *fil, int lin)
-{
- if (fil != NULL) m_fileName = fil;
- m_line = lin;
-}
-
-
-// report exception
-void Exception::report(void)
-{
- // set exception description
- setXptDesc();
- // set python error
- PyErr_SetString(PyExc_RuntimeError, what());
- // if log file is set
- if (m_logFile != NULL)
- {
- // write description to log
- std::ofstream logf (m_logFile, std::ios_base::app);
- logf << m_fileName << ':' << m_line << ':' << m_desc << std::endl;
- logf.flush();
- logf.close();
- }
-}
-
-
-// set exception description
-void Exception::setXptDesc (void)
-{
- // if description is not set
- if (m_desc.size() == 0)
- {
- // start of search -1
- // found description "NotFound" 0
- // found description without matching result 1
- // found description with matching result 2
- int best = -1;
- // find exception description
- for (std::vector<ExpDesc*>::iterator it = ExpDesc::m_expDescs.begin(); it != ExpDesc::m_expDescs.end(); ++it)
- {
- // use "NotFound", if there is not better
- if (best < 0 && (*it)->isExp(&ErrNotFound) > 0)
- {
- (*it)->loadDesc(m_desc);
- best = 0;
- }
- // match exception
- int nBest = (*it)->isExp(m_expID, m_hRslt);
- // if exception is matching better
- if (nBest > 0 && best < nBest)
- {
- // set description
- (*it)->loadDesc(m_desc);
- best = nBest;
- // if matching exactly, finish search
- if (best == 2) break;
- }
- }
- // add result code
- // length of result code
- const size_t rsltSize = 11;
- // delimit description
- //const char delimRslt[] = ": ";
- // set text of description
- char rsltTxt[rsltSize];
- std::ostringstream os;
- os << std::hex << m_hRslt << ": " << '\0';
- // copy result to description
- m_desc.insert(0, rsltTxt);
- // copy exception description to last exception string
- m_lastError = m_desc;
- }
-}
-
-
-// copy exception data
-void Exception::copy (const Exception & xpt)
-{
- // standard data
- m_expID = xpt.m_expID;
- m_hRslt = xpt.m_hRslt;
- m_desc = xpt.m_desc;
-
- // debug data
- m_fileName = xpt.m_fileName;
- m_line = xpt.m_line;
-}
-
-void registerAllExceptions(void)
-{
- errGenerDesc.registerDesc();
- errNFoundDesc.registerDesc();
- MaterialNotAvailDesc.registerDesc();
- ImageSizesNotMatchDesc.registerDesc();
- ImageHasExportsDesc.registerDesc();
- InvalidColorChannelDesc.registerDesc();
- InvalidImageModeDesc.registerDesc();
- SceneInvalidDesc.registerDesc();
- CameraInvalidDesc.registerDesc();
- ObserverInvalidDesc.registerDesc();
- MirrorInvalidDesc.registerDesc();
- MirrorSizeInvalidDesc.registerDesc();
- MirrorNormalInvalidDesc.registerDesc();
- MirrorHorizontalDesc.registerDesc();
- MirrorTooSmallDesc.registerDesc();
- SourceVideoEmptyDesc.registerDesc();
- SourceVideoCreationDesc.registerDesc();
- OffScreenInvalidDesc.registerDesc();
-#ifdef WITH_GAMEENGINE_DECKLINK
- AutoDetectionNotAvailDesc.registerDesc();
- DeckLinkBadDisplayModeDesc.registerDesc();
- DeckLinkBadPixelFormatDesc.registerDesc();
- DeckLinkOpenCardDesc.registerDesc();
- DeckLinkBadFormatDesc.registerDesc();
- DeckLinkInternalErrorDesc.registerDesc();
- SourceVideoOnlyCaptureDesc.registerDesc();
- VideoDeckLinkBadFormatDesc.registerDesc();
- VideoDeckLinkOpenCardDesc.registerDesc();
- VideoDeckLinkDvpInternalErrorDesc.registerDesc();
- VideoDeckLinkPinMemoryErrorDesc.registerDesc();
-#endif
-}
diff --git a/source/gameengine/VideoTexture/Exception.h b/source/gameengine/VideoTexture/Exception.h
deleted file mode 100644
index c4de85ff34d..00000000000
--- a/source/gameengine/VideoTexture/Exception.h
+++ /dev/null
@@ -1,239 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * Copyright (c) 2006 The Zdeno Ash Miklas
- *
- * This source file is part of VideoTexture library
- *
- * Contributor(s):
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/VideoTexture/Exception.h
- * \ingroup bgevideotex
- */
-
-#ifndef __EXCEPTION_H__
-#define __EXCEPTION_H__
-
-#include <exception>
-#include <vector>
-#include <string>
-#include <algorithm>
-
-#include "Common.h"
-
-
-#define CHCKHRSLTV(fnc,val,err) \
-{ \
- HRESULT macroHRslt = (fnc); \
- if (macroHRslt != val) \
- throw Exception (err, macroHRslt, __FILE__, __LINE__); \
-}
-
-#define THRWEXCP(err,hRslt) throw Exception (err, hRslt, __FILE__, __LINE__)
-
-
-#if defined WIN32
-
-#define CHCKHRSLT(fnc,err) \
-{ \
- HRESULT macroHRslt = (fnc); \
- if (FAILED(macroHRslt)) \
- throw Exception (err, macroHRslt, __FILE__, __LINE__); \
-}
-
-#else
-
-#define CHCKHRSLT(fnc,err) CHCKHRSLTV(fnc,S_OK,err)
-
-#endif
-
-
-// forward declarations
-class ExceptionID;
-class Exception;
-
-
-// exception identificators
-extern ExceptionID ErrGeneral, ErrNotFound;
-
-
-// result type
-typedef long RESULT;
-
-
-// class ExceptionID for exception identification
-class ExceptionID
-{
-public:
- // constructor a destructor
- ExceptionID (void) {}
- ~ExceptionID (void) {}
-
-private:
- // not allowed
- ExceptionID (const ExceptionID & obj) throw() {}
- ExceptionID & operator= (const ExceptionID & obj) throw() { return *this; }
-};
-
-
-// class ExpDesc for exception description
-class ExpDesc
-{
-public:
- // constructor a destructor
- ExpDesc (ExceptionID & exp, const char * desc, RESULT hres = S_OK);
- ~ExpDesc (void);
-
- // comparision function
- // returns 0, if exception identification don't match at all
- // returns 1, if only exception identification is matching
- // returns 2, if both exception identification and result are matching
- int isExp (ExceptionID *exp, RESULT hres = S_OK) throw()
- {
- // check exception identification
- if (&m_expID == exp)
- {
- // check result value
- if (m_hRslt == hres) return 2;
- // only identification match
- if (m_hRslt == S_OK) return 1;
- }
- // no match
- return 0;
- }
-
- // get exception description
- void loadDesc (std::string & desc) throw()
- {
- desc = m_description;
- }
-
- void registerDesc(void)
- {
- if (std::find(m_expDescs.begin(), m_expDescs.end(), this) == m_expDescs.end())
- m_expDescs.push_back(this);
- }
- // list of exception descriptions
- static std::vector<ExpDesc*> m_expDescs;
-
-private:
- // exception ID
- ExceptionID & m_expID;
- // result
- RESULT m_hRslt;
- // description
- const char * m_description;
-
- // not allowed
- ExpDesc (const ExpDesc & obj) : m_expID (ErrNotFound) {}
- ExpDesc & operator= (const ExpDesc & obj) { return *this; }
-};
-
-
-
-// class Exception
-class Exception : public std::exception
-{
-public:
- // constructor
- Exception ();
- // destructor
- virtual ~Exception () throw();
- // copy constructor
- Exception (const Exception & xpt);
- // assignment operator
- Exception & operator= (const Exception & xpt);
- // get exception description
- virtual const char * what(void);
-
- // debug version of constructor
- Exception (ExceptionID & expID, RESULT rslt, const char * fil, int lin);
- // set source file and line of exception
- void setFileLine (const char * fil, int lin);
-
- // get description in string
- std::string & getDesc (void) throw() { return m_desc; }
-
- // report exception
- virtual void report (void);
-
- // get exception id
- ExceptionID * getID (void) throw() { return m_expID; }
-
- /// last exception description
- static std::string m_lastError;
-
- /// log file name
- static const char * m_logFile;
-
-protected:
- // exception identification
- ExceptionID * m_expID;
- // RESULT code
- RESULT m_hRslt;
-
- // exception description
- std::string m_desc;
-
- // set exception description
- virtual void setXptDesc (void);
-
- // copy exception
- void copy (const Exception & xpt);
-
- // file name where exception was thrown
- std::string m_fileName;
- // line number in file
- int m_line;
-
-};
-
-extern ExpDesc MaterialNotAvailDesc;
-extern ExpDesc ImageSizesNotMatchDesc;
-extern ExpDesc ImageHasExportsDesc;
-extern ExpDesc InvalidColorChannelDesc;
-extern ExpDesc InvalidImageModeDesc;
-extern ExpDesc SceneInvalidDesc;
-extern ExpDesc CameraInvalidDesc;
-extern ExpDesc ObserverInvalidDesc;
-extern ExpDesc OffScreenInvalidDesc;
-extern ExpDesc MirrorInvalidDesc;
-extern ExpDesc MirrorSizeInvalidDesc;
-extern ExpDesc MirrorNormalInvalidDesc;
-extern ExpDesc MirrorHorizontalDesc;
-extern ExpDesc MirrorTooSmallDesc;
-extern ExpDesc SourceVideoEmptyDesc;
-extern ExpDesc SourceVideoCreationDesc;
-extern ExpDesc DeckLinkBadDisplayModeDesc;
-extern ExpDesc DeckLinkBadPixelFormatDesc;
-extern ExpDesc AutoDetectionNotAvailDesc;
-extern ExpDesc DeckLinkOpenCardDesc;
-extern ExpDesc DeckLinkBadFormatDesc;
-extern ExpDesc DeckLinkInternalErrorDesc;
-extern ExpDesc SourceVideoOnlyCaptureDesc;
-extern ExpDesc VideoDeckLinkBadFormatDesc;
-extern ExpDesc VideoDeckLinkOpenCardDesc;
-extern ExpDesc VideoDeckLinkDvpInternalErrorDesc;
-extern ExpDesc VideoDeckLinkPinMemoryErrorDesc;
-
-extern ExceptionID InvalidImageMode;
-
-void registerAllExceptions(void);
-#endif
diff --git a/source/gameengine/VideoTexture/FilterBase.cpp b/source/gameengine/VideoTexture/FilterBase.cpp
deleted file mode 100644
index b41a2095890..00000000000
--- a/source/gameengine/VideoTexture/FilterBase.cpp
+++ /dev/null
@@ -1,160 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * Copyright (c) 2007 The Zdeno Ash Miklas
- *
- * This source file is part of VideoTexture library
- *
- * Contributor(s):
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/VideoTexture/FilterBase.cpp
- * \ingroup bgevideotex
- */
-
-
-#include "FilterBase.h"
-
-#include "EXP_PyObjectPlus.h"
-#include <structmember.h>
-
-
-// FilterBase class implementation
-
-// constructor
-FilterBase::FilterBase (void) : m_previous(NULL) {}
-
-
-// destructor
-FilterBase::~FilterBase (void)
-{
- // release Python objects, if not released yet
- release();
-}
-
-
-// release python objects
-void FilterBase::release (void)
-{
- // release previous filter object
- setPrevious(NULL);
-}
-
-
-// set new previous filter
-void FilterBase::setPrevious(PyFilter *filt, bool useRefCnt)
-{
- // if reference counting has to be used
- if (useRefCnt)
- {
- // reference new filter
- if (filt != NULL) Py_INCREF(filt);
- // release old filter
- Py_XDECREF(m_previous);
- }
- // set new previous filter
- m_previous = filt;
-}
-
-
-// find first filter
-FilterBase * FilterBase::findFirst (void)
-{
- // find first filter in chain
- FilterBase * frst;
- for (frst = this; frst->m_previous != NULL; frst = frst->m_previous->m_filter) {};
- // set first filter
- return frst;
-}
-
-
-
-// list offilter types
-PyTypeList pyFilterTypes;
-
-
-
-// functions for python interface
-
-
-// object allocation
-PyObject *Filter_allocNew (PyTypeObject *type, PyObject *args, PyObject *kwds)
-{
- // allocate object
- PyFilter *self = reinterpret_cast<PyFilter*>(type->tp_alloc(type, 0));
- // initialize object structure
- self->m_filter = NULL;
- // return allocated object
- return reinterpret_cast<PyObject*>(self);
-}
-
-// object deallocation
-void Filter_dealloc(PyFilter *self)
-{
- // release object attributes
- if (self->m_filter != NULL)
- {
- self->m_filter->release();
- delete self->m_filter;
- self->m_filter = NULL;
- }
- Py_TYPE((PyObject *)self)->tp_free((PyObject *)self);
-}
-
-
-// get previous pixel filter object
-PyObject *Filter_getPrevious (PyFilter *self, void *closure)
-{
- // if filter object is available
- if (self->m_filter != NULL)
- {
- // pixel filter object
- PyObject *filt = reinterpret_cast<PyObject*>(self->m_filter->getPrevious());
- // if filter is present
- if (filt != NULL)
- {
- // return it
- Py_INCREF(filt);
- return filt;
- }
- }
- // otherwise return none
- Py_RETURN_NONE;
-}
-
-
-// set previous pixel filter object
-int Filter_setPrevious(PyFilter *self, PyObject *value, void *closure)
-{
- // if filter object is available
- if (self->m_filter != NULL)
- {
- // check new value
- if (value == NULL || !pyFilterTypes.in(Py_TYPE(value)))
- {
- // report value error
- PyErr_SetString(PyExc_TypeError, "Invalid type of value");
- return -1;
- }
- // set new value
- self->m_filter->setPrevious(reinterpret_cast<PyFilter*>(value));
- }
- // return success
- return 0;
-}
diff --git a/source/gameengine/VideoTexture/FilterBase.h b/source/gameengine/VideoTexture/FilterBase.h
deleted file mode 100644
index db688d551d0..00000000000
--- a/source/gameengine/VideoTexture/FilterBase.h
+++ /dev/null
@@ -1,161 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * Copyright (c) 2007 The Zdeno Ash Miklas
- *
- * This source file is part of VideoTexture library
- *
- * Contributor(s):
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file FilterBase.h
- * \ingroup bgevideotex
- */
-
-#ifndef __FILTERBASE_H__
-#define __FILTERBASE_H__
-
-#include "Common.h"
-
-#include "EXP_PyObjectPlus.h"
-
-#include "PyTypeList.h"
-
-#define VT_C(v,idx) ((unsigned char*)&v)[idx]
-#define VT_R(v) ((unsigned char*)&v)[0]
-#define VT_G(v) ((unsigned char*)&v)[1]
-#define VT_B(v) ((unsigned char*)&v)[2]
-#define VT_A(v) ((unsigned char*)&v)[3]
-#define VT_RGBA(v,r,g,b,a) VT_R(v)=(unsigned char)r, VT_G(v)=(unsigned char)g, VT_B(v)=(unsigned char)b, VT_A(v)=(unsigned char)a
-
-#ifdef __BIG_ENDIAN__
-# define VT_SWAPBR(i) ((((i) >> 16) & 0xFF00) + (((i) & 0xFF00) << 16) + ((i) & 0xFF00FF))
-#else
-# define VT_SWAPBR(i) ((((i) & 0xFF) << 16) + (((i) >> 16) & 0xFF) + ((i) & 0xFF00FF00))
-#endif
-
-
-// forward declaration
-class FilterBase;
-
-
-// python structure for filter
-struct PyFilter
-{
- PyObject_HEAD
- // source object
- FilterBase * m_filter;
-};
-
-
-/// base class for pixel filters
-class FilterBase
-{
-public:
- /// constructor
- FilterBase (void);
- /// destructor
- virtual ~FilterBase (void);
- // release python objects
- virtual void release (void);
-
- /// convert pixel
- template <class SRC> unsigned int convert (SRC src, short x, short y,
- short * size, unsigned int pixSize)
- {
- return filter(src, x, y, size, pixSize,
- convertPrevious(src, x, y, size, pixSize));
- }
-
- /// get previous filter
- PyFilter * getPrevious (void) { return m_previous; }
- /// set previous filter
- void setPrevious (PyFilter *filt, bool useRefCnt = true);
-
- /// find first filter in chain
- FilterBase * findFirst (void);
-
- /// get first filter's source pixel size
- unsigned int firstPixelSize (void) { return findFirst()->getPixelSize(); }
-
-protected:
- /// previous pixel filter
- PyFilter * m_previous;
-
- /// filter pixel, source byte buffer
- virtual unsigned int filter(unsigned char *src, short x, short y,
- short *size, unsigned int pixSize, unsigned int val = 0)
- { return val; }
- /// filter pixel, source int buffer
- virtual unsigned int filter(unsigned int *src, short x, short y,
- short *size, unsigned int pixSize, unsigned int val = 0)
- { return val; }
- /// filter pixel, source float buffer
- virtual unsigned int filter(float *src, short x, short y,
- short *size, unsigned int pixSize, unsigned int val = 0)
- { return val; }
-
- /// get source pixel size
- virtual unsigned int getPixelSize(void) { return 1; }
-
- /// get converted pixel from previous filters
- template <class SRC> unsigned int convertPrevious (SRC src, short x, short y,
- short * size, unsigned int pixSize)
- {
- // if previous filter doesn't exists, return source pixel
- if (m_previous == NULL) return *src;
- // otherwise return converted pixel
- return m_previous->m_filter->convert(src, x, y, size, pixSize);
- }
-
-#ifdef WITH_CXX_GUARDEDALLOC
- MEM_CXX_CLASS_ALLOC_FUNCS("GE:FilterBase")
-#endif
-};
-
-
-// list of python filter types
-extern PyTypeList pyFilterTypes;
-
-
-// functions for python interface
-
-// object initialization
-template <class T> static int Filter_init (PyObject *pySelf, PyObject *args, PyObject *kwds)
-{
- PyFilter *self = reinterpret_cast<PyFilter*>(pySelf);
- // create filter object
- if (self->m_filter != NULL) delete self->m_filter;
- self->m_filter = new T();
- // initialization succeded
- return 0;
-}
-
-// object allocation
-PyObject *Filter_allocNew(PyTypeObject *type, PyObject *args, PyObject *kwds);
-// object deallocation
-void Filter_dealloc(PyFilter *self);
-
-// get previous pixel filter object
-PyObject *Filter_getPrevious(PyFilter *self, void *closure);
-// set previous pixel filter object
-int Filter_setPrevious(PyFilter *self, PyObject *value, void *closure);
-
-
-#endif
diff --git a/source/gameengine/VideoTexture/FilterBlueScreen.cpp b/source/gameengine/VideoTexture/FilterBlueScreen.cpp
deleted file mode 100644
index a25d09e1eee..00000000000
--- a/source/gameengine/VideoTexture/FilterBlueScreen.cpp
+++ /dev/null
@@ -1,190 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * Copyright (c) 2007 The Zdeno Ash Miklas
- *
- * This source file is part of VideoTexture library
- *
- * Contributor(s):
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/VideoTexture/FilterBlueScreen.cpp
- * \ingroup bgevideotex
- */
-
-#include "EXP_PyObjectPlus.h"
-#include <structmember.h>
-
-#include "FilterBlueScreen.h"
-
-#include "FilterBase.h"
-#include "PyTypeList.h"
-
-// implementation FilterBlueScreen
-
-// constructor
-FilterBlueScreen::FilterBlueScreen (void)
-{
- // set color to blue
- setColor(0, 0, 255);
- // set limits
- setLimits(64, 64);
-}
-
-// set color
-void FilterBlueScreen::setColor (unsigned char red, unsigned char green, unsigned char blue)
-{
- m_color[0] = red;
- m_color[1] = green;
- m_color[2] = blue;
-}
-
-// set limits for color variation
-void FilterBlueScreen::setLimits (unsigned short minLimit, unsigned short maxLimit)
-{
- m_limits[0] = minLimit;
- m_limits[1] = maxLimit > minLimit ? maxLimit : minLimit;
- // calculate square values
- for (short idx = 0; idx < 2; ++idx)
- m_squareLimits[idx] = m_limits[idx] * m_limits[idx];
- // limits distance
- m_limitDist = m_squareLimits[1] - m_squareLimits[0];
-}
-
-
-
-// cast Filter pointer to FilterBlueScreen
-inline FilterBlueScreen * getFilter (PyFilter *self)
-{ return static_cast<FilterBlueScreen*>(self->m_filter); }
-
-
-// python methods and get/sets
-
-// get color
-static PyObject *getColor (PyFilter *self, void *closure)
-{
- return Py_BuildValue("[BBB]", getFilter(self)->getColor()[0],
- getFilter(self)->getColor()[1], getFilter(self)->getColor()[2]);
-}
-
-// set color
-static int setColor(PyFilter *self, PyObject *value, void *closure)
-{
- // check validity of parameter
- if (value == NULL ||
- !(PyTuple_Check(value) || PyList_Check(value)) ||
- PySequence_Fast_GET_SIZE(value) != 3 ||
- !PyLong_Check(PySequence_Fast_GET_ITEM(value, 0)) ||
- !PyLong_Check(PySequence_Fast_GET_ITEM(value, 1)) ||
- !PyLong_Check(PySequence_Fast_GET_ITEM(value, 2)))
- {
- PyErr_SetString(PyExc_TypeError, "The value must be a sequence of 3 ints");
- return -1;
- }
- // set color
- getFilter(self)->setColor(
- (unsigned char)(PyLong_AsLong(PySequence_Fast_GET_ITEM(value, 0))),
- (unsigned char)(PyLong_AsLong(PySequence_Fast_GET_ITEM(value, 1))),
- (unsigned char)(PyLong_AsLong(PySequence_Fast_GET_ITEM(value, 2))));
- // success
- return 0;
-}
-
-// get limits
-static PyObject *getLimits (PyFilter *self, void *closure)
-{
- return Py_BuildValue("[II]", getFilter(self)->getLimits()[0],
- getFilter(self)->getLimits()[1]);
-}
-
-// set limit
-static int setLimits(PyFilter *self, PyObject *value, void *closure)
-{
- // check validity of parameter
- if (value == NULL ||
- !(PyTuple_Check(value) || PyList_Check(value)) ||
- PySequence_Fast_GET_SIZE(value) != 2 ||
- !PyLong_Check(PySequence_Fast_GET_ITEM(value, 0)) ||
- !PyLong_Check(PySequence_Fast_GET_ITEM(value, 1)))
- {
- PyErr_SetString(PyExc_TypeError, "The value must be a sequence of 2 ints");
- return -1;
- }
- // set limits
- getFilter(self)->setLimits(
- (unsigned short)(PyLong_AsLong(PySequence_Fast_GET_ITEM(value, 0))),
- (unsigned short)(PyLong_AsLong(PySequence_Fast_GET_ITEM(value, 1))));
- // success
- return 0;
-}
-
-
-// attributes structure
-static PyGetSetDef filterBSGetSets[] =
-{
- {(char*)"color", (getter)getColor, (setter)setColor, (char*)"blue screen color", NULL},
- {(char*)"limits", (getter)getLimits, (setter)setLimits, (char*)"blue screen color limits", NULL},
- // attributes from FilterBase class
- {(char*)"previous", (getter)Filter_getPrevious, (setter)Filter_setPrevious, (char*)"previous pixel filter", NULL},
- {NULL}
-};
-
-// define python type
-PyTypeObject FilterBlueScreenType =
-{
- PyVarObject_HEAD_INIT(NULL, 0)
- "VideoTexture.FilterBlueScreen", /*tp_name*/
- sizeof(PyFilter), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- (destructor)Filter_dealloc,/*tp_dealloc*/
- 0, /*tp_print*/
- 0, /*tp_getattr*/
- 0, /*tp_setattr*/
- 0, /*tp_compare*/
- 0, /*tp_repr*/
- 0, /*tp_as_number*/
- 0, /*tp_as_sequence*/
- 0, /*tp_as_mapping*/
- 0, /*tp_hash */
- 0, /*tp_call*/
- 0, /*tp_str*/
- 0, /*tp_getattro*/
- 0, /*tp_setattro*/
- 0, /*tp_as_buffer*/
- Py_TPFLAGS_DEFAULT, /*tp_flags*/
- "Filter for Blue Screen objects", /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- NULL, /* tp_methods */
- 0, /* tp_members */
- filterBSGetSets, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- (initproc)Filter_init<FilterBlueScreen>, /* tp_init */
- 0, /* tp_alloc */
- Filter_allocNew, /* tp_new */
-};
-
diff --git a/source/gameengine/VideoTexture/FilterBlueScreen.h b/source/gameengine/VideoTexture/FilterBlueScreen.h
deleted file mode 100644
index cf74a6705b7..00000000000
--- a/source/gameengine/VideoTexture/FilterBlueScreen.h
+++ /dev/null
@@ -1,105 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * Copyright (c) 2007 The Zdeno Ash Miklas
- *
- * This source file is part of blendTex library
- *
- * Contributor(s):
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file FilterBlueScreen.h
- * \ingroup bgevideotex
- */
-
-#ifndef __FILTERBLUESCREEN_H__
-#define __FILTERBLUESCREEN_H__
-
-#include "Common.h"
-
-#include "FilterBase.h"
-
-
-/// pixel filter for blue screen
-class FilterBlueScreen : public FilterBase
-{
-public:
- /// constructor
- FilterBlueScreen (void);
- /// destructor
- virtual ~FilterBlueScreen (void) {}
-
- /// get color
- unsigned char * getColor (void) { return m_color; }
- /// set color
- void setColor (unsigned char red, unsigned char green, unsigned char blue);
-
- /// get limits for color variation
- unsigned short * getLimits (void) { return m_limits; }
- /// set limits for color variation
- void setLimits (unsigned short minLimit, unsigned short maxLimit);
-
-protected:
- /// blue screen color (red component first)
- unsigned char m_color[3];
- /// limits for color variation - first defines, where ends fully transparent
- /// color, second defines, where begins fully opaque color
- unsigned short m_limits[2];
- /// squared limits for color variation
- unsigned int m_squareLimits[2];
- /// distance between squared limits
- unsigned int m_limitDist;
-
- /// filter pixel template, source int buffer
- template <class SRC> unsigned int tFilter (SRC src, short x, short y,
- short * size, unsigned int pixSize, unsigned int val)
- {
- // calculate differences
- int difRed = int(VT_R(val)) - int(m_color[0]);
- int difGreen = int(VT_G(val)) - int(m_color[1]);
- int difBlue = int(VT_B(val)) - int(m_color[2]);
- // calc distance from "blue screen" color
- unsigned int dist = (unsigned int)(difRed * difRed + difGreen * difGreen
- + difBlue * difBlue);
- // condition for fully transparent color
- if (m_squareLimits[0] >= dist)
- // return color with zero alpha
- VT_A(val) = 0;
- // condition for fully opaque color
- else if (m_squareLimits[1] <= dist)
- // return normal color
- VT_A(val) = 0xFF;
- // otherwise calc alpha
- else
- VT_A(val) = (((dist - m_squareLimits[0]) << 8) / m_limitDist);
- return val;
- }
-
- /// virtual filtering function for byte source
- virtual unsigned int filter (unsigned char *src, short x, short y,
- short * size, unsigned int pixSize, unsigned int val = 0)
- { return tFilter(src, x, y, size, pixSize, val); }
- /// virtual filtering function for unsigned int source
- virtual unsigned int filter (unsigned int *src, short x, short y,
- short * size, unsigned int pixSize, unsigned int val = 0)
- { return tFilter(src, x, y, size, pixSize, val); }
-};
-
-
-#endif
diff --git a/source/gameengine/VideoTexture/FilterColor.cpp b/source/gameengine/VideoTexture/FilterColor.cpp
deleted file mode 100644
index 15a7e9e4cd1..00000000000
--- a/source/gameengine/VideoTexture/FilterColor.cpp
+++ /dev/null
@@ -1,354 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * Copyright (c) 2007 The Zdeno Ash Miklas
- *
- * This source file is part of VideoTexture library
- *
- * Contributor(s):
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/VideoTexture/FilterColor.cpp
- * \ingroup bgevideotex
- */
-
-#include "EXP_PyObjectPlus.h"
-#include <structmember.h>
-
-#include "FilterColor.h"
-
-#include "FilterBase.h"
-#include "PyTypeList.h"
-
-// implementation FilterGray
-
-// attributes structure
-static PyGetSetDef filterGrayGetSets[] =
-{ // attributes from FilterBase class
- {(char*)"previous", (getter)Filter_getPrevious, (setter)Filter_setPrevious, (char*)"previous pixel filter", NULL},
- {NULL}
-};
-
-// define python type
-PyTypeObject FilterGrayType =
-{
- PyVarObject_HEAD_INIT(NULL, 0)
- "VideoTexture.FilterGray", /*tp_name*/
- sizeof(PyFilter), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- (destructor)Filter_dealloc,/*tp_dealloc*/
- 0, /*tp_print*/
- 0, /*tp_getattr*/
- 0, /*tp_setattr*/
- 0, /*tp_compare*/
- 0, /*tp_repr*/
- 0, /*tp_as_number*/
- 0, /*tp_as_sequence*/
- 0, /*tp_as_mapping*/
- 0, /*tp_hash */
- 0, /*tp_call*/
- 0, /*tp_str*/
- 0, /*tp_getattro*/
- 0, /*tp_setattro*/
- 0, /*tp_as_buffer*/
- Py_TPFLAGS_DEFAULT, /*tp_flags*/
- "Filter for grayscale effect", /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- NULL, /* tp_methods */
- 0, /* tp_members */
- filterGrayGetSets, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- (initproc)Filter_init<FilterGray>, /* tp_init */
- 0, /* tp_alloc */
- Filter_allocNew, /* tp_new */
-};
-
-
-// implementation FilterColor
-
-// constructor
-FilterColor::FilterColor (void)
-{
- // reset color matrix to identity
- for (int r = 0; r < 4; ++r)
- for (int c = 0; c < 5; ++c)
- m_matrix[r][c] = (r == c) ? 256 : 0;
-}
-
-// set color matrix
-void FilterColor::setMatrix (ColorMatrix & mat)
-{
- // copy matrix
- for (int r = 0; r < 4; ++r)
- for (int c = 0; c < 5; ++c)
- m_matrix[r][c] = mat[r][c];
-}
-
-
-
-// cast Filter pointer to FilterColor
-inline FilterColor * getFilterColor (PyFilter *self)
-{ return static_cast<FilterColor*>(self->m_filter); }
-
-
-// python methods and get/sets
-
-// get color matrix
-static PyObject *getMatrix (PyFilter *self, void *closure)
-{
- ColorMatrix & mat = getFilterColor(self)->getMatrix();
- return Py_BuildValue("((hhhhh)(hhhhh)(hhhhh)(hhhhh))",
- mat[0][0], mat[0][1], mat[0][2], mat[0][3], mat[0][4],
- mat[1][0], mat[1][1], mat[1][2], mat[1][3], mat[1][4],
- mat[2][0], mat[2][1], mat[2][2], mat[2][3], mat[2][4],
- mat[3][0], mat[3][1], mat[3][2], mat[3][3], mat[3][4]);
-}
-
-// set color matrix
-static int setMatrix(PyFilter *self, PyObject *value, void *closure)
-{
- // matrix to store items
- ColorMatrix mat;
- // check validity of parameter
- bool valid = value != NULL && PySequence_Check(value)
- && PySequence_Size(value) == 4;
- // check rows
- for (int r = 0; valid && r < 4; ++r)
- {
- // get row object
- PyObject *row = PySequence_Fast_GET_ITEM(value, r);
- // check sequence
- valid = PySequence_Check(row) && PySequence_Size(row) == 5;
- // check items
- for (int c = 0; valid && c < 5; ++c)
- {
- // item must be int
- valid = PyLong_Check(PySequence_Fast_GET_ITEM(row, c));
- // if it is valid, save it in matrix
- if (valid)
- mat[r][c] = short(PyLong_AsLong(PySequence_Fast_GET_ITEM(row, c)));
- }
- }
- // if parameter is not valid, report error
- if (!valid)
- {
- PyErr_SetString(PyExc_TypeError, "The value must be a matrix [4][5] of ints");
- return -1;
- }
- // set color matrix
- getFilterColor(self)->setMatrix(mat);
- // success
- return 0;
-}
-
-
-// attributes structure
-static PyGetSetDef filterColorGetSets[] =
-{
- {(char*)"matrix", (getter)getMatrix, (setter)setMatrix, (char*)"matrix [4][5] for color calculation", NULL},
- // attributes from FilterBase class
- {(char*)"previous", (getter)Filter_getPrevious, (setter)Filter_setPrevious, (char*)"previous pixel filter", NULL},
- {NULL}
-};
-
-// define python type
-PyTypeObject FilterColorType =
-{
- PyVarObject_HEAD_INIT(NULL, 0)
- "VideoTexture.FilterColor", /*tp_name*/
- sizeof(PyFilter), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- (destructor)Filter_dealloc,/*tp_dealloc*/
- 0, /*tp_print*/
- 0, /*tp_getattr*/
- 0, /*tp_setattr*/
- 0, /*tp_compare*/
- 0, /*tp_repr*/
- 0, /*tp_as_number*/
- 0, /*tp_as_sequence*/
- 0, /*tp_as_mapping*/
- 0, /*tp_hash */
- 0, /*tp_call*/
- 0, /*tp_str*/
- 0, /*tp_getattro*/
- 0, /*tp_setattro*/
- 0, /*tp_as_buffer*/
- Py_TPFLAGS_DEFAULT, /*tp_flags*/
- "Filter for color calculations", /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- NULL, /* tp_methods */
- 0, /* tp_members */
- filterColorGetSets, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- (initproc)Filter_init<FilterColor>, /* tp_init */
- 0, /* tp_alloc */
- Filter_allocNew, /* tp_new */
-};
-
-// implementation FilterLevel
-
-// constructor
-FilterLevel::FilterLevel (void)
-{
- // reset color levels
- for (int r = 0; r < 4; ++r)
- {
- levels[r][0] = 0;
- levels[r][1] = 0xFF;
- levels[r][2] = 0xFF;
- }
-}
-
-// set color levels
-void FilterLevel::setLevels (ColorLevel & lev)
-{
- // copy levels
- for (int r = 0; r < 4; ++r)
- {
- for (int c = 0; c < 2; ++c)
- levels[r][c] = lev[r][c];
- levels[r][2] = lev[r][0] < lev[r][1] ? lev[r][1] - lev[r][0] : 1;
- }
-}
-
-
-// cast Filter pointer to FilterLevel
-inline FilterLevel * getFilterLevel (PyFilter *self)
-{ return static_cast<FilterLevel*>(self->m_filter); }
-
-
-// python methods and get/sets
-
-// get color levels
-static PyObject *getLevels (PyFilter *self, void *closure)
-{
- ColorLevel & lev = getFilterLevel(self)->getLevels();
- return Py_BuildValue("((HH)(HH)(HH)(HH))",
- lev[0][0], lev[0][1], lev[1][0], lev[1][1],
- lev[2][0], lev[2][1], lev[3][0], lev[3][1]);
-}
-
-// set color levels
-static int setLevels(PyFilter *self, PyObject *value, void *closure)
-{
- // matrix to store items
- ColorLevel lev;
- // check validity of parameter
- bool valid = value != NULL && PySequence_Check(value)
- && PySequence_Size(value) == 4;
- // check rows
- for (int r = 0; valid && r < 4; ++r)
- {
- // get row object
- PyObject *row = PySequence_Fast_GET_ITEM(value, r);
- // check sequence
- valid = PySequence_Check(row) && PySequence_Size(row) == 2;
- // check items
- for (int c = 0; valid && c < 2; ++c)
- {
- // item must be int
- valid = PyLong_Check(PySequence_Fast_GET_ITEM(row, c));
- // if it is valid, save it in matrix
- if (valid)
- lev[r][c] = (unsigned short)(PyLong_AsLong(PySequence_Fast_GET_ITEM(row, c)));
- }
- }
- // if parameter is not valid, report error
- if (!valid)
- {
- PyErr_SetString(PyExc_TypeError, "The value must be a matrix [4][2] of ints");
- return -1;
- }
- // set color matrix
- getFilterLevel(self)->setLevels(lev);
- // success
- return 0;
-}
-
-
-// attributes structure
-static PyGetSetDef filterLevelGetSets[] =
-{
- {(char*)"levels", (getter)getLevels, (setter)setLevels, (char*)"levels matrix [4] (min, max)", NULL},
- // attributes from FilterBase class
- {(char*)"previous", (getter)Filter_getPrevious, (setter)Filter_setPrevious, (char*)"previous pixel filter", NULL},
- {NULL}
-};
-
-// define python type
-PyTypeObject FilterLevelType =
-{
- PyVarObject_HEAD_INIT(NULL, 0)
- "VideoTexture.FilterLevel", /*tp_name*/
- sizeof(PyFilter), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- (destructor)Filter_dealloc,/*tp_dealloc*/
- 0, /*tp_print*/
- 0, /*tp_getattr*/
- 0, /*tp_setattr*/
- 0, /*tp_compare*/
- 0, /*tp_repr*/
- 0, /*tp_as_number*/
- 0, /*tp_as_sequence*/
- 0, /*tp_as_mapping*/
- 0, /*tp_hash */
- 0, /*tp_call*/
- 0, /*tp_str*/
- 0, /*tp_getattro*/
- 0, /*tp_setattro*/
- 0, /*tp_as_buffer*/
- Py_TPFLAGS_DEFAULT, /*tp_flags*/
- "Filter for levels calculations", /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- NULL, /* tp_methods */
- 0, /* tp_members */
- filterLevelGetSets, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- (initproc)Filter_init<FilterLevel>, /* tp_init */
- 0, /* tp_alloc */
- Filter_allocNew, /* tp_new */
-};
-
diff --git a/source/gameengine/VideoTexture/FilterColor.h b/source/gameengine/VideoTexture/FilterColor.h
deleted file mode 100644
index d042863d7e8..00000000000
--- a/source/gameengine/VideoTexture/FilterColor.h
+++ /dev/null
@@ -1,176 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * Copyright (c) 2007 The Zdeno Ash Miklas
- *
- * This source file is part of blendTex library
- *
- * Contributor(s):
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file FilterColor.h
- * \ingroup bgevideotex
- */
-
-#ifndef __FILTERCOLOR_H__
-#define __FILTERCOLOR_H__
-
-#include "Common.h"
-
-#include "FilterBase.h"
-
-
-/// pixel filter for grayscale
-class FilterGray : public FilterBase
-{
-public:
- /// constructor
- FilterGray (void) {}
- /// destructor
- virtual ~FilterGray (void) {}
-
-protected:
- /// filter pixel template, source int buffer
- template <class SRC> unsigned int tFilter (SRC src, short x, short y,
- short * size, unsigned int pixSize, unsigned int val)
- {
- // calculate gray value
- unsigned int gray = (28 * (VT_B(val)) + 151 * (VT_G(val))
- + 77 * (VT_R(val))) >> 8;
- // return grayscale value
- VT_R(val) = gray;
- VT_G(val) = gray;
- VT_B(val) = gray;
- return val;
- }
-
- /// virtual filtering function for byte source
- virtual unsigned int filter (unsigned char * src, short x, short y,
- short * size, unsigned int pixSize, unsigned int val = 0)
- { return tFilter(src, x, y, size, pixSize, val); }
- /// virtual filtering function for unsigned int source
- virtual unsigned int filter (unsigned int * src, short x, short y,
- short * size, unsigned int pixSize, unsigned int val = 0)
- { return tFilter(src, x, y, size, pixSize, val); }
-};
-
-
-/// type for color matrix
-typedef short ColorMatrix[4][5];
-
-/// pixel filter for color calculation
-class FilterColor : public FilterBase
-{
-public:
- /// constructor
- FilterColor (void);
- /// destructor
- virtual ~FilterColor (void) {}
-
- /// get color matrix
- ColorMatrix & getMatrix (void) { return m_matrix; }
- /// set color matrix
- void setMatrix (ColorMatrix & mat);
-
-protected:
- /// color calculation matrix
- ColorMatrix m_matrix;
-
- /// calculate one color component
- unsigned char calcColor (unsigned int val, short idx)
- {
- return (((m_matrix[idx][0] * (VT_R(val)) + m_matrix[idx][1] * (VT_G(val)) +
- m_matrix[idx][2] * (VT_B(val)) + m_matrix[idx][3] * (VT_A(val)) +
- m_matrix[idx][4]) >> 8) & 0xFF);
- }
-
- /// filter pixel template, source int buffer
- template <class SRC> unsigned int tFilter (SRC src, short x, short y,
- short * size, unsigned int pixSize, unsigned int val)
- {
- // return calculated color
- int color;
- VT_RGBA(color, calcColor(val, 0), calcColor(val, 1), calcColor(val, 2), calcColor(val, 3));
- return color;
- }
-
- /// virtual filtering function for byte source
- virtual unsigned int filter (unsigned char * src, short x, short y,
- short * size, unsigned int pixSize, unsigned int val = 0)
- { return tFilter(src, x, y, size, pixSize, val); }
- /// virtual filtering function for unsigned int source
- virtual unsigned int filter (unsigned int * src, short x, short y,
- short * size, unsigned int pixSize, unsigned int val = 0)
- { return tFilter(src, x, y, size, pixSize, val); }
-};
-
-
-/// type for color levels
-typedef unsigned short ColorLevel[4][3];
-
-/// pixel filter for color calculation
-class FilterLevel : public FilterBase
-{
-public:
- /// constructor
- FilterLevel (void);
- /// destructor
- virtual ~FilterLevel (void) {}
-
- /// get color matrix
- ColorLevel & getLevels (void) { return levels; }
- /// set color matrix
- void setLevels (ColorLevel & lev);
-
-protected:
- /// color calculation matrix
- ColorLevel levels;
-
- /// calculate one color component
- unsigned int calcColor (unsigned int val, short idx)
- {
- unsigned int col = VT_C(val,idx);
- if (col <= levels[idx][0]) col = 0;
- else if (col >= levels[idx][1]) col = 0xFF;
- else col = (((col - levels[idx][0]) << 8) / levels[idx][2]) & 0xFF;
- return col;
- }
-
- /// filter pixel template, source int buffer
- template <class SRC> unsigned int tFilter (SRC src, short x, short y,
- short * size, unsigned int pixSize, unsigned int val)
- {
- // return calculated color
- int color;
- VT_RGBA(color, calcColor(val, 0), calcColor(val, 1), calcColor(val, 2), calcColor(val, 3));
- return color;
- }
-
- /// virtual filtering function for byte source
- virtual unsigned int filter (unsigned char * src, short x, short y,
- short * size, unsigned int pixSize, unsigned int val = 0)
- { return tFilter(src, x, y, size, pixSize, val); }
- /// virtual filtering function for unsigned int source
- virtual unsigned int filter (unsigned int * src, short x, short y,
- short * size, unsigned int pixSize, unsigned int val = 0)
- { return tFilter(src, x, y, size, pixSize, val); }
-};
-
-
-#endif
diff --git a/source/gameengine/VideoTexture/FilterNormal.cpp b/source/gameengine/VideoTexture/FilterNormal.cpp
deleted file mode 100644
index 3a5333710fd..00000000000
--- a/source/gameengine/VideoTexture/FilterNormal.cpp
+++ /dev/null
@@ -1,173 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * Copyright (c) 2007 The Zdeno Ash Miklas
- *
- * This source file is part of VideoTexture library
- *
- * Contributor(s):
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/VideoTexture/FilterNormal.cpp
- * \ingroup bgevideotex
- */
-
-#include "EXP_PyObjectPlus.h"
-#include <structmember.h>
-
-#include "FilterNormal.h"
-
-#include "FilterBase.h"
-#include "PyTypeList.h"
-
-// implementation FilterNormal
-
-// constructor
-FilterNormal::FilterNormal (void) : m_colIdx(0)
-{
- // set default depth
- setDepth(4);
-}
-
-// set color shift
-void FilterNormal::setColor (unsigned short colIdx)
-{
- // check validity of index
- if (colIdx < 3)
- // set color shift
- m_colIdx = colIdx;
-}
-
-// set depth
-void FilterNormal::setDepth (float depth)
-{
- m_depth = depth;
- m_depthScale = depth / depthScaleKoef;
-}
-
-
-// cast Filter pointer to FilterNormal
-inline FilterNormal * getFilter (PyFilter *self)
-{ return static_cast<FilterNormal*>(self->m_filter); }
-
-
-// python methods and get/sets
-
-// get index of color used to calculate normal
-static PyObject *getColor (PyFilter *self, void *closure)
-{
- return Py_BuildValue("H", getFilter(self)->getColor());
-}
-
-// set index of color used to calculate normal
-static int setColor(PyFilter *self, PyObject *value, void *closure)
-{
- // check validity of parameter
- if (value == NULL || !PyLong_Check(value))
- {
- PyErr_SetString(PyExc_TypeError, "filt.colorIdx = int: VideoTexture.FilterNormal, expected the value must be a int");
- return -1;
- }
- // set color index
- getFilter(self)->setColor((unsigned short)(PyLong_AsLong(value)));
- // success
- return 0;
-}
-
-
-// get depth
-static PyObject *getDepth (PyFilter *self, void *closure)
-{
- return Py_BuildValue("f", getFilter(self)->getDepth());
-}
-
-// set depth
-static int setDepth(PyFilter *self, PyObject *value, void *closure)
-{
- // check validity of parameter
- if (value)
- {
- float depth= (float)PyFloat_AsDouble(value);
- if ((depth==-1 && PyErr_Occurred()) == 0) /* no error converting to a float? */
- {
- // set depth
- getFilter(self)->setDepth(depth);
- // success
- return 0;
- }
- }
-
- PyErr_SetString(PyExc_TypeError, "filt.depth = float: VideoTexture.FilterNormal, expected the value must be a float");
- return -1;
-}
-
-
-// attributes structure
-static PyGetSetDef filterNormalGetSets[] =
-{
- {(char*)"colorIdx", (getter)getColor, (setter)setColor, (char*)"index of color used to calculate normal (0 - red, 1 - green, 2 - blue)", NULL},
- {(char*)"depth", (getter)getDepth, (setter)setDepth, (char*)"depth of relief", NULL},
- // attributes from FilterBase class
- {(char*)"previous", (getter)Filter_getPrevious, (setter)Filter_setPrevious, (char*)"previous pixel filter", NULL},
- {NULL}
-};
-
-// define python type
-PyTypeObject FilterNormalType =
-{
- PyVarObject_HEAD_INIT(NULL, 0)
- "VideoTexture.FilterNormal", /*tp_name*/
- sizeof(PyFilter), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- (destructor)Filter_dealloc,/*tp_dealloc*/
- 0, /*tp_print*/
- 0, /*tp_getattr*/
- 0, /*tp_setattr*/
- 0, /*tp_compare*/
- 0, /*tp_repr*/
- 0, /*tp_as_number*/
- 0, /*tp_as_sequence*/
- 0, /*tp_as_mapping*/
- 0, /*tp_hash */
- 0, /*tp_call*/
- 0, /*tp_str*/
- 0, /*tp_getattro*/
- 0, /*tp_setattro*/
- 0, /*tp_as_buffer*/
- Py_TPFLAGS_DEFAULT, /*tp_flags*/
- "Filter for Blue Screen objects", /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- NULL, /* tp_methods */
- 0, /* tp_members */
- filterNormalGetSets, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- (initproc)Filter_init<FilterNormal>, /* tp_init */
- 0, /* tp_alloc */
- Filter_allocNew, /* tp_new */
-};
-
diff --git a/source/gameengine/VideoTexture/FilterNormal.h b/source/gameengine/VideoTexture/FilterNormal.h
deleted file mode 100644
index 951ecb84d9d..00000000000
--- a/source/gameengine/VideoTexture/FilterNormal.h
+++ /dev/null
@@ -1,115 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * Copyright (c) 2007 The Zdeno Ash Miklas
- *
- * This source file is part of blendTex library
- *
- * Contributor(s):
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file FilterNormal.h
- * \ingroup bgevideotex
- */
-
-#ifndef __FILTERNORMAL_H__
-#define __FILTERNORMAL_H__
-
-#include "Common.h"
-
-#include "FilterBase.h"
-
-
-// scale constants for normals
-const float depthScaleKoef = 255.0;
-const float normScaleKoef = float(depthScaleKoef / 2.0);
-
-
-/// pixel filter for normal mapping
-class FilterNormal : public FilterBase
-{
-public:
- /// constructor
- FilterNormal (void);
- /// destructor
- virtual ~FilterNormal (void) {}
-
- /// get index of color used to calculate normals
- unsigned short getColor (void) { return m_colIdx; }
- /// set index of color used to calculate normals
- void setColor (unsigned short colIdx);
-
- /// get depth
- float getDepth (void) { return m_depth; }
- /// set depth
- void setDepth (float depth);
-
-protected:
- /// depth of normal relief
- float m_depth;
- /// scale to calculate normals
- float m_depthScale;
-
- /// color index, 0=red, 1=green, 2=blue, 3=alpha
- unsigned short m_colIdx;
-
- /// filter pixel, source int buffer
- template <class SRC> unsigned int tFilter (SRC *src, short x, short y,
- short * size, unsigned int pixSize, unsigned int val = 0)
- {
- // get value of required color
- int actPix = int(VT_C(val,m_colIdx));
- int upPix = actPix;
- int leftPix = actPix;
- // get upper and left pixel from actual pixel
- if (y > 0)
- {
- val = convertPrevious(src - pixSize * size[0], x, y - 1, size, pixSize);
- upPix = VT_C(val,m_colIdx);
- }
- if (x > 0)
- {
- val = convertPrevious(src - pixSize, x - 1, y, size, pixSize);
- leftPix = VT_C(val,m_colIdx);
- }
- // height differences (from blue color)
- float dx = (actPix - leftPix) * m_depthScale;
- float dy = (actPix - upPix) * m_depthScale;
- // normalize vector
- float dz = float(normScaleKoef / sqrt(dx * dx + dy * dy + 1.0));
- dx = dx * dz + normScaleKoef;
- dy = dy * dz + normScaleKoef;
- dz += normScaleKoef;
- // return normal vector converted to color
- VT_RGBA(val, dx, dy, dz, 0xFF);
- return val;
- }
-
- /// filter pixel, source byte buffer
- virtual unsigned int filter (unsigned char * src, short x, short y,
- short * size, unsigned int pixSize, unsigned int val = 0)
- { return tFilter(src, x, y, size, pixSize, val); }
- /// filter pixel, source int buffer
- virtual unsigned int filter (unsigned int * src, short x, short y,
- short * size, unsigned int pixSize, unsigned int val = 0)
- { return tFilter(src, x, y, size, pixSize, val); }
-};
-
-
-#endif
diff --git a/source/gameengine/VideoTexture/FilterSource.cpp b/source/gameengine/VideoTexture/FilterSource.cpp
deleted file mode 100644
index c8faa1f9f07..00000000000
--- a/source/gameengine/VideoTexture/FilterSource.cpp
+++ /dev/null
@@ -1,176 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * Copyright (c) 2007 The Zdeno Ash Miklas
- *
- * This source file is part of VideoTexture library
- *
- * Contributor(s):
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/VideoTexture/FilterSource.cpp
- * \ingroup bgevideotex
- */
-
-// implementation
-
-#include "EXP_PyObjectPlus.h"
-#include <structmember.h>
-
-#include "FilterSource.h"
-
-#include "FilterBase.h"
-#include "PyTypeList.h"
-
-
-// FilterRGB24
-
-// define python type
-PyTypeObject FilterRGB24Type =
-{
- PyVarObject_HEAD_INIT(NULL, 0)
- "VideoTexture.FilterRGB24", /*tp_name*/
- sizeof(PyFilter), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- (destructor)Filter_dealloc,/*tp_dealloc*/
- 0, /*tp_print*/
- 0, /*tp_getattr*/
- 0, /*tp_setattr*/
- 0, /*tp_compare*/
- 0, /*tp_repr*/
- 0, /*tp_as_number*/
- 0, /*tp_as_sequence*/
- 0, /*tp_as_mapping*/
- 0, /*tp_hash */
- 0, /*tp_call*/
- 0, /*tp_str*/
- 0, /*tp_getattro*/
- 0, /*tp_setattro*/
- 0, /*tp_as_buffer*/
- Py_TPFLAGS_DEFAULT, /*tp_flags*/
- "Source filter RGB24 objects", /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- NULL, /* tp_methods */
- 0, /* tp_members */
- NULL, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- (initproc)Filter_init<FilterRGB24>, /* tp_init */
- 0, /* tp_alloc */
- Filter_allocNew, /* tp_new */
-};
-
-// FilterRGBA32
-
-// define python type
-PyTypeObject FilterRGBA32Type =
-{
- PyVarObject_HEAD_INIT(NULL, 0)
- "VideoTexture.FilterRGBA32", /*tp_name*/
- sizeof(PyFilter), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- (destructor)Filter_dealloc,/*tp_dealloc*/
- 0, /*tp_print*/
- 0, /*tp_getattr*/
- 0, /*tp_setattr*/
- 0, /*tp_compare*/
- 0, /*tp_repr*/
- 0, /*tp_as_number*/
- 0, /*tp_as_sequence*/
- 0, /*tp_as_mapping*/
- 0, /*tp_hash */
- 0, /*tp_call*/
- 0, /*tp_str*/
- 0, /*tp_getattro*/
- 0, /*tp_setattro*/
- 0, /*tp_as_buffer*/
- Py_TPFLAGS_DEFAULT, /*tp_flags*/
- "Source filter RGBA32 objects", /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- NULL, /* tp_methods */
- 0, /* tp_members */
- NULL, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- (initproc)Filter_init<FilterRGBA32>, /* tp_init */
- 0, /* tp_alloc */
- Filter_allocNew, /* tp_new */
-};
-
-// FilterBGR24
-
-// define python type
-PyTypeObject FilterBGR24Type =
-{
- PyVarObject_HEAD_INIT(NULL, 0)
- "VideoTexture.FilterBGR24", /*tp_name*/
- sizeof(PyFilter), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- (destructor)Filter_dealloc,/*tp_dealloc*/
- 0, /*tp_print*/
- 0, /*tp_getattr*/
- 0, /*tp_setattr*/
- 0, /*tp_compare*/
- 0, /*tp_repr*/
- 0, /*tp_as_number*/
- 0, /*tp_as_sequence*/
- 0, /*tp_as_mapping*/
- 0, /*tp_hash */
- 0, /*tp_call*/
- 0, /*tp_str*/
- 0, /*tp_getattro*/
- 0, /*tp_setattro*/
- 0, /*tp_as_buffer*/
- Py_TPFLAGS_DEFAULT, /*tp_flags*/
- "Source filter BGR24 objects", /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- NULL, /* tp_methods */
- 0, /* tp_members */
- NULL, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- (initproc)Filter_init<FilterBGR24>, /* tp_init */
- 0, /* tp_alloc */
- Filter_allocNew, /* tp_new */
-};
-
diff --git a/source/gameengine/VideoTexture/FilterSource.h b/source/gameengine/VideoTexture/FilterSource.h
deleted file mode 100644
index 820576dfff9..00000000000
--- a/source/gameengine/VideoTexture/FilterSource.h
+++ /dev/null
@@ -1,352 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * Copyright (c) 2007 The Zdeno Ash Miklas
- *
- * This source file is part of blendTex library
- *
- * Contributor(s):
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file FilterSource.h
- * \ingroup bgevideotex
- */
-
-#ifndef __FILTERSOURCE_H__
-#define __FILTERSOURCE_H__
-
-#include "Common.h"
-
-#include "FilterBase.h"
-
-/// class for RGB24 conversion
-class FilterRGB24 : public FilterBase
-{
-public:
- /// constructor
- FilterRGB24 (void) {}
- /// destructor
- virtual ~FilterRGB24 (void) {}
-
- /// get source pixel size
- virtual unsigned int getPixelSize (void) { return 3; }
-
-protected:
- /// filter pixel, source byte buffer
- virtual unsigned int filter (unsigned char *src, short x, short y,
- short * size, unsigned int pixSize, unsigned int val)
- { VT_RGBA(val,src[0],src[1],src[2],0xFF); return val; }
-};
-
-/// class for RGBA32 conversion
-class FilterRGBA32 : public FilterBase
-{
-public:
- /// constructor
- FilterRGBA32 (void) {}
- /// destructor
- virtual ~FilterRGBA32 (void) {}
-
- /// get source pixel size
- virtual unsigned int getPixelSize (void) { return 4; }
-
-protected:
- /// filter pixel, source byte buffer
- virtual unsigned int filter (unsigned char *src, short x, short y,
- short * size, unsigned int pixSize, unsigned int val)
- {
- if ((intptr_t(src)&0x3) == 0)
- return *(unsigned int*)src;
- else
- {
- VT_RGBA(val,src[0],src[1],src[2],src[3]);
- return val;
- }
- }
-};
-
-/// class for BGRA32 conversion
-class FilterBGRA32 : public FilterBase
-{
-public:
- /// constructor
- FilterBGRA32 (void) {}
- /// destructor
- virtual ~FilterBGRA32 (void) {}
-
- /// get source pixel size
- virtual unsigned int getPixelSize (void) { return 4; }
-
-protected:
- /// filter pixel, source byte buffer
- virtual unsigned int filter(
- unsigned char *src, short x, short y,
- short * size, unsigned int pixSize, unsigned int val)
- {
- VT_RGBA(val,src[2],src[1],src[0],src[3]);
- return val;
- }
-};
-
-
-/// class for BGR24 conversion
-class FilterBGR24 : public FilterBase
-{
-public:
- /// constructor
- FilterBGR24 (void) {}
- /// destructor
- virtual ~FilterBGR24 (void) {}
-
- /// get source pixel size
- virtual unsigned int getPixelSize (void) { return 3; }
-
-protected:
- /// filter pixel, source byte buffer
- virtual unsigned int filter (unsigned char *src, short x, short y,
- short * size, unsigned int pixSize, unsigned int val)
- { VT_RGBA(val,src[2],src[1],src[0],0xFF); return val; }
-};
-
-/// class for Z_buffer conversion
-class FilterZZZA : public FilterBase
-{
-public:
- /// constructor
- FilterZZZA (void) {}
- /// destructor
- virtual ~FilterZZZA (void) {}
-
- /// get source pixel size
- virtual unsigned int getPixelSize (void) { return 1; }
-
-protected:
- /// filter pixel, source float buffer
- virtual unsigned int filter (float *src, short x, short y,
- short * size, unsigned int pixSize, unsigned int val)
- {
- // calculate gray value
- // convert float to unsigned char
- unsigned int depth = int(src[0] * 255);
- // return depth scale value
- VT_R(val) = depth;
- VT_G(val) = depth;
- VT_B(val) = depth;
- VT_A(val) = 0xFF;
-
- return val;
- }
-};
-
-
-/// class for Z_buffer conversion
-class FilterDEPTH : public FilterBase
-{
-public:
- /// constructor
- FilterDEPTH (void) {}
- /// destructor
- virtual ~FilterDEPTH (void) {}
-
- /// get source pixel size
- virtual unsigned int getPixelSize (void) { return 1; }
-
-protected:
- /// filter pixel, source float buffer
- virtual unsigned int filter (float *src, short x, short y,
- short *size, unsigned int pixSize, unsigned int val)
- {
- /* Copy the float value straight away
- * The user can retrieve the original float value by using
- * 'F' mode in BGL buffer */
- memcpy(&val, src, sizeof (unsigned int));
- return val;
- }
-};
-
-
-
-
-/// class for YV12 conversion
-class FilterYV12 : public FilterBase
-{
-public:
- /// constructor
- FilterYV12 (void): m_buffV(NULL), m_buffU(NULL), m_pitchUV(0) {}
- /// destructor
- virtual ~FilterYV12 (void) {}
-
- /// get source pixel size
- virtual unsigned int getPixelSize (void) { return 1; }
-
- /// set pointers to color buffers
- void setBuffs (unsigned char * buff, short * size)
- {
- unsigned int buffSize = size[0] * size[1];
- m_buffV = buff + buffSize;
- m_buffU = m_buffV + (buffSize >> 2);
- m_pitchUV = size[0] >> 1;
- }
-
-protected:
- /// begin of V buffer
- unsigned char * m_buffV;
- /// begin of U buffer
- unsigned char * m_buffU;
- /// pitch for V & U buffers
- short m_pitchUV;
-
- /// interpolation function
- int interpol (int a, int b, int c, int d)
- { return (9 * (b + c) - a - d + 8) >> 4; }
-
- /// common horizontal interpolation
- int interpolH (unsigned char *src)
- { return interpol(*(src-1), *src, *(src+1), *(src+2)); }
-
- /// common vertical interpolation
- int interpolV (unsigned char *src)
- { return interpol(*(src-m_pitchUV), *src, *(src+m_pitchUV), *(src+2*m_pitchUV)); }
-
- /// common joined vertical and horizontal interpolation
- int interpolVH (unsigned char *src)
- {
- return interpol(interpolV(src-1), interpolV(src), interpolV(src+1),
- interpolV(src+2));
- }
-
- /// is pixel on edge
- bool isEdge (short x, short y, const short size[2])
- { return x <= 1 || x >= size[0] - 4 || y <= 1 || y >= size[1] - 4; }
-
- /// get the first parameter on the low edge
- unsigned char * interParA (unsigned char *src, short x, short size, short shift)
- { return x > 1 ? src - shift : src; }
- /// get the third parameter on the high edge
- unsigned char * interParC (unsigned char *src, short x, short size, short shift)
- { return x < size - 2 ? src + shift : src; }
- /// get the fourth parameter on the high edge
- unsigned char * interParD (unsigned char *src, short x, short size, short shift)
- { return x < size - 4 ? src + 2 * shift : x < size - 2 ? src + shift : src; }
-
- /// horizontal interpolation on edges
- int interpolEH (unsigned char *src, short x, short size)
- {
- return interpol(*interParA(src, x, size, 1), *src,
- *interParC(src, x, size, 1), *interParD(src, x, size, 1));
- }
-
- /// vertical interpolation on edges
- int interpolEV (unsigned char *src, short y, short size)
- {
- return interpol(*interParA(src, y, size, m_pitchUV), *src,
- *interParC(src, y, size, m_pitchUV), *interParD(src, y, size, m_pitchUV));
- }
-
- /// joined vertical and horizontal interpolation on edges
- int interpolEVH (unsigned char *src, short x, short y, short * size)
- {
- return interpol(interpolEV(interParA(src, x, size[0], 1), y, size[1]),
- interpolEV(src, y, size[1]), interpolEV(interParC(src, x, size[0], 1), y, size[1]),
- interpolEV(interParD(src, x, size[0], 1), y, size[1]));
- }
-
-
- /// filter pixel, source byte buffer
- virtual unsigned int filter (unsigned char *src, short x, short y,
- short * size, unsigned int pixSize, unsigned int val)
- {
- // V & U offset
- long offset = (x >> 1) + m_pitchUV * (y >> 1);
- // get modified YUV -> CDE: C = Y - 16; D = U - 128; E = V - 128
- int c = *src - 16;
- int d = m_buffU[offset] - 128;
- int e = m_buffV[offset] - 128;
- // if horizontal interpolation is needed
- if ((x & 1) == 1) {
- // if vertical interpolation is needed too
- if ((y & 1) == 1)
- {
- // if this pixel is on the edge
- if (isEdge(x, y, size))
- {
- // get U & V from edge
- d = interpolEVH(m_buffU + offset, x, y, size) - 128;
- e = interpolEVH(m_buffV + offset, x, y, size) - 128;
- }
- // otherwise get U & V from inner range
- else
- {
- d = interpolVH(m_buffU + offset) - 128;
- e = interpolVH(m_buffV + offset) - 128;
- }
- // otherwise use horizontal interpolation only
- }
- else {
- // if this pixel is on the edge
- if (isEdge(x, y, size))
- {
- // get U & V from edge
- d = interpolEH(m_buffU + offset, x, size[0]) - 128;
- e = interpolEH(m_buffV + offset, x, size[0]) - 128;
- }
- // otherwise get U & V from inner range
- else
- {
- d = interpolH(m_buffU + offset) - 128;
- e = interpolH(m_buffV + offset) - 128;
- }
- // otherwise if only vertical interpolation is needed
- }
- }
- else if ((y & 1) == 1) {
- // if this pixel is on the edge
- if (isEdge(x, y, size))
- {
- // get U & V from edge
- d = interpolEV(m_buffU + offset, y, size[1]) - 128;
- e = interpolEV(m_buffV + offset, y, size[1]) - 128;
- }
- // otherwise get U & V from inner range
- else
- {
- d = interpolV(m_buffU + offset) - 128;
- e = interpolV(m_buffV + offset) - 128;
- }
- }
- // convert to RGB
- // R = clip(( 298 * C + 409 * E + 128) >> 8)
- // G = clip(( 298 * C - 100 * D - 208 * E + 128) >> 8)
- // B = clip(( 298 * C + 516 * D + 128) >> 8)
- int red = (298 * c + 409 * e + 128) >> 8;
- if (red >= 0x100) red = 0xFF;
- else if (red < 0) red = 0;
- int green = (298 * c - 100 * d - 208 * e) >> 8;
- if (green >= 0x100) green = 0xFF;
- else if (green < 0) green = 0;
- int blue = (298 * c + 516 * d + 128) >> 8;
- if (blue >= 0x100) blue = 0xFF;
- else if (blue < 0) blue = 0;
- // return result
- VT_RGBA(val, red, green, blue, 0xFF);
- return val;
- }
-};
-
-#endif /* __FILTERSOURCE_H__ */
diff --git a/source/gameengine/VideoTexture/ImageBase.cpp b/source/gameengine/VideoTexture/ImageBase.cpp
deleted file mode 100644
index a547d2a7a85..00000000000
--- a/source/gameengine/VideoTexture/ImageBase.cpp
+++ /dev/null
@@ -1,834 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * Copyright (c) 2007 The Zdeno Ash Miklas
- *
- * This source file is part of VideoTexture library
- *
- * Contributor(s):
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/VideoTexture/ImageBase.cpp
- * \ingroup bgevideotex
- */
-
-#include "ImageBase.h"
-extern "C" {
-#include "bgl.h"
-}
-
-#include <vector>
-#include <string.h>
-
-#include "EXP_PyObjectPlus.h"
-#include <structmember.h>
-
-#include "FilterBase.h"
-
-#include "Exception.h"
-
-#if (defined(WIN32) || defined(WIN64))
-#define strcasecmp _stricmp
-#endif
-
-// ImageBase class implementation
-
-ExceptionID ImageHasExports;
-ExceptionID InvalidColorChannel;
-ExceptionID InvalidImageMode;
-
-ExpDesc ImageHasExportsDesc(ImageHasExports, "Image has exported buffers, cannot resize");
-ExpDesc InvalidColorChannelDesc(InvalidColorChannel, "Invalid or too many color channels specified. At most 4 values within R, G, B, A, 0, 1");
-ExpDesc InvalidImageModeDesc(InvalidImageMode, "Invalid image mode, only RGBA and BGRA are supported");
-
-// constructor
-ImageBase::ImageBase (bool staticSrc) : m_image(NULL), m_imgSize(0),
-m_avail(false), m_scale(false), m_scaleChange(false), m_flip(false),
-m_zbuff(false),
-m_depth(false),
-m_staticSources(staticSrc), m_pyfilter(NULL)
-{
- m_size[0] = m_size[1] = 0;
- m_exports = 0;
-}
-
-
-// destructor
-ImageBase::~ImageBase (void)
-{
- // release image
- if (m_image)
- delete [] m_image;
-}
-
-
-// release python objects
-bool ImageBase::release (void)
-{
- // iterate sources
- for (ImageSourceList::iterator it = m_sources.begin(); it != m_sources.end(); ++it)
- {
- // release source object
- delete *it;
- *it = NULL;
- }
- // release filter object
- Py_XDECREF(m_pyfilter);
- m_pyfilter = NULL;
- return true;
-}
-
-
-// get image
-unsigned int * ImageBase::getImage (unsigned int texId, double ts)
-{
- // if image is not available
- if (!m_avail)
- {
- // if there are any sources
- if (!m_sources.empty())
- {
- // get images from sources
- for (ImageSourceList::iterator it = m_sources.begin(); it != m_sources.end(); ++it)
- // get source image
- (*it)->getImage(ts);
- // init image
- init(m_sources[0]->getSize()[0], m_sources[0]->getSize()[1]);
- }
- // calculate new image
- calcImage(texId, ts);
- }
- // if image is available, return it, otherwise NULL
- return m_avail ? m_image : NULL;
-}
-
-bool ImageBase::loadImage(unsigned int *buffer, unsigned int size, unsigned int format, double ts)
-{
- unsigned int *d, *s, v, len;
- if (getImage(0, ts) != NULL && size >= getBuffSize()) {
- switch (format) {
- case GL_RGBA:
- memcpy(buffer, m_image, getBuffSize());
- break;
- case GL_BGRA:
- len = (unsigned int)m_size[0] * m_size[1];
- for (s=m_image, d=buffer; len; len--) {
- v = *s++;
- *d++ = VT_SWAPBR(v);
- }
- break;
- default:
- THRWEXCP(InvalidImageMode,S_OK);
- }
- return true;
- }
- return false;
-}
-
-// refresh image source
-void ImageBase::refresh (void)
-{
- // invalidate this image
- m_avail = false;
- // refresh all sources
- for (ImageSourceList::iterator it = m_sources.begin(); it != m_sources.end(); ++it)
- (*it)->refresh();
-}
-
-
-// get source object
-PyImage * ImageBase::getSource (const char *id)
-{
- // find source
- ImageSourceList::iterator src = findSource(id);
- // return it, if found
- return src != m_sources.end() ? (*src)->getSource() : NULL;
-}
-
-
-// set source object
-bool ImageBase::setSource (const char *id, PyImage *source)
-{
- // find source
- ImageSourceList::iterator src = findSource(id);
- // check source loop
- if (source != NULL && source->m_image->loopDetect(this))
- return false;
- // if found, set new object
- if (src != m_sources.end())
- // if new object is not empty or sources are static
- if (source != NULL || m_staticSources)
- // replace previous source
- (*src)->setSource(source);
- // otherwise delete source
- else
- m_sources.erase(src);
- // if source is not found and adding is allowed
- else
- if (!m_staticSources)
- {
- // create new source
- ImageSource * newSrc = newSource(id);
- newSrc->setSource(source);
- // if source was created, add it to source list
- if (newSrc != NULL) m_sources.push_back(newSrc);
- }
- // otherwise source wasn't set
- else
- return false;
- // source was set
- return true;
-}
-
-
-// set pixel filter
-void ImageBase::setFilter (PyFilter * filt)
-{
- // reference new filter
- if (filt != NULL) Py_INCREF(filt);
- // release previous filter
- Py_XDECREF(m_pyfilter);
- // set new filter
- m_pyfilter = filt;
-}
-
-void ImageBase::swapImageBR()
-{
- unsigned int size, v, *s;
-
- if (m_avail) {
- size = 1 * m_size[0] * m_size[1];
- for (s=m_image; size; size--) {
- v = *s;
- *s++ = VT_SWAPBR(v);
- }
- }
-}
-
-// initialize image data
-void ImageBase::init (short width, short height)
-{
- // if image has to be scaled
- if (m_scale)
- {
- // recalc sizes of image
- width = calcSize(width);
- height = calcSize(height);
- }
- // if sizes differ
- if (width != m_size[0] || height != m_size[1])
- {
- if (m_exports > 0)
- THRWEXCP(ImageHasExports,S_OK);
-
- // new buffer size
- unsigned int newSize = width * height;
- // if new buffer is larger than previous
- if (newSize > m_imgSize)
- {
- // set new buffer size
- m_imgSize = newSize;
- // release previous and create new buffer
- if (m_image)
- delete [] m_image;
- m_image = new unsigned int[m_imgSize];
- }
- // new image size
- m_size[0] = width;
- m_size[1] = height;
- // scale was processed
- m_scaleChange = false;
- }
-}
-
-
-// find source
-ImageSourceList::iterator ImageBase::findSource (const char *id)
-{
- // iterate sources
- ImageSourceList::iterator it;
- for (it = m_sources.begin(); it != m_sources.end(); ++it)
- // if id matches, return iterator
- if ((*it)->is(id)) return it;
- // source not found
- return it;
-}
-
-
-// check sources sizes
-bool ImageBase::checkSourceSizes (void)
-{
- // reference size
- short * refSize = NULL;
- // iterate sources
- for (ImageSourceList::iterator it = m_sources.begin(); it != m_sources.end(); ++it)
- {
- // get size of current source
- short * curSize = (*it)->getSize();
- // if size is available and is not empty
- if (curSize[0] != 0 && curSize[1] != 0) {
- // if reference size is not set
- if (refSize == NULL) {
- // set current size as reference
- refSize = curSize;
- // otherwise check with current size
- }
- else if (curSize[0] != refSize[0] || curSize[1] != refSize[1]) {
- // if they don't match, report it
- return false;
- }
- }
- }
- // all sizes match
- return true;
-}
-
-
-// compute nearest power of 2 value
-short ImageBase::calcSize (short size)
-{
- // while there is more than 1 bit in size value
- while ((size & (size - 1)) != 0)
- // clear last bit
- size = size & (size - 1);
- // return result
- return size;
-}
-
-
-// perform loop detection
-bool ImageBase::loopDetect (ImageBase * img)
-{
- // if this object is the same as parameter, loop is detected
- if (this == img) return true;
- // check all sources
- for (ImageSourceList::iterator it = m_sources.begin(); it != m_sources.end(); ++it)
- // if source detected loop, return this result
- if ((*it)->getSource() != NULL && (*it)->getSource()->m_image->loopDetect(img))
- return true;
- // no loop detected
- return false;
-}
-
-
-// ImageSource class implementation
-
-// constructor
-ImageSource::ImageSource (const char *id) : m_source(NULL), m_image(NULL)
-{
- // copy id
- int idx;
- for (idx = 0; id[idx] != '\0' && idx < SourceIdSize - 1; ++idx)
- m_id[idx] = id[idx];
- m_id[idx] = '\0';
-}
-
-// destructor
-ImageSource::~ImageSource (void)
-{
- // release source
- setSource(NULL);
-}
-
-
-// compare id
-bool ImageSource::is (const char *id)
-{
- for (char *myId = m_id; *myId != '\0'; ++myId, ++id)
- if (*myId != *id) return false;
- return *id == '\0';
-}
-
-
-// set source object
-void ImageSource::setSource (PyImage *source)
-{
- // reference new source
- if (source != NULL) Py_INCREF(source);
- // release previous source
- Py_XDECREF(m_source);
- // set new source
- m_source = source;
-}
-
-
-// get image from source
-unsigned int * ImageSource::getImage (double ts)
-{
- // if source is available
- if (m_source != NULL)
- // get image from source
- m_image = m_source->m_image->getImage(0, ts);
- // otherwise reset buffer
- else
- m_image = NULL;
- // return image
- return m_image;
-}
-
-
-// refresh source
-void ImageSource::refresh (void)
-{
- // if source is available, refresh it
- if (m_source != NULL) m_source->m_image->refresh();
-}
-
-
-
-// list of image types
-PyTypeList pyImageTypes;
-
-
-
-// functions for python interface
-
-// object allocation
-PyObject *Image_allocNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
-{
- // allocate object
- PyImage *self = reinterpret_cast<PyImage*>(type->tp_alloc(type, 0));
- // initialize object structure
- self->m_image = NULL;
- // return allocated object
- return reinterpret_cast<PyObject*>(self);
-}
-
-// object deallocation
-void Image_dealloc(PyImage *self)
-{
- // release object attributes
- if (self->m_image != NULL)
- {
- if (self->m_image->m_exports > 0)
- {
- PyErr_SetString(PyExc_SystemError,
- "deallocated Image object has exported buffers");
- PyErr_Print();
- }
- // if release requires deleting of object, do it
- if (self->m_image->release())
- delete self->m_image;
- self->m_image = NULL;
- }
- Py_TYPE((PyObject *)self)->tp_free((PyObject *)self);
-}
-
-// get image data
-PyObject *Image_getImage(PyImage *self, char *mode)
-{
- try
- {
- unsigned int * image = self->m_image->getImage();
- if (image)
- {
- // build BGL buffer
- int dimensions = self->m_image->getBuffSize();
- Buffer * buffer;
- if (mode == NULL || !strcasecmp(mode, "RGBA"))
- {
- buffer = BGL_MakeBuffer( GL_BYTE, 1, &dimensions, image);
- }
- else if (!strcasecmp(mode, "F"))
- {
- // this mode returns the image as an array of float.
- // This makes sense ONLY for the depth buffer:
- // source = VideoTexture.ImageViewport()
- // source.depth = True
- // depth = VideoTexture.imageToArray(source, 'F')
-
- // adapt dimension from byte to float
- dimensions /= sizeof(float);
- buffer = BGL_MakeBuffer( GL_FLOAT, 1, &dimensions, image);
- }
- else
- {
- int i, c, ncolor, pixels;
- int offset[4];
- unsigned char *s, *d;
- // scan the mode to get the channels requested, no more than 4
- for (i=ncolor=0; mode[i] != 0 && ncolor < 4; i++)
- {
- switch (toupper(mode[i]))
- {
- case 'R':
- offset[ncolor++] = 0;
- break;
- case 'G':
- offset[ncolor++] = 1;
- break;
- case 'B':
- offset[ncolor++] = 2;
- break;
- case 'A':
- offset[ncolor++] = 3;
- break;
- case '0':
- offset[ncolor++] = -1;
- break;
- case '1':
- offset[ncolor++] = -2;
- break;
- // if you add more color code, change the switch further down
- default:
- THRWEXCP(InvalidColorChannel,S_OK);
- }
- }
- if (mode[i] != 0) {
- THRWEXCP(InvalidColorChannel,S_OK);
- }
- // first get the number of pixels
- pixels = dimensions / 4;
- // multiple by the number of channels, each is one byte
- dimensions = pixels * ncolor;
- // get an empty buffer
- buffer = BGL_MakeBuffer( GL_BYTE, 1, &dimensions, NULL);
- // and fill it
- for (i = 0, d = (unsigned char *)buffer->buf.asbyte, s = (unsigned char *)image;
- i < pixels;
- i++, d += ncolor, s += 4)
- {
- for (c=0; c<ncolor; c++)
- {
- switch (offset[c])
- {
- case 0: d[c] = s[0]; break;
- case 1: d[c] = s[1]; break;
- case 2: d[c] = s[2]; break;
- case 3: d[c] = s[3]; break;
- case -1: d[c] = 0; break;
- case -2: d[c] = 0xFF; break;
- }
- }
- }
- }
- return (PyObject *)buffer;
- }
- }
- catch (Exception & exp)
- {
- exp.report();
- return NULL;
- }
- Py_RETURN_NONE;
-}
-
-// get image size
-PyObject *Image_getSize (PyImage *self, void *closure)
-{
- return Py_BuildValue("(hh)", self->m_image->getSize()[0],
- self->m_image->getSize()[1]);
-}
-
-// refresh image
-PyObject *Image_refresh (PyImage *self, PyObject *args)
-{
- Py_buffer buffer;
- bool done = true;
- char *mode = NULL;
- double ts = -1.0;
- unsigned int format;
-
- memset(&buffer, 0, sizeof(buffer));
- if (PyArg_ParseTuple(args, "|s*sd:refresh", &buffer, &mode, &ts)) {
- if (buffer.buf) {
- // a target buffer is provided, verify its format
- if (buffer.readonly) {
- PyErr_SetString(PyExc_TypeError, "Buffers passed in argument must be writable");
- }
- else if (!PyBuffer_IsContiguous(&buffer, 'C')) {
- PyErr_SetString(PyExc_TypeError, "Buffers passed in argument must be contiguous in memory");
- }
- else if (((intptr_t)buffer.buf & 3) != 0) {
- PyErr_SetString(PyExc_TypeError, "Buffers passed in argument must be aligned to 4 bytes boundary");
- }
- else {
- // ready to get the image into our buffer
- try {
- if (mode == NULL || !strcmp(mode, "RGBA"))
- format = GL_RGBA;
- else if (!strcmp(mode, "BGRA"))
- format = GL_BGRA;
- else
- THRWEXCP(InvalidImageMode,S_OK);
-
- done = self->m_image->loadImage((unsigned int *)buffer.buf, buffer.len, format, ts);
- }
- catch (Exception & exp) {
- exp.report();
- }
- }
- PyBuffer_Release(&buffer);
- if (PyErr_Occurred()) {
- return NULL;
- }
- }
- }
- else {
- return NULL;
- }
-
- self->m_image->refresh();
- if (done)
- Py_RETURN_TRUE;
- Py_RETURN_FALSE;
-}
-
-// get scale
-PyObject *Image_getScale (PyImage *self, void *closure)
-{
- if (self->m_image != NULL && self->m_image->getScale()) Py_RETURN_TRUE;
- else Py_RETURN_FALSE;
-}
-
-// set scale
-int Image_setScale(PyImage *self, PyObject *value, void *closure)
-{
- // check parameter, report failure
- if (value == NULL || !PyBool_Check(value))
- {
- PyErr_SetString(PyExc_TypeError, "The value must be a bool");
- return -1;
- }
- // set scale
- if (self->m_image != NULL) self->m_image->setScale(value == Py_True);
- // success
- return 0;
-}
-
-// get flip
-PyObject *Image_getFlip (PyImage *self, void *closure)
-{
- if (self->m_image != NULL && self->m_image->getFlip()) Py_RETURN_TRUE;
- else Py_RETURN_FALSE;
-}
-
-// set flip
-int Image_setFlip(PyImage *self, PyObject *value, void *closure)
-{
- // check parameter, report failure
- if (value == NULL || !PyBool_Check(value))
- {
- PyErr_SetString(PyExc_TypeError, "The value must be a bool");
- return -1;
- }
- // set scale
- if (self->m_image != NULL) self->m_image->setFlip(value == Py_True);
- // success
- return 0;
-}
-
-// get zbuff
-PyObject *Image_getZbuff(PyImage *self, void *closure)
-{
- if (self->m_image != NULL && self->m_image->getZbuff()) Py_RETURN_TRUE;
- else Py_RETURN_FALSE;
-}
-
-// set zbuff
-int Image_setZbuff(PyImage *self, PyObject *value, void *closure)
-{
- // check parameter, report failure
- if (value == NULL || !PyBool_Check(value))
- {
- PyErr_SetString(PyExc_TypeError, "The value must be a bool");
- return -1;
- }
- // set scale
- if (self->m_image != NULL) self->m_image->setZbuff(value == Py_True);
- // success
- return 0;
-}
-
-// get depth
-PyObject *Image_getDepth(PyImage *self, void *closure)
-{
- if (self->m_image != NULL && self->m_image->getDepth()) Py_RETURN_TRUE;
- else Py_RETURN_FALSE;
-}
-
-// set depth
-int Image_setDepth(PyImage *self, PyObject *value, void *closure)
-{
- // check parameter, report failure
- if (value == NULL || !PyBool_Check(value))
- {
- PyErr_SetString(PyExc_TypeError, "The value must be a bool");
- return -1;
- }
- // set scale
- if (self->m_image != NULL) self->m_image->setDepth(value == Py_True);
- // success
- return 0;
-}
-
-
-
-
-// get filter source object
-PyObject *Image_getSource(PyImage *self, PyObject *args)
-{
- // get arguments
- char *id;
- if (!PyArg_ParseTuple(args, "s:getSource", &id))
- return NULL;
- if (self->m_image != NULL)
- {
- // get source object
- PyObject *src = reinterpret_cast<PyObject*>(self->m_image->getSource(id));
- // if source is available
- if (src != NULL)
- {
- // return source
- Py_INCREF(src);
- return src;
- }
- }
- // source was not found
- Py_RETURN_NONE;
-}
-
-
-// set filter source object
-PyObject *Image_setSource(PyImage *self, PyObject *args)
-{
- // get arguments
- char *id;
- PyObject *obj;
- if (!PyArg_ParseTuple(args, "sO:setSource", &id, &obj))
- return NULL;
- if (self->m_image != NULL)
- {
- // check type of object
- if (pyImageTypes.in(Py_TYPE(obj)))
- {
- // convert to image struct
- PyImage * img = reinterpret_cast<PyImage*>(obj);
- // set source
- if (!self->m_image->setSource(id, img))
- {
- // if not set, retport error
- PyErr_SetString(PyExc_RuntimeError, "Invalid source or id");
- return NULL;
- }
- }
- // else report error
- else
- {
- PyErr_SetString(PyExc_RuntimeError, "Invalid type of object");
- return NULL;
- }
- }
- // return none
- Py_RETURN_NONE;
-}
-
-
-// get pixel filter object
-PyObject *Image_getFilter(PyImage *self, void *closure)
-{
- // if image object is available
- if (self->m_image != NULL)
- {
- // pixel filter object
- PyObject *filt = reinterpret_cast<PyObject*>(self->m_image->getFilter());
- // if filter is present
- if (filt != NULL)
- {
- // return it
- Py_INCREF(filt);
- return filt;
- }
- }
- // otherwise return none
- Py_RETURN_NONE;
-}
-
-
-// set pixel filter object
-int Image_setFilter(PyImage *self, PyObject *value, void *closure)
-{
- // if image object is available
- if (self->m_image != NULL)
- {
- // check new value
- if (value == NULL || !pyFilterTypes.in(Py_TYPE(value)))
- {
- // report value error
- PyErr_SetString(PyExc_TypeError, "Invalid type of value");
- return -1;
- }
- // set new value
- self->m_image->setFilter(reinterpret_cast<PyFilter*>(value));
- }
- // return success
- return 0;
-}
-PyObject *Image_valid(PyImage *self, void *closure)
-{
- if (self->m_image->isImageAvailable())
- {
- Py_RETURN_TRUE;
- }
- else
- {
- Py_RETURN_FALSE;
- }
-}
-
-static int Image_getbuffer(PyImage *self, Py_buffer *view, int flags)
-{
- unsigned int * image;
- int ret;
-
- try {
- // can throw in case of resize
- image = self->m_image->getImage();
- }
- catch (Exception & exp) {
- exp.report();
- return -1;
- }
-
- if (!image) {
- PyErr_SetString(PyExc_BufferError, "Image buffer is not available");
- return -1;
- }
- if (view == NULL)
- {
- self->m_image->m_exports++;
- return 0;
- }
- ret = PyBuffer_FillInfo(view, (PyObject *)self, image, self->m_image->getBuffSize(), 0, flags);
- if (ret >= 0)
- self->m_image->m_exports++;
- return ret;
-}
-
-static void Image_releaseBuffer(PyImage *self, Py_buffer *buffer)
-{
- self->m_image->m_exports--;
-}
-
-PyBufferProcs imageBufferProcs =
-{
- (getbufferproc)Image_getbuffer,
- (releasebufferproc)Image_releaseBuffer
-};
-
diff --git a/source/gameengine/VideoTexture/ImageBase.h b/source/gameengine/VideoTexture/ImageBase.h
deleted file mode 100644
index 5a09c9a67b3..00000000000
--- a/source/gameengine/VideoTexture/ImageBase.h
+++ /dev/null
@@ -1,392 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * Copyright (c) 2007 The Zdeno Ash Miklas
- *
- * This source file is part of blendTex library
- *
- * Contributor(s):
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file ImageBase.h
- * \ingroup bgevideotex
- */
-
-#ifndef __IMAGEBASE_H__
-#define __IMAGEBASE_H__
-
-#include "Common.h"
-
-#include <vector>
-#include "EXP_PyObjectPlus.h"
-
-#include "PyTypeList.h"
-
-#include "FilterBase.h"
-
-#include "GPU_glew.h"
-
-// forward declarations
-struct PyImage;
-class ImageSource;
-
-
-/// type for list of image sources
-typedef std::vector<ImageSource*> ImageSourceList;
-
-
-/// base class for image filters
-class ImageBase
-{
-public:
- /// constructor
- ImageBase (bool staticSrc = false);
- /// destructor
- virtual ~ImageBase(void);
- /// release contained objects, if returns true, object should be deleted
- virtual bool release(void);
-
- /// is an image available
- bool isImageAvailable(void)
- { return m_avail; }
- /// get image
- unsigned int *getImage(unsigned int texId = 0, double timestamp=-1.0);
- /// get image size
- short * getSize(void) { return m_size; }
- /// get image buffer size
- unsigned long getBuffSize(void)
- { return m_size[0] * m_size[1] * sizeof(unsigned int); }
- /// refresh image - invalidate its current content
- virtual void refresh(void);
-
- /// get scale
- bool getScale(void) { return m_scale; }
- /// set scale
- void setScale(bool scale) { m_scale = scale; m_scaleChange = true; }
- /// get vertical flip
- bool getFlip(void) { return m_flip; }
- /// set vertical flip
- void setFlip(bool flip) { m_flip = flip; }
- /// get Z buffer
- bool getZbuff(void) { return m_zbuff; }
- /// set Z buffer
- void setZbuff(bool zbuff) { m_zbuff = zbuff; }
- /// get depth
- bool getDepth(void) { return m_depth; }
- /// set depth
- void setDepth(bool depth) { m_depth = depth; }
-
- /// get source object
- PyImage * getSource(const char *id);
- /// set source object, return true, if source was set
- bool setSource(const char *id, PyImage *source);
-
- /// get pixel filter
- PyFilter * getFilter(void) { return m_pyfilter; }
- /// set pixel filter
- void setFilter(PyFilter * filt);
-
- /// calculate size(nearest power of 2)
- static short calcSize(short size);
-
- /// calculate image from sources and send it to a target buffer instead of a texture
- /// format is GL_RGBA or GL_BGRA
- virtual bool loadImage(unsigned int *buffer, unsigned int size, unsigned int format, double ts);
-
- /// swap the B and R channel in-place in the image buffer
- void swapImageBR();
-
- /// number of buffer pointing to m_image, public because not handled by this class
- int m_exports;
-
-protected:
- /// image buffer
- unsigned int * m_image;
- /// image buffer size
- unsigned int m_imgSize;
- /// image size
- short m_size[2];
- /// image is available
- bool m_avail;
-
- /// scale image to power 2 sizes
- bool m_scale;
- /// scale was changed
- bool m_scaleChange;
- /// flip image vertically
- bool m_flip;
- /// use the Z buffer as a texture
- bool m_zbuff;
- /// extract the Z buffer with unisgned int precision
- bool m_depth;
-
- /// source image list
- ImageSourceList m_sources;
- /// flag for disabling addition and deletion of sources
- bool m_staticSources;
-
- /// pixel filter
- PyFilter * m_pyfilter;
-
- /// initialize image data
- void init(short width, short height);
-
- /// find source
- ImageSourceList::iterator findSource(const char *id);
-
- /// create new source
- virtual ImageSource *newSource(const char *id) { return NULL; }
-
- /// check source sizes
- bool checkSourceSizes(void);
-
- /// calculate image from sources and set its availability
- virtual void calcImage(unsigned int texId, double ts) {}
-
- /// perform loop detection
- bool loopDetect(ImageBase * img);
-
- /// template for image conversion
- template<class FLT, class SRC> void convImage(FLT & filter, SRC srcBuff,
- short * srcSize)
- {
- // destination buffer
- unsigned int * dstBuff = m_image;
- // pixel size from filter
- unsigned int pixSize = filter.firstPixelSize();
- // if no scaling is needed
- if (srcSize[0] == m_size[0] && srcSize[1] == m_size[1])
- // if flipping isn't required
- if (!m_flip)
- // copy bitmap
- for (short y = 0; y < m_size[1]; ++y)
- for (short x = 0; x < m_size[0]; ++x, ++dstBuff, srcBuff += pixSize)
- // copy pixel
- *dstBuff = filter.convert(srcBuff, x, y, srcSize, pixSize);
- // otherwise flip image top to bottom
- else
- {
- // go to last row of image
- srcBuff += srcSize[0] * (srcSize[1] - 1) * pixSize;
- // copy bitmap
- for (short y = m_size[1] - 1; y >= 0; --y, srcBuff -= 2 * srcSize[0] * pixSize)
- for (short x = 0; x < m_size[0]; ++x, ++dstBuff, srcBuff += pixSize)
- // copy pixel
- *dstBuff = filter.convert(srcBuff, x, y, srcSize, pixSize);
- }
- // else scale picture (nearest neighbor)
- else
- {
- // interpolation accumulator
- int accHeight = srcSize[1] >> 1;
- // if flipping is required
- if (m_flip)
- // go to last row of image
- srcBuff += srcSize[0] * (srcSize[1] - 1) * pixSize;
- // process image rows
- for (int y = 0; y < srcSize[1]; ++y)
- {
- // increase height accum
- accHeight += m_size[1];
- // if pixel row has to be drawn
- if (accHeight >= srcSize[1])
- {
- // decrease accum
- accHeight -= srcSize[1];
- // width accum
- int accWidth = srcSize[0] >> 1;
- // process row
- for (int x = 0; x < srcSize[0]; ++x)
- {
- // increase width accum
- accWidth += m_size[0];
- // if pixel has to be drawn
- if (accWidth >= srcSize[0])
- {
- // decrease accum
- accWidth -= srcSize[0];
- // convert pixel
- *dstBuff = filter.convert(srcBuff, x, m_flip ? srcSize[1] - y - 1 : y,
- srcSize, pixSize);
- // next pixel
- ++dstBuff;
- }
- // shift source pointer
- srcBuff += pixSize;
- }
- }
- // if pixel row will not be drawn
- else
- // move source pointer to next row
- srcBuff += pixSize * srcSize[0];
- // if y flipping is required
- if (m_flip)
- // go to previous row of image
- srcBuff -= 2 * pixSize * srcSize[0];
- }
- }
- }
-
- // template for specific filter preprocessing
- template <class F, class SRC> void filterImage (F & filt, SRC srcBuff, short *srcSize)
- {
- // find first filter in chain
- FilterBase * firstFilter = NULL;
- if (m_pyfilter != NULL) firstFilter = m_pyfilter->m_filter->findFirst();
- // if first filter is available
- if (firstFilter != NULL)
- {
- // python wrapper for filter
- PyFilter pyFilt;
- pyFilt.m_filter = &filt;
- // set specified filter as first in chain
- firstFilter->setPrevious(&pyFilt, false);
- // convert video image
- convImage(*(m_pyfilter->m_filter), srcBuff, srcSize);
- // delete added filter
- firstFilter->setPrevious(NULL, false);
- }
- // otherwise use given filter for conversion
- else convImage(filt, srcBuff, srcSize);
- // source was processed
- m_avail = true;
- }
-};
-
-
-// python structure for image filter
-struct PyImage
-{
- PyObject_HEAD
- // source object
- ImageBase * m_image;
-};
-
-
-// size of id
-const int SourceIdSize = 32;
-
-
-/// class for source of image
-class ImageSource
-{
-public:
- /// constructor
- ImageSource (const char *id);
- /// destructor
- virtual ~ImageSource (void);
-
- /// get id
- const char * getId (void) { return m_id; }
- /// compare id to argument
- bool is (const char *id);
-
- /// get source object
- PyImage * getSource (void) { return m_source; }
- /// set source object
- void setSource (PyImage *source);
-
- /// get image from source
- unsigned int * getImage (double ts=-1.0);
- /// get buffered image
- unsigned int * getImageBuf (void) { return m_image; }
- /// refresh source
- void refresh (void);
-
- /// get image size
- short * getSize (void)
- {
- static short defSize [] = {0, 0};
- return m_source != NULL ? m_source->m_image->getSize() : defSize;
- }
-
-protected:
- /// id of source
- char m_id [SourceIdSize];
- /// pointer to source structure
- PyImage * m_source;
- /// buffered image from source
- unsigned int * m_image;
-
-private:
- /// default constructor is forbidden
- ImageSource (void) {}
-};
-
-// list of python image types
-extern PyTypeList pyImageTypes;
-
-
-// functions for python interface
-
-// object initialization
-template <class T> static int Image_init(PyObject *pySelf, PyObject *args, PyObject *kwds)
-{
- PyImage *self = reinterpret_cast<PyImage *>(pySelf);
- // create source object
- if (self->m_image != NULL) delete self->m_image;
- self->m_image = new T();
- // initialization succeded
- return 0;
-}
-
-// object allocation
-PyObject *Image_allocNew(PyTypeObject *type, PyObject *args, PyObject *kwds);
-// object deallocation
-void Image_dealloc(PyImage *self);
-
-// get image data
-PyObject *Image_getImage(PyImage *self, char *mode);
-// get image size
-PyObject *Image_getSize(PyImage *self, void *closure);
-// refresh image - invalidate current content
-PyObject *Image_refresh(PyImage *self, PyObject *args);
-
-// get scale
-PyObject *Image_getScale(PyImage *self, void *closure);
-// set scale
-int Image_setScale(PyImage *self, PyObject *value, void *closure);
-// get flip
-PyObject *Image_getFlip(PyImage *self, void *closure);
-// set flip
-int Image_setFlip(PyImage *self, PyObject *value, void *closure);
-
-// get filter source object
-PyObject *Image_getSource(PyImage *self, PyObject *args);
-// set filter source object
-PyObject *Image_setSource(PyImage *self, PyObject *args);
-// get Z buffer
-PyObject *Image_getZbuff(PyImage *self, void *closure);
-// set Z buffer
-int Image_setZbuff(PyImage *self, PyObject *value, void *closure);
-// get depth
-PyObject *Image_getDepth(PyImage *self, void *closure);
-// set depth
-int Image_setDepth(PyImage *self, PyObject *value, void *closure);
-
-// get pixel filter object
-PyObject *Image_getFilter(PyImage *self, void *closure);
-// set pixel filter object
-int Image_setFilter(PyImage *self, PyObject *value, void *closure);
-// check if a buffer can be extracted
-PyObject *Image_valid(PyImage *self, void *closure);
-// for buffer access to PyImage objects
-extern PyBufferProcs imageBufferProcs;
-
-#endif
diff --git a/source/gameengine/VideoTexture/ImageBuff.cpp b/source/gameengine/VideoTexture/ImageBuff.cpp
deleted file mode 100644
index 77270865b17..00000000000
--- a/source/gameengine/VideoTexture/ImageBuff.cpp
+++ /dev/null
@@ -1,424 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * Copyright (c) 2007 The Zdeno Ash Miklas
- *
- * This source file is part of VideoTexture library
- *
- * Contributor(s):
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/VideoTexture/ImageBuff.cpp
- * \ingroup bgevideotex
- */
-
-// implementation
-
-#include "EXP_PyObjectPlus.h"
-#include <structmember.h>
-
-#include "ImageBuff.h"
-#include "Exception.h"
-#include "ImageBase.h"
-#include "FilterSource.h"
-
-// use ImBuf API for image manipulation
-extern "C" {
-#include "IMB_imbuf_types.h"
-#include "IMB_imbuf.h"
-#include "bgl.h"
-};
-
-// default filter
-FilterRGB24 defFilter;
-
-// forward declaration;
-extern PyTypeObject ImageBuffType;
-
-static int ImageBuff_init(PyObject *pySelf, PyObject *args, PyObject *kwds)
-{
- short width = -1;
- short height = -1;
- unsigned char color = 0;
- PyObject *py_scale = Py_False;
- ImageBuff *image;
-
- PyImage *self = reinterpret_cast<PyImage*>(pySelf);
- // create source object
- if (self->m_image != NULL)
- delete self->m_image;
- image = new ImageBuff();
- self->m_image = image;
-
- if (PyArg_ParseTuple(args, "hh|bO!:ImageBuff", &width, &height, &color, &PyBool_Type, &py_scale))
- {
- // initialize image buffer
- image->setScale(py_scale == Py_True);
- image->clear(width, height, color);
- }
- else
- {
- // check if at least one argument was passed
- if (width != -1 || height != -1)
- // yes and they didn't match => it's an error
- return -1;
- // empty argument list is okay
- PyErr_Clear();
- }
- // initialization succeded
- return 0;
-
-}
-
-ImageBuff::~ImageBuff (void)
-{
- if (m_imbuf)
- IMB_freeImBuf(m_imbuf);
-}
-
-
-// load image from buffer
-void ImageBuff::load(unsigned char *img, short width, short height)
-{
- // loading a new buffer implies to reset the imbuf if any, because the size may change
- if (m_imbuf)
- {
- IMB_freeImBuf(m_imbuf);
- m_imbuf = NULL;
- }
- // initialize image buffer
- init(width, height);
- // original size
- short orgSize[2] = {width, height};
- // is filter available
- if (m_pyfilter != NULL)
- // use it to process image
- convImage(*(m_pyfilter->m_filter), img, orgSize);
- else
- // otherwise use default filter
- convImage(defFilter, img, orgSize);
- // image is available
- m_avail = true;
-}
-
-void ImageBuff::clear(short width, short height, unsigned char color)
-{
- unsigned char *p;
- int size;
-
- // loading a new buffer implies to reset the imbuf if any, because the size may change
- if (m_imbuf)
- {
- IMB_freeImBuf(m_imbuf);
- m_imbuf = NULL;
- }
- // initialize image buffer
- init(width, height);
- // the width/height may be different due to scaling
- size = (m_size[0] * m_size[1]);
- // initialize memory with color for all channels
- memset(m_image, color, size*4);
- // and change the alpha channel
- p = &((unsigned char*)m_image)[3];
- for (; size>0; size--)
- {
- *p = 0xFF;
- p += 4;
- }
- // image is available
- m_avail = true;
-}
-
-// img must point to a array of RGBA data of size width*height
-void ImageBuff::plot(unsigned char *img, short width, short height, short x, short y, short mode)
-{
- struct ImBuf *tmpbuf;
-
- if (m_size[0] == 0 || m_size[1] == 0 || width <= 0 || height <= 0)
- return;
-
- if (!m_imbuf) {
- // allocate most basic imbuf, we will assign the rect buffer on the fly
- m_imbuf = IMB_allocImBuf(m_size[0], m_size[1], 0, 0);
- }
-
- tmpbuf = IMB_allocImBuf(width, height, 0, 0);
-
- // assign temporarily our buffer to the ImBuf buffer, we use the same format
- tmpbuf->rect = (unsigned int*)img;
- m_imbuf->rect = m_image;
- IMB_rectblend(m_imbuf, m_imbuf, tmpbuf, NULL, NULL, NULL, 0, x, y, x, y, 0, 0, width, height, (IMB_BlendMode)mode, false);
- // remove so that MB_freeImBuf will free our buffer
- m_imbuf->rect = NULL;
- tmpbuf->rect = NULL;
- IMB_freeImBuf(tmpbuf);
-}
-
-void ImageBuff::plot(ImageBuff *img, short x, short y, short mode)
-{
- if (m_size[0] == 0 || m_size[1] == 0 || img->m_size[0] == 0 || img->m_size[1] == 0)
- return;
-
- if (!m_imbuf) {
- // allocate most basic imbuf, we will assign the rect buffer on the fly
- m_imbuf = IMB_allocImBuf(m_size[0], m_size[1], 0, 0);
- }
- if (!img->m_imbuf) {
- // allocate most basic imbuf, we will assign the rect buffer on the fly
- img->m_imbuf = IMB_allocImBuf(img->m_size[0], img->m_size[1], 0, 0);
- }
- // assign temporarily our buffer to the ImBuf buffer, we use the same format
- img->m_imbuf->rect = img->m_image;
- m_imbuf->rect = m_image;
- IMB_rectblend(m_imbuf, m_imbuf, img->m_imbuf, NULL, NULL, NULL, 0, x, y, x, y, 0, 0, img->m_imbuf->x, img->m_imbuf->y, (IMB_BlendMode)mode, false);
- // remove so that MB_freeImBuf will free our buffer
- m_imbuf->rect = NULL;
- img->m_imbuf->rect = NULL;
-}
-
-
-// cast Image pointer to ImageBuff
-inline ImageBuff *getImageBuff(PyImage *self)
-{ return static_cast<ImageBuff *>(self->m_image); }
-
-
-// python methods
-
-static bool testPyBuffer(Py_buffer *buffer, int width, int height, unsigned int pixsize)
-{
- if (buffer->itemsize != 1)
- {
- PyErr_SetString(PyExc_ValueError, "Buffer must be an array of bytes");
- return false;
- }
- if (buffer->len != width*height*pixsize)
- {
- PyErr_SetString(PyExc_ValueError, "Buffer hasn't the correct size");
- return false;
- }
- // multi dimension are ok as long as there is no hole in the memory
- Py_ssize_t size = buffer->itemsize;
- for (int i=buffer->ndim-1; i>=0 ; i--)
- {
- if (buffer->suboffsets != NULL && buffer->suboffsets[i] >= 0)
- {
- PyErr_SetString(PyExc_ValueError, "Buffer must be of one block");
- return false;
- }
- if (buffer->strides != NULL && buffer->strides[i] != size)
- {
- PyErr_SetString(PyExc_ValueError, "Buffer must be of one block");
- return false;
- }
- if (i > 0)
- size *= buffer->shape[i];
- }
- return true;
-}
-
-static bool testBGLBuffer(Buffer *buffer, int width, int height, unsigned int pixsize)
-{
- unsigned int size = BGL_typeSize(buffer->type);
- for (int i=0; i<buffer->ndimensions; i++)
- {
- size *= buffer->dimensions[i];
- }
- if (size != width*height*pixsize)
- {
- PyErr_SetString(PyExc_ValueError, "Buffer hasn't the correct size");
- return false;
- }
- return true;
-}
-
-
-// load image
-static PyObject *load(PyImage *self, PyObject *args)
-{
- // parameters: string image buffer, its size, width, height
- Py_buffer buffer;
- Buffer *bglBuffer;
- short width;
- short height;
- unsigned int pixSize;
-
- // calc proper buffer size
- // use pixel size from filter
- if (self->m_image->getFilter() != NULL)
- pixSize = self->m_image->getFilter()->m_filter->firstPixelSize();
- else
- pixSize = defFilter.firstPixelSize();
-
- // parse parameters
- if (!PyArg_ParseTuple(args, "s*hh:load", &buffer, &width, &height))
- {
- PyErr_Clear();
- // check if it is BGL buffer
- if (!PyArg_ParseTuple(args, "O!hh:load", &BGL_bufferType, &bglBuffer, &width, &height))
- {
- // report error
- return NULL;
- }
- else
- {
- if (testBGLBuffer(bglBuffer, width, height, pixSize))
- {
- try
- {
- // if correct, load image
- getImageBuff(self)->load((unsigned char*)bglBuffer->buf.asvoid, width, height);
- }
- catch (Exception & exp)
- {
- exp.report();
- }
- }
- }
- }
- else
- {
- // check if buffer size is correct
- if (testPyBuffer(&buffer, width, height, pixSize))
- {
- try
- {
- // if correct, load image
- getImageBuff(self)->load((unsigned char*)buffer.buf, width, height);
- }
- catch (Exception & exp)
- {
- exp.report();
- }
- }
- PyBuffer_Release(&buffer);
- }
- if (PyErr_Occurred())
- return NULL;
- Py_RETURN_NONE;
-}
-
-static PyObject *plot(PyImage *self, PyObject *args)
-{
- PyImage * other;
- Buffer* bglBuffer;
- Py_buffer buffer;
- //unsigned char * buff;
- //unsigned int buffSize;
- short width;
- short height;
- short x, y;
- short mode = IMB_BLEND_COPY;
-
- if (PyArg_ParseTuple(args, "s*hhhh|h:plot", &buffer, &width, &height, &x, &y, &mode))
- {
- // correct decoding, verify that buffer size is correct
- // we need a continuous memory buffer
- if (testPyBuffer(&buffer, width, height, 4))
- {
- getImageBuff(self)->plot((unsigned char*)buffer.buf, width, height, x, y, mode);
- }
- PyBuffer_Release(&buffer);
- if (PyErr_Occurred())
- return NULL;
- Py_RETURN_NONE;
- }
- PyErr_Clear();
- // try the other format
- if (PyArg_ParseTuple(args, "O!hh|h:plot", &ImageBuffType, &other, &x, &y, &mode))
- {
- getImageBuff(self)->plot(getImageBuff(other), x, y, mode);
- Py_RETURN_NONE;
- }
- PyErr_Clear();
- // try the last format (BGL buffer)
- if (!PyArg_ParseTuple(args, "O!hhhh|h:plot", &BGL_bufferType, &bglBuffer, &width, &height, &x, &y, &mode))
- {
- PyErr_SetString(PyExc_TypeError, "Expecting ImageBuff or Py buffer or BGL buffer as first argument; width, height next; postion x, y and mode as last arguments");
- return NULL;
- }
- if (testBGLBuffer(bglBuffer, width, height, 4))
- {
- getImageBuff(self)->plot((unsigned char*)bglBuffer->buf.asvoid, width, height, x, y, mode);
- }
- if (PyErr_Occurred())
- return NULL;
- Py_RETURN_NONE;
-}
-
-// methods structure
-static PyMethodDef imageBuffMethods[] = {
- {"load", (PyCFunction)load, METH_VARARGS, "Load image from buffer"},
- {"plot", (PyCFunction)plot, METH_VARARGS, "update image buffer"},
- {NULL}
-};
-// attributes structure
-static PyGetSetDef imageBuffGetSets[] = {
- // attributes from ImageBase class
- {(char*)"valid", (getter)Image_valid, NULL, (char*)"bool to tell if an image is available", NULL},
- {(char*)"image", (getter)Image_getImage, NULL, (char*)"image data", NULL},
- {(char*)"size", (getter)Image_getSize, NULL, (char*)"image size", NULL},
- {(char*)"scale", (getter)Image_getScale, (setter)Image_setScale, (char*)"fast scale of image (near neighbor)", NULL},
- {(char*)"flip", (getter)Image_getFlip, (setter)Image_setFlip, (char*)"flip image vertically", NULL},
- {(char*)"filter", (getter)Image_getFilter, (setter)Image_setFilter, (char*)"pixel filter", NULL},
- {NULL}
-};
-
-
-// define python type
-PyTypeObject ImageBuffType = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "VideoTexture.ImageBuff", /*tp_name*/
- sizeof(PyImage), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- (destructor)Image_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- 0, /*tp_getattr*/
- 0, /*tp_setattr*/
- 0, /*tp_compare*/
- 0, /*tp_repr*/
- 0, /*tp_as_number*/
- 0, /*tp_as_sequence*/
- 0, /*tp_as_mapping*/
- 0, /*tp_hash */
- 0, /*tp_call*/
- 0, /*tp_str*/
- 0, /*tp_getattro*/
- 0, /*tp_setattro*/
- &imageBufferProcs, /*tp_as_buffer*/
- Py_TPFLAGS_DEFAULT, /*tp_flags*/
- "Image source from image buffer", /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- imageBuffMethods, /* tp_methods */
- 0, /* tp_members */
- imageBuffGetSets, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- (initproc)ImageBuff_init, /* tp_init */
- 0, /* tp_alloc */
- Image_allocNew, /* tp_new */
-};
-
diff --git a/source/gameengine/VideoTexture/ImageBuff.h b/source/gameengine/VideoTexture/ImageBuff.h
deleted file mode 100644
index 19299506747..00000000000
--- a/source/gameengine/VideoTexture/ImageBuff.h
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * Copyright (c) 2007 The Zdeno Ash Miklas
- *
- * This source file is part of VideoTexture library
- *
- * Contributor(s):
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file ImageBuff.h
- * \ingroup bgevideotex
- */
-
-#ifndef __IMAGEBUFF_H__
-#define __IMAGEBUFF_H__
-
-
-#include "Common.h"
-
-#include "ImageBase.h"
-
-struct ImBuf;
-
-/// class for image buffer
-class ImageBuff : public ImageBase
-{
-private:
- struct ImBuf *m_imbuf; // temporary structure for buffer manipulation
-public:
- /// constructor
- ImageBuff (void) : ImageBase(true), m_imbuf(NULL) {}
-
- /// destructor
- virtual ~ImageBuff (void);
-
- /// load image from buffer
- void load (unsigned char * img, short width, short height);
- /// clear image with color set on RGB channels and 0xFF on alpha channel
- void clear (short width, short height, unsigned char color);
-
- /// plot image from extern RGBA buffer to image at position x,y using one of IMB_BlendMode
- void plot (unsigned char * img, short width, short height, short x, short y, short mode);
- /// plot image from other ImageBuf to image at position x,y using one of IMB_BlendMode
- void plot (ImageBuff* img, short x, short y, short mode);
-
- /// refresh image - do nothing
- virtual void refresh (void) {}
-};
-
-
-#endif
-
diff --git a/source/gameengine/VideoTexture/ImageMix.cpp b/source/gameengine/VideoTexture/ImageMix.cpp
deleted file mode 100644
index 2de00f5ba05..00000000000
--- a/source/gameengine/VideoTexture/ImageMix.cpp
+++ /dev/null
@@ -1,216 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * Copyright (c) 2007 The Zdeno Ash Miklas
- *
- * This source file is part of VideoTexture library
- *
- * Contributor(s):
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/VideoTexture/ImageMix.cpp
- * \ingroup bgevideotex
- */
-
-
-// implementation
-
-#include "EXP_PyObjectPlus.h"
-#include <structmember.h>
-
-#include "ImageMix.h"
-
-#include "ImageBase.h"
-
-#include "Exception.h"
-
-
-// cast ImageSource pointer to ImageSourceMix
-inline ImageSourceMix *getImageSourceMix(ImageSource *src)
-{ return static_cast<ImageSourceMix*>(src); }
-
-
-// get weight
-short ImageMix::getWeight(const char *id)
-{
- // find source
- ImageSourceList::iterator src = findSource(id);
- // if found, return its weight
- return src != m_sources.end() ? getImageSourceMix(*src)->getWeight() : 0;
-}
-
-// set weight
-bool ImageMix::setWeight(const char *id, short weight)
-{
- // find source
- ImageSourceList::iterator src = findSource(id);
- // if source isn't found, report it
- if (src == m_sources.end()) return false;
- // set its weight
- getImageSourceMix(*src)->setWeight(weight);
- return true;
-}
-
-ExceptionID ImageSizesNotMatch;
-
-ExpDesc ImageSizesNotMatchDesc(ImageSizesNotMatch, "Image sizes of sources are different");
-
-// calculate image from sources and set its availability
-void ImageMix::calcImage(unsigned int texId, double ts)
-{
- // check source sizes
- if (!checkSourceSizes()) THRWEXCP(ImageSizesNotMatch, S_OK);
- // set offsets to image buffers
- for (ImageSourceList::iterator it = m_sources.begin(); it != m_sources.end(); ++it)
- // if image buffer is available
- if ((*it)->getImageBuf() != NULL)
- // set its offset
- getImageSourceMix(*it)->setOffset(m_sources[0]->getImageBuf());
- // otherwise don't calculate image
- else
- return;
- // if there is only single source
- if (m_sources.size() == 1)
- {
- // use single filter
- FilterBase mixFilt;
- // fiter and convert image
- filterImage(mixFilt, m_sources[0]->getImageBuf(), m_sources[0]->getSize());
- }
- // otherwise use mix filter to merge source images
- else
- {
- FilterImageMix mixFilt (m_sources);
- // fiter and convert image
- filterImage(mixFilt, m_sources[0]->getImageBuf(), m_sources[0]->getSize());
- }
-}
-
-
-
-// cast Image pointer to ImageMix
-inline ImageMix * getImageMix(PyImage *self)
-{ return static_cast<ImageMix*>(self->m_image); }
-
-
-// python methods
-
-// get source weight
-static PyObject *getWeight(PyImage *self, PyObject *args)
-{
- // weight
- short weight = 0;
- // get arguments
- char *id;
- if (!PyArg_ParseTuple(args, "s:getWeight", &id))
- return NULL;
- if (self->m_image != NULL)
- // get weight
- weight = getImageMix(self)->getWeight(id);
- // return weight
- return Py_BuildValue("h", weight);
-}
-
-
-// set source weight
-static PyObject *setWeight(PyImage *self, PyObject *args)
-{
- // get arguments
- char *id;
- short weight = 0;
- if (!PyArg_ParseTuple(args, "sh:setWeight", &id, &weight))
- return NULL;
- if (self->m_image != NULL)
- // set weight
- if (!getImageMix(self)->setWeight(id, weight))
- {
- // if not set, report error
- PyErr_SetString(PyExc_RuntimeError, "Invalid id of source");
- return NULL;
- }
- // return none
- Py_RETURN_NONE;
-}
-
-
-// methods structure
-static PyMethodDef imageMixMethods[] = {
- {"getSource", (PyCFunction)Image_getSource, METH_VARARGS, "get image source"},
- {"setSource", (PyCFunction)Image_setSource, METH_VARARGS, "set image source"},
- {"getWeight", (PyCFunction)getWeight, METH_VARARGS, "get image source weight"},
- {"setWeight", (PyCFunction)setWeight, METH_VARARGS, "set image source weight"},
- // methods from ImageBase class
- {"refresh", (PyCFunction)Image_refresh, METH_VARARGS, "Refresh image - invalidate its current content"},
- {NULL}
-};
-// attributes structure
-static PyGetSetDef imageMixGetSets[] = {
- // attributes from ImageBase class
- {(char*)"valid", (getter)Image_valid, NULL, (char*)"bool to tell if an image is available", NULL},
- {(char*)"image", (getter)Image_getImage, NULL, (char*)"image data", NULL},
- {(char*)"size", (getter)Image_getSize, NULL, (char*)"image size", NULL},
- {(char*)"scale", (getter)Image_getScale, (setter)Image_setScale, (char*)"fast scale of image (near neighbor)", NULL},
- {(char*)"flip", (getter)Image_getFlip, (setter)Image_setFlip, (char*)"flip image vertically", NULL},
- {(char*)"filter", (getter)Image_getFilter, (setter)Image_setFilter, (char*)"pixel filter", NULL},
- {NULL}
-};
-
-
-// define python type
-PyTypeObject ImageMixType = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "VideoTexture.ImageMix", /*tp_name*/
- sizeof(PyImage), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- (destructor)Image_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- 0, /*tp_getattr*/
- 0, /*tp_setattr*/
- 0, /*tp_compare*/
- 0, /*tp_repr*/
- 0, /*tp_as_number*/
- 0, /*tp_as_sequence*/
- 0, /*tp_as_mapping*/
- 0, /*tp_hash */
- 0, /*tp_call*/
- 0, /*tp_str*/
- 0, /*tp_getattro*/
- 0, /*tp_setattro*/
- &imageBufferProcs, /*tp_as_buffer*/
- Py_TPFLAGS_DEFAULT, /*tp_flags*/
- "Image mixer", /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- imageMixMethods, /* tp_methods */
- 0, /* tp_members */
- imageMixGetSets, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- (initproc)Image_init<ImageMix>, /* tp_init */
- 0, /* tp_alloc */
- Image_allocNew, /* tp_new */
-};
-
diff --git a/source/gameengine/VideoTexture/ImageMix.h b/source/gameengine/VideoTexture/ImageMix.h
deleted file mode 100644
index 161a8b375ea..00000000000
--- a/source/gameengine/VideoTexture/ImageMix.h
+++ /dev/null
@@ -1,131 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * Copyright (c) 2007 The Zdeno Ash Miklas
- *
- * This source file is part of VideoTexture library
- *
- * Contributor(s):
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file ImageMix.h
- * \ingroup bgevideotex
- */
-
-#ifndef __IMAGEMIX_H__
-#define __IMAGEMIX_H__
-
-
-#include "Common.h"
-
-#include "ImageBase.h"
-#include "FilterBase.h"
-
-
-/// class for source mixing
-class ImageSourceMix : public ImageSource
-{
-public:
- /// constructor
- ImageSourceMix (const char *id) : ImageSource(id), m_offset(0), m_weight(0x100) {}
- /// destructor
- virtual ~ImageSourceMix (void) {}
-
- /// get offset
- long long getOffset (void) { return m_offset; }
- /// set offset
- void setOffset (unsigned int * firstImg) { m_offset = m_image - firstImg; }
-
- /// get weight
- short getWeight (void) { return m_weight; }
- /// set weight
- void setWeight (short weight) { m_weight = weight; }
-
-protected:
- /// buffer offset to the first source buffer
- long long m_offset;
- /// source weight
- short m_weight;
-};
-
-
-/// class for image mixer
-class ImageMix : public ImageBase
-{
-public:
- /// constructor
- ImageMix (void) : ImageBase(false) {}
-
- /// destructor
- virtual ~ImageMix (void) {}
-
- /// get weight
- short getWeight(const char *id);
- /// set weight
- bool setWeight(const char *id, short weight);
-
-protected:
-
- /// create new source
- virtual ImageSource *newSource(const char *id) { return new ImageSourceMix(id); }
-
- /// calculate image from sources and set its availability
- virtual void calcImage (unsigned int texId, double ts);
-};
-
-
-/// pixel filter for image mixer
-class FilterImageMix : public FilterBase
-{
-public:
- /// constructor
- FilterImageMix (ImageSourceList & sources) : m_sources(sources) {}
- /// destructor
- virtual ~FilterImageMix (void) {}
-
-protected:
- /// source list
- ImageSourceList & m_sources;
-
- /// filter pixel, source int buffer
- virtual unsigned int filter (unsigned int * src, short x, short y,
- short * size, unsigned int pixSize, unsigned int val = 0)
- {
- // resulting pixel color
- int color[] = {0, 0, 0, 0};
- // iterate sources
- for (ImageSourceList::iterator it = m_sources.begin(); it != m_sources.end(); ++it)
- {
- // get pointer to mixer source
- ImageSourceMix * mixSrc = static_cast<ImageSourceMix*>(*it);
- // add weighted source pixel to result
- color[0] += mixSrc->getWeight() * (src[mixSrc->getOffset()] & 0xFF);
- color[1] += mixSrc->getWeight() * ((src[mixSrc->getOffset()] >> 8) & 0xFF);
- color[2] += mixSrc->getWeight() * ((src[mixSrc->getOffset()] >> 16) & 0xFF);
- color[3] += mixSrc->getWeight() * ((src[mixSrc->getOffset()] >> 24) & 0xFF);
- }
- // return resulting color
- return ((color[0] >> 8) & 0xFF) | (color[1] & 0xFF00)
- | ((color[2] << 8) & 0xFF0000) | ((color[3] << 16) & 0xFF000000);
- }
-};
-
-
-#endif
-
diff --git a/source/gameengine/VideoTexture/ImageRender.cpp b/source/gameengine/VideoTexture/ImageRender.cpp
deleted file mode 100644
index 57062343b67..00000000000
--- a/source/gameengine/VideoTexture/ImageRender.cpp
+++ /dev/null
@@ -1,946 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * Copyright (c) 2007 The Zdeno Ash Miklas
- *
- * This source file is part of VideoTexture library
- *
- * Contributor(s):
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/VideoTexture/ImageRender.cpp
- * \ingroup bgevideotex
- */
-
-// implementation
-
-#include "EXP_PyObjectPlus.h"
-#include <structmember.h>
-#include <float.h>
-#include <math.h>
-
-
-#include "GPU_glew.h"
-
-#include "KX_PythonInit.h"
-#include "DNA_scene_types.h"
-#include "RAS_CameraData.h"
-#include "RAS_MeshObject.h"
-#include "RAS_Polygon.h"
-#include "RAS_IOffScreen.h"
-#include "RAS_ISync.h"
-#include "BLI_math.h"
-
-#include "ImageRender.h"
-#include "ImageBase.h"
-#include "BlendType.h"
-#include "Exception.h"
-#include "Texture.h"
-
-ExceptionID SceneInvalid, CameraInvalid, ObserverInvalid, OffScreenInvalid;
-ExceptionID MirrorInvalid, MirrorSizeInvalid, MirrorNormalInvalid, MirrorHorizontal, MirrorTooSmall;
-ExpDesc SceneInvalidDesc(SceneInvalid, "Scene object is invalid");
-ExpDesc CameraInvalidDesc(CameraInvalid, "Camera object is invalid");
-ExpDesc ObserverInvalidDesc(ObserverInvalid, "Observer object is invalid");
-ExpDesc OffScreenInvalidDesc(OffScreenInvalid, "Offscreen object is invalid");
-ExpDesc MirrorInvalidDesc(MirrorInvalid, "Mirror object is invalid");
-ExpDesc MirrorSizeInvalidDesc(MirrorSizeInvalid, "Mirror has no vertex or no size");
-ExpDesc MirrorNormalInvalidDesc(MirrorNormalInvalid, "Cannot determine mirror plane");
-ExpDesc MirrorHorizontalDesc(MirrorHorizontal, "Mirror is horizontal in local space");
-ExpDesc MirrorTooSmallDesc(MirrorTooSmall, "Mirror is too small");
-
-// constructor
-ImageRender::ImageRender (KX_Scene *scene, KX_Camera * camera, PyRASOffScreen * offscreen) :
- ImageViewport(offscreen),
- m_render(true),
- m_done(false),
- m_scene(scene),
- m_camera(camera),
- m_owncamera(false),
- m_offscreen(offscreen),
- m_sync(NULL),
- m_observer(NULL),
- m_mirror(NULL),
- m_clip(100.f),
- m_mirrorHalfWidth(0.f),
- m_mirrorHalfHeight(0.f)
-{
- // initialize background color to scene background color as default
- setBackgroundFromScene(m_scene);
- // retrieve rendering objects
- m_engine = KX_GetActiveEngine();
- m_rasterizer = m_engine->GetRasterizer();
- m_canvas = m_engine->GetCanvas();
- // keep a reference to the offscreen buffer
- if (m_offscreen) {
- Py_INCREF(m_offscreen);
- }
-}
-
-// destructor
-ImageRender::~ImageRender (void)
-{
- if (m_owncamera)
- m_camera->Release();
- if (m_sync)
- delete m_sync;
- Py_XDECREF(m_offscreen);
-}
-
-// get background color
-float ImageRender::getBackground (int idx)
-{
- return (idx < 0 || idx > 3) ? 0.0f : m_background[idx] * 255.0f;
-}
-
-// set background color
-void ImageRender::setBackground (float red, float green, float blue, float alpha)
-{
- m_background[0] = (red < 0.0f) ? 0.0f : (red > 255.0f) ? 1.0f : red / 255.0f;
- m_background[1] = (green < 0.0f) ? 0.0f : (green > 255.0f) ? 1.0f : green / 255.0f;
- m_background[2] = (blue < 0.0f) ? 0.0f : (blue > 255.0f) ? 1.0f : blue / 255.0f;
- m_background[3] = (alpha < 0.0f) ? 0.0f : (alpha > 255.0f) ? 1.0f : alpha / 255.0f;
-}
-
-// set background color from scene
-void ImageRender::setBackgroundFromScene (KX_Scene *scene)
-{
- if (scene) {
- const float *background_color = scene->GetWorldInfo()->getBackColorConverted();
- copy_v3_v3(m_background, background_color);
- m_background[3] = 1.0f;
- }
- else {
- const float blue_color[] = {0.0f, 0.0f, 1.0f, 1.0f};
- copy_v4_v4(m_background, blue_color);
- }
-}
-
-
-// capture image from viewport
-void ImageRender::calcViewport (unsigned int texId, double ts, unsigned int format)
-{
- // render the scene from the camera
- if (!m_done) {
- if (!Render()) {
- return;
- }
- }
- else if (m_offscreen) {
- m_offscreen->ofs->Bind(RAS_IOffScreen::RAS_OFS_BIND_READ);
- }
- // wait until all render operations are completed
- WaitSync();
- // get image from viewport (or FBO)
- ImageViewport::calcViewport(texId, ts, format);
- if (m_offscreen) {
- m_offscreen->ofs->Unbind();
- }
-}
-
-bool ImageRender::Render()
-{
- RAS_FrameFrustum frustum;
-
- if (!m_render ||
- m_rasterizer->GetDrawingMode() != RAS_IRasterizer::KX_TEXTURED || // no need for texture
- m_camera->GetViewport() || // camera must be inactive
- m_camera == m_scene->GetActiveCamera())
- {
- // no need to compute texture in non texture rendering
- return false;
- }
-
- if (!m_scene->IsShadowDone())
- m_engine->RenderShadowBuffers(m_scene);
-
- if (m_mirror)
- {
- // mirror mode, compute camera frustum, position and orientation
- // convert mirror position and normal in world space
- const MT_Matrix3x3 & mirrorObjWorldOri = m_mirror->GetSGNode()->GetWorldOrientation();
- const MT_Point3 & mirrorObjWorldPos = m_mirror->GetSGNode()->GetWorldPosition();
- const MT_Vector3 & mirrorObjWorldScale = m_mirror->GetSGNode()->GetWorldScaling();
- MT_Point3 mirrorWorldPos =
- mirrorObjWorldPos + mirrorObjWorldScale * (mirrorObjWorldOri * m_mirrorPos);
- MT_Vector3 mirrorWorldZ = mirrorObjWorldOri * m_mirrorZ;
- // get observer world position
- const MT_Point3 & observerWorldPos = m_observer->GetSGNode()->GetWorldPosition();
- // get plane D term = mirrorPos . normal
- MT_Scalar mirrorPlaneDTerm = mirrorWorldPos.dot(mirrorWorldZ);
- // compute distance of observer to mirror = D - observerPos . normal
- MT_Scalar observerDistance = mirrorPlaneDTerm - observerWorldPos.dot(mirrorWorldZ);
- // if distance < 0.01 => observer is on wrong side of mirror, don't render
- if (observerDistance < 0.01)
- return false;
- // set camera world position = observerPos + normal * 2 * distance
- MT_Point3 cameraWorldPos = observerWorldPos + (MT_Scalar(2.0)*observerDistance)*mirrorWorldZ;
- m_camera->GetSGNode()->SetLocalPosition(cameraWorldPos);
- // set camera orientation: z=normal, y=mirror_up in world space, x= y x z
- MT_Vector3 mirrorWorldY = mirrorObjWorldOri * m_mirrorY;
- MT_Vector3 mirrorWorldX = mirrorObjWorldOri * m_mirrorX;
- MT_Matrix3x3 cameraWorldOri(
- mirrorWorldX[0], mirrorWorldY[0], mirrorWorldZ[0],
- mirrorWorldX[1], mirrorWorldY[1], mirrorWorldZ[1],
- mirrorWorldX[2], mirrorWorldY[2], mirrorWorldZ[2]);
- m_camera->GetSGNode()->SetLocalOrientation(cameraWorldOri);
- m_camera->GetSGNode()->UpdateWorldData(0.0);
- // compute camera frustum:
- // get position of mirror relative to camera: offset = mirrorPos-cameraPos
- MT_Vector3 mirrorOffset = mirrorWorldPos - cameraWorldPos;
- // convert to camera orientation
- mirrorOffset = mirrorOffset * cameraWorldOri;
- // scale mirror size to world scale:
- // get closest local axis for mirror Y and X axis and scale height and width by local axis scale
- MT_Scalar x, y;
- x = fabs(m_mirrorY[0]);
- y = fabs(m_mirrorY[1]);
- float height = (x > y) ?
- ((x > fabs(m_mirrorY[2])) ? mirrorObjWorldScale[0] : mirrorObjWorldScale[2]):
- ((y > fabs(m_mirrorY[2])) ? mirrorObjWorldScale[1] : mirrorObjWorldScale[2]);
- x = fabs(m_mirrorX[0]);
- y = fabs(m_mirrorX[1]);
- float width = (x > y) ?
- ((x > fabs(m_mirrorX[2])) ? mirrorObjWorldScale[0] : mirrorObjWorldScale[2]):
- ((y > fabs(m_mirrorX[2])) ? mirrorObjWorldScale[1] : mirrorObjWorldScale[2]);
- width *= m_mirrorHalfWidth;
- height *= m_mirrorHalfHeight;
- // left = offsetx-width
- // right = offsetx+width
- // top = offsety+height
- // bottom = offsety-height
- // near = -offsetz
- // far = near+100
- frustum.x1 = mirrorOffset[0]-width;
- frustum.x2 = mirrorOffset[0]+width;
- frustum.y1 = mirrorOffset[1]-height;
- frustum.y2 = mirrorOffset[1]+height;
- frustum.camnear = -mirrorOffset[2];
- frustum.camfar = -mirrorOffset[2]+m_clip;
- }
- // Store settings to be restored later
- const RAS_IRasterizer::StereoMode stereomode = m_rasterizer->GetStereoMode();
- RAS_Rect area = m_canvas->GetWindowArea();
-
- // The screen area that ImageViewport will copy is also the rendering zone
- if (m_offscreen) {
- // bind the fbo and set the viewport to full size
- m_offscreen->ofs->Bind(RAS_IOffScreen::RAS_OFS_BIND_RENDER);
- // this is needed to stop crashing in canvas check
- m_canvas->UpdateViewPort(0, 0, m_offscreen->ofs->GetWidth(), m_offscreen->ofs->GetHeight());
- }
- else {
- m_canvas->SetViewPort(m_position[0], m_position[1], m_position[0]+m_capSize[0]-1, m_position[1]+m_capSize[1]-1);
- }
- m_canvas->ClearColor(m_background[0], m_background[1], m_background[2], m_background[3]);
- m_canvas->ClearBuffer(RAS_ICanvas::COLOR_BUFFER|RAS_ICanvas::DEPTH_BUFFER);
- m_rasterizer->BeginFrame(m_engine->GetClockTime());
- m_scene->GetWorldInfo()->UpdateWorldSettings();
- m_rasterizer->SetAuxilaryClientInfo(m_scene);
- m_rasterizer->DisplayFog();
- // matrix calculation, don't apply any of the stereo mode
- m_rasterizer->SetStereoMode(RAS_IRasterizer::RAS_STEREO_NOSTEREO);
- if (m_mirror)
- {
- // frustum was computed above
- // get frustum matrix and set projection matrix
- MT_Matrix4x4 projmat = m_rasterizer->GetFrustumMatrix(
- frustum.x1, frustum.x2, frustum.y1, frustum.y2, frustum.camnear, frustum.camfar);
-
- m_camera->SetProjectionMatrix(projmat);
- }
- else if (m_camera->hasValidProjectionMatrix()) {
- m_rasterizer->SetProjectionMatrix(m_camera->GetProjectionMatrix());
- }
- else {
- float lens = m_camera->GetLens();
- float sensor_x = m_camera->GetSensorWidth();
- float sensor_y = m_camera->GetSensorHeight();
- float shift_x = m_camera->GetShiftHorizontal();
- float shift_y = m_camera->GetShiftVertical();
- bool orthographic = !m_camera->GetCameraData()->m_perspective;
- float nearfrust = m_camera->GetCameraNear();
- float farfrust = m_camera->GetCameraFar();
- float aspect_ratio = 1.0f;
- Scene *blenderScene = m_scene->GetBlenderScene();
- MT_Matrix4x4 projmat;
-
- // compute the aspect ratio from frame blender scene settings so that render to texture
- // works the same in Blender and in Blender player
- if (blenderScene->r.ysch != 0)
- aspect_ratio = float(blenderScene->r.xsch*blenderScene->r.xasp) / float(blenderScene->r.ysch*blenderScene->r.yasp);
-
- if (orthographic) {
-
- RAS_FramingManager::ComputeDefaultOrtho(
- nearfrust,
- farfrust,
- m_camera->GetScale(),
- aspect_ratio,
- m_camera->GetSensorFit(),
- shift_x,
- shift_y,
- frustum
- );
-
- projmat = m_rasterizer->GetOrthoMatrix(
- frustum.x1, frustum.x2, frustum.y1, frustum.y2, frustum.camnear, frustum.camfar);
- }
- else {
- RAS_FramingManager::ComputeDefaultFrustum(
- nearfrust,
- farfrust,
- lens,
- sensor_x,
- sensor_y,
- RAS_SENSORFIT_AUTO,
- shift_x,
- shift_y,
- aspect_ratio,
- frustum);
-
- projmat = m_rasterizer->GetFrustumMatrix(
- frustum.x1, frustum.x2, frustum.y1, frustum.y2, frustum.camnear, frustum.camfar);
- }
- m_camera->SetProjectionMatrix(projmat);
- }
-
- MT_Transform camtrans(m_camera->GetWorldToCamera());
- MT_Matrix4x4 viewmat(camtrans);
-
- m_rasterizer->SetViewMatrix(viewmat, m_camera->NodeGetWorldOrientation(), m_camera->NodeGetWorldPosition(), m_camera->NodeGetLocalScaling(), m_camera->GetCameraData()->m_perspective);
- m_camera->SetModelviewMatrix(viewmat);
- // restore the stereo mode now that the matrix is computed
- m_rasterizer->SetStereoMode(stereomode);
-
- if (m_rasterizer->Stereo()) {
- // stereo mode change render settings that disturb this render, cancel them all
- // we don't need to restore them as they are set before each frame render.
- glDrawBuffer(GL_BACK_LEFT);
- glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
- glDisable(GL_POLYGON_STIPPLE);
- }
-
- m_scene->CalculateVisibleMeshes(m_rasterizer,m_camera);
-
- m_engine->UpdateAnimations(m_scene);
-
- m_scene->RenderBuckets(camtrans, m_rasterizer);
-
- m_scene->RenderFonts();
-
- // restore the canvas area now that the render is completed
- m_canvas->GetWindowArea() = area;
- m_canvas->EndFrame();
-
- // In case multisample is active, blit the FBO
- if (m_offscreen)
- m_offscreen->ofs->Blit();
- // end of all render operations, let's create a sync object just in case
- if (m_sync) {
- // a sync from a previous render, should not happen
- delete m_sync;
- m_sync = NULL;
- }
- m_sync = m_rasterizer->CreateSync(RAS_ISync::RAS_SYNC_TYPE_FENCE);
- // remember that we have done render
- m_done = true;
- // the image is not available at this stage
- m_avail = false;
- return true;
-}
-
-void ImageRender::Unbind()
-{
- if (m_offscreen)
- {
- m_offscreen->ofs->Unbind();
- }
-}
-
-void ImageRender::WaitSync()
-{
- if (m_sync) {
- m_sync->Wait();
- // done with it, deleted it
- delete m_sync;
- m_sync = NULL;
- }
- if (m_offscreen) {
- // this is needed to finalize the image if the target is a texture
- m_offscreen->ofs->MipMap();
- }
- // all rendered operation done and complete, invalidate render for next time
- m_done = false;
-}
-
-// cast Image pointer to ImageRender
-inline ImageRender * getImageRender (PyImage *self)
-{ return static_cast<ImageRender*>(self->m_image); }
-
-
-// python methods
-
-// Blender Scene type
-static BlendType<KX_Scene> sceneType ("KX_Scene");
-// Blender Camera type
-static BlendType<KX_Camera> cameraType ("KX_Camera");
-
-
-// object initialization
-static int ImageRender_init(PyObject *pySelf, PyObject *args, PyObject *kwds)
-{
- // parameters - scene object
- PyObject *scene;
- // camera object
- PyObject *camera;
- // offscreen buffer object
- PyRASOffScreen *offscreen = NULL;
- // parameter keywords
- static const char *kwlist[] = {"sceneObj", "cameraObj", "ofsObj", NULL};
- // get parameters
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO|O",
- const_cast<char**>(kwlist), &scene, &camera, &offscreen))
- return -1;
- try
- {
- // get scene pointer
- KX_Scene * scenePtr (NULL);
- if (scene != NULL) scenePtr = sceneType.checkType(scene);
- // throw exception if scene is not available
- if (scenePtr == NULL) THRWEXCP(SceneInvalid, S_OK);
-
- // get camera pointer
- KX_Camera * cameraPtr (NULL);
- if (camera != NULL) cameraPtr = cameraType.checkType(camera);
- // throw exception if camera is not available
- if (cameraPtr == NULL) THRWEXCP(CameraInvalid, S_OK);
-
- if (offscreen) {
- if (Py_TYPE(offscreen) != &PyRASOffScreen_Type) {
- THRWEXCP(OffScreenInvalid, S_OK);
- }
- }
- // get pointer to image structure
- PyImage *self = reinterpret_cast<PyImage*>(pySelf);
- // create source object
- if (self->m_image != NULL) delete self->m_image;
- self->m_image = new ImageRender(scenePtr, cameraPtr, offscreen);
- }
- catch (Exception & exp)
- {
- exp.report();
- return -1;
- }
- // initialization succeded
- return 0;
-}
-
-static PyObject *ImageRender_refresh(PyImage *self, PyObject *args)
-{
- ImageRender *imageRender = getImageRender(self);
-
- if (!imageRender) {
- PyErr_SetString(PyExc_TypeError, "Incomplete ImageRender() object");
- return NULL;
- }
- if (PyArg_ParseTuple(args, "")) {
- // refresh called with no argument.
- // For other image objects it simply invalidates the image buffer
- // For ImageRender it triggers a render+sync
- // Note that this only makes sense when doing offscreen render on texture
- if (!imageRender->isDone()) {
- if (!imageRender->Render()) {
- Py_RETURN_FALSE;
- }
- // as we are not trying to read the pixels, just unbind
- imageRender->Unbind();
- }
- // wait until all render operations are completed
- // this will also finalize the texture
- imageRender->WaitSync();
- Py_RETURN_TRUE;
- }
- else {
- // fallback on standard processing
- PyErr_Clear();
- return Image_refresh(self, args);
- }
-}
-
-// refresh image
-static PyObject *ImageRender_render(PyImage *self)
-{
- ImageRender *imageRender = getImageRender(self);
-
- if (!imageRender) {
- PyErr_SetString(PyExc_TypeError, "Incomplete ImageRender() object");
- return NULL;
- }
- if (!imageRender->Render()) {
- Py_RETURN_FALSE;
- }
- // we are not reading the pixels now, unbind
- imageRender->Unbind();
- Py_RETURN_TRUE;
-}
-
-
-// get background color
-static PyObject *getBackground (PyImage *self, void *closure)
-{
- return Py_BuildValue("[ffff]",
- getImageRender(self)->getBackground(0),
- getImageRender(self)->getBackground(1),
- getImageRender(self)->getBackground(2),
- getImageRender(self)->getBackground(3));
-}
-
-// set color
-static int setBackground(PyImage *self, PyObject *value, void *closure)
-{
- // check validity of parameter
- if (value == NULL || !PySequence_Check(value) || PySequence_Size(value) != 4
- || (!PyFloat_Check(PySequence_Fast_GET_ITEM(value, 0)) && !PyLong_Check(PySequence_Fast_GET_ITEM(value, 0)))
- || (!PyFloat_Check(PySequence_Fast_GET_ITEM(value, 1)) && !PyLong_Check(PySequence_Fast_GET_ITEM(value, 1)))
- || (!PyFloat_Check(PySequence_Fast_GET_ITEM(value, 2)) && !PyLong_Check(PySequence_Fast_GET_ITEM(value, 2)))
- || (!PyFloat_Check(PySequence_Fast_GET_ITEM(value, 3)) && !PyLong_Check(PySequence_Fast_GET_ITEM(value, 3)))) {
-
- PyErr_SetString(PyExc_TypeError, "The value must be a sequence of 4 floats or ints between 0.0 and 255.0");
- return -1;
- }
- // set background color
- getImageRender(self)->setBackground(
- PyFloat_AsDouble(PySequence_Fast_GET_ITEM(value, 0)),
- PyFloat_AsDouble(PySequence_Fast_GET_ITEM(value, 1)),
- PyFloat_AsDouble(PySequence_Fast_GET_ITEM(value, 2)),
- PyFloat_AsDouble(PySequence_Fast_GET_ITEM(value, 3)));
- // success
- return 0;
-}
-
-
-// methods structure
-static PyMethodDef imageRenderMethods[] =
-{ // methods from ImageBase class
- {"refresh", (PyCFunction)ImageRender_refresh, METH_VARARGS, "Refresh image - invalidate its current content after optionally transferring its content to a target buffer"},
- {"render", (PyCFunction)ImageRender_render, METH_NOARGS, "Render scene - run before refresh() to performs asynchronous render"},
- {NULL}
-};
-// attributes structure
-static PyGetSetDef imageRenderGetSets[] =
-{
- {(char*)"background", (getter)getBackground, (setter)setBackground, (char*)"background color", NULL},
- // attribute from ImageViewport
- {(char*)"capsize", (getter)ImageViewport_getCaptureSize, (setter)ImageViewport_setCaptureSize, (char*)"size of render area", NULL},
- {(char*)"alpha", (getter)ImageViewport_getAlpha, (setter)ImageViewport_setAlpha, (char*)"use alpha in texture", NULL},
- {(char*)"whole", (getter)ImageViewport_getWhole, (setter)ImageViewport_setWhole, (char*)"use whole viewport to render", NULL},
- // attributes from ImageBase class
- {(char*)"valid", (getter)Image_valid, NULL, (char*)"bool to tell if an image is available", NULL},
- {(char*)"image", (getter)Image_getImage, NULL, (char*)"image data", NULL},
- {(char*)"size", (getter)Image_getSize, NULL, (char*)"image size", NULL},
- {(char*)"scale", (getter)Image_getScale, (setter)Image_setScale, (char*)"fast scale of image (near neighbor)", NULL},
- {(char*)"flip", (getter)Image_getFlip, (setter)Image_setFlip, (char*)"flip image vertically", NULL},
- {(char*)"zbuff", (getter)Image_getZbuff, (setter)Image_setZbuff, (char*)"use depth buffer as texture", NULL},
- {(char*)"depth", (getter)Image_getDepth, (setter)Image_setDepth, (char*)"get depth information from z-buffer using unsigned int precision", NULL},
- {(char*)"filter", (getter)Image_getFilter, (setter)Image_setFilter, (char*)"pixel filter", NULL},
- {NULL}
-};
-
-
-// define python type
-PyTypeObject ImageRenderType = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "VideoTexture.ImageRender", /*tp_name*/
- sizeof(PyImage), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- (destructor)Image_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- 0, /*tp_getattr*/
- 0, /*tp_setattr*/
- 0, /*tp_compare*/
- 0, /*tp_repr*/
- 0, /*tp_as_number*/
- 0, /*tp_as_sequence*/
- 0, /*tp_as_mapping*/
- 0, /*tp_hash */
- 0, /*tp_call*/
- 0, /*tp_str*/
- 0, /*tp_getattro*/
- 0, /*tp_setattro*/
- &imageBufferProcs, /*tp_as_buffer*/
- Py_TPFLAGS_DEFAULT, /*tp_flags*/
- "Image source from render", /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- imageRenderMethods, /* tp_methods */
- 0, /* tp_members */
- imageRenderGetSets, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- (initproc)ImageRender_init, /* tp_init */
- 0, /* tp_alloc */
- Image_allocNew, /* tp_new */
-};
-
-// object initialization
-static int ImageMirror_init(PyObject *pySelf, PyObject *args, PyObject *kwds)
-{
- // parameters - scene object
- PyObject *scene;
- // reference object for mirror
- PyObject *observer;
- // object holding the mirror
- PyObject *mirror;
- // material of the mirror
- short materialID = 0;
- // parameter keywords
- static const char *kwlist[] = {"scene", "observer", "mirror", "material", NULL};
- // get parameters
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "OOO|h",
- const_cast<char**>(kwlist), &scene, &observer, &mirror, &materialID))
- return -1;
- try
- {
- // get scene pointer
- KX_Scene * scenePtr (NULL);
- if (scene != NULL && PyObject_TypeCheck(scene, &KX_Scene::Type))
- scenePtr = static_cast<KX_Scene*>BGE_PROXY_REF(scene);
- else
- THRWEXCP(SceneInvalid, S_OK);
-
- if (scenePtr==NULL) /* in case the python proxy reference is invalid */
- THRWEXCP(SceneInvalid, S_OK);
-
- // get observer pointer
- KX_GameObject * observerPtr (NULL);
- if (observer != NULL && PyObject_TypeCheck(observer, &KX_GameObject::Type))
- observerPtr = static_cast<KX_GameObject*>BGE_PROXY_REF(observer);
- else if (observer != NULL && PyObject_TypeCheck(observer, &KX_Camera::Type))
- observerPtr = static_cast<KX_Camera*>BGE_PROXY_REF(observer);
- else
- THRWEXCP(ObserverInvalid, S_OK);
-
- if (observerPtr==NULL) /* in case the python proxy reference is invalid */
- THRWEXCP(ObserverInvalid, S_OK);
-
- // get mirror pointer
- KX_GameObject * mirrorPtr (NULL);
- if (mirror != NULL && PyObject_TypeCheck(mirror, &KX_GameObject::Type))
- mirrorPtr = static_cast<KX_GameObject*>BGE_PROXY_REF(mirror);
- else
- THRWEXCP(MirrorInvalid, S_OK);
-
- if (mirrorPtr==NULL) /* in case the python proxy reference is invalid */
- THRWEXCP(MirrorInvalid, S_OK);
-
- // locate the material in the mirror
- RAS_IPolyMaterial * material = getMaterial(mirror, materialID);
- if (material == NULL)
- THRWEXCP(MaterialNotAvail, S_OK);
-
- // get pointer to image structure
- PyImage *self = reinterpret_cast<PyImage*>(pySelf);
-
- // create source object
- if (self->m_image != NULL)
- {
- delete self->m_image;
- self->m_image = NULL;
- }
- self->m_image = new ImageRender(scenePtr, observerPtr, mirrorPtr, material);
- }
- catch (Exception & exp)
- {
- exp.report();
- return -1;
- }
- // initialization succeeded
- return 0;
-}
-
-// get background color
-static PyObject *getClip (PyImage *self, void *closure)
-{
- return PyFloat_FromDouble(getImageRender(self)->getClip());
-}
-
-// set clip
-static int setClip(PyImage *self, PyObject *value, void *closure)
-{
- // check validity of parameter
- double clip;
- if (value == NULL || !PyFloat_Check(value) || (clip = PyFloat_AsDouble(value)) < 0.01 || clip > 5000.0)
- {
- PyErr_SetString(PyExc_TypeError, "The value must be an float between 0.01 and 5000");
- return -1;
- }
- // set background color
- getImageRender(self)->setClip(float(clip));
- // success
- return 0;
-}
-
-// attributes structure
-static PyGetSetDef imageMirrorGetSets[] =
-{
- {(char*)"clip", (getter)getClip, (setter)setClip, (char*)"clipping distance", NULL},
- // attribute from ImageRender
- {(char*)"background", (getter)getBackground, (setter)setBackground, (char*)"background color", NULL},
- // attribute from ImageViewport
- {(char*)"capsize", (getter)ImageViewport_getCaptureSize, (setter)ImageViewport_setCaptureSize, (char*)"size of render area", NULL},
- {(char*)"alpha", (getter)ImageViewport_getAlpha, (setter)ImageViewport_setAlpha, (char*)"use alpha in texture", NULL},
- {(char*)"whole", (getter)ImageViewport_getWhole, (setter)ImageViewport_setWhole, (char*)"use whole viewport to render", NULL},
- // attributes from ImageBase class
- {(char*)"valid", (getter)Image_valid, NULL, (char*)"bool to tell if an image is available", NULL},
- {(char*)"image", (getter)Image_getImage, NULL, (char*)"image data", NULL},
- {(char*)"size", (getter)Image_getSize, NULL, (char*)"image size", NULL},
- {(char*)"scale", (getter)Image_getScale, (setter)Image_setScale, (char*)"fast scale of image (near neighbor)", NULL},
- {(char*)"flip", (getter)Image_getFlip, (setter)Image_setFlip, (char*)"flip image vertically", NULL},
- {(char*)"zbuff", (getter)Image_getZbuff, (setter)Image_setZbuff, (char*)"use depth buffer as texture", NULL},
- {(char*)"depth", (getter)Image_getDepth, (setter)Image_setDepth, (char*)"get depth information from z-buffer using unsigned int precision", NULL},
- {(char*)"filter", (getter)Image_getFilter, (setter)Image_setFilter, (char*)"pixel filter", NULL},
- {NULL}
-};
-
-
-// constructor
-ImageRender::ImageRender (KX_Scene *scene, KX_GameObject *observer, KX_GameObject *mirror, RAS_IPolyMaterial *mat) :
- ImageViewport(),
- m_render(false),
- m_done(false),
- m_scene(scene),
- m_offscreen(NULL),
- m_sync(NULL),
- m_observer(observer),
- m_mirror(mirror),
- m_clip(100.f)
-{
- // this constructor is used for automatic planar mirror
- // create a camera, take all data by default, in any case we will recompute the frustum on each frame
- RAS_CameraData camdata;
- vector<RAS_TexVert*> mirrorVerts;
- vector<RAS_TexVert*>::iterator it;
- float mirrorArea = 0.f;
- float mirrorNormal[3] = {0.f, 0.f, 0.f};
- float mirrorUp[3];
- float dist, vec[3], axis[3];
- float zaxis[3] = {0.f, 0.f, 1.f};
- float yaxis[3] = {0.f, 1.f, 0.f};
- float mirrorMat[3][3];
- float left, right, top, bottom, back;
- // make sure this camera will delete its node
- m_camera= new KX_Camera(scene, KX_Scene::m_callbacks, camdata, true, true);
- m_camera->SetName("__mirror__cam__");
- // don't add the camera to the scene object list, it doesn't need to be accessible
- m_owncamera = true;
- // retrieve rendering objects
- m_engine = KX_GetActiveEngine();
- m_rasterizer = m_engine->GetRasterizer();
- m_canvas = m_engine->GetCanvas();
- // locate the vertex assigned to mat and do following calculation in mesh coordinates
- for (int meshIndex = 0; meshIndex < mirror->GetMeshCount(); meshIndex++)
- {
- RAS_MeshObject* mesh = mirror->GetMesh(meshIndex);
- int numPolygons = mesh->NumPolygons();
- for (int polygonIndex=0; polygonIndex < numPolygons; polygonIndex++)
- {
- RAS_Polygon* polygon = mesh->GetPolygon(polygonIndex);
- if (polygon->GetMaterial()->GetPolyMaterial() == mat)
- {
- RAS_TexVert *v1, *v2, *v3, *v4;
- float normal[3];
- float area;
- // this polygon is part of the mirror
- v1 = polygon->GetVertex(0);
- v2 = polygon->GetVertex(1);
- v3 = polygon->GetVertex(2);
- mirrorVerts.push_back(v1);
- mirrorVerts.push_back(v2);
- mirrorVerts.push_back(v3);
- if (polygon->VertexCount() == 4) {
- v4 = polygon->GetVertex(3);
- mirrorVerts.push_back(v4);
- area = normal_quad_v3(normal,(float*)v1->getXYZ(), (float*)v2->getXYZ(), (float*)v3->getXYZ(), (float*)v4->getXYZ());
- }
- else {
- area = normal_tri_v3(normal,(float*)v1->getXYZ(), (float*)v2->getXYZ(), (float*)v3->getXYZ());
- }
- area = fabs(area);
- mirrorArea += area;
- mul_v3_fl(normal, area);
- add_v3_v3v3(mirrorNormal, mirrorNormal, normal);
- }
- }
- }
- if (mirrorVerts.size() == 0 || mirrorArea < FLT_EPSILON)
- {
- // no vertex or zero size mirror
- THRWEXCP(MirrorSizeInvalid, S_OK);
- }
- // compute average normal of mirror faces
- mul_v3_fl(mirrorNormal, 1.0f/mirrorArea);
- if (normalize_v3(mirrorNormal) == 0.f)
- {
- // no normal
- THRWEXCP(MirrorNormalInvalid, S_OK);
- }
- // the mirror plane has an equation of the type ax+by+cz = d where (a,b,c) is the normal vector
- // if the mirror is more vertical then horizontal, the Z axis is the up direction.
- // otherwise the Y axis is the up direction.
- // If the mirror is not perfectly vertical(horizontal), the Z(Y) axis projection on the mirror
- // plan by the normal will be the up direction.
- if (fabsf(mirrorNormal[2]) > fabsf(mirrorNormal[1]) &&
- fabsf(mirrorNormal[2]) > fabsf(mirrorNormal[0]))
- {
- // the mirror is more horizontal than vertical
- copy_v3_v3(axis, yaxis);
- }
- else
- {
- // the mirror is more vertical than horizontal
- copy_v3_v3(axis, zaxis);
- }
- dist = dot_v3v3(mirrorNormal, axis);
- if (fabsf(dist) < FLT_EPSILON)
- {
- // the mirror is already fully aligned with up axis
- copy_v3_v3(mirrorUp, axis);
- }
- else
- {
- // projection of axis to mirror plane through normal
- copy_v3_v3(vec, mirrorNormal);
- mul_v3_fl(vec, dist);
- sub_v3_v3v3(mirrorUp, axis, vec);
- if (normalize_v3(mirrorUp) == 0.f)
- {
- // should not happen
- THRWEXCP(MirrorHorizontal, S_OK);
- return;
- }
- }
- // compute rotation matrix between local coord and mirror coord
- // to match camera orientation, we select mirror z = -normal, y = up, x = y x z
- negate_v3_v3(mirrorMat[2], mirrorNormal);
- copy_v3_v3(mirrorMat[1], mirrorUp);
- cross_v3_v3v3(mirrorMat[0], mirrorMat[1], mirrorMat[2]);
- // transpose to make it a orientation matrix from local space to mirror space
- transpose_m3(mirrorMat);
- // transform all vertex to plane coordinates and determine mirror position
- left = FLT_MAX;
- right = -FLT_MAX;
- bottom = FLT_MAX;
- top = -FLT_MAX;
- back = -FLT_MAX; // most backward vertex (=highest Z coord in mirror space)
- for (it = mirrorVerts.begin(); it != mirrorVerts.end(); it++)
- {
- copy_v3_v3(vec, (float*)(*it)->getXYZ());
- mul_m3_v3(mirrorMat, vec);
- if (vec[0] < left)
- left = vec[0];
- if (vec[0] > right)
- right = vec[0];
- if (vec[1] < bottom)
- bottom = vec[1];
- if (vec[1] > top)
- top = vec[1];
- if (vec[2] > back)
- back = vec[2];
- }
- // now store this information in the object for later rendering
- m_mirrorHalfWidth = (right-left)*0.5f;
- m_mirrorHalfHeight = (top-bottom)*0.5f;
- if (m_mirrorHalfWidth < 0.01f || m_mirrorHalfHeight < 0.01f)
- {
- // mirror too small
- THRWEXCP(MirrorTooSmall, S_OK);
- }
- // mirror position in mirror coord
- vec[0] = (left+right)*0.5f;
- vec[1] = (top+bottom)*0.5f;
- vec[2] = back;
- // convert it in local space: transpose again the matrix to get back to mirror to local transform
- transpose_m3(mirrorMat);
- mul_m3_v3(mirrorMat, vec);
- // mirror position in local space
- m_mirrorPos.setValue(vec[0], vec[1], vec[2]);
- // mirror normal vector (pointed towards the back of the mirror) in local space
- m_mirrorZ.setValue(-mirrorNormal[0], -mirrorNormal[1], -mirrorNormal[2]);
- m_mirrorY.setValue(mirrorUp[0], mirrorUp[1], mirrorUp[2]);
- m_mirrorX = m_mirrorY.cross(m_mirrorZ);
- m_render = true;
-
- // set mirror background color to scene background color as default
- setBackgroundFromScene(m_scene);
-}
-
-
-
-
-// define python type
-PyTypeObject ImageMirrorType = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "VideoTexture.ImageMirror", /*tp_name*/
- sizeof(PyImage), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- (destructor)Image_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- 0, /*tp_getattr*/
- 0, /*tp_setattr*/
- 0, /*tp_compare*/
- 0, /*tp_repr*/
- 0, /*tp_as_number*/
- 0, /*tp_as_sequence*/
- 0, /*tp_as_mapping*/
- 0, /*tp_hash */
- 0, /*tp_call*/
- 0, /*tp_str*/
- 0, /*tp_getattro*/
- 0, /*tp_setattro*/
- &imageBufferProcs, /*tp_as_buffer*/
- Py_TPFLAGS_DEFAULT, /*tp_flags*/
- "Image source from mirror", /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- imageRenderMethods, /* tp_methods */
- 0, /* tp_members */
- imageMirrorGetSets, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- (initproc)ImageMirror_init, /* tp_init */
- 0, /* tp_alloc */
- Image_allocNew, /* tp_new */
-};
-
-
diff --git a/source/gameengine/VideoTexture/ImageRender.h b/source/gameengine/VideoTexture/ImageRender.h
deleted file mode 100644
index d062db44348..00000000000
--- a/source/gameengine/VideoTexture/ImageRender.h
+++ /dev/null
@@ -1,125 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * Copyright (c) 2007 The Zdeno Ash Miklas
- *
- * This source file is part of VideoTexture library
- *
- * Contributor(s):
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file ImageRender.h
- * \ingroup bgevideotex
- */
-
-#ifndef __IMAGERENDER_H__
-#define __IMAGERENDER_H__
-
-
-#include "Common.h"
-
-#include "KX_Scene.h"
-#include "KX_Camera.h"
-#include "DNA_screen_types.h"
-#include "RAS_ICanvas.h"
-#include "RAS_IRasterizer.h"
-#include "RAS_IOffScreen.h"
-#include "RAS_ISync.h"
-
-#include "ImageViewport.h"
-
-
-/// class for render 3d scene
-class ImageRender : public ImageViewport
-{
-public:
- /// constructor
- ImageRender(KX_Scene *scene, KX_Camera *camera, PyRASOffScreen *offscreen);
- ImageRender(KX_Scene *scene, KX_GameObject *observer, KX_GameObject *mirror, RAS_IPolyMaterial * mat);
-
- /// destructor
- virtual ~ImageRender (void);
-
- /// get background color
- float getBackground (int idx);
- /// set background color
- void setBackground (float red, float green, float blue, float alpha);
-
- /// clipping distance
- float getClip (void) { return m_clip; }
- /// set whole buffer use
- void setClip (float clip) { m_clip = clip; }
- /// render status
- bool isDone() { return m_done; }
- /// render frame (public so that it is accessible from python)
- bool Render();
- /// in case fbo is used, method to unbind
- void Unbind();
- /// wait for render to complete
- void WaitSync();
-
-protected:
- /// true if ready to render
- bool m_render;
- /// is render done already?
- bool m_done;
- /// rendered scene
- KX_Scene * m_scene;
- /// camera for render
- KX_Camera * m_camera;
- /// do we own the camera?
- bool m_owncamera;
- /// if offscreen render
- PyRASOffScreen *m_offscreen;
- /// object to synchronize render even if no buffer transfer
- RAS_ISync *m_sync;
- /// for mirror operation
- KX_GameObject * m_observer;
- KX_GameObject * m_mirror;
- float m_clip; // clipping distance
- float m_mirrorHalfWidth; // mirror width in mirror space
- float m_mirrorHalfHeight; // mirror height in mirror space
- MT_Point3 m_mirrorPos; // mirror center position in local space
- MT_Vector3 m_mirrorZ; // mirror Z axis in local space
- MT_Vector3 m_mirrorY; // mirror Y axis in local space
- MT_Vector3 m_mirrorX; // mirror X axis in local space
- /// canvas
- RAS_ICanvas* m_canvas;
- /// rasterizer
- RAS_IRasterizer* m_rasterizer;
- /// engine
- KX_KetsjiEngine* m_engine;
-
- /// background color
- float m_background[4];
-
-
- /// render 3d scene to image
- virtual void calcImage (unsigned int texId, double ts) { calcViewport(texId, ts, GL_RGBA); }
-
- /// render 3d scene to image
- virtual void calcViewport (unsigned int texId, double ts, unsigned int format);
-
- void setBackgroundFromScene(KX_Scene *scene);
- void SetWorldSettings(KX_WorldInfo* wi);
-};
-
-
-#endif
-
diff --git a/source/gameengine/VideoTexture/ImageViewport.cpp b/source/gameengine/VideoTexture/ImageViewport.cpp
deleted file mode 100644
index ad3d8875e28..00000000000
--- a/source/gameengine/VideoTexture/ImageViewport.cpp
+++ /dev/null
@@ -1,467 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * Copyright (c) 2007 The Zdeno Ash Miklas
- *
- * This source file is part of VideoTexture library
- *
- * Contributor(s):
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/VideoTexture/ImageViewport.cpp
- * \ingroup bgevideotex
- */
-
-// implementation
-
-#include "EXP_PyObjectPlus.h"
-#include <structmember.h>
-
-#include "GPU_glew.h"
-
-#include "KX_PythonInit.h"
-#include "RAS_ICanvas.h"
-#include "Texture.h"
-#include "ImageBase.h"
-#include "VideoBase.h"
-#include "FilterSource.h"
-#include "ImageViewport.h"
-
-
-// constructor
-ImageViewport::ImageViewport (PyRASOffScreen *offscreen) : m_alpha(false), m_texInit(false)
-{
- // get viewport rectangle
- if (offscreen) {
- m_viewport[0] = 0;
- m_viewport[1] = 0;
- m_viewport[2] = offscreen->ofs->GetWidth();
- m_viewport[3] = offscreen->ofs->GetHeight();
- }
- else {
- RAS_Rect rect = KX_GetActiveEngine()->GetCanvas()->GetWindowArea();
- m_viewport[0] = rect.GetLeft();
- m_viewport[1] = rect.GetBottom();
- m_viewport[2] = rect.GetWidth();
- m_viewport[3] = rect.GetHeight();
- }
-
- //glGetIntegerv(GL_VIEWPORT, m_viewport);
- // create buffer for viewport image
- // Warning: this buffer is also used to get the depth buffer as an array of
- // float (1 float = 4 bytes per pixel)
- m_viewportImage = new BYTE [4 * getViewportSize()[0] * getViewportSize()[1]];
- // set attributes
- setWhole((offscreen) ? true : false);
-}
-
-// destructor
-ImageViewport::~ImageViewport (void)
-{
- delete [] m_viewportImage;
-}
-
-
-// use whole viewport to capture image
-void ImageViewport::setWhole (bool whole)
-{
- // set whole
- m_whole = whole;
- // set capture size to viewport size, if whole,
- // otherwise place area in the middle of viewport
- for (int idx = 0; idx < 2; ++idx)
- {
- // capture size
- m_capSize[idx] = whole ? short(getViewportSize()[idx])
- : calcSize(short(getViewportSize()[idx]));
- // position
- m_position[idx] = whole ? 0 : ((getViewportSize()[idx] - m_capSize[idx]) >> 1);
- }
- // init image
- init(m_capSize[0], m_capSize[1]);
- // set capture position
- setPosition();
-}
-
-void ImageViewport::setCaptureSize (short size[2])
-{
- m_whole = false;
- if (size == NULL)
- size = m_capSize;
- for (int idx = 0; idx < 2; ++idx)
- {
- if (size[idx] < 1)
- m_capSize[idx] = 1;
- else if (size[idx] > getViewportSize()[idx])
- m_capSize[idx] = short(getViewportSize()[idx]);
- else
- m_capSize[idx] = size[idx];
- }
- init(m_capSize[0], m_capSize[1]);
- // set capture position
- setPosition();
-}
-
-// set position of capture rectangle
-void ImageViewport::setPosition (GLint pos[2])
-{
- // if new position is not provided, use existing position
- if (pos == NULL) pos = m_position;
- // save position
- for (int idx = 0; idx < 2; ++idx)
- m_position[idx] = pos[idx] < 0 ? 0 : pos[idx] >= getViewportSize()[idx]
- - m_capSize[idx] ? getViewportSize()[idx] - m_capSize[idx] : pos[idx];
- // recalc up left corner
- for (int idx = 0; idx < 2; ++idx)
- m_upLeft[idx] = m_position[idx] + m_viewport[idx];
-}
-
-
-// capture image from viewport
-void ImageViewport::calcViewport (unsigned int texId, double ts, unsigned int format)
-{
- // if scale was changed
- if (m_scaleChange)
- // reset image
- init(m_capSize[0], m_capSize[1]);
- // if texture wasn't initialized
- if (!m_texInit && texId != 0) {
- // initialize it
- loadTexture(texId, m_image, m_size);
- m_texInit = true;
- }
- // if texture can be directly created
- if (texId != 0 && m_pyfilter == NULL && m_size[0] == m_capSize[0] &&
- m_size[1] == m_capSize[1] && !m_flip && !m_zbuff && !m_depth)
- {
- // just copy current viewport to texture
- glBindTexture(GL_TEXTURE_2D, texId);
- glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, m_upLeft[0], m_upLeft[1], (GLsizei)m_capSize[0], (GLsizei)m_capSize[1]);
- glBindTexture(GL_TEXTURE_2D, 0);
- // image is not available
- m_avail = false;
- }
- // otherwise copy viewport to buffer, if image is not available
- else if (!m_avail) {
- if (m_zbuff) {
- // Use read pixels with the depth buffer
- // *** misusing m_viewportImage here, but since it has the correct size
- // (4 bytes per pixel = size of float) and we just need it to apply
- // the filter, it's ok
- glReadPixels(m_upLeft[0], m_upLeft[1], (GLsizei)m_capSize[0], (GLsizei)m_capSize[1],
- GL_DEPTH_COMPONENT, GL_FLOAT, m_viewportImage);
- // filter loaded data
- FilterZZZA filt;
- filterImage(filt, (float *)m_viewportImage, m_capSize);
- }
- else {
-
- if (m_depth) {
- // Use read pixels with the depth buffer
- // See warning above about m_viewportImage.
- glReadPixels(m_upLeft[0], m_upLeft[1], (GLsizei)m_capSize[0], (GLsizei)m_capSize[1],
- GL_DEPTH_COMPONENT, GL_FLOAT, m_viewportImage);
- // filter loaded data
- FilterDEPTH filt;
- filterImage(filt, (float *)m_viewportImage, m_capSize);
- }
- else {
-
- // get frame buffer data
- if (m_alpha) {
- // as we are reading the pixel in the native format, we can read directly in the image buffer
- // if we are sure that no processing is needed on the image
- if (m_size[0] == m_capSize[0] &&
- m_size[1] == m_capSize[1] &&
- !m_flip &&
- !m_pyfilter)
- {
- glReadPixels(m_upLeft[0], m_upLeft[1], (GLsizei)m_capSize[0], (GLsizei)m_capSize[1], format,
- GL_UNSIGNED_BYTE, m_image);
- m_avail = true;
- }
- else if (!m_pyfilter) {
- glReadPixels(m_upLeft[0], m_upLeft[1], (GLsizei)m_capSize[0], (GLsizei)m_capSize[1], format,
- GL_UNSIGNED_BYTE, m_viewportImage);
- FilterRGBA32 filt;
- filterImage(filt, m_viewportImage, m_capSize);
- }
- else {
- glReadPixels(m_upLeft[0], m_upLeft[1], (GLsizei)m_capSize[0], (GLsizei)m_capSize[1], GL_RGBA,
- GL_UNSIGNED_BYTE, m_viewportImage);
- FilterRGBA32 filt;
- filterImage(filt, m_viewportImage, m_capSize);
- if (format == GL_BGRA) {
- // in place byte swapping
- swapImageBR();
- }
- }
- }
- else {
- glReadPixels(m_upLeft[0], m_upLeft[1], (GLsizei)m_capSize[0], (GLsizei)m_capSize[1], GL_RGB,
- GL_UNSIGNED_BYTE, m_viewportImage);
- // filter loaded data
- FilterRGB24 filt;
- filterImage(filt, m_viewportImage, m_capSize);
- if (format == GL_BGRA) {
- // in place byte swapping
- swapImageBR();
- }
- }
- }
- }
- }
-}
-
-bool ImageViewport::loadImage(unsigned int *buffer, unsigned int size, unsigned int format, double ts)
-{
- unsigned int *tmp_image;
- bool ret;
-
- // if scale was changed
- if (m_scaleChange) {
- // reset image
- init(m_capSize[0], m_capSize[1]);
- }
-
- // size must be identical
- if (size < getBuffSize())
- return false;
-
- if (m_avail) {
- // just copy
- return ImageBase::loadImage(buffer, size, format, ts);
- }
- else {
- tmp_image = m_image;
- m_image = buffer;
- calcViewport(0, ts, format);
- ret = m_avail;
- m_image = tmp_image;
- // since the image was not loaded to our buffer, it's not valid
- m_avail = false;
- }
- return ret;
-}
-
-
-// cast Image pointer to ImageViewport
-inline ImageViewport * getImageViewport (PyImage *self)
-{ return static_cast<ImageViewport*>(self->m_image); }
-
-
-// python methods
-
-
-// get whole
-PyObject *ImageViewport_getWhole (PyImage *self, void *closure)
-{
- if (self->m_image != NULL && getImageViewport(self)->getWhole()) Py_RETURN_TRUE;
- else Py_RETURN_FALSE;
-}
-
-// set whole
-int ImageViewport_setWhole(PyImage *self, PyObject *value, void *closure)
-{
- // check parameter, report failure
- if (value == NULL || !PyBool_Check(value))
- {
- PyErr_SetString(PyExc_TypeError, "The value must be a bool");
- return -1;
- }
- try
- {
- // set whole, can throw in case of resize and buffer exports
- if (self->m_image != NULL) getImageViewport(self)->setWhole(value == Py_True);
- }
- catch (Exception & exp)
- {
- exp.report();
- return -1;
- }
- // success
- return 0;
-}
-
-// get alpha
-PyObject *ImageViewport_getAlpha (PyImage *self, void *closure)
-{
- if (self->m_image != NULL && getImageViewport(self)->getAlpha()) Py_RETURN_TRUE;
- else Py_RETURN_FALSE;
-}
-
-// set whole
-int ImageViewport_setAlpha(PyImage *self, PyObject *value, void *closure)
-{
- // check parameter, report failure
- if (value == NULL || !PyBool_Check(value))
- {
- PyErr_SetString(PyExc_TypeError, "The value must be a bool");
- return -1;
- }
- // set alpha
- if (self->m_image != NULL) getImageViewport(self)->setAlpha(value == Py_True);
- // success
- return 0;
-}
-
-
-// get position
-static PyObject *ImageViewport_getPosition (PyImage *self, void *closure)
-{
- GLint *pos = getImageViewport(self)->getPosition();
- PyObject *ret = PyTuple_New(2);
- PyTuple_SET_ITEM(ret, 0, PyLong_FromLong(pos[0]));
- PyTuple_SET_ITEM(ret, 1, PyLong_FromLong(pos[1]));
- return ret;
-}
-
-// set position
-static int ImageViewport_setPosition(PyImage *self, PyObject *value, void *closure)
-{
- // check validity of parameter
- if (value == NULL ||
- !(PyTuple_Check(value) || PyList_Check(value)) ||
- PySequence_Fast_GET_SIZE(value) != 2 ||
- !PyLong_Check(PySequence_Fast_GET_ITEM(value, 0)) ||
- !PyLong_Check(PySequence_Fast_GET_ITEM(value, 1)))
- {
- PyErr_SetString(PyExc_TypeError, "The value must be a sequence of 2 ints");
- return -1;
- }
- // set position
- GLint pos[2] = {
- GLint(PyLong_AsLong(PySequence_Fast_GET_ITEM(value, 0))),
- GLint(PyLong_AsLong(PySequence_Fast_GET_ITEM(value, 1)))
- };
- getImageViewport(self)->setPosition(pos);
- // success
- return 0;
-}
-
-// get capture size
-PyObject *ImageViewport_getCaptureSize (PyImage *self, void *closure)
-{
- short *size = getImageViewport(self)->getCaptureSize();
- PyObject *ret = PyTuple_New(2);
- PyTuple_SET_ITEM(ret, 0, PyLong_FromLong(size[0]));
- PyTuple_SET_ITEM(ret, 1, PyLong_FromLong(size[1]));
- return ret;
-}
-
-// set capture size
-int ImageViewport_setCaptureSize(PyImage *self, PyObject *value, void *closure)
-{
- // check validity of parameter
- if (value == NULL ||
- !(PyTuple_Check(value) || PyList_Check(value)) ||
- PySequence_Fast_GET_SIZE(value) != 2 ||
- !PyLong_Check(PySequence_Fast_GET_ITEM(value, 0)) ||
- !PyLong_Check(PySequence_Fast_GET_ITEM(value, 1)))
- {
- PyErr_SetString(PyExc_TypeError, "The value must be a sequence of 2 ints");
- return -1;
- }
- // set capture size
- short size[2] = {
- short(PyLong_AsLong(PySequence_Fast_GET_ITEM(value, 0))),
- short(PyLong_AsLong(PySequence_Fast_GET_ITEM(value, 1)))
- };
- try
- {
- // can throw in case of resize and buffer exports
- getImageViewport(self)->setCaptureSize(size);
- }
- catch (Exception & exp)
- {
- exp.report();
- return -1;
- }
- // success
- return 0;
-}
-
-
-// methods structure
-static PyMethodDef imageViewportMethods[] =
-{ // methods from ImageBase class
- {"refresh", (PyCFunction)Image_refresh, METH_VARARGS, "Refresh image - invalidate its current content"},
- {NULL}
-};
-// attributes structure
-static PyGetSetDef imageViewportGetSets[] =
-{
- {(char*)"whole", (getter)ImageViewport_getWhole, (setter)ImageViewport_setWhole, (char*)"use whole viewport to capture", NULL},
- {(char*)"position", (getter)ImageViewport_getPosition, (setter)ImageViewport_setPosition, (char*)"upper left corner of captured area", NULL},
- {(char*)"capsize", (getter)ImageViewport_getCaptureSize, (setter)ImageViewport_setCaptureSize, (char*)"size of viewport area being captured", NULL},
- {(char*)"alpha", (getter)ImageViewport_getAlpha, (setter)ImageViewport_setAlpha, (char*)"use alpha in texture", NULL},
- // attributes from ImageBase class
- {(char*)"valid", (getter)Image_valid, NULL, (char*)"bool to tell if an image is available", NULL},
- {(char*)"image", (getter)Image_getImage, NULL, (char*)"image data", NULL},
- {(char*)"size", (getter)Image_getSize, NULL, (char*)"image size", NULL},
- {(char*)"scale", (getter)Image_getScale, (setter)Image_setScale, (char*)"fast scale of image (near neighbor)", NULL},
- {(char*)"flip", (getter)Image_getFlip, (setter)Image_setFlip, (char*)"flip image vertically", NULL},
- {(char*)"zbuff", (getter)Image_getZbuff, (setter)Image_setZbuff, (char*)"use depth buffer as texture", NULL},
- {(char*)"depth", (getter)Image_getDepth, (setter)Image_setDepth, (char*)"get depth information from z-buffer as array of float", NULL},
- {(char*)"filter", (getter)Image_getFilter, (setter)Image_setFilter, (char*)"pixel filter", NULL},
- {NULL}
-};
-
-
-// define python type
-PyTypeObject ImageViewportType = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "VideoTexture.ImageViewport", /*tp_name*/
- sizeof(PyImage), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- (destructor)Image_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- 0, /*tp_getattr*/
- 0, /*tp_setattr*/
- 0, /*tp_compare*/
- 0, /*tp_repr*/
- 0, /*tp_as_number*/
- 0, /*tp_as_sequence*/
- 0, /*tp_as_mapping*/
- 0, /*tp_hash */
- 0, /*tp_call*/
- 0, /*tp_str*/
- 0, /*tp_getattro*/
- 0, /*tp_setattro*/
- &imageBufferProcs, /*tp_as_buffer*/
- Py_TPFLAGS_DEFAULT, /*tp_flags*/
- "Image source from viewport", /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- imageViewportMethods, /* tp_methods */
- 0, /* tp_members */
- imageViewportGetSets, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- (initproc)Image_init<ImageViewport>, /* tp_init */
- 0, /* tp_alloc */
- Image_allocNew, /* tp_new */
-};
diff --git a/source/gameengine/VideoTexture/ImageViewport.h b/source/gameengine/VideoTexture/ImageViewport.h
deleted file mode 100644
index 8a7e9cfd2ba..00000000000
--- a/source/gameengine/VideoTexture/ImageViewport.h
+++ /dev/null
@@ -1,113 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * Copyright (c) 2007 The Zdeno Ash Miklas
- *
- * This source file is part of VideoTexture library
- *
- * Contributor(s):
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file ImageViewport.h
- * \ingroup bgevideotex
- */
-
-#ifndef __IMAGEVIEWPORT_H__
-#define __IMAGEVIEWPORT_H__
-
-
-#include "Common.h"
-
-#include "ImageBase.h"
-#include "RAS_IOffScreen.h"
-
-
-/// class for viewport access
-class ImageViewport : public ImageBase
-{
-public:
- /// constructor
- ImageViewport (PyRASOffScreen *offscreen=NULL);
-
- /// destructor
- virtual ~ImageViewport (void);
-
- /// is whole buffer used
- bool getWhole (void) { return m_whole; }
- /// set whole buffer use
- void setWhole (bool whole);
-
- /// is alpha channel used
- bool getAlpha (void) { return m_alpha; }
- /// set whole buffer use
- void setAlpha (bool alpha) { m_alpha = alpha; }
-
- /// get capture size in viewport
- short * getCaptureSize (void) { return m_capSize; }
- /// set capture size in viewport
- void setCaptureSize (short size[2] = NULL);
-
- /// get position in viewport
- GLint * getPosition (void) { return m_position; }
- /// set position in viewport
- void setPosition (GLint pos[2] = NULL);
-
- /// capture image from viewport to user buffer
- virtual bool loadImage(unsigned int *buffer, unsigned int size, unsigned int format, double ts);
-
-protected:
- /// frame buffer rectangle
- GLint m_viewport[4];
-
- /// size of captured area
- short m_capSize[2];
- /// use whole viewport
- bool m_whole;
- /// use alpha channel
- bool m_alpha;
-
- /// position of capture rectangle in viewport
- GLint m_position[2];
- /// upper left point for capturing
- GLint m_upLeft[2];
-
- /// buffer to copy viewport
- BYTE * m_viewportImage;
- /// texture is initialized
- bool m_texInit;
-
- /// capture image from viewport
- virtual void calcImage (unsigned int texId, double ts) { calcViewport(texId, ts, GL_RGBA); }
-
- /// capture image from viewport
- virtual void calcViewport (unsigned int texId, double ts, unsigned int format);
-
- /// get viewport size
- GLint * getViewportSize (void) { return m_viewport + 2; }
-};
-
-PyObject *ImageViewport_getCaptureSize(PyImage *self, void *closure);
-int ImageViewport_setCaptureSize(PyImage *self, PyObject *value, void *closure);
-PyObject *ImageViewport_getWhole(PyImage *self, void *closure);
-int ImageViewport_setWhole(PyImage *self, PyObject *value, void *closure);
-PyObject *ImageViewport_getAlpha(PyImage *self, void *closure);
-int ImageViewport_setAlpha(PyImage *self, PyObject *value, void *closure);
-
-#endif
-
diff --git a/source/gameengine/VideoTexture/PyTypeList.cpp b/source/gameengine/VideoTexture/PyTypeList.cpp
deleted file mode 100644
index 18f477f6178..00000000000
--- a/source/gameengine/VideoTexture/PyTypeList.cpp
+++ /dev/null
@@ -1,97 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * Copyright (c) 2007 The Zdeno Ash Miklas
- *
- * This source file is part of blendTex library
- *
- * Contributor(s):
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/VideoTexture/PyTypeList.cpp
- * \ingroup bgevideotex
- */
-
-#include "PyTypeList.h"
-
-#include <memory>
-#include <vector>
-
-#include "EXP_PyObjectPlus.h"
-
-/// destructor
-PyTypeList::~PyTypeList()
-{
- // if list exists
- if (m_list.get() != NULL)
- for (PyTypeListType::iterator it = m_list->begin(); it != m_list->end(); ++it)
- delete *it;
-}
-
-/// check, if type is in list
-bool PyTypeList::in (PyTypeObject *type)
-{
- // if list exists
- if (m_list.get() != NULL)
- // iterate items in list
- for (PyTypeListType::iterator it = m_list->begin(); it != m_list->end(); ++it)
- // if item is found, return with success
- if ((*it)->getType() == type) return true;
- // otherwise return not found
- return false;
-}
-
-/// add type to list
-void PyTypeList::add (PyTypeObject *type, const char *name)
-{
- // if list doesn't exist, create it
- if (m_list.get() == NULL)
- m_list.reset(new PyTypeListType());
- if (!in(type))
- // add new item to list
- m_list->push_back(new PyTypeListItem(type, name));
-}
-
-/// prepare types
-bool PyTypeList::ready (void)
-{
- // if list exists
- if (m_list.get() != NULL)
- // iterate items in list
- for (PyTypeListType::iterator it = m_list->begin(); it != m_list->end(); ++it)
- // if preparation failed, report it
- if (PyType_Ready((*it)->getType()) < 0) return false;
- // success
- return true;
-}
-
-/// register types to module
-void PyTypeList::reg(PyObject *module)
-{
- // if list exists
- if (m_list.get() != NULL)
- // iterate items in list
- for (PyTypeListType::iterator it = m_list->begin(); it != m_list->end(); ++it)
- {
- // increase ref count
- Py_INCREF((*it)->getType());
- // add type to module
- PyModule_AddObject(module, (*it)->getName(), (PyObject *)(*it)->getType());
- }
-}
diff --git a/source/gameengine/VideoTexture/PyTypeList.h b/source/gameengine/VideoTexture/PyTypeList.h
deleted file mode 100644
index ce0eb81e656..00000000000
--- a/source/gameengine/VideoTexture/PyTypeList.h
+++ /dev/null
@@ -1,100 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * Copyright (c) 2007 The Zdeno Ash Miklas
- *
- * This source file is part of blendTex library
- *
- * Contributor(s):
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file PyTypeList.h
- * \ingroup bgevideotex
- */
-
-#ifndef __PYTYPELIST_H__
-#define __PYTYPELIST_H__
-
-#include "Common.h"
-
-#include <memory>
-#include <vector>
-
-#include "EXP_PyObjectPlus.h"
-
-// forward declaration
-class PyTypeListItem;
-
-// type for list of types
-typedef std::vector<PyTypeListItem*> PyTypeListType;
-
-
-/// class to store list of python types
-class PyTypeList
-{
-public:
- /// destructor
- ~PyTypeList();
-
- /// check, if type is in list
- bool in (PyTypeObject *type);
-
- /// add type to list
- void add (PyTypeObject *type, const char * name);
-
- /// prepare types
- bool ready (void);
-
- /// register types to module
- void reg(PyObject *module);
-
-protected:
- /// pointer to list of types
-#if (__cplusplus > 199711L) /* || (defined(_MSC_VER) && _MSC_VER >= 1800) */
- std::unique_ptr<PyTypeListType> m_list;
-#else
- std::auto_ptr<PyTypeListType> m_list;
-#endif
-};
-
-
-/// class for item of python type list
-class PyTypeListItem
-{
-public:
- /// constructor adds type into list
- PyTypeListItem (PyTypeObject *type, const char * name)
- : m_type(type), m_name(name)
- { }
-
- /// does type match
- PyTypeObject *getType (void) { return m_type; }
-
- /// get name of type
- const char * getName (void) { return m_name; }
-
-protected:
- /// pointer to type object
- PyTypeObject *m_type;
- /// name of type
- const char *m_name;
-};
-
-
-#endif
diff --git a/source/gameengine/VideoTexture/Texture.cpp b/source/gameengine/VideoTexture/Texture.cpp
deleted file mode 100644
index 48dc4c705bf..00000000000
--- a/source/gameengine/VideoTexture/Texture.cpp
+++ /dev/null
@@ -1,533 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * Copyright (c) 2007 The Zdeno Ash Miklas
- *
- * This source file is part of VideoTexture library
- *
- * Contributor(s):
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/VideoTexture/Texture.cpp
- * \ingroup bgevideotex
- */
-
-// implementation
-
-#include "EXP_PyObjectPlus.h"
-#include <structmember.h>
-
-#include "KX_GameObject.h"
-#include "KX_Light.h"
-#include "RAS_MeshObject.h"
-#include "RAS_ILightObject.h"
-#include "DNA_mesh_types.h"
-#include "DNA_meshdata_types.h"
-#include "DNA_image_types.h"
-#include "IMB_imbuf_types.h"
-#include "BKE_image.h"
-
-#include "MEM_guardedalloc.h"
-
-#include "KX_BlenderMaterial.h"
-#include "BL_Texture.h"
-
-#include "KX_KetsjiEngine.h"
-#include "KX_PythonInit.h"
-#include "Texture.h"
-#include "ImageBase.h"
-#include "Exception.h"
-
-#include <memory.h>
-#include "GPU_glew.h"
-
-extern "C" {
- #include "IMB_imbuf.h"
-}
-
-// macro for exception handling and logging
-#define CATCH_EXCP catch (Exception & exp) \
-{ exp.report(); return NULL; }
-
-
-// Blender GameObject type
-static BlendType<KX_GameObject> gameObjectType ("KX_GameObject");
-static BlendType<KX_LightObject> lightObjectType ("KX_LightObject");
-
-
-// load texture
-void loadTexture(unsigned int texId, unsigned int *texture, short *size,
- bool mipmap)
-{
- // load texture for rendering
- glBindTexture(GL_TEXTURE_2D, texId);
- if (mipmap)
- {
- int i;
- ImBuf *ibuf;
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
-
- ibuf = IMB_allocFromBuffer(texture, NULL, size[0], size[1]);
-
- IMB_makemipmap(ibuf, true);
-
- for (i = 0; i < ibuf->miptot; i++) {
- ImBuf *mip = IMB_getmipmap(ibuf, i);
-
- glTexImage2D(GL_TEXTURE_2D, i, GL_RGBA, mip->x, mip->y, 0, GL_RGBA, GL_UNSIGNED_BYTE, mip->rect);
- }
- IMB_freeImBuf(ibuf);
- }
- else
- {
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
- glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, size[0], size[1], 0, GL_RGBA, GL_UNSIGNED_BYTE, texture);
- }
- glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
-}
-
-
-// get pointer to material
-RAS_IPolyMaterial * getMaterial (PyObject *obj, short matID)
-{
- // if object is available
- if (obj != NULL)
- {
- // get pointer to texture image
- KX_GameObject * gameObj = gameObjectType.checkType(obj);
- if (gameObj != NULL && gameObj->GetMeshCount() > 0)
- {
- // get material from mesh
- RAS_MeshObject * mesh = gameObj->GetMesh(0);
- RAS_MeshMaterial *meshMat = mesh->GetMeshMaterial(matID);
- if (meshMat != NULL && meshMat->m_bucket != NULL)
- // return pointer to polygon or blender material
- return meshMat->m_bucket->GetPolyMaterial();
- }
- }
- // otherwise material was not found
- return NULL;
-}
-
-// get pointer to a lamp
-static KX_LightObject *getLamp(PyObject *obj)
-{
- // if object is available
- if (obj == NULL) return NULL;
-
- // returns NULL if obj is not a KX_LightObject
- return lightObjectType.checkType(obj);
-}
-
-
-// get material ID
-short getMaterialID(PyObject *obj, const char *name)
-{
- // search for material
- for (short matID = 0;; ++matID)
- {
- // get material
- RAS_IPolyMaterial * mat = getMaterial(obj, matID);
- // if material is not available, report that no material was found
- if (mat == NULL)
- break;
- // name is a material name if it starts with MA and a UV texture name if it starts with IM
- if (name[0] == 'I' && name[1] == 'M') {
- // if texture name matches
- if (strcmp(mat->GetTextureName().ReadPtr(), name) == 0)
- return matID;
- }
- else {
- // if material name matches
- if (strcmp(mat->GetMaterialName().ReadPtr(), name) == 0)
- return matID;
- }
- }
- // material was not found
- return -1;
-}
-
-
-// Texture object allocation
-static PyObject *Texture_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
-{
- // allocate object
- Texture * self = reinterpret_cast<Texture*>(type->tp_alloc(type, 0));
- // initialize object structure
- self->m_actTex = 0;
- self->m_orgSaved = false;
- self->m_imgBuf = NULL;
- self->m_imgTexture = NULL;
- self->m_matTexture = NULL;
- self->m_mipmap = false;
- self->m_scaledImBuf = NULL;
- self->m_source = NULL;
- self->m_lastClock = 0.0;
- // return allocated object
- return reinterpret_cast<PyObject*>(self);
-}
-
-
-// forward declaration
-PyObject *Texture_close(Texture *self);
-int Texture_setSource(Texture *self, PyObject *value, void *closure);
-
-
-// Texture object deallocation
-static void Texture_dealloc(Texture *self)
-{
- // release renderer
- Py_XDECREF(self->m_source);
- // close texture
- PyObject *ret = Texture_close(self);
- Py_DECREF(ret);
- // release scaled image buffer
- IMB_freeImBuf(self->m_scaledImBuf);
- // release object
- Py_TYPE((PyObject *)self)->tp_free((PyObject *)self);
-}
-
-
-ExceptionID MaterialNotAvail;
-ExpDesc MaterialNotAvailDesc(MaterialNotAvail, "Texture material is not available");
-
-// Texture object initialization
-static int Texture_init(Texture *self, PyObject *args, PyObject *kwds)
-{
- // parameters - game object with video texture
- PyObject *obj = NULL;
- // material ID
- short matID = 0;
- // texture ID
- short texID = 0;
- // texture object with shared texture ID
- Texture * texObj = NULL;
-
- static const char *kwlist[] = {"gameObj", "materialID", "textureID", "textureObj", NULL};
-
- // get parameters
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|hhO!",
- const_cast<char**>(kwlist), &obj, &matID, &texID, &TextureType,
- &texObj))
- return -1;
-
- // if parameters are available
- if (obj != NULL)
- {
- // process polygon material or blender material
- try
- {
- // get pointer to texture image
- RAS_IPolyMaterial * mat = getMaterial(obj, matID);
- KX_LightObject * lamp = getLamp(obj);
- if (mat != NULL)
- {
- // is it blender material or polygon material
- if (mat->GetFlag() & RAS_BLENDERGLSL)
- {
- self->m_imgTexture = static_cast<KX_BlenderMaterial*>(mat)->getImage(texID);
- self->m_useMatTexture = false;
- } else
- {
- // get blender material texture
- self->m_matTexture = static_cast<KX_BlenderMaterial*>(mat)->getTex(texID);
- self->m_useMatTexture = true;
- }
- }
- else if (lamp != NULL)
- {
- self->m_imgTexture = lamp->GetLightData()->GetTextureImage(texID);
- self->m_useMatTexture = false;
- }
-
- // check if texture is available, if not, initialization failed
- if (self->m_imgTexture == NULL && self->m_matTexture == NULL)
- // throw exception if initialization failed
- THRWEXCP(MaterialNotAvail, S_OK);
-
- // if texture object is provided
- if (texObj != NULL)
- {
- // copy texture code
- self->m_actTex = texObj->m_actTex;
- self->m_mipmap = texObj->m_mipmap;
- if (texObj->m_source != NULL)
- Texture_setSource(self, reinterpret_cast<PyObject*>(texObj->m_source), NULL);
- }
- else
- // otherwise generate texture code
- glGenTextures(1, (GLuint*)&self->m_actTex);
- }
- catch (Exception & exp)
- {
- exp.report();
- return -1;
- }
- }
- // initialization succeded
- return 0;
-}
-
-
-// close added texture
-PyObject *Texture_close(Texture * self)
-{
- // restore texture
- if (self->m_orgSaved)
- {
- self->m_orgSaved = false;
- // restore original texture code
- if (self->m_useMatTexture)
- self->m_matTexture->swapTexture(self->m_orgTex);
- else
- {
- self->m_imgTexture->bindcode[TEXTARGET_TEXTURE_2D] = self->m_orgTex;
- BKE_image_release_ibuf(self->m_imgTexture, self->m_imgBuf, NULL);
- self->m_imgBuf = NULL;
- }
- // drop actual texture
- if (self->m_actTex != 0)
- {
- glDeleteTextures(1, (GLuint *)&self->m_actTex);
- self->m_actTex = 0;
- }
- }
- Py_RETURN_NONE;
-}
-
-
-// refresh texture
-static PyObject *Texture_refresh(Texture *self, PyObject *args)
-{
- // get parameter - refresh source
- PyObject *param;
- double ts = -1.0;
-
- if (!PyArg_ParseTuple(args, "O|d:refresh", &param, &ts) || !PyBool_Check(param))
- {
- // report error
- PyErr_SetString(PyExc_TypeError, "The value must be a bool");
- return NULL;
- }
- // some trick here: we are in the business of loading a texture,
- // no use to do it if we are still in the same rendering frame.
- // We find this out by looking at the engine current clock time
- KX_KetsjiEngine* engine = KX_GetActiveEngine();
- if (engine->GetClockTime() != self->m_lastClock)
- {
- self->m_lastClock = engine->GetClockTime();
- // set source refresh
- bool refreshSource = (param == Py_True);
- // try to proces texture from source
- try
- {
- // if source is available
- if (self->m_source != NULL)
- {
- // check texture code
- if (!self->m_orgSaved)
- {
- self->m_orgSaved = true;
- // save original image code
- if (self->m_useMatTexture)
- self->m_orgTex = self->m_matTexture->swapTexture(self->m_actTex);
- else
- {
- // Swapping will work only if the GPU has already loaded the image.
- // If not, it will delete and overwrite our texture on next render.
- // To avoid that, we acquire the image buffer now.
- // WARNING: GPU has a ImageUser to pass, we don't. Using NULL
- // works on image file, not necessarily on other type of image.
- self->m_imgBuf = BKE_image_acquire_ibuf(self->m_imgTexture, NULL, NULL);
- self->m_orgTex = self->m_imgTexture->bindcode[TEXTARGET_TEXTURE_2D];
- self->m_imgTexture->bindcode[TEXTARGET_TEXTURE_2D] = self->m_actTex;
- }
- }
-
- // get texture
- unsigned int * texture = self->m_source->m_image->getImage(self->m_actTex, ts);
- // if texture is available
- if (texture != NULL)
- {
- // get texture size
- short * orgSize = self->m_source->m_image->getSize();
- // calc scaled sizes
- short size[2];
- if (GLEW_ARB_texture_non_power_of_two)
- {
- size[0] = orgSize[0];
- size[1] = orgSize[1];
- }
- else
- {
- size[0] = ImageBase::calcSize(orgSize[0]);
- size[1] = ImageBase::calcSize(orgSize[1]);
- }
- // scale texture if needed
- if (size[0] != orgSize[0] || size[1] != orgSize[1])
- {
- IMB_freeImBuf(self->m_scaledImBuf);
- self->m_scaledImBuf = IMB_allocFromBuffer(texture, NULL, orgSize[0], orgSize[1]);
- IMB_scaleImBuf(self->m_scaledImBuf, size[0], size[1]);
-
- // use scaled image instead original
- texture = self->m_scaledImBuf->rect;
- }
- // load texture for rendering
- loadTexture(self->m_actTex, texture, size, self->m_mipmap);
- }
- // refresh texture source, if required
- if (refreshSource) {
- self->m_source->m_image->refresh();
- }
- }
- }
- CATCH_EXCP;
- }
- Py_RETURN_NONE;
-}
-
-// get OpenGL Bind Id
-static PyObject *Texture_getBindId(Texture *self, void *closure)
-{
- unsigned int id = self->m_actTex;
- return Py_BuildValue("h", id);
-}
-
-// get mipmap value
-static PyObject *Texture_getMipmap(Texture *self, void *closure)
-{
- // return true if flag is set, otherwise false
- if (self->m_mipmap) Py_RETURN_TRUE;
- else Py_RETURN_FALSE;
-}
-
-// set mipmap value
-static int Texture_setMipmap(Texture *self, PyObject *value, void *closure)
-{
- // check parameter, report failure
- if (value == NULL || !PyBool_Check(value))
- {
- PyErr_SetString(PyExc_TypeError, "The value must be a bool");
- return -1;
- }
- // set mipmap
- self->m_mipmap = value == Py_True;
- // success
- return 0;
-}
-
-
-// get source object
-static PyObject *Texture_getSource(Texture *self, PyObject *value, void *closure)
-{
- // if source exists
- if (self->m_source != NULL)
- {
- Py_INCREF(self->m_source);
- return reinterpret_cast<PyObject*>(self->m_source);
- }
- // otherwise return None
- Py_RETURN_NONE;
-}
-
-
-// set source object
-int Texture_setSource(Texture *self, PyObject *value, void *closure)
-{
- // check new value
- if (value == NULL || !pyImageTypes.in(Py_TYPE(value)))
- {
- // report value error
- PyErr_SetString(PyExc_TypeError, "Invalid type of value");
- return -1;
- }
- // increase ref count for new value
- Py_INCREF(value);
- // release previous
- Py_XDECREF(self->m_source);
- // set new value
- self->m_source = reinterpret_cast<PyImage*>(value);
- // return success
- return 0;
-}
-
-
-// class Texture methods
-static PyMethodDef textureMethods[] =
-{
- { "close", (PyCFunction)Texture_close, METH_NOARGS, "Close dynamic texture and restore original"},
- { "refresh", (PyCFunction)Texture_refresh, METH_VARARGS, "Refresh texture from source"},
- {NULL} /* Sentinel */
-};
-
-// class Texture attributes
-static PyGetSetDef textureGetSets[] =
-{
- {(char*)"source", (getter)Texture_getSource, (setter)Texture_setSource, (char*)"source of texture", NULL},
- {(char*)"mipmap", (getter)Texture_getMipmap, (setter)Texture_setMipmap, (char*)"mipmap texture", NULL},
- {(char*)"bindId", (getter)Texture_getBindId, NULL, (char*)"OpenGL Bind Name", NULL},
- {NULL}
-};
-
-
-// class Texture declaration
-PyTypeObject TextureType =
-{
- PyVarObject_HEAD_INIT(NULL, 0)
- "VideoTexture.Texture", /*tp_name*/
- sizeof(Texture), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- (destructor)Texture_dealloc,/*tp_dealloc*/
- 0, /*tp_print*/
- 0, /*tp_getattr*/
- 0, /*tp_setattr*/
- 0, /*tp_compare*/
- 0, /*tp_repr*/
- 0, /*tp_as_number*/
- 0, /*tp_as_sequence*/
- 0, /*tp_as_mapping*/
- 0, /*tp_hash */
- 0, /*tp_call*/
- 0, /*tp_str*/
- 0, /*tp_getattro*/
- 0, /*tp_setattro*/
- &imageBufferProcs, /*tp_as_buffer*/
- Py_TPFLAGS_DEFAULT, /*tp_flags*/
- "Texture objects", /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- textureMethods, /* tp_methods */
- 0, /* tp_members */
- textureGetSets, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- (initproc)Texture_init, /* tp_init */
- 0, /* tp_alloc */
- Texture_new, /* tp_new */
-};
diff --git a/source/gameengine/VideoTexture/Texture.h b/source/gameengine/VideoTexture/Texture.h
deleted file mode 100644
index dc38b4181bb..00000000000
--- a/source/gameengine/VideoTexture/Texture.h
+++ /dev/null
@@ -1,99 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * Copyright (c) 2006 The Zdeno Ash Miklas
- *
- * This source file is part of VideoTexture library
- *
- * Contributor(s):
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file VideoTexture/Texture.h
- * \ingroup bgevideotex
- */
-
-#ifndef __TEXTURE_H__
-#define __TEXTURE_H__
-
-#include "EXP_PyObjectPlus.h"
-#include <structmember.h>
-
-#include "DNA_image_types.h"
-#include "BL_Texture.h"
-#include "KX_BlenderMaterial.h"
-
-#include "ImageBase.h"
-#include "BlendType.h"
-#include "Exception.h"
-
-
-struct ImBuf;
-
-// type Texture declaration
-struct Texture
-{
- PyObject_HEAD
-
- // texture is using blender material
- bool m_useMatTexture;
-
- // video texture bind code
- unsigned int m_actTex;
- // original texture bind code
- unsigned int m_orgTex;
- // original texture saved
- bool m_orgSaved;
-
- // kernel image buffer, to make sure the image is loaded before we swap the bindcode
- struct ImBuf *m_imgBuf;
- // texture image for game materials
- Image * m_imgTexture;
- // texture for blender materials
- BL_Texture * m_matTexture;
-
- // use mipmapping
- bool m_mipmap;
-
- // scaled image buffer
- ImBuf * m_scaledImBuf;
- // last refresh
- double m_lastClock;
-
- // image source
- PyImage * m_source;
-};
-
-
-// Texture type description
-extern PyTypeObject TextureType;
-
-// load texture
-void loadTexture(unsigned int texId, unsigned int *texture, short *size,
- bool mipmap = false);
-
-// get material
-RAS_IPolyMaterial *getMaterial(PyObject *obj, short matID);
-
-// get material ID
-short getMaterialID(PyObject *obj, const char *name);
-
-// Exceptions
-extern ExceptionID MaterialNotAvail;
-
-#endif
diff --git a/source/gameengine/VideoTexture/VideoBase.cpp b/source/gameengine/VideoTexture/VideoBase.cpp
deleted file mode 100644
index d373055b5df..00000000000
--- a/source/gameengine/VideoTexture/VideoBase.cpp
+++ /dev/null
@@ -1,254 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * Copyright (c) 2007 The Zdeno Ash Miklas
- *
- * This source file is part of VideoTexture library
- *
- * Contributor(s):
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/VideoTexture/VideoBase.cpp
- * \ingroup bgevideotex
- */
-
-#if defined WIN32
-#define WINDOWS_LEAN_AND_MEAN
-#include <windows.h>
-#endif
-
-#include "VideoBase.h"
-
-#include "FilterSource.h"
-
-// VideoBase implementation
-
-
-// initialize image data
-void VideoBase::init(short width, short height)
-{
- // save original sizes
- m_orgSize[0] = width;
- m_orgSize[1] = height;
- // call base class initialization
- ImageBase::init(width, height);
-}
-
-
-// process video frame
-void VideoBase::process (BYTE *sample)
-{
- // if scale was changed
- if (m_scaleChange)
- // reset image
- init(m_orgSize[0], m_orgSize[1]);
- // if image is allocated and is able to store new image
- if (m_image != NULL && !m_avail)
- {
- // filters used
- // convert video format to image
- switch (m_format)
- {
- case RGBA32:
- {
- FilterRGBA32 filtRGBA;
- // use filter object for format to convert image
- filterImage(filtRGBA, sample, m_orgSize);
- // finish
- break;
- }
- case RGB24:
- {
- FilterRGB24 filtRGB;
- // use filter object for format to convert image
- filterImage(filtRGB, sample, m_orgSize);
- // finish
- break;
- }
- case YV12:
- {
- // use filter object for format to convert image
- FilterYV12 filtYUV;
- filtYUV.setBuffs(sample, m_orgSize);
- filterImage(filtYUV, sample, m_orgSize);
- // finish
- break;
- }
- case None:
- break; /* assert? */
- }
- }
-}
-
-
-// python functions
-
-
-// exceptions for video source initialization
-ExceptionID SourceVideoEmpty, SourceVideoCreation;
-ExpDesc SourceVideoEmptyDesc(SourceVideoEmpty, "Source Video is empty");
-ExpDesc SourceVideoCreationDesc(SourceVideoCreation, "SourceVideo object was not created");
-
-// open video source
-void Video_open(VideoBase *self, char *file, short captureID)
-{
- // if file is empty, throw exception
- if (file == NULL) THRWEXCP(SourceVideoEmpty, S_OK);
-
- // open video file or capture device
- if (captureID >= 0)
- self->openCam(file, captureID);
- else
- self->openFile(file);
-}
-
-
-// play video
-PyObject *Video_play(PyImage *self)
-{ if (getVideo(self)->play()) Py_RETURN_TRUE; else Py_RETURN_FALSE; }
-
-// pause video
-PyObject *Video_pause(PyImage *self)
-{ if (getVideo(self)->pause()) Py_RETURN_TRUE; else Py_RETURN_FALSE; }
-
-PyObject *Video_stop(PyImage *self)
-{ if (getVideo(self)->stop()) Py_RETURN_TRUE; else Py_RETURN_FALSE; }
-
-// get status
-PyObject *Video_getStatus(PyImage *self, void *closure)
-{
- return Py_BuildValue("h", getVideo(self)->getStatus());
-}
-
-// refresh video
-PyObject *Video_refresh(PyImage *self, PyObject *args)
-{
- Py_buffer buffer;
- char *mode = NULL;
- unsigned int format;
- double ts = -1.0;
-
- memset(&buffer, 0, sizeof(buffer));
- if (PyArg_ParseTuple(args, "|s*sd:refresh", &buffer, &mode, &ts)) {
- if (buffer.buf) {
- // a target buffer is provided, verify its format
- if (buffer.readonly) {
- PyErr_SetString(PyExc_TypeError, "Buffers passed in argument must be writable");
- }
- else if (!PyBuffer_IsContiguous(&buffer, 'C')) {
- PyErr_SetString(PyExc_TypeError, "Buffers passed in argument must be contiguous in memory");
- }
- else if (((intptr_t)buffer.buf & 3) != 0) {
- PyErr_SetString(PyExc_TypeError, "Buffers passed in argument must be aligned to 4 bytes boundary");
- }
- else {
- // ready to get the image into our buffer
- try {
- if (mode == NULL || !strcmp(mode, "RGBA"))
- format = GL_RGBA;
- else if (!strcmp(mode, "BGRA"))
- format = GL_BGRA;
- else
- THRWEXCP(InvalidImageMode,S_OK);
-
- if (!self->m_image->loadImage((unsigned int *)buffer.buf, buffer.len, format, ts)) {
- PyErr_SetString(PyExc_TypeError, "Could not load the buffer, perhaps size is not compatible");
- }
- }
- catch (Exception & exp) {
- exp.report();
- }
- }
- PyBuffer_Release(&buffer);
- if (PyErr_Occurred())
- return NULL;
- }
- }
- else
- {
- return NULL;
- }
- getVideo(self)->refresh();
- return Video_getStatus(self, NULL);
-}
-
-
-// get range
-PyObject *Video_getRange(PyImage *self, void *closure)
-{
- return Py_BuildValue("[ff]", getVideo(self)->getRange()[0],
- getVideo(self)->getRange()[1]);
-}
-
-// set range
-int Video_setRange(PyImage *self, PyObject *value, void *closure)
-{
- // check validity of parameter
- if (value == NULL || !PySequence_Check(value) || PySequence_Size(value) != 2 ||
- /* XXX - this is incorrect if the sequence is not a list/tuple! */
- !PyFloat_Check(PySequence_Fast_GET_ITEM(value, 0)) ||
- !PyFloat_Check(PySequence_Fast_GET_ITEM(value, 1)))
- {
- PyErr_SetString(PyExc_TypeError, "The value must be a sequence of 2 float");
- return -1;
- }
- // set range
- getVideo(self)->setRange(PyFloat_AsDouble(PySequence_Fast_GET_ITEM(value, 0)),
- PyFloat_AsDouble(PySequence_Fast_GET_ITEM(value, 1)));
- // success
- return 0;
-}
-
-// get repeat
-PyObject *Video_getRepeat (PyImage *self, void *closure)
-{ return Py_BuildValue("h", getVideo(self)->getRepeat()); }
-
-// set repeat
-int Video_setRepeat(PyImage *self, PyObject *value, void *closure)
-{
- // check validity of parameter
- if (value == NULL || !PyLong_Check(value))
- {
- PyErr_SetString(PyExc_TypeError, "The value must be an int");
- return -1;
- }
- // set repeat
- getVideo(self)->setRepeat(int(PyLong_AsLong(value)));
- // success
- return 0;
-}
-
-// get frame rate
-PyObject *Video_getFrameRate (PyImage *self, void *closure)
-{ return Py_BuildValue("f", double(getVideo(self)->getFrameRate())); }
-
-// set frame rate
-int Video_setFrameRate(PyImage *self, PyObject *value, void *closure)
-{
- // check validity of parameter
- if (value == NULL || !PyFloat_Check(value))
- {
- PyErr_SetString(PyExc_TypeError, "The value must be a float");
- return -1;
- }
- // set repeat
- getVideo(self)->setFrameRate(float(PyFloat_AsDouble(value)));
- // success
- return 0;
-}
diff --git a/source/gameengine/VideoTexture/VideoBase.h b/source/gameengine/VideoTexture/VideoBase.h
deleted file mode 100644
index 77f46fdccd8..00000000000
--- a/source/gameengine/VideoTexture/VideoBase.h
+++ /dev/null
@@ -1,207 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * Copyright (c) 2007 The Zdeno Ash Miklas
- *
- * This source file is part of VideoTexture library
- *
- * Contributor(s):
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file VideoBase.h
- * \ingroup bgevideotex
- */
-
-#ifndef __VIDEOBASE_H__
-#define __VIDEOBASE_H__
-
-
-#include "EXP_PyObjectPlus.h"
-
-#include "ImageBase.h"
-
-#include "Exception.h"
-
-// source states
-const int SourceError = -1;
-const int SourceEmpty = 0;
-const int SourceReady = 1;
-const int SourcePlaying = 2;
-const int SourceStopped = 3;
-
-
-// video source formats
-enum VideoFormat { None, RGB24, YV12, RGBA32 };
-
-
-/// base class for video source
-class VideoBase : public ImageBase
-{
-public:
- /// constructor
- VideoBase (void) : ImageBase(true), m_format(None), m_status(SourceEmpty),
- m_repeat(0), m_frameRate(1.0)
- {
- m_orgSize[0] = m_orgSize[1] = 0;
- m_range[0] = m_range[1] = 0.0;
- }
-
- /// destructor
- virtual ~VideoBase (void) {}
-
- /// open video file
- virtual void openFile(char *file)
- {
- m_isFile = true;
- m_status = SourceReady;
- }
- /// open video capture device
- virtual void openCam(char *file, short camIdx)
- {
- m_isFile = false;
- m_status = SourceReady;
- }
-
- /// play video
- virtual bool play (void)
- {
- if (m_status == SourceReady || m_status == SourceStopped)
- {
- m_status = SourcePlaying;
- return true;
- }
- return false;
- }
- /// pause video
- virtual bool pause (void)
- {
- if (m_status == SourcePlaying)
- {
- m_status = SourceStopped;
- return true;
- }
- return false;
- }
- /// stop video
- virtual bool stop (void)
- {
- if (m_status == SourcePlaying)
- {
- m_status = SourceStopped;
- return true;
- }
- return false;
- }
-
- // get video status
- int getStatus (void) { return m_status; }
-
- /// get play range
- const double * getRange (void) { return m_range; }
- /// set play range
- virtual void setRange (double start, double stop)
- {
- if (m_isFile)
- {
- m_range[0] = start;
- m_range[1] = stop;
- }
- }
-
- // get video repeat
- int getRepeat (void) { return m_repeat; }
- /// set video repeat
- virtual void setRepeat (int rep)
- { if (m_isFile) m_repeat = rep; }
-
- /// get frame rate
- float getFrameRate (void) { return m_frameRate; }
- /// set frame rate
- virtual void setFrameRate (float rate)
- { if (m_isFile) m_frameRate = rate > 0.0f ? rate : 1.0f; }
-
-protected:
- /// video format
- VideoFormat m_format;
- /// original video size
- short m_orgSize[2];
-
- /// video status
- int m_status;
-
- /// is source file
- bool m_isFile;
-
- /// replay range
- double m_range[2];
- /// repeat count
- int m_repeat;
- /// frame rate
- float m_frameRate;
-
- /// initialize image data
- void init (short width, short height);
-
- /// process source data
- void process (BYTE * sample);
-};
-
-
-
-// python fuctions
-
-
-// cast Image pointer to Video
-inline VideoBase *getVideo(PyImage *self)
-{ return static_cast<VideoBase*>(self->m_image); }
-
-
-extern ExceptionID SourceVideoCreation;
-
-// object initialization
-template <class T> void Video_init(PyImage *self)
-{
- // create source video object
- if (self->m_image != NULL) delete self->m_image;
- HRESULT hRslt = S_OK;
- self->m_image = new T(&hRslt);
- CHCKHRSLT(hRslt, SourceVideoCreation);
-}
-
-
-// video functions
-void Video_open(VideoBase *self, char *file, short captureID);
-PyObject *Video_play(PyImage *self);
-PyObject *Video_pause(PyImage *self);
-PyObject *Video_stop(PyImage *self);
-PyObject *Video_refresh(PyImage *self, PyObject *args);
-PyObject *Video_getStatus(PyImage *self, void *closure);
-PyObject *Video_getRange(PyImage *self, void *closure);
-int Video_setRange(PyImage *self, PyObject *value, void *closure);
-PyObject *Video_getRepeat(PyImage *self, void *closure);
-int Video_setRepeat(PyImage *self, PyObject *value, void *closure);
-PyObject *Video_getFrameRate(PyImage *self, void *closure);
-int Video_setFrameRate(PyImage *self, PyObject *value, void *closure);
-
-/* py api */
-extern PyTypeObject ImageRenderType;
-extern PyTypeObject ImageMirrorType;
-extern PyTypeObject ImageViewportType;
-
-#endif /* __VIDEOBASE_H__ */
diff --git a/source/gameengine/VideoTexture/VideoDeckLink.cpp b/source/gameengine/VideoTexture/VideoDeckLink.cpp
deleted file mode 100644
index c588a4b33cf..00000000000
--- a/source/gameengine/VideoTexture/VideoDeckLink.cpp
+++ /dev/null
@@ -1,1228 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2015, Blender Foundation
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): Blender Foundation.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/VideoTexture/VideoDeckLink.cpp
- * \ingroup bgevideotex
- */
-
-#ifdef WITH_GAMEENGINE_DECKLINK
-
-// FFmpeg defines its own version of stdint.h on Windows.
-// Decklink needs FFmpeg, so it uses its version of stdint.h
-// this is necessary for INT64_C macro
-#ifndef __STDC_CONSTANT_MACROS
-#define __STDC_CONSTANT_MACROS
-#endif
-// this is necessary for UINTPTR_MAX (used by atomic-ops)
-#ifndef __STDC_LIMIT_MACROS
-#define __STDC_LIMIT_MACROS
-#ifdef __STDC_LIMIT_MACROS /* else it may be unused */
-#endif
-#endif
-#include <stdint.h>
-#include <string.h>
-#ifndef WIN32
-#include <sys/time.h>
-#include <sys/resource.h>
-#include <sys/mman.h>
-#endif
-
-#include "atomic_ops.h"
-
-#include "MEM_guardedalloc.h"
-#include "PIL_time.h"
-#include "VideoDeckLink.h"
-#include "DeckLink.h"
-#include "Exception.h"
-#include "KX_KetsjiEngine.h"
-#include "KX_PythonInit.h"
-
-extern ExceptionID DeckLinkInternalError;
-ExceptionID SourceVideoOnlyCapture, VideoDeckLinkBadFormat, VideoDeckLinkOpenCard, VideoDeckLinkDvpInternalError, VideoDeckLinkPinMemoryError;
-ExpDesc SourceVideoOnlyCaptureDesc(SourceVideoOnlyCapture, "This video source only allows live capture");
-ExpDesc VideoDeckLinkBadFormatDesc(VideoDeckLinkBadFormat, "Invalid or unsupported capture format, should be <mode>/<pixel>[/3D]");
-ExpDesc VideoDeckLinkOpenCardDesc(VideoDeckLinkOpenCard, "Cannot open capture card, check if driver installed");
-ExpDesc VideoDeckLinkDvpInternalErrorDesc(VideoDeckLinkDvpInternalError, "DVP API internal error, please report");
-ExpDesc VideoDeckLinkPinMemoryErrorDesc(VideoDeckLinkPinMemoryError, "Error pinning memory");
-
-
-#ifdef WIN32
-////////////////////////////////////////////
-// SynInfo
-//
-// Sets up a semaphore which is shared between the GPU and CPU and used to
-// synchronise access to DVP buffers.
-#define DVP_CHECK(cmd) if ((cmd) != DVP_STATUS_OK) THRWEXCP(VideoDeckLinkDvpInternalError, S_OK)
-
-struct SyncInfo
-{
- SyncInfo(uint32_t semaphoreAllocSize, uint32_t semaphoreAddrAlignment)
- {
- mSemUnaligned = (uint32_t*)malloc(semaphoreAllocSize + semaphoreAddrAlignment - 1);
-
- // Apply alignment constraints
- uint64_t val = (uint64_t)mSemUnaligned;
- val += semaphoreAddrAlignment - 1;
- val &= ~((uint64_t)semaphoreAddrAlignment - 1);
- mSem = (uint32_t*)val;
-
- // Initialise
- mSem[0] = 0;
- mReleaseValue = 0;
- mAcquireValue = 0;
-
- // Setup DVP sync object and import it
- DVPSyncObjectDesc syncObjectDesc;
- syncObjectDesc.externalClientWaitFunc = NULL;
- syncObjectDesc.sem = (uint32_t*)mSem;
-
- DVP_CHECK(dvpImportSyncObject(&syncObjectDesc, &mDvpSync));
-
- }
- ~SyncInfo()
- {
- dvpFreeSyncObject(mDvpSync);
- free((void*)mSemUnaligned);
- }
-
- volatile uint32_t* mSem;
- volatile uint32_t* mSemUnaligned;
- volatile uint32_t mReleaseValue;
- volatile uint32_t mAcquireValue;
- DVPSyncObjectHandle mDvpSync;
-};
-
-////////////////////////////////////////////
-// TextureTransferDvp: transfer with GPUDirect
-////////////////////////////////////////////
-
-class TextureTransferDvp : public TextureTransfer
-{
-public:
- TextureTransferDvp(DVPBufferHandle dvpTextureHandle, TextureDesc *pDesc, void *address, uint32_t allocatedSize)
- {
- DVPSysmemBufferDesc sysMemBuffersDesc;
-
- mExtSync = NULL;
- mGpuSync = NULL;
- mDvpSysMemHandle = 0;
- mDvpTextureHandle = 0;
- mTextureHeight = 0;
- mAllocatedSize = 0;
- mBuffer = NULL;
-
- if (!_PinBuffer(address, allocatedSize))
- THRWEXCP(VideoDeckLinkPinMemoryError, S_OK);
- mAllocatedSize = allocatedSize;
- mBuffer = address;
-
- try {
- if (!mBufferAddrAlignment) {
- DVP_CHECK(dvpGetRequiredConstantsGLCtx(&mBufferAddrAlignment, &mBufferGpuStrideAlignment,
- &mSemaphoreAddrAlignment, &mSemaphoreAllocSize,
- &mSemaphorePayloadOffset, &mSemaphorePayloadSize));
- }
- mExtSync = new SyncInfo(mSemaphoreAllocSize, mSemaphoreAddrAlignment);
- mGpuSync = new SyncInfo(mSemaphoreAllocSize, mSemaphoreAddrAlignment);
- sysMemBuffersDesc.width = pDesc->width;
- sysMemBuffersDesc.height = pDesc->height;
- sysMemBuffersDesc.stride = pDesc->stride;
- switch (pDesc->format) {
- case GL_RED_INTEGER:
- sysMemBuffersDesc.format = DVP_RED_INTEGER;
- break;
- default:
- sysMemBuffersDesc.format = DVP_BGRA;
- break;
- }
- switch (pDesc->type) {
- case GL_UNSIGNED_BYTE:
- sysMemBuffersDesc.type = DVP_UNSIGNED_BYTE;
- break;
- case GL_UNSIGNED_INT_2_10_10_10_REV:
- sysMemBuffersDesc.type = DVP_UNSIGNED_INT_2_10_10_10_REV;
- break;
- case GL_UNSIGNED_INT_8_8_8_8:
- sysMemBuffersDesc.type = DVP_UNSIGNED_INT_8_8_8_8;
- break;
- case GL_UNSIGNED_INT_10_10_10_2:
- sysMemBuffersDesc.type = DVP_UNSIGNED_INT_10_10_10_2;
- break;
- default:
- sysMemBuffersDesc.type = DVP_UNSIGNED_INT;
- break;
- }
- sysMemBuffersDesc.size = pDesc->width * pDesc->height * 4;
- sysMemBuffersDesc.bufAddr = mBuffer;
- DVP_CHECK(dvpCreateBuffer(&sysMemBuffersDesc, &mDvpSysMemHandle));
- DVP_CHECK(dvpBindToGLCtx(mDvpSysMemHandle));
- mDvpTextureHandle = dvpTextureHandle;
- mTextureHeight = pDesc->height;
- }
- catch (Exception &) {
- clean();
- throw;
- }
- }
- ~TextureTransferDvp()
- {
- clean();
- }
-
- virtual void PerformTransfer()
- {
- // perform the transfer
- // tell DVP that the old texture buffer will no longer be used
- dvpMapBufferEndAPI(mDvpTextureHandle);
- // do we need this?
- mGpuSync->mReleaseValue++;
- dvpBegin();
- // Copy from system memory to GPU texture
- dvpMapBufferWaitDVP(mDvpTextureHandle);
- dvpMemcpyLined(mDvpSysMemHandle, mExtSync->mDvpSync, mExtSync->mAcquireValue, DVP_TIMEOUT_IGNORED,
- mDvpTextureHandle, mGpuSync->mDvpSync, mGpuSync->mReleaseValue, 0, mTextureHeight);
- dvpMapBufferEndDVP(mDvpTextureHandle);
- dvpEnd();
- dvpMapBufferWaitAPI(mDvpTextureHandle);
- // the transfer is now complete and the texture is ready for use
- }
-
-private:
- static uint32_t mBufferAddrAlignment;
- static uint32_t mBufferGpuStrideAlignment;
- static uint32_t mSemaphoreAddrAlignment;
- static uint32_t mSemaphoreAllocSize;
- static uint32_t mSemaphorePayloadOffset;
- static uint32_t mSemaphorePayloadSize;
-
- void clean()
- {
- if (mDvpSysMemHandle) {
- dvpUnbindFromGLCtx(mDvpSysMemHandle);
- dvpDestroyBuffer(mDvpSysMemHandle);
- }
- if (mExtSync)
- delete mExtSync;
- if (mGpuSync)
- delete mGpuSync;
- if (mBuffer)
- _UnpinBuffer(mBuffer, mAllocatedSize);
- }
- SyncInfo* mExtSync;
- SyncInfo* mGpuSync;
- DVPBufferHandle mDvpSysMemHandle;
- DVPBufferHandle mDvpTextureHandle;
- uint32_t mTextureHeight;
- uint32_t mAllocatedSize;
- void* mBuffer;
-};
-
-uint32_t TextureTransferDvp::mBufferAddrAlignment;
-uint32_t TextureTransferDvp::mBufferGpuStrideAlignment;
-uint32_t TextureTransferDvp::mSemaphoreAddrAlignment;
-uint32_t TextureTransferDvp::mSemaphoreAllocSize;
-uint32_t TextureTransferDvp::mSemaphorePayloadOffset;
-uint32_t TextureTransferDvp::mSemaphorePayloadSize;
-
-#endif
-
-////////////////////////////////////////////
-// TextureTransferOGL: transfer using standard OGL buffers
-////////////////////////////////////////////
-
-class TextureTransferOGL : public TextureTransfer
-{
-public:
- TextureTransferOGL(GLuint texId, TextureDesc *pDesc, void *address)
- {
- memcpy(&mDesc, pDesc, sizeof(mDesc));
- mTexId = texId;
- mBuffer = address;
-
- // as we cache transfer object, we will create one texture to hold the buffer
- glGenBuffers(1, &mUnpinnedTextureBuffer);
- // create a storage for it
- glBindBuffer(GL_PIXEL_UNPACK_BUFFER, mUnpinnedTextureBuffer);
- glBufferData(GL_PIXEL_UNPACK_BUFFER, pDesc->size, NULL, GL_DYNAMIC_DRAW);
- glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
- }
- ~TextureTransferOGL()
- {
- glDeleteBuffers(1, &mUnpinnedTextureBuffer);
- }
-
- virtual void PerformTransfer()
- {
- glBindBuffer(GL_PIXEL_UNPACK_BUFFER, mUnpinnedTextureBuffer);
- glBufferSubData(GL_PIXEL_UNPACK_BUFFER, 0, mDesc.size, mBuffer);
- glBindTexture(GL_TEXTURE_2D, mTexId);
- // NULL for last arg indicates use current GL_PIXEL_UNPACK_BUFFER target as texture data
- glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, mDesc.width, mDesc.height, mDesc.format, mDesc.type, NULL);
- glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
- }
-private:
- // intermediate texture to receive the buffer
- GLuint mUnpinnedTextureBuffer;
- // target texture to receive the image
- GLuint mTexId;
- // buffer
- void *mBuffer;
- // characteristic of the image
- TextureDesc mDesc;
-};
-
-////////////////////////////////////////////
-// TextureTransferPMB: transfer using pinned memory buffer
-////////////////////////////////////////////
-
-class TextureTransferPMD : public TextureTransfer
-{
-public:
- TextureTransferPMD(GLuint texId, TextureDesc *pDesc, void *address, uint32_t allocatedSize)
- {
- memcpy(&mDesc, pDesc, sizeof(mDesc));
- mTexId = texId;
- mBuffer = address;
- mAllocatedSize = allocatedSize;
-
- _PinBuffer(address, allocatedSize);
-
- // as we cache transfer object, we will create one texture to hold the buffer
- glGenBuffers(1, &mPinnedTextureBuffer);
- // create a storage for it
- glBindBuffer(GL_EXTERNAL_VIRTUAL_MEMORY_BUFFER_AMD, mPinnedTextureBuffer);
- glBufferData(GL_EXTERNAL_VIRTUAL_MEMORY_BUFFER_AMD, pDesc->size, address, GL_STREAM_DRAW);
- glBindBuffer(GL_EXTERNAL_VIRTUAL_MEMORY_BUFFER_AMD, 0);
- }
- ~TextureTransferPMD()
- {
- glDeleteBuffers(1, &mPinnedTextureBuffer);
- if (mBuffer)
- _UnpinBuffer(mBuffer, mAllocatedSize);
- }
-
- virtual void PerformTransfer()
- {
- glBindBuffer(GL_PIXEL_UNPACK_BUFFER, mPinnedTextureBuffer);
- glBindTexture(GL_TEXTURE_2D, mTexId);
- // NULL for last arg indicates use current GL_PIXEL_UNPACK_BUFFER target as texture data
- glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, mDesc.width, mDesc.height, mDesc.format, mDesc.type, NULL);
- // wait for the trasnfer to complete
- GLsync fence = glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0);
- glClientWaitSync(fence, GL_SYNC_FLUSH_COMMANDS_BIT, 40 * 1000 * 1000); // timeout in nanosec
- glDeleteSync(fence);
- glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
- }
-private:
- // intermediate texture to receive the buffer
- GLuint mPinnedTextureBuffer;
- // target texture to receive the image
- GLuint mTexId;
- // buffer
- void *mBuffer;
- // the allocated size
- uint32_t mAllocatedSize;
- // characteristic of the image
- TextureDesc mDesc;
-};
-
-bool TextureTransfer::_PinBuffer(void *address, uint32_t size)
-{
-#ifdef WIN32
- return VirtualLock(address, size);
-#elif defined(_POSIX_MEMLOCK_RANGE)
- return !mlock(address, size);
-#endif
-}
-
-void TextureTransfer::_UnpinBuffer(void* address, uint32_t size)
-{
-#ifdef WIN32
- VirtualUnlock(address, size);
-#elif defined(_POSIX_MEMLOCK_RANGE)
- munlock(address, size);
-#endif
-}
-
-
-
-////////////////////////////////////////////
-// PinnedMemoryAllocator
-////////////////////////////////////////////
-
-
-// static members
-bool PinnedMemoryAllocator::mGPUDirectInitialized = false;
-bool PinnedMemoryAllocator::mHasDvp = false;
-bool PinnedMemoryAllocator::mHasAMDPinnedMemory = false;
-size_t PinnedMemoryAllocator::mReservedProcessMemory = 0;
-
-bool PinnedMemoryAllocator::ReserveMemory(size_t size)
-{
-#ifdef WIN32
- // Increase the process working set size to allow pinning of memory.
- if (size <= mReservedProcessMemory)
- return true;
- SIZE_T dwMin = 0, dwMax = 0;
- HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_SET_QUOTA, FALSE, GetCurrentProcessId());
- if (!hProcess)
- return false;
-
- // Retrieve the working set size of the process.
- if (!dwMin && !GetProcessWorkingSetSize(hProcess, &dwMin, &dwMax))
- return false;
-
- BOOL res = SetProcessWorkingSetSize(hProcess, (size - mReservedProcessMemory) + dwMin, (size - mReservedProcessMemory) + dwMax);
- if (!res)
- return false;
- mReservedProcessMemory = size;
- CloseHandle(hProcess);
- return true;
-#else
- struct rlimit rlim;
- if (getrlimit(RLIMIT_MEMLOCK, &rlim) == 0) {
- if (rlim.rlim_cur < size) {
- if (rlim.rlim_max < size)
- rlim.rlim_max = size;
- rlim.rlim_cur = size;
- return !setrlimit(RLIMIT_MEMLOCK, &rlim);
- }
- }
- return false;
-#endif
-}
-
-PinnedMemoryAllocator::PinnedMemoryAllocator(unsigned cacheSize, size_t memSize) :
-mRefCount(1U),
-#ifdef WIN32
-mDvpCaptureTextureHandle(0),
-#endif
-mTexId(0),
-mBufferCacheSize(cacheSize)
-{
- pthread_mutex_init(&mMutex, NULL);
- // do it once
- if (!mGPUDirectInitialized) {
-#ifdef WIN32
- // In windows, AMD_pinned_memory option is not available,
- // we must use special DVP API only available for Quadro cards
- const char* renderer = (const char *)glGetString(GL_RENDERER);
- mHasDvp = (strstr(renderer, "Quadro") != NULL);
-
- if (mHasDvp) {
- // In case the DLL is not in place, don't fail, just fallback on OpenGL
- if (dvpInitGLContext(DVP_DEVICE_FLAGS_SHARE_APP_CONTEXT) != DVP_STATUS_OK) {
- printf("Warning: Could not initialize DVP context, fallback on OpenGL transfer.\nInstall dvp.dll to take advantage of nVidia GPUDirect.\n");
- mHasDvp = false;
- }
- }
-#endif
- if (GLEW_AMD_pinned_memory)
- mHasAMDPinnedMemory = true;
-
- mGPUDirectInitialized = true;
- }
- if (mHasDvp || mHasAMDPinnedMemory) {
- ReserveMemory(memSize);
- }
-}
-
-PinnedMemoryAllocator::~PinnedMemoryAllocator()
-{
- void *address;
- // first clean the cache if not already done
- while (!mBufferCache.empty()) {
- address = mBufferCache.back();
- mBufferCache.pop_back();
- _ReleaseBuffer(address);
- }
- // clean preallocated buffers
- while (!mAllocatedSize.empty()) {
- address = mAllocatedSize.begin()->first;
- _ReleaseBuffer(address);
- }
-
-#ifdef WIN32
- if (mDvpCaptureTextureHandle)
- dvpDestroyBuffer(mDvpCaptureTextureHandle);
-#endif
-}
-
-void PinnedMemoryAllocator::TransferBuffer(void* address, TextureDesc* texDesc, GLuint texId)
-{
- uint32_t allocatedSize = 0;
- TextureTransfer *pTransfer = NULL;
-
- Lock();
- if (mAllocatedSize.count(address) > 0)
- allocatedSize = mAllocatedSize[address];
- Unlock();
- if (!allocatedSize)
- // internal error!!
- return;
- if (mTexId != texId)
- {
- // first time we try to send data to the GPU, allocate a buffer for the texture
- glBindTexture(GL_TEXTURE_2D, texId);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
- glTexImage2D(GL_TEXTURE_2D, 0, texDesc->internalFormat, texDesc->width, texDesc->height, 0, texDesc->format, texDesc->type, NULL);
- glBindTexture(GL_TEXTURE_2D, 0);
- mTexId = texId;
- }
-#ifdef WIN32
- if (mHasDvp)
- {
- if (!mDvpCaptureTextureHandle)
- {
- // bind DVP to the OGL texture
- DVP_CHECK(dvpCreateGPUTextureGL(texId, &mDvpCaptureTextureHandle));
- }
- }
-#endif
- Lock();
- if (mPinnedBuffer.count(address) > 0)
- {
- pTransfer = mPinnedBuffer[address];
- }
- Unlock();
- if (!pTransfer)
- {
-#ifdef WIN32
- if (mHasDvp)
- pTransfer = new TextureTransferDvp(mDvpCaptureTextureHandle, texDesc, address, allocatedSize);
- else
-#endif
- if (mHasAMDPinnedMemory) {
- pTransfer = new TextureTransferPMD(texId, texDesc, address, allocatedSize);
- }
- else {
- pTransfer = new TextureTransferOGL(texId, texDesc, address);
- }
- if (pTransfer)
- {
- Lock();
- mPinnedBuffer[address] = pTransfer;
- Unlock();
- }
- }
- if (pTransfer)
- pTransfer->PerformTransfer();
-}
-
-// IUnknown methods
-HRESULT STDMETHODCALLTYPE PinnedMemoryAllocator::QueryInterface(REFIID /*iid*/, LPVOID* /*ppv*/)
-{
- return E_NOTIMPL;
-}
-
-ULONG STDMETHODCALLTYPE PinnedMemoryAllocator::AddRef(void)
-{
- return atomic_add_and_fetch_uint32(&mRefCount, 1U);
-}
-
-ULONG STDMETHODCALLTYPE PinnedMemoryAllocator::Release(void)
-{
- uint32_t newCount = atomic_sub_and_fetch_uint32(&mRefCount, 1U);
- if (newCount == 0)
- delete this;
- return (ULONG)newCount;
-}
-
-// IDeckLinkMemoryAllocator methods
-HRESULT STDMETHODCALLTYPE PinnedMemoryAllocator::AllocateBuffer(dl_size_t bufferSize, void* *allocatedBuffer)
-{
- Lock();
- if (mBufferCache.empty())
- {
- // Allocate memory on a page boundary
- // Note: aligned alloc exist in Blender but only for small alignment, use direct allocation then.
- // Note: the DeckLink API tries to allocate up to 65 buffer in advance, we will limit this to 3
- // because we don't need any caching
- if (mAllocatedSize.size() >= mBufferCacheSize)
- *allocatedBuffer = NULL;
- else {
-#ifdef WIN32
- *allocatedBuffer = VirtualAlloc(NULL, bufferSize, MEM_COMMIT | MEM_RESERVE | MEM_WRITE_WATCH, PAGE_READWRITE);
-#else
- if (posix_memalign(allocatedBuffer, 4096, bufferSize) != 0)
- *allocatedBuffer = NULL;
-#endif
- mAllocatedSize[*allocatedBuffer] = bufferSize;
- }
- }
- else {
- // Re-use most recently ReleaseBuffer'd address
- *allocatedBuffer = mBufferCache.back();
- mBufferCache.pop_back();
- }
- Unlock();
- return (*allocatedBuffer) ? S_OK : E_OUTOFMEMORY;
-}
-
-HRESULT STDMETHODCALLTYPE PinnedMemoryAllocator::ReleaseBuffer(void* buffer)
-{
- HRESULT result = S_OK;
- Lock();
- if (mBufferCache.size() < mBufferCacheSize) {
- mBufferCache.push_back(buffer);
- }
- else {
- result = _ReleaseBuffer(buffer);
- }
- Unlock();
- return result;
-}
-
-
-HRESULT PinnedMemoryAllocator::_ReleaseBuffer(void* buffer)
-{
- TextureTransfer *pTransfer;
- if (mAllocatedSize.count(buffer) == 0) {
- // Internal error!!
- return S_OK;
- }
- else {
- // No room left in cache, so un-pin (if it was pinned) and free this buffer
- if (mPinnedBuffer.count(buffer) > 0) {
- pTransfer = mPinnedBuffer[buffer];
- mPinnedBuffer.erase(buffer);
- delete pTransfer;
- }
-#ifdef WIN32
- VirtualFree(buffer, 0, MEM_RELEASE);
-#else
- free(buffer);
-#endif
- mAllocatedSize.erase(buffer);
- }
- return S_OK;
-}
-
-HRESULT STDMETHODCALLTYPE PinnedMemoryAllocator::Commit()
-{
- return S_OK;
-}
-
-HRESULT STDMETHODCALLTYPE PinnedMemoryAllocator::Decommit()
-{
- void *buffer;
- Lock();
- while (!mBufferCache.empty()) {
- // Cleanup any frames allocated and pinned in AllocateBuffer() but not freed in ReleaseBuffer()
- buffer = mBufferCache.back();
- mBufferCache.pop_back();
- _ReleaseBuffer(buffer);
- }
- Unlock();
- return S_OK;
-}
-
-
-////////////////////////////////////////////
-// Capture Delegate Class
-////////////////////////////////////////////
-
-CaptureDelegate::CaptureDelegate(VideoDeckLink* pOwner) : mpOwner(pOwner)
-{
-}
-
-HRESULT CaptureDelegate::VideoInputFrameArrived(IDeckLinkVideoInputFrame* inputFrame, IDeckLinkAudioInputPacket* /*audioPacket*/)
-{
- if (!inputFrame) {
- // It's possible to receive a NULL inputFrame, but a valid audioPacket. Ignore audio-only frame.
- return S_OK;
- }
- if ((inputFrame->GetFlags() & bmdFrameHasNoInputSource) == bmdFrameHasNoInputSource) {
- // let's not bother transferring frames if there is no source
- return S_OK;
- }
- mpOwner->VideoFrameArrived(inputFrame);
- return S_OK;
-}
-
-HRESULT CaptureDelegate::VideoInputFormatChanged(BMDVideoInputFormatChangedEvents notificationEvents, IDeckLinkDisplayMode *newDisplayMode, BMDDetectedVideoInputFormatFlags detectedSignalFlags)
-{
- return S_OK;
-}
-
-
-
-
-// macro for exception handling and logging
-#define CATCH_EXCP catch (Exception & exp) \
-{ exp.report(); m_status = SourceError; }
-
-// class VideoDeckLink
-
-
-// constructor
-VideoDeckLink::VideoDeckLink (HRESULT * hRslt) : VideoBase(),
-mDLInput(NULL),
-mUse3D(false),
-mFrameWidth(0),
-mFrameHeight(0),
-mpAllocator(NULL),
-mpCaptureDelegate(NULL),
-mpCacheFrame(NULL),
-mClosing(false)
-{
- mDisplayMode = (BMDDisplayMode)0;
- mPixelFormat = (BMDPixelFormat)0;
- pthread_mutex_init(&mCacheMutex, NULL);
-}
-
-// destructor
-VideoDeckLink::~VideoDeckLink ()
-{
- LockCache();
- mClosing = true;
- if (mpCacheFrame)
- {
- mpCacheFrame->Release();
- mpCacheFrame = NULL;
- }
- UnlockCache();
- if (mDLInput != NULL)
- {
- // Cleanup for Capture
- mDLInput->StopStreams();
- mDLInput->SetCallback(NULL);
- mDLInput->DisableVideoInput();
- mDLInput->DisableAudioInput();
- mDLInput->FlushStreams();
- if (mDLInput->Release() != 0) {
- printf("Reference count not NULL on DeckLink device when closing it, please report!\n");
- }
- mDLInput = NULL;
- }
-
- if (mpAllocator)
- {
- // if the device was properly cleared, this should be 0
- if (mpAllocator->Release() != 0) {
- printf("Reference count not NULL on Allocator when closing it, please report!\n");
- }
- mpAllocator = NULL;
- }
- if (mpCaptureDelegate)
- {
- delete mpCaptureDelegate;
- mpCaptureDelegate = NULL;
- }
-}
-
-void VideoDeckLink::refresh(void)
-{
- m_avail = false;
-}
-
-// release components
-bool VideoDeckLink::release()
-{
- // release
- return true;
-}
-
-// open video file
-void VideoDeckLink::openFile (char *filename)
-{
- // only live capture on this device
- THRWEXCP(SourceVideoOnlyCapture, S_OK);
-}
-
-
-// open video capture device
-void VideoDeckLink::openCam (char *format, short camIdx)
-{
- IDeckLinkDisplayModeIterator* pDLDisplayModeIterator;
- BMDDisplayModeSupport modeSupport;
- IDeckLinkDisplayMode* pDLDisplayMode;
- IDeckLinkIterator* pIterator;
- BMDTimeValue frameDuration;
- BMDTimeScale frameTimescale;
- IDeckLink* pDL;
- uint32_t displayFlags, inputFlags;
- char *pPixel, *p3D, *pEnd, *pSize;
- size_t len;
- int i, modeIdx, cacheSize;
-
- // format is constructed as <displayMode>/<pixelFormat>[/3D][:<cacheSize>]
- // <displayMode> takes the form of BMDDisplayMode identifier minus the 'bmdMode' prefix.
- // This implementation understands all the modes defined in SDK 10.3.1 but you can alternatively
- // use the 4 characters internal representation of the mode (e.g. 'HD1080p24' == '24ps')
- // <pixelFormat> takes the form of BMDPixelFormat identifier minus the 'bmdFormat' prefix.
- // This implementation understand all the formats defined in SDK 10.32.1 but you can alternatively
- // use the 4 characters internal representation of the format (e.g. '10BitRGB' == 'r210')
- // Not all combinations of mode and pixel format are possible and it also depends on the card!
- // Use /3D postfix if you are capturing a 3D stream with frame packing
- // Example: To capture FullHD 1920x1080@24Hz with 3D packing and 4:4:4 10 bits RGB pixel format, use
- // "HD1080p24/10BitRGB/3D" (same as "24ps/r210/3D")
- // (this will be the normal capture format for FullHD on the DeckLink 4k extreme)
-
- if ((pSize = strchr(format, ':')) != NULL) {
- cacheSize = strtol(pSize+1, &pEnd, 10);
- }
- else {
- cacheSize = 8;
- pSize = format + strlen(format);
- }
- if ((pPixel = strchr(format, '/')) == NULL ||
- ((p3D = strchr(pPixel + 1, '/')) != NULL && strncmp(p3D, "/3D", pSize-p3D)))
- THRWEXCP(VideoDeckLinkBadFormat, S_OK);
- mUse3D = (p3D) ? true : false;
- // to simplify pixel format parsing
- if (!p3D)
- p3D = pSize;
-
- // read the mode
- len = (size_t)(pPixel - format);
- // accept integer display mode
-
- try {
- // throws if bad mode
- decklink_ReadDisplayMode(format, len, &mDisplayMode);
- // found a valid mode, remember that we do not look for an index
- modeIdx = -1;
- }
- catch (Exception &) {
- // accept also purely numerical mode as a mode index
- modeIdx = strtol(format, &pEnd, 10);
- if (pEnd != pPixel || modeIdx < 0)
- // not a pure number, give up
- throw;
- }
-
- // skip /
- pPixel++;
- len = (size_t)(p3D - pPixel);
- // throws if bad format
- decklink_ReadPixelFormat(pPixel, len, &mPixelFormat);
-
- // Caution: DeckLink API used from this point, make sure entity are released before throwing
- // open the card
- pIterator = BMD_CreateDeckLinkIterator();
- if (pIterator) {
- i = 0;
- while (pIterator->Next(&pDL) == S_OK) {
- if (i == camIdx) {
- if (pDL->QueryInterface(IID_IDeckLinkInput, (void**)&mDLInput) != S_OK)
- mDLInput = NULL;
- pDL->Release();
- break;
- }
- i++;
- pDL->Release();
- }
- pIterator->Release();
- }
- if (!mDLInput)
- THRWEXCP(VideoDeckLinkOpenCard, S_OK);
-
-
- // check if display mode and pixel format are supported
- if (mDLInput->GetDisplayModeIterator(&pDLDisplayModeIterator) != S_OK)
- THRWEXCP(DeckLinkInternalError, S_OK);
-
- pDLDisplayMode = NULL;
- displayFlags = (mUse3D) ? bmdDisplayModeSupports3D : 0;
- inputFlags = (mUse3D) ? bmdVideoInputDualStream3D : bmdVideoInputFlagDefault;
- while (pDLDisplayModeIterator->Next(&pDLDisplayMode) == S_OK)
- {
- if (modeIdx == 0 || pDLDisplayMode->GetDisplayMode() == mDisplayMode) {
- // in case we get here because of modeIdx, make sure we have mDisplayMode set
- mDisplayMode = pDLDisplayMode->GetDisplayMode();
- if ((pDLDisplayMode->GetFlags() & displayFlags) == displayFlags &&
- mDLInput->DoesSupportVideoMode(mDisplayMode, mPixelFormat, inputFlags, &modeSupport, NULL) == S_OK &&
- modeSupport == bmdDisplayModeSupported)
- {
- break;
- }
- }
- pDLDisplayMode->Release();
- pDLDisplayMode = NULL;
- if (modeIdx-- == 0) {
- // reached the correct mode index but it does not meet the pixel format, give up
- break;
- }
- }
- pDLDisplayModeIterator->Release();
-
- if (pDLDisplayMode == NULL)
- THRWEXCP(VideoDeckLinkBadFormat, S_OK);
-
- mFrameWidth = pDLDisplayMode->GetWidth();
- mFrameHeight = pDLDisplayMode->GetHeight();
- mTextureDesc.height = (mUse3D) ? 2 * mFrameHeight : mFrameHeight;
- pDLDisplayMode->GetFrameRate(&frameDuration, &frameTimescale);
- pDLDisplayMode->Release();
- // for information, in case the application wants to know
- m_size[0] = mFrameWidth;
- m_size[1] = mTextureDesc.height;
- m_frameRate = (float)frameTimescale / (float)frameDuration;
-
- switch (mPixelFormat)
- {
- case bmdFormat8BitYUV:
- // 2 pixels per word
- mTextureDesc.stride = mFrameWidth * 2;
- mTextureDesc.width = mFrameWidth / 2;
- mTextureDesc.internalFormat = GL_RGBA;
- mTextureDesc.format = GL_BGRA;
- mTextureDesc.type = GL_UNSIGNED_BYTE;
- break;
- case bmdFormat10BitYUV:
- // 6 pixels in 4 words, rounded to 48 pixels
- mTextureDesc.stride = ((mFrameWidth + 47) / 48) * 128;
- mTextureDesc.width = mTextureDesc.stride/4;
- mTextureDesc.internalFormat = GL_RGB10_A2;
- mTextureDesc.format = GL_BGRA;
- mTextureDesc.type = GL_UNSIGNED_INT_2_10_10_10_REV;
- break;
- case bmdFormat8BitARGB:
- mTextureDesc.stride = mFrameWidth * 4;
- mTextureDesc.width = mFrameWidth;
- mTextureDesc.internalFormat = GL_RGBA;
- mTextureDesc.format = GL_BGRA;
- mTextureDesc.type = GL_UNSIGNED_INT_8_8_8_8;
- break;
- case bmdFormat8BitBGRA:
- mTextureDesc.stride = mFrameWidth * 4;
- mTextureDesc.width = mFrameWidth;
- mTextureDesc.internalFormat = GL_RGBA;
- mTextureDesc.format = GL_BGRA;
- mTextureDesc.type = GL_UNSIGNED_BYTE;
- break;
- case bmdFormat10BitRGBXLE:
- // 1 pixel per word, rounded to 64 pixels
- mTextureDesc.stride = ((mFrameWidth + 63) / 64) * 256;
- mTextureDesc.width = mTextureDesc.stride/4;
- mTextureDesc.internalFormat = GL_RGB10_A2;
- mTextureDesc.format = GL_RGBA;
- mTextureDesc.type = GL_UNSIGNED_INT_10_10_10_2;
- break;
- case bmdFormat10BitRGBX:
- case bmdFormat10BitRGB:
- // 1 pixel per word, rounded to 64 pixels
- mTextureDesc.stride = ((mFrameWidth + 63) / 64) * 256;
- mTextureDesc.width = mTextureDesc.stride/4;
- mTextureDesc.internalFormat = GL_R32UI;
- mTextureDesc.format = GL_RED_INTEGER;
- mTextureDesc.type = GL_UNSIGNED_INT;
- break;
- case bmdFormat12BitRGB:
- case bmdFormat12BitRGBLE:
- // 8 pixels in 9 word
- mTextureDesc.stride = (mFrameWidth * 36) / 8;
- mTextureDesc.width = mTextureDesc.stride/4;
- mTextureDesc.internalFormat = GL_R32UI;
- mTextureDesc.format = GL_RED_INTEGER;
- mTextureDesc.type = GL_UNSIGNED_INT;
- break;
- default:
- // for unknown pixel format, this will be resolved when a frame arrives
- mTextureDesc.format = GL_RED_INTEGER;
- mTextureDesc.type = GL_UNSIGNED_INT;
- break;
- }
- // reserve memory for cache frame + 1 to accomodate for pixel format that we don't know yet
- // note: we can't use stride as it is not yet known if the pixel format is unknown
- // use instead the frame width as in worst case it's not much different (e.g. HD720/10BITYUV: 1296 pixels versus 1280)
- // note: some pixel format take more than 4 bytes take that into account (9/8 versus 1)
- mpAllocator = new PinnedMemoryAllocator(cacheSize, mFrameWidth*mTextureDesc.height * 4 * (1+cacheSize*9/8));
-
- if (mDLInput->SetVideoInputFrameMemoryAllocator(mpAllocator) != S_OK)
- THRWEXCP(DeckLinkInternalError, S_OK);
-
- mpCaptureDelegate = new CaptureDelegate(this);
- if (mDLInput->SetCallback(mpCaptureDelegate) != S_OK)
- THRWEXCP(DeckLinkInternalError, S_OK);
-
- if (mDLInput->EnableVideoInput(mDisplayMode, mPixelFormat, ((mUse3D) ? bmdVideoInputDualStream3D : bmdVideoInputFlagDefault)) != S_OK)
- // this shouldn't failed, we tested above
- THRWEXCP(DeckLinkInternalError, S_OK);
-
- // just in case it is needed to capture from certain cards, we don't check error because we don't need audio
- mDLInput->EnableAudioInput(bmdAudioSampleRate48kHz, bmdAudioSampleType16bitInteger, 2);
-
- // open base class
- VideoBase::openCam(format, camIdx);
-
- // ready to capture, will start when application calls play()
-}
-
-// play video
-bool VideoDeckLink::play (void)
-{
- try
- {
- // if object is able to play
- if (VideoBase::play())
- {
- mDLInput->FlushStreams();
- return (mDLInput->StartStreams() == S_OK);
- }
- }
- CATCH_EXCP;
- return false;
-}
-
-
-// pause video
-bool VideoDeckLink::pause (void)
-{
- try
- {
- if (VideoBase::pause())
- {
- mDLInput->PauseStreams();
- return true;
- }
- }
- CATCH_EXCP;
- return false;
-}
-
-// stop video
-bool VideoDeckLink::stop (void)
-{
- try
- {
- VideoBase::stop();
- mDLInput->StopStreams();
- return true;
- }
- CATCH_EXCP;
- return false;
-}
-
-
-// set video range
-void VideoDeckLink::setRange (double start, double stop)
-{
-}
-
-// set framerate
-void VideoDeckLink::setFrameRate (float rate)
-{
-}
-
-
-// image calculation
-// send cache frame directly to GPU
-void VideoDeckLink::calcImage (unsigned int texId, double ts)
-{
- IDeckLinkVideoInputFrame* pFrame;
- LockCache();
- pFrame = mpCacheFrame;
- mpCacheFrame = NULL;
- UnlockCache();
- if (pFrame) {
- // BUG: the dvpBindToGLCtx function fails the first time it is used, don't know why.
- // This causes an exception to be thrown.
- // This should be fixed but in the meantime we will catch the exception because
- // it is crucial that we release the frame to keep the reference count right on the DeckLink device
- try {
- uint32_t rowSize = pFrame->GetRowBytes();
- uint32_t textureSize = rowSize * pFrame->GetHeight();
- void* videoPixels = NULL;
- void* rightEyePixels = NULL;
- if (!mTextureDesc.stride) {
- // we could not compute the texture size earlier (unknown pixel size)
- // let's do it now
- mTextureDesc.stride = rowSize;
- mTextureDesc.width = mTextureDesc.stride / 4;
- }
- if (mTextureDesc.stride != rowSize) {
- // unexpected frame size, ignore
- // TBD: print a warning
- }
- else {
- pFrame->GetBytes(&videoPixels);
- if (mUse3D) {
- IDeckLinkVideoFrame3DExtensions *if3DExtensions = NULL;
- IDeckLinkVideoFrame *rightEyeFrame = NULL;
- if (pFrame->QueryInterface(IID_IDeckLinkVideoFrame3DExtensions, (void **)&if3DExtensions) == S_OK &&
- if3DExtensions->GetFrameForRightEye(&rightEyeFrame) == S_OK) {
- rightEyeFrame->GetBytes(&rightEyePixels);
- textureSize += ((uint64_t)rightEyePixels - (uint64_t)videoPixels);
- }
- if (rightEyeFrame)
- rightEyeFrame->Release();
- if (if3DExtensions)
- if3DExtensions->Release();
- }
- mTextureDesc.size = mTextureDesc.width * mTextureDesc.height * 4;
- if (mTextureDesc.size == textureSize) {
- // this means that both left and right frame are contiguous and that there is no padding
- // do the transfer
- mpAllocator->TransferBuffer(videoPixels, &mTextureDesc, texId);
- }
- }
- }
- catch (Exception &) {
- pFrame->Release();
- throw;
- }
- // this will trigger PinnedMemoryAllocator::RealaseBuffer
- pFrame->Release();
- }
- // currently we don't pass the image to the application
- m_avail = false;
-}
-
-// A frame is available from the board
-// Called from an internal thread, just pass the frame to the main thread
-void VideoDeckLink::VideoFrameArrived(IDeckLinkVideoInputFrame* inputFrame)
-{
- IDeckLinkVideoInputFrame* pOldFrame = NULL;
- LockCache();
- if (!mClosing)
- {
- pOldFrame = mpCacheFrame;
- mpCacheFrame = inputFrame;
- inputFrame->AddRef();
- }
- UnlockCache();
- // old frame no longer needed, just release it
- if (pOldFrame)
- pOldFrame->Release();
-}
-
-// python methods
-
-// object initialization
-static int VideoDeckLink_init(PyObject *pySelf, PyObject *args, PyObject *kwds)
-{
- static const char *kwlist[] = { "format", "capture", NULL };
- PyImage *self = reinterpret_cast<PyImage*>(pySelf);
- // see openCam for a description of format
- char * format = NULL;
- // capture device number, i.e. DeckLink card number, default first one
- short capt = 0;
-
- if (!GLEW_VERSION_1_5) {
- PyErr_SetString(PyExc_RuntimeError, "VideoDeckLink requires at least OpenGL 1.5");
- return -1;
- }
- // get parameters
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|h",
- const_cast<char**>(kwlist), &format, &capt))
- return -1;
-
- try {
- // create video object
- Video_init<VideoDeckLink>(self);
-
- // open video source, control comes back to VideoDeckLink::openCam
- Video_open(getVideo(self), format, capt);
- }
- catch (Exception & exp) {
- exp.report();
- return -1;
- }
- // initialization succeded
- return 0;
-}
-
-// methods structure
-static PyMethodDef videoMethods[] =
-{ // methods from VideoBase class
- {"play", (PyCFunction)Video_play, METH_NOARGS, "Play (restart) video"},
- {"pause", (PyCFunction)Video_pause, METH_NOARGS, "pause video"},
- {"stop", (PyCFunction)Video_stop, METH_NOARGS, "stop video (play will replay it from start)"},
- {"refresh", (PyCFunction)Video_refresh, METH_VARARGS, "Refresh video - get its status"},
- {NULL}
-};
-// attributes structure
-static PyGetSetDef videoGetSets[] =
-{ // methods from VideoBase class
- {(char*)"status", (getter)Video_getStatus, NULL, (char*)"video status", NULL},
- {(char*)"framerate", (getter)Video_getFrameRate, NULL, (char*)"frame rate", NULL},
- // attributes from ImageBase class
- {(char*)"valid", (getter)Image_valid, NULL, (char*)"bool to tell if an image is available", NULL},
- {(char*)"image", (getter)Image_getImage, NULL, (char*)"image data", NULL},
- {(char*)"size", (getter)Image_getSize, NULL, (char*)"image size", NULL},
- {(char*)"scale", (getter)Image_getScale, (setter)Image_setScale, (char*)"fast scale of image (near neighbor)", NULL},
- {(char*)"flip", (getter)Image_getFlip, (setter)Image_setFlip, (char*)"flip image vertically", NULL},
- {(char*)"filter", (getter)Image_getFilter, (setter)Image_setFilter, (char*)"pixel filter", NULL},
- {NULL}
-};
-
-// python type declaration
-PyTypeObject VideoDeckLinkType =
-{
- PyVarObject_HEAD_INIT(NULL, 0)
- "VideoTexture.VideoDeckLink", /*tp_name*/
- sizeof(PyImage), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- (destructor)Image_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- 0, /*tp_getattr*/
- 0, /*tp_setattr*/
- 0, /*tp_compare*/
- 0, /*tp_repr*/
- 0, /*tp_as_number*/
- 0, /*tp_as_sequence*/
- 0, /*tp_as_mapping*/
- 0, /*tp_hash */
- 0, /*tp_call*/
- 0, /*tp_str*/
- 0, /*tp_getattro*/
- 0, /*tp_setattro*/
- &imageBufferProcs, /*tp_as_buffer*/
- Py_TPFLAGS_DEFAULT, /*tp_flags*/
- "DeckLink video source", /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- videoMethods, /* tp_methods */
- 0, /* tp_members */
- videoGetSets, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- (initproc)VideoDeckLink_init, /* tp_init */
- 0, /* tp_alloc */
- Image_allocNew, /* tp_new */
-};
-
-
-
-////////////////////////////////////////////
-// DeckLink Capture Delegate Class
-////////////////////////////////////////////
-
-#endif // WITH_GAMEENGINE_DECKLINK
-
diff --git a/source/gameengine/VideoTexture/VideoDeckLink.h b/source/gameengine/VideoTexture/VideoDeckLink.h
deleted file mode 100644
index d5419176691..00000000000
--- a/source/gameengine/VideoTexture/VideoDeckLink.h
+++ /dev/null
@@ -1,256 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2015, Blender Foundation
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): Blender Foundation.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file VideoDeckLink.h
- * \ingroup bgevideotex
- */
-
-#ifndef __VIDEODECKLINK_H__
-#define __VIDEODECKLINK_H__
-
-#ifdef WITH_GAMEENGINE_DECKLINK
-
-/* this needs to be parsed with __cplusplus defined before included through DeckLink_compat.h */
-#if defined(__FreeBSD__)
-# include <inttypes.h>
-#endif
-#include <map>
-#include <set>
-
-extern "C" {
-#include <pthread.h>
-#include "DNA_listBase.h"
-#include "BLI_threads.h"
-#include "BLI_blenlib.h"
-}
-#include "GPU_glew.h"
-#ifdef WIN32
-#include "dvpapi.h"
-#endif
-#include "DeckLinkAPI.h"
-#include "VideoBase.h"
-
-class PinnedMemoryAllocator;
-
-struct TextureDesc
-{
- uint32_t width;
- uint32_t height;
- uint32_t stride;
- uint32_t size;
- GLenum internalFormat;
- GLenum format;
- GLenum type;
- TextureDesc()
- {
- width = 0;
- height = 0;
- stride = 0;
- size = 0;
- internalFormat = 0;
- format = 0;
- type = 0;
- }
-};
-
-class CaptureDelegate;
-
-// type VideoDeckLink declaration
-class VideoDeckLink : public VideoBase
-{
- friend class CaptureDelegate;
-public:
- /// constructor
- VideoDeckLink (HRESULT * hRslt);
- /// destructor
- virtual ~VideoDeckLink ();
-
- /// open video/image file
- virtual void openFile(char *file);
- /// open video capture device
- virtual void openCam(char *driver, short camIdx);
-
- /// release video source
- virtual bool release (void);
- /// overwrite base refresh to handle fixed image
- virtual void refresh(void);
- /// play video
- virtual bool play (void);
- /// pause video
- virtual bool pause (void);
- /// stop video
- virtual bool stop (void);
- /// set play range
- virtual void setRange (double start, double stop);
- /// set frame rate
- virtual void setFrameRate (float rate);
-
-protected:
- // format and codec information
- /// image calculation
- virtual void calcImage (unsigned int texId, double ts);
-
-private:
- void VideoFrameArrived(IDeckLinkVideoInputFrame* inputFrame);
- void LockCache()
- {
- pthread_mutex_lock(&mCacheMutex);
- }
- void UnlockCache()
- {
- pthread_mutex_unlock(&mCacheMutex);
- }
-
- IDeckLinkInput* mDLInput;
- BMDDisplayMode mDisplayMode;
- BMDPixelFormat mPixelFormat;
- bool mUse3D;
- uint32_t mFrameWidth;
- uint32_t mFrameHeight;
- TextureDesc mTextureDesc;
- PinnedMemoryAllocator* mpAllocator;
- CaptureDelegate* mpCaptureDelegate;
-
- // cache frame in transit between the callback thread and the main BGE thread
- // keep only one frame in cache because we just want to keep up with real time
- pthread_mutex_t mCacheMutex;
- IDeckLinkVideoInputFrame* mpCacheFrame;
- bool mClosing;
-
-};
-
-inline VideoDeckLink *getDeckLink(PyImage *self)
-{
- return static_cast<VideoDeckLink*>(self->m_image);
-}
-
-////////////////////////////////////////////
-// TextureTransfer : Abstract class to perform a transfer to GPU memory using fast transfer if available
-////////////////////////////////////////////
-class TextureTransfer
-{
-public:
- TextureTransfer() {}
- virtual ~TextureTransfer() { }
-
- virtual void PerformTransfer() = 0;
-protected:
- static bool _PinBuffer(void *address, uint32_t size);
- static void _UnpinBuffer(void* address, uint32_t size);
-};
-
-////////////////////////////////////////////
-// PinnedMemoryAllocator
-////////////////////////////////////////////
-
-// PinnedMemoryAllocator implements the IDeckLinkMemoryAllocator interface and can be used instead of the
-// built-in frame allocator, by setting with SetVideoInputFrameMemoryAllocator() or SetVideoOutputFrameMemoryAllocator().
-//
-// For this sample application a custom frame memory allocator is used to ensure each address
-// of frame memory is aligned on a 4kB boundary required by the OpenGL pinned memory extension.
-// If the pinned memory extension is not available, this allocator will still be used and
-// demonstrates how to cache frame allocations for efficiency.
-//
-// The frame cache delays the releasing of buffers until the cache fills up, thereby avoiding an
-// allocate plus pin operation for every frame, followed by an unpin and deallocate on every frame.
-
-
-class PinnedMemoryAllocator : public IDeckLinkMemoryAllocator
-{
-public:
- PinnedMemoryAllocator(unsigned cacheSize, size_t memSize);
- virtual ~PinnedMemoryAllocator();
-
- void TransferBuffer(void* address, TextureDesc* texDesc, GLuint texId);
-
- // IUnknown methods
- virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, LPVOID *ppv);
- virtual ULONG STDMETHODCALLTYPE AddRef(void);
- virtual ULONG STDMETHODCALLTYPE Release(void);
-
- // IDeckLinkMemoryAllocator methods
- virtual HRESULT STDMETHODCALLTYPE AllocateBuffer(dl_size_t bufferSize, void* *allocatedBuffer);
- virtual HRESULT STDMETHODCALLTYPE ReleaseBuffer(void* buffer);
- virtual HRESULT STDMETHODCALLTYPE Commit();
- virtual HRESULT STDMETHODCALLTYPE Decommit();
-
-private:
- static bool mGPUDirectInitialized;
- static bool mHasDvp;
- static bool mHasAMDPinnedMemory;
- static size_t mReservedProcessMemory;
- static bool ReserveMemory(size_t size);
-
- void Lock()
- {
- pthread_mutex_lock(&mMutex);
- }
- void Unlock()
- {
- pthread_mutex_unlock(&mMutex);
- }
- HRESULT _ReleaseBuffer(void* buffer);
-
- uint32_t mRefCount;
- // protect the cache and the allocated map,
- // not the pinnedBuffer map as it is only used from main thread
- pthread_mutex_t mMutex;
- std::map<void*, uint32_t> mAllocatedSize;
- std::vector<void*> mBufferCache;
- std::map<void *, TextureTransfer*> mPinnedBuffer;
-#ifdef WIN32
- DVPBufferHandle mDvpCaptureTextureHandle;
-#endif
- // target texture in GPU
- GLuint mTexId;
- uint32_t mBufferCacheSize;
-};
-
-////////////////////////////////////////////
-// Capture Delegate Class
-////////////////////////////////////////////
-
-class CaptureDelegate : public IDeckLinkInputCallback
-{
- VideoDeckLink* mpOwner;
-
-public:
- CaptureDelegate(VideoDeckLink* pOwner);
-
- // IUnknown needs only a dummy implementation
- virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, LPVOID *ppv) { return E_NOINTERFACE; }
- virtual ULONG STDMETHODCALLTYPE AddRef() { return 1; }
- virtual ULONG STDMETHODCALLTYPE Release() { return 1; }
-
- virtual HRESULT STDMETHODCALLTYPE VideoInputFrameArrived(IDeckLinkVideoInputFrame *videoFrame, IDeckLinkAudioInputPacket *audioPacket);
- virtual HRESULT STDMETHODCALLTYPE VideoInputFormatChanged(BMDVideoInputFormatChangedEvents notificationEvents, IDeckLinkDisplayMode *newDisplayMode, BMDDetectedVideoInputFormatFlags detectedSignalFlags);
-};
-
-
-#endif /* WITH_GAMEENGINE_DECKLINK */
-
-#endif /* __VIDEODECKLINK_H__ */
diff --git a/source/gameengine/VideoTexture/VideoFFmpeg.cpp b/source/gameengine/VideoTexture/VideoFFmpeg.cpp
deleted file mode 100644
index 11ec97ca5f8..00000000000
--- a/source/gameengine/VideoTexture/VideoFFmpeg.cpp
+++ /dev/null
@@ -1,1392 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * Copyright (c) 2007 The Zdeno Ash Miklas
- *
- * This source file is part of VideoTexture library
- *
- * Contributor(s):
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/VideoTexture/VideoFFmpeg.cpp
- * \ingroup bgevideotex
- */
-
-
-#ifdef WITH_FFMPEG
-
-// INT64_C fix for some linux machines (C99ism)
-#ifndef __STDC_CONSTANT_MACROS
-#define __STDC_CONSTANT_MACROS
-#ifdef __STDC_CONSTANT_MACROS /* quiet warning */
-#endif
-#endif
-
-#include <stdint.h>
-
-
-#include "MEM_guardedalloc.h"
-#include "PIL_time.h"
-
-#include <string>
-
-#include "VideoFFmpeg.h"
-#include "Exception.h"
-
-
-// default framerate
-const double defFrameRate = 25.0;
-
-// macro for exception handling and logging
-#define CATCH_EXCP catch (Exception & exp) \
-{ exp.report(); m_status = SourceError; }
-
-// class RenderVideo
-
-// constructor
-VideoFFmpeg::VideoFFmpeg (HRESULT * hRslt) : VideoBase(),
-m_codec(NULL), m_formatCtx(NULL), m_codecCtx(NULL),
-m_frame(NULL), m_frameDeinterlaced(NULL), m_frameRGB(NULL), m_imgConvertCtx(NULL),
-m_deinterlace(false), m_preseek(0), m_videoStream(-1), m_baseFrameRate(25.0),
-m_lastFrame(-1), m_eof(false), m_externTime(false), m_curPosition(-1), m_startTime(0),
-m_captWidth(0), m_captHeight(0), m_captRate(0.f), m_isImage(false),
-m_isThreaded(false), m_isStreaming(false), m_stopThread(false), m_cacheStarted(false)
-{
- // set video format
- m_format = RGB24;
- // force flip because ffmpeg always return the image in the wrong orientation for texture
- setFlip(true);
- // construction is OK
- *hRslt = S_OK;
- BLI_listbase_clear(&m_thread);
- pthread_mutex_init(&m_cacheMutex, NULL);
- BLI_listbase_clear(&m_frameCacheFree);
- BLI_listbase_clear(&m_frameCacheBase);
- BLI_listbase_clear(&m_packetCacheFree);
- BLI_listbase_clear(&m_packetCacheBase);
-}
-
-// destructor
-VideoFFmpeg::~VideoFFmpeg ()
-{
-}
-
-void VideoFFmpeg::refresh(void)
-{
- // a fixed image will not refresh because it is loaded only once at creation
- if (m_isImage)
- return;
- m_avail = false;
-}
-
-// release components
-bool VideoFFmpeg::release()
-{
- // release
- stopCache();
- if (m_codecCtx)
- {
- avcodec_close(m_codecCtx);
- m_codecCtx = NULL;
- }
- if (m_formatCtx)
- {
- avformat_close_input(&m_formatCtx);
- m_formatCtx = NULL;
- }
- if (m_frame)
- {
- av_free(m_frame);
- m_frame = NULL;
- }
- if (m_frameDeinterlaced)
- {
- MEM_freeN(m_frameDeinterlaced->data[0]);
- av_free(m_frameDeinterlaced);
- m_frameDeinterlaced = NULL;
- }
- if (m_frameRGB)
- {
- MEM_freeN(m_frameRGB->data[0]);
- av_free(m_frameRGB);
- m_frameRGB = NULL;
- }
- if (m_imgConvertCtx)
- {
- sws_freeContext(m_imgConvertCtx);
- m_imgConvertCtx = NULL;
- }
- m_codec = NULL;
- m_status = SourceStopped;
- m_lastFrame = -1;
- return true;
-}
-
-AVFrame *VideoFFmpeg::allocFrameRGB()
-{
- AVFrame *frame;
- frame = av_frame_alloc();
- if (m_format == RGBA32)
- {
- avpicture_fill((AVPicture*)frame,
- (uint8_t*)MEM_callocN(avpicture_get_size(
- AV_PIX_FMT_RGBA,
- m_codecCtx->width, m_codecCtx->height),
- "ffmpeg rgba"),
- AV_PIX_FMT_RGBA, m_codecCtx->width, m_codecCtx->height);
- } else
- {
- avpicture_fill((AVPicture*)frame,
- (uint8_t*)MEM_callocN(avpicture_get_size(
- AV_PIX_FMT_RGB24,
- m_codecCtx->width, m_codecCtx->height),
- "ffmpeg rgb"),
- AV_PIX_FMT_RGB24, m_codecCtx->width, m_codecCtx->height);
- }
- return frame;
-}
-
-// set initial parameters
-void VideoFFmpeg::initParams (short width, short height, float rate, bool image)
-{
- m_captWidth = width;
- m_captHeight = height;
- m_captRate = rate;
- m_isImage = image;
-}
-
-
-int VideoFFmpeg::openStream(const char *filename, AVInputFormat *inputFormat, AVDictionary **formatParams)
-{
- AVFormatContext *formatCtx = NULL;
- int i, videoStream;
- AVCodec *codec;
- AVCodecContext *codecCtx;
-
- if (avformat_open_input(&formatCtx, filename, inputFormat, formatParams)!=0)
- return -1;
-
- if (avformat_find_stream_info(formatCtx, NULL) < 0)
- {
- avformat_close_input(&formatCtx);
- return -1;
- }
-
- /* Find the first video stream */
- videoStream=-1;
- for (i=0; i<formatCtx->nb_streams; i++)
- {
- if (formatCtx->streams[i] &&
- get_codec_from_stream(formatCtx->streams[i]) &&
- (get_codec_from_stream(formatCtx->streams[i])->codec_type==AVMEDIA_TYPE_VIDEO))
- {
- videoStream=i;
- break;
- }
- }
-
- if (videoStream==-1)
- {
- avformat_close_input(&formatCtx);
- return -1;
- }
-
- codecCtx = get_codec_from_stream(formatCtx->streams[videoStream]);
-
- /* Find the decoder for the video stream */
- codec=avcodec_find_decoder(codecCtx->codec_id);
- if (codec==NULL)
- {
- avformat_close_input(&formatCtx);
- return -1;
- }
- codecCtx->workaround_bugs = 1;
- if (avcodec_open2(codecCtx, codec, NULL) < 0)
- {
- avformat_close_input(&formatCtx);
- return -1;
- }
-
-#ifdef FFMPEG_OLD_FRAME_RATE
- if (codecCtx->frame_rate>1000 && codecCtx->frame_rate_base==1)
- codecCtx->frame_rate_base=1000;
- m_baseFrameRate = (double)codecCtx->frame_rate / (double)codecCtx->frame_rate_base;
-#else
- m_baseFrameRate = av_q2d(av_get_r_frame_rate_compat(formatCtx, formatCtx->streams[videoStream]));
-#endif
- if (m_baseFrameRate <= 0.0)
- m_baseFrameRate = defFrameRate;
-
- m_codec = codec;
- m_codecCtx = codecCtx;
- m_formatCtx = formatCtx;
- m_videoStream = videoStream;
- m_frame = av_frame_alloc();
- m_frameDeinterlaced = av_frame_alloc();
-
- // allocate buffer if deinterlacing is required
- avpicture_fill((AVPicture*)m_frameDeinterlaced,
- (uint8_t*)MEM_callocN(avpicture_get_size(
- m_codecCtx->pix_fmt,
- m_codecCtx->width, m_codecCtx->height),
- "ffmpeg deinterlace"),
- m_codecCtx->pix_fmt, m_codecCtx->width, m_codecCtx->height);
-
- // check if the pixel format supports Alpha
- if (m_codecCtx->pix_fmt == AV_PIX_FMT_RGB32 ||
- m_codecCtx->pix_fmt == AV_PIX_FMT_BGR32 ||
- m_codecCtx->pix_fmt == AV_PIX_FMT_RGB32_1 ||
- m_codecCtx->pix_fmt == AV_PIX_FMT_BGR32_1)
- {
- // allocate buffer to store final decoded frame
- m_format = RGBA32;
- // allocate sws context
- m_imgConvertCtx = sws_getContext(
- m_codecCtx->width,
- m_codecCtx->height,
- m_codecCtx->pix_fmt,
- m_codecCtx->width,
- m_codecCtx->height,
- AV_PIX_FMT_RGBA,
- SWS_FAST_BILINEAR,
- NULL, NULL, NULL);
- } else
- {
- // allocate buffer to store final decoded frame
- m_format = RGB24;
- // allocate sws context
- m_imgConvertCtx = sws_getContext(
- m_codecCtx->width,
- m_codecCtx->height,
- m_codecCtx->pix_fmt,
- m_codecCtx->width,
- m_codecCtx->height,
- AV_PIX_FMT_RGB24,
- SWS_FAST_BILINEAR,
- NULL, NULL, NULL);
- }
- m_frameRGB = allocFrameRGB();
-
- if (!m_imgConvertCtx) {
- avcodec_close(m_codecCtx);
- m_codecCtx = NULL;
- avformat_close_input(&m_formatCtx);
- m_formatCtx = NULL;
- av_free(m_frame);
- m_frame = NULL;
- MEM_freeN(m_frameDeinterlaced->data[0]);
- av_free(m_frameDeinterlaced);
- m_frameDeinterlaced = NULL;
- MEM_freeN(m_frameRGB->data[0]);
- av_free(m_frameRGB);
- m_frameRGB = NULL;
- return -1;
- }
- return 0;
-}
-
-/*
- * This thread is used to load video frame asynchronously.
- * It provides a frame caching service.
- * The main thread is responsible for positioning the frame pointer in the
- * file correctly before calling startCache() which starts this thread.
- * The cache is organized in two layers: 1) a cache of 20-30 undecoded packets to keep
- * memory and CPU low 2) a cache of 5 decoded frames.
- * If the main thread does not find the frame in the cache (because the video has restarted
- * or because the GE is lagging), it stops the cache with StopCache() (this is a synchronous
- * function: it sends a signal to stop the cache thread and wait for confirmation), then
- * change the position in the stream and restarts the cache thread.
- */
-void *VideoFFmpeg::cacheThread(void *data)
-{
- VideoFFmpeg* video = (VideoFFmpeg*)data;
- // holds the frame that is being decoded
- CacheFrame *currentFrame = NULL;
- CachePacket *cachePacket;
- bool endOfFile = false;
- int frameFinished = 0;
- double timeBase = av_q2d(video->m_formatCtx->streams[video->m_videoStream]->time_base);
- int64_t startTs = video->m_formatCtx->streams[video->m_videoStream]->start_time;
-
- if (startTs == AV_NOPTS_VALUE)
- startTs = 0;
-
- while (!video->m_stopThread)
- {
- // packet cache is used solely by this thread, no need to lock
- // In case the stream/file contains other stream than the one we are looking for,
- // allow a bit of cycling to get rid quickly of those frames
- frameFinished = 0;
- while ( !endOfFile
- && (cachePacket = (CachePacket *)video->m_packetCacheFree.first) != NULL
- && frameFinished < 25)
- {
- // free packet => packet cache is not full yet, just read more
- if (av_read_frame(video->m_formatCtx, &cachePacket->packet)>=0)
- {
- if (cachePacket->packet.stream_index == video->m_videoStream)
- {
- // make sure fresh memory is allocated for the packet and move it to queue
- av_dup_packet(&cachePacket->packet);
- BLI_remlink(&video->m_packetCacheFree, cachePacket);
- BLI_addtail(&video->m_packetCacheBase, cachePacket);
- break;
- } else {
- // this is not a good packet for us, just leave it on free queue
- // Note: here we could handle sound packet
- av_free_packet(&cachePacket->packet);
- frameFinished++;
- }
-
- } else {
- if (video->m_isFile)
- // this mark the end of the file
- endOfFile = true;
- // if we cannot read a packet, no need to continue
- break;
- }
- }
- // frame cache is also used by main thread, lock
- if (currentFrame == NULL)
- {
- // no current frame being decoded, take free one
- pthread_mutex_lock(&video->m_cacheMutex);
- if ((currentFrame = (CacheFrame *)video->m_frameCacheFree.first) != NULL)
- BLI_remlink(&video->m_frameCacheFree, currentFrame);
- pthread_mutex_unlock(&video->m_cacheMutex);
- }
- if (currentFrame != NULL)
- {
- // this frame is out of free and busy queue, we can manipulate it without locking
- frameFinished = 0;
- while (!frameFinished && (cachePacket = (CachePacket *)video->m_packetCacheBase.first) != NULL)
- {
- BLI_remlink(&video->m_packetCacheBase, cachePacket);
- // use m_frame because when caching, it is not used in main thread
- // we can't use currentFrame directly because we need to convert to RGB first
- avcodec_decode_video2(video->m_codecCtx,
- video->m_frame, &frameFinished,
- &cachePacket->packet);
- if (frameFinished)
- {
- AVFrame * input = video->m_frame;
-
- /* This means the data wasnt read properly, this check stops crashing */
- if ( input->data[0]!=0 || input->data[1]!=0
- || input->data[2]!=0 || input->data[3]!=0)
- {
- if (video->m_deinterlace)
- {
- if (avpicture_deinterlace(
- (AVPicture*) video->m_frameDeinterlaced,
- (const AVPicture*) video->m_frame,
- video->m_codecCtx->pix_fmt,
- video->m_codecCtx->width,
- video->m_codecCtx->height) >= 0)
- {
- input = video->m_frameDeinterlaced;
- }
- }
- // convert to RGB24
- sws_scale(video->m_imgConvertCtx,
- input->data,
- input->linesize,
- 0,
- video->m_codecCtx->height,
- currentFrame->frame->data,
- currentFrame->frame->linesize);
- // move frame to queue, this frame is necessarily the next one
- video->m_curPosition = (long)((cachePacket->packet.dts-startTs) * (video->m_baseFrameRate*timeBase) + 0.5);
- currentFrame->framePosition = video->m_curPosition;
- pthread_mutex_lock(&video->m_cacheMutex);
- BLI_addtail(&video->m_frameCacheBase, currentFrame);
- pthread_mutex_unlock(&video->m_cacheMutex);
- currentFrame = NULL;
- }
- }
- av_free_packet(&cachePacket->packet);
- BLI_addtail(&video->m_packetCacheFree, cachePacket);
- }
- if (currentFrame && endOfFile)
- {
- // no more packet and end of file => put a special frame that indicates that
- currentFrame->framePosition = -1;
- pthread_mutex_lock(&video->m_cacheMutex);
- BLI_addtail(&video->m_frameCacheBase, currentFrame);
- pthread_mutex_unlock(&video->m_cacheMutex);
- currentFrame = NULL;
- // no need to stay any longer in this thread
- break;
- }
- }
- // small sleep to avoid unnecessary looping
- PIL_sleep_ms(10);
- }
- // before quitting, put back the current frame to queue to allow freeing
- if (currentFrame)
- {
- pthread_mutex_lock(&video->m_cacheMutex);
- BLI_addtail(&video->m_frameCacheFree, currentFrame);
- pthread_mutex_unlock(&video->m_cacheMutex);
- }
- return 0;
-}
-
-// start thread to cache video frame from file/capture/stream
-// this function should be called only when the position in the stream is set for the
-// first frame to cache
-bool VideoFFmpeg::startCache()
-{
- if (!m_cacheStarted && m_isThreaded)
- {
- m_stopThread = false;
- for (int i=0; i<CACHE_FRAME_SIZE; i++)
- {
- CacheFrame *frame = new CacheFrame();
- frame->frame = allocFrameRGB();
- BLI_addtail(&m_frameCacheFree, frame);
- }
- for (int i=0; i<CACHE_PACKET_SIZE; i++)
- {
- CachePacket *packet = new CachePacket();
- BLI_addtail(&m_packetCacheFree, packet);
- }
- BLI_threadpool_init(&m_thread, cacheThread, 1);
- BLI_threadpool_insert(&m_thread, this);
- m_cacheStarted = true;
- }
- return m_cacheStarted;
-}
-
-void VideoFFmpeg::stopCache()
-{
- if (m_cacheStarted)
- {
- m_stopThread = true;
- BLI_threadpool_end(&m_thread);
- // now delete the cache
- CacheFrame *frame;
- CachePacket *packet;
- while ((frame = (CacheFrame *)m_frameCacheBase.first) != NULL)
- {
- BLI_remlink(&m_frameCacheBase, frame);
- MEM_freeN(frame->frame->data[0]);
- av_free(frame->frame);
- delete frame;
- }
- while ((frame = (CacheFrame *)m_frameCacheFree.first) != NULL)
- {
- BLI_remlink(&m_frameCacheFree, frame);
- MEM_freeN(frame->frame->data[0]);
- av_free(frame->frame);
- delete frame;
- }
- while ((packet = (CachePacket *)m_packetCacheBase.first) != NULL)
- {
- BLI_remlink(&m_packetCacheBase, packet);
- av_free_packet(&packet->packet);
- delete packet;
- }
- while ((packet = (CachePacket *)m_packetCacheFree.first) != NULL)
- {
- BLI_remlink(&m_packetCacheFree, packet);
- delete packet;
- }
- m_cacheStarted = false;
- }
-}
-
-void VideoFFmpeg::releaseFrame(AVFrame *frame)
-{
- if (frame == m_frameRGB)
- {
- // this is not a frame from the cache, ignore
- return;
- }
- // this frame MUST be the first one of the queue
- pthread_mutex_lock(&m_cacheMutex);
- CacheFrame *cacheFrame = (CacheFrame *)m_frameCacheBase.first;
- assert (cacheFrame != NULL && cacheFrame->frame == frame);
- BLI_remlink(&m_frameCacheBase, cacheFrame);
- BLI_addtail(&m_frameCacheFree, cacheFrame);
- pthread_mutex_unlock(&m_cacheMutex);
-}
-
-// open video file
-void VideoFFmpeg::openFile (char *filename)
-{
- if (openStream(filename, NULL, NULL) != 0)
- return;
-
- if (m_codecCtx->gop_size)
- m_preseek = (m_codecCtx->gop_size < 25) ? m_codecCtx->gop_size+1 : 25;
- else if (m_codecCtx->has_b_frames)
- m_preseek = 25; // should determine gopsize
- else
- m_preseek = 0;
-
- // get video time range
- m_range[0] = 0.0;
- m_range[1] = (double)m_formatCtx->duration / AV_TIME_BASE;
-
- // open base class
- VideoBase::openFile(filename);
-
- if (
- // ffmpeg reports that http source are actually non stream
- // but it is really not desirable to seek on http file, so force streaming.
- // It would be good to find this information from the context but there are no simple indication
- !strncmp(filename, "http://", 7) ||
- !strncmp(filename, "rtsp://", 7) ||
- (m_formatCtx->pb && !m_formatCtx->pb->seekable)
- )
- {
- // the file is in fact a streaming source, treat as cam to prevent seeking
- m_isFile = false;
- // but it's not handled exactly like a camera.
- m_isStreaming = true;
- // for streaming it is important to do non blocking read
- m_formatCtx->flags |= AVFMT_FLAG_NONBLOCK;
- }
-
- if (m_isImage)
- {
- // the file is to be treated as an image, i.e. load the first frame only
- m_isFile = false;
- // in case of reload, the filename is taken from m_imageName, no need to change it
- if (m_imageName.Ptr() != filename)
- m_imageName = filename;
- m_preseek = 0;
- m_avail = false;
- play();
- }
- // check if we should do multi-threading?
- if (!m_isImage && BLI_system_thread_count() > 1)
- {
- // never thread image: there are no frame to read ahead
- // no need to thread if the system has a single core
- m_isThreaded = true;
- }
-}
-
-
-// open video capture device
-void VideoFFmpeg::openCam (char *file, short camIdx)
-{
- // open camera source
- AVInputFormat *inputFormat;
- AVDictionary *formatParams = NULL;
- char filename[28], rateStr[20];
-
-#ifdef WIN32
- // video capture on windows only through Video For Windows driver
- inputFormat = av_find_input_format("vfwcap");
- if (!inputFormat)
- // Video For Windows not supported??
- return;
- sprintf(filename, "%d", camIdx);
-#else
- // In Linux we support two types of devices: VideoForLinux and DV1394.
- // the user specify it with the filename:
- // [<device_type>][:<standard>]
- // <device_type> : 'v4l' for VideoForLinux, 'dv1394' for DV1394. By default 'v4l'
- // <standard> : 'pal', 'secam' or 'ntsc'. By default 'ntsc'
- // The driver name is constructed automatically from the device type:
- // v4l : /dev/video<camIdx>
- // dv1394: /dev/dv1394/<camIdx>
- // If you have different driver name, you can specify the driver name explicitly
- // instead of device type. Examples of valid filename:
- // /dev/v4l/video0:pal
- // /dev/ieee1394/1:ntsc
- // dv1394:secam
- // v4l:pal
- char *p;
-
- if (file && strstr(file, "1394") != NULL)
- {
- // the user specifies a driver, check if it is v4l or d41394
- inputFormat = av_find_input_format("dv1394");
- sprintf(filename, "/dev/dv1394/%d", camIdx);
- } else
- {
- const char *formats[] = {"video4linux2,v4l2", "video4linux2", "video4linux"};
- int i, formatsCount = sizeof(formats) / sizeof(char*);
- for (i = 0; i < formatsCount; i++) {
- inputFormat = av_find_input_format(formats[i]);
- if (inputFormat)
- break;
- }
- sprintf(filename, "/dev/video%d", camIdx);
- }
- if (!inputFormat)
- // these format should be supported, check ffmpeg compilation
- return;
- if (file && strncmp(file, "/dev", 4) == 0)
- {
- // user does not specify a driver
- strncpy(filename, file, sizeof(filename));
- filename[sizeof(filename)-1] = 0;
- if ((p = strchr(filename, ':')) != 0)
- *p = 0;
- }
- if (file && (p = strchr(file, ':')) != NULL) {
- av_dict_set(&formatParams, "standard", p+1, 0);
- }
-#endif
- //frame rate
- if (m_captRate <= 0.f)
- m_captRate = defFrameRate;
- sprintf(rateStr, "%f", m_captRate);
-
- av_dict_set(&formatParams, "framerate", rateStr, 0);
-
- if (m_captWidth > 0 && m_captHeight > 0) {
- char video_size[64];
- BLI_snprintf(video_size, sizeof(video_size), "%dx%d", m_captWidth, m_captHeight);
- av_dict_set(&formatParams, "video_size", video_size, 0);
- }
-
- if (openStream(filename, inputFormat, &formatParams) != 0)
- return;
-
- // for video capture it is important to do non blocking read
- m_formatCtx->flags |= AVFMT_FLAG_NONBLOCK;
- // open base class
- VideoBase::openCam(file, camIdx);
- // check if we should do multi-threading?
- if (BLI_system_thread_count() > 1)
- {
- // no need to thread if the system has a single core
- m_isThreaded = true;
- }
-
- av_dict_free(&formatParams);
-}
-
-// play video
-bool VideoFFmpeg::play (void)
-{
- try
- {
- // if object is able to play
- if (VideoBase::play())
- {
- // set video position
- setPositions();
-
- if (m_isStreaming)
- {
- av_read_play(m_formatCtx);
- }
-
- // return success
- return true;
- }
- }
- CATCH_EXCP;
- return false;
-}
-
-
-// pause video
-bool VideoFFmpeg::pause (void)
-{
- try
- {
- if (VideoBase::pause())
- {
- if (m_isStreaming)
- {
- av_read_pause(m_formatCtx);
- }
- return true;
- }
- }
- CATCH_EXCP;
- return false;
-}
-
-// stop video
-bool VideoFFmpeg::stop (void)
-{
- try
- {
- VideoBase::stop();
- // force restart when play
- m_lastFrame = -1;
- return true;
- }
- CATCH_EXCP;
- return false;
-}
-
-
-// set video range
-void VideoFFmpeg::setRange (double start, double stop)
-{
- try
- {
- // set range
- if (m_isFile)
- {
- VideoBase::setRange(start, stop);
- // set range for video
- setPositions();
- }
- }
- CATCH_EXCP;
-}
-
-// set framerate
-void VideoFFmpeg::setFrameRate (float rate)
-{
- VideoBase::setFrameRate(rate);
-}
-
-
-// image calculation
-// load frame from video
-void VideoFFmpeg::calcImage (unsigned int texId, double ts)
-{
- if (m_status == SourcePlaying)
- {
- // get actual time
- double startTime = PIL_check_seconds_timer();
- double actTime;
- // timestamp passed from audio actuators can sometimes be slightly negative
- if (m_isFile && ts >= -0.5)
- {
- // allow setting timestamp only when not streaming
- actTime = ts;
- if (actTime * actFrameRate() < m_lastFrame)
- {
- // user is asking to rewind, force a cache clear to make sure we will do a seek
- // note that this does not decrement m_repeat if ts didn't reach m_range[1]
- stopCache();
- }
- }
- else
- {
- if (m_lastFrame == -1 && !m_isFile)
- m_startTime = startTime;
- actTime = startTime - m_startTime;
- }
- // if video has ended
- if (m_isFile && actTime * m_frameRate >= m_range[1])
- {
- // in any case, this resets the cache
- stopCache();
- // if repeats are set, decrease them
- if (m_repeat > 0)
- --m_repeat;
- // if video has to be replayed
- if (m_repeat != 0)
- {
- // reset its position
- actTime -= (m_range[1] - m_range[0]) / m_frameRate;
- m_startTime += (m_range[1] - m_range[0]) / m_frameRate;
- }
- // if video has to be stopped, stop it
- else
- {
- m_status = SourceStopped;
- return;
- }
- }
- // actual frame
- long actFrame = (m_isImage) ? m_lastFrame+1 : long(actTime * actFrameRate());
- // if actual frame differs from last frame
- if (actFrame != m_lastFrame)
- {
- AVFrame* frame;
- // get image
- if ((frame = grabFrame(actFrame)) != NULL)
- {
- if (!m_isFile && !m_cacheStarted)
- {
- // streaming without cache: detect synchronization problem
- double execTime = PIL_check_seconds_timer() - startTime;
- if (execTime > 0.005)
- {
- // exec time is too long, it means that the function was blocking
- // resynchronize the stream from this time
- m_startTime += execTime;
- }
- }
- // save actual frame
- m_lastFrame = actFrame;
- // init image, if needed
- init(short(m_codecCtx->width), short(m_codecCtx->height));
- // process image
- process((BYTE*)(frame->data[0]));
- // finished with the frame, release it so that cache can reuse it
- releaseFrame(frame);
- // in case it is an image, automatically stop reading it
- if (m_isImage)
- {
- m_status = SourceStopped;
- // close the file as we don't need it anymore
- release();
- }
- } else if (m_isStreaming)
- {
- // we didn't get a frame and we are streaming, this may be due to
- // a delay in the network or because we are getting the frame too fast.
- // In the later case, shift time by a small amount to compensate for a drift
- m_startTime += 0.001;
- }
- }
- }
-}
-
-
-// set actual position
-void VideoFFmpeg::setPositions (void)
-{
- // set video start time
- m_startTime = PIL_check_seconds_timer();
- // if file is played and actual position is before end position
- if (!m_eof && m_lastFrame >= 0 && (!m_isFile || m_lastFrame < m_range[1] * actFrameRate()))
- // continue from actual position
- m_startTime -= double(m_lastFrame) / actFrameRate();
- else {
- m_startTime -= m_range[0];
- // start from beginning, stop cache just in case
- stopCache();
- }
-}
-
-// position pointer in file, position in second
-AVFrame *VideoFFmpeg::grabFrame(long position)
-{
- AVPacket packet;
- int frameFinished;
- int posFound = 1;
- bool frameLoaded = false;
- int64_t targetTs = 0;
- CacheFrame *frame;
- int64_t dts = 0;
-
- if (m_cacheStarted)
- {
- // when cache is active, we must not read the file directly
- do {
- pthread_mutex_lock(&m_cacheMutex);
- frame = (CacheFrame *)m_frameCacheBase.first;
- pthread_mutex_unlock(&m_cacheMutex);
- // no need to remove the frame from the queue: the cache thread does not touch the head, only the tail
- if (frame == NULL)
- {
- // no frame in cache, in case of file it is an abnormal situation
- if (m_isFile)
- {
- // go back to no threaded reading
- stopCache();
- break;
- }
- return NULL;
- }
- if (frame->framePosition == -1)
- {
- // this frame mark the end of the file (only used for file)
- // leave in cache to make sure we don't miss it
- m_eof = true;
- return NULL;
- }
- // for streaming, always return the next frame,
- // that's what grabFrame does in non cache mode anyway.
- if (m_isStreaming || frame->framePosition == position)
- {
- return frame->frame;
- }
- // for cam, skip old frames to keep image realtime.
- // There should be no risk of clock drift since it all happens on the same CPU
- if (frame->framePosition > position)
- {
- // this can happen after rewind if the seek didn't find the first frame
- // the frame in the buffer is ahead of time, just leave it there
- return NULL;
- }
- // this frame is not useful, release it
- pthread_mutex_lock(&m_cacheMutex);
- BLI_remlink(&m_frameCacheBase, frame);
- BLI_addtail(&m_frameCacheFree, frame);
- pthread_mutex_unlock(&m_cacheMutex);
- } while (true);
- }
- double timeBase = av_q2d(m_formatCtx->streams[m_videoStream]->time_base);
- int64_t startTs = m_formatCtx->streams[m_videoStream]->start_time;
- if (startTs == AV_NOPTS_VALUE)
- startTs = 0;
-
- // come here when there is no cache or cache has been stopped
- // locate the frame, by seeking if necessary (seeking is only possible for files)
- if (m_isFile)
- {
- // first check if the position that we are looking for is in the preseek range
- // if so, just read the frame until we get there
- if (position > m_curPosition + 1
- && m_preseek
- && position - (m_curPosition + 1) < m_preseek)
- {
- while (av_read_frame(m_formatCtx, &packet)>=0)
- {
- if (packet.stream_index == m_videoStream)
- {
- avcodec_decode_video2(
- m_codecCtx,
- m_frame, &frameFinished,
- &packet);
- if (frameFinished)
- {
- m_curPosition = (long)((packet.dts-startTs) * (m_baseFrameRate*timeBase) + 0.5);
- }
- }
- av_free_packet(&packet);
- if (position == m_curPosition+1)
- break;
- }
- }
- // if the position is not in preseek, do a direct jump
- if (position != m_curPosition + 1)
- {
- int64_t pos = (int64_t)((position - m_preseek) / (m_baseFrameRate*timeBase));
-
- if (pos < 0)
- pos = 0;
-
- pos += startTs;
-
- if (position <= m_curPosition || !m_eof)
- {
-#if 0
- // Tried to make this work but couldn't: seeking on byte is ignored by the
- // format plugin and it will generally continue to read from last timestamp.
- // Too bad because frame seek is not always able to get the first frame
- // of the file.
- if (position <= m_preseek)
- {
- // we can safely go the beginning of the file
- if (av_seek_frame(m_formatCtx, m_videoStream, 0, AVSEEK_FLAG_BYTE) >= 0)
- {
- // binary seek does not reset the timestamp, must do it now
- av_update_cur_dts(m_formatCtx, m_formatCtx->streams[m_videoStream], startTs);
- m_curPosition = 0;
- }
- }
- else
-#endif
- {
- // current position is now lost, guess a value.
- if (av_seek_frame(m_formatCtx, m_videoStream, pos, AVSEEK_FLAG_BACKWARD) >= 0)
- {
- // current position is now lost, guess a value.
- // It's not important because it will be set at this end of this function
- m_curPosition = position - m_preseek - 1;
- }
- }
- }
- // this is the timestamp of the frame we're looking for
- targetTs = (int64_t)(position / (m_baseFrameRate * timeBase)) + startTs;
-
- posFound = 0;
- avcodec_flush_buffers(m_codecCtx);
- }
- } else if (m_isThreaded)
- {
- // cache is not started but threading is possible
- // better not read the stream => make take some time, better start caching
- if (startCache())
- return NULL;
- // Abnormal!!! could not start cache, fall back on direct read
- m_isThreaded = false;
- }
-
- // find the correct frame, in case of streaming and no cache, it means just
- // return the next frame. This is not quite correct, may need more work
- while (av_read_frame(m_formatCtx, &packet) >= 0)
- {
- if (packet.stream_index == m_videoStream)
- {
- AVFrame *input = m_frame;
- short counter = 0;
-
- /* If m_isImage, while the data is not read properly (png, tiffs, etc formats may need several pass), else don't need while loop*/
- do {
- avcodec_decode_video2(m_codecCtx, m_frame, &frameFinished, &packet);
- counter++;
- } while ((input->data[0] == 0 && input->data[1] == 0 && input->data[2] == 0 && input->data[3] == 0) && counter < 10 && m_isImage);
-
- // remember dts to compute exact frame number
- dts = packet.dts;
- if (frameFinished && !posFound)
- {
- if (dts >= targetTs)
- {
- posFound = 1;
- }
- }
-
- if (frameFinished && posFound == 1)
- {
- AVFrame * input = m_frame;
-
- /* This means the data wasnt read properly,
- * this check stops crashing */
- if ( input->data[0]==0 && input->data[1]==0
- && input->data[2]==0 && input->data[3]==0)
- {
- av_free_packet(&packet);
- break;
- }
-
- if (m_deinterlace)
- {
- if (avpicture_deinterlace(
- (AVPicture*) m_frameDeinterlaced,
- (const AVPicture*) m_frame,
- m_codecCtx->pix_fmt,
- m_codecCtx->width,
- m_codecCtx->height) >= 0)
- {
- input = m_frameDeinterlaced;
- }
- }
- // convert to RGB24
- sws_scale(m_imgConvertCtx,
- input->data,
- input->linesize,
- 0,
- m_codecCtx->height,
- m_frameRGB->data,
- m_frameRGB->linesize);
- av_free_packet(&packet);
- frameLoaded = true;
- break;
- }
- }
- av_free_packet(&packet);
- }
- m_eof = m_isFile && !frameLoaded;
- if (frameLoaded)
- {
- m_curPosition = (long)((dts-startTs) * (m_baseFrameRate*timeBase) + 0.5);
- if (m_isThreaded)
- {
- // normal case for file: first locate, then start cache
- if (!startCache())
- {
- // Abnormal!! could not start cache, return to non-cache mode
- m_isThreaded = false;
- }
- }
- return m_frameRGB;
- }
- return NULL;
-}
-
-
-// python methods
-
-
-// cast Image pointer to VideoFFmpeg
-inline VideoFFmpeg * getVideoFFmpeg (PyImage *self)
-{ return static_cast<VideoFFmpeg*>(self->m_image); }
-
-
-// object initialization
-static int VideoFFmpeg_init(PyObject *pySelf, PyObject *args, PyObject *kwds)
-{
- PyImage *self = reinterpret_cast<PyImage*>(pySelf);
- // parameters - video source
- // file name or format type for capture (only for Linux: video4linux or dv1394)
- char * file = NULL;
- // capture device number
- short capt = -1;
- // capture width, only if capt is >= 0
- short width = 0;
- // capture height, only if capt is >= 0
- short height = 0;
- // capture rate, only if capt is >= 0
- float rate = 25.f;
-
- static const char *kwlist[] = {"file", "capture", "rate", "width", "height", NULL};
-
- // get parameters
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|hfhh",
- const_cast<char**>(kwlist), &file, &capt, &rate, &width, &height))
- return -1;
-
- try
- {
- // create video object
- Video_init<VideoFFmpeg>(self);
-
- // set thread usage
- getVideoFFmpeg(self)->initParams(width, height, rate);
-
- // open video source
- Video_open(getVideo(self), file, capt);
- }
- catch (Exception & exp)
- {
- exp.report();
- return -1;
- }
- // initialization succeded
- return 0;
-}
-
-static PyObject *VideoFFmpeg_getPreseek(PyImage *self, void *closure)
-{
- return Py_BuildValue("h", getFFmpeg(self)->getPreseek());
-}
-
-// set range
-static int VideoFFmpeg_setPreseek(PyImage *self, PyObject *value, void *closure)
-{
- // check validity of parameter
- if (value == NULL || !PyLong_Check(value))
- {
- PyErr_SetString(PyExc_TypeError, "The value must be an integer");
- return -1;
- }
- // set preseek
- getFFmpeg(self)->setPreseek(PyLong_AsLong(value));
- // success
- return 0;
-}
-
-// get deinterlace
-static PyObject *VideoFFmpeg_getDeinterlace(PyImage *self, void *closure)
-{
- if (getFFmpeg(self)->getDeinterlace())
- Py_RETURN_TRUE;
- else
- Py_RETURN_FALSE;
-}
-
-// set flip
-static int VideoFFmpeg_setDeinterlace(PyImage *self, PyObject *value, void *closure)
-{
- // check parameter, report failure
- if (value == NULL || !PyBool_Check(value))
- {
- PyErr_SetString(PyExc_TypeError, "The value must be a bool");
- return -1;
- }
- // set deinterlace
- getFFmpeg(self)->setDeinterlace(value == Py_True);
- // success
- return 0;
-}
-
-// methods structure
-static PyMethodDef videoMethods[] =
-{ // methods from VideoBase class
- {"play", (PyCFunction)Video_play, METH_NOARGS, "Play (restart) video"},
- {"pause", (PyCFunction)Video_pause, METH_NOARGS, "pause video"},
- {"stop", (PyCFunction)Video_stop, METH_NOARGS, "stop video (play will replay it from start)"},
- {"refresh", (PyCFunction)Video_refresh, METH_VARARGS, "Refresh video - get its status"},
- {NULL}
-};
-// attributes structure
-static PyGetSetDef videoGetSets[] =
-{ // methods from VideoBase class
- {(char*)"status", (getter)Video_getStatus, NULL, (char*)"video status", NULL},
- {(char*)"range", (getter)Video_getRange, (setter)Video_setRange, (char*)"replay range", NULL},
- {(char*)"repeat", (getter)Video_getRepeat, (setter)Video_setRepeat, (char*)"repeat count, -1 for infinite repeat", NULL},
- {(char*)"framerate", (getter)Video_getFrameRate, (setter)Video_setFrameRate, (char*)"frame rate", NULL},
- // attributes from ImageBase class
- {(char*)"valid", (getter)Image_valid, NULL, (char*)"bool to tell if an image is available", NULL},
- {(char*)"image", (getter)Image_getImage, NULL, (char*)"image data", NULL},
- {(char*)"size", (getter)Image_getSize, NULL, (char*)"image size", NULL},
- {(char*)"scale", (getter)Image_getScale, (setter)Image_setScale, (char*)"fast scale of image (near neighbor)", NULL},
- {(char*)"flip", (getter)Image_getFlip, (setter)Image_setFlip, (char*)"flip image vertically", NULL},
- {(char*)"filter", (getter)Image_getFilter, (setter)Image_setFilter, (char*)"pixel filter", NULL},
- {(char*)"preseek", (getter)VideoFFmpeg_getPreseek, (setter)VideoFFmpeg_setPreseek, (char*)"nb of frames of preseek", NULL},
- {(char*)"deinterlace", (getter)VideoFFmpeg_getDeinterlace, (setter)VideoFFmpeg_setDeinterlace, (char*)"deinterlace image", NULL},
- {NULL}
-};
-
-// python type declaration
-PyTypeObject VideoFFmpegType =
-{
- PyVarObject_HEAD_INIT(NULL, 0)
- "VideoTexture.VideoFFmpeg", /*tp_name*/
- sizeof(PyImage), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- (destructor)Image_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- 0, /*tp_getattr*/
- 0, /*tp_setattr*/
- 0, /*tp_compare*/
- 0, /*tp_repr*/
- 0, /*tp_as_number*/
- 0, /*tp_as_sequence*/
- 0, /*tp_as_mapping*/
- 0, /*tp_hash */
- 0, /*tp_call*/
- 0, /*tp_str*/
- 0, /*tp_getattro*/
- 0, /*tp_setattro*/
- &imageBufferProcs, /*tp_as_buffer*/
- Py_TPFLAGS_DEFAULT, /*tp_flags*/
- "FFmpeg video source", /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- videoMethods, /* tp_methods */
- 0, /* tp_members */
- videoGetSets, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- (initproc)VideoFFmpeg_init, /* tp_init */
- 0, /* tp_alloc */
- Image_allocNew, /* tp_new */
-};
-
-// object initialization
-static int ImageFFmpeg_init(PyObject *pySelf, PyObject *args, PyObject *kwds)
-{
- PyImage *self = reinterpret_cast<PyImage*>(pySelf);
- // parameters - video source
- // file name or format type for capture (only for Linux: video4linux or dv1394)
- char * file = NULL;
-
- // get parameters
- if (!PyArg_ParseTuple(args, "s:ImageFFmpeg", &file))
- return -1;
-
- try
- {
- // create video object
- Video_init<VideoFFmpeg>(self);
-
- getVideoFFmpeg(self)->initParams(0, 0, 1.0, true);
-
- // open video source
- Video_open(getVideo(self), file, -1);
- }
- catch (Exception & exp)
- {
- exp.report();
- return -1;
- }
- // initialization succeded
- return 0;
-}
-
-static PyObject *Image_reload(PyImage *self, PyObject *args)
-{
- char * newname = NULL;
- if (!PyArg_ParseTuple(args, "|s:reload", &newname))
- return NULL;
- if (self->m_image != NULL)
- {
- VideoFFmpeg* video = getFFmpeg(self);
- // check type of object
- if (!newname)
- newname = video->getImageName();
- if (!newname) {
- // if not set, retport error
- PyErr_SetString(PyExc_RuntimeError, "No image file name given");
- return NULL;
- }
- // make sure the previous file is cleared
- video->release();
- // open the new file
- video->openFile(newname);
- }
- Py_RETURN_NONE;
-}
-
-// methods structure
-static PyMethodDef imageMethods[] =
-{ // methods from VideoBase class
- {"refresh", (PyCFunction)Video_refresh, METH_VARARGS, "Refresh image, i.e. load it"},
- {"reload", (PyCFunction)Image_reload, METH_VARARGS, "Reload image, i.e. reopen it"},
- {NULL}
-};
-// attributes structure
-static PyGetSetDef imageGetSets[] =
-{ // methods from VideoBase class
- {(char*)"status", (getter)Video_getStatus, NULL, (char*)"video status", NULL},
- // attributes from ImageBase class
- {(char*)"valid", (getter)Image_valid, NULL, (char*)"bool to tell if an image is available", NULL},
- {(char*)"image", (getter)Image_getImage, NULL, (char*)"image data", NULL},
- {(char*)"size", (getter)Image_getSize, NULL, (char*)"image size", NULL},
- {(char*)"scale", (getter)Image_getScale, (setter)Image_setScale, (char*)"fast scale of image (near neighbor)", NULL},
- {(char*)"flip", (getter)Image_getFlip, (setter)Image_setFlip, (char*)"flip image vertically", NULL},
- {(char*)"filter", (getter)Image_getFilter, (setter)Image_setFilter, (char*)"pixel filter", NULL},
- {NULL}
-};
-
-// python type declaration
-PyTypeObject ImageFFmpegType =
-{
- PyVarObject_HEAD_INIT(NULL, 0)
- "VideoTexture.ImageFFmpeg", /*tp_name*/
- sizeof(PyImage), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- (destructor)Image_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- 0, /*tp_getattr*/
- 0, /*tp_setattr*/
- 0, /*tp_compare*/
- 0, /*tp_repr*/
- 0, /*tp_as_number*/
- 0, /*tp_as_sequence*/
- 0, /*tp_as_mapping*/
- 0, /*tp_hash */
- 0, /*tp_call*/
- 0, /*tp_str*/
- 0, /*tp_getattro*/
- 0, /*tp_setattro*/
- &imageBufferProcs, /*tp_as_buffer*/
- Py_TPFLAGS_DEFAULT, /*tp_flags*/
- "FFmpeg image source", /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- imageMethods, /* tp_methods */
- 0, /* tp_members */
- imageGetSets, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- (initproc)ImageFFmpeg_init, /* tp_init */
- 0, /* tp_alloc */
- Image_allocNew, /* tp_new */
-};
-
-#endif //WITH_FFMPEG
-
-
diff --git a/source/gameengine/VideoTexture/VideoFFmpeg.h b/source/gameengine/VideoTexture/VideoFFmpeg.h
deleted file mode 100644
index 0a49a0b19bb..00000000000
--- a/source/gameengine/VideoTexture/VideoFFmpeg.h
+++ /dev/null
@@ -1,219 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * Copyright (c) 2007 The Zdeno Ash Miklas
- *
- * This source file is part of VideoTexture library
- *
- * Contributor(s):
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file VideoFFmpeg.h
- * \ingroup bgevideotex
- */
-
-#ifndef __VIDEOFFMPEG_H__
-#define __VIDEOFFMPEG_H__
-
-#ifdef WITH_FFMPEG
-/* this needs to be parsed with __cplusplus defined before included through ffmpeg_compat.h */
-#if defined(__FreeBSD__)
-# include <inttypes.h>
-#endif
-extern "C" {
-#include <pthread.h>
-#include "ffmpeg_compat.h"
-#include "DNA_listBase.h"
-#include "BLI_threads.h"
-#include "BLI_blenlib.h"
-}
-
-#if LIBAVFORMAT_VERSION_INT < (49 << 16)
-# define FFMPEG_OLD_FRAME_RATE 1
-#else
-# define FFMPEG_CODEC_IS_POINTER 1
-#endif
-
-#ifdef FFMPEG_CODEC_IS_POINTER
-static inline AVCodecContext *get_codec_from_stream(AVStream* stream)
-{
- return stream->codec;
-}
-#else
-static inline AVCodecContext *get_codec_from_stream(AVStream* stream)
-{
- return &stream->codec;
-}
-#endif
-
-#include "VideoBase.h"
-
-#define CACHE_FRAME_SIZE 10
-#define CACHE_PACKET_SIZE 30
-
-// type VideoFFmpeg declaration
-class VideoFFmpeg : public VideoBase
-{
-public:
- /// constructor
- VideoFFmpeg (HRESULT * hRslt);
- /// destructor
- virtual ~VideoFFmpeg ();
-
- /// set initial parameters
- void initParams (short width, short height, float rate, bool image=false);
- /// open video/image file
- virtual void openFile(char *file);
- /// open video capture device
- virtual void openCam(char *driver, short camIdx);
-
- /// release video source
- virtual bool release (void);
- /// overwrite base refresh to handle fixed image
- virtual void refresh(void);
- /// play video
- virtual bool play (void);
- /// pause video
- virtual bool pause (void);
- /// stop video
- virtual bool stop (void);
- /// set play range
- virtual void setRange (double start, double stop);
- /// set frame rate
- virtual void setFrameRate (float rate);
- // some specific getters and setters
- int getPreseek(void) { return m_preseek; }
- void setPreseek(int preseek) { if (preseek >= 0) m_preseek = preseek; }
- bool getDeinterlace(void) { return m_deinterlace; }
- void setDeinterlace(bool deinterlace) { m_deinterlace = deinterlace; }
- char *getImageName(void) { return (m_isImage) ? m_imageName.Ptr() : NULL; }
-
-protected:
- // format and codec information
- AVCodec *m_codec;
- AVFormatContext *m_formatCtx;
- AVCodecContext *m_codecCtx;
- // raw frame extracted from video file
- AVFrame *m_frame;
- // deinterlaced frame if codec requires it
- AVFrame *m_frameDeinterlaced;
- // decoded RGB24 frame if codec requires it
- AVFrame *m_frameRGB;
- // conversion from raw to RGB is done with sws_scale
- struct SwsContext *m_imgConvertCtx;
- // should the codec be deinterlaced?
- bool m_deinterlace;
- // number of frame of preseek
- int m_preseek;
- // order number of stream holding the video in format context
- int m_videoStream;
-
- // the actual frame rate
- double m_baseFrameRate;
-
- /// last displayed frame
- long m_lastFrame;
-
- /// end of file reached
- bool m_eof;
-
- /// flag to indicate that time is coming from application
- bool m_externTime;
-
- /// current file pointer position in file expressed in frame number
- long m_curPosition;
-
- /// time of video play start
- double m_startTime;
-
- /// width of capture in pixel
- short m_captWidth;
-
- /// height of capture in pixel
- short m_captHeight;
-
- /// frame rate of capture in frames per seconds
- float m_captRate;
-
- /// is file an image?
- bool m_isImage;
-
- /// is image loading done in a separate thread?
- bool m_isThreaded;
-
- /// is streaming or camera?
- bool m_isStreaming;
-
- /// keep last image name
- STR_String m_imageName;
-
- /// image calculation
- virtual void calcImage (unsigned int texId, double ts);
-
- /// set actual position
- void setPositions (void);
-
- /// get actual framerate
- double actFrameRate (void) { return m_frameRate * m_baseFrameRate; }
-
- /// common function to video file and capture
- int openStream(const char *filename, AVInputFormat *inputFormat, AVDictionary **formatParams);
-
- /// check if a frame is available and load it in pFrame, return true if a frame could be retrieved
- AVFrame* grabFrame(long frame);
-
- /// in case of caching, put the frame back in free queue
- void releaseFrame(AVFrame* frame);
-
- /// start thread to load the video file/capture/stream
- bool startCache();
- void stopCache();
-
-private:
- typedef struct {
- Link link;
- long framePosition;
- AVFrame *frame;
- } CacheFrame;
- typedef struct {
- Link link;
- AVPacket packet;
- } CachePacket;
-
- bool m_stopThread;
- bool m_cacheStarted;
- ListBase m_thread;
- ListBase m_frameCacheBase; // list of frames that are ready
- ListBase m_frameCacheFree; // list of frames that are unused
- ListBase m_packetCacheBase; // list of packets that are ready for decoding
- ListBase m_packetCacheFree; // list of packets that are unused
- pthread_mutex_t m_cacheMutex;
-
- AVFrame *allocFrameRGB();
- static void *cacheThread(void *);
-};
-
-inline VideoFFmpeg *getFFmpeg(PyImage *self)
-{
- return static_cast<VideoFFmpeg*>(self->m_image);
-}
-
-#endif /* WITH_FFMPEG */
-
-#endif /* __VIDEOFFMPEG_H__ */
diff --git a/source/gameengine/VideoTexture/blendVideoTex.cpp b/source/gameengine/VideoTexture/blendVideoTex.cpp
deleted file mode 100644
index 9b046d46412..00000000000
--- a/source/gameengine/VideoTexture/blendVideoTex.cpp
+++ /dev/null
@@ -1,266 +0,0 @@
-/*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * Copyright (c) 2006 The Zdeno Ash Miklas
- *
- * This source file is part of VideoTexture library
- *
- * Contributor(s):
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file gameengine/VideoTexture/blendVideoTex.cpp
- * \ingroup bgevideotex
- */
-
-#include "EXP_PyObjectPlus.h"
-
-#include "KX_PythonInit.h"
-
-#include <RAS_IPolygonMaterial.h>
-
-//Old API
-//#include "TexPlayer.h"
-//#include "TexImage.h"
-//#include "TexFrameBuff.h"
-
-//#include "TexPlayerGL.h"
-
-#include "ImageBase.h"
-#include "VideoBase.h"
-#include "FilterBase.h"
-#include "Texture.h"
-
-#include "Exception.h"
-
-// access to IMB_BLEND_* constants
-extern "C"
-{
-#include "IMB_imbuf.h"
-};
-
-
-// get material id
-static PyObject *getMaterialID (PyObject *self, PyObject *args)
-{
- // parameters - game object with video texture
- PyObject *obj = NULL;
- // material name
- char * matName;
-
- // get parameters
- if (!PyArg_ParseTuple(args, "Os:materialID", &obj, &matName))
- return NULL;
- // get material id
- short matID = getMaterialID(obj, matName);
- // if material was not found, report errot
- if (matID < 0)
- {
- PyErr_SetString(PyExc_RuntimeError, "VideoTexture.materialID(ob, string): Object doesn't have material with given name");
- return NULL;
- }
- // return material ID
- return Py_BuildValue("h", matID);
-}
-
-
-// get last error description
-static PyObject *getLastError (PyObject *self, PyObject *args)
-{
- return PyUnicode_FromString(Exception::m_lastError.c_str());
-}
-
-// set log file
-static PyObject *setLogFile (PyObject *self, PyObject *args)
-{
- // get parameters
- if (!PyArg_ParseTuple(args, "s:setLogFile", &Exception::m_logFile))
- return Py_BuildValue("i", -1);
- // log file was loaded
- return Py_BuildValue("i", 0);
-}
-
-
-// image to numpy array
-static PyObject *imageToArray(PyObject *self, PyObject *args)
-{
- // parameter is Image object
- PyObject *pyImg;
- char *mode = NULL;
- if (!PyArg_ParseTuple(args, "O|s:imageToArray", &pyImg, &mode) || !pyImageTypes.in(Py_TYPE(pyImg)))
- {
- // if object is incorect, report error
- PyErr_SetString(PyExc_TypeError, "VideoTexture.imageToArray(image): The value must be a image source object");
- return NULL;
- }
- // get image structure
- PyImage * img = reinterpret_cast<PyImage*>(pyImg);
- return Image_getImage(img, mode);
-}
-
-
-// metody modulu
-static PyMethodDef moduleMethods[] =
-{
- {"materialID", getMaterialID, METH_VARARGS, "Gets object's Blender Material ID"},
- {"getLastError", getLastError, METH_NOARGS, "Gets last error description"},
- {"setLogFile", setLogFile, METH_VARARGS, "Sets log file name"},
- {"imageToArray", imageToArray, METH_VARARGS, "get buffer from image source, color channels are selectable"},
- {NULL} /* Sentinel */
-};
-
-#ifdef WITH_FFMPEG
-extern PyTypeObject VideoFFmpegType;
-extern PyTypeObject ImageFFmpegType;
-#endif
-#ifdef WITH_GAMEENGINE_DECKLINK
-extern PyTypeObject VideoDeckLinkType;
-extern PyTypeObject DeckLinkType;
-#endif
-extern PyTypeObject FilterBlueScreenType;
-extern PyTypeObject FilterGrayType;
-extern PyTypeObject FilterColorType;
-extern PyTypeObject FilterLevelType;
-extern PyTypeObject FilterNormalType;
-extern PyTypeObject FilterRGB24Type;
-extern PyTypeObject FilterRGBA32Type;
-extern PyTypeObject FilterBGR24Type;
-extern PyTypeObject ImageBuffType;
-extern PyTypeObject ImageMixType;
-
-static void registerAllTypes(void)
-{
-#ifdef WITH_FFMPEG
- pyImageTypes.add(&VideoFFmpegType, "VideoFFmpeg");
- pyImageTypes.add(&ImageFFmpegType, "ImageFFmpeg");
-#endif
-#ifdef WITH_GAMEENGINE_DECKLINK
- pyImageTypes.add(&VideoDeckLinkType, "VideoDeckLink");
-#endif
- pyImageTypes.add(&ImageBuffType, "ImageBuff");
- pyImageTypes.add(&ImageMixType, "ImageMix");
- pyImageTypes.add(&ImageRenderType, "ImageRender");
- pyImageTypes.add(&ImageMirrorType, "ImageMirror");
- pyImageTypes.add(&ImageViewportType, "ImageViewport");
-
- pyFilterTypes.add(&FilterBlueScreenType, "FilterBlueScreen");
- pyFilterTypes.add(&FilterGrayType, "FilterGray");
- pyFilterTypes.add(&FilterColorType, "FilterColor");
- pyFilterTypes.add(&FilterLevelType, "FilterLevel");
- pyFilterTypes.add(&FilterNormalType, "FilterNormal");
- pyFilterTypes.add(&FilterRGB24Type, "FilterRGB24");
- pyFilterTypes.add(&FilterRGBA32Type, "FilterRGBA32");
- pyFilterTypes.add(&FilterBGR24Type, "FilterBGR24");
-}
-
-PyDoc_STRVAR(VideoTexture_module_documentation,
-"Module that allows to play video files on textures in GameBlender."
-);
-
-static struct PyModuleDef VideoTexture_module_def = {
- PyModuleDef_HEAD_INIT,
- "VideoTexture", /* m_name */
- VideoTexture_module_documentation, /* m_doc */
- 0, /* m_size */
- moduleMethods, /* m_methods */
- 0, /* m_reload */
- 0, /* m_traverse */
- 0, /* m_clear */
- 0, /* m_free */
-};
-
-PyMODINIT_FUNC initVideoTexturePythonBinding(void)
-{
- PyObject *m;
-
- // initialize GL extensions
- //bgl::InitExtensions(0);
-
- // prepare classes
- registerAllTypes();
- registerAllExceptions();
-
- if (!pyImageTypes.ready())
- return NULL;
- if (!pyFilterTypes.ready())
- return NULL;
- if (PyType_Ready(&TextureType) < 0)
- return NULL;
-#ifdef WITH_GAMEENGINE_DECKLINK
- if (PyType_Ready(&DeckLinkType) < 0)
- return NULL;
-#endif
-
- m = PyModule_Create(&VideoTexture_module_def);
- PyDict_SetItemString(PySys_GetObject("modules"), VideoTexture_module_def.m_name, m);
-
- if (m == NULL)
- return NULL;
-
- // initialize classes
- pyImageTypes.reg(m);
- pyFilterTypes.reg(m);
-
- Py_INCREF(&TextureType);
- PyModule_AddObject(m, "Texture", (PyObject *)&TextureType);
-#ifdef WITH_GAMEENGINE_DECKLINK
- Py_INCREF(&DeckLinkType);
- PyModule_AddObject(m, "DeckLink", (PyObject *)&DeckLinkType);
-#endif
- PyModule_AddIntConstant(m, "SOURCE_ERROR", SourceError);
- PyModule_AddIntConstant(m, "SOURCE_EMPTY", SourceEmpty);
- PyModule_AddIntConstant(m, "SOURCE_READY", SourceReady);
- PyModule_AddIntConstant(m, "SOURCE_PLAYING", SourcePlaying);
- PyModule_AddIntConstant(m, "SOURCE_STOPPED", SourceStopped);
-
- PyModule_AddIntConstant(m, "IMB_BLEND_MIX", IMB_BLEND_MIX);
- PyModule_AddIntConstant(m, "IMB_BLEND_ADD", IMB_BLEND_ADD);
- PyModule_AddIntConstant(m, "IMB_BLEND_SUB", IMB_BLEND_SUB);
- PyModule_AddIntConstant(m, "IMB_BLEND_MUL", IMB_BLEND_MUL);
- PyModule_AddIntConstant(m, "IMB_BLEND_LIGHTEN", IMB_BLEND_LIGHTEN);
- PyModule_AddIntConstant(m, "IMB_BLEND_DARKEN", IMB_BLEND_DARKEN);
- PyModule_AddIntConstant(m, "IMB_BLEND_ERASE_ALPHA", IMB_BLEND_ERASE_ALPHA);
- PyModule_AddIntConstant(m, "IMB_BLEND_ADD_ALPHA", IMB_BLEND_ADD_ALPHA);
- PyModule_AddIntConstant(m, "IMB_BLEND_OVERLAY", IMB_BLEND_OVERLAY);
- PyModule_AddIntConstant(m, "IMB_BLEND_HARDLIGHT", IMB_BLEND_HARDLIGHT);
- PyModule_AddIntConstant(m, "IMB_BLEND_COLORBURN", IMB_BLEND_COLORBURN);
- PyModule_AddIntConstant(m, "IMB_BLEND_LINEARBURN", IMB_BLEND_LINEARBURN);
- PyModule_AddIntConstant(m, "IMB_BLEND_COLORDODGE", IMB_BLEND_COLORDODGE);
- PyModule_AddIntConstant(m, "IMB_BLEND_SCREEN", IMB_BLEND_SCREEN);
- PyModule_AddIntConstant(m, "IMB_BLEND_SOFTLIGHT", IMB_BLEND_SOFTLIGHT);
- PyModule_AddIntConstant(m, "IMB_BLEND_PINLIGHT", IMB_BLEND_PINLIGHT);
- PyModule_AddIntConstant(m, "IMB_BLEND_VIVIDLIGHT", IMB_BLEND_VIVIDLIGHT);
- PyModule_AddIntConstant(m, "IMB_BLEND_LINEARLIGHT", IMB_BLEND_LINEARLIGHT);
- PyModule_AddIntConstant(m, "IMB_BLEND_DIFFERENCE", IMB_BLEND_DIFFERENCE);
- PyModule_AddIntConstant(m, "IMB_BLEND_EXCLUSION", IMB_BLEND_EXCLUSION);
- PyModule_AddIntConstant(m, "IMB_BLEND_HUE", IMB_BLEND_HUE);
- PyModule_AddIntConstant(m, "IMB_BLEND_SATURATION", IMB_BLEND_SATURATION);
- PyModule_AddIntConstant(m, "IMB_BLEND_LUMINOSITY", IMB_BLEND_LUMINOSITY);
- PyModule_AddIntConstant(m, "IMB_BLEND_COLOR", IMB_BLEND_COLOR);
-
- PyModule_AddIntConstant(m, "IMB_BLEND_COPY", IMB_BLEND_COPY);
- PyModule_AddIntConstant(m, "IMB_BLEND_COPY_RGB", IMB_BLEND_COPY_RGB);
- PyModule_AddIntConstant(m, "IMB_BLEND_COPY_ALPHA", IMB_BLEND_COPY_ALPHA);
-
- // init last error description
- Exception::m_lastError = "";
-
- return m;
-}
-
-// registration to Image types, put here because of silly linker bug