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:
-rw-r--r--extern/bullet2/src/BulletCollision/BroadphaseCollision/btDbvt.cpp1289
-rw-r--r--extern/bullet2/src/BulletCollision/BroadphaseCollision/btDbvt.h1112
-rw-r--r--extern/bullet2/src/BulletCollision/BroadphaseCollision/btDbvtBroadphase.cpp548
-rw-r--r--extern/bullet2/src/BulletCollision/BroadphaseCollision/btDbvtBroadphase.h116
-rw-r--r--extern/bullet2/src/BulletCollision/BroadphaseCollision/btMultiSapBroadphase.cpp466
-rw-r--r--extern/bullet2/src/BulletCollision/BroadphaseCollision/btMultiSapBroadphase.h144
-rw-r--r--extern/bullet2/src/BulletCollision/BroadphaseCollision/btOverlappingPairCallback.h40
-rw-r--r--extern/bullet2/src/BulletCollision/BroadphaseCollision/btQuantizedBvh.cpp1025
-rw-r--r--extern/bullet2/src/BulletCollision/BroadphaseCollision/btQuantizedBvh.h486
-rw-r--r--extern/bullet2/src/BulletCollision/CollisionDispatch/btBoxBoxCollisionAlgorithm.cpp85
-rw-r--r--extern/bullet2/src/BulletCollision/CollisionDispatch/btBoxBoxCollisionAlgorithm.h66
-rw-r--r--extern/bullet2/src/BulletCollision/CollisionDispatch/btBoxBoxDetector.cpp683
-rw-r--r--extern/bullet2/src/BulletCollision/CollisionDispatch/btBoxBoxDetector.h44
-rw-r--r--extern/bullet2/src/BulletCollision/CollisionDispatch/btCollisionConfiguration.h47
-rw-r--r--extern/bullet2/src/BulletCollision/CollisionDispatch/btConvexPlaneCollisionAlgorithm.cpp108
-rw-r--r--extern/bullet2/src/BulletCollision/CollisionDispatch/btConvexPlaneCollisionAlgorithm.h71
-rw-r--r--extern/bullet2/src/BulletCollision/CollisionDispatch/btDefaultCollisionConfiguration.cpp291
-rw-r--r--extern/bullet2/src/BulletCollision/CollisionDispatch/btDefaultCollisionConfiguration.h118
-rw-r--r--extern/bullet2/src/BulletCollision/CollisionShapes/btConvexInternalShape.cpp78
-rw-r--r--extern/bullet2/src/BulletCollision/CollisionShapes/btConvexInternalShape.h98
-rw-r--r--extern/bullet2/src/BulletCollision/CollisionShapes/btMaterial.h34
-rw-r--r--extern/bullet2/src/BulletCollision/CollisionShapes/btMultimaterialTriangleMeshShape.cpp45
-rw-r--r--extern/bullet2/src/BulletCollision/CollisionShapes/btMultimaterialTriangleMeshShape.h124
-rw-r--r--extern/bullet2/src/BulletCollision/CollisionShapes/btScaledBvhTriangleMeshShape.cpp121
-rw-r--r--extern/bullet2/src/BulletCollision/CollisionShapes/btScaledBvhTriangleMeshShape.h67
-rw-r--r--extern/bullet2/src/BulletCollision/CollisionShapes/btShapeHull.cpp164
-rw-r--r--extern/bullet2/src/BulletCollision/CollisionShapes/btShapeHull.h56
-rw-r--r--extern/bullet2/src/BulletCollision/CollisionShapes/btTriangleIndexVertexMaterialArray.cpp86
-rw-r--r--extern/bullet2/src/BulletCollision/CollisionShapes/btTriangleIndexVertexMaterialArray.h84
-rw-r--r--extern/bullet2/src/BulletCollision/CollisionShapes/btUniformScalingShape.cpp114
-rw-r--r--extern/bullet2/src/BulletCollision/CollisionShapes/btUniformScalingShape.h88
-rw-r--r--extern/bullet2/src/BulletCollision/NarrowPhaseCollision/btGjkEpa2.cpp943
-rw-r--r--extern/bullet2/src/BulletCollision/NarrowPhaseCollision/btGjkEpa2.h71
-rw-r--r--extern/bullet2/src/BulletDynamics/ConstraintSolver/btSliderConstraint.cpp415
-rw-r--r--extern/bullet2/src/BulletDynamics/ConstraintSolver/btSliderConstraint.h218
-rw-r--r--extern/bullet2/src/BulletDynamics/Dynamics/btContinuousDynamicsWorld.cpp193
-rw-r--r--extern/bullet2/src/BulletDynamics/Dynamics/btContinuousDynamicsWorld.h46
-rw-r--r--extern/bullet2/src/BulletSoftBody/btSoftBodyRigidBodyCollisionConfiguration.cpp1
-rw-r--r--extern/bullet2/src/LinearMath/btConvexHull.cpp1174
-rw-r--r--extern/bullet2/src/LinearMath/btConvexHull.h245
-rw-r--r--extern/bullet2/src/LinearMath/btHashMap.h303
-rw-r--r--extern/bullet2/src/LinearMath/btPoolAllocator.h102
-rw-r--r--intern/elbeem/intern/controlparticles.cpp1461
-rw-r--r--intern/elbeem/intern/controlparticles.h301
-rw-r--r--intern/elbeem/intern/elbeem_control.cpp25
-rw-r--r--intern/elbeem/intern/elbeem_control.h62
-rw-r--r--intern/elbeem/intern/mvmcoords.cpp193
-rw-r--r--intern/elbeem/intern/mvmcoords.h89
-rw-r--r--intern/elbeem/intern/solver_control.cpp1020
-rw-r--r--intern/elbeem/intern/solver_control.h182
-rw-r--r--intern/guardedalloc/BLO_sys_types.h125
-rw-r--r--intern/opennl/superlu/BLO_sys_types.h127
-rw-r--r--release/Makefile6
-rw-r--r--release/VERSION2
-rw-r--r--release/datafiles/blenderbuttonsbin68242 -> 69599 bytes
-rw-r--r--release/datafiles/datatoc.c2
-rw-r--r--release/datafiles/preview.blendbin446288 -> 433792 bytes
-rw-r--r--release/datafiles/splash.jpgbin288981 -> 95515 bytes
-rw-r--r--release/plugins/sequence/dnr.c6
-rw-r--r--release/scripts/DirectX8Exporter.py2
-rw-r--r--release/scripts/animation_bake_constraints.py4
-rw-r--r--release/scripts/bpymodules/BPyImage.py19
-rw-r--r--release/scripts/bpymodules/BPyMathutils.py14
-rw-r--r--release/scripts/bpymodules/BPyMesh.py2
-rw-r--r--release/scripts/bpymodules/BPySys.py60
-rw-r--r--release/scripts/bpymodules/BPyTextPlugin.py814
-rw-r--r--release/scripts/bpymodules/dxfLibrary.py715
-rw-r--r--release/scripts/bvh_import.py4
-rw-r--r--release/scripts/c3d_import.py2
-rw-r--r--release/scripts/config.py4
-rw-r--r--release/scripts/console.py65
-rw-r--r--release/scripts/export_dxf.py407
-rw-r--r--release/scripts/export_fbx.py49
-rw-r--r--release/scripts/export_m3g.py2
-rw-r--r--release/scripts/export_obj.py148
-rw-r--r--release/scripts/flt_dofedit.py835
-rw-r--r--release/scripts/flt_lodedit.py502
-rw-r--r--release/scripts/flt_properties.py19
-rw-r--r--release/scripts/help_browser.py12
-rw-r--r--release/scripts/hotkeys.py63
-rw-r--r--release/scripts/image_auto_layout.py9
-rw-r--r--release/scripts/image_edit.py72
-rw-r--r--release/scripts/import_dxf.py107
-rw-r--r--release/scripts/import_lightwave_motion.py2
-rw-r--r--release/scripts/import_obj.py125
-rwxr-xr-xrelease/scripts/import_web3d.py2506
-rw-r--r--release/scripts/lightwave_import.py6
-rw-r--r--release/scripts/mesh_cleanup.py32
-rw-r--r--release/scripts/mesh_edges2curves.py6
-rw-r--r--release/scripts/ms3d_import_ascii.py479
-rw-r--r--release/scripts/object_drop.py2
-rw-r--r--release/scripts/object_find.py26
-rw-r--r--release/scripts/ply_export.py8
-rw-r--r--release/scripts/ply_import.py194
-rw-r--r--release/scripts/render_save_layers.py6
-rw-r--r--release/scripts/scripttemplate_gamelogic.py94
-rw-r--r--release/scripts/scripttemplate_gamelogic_basic.py33
-rw-r--r--release/scripts/scripttemplate_ipo_gen.py4
-rw-r--r--release/scripts/scripttemplate_text_plugin.py69
-rw-r--r--release/scripts/sysinfo.py2
-rw-r--r--release/scripts/textplugin_functiondocs.py64
-rw-r--r--release/scripts/textplugin_imports.py91
-rw-r--r--release/scripts/textplugin_membersuggest.py90
-rw-r--r--release/scripts/textplugin_outliner.py142
-rw-r--r--release/scripts/textplugin_suggest.py94
-rw-r--r--release/scripts/textplugin_templates.py123
-rw-r--r--release/scripts/uvcalc_lightmap.py11
-rw-r--r--release/scripts/vertexpaint_from_material.py3
-rw-r--r--release/scripts/vrml97_export.py110
-rw-r--r--release/scripts/wizard_curve2tree.py28
-rw-r--r--release/text/Python-license.txt31
-rw-r--r--release/text/blender.html154
-rw-r--r--release/text/copyright.txt2
-rw-r--r--release/windows/installer/00.sconsblender.nsi52
-rw-r--r--source/blender/blenkernel/BKE_bullet.h43
-rw-r--r--source/blender/blenkernel/BKE_fluidsim.h56
-rw-r--r--source/blender/blenkernel/BKE_multires.h78
-rw-r--r--source/blender/blenkernel/BKE_sculpt.h9
-rw-r--r--source/blender/blenkernel/BKE_shrinkwrap.h150
-rw-r--r--source/blender/blenkernel/BKE_simple_deform.h39
-rw-r--r--source/blender/blenkernel/BKE_subsurf.h8
-rw-r--r--source/blender/blenkernel/BKE_suggestions.h93
-rw-r--r--source/blender/blenkernel/intern/DerivedMesh.c96
-rw-r--r--source/blender/blenkernel/intern/bullet.c96
-rw-r--r--source/blender/blenkernel/intern/cdderivedmesh.c199
-rw-r--r--source/blender/blenkernel/intern/customdata.c163
-rw-r--r--source/blender/blenkernel/intern/fluidsim.c660
-rw-r--r--source/blender/blenkernel/intern/mesh.c6
-rw-r--r--source/blender/blenkernel/intern/modifier.c70
-rw-r--r--source/blender/blenkernel/intern/multires-firstlevel.c409
-rw-r--r--source/blender/blenkernel/intern/multires.c2366
-rw-r--r--source/blender/blenkernel/intern/scene.c19
-rw-r--r--source/blender/blenkernel/intern/shrinkwrap.c599
-rw-r--r--source/blender/blenkernel/intern/simple_deform.c256
-rw-r--r--source/blender/blenkernel/intern/subsurf_ccg.c49
-rw-r--r--source/blender/blenkernel/intern/suggestions.c254
-rw-r--r--source/blender/blenloader/intern/readfile.c83
-rw-r--r--source/blender/blenloader/intern/writefile.c56
-rw-r--r--source/blender/gpu/intern/gpu_material.c2
-rw-r--r--source/blender/include/BIF_keyframing.h131
-rw-r--r--source/blender/include/multires.h59
-rw-r--r--source/blender/makesdna/DNA_customdata_types.h5
-rw-r--r--source/blender/makesdna/DNA_meshdata_types.h22
-rw-r--r--source/blender/makesdna/DNA_modifier_types.h12
-rw-r--r--source/blender/python/api2_2x/Mesh.c23
-rw-r--r--source/blender/render/intern/include/render_types.h1
-rw-r--r--source/blender/render/intern/source/convertblender.c10
-rw-r--r--source/blender/src/buttons_editing.c197
-rw-r--r--source/blender/src/drawview.c21
-rw-r--r--source/blender/src/editdeform.c7
-rw-r--r--source/blender/src/editface.c11
-rw-r--r--source/blender/src/editkey.c37
-rw-r--r--source/blender/src/editmesh.c48
-rw-r--r--source/blender/src/editmesh_add.c6
-rw-r--r--source/blender/src/editmesh_mods.c9
-rw-r--r--source/blender/src/editmesh_tools.c33
-rw-r--r--source/blender/src/editobject.c3
-rw-r--r--source/blender/src/editsima.c2
-rw-r--r--source/blender/src/header_view3d.c13
-rw-r--r--source/blender/src/keyframing.c2104
-rw-r--r--source/blender/src/meshtools.c14
-rw-r--r--source/blender/src/multires.c431
-rw-r--r--source/blender/src/sculptmode.c316
-rw-r--r--source/blender/src/space.c22
-rw-r--r--source/blender/src/usiblender.c9
-rw-r--r--source/blender/src/vpaint.c5
-rw-r--r--source/gameengine/BlenderRoutines/BL_KetsjiEmbedStart.cpp177
-rw-r--r--source/gameengine/BlenderRoutines/CMakeLists.txt1
-rw-r--r--source/gameengine/BlenderRoutines/KX_BlenderGL.cpp101
-rw-r--r--source/gameengine/BlenderRoutines/KX_BlenderGL.h3
-rw-r--r--source/gameengine/BlenderRoutines/KX_BlenderRenderTools.cpp262
-rw-r--r--source/gameengine/BlenderRoutines/KX_BlenderRenderTools.h71
-rw-r--r--source/gameengine/BlenderRoutines/Makefile6
-rw-r--r--source/gameengine/BlenderRoutines/SConscript5
-rw-r--r--source/gameengine/CMakeLists.txt1
-rw-r--r--source/gameengine/Converter/BL_ActionActuator.cpp135
-rw-r--r--source/gameengine/Converter/BL_ArmatureObject.cpp91
-rw-r--r--source/gameengine/Converter/BL_ArmatureObject.h10
-rw-r--r--source/gameengine/Converter/BL_BlenderDataConversion.cpp365
-rw-r--r--source/gameengine/Converter/BL_DeformableGameObject.cpp8
-rw-r--r--source/gameengine/Converter/BL_DeformableGameObject.h14
-rw-r--r--source/gameengine/Converter/BL_MeshDeformer.cpp89
-rw-r--r--source/gameengine/Converter/BL_MeshDeformer.h5
-rw-r--r--source/gameengine/Converter/BL_ShapeActionActuator.cpp168
-rw-r--r--source/gameengine/Converter/BL_ShapeActionActuator.h5
-rw-r--r--source/gameengine/Converter/BL_ShapeDeformer.cpp9
-rw-r--r--source/gameengine/Converter/BL_ShapeDeformer.h13
-rw-r--r--source/gameengine/Converter/BL_SkinDeformer.cpp51
-rw-r--r--source/gameengine/Converter/BL_SkinDeformer.h18
-rw-r--r--source/gameengine/Converter/BL_SkinMeshObject.cpp74
-rw-r--r--source/gameengine/Converter/BL_SkinMeshObject.h45
-rw-r--r--source/gameengine/Converter/CMakeLists.txt1
-rw-r--r--source/gameengine/Converter/KX_BlenderScalarInterpolator.cpp13
-rw-r--r--source/gameengine/Converter/KX_BlenderSceneConverter.cpp72
-rw-r--r--source/gameengine/Converter/KX_BlenderSceneConverter.h2
-rw-r--r--source/gameengine/Converter/KX_ConvertActuators.cpp193
-rw-r--r--source/gameengine/Converter/KX_ConvertProperties.cpp8
-rw-r--r--source/gameengine/Converter/KX_ConvertSensors.cpp60
-rw-r--r--source/gameengine/Converter/KX_ConvertSensors.h1
-rw-r--r--source/gameengine/Converter/Makefile1
-rw-r--r--source/gameengine/Converter/SConscript2
-rw-r--r--source/gameengine/Expressions/InputParser.cpp5
-rw-r--r--source/gameengine/Expressions/ListValue.cpp13
-rw-r--r--source/gameengine/Expressions/Makefile1
-rw-r--r--source/gameengine/Expressions/PyObjectPlus.cpp459
-rw-r--r--source/gameengine/Expressions/PyObjectPlus.h187
-rw-r--r--source/gameengine/Expressions/Value.cpp58
-rw-r--r--source/gameengine/Expressions/Value.h7
-rw-r--r--source/gameengine/GameLogic/Joystick/SCA_Joystick.cpp343
-rw-r--r--source/gameengine/GameLogic/Joystick/SCA_Joystick.h252
-rw-r--r--source/gameengine/GameLogic/Joystick/SCA_JoystickDefines.h8
-rw-r--r--source/gameengine/GameLogic/Joystick/SCA_JoystickEvents.cpp89
-rw-r--r--source/gameengine/GameLogic/Joystick/SCA_JoystickPrivate.h7
-rw-r--r--source/gameengine/GameLogic/Makefile1
-rw-r--r--source/gameengine/GameLogic/SCA_2DFilterActuator.cpp8
-rw-r--r--source/gameengine/GameLogic/SCA_ActuatorSensor.cpp33
-rw-r--r--source/gameengine/GameLogic/SCA_ActuatorSensor.h1
-rw-r--r--source/gameengine/GameLogic/SCA_DelaySensor.cpp302
-rw-r--r--source/gameengine/GameLogic/SCA_DelaySensor.h78
-rw-r--r--source/gameengine/GameLogic/SCA_IController.cpp2
-rw-r--r--source/gameengine/GameLogic/SCA_ILogicBrick.cpp6
-rw-r--r--source/gameengine/GameLogic/SCA_ISensor.cpp289
-rw-r--r--source/gameengine/GameLogic/SCA_ISensor.h28
-rw-r--r--source/gameengine/GameLogic/SCA_JoystickManager.cpp36
-rw-r--r--source/gameengine/GameLogic/SCA_JoystickManager.h4
-rw-r--r--source/gameengine/GameLogic/SCA_JoystickSensor.cpp408
-rw-r--r--source/gameengine/GameLogic/SCA_JoystickSensor.h86
-rw-r--r--source/gameengine/GameLogic/SCA_KeyboardSensor.cpp216
-rw-r--r--source/gameengine/GameLogic/SCA_KeyboardSensor.h16
-rw-r--r--source/gameengine/GameLogic/SCA_LogicManager.cpp31
-rw-r--r--source/gameengine/GameLogic/SCA_LogicManager.h2
-rw-r--r--source/gameengine/GameLogic/SCA_MouseSensor.cpp237
-rw-r--r--source/gameengine/GameLogic/SCA_MouseSensor.h12
-rw-r--r--source/gameengine/GameLogic/SCA_PropertyActuator.cpp51
-rw-r--r--source/gameengine/GameLogic/SCA_PropertyActuator.h1
-rw-r--r--source/gameengine/GameLogic/SCA_PropertySensor.cpp76
-rw-r--r--source/gameengine/GameLogic/SCA_PropertySensor.h1
-rw-r--r--source/gameengine/GameLogic/SCA_PythonController.cpp81
-rw-r--r--source/gameengine/GameLogic/SCA_PythonController.h11
-rw-r--r--source/gameengine/GameLogic/SCA_RandomActuator.cpp132
-rw-r--r--source/gameengine/GameLogic/SCA_RandomActuator.h1
-rw-r--r--source/gameengine/GameLogic/SCA_RandomSensor.cpp12
-rw-r--r--source/gameengine/GameLogic/SConscript11
-rw-r--r--source/gameengine/GamePlayer/CMakeLists.txt4
-rw-r--r--source/gameengine/GamePlayer/common/CMakeLists.txt2
-rw-r--r--source/gameengine/GamePlayer/common/GPC_RawImage.cpp2
-rw-r--r--source/gameengine/GamePlayer/common/GPC_RawImage.h2
-rw-r--r--source/gameengine/GamePlayer/common/GPC_RenderTools.cpp538
-rw-r--r--source/gameengine/GamePlayer/common/GPC_RenderTools.h168
-rw-r--r--source/gameengine/GamePlayer/common/Makefile5
-rw-r--r--source/gameengine/GamePlayer/common/SConscript2
-rw-r--r--source/gameengine/GamePlayer/common/unix/GPU_PolygonMaterial.h4
-rw-r--r--source/gameengine/GamePlayer/common/unix/Makefile1
-rw-r--r--source/gameengine/GamePlayer/ghost/CMakeLists.txt5
-rw-r--r--source/gameengine/GamePlayer/ghost/GPG_Application.cpp111
-rw-r--r--source/gameengine/GamePlayer/ghost/GPG_Application.h17
-rw-r--r--source/gameengine/GamePlayer/ghost/GPG_ghost.cpp162
-rw-r--r--source/gameengine/GamePlayer/ghost/Makefile7
-rw-r--r--source/gameengine/GamePlayer/ghost/SConscript9
-rw-r--r--source/gameengine/Ketsji/BL_BlenderShader.cpp124
-rw-r--r--source/gameengine/Ketsji/BL_BlenderShader.h10
-rw-r--r--source/gameengine/Ketsji/BL_Material.h6
-rw-r--r--source/gameengine/Ketsji/BL_Shader.cpp90
-rw-r--r--source/gameengine/Ketsji/BL_Shader.h6
-rw-r--r--source/gameengine/Ketsji/BL_Texture.h8
-rw-r--r--source/gameengine/Ketsji/CMakeLists.txt1
-rw-r--r--source/gameengine/Ketsji/KXNetwork/KX_NetworkMessageSensor.cpp88
-rw-r--r--source/gameengine/Ketsji/KXNetwork/KX_NetworkMessageSensor.h10
-rw-r--r--source/gameengine/Ketsji/KX_BlenderMaterial.cpp126
-rw-r--r--source/gameengine/Ketsji/KX_BlenderMaterial.h9
-rw-r--r--source/gameengine/Ketsji/KX_BulletPhysicsController.cpp46
-rw-r--r--source/gameengine/Ketsji/KX_BulletPhysicsController.h5
-rw-r--r--source/gameengine/Ketsji/KX_Camera.cpp77
-rw-r--r--source/gameengine/Ketsji/KX_CameraActuator.cpp105
-rw-r--r--source/gameengine/Ketsji/KX_CameraActuator.h4
-rw-r--r--source/gameengine/Ketsji/KX_ConstraintActuator.cpp366
-rw-r--r--source/gameengine/Ketsji/KX_ConstraintActuator.h26
-rw-r--r--source/gameengine/Ketsji/KX_ConstraintWrapper.cpp4
-rw-r--r--source/gameengine/Ketsji/KX_ConvertPhysicsObject.h42
-rw-r--r--source/gameengine/Ketsji/KX_ConvertPhysicsObjects.cpp655
-rw-r--r--source/gameengine/Ketsji/KX_GameActuator.cpp74
-rw-r--r--source/gameengine/Ketsji/KX_GameActuator.h2
-rw-r--r--source/gameengine/Ketsji/KX_GameObject.cpp604
-rw-r--r--source/gameengine/Ketsji/KX_GameObject.h127
-rw-r--r--source/gameengine/Ketsji/KX_IPO_SGController.cpp117
-rw-r--r--source/gameengine/Ketsji/KX_IPO_SGController.h6
-rw-r--r--source/gameengine/Ketsji/KX_IPhysicsController.h4
-rw-r--r--source/gameengine/Ketsji/KX_ISceneConverter.h4
-rw-r--r--source/gameengine/Ketsji/KX_IpoActuator.cpp103
-rw-r--r--source/gameengine/Ketsji/KX_IpoActuator.h4
-rw-r--r--source/gameengine/Ketsji/KX_KetsjiEngine.cpp255
-rw-r--r--source/gameengine/Ketsji/KX_KetsjiEngine.h23
-rw-r--r--source/gameengine/Ketsji/KX_Light.cpp64
-rw-r--r--source/gameengine/Ketsji/KX_Light.h11
-rw-r--r--source/gameengine/Ketsji/KX_MaterialIpoController.cpp10
-rw-r--r--source/gameengine/Ketsji/KX_MeshProxy.cpp48
-rw-r--r--source/gameengine/Ketsji/KX_MeshProxy.h2
-rw-r--r--source/gameengine/Ketsji/KX_MouseFocusSensor.cpp60
-rw-r--r--source/gameengine/Ketsji/KX_MouseFocusSensor.h16
-rw-r--r--source/gameengine/Ketsji/KX_NearSensor.cpp22
-rw-r--r--source/gameengine/Ketsji/KX_ObjectActuator.cpp11
-rw-r--r--source/gameengine/Ketsji/KX_OdePhysicsController.cpp5
-rw-r--r--source/gameengine/Ketsji/KX_OdePhysicsController.h2
-rw-r--r--source/gameengine/Ketsji/KX_ParentActuator.cpp76
-rw-r--r--source/gameengine/Ketsji/KX_ParentActuator.h4
-rw-r--r--source/gameengine/Ketsji/KX_PhysicsObjectWrapper.cpp10
-rw-r--r--source/gameengine/Ketsji/KX_PolyProxy.cpp265
-rw-r--r--source/gameengine/Ketsji/KX_PolyProxy.h71
-rw-r--r--source/gameengine/Ketsji/KX_PolygonMaterial.cpp50
-rw-r--r--source/gameengine/Ketsji/KX_PolygonMaterial.h2
-rw-r--r--source/gameengine/Ketsji/KX_PyConstraintBinding.cpp78
-rw-r--r--source/gameengine/Ketsji/KX_PythonInit.cpp955
-rw-r--r--source/gameengine/Ketsji/KX_PythonInit.h16
-rw-r--r--source/gameengine/Ketsji/KX_RadarSensor.cpp12
-rw-r--r--source/gameengine/Ketsji/KX_RayCast.cpp85
-rw-r--r--source/gameengine/Ketsji/KX_RayCast.h60
-rw-r--r--source/gameengine/Ketsji/KX_RaySensor.cpp74
-rw-r--r--source/gameengine/Ketsji/KX_RaySensor.h8
-rw-r--r--source/gameengine/Ketsji/KX_SCA_AddObjectActuator.cpp211
-rw-r--r--source/gameengine/Ketsji/KX_SCA_AddObjectActuator.h34
-rw-r--r--source/gameengine/Ketsji/KX_SCA_ReplaceMeshActuator.cpp43
-rw-r--r--source/gameengine/Ketsji/KX_SCA_ReplaceMeshActuator.h2
-rw-r--r--source/gameengine/Ketsji/KX_SG_BoneParentNodeRelationship.cpp2
-rw-r--r--source/gameengine/Ketsji/KX_Scene.cpp118
-rw-r--r--source/gameengine/Ketsji/KX_Scene.h16
-rw-r--r--source/gameengine/Ketsji/KX_SceneActuator.cpp24
-rw-r--r--source/gameengine/Ketsji/KX_SoundActuator.cpp122
-rw-r--r--source/gameengine/Ketsji/KX_StateActuator.cpp8
-rw-r--r--source/gameengine/Ketsji/KX_SumoPhysicsController.cpp5
-rw-r--r--source/gameengine/Ketsji/KX_SumoPhysicsController.h1
-rw-r--r--source/gameengine/Ketsji/KX_TouchSensor.cpp33
-rw-r--r--source/gameengine/Ketsji/KX_TouchSensor.h1
-rw-r--r--source/gameengine/Ketsji/KX_TrackToActuator.cpp84
-rw-r--r--source/gameengine/Ketsji/KX_TrackToActuator.h4
-rw-r--r--source/gameengine/Ketsji/KX_VehicleWrapper.cpp72
-rw-r--r--source/gameengine/Ketsji/KX_VertexProxy.cpp14
-rw-r--r--source/gameengine/Ketsji/KX_VisibilityActuator.cpp14
-rw-r--r--source/gameengine/Ketsji/KX_VisibilityActuator.h2
-rw-r--r--source/gameengine/Ketsji/Makefile11
-rw-r--r--source/gameengine/Ketsji/SConscript9
-rw-r--r--source/gameengine/Makefile2
-rw-r--r--source/gameengine/Physics/BlOde/OdePhysicsController.h2
-rw-r--r--source/gameengine/Physics/BlOde/OdePhysicsEnvironment.cpp5
-rw-r--r--source/gameengine/Physics/BlOde/OdePhysicsEnvironment.h3
-rw-r--r--source/gameengine/Physics/Bullet/CMakeLists.txt4
-rw-r--r--source/gameengine/Physics/Bullet/CcdPhysicsController.cpp1098
-rw-r--r--source/gameengine/Physics/Bullet/CcdPhysicsController.h263
-rw-r--r--source/gameengine/Physics/Bullet/CcdPhysicsEnvironment.cpp752
-rw-r--r--source/gameengine/Physics/Bullet/CcdPhysicsEnvironment.h26
-rw-r--r--source/gameengine/Physics/Bullet/Makefile5
-rw-r--r--source/gameengine/Physics/Bullet/SConscript2
-rw-r--r--source/gameengine/Physics/Dummy/DummyPhysicsEnvironment.cpp6
-rw-r--r--source/gameengine/Physics/Dummy/DummyPhysicsEnvironment.h5
-rw-r--r--source/gameengine/Physics/Sumo/SConscript3
-rw-r--r--source/gameengine/Physics/Sumo/SumoPhysicsController.h1
-rw-r--r--source/gameengine/Physics/Sumo/SumoPhysicsEnvironment.cpp35
-rw-r--r--source/gameengine/Physics/Sumo/SumoPhysicsEnvironment.h5
-rw-r--r--source/gameengine/Physics/common/PHY_DynamicTypes.h12
-rw-r--r--source/gameengine/Physics/common/PHY_IPhysicsController.h3
-rw-r--r--source/gameengine/Physics/common/PHY_IPhysicsEnvironment.h49
-rw-r--r--source/gameengine/PyDoc/BL_ActionActuator.py13
-rw-r--r--source/gameengine/PyDoc/BL_ShapeActionActuator.py13
-rw-r--r--source/gameengine/PyDoc/GameKeys.py9
-rw-r--r--source/gameengine/PyDoc/GameLogic.py80
-rw-r--r--source/gameengine/PyDoc/KX_ActuatorSensor.py8
-rw-r--r--source/gameengine/PyDoc/KX_CameraActuator.py8
-rw-r--r--source/gameengine/PyDoc/KX_ConstraintActuator.py22
-rw-r--r--source/gameengine/PyDoc/KX_GameObject.py143
-rw-r--r--source/gameengine/PyDoc/KX_IpoActuator.py6
-rw-r--r--source/gameengine/PyDoc/KX_MeshProxy.py15
-rw-r--r--source/gameengine/PyDoc/KX_ObjectActuator.py4
-rw-r--r--source/gameengine/PyDoc/KX_ParentActuator.py9
-rw-r--r--source/gameengine/PyDoc/KX_PolyProxy.py100
-rw-r--r--source/gameengine/PyDoc/KX_SCA_AddObjectActuator.py30
-rw-r--r--source/gameengine/PyDoc/KX_SCA_ReplaceMeshActuator.py5
-rw-r--r--source/gameengine/PyDoc/KX_TrackToActuator.py10
-rw-r--r--source/gameengine/PyDoc/Rasterizer.py53
-rw-r--r--source/gameengine/PyDoc/SCA_DelaySensor.py73
-rw-r--r--source/gameengine/PyDoc/SCA_ILogicBrick.py9
-rw-r--r--source/gameengine/PyDoc/SCA_ISensor.py35
-rw-r--r--source/gameengine/PyDoc/SCA_JoystickSensor.py163
-rw-r--r--source/gameengine/PyDoc/SCA_KeyboardSensor.py65
-rw-r--r--source/gameengine/PyDoc/SCA_MouseSensor.py11
-rw-r--r--source/gameengine/PyDoc/SCA_PropertyActuator.py11
-rw-r--r--source/gameengine/PyDoc/SCA_PropertySensor.py17
-rw-r--r--source/gameengine/PyDoc/SCA_PythonController.py10
-rw-r--r--source/gameengine/PyDoc/SCA_RandomActuator.py32
-rw-r--r--source/gameengine/PyDoc/SConscript28
-rw-r--r--source/gameengine/PyDoc/epy_docgen.sh2
-rw-r--r--source/gameengine/Rasterizer/Makefile4
-rw-r--r--source/gameengine/Rasterizer/RAS_2DFilterManager.cpp279
-rw-r--r--source/gameengine/Rasterizer/RAS_2DFilterManager.h9
-rw-r--r--source/gameengine/Rasterizer/RAS_BucketManager.cpp254
-rw-r--r--source/gameengine/Rasterizer/RAS_BucketManager.h21
-rw-r--r--source/gameengine/Rasterizer/RAS_Deformer.h6
-rw-r--r--source/gameengine/Rasterizer/RAS_FramingManager.h20
-rw-r--r--source/gameengine/Rasterizer/RAS_IPolygonMaterial.cpp25
-rw-r--r--source/gameengine/Rasterizer/RAS_IPolygonMaterial.h9
-rw-r--r--source/gameengine/Rasterizer/RAS_IRasterizer.h53
-rw-r--r--source/gameengine/Rasterizer/RAS_IRenderTools.cpp24
-rw-r--r--source/gameengine/Rasterizer/RAS_IRenderTools.h39
-rw-r--r--source/gameengine/Rasterizer/RAS_MaterialBucket.cpp576
-rw-r--r--source/gameengine/Rasterizer/RAS_MaterialBucket.h213
-rw-r--r--source/gameengine/Rasterizer/RAS_MeshObject.cpp725
-rw-r--r--source/gameengine/Rasterizer/RAS_MeshObject.h240
-rw-r--r--source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Blur2DFilter.h2
-rw-r--r--source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Dilation2DFilter.h2
-rw-r--r--source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Erosion2DFilter.h2
-rw-r--r--source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_GrayScale2DFilter.h2
-rw-r--r--source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Invert2DFilter.h2
-rw-r--r--source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Laplacian2DFilter.h2
-rw-r--r--source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Prewitt2DFilter.h2
-rw-r--r--source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Sepia2DFilter.h2
-rw-r--r--source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Sharpen2DFilter.h2
-rw-r--r--source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Sobel2DFilter.h2
-rw-r--r--source/gameengine/Rasterizer/RAS_OpenGLRasterizer/CMakeLists.txt1
-rw-r--r--source/gameengine/Rasterizer/RAS_OpenGLRasterizer/Makefile5
-rw-r--r--source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_ListRasterizer.cpp84
-rw-r--r--source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_ListRasterizer.h24
-rw-r--r--source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLRasterizer.cpp790
-rw-r--r--source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLRasterizer.h50
-rw-r--r--source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_VAOpenGLRasterizer.cpp216
-rw-r--r--source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_VAOpenGLRasterizer.h18
-rw-r--r--source/gameengine/Rasterizer/RAS_OpenGLRasterizer/SConscript5
-rw-r--r--source/gameengine/Rasterizer/RAS_Polygon.cpp83
-rw-r--r--source/gameengine/Rasterizer/RAS_Polygon.h56
-rw-r--r--source/gameengine/Rasterizer/RAS_TexVert.cpp31
-rw-r--r--source/gameengine/Rasterizer/RAS_TexVert.h49
-rw-r--r--source/gameengine/Rasterizer/SConscript5
-rw-r--r--source/gameengine/SConscript3
-rw-r--r--source/gameengine/VideoTexture/BlendType.h75
-rw-r--r--source/gameengine/VideoTexture/CMakeLists.txt61
-rw-r--r--source/gameengine/VideoTexture/Common.h55
-rw-r--r--source/gameengine/VideoTexture/Exception.cpp215
-rw-r--r--source/gameengine/VideoTexture/Exception.h216
-rw-r--r--source/gameengine/VideoTexture/FilterBase.cpp150
-rw-r--r--source/gameengine/VideoTexture/FilterBase.h138
-rw-r--r--source/gameengine/VideoTexture/FilterBlueScreen.cpp178
-rw-r--r--source/gameengine/VideoTexture/FilterBlueScreen.h97
-rw-r--r--source/gameengine/VideoTexture/FilterColor.cpp350
-rw-r--r--source/gameengine/VideoTexture/FilterColor.h168
-rw-r--r--source/gameengine/VideoTexture/FilterNormal.cpp162
-rw-r--r--source/gameengine/VideoTexture/FilterNormal.h107
-rw-r--r--source/gameengine/VideoTexture/FilterSource.cpp171
-rw-r--r--source/gameengine/VideoTexture/FilterSource.h258
-rw-r--r--source/gameengine/VideoTexture/ImageBase.cpp529
-rw-r--r--source/gameengine/VideoTexture/ImageBase.h349
-rw-r--r--source/gameengine/VideoTexture/ImageBuff.cpp166
-rw-r--r--source/gameengine/VideoTexture/ImageBuff.h51
-rw-r--r--source/gameengine/VideoTexture/ImageMix.cpp205
-rw-r--r--source/gameengine/VideoTexture/ImageMix.h123
-rw-r--r--source/gameengine/VideoTexture/ImageRender.cpp742
-rw-r--r--source/gameengine/VideoTexture/ImageRender.h104
-rw-r--r--source/gameengine/VideoTexture/ImageViewport.cpp331
-rw-r--r--source/gameengine/VideoTexture/ImageViewport.h98
-rw-r--r--source/gameengine/VideoTexture/Makefile65
-rw-r--r--source/gameengine/VideoTexture/PyTypeList.cpp83
-rw-r--r--source/gameengine/VideoTexture/PyTypeList.h85
-rw-r--r--source/gameengine/VideoTexture/SConscript32
-rw-r--r--source/gameengine/VideoTexture/Texture.cpp476
-rw-r--r--source/gameengine/VideoTexture/Texture.h92
-rw-r--r--source/gameengine/VideoTexture/VideoBase.cpp195
-rw-r--r--source/gameengine/VideoTexture/VideoBase.h185
-rw-r--r--source/gameengine/VideoTexture/VideoFFmpeg.cpp927
-rw-r--r--source/gameengine/VideoTexture/VideoFFmpeg.h173
-rw-r--r--source/gameengine/VideoTexture/blendVideoTex.cpp196
466 files changed, 10037 insertions, 50611 deletions
diff --git a/extern/bullet2/src/BulletCollision/BroadphaseCollision/btDbvt.cpp b/extern/bullet2/src/BulletCollision/BroadphaseCollision/btDbvt.cpp
deleted file mode 100644
index 7c41c8d8f71..00000000000
--- a/extern/bullet2/src/BulletCollision/BroadphaseCollision/btDbvt.cpp
+++ /dev/null
@@ -1,1289 +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.
-*/
-///btDbvt implementation by Nathanael Presson
-
-#include "btDbvt.h"
-
-//
-typedef btAlignedObjectArray<btDbvtNode*> tNodeArray;
-typedef btAlignedObjectArray<const btDbvtNode*> tConstNodeArray;
-
-//
-struct btDbvtNodeEnumerator : btDbvt::ICollide
-{
-tConstNodeArray nodes;
-void Process(const btDbvtNode* n) { nodes.push_back(n); }
-};
-
-//
-static DBVT_INLINE int indexof(const btDbvtNode* node)
-{
-return(node->parent->childs[1]==node);
-}
-
-//
-static DBVT_INLINE btDbvtVolume merge( const btDbvtVolume& a,
- const btDbvtVolume& b)
-{
-#if DBVT_MERGE_IMPL==DBVT_IMPL_SSE
-DBVT_ALIGN char locals[sizeof(btDbvtAabbMm)];
-btDbvtVolume& res=*(btDbvtVolume*)locals;
-#else
-btDbvtVolume res;
-#endif
-Merge(a,b,res);
-return(res);
-}
-
-// volume+edge lengths
-static DBVT_INLINE btScalar size(const btDbvtVolume& a)
-{
-const btVector3 edges=a.Lengths();
-return( edges.x()*edges.y()*edges.z()+
- edges.x()+edges.y()+edges.z());
-}
-
-//
-static void getmaxdepth(const btDbvtNode* node,int depth,int& maxdepth)
-{
-if(node->isinternal())
- {
- getmaxdepth(node->childs[0],depth+1,maxdepth);
- getmaxdepth(node->childs[0],depth+1,maxdepth);
- } else maxdepth=btMax(maxdepth,depth);
-}
-
-//
-static DBVT_INLINE void deletenode( btDbvt* pdbvt,
- btDbvtNode* node)
-{
-btAlignedFree(pdbvt->m_free);
-pdbvt->m_free=node;
-}
-
-//
-static void recursedeletenode( btDbvt* pdbvt,
- btDbvtNode* node)
-{
-if(!node->isleaf())
- {
- recursedeletenode(pdbvt,node->childs[0]);
- recursedeletenode(pdbvt,node->childs[1]);
- }
-if(node==pdbvt->m_root) pdbvt->m_root=0;
-deletenode(pdbvt,node);
-}
-
-//
-static DBVT_INLINE btDbvtNode* createnode( btDbvt* pdbvt,
- btDbvtNode* parent,
- void* data)
-{
-btDbvtNode* node;
-if(pdbvt->m_free)
- { node=pdbvt->m_free;pdbvt->m_free=0; }
- else
- { node=new(btAlignedAlloc(sizeof(btDbvtNode),16)) btDbvtNode(); }
-node->parent = parent;
-node->data = data;
-node->childs[1] = 0;
-return(node);
-}
-
-//
-static DBVT_INLINE btDbvtNode* createnode( btDbvt* pdbvt,
- btDbvtNode* parent,
- const btDbvtVolume& volume,
- void* data)
-{
-btDbvtNode* node=createnode(pdbvt,parent,data);
-node->volume=volume;
-return(node);
-}
-
-//
-static DBVT_INLINE btDbvtNode* createnode( btDbvt* pdbvt,
- btDbvtNode* parent,
- const btDbvtVolume& volume0,
- const btDbvtVolume& volume1,
- void* data)
-{
-btDbvtNode* node=createnode(pdbvt,parent,data);
-Merge(volume0,volume1,node->volume);
-return(node);
-}
-
-//
-static void insertleaf( btDbvt* pdbvt,
- btDbvtNode* root,
- btDbvtNode* leaf)
-{
-if(!pdbvt->m_root)
- {
- pdbvt->m_root = leaf;
- leaf->parent = 0;
- }
- else
- {
- if(!root->isleaf())
- {
- do {
- root=root->childs[Select( leaf->volume,
- root->childs[0]->volume,
- root->childs[1]->volume)];
- } while(!root->isleaf());
- }
- btDbvtNode* prev=root->parent;
- btDbvtNode* node=createnode(pdbvt,prev,leaf->volume,root->volume,0);
- if(prev)
- {
- prev->childs[indexof(root)] = node;
- node->childs[0] = root;root->parent=node;
- node->childs[1] = leaf;leaf->parent=node;
- do {
- if(!prev->volume.Contain(node->volume))
- Merge(prev->childs[0]->volume,prev->childs[1]->volume,prev->volume);
- else
- break;
- node=prev;
- } while(0!=(prev=node->parent));
- }
- else
- {
- node->childs[0] = root;root->parent=node;
- node->childs[1] = leaf;leaf->parent=node;
- pdbvt->m_root = node;
- }
- }
-}
-
-//
-static btDbvtNode* removeleaf( btDbvt* pdbvt,
- btDbvtNode* leaf)
-{
-if(leaf==pdbvt->m_root)
- {
- pdbvt->m_root=0;
- return(0);
- }
- else
- {
- btDbvtNode* parent=leaf->parent;
- btDbvtNode* prev=parent->parent;
- btDbvtNode* sibling=parent->childs[1-indexof(leaf)];
- if(prev)
- {
- prev->childs[indexof(parent)]=sibling;
- sibling->parent=prev;
- deletenode(pdbvt,parent);
- while(prev)
- {
- const btDbvtVolume pb=prev->volume;
- Merge(prev->childs[0]->volume,prev->childs[1]->volume,prev->volume);
- if(NotEqual(pb,prev->volume))
- {
- prev=prev->parent;
- } else break;
- }
- return(prev?prev:pdbvt->m_root);
- }
- else
- {
- pdbvt->m_root=sibling;
- sibling->parent=0;
- deletenode(pdbvt,parent);
- return(pdbvt->m_root);
- }
- }
-}
-
-//
-static void fetchleaves(btDbvt* pdbvt,
- btDbvtNode* root,
- tNodeArray& leaves,
- int depth=-1)
-{
-if(root->isinternal()&&depth)
- {
- fetchleaves(pdbvt,root->childs[0],leaves,depth-1);
- fetchleaves(pdbvt,root->childs[1],leaves,depth-1);
- deletenode(pdbvt,root);
- }
- else
- {
- leaves.push_back(root);
- }
-}
-
-//
-static void split( const tNodeArray& leaves,
- tNodeArray& left,
- tNodeArray& right,
- const btVector3& org,
- const btVector3& axis)
-{
-left.resize(0);
-right.resize(0);
-for(int i=0,ni=leaves.size();i<ni;++i)
- {
- if(dot(axis,leaves[i]->volume.Center()-org)<0)
- left.push_back(leaves[i]);
- else
- right.push_back(leaves[i]);
- }
-}
-
-//
-static btDbvtVolume bounds( const tNodeArray& leaves)
-{
-#if DBVT_MERGE_IMPL==DBVT_IMPL_SSE
-DBVT_ALIGN char locals[sizeof(btDbvtVolume)];
-btDbvtVolume& volume=*(btDbvtVolume*)locals;
-volume=leaves[0]->volume;
-#else
-btDbvtVolume volume=leaves[0]->volume;
-#endif
-for(int i=1,ni=leaves.size();i<ni;++i)
- {
- Merge(volume,leaves[i]->volume,volume);
- }
-return(volume);
-}
-
-//
-static void bottomup( btDbvt* pdbvt,
- tNodeArray& leaves)
-{
-while(leaves.size()>1)
- {
- btScalar minsize=SIMD_INFINITY;
- int minidx[2]={-1,-1};
- for(int i=0;i<leaves.size();++i)
- {
- for(int j=i+1;j<leaves.size();++j)
- {
- const btScalar sz=size(merge(leaves[i]->volume,leaves[j]->volume));
- if(sz<minsize)
- {
- minsize = sz;
- minidx[0] = i;
- minidx[1] = j;
- }
- }
- }
- btDbvtNode* n[] = {leaves[minidx[0]],leaves[minidx[1]]};
- btDbvtNode* p = createnode(pdbvt,0,n[0]->volume,n[1]->volume,0);
- p->childs[0] = n[0];
- p->childs[1] = n[1];
- n[0]->parent = p;
- n[1]->parent = p;
- leaves[minidx[0]] = p;
- leaves.swap(minidx[1],leaves.size()-1);
- leaves.pop_back();
- }
-}
-
-//
-static btDbvtNode* topdown(btDbvt* pdbvt,
- tNodeArray& leaves,
- int bu_treshold)
-{
-static const btVector3 axis[]={btVector3(1,0,0),
- btVector3(0,1,0),
- btVector3(0,0,1)};
-if(leaves.size()>1)
- {
- if(leaves.size()>bu_treshold)
- {
- const btDbvtVolume vol=bounds(leaves);
- const btVector3 org=vol.Center();
- tNodeArray sets[2];
- int bestaxis=-1;
- int bestmidp=leaves.size();
- int splitcount[3][2]={{0,0},{0,0},{0,0}};
- int i;
- for( i=0;i<leaves.size();++i)
- {
- const btVector3 x=leaves[i]->volume.Center()-org;
- for(int j=0;j<3;++j)
- {
- ++splitcount[j][dot(x,axis[j])>0?1:0];
- }
- }
- for( i=0;i<3;++i)
- {
- if((splitcount[i][0]>0)&&(splitcount[i][1]>0))
- {
- const int midp=(int)btFabs(btScalar(splitcount[i][0]-splitcount[i][1]));
- if(midp<bestmidp)
- {
- bestaxis=i;
- bestmidp=midp;
- }
- }
- }
- if(bestaxis>=0)
- {
- sets[0].reserve(splitcount[bestaxis][0]);
- sets[1].reserve(splitcount[bestaxis][1]);
- split(leaves,sets[0],sets[1],org,axis[bestaxis]);
- }
- else
- {
- sets[0].reserve(leaves.size()/2+1);
- sets[1].reserve(leaves.size()/2);
- for(int i=0,ni=leaves.size();i<ni;++i)
- {
- sets[i&1].push_back(leaves[i]);
- }
- }
- btDbvtNode* node=createnode(pdbvt,0,vol,0);
- node->childs[0]=topdown(pdbvt,sets[0],bu_treshold);
- node->childs[1]=topdown(pdbvt,sets[1],bu_treshold);
- node->childs[0]->parent=node;
- node->childs[1]->parent=node;
- return(node);
- }
- else
- {
- bottomup(pdbvt,leaves);
- return(leaves[0]);
- }
- }
-return(leaves[0]);
-}
-
-//
-static DBVT_INLINE btDbvtNode* sort(btDbvtNode* n,btDbvtNode*& r)
-{
-btDbvtNode* p=n->parent;
-btAssert(n->isinternal());
-if(p>n)
- {
- const int i=indexof(n);
- const int j=1-i;
- btDbvtNode* s=p->childs[j];
- btDbvtNode* q=p->parent;
- btAssert(n==p->childs[i]);
- if(q) q->childs[indexof(p)]=n; else r=n;
- s->parent=n;
- p->parent=n;
- n->parent=q;
- p->childs[0]=n->childs[0];
- p->childs[1]=n->childs[1];
- n->childs[0]->parent=p;
- n->childs[1]->parent=p;
- n->childs[i]=p;
- n->childs[j]=s;
- btSwap(p->volume,n->volume);
- return(p);
- }
-return(n);
-}
-
-//
-static DBVT_INLINE btDbvtNode* walkup(btDbvtNode* n,int count)
-{
-while(n&&(count--)) n=n->parent;
-return(n);
-}
-
-//
-// Api
-//
-
-//
- btDbvt::btDbvt()
-{
-m_root = 0;
-m_free = 0;
-m_lkhd = -1;
-m_leaves = 0;
-m_opath = 0;
-}
-
-//
- btDbvt::~btDbvt()
-{
-clear();
-}
-
-//
-void btDbvt::clear()
-{
-if(m_root) recursedeletenode(this,m_root);
-btAlignedFree(m_free);
-m_free=0;
-}
-
-//
-void btDbvt::optimizeBottomUp()
-{
-if(m_root)
- {
- tNodeArray leaves;
- leaves.reserve(m_leaves);
- fetchleaves(this,m_root,leaves);
- bottomup(this,leaves);
- m_root=leaves[0];
- }
-}
-
-//
-void btDbvt::optimizeTopDown(int bu_treshold)
-{
-if(m_root)
- {
- tNodeArray leaves;
- leaves.reserve(m_leaves);
- fetchleaves(this,m_root,leaves);
- m_root=topdown(this,leaves,bu_treshold);
- }
-}
-
-//
-void btDbvt::optimizeIncremental(int passes)
-{
-if(passes<0) passes=m_leaves;
-if(m_root&&(passes>0))
- {
- do {
- btDbvtNode* node=m_root;
- unsigned bit=0;
- while(node->isinternal())
- {
- node=sort(node,m_root)->childs[(m_opath>>bit)&1];
- bit=(bit+1)&(sizeof(unsigned)*8-1);
- }
- update(node);
- ++m_opath;
- } while(--passes);
- }
-}
-
-//
-btDbvtNode* btDbvt::insert(const btDbvtVolume& volume,void* data)
-{
-btDbvtNode* leaf=createnode(this,0,volume,data);
-insertleaf(this,m_root,leaf);
-++m_leaves;
-return(leaf);
-}
-
-//
-void btDbvt::update(btDbvtNode* leaf,int lookahead)
-{
-btDbvtNode* root=removeleaf(this,leaf);
-if(root)
- {
- if(lookahead>=0)
- {
- for(int i=0;(i<lookahead)&&root->parent;++i)
- {
- root=root->parent;
- }
- } else root=m_root;
- }
-insertleaf(this,root,leaf);
-}
-
-//
-void btDbvt::update(btDbvtNode* leaf,const btDbvtVolume& volume)
-{
-btDbvtNode* root=removeleaf(this,leaf);
-if(root)
- {
- if(m_lkhd>=0)
- {
- for(int i=0;(i<m_lkhd)&&root->parent;++i)
- {
- root=root->parent;
- }
- } else root=m_root;
- }
-leaf->volume=volume;
-insertleaf(this,root,leaf);
-}
-
-//
-bool btDbvt::update(btDbvtNode* leaf,btDbvtVolume volume,const btVector3& velocity,btScalar margin)
-{
-if(leaf->volume.Contain(volume)) return(false);
-volume.Expand(btVector3(margin,margin,margin));
-volume.SignedExpand(velocity);
-update(leaf,volume);
-return(true);
-}
-
-//
-bool btDbvt::update(btDbvtNode* leaf,btDbvtVolume volume,const btVector3& velocity)
-{
-if(leaf->volume.Contain(volume)) return(false);
-volume.SignedExpand(velocity);
-update(leaf,volume);
-return(true);
-}
-
-//
-bool btDbvt::update(btDbvtNode* leaf,btDbvtVolume volume,btScalar margin)
-{
-if(leaf->volume.Contain(volume)) return(false);
-volume.Expand(btVector3(margin,margin,margin));
-update(leaf,volume);
-return(true);
-}
-
-//
-void btDbvt::remove(btDbvtNode* leaf)
-{
-removeleaf(this,leaf);
-deletenode(this,leaf);
---m_leaves;
-}
-
-//
-void btDbvt::write(IWriter* iwriter) const
-{
-btDbvtNodeEnumerator nodes;
-nodes.nodes.reserve(m_leaves*2);
-enumNodes(m_root,nodes);
-iwriter->Prepare(m_root,nodes.nodes.size());
-for(int i=0;i<nodes.nodes.size();++i)
- {
- const btDbvtNode* n=nodes.nodes[i];
- int p=-1;
- if(n->parent) p=nodes.nodes.findLinearSearch(n->parent);
- if(n->isinternal())
- {
- const int c0=nodes.nodes.findLinearSearch(n->childs[0]);
- const int c1=nodes.nodes.findLinearSearch(n->childs[1]);
- iwriter->WriteNode(n,i,p,c0,c1);
- }
- else
- {
- iwriter->WriteLeaf(n,i,p);
- }
- }
-}
-
-//
-void btDbvt::clone(btDbvt& dest,IClone* iclone) const
-{
-dest.clear();
-if(m_root!=0)
- {
- btAlignedObjectArray<sStkCLN> stack;
- stack.reserve(m_leaves);
- stack.push_back(sStkCLN(m_root,0));
- do {
- const int i=stack.size()-1;
- const sStkCLN e=stack[i];
- btDbvtNode* n=createnode(&dest,e.parent,e.node->volume,e.node->data);
- stack.pop_back();
- if(e.parent!=0)
- e.parent->childs[i&1]=n;
- else
- dest.m_root=n;
- if(e.node->isinternal())
- {
- stack.push_back(sStkCLN(e.node->childs[0],n));
- stack.push_back(sStkCLN(e.node->childs[1],n));
- }
- else
- {
- iclone->CloneLeaf(n);
- }
- } while(stack.size()>0);
- }
-}
-
-//
-int btDbvt::maxdepth(const btDbvtNode* node)
-{
-int depth=0;
-if(node) getmaxdepth(node,1,depth);
-return(depth);
-}
-
-//
-int btDbvt::countLeaves(const btDbvtNode* node)
-{
-if(node->isinternal())
- return(countLeaves(node->childs[0])+countLeaves(node->childs[1]));
- else
- return(1);
-}
-
-//
-void btDbvt::extractLeaves(const btDbvtNode* node,btAlignedObjectArray<const btDbvtNode*>& leaves)
-{
-if(node->isinternal())
- {
- extractLeaves(node->childs[0],leaves);
- extractLeaves(node->childs[1],leaves);
- }
- else
- {
- leaves.push_back(node);
- }
-}
-
-//
-#if DBVT_ENABLE_BENCHMARK
-
-#include <stdio.h>
-#include <stdlib.h>
-#include "LinearMath/btQuickProf.h"
-
-/*
-q6600,2.4ghz
-
-/Ox /Ob2 /Oi /Ot /I "." /I "..\.." /I "..\..\src" /D "NDEBUG" /D "_LIB" /D "_WINDOWS" /D "_CRT_SECURE_NO_DEPRECATE" /D "_CRT_NONSTDC_NO_DEPRECATE" /D "WIN32"
-/GF /FD /MT /GS- /Gy /arch:SSE2 /Zc:wchar_t- /Fp"..\..\out\release8\build\libbulletcollision\libbulletcollision.pch"
-/Fo"..\..\out\release8\build\libbulletcollision\\"
-/Fd"..\..\out\release8\build\libbulletcollision\bulletcollision.pdb"
-/W3 /nologo /c /Wp64 /Zi /errorReport:prompt
-
-Benchmarking dbvt...
- World scale: 100.000000
- Extents base: 1.000000
- Extents range: 4.000000
- Leaves: 8192
- sizeof(btDbvtVolume): 32 bytes
- sizeof(btDbvtNode): 44 bytes
-[1] btDbvtVolume intersections: 3499 ms (-1%)
-[2] btDbvtVolume merges: 1934 ms (0%)
-[3] btDbvt::collideTT: 5485 ms (-21%)
-[4] btDbvt::collideTT self: 2814 ms (-20%)
-[5] btDbvt::collideTT xform: 7379 ms (-1%)
-[6] btDbvt::collideTT xform,self: 7270 ms (-2%)
-[7] btDbvt::collideRAY: 6314 ms (0%),(332143 r/s)
-[8] insert/remove: 2093 ms (0%),(1001983 ir/s)
-[9] updates (teleport): 1879 ms (-3%),(1116100 u/s)
-[10] updates (jitter): 1244 ms (-4%),(1685813 u/s)
-[11] optimize (incremental): 2514 ms (0%),(1668000 o/s)
-[12] btDbvtVolume notequal: 3659 ms (0%)
-[13] culling(OCL+fullsort): 2218 ms (0%),(461 t/s)
-[14] culling(OCL+qsort): 3688 ms (5%),(2221 t/s)
-[15] culling(KDOP+qsort): 1139 ms (-1%),(7192 t/s)
-[16] insert/remove batch(256): 5092 ms (0%),(823704 bir/s)
-[17] btDbvtVolume select: 3419 ms (0%)
-*/
-
-struct btDbvtBenchmark
-{
-struct NilPolicy : btDbvt::ICollide
- {
- NilPolicy() : m_pcount(0),m_depth(-SIMD_INFINITY),m_checksort(true) {}
- void Process(const btDbvtNode*,const btDbvtNode*) { ++m_pcount; }
- void Process(const btDbvtNode*) { ++m_pcount; }
- void Process(const btDbvtNode*,btScalar depth)
- {
- ++m_pcount;
- if(m_checksort)
- { if(depth>=m_depth) m_depth=depth; else printf("wrong depth: %f (should be >= %f)\r\n",depth,m_depth); }
- }
- int m_pcount;
- btScalar m_depth;
- bool m_checksort;
- };
-struct P14 : btDbvt::ICollide
- {
- struct Node
- {
- const btDbvtNode* leaf;
- btScalar depth;
- };
- void Process(const btDbvtNode* leaf,btScalar depth)
- {
- Node n;
- n.leaf = leaf;
- n.depth = depth;
- }
- static int sortfnc(const Node& a,const Node& b)
- {
- if(a.depth<b.depth) return(+1);
- if(a.depth>b.depth) return(-1);
- return(0);
- }
- btAlignedObjectArray<Node> m_nodes;
- };
-struct P15 : btDbvt::ICollide
- {
- struct Node
- {
- const btDbvtNode* leaf;
- btScalar depth;
- };
- void Process(const btDbvtNode* leaf)
- {
- Node n;
- n.leaf = leaf;
- n.depth = dot(leaf->volume.Center(),m_axis);
- }
- static int sortfnc(const Node& a,const Node& b)
- {
- if(a.depth<b.depth) return(+1);
- if(a.depth>b.depth) return(-1);
- return(0);
- }
- btAlignedObjectArray<Node> m_nodes;
- btVector3 m_axis;
- };
-static btScalar RandUnit()
- {
- return(rand()/(btScalar)RAND_MAX);
- }
-static btVector3 RandVector3()
- {
- return(btVector3(RandUnit(),RandUnit(),RandUnit()));
- }
-static btVector3 RandVector3(btScalar cs)
- {
- return(RandVector3()*cs-btVector3(cs,cs,cs)/2);
- }
-static btDbvtVolume RandVolume(btScalar cs,btScalar eb,btScalar es)
- {
- return(btDbvtVolume::FromCE(RandVector3(cs),btVector3(eb,eb,eb)+RandVector3()*es));
- }
-static btTransform RandTransform(btScalar cs)
- {
- btTransform t;
- t.setOrigin(RandVector3(cs));
- t.setRotation(btQuaternion(RandUnit()*SIMD_PI*2,RandUnit()*SIMD_PI*2,RandUnit()*SIMD_PI*2).normalized());
- return(t);
- }
-static void RandTree(btScalar cs,btScalar eb,btScalar es,int leaves,btDbvt& dbvt)
- {
- dbvt.clear();
- for(int i=0;i<leaves;++i)
- {
- dbvt.insert(RandVolume(cs,eb,es),0);
- }
- }
-};
-
-void btDbvt::benchmark()
-{
-static const btScalar cfgVolumeCenterScale = 100;
-static const btScalar cfgVolumeExentsBase = 1;
-static const btScalar cfgVolumeExentsScale = 4;
-static const int cfgLeaves = 8192;
-static const bool cfgEnable = true;
-
-//[1] btDbvtVolume intersections
-bool cfgBenchmark1_Enable = cfgEnable;
-static const int cfgBenchmark1_Iterations = 8;
-static const int cfgBenchmark1_Reference = 3499;
-//[2] btDbvtVolume merges
-bool cfgBenchmark2_Enable = cfgEnable;
-static const int cfgBenchmark2_Iterations = 4;
-static const int cfgBenchmark2_Reference = 1945;
-//[3] btDbvt::collideTT
-bool cfgBenchmark3_Enable = cfgEnable;
-static const int cfgBenchmark3_Iterations = 512;
-static const int cfgBenchmark3_Reference = 5485;
-//[4] btDbvt::collideTT self
-bool cfgBenchmark4_Enable = cfgEnable;
-static const int cfgBenchmark4_Iterations = 512;
-static const int cfgBenchmark4_Reference = 2814;
-//[5] btDbvt::collideTT xform
-bool cfgBenchmark5_Enable = cfgEnable;
-static const int cfgBenchmark5_Iterations = 512;
-static const btScalar cfgBenchmark5_OffsetScale = 2;
-static const int cfgBenchmark5_Reference = 7379;
-//[6] btDbvt::collideTT xform,self
-bool cfgBenchmark6_Enable = cfgEnable;
-static const int cfgBenchmark6_Iterations = 512;
-static const btScalar cfgBenchmark6_OffsetScale = 2;
-static const int cfgBenchmark6_Reference = 7270;
-//[7] btDbvt::collideRAY
-bool cfgBenchmark7_Enable = cfgEnable;
-static const int cfgBenchmark7_Passes = 32;
-static const int cfgBenchmark7_Iterations = 65536;
-static const int cfgBenchmark7_Reference = 6307;
-//[8] insert/remove
-bool cfgBenchmark8_Enable = cfgEnable;
-static const int cfgBenchmark8_Passes = 32;
-static const int cfgBenchmark8_Iterations = 65536;
-static const int cfgBenchmark8_Reference = 2105;
-//[9] updates (teleport)
-bool cfgBenchmark9_Enable = cfgEnable;
-static const int cfgBenchmark9_Passes = 32;
-static const int cfgBenchmark9_Iterations = 65536;
-static const int cfgBenchmark9_Reference = 1879;
-//[10] updates (jitter)
-bool cfgBenchmark10_Enable = cfgEnable;
-static const btScalar cfgBenchmark10_Scale = cfgVolumeCenterScale/10000;
-static const int cfgBenchmark10_Passes = 32;
-static const int cfgBenchmark10_Iterations = 65536;
-static const int cfgBenchmark10_Reference = 1244;
-//[11] optimize (incremental)
-bool cfgBenchmark11_Enable = cfgEnable;
-static const int cfgBenchmark11_Passes = 64;
-static const int cfgBenchmark11_Iterations = 65536;
-static const int cfgBenchmark11_Reference = 2510;
-//[12] btDbvtVolume notequal
-bool cfgBenchmark12_Enable = cfgEnable;
-static const int cfgBenchmark12_Iterations = 32;
-static const int cfgBenchmark12_Reference = 3677;
-//[13] culling(OCL+fullsort)
-bool cfgBenchmark13_Enable = cfgEnable;
-static const int cfgBenchmark13_Iterations = 1024;
-static const int cfgBenchmark13_Reference = 2231;
-//[14] culling(OCL+qsort)
-bool cfgBenchmark14_Enable = cfgEnable;
-static const int cfgBenchmark14_Iterations = 8192;
-static const int cfgBenchmark14_Reference = 3500;
-//[15] culling(KDOP+qsort)
-bool cfgBenchmark15_Enable = cfgEnable;
-static const int cfgBenchmark15_Iterations = 8192;
-static const int cfgBenchmark15_Reference = 1151;
-//[16] insert/remove batch
-bool cfgBenchmark16_Enable = cfgEnable;
-static const int cfgBenchmark16_BatchCount = 256;
-static const int cfgBenchmark16_Passes = 16384;
-static const int cfgBenchmark16_Reference = 5138;
-//[17] select
-bool cfgBenchmark17_Enable = cfgEnable;
-static const int cfgBenchmark17_Iterations = 4;
-static const int cfgBenchmark17_Reference = 3390;
-
-btClock wallclock;
-printf("Benchmarking dbvt...\r\n");
-printf("\tWorld scale: %f\r\n",cfgVolumeCenterScale);
-printf("\tExtents base: %f\r\n",cfgVolumeExentsBase);
-printf("\tExtents range: %f\r\n",cfgVolumeExentsScale);
-printf("\tLeaves: %u\r\n",cfgLeaves);
-printf("\tsizeof(btDbvtVolume): %u bytes\r\n",sizeof(btDbvtVolume));
-printf("\tsizeof(btDbvtNode): %u bytes\r\n",sizeof(btDbvtNode));
-if(cfgBenchmark1_Enable)
- {// Benchmark 1
- srand(380843);
- btAlignedObjectArray<btDbvtVolume> volumes;
- btAlignedObjectArray<bool> results;
- volumes.resize(cfgLeaves);
- results.resize(cfgLeaves);
- for(int i=0;i<cfgLeaves;++i)
- {
- volumes[i]=btDbvtBenchmark::RandVolume(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale);
- }
- printf("[1] btDbvtVolume intersections: ");
- wallclock.reset();
- for(int i=0;i<cfgBenchmark1_Iterations;++i)
- {
- for(int j=0;j<cfgLeaves;++j)
- {
- for(int k=0;k<cfgLeaves;++k)
- {
- results[k]=Intersect(volumes[j],volumes[k]);
- }
- }
- }
- const int time=(int)wallclock.getTimeMilliseconds();
- printf("%u ms (%i%%)\r\n",time,(time-cfgBenchmark1_Reference)*100/time);
- }
-if(cfgBenchmark2_Enable)
- {// Benchmark 2
- srand(380843);
- btAlignedObjectArray<btDbvtVolume> volumes;
- btAlignedObjectArray<btDbvtVolume> results;
- volumes.resize(cfgLeaves);
- results.resize(cfgLeaves);
- for(int i=0;i<cfgLeaves;++i)
- {
- volumes[i]=btDbvtBenchmark::RandVolume(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale);
- }
- printf("[2] btDbvtVolume merges: ");
- wallclock.reset();
- for(int i=0;i<cfgBenchmark2_Iterations;++i)
- {
- for(int j=0;j<cfgLeaves;++j)
- {
- for(int k=0;k<cfgLeaves;++k)
- {
- Merge(volumes[j],volumes[k],results[k]);
- }
- }
- }
- const int time=(int)wallclock.getTimeMilliseconds();
- printf("%u ms (%i%%)\r\n",time,(time-cfgBenchmark2_Reference)*100/time);
- }
-if(cfgBenchmark3_Enable)
- {// Benchmark 3
- srand(380843);
- btDbvt dbvt[2];
- btDbvtBenchmark::NilPolicy policy;
- btDbvtBenchmark::RandTree(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale,cfgLeaves,dbvt[0]);
- btDbvtBenchmark::RandTree(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale,cfgLeaves,dbvt[1]);
- dbvt[0].optimizeTopDown();
- dbvt[1].optimizeTopDown();
- printf("[3] btDbvt::collideTT: ");
- wallclock.reset();
- for(int i=0;i<cfgBenchmark3_Iterations;++i)
- {
- btDbvt::collideTT(dbvt[0].m_root,dbvt[1].m_root,policy);
- }
- const int time=(int)wallclock.getTimeMilliseconds();
- printf("%u ms (%i%%)\r\n",time,(time-cfgBenchmark3_Reference)*100/time);
- }
-if(cfgBenchmark4_Enable)
- {// Benchmark 4
- srand(380843);
- btDbvt dbvt;
- btDbvtBenchmark::NilPolicy policy;
- btDbvtBenchmark::RandTree(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale,cfgLeaves,dbvt);
- dbvt.optimizeTopDown();
- printf("[4] btDbvt::collideTT self: ");
- wallclock.reset();
- for(int i=0;i<cfgBenchmark4_Iterations;++i)
- {
- btDbvt::collideTT(dbvt.m_root,dbvt.m_root,policy);
- }
- const int time=(int)wallclock.getTimeMilliseconds();
- printf("%u ms (%i%%)\r\n",time,(time-cfgBenchmark4_Reference)*100/time);
- }
-if(cfgBenchmark5_Enable)
- {// Benchmark 5
- srand(380843);
- btDbvt dbvt[2];
- btAlignedObjectArray<btTransform> transforms;
- btDbvtBenchmark::NilPolicy policy;
- transforms.resize(cfgBenchmark5_Iterations);
- for(int i=0;i<transforms.size();++i)
- {
- transforms[i]=btDbvtBenchmark::RandTransform(cfgVolumeCenterScale*cfgBenchmark5_OffsetScale);
- }
- btDbvtBenchmark::RandTree(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale,cfgLeaves,dbvt[0]);
- btDbvtBenchmark::RandTree(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale,cfgLeaves,dbvt[1]);
- dbvt[0].optimizeTopDown();
- dbvt[1].optimizeTopDown();
- printf("[5] btDbvt::collideTT xform: ");
- wallclock.reset();
- for(int i=0;i<cfgBenchmark5_Iterations;++i)
- {
- btDbvt::collideTT(dbvt[0].m_root,dbvt[1].m_root,transforms[i],policy);
- }
- const int time=(int)wallclock.getTimeMilliseconds();
- printf("%u ms (%i%%)\r\n",time,(time-cfgBenchmark5_Reference)*100/time);
- }
-if(cfgBenchmark6_Enable)
- {// Benchmark 6
- srand(380843);
- btDbvt dbvt;
- btAlignedObjectArray<btTransform> transforms;
- btDbvtBenchmark::NilPolicy policy;
- transforms.resize(cfgBenchmark6_Iterations);
- for(int i=0;i<transforms.size();++i)
- {
- transforms[i]=btDbvtBenchmark::RandTransform(cfgVolumeCenterScale*cfgBenchmark6_OffsetScale);
- }
- btDbvtBenchmark::RandTree(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale,cfgLeaves,dbvt);
- dbvt.optimizeTopDown();
- printf("[6] btDbvt::collideTT xform,self: ");
- wallclock.reset();
- for(int i=0;i<cfgBenchmark6_Iterations;++i)
- {
- btDbvt::collideTT(dbvt.m_root,dbvt.m_root,transforms[i],policy);
- }
- const int time=(int)wallclock.getTimeMilliseconds();
- printf("%u ms (%i%%)\r\n",time,(time-cfgBenchmark6_Reference)*100/time);
- }
-if(cfgBenchmark7_Enable)
- {// Benchmark 7
- srand(380843);
- btDbvt dbvt;
- btAlignedObjectArray<btVector3> rayorg;
- btAlignedObjectArray<btVector3> raydir;
- btDbvtBenchmark::NilPolicy policy;
- rayorg.resize(cfgBenchmark7_Iterations);
- raydir.resize(cfgBenchmark7_Iterations);
- for(int i=0;i<rayorg.size();++i)
- {
- rayorg[i]=btDbvtBenchmark::RandVector3(cfgVolumeCenterScale*2);
- raydir[i]=btDbvtBenchmark::RandVector3(cfgVolumeCenterScale*2);
- }
- btDbvtBenchmark::RandTree(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale,cfgLeaves,dbvt);
- dbvt.optimizeTopDown();
- printf("[7] btDbvt::collideRAY: ");
- wallclock.reset();
- for(int i=0;i<cfgBenchmark7_Passes;++i)
- {
- for(int j=0;j<cfgBenchmark7_Iterations;++j)
- {
- btDbvt::collideRAY(dbvt.m_root,rayorg[j],raydir[j],policy);
- }
- }
- const int time=(int)wallclock.getTimeMilliseconds();
- unsigned rays=cfgBenchmark7_Passes*cfgBenchmark7_Iterations;
- printf("%u ms (%i%%),(%u r/s)\r\n",time,(time-cfgBenchmark7_Reference)*100/time,(rays*1000)/time);
- }
-if(cfgBenchmark8_Enable)
- {// Benchmark 8
- srand(380843);
- btDbvt dbvt;
- btDbvtBenchmark::RandTree(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale,cfgLeaves,dbvt);
- dbvt.optimizeTopDown();
- printf("[8] insert/remove: ");
- wallclock.reset();
- for(int i=0;i<cfgBenchmark8_Passes;++i)
- {
- for(int j=0;j<cfgBenchmark8_Iterations;++j)
- {
- dbvt.remove(dbvt.insert(btDbvtBenchmark::RandVolume(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale),0));
- }
- }
- const int time=(int)wallclock.getTimeMilliseconds();
- const int ir=cfgBenchmark8_Passes*cfgBenchmark8_Iterations;
- printf("%u ms (%i%%),(%u ir/s)\r\n",time,(time-cfgBenchmark8_Reference)*100/time,ir*1000/time);
- }
-if(cfgBenchmark9_Enable)
- {// Benchmark 9
- srand(380843);
- btDbvt dbvt;
- btAlignedObjectArray<const btDbvtNode*> leaves;
- btDbvtBenchmark::RandTree(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale,cfgLeaves,dbvt);
- dbvt.optimizeTopDown();
- dbvt.extractLeaves(dbvt.m_root,leaves);
- printf("[9] updates (teleport): ");
- wallclock.reset();
- for(int i=0;i<cfgBenchmark9_Passes;++i)
- {
- for(int j=0;j<cfgBenchmark9_Iterations;++j)
- {
- dbvt.update(const_cast<btDbvtNode*>(leaves[rand()%cfgLeaves]),
- btDbvtBenchmark::RandVolume(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale));
- }
- }
- const int time=(int)wallclock.getTimeMilliseconds();
- const int up=cfgBenchmark9_Passes*cfgBenchmark9_Iterations;
- printf("%u ms (%i%%),(%u u/s)\r\n",time,(time-cfgBenchmark9_Reference)*100/time,up*1000/time);
- }
-if(cfgBenchmark10_Enable)
- {// Benchmark 10
- srand(380843);
- btDbvt dbvt;
- btAlignedObjectArray<const btDbvtNode*> leaves;
- btAlignedObjectArray<btVector3> vectors;
- vectors.resize(cfgBenchmark10_Iterations);
- for(int i=0;i<vectors.size();++i)
- {
- vectors[i]=(btDbvtBenchmark::RandVector3()*2-btVector3(1,1,1))*cfgBenchmark10_Scale;
- }
- btDbvtBenchmark::RandTree(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale,cfgLeaves,dbvt);
- dbvt.optimizeTopDown();
- dbvt.extractLeaves(dbvt.m_root,leaves);
- printf("[10] updates (jitter): ");
- wallclock.reset();
-
- for(int i=0;i<cfgBenchmark10_Passes;++i)
- {
- for(int j=0;j<cfgBenchmark10_Iterations;++j)
- {
- const btVector3& d=vectors[j];
- btDbvtNode* l=const_cast<btDbvtNode*>(leaves[rand()%cfgLeaves]);
- btDbvtVolume v=btDbvtVolume::FromMM(l->volume.Mins()+d,l->volume.Maxs()+d);
- dbvt.update(l,v);
- }
- }
- const int time=(int)wallclock.getTimeMilliseconds();
- const int up=cfgBenchmark10_Passes*cfgBenchmark10_Iterations;
- printf("%u ms (%i%%),(%u u/s)\r\n",time,(time-cfgBenchmark10_Reference)*100/time,up*1000/time);
- }
-if(cfgBenchmark11_Enable)
- {// Benchmark 11
- srand(380843);
- btDbvt dbvt;
- btDbvtBenchmark::RandTree(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale,cfgLeaves,dbvt);
- dbvt.optimizeTopDown();
- printf("[11] optimize (incremental): ");
- wallclock.reset();
- for(int i=0;i<cfgBenchmark11_Passes;++i)
- {
- dbvt.optimizeIncremental(cfgBenchmark11_Iterations);
- }
- const int time=(int)wallclock.getTimeMilliseconds();
- const int op=cfgBenchmark11_Passes*cfgBenchmark11_Iterations;
- printf("%u ms (%i%%),(%u o/s)\r\n",time,(time-cfgBenchmark11_Reference)*100/time,op/time*1000);
- }
-if(cfgBenchmark12_Enable)
- {// Benchmark 12
- srand(380843);
- btAlignedObjectArray<btDbvtVolume> volumes;
- btAlignedObjectArray<bool> results;
- volumes.resize(cfgLeaves);
- results.resize(cfgLeaves);
- for(int i=0;i<cfgLeaves;++i)
- {
- volumes[i]=btDbvtBenchmark::RandVolume(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale);
- }
- printf("[12] btDbvtVolume notequal: ");
- wallclock.reset();
- for(int i=0;i<cfgBenchmark12_Iterations;++i)
- {
- for(int j=0;j<cfgLeaves;++j)
- {
- for(int k=0;k<cfgLeaves;++k)
- {
- results[k]=NotEqual(volumes[j],volumes[k]);
- }
- }
- }
- const int time=(int)wallclock.getTimeMilliseconds();
- printf("%u ms (%i%%)\r\n",time,(time-cfgBenchmark12_Reference)*100/time);
- }
-if(cfgBenchmark13_Enable)
- {// Benchmark 13
- srand(380843);
- btDbvt dbvt;
- btAlignedObjectArray<btVector3> vectors;
- btDbvtBenchmark::NilPolicy policy;
- vectors.resize(cfgBenchmark13_Iterations);
- for(int i=0;i<vectors.size();++i)
- {
- vectors[i]=(btDbvtBenchmark::RandVector3()*2-btVector3(1,1,1)).normalized();
- }
- btDbvtBenchmark::RandTree(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale,cfgLeaves,dbvt);
- dbvt.optimizeTopDown();
- printf("[13] culling(OCL+fullsort): ");
- wallclock.reset();
- for(int i=0;i<cfgBenchmark13_Iterations;++i)
- {
- static const btScalar offset=0;
- policy.m_depth=-SIMD_INFINITY;
- dbvt.collideOCL(dbvt.m_root,&vectors[i],&offset,vectors[i],1,policy);
- }
- const int time=(int)wallclock.getTimeMilliseconds();
- const int t=cfgBenchmark13_Iterations;
- printf("%u ms (%i%%),(%u t/s)\r\n",time,(time-cfgBenchmark13_Reference)*100/time,(t*1000)/time);
- }
-if(cfgBenchmark14_Enable)
- {// Benchmark 14
- srand(380843);
- btDbvt dbvt;
- btAlignedObjectArray<btVector3> vectors;
- btDbvtBenchmark::P14 policy;
- vectors.resize(cfgBenchmark14_Iterations);
- for(int i=0;i<vectors.size();++i)
- {
- vectors[i]=(btDbvtBenchmark::RandVector3()*2-btVector3(1,1,1)).normalized();
- }
- btDbvtBenchmark::RandTree(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale,cfgLeaves,dbvt);
- dbvt.optimizeTopDown();
- policy.m_nodes.reserve(cfgLeaves);
- printf("[14] culling(OCL+qsort): ");
- wallclock.reset();
- for(int i=0;i<cfgBenchmark14_Iterations;++i)
- {
- static const btScalar offset=0;
- policy.m_nodes.resize(0);
- dbvt.collideOCL(dbvt.m_root,&vectors[i],&offset,vectors[i],1,policy,false);
- policy.m_nodes.quickSort(btDbvtBenchmark::P14::sortfnc);
- }
- const int time=(int)wallclock.getTimeMilliseconds();
- const int t=cfgBenchmark14_Iterations;
- printf("%u ms (%i%%),(%u t/s)\r\n",time,(time-cfgBenchmark14_Reference)*100/time,(t*1000)/time);
- }
-if(cfgBenchmark15_Enable)
- {// Benchmark 15
- srand(380843);
- btDbvt dbvt;
- btAlignedObjectArray<btVector3> vectors;
- btDbvtBenchmark::P15 policy;
- vectors.resize(cfgBenchmark15_Iterations);
- for(int i=0;i<vectors.size();++i)
- {
- vectors[i]=(btDbvtBenchmark::RandVector3()*2-btVector3(1,1,1)).normalized();
- }
- btDbvtBenchmark::RandTree(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale,cfgLeaves,dbvt);
- dbvt.optimizeTopDown();
- policy.m_nodes.reserve(cfgLeaves);
- printf("[15] culling(KDOP+qsort): ");
- wallclock.reset();
- for(int i=0;i<cfgBenchmark15_Iterations;++i)
- {
- static const btScalar offset=0;
- policy.m_nodes.resize(0);
- policy.m_axis=vectors[i];
- dbvt.collideKDOP(dbvt.m_root,&vectors[i],&offset,1,policy);
- policy.m_nodes.quickSort(btDbvtBenchmark::P15::sortfnc);
- }
- const int time=(int)wallclock.getTimeMilliseconds();
- const int t=cfgBenchmark15_Iterations;
- printf("%u ms (%i%%),(%u t/s)\r\n",time,(time-cfgBenchmark15_Reference)*100/time,(t*1000)/time);
- }
-if(cfgBenchmark16_Enable)
- {// Benchmark 16
- srand(380843);
- btDbvt dbvt;
- btAlignedObjectArray<btDbvtNode*> batch;
- btDbvtBenchmark::RandTree(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale,cfgLeaves,dbvt);
- dbvt.optimizeTopDown();
- batch.reserve(cfgBenchmark16_BatchCount);
- printf("[16] insert/remove batch(%u): ",cfgBenchmark16_BatchCount);
- wallclock.reset();
- for(int i=0;i<cfgBenchmark16_Passes;++i)
- {
- for(int j=0;j<cfgBenchmark16_BatchCount;++j)
- {
- batch.push_back(dbvt.insert(btDbvtBenchmark::RandVolume(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale),0));
- }
- for(int j=0;j<cfgBenchmark16_BatchCount;++j)
- {
- dbvt.remove(batch[j]);
- }
- batch.resize(0);
- }
- const int time=(int)wallclock.getTimeMilliseconds();
- const int ir=cfgBenchmark16_Passes*cfgBenchmark16_BatchCount;
- printf("%u ms (%i%%),(%u bir/s)\r\n",time,(time-cfgBenchmark16_Reference)*100/time,int(ir*1000.0/time));
- }
-if(cfgBenchmark17_Enable)
- {// Benchmark 17
- srand(380843);
- btAlignedObjectArray<btDbvtVolume> volumes;
- btAlignedObjectArray<int> results;
- btAlignedObjectArray<int> indices;
- volumes.resize(cfgLeaves);
- results.resize(cfgLeaves);
- indices.resize(cfgLeaves);
- for(int i=0;i<cfgLeaves;++i)
- {
- indices[i]=i;
- volumes[i]=btDbvtBenchmark::RandVolume(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale);
- }
- for(int i=0;i<cfgLeaves;++i)
- {
- btSwap(indices[i],indices[rand()%cfgLeaves]);
- }
- printf("[17] btDbvtVolume select: ");
- wallclock.reset();
- for(int i=0;i<cfgBenchmark17_Iterations;++i)
- {
- for(int j=0;j<cfgLeaves;++j)
- {
- for(int k=0;k<cfgLeaves;++k)
- {
- const int idx=indices[k];
- results[idx]=Select(volumes[idx],volumes[j],volumes[k]);
- }
- }
- }
- const int time=(int)wallclock.getTimeMilliseconds();
- printf("%u ms (%i%%)\r\n",time,(time-cfgBenchmark17_Reference)*100/time);
- }
-printf("\r\n\r\n");
-}
-#endif
diff --git a/extern/bullet2/src/BulletCollision/BroadphaseCollision/btDbvt.h b/extern/bullet2/src/BulletCollision/BroadphaseCollision/btDbvt.h
deleted file mode 100644
index 21d69acf151..00000000000
--- a/extern/bullet2/src/BulletCollision/BroadphaseCollision/btDbvt.h
+++ /dev/null
@@ -1,1112 +0,0 @@
-/*
-Bullet Continuous Collision Detection and Physics Library
-Copyright (c) 2003-2007 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.
-*/
-///btDbvt implementation by Nathanael Presson
-
-#ifndef BT_DYNAMIC_BOUNDING_VOLUME_TREE_H
-#define BT_DYNAMIC_BOUNDING_VOLUME_TREE_H
-
-#include "LinearMath/btAlignedObjectArray.h"
-#include "LinearMath/btVector3.h"
-#include "LinearMath/btTransform.h"
-
-//
-// Compile time configuration
-//
-
-
-// Implementation profiles
-#define DBVT_IMPL_GENERIC 0 // Generic implementation
-#define DBVT_IMPL_SSE 1 // SSE
-
-// Template implementation of ICollide
-#ifdef WIN32_AVOID_SSE_WHEN_EMBEDDED_INSIDE_BLENDER //there is always some weird compiler that breaks SSE builds
- #if (defined (_MSC_VER) && _MSC_VER >= 1400)
- #define DBVT_USE_TEMPLATE 1
- #else
- #define DBVT_USE_TEMPLATE 0
-#endif
-#else
-#define DBVT_USE_TEMPLATE 0
-#endif
-
-// Use only intrinsics instead of inline asm
-#define DBVT_USE_INTRINSIC_SSE 1
-
-// Using memmov for collideOCL
-#define DBVT_USE_MEMMOVE 1
-
-// Enable benchmarking code
-#define DBVT_ENABLE_BENCHMARK 0
-
-// Inlining
-#define DBVT_INLINE SIMD_FORCE_INLINE
-// Align
-#ifdef WIN32
-#define DBVT_ALIGN __declspec(align(16))
-#else
-#define DBVT_ALIGN
-#endif
-
-// Specific methods implementation
-
-#ifdef WIN32_AVOID_SSE_WHEN_EMBEDDED_INSIDE_BLENDER //there is always some weird compiler that breaks SSE builds
-#define DBVT_SELECT_IMPL DBVT_IMPL_SSE
-#define DBVT_MERGE_IMPL DBVT_IMPL_SSE
-#define DBVT_INT0_IMPL DBVT_IMPL_SSE
-#else
-#define DBVT_SELECT_IMPL DBVT_IMPL_GENERIC
-#define DBVT_MERGE_IMPL DBVT_IMPL_GENERIC
-#define DBVT_INT0_IMPL DBVT_IMPL_GENERIC
-#endif
-
-#if (DBVT_SELECT_IMPL==DBVT_IMPL_SSE)|| \
- (DBVT_MERGE_IMPL==DBVT_IMPL_SSE)|| \
- (DBVT_INT0_IMPL==DBVT_IMPL_SSE)
-#include <emmintrin.h>
-#endif
-
-//
-// Auto config and checks
-//
-
-#if DBVT_USE_TEMPLATE
-#define DBVT_VIRTUAL
-#define DBVT_VIRTUAL_DTOR(a)
-#define DBVT_PREFIX template <typename T>
-#define DBVT_IPOLICY T& policy
-#define DBVT_CHECKTYPE static const ICollide& typechecker=*(T*)0;
-#else
-#define DBVT_VIRTUAL_DTOR(a) virtual ~a() {}
-#define DBVT_VIRTUAL virtual
-#define DBVT_PREFIX
-#define DBVT_IPOLICY ICollide& policy
-#define DBVT_CHECKTYPE
-#endif
-
-#if DBVT_USE_MEMMOVE
-#ifndef __CELLOS_LV2__
-#include <memory.h>
-#endif
-#include <string.h>
-#endif
-
-#ifndef DBVT_USE_TEMPLATE
-#error "DBVT_USE_TEMPLATE undefined"
-#endif
-
-#ifndef DBVT_USE_MEMMOVE
-#error "DBVT_USE_MEMMOVE undefined"
-#endif
-
-#ifndef DBVT_ENABLE_BENCHMARK
-#error "DBVT_ENABLE_BENCHMARK undefined"
-#endif
-
-#ifndef DBVT_SELECT_IMPL
-#error "DBVT_SELECT_IMPL undefined"
-#endif
-
-#ifndef DBVT_MERGE_IMPL
-#error "DBVT_MERGE_IMPL undefined"
-#endif
-
-#ifndef DBVT_INT0_IMPL
-#error "DBVT_INT0_IMPL undefined"
-#endif
-
-//
-// Defaults volumes
-//
-
-/* btDbvtAabbMm */
-struct btDbvtAabbMm
-{
-DBVT_INLINE btVector3 Center() const { return((mi+mx)/2); }
-DBVT_INLINE btVector3 Lengths() const { return(mx-mi); }
-DBVT_INLINE btVector3 Extents() const { return((mx-mi)/2); }
-DBVT_INLINE const btVector3& Mins() const { return(mi); }
-DBVT_INLINE const btVector3& Maxs() const { return(mx); }
-static inline btDbvtAabbMm FromCE(const btVector3& c,const btVector3& e);
-static inline btDbvtAabbMm FromCR(const btVector3& c,btScalar r);
-static inline btDbvtAabbMm FromMM(const btVector3& mi,const btVector3& mx);
-static inline btDbvtAabbMm FromPoints(const btVector3* pts,int n);
-static inline btDbvtAabbMm FromPoints(const btVector3** ppts,int n);
-DBVT_INLINE void Expand(const btVector3& e);
-DBVT_INLINE void SignedExpand(const btVector3& e);
-DBVT_INLINE bool Contain(const btDbvtAabbMm& a) const;
-DBVT_INLINE int Classify(const btVector3& n,btScalar o,int s) const;
-DBVT_INLINE btScalar ProjectMinimum(const btVector3& v,unsigned signs) const;
-DBVT_INLINE friend bool Intersect( const btDbvtAabbMm& a,
- const btDbvtAabbMm& b);
-DBVT_INLINE friend bool Intersect( const btDbvtAabbMm& a,
- const btDbvtAabbMm& b,
- const btTransform& xform);
-DBVT_INLINE friend bool Intersect( const btDbvtAabbMm& a,
- const btVector3& b);
-DBVT_INLINE friend bool Intersect( const btDbvtAabbMm& a,
- const btVector3& org,
- const btVector3& invdir,
- const unsigned* signs);
-DBVT_INLINE friend btScalar Proximity( const btDbvtAabbMm& a,
- const btDbvtAabbMm& b);
-DBVT_INLINE friend int Select( const btDbvtAabbMm& o,
- const btDbvtAabbMm& a,
- const btDbvtAabbMm& b);
-DBVT_INLINE friend void Merge( const btDbvtAabbMm& a,
- const btDbvtAabbMm& b,
- btDbvtAabbMm& r);
-DBVT_INLINE friend bool NotEqual( const btDbvtAabbMm& a,
- const btDbvtAabbMm& b);
-private:
-DBVT_INLINE void AddSpan(const btVector3& d,btScalar& smi,btScalar& smx) const;
-private:
-btVector3 mi,mx;
-};
-
-// Types
-typedef btDbvtAabbMm btDbvtVolume;
-
-/* btDbvtNode */
-struct btDbvtNode
-{
- btDbvtVolume volume;
- btDbvtNode* parent;
- DBVT_INLINE bool isleaf() const { return(childs[1]==0); }
- DBVT_INLINE bool isinternal() const { return(!isleaf()); }
- union {
- btDbvtNode* childs[2];
- void* data;
- int dataAsInt;
- };
-};
-
-///The btDbvt class implements a fast dynamic bounding volume tree based on axis aligned bounding boxes (aabb tree).
-///This btDbvt is used for soft body collision detection and for the btDbvtBroadphase. It has a fast insert, remove and update of nodes.
-///Unlike the btQuantizedBvh, nodes can be dynamically moved around, which allows for change in topology of the underlying data structure.
-struct btDbvt
- {
- /* Stack element */
- struct sStkNN
- {
- const btDbvtNode* a;
- const btDbvtNode* b;
- sStkNN() {}
- sStkNN(const btDbvtNode* na,const btDbvtNode* nb) : a(na),b(nb) {}
- };
- struct sStkNP
- {
- const btDbvtNode* node;
- int mask;
- sStkNP(const btDbvtNode* n,unsigned m) : node(n),mask(m) {}
- };
- struct sStkNPS
- {
- const btDbvtNode* node;
- int mask;
- btScalar value;
- sStkNPS() {}
- sStkNPS(const btDbvtNode* n,unsigned m,btScalar v) : node(n),mask(m),value(v) {}
- };
- struct sStkCLN
- {
- const btDbvtNode* node;
- btDbvtNode* parent;
- sStkCLN(const btDbvtNode* n,btDbvtNode* p) : node(n),parent(p) {}
- };
- // Policies/Interfaces
-
- /* ICollide */
- struct ICollide
- {
- DBVT_VIRTUAL_DTOR(ICollide)
- DBVT_VIRTUAL void Process(const btDbvtNode*,const btDbvtNode*) {}
- DBVT_VIRTUAL void Process(const btDbvtNode*) {}
- DBVT_VIRTUAL void Process(const btDbvtNode* n,btScalar) { Process(n); }
- DBVT_VIRTUAL bool Descent(const btDbvtNode*) { return(true); }
- DBVT_VIRTUAL bool AllLeaves(const btDbvtNode*) { return(true); }
- };
- /* IWriter */
- struct IWriter
- {
- virtual ~IWriter() {}
- virtual void Prepare(const btDbvtNode* root,int numnodes)=0;
- virtual void WriteNode(const btDbvtNode*,int index,int parent,int child0,int child1)=0;
- virtual void WriteLeaf(const btDbvtNode*,int index,int parent)=0;
- };
- /* IClone */
- struct IClone
- {
- virtual ~IClone() {}
- virtual void CloneLeaf(btDbvtNode*) {}
- };
-
- // Constants
- enum {
- SIMPLE_STACKSIZE = 64,
- DOUBLE_STACKSIZE = SIMPLE_STACKSIZE*2
- };
-
- // Fields
- btDbvtNode* m_root;
- btDbvtNode* m_free;
- int m_lkhd;
- int m_leaves;
- unsigned m_opath;
- // Methods
- btDbvt();
- ~btDbvt();
- void clear();
- bool empty() const { return(0==m_root); }
- void optimizeBottomUp();
- void optimizeTopDown(int bu_treshold=128);
- void optimizeIncremental(int passes);
- btDbvtNode* insert(const btDbvtVolume& box,void* data);
- void update(btDbvtNode* leaf,int lookahead=-1);
- void update(btDbvtNode* leaf,const btDbvtVolume& volume);
- bool update(btDbvtNode* leaf,btDbvtVolume volume,const btVector3& velocity,btScalar margin);
- bool update(btDbvtNode* leaf,btDbvtVolume volume,const btVector3& velocity);
- bool update(btDbvtNode* leaf,btDbvtVolume volume,btScalar margin);
- void remove(btDbvtNode* leaf);
- void write(IWriter* iwriter) const;
- void clone(btDbvt& dest,IClone* iclone=0) const;
- static int maxdepth(const btDbvtNode* node);
- static int countLeaves(const btDbvtNode* node);
- static void extractLeaves(const btDbvtNode* node,btAlignedObjectArray<const btDbvtNode*>& leaves);
- #if DBVT_ENABLE_BENCHMARK
- static void benchmark();
- #else
- static void benchmark(){}
- #endif
- // DBVT_IPOLICY must support ICollide policy/interface
- DBVT_PREFIX
- static void enumNodes( const btDbvtNode* root,
- DBVT_IPOLICY);
- DBVT_PREFIX
- static void enumLeaves( const btDbvtNode* root,
- DBVT_IPOLICY);
- DBVT_PREFIX
- static void collideTT( const btDbvtNode* root0,
- const btDbvtNode* root1,
- DBVT_IPOLICY);
- DBVT_PREFIX
- static void collideTT( const btDbvtNode* root0,
- const btDbvtNode* root1,
- const btTransform& xform,
- DBVT_IPOLICY);
- DBVT_PREFIX
- static void collideTT( const btDbvtNode* root0,
- const btTransform& xform0,
- const btDbvtNode* root1,
- const btTransform& xform1,
- DBVT_IPOLICY);
- DBVT_PREFIX
- static void collideTV( const btDbvtNode* root,
- const btDbvtVolume& volume,
- DBVT_IPOLICY);
- DBVT_PREFIX
- static void collideRAY( const btDbvtNode* root,
- const btVector3& origin,
- const btVector3& direction,
- DBVT_IPOLICY);
- DBVT_PREFIX
- static void collideKDOP(const btDbvtNode* root,
- const btVector3* normals,
- const btScalar* offsets,
- int count,
- DBVT_IPOLICY);
- DBVT_PREFIX
- static void collideOCL( const btDbvtNode* root,
- const btVector3* normals,
- const btScalar* offsets,
- const btVector3& sortaxis,
- int count,
- DBVT_IPOLICY,
- bool fullsort=true);
- DBVT_PREFIX
- static void collideTU( const btDbvtNode* root,
- DBVT_IPOLICY);
- // Helpers
- static DBVT_INLINE int nearest(const int* i,const btDbvt::sStkNPS* a,btScalar v,int l,int h)
- {
- int m=0;
- while(l<h)
- {
- m=(l+h)>>1;
- if(a[i[m]].value>=v) l=m+1; else h=m;
- }
- return(h);
- }
- static DBVT_INLINE int allocate( btAlignedObjectArray<int>& ifree,
- btAlignedObjectArray<sStkNPS>& stock,
- const sStkNPS& value)
- {
- int i;
- if(ifree.size()>0)
- { i=ifree[ifree.size()-1];ifree.pop_back();stock[i]=value; }
- else
- { i=stock.size();stock.push_back(value); }
- return(i);
- }
- //
- private:
- btDbvt(const btDbvt&) {}
- };
-
-//
-// Inline's
-//
-
-//
-inline btDbvtAabbMm btDbvtAabbMm::FromCE(const btVector3& c,const btVector3& e)
-{
-btDbvtAabbMm box;
-box.mi=c-e;box.mx=c+e;
-return(box);
-}
-
-//
-inline btDbvtAabbMm btDbvtAabbMm::FromCR(const btVector3& c,btScalar r)
-{
-return(FromCE(c,btVector3(r,r,r)));
-}
-
-//
-inline btDbvtAabbMm btDbvtAabbMm::FromMM(const btVector3& mi,const btVector3& mx)
-{
-btDbvtAabbMm box;
-box.mi=mi;box.mx=mx;
-return(box);
-}
-
-//
-inline btDbvtAabbMm btDbvtAabbMm::FromPoints(const btVector3* pts,int n)
-{
-btDbvtAabbMm box;
-box.mi=box.mx=pts[0];
-for(int i=1;i<n;++i)
- {
- box.mi.setMin(pts[i]);
- box.mx.setMax(pts[i]);
- }
-return(box);
-}
-
-//
-inline btDbvtAabbMm btDbvtAabbMm::FromPoints(const btVector3** ppts,int n)
-{
-btDbvtAabbMm box;
-box.mi=box.mx=*ppts[0];
-for(int i=1;i<n;++i)
- {
- box.mi.setMin(*ppts[i]);
- box.mx.setMax(*ppts[i]);
- }
-return(box);
-}
-
-//
-DBVT_INLINE void btDbvtAabbMm::Expand(const btVector3& e)
-{
-mi-=e;mx+=e;
-}
-
-//
-DBVT_INLINE void btDbvtAabbMm::SignedExpand(const btVector3& e)
-{
-if(e.x()>0) mx.setX(mx.x()+e[0]); else mi.setX(mi.x()+e[0]);
-if(e.y()>0) mx.setY(mx.y()+e[1]); else mi.setY(mi.y()+e[1]);
-if(e.z()>0) mx.setZ(mx.z()+e[2]); else mi.setZ(mi.z()+e[2]);
-}
-
-//
-DBVT_INLINE bool btDbvtAabbMm::Contain(const btDbvtAabbMm& a) const
-{
-return( (mi.x()<=a.mi.x())&&
- (mi.y()<=a.mi.y())&&
- (mi.z()<=a.mi.z())&&
- (mx.x()>=a.mx.x())&&
- (mx.y()>=a.mx.y())&&
- (mx.z()>=a.mx.z()));
-}
-
-//
-DBVT_INLINE int btDbvtAabbMm::Classify(const btVector3& n,btScalar o,int s) const
-{
-btVector3 pi,px;
-switch(s)
- {
- case (0+0+0): px=btVector3(mi.x(),mi.y(),mi.z());
- pi=btVector3(mx.x(),mx.y(),mx.z());break;
- case (1+0+0): px=btVector3(mx.x(),mi.y(),mi.z());
- pi=btVector3(mi.x(),mx.y(),mx.z());break;
- case (0+2+0): px=btVector3(mi.x(),mx.y(),mi.z());
- pi=btVector3(mx.x(),mi.y(),mx.z());break;
- case (1+2+0): px=btVector3(mx.x(),mx.y(),mi.z());
- pi=btVector3(mi.x(),mi.y(),mx.z());break;
- case (0+0+4): px=btVector3(mi.x(),mi.y(),mx.z());
- pi=btVector3(mx.x(),mx.y(),mi.z());break;
- case (1+0+4): px=btVector3(mx.x(),mi.y(),mx.z());
- pi=btVector3(mi.x(),mx.y(),mi.z());break;
- case (0+2+4): px=btVector3(mi.x(),mx.y(),mx.z());
- pi=btVector3(mx.x(),mi.y(),mi.z());break;
- case (1+2+4): px=btVector3(mx.x(),mx.y(),mx.z());
- pi=btVector3(mi.x(),mi.y(),mi.z());break;
- }
-if((dot(n,px)+o)<0) return(-1);
-if((dot(n,pi)+o)>=0) return(+1);
-return(0);
-}
-
-//
-DBVT_INLINE btScalar btDbvtAabbMm::ProjectMinimum(const btVector3& v,unsigned signs) const
-{
-const btVector3* b[]={&mx,&mi};
-const btVector3 p( b[(signs>>0)&1]->x(),
- b[(signs>>1)&1]->y(),
- b[(signs>>2)&1]->z());
-return(dot(p,v));
-}
-
-//
-DBVT_INLINE void btDbvtAabbMm::AddSpan(const btVector3& d,btScalar& smi,btScalar& smx) const
-{
-for(int i=0;i<3;++i)
- {
- if(d[i]<0)
- { smi+=mx[i]*d[i];smx+=mi[i]*d[i]; }
- else
- { smi+=mi[i]*d[i];smx+=mx[i]*d[i]; }
- }
-}
-
-//
-DBVT_INLINE bool Intersect( const btDbvtAabbMm& a,
- const btDbvtAabbMm& b)
-{
-#if DBVT_INT0_IMPL == DBVT_IMPL_SSE
-const __m128 rt(_mm_or_ps( _mm_cmplt_ps(_mm_load_ps(b.mx),_mm_load_ps(a.mi)),
- _mm_cmplt_ps(_mm_load_ps(a.mx),_mm_load_ps(b.mi))));
-const __int32* pu((const __int32*)&rt);
-return((pu[0]|pu[1]|pu[2])==0);
-#else
-return( (a.mi.x()<=b.mx.x())&&
- (a.mx.x()>=b.mi.x())&&
- (a.mi.y()<=b.mx.y())&&
- (a.mx.y()>=b.mi.y())&&
- (a.mi.z()<=b.mx.z())&&
- (a.mx.z()>=b.mi.z()));
-#endif
-}
-
-//
-DBVT_INLINE bool Intersect( const btDbvtAabbMm& a,
- const btDbvtAabbMm& b,
- const btTransform& xform)
-{
-const btVector3 d0=xform*b.Center()-a.Center();
-const btVector3 d1=d0*xform.getBasis();
-btScalar s0[2]={0,0};
-btScalar s1[2]={dot(xform.getOrigin(),d0),s1[0]};
-a.AddSpan(d0,s0[0],s0[1]);
-b.AddSpan(d1,s1[0],s1[1]);
-if(s0[0]>(s1[1])) return(false);
-if(s0[1]<(s1[0])) return(false);
-return(true);
-}
-
-//
-DBVT_INLINE bool Intersect( const btDbvtAabbMm& a,
- const btVector3& b)
-{
-return( (b.x()>=a.mi.x())&&
- (b.y()>=a.mi.y())&&
- (b.z()>=a.mi.z())&&
- (b.x()<=a.mx.x())&&
- (b.y()<=a.mx.y())&&
- (b.z()<=a.mx.z()));
-}
-
-//
-DBVT_INLINE bool Intersect( const btDbvtAabbMm& a,
- const btVector3& org,
- const btVector3& invdir,
- const unsigned* signs)
-{
-#if 0
-const btVector3 b0((a.mi-org)*invdir);
-const btVector3 b1((a.mx-org)*invdir);
-const btVector3 tmin(btMin(b0[0],b1[0]),btMin(b0[1],b1[1]),btMin(b0[2],b1[2]));
-const btVector3 tmax(btMax(b0[0],b1[0]),btMax(b0[1],b1[1]),btMax(b0[2],b1[2]));
-const btScalar tin=btMax(tmin[0],btMax(tmin[1],tmin[2]));
-const btScalar tout=btMin(tmax[0],btMin(tmax[1],tmax[2]));
-return(tin<tout);
-#else
-const btVector3* bounds[2]={&a.mi,&a.mx};
-btScalar txmin=(bounds[ signs[0]]->x()-org[0])*invdir[0];
-btScalar txmax=(bounds[1-signs[0]]->x()-org[0])*invdir[0];
-const btScalar tymin=(bounds[ signs[1]]->y()-org[1])*invdir[1];
-const btScalar tymax=(bounds[1-signs[1]]->y()-org[1])*invdir[1];
-if((txmin>tymax)||(tymin>txmax)) return(false);
-if(tymin>txmin) txmin=tymin;
-if(tymax<txmax) txmax=tymax;
-const btScalar tzmin=(bounds[ signs[2]]->z()-org[2])*invdir[2];
-const btScalar tzmax=(bounds[1-signs[2]]->z()-org[2])*invdir[2];
-if((txmin>tzmax)||(tzmin>txmax)) return(false);
-if(tzmin>txmin) txmin=tzmin;
-if(tzmax<txmax) txmax=tzmax;
-return(txmax>0);
-#endif
-}
-
-//
-DBVT_INLINE btScalar Proximity( const btDbvtAabbMm& a,
- const btDbvtAabbMm& b)
-{
-const btVector3 d=(a.mi+a.mx)-(b.mi+b.mx);
-return(btFabs(d.x())+btFabs(d.y())+btFabs(d.z()));
-}
-
-//
-DBVT_INLINE int Select( const btDbvtAabbMm& o,
- const btDbvtAabbMm& a,
- const btDbvtAabbMm& b)
-{
-#if DBVT_SELECT_IMPL == DBVT_IMPL_SSE
-static DBVT_ALIGN const unsigned __int32 mask[]={0x7fffffff,0x7fffffff,0x7fffffff,0x7fffffff};
- // TODO: the intrinsic version is 11% slower
- #if DBVT_USE_INTRINSIC_SSE
- __m128 omi(_mm_load_ps(o.mi));
- omi=_mm_add_ps(omi,_mm_load_ps(o.mx));
- __m128 ami(_mm_load_ps(a.mi));
- ami=_mm_add_ps(ami,_mm_load_ps(a.mx));
- ami=_mm_sub_ps(ami,omi);
- ami=_mm_and_ps(ami,_mm_load_ps((const float*)mask));
- __m128 bmi(_mm_load_ps(b.mi));
- bmi=_mm_add_ps(bmi,_mm_load_ps(b.mx));
- bmi=_mm_sub_ps(bmi,omi);
- bmi=_mm_and_ps(bmi,_mm_load_ps((const float*)mask));
- __m128 t0(_mm_movehl_ps(ami,ami));
- ami=_mm_add_ps(ami,t0);
- ami=_mm_add_ss(ami,_mm_shuffle_ps(ami,ami,1));
- __m128 t1(_mm_movehl_ps(bmi,bmi));
- bmi=_mm_add_ps(bmi,t1);
- bmi=_mm_add_ss(bmi,_mm_shuffle_ps(bmi,bmi,1));
- return(_mm_cmple_ss(bmi,ami).m128_u32[0]&1);
- #else
- DBVT_ALIGN __int32 r[1];
- __asm
- {
- mov eax,o
- mov ecx,a
- mov edx,b
- movaps xmm0,[eax]
- movaps xmm5,mask
- addps xmm0,[eax+16]
- movaps xmm1,[ecx]
- movaps xmm2,[edx]
- addps xmm1,[ecx+16]
- addps xmm2,[edx+16]
- subps xmm1,xmm0
- subps xmm2,xmm0
- andps xmm1,xmm5
- andps xmm2,xmm5
- movhlps xmm3,xmm1
- movhlps xmm4,xmm2
- addps xmm1,xmm3
- addps xmm2,xmm4
- pshufd xmm3,xmm1,1
- pshufd xmm4,xmm2,1
- addss xmm1,xmm3
- addss xmm2,xmm4
- cmpless xmm2,xmm1
- movss r,xmm2
- }
- return(r[0]&1);
- #endif
-#else
-return(Proximity(o,a)<Proximity(o,b)?0:1);
-#endif
-}
-
-//
-DBVT_INLINE void Merge( const btDbvtAabbMm& a,
- const btDbvtAabbMm& b,
- btDbvtAabbMm& r)
-{
-#if DBVT_MERGE_IMPL==DBVT_IMPL_SSE
-__m128 ami(_mm_load_ps(a.mi));
-__m128 amx(_mm_load_ps(a.mx));
-__m128 bmi(_mm_load_ps(b.mi));
-__m128 bmx(_mm_load_ps(b.mx));
-ami=_mm_min_ps(ami,bmi);
-amx=_mm_max_ps(amx,bmx);
-_mm_store_ps(r.mi,ami);
-_mm_store_ps(r.mx,amx);
-#else
-for(int i=0;i<3;++i)
- {
- if(a.mi[i]<b.mi[i]) r.mi[i]=a.mi[i]; else r.mi[i]=b.mi[i];
- if(a.mx[i]>b.mx[i]) r.mx[i]=a.mx[i]; else r.mx[i]=b.mx[i];
- }
-#endif
-}
-
-//
-DBVT_INLINE bool NotEqual( const btDbvtAabbMm& a,
- const btDbvtAabbMm& b)
-{
-return( (a.mi.x()!=b.mi.x())||
- (a.mi.y()!=b.mi.y())||
- (a.mi.z()!=b.mi.z())||
- (a.mx.x()!=b.mx.x())||
- (a.mx.y()!=b.mx.y())||
- (a.mx.z()!=b.mx.z()));
-}
-
-//
-// Inline's
-//
-
-//
-DBVT_PREFIX
-inline void btDbvt::enumNodes( const btDbvtNode* root,
- DBVT_IPOLICY)
-{
-DBVT_CHECKTYPE
-policy.Process(root);
-if(root->isinternal())
- {
- enumNodes(root->childs[0],policy);
- enumNodes(root->childs[1],policy);
- }
-}
-
-//
-DBVT_PREFIX
-inline void btDbvt::enumLeaves( const btDbvtNode* root,
- DBVT_IPOLICY)
-{
-DBVT_CHECKTYPE
-if(root->isinternal())
- {
- enumLeaves(root->childs[0],policy);
- enumLeaves(root->childs[1],policy);
- }
- else
- {
- policy.Process(root);
- }
-}
-
-//
-DBVT_PREFIX
-inline void btDbvt::collideTT( const btDbvtNode* root0,
- const btDbvtNode* root1,
- DBVT_IPOLICY)
-{
-DBVT_CHECKTYPE
-if(root0&&root1)
- {
- btAlignedObjectArray<sStkNN> stack;
- int depth=1;
- int treshold=DOUBLE_STACKSIZE-4;
- stack.resize(DOUBLE_STACKSIZE);
- stack[0]=sStkNN(root0,root1);
- do {
- sStkNN p=stack[--depth];
- if(depth>treshold)
- {
- stack.resize(stack.size()*2);
- treshold=stack.size()-4;
- }
- if(p.a==p.b)
- {
- if(p.a->isinternal())
- {
- stack[depth++]=sStkNN(p.a->childs[0],p.a->childs[0]);
- stack[depth++]=sStkNN(p.a->childs[1],p.a->childs[1]);
- stack[depth++]=sStkNN(p.a->childs[0],p.a->childs[1]);
- }
- }
- else if(Intersect(p.a->volume,p.b->volume))
- {
- if(p.a->isinternal())
- {
- if(p.b->isinternal())
- {
- stack[depth++]=sStkNN(p.a->childs[0],p.b->childs[0]);
- stack[depth++]=sStkNN(p.a->childs[1],p.b->childs[0]);
- stack[depth++]=sStkNN(p.a->childs[0],p.b->childs[1]);
- stack[depth++]=sStkNN(p.a->childs[1],p.b->childs[1]);
- }
- else
- {
- stack[depth++]=sStkNN(p.a->childs[0],p.b);
- stack[depth++]=sStkNN(p.a->childs[1],p.b);
- }
- }
- else
- {
- if(p.b->isinternal())
- {
- stack[depth++]=sStkNN(p.a,p.b->childs[0]);
- stack[depth++]=sStkNN(p.a,p.b->childs[1]);
- }
- else
- {
- policy.Process(p.a,p.b);
- }
- }
- }
- } while(depth);
- }
-}
-
-//
-DBVT_PREFIX
-inline void btDbvt::collideTT( const btDbvtNode* root0,
- const btDbvtNode* root1,
- const btTransform& xform,
- DBVT_IPOLICY)
-{
-DBVT_CHECKTYPE
-if(root0&&root1)
- {
- btAlignedObjectArray<sStkNN> stack;
- int depth=1;
- int treshold=DOUBLE_STACKSIZE-4;
- stack.resize(DOUBLE_STACKSIZE);
- stack[0]=sStkNN(root0,root1);
- do {
- sStkNN p=stack[--depth];
- if(Intersect(p.a->volume,p.b->volume,xform))
- {
- if(depth>treshold)
- {
- stack.resize(stack.size()*2);
- treshold=stack.size()-4;
- }
- if(p.a->isinternal())
- {
- if(p.b->isinternal())
- {
- stack[depth++]=sStkNN(p.a->childs[0],p.b->childs[0]);
- stack[depth++]=sStkNN(p.a->childs[1],p.b->childs[0]);
- stack[depth++]=sStkNN(p.a->childs[0],p.b->childs[1]);
- stack[depth++]=sStkNN(p.a->childs[1],p.b->childs[1]);
- }
- else
- {
- stack[depth++]=sStkNN(p.a->childs[0],p.b);
- stack[depth++]=sStkNN(p.a->childs[1],p.b);
- }
- }
- else
- {
- if(p.b->isinternal())
- {
- stack[depth++]=sStkNN(p.a,p.b->childs[0]);
- stack[depth++]=sStkNN(p.a,p.b->childs[1]);
- }
- else
- {
- policy.Process(p.a,p.b);
- }
- }
- }
- } while(depth);
- }
-}
-
-//
-DBVT_PREFIX
-inline void btDbvt::collideTT( const btDbvtNode* root0,
- const btTransform& xform0,
- const btDbvtNode* root1,
- const btTransform& xform1,
- DBVT_IPOLICY)
-{
-const btTransform xform=xform0.inverse()*xform1;
-collideTT(root0,root1,xform,policy);
-}
-
-//
-DBVT_PREFIX
-inline void btDbvt::collideTV( const btDbvtNode* root,
- const btDbvtVolume& vol,
- DBVT_IPOLICY)
-{
-DBVT_CHECKTYPE
-if(root)
- {
- ATTRIBUTE_ALIGNED16(btDbvtVolume) volume(vol);
- btAlignedObjectArray<const btDbvtNode*> stack;
- stack.reserve(SIMPLE_STACKSIZE);
- stack.push_back(root);
- do {
- const btDbvtNode* n=stack[stack.size()-1];
- stack.pop_back();
- if(Intersect(n->volume,volume))
- {
- if(n->isinternal())
- {
- stack.push_back(n->childs[0]);
- stack.push_back(n->childs[1]);
- }
- else
- {
- policy.Process(n);
- }
- }
- } while(stack.size()>0);
- }
-}
-
-//
-DBVT_PREFIX
-inline void btDbvt::collideRAY( const btDbvtNode* root,
- const btVector3& origin,
- const btVector3& direction,
- DBVT_IPOLICY)
-{
-DBVT_CHECKTYPE
-if(root)
- {
- const btVector3 normal=direction.normalized();
- const btVector3 invdir( 1/normal.x(),
- 1/normal.y(),
- 1/normal.z());
- const unsigned signs[]={ direction.x()<0,
- direction.y()<0,
- direction.z()<0};
- btAlignedObjectArray<const btDbvtNode*> stack;
- stack.reserve(SIMPLE_STACKSIZE);
- stack.push_back(root);
- do {
- const btDbvtNode* node=stack[stack.size()-1];
- stack.pop_back();
- if(Intersect(node->volume,origin,invdir,signs))
- {
- if(node->isinternal())
- {
- stack.push_back(node->childs[0]);
- stack.push_back(node->childs[1]);
- }
- else
- {
- policy.Process(node);
- }
- }
- } while(stack.size());
- }
-}
-
-//
-DBVT_PREFIX
-inline void btDbvt::collideKDOP(const btDbvtNode* root,
- const btVector3* normals,
- const btScalar* offsets,
- int count,
- DBVT_IPOLICY)
-{
-DBVT_CHECKTYPE
-if(root)
- {
- const int inside=(1<<count)-1;
- btAlignedObjectArray<sStkNP> stack;
- int signs[sizeof(unsigned)*8];
- btAssert(count<int (sizeof(signs)/sizeof(signs[0])));
- for(int i=0;i<count;++i)
- {
- signs[i]= ((normals[i].x()>=0)?1:0)+
- ((normals[i].y()>=0)?2:0)+
- ((normals[i].z()>=0)?4:0);
- }
- stack.reserve(SIMPLE_STACKSIZE);
- stack.push_back(sStkNP(root,0));
- do {
- sStkNP se=stack[stack.size()-1];
- bool out=false;
- stack.pop_back();
- for(int i=0,j=1;(!out)&&(i<count);++i,j<<=1)
- {
- if(0==(se.mask&j))
- {
- const int side=se.node->volume.Classify(normals[i],offsets[i],signs[i]);
- switch(side)
- {
- case -1: out=true;break;
- case +1: se.mask|=j;break;
- }
- }
- }
- if(!out)
- {
- if((se.mask!=inside)&&(se.node->isinternal()))
- {
- stack.push_back(sStkNP(se.node->childs[0],se.mask));
- stack.push_back(sStkNP(se.node->childs[1],se.mask));
- }
- else
- {
- if(policy.AllLeaves(se.node)) enumLeaves(se.node,policy);
- }
- }
- } while(stack.size());
- }
-}
-
-//
-DBVT_PREFIX
-inline void btDbvt::collideOCL( const btDbvtNode* root,
- const btVector3* normals,
- const btScalar* offsets,
- const btVector3& sortaxis,
- int count,
- DBVT_IPOLICY,
- bool fsort)
-{
-DBVT_CHECKTYPE
-if(root)
- {
- const unsigned srtsgns=(sortaxis[0]>=0?1:0)+
- (sortaxis[1]>=0?2:0)+
- (sortaxis[2]>=0?4:0);
- const int inside=(1<<count)-1;
- btAlignedObjectArray<sStkNPS> stock;
- btAlignedObjectArray<int> ifree;
- btAlignedObjectArray<int> stack;
- int signs[sizeof(unsigned)*8];
- btAssert(count<int (sizeof(signs)/sizeof(signs[0])));
- for(int i=0;i<count;++i)
- {
- signs[i]= ((normals[i].x()>=0)?1:0)+
- ((normals[i].y()>=0)?2:0)+
- ((normals[i].z()>=0)?4:0);
- }
- stock.reserve(SIMPLE_STACKSIZE);
- stack.reserve(SIMPLE_STACKSIZE);
- ifree.reserve(SIMPLE_STACKSIZE);
- stack.push_back(allocate(ifree,stock,sStkNPS(root,0,root->volume.ProjectMinimum(sortaxis,srtsgns))));
- do {
- const int id=stack[stack.size()-1];
- sStkNPS se=stock[id];
- stack.pop_back();ifree.push_back(id);
- if(se.mask!=inside)
- {
- bool out=false;
- for(int i=0,j=1;(!out)&&(i<count);++i,j<<=1)
- {
- if(0==(se.mask&j))
- {
- const int side=se.node->volume.Classify(normals[i],offsets[i],signs[i]);
- switch(side)
- {
- case -1: out=true;break;
- case +1: se.mask|=j;break;
- }
- }
- }
- if(out) continue;
- }
- if(policy.Descent(se.node))
- {
- if(se.node->isinternal())
- {
- const btDbvtNode* pns[]={ se.node->childs[0],se.node->childs[1]};
- sStkNPS nes[]={ sStkNPS(pns[0],se.mask,pns[0]->volume.ProjectMinimum(sortaxis,srtsgns)),
- sStkNPS(pns[1],se.mask,pns[1]->volume.ProjectMinimum(sortaxis,srtsgns))};
- const int q=nes[0].value<nes[1].value?1:0;
- int j=stack.size();
- if(fsort&&(j>0))
- {
- /* Insert 0 */
- j=nearest(&stack[0],&stock[0],nes[q].value,0,stack.size());
- stack.push_back(0);
- #if DBVT_USE_MEMMOVE
- memmove(&stack[j+1],&stack[j],sizeof(int)*(stack.size()-j-1));
- #else
- for(int k=stack.size()-1;k>j;--k) stack[k]=stack[k-1];
- #endif
- stack[j]=allocate(ifree,stock,nes[q]);
- /* Insert 1 */
- j=nearest(&stack[0],&stock[0],nes[1-q].value,j,stack.size());
- stack.push_back(0);
- #if DBVT_USE_MEMMOVE
- memmove(&stack[j+1],&stack[j],sizeof(int)*(stack.size()-j-1));
- #else
- for(int k=stack.size()-1;k>j;--k) stack[k]=stack[k-1];
- #endif
- stack[j]=allocate(ifree,stock,nes[1-q]);
- }
- else
- {
- stack.push_back(allocate(ifree,stock,nes[q]));
- stack.push_back(allocate(ifree,stock,nes[1-q]));
- }
- }
- else
- {
- policy.Process(se.node,se.value);
- }
- }
- } while(stack.size());
- }
-}
-
-//
-DBVT_PREFIX
-inline void btDbvt::collideTU( const btDbvtNode* root,
- DBVT_IPOLICY)
-{
-DBVT_CHECKTYPE
-if(root)
- {
- btAlignedObjectArray<const btDbvtNode*> stack;
- stack.reserve(SIMPLE_STACKSIZE);
- stack.push_back(root);
- do {
- const btDbvtNode* n=stack[stack.size()-1];
- stack.pop_back();
- if(policy.Descent(n))
- {
- if(n->isinternal())
- { stack.push_back(n->childs[0]);stack.push_back(n->childs[1]); }
- else
- { policy.Process(n); }
- }
- } while(stack.size()>0);
- }
-}
-
-//
-// PP Cleanup
-//
-
-#undef DBVT_USE_MEMMOVE
-#undef DBVT_USE_TEMPLATE
-#undef DBVT_VIRTUAL_DTOR
-#undef DBVT_VIRTUAL
-#undef DBVT_PREFIX
-#undef DBVT_IPOLICY
-#undef DBVT_CHECKTYPE
-#undef DBVT_IMPL_GENERIC
-#undef DBVT_IMPL_SSE
-#undef DBVT_USE_INTRINSIC_SSE
-#undef DBVT_SELECT_IMPL
-#undef DBVT_MERGE_IMPL
-#undef DBVT_INT0_IMPL
-
-#endif
diff --git a/extern/bullet2/src/BulletCollision/BroadphaseCollision/btDbvtBroadphase.cpp b/extern/bullet2/src/BulletCollision/BroadphaseCollision/btDbvtBroadphase.cpp
deleted file mode 100644
index e00fc6aa5e3..00000000000
--- a/extern/bullet2/src/BulletCollision/BroadphaseCollision/btDbvtBroadphase.cpp
+++ /dev/null
@@ -1,548 +0,0 @@
-/*
-Bullet Continuous Collision Detection and Physics Library
-Copyright (c) 2003-2007 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.
-*/
-///btDbvtBroadphase implementation by Nathanael Presson
-
-#include "btDbvtBroadphase.h"
-
-//
-// Profiling
-//
-
-#if DBVT_BP_PROFILE||DBVT_BP_ENABLE_BENCHMARK
-#include <stdio.h>
-#endif
-
-#if DBVT_BP_PROFILE
-struct ProfileScope
- {
- __forceinline ProfileScope(btClock& clock,unsigned long& value) :
- m_clock(&clock),m_value(&value),m_base(clock.getTimeMicroseconds())
- {
- }
- __forceinline ~ProfileScope()
- {
- (*m_value)+=m_clock->getTimeMicroseconds()-m_base;
- }
- btClock* m_clock;
- unsigned long* m_value;
- unsigned long m_base;
- };
-#define SPC(_value_) ProfileScope spc_scope(m_clock,_value_)
-#else
-#define SPC(_value_)
-#endif
-
-//
-// Helpers
-//
-
-//
-template <typename T>
-static inline void listappend(T* item,T*& list)
-{
-item->links[0]=0;
-item->links[1]=list;
-if(list) list->links[0]=item;
-list=item;
-}
-
-//
-template <typename T>
-static inline void listremove(T* item,T*& list)
-{
-if(item->links[0]) item->links[0]->links[1]=item->links[1]; else list=item->links[1];
-if(item->links[1]) item->links[1]->links[0]=item->links[0];
-}
-
-//
-template <typename T>
-static inline int listcount(T* root)
-{
-int n=0;
-while(root) { ++n;root=root->links[1]; }
-return(n);
-}
-
-//
-template <typename T>
-static inline void clear(T& value)
-{
-static const struct ZeroDummy : T {} zerodummy;
-value=zerodummy;
-}
-
-//
-// Colliders
-//
-
-/* Tree collider */
-struct btDbvtTreeCollider : btDbvt::ICollide
-{
-btDbvtBroadphase* pbp;
-btDbvtProxy* proxy;
- btDbvtTreeCollider(btDbvtBroadphase* p) : pbp(p) {}
-void Process(const btDbvtNode* na,const btDbvtNode* nb)
- {
- if(na!=nb)
- {
- btDbvtProxy* pa=(btDbvtProxy*)na->data;
- btDbvtProxy* pb=(btDbvtProxy*)nb->data;
- #if DBVT_BP_SORTPAIRS
- if(pa>pb) btSwap(pa,pb);
- #endif
- pbp->m_paircache->addOverlappingPair(pa,pb);
- ++pbp->m_newpairs;
- }
- }
-void Process(const btDbvtNode* n)
- {
- Process(n,proxy->leaf);
- }
-};
-
-//
-// btDbvtBroadphase
-//
-
-//
-btDbvtBroadphase::btDbvtBroadphase(btOverlappingPairCache* paircache)
-{
-m_deferedcollide = false;
-m_needcleanup = true;
-m_releasepaircache = (paircache!=0)?false:true;
-m_prediction = 1/(btScalar)2;
-m_stageCurrent = 0;
-m_fixedleft = 0;
-m_fupdates = 1;
-m_dupdates = 0;
-m_cupdates = 10;
-m_newpairs = 1;
-m_updates_call = 0;
-m_updates_done = 0;
-m_updates_ratio = 0;
-m_paircache = paircache?
- paircache :
- new(btAlignedAlloc(sizeof(btHashedOverlappingPairCache),16)) btHashedOverlappingPairCache();
-m_gid = 0;
-m_pid = 0;
-m_cid = 0;
-for(int i=0;i<=STAGECOUNT;++i)
- {
- m_stageRoots[i]=0;
- }
-#if DBVT_BP_PROFILE
-clear(m_profiling);
-#endif
-}
-
-//
-btDbvtBroadphase::~btDbvtBroadphase()
-{
-if(m_releasepaircache)
-{
- m_paircache->~btOverlappingPairCache();
- btAlignedFree(m_paircache);
-}
-}
-
-//
-btBroadphaseProxy* btDbvtBroadphase::createProxy( const btVector3& aabbMin,
- const btVector3& aabbMax,
- int /*shapeType*/,
- void* userPtr,
- short int collisionFilterGroup,
- short int collisionFilterMask,
- btDispatcher* /*dispatcher*/,
- void* /*multiSapProxy*/)
-{
-btDbvtProxy* proxy=new(btAlignedAlloc(sizeof(btDbvtProxy),16)) btDbvtProxy( userPtr,
- collisionFilterGroup,
- collisionFilterMask);
-proxy->aabb = btDbvtVolume::FromMM(aabbMin,aabbMax);
-proxy->stage = m_stageCurrent;
-proxy->m_uniqueId = ++m_gid;
-proxy->leaf = m_sets[0].insert(proxy->aabb,proxy);
-listappend(proxy,m_stageRoots[m_stageCurrent]);
-if(!m_deferedcollide)
- {
- btDbvtTreeCollider collider(this);
- collider.proxy=proxy;
- btDbvt::collideTV(m_sets[0].m_root,proxy->aabb,collider);
- btDbvt::collideTV(m_sets[1].m_root,proxy->aabb,collider);
- }
-return(proxy);
-}
-
-//
-void btDbvtBroadphase::destroyProxy( btBroadphaseProxy* absproxy,
- btDispatcher* dispatcher)
-{
-btDbvtProxy* proxy=(btDbvtProxy*)absproxy;
-if(proxy->stage==STAGECOUNT)
- m_sets[1].remove(proxy->leaf);
- else
- m_sets[0].remove(proxy->leaf);
-listremove(proxy,m_stageRoots[proxy->stage]);
-m_paircache->removeOverlappingPairsContainingProxy(proxy,dispatcher);
-btAlignedFree(proxy);
-m_needcleanup=true;
-}
-
-//
-void btDbvtBroadphase::setAabb( btBroadphaseProxy* absproxy,
- const btVector3& aabbMin,
- const btVector3& aabbMax,
- btDispatcher* /*dispatcher*/)
-{
-btDbvtProxy* proxy=(btDbvtProxy*)absproxy;
-ATTRIBUTE_ALIGNED16(btDbvtVolume) aabb=btDbvtVolume::FromMM(aabbMin,aabbMax);
-#if DBVT_BP_PREVENTFALSEUPDATE
-if(NotEqual(aabb,proxy->leaf->volume))
-#endif
- {
- bool docollide=false;
- if(proxy->stage==STAGECOUNT)
- {/* fixed -> dynamic set */
- m_sets[1].remove(proxy->leaf);
- proxy->leaf=m_sets[0].insert(aabb,proxy);
- docollide=true;
- }
- else
- {/* dynamic set */
- ++m_updates_call;
- if(Intersect(proxy->leaf->volume,aabb))
- {/* Moving */
- const btVector3 delta=aabbMin-proxy->aabb.Mins();
- btVector3 velocity(aabb.Extents()*m_prediction);
- if(delta[0]<0) velocity[0]=-velocity[0];
- if(delta[1]<0) velocity[1]=-velocity[1];
- if(delta[2]<0) velocity[2]=-velocity[2];
- if (
- #ifdef DBVT_BP_MARGIN
- m_sets[0].update(proxy->leaf,aabb,velocity,DBVT_BP_MARGIN)
- #else
- m_sets[0].update(proxy->leaf,aabb,velocity)
- #endif
- )
- {
- ++m_updates_done;
- docollide=true;
- }
- }
- else
- {/* Teleporting */
- m_sets[0].update(proxy->leaf,aabb);
- ++m_updates_done;
- docollide=true;
- }
- }
- listremove(proxy,m_stageRoots[proxy->stage]);
- proxy->aabb = aabb;
- proxy->stage = m_stageCurrent;
- listappend(proxy,m_stageRoots[m_stageCurrent]);
- if(docollide)
- {
- m_needcleanup=true;
- if(!m_deferedcollide)
- {
- btDbvtTreeCollider collider(this);
- btDbvt::collideTT(m_sets[1].m_root,proxy->leaf,collider);
- btDbvt::collideTT(m_sets[0].m_root,proxy->leaf,collider);
- }
- }
- }
-}
-
-//
-void btDbvtBroadphase::calculateOverlappingPairs(btDispatcher* dispatcher)
-{
-collide(dispatcher);
-#if DBVT_BP_PROFILE
-if(0==(m_pid%DBVT_BP_PROFILING_RATE))
- {
- printf("fixed(%u) dynamics(%u) pairs(%u)\r\n",m_sets[1].m_leaves,m_sets[0].m_leaves,m_paircache->getNumOverlappingPairs());
- unsigned int total=m_profiling.m_total;
- if(total<=0) total=1;
- printf("ddcollide: %u%% (%uus)\r\n",(50+m_profiling.m_ddcollide*100)/total,m_profiling.m_ddcollide/DBVT_BP_PROFILING_RATE);
- printf("fdcollide: %u%% (%uus)\r\n",(50+m_profiling.m_fdcollide*100)/total,m_profiling.m_fdcollide/DBVT_BP_PROFILING_RATE);
- printf("cleanup: %u%% (%uus)\r\n",(50+m_profiling.m_cleanup*100)/total,m_profiling.m_cleanup/DBVT_BP_PROFILING_RATE);
- printf("total: %uus\r\n",total/DBVT_BP_PROFILING_RATE);
- const unsigned long sum=m_profiling.m_ddcollide+
- m_profiling.m_fdcollide+
- m_profiling.m_cleanup;
- printf("leaked: %u%% (%uus)\r\n",100-((50+sum*100)/total),(total-sum)/DBVT_BP_PROFILING_RATE);
- printf("job counts: %u%%\r\n",(m_profiling.m_jobcount*100)/((m_sets[0].m_leaves+m_sets[1].m_leaves)*DBVT_BP_PROFILING_RATE));
- clear(m_profiling);
- m_clock.reset();
- }
-#endif
-}
-
-//
-void btDbvtBroadphase::collide(btDispatcher* dispatcher)
-{
-SPC(m_profiling.m_total);
-/* optimize */
-m_sets[0].optimizeIncremental(1+(m_sets[0].m_leaves*m_dupdates)/100);
-if(m_fixedleft)
- {
- const int count=1+(m_sets[1].m_leaves*m_fupdates)/100;
- m_sets[1].optimizeIncremental(1+(m_sets[1].m_leaves*m_fupdates)/100);
- m_fixedleft=btMax<int>(0,m_fixedleft-count);
- }
-/* dynamic -> fixed set */
-m_stageCurrent=(m_stageCurrent+1)%STAGECOUNT;
-btDbvtProxy* current=m_stageRoots[m_stageCurrent];
-if(current)
- {
- btDbvtTreeCollider collider(this);
- do {
- btDbvtProxy* next=current->links[1];
- listremove(current,m_stageRoots[current->stage]);
- listappend(current,m_stageRoots[STAGECOUNT]);
- #if DBVT_BP_ACCURATESLEEPING
- m_paircache->removeOverlappingPairsContainingProxy(current,dispatcher);
- collider.proxy=current;
- btDbvt::collideTV(m_sets[0].m_root,current->aabb,collider);
- btDbvt::collideTV(m_sets[1].m_root,current->aabb,collider);
- #endif
- m_sets[0].remove(current->leaf);
- current->leaf = m_sets[1].insert(current->aabb,current);
- current->stage = STAGECOUNT;
- current = next;
- } while(current);
- m_fixedleft=m_sets[1].m_leaves;
- m_needcleanup=true;
- }
-/* collide dynamics */
- {
- btDbvtTreeCollider collider(this);
- if(m_deferedcollide)
- {
- SPC(m_profiling.m_fdcollide);
- btDbvt::collideTT(m_sets[0].m_root,m_sets[1].m_root,collider);
- }
- if(m_deferedcollide)
- {
- SPC(m_profiling.m_ddcollide);
- btDbvt::collideTT(m_sets[0].m_root,m_sets[0].m_root,collider);
- }
- }
-/* clean up */
-if(m_needcleanup)
- {
- SPC(m_profiling.m_cleanup);
- btBroadphasePairArray& pairs=m_paircache->getOverlappingPairArray();
- if(pairs.size()>0)
- {
- const int ci=pairs.size();
- int ni=btMin(ci,btMax<int>(m_newpairs,(ci*m_cupdates)/100));
- for(int i=0;i<ni;++i)
- {
- btBroadphasePair& p=pairs[(m_cid+i)%ci];
- btDbvtProxy* pa=(btDbvtProxy*)p.m_pProxy0;
- btDbvtProxy* pb=(btDbvtProxy*)p.m_pProxy1;
- if(!Intersect(pa->leaf->volume,pb->leaf->volume))
- {
- #if DBVT_BP_SORTPAIRS
- if(pa>pb) btSwap(pa,pb);
- #endif
- m_paircache->removeOverlappingPair(pa,pb,dispatcher);
- --ni;--i;
- }
- }
- if(pairs.size()>0) m_cid=(m_cid+ni)%pairs.size(); else m_cid=0;
- }
- }
-++m_pid;
-m_newpairs=1;
-m_needcleanup=false;
-if(m_updates_call>0)
- { m_updates_ratio=m_updates_done/(btScalar)m_updates_call; }
- else
- { m_updates_ratio=0; }
-m_updates_done/=2;
-m_updates_call/=2;
-}
-
-//
-void btDbvtBroadphase::optimize()
-{
-m_sets[0].optimizeTopDown();
-m_sets[1].optimizeTopDown();
-}
-
-//
-btOverlappingPairCache* btDbvtBroadphase::getOverlappingPairCache()
-{
-return(m_paircache);
-}
-
-//
-const btOverlappingPairCache* btDbvtBroadphase::getOverlappingPairCache() const
-{
-return(m_paircache);
-}
-
-//
-void btDbvtBroadphase::getBroadphaseAabb(btVector3& aabbMin,btVector3& aabbMax) const
-{
-
- ATTRIBUTE_ALIGNED16(btDbvtVolume) bounds;
-
-if(!m_sets[0].empty())
- if(!m_sets[1].empty()) Merge( m_sets[0].m_root->volume,
- m_sets[1].m_root->volume,bounds);
- else
- bounds=m_sets[0].m_root->volume;
-else if(!m_sets[1].empty()) bounds=m_sets[1].m_root->volume;
- else
- bounds=btDbvtVolume::FromCR(btVector3(0,0,0),0);
-aabbMin=bounds.Mins();
-aabbMax=bounds.Maxs();
-}
-
-//
-void btDbvtBroadphase::printStats()
-{}
-
-//
-#if DBVT_BP_ENABLE_BENCHMARK
-
-struct btBroadphaseBenchmark
- {
- struct Experiment
- {
- const char* name;
- int object_count;
- int update_count;
- int spawn_count;
- int iterations;
- btScalar speed;
- btScalar amplitude;
- };
- struct Object
- {
- btVector3 center;
- btVector3 extents;
- btBroadphaseProxy* proxy;
- btScalar time;
- void update(btScalar speed,btScalar amplitude,btBroadphaseInterface* pbi)
- {
- time += speed;
- center[0] = btCos(time*(btScalar)2.17)*amplitude+
- btSin(time)*amplitude/2;
- center[1] = btCos(time*(btScalar)1.38)*amplitude+
- btSin(time)*amplitude;
- center[2] = btSin(time*(btScalar)0.777)*amplitude;
- pbi->setAabb(proxy,center-extents,center+extents,0);
- }
- };
- static int UnsignedRand(int range=RAND_MAX-1) { return(rand()%(range+1)); }
- static btScalar UnitRand() { return(UnsignedRand(16384)/(btScalar)16384); }
- static void OutputTime(const char* name,btClock& c,unsigned count=0)
- {
- const unsigned long us=c.getTimeMicroseconds();
- const unsigned long ms=(us+500)/1000;
- const btScalar sec=us/(btScalar)(1000*1000);
- if(count>0)
- printf("%s : %u us (%u ms), %.2f/s\r\n",name,us,ms,count/sec);
- else
- printf("%s : %u us (%u ms)\r\n",name,us,ms);
- }
- };
-
-void btDbvtBroadphase::benchmark(btBroadphaseInterface* pbi)
-{
-static const btBroadphaseBenchmark::Experiment experiments[]=
- {
- {"1024o.10%",1024,10,0,8192,(btScalar)0.005,(btScalar)100},
- /*{"4096o.10%",4096,10,0,8192,(btScalar)0.005,(btScalar)100},
- {"8192o.10%",8192,10,0,8192,(btScalar)0.005,(btScalar)100},*/
- };
-static const int nexperiments=sizeof(experiments)/sizeof(experiments[0]);
-btAlignedObjectArray<btBroadphaseBenchmark::Object*> objects;
-btClock wallclock;
-/* Begin */
-for(int iexp=0;iexp<nexperiments;++iexp)
- {
- const btBroadphaseBenchmark::Experiment& experiment=experiments[iexp];
- const int object_count=experiment.object_count;
- const int update_count=(object_count*experiment.update_count)/100;
- const int spawn_count=(object_count*experiment.spawn_count)/100;
- const btScalar speed=experiment.speed;
- const btScalar amplitude=experiment.amplitude;
- printf("Experiment #%u '%s':\r\n",iexp,experiment.name);
- printf("\tObjects: %u\r\n",object_count);
- printf("\tUpdate: %u\r\n",update_count);
- printf("\tSpawn: %u\r\n",spawn_count);
- printf("\tSpeed: %f\r\n",speed);
- printf("\tAmplitude: %f\r\n",amplitude);
- srand(180673);
- /* Create objects */
- wallclock.reset();
- objects.reserve(object_count);
- for(int i=0;i<object_count;++i)
- {
- btBroadphaseBenchmark::Object* po=new btBroadphaseBenchmark::Object();
- po->center[0]=btBroadphaseBenchmark::UnitRand()*50;
- po->center[1]=btBroadphaseBenchmark::UnitRand()*50;
- po->center[2]=btBroadphaseBenchmark::UnitRand()*50;
- po->extents[0]=btBroadphaseBenchmark::UnitRand()*2+2;
- po->extents[1]=btBroadphaseBenchmark::UnitRand()*2+2;
- po->extents[2]=btBroadphaseBenchmark::UnitRand()*2+2;
- po->time=btBroadphaseBenchmark::UnitRand()*2000;
- po->proxy=pbi->createProxy(po->center-po->extents,po->center+po->extents,0,po,1,1,0,0);
- objects.push_back(po);
- }
- btBroadphaseBenchmark::OutputTime("\tInitialization",wallclock);
- /* First update */
- wallclock.reset();
- for(int i=0;i<objects.size();++i)
- {
- objects[i]->update(speed,amplitude,pbi);
- }
- btBroadphaseBenchmark::OutputTime("\tFirst update",wallclock);
- /* Updates */
- wallclock.reset();
- for(int i=0;i<experiment.iterations;++i)
- {
- for(int j=0;j<update_count;++j)
- {
- objects[j]->update(speed,amplitude,pbi);
- }
- pbi->calculateOverlappingPairs(0);
- }
- btBroadphaseBenchmark::OutputTime("\tUpdate",wallclock,experiment.iterations);
- /* Clean up */
- wallclock.reset();
- for(int i=0;i<objects.size();++i)
- {
- pbi->destroyProxy(objects[i]->proxy,0);
- delete objects[i];
- }
- objects.resize(0);
- btBroadphaseBenchmark::OutputTime("\tRelease",wallclock);
- }
-
-}
-#else
-void btDbvtBroadphase::benchmark(btBroadphaseInterface*)
-{}
-#endif
-
-#if DBVT_BP_PROFILE
-#undef SPC
-#endif
diff --git a/extern/bullet2/src/BulletCollision/BroadphaseCollision/btDbvtBroadphase.h b/extern/bullet2/src/BulletCollision/BroadphaseCollision/btDbvtBroadphase.h
deleted file mode 100644
index 1f16043a7a8..00000000000
--- a/extern/bullet2/src/BulletCollision/BroadphaseCollision/btDbvtBroadphase.h
+++ /dev/null
@@ -1,116 +0,0 @@
-/*
-Bullet Continuous Collision Detection and Physics Library
-Copyright (c) 2003-2007 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.
-*/
-///btDbvtBroadphase implementation by Nathanael Presson
-#ifndef BT_DBVT_BROADPHASE_H
-#define BT_DBVT_BROADPHASE_H
-
-#include "BulletCollision/BroadphaseCollision/btDbvt.h"
-#include "BulletCollision/BroadphaseCollision/btOverlappingPairCache.h"
-
-//
-// Compile time config
-//
-
-#define DBVT_BP_PROFILE 0
-#define DBVT_BP_SORTPAIRS 1
-#define DBVT_BP_PREVENTFALSEUPDATE 0
-#define DBVT_BP_ACCURATESLEEPING 0
-#define DBVT_BP_ENABLE_BENCHMARK 0
-#define DBVT_BP_MARGIN (btScalar)0.05
-
-#if DBVT_BP_PROFILE
- #define DBVT_BP_PROFILING_RATE 256
- #include "LinearMath/btQuickprof.h"
-#endif
-
-//
-// btDbvtProxy
-//
-struct btDbvtProxy : btBroadphaseProxy
-{
-/* Fields */
-btDbvtAabbMm aabb;
-btDbvtNode* leaf;
-btDbvtProxy* links[2];
-int stage;
-/* ctor */
-btDbvtProxy(void* userPtr,short int collisionFilterGroup, short int collisionFilterMask) :
- btBroadphaseProxy(userPtr,collisionFilterGroup,collisionFilterMask)
- {
- links[0]=links[1]=0;
- }
-};
-
-typedef btAlignedObjectArray<btDbvtProxy*> btDbvtProxyArray;
-
-///The btDbvtBroadphase implements a broadphase using two dynamic AABB bounding volume hierarchies/trees (see btDbvt).
-///One tree is used for static/non-moving objects, and another tree is used for dynamic objects. Objects can move from one tree to the other.
-///This is a very fast broadphase, especially for very dynamic worlds where many objects are moving. Its insert/add and remove of objects is generally faster than the sweep and prune broadphases btAxisSweep3 and bt32BitAxisSweep3.
-struct btDbvtBroadphase : btBroadphaseInterface
-{
-/* Config */
-enum {
- DYNAMIC_SET = 0, /* Dynamic set index */
- FIXED_SET = 1, /* Fixed set index */
- STAGECOUNT = 2 /* Number of stages */
- };
-/* Fields */
-btDbvt m_sets[2]; // Dbvt sets
-btDbvtProxy* m_stageRoots[STAGECOUNT+1]; // Stages list
-btOverlappingPairCache* m_paircache; // Pair cache
-btScalar m_prediction; // Velocity prediction
-int m_stageCurrent; // Current stage
-int m_fupdates; // % of fixed updates per frame
-int m_dupdates; // % of dynamic updates per frame
-int m_cupdates; // % of cleanup updates per frame
-int m_newpairs; // Number of pairs created
-int m_fixedleft; // Fixed optimization left
-unsigned m_updates_call; // Number of updates call
-unsigned m_updates_done; // Number of updates done
-btScalar m_updates_ratio; // m_updates_done/m_updates_call
-int m_pid; // Parse id
-int m_cid; // Cleanup index
-int m_gid; // Gen id
-bool m_releasepaircache; // Release pair cache on delete
-bool m_deferedcollide; // Defere dynamic/static collision to collide call
-bool m_needcleanup; // Need to run cleanup?
-#if DBVT_BP_PROFILE
-btClock m_clock;
-struct {
- unsigned long m_total;
- unsigned long m_ddcollide;
- unsigned long m_fdcollide;
- unsigned long m_cleanup;
- unsigned long m_jobcount;
- } m_profiling;
-#endif
-/* Methods */
-btDbvtBroadphase(btOverlappingPairCache* paircache=0);
-~btDbvtBroadphase();
-void collide(btDispatcher* dispatcher);
-void optimize();
-/* btBroadphaseInterface Implementation */
-btBroadphaseProxy* createProxy(const btVector3& aabbMin,const btVector3& aabbMax,int shapeType,void* userPtr,short int collisionFilterGroup,short int collisionFilterMask,btDispatcher* dispatcher,void* multiSapProxy);
-void destroyProxy(btBroadphaseProxy* proxy,btDispatcher* dispatcher);
-void setAabb(btBroadphaseProxy* proxy,const btVector3& aabbMin,const btVector3& aabbMax,btDispatcher* dispatcher);
-void calculateOverlappingPairs(btDispatcher* dispatcher);
-btOverlappingPairCache* getOverlappingPairCache();
-const btOverlappingPairCache* getOverlappingPairCache() const;
-void getBroadphaseAabb(btVector3& aabbMin,btVector3& aabbMax) const;
-void printStats();
-static void benchmark(btBroadphaseInterface*);
-};
-
-#endif
diff --git a/extern/bullet2/src/BulletCollision/BroadphaseCollision/btMultiSapBroadphase.cpp b/extern/bullet2/src/BulletCollision/BroadphaseCollision/btMultiSapBroadphase.cpp
deleted file mode 100644
index 3f866ab7c5f..00000000000
--- a/extern/bullet2/src/BulletCollision/BroadphaseCollision/btMultiSapBroadphase.cpp
+++ /dev/null
@@ -1,466 +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.
-*/
-
-#include "btMultiSapBroadphase.h"
-
-#include "btSimpleBroadphase.h"
-#include "LinearMath/btAabbUtil2.h"
-#include "btQuantizedBvh.h"
-
-/// btSapBroadphaseArray m_sapBroadphases;
-
-/// btOverlappingPairCache* m_overlappingPairs;
-extern int gOverlappingPairs;
-
-/*
-class btMultiSapSortedOverlappingPairCache : public btSortedOverlappingPairCache
-{
-public:
-
- virtual btBroadphasePair* addOverlappingPair(btBroadphaseProxy* proxy0,btBroadphaseProxy* proxy1)
- {
- return btSortedOverlappingPairCache::addOverlappingPair((btBroadphaseProxy*)proxy0->m_multiSapParentProxy,(btBroadphaseProxy*)proxy1->m_multiSapParentProxy);
- }
-};
-
-*/
-
-btMultiSapBroadphase::btMultiSapBroadphase(int /*maxProxies*/,btOverlappingPairCache* pairCache)
-:m_overlappingPairs(pairCache),
-m_optimizedAabbTree(0),
-m_ownsPairCache(false),
-m_invalidPair(0)
-{
- if (!m_overlappingPairs)
- {
- m_ownsPairCache = true;
- void* mem = btAlignedAlloc(sizeof(btSortedOverlappingPairCache),16);
- m_overlappingPairs = new (mem)btSortedOverlappingPairCache();
- }
-
- struct btMultiSapOverlapFilterCallback : public btOverlapFilterCallback
- {
- virtual ~btMultiSapOverlapFilterCallback()
- {}
- // return true when pairs need collision
- virtual bool needBroadphaseCollision(btBroadphaseProxy* childProxy0,btBroadphaseProxy* childProxy1) const
- {
- btBroadphaseProxy* multiProxy0 = (btBroadphaseProxy*)childProxy0->m_multiSapParentProxy;
- btBroadphaseProxy* multiProxy1 = (btBroadphaseProxy*)childProxy1->m_multiSapParentProxy;
-
- bool collides = (multiProxy0->m_collisionFilterGroup & multiProxy1->m_collisionFilterMask) != 0;
- collides = collides && (multiProxy1->m_collisionFilterGroup & multiProxy0->m_collisionFilterMask);
-
- return collides;
- }
- };
-
- void* mem = btAlignedAlloc(sizeof(btMultiSapOverlapFilterCallback),16);
- m_filterCallback = new (mem)btMultiSapOverlapFilterCallback();
-
- m_overlappingPairs->setOverlapFilterCallback(m_filterCallback);
-// mem = btAlignedAlloc(sizeof(btSimpleBroadphase),16);
-// m_simpleBroadphase = new (mem) btSimpleBroadphase(maxProxies,m_overlappingPairs);
-}
-
-btMultiSapBroadphase::~btMultiSapBroadphase()
-{
- if (m_ownsPairCache)
- {
- m_overlappingPairs->~btOverlappingPairCache();
- btAlignedFree(m_overlappingPairs);
- }
-}
-
-
-void btMultiSapBroadphase::buildTree(const btVector3& bvhAabbMin,const btVector3& bvhAabbMax)
-{
- m_optimizedAabbTree = new btQuantizedBvh();
- m_optimizedAabbTree->setQuantizationValues(bvhAabbMin,bvhAabbMax);
- QuantizedNodeArray& nodes = m_optimizedAabbTree->getLeafNodeArray();
- for (int i=0;i<m_sapBroadphases.size();i++)
- {
- btQuantizedBvhNode node;
- btVector3 aabbMin,aabbMax;
- m_sapBroadphases[i]->getBroadphaseAabb(aabbMin,aabbMax);
- m_optimizedAabbTree->quantize(&node.m_quantizedAabbMin[0],aabbMin,0);
- m_optimizedAabbTree->quantize(&node.m_quantizedAabbMax[0],aabbMax,1);
- int partId = 0;
- node.m_escapeIndexOrTriangleIndex = (partId<<(31-MAX_NUM_PARTS_IN_BITS)) | i;
- nodes.push_back(node);
- }
- m_optimizedAabbTree->buildInternal();
-}
-
-btBroadphaseProxy* btMultiSapBroadphase::createProxy( const btVector3& aabbMin, const btVector3& aabbMax,int shapeType,void* userPtr, short int collisionFilterGroup,short int collisionFilterMask, btDispatcher* dispatcher,void* /*ignoreMe*/)
-{
- //void* ignoreMe -> we could think of recursive multi-sap, if someone is interested
-
- void* mem = btAlignedAlloc(sizeof(btMultiSapProxy),16);
- btMultiSapProxy* proxy = new (mem)btMultiSapProxy(aabbMin, aabbMax,shapeType,userPtr, collisionFilterGroup,collisionFilterMask);
- m_multiSapProxies.push_back(proxy);
-
- ///this should deal with inserting/removal into child broadphases
- setAabb(proxy,aabbMin,aabbMax,dispatcher);
- return proxy;
-}
-
-void btMultiSapBroadphase::destroyProxy(btBroadphaseProxy* /*proxy*/,btDispatcher* /*dispatcher*/)
-{
- ///not yet
- btAssert(0);
-
-}
-
-
-void btMultiSapBroadphase::addToChildBroadphase(btMultiSapProxy* parentMultiSapProxy, btBroadphaseProxy* childProxy, btBroadphaseInterface* childBroadphase)
-{
- void* mem = btAlignedAlloc(sizeof(btBridgeProxy),16);
- btBridgeProxy* bridgeProxyRef = new(mem) btBridgeProxy;
- bridgeProxyRef->m_childProxy = childProxy;
- bridgeProxyRef->m_childBroadphase = childBroadphase;
- parentMultiSapProxy->m_bridgeProxies.push_back(bridgeProxyRef);
-}
-
-
-bool boxIsContainedWithinBox(const btVector3& amin,const btVector3& amax,const btVector3& bmin,const btVector3& bmax);
-bool boxIsContainedWithinBox(const btVector3& amin,const btVector3& amax,const btVector3& bmin,const btVector3& bmax)
-{
-return
-amin.getX() >= bmin.getX() && amax.getX() <= bmax.getX() &&
-amin.getY() >= bmin.getY() && amax.getY() <= bmax.getY() &&
-amin.getZ() >= bmin.getZ() && amax.getZ() <= bmax.getZ();
-}
-
-
-
-
-
-
-//#include <stdio.h>
-
-void btMultiSapBroadphase::setAabb(btBroadphaseProxy* proxy,const btVector3& aabbMin,const btVector3& aabbMax, btDispatcher* dispatcher)
-{
- btMultiSapProxy* multiProxy = static_cast<btMultiSapProxy*>(proxy);
- multiProxy->m_aabbMin = aabbMin;
- multiProxy->m_aabbMax = aabbMax;
-
-
-// bool fullyContained = false;
-// bool alreadyInSimple = false;
-
-
-
-
- struct MyNodeOverlapCallback : public btNodeOverlapCallback
- {
- btMultiSapBroadphase* m_multiSap;
- btMultiSapProxy* m_multiProxy;
- btDispatcher* m_dispatcher;
-
- MyNodeOverlapCallback(btMultiSapBroadphase* multiSap,btMultiSapProxy* multiProxy,btDispatcher* dispatcher)
- :m_multiSap(multiSap),
- m_multiProxy(multiProxy),
- m_dispatcher(dispatcher)
- {
-
- }
-
- virtual void processNode(int /*nodeSubPart*/, int broadphaseIndex)
- {
- btBroadphaseInterface* childBroadphase = m_multiSap->getBroadphaseArray()[broadphaseIndex];
-
- int containingBroadphaseIndex = -1;
- //already found?
- for (int i=0;i<m_multiProxy->m_bridgeProxies.size();i++)
- {
-
- if (m_multiProxy->m_bridgeProxies[i]->m_childBroadphase == childBroadphase)
- {
- containingBroadphaseIndex = i;
- break;
- }
- }
- if (containingBroadphaseIndex<0)
- {
- //add it
- btBroadphaseProxy* childProxy = childBroadphase->createProxy(m_multiProxy->m_aabbMin,m_multiProxy->m_aabbMax,m_multiProxy->m_shapeType,m_multiProxy->m_clientObject,m_multiProxy->m_collisionFilterGroup,m_multiProxy->m_collisionFilterMask, m_dispatcher,m_multiProxy);
- m_multiSap->addToChildBroadphase(m_multiProxy,childProxy,childBroadphase);
-
- }
- }
- };
-
- MyNodeOverlapCallback myNodeCallback(this,multiProxy,dispatcher);
-
-
-
-
- m_optimizedAabbTree->reportAabbOverlappingNodex(&myNodeCallback,aabbMin,aabbMax);
- int i;
-
- for ( i=0;i<multiProxy->m_bridgeProxies.size();i++)
- {
- btVector3 worldAabbMin,worldAabbMax;
- multiProxy->m_bridgeProxies[i]->m_childBroadphase->getBroadphaseAabb(worldAabbMin,worldAabbMax);
- bool overlapsBroadphase = TestAabbAgainstAabb2(worldAabbMin,worldAabbMax,multiProxy->m_aabbMin,multiProxy->m_aabbMax);
- if (!overlapsBroadphase)
- {
- //remove it now
- btBridgeProxy* bridgeProxy = multiProxy->m_bridgeProxies[i];
-
- btBroadphaseProxy* childProxy = bridgeProxy->m_childProxy;
- bridgeProxy->m_childBroadphase->destroyProxy(childProxy,dispatcher);
-
- multiProxy->m_bridgeProxies.swap( i,multiProxy->m_bridgeProxies.size()-1);
- multiProxy->m_bridgeProxies.pop_back();
-
- }
- }
-
-
- /*
-
- if (1)
- {
-
- //find broadphase that contain this multiProxy
- int numChildBroadphases = getBroadphaseArray().size();
- for (int i=0;i<numChildBroadphases;i++)
- {
- btBroadphaseInterface* childBroadphase = getBroadphaseArray()[i];
- btVector3 worldAabbMin,worldAabbMax;
- childBroadphase->getBroadphaseAabb(worldAabbMin,worldAabbMax);
- bool overlapsBroadphase = TestAabbAgainstAabb2(worldAabbMin,worldAabbMax,multiProxy->m_aabbMin,multiProxy->m_aabbMax);
-
- // fullyContained = fullyContained || boxIsContainedWithinBox(worldAabbMin,worldAabbMax,multiProxy->m_aabbMin,multiProxy->m_aabbMax);
- int containingBroadphaseIndex = -1;
-
- //if already contains this
-
- for (int i=0;i<multiProxy->m_bridgeProxies.size();i++)
- {
- if (multiProxy->m_bridgeProxies[i]->m_childBroadphase == childBroadphase)
- {
- containingBroadphaseIndex = i;
- }
- alreadyInSimple = alreadyInSimple || (multiProxy->m_bridgeProxies[i]->m_childBroadphase == m_simpleBroadphase);
- }
-
- if (overlapsBroadphase)
- {
- if (containingBroadphaseIndex<0)
- {
- btBroadphaseProxy* childProxy = childBroadphase->createProxy(aabbMin,aabbMax,multiProxy->m_shapeType,multiProxy->m_clientObject,multiProxy->m_collisionFilterGroup,multiProxy->m_collisionFilterMask, dispatcher);
- childProxy->m_multiSapParentProxy = multiProxy;
- addToChildBroadphase(multiProxy,childProxy,childBroadphase);
- }
- } else
- {
- if (containingBroadphaseIndex>=0)
- {
- //remove
- btBridgeProxy* bridgeProxy = multiProxy->m_bridgeProxies[containingBroadphaseIndex];
-
- btBroadphaseProxy* childProxy = bridgeProxy->m_childProxy;
- bridgeProxy->m_childBroadphase->destroyProxy(childProxy,dispatcher);
-
- multiProxy->m_bridgeProxies.swap( containingBroadphaseIndex,multiProxy->m_bridgeProxies.size()-1);
- multiProxy->m_bridgeProxies.pop_back();
- }
- }
- }
-
-
- ///If we are in no other child broadphase, stick the proxy in the global 'simple' broadphase (brute force)
- ///hopefully we don't end up with many entries here (can assert/provide feedback on stats)
- if (0)//!multiProxy->m_bridgeProxies.size())
- {
- ///we don't pass the userPtr but our multisap proxy. We need to patch this, before processing an actual collision
- ///this is needed to be able to calculate the aabb overlap
- btBroadphaseProxy* childProxy = m_simpleBroadphase->createProxy(aabbMin,aabbMax,multiProxy->m_shapeType,multiProxy->m_clientObject,multiProxy->m_collisionFilterGroup,multiProxy->m_collisionFilterMask, dispatcher);
- childProxy->m_multiSapParentProxy = multiProxy;
- addToChildBroadphase(multiProxy,childProxy,m_simpleBroadphase);
- }
- }
-
- if (!multiProxy->m_bridgeProxies.size())
- {
- ///we don't pass the userPtr but our multisap proxy. We need to patch this, before processing an actual collision
- ///this is needed to be able to calculate the aabb overlap
- btBroadphaseProxy* childProxy = m_simpleBroadphase->createProxy(aabbMin,aabbMax,multiProxy->m_shapeType,multiProxy->m_clientObject,multiProxy->m_collisionFilterGroup,multiProxy->m_collisionFilterMask, dispatcher);
- childProxy->m_multiSapParentProxy = multiProxy;
- addToChildBroadphase(multiProxy,childProxy,m_simpleBroadphase);
- }
-*/
-
-
- //update
- for ( i=0;i<multiProxy->m_bridgeProxies.size();i++)
- {
- btBridgeProxy* bridgeProxyRef = multiProxy->m_bridgeProxies[i];
- bridgeProxyRef->m_childBroadphase->setAabb(bridgeProxyRef->m_childProxy,aabbMin,aabbMax,dispatcher);
- }
-
-}
-bool stopUpdating=false;
-
-
-
-class btMultiSapBroadphasePairSortPredicate
-{
- public:
-
- bool operator() ( const btBroadphasePair& a1, const btBroadphasePair& b1 )
- {
- btMultiSapBroadphase::btMultiSapProxy* aProxy0 = a1.m_pProxy0 ? (btMultiSapBroadphase::btMultiSapProxy*)a1.m_pProxy0->m_multiSapParentProxy : 0;
- btMultiSapBroadphase::btMultiSapProxy* aProxy1 = a1.m_pProxy1 ? (btMultiSapBroadphase::btMultiSapProxy*)a1.m_pProxy1->m_multiSapParentProxy : 0;
- btMultiSapBroadphase::btMultiSapProxy* bProxy0 = b1.m_pProxy0 ? (btMultiSapBroadphase::btMultiSapProxy*)b1.m_pProxy0->m_multiSapParentProxy : 0;
- btMultiSapBroadphase::btMultiSapProxy* bProxy1 = b1.m_pProxy1 ? (btMultiSapBroadphase::btMultiSapProxy*)b1.m_pProxy1->m_multiSapParentProxy : 0;
-
- return aProxy0 > bProxy0 ||
- (aProxy0 == bProxy0 && aProxy1 > bProxy1) ||
- (aProxy0 == bProxy0 && aProxy1 == bProxy1 && a1.m_algorithm > b1.m_algorithm);
- }
-};
-
-
- ///calculateOverlappingPairs is optional: incremental algorithms (sweep and prune) might do it during the set aabb
-void btMultiSapBroadphase::calculateOverlappingPairs(btDispatcher* dispatcher)
-{
-
-// m_simpleBroadphase->calculateOverlappingPairs(dispatcher);
-
- if (!stopUpdating && getOverlappingPairCache()->hasDeferredRemoval())
- {
-
- btBroadphasePairArray& overlappingPairArray = getOverlappingPairCache()->getOverlappingPairArray();
-
- // quicksort(overlappingPairArray,0,overlappingPairArray.size());
-
- overlappingPairArray.quickSort(btMultiSapBroadphasePairSortPredicate());
-
- //perform a sort, to find duplicates and to sort 'invalid' pairs to the end
- // overlappingPairArray.heapSort(btMultiSapBroadphasePairSortPredicate());
-
- overlappingPairArray.resize(overlappingPairArray.size() - m_invalidPair);
- m_invalidPair = 0;
-
-
- int i;
-
- btBroadphasePair previousPair;
- previousPair.m_pProxy0 = 0;
- previousPair.m_pProxy1 = 0;
- previousPair.m_algorithm = 0;
-
-
- for (i=0;i<overlappingPairArray.size();i++)
- {
-
- btBroadphasePair& pair = overlappingPairArray[i];
-
- btMultiSapProxy* aProxy0 = pair.m_pProxy0 ? (btMultiSapProxy*)pair.m_pProxy0->m_multiSapParentProxy : 0;
- btMultiSapProxy* aProxy1 = pair.m_pProxy1 ? (btMultiSapProxy*)pair.m_pProxy1->m_multiSapParentProxy : 0;
- btMultiSapProxy* bProxy0 = previousPair.m_pProxy0 ? (btMultiSapProxy*)previousPair.m_pProxy0->m_multiSapParentProxy : 0;
- btMultiSapProxy* bProxy1 = previousPair.m_pProxy1 ? (btMultiSapProxy*)previousPair.m_pProxy1->m_multiSapParentProxy : 0;
-
- bool isDuplicate = (aProxy0 == bProxy0) && (aProxy1 == bProxy1);
-
- previousPair = pair;
-
- bool needsRemoval = false;
-
- if (!isDuplicate)
- {
- bool hasOverlap = testAabbOverlap(pair.m_pProxy0,pair.m_pProxy1);
-
- if (hasOverlap)
- {
- needsRemoval = false;//callback->processOverlap(pair);
- } else
- {
- needsRemoval = true;
- }
- } else
- {
- //remove duplicate
- needsRemoval = true;
- //should have no algorithm
- btAssert(!pair.m_algorithm);
- }
-
- if (needsRemoval)
- {
- getOverlappingPairCache()->cleanOverlappingPair(pair,dispatcher);
-
- // m_overlappingPairArray.swap(i,m_overlappingPairArray.size()-1);
- // m_overlappingPairArray.pop_back();
- pair.m_pProxy0 = 0;
- pair.m_pProxy1 = 0;
- m_invalidPair++;
- gOverlappingPairs--;
- }
-
- }
-
- ///if you don't like to skip the invalid pairs in the array, execute following code:
- #define CLEAN_INVALID_PAIRS 1
- #ifdef CLEAN_INVALID_PAIRS
-
- //perform a sort, to sort 'invalid' pairs to the end
- //overlappingPairArray.heapSort(btMultiSapBroadphasePairSortPredicate());
- overlappingPairArray.quickSort(btMultiSapBroadphasePairSortPredicate());
-
- overlappingPairArray.resize(overlappingPairArray.size() - m_invalidPair);
- m_invalidPair = 0;
- #endif//CLEAN_INVALID_PAIRS
-
- //printf("overlappingPairArray.size()=%d\n",overlappingPairArray.size());
- }
-
-
-}
-
-
-bool btMultiSapBroadphase::testAabbOverlap(btBroadphaseProxy* childProxy0,btBroadphaseProxy* childProxy1)
-{
- btMultiSapProxy* multiSapProxy0 = (btMultiSapProxy*)childProxy0->m_multiSapParentProxy;
- btMultiSapProxy* multiSapProxy1 = (btMultiSapProxy*)childProxy1->m_multiSapParentProxy;
-
- return TestAabbAgainstAabb2(multiSapProxy0->m_aabbMin,multiSapProxy0->m_aabbMax,
- multiSapProxy1->m_aabbMin,multiSapProxy1->m_aabbMax);
-
-}
-
-
-void btMultiSapBroadphase::printStats()
-{
-/* printf("---------------------------------\n");
-
- printf("btMultiSapBroadphase.h\n");
- printf("numHandles = %d\n",m_multiSapProxies.size());
- //find broadphase that contain this multiProxy
- int numChildBroadphases = getBroadphaseArray().size();
- for (int i=0;i<numChildBroadphases;i++)
- {
-
- btBroadphaseInterface* childBroadphase = getBroadphaseArray()[i];
- childBroadphase->printStats();
-
- }
- */
-
-}
diff --git a/extern/bullet2/src/BulletCollision/BroadphaseCollision/btMultiSapBroadphase.h b/extern/bullet2/src/BulletCollision/BroadphaseCollision/btMultiSapBroadphase.h
deleted file mode 100644
index a0c002de856..00000000000
--- a/extern/bullet2/src/BulletCollision/BroadphaseCollision/btMultiSapBroadphase.h
+++ /dev/null
@@ -1,144 +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.
-*/
-#ifndef BT_MULTI_SAP_BROADPHASE
-#define BT_MULTI_SAP_BROADPHASE
-
-#include "btBroadphaseInterface.h"
-#include "LinearMath/btAlignedObjectArray.h"
-#include "btOverlappingPairCache.h"
-
-
-class btBroadphaseInterface;
-class btSimpleBroadphase;
-
-
-typedef btAlignedObjectArray<btBroadphaseInterface*> btSapBroadphaseArray;
-
-///The btMultiSapBroadphase is a broadphase that contains multiple SAP broadphases.
-///The user can add SAP broadphases that cover the world. A btBroadphaseProxy can be in multiple child broadphases at the same time.
-///A btQuantizedBvh acceleration structures finds overlapping SAPs for each btBroadphaseProxy.
-///See http://www.continuousphysics.com/Bullet/phpBB2/viewtopic.php?t=328
-///and http://www.continuousphysics.com/Bullet/phpBB2/viewtopic.php?t=1329
-class btMultiSapBroadphase :public btBroadphaseInterface
-{
- btSapBroadphaseArray m_sapBroadphases;
-
- btSimpleBroadphase* m_simpleBroadphase;
-
- btOverlappingPairCache* m_overlappingPairs;
-
- class btQuantizedBvh* m_optimizedAabbTree;
-
-
- bool m_ownsPairCache;
-
- btOverlapFilterCallback* m_filterCallback;
-
- int m_invalidPair;
-
- struct btBridgeProxy
- {
- btBroadphaseProxy* m_childProxy;
- btBroadphaseInterface* m_childBroadphase;
- };
-
-
-public:
-
- struct btMultiSapProxy : public btBroadphaseProxy
- {
-
- ///array with all the entries that this proxy belongs to
- btAlignedObjectArray<btBridgeProxy*> m_bridgeProxies;
- btVector3 m_aabbMin;
- btVector3 m_aabbMax;
-
- int m_shapeType;
-
-/* void* m_userPtr;
- short int m_collisionFilterGroup;
- short int m_collisionFilterMask;
-*/
- btMultiSapProxy(const btVector3& aabbMin, const btVector3& aabbMax,int shapeType,void* userPtr, short int collisionFilterGroup,short int collisionFilterMask)
- :btBroadphaseProxy(userPtr,collisionFilterGroup,collisionFilterMask),
- m_aabbMin(aabbMin),
- m_aabbMax(aabbMax),
- m_shapeType(shapeType)
- {
- m_multiSapParentProxy =this;
- }
-
-
- };
-
-protected:
-
-
- btAlignedObjectArray<btMultiSapProxy*> m_multiSapProxies;
-
-public:
-
- btMultiSapBroadphase(int maxProxies = 16384,btOverlappingPairCache* pairCache=0);
-
-
- btSapBroadphaseArray& getBroadphaseArray()
- {
- return m_sapBroadphases;
- }
-
- const btSapBroadphaseArray& getBroadphaseArray() const
- {
- return m_sapBroadphases;
- }
-
- virtual ~btMultiSapBroadphase();
-
- virtual btBroadphaseProxy* createProxy( const btVector3& aabbMin, const btVector3& aabbMax,int shapeType,void* userPtr, short int collisionFilterGroup,short int collisionFilterMask, btDispatcher* dispatcher,void* multiSapProxy);
- virtual void destroyProxy(btBroadphaseProxy* proxy,btDispatcher* dispatcher);
- virtual void setAabb(btBroadphaseProxy* proxy,const btVector3& aabbMin,const btVector3& aabbMax, btDispatcher* dispatcher);
-
- void addToChildBroadphase(btMultiSapProxy* parentMultiSapProxy, btBroadphaseProxy* childProxy, btBroadphaseInterface* childBroadphase);
-
- ///calculateOverlappingPairs is optional: incremental algorithms (sweep and prune) might do it during the set aabb
- virtual void calculateOverlappingPairs(btDispatcher* dispatcher);
-
- bool testAabbOverlap(btBroadphaseProxy* proxy0,btBroadphaseProxy* proxy1);
-
- virtual btOverlappingPairCache* getOverlappingPairCache()
- {
- return m_overlappingPairs;
- }
- virtual const btOverlappingPairCache* getOverlappingPairCache() const
- {
- return m_overlappingPairs;
- }
-
- ///getAabb returns the axis aligned bounding box in the 'global' coordinate frame
- ///will add some transform later
- virtual void getBroadphaseAabb(btVector3& aabbMin,btVector3& aabbMax) const
- {
- aabbMin.setValue(-1e30f,-1e30f,-1e30f);
- aabbMax.setValue(1e30f,1e30f,1e30f);
- }
-
- void buildTree(const btVector3& bvhAabbMin,const btVector3& bvhAabbMax);
-
- virtual void printStats();
-
- void quicksort (btBroadphasePairArray& a, int lo, int hi);
-
-};
-
-#endif //BT_MULTI_SAP_BROADPHASE
diff --git a/extern/bullet2/src/BulletCollision/BroadphaseCollision/btOverlappingPairCallback.h b/extern/bullet2/src/BulletCollision/BroadphaseCollision/btOverlappingPairCallback.h
deleted file mode 100644
index 9c7b6f81367..00000000000
--- a/extern/bullet2/src/BulletCollision/BroadphaseCollision/btOverlappingPairCallback.h
+++ /dev/null
@@ -1,40 +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.
-*/
-
-#ifndef OVERLAPPING_PAIR_CALLBACK_H
-#define OVERLAPPING_PAIR_CALLBACK_H
-
-class btDispatcher;
-struct btBroadphasePair;
-
-///The btOverlappingPairCallback class is an additional optional broadphase user callback for adding/removing overlapping pairs, similar interface to btOverlappingPairCache.
-class btOverlappingPairCallback
-{
-public:
- virtual ~btOverlappingPairCallback()
- {
-
- }
-
- virtual btBroadphasePair* addOverlappingPair(btBroadphaseProxy* proxy0,btBroadphaseProxy* proxy1) = 0;
-
- virtual void* removeOverlappingPair(btBroadphaseProxy* proxy0,btBroadphaseProxy* proxy1,btDispatcher* dispatcher) = 0;
-
- virtual void removeOverlappingPairsContainingProxy(btBroadphaseProxy* proxy0,btDispatcher* dispatcher) = 0;
-
-};
-
-#endif //OVERLAPPING_PAIR_CALLBACK_H
diff --git a/extern/bullet2/src/BulletCollision/BroadphaseCollision/btQuantizedBvh.cpp b/extern/bullet2/src/BulletCollision/BroadphaseCollision/btQuantizedBvh.cpp
deleted file mode 100644
index a30bd1fd9e1..00000000000
--- a/extern/bullet2/src/BulletCollision/BroadphaseCollision/btQuantizedBvh.cpp
+++ /dev/null
@@ -1,1025 +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.
-*/
-
-#include "btQuantizedBvh.h"
-
-#include "LinearMath/btAabbUtil2.h"
-#include "LinearMath/btIDebugDraw.h"
-
-
-btQuantizedBvh::btQuantizedBvh() : m_useQuantization(false),
- //m_traversalMode(TRAVERSAL_STACKLESS_CACHE_FRIENDLY)
- m_traversalMode(TRAVERSAL_STACKLESS)
- //m_traversalMode(TRAVERSAL_RECURSIVE)
- ,m_subtreeHeaderCount(0) //PCK: add this line
-{
-
-}
-
-
-
-
-
-void btQuantizedBvh::buildInternal()
-{
- ///assumes that caller filled in the m_quantizedLeafNodes
- m_useQuantization = true;
- int numLeafNodes = 0;
-
- if (m_useQuantization)
- {
- //now we have an array of leafnodes in m_leafNodes
- numLeafNodes = m_quantizedLeafNodes.size();
-
- m_quantizedContiguousNodes.resize(2*numLeafNodes);
-
- }
-
- m_curNodeIndex = 0;
-
- buildTree(0,numLeafNodes);
-
- ///if the entire tree is small then subtree size, we need to create a header info for the tree
- if(m_useQuantization && !m_SubtreeHeaders.size())
- {
- btBvhSubtreeInfo& subtree = m_SubtreeHeaders.expand();
- subtree.setAabbFromQuantizeNode(m_quantizedContiguousNodes[0]);
- subtree.m_rootNodeIndex = 0;
- subtree.m_subtreeSize = m_quantizedContiguousNodes[0].isLeafNode() ? 1 : m_quantizedContiguousNodes[0].getEscapeIndex();
- }
-
- //PCK: update the copy of the size
- m_subtreeHeaderCount = m_SubtreeHeaders.size();
-
- //PCK: clear m_quantizedLeafNodes and m_leafNodes, they are temporary
- m_quantizedLeafNodes.clear();
- m_leafNodes.clear();
-}
-
-
-
-///just for debugging, to visualize the individual patches/subtrees
-#ifdef DEBUG_PATCH_COLORS
-btVector3 color[4]=
-{
- btVector3(255,0,0),
- btVector3(0,255,0),
- btVector3(0,0,255),
- btVector3(0,255,255)
-};
-#endif //DEBUG_PATCH_COLORS
-
-
-
-void btQuantizedBvh::setQuantizationValues(const btVector3& bvhAabbMin,const btVector3& bvhAabbMax,btScalar quantizationMargin)
-{
- //enlarge the AABB to avoid division by zero when initializing the quantization values
- btVector3 clampValue(quantizationMargin,quantizationMargin,quantizationMargin);
- m_bvhAabbMin = bvhAabbMin - clampValue;
- m_bvhAabbMax = bvhAabbMax + clampValue;
- btVector3 aabbSize = m_bvhAabbMax - m_bvhAabbMin;
- m_bvhQuantization = btVector3(btScalar(65533.0),btScalar(65533.0),btScalar(65533.0)) / aabbSize;
- m_useQuantization = true;
-}
-
-
-
-
-btQuantizedBvh::~btQuantizedBvh()
-{
-}
-
-#ifdef DEBUG_TREE_BUILDING
-int gStackDepth = 0;
-int gMaxStackDepth = 0;
-#endif //DEBUG_TREE_BUILDING
-
-void btQuantizedBvh::buildTree (int startIndex,int endIndex)
-{
-#ifdef DEBUG_TREE_BUILDING
- gStackDepth++;
- if (gStackDepth > gMaxStackDepth)
- gMaxStackDepth = gStackDepth;
-#endif //DEBUG_TREE_BUILDING
-
-
- int splitAxis, splitIndex, i;
- int numIndices =endIndex-startIndex;
- int curIndex = m_curNodeIndex;
-
- assert(numIndices>0);
-
- if (numIndices==1)
- {
-#ifdef DEBUG_TREE_BUILDING
- gStackDepth--;
-#endif //DEBUG_TREE_BUILDING
-
- assignInternalNodeFromLeafNode(m_curNodeIndex,startIndex);
-
- m_curNodeIndex++;
- return;
- }
- //calculate Best Splitting Axis and where to split it. Sort the incoming 'leafNodes' array within range 'startIndex/endIndex'.
-
- splitAxis = calcSplittingAxis(startIndex,endIndex);
-
- splitIndex = sortAndCalcSplittingIndex(startIndex,endIndex,splitAxis);
-
- int internalNodeIndex = m_curNodeIndex;
-
- setInternalNodeAabbMax(m_curNodeIndex,m_bvhAabbMin);
- setInternalNodeAabbMin(m_curNodeIndex,m_bvhAabbMax);
-
- for (i=startIndex;i<endIndex;i++)
- {
- mergeInternalNodeAabb(m_curNodeIndex,getAabbMin(i),getAabbMax(i));
- }
-
- m_curNodeIndex++;
-
-
- //internalNode->m_escapeIndex;
-
- int leftChildNodexIndex = m_curNodeIndex;
-
- //build left child tree
- buildTree(startIndex,splitIndex);
-
- int rightChildNodexIndex = m_curNodeIndex;
- //build right child tree
- buildTree(splitIndex,endIndex);
-
-#ifdef DEBUG_TREE_BUILDING
- gStackDepth--;
-#endif //DEBUG_TREE_BUILDING
-
- int escapeIndex = m_curNodeIndex - curIndex;
-
- if (m_useQuantization)
- {
- //escapeIndex is the number of nodes of this subtree
- const int sizeQuantizedNode =sizeof(btQuantizedBvhNode);
- const int treeSizeInBytes = escapeIndex * sizeQuantizedNode;
- if (treeSizeInBytes > MAX_SUBTREE_SIZE_IN_BYTES)
- {
- updateSubtreeHeaders(leftChildNodexIndex,rightChildNodexIndex);
- }
- }
-
- setInternalNodeEscapeIndex(internalNodeIndex,escapeIndex);
-
-}
-
-void btQuantizedBvh::updateSubtreeHeaders(int leftChildNodexIndex,int rightChildNodexIndex)
-{
- btAssert(m_useQuantization);
-
- btQuantizedBvhNode& leftChildNode = m_quantizedContiguousNodes[leftChildNodexIndex];
- int leftSubTreeSize = leftChildNode.isLeafNode() ? 1 : leftChildNode.getEscapeIndex();
- int leftSubTreeSizeInBytes = leftSubTreeSize * static_cast<int>(sizeof(btQuantizedBvhNode));
-
- btQuantizedBvhNode& rightChildNode = m_quantizedContiguousNodes[rightChildNodexIndex];
- int rightSubTreeSize = rightChildNode.isLeafNode() ? 1 : rightChildNode.getEscapeIndex();
- int rightSubTreeSizeInBytes = rightSubTreeSize * static_cast<int>(sizeof(btQuantizedBvhNode));
-
- if(leftSubTreeSizeInBytes <= MAX_SUBTREE_SIZE_IN_BYTES)
- {
- btBvhSubtreeInfo& subtree = m_SubtreeHeaders.expand();
- subtree.setAabbFromQuantizeNode(leftChildNode);
- subtree.m_rootNodeIndex = leftChildNodexIndex;
- subtree.m_subtreeSize = leftSubTreeSize;
- }
-
- if(rightSubTreeSizeInBytes <= MAX_SUBTREE_SIZE_IN_BYTES)
- {
- btBvhSubtreeInfo& subtree = m_SubtreeHeaders.expand();
- subtree.setAabbFromQuantizeNode(rightChildNode);
- subtree.m_rootNodeIndex = rightChildNodexIndex;
- subtree.m_subtreeSize = rightSubTreeSize;
- }
-
- //PCK: update the copy of the size
- m_subtreeHeaderCount = m_SubtreeHeaders.size();
-}
-
-
-int btQuantizedBvh::sortAndCalcSplittingIndex(int startIndex,int endIndex,int splitAxis)
-{
- int i;
- int splitIndex =startIndex;
- int numIndices = endIndex - startIndex;
- btScalar splitValue;
-
- btVector3 means(btScalar(0.),btScalar(0.),btScalar(0.));
- for (i=startIndex;i<endIndex;i++)
- {
- btVector3 center = btScalar(0.5)*(getAabbMax(i)+getAabbMin(i));
- means+=center;
- }
- means *= (btScalar(1.)/(btScalar)numIndices);
-
- splitValue = means[splitAxis];
-
- //sort leafNodes so all values larger then splitValue comes first, and smaller values start from 'splitIndex'.
- for (i=startIndex;i<endIndex;i++)
- {
- btVector3 center = btScalar(0.5)*(getAabbMax(i)+getAabbMin(i));
- if (center[splitAxis] > splitValue)
- {
- //swap
- swapLeafNodes(i,splitIndex);
- splitIndex++;
- }
- }
-
- //if the splitIndex causes unbalanced trees, fix this by using the center in between startIndex and endIndex
- //otherwise the tree-building might fail due to stack-overflows in certain cases.
- //unbalanced1 is unsafe: it can cause stack overflows
- //bool unbalanced1 = ((splitIndex==startIndex) || (splitIndex == (endIndex-1)));
-
- //unbalanced2 should work too: always use center (perfect balanced trees)
- //bool unbalanced2 = true;
-
- //this should be safe too:
- int rangeBalancedIndices = numIndices/3;
- bool unbalanced = ((splitIndex<=(startIndex+rangeBalancedIndices)) || (splitIndex >=(endIndex-1-rangeBalancedIndices)));
-
- if (unbalanced)
- {
- splitIndex = startIndex+ (numIndices>>1);
- }
-
- bool unbal = (splitIndex==startIndex) || (splitIndex == (endIndex));
- (void)unbal;
- btAssert(!unbal);
-
- return splitIndex;
-}
-
-
-int btQuantizedBvh::calcSplittingAxis(int startIndex,int endIndex)
-{
- int i;
-
- btVector3 means(btScalar(0.),btScalar(0.),btScalar(0.));
- btVector3 variance(btScalar(0.),btScalar(0.),btScalar(0.));
- int numIndices = endIndex-startIndex;
-
- for (i=startIndex;i<endIndex;i++)
- {
- btVector3 center = btScalar(0.5)*(getAabbMax(i)+getAabbMin(i));
- means+=center;
- }
- means *= (btScalar(1.)/(btScalar)numIndices);
-
- for (i=startIndex;i<endIndex;i++)
- {
- btVector3 center = btScalar(0.5)*(getAabbMax(i)+getAabbMin(i));
- btVector3 diff2 = center-means;
- diff2 = diff2 * diff2;
- variance += diff2;
- }
- variance *= (btScalar(1.)/ ((btScalar)numIndices-1) );
-
- return variance.maxAxis();
-}
-
-
-
-void btQuantizedBvh::reportAabbOverlappingNodex(btNodeOverlapCallback* nodeCallback,const btVector3& aabbMin,const btVector3& aabbMax) const
-{
- //either choose recursive traversal (walkTree) or stackless (walkStacklessTree)
-
- if (m_useQuantization)
- {
- ///quantize query AABB
- unsigned short int quantizedQueryAabbMin[3];
- unsigned short int quantizedQueryAabbMax[3];
- quantizeWithClamp(quantizedQueryAabbMin,aabbMin,0);
- quantizeWithClamp(quantizedQueryAabbMax,aabbMax,1);
-
- switch (m_traversalMode)
- {
- case TRAVERSAL_STACKLESS:
- walkStacklessQuantizedTree(nodeCallback,quantizedQueryAabbMin,quantizedQueryAabbMax,0,m_curNodeIndex);
- break;
- case TRAVERSAL_STACKLESS_CACHE_FRIENDLY:
- walkStacklessQuantizedTreeCacheFriendly(nodeCallback,quantizedQueryAabbMin,quantizedQueryAabbMax);
- break;
- case TRAVERSAL_RECURSIVE:
- {
- const btQuantizedBvhNode* rootNode = &m_quantizedContiguousNodes[0];
- walkRecursiveQuantizedTreeAgainstQueryAabb(rootNode,nodeCallback,quantizedQueryAabbMin,quantizedQueryAabbMax);
- }
- break;
- default:
- //unsupported
- btAssert(0);
- }
- } else
- {
- walkStacklessTree(nodeCallback,aabbMin,aabbMax);
- }
-}
-
-
-int maxIterations = 0;
-
-void btQuantizedBvh::walkStacklessTree(btNodeOverlapCallback* nodeCallback,const btVector3& aabbMin,const btVector3& aabbMax) const
-{
- btAssert(!m_useQuantization);
-
- const btOptimizedBvhNode* rootNode = &m_contiguousNodes[0];
- int escapeIndex, curIndex = 0;
- int walkIterations = 0;
- bool isLeafNode;
- //PCK: unsigned instead of bool
- unsigned aabbOverlap;
-
- while (curIndex < m_curNodeIndex)
- {
- //catch bugs in tree data
- assert (walkIterations < m_curNodeIndex);
-
- walkIterations++;
- aabbOverlap = TestAabbAgainstAabb2(aabbMin,aabbMax,rootNode->m_aabbMinOrg,rootNode->m_aabbMaxOrg);
- isLeafNode = rootNode->m_escapeIndex == -1;
-
- //PCK: unsigned instead of bool
- if (isLeafNode && (aabbOverlap != 0))
- {
- nodeCallback->processNode(rootNode->m_subPart,rootNode->m_triangleIndex);
- }
-
- //PCK: unsigned instead of bool
- if ((aabbOverlap != 0) || isLeafNode)
- {
- rootNode++;
- curIndex++;
- } else
- {
- escapeIndex = rootNode->m_escapeIndex;
- rootNode += escapeIndex;
- curIndex += escapeIndex;
- }
- }
- if (maxIterations < walkIterations)
- maxIterations = walkIterations;
-
-}
-
-/*
-///this was the original recursive traversal, before we optimized towards stackless traversal
-void btQuantizedBvh::walkTree(btOptimizedBvhNode* rootNode,btNodeOverlapCallback* nodeCallback,const btVector3& aabbMin,const btVector3& aabbMax) const
-{
- bool isLeafNode, aabbOverlap = TestAabbAgainstAabb2(aabbMin,aabbMax,rootNode->m_aabbMin,rootNode->m_aabbMax);
- if (aabbOverlap)
- {
- isLeafNode = (!rootNode->m_leftChild && !rootNode->m_rightChild);
- if (isLeafNode)
- {
- nodeCallback->processNode(rootNode);
- } else
- {
- walkTree(rootNode->m_leftChild,nodeCallback,aabbMin,aabbMax);
- walkTree(rootNode->m_rightChild,nodeCallback,aabbMin,aabbMax);
- }
- }
-
-}
-*/
-
-void btQuantizedBvh::walkRecursiveQuantizedTreeAgainstQueryAabb(const btQuantizedBvhNode* currentNode,btNodeOverlapCallback* nodeCallback,unsigned short int* quantizedQueryAabbMin,unsigned short int* quantizedQueryAabbMax) const
-{
- btAssert(m_useQuantization);
-
- bool isLeafNode;
- //PCK: unsigned instead of bool
- unsigned aabbOverlap;
-
- //PCK: unsigned instead of bool
- aabbOverlap = testQuantizedAabbAgainstQuantizedAabb(quantizedQueryAabbMin,quantizedQueryAabbMax,currentNode->m_quantizedAabbMin,currentNode->m_quantizedAabbMax);
- isLeafNode = currentNode->isLeafNode();
-
- //PCK: unsigned instead of bool
- if (aabbOverlap != 0)
- {
- if (isLeafNode)
- {
- nodeCallback->processNode(currentNode->getPartId(),currentNode->getTriangleIndex());
- } else
- {
- //process left and right children
- const btQuantizedBvhNode* leftChildNode = currentNode+1;
- walkRecursiveQuantizedTreeAgainstQueryAabb(leftChildNode,nodeCallback,quantizedQueryAabbMin,quantizedQueryAabbMax);
-
- const btQuantizedBvhNode* rightChildNode = leftChildNode->isLeafNode() ? leftChildNode+1:leftChildNode+leftChildNode->getEscapeIndex();
- walkRecursiveQuantizedTreeAgainstQueryAabb(rightChildNode,nodeCallback,quantizedQueryAabbMin,quantizedQueryAabbMax);
- }
- }
-}
-
-
-
-
-
-void btQuantizedBvh::walkStacklessQuantizedTreeAgainstRay(btNodeOverlapCallback* nodeCallback, const btVector3& raySource, const btVector3& rayTarget, const btVector3& aabbMin, const btVector3& aabbMax, int startNodeIndex,int endNodeIndex) const
-{
- btAssert(m_useQuantization);
-
- int curIndex = startNodeIndex;
- int walkIterations = 0;
- int subTreeSize = endNodeIndex - startNodeIndex;
- (void)subTreeSize;
-
- const btQuantizedBvhNode* rootNode = &m_quantizedContiguousNodes[startNodeIndex];
- int escapeIndex;
-
- bool isLeafNode;
- //PCK: unsigned instead of bool
- unsigned boxBoxOverlap = 0;
- unsigned rayBoxOverlap = 0;
-
- btScalar lambda_max = 1.0;
-#define RAYAABB2
-#ifdef RAYAABB2
- btVector3 rayFrom = raySource;
- btVector3 rayDirection = (rayTarget-raySource);
- rayDirection.normalize ();
- lambda_max = rayDirection.dot(rayTarget-raySource);
- ///what about division by zero? --> just set rayDirection[i] to 1.0
- rayDirection[0] = rayDirection[0] == btScalar(0.0) ? btScalar(1e30) : btScalar(1.0) / rayDirection[0];
- rayDirection[1] = rayDirection[1] == btScalar(0.0) ? btScalar(1e30) : btScalar(1.0) / rayDirection[1];
- rayDirection[2] = rayDirection[2] == btScalar(0.0) ? btScalar(1e30) : btScalar(1.0) / rayDirection[2];
- unsigned int sign[3] = { rayDirection[0] < 0.0, rayDirection[1] < 0.0, rayDirection[2] < 0.0};
-#endif
-
- /* Quick pruning by quantized box */
- btVector3 rayAabbMin = raySource;
- btVector3 rayAabbMax = raySource;
- rayAabbMin.setMin(rayTarget);
- rayAabbMax.setMax(rayTarget);
-
- /* Add box cast extents to bounding box */
- rayAabbMin += aabbMin;
- rayAabbMax += aabbMax;
-
- unsigned short int quantizedQueryAabbMin[3];
- unsigned short int quantizedQueryAabbMax[3];
- quantizeWithClamp(quantizedQueryAabbMin,rayAabbMin,0);
- quantizeWithClamp(quantizedQueryAabbMax,rayAabbMax,1);
-
- while (curIndex < endNodeIndex)
- {
-
-//#define VISUALLY_ANALYZE_BVH 1
-#ifdef VISUALLY_ANALYZE_BVH
- //some code snippet to debugDraw aabb, to visually analyze bvh structure
- static int drawPatch = 0;
- //need some global access to a debugDrawer
- extern btIDebugDraw* debugDrawerPtr;
- if (curIndex==drawPatch)
- {
- btVector3 aabbMin,aabbMax;
- aabbMin = unQuantize(rootNode->m_quantizedAabbMin);
- aabbMax = unQuantize(rootNode->m_quantizedAabbMax);
- btVector3 color(1,0,0);
- debugDrawerPtr->drawAabb(aabbMin,aabbMax,color);
- }
-#endif//VISUALLY_ANALYZE_BVH
-
- //catch bugs in tree data
- assert (walkIterations < subTreeSize);
-
- walkIterations++;
- //PCK: unsigned instead of bool
- // only interested if this is closer than any previous hit
- btScalar param = 1.0;
- rayBoxOverlap = 0;
- boxBoxOverlap = testQuantizedAabbAgainstQuantizedAabb(quantizedQueryAabbMin,quantizedQueryAabbMax,rootNode->m_quantizedAabbMin,rootNode->m_quantizedAabbMax);
- isLeafNode = rootNode->isLeafNode();
- if (boxBoxOverlap)
- {
- btVector3 bounds[2];
- bounds[0] = unQuantize(rootNode->m_quantizedAabbMin);
- bounds[1] = unQuantize(rootNode->m_quantizedAabbMax);
- /* Add box cast extents */
- bounds[0] += aabbMin;
- bounds[1] += aabbMax;
- btVector3 normal;
-#if 0
- bool ra2 = btRayAabb2 (raySource, rayDirection, sign, bounds, param, 0.0, lambda_max);
- bool ra = btRayAabb (raySource, rayTarget, bounds[0], bounds[1], param, normal);
- if (ra2 != ra)
- {
- printf("functions don't match\n");
- }
-#endif
-#ifdef RAYAABB2
- ///careful with this check: need to check division by zero (above) and fix the unQuantize method
- ///thanks Joerg/hiker for the reproduction case!
- ///http://www.bulletphysics.com/Bullet/phpBB3/viewtopic.php?f=9&t=1858
-
- rayBoxOverlap = btRayAabb2 (raySource, rayDirection, sign, bounds, param, 0.0f, lambda_max);
-#else
- rayBoxOverlap = true;//btRayAabb(raySource, rayTarget, bounds[0], bounds[1], param, normal);
-#endif
- }
-
- if (isLeafNode && rayBoxOverlap)
- {
- nodeCallback->processNode(rootNode->getPartId(),rootNode->getTriangleIndex());
- }
-
- //PCK: unsigned instead of bool
- if ((rayBoxOverlap != 0) || isLeafNode)
- {
- rootNode++;
- curIndex++;
- } else
- {
- escapeIndex = rootNode->getEscapeIndex();
- rootNode += escapeIndex;
- curIndex += escapeIndex;
- }
- }
- if (maxIterations < walkIterations)
- maxIterations = walkIterations;
-
-}
-
-void btQuantizedBvh::walkStacklessQuantizedTree(btNodeOverlapCallback* nodeCallback,unsigned short int* quantizedQueryAabbMin,unsigned short int* quantizedQueryAabbMax,int startNodeIndex,int endNodeIndex) const
-{
- btAssert(m_useQuantization);
-
- int curIndex = startNodeIndex;
- int walkIterations = 0;
- int subTreeSize = endNodeIndex - startNodeIndex;
- (void)subTreeSize;
-
- const btQuantizedBvhNode* rootNode = &m_quantizedContiguousNodes[startNodeIndex];
- int escapeIndex;
-
- bool isLeafNode;
- //PCK: unsigned instead of bool
- unsigned aabbOverlap;
-
- while (curIndex < endNodeIndex)
- {
-
-//#define VISUALLY_ANALYZE_BVH 1
-#ifdef VISUALLY_ANALYZE_BVH
- //some code snippet to debugDraw aabb, to visually analyze bvh structure
- static int drawPatch = 0;
- //need some global access to a debugDrawer
- extern btIDebugDraw* debugDrawerPtr;
- if (curIndex==drawPatch)
- {
- btVector3 aabbMin,aabbMax;
- aabbMin = unQuantize(rootNode->m_quantizedAabbMin);
- aabbMax = unQuantize(rootNode->m_quantizedAabbMax);
- btVector3 color(1,0,0);
- debugDrawerPtr->drawAabb(aabbMin,aabbMax,color);
- }
-#endif//VISUALLY_ANALYZE_BVH
-
- //catch bugs in tree data
- assert (walkIterations < subTreeSize);
-
- walkIterations++;
- //PCK: unsigned instead of bool
- aabbOverlap = testQuantizedAabbAgainstQuantizedAabb(quantizedQueryAabbMin,quantizedQueryAabbMax,rootNode->m_quantizedAabbMin,rootNode->m_quantizedAabbMax);
- isLeafNode = rootNode->isLeafNode();
-
- if (isLeafNode && aabbOverlap)
- {
- nodeCallback->processNode(rootNode->getPartId(),rootNode->getTriangleIndex());
- }
-
- //PCK: unsigned instead of bool
- if ((aabbOverlap != 0) || isLeafNode)
- {
- rootNode++;
- curIndex++;
- } else
- {
- escapeIndex = rootNode->getEscapeIndex();
- rootNode += escapeIndex;
- curIndex += escapeIndex;
- }
- }
- if (maxIterations < walkIterations)
- maxIterations = walkIterations;
-
-}
-
-//This traversal can be called from Playstation 3 SPU
-void btQuantizedBvh::walkStacklessQuantizedTreeCacheFriendly(btNodeOverlapCallback* nodeCallback,unsigned short int* quantizedQueryAabbMin,unsigned short int* quantizedQueryAabbMax) const
-{
- btAssert(m_useQuantization);
-
- int i;
-
-
- for (i=0;i<this->m_SubtreeHeaders.size();i++)
- {
- const btBvhSubtreeInfo& subtree = m_SubtreeHeaders[i];
-
- //PCK: unsigned instead of bool
- unsigned overlap = testQuantizedAabbAgainstQuantizedAabb(quantizedQueryAabbMin,quantizedQueryAabbMax,subtree.m_quantizedAabbMin,subtree.m_quantizedAabbMax);
- if (overlap != 0)
- {
- walkStacklessQuantizedTree(nodeCallback,quantizedQueryAabbMin,quantizedQueryAabbMax,
- subtree.m_rootNodeIndex,
- subtree.m_rootNodeIndex+subtree.m_subtreeSize);
- }
- }
-}
-
-
-void btQuantizedBvh::reportRayOverlappingNodex (btNodeOverlapCallback* nodeCallback, const btVector3& raySource, const btVector3& rayTarget) const
-{
- bool fast_path = m_useQuantization && m_traversalMode == TRAVERSAL_STACKLESS;
- if (fast_path)
- {
- walkStacklessQuantizedTreeAgainstRay(nodeCallback, raySource, rayTarget, btVector3(0, 0, 0), btVector3(0, 0, 0), 0, m_curNodeIndex);
- } else {
- /* Otherwise fallback to AABB overlap test */
- btVector3 aabbMin = raySource;
- btVector3 aabbMax = raySource;
- aabbMin.setMin(rayTarget);
- aabbMax.setMax(rayTarget);
- reportAabbOverlappingNodex(nodeCallback,aabbMin,aabbMax);
- }
-}
-
-
-void btQuantizedBvh::reportBoxCastOverlappingNodex(btNodeOverlapCallback* nodeCallback, const btVector3& raySource, const btVector3& rayTarget, const btVector3& aabbMin,const btVector3& aabbMax) const
-{
- bool fast_path = m_useQuantization && m_traversalMode == TRAVERSAL_STACKLESS;
- if (fast_path)
- {
- walkStacklessQuantizedTreeAgainstRay(nodeCallback, raySource, rayTarget, aabbMin, aabbMax, 0, m_curNodeIndex);
- } else {
- /* Slow path:
- Construct the bounding box for the entire box cast and send that down the tree */
- btVector3 qaabbMin = raySource;
- btVector3 qaabbMax = raySource;
- qaabbMin.setMin(rayTarget);
- qaabbMax.setMax(rayTarget);
- qaabbMin += aabbMin;
- qaabbMax += aabbMax;
- reportAabbOverlappingNodex(nodeCallback,qaabbMin,qaabbMax);
- }
-}
-
-
-void btQuantizedBvh::swapLeafNodes(int i,int splitIndex)
-{
- if (m_useQuantization)
- {
- btQuantizedBvhNode tmp = m_quantizedLeafNodes[i];
- m_quantizedLeafNodes[i] = m_quantizedLeafNodes[splitIndex];
- m_quantizedLeafNodes[splitIndex] = tmp;
- } else
- {
- btOptimizedBvhNode tmp = m_leafNodes[i];
- m_leafNodes[i] = m_leafNodes[splitIndex];
- m_leafNodes[splitIndex] = tmp;
- }
-}
-
-void btQuantizedBvh::assignInternalNodeFromLeafNode(int internalNode,int leafNodeIndex)
-{
- if (m_useQuantization)
- {
- m_quantizedContiguousNodes[internalNode] = m_quantizedLeafNodes[leafNodeIndex];
- } else
- {
- m_contiguousNodes[internalNode] = m_leafNodes[leafNodeIndex];
- }
-}
-
-//PCK: include
-#include <new>
-
-//PCK: consts
-static const unsigned BVH_ALIGNMENT = 16;
-static const unsigned BVH_ALIGNMENT_MASK = BVH_ALIGNMENT-1;
-
-static const unsigned BVH_ALIGNMENT_BLOCKS = 2;
-
-
-
-unsigned int btQuantizedBvh::getAlignmentSerializationPadding()
-{
- return BVH_ALIGNMENT_BLOCKS * BVH_ALIGNMENT;
-}
-
-unsigned btQuantizedBvh::calculateSerializeBufferSize()
-{
- unsigned baseSize = sizeof(btQuantizedBvh) + getAlignmentSerializationPadding();
- baseSize += sizeof(btBvhSubtreeInfo) * m_subtreeHeaderCount;
- if (m_useQuantization)
- {
- return baseSize + m_curNodeIndex * sizeof(btQuantizedBvhNode);
- }
- return baseSize + m_curNodeIndex * sizeof(btOptimizedBvhNode);
-}
-
-bool btQuantizedBvh::serialize(void *o_alignedDataBuffer, unsigned /*i_dataBufferSize */, bool i_swapEndian)
-{
- assert(m_subtreeHeaderCount == m_SubtreeHeaders.size());
- m_subtreeHeaderCount = m_SubtreeHeaders.size();
-
-/* if (i_dataBufferSize < calculateSerializeBufferSize() || o_alignedDataBuffer == NULL || (((unsigned)o_alignedDataBuffer & BVH_ALIGNMENT_MASK) != 0))
- {
- ///check alignedment for buffer?
- btAssert(0);
- return false;
- }
-*/
-
- btQuantizedBvh *targetBvh = (btQuantizedBvh *)o_alignedDataBuffer;
-
- // construct the class so the virtual function table, etc will be set up
- // Also, m_leafNodes and m_quantizedLeafNodes will be initialized to default values by the constructor
- new (targetBvh) btQuantizedBvh;
-
- if (i_swapEndian)
- {
- targetBvh->m_curNodeIndex = static_cast<int>(btSwapEndian(m_curNodeIndex));
-
-
- btSwapVector3Endian(m_bvhAabbMin,targetBvh->m_bvhAabbMin);
- btSwapVector3Endian(m_bvhAabbMax,targetBvh->m_bvhAabbMax);
- btSwapVector3Endian(m_bvhQuantization,targetBvh->m_bvhQuantization);
-
- targetBvh->m_traversalMode = (btTraversalMode)btSwapEndian(m_traversalMode);
- targetBvh->m_subtreeHeaderCount = static_cast<int>(btSwapEndian(m_subtreeHeaderCount));
- }
- else
- {
- targetBvh->m_curNodeIndex = m_curNodeIndex;
- targetBvh->m_bvhAabbMin = m_bvhAabbMin;
- targetBvh->m_bvhAabbMax = m_bvhAabbMax;
- targetBvh->m_bvhQuantization = m_bvhQuantization;
- targetBvh->m_traversalMode = m_traversalMode;
- targetBvh->m_subtreeHeaderCount = m_subtreeHeaderCount;
- }
-
- targetBvh->m_useQuantization = m_useQuantization;
-
- unsigned char *nodeData = (unsigned char *)targetBvh;
- nodeData += sizeof(btQuantizedBvh);
-
- unsigned sizeToAdd = 0;//(BVH_ALIGNMENT-((unsigned)nodeData & BVH_ALIGNMENT_MASK))&BVH_ALIGNMENT_MASK;
- nodeData += sizeToAdd;
-
- int nodeCount = m_curNodeIndex;
-
- if (m_useQuantization)
- {
- targetBvh->m_quantizedContiguousNodes.initializeFromBuffer(nodeData, nodeCount, nodeCount);
-
- if (i_swapEndian)
- {
- for (int nodeIndex = 0; nodeIndex < nodeCount; nodeIndex++)
- {
- targetBvh->m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMin[0] = btSwapEndian(m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMin[0]);
- targetBvh->m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMin[1] = btSwapEndian(m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMin[1]);
- targetBvh->m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMin[2] = btSwapEndian(m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMin[2]);
-
- targetBvh->m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMax[0] = btSwapEndian(m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMax[0]);
- targetBvh->m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMax[1] = btSwapEndian(m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMax[1]);
- targetBvh->m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMax[2] = btSwapEndian(m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMax[2]);
-
- targetBvh->m_quantizedContiguousNodes[nodeIndex].m_escapeIndexOrTriangleIndex = static_cast<int>(btSwapEndian(m_quantizedContiguousNodes[nodeIndex].m_escapeIndexOrTriangleIndex));
- }
- }
- else
- {
- for (int nodeIndex = 0; nodeIndex < nodeCount; nodeIndex++)
- {
-
- targetBvh->m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMin[0] = m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMin[0];
- targetBvh->m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMin[1] = m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMin[1];
- targetBvh->m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMin[2] = m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMin[2];
-
- targetBvh->m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMax[0] = m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMax[0];
- targetBvh->m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMax[1] = m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMax[1];
- targetBvh->m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMax[2] = m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMax[2];
-
- targetBvh->m_quantizedContiguousNodes[nodeIndex].m_escapeIndexOrTriangleIndex = m_quantizedContiguousNodes[nodeIndex].m_escapeIndexOrTriangleIndex;
-
-
- }
- }
- nodeData += sizeof(btQuantizedBvhNode) * nodeCount;
- }
- else
- {
- targetBvh->m_contiguousNodes.initializeFromBuffer(nodeData, nodeCount, nodeCount);
-
- if (i_swapEndian)
- {
- for (int nodeIndex = 0; nodeIndex < nodeCount; nodeIndex++)
- {
- btSwapVector3Endian(m_contiguousNodes[nodeIndex].m_aabbMinOrg, targetBvh->m_contiguousNodes[nodeIndex].m_aabbMinOrg);
- btSwapVector3Endian(m_contiguousNodes[nodeIndex].m_aabbMaxOrg, targetBvh->m_contiguousNodes[nodeIndex].m_aabbMaxOrg);
-
- targetBvh->m_contiguousNodes[nodeIndex].m_escapeIndex = static_cast<int>(btSwapEndian(m_contiguousNodes[nodeIndex].m_escapeIndex));
- targetBvh->m_contiguousNodes[nodeIndex].m_subPart = static_cast<int>(btSwapEndian(m_contiguousNodes[nodeIndex].m_subPart));
- targetBvh->m_contiguousNodes[nodeIndex].m_triangleIndex = static_cast<int>(btSwapEndian(m_contiguousNodes[nodeIndex].m_triangleIndex));
- }
- }
- else
- {
- for (int nodeIndex = 0; nodeIndex < nodeCount; nodeIndex++)
- {
- targetBvh->m_contiguousNodes[nodeIndex].m_aabbMinOrg = m_contiguousNodes[nodeIndex].m_aabbMinOrg;
- targetBvh->m_contiguousNodes[nodeIndex].m_aabbMaxOrg = m_contiguousNodes[nodeIndex].m_aabbMaxOrg;
-
- targetBvh->m_contiguousNodes[nodeIndex].m_escapeIndex = m_contiguousNodes[nodeIndex].m_escapeIndex;
- targetBvh->m_contiguousNodes[nodeIndex].m_subPart = m_contiguousNodes[nodeIndex].m_subPart;
- targetBvh->m_contiguousNodes[nodeIndex].m_triangleIndex = m_contiguousNodes[nodeIndex].m_triangleIndex;
- }
- }
- nodeData += sizeof(btOptimizedBvhNode) * nodeCount;
- }
-
- sizeToAdd = 0;//(BVH_ALIGNMENT-((unsigned)nodeData & BVH_ALIGNMENT_MASK))&BVH_ALIGNMENT_MASK;
- nodeData += sizeToAdd;
-
- // Now serialize the subtree headers
- targetBvh->m_SubtreeHeaders.initializeFromBuffer(nodeData, m_subtreeHeaderCount, m_subtreeHeaderCount);
- if (i_swapEndian)
- {
- for (int i = 0; i < m_subtreeHeaderCount; i++)
- {
- targetBvh->m_SubtreeHeaders[i].m_quantizedAabbMin[0] = btSwapEndian(m_SubtreeHeaders[i].m_quantizedAabbMin[0]);
- targetBvh->m_SubtreeHeaders[i].m_quantizedAabbMin[1] = btSwapEndian(m_SubtreeHeaders[i].m_quantizedAabbMin[1]);
- targetBvh->m_SubtreeHeaders[i].m_quantizedAabbMin[2] = btSwapEndian(m_SubtreeHeaders[i].m_quantizedAabbMin[2]);
-
- targetBvh->m_SubtreeHeaders[i].m_quantizedAabbMax[0] = btSwapEndian(m_SubtreeHeaders[i].m_quantizedAabbMax[0]);
- targetBvh->m_SubtreeHeaders[i].m_quantizedAabbMax[1] = btSwapEndian(m_SubtreeHeaders[i].m_quantizedAabbMax[1]);
- targetBvh->m_SubtreeHeaders[i].m_quantizedAabbMax[2] = btSwapEndian(m_SubtreeHeaders[i].m_quantizedAabbMax[2]);
-
- targetBvh->m_SubtreeHeaders[i].m_rootNodeIndex = static_cast<int>(btSwapEndian(m_SubtreeHeaders[i].m_rootNodeIndex));
- targetBvh->m_SubtreeHeaders[i].m_subtreeSize = static_cast<int>(btSwapEndian(m_SubtreeHeaders[i].m_subtreeSize));
- }
- }
- else
- {
- for (int i = 0; i < m_subtreeHeaderCount; i++)
- {
- targetBvh->m_SubtreeHeaders[i].m_quantizedAabbMin[0] = (m_SubtreeHeaders[i].m_quantizedAabbMin[0]);
- targetBvh->m_SubtreeHeaders[i].m_quantizedAabbMin[1] = (m_SubtreeHeaders[i].m_quantizedAabbMin[1]);
- targetBvh->m_SubtreeHeaders[i].m_quantizedAabbMin[2] = (m_SubtreeHeaders[i].m_quantizedAabbMin[2]);
-
- targetBvh->m_SubtreeHeaders[i].m_quantizedAabbMax[0] = (m_SubtreeHeaders[i].m_quantizedAabbMax[0]);
- targetBvh->m_SubtreeHeaders[i].m_quantizedAabbMax[1] = (m_SubtreeHeaders[i].m_quantizedAabbMax[1]);
- targetBvh->m_SubtreeHeaders[i].m_quantizedAabbMax[2] = (m_SubtreeHeaders[i].m_quantizedAabbMax[2]);
-
- targetBvh->m_SubtreeHeaders[i].m_rootNodeIndex = (m_SubtreeHeaders[i].m_rootNodeIndex);
- targetBvh->m_SubtreeHeaders[i].m_subtreeSize = (m_SubtreeHeaders[i].m_subtreeSize);
- targetBvh->m_SubtreeHeaders[i] = m_SubtreeHeaders[i];
- }
- }
-
- nodeData += sizeof(btBvhSubtreeInfo) * m_subtreeHeaderCount;
-
- return true;
-}
-
-btQuantizedBvh *btQuantizedBvh::deSerializeInPlace(void *i_alignedDataBuffer, unsigned int i_dataBufferSize, bool i_swapEndian)
-{
-
- if (i_alignedDataBuffer == NULL)// || (((unsigned)i_alignedDataBuffer & BVH_ALIGNMENT_MASK) != 0))
- {
- return NULL;
- }
- btQuantizedBvh *bvh = (btQuantizedBvh *)i_alignedDataBuffer;
-
- if (i_swapEndian)
- {
- bvh->m_curNodeIndex = static_cast<int>(btSwapEndian(bvh->m_curNodeIndex));
-
- btUnSwapVector3Endian(bvh->m_bvhAabbMin);
- btUnSwapVector3Endian(bvh->m_bvhAabbMax);
- btUnSwapVector3Endian(bvh->m_bvhQuantization);
-
- bvh->m_traversalMode = (btTraversalMode)btSwapEndian(bvh->m_traversalMode);
- bvh->m_subtreeHeaderCount = static_cast<int>(btSwapEndian(bvh->m_subtreeHeaderCount));
- }
-
- unsigned int calculatedBufSize = bvh->calculateSerializeBufferSize();
- btAssert(calculatedBufSize <= i_dataBufferSize);
-
- if (calculatedBufSize > i_dataBufferSize)
- {
- return NULL;
- }
-
- unsigned char *nodeData = (unsigned char *)bvh;
- nodeData += sizeof(btQuantizedBvh);
-
- unsigned sizeToAdd = 0;//(BVH_ALIGNMENT-((unsigned)nodeData & BVH_ALIGNMENT_MASK))&BVH_ALIGNMENT_MASK;
- nodeData += sizeToAdd;
-
- int nodeCount = bvh->m_curNodeIndex;
-
- // Must call placement new to fill in virtual function table, etc, but we don't want to overwrite most data, so call a special version of the constructor
- // Also, m_leafNodes and m_quantizedLeafNodes will be initialized to default values by the constructor
- new (bvh) btQuantizedBvh(*bvh, false);
-
- if (bvh->m_useQuantization)
- {
- bvh->m_quantizedContiguousNodes.initializeFromBuffer(nodeData, nodeCount, nodeCount);
-
- if (i_swapEndian)
- {
- for (int nodeIndex = 0; nodeIndex < nodeCount; nodeIndex++)
- {
- bvh->m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMin[0] = btSwapEndian(bvh->m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMin[0]);
- bvh->m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMin[1] = btSwapEndian(bvh->m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMin[1]);
- bvh->m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMin[2] = btSwapEndian(bvh->m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMin[2]);
-
- bvh->m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMax[0] = btSwapEndian(bvh->m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMax[0]);
- bvh->m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMax[1] = btSwapEndian(bvh->m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMax[1]);
- bvh->m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMax[2] = btSwapEndian(bvh->m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMax[2]);
-
- bvh->m_quantizedContiguousNodes[nodeIndex].m_escapeIndexOrTriangleIndex = static_cast<int>(btSwapEndian(bvh->m_quantizedContiguousNodes[nodeIndex].m_escapeIndexOrTriangleIndex));
- }
- }
- nodeData += sizeof(btQuantizedBvhNode) * nodeCount;
- }
- else
- {
- bvh->m_contiguousNodes.initializeFromBuffer(nodeData, nodeCount, nodeCount);
-
- if (i_swapEndian)
- {
- for (int nodeIndex = 0; nodeIndex < nodeCount; nodeIndex++)
- {
- btUnSwapVector3Endian(bvh->m_contiguousNodes[nodeIndex].m_aabbMinOrg);
- btUnSwapVector3Endian(bvh->m_contiguousNodes[nodeIndex].m_aabbMaxOrg);
-
- bvh->m_contiguousNodes[nodeIndex].m_escapeIndex = static_cast<int>(btSwapEndian(bvh->m_contiguousNodes[nodeIndex].m_escapeIndex));
- bvh->m_contiguousNodes[nodeIndex].m_subPart = static_cast<int>(btSwapEndian(bvh->m_contiguousNodes[nodeIndex].m_subPart));
- bvh->m_contiguousNodes[nodeIndex].m_triangleIndex = static_cast<int>(btSwapEndian(bvh->m_contiguousNodes[nodeIndex].m_triangleIndex));
- }
- }
- nodeData += sizeof(btOptimizedBvhNode) * nodeCount;
- }
-
- sizeToAdd = 0;//(BVH_ALIGNMENT-((unsigned)nodeData & BVH_ALIGNMENT_MASK))&BVH_ALIGNMENT_MASK;
- nodeData += sizeToAdd;
-
- // Now serialize the subtree headers
- bvh->m_SubtreeHeaders.initializeFromBuffer(nodeData, bvh->m_subtreeHeaderCount, bvh->m_subtreeHeaderCount);
- if (i_swapEndian)
- {
- for (int i = 0; i < bvh->m_subtreeHeaderCount; i++)
- {
- bvh->m_SubtreeHeaders[i].m_quantizedAabbMin[0] = btSwapEndian(bvh->m_SubtreeHeaders[i].m_quantizedAabbMin[0]);
- bvh->m_SubtreeHeaders[i].m_quantizedAabbMin[1] = btSwapEndian(bvh->m_SubtreeHeaders[i].m_quantizedAabbMin[1]);
- bvh->m_SubtreeHeaders[i].m_quantizedAabbMin[2] = btSwapEndian(bvh->m_SubtreeHeaders[i].m_quantizedAabbMin[2]);
-
- bvh->m_SubtreeHeaders[i].m_quantizedAabbMax[0] = btSwapEndian(bvh->m_SubtreeHeaders[i].m_quantizedAabbMax[0]);
- bvh->m_SubtreeHeaders[i].m_quantizedAabbMax[1] = btSwapEndian(bvh->m_SubtreeHeaders[i].m_quantizedAabbMax[1]);
- bvh->m_SubtreeHeaders[i].m_quantizedAabbMax[2] = btSwapEndian(bvh->m_SubtreeHeaders[i].m_quantizedAabbMax[2]);
-
- bvh->m_SubtreeHeaders[i].m_rootNodeIndex = static_cast<int>(btSwapEndian(bvh->m_SubtreeHeaders[i].m_rootNodeIndex));
- bvh->m_SubtreeHeaders[i].m_subtreeSize = static_cast<int>(btSwapEndian(bvh->m_SubtreeHeaders[i].m_subtreeSize));
- }
- }
-
- return bvh;
-}
-
-// Constructor that prevents btVector3's default constructor from being called
-btQuantizedBvh::btQuantizedBvh(btQuantizedBvh &self, bool /* ownsMemory */) :
-m_bvhAabbMin(self.m_bvhAabbMin),
-m_bvhAabbMax(self.m_bvhAabbMax),
-m_bvhQuantization(self.m_bvhQuantization)
-{
-
-
-}
-
-
-
diff --git a/extern/bullet2/src/BulletCollision/BroadphaseCollision/btQuantizedBvh.h b/extern/bullet2/src/BulletCollision/BroadphaseCollision/btQuantizedBvh.h
deleted file mode 100644
index 8a149b533fa..00000000000
--- a/extern/bullet2/src/BulletCollision/BroadphaseCollision/btQuantizedBvh.h
+++ /dev/null
@@ -1,486 +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.
-*/
-
-#ifndef QUANTIZED_BVH_H
-#define QUANTIZED_BVH_H
-
-//#define DEBUG_CHECK_DEQUANTIZATION 1
-#ifdef DEBUG_CHECK_DEQUANTIZATION
-#ifdef __SPU__
-#define printf spu_printf
-#endif //__SPU__
-
-#include <stdio.h>
-#include <stdlib.h>
-#endif //DEBUG_CHECK_DEQUANTIZATION
-
-#include "LinearMath/btVector3.h"
-#include "LinearMath/btAlignedAllocator.h"
-
-
-//http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vclang/html/vclrf__m128.asp
-
-
-//Note: currently we have 16 bytes per quantized node
-#define MAX_SUBTREE_SIZE_IN_BYTES 2048
-
-// 10 gives the potential for 1024 parts, with at most 2^21 (2097152) (minus one
-// actually) triangles each (since the sign bit is reserved
-#define MAX_NUM_PARTS_IN_BITS 10
-
-///btQuantizedBvhNode is a compressed aabb node, 16 bytes.
-///Node can be used for leafnode or internal node. Leafnodes can point to 32-bit triangle index (non-negative range).
-ATTRIBUTE_ALIGNED16 (struct) btQuantizedBvhNode
-{
- BT_DECLARE_ALIGNED_ALLOCATOR();
-
- //12 bytes
- unsigned short int m_quantizedAabbMin[3];
- unsigned short int m_quantizedAabbMax[3];
- //4 bytes
- int m_escapeIndexOrTriangleIndex;
-
- bool isLeafNode() const
- {
- //skipindex is negative (internal node), triangleindex >=0 (leafnode)
- return (m_escapeIndexOrTriangleIndex >= 0);
- }
- int getEscapeIndex() const
- {
- btAssert(!isLeafNode());
- return -m_escapeIndexOrTriangleIndex;
- }
- int getTriangleIndex() const
- {
- btAssert(isLeafNode());
- // Get only the lower bits where the triangle index is stored
- return (m_escapeIndexOrTriangleIndex&~((~0)<<(31-MAX_NUM_PARTS_IN_BITS)));
- }
- int getPartId() const
- {
- btAssert(isLeafNode());
- // Get only the highest bits where the part index is stored
- return (m_escapeIndexOrTriangleIndex>>(31-MAX_NUM_PARTS_IN_BITS));
- }
-}
-;
-
-/// btOptimizedBvhNode contains both internal and leaf node information.
-/// Total node size is 44 bytes / node. You can use the compressed version of 16 bytes.
-ATTRIBUTE_ALIGNED16 (struct) btOptimizedBvhNode
-{
- BT_DECLARE_ALIGNED_ALLOCATOR();
-
- //32 bytes
- btVector3 m_aabbMinOrg;
- btVector3 m_aabbMaxOrg;
-
- //4
- int m_escapeIndex;
-
- //8
- //for child nodes
- int m_subPart;
- int m_triangleIndex;
- int m_padding[5];//bad, due to alignment
-
-
-};
-
-
-///btBvhSubtreeInfo provides info to gather a subtree of limited size
-ATTRIBUTE_ALIGNED16(class) btBvhSubtreeInfo
-{
-public:
- BT_DECLARE_ALIGNED_ALLOCATOR();
-
- //12 bytes
- unsigned short int m_quantizedAabbMin[3];
- unsigned short int m_quantizedAabbMax[3];
- //4 bytes, points to the root of the subtree
- int m_rootNodeIndex;
- //4 bytes
- int m_subtreeSize;
- int m_padding[3];
-
- btBvhSubtreeInfo()
- {
- //memset(&m_padding[0], 0, sizeof(m_padding));
- }
-
-
- void setAabbFromQuantizeNode(const btQuantizedBvhNode& quantizedNode)
- {
- m_quantizedAabbMin[0] = quantizedNode.m_quantizedAabbMin[0];
- m_quantizedAabbMin[1] = quantizedNode.m_quantizedAabbMin[1];
- m_quantizedAabbMin[2] = quantizedNode.m_quantizedAabbMin[2];
- m_quantizedAabbMax[0] = quantizedNode.m_quantizedAabbMax[0];
- m_quantizedAabbMax[1] = quantizedNode.m_quantizedAabbMax[1];
- m_quantizedAabbMax[2] = quantizedNode.m_quantizedAabbMax[2];
- }
-}
-;
-
-
-class btNodeOverlapCallback
-{
-public:
- virtual ~btNodeOverlapCallback() {};
-
- virtual void processNode(int subPart, int triangleIndex) = 0;
-};
-
-#include "LinearMath/btAlignedAllocator.h"
-#include "LinearMath/btAlignedObjectArray.h"
-
-
-
-///for code readability:
-typedef btAlignedObjectArray<btOptimizedBvhNode> NodeArray;
-typedef btAlignedObjectArray<btQuantizedBvhNode> QuantizedNodeArray;
-typedef btAlignedObjectArray<btBvhSubtreeInfo> BvhSubtreeInfoArray;
-
-
-///The btQuantizedBvh class stores an AABB tree that can be quickly traversed on CPU and Cell SPU.
-///It is used by the btBvhTriangleMeshShape as midphase, and by the btMultiSapBroadphase.
-///It is recommended to use quantization for better performance and lower memory requirements.
-ATTRIBUTE_ALIGNED16(class) btQuantizedBvh
-{
-protected:
-
- NodeArray m_leafNodes;
- NodeArray m_contiguousNodes;
-
- QuantizedNodeArray m_quantizedLeafNodes;
-
- QuantizedNodeArray m_quantizedContiguousNodes;
-
- int m_curNodeIndex;
-
-
- //quantization data
- bool m_useQuantization;
- btVector3 m_bvhAabbMin;
- btVector3 m_bvhAabbMax;
- btVector3 m_bvhQuantization;
-public:
- BT_DECLARE_ALIGNED_ALLOCATOR();
-
- enum btTraversalMode
- {
- TRAVERSAL_STACKLESS = 0,
- TRAVERSAL_STACKLESS_CACHE_FRIENDLY,
- TRAVERSAL_RECURSIVE
- };
-protected:
-
- btTraversalMode m_traversalMode;
-
- BvhSubtreeInfoArray m_SubtreeHeaders;
-
- //This is only used for serialization so we don't have to add serialization directly to btAlignedObjectArray
- int m_subtreeHeaderCount;
-
-
- ///two versions, one for quantized and normal nodes. This allows code-reuse while maintaining readability (no template/macro!)
- ///this might be refactored into a virtual, it is usually not calculated at run-time
- void setInternalNodeAabbMin(int nodeIndex, const btVector3& aabbMin)
- {
- if (m_useQuantization)
- {
- quantize(&m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMin[0] ,aabbMin,0);
- } else
- {
- m_contiguousNodes[nodeIndex].m_aabbMinOrg = aabbMin;
-
- }
- }
- void setInternalNodeAabbMax(int nodeIndex,const btVector3& aabbMax)
- {
- if (m_useQuantization)
- {
- quantize(&m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMax[0],aabbMax,1);
- } else
- {
- m_contiguousNodes[nodeIndex].m_aabbMaxOrg = aabbMax;
- }
- }
-
- btVector3 getAabbMin(int nodeIndex) const
- {
- if (m_useQuantization)
- {
- return unQuantize(&m_quantizedLeafNodes[nodeIndex].m_quantizedAabbMin[0]);
- }
- //non-quantized
- return m_leafNodes[nodeIndex].m_aabbMinOrg;
-
- }
- btVector3 getAabbMax(int nodeIndex) const
- {
- if (m_useQuantization)
- {
- return unQuantize(&m_quantizedLeafNodes[nodeIndex].m_quantizedAabbMax[0]);
- }
- //non-quantized
- return m_leafNodes[nodeIndex].m_aabbMaxOrg;
-
- }
-
-
- void setInternalNodeEscapeIndex(int nodeIndex, int escapeIndex)
- {
- if (m_useQuantization)
- {
- m_quantizedContiguousNodes[nodeIndex].m_escapeIndexOrTriangleIndex = -escapeIndex;
- }
- else
- {
- m_contiguousNodes[nodeIndex].m_escapeIndex = escapeIndex;
- }
-
- }
-
- void mergeInternalNodeAabb(int nodeIndex,const btVector3& newAabbMin,const btVector3& newAabbMax)
- {
- if (m_useQuantization)
- {
- unsigned short int quantizedAabbMin[3];
- unsigned short int quantizedAabbMax[3];
- quantize(quantizedAabbMin,newAabbMin,0);
- quantize(quantizedAabbMax,newAabbMax,1);
- for (int i=0;i<3;i++)
- {
- if (m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMin[i] > quantizedAabbMin[i])
- m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMin[i] = quantizedAabbMin[i];
-
- if (m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMax[i] < quantizedAabbMax[i])
- m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMax[i] = quantizedAabbMax[i];
-
- }
- } else
- {
- //non-quantized
- m_contiguousNodes[nodeIndex].m_aabbMinOrg.setMin(newAabbMin);
- m_contiguousNodes[nodeIndex].m_aabbMaxOrg.setMax(newAabbMax);
- }
- }
-
- void swapLeafNodes(int firstIndex,int secondIndex);
-
- void assignInternalNodeFromLeafNode(int internalNode,int leafNodeIndex);
-
-protected:
-
-
-
- void buildTree (int startIndex,int endIndex);
-
- int calcSplittingAxis(int startIndex,int endIndex);
-
- int sortAndCalcSplittingIndex(int startIndex,int endIndex,int splitAxis);
-
- void walkStacklessTree(btNodeOverlapCallback* nodeCallback,const btVector3& aabbMin,const btVector3& aabbMax) const;
-
- void walkStacklessQuantizedTreeAgainstRay(btNodeOverlapCallback* nodeCallback, const btVector3& raySource, const btVector3& rayTarget, const btVector3& aabbMin, const btVector3& aabbMax, int startNodeIndex,int endNodeIndex) const;
- void walkStacklessQuantizedTree(btNodeOverlapCallback* nodeCallback,unsigned short int* quantizedQueryAabbMin,unsigned short int* quantizedQueryAabbMax,int startNodeIndex,int endNodeIndex) const;
-
- ///tree traversal designed for small-memory processors like PS3 SPU
- void walkStacklessQuantizedTreeCacheFriendly(btNodeOverlapCallback* nodeCallback,unsigned short int* quantizedQueryAabbMin,unsigned short int* quantizedQueryAabbMax) const;
-
- ///use the 16-byte stackless 'skipindex' node tree to do a recursive traversal
- void walkRecursiveQuantizedTreeAgainstQueryAabb(const btQuantizedBvhNode* currentNode,btNodeOverlapCallback* nodeCallback,unsigned short int* quantizedQueryAabbMin,unsigned short int* quantizedQueryAabbMax) const;
-
- ///use the 16-byte stackless 'skipindex' node tree to do a recursive traversal
- void walkRecursiveQuantizedTreeAgainstQuantizedTree(const btQuantizedBvhNode* treeNodeA,const btQuantizedBvhNode* treeNodeB,btNodeOverlapCallback* nodeCallback) const;
-
-
-#define USE_BANCHLESS 1
-#ifdef USE_BANCHLESS
- //This block replaces the block below and uses no branches, and replaces the 8 bit return with a 32 bit return for improved performance (~3x on XBox 360)
- SIMD_FORCE_INLINE unsigned testQuantizedAabbAgainstQuantizedAabb(unsigned short int* aabbMin1,unsigned short int* aabbMax1,const unsigned short int* aabbMin2,const unsigned short int* aabbMax2) const
- {
- return static_cast<unsigned int>(btSelect((unsigned)((aabbMin1[0] <= aabbMax2[0]) & (aabbMax1[0] >= aabbMin2[0])
- & (aabbMin1[2] <= aabbMax2[2]) & (aabbMax1[2] >= aabbMin2[2])
- & (aabbMin1[1] <= aabbMax2[1]) & (aabbMax1[1] >= aabbMin2[1])),
- 1, 0));
- }
-#else
- SIMD_FORCE_INLINE bool testQuantizedAabbAgainstQuantizedAabb(unsigned short int* aabbMin1,unsigned short int* aabbMax1,const unsigned short int* aabbMin2,const unsigned short int* aabbMax2) const
- {
- bool overlap = true;
- overlap = (aabbMin1[0] > aabbMax2[0] || aabbMax1[0] < aabbMin2[0]) ? false : overlap;
- overlap = (aabbMin1[2] > aabbMax2[2] || aabbMax1[2] < aabbMin2[2]) ? false : overlap;
- overlap = (aabbMin1[1] > aabbMax2[1] || aabbMax1[1] < aabbMin2[1]) ? false : overlap;
- return overlap;
- }
-#endif //USE_BANCHLESS
-
- void updateSubtreeHeaders(int leftChildNodexIndex,int rightChildNodexIndex);
-
-public:
- btQuantizedBvh();
-
- virtual ~btQuantizedBvh();
-
-
- ///***************************************** expert/internal use only *************************
- void setQuantizationValues(const btVector3& bvhAabbMin,const btVector3& bvhAabbMax,btScalar quantizationMargin=btScalar(1.0));
- QuantizedNodeArray& getLeafNodeArray() { return m_quantizedLeafNodes; }
- ///buildInternal is expert use only: assumes that setQuantizationValues and LeafNodeArray are initialized
- void buildInternal();
- ///***************************************** expert/internal use only *************************
-
- void reportAabbOverlappingNodex(btNodeOverlapCallback* nodeCallback,const btVector3& aabbMin,const btVector3& aabbMax) const;
- void reportRayOverlappingNodex (btNodeOverlapCallback* nodeCallback, const btVector3& raySource, const btVector3& rayTarget) const;
- void reportBoxCastOverlappingNodex(btNodeOverlapCallback* nodeCallback, const btVector3& raySource, const btVector3& rayTarget, const btVector3& aabbMin,const btVector3& aabbMax) const;
-
- SIMD_FORCE_INLINE void quantize(unsigned short* out, const btVector3& point,int isMax) const
- {
-
- btAssert(m_useQuantization);
-
- btAssert(point.getX() <= m_bvhAabbMax.getX());
- btAssert(point.getY() <= m_bvhAabbMax.getY());
- btAssert(point.getZ() <= m_bvhAabbMax.getZ());
-
- btAssert(point.getX() >= m_bvhAabbMin.getX());
- btAssert(point.getY() >= m_bvhAabbMin.getY());
- btAssert(point.getZ() >= m_bvhAabbMin.getZ());
-
- btVector3 v = (point - m_bvhAabbMin) * m_bvhQuantization;
- ///Make sure rounding is done in a way that unQuantize(quantizeWithClamp(...)) is conservative
- ///end-points always set the first bit, so that they are sorted properly (so that neighbouring AABBs overlap properly)
- ///todo: double-check this
- if (isMax)
- {
- out[0] = (unsigned short) (((unsigned short)(v.getX()+btScalar(1.)) | 1));
- out[1] = (unsigned short) (((unsigned short)(v.getY()+btScalar(1.)) | 1));
- out[2] = (unsigned short) (((unsigned short)(v.getZ()+btScalar(1.)) | 1));
- } else
- {
- out[0] = (unsigned short) (((unsigned short)(v.getX()) & 0xfffe));
- out[1] = (unsigned short) (((unsigned short)(v.getY()) & 0xfffe));
- out[2] = (unsigned short) (((unsigned short)(v.getZ()) & 0xfffe));
- }
-
-
-#ifdef DEBUG_CHECK_DEQUANTIZATION
- btVector3 newPoint = unQuantize(out);
- if (isMax)
- {
- if (newPoint.getX() < point.getX())
- {
- printf("unconservative X, diffX = %f, oldX=%f,newX=%f\n",newPoint.getX()-point.getX(), newPoint.getX(),point.getX());
- }
- if (newPoint.getY() < point.getY())
- {
- printf("unconservative Y, diffY = %f, oldY=%f,newY=%f\n",newPoint.getY()-point.getY(), newPoint.getY(),point.getY());
- }
- if (newPoint.getZ() < point.getZ())
- {
-
- printf("unconservative Z, diffZ = %f, oldZ=%f,newZ=%f\n",newPoint.getZ()-point.getZ(), newPoint.getZ(),point.getZ());
- }
- } else
- {
- if (newPoint.getX() > point.getX())
- {
- printf("unconservative X, diffX = %f, oldX=%f,newX=%f\n",newPoint.getX()-point.getX(), newPoint.getX(),point.getX());
- }
- if (newPoint.getY() > point.getY())
- {
- printf("unconservative Y, diffY = %f, oldY=%f,newY=%f\n",newPoint.getY()-point.getY(), newPoint.getY(),point.getY());
- }
- if (newPoint.getZ() > point.getZ())
- {
- printf("unconservative Z, diffZ = %f, oldZ=%f,newZ=%f\n",newPoint.getZ()-point.getZ(), newPoint.getZ(),point.getZ());
- }
- }
-#endif //DEBUG_CHECK_DEQUANTIZATION
-
- }
-
-
- SIMD_FORCE_INLINE void quantizeWithClamp(unsigned short* out, const btVector3& point2,int isMax) const
- {
-
- btAssert(m_useQuantization);
-
- btVector3 clampedPoint(point2);
- clampedPoint.setMax(m_bvhAabbMin);
- clampedPoint.setMin(m_bvhAabbMax);
-
- quantize(out,clampedPoint,isMax);
-
- }
-
- SIMD_FORCE_INLINE btVector3 unQuantize(const unsigned short* vecIn) const
- {
- btVector3 vecOut;
- vecOut.setValue(
- (btScalar)(vecIn[0]) / (m_bvhQuantization.getX()),
- (btScalar)(vecIn[1]) / (m_bvhQuantization.getY()),
- (btScalar)(vecIn[2]) / (m_bvhQuantization.getZ()));
- vecOut += m_bvhAabbMin;
- return vecOut;
- }
-
- ///setTraversalMode let's you choose between stackless, recursive or stackless cache friendly tree traversal. Note this is only implemented for quantized trees.
- void setTraversalMode(btTraversalMode traversalMode)
- {
- m_traversalMode = traversalMode;
- }
-
-
- SIMD_FORCE_INLINE QuantizedNodeArray& getQuantizedNodeArray()
- {
- return m_quantizedContiguousNodes;
- }
-
-
- SIMD_FORCE_INLINE BvhSubtreeInfoArray& getSubtreeInfoArray()
- {
- return m_SubtreeHeaders;
- }
-
-
- /////Calculate space needed to store BVH for serialization
- unsigned calculateSerializeBufferSize();
-
- /// Data buffer MUST be 16 byte aligned
- virtual bool serialize(void *o_alignedDataBuffer, unsigned i_dataBufferSize, bool i_swapEndian);
-
- ///deSerializeInPlace loads and initializes a BVH from a buffer in memory 'in place'
- static btQuantizedBvh *deSerializeInPlace(void *i_alignedDataBuffer, unsigned int i_dataBufferSize, bool i_swapEndian);
-
- static unsigned int getAlignmentSerializationPadding();
-
- SIMD_FORCE_INLINE bool isQuantized()
- {
- return m_useQuantization;
- }
-
-private:
- // Special "copy" constructor that allows for in-place deserialization
- // Prevents btVector3's default constructor from being called, but doesn't inialize much else
- // ownsMemory should most likely be false if deserializing, and if you are not, don't call this (it also changes the function signature, which we need)
- btQuantizedBvh(btQuantizedBvh &other, bool ownsMemory);
-
-}
-;
-
-
-#endif //QUANTIZED_BVH_H
diff --git a/extern/bullet2/src/BulletCollision/CollisionDispatch/btBoxBoxCollisionAlgorithm.cpp b/extern/bullet2/src/BulletCollision/CollisionDispatch/btBoxBoxCollisionAlgorithm.cpp
deleted file mode 100644
index cd0c028012c..00000000000
--- a/extern/bullet2/src/BulletCollision/CollisionDispatch/btBoxBoxCollisionAlgorithm.cpp
+++ /dev/null
@@ -1,85 +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.
-*/
-
-#include "btBoxBoxCollisionAlgorithm.h"
-#include "BulletCollision/CollisionDispatch/btCollisionDispatcher.h"
-#include "BulletCollision/CollisionShapes/btBoxShape.h"
-#include "BulletCollision/CollisionDispatch/btCollisionObject.h"
-#include "btBoxBoxDetector.h"
-
-#define USE_PERSISTENT_CONTACTS 1
-
-btBoxBoxCollisionAlgorithm::btBoxBoxCollisionAlgorithm(btPersistentManifold* mf,const btCollisionAlgorithmConstructionInfo& ci,btCollisionObject* obj0,btCollisionObject* obj1)
-: btCollisionAlgorithm(ci),
-m_ownManifold(false),
-m_manifoldPtr(mf)
-{
- if (!m_manifoldPtr && m_dispatcher->needsCollision(obj0,obj1))
- {
- m_manifoldPtr = m_dispatcher->getNewManifold(obj0,obj1);
- m_ownManifold = true;
- }
-}
-
-btBoxBoxCollisionAlgorithm::~btBoxBoxCollisionAlgorithm()
-{
- if (m_ownManifold)
- {
- if (m_manifoldPtr)
- m_dispatcher->releaseManifold(m_manifoldPtr);
- }
-}
-
-void btBoxBoxCollisionAlgorithm::processCollision (btCollisionObject* body0,btCollisionObject* body1,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut)
-{
- if (!m_manifoldPtr)
- return;
-
- btCollisionObject* col0 = body0;
- btCollisionObject* col1 = body1;
- btBoxShape* box0 = (btBoxShape*)col0->getCollisionShape();
- btBoxShape* box1 = (btBoxShape*)col1->getCollisionShape();
-
-
-
- /// report a contact. internally this will be kept persistent, and contact reduction is done
- resultOut->setPersistentManifold(m_manifoldPtr);
-#ifndef USE_PERSISTENT_CONTACTS
- m_manifoldPtr->clearManifold();
-#endif //USE_PERSISTENT_CONTACTS
-
- btDiscreteCollisionDetectorInterface::ClosestPointInput input;
- input.m_maximumDistanceSquared = 1e30f;
- input.m_transformA = body0->getWorldTransform();
- input.m_transformB = body1->getWorldTransform();
-
- btBoxBoxDetector detector(box0,box1);
- detector.getClosestPoints(input,*resultOut,dispatchInfo.m_debugDraw);
-
-#ifdef USE_PERSISTENT_CONTACTS
- // refreshContactPoints is only necessary when using persistent contact points. otherwise all points are newly added
- if (m_ownManifold)
- {
- resultOut->refreshContactPoints();
- }
-#endif //USE_PERSISTENT_CONTACTS
-
-}
-
-btScalar btBoxBoxCollisionAlgorithm::calculateTimeOfImpact(btCollisionObject* /*body0*/,btCollisionObject* /*body1*/,const btDispatcherInfo& /*dispatchInfo*/,btManifoldResult* /*resultOut*/)
-{
- //not yet
- return 1.f;
-}
diff --git a/extern/bullet2/src/BulletCollision/CollisionDispatch/btBoxBoxCollisionAlgorithm.h b/extern/bullet2/src/BulletCollision/CollisionDispatch/btBoxBoxCollisionAlgorithm.h
deleted file mode 100644
index 35afaf175a1..00000000000
--- a/extern/bullet2/src/BulletCollision/CollisionDispatch/btBoxBoxCollisionAlgorithm.h
+++ /dev/null
@@ -1,66 +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.
-*/
-
-#ifndef BOX_BOX__COLLISION_ALGORITHM_H
-#define BOX_BOX__COLLISION_ALGORITHM_H
-
-#include "BulletCollision/BroadphaseCollision/btCollisionAlgorithm.h"
-#include "BulletCollision/BroadphaseCollision/btBroadphaseProxy.h"
-#include "BulletCollision/BroadphaseCollision/btDispatcher.h"
-#include "BulletCollision/CollisionDispatch/btCollisionCreateFunc.h"
-
-class btPersistentManifold;
-
-///box-box collision detection
-class btBoxBoxCollisionAlgorithm : public btCollisionAlgorithm
-{
- bool m_ownManifold;
- btPersistentManifold* m_manifoldPtr;
-
-public:
- btBoxBoxCollisionAlgorithm(const btCollisionAlgorithmConstructionInfo& ci)
- : btCollisionAlgorithm(ci) {}
-
- virtual void processCollision (btCollisionObject* body0,btCollisionObject* body1,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut);
-
- virtual btScalar calculateTimeOfImpact(btCollisionObject* body0,btCollisionObject* body1,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut);
-
- btBoxBoxCollisionAlgorithm(btPersistentManifold* mf,const btCollisionAlgorithmConstructionInfo& ci,btCollisionObject* body0,btCollisionObject* body1);
-
- virtual ~btBoxBoxCollisionAlgorithm();
-
- virtual void getAllContactManifolds(btManifoldArray& manifoldArray)
- {
- if (m_manifoldPtr && m_ownManifold)
- {
- manifoldArray.push_back(m_manifoldPtr);
- }
- }
-
-
- struct CreateFunc :public btCollisionAlgorithmCreateFunc
- {
- virtual btCollisionAlgorithm* CreateCollisionAlgorithm(btCollisionAlgorithmConstructionInfo& ci, btCollisionObject* body0,btCollisionObject* body1)
- {
- int bbsize = sizeof(btBoxBoxCollisionAlgorithm);
- void* ptr = ci.m_dispatcher1->allocateCollisionAlgorithm(bbsize);
- return new(ptr) btBoxBoxCollisionAlgorithm(0,ci,body0,body1);
- }
- };
-
-};
-
-#endif //BOX_BOX__COLLISION_ALGORITHM_H
-
diff --git a/extern/bullet2/src/BulletCollision/CollisionDispatch/btBoxBoxDetector.cpp b/extern/bullet2/src/BulletCollision/CollisionDispatch/btBoxBoxDetector.cpp
deleted file mode 100644
index 45ebff5dc45..00000000000
--- a/extern/bullet2/src/BulletCollision/CollisionDispatch/btBoxBoxDetector.cpp
+++ /dev/null
@@ -1,683 +0,0 @@
-
-/*
- * Box-Box collision detection re-distributed under the ZLib license with permission from Russell L. Smith
- * Original version is from Open Dynamics Engine, Copyright (C) 2001,2002 Russell L. Smith.
- * All rights reserved. Email: russ@q12.org Web: www.q12.org
- Bullet Continuous Collision Detection and Physics Library
- Bullet is 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.
-*/
-
-///ODE box-box collision detection is adapted to work with Bullet
-
-#include "btBoxBoxDetector.h"
-#include "BulletCollision/CollisionShapes/btBoxShape.h"
-
-#include <float.h>
-#include <string.h>
-
-btBoxBoxDetector::btBoxBoxDetector(btBoxShape* box1,btBoxShape* box2)
-: m_box1(box1),
-m_box2(box2)
-{
-
-}
-
-
-// given two boxes (p1,R1,side1) and (p2,R2,side2), collide them together and
-// generate contact points. this returns 0 if there is no contact otherwise
-// it returns the number of contacts generated.
-// `normal' returns the contact normal.
-// `depth' returns the maximum penetration depth along that normal.
-// `return_code' returns a number indicating the type of contact that was
-// detected:
-// 1,2,3 = box 2 intersects with a face of box 1
-// 4,5,6 = box 1 intersects with a face of box 2
-// 7..15 = edge-edge contact
-// `maxc' is the maximum number of contacts allowed to be generated, i.e.
-// the size of the `contact' array.
-// `contact' and `skip' are the contact array information provided to the
-// collision functions. this function only fills in the position and depth
-// fields.
-struct dContactGeom;
-#define dDOTpq(a,b,p,q) ((a)[0]*(b)[0] + (a)[p]*(b)[q] + (a)[2*(p)]*(b)[2*(q)])
-#define dInfinity FLT_MAX
-
-
-/*PURE_INLINE btScalar dDOT (const btScalar *a, const btScalar *b) { return dDOTpq(a,b,1,1); }
-PURE_INLINE btScalar dDOT13 (const btScalar *a, const btScalar *b) { return dDOTpq(a,b,1,3); }
-PURE_INLINE btScalar dDOT31 (const btScalar *a, const btScalar *b) { return dDOTpq(a,b,3,1); }
-PURE_INLINE btScalar dDOT33 (const btScalar *a, const btScalar *b) { return dDOTpq(a,b,3,3); }
-*/
-static btScalar dDOT (const btScalar *a, const btScalar *b) { return dDOTpq(a,b,1,1); }
-static btScalar dDOT44 (const btScalar *a, const btScalar *b) { return dDOTpq(a,b,4,4); }
-static btScalar dDOT41 (const btScalar *a, const btScalar *b) { return dDOTpq(a,b,4,1); }
-static btScalar dDOT14 (const btScalar *a, const btScalar *b) { return dDOTpq(a,b,1,4); }
-#define dMULTIPLYOP1_331(A,op,B,C) \
-{\
- (A)[0] op dDOT41((B),(C)); \
- (A)[1] op dDOT41((B+1),(C)); \
- (A)[2] op dDOT41((B+2),(C)); \
-}
-
-#define dMULTIPLYOP0_331(A,op,B,C) \
-{ \
- (A)[0] op dDOT((B),(C)); \
- (A)[1] op dDOT((B+4),(C)); \
- (A)[2] op dDOT((B+8),(C)); \
-}
-
-#define dMULTIPLY1_331(A,B,C) dMULTIPLYOP1_331(A,=,B,C)
-#define dMULTIPLY0_331(A,B,C) dMULTIPLYOP0_331(A,=,B,C)
-
-typedef btScalar dMatrix3[4*3];
-
-void dLineClosestApproach (const btVector3& pa, const btVector3& ua,
- const btVector3& pb, const btVector3& ub,
- btScalar *alpha, btScalar *beta);
-void dLineClosestApproach (const btVector3& pa, const btVector3& ua,
- const btVector3& pb, const btVector3& ub,
- btScalar *alpha, btScalar *beta)
-{
- btVector3 p;
- p[0] = pb[0] - pa[0];
- p[1] = pb[1] - pa[1];
- p[2] = pb[2] - pa[2];
- btScalar uaub = dDOT(ua,ub);
- btScalar q1 = dDOT(ua,p);
- btScalar q2 = -dDOT(ub,p);
- btScalar d = 1-uaub*uaub;
- if (d <= btScalar(0.0001f)) {
- // @@@ this needs to be made more robust
- *alpha = 0;
- *beta = 0;
- }
- else {
- d = 1.f/d;
- *alpha = (q1 + uaub*q2)*d;
- *beta = (uaub*q1 + q2)*d;
- }
-}
-
-
-
-// find all the intersection points between the 2D rectangle with vertices
-// at (+/-h[0],+/-h[1]) and the 2D quadrilateral with vertices (p[0],p[1]),
-// (p[2],p[3]),(p[4],p[5]),(p[6],p[7]).
-//
-// the intersection points are returned as x,y pairs in the 'ret' array.
-// the number of intersection points is returned by the function (this will
-// be in the range 0 to 8).
-
-static int intersectRectQuad2 (btScalar h[2], btScalar p[8], btScalar ret[16])
-{
- // q (and r) contain nq (and nr) coordinate points for the current (and
- // chopped) polygons
- int nq=4,nr=0;
- btScalar buffer[16];
- btScalar *q = p;
- btScalar *r = ret;
- for (int dir=0; dir <= 1; dir++) {
- // direction notation: xy[0] = x axis, xy[1] = y axis
- for (int sign=-1; sign <= 1; sign += 2) {
- // chop q along the line xy[dir] = sign*h[dir]
- btScalar *pq = q;
- btScalar *pr = r;
- nr = 0;
- for (int i=nq; i > 0; i--) {
- // go through all points in q and all lines between adjacent points
- if (sign*pq[dir] < h[dir]) {
- // this point is inside the chopping line
- pr[0] = pq[0];
- pr[1] = pq[1];
- pr += 2;
- nr++;
- if (nr & 8) {
- q = r;
- goto done;
- }
- }
- btScalar *nextq = (i > 1) ? pq+2 : q;
- if ((sign*pq[dir] < h[dir]) ^ (sign*nextq[dir] < h[dir])) {
- // this line crosses the chopping line
- pr[1-dir] = pq[1-dir] + (nextq[1-dir]-pq[1-dir]) /
- (nextq[dir]-pq[dir]) * (sign*h[dir]-pq[dir]);
- pr[dir] = sign*h[dir];
- pr += 2;
- nr++;
- if (nr & 8) {
- q = r;
- goto done;
- }
- }
- pq += 2;
- }
- q = r;
- r = (q==ret) ? buffer : ret;
- nq = nr;
- }
- }
- done:
- if (q != ret) memcpy (ret,q,nr*2*sizeof(btScalar));
- return nr;
-}
-
-
-#define M__PI 3.14159265f
-
-// given n points in the plane (array p, of size 2*n), generate m points that
-// best represent the whole set. the definition of 'best' here is not
-// predetermined - the idea is to select points that give good box-box
-// collision detection behavior. the chosen point indexes are returned in the
-// array iret (of size m). 'i0' is always the first entry in the array.
-// n must be in the range [1..8]. m must be in the range [1..n]. i0 must be
-// in the range [0..n-1].
-
-void cullPoints2 (int n, btScalar p[], int m, int i0, int iret[]);
-void cullPoints2 (int n, btScalar p[], int m, int i0, int iret[])
-{
- // compute the centroid of the polygon in cx,cy
- int i,j;
- btScalar a,cx,cy,q;
- if (n==1) {
- cx = p[0];
- cy = p[1];
- }
- else if (n==2) {
- cx = btScalar(0.5)*(p[0] + p[2]);
- cy = btScalar(0.5)*(p[1] + p[3]);
- }
- else {
- a = 0;
- cx = 0;
- cy = 0;
- for (i=0; i<(n-1); i++) {
- q = p[i*2]*p[i*2+3] - p[i*2+2]*p[i*2+1];
- a += q;
- cx += q*(p[i*2]+p[i*2+2]);
- cy += q*(p[i*2+1]+p[i*2+3]);
- }
- q = p[n*2-2]*p[1] - p[0]*p[n*2-1];
- a = 1.f/(btScalar(3.0)*(a+q));
- cx = a*(cx + q*(p[n*2-2]+p[0]));
- cy = a*(cy + q*(p[n*2-1]+p[1]));
- }
-
- // compute the angle of each point w.r.t. the centroid
- btScalar A[8];
- for (i=0; i<n; i++) A[i] = btAtan2(p[i*2+1]-cy,p[i*2]-cx);
-
- // search for points that have angles closest to A[i0] + i*(2*pi/m).
- int avail[8];
- for (i=0; i<n; i++) avail[i] = 1;
- avail[i0] = 0;
- iret[0] = i0;
- iret++;
- for (j=1; j<m; j++) {
- a = btScalar(j)*(2*M__PI/m) + A[i0];
- if (a > M__PI) a -= 2*M__PI;
- btScalar maxdiff=1e9,diff;
-#if defined(DEBUG) || defined (_DEBUG)
- *iret = i0; // iret is not allowed to keep this value
-#endif
- for (i=0; i<n; i++) {
- if (avail[i]) {
- diff = btFabs (A[i]-a);
- if (diff > M__PI) diff = 2*M__PI - diff;
- if (diff < maxdiff) {
- maxdiff = diff;
- *iret = i;
- }
- }
- }
-#if defined(DEBUG) || defined (_DEBUG)
- btAssert (*iret != i0); // ensure iret got set
-#endif
- avail[*iret] = 0;
- iret++;
- }
-}
-
-
-
-int dBoxBox2 (const btVector3& p1, const dMatrix3 R1,
- const btVector3& side1, const btVector3& p2,
- const dMatrix3 R2, const btVector3& side2,
- btVector3& normal, btScalar *depth, int *return_code,
- int maxc, dContactGeom * /*contact*/, int /*skip*/,btDiscreteCollisionDetectorInterface::Result& output);
-int dBoxBox2 (const btVector3& p1, const dMatrix3 R1,
- const btVector3& side1, const btVector3& p2,
- const dMatrix3 R2, const btVector3& side2,
- btVector3& normal, btScalar *depth, int *return_code,
- int maxc, dContactGeom * /*contact*/, int /*skip*/,btDiscreteCollisionDetectorInterface::Result& output)
-{
- const btScalar fudge_factor = btScalar(1.05);
- btVector3 p,pp,normalC;
- const btScalar *normalR = 0;
- btScalar A[3],B[3],R11,R12,R13,R21,R22,R23,R31,R32,R33,
- Q11,Q12,Q13,Q21,Q22,Q23,Q31,Q32,Q33,s,s2,l;
- int i,j,invert_normal,code;
-
- // get vector from centers of box 1 to box 2, relative to box 1
- p = p2 - p1;
- dMULTIPLY1_331 (pp,R1,p); // get pp = p relative to body 1
-
- // get side lengths / 2
- A[0] = side1[0]*btScalar(0.5);
- A[1] = side1[1]*btScalar(0.5);
- A[2] = side1[2]*btScalar(0.5);
- B[0] = side2[0]*btScalar(0.5);
- B[1] = side2[1]*btScalar(0.5);
- B[2] = side2[2]*btScalar(0.5);
-
- // Rij is R1'*R2, i.e. the relative rotation between R1 and R2
- R11 = dDOT44(R1+0,R2+0); R12 = dDOT44(R1+0,R2+1); R13 = dDOT44(R1+0,R2+2);
- R21 = dDOT44(R1+1,R2+0); R22 = dDOT44(R1+1,R2+1); R23 = dDOT44(R1+1,R2+2);
- R31 = dDOT44(R1+2,R2+0); R32 = dDOT44(R1+2,R2+1); R33 = dDOT44(R1+2,R2+2);
-
- Q11 = btFabs(R11); Q12 = btFabs(R12); Q13 = btFabs(R13);
- Q21 = btFabs(R21); Q22 = btFabs(R22); Q23 = btFabs(R23);
- Q31 = btFabs(R31); Q32 = btFabs(R32); Q33 = btFabs(R33);
-
- // for all 15 possible separating axes:
- // * see if the axis separates the boxes. if so, return 0.
- // * find the depth of the penetration along the separating axis (s2)
- // * if this is the largest depth so far, record it.
- // the normal vector will be set to the separating axis with the smallest
- // depth. note: normalR is set to point to a column of R1 or R2 if that is
- // the smallest depth normal so far. otherwise normalR is 0 and normalC is
- // set to a vector relative to body 1. invert_normal is 1 if the sign of
- // the normal should be flipped.
-
-#define TST(expr1,expr2,norm,cc) \
- s2 = btFabs(expr1) - (expr2); \
- if (s2 > 0) return 0; \
- if (s2 > s) { \
- s = s2; \
- normalR = norm; \
- invert_normal = ((expr1) < 0); \
- code = (cc); \
- }
-
- s = -dInfinity;
- invert_normal = 0;
- code = 0;
-
- // separating axis = u1,u2,u3
- TST (pp[0],(A[0] + B[0]*Q11 + B[1]*Q12 + B[2]*Q13),R1+0,1);
- TST (pp[1],(A[1] + B[0]*Q21 + B[1]*Q22 + B[2]*Q23),R1+1,2);
- TST (pp[2],(A[2] + B[0]*Q31 + B[1]*Q32 + B[2]*Q33),R1+2,3);
-
- // separating axis = v1,v2,v3
- TST (dDOT41(R2+0,p),(A[0]*Q11 + A[1]*Q21 + A[2]*Q31 + B[0]),R2+0,4);
- TST (dDOT41(R2+1,p),(A[0]*Q12 + A[1]*Q22 + A[2]*Q32 + B[1]),R2+1,5);
- TST (dDOT41(R2+2,p),(A[0]*Q13 + A[1]*Q23 + A[2]*Q33 + B[2]),R2+2,6);
-
- // note: cross product axes need to be scaled when s is computed.
- // normal (n1,n2,n3) is relative to box 1.
-#undef TST
-#define TST(expr1,expr2,n1,n2,n3,cc) \
- s2 = btFabs(expr1) - (expr2); \
- if (s2 > 0) return 0; \
- l = btSqrt((n1)*(n1) + (n2)*(n2) + (n3)*(n3)); \
- if (l > 0) { \
- s2 /= l; \
- if (s2*fudge_factor > s) { \
- s = s2; \
- normalR = 0; \
- normalC[0] = (n1)/l; normalC[1] = (n2)/l; normalC[2] = (n3)/l; \
- invert_normal = ((expr1) < 0); \
- code = (cc); \
- } \
- }
-
- // separating axis = u1 x (v1,v2,v3)
- TST(pp[2]*R21-pp[1]*R31,(A[1]*Q31+A[2]*Q21+B[1]*Q13+B[2]*Q12),0,-R31,R21,7);
- TST(pp[2]*R22-pp[1]*R32,(A[1]*Q32+A[2]*Q22+B[0]*Q13+B[2]*Q11),0,-R32,R22,8);
- TST(pp[2]*R23-pp[1]*R33,(A[1]*Q33+A[2]*Q23+B[0]*Q12+B[1]*Q11),0,-R33,R23,9);
-
- // separating axis = u2 x (v1,v2,v3)
- TST(pp[0]*R31-pp[2]*R11,(A[0]*Q31+A[2]*Q11+B[1]*Q23+B[2]*Q22),R31,0,-R11,10);
- TST(pp[0]*R32-pp[2]*R12,(A[0]*Q32+A[2]*Q12+B[0]*Q23+B[2]*Q21),R32,0,-R12,11);
- TST(pp[0]*R33-pp[2]*R13,(A[0]*Q33+A[2]*Q13+B[0]*Q22+B[1]*Q21),R33,0,-R13,12);
-
- // separating axis = u3 x (v1,v2,v3)
- TST(pp[1]*R11-pp[0]*R21,(A[0]*Q21+A[1]*Q11+B[1]*Q33+B[2]*Q32),-R21,R11,0,13);
- TST(pp[1]*R12-pp[0]*R22,(A[0]*Q22+A[1]*Q12+B[0]*Q33+B[2]*Q31),-R22,R12,0,14);
- TST(pp[1]*R13-pp[0]*R23,(A[0]*Q23+A[1]*Q13+B[0]*Q32+B[1]*Q31),-R23,R13,0,15);
-
-#undef TST
-
- if (!code) return 0;
-
- // if we get to this point, the boxes interpenetrate. compute the normal
- // in global coordinates.
- if (normalR) {
- normal[0] = normalR[0];
- normal[1] = normalR[4];
- normal[2] = normalR[8];
- }
- else {
- dMULTIPLY0_331 (normal,R1,normalC);
- }
- if (invert_normal) {
- normal[0] = -normal[0];
- normal[1] = -normal[1];
- normal[2] = -normal[2];
- }
- *depth = -s;
-
- // compute contact point(s)
-
- if (code > 6) {
- // an edge from box 1 touches an edge from box 2.
- // find a point pa on the intersecting edge of box 1
- btVector3 pa;
- btScalar sign;
- for (i=0; i<3; i++) pa[i] = p1[i];
- for (j=0; j<3; j++) {
- sign = (dDOT14(normal,R1+j) > 0) ? btScalar(1.0) : btScalar(-1.0);
- for (i=0; i<3; i++) pa[i] += sign * A[j] * R1[i*4+j];
- }
-
- // find a point pb on the intersecting edge of box 2
- btVector3 pb;
- for (i=0; i<3; i++) pb[i] = p2[i];
- for (j=0; j<3; j++) {
- sign = (dDOT14(normal,R2+j) > 0) ? btScalar(-1.0) : btScalar(1.0);
- for (i=0; i<3; i++) pb[i] += sign * B[j] * R2[i*4+j];
- }
-
- btScalar alpha,beta;
- btVector3 ua,ub;
- for (i=0; i<3; i++) ua[i] = R1[((code)-7)/3 + i*4];
- for (i=0; i<3; i++) ub[i] = R2[((code)-7)%3 + i*4];
-
- dLineClosestApproach (pa,ua,pb,ub,&alpha,&beta);
- for (i=0; i<3; i++) pa[i] += ua[i]*alpha;
- for (i=0; i<3; i++) pb[i] += ub[i]*beta;
-
- {
-
- //contact[0].pos[i] = btScalar(0.5)*(pa[i]+pb[i]);
- //contact[0].depth = *depth;
- btVector3 pointInWorld;
-
-#ifdef USE_CENTER_POINT
- for (i=0; i<3; i++)
- pointInWorld[i] = (pa[i]+pb[i])*btScalar(0.5);
- output.addContactPoint(-normal,pointInWorld,-*depth);
-#else
- output.addContactPoint(-normal,pb,-*depth);
-#endif //
- *return_code = code;
- }
- return 1;
- }
-
- // okay, we have a face-something intersection (because the separating
- // axis is perpendicular to a face). define face 'a' to be the reference
- // face (i.e. the normal vector is perpendicular to this) and face 'b' to be
- // the incident face (the closest face of the other box).
-
- const btScalar *Ra,*Rb,*pa,*pb,*Sa,*Sb;
- if (code <= 3) {
- Ra = R1;
- Rb = R2;
- pa = p1;
- pb = p2;
- Sa = A;
- Sb = B;
- }
- else {
- Ra = R2;
- Rb = R1;
- pa = p2;
- pb = p1;
- Sa = B;
- Sb = A;
- }
-
- // nr = normal vector of reference face dotted with axes of incident box.
- // anr = absolute values of nr.
- btVector3 normal2,nr,anr;
- if (code <= 3) {
- normal2[0] = normal[0];
- normal2[1] = normal[1];
- normal2[2] = normal[2];
- }
- else {
- normal2[0] = -normal[0];
- normal2[1] = -normal[1];
- normal2[2] = -normal[2];
- }
- dMULTIPLY1_331 (nr,Rb,normal2);
- anr[0] = btFabs (nr[0]);
- anr[1] = btFabs (nr[1]);
- anr[2] = btFabs (nr[2]);
-
- // find the largest compontent of anr: this corresponds to the normal
- // for the indident face. the other axis numbers of the indicent face
- // are stored in a1,a2.
- int lanr,a1,a2;
- if (anr[1] > anr[0]) {
- if (anr[1] > anr[2]) {
- a1 = 0;
- lanr = 1;
- a2 = 2;
- }
- else {
- a1 = 0;
- a2 = 1;
- lanr = 2;
- }
- }
- else {
- if (anr[0] > anr[2]) {
- lanr = 0;
- a1 = 1;
- a2 = 2;
- }
- else {
- a1 = 0;
- a2 = 1;
- lanr = 2;
- }
- }
-
- // compute center point of incident face, in reference-face coordinates
- btVector3 center;
- if (nr[lanr] < 0) {
- for (i=0; i<3; i++) center[i] = pb[i] - pa[i] + Sb[lanr] * Rb[i*4+lanr];
- }
- else {
- for (i=0; i<3; i++) center[i] = pb[i] - pa[i] - Sb[lanr] * Rb[i*4+lanr];
- }
-
- // find the normal and non-normal axis numbers of the reference box
- int codeN,code1,code2;
- if (code <= 3) codeN = code-1; else codeN = code-4;
- if (codeN==0) {
- code1 = 1;
- code2 = 2;
- }
- else if (codeN==1) {
- code1 = 0;
- code2 = 2;
- }
- else {
- code1 = 0;
- code2 = 1;
- }
-
- // find the four corners of the incident face, in reference-face coordinates
- btScalar quad[8]; // 2D coordinate of incident face (x,y pairs)
- btScalar c1,c2,m11,m12,m21,m22;
- c1 = dDOT14 (center,Ra+code1);
- c2 = dDOT14 (center,Ra+code2);
- // optimize this? - we have already computed this data above, but it is not
- // stored in an easy-to-index format. for now it's quicker just to recompute
- // the four dot products.
- m11 = dDOT44 (Ra+code1,Rb+a1);
- m12 = dDOT44 (Ra+code1,Rb+a2);
- m21 = dDOT44 (Ra+code2,Rb+a1);
- m22 = dDOT44 (Ra+code2,Rb+a2);
- {
- btScalar k1 = m11*Sb[a1];
- btScalar k2 = m21*Sb[a1];
- btScalar k3 = m12*Sb[a2];
- btScalar k4 = m22*Sb[a2];
- quad[0] = c1 - k1 - k3;
- quad[1] = c2 - k2 - k4;
- quad[2] = c1 - k1 + k3;
- quad[3] = c2 - k2 + k4;
- quad[4] = c1 + k1 + k3;
- quad[5] = c2 + k2 + k4;
- quad[6] = c1 + k1 - k3;
- quad[7] = c2 + k2 - k4;
- }
-
- // find the size of the reference face
- btScalar rect[2];
- rect[0] = Sa[code1];
- rect[1] = Sa[code2];
-
- // intersect the incident and reference faces
- btScalar ret[16];
- int n = intersectRectQuad2 (rect,quad,ret);
- if (n < 1) return 0; // this should never happen
-
- // convert the intersection points into reference-face coordinates,
- // and compute the contact position and depth for each point. only keep
- // those points that have a positive (penetrating) depth. delete points in
- // the 'ret' array as necessary so that 'point' and 'ret' correspond.
- btScalar point[3*8]; // penetrating contact points
- btScalar dep[8]; // depths for those points
- btScalar det1 = 1.f/(m11*m22 - m12*m21);
- m11 *= det1;
- m12 *= det1;
- m21 *= det1;
- m22 *= det1;
- int cnum = 0; // number of penetrating contact points found
- for (j=0; j < n; j++) {
- btScalar k1 = m22*(ret[j*2]-c1) - m12*(ret[j*2+1]-c2);
- btScalar k2 = -m21*(ret[j*2]-c1) + m11*(ret[j*2+1]-c2);
- for (i=0; i<3; i++) point[cnum*3+i] =
- center[i] + k1*Rb[i*4+a1] + k2*Rb[i*4+a2];
- dep[cnum] = Sa[codeN] - dDOT(normal2,point+cnum*3);
- if (dep[cnum] >= 0) {
- ret[cnum*2] = ret[j*2];
- ret[cnum*2+1] = ret[j*2+1];
- cnum++;
- }
- }
- if (cnum < 1) return 0; // this should never happen
-
- // we can't generate more contacts than we actually have
- if (maxc > cnum) maxc = cnum;
- if (maxc < 1) maxc = 1;
-
- if (cnum <= maxc) {
- // we have less contacts than we need, so we use them all
- for (j=0; j < cnum; j++) {
-
- //AddContactPoint...
-
- //dContactGeom *con = CONTACT(contact,skip*j);
- //for (i=0; i<3; i++) con->pos[i] = point[j*3+i] + pa[i];
- //con->depth = dep[j];
-
- btVector3 pointInWorld;
- for (i=0; i<3; i++)
- pointInWorld[i] = point[j*3+i] + pa[i];
- output.addContactPoint(-normal,pointInWorld,-dep[j]);
-
- }
- }
- else {
- // we have more contacts than are wanted, some of them must be culled.
- // find the deepest point, it is always the first contact.
- int i1 = 0;
- btScalar maxdepth = dep[0];
- for (i=1; i<cnum; i++) {
- if (dep[i] > maxdepth) {
- maxdepth = dep[i];
- i1 = i;
- }
- }
-
- int iret[8];
- cullPoints2 (cnum,ret,maxc,i1,iret);
-
- for (j=0; j < maxc; j++) {
-// dContactGeom *con = CONTACT(contact,skip*j);
- // for (i=0; i<3; i++) con->pos[i] = point[iret[j]*3+i] + pa[i];
- // con->depth = dep[iret[j]];
-
- btVector3 posInWorld;
- for (i=0; i<3; i++)
- posInWorld[i] = point[iret[j]*3+i] + pa[i];
- output.addContactPoint(-normal,posInWorld,-dep[iret[j]]);
- }
- cnum = maxc;
- }
-
- *return_code = code;
- return cnum;
-}
-
-void btBoxBoxDetector::getClosestPoints(const ClosestPointInput& input,Result& output,class btIDebugDraw* /*debugDraw*/,bool /*swapResults*/)
-{
-
- const btTransform& transformA = input.m_transformA;
- const btTransform& transformB = input.m_transformB;
-
- int skip = 0;
- dContactGeom *contact = 0;
-
- dMatrix3 R1;
- dMatrix3 R2;
-
- for (int j=0;j<3;j++)
- {
- R1[0+4*j] = transformA.getBasis()[j].x();
- R2[0+4*j] = transformB.getBasis()[j].x();
-
- R1[1+4*j] = transformA.getBasis()[j].y();
- R2[1+4*j] = transformB.getBasis()[j].y();
-
-
- R1[2+4*j] = transformA.getBasis()[j].z();
- R2[2+4*j] = transformB.getBasis()[j].z();
-
- }
-
-
-
- btVector3 normal;
- btScalar depth;
- int return_code;
- int maxc = 4;
-
-
- dBoxBox2 (transformA.getOrigin(),
- R1,
- 2.f*m_box1->getHalfExtentsWithMargin(),
- transformB.getOrigin(),
- R2,
- 2.f*m_box2->getHalfExtentsWithMargin(),
- normal, &depth, &return_code,
- maxc, contact, skip,
- output
- );
-
-}
diff --git a/extern/bullet2/src/BulletCollision/CollisionDispatch/btBoxBoxDetector.h b/extern/bullet2/src/BulletCollision/CollisionDispatch/btBoxBoxDetector.h
deleted file mode 100644
index 605294d47bd..00000000000
--- a/extern/bullet2/src/BulletCollision/CollisionDispatch/btBoxBoxDetector.h
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * Box-Box collision detection re-distributed under the ZLib license with permission from Russell L. Smith
- * Original version is from Open Dynamics Engine, Copyright (C) 2001,2002 Russell L. Smith.
- * All rights reserved. Email: russ@q12.org Web: www.q12.org
-
-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 BOX_BOX_DETECTOR_H
-#define BOX_BOX_DETECTOR_H
-
-
-class btBoxShape;
-#include "BulletCollision/NarrowPhaseCollision/btDiscreteCollisionDetectorInterface.h"
-
-
-/// btBoxBoxDetector wraps the ODE box-box collision detector
-/// re-distributed under the Zlib license with permission from Russell L. Smith
-struct btBoxBoxDetector : public btDiscreteCollisionDetectorInterface
-{
- btBoxShape* m_box1;
- btBoxShape* m_box2;
-
-public:
-
- btBoxBoxDetector(btBoxShape* box1,btBoxShape* box2);
-
- virtual ~btBoxBoxDetector() {};
-
- virtual void getClosestPoints(const ClosestPointInput& input,Result& output,class btIDebugDraw* debugDraw,bool swapResults=false);
-
-};
-
-#endif //BT_BOX_BOX_DETECTOR_H
diff --git a/extern/bullet2/src/BulletCollision/CollisionDispatch/btCollisionConfiguration.h b/extern/bullet2/src/BulletCollision/CollisionDispatch/btCollisionConfiguration.h
deleted file mode 100644
index fad770ac26d..00000000000
--- a/extern/bullet2/src/BulletCollision/CollisionDispatch/btCollisionConfiguration.h
+++ /dev/null
@@ -1,47 +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.
-*/
-
-#ifndef BT_COLLISION_CONFIGURATION
-#define BT_COLLISION_CONFIGURATION
-struct btCollisionAlgorithmCreateFunc;
-
-class btStackAlloc;
-class btPoolAllocator;
-
-///btCollisionConfiguration allows to configure Bullet collision detection
-///stack allocator size, default collision algorithms and persistent manifold pool size
-///todo: describe the meaning
-class btCollisionConfiguration
-{
-
-public:
-
- virtual ~btCollisionConfiguration()
- {
- }
-
- ///memory pools
- virtual btPoolAllocator* getPersistentManifoldPool() = 0;
-
- virtual btPoolAllocator* getCollisionAlgorithmPool() = 0;
-
- virtual btStackAlloc* getStackAllocator() = 0;
-
- virtual btCollisionAlgorithmCreateFunc* getCollisionAlgorithmCreateFunc(int proxyType0,int proxyType1) =0;
-
-};
-
-#endif //BT_COLLISION_CONFIGURATION
-
diff --git a/extern/bullet2/src/BulletCollision/CollisionDispatch/btConvexPlaneCollisionAlgorithm.cpp b/extern/bullet2/src/BulletCollision/CollisionDispatch/btConvexPlaneCollisionAlgorithm.cpp
deleted file mode 100644
index 391cf6c7bc4..00000000000
--- a/extern/bullet2/src/BulletCollision/CollisionDispatch/btConvexPlaneCollisionAlgorithm.cpp
+++ /dev/null
@@ -1,108 +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.
-*/
-
-#include "btConvexPlaneCollisionAlgorithm.h"
-
-#include "BulletCollision/CollisionDispatch/btCollisionDispatcher.h"
-#include "BulletCollision/CollisionDispatch/btCollisionObject.h"
-#include "BulletCollision/CollisionShapes/btConvexShape.h"
-#include "BulletCollision/CollisionShapes/btStaticPlaneShape.h"
-
-//#include <stdio.h>
-
-btConvexPlaneCollisionAlgorithm::btConvexPlaneCollisionAlgorithm(btPersistentManifold* mf,const btCollisionAlgorithmConstructionInfo& ci,btCollisionObject* col0,btCollisionObject* col1, bool isSwapped)
-: btCollisionAlgorithm(ci),
-m_ownManifold(false),
-m_manifoldPtr(mf),
-m_isSwapped(isSwapped)
-{
- btCollisionObject* convexObj = m_isSwapped? col1 : col0;
- btCollisionObject* planeObj = m_isSwapped? col0 : col1;
-
- if (!m_manifoldPtr && m_dispatcher->needsCollision(convexObj,planeObj))
- {
- m_manifoldPtr = m_dispatcher->getNewManifold(convexObj,planeObj);
- m_ownManifold = true;
- }
-}
-
-
-btConvexPlaneCollisionAlgorithm::~btConvexPlaneCollisionAlgorithm()
-{
- if (m_ownManifold)
- {
- if (m_manifoldPtr)
- m_dispatcher->releaseManifold(m_manifoldPtr);
- }
-}
-
-
-
-void btConvexPlaneCollisionAlgorithm::processCollision (btCollisionObject* body0,btCollisionObject* body1,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut)
-{
- (void)dispatchInfo;
- (void)resultOut;
- if (!m_manifoldPtr)
- return;
-
- btCollisionObject* convexObj = m_isSwapped? body1 : body0;
- btCollisionObject* planeObj = m_isSwapped? body0: body1;
-
- btConvexShape* convexShape = (btConvexShape*) convexObj->getCollisionShape();
- btStaticPlaneShape* planeShape = (btStaticPlaneShape*) planeObj->getCollisionShape();
-
- bool hasCollision = false;
- const btVector3& planeNormal = planeShape->getPlaneNormal();
- const btScalar& planeConstant = planeShape->getPlaneConstant();
- btTransform planeInConvex;
- planeInConvex= convexObj->getWorldTransform().inverse() * planeObj->getWorldTransform();
- btTransform convexInPlaneTrans;
- convexInPlaneTrans= planeObj->getWorldTransform().inverse() * convexObj->getWorldTransform();
-
- btVector3 vtx = convexShape->localGetSupportingVertex(planeInConvex.getBasis()*-planeNormal);
- btVector3 vtxInPlane = convexInPlaneTrans(vtx);
- btScalar distance = (planeNormal.dot(vtxInPlane) - planeConstant);
-
- btVector3 vtxInPlaneProjected = vtxInPlane - distance*planeNormal;
- btVector3 vtxInPlaneWorld = planeObj->getWorldTransform() * vtxInPlaneProjected;
-
- hasCollision = distance < m_manifoldPtr->getContactBreakingThreshold();
- resultOut->setPersistentManifold(m_manifoldPtr);
- if (hasCollision)
- {
- /// report a contact. internally this will be kept persistent, and contact reduction is done
- btVector3 normalOnSurfaceB = planeObj->getWorldTransform().getBasis() * planeNormal;
- btVector3 pOnB = vtxInPlaneWorld;
- resultOut->addContactPoint(normalOnSurfaceB,pOnB,distance);
- }
- if (m_ownManifold)
- {
- if (m_manifoldPtr->getNumContacts())
- {
- resultOut->refreshContactPoints();
- }
- }
-}
-
-btScalar btConvexPlaneCollisionAlgorithm::calculateTimeOfImpact(btCollisionObject* col0,btCollisionObject* col1,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut)
-{
- (void)resultOut;
- (void)dispatchInfo;
- (void)col0;
- (void)col1;
-
- //not yet
- return btScalar(1.);
-}
diff --git a/extern/bullet2/src/BulletCollision/CollisionDispatch/btConvexPlaneCollisionAlgorithm.h b/extern/bullet2/src/BulletCollision/CollisionDispatch/btConvexPlaneCollisionAlgorithm.h
deleted file mode 100644
index 7b258554171..00000000000
--- a/extern/bullet2/src/BulletCollision/CollisionDispatch/btConvexPlaneCollisionAlgorithm.h
+++ /dev/null
@@ -1,71 +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.
-*/
-
-#ifndef CONVEX_PLANE_COLLISION_ALGORITHM_H
-#define CONVEX_PLANE_COLLISION_ALGORITHM_H
-
-#include "BulletCollision/BroadphaseCollision/btCollisionAlgorithm.h"
-#include "BulletCollision/BroadphaseCollision/btBroadphaseProxy.h"
-#include "BulletCollision/CollisionDispatch/btCollisionCreateFunc.h"
-class btPersistentManifold;
-#include "btCollisionDispatcher.h"
-
-#include "LinearMath/btVector3.h"
-
-/// btSphereBoxCollisionAlgorithm provides sphere-box collision detection.
-/// Other features are frame-coherency (persistent data) and collision response.
-class btConvexPlaneCollisionAlgorithm : public btCollisionAlgorithm
-{
- bool m_ownManifold;
- btPersistentManifold* m_manifoldPtr;
- bool m_isSwapped;
-
-public:
-
- btConvexPlaneCollisionAlgorithm(btPersistentManifold* mf,const btCollisionAlgorithmConstructionInfo& ci,btCollisionObject* col0,btCollisionObject* col1, bool isSwapped);
-
- virtual ~btConvexPlaneCollisionAlgorithm();
-
- virtual void processCollision (btCollisionObject* body0,btCollisionObject* body1,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut);
-
- virtual btScalar calculateTimeOfImpact(btCollisionObject* body0,btCollisionObject* body1,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut);
-
- virtual void getAllContactManifolds(btManifoldArray& manifoldArray)
- {
- if (m_manifoldPtr && m_ownManifold)
- {
- manifoldArray.push_back(m_manifoldPtr);
- }
- }
-
- struct CreateFunc :public btCollisionAlgorithmCreateFunc
- {
- virtual btCollisionAlgorithm* CreateCollisionAlgorithm(btCollisionAlgorithmConstructionInfo& ci, btCollisionObject* body0,btCollisionObject* body1)
- {
- void* mem = ci.m_dispatcher1->allocateCollisionAlgorithm(sizeof(btConvexPlaneCollisionAlgorithm));
- if (!m_swapped)
- {
- return new(mem) btConvexPlaneCollisionAlgorithm(0,ci,body0,body1,false);
- } else
- {
- return new(mem) btConvexPlaneCollisionAlgorithm(0,ci,body0,body1,true);
- }
- }
- };
-
-};
-
-#endif //CONVEX_PLANE_COLLISION_ALGORITHM_H
-
diff --git a/extern/bullet2/src/BulletCollision/CollisionDispatch/btDefaultCollisionConfiguration.cpp b/extern/bullet2/src/BulletCollision/CollisionDispatch/btDefaultCollisionConfiguration.cpp
deleted file mode 100644
index 1c317080544..00000000000
--- a/extern/bullet2/src/BulletCollision/CollisionDispatch/btDefaultCollisionConfiguration.cpp
+++ /dev/null
@@ -1,291 +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.
-*/
-
-#include "btDefaultCollisionConfiguration.h"
-
-#include "BulletCollision/CollisionDispatch/btConvexConvexAlgorithm.h"
-#include "BulletCollision/CollisionDispatch/btEmptyCollisionAlgorithm.h"
-#include "BulletCollision/CollisionDispatch/btConvexConcaveCollisionAlgorithm.h"
-#include "BulletCollision/CollisionDispatch/btCompoundCollisionAlgorithm.h"
-#include "BulletCollision/CollisionDispatch/btConvexPlaneCollisionAlgorithm.h"
-#include "BulletCollision/CollisionDispatch/btBoxBoxCollisionAlgorithm.h"
-#include "BulletCollision/CollisionDispatch/btSphereSphereCollisionAlgorithm.h"
-#ifdef USE_BUGGY_SPHERE_BOX_ALGORITHM
-#include "BulletCollision/CollisionDispatch/btSphereBoxCollisionAlgorithm.h"
-#endif //USE_BUGGY_SPHERE_BOX_ALGORITHM
-#include "BulletCollision/CollisionDispatch/btSphereTriangleCollisionAlgorithm.h"
-#include "BulletCollision/NarrowPhaseCollision/btGjkEpaPenetrationDepthSolver.h"
-#include "BulletCollision/NarrowPhaseCollision/btMinkowskiPenetrationDepthSolver.h"
-#include "BulletCollision/NarrowPhaseCollision/btVoronoiSimplexSolver.h"
-
-
-
-#include "LinearMath/btStackAlloc.h"
-#include "LinearMath/btPoolAllocator.h"
-
-
-
-
-
-btDefaultCollisionConfiguration::btDefaultCollisionConfiguration(const btDefaultCollisionConstructionInfo& constructionInfo)
-//btDefaultCollisionConfiguration::btDefaultCollisionConfiguration(btStackAlloc* stackAlloc,btPoolAllocator* persistentManifoldPool,btPoolAllocator* collisionAlgorithmPool)
-{
-
- void* mem = btAlignedAlloc(sizeof(btVoronoiSimplexSolver),16);
- m_simplexSolver = new (mem)btVoronoiSimplexSolver();
-
-#define USE_EPA 1
-#ifdef USE_EPA
- mem = btAlignedAlloc(sizeof(btGjkEpaPenetrationDepthSolver),16);
- m_pdSolver = new (mem)btGjkEpaPenetrationDepthSolver;
-#else
- mem = btAlignedAlloc(sizeof(btMinkowskiPenetrationDepthSolver),16);
- m_pdSolver = new (mem)btMinkowskiPenetrationDepthSolver;
-#endif//USE_EPA
-
-
- //default CreationFunctions, filling the m_doubleDispatch table
- mem = btAlignedAlloc(sizeof(btConvexConvexAlgorithm::CreateFunc),16);
- m_convexConvexCreateFunc = new(mem) btConvexConvexAlgorithm::CreateFunc(m_simplexSolver,m_pdSolver);
- mem = btAlignedAlloc(sizeof(btConvexConcaveCollisionAlgorithm::CreateFunc),16);
- m_convexConcaveCreateFunc = new (mem)btConvexConcaveCollisionAlgorithm::CreateFunc;
- mem = btAlignedAlloc(sizeof(btConvexConcaveCollisionAlgorithm::CreateFunc),16);
- m_swappedConvexConcaveCreateFunc = new (mem)btConvexConcaveCollisionAlgorithm::SwappedCreateFunc;
- mem = btAlignedAlloc(sizeof(btCompoundCollisionAlgorithm::CreateFunc),16);
- m_compoundCreateFunc = new (mem)btCompoundCollisionAlgorithm::CreateFunc;
- mem = btAlignedAlloc(sizeof(btCompoundCollisionAlgorithm::SwappedCreateFunc),16);
- m_swappedCompoundCreateFunc = new (mem)btCompoundCollisionAlgorithm::SwappedCreateFunc;
- mem = btAlignedAlloc(sizeof(btEmptyAlgorithm::CreateFunc),16);
- m_emptyCreateFunc = new(mem) btEmptyAlgorithm::CreateFunc;
-
- mem = btAlignedAlloc(sizeof(btSphereSphereCollisionAlgorithm::CreateFunc),16);
- m_sphereSphereCF = new(mem) btSphereSphereCollisionAlgorithm::CreateFunc;
-#ifdef USE_BUGGY_SPHERE_BOX_ALGORITHM
- mem = btAlignedAlloc(sizeof(btSphereBoxCollisionAlgorithm::CreateFunc),16);
- m_sphereBoxCF = new(mem) btSphereBoxCollisionAlgorithm::CreateFunc;
- mem = btAlignedAlloc(sizeof(btSphereBoxCollisionAlgorithm::CreateFunc),16);
- m_boxSphereCF = new (mem)btSphereBoxCollisionAlgorithm::CreateFunc;
- m_boxSphereCF->m_swapped = true;
-#endif //USE_BUGGY_SPHERE_BOX_ALGORITHM
-
- mem = btAlignedAlloc(sizeof(btSphereTriangleCollisionAlgorithm::CreateFunc),16);
- m_sphereTriangleCF = new (mem)btSphereTriangleCollisionAlgorithm::CreateFunc;
- mem = btAlignedAlloc(sizeof(btSphereTriangleCollisionAlgorithm::CreateFunc),16);
- m_triangleSphereCF = new (mem)btSphereTriangleCollisionAlgorithm::CreateFunc;
- m_triangleSphereCF->m_swapped = true;
-
- mem = btAlignedAlloc(sizeof(btBoxBoxCollisionAlgorithm::CreateFunc),16);
- m_boxBoxCF = new(mem)btBoxBoxCollisionAlgorithm::CreateFunc;
-
- //convex versus plane
- mem = btAlignedAlloc (sizeof(btConvexPlaneCollisionAlgorithm::CreateFunc),16);
- m_convexPlaneCF = new (mem) btConvexPlaneCollisionAlgorithm::CreateFunc;
- mem = btAlignedAlloc (sizeof(btConvexPlaneCollisionAlgorithm::CreateFunc),16);
- m_planeConvexCF = new (mem) btConvexPlaneCollisionAlgorithm::CreateFunc;
- m_planeConvexCF->m_swapped = true;
-
- ///calculate maximum element size, big enough to fit any collision algorithm in the memory pool
- int maxSize = sizeof(btConvexConvexAlgorithm);
- int maxSize2 = sizeof(btConvexConcaveCollisionAlgorithm);
- int maxSize3 = sizeof(btCompoundCollisionAlgorithm);
- int maxSize4 = sizeof(btEmptyAlgorithm);
-
- int collisionAlgorithmMaxElementSize = btMax(maxSize,maxSize2);
- collisionAlgorithmMaxElementSize = btMax(collisionAlgorithmMaxElementSize,maxSize3);
- collisionAlgorithmMaxElementSize = btMax(collisionAlgorithmMaxElementSize,maxSize4);
-
- if (constructionInfo.m_stackAlloc)
- {
- m_ownsStackAllocator = false;
- this->m_stackAlloc = constructionInfo.m_stackAlloc;
- } else
- {
- m_ownsStackAllocator = true;
- void* mem = btAlignedAlloc(sizeof(btStackAlloc),16);
- m_stackAlloc = new(mem)btStackAlloc(constructionInfo.m_defaultStackAllocatorSize);
- }
-
- if (constructionInfo.m_persistentManifoldPool)
- {
- m_ownsPersistentManifoldPool = false;
- m_persistentManifoldPool = constructionInfo.m_persistentManifoldPool;
- } else
- {
- m_ownsPersistentManifoldPool = true;
- void* mem = btAlignedAlloc(sizeof(btPoolAllocator),16);
- m_persistentManifoldPool = new (mem) btPoolAllocator(sizeof(btPersistentManifold),constructionInfo.m_defaultMaxPersistentManifoldPoolSize);
- }
-
- if (constructionInfo.m_collisionAlgorithmPool)
- {
- m_ownsCollisionAlgorithmPool = false;
- m_collisionAlgorithmPool = constructionInfo.m_collisionAlgorithmPool;
- } else
- {
- m_ownsCollisionAlgorithmPool = true;
- void* mem = btAlignedAlloc(sizeof(btPoolAllocator),16);
- m_collisionAlgorithmPool = new(mem) btPoolAllocator(collisionAlgorithmMaxElementSize,constructionInfo.m_defaultMaxCollisionAlgorithmPoolSize);
- }
-
-
-}
-
-btDefaultCollisionConfiguration::~btDefaultCollisionConfiguration()
-{
- if (m_ownsStackAllocator)
- {
- m_stackAlloc->destroy();
- m_stackAlloc->~btStackAlloc();
- btAlignedFree(m_stackAlloc);
- }
- if (m_ownsCollisionAlgorithmPool)
- {
- m_collisionAlgorithmPool->~btPoolAllocator();
- btAlignedFree(m_collisionAlgorithmPool);
- }
- if (m_ownsPersistentManifoldPool)
- {
- m_persistentManifoldPool->~btPoolAllocator();
- btAlignedFree(m_persistentManifoldPool);
- }
-
- m_convexConvexCreateFunc->~btCollisionAlgorithmCreateFunc();
- btAlignedFree( m_convexConvexCreateFunc);
-
- m_convexConcaveCreateFunc->~btCollisionAlgorithmCreateFunc();
- btAlignedFree( m_convexConcaveCreateFunc);
- m_swappedConvexConcaveCreateFunc->~btCollisionAlgorithmCreateFunc();
- btAlignedFree( m_swappedConvexConcaveCreateFunc);
-
- m_compoundCreateFunc->~btCollisionAlgorithmCreateFunc();
- btAlignedFree( m_compoundCreateFunc);
-
- m_swappedCompoundCreateFunc->~btCollisionAlgorithmCreateFunc();
- btAlignedFree( m_swappedCompoundCreateFunc);
-
- m_emptyCreateFunc->~btCollisionAlgorithmCreateFunc();
- btAlignedFree( m_emptyCreateFunc);
-
- m_sphereSphereCF->~btCollisionAlgorithmCreateFunc();
- btAlignedFree( m_sphereSphereCF);
-
-#ifdef USE_BUGGY_SPHERE_BOX_ALGORITHM
- m_sphereBoxCF->~btCollisionAlgorithmCreateFunc();
- btAlignedFree( m_sphereBoxCF);
- m_boxSphereCF->~btCollisionAlgorithmCreateFunc();
- btAlignedFree( m_boxSphereCF);
-#endif //USE_BUGGY_SPHERE_BOX_ALGORITHM
-
- m_sphereTriangleCF->~btCollisionAlgorithmCreateFunc();
- btAlignedFree( m_sphereTriangleCF);
- m_triangleSphereCF->~btCollisionAlgorithmCreateFunc();
- btAlignedFree( m_triangleSphereCF);
- m_boxBoxCF->~btCollisionAlgorithmCreateFunc();
- btAlignedFree( m_boxBoxCF);
-
- m_convexPlaneCF->~btCollisionAlgorithmCreateFunc();
- btAlignedFree( m_convexPlaneCF);
- m_planeConvexCF->~btCollisionAlgorithmCreateFunc();
- btAlignedFree( m_planeConvexCF);
-
- m_simplexSolver->~btVoronoiSimplexSolver();
- btAlignedFree(m_simplexSolver);
-
- m_pdSolver->~btConvexPenetrationDepthSolver();
-
- btAlignedFree(m_pdSolver);
-
-
-}
-
-
-btCollisionAlgorithmCreateFunc* btDefaultCollisionConfiguration::getCollisionAlgorithmCreateFunc(int proxyType0,int proxyType1)
-{
-
-
-
- if ((proxyType0 == SPHERE_SHAPE_PROXYTYPE) && (proxyType1==SPHERE_SHAPE_PROXYTYPE))
- {
- return m_sphereSphereCF;
- }
-#ifdef USE_BUGGY_SPHERE_BOX_ALGORITHM
- if ((proxyType0 == SPHERE_SHAPE_PROXYTYPE) && (proxyType1==BOX_SHAPE_PROXYTYPE))
- {
- return m_sphereBoxCF;
- }
-
- if ((proxyType0 == BOX_SHAPE_PROXYTYPE ) && (proxyType1==SPHERE_SHAPE_PROXYTYPE))
- {
- return m_boxSphereCF;
- }
-#endif //USE_BUGGY_SPHERE_BOX_ALGORITHM
-
-
- if ((proxyType0 == SPHERE_SHAPE_PROXYTYPE ) && (proxyType1==TRIANGLE_SHAPE_PROXYTYPE))
- {
- return m_sphereTriangleCF;
- }
-
- if ((proxyType0 == TRIANGLE_SHAPE_PROXYTYPE ) && (proxyType1==SPHERE_SHAPE_PROXYTYPE))
- {
- return m_triangleSphereCF;
- }
-
- if ((proxyType0 == BOX_SHAPE_PROXYTYPE) && (proxyType1 == BOX_SHAPE_PROXYTYPE))
- {
- return m_boxBoxCF;
- }
-
- if (btBroadphaseProxy::isConvex(proxyType0) && (proxyType1 == STATIC_PLANE_PROXYTYPE))
- {
- return m_convexPlaneCF;
- }
-
- if (btBroadphaseProxy::isConvex(proxyType1) && (proxyType0 == STATIC_PLANE_PROXYTYPE))
- {
- return m_planeConvexCF;
- }
-
-
-
- if (btBroadphaseProxy::isConvex(proxyType0) && btBroadphaseProxy::isConvex(proxyType1))
- {
- return m_convexConvexCreateFunc;
- }
-
- if (btBroadphaseProxy::isConvex(proxyType0) && btBroadphaseProxy::isConcave(proxyType1))
- {
- return m_convexConcaveCreateFunc;
- }
-
- if (btBroadphaseProxy::isConvex(proxyType1) && btBroadphaseProxy::isConcave(proxyType0))
- {
- return m_swappedConvexConcaveCreateFunc;
- }
-
- if (btBroadphaseProxy::isCompound(proxyType0))
- {
- return m_compoundCreateFunc;
- } else
- {
- if (btBroadphaseProxy::isCompound(proxyType1))
- {
- return m_swappedCompoundCreateFunc;
- }
- }
-
- //failed to find an algorithm
- return m_emptyCreateFunc;
-}
diff --git a/extern/bullet2/src/BulletCollision/CollisionDispatch/btDefaultCollisionConfiguration.h b/extern/bullet2/src/BulletCollision/CollisionDispatch/btDefaultCollisionConfiguration.h
deleted file mode 100644
index df48ee95a18..00000000000
--- a/extern/bullet2/src/BulletCollision/CollisionDispatch/btDefaultCollisionConfiguration.h
+++ /dev/null
@@ -1,118 +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.
-*/
-
-#ifndef BT_DEFAULT_COLLISION_CONFIGURATION
-#define BT_DEFAULT_COLLISION_CONFIGURATION
-
-#include "btCollisionConfiguration.h"
-class btVoronoiSimplexSolver;
-class btConvexPenetrationDepthSolver;
-
-struct btDefaultCollisionConstructionInfo
-{
- btStackAlloc* m_stackAlloc;
- btPoolAllocator* m_persistentManifoldPool;
- btPoolAllocator* m_collisionAlgorithmPool;
- int m_defaultMaxPersistentManifoldPoolSize;
- int m_defaultMaxCollisionAlgorithmPoolSize;
- int m_defaultStackAllocatorSize;
-
- btDefaultCollisionConstructionInfo()
- :m_stackAlloc(0),
- m_persistentManifoldPool(0),
- m_collisionAlgorithmPool(0),
- m_defaultMaxPersistentManifoldPoolSize(65535),
- m_defaultMaxCollisionAlgorithmPoolSize(65535),
- m_defaultStackAllocatorSize(5*1024*1024)
- {
- }
-};
-
-
-
-///btCollisionConfiguration allows to configure Bullet collision detection
-///stack allocator, pool memory allocators
-///todo: describe the meaning
-class btDefaultCollisionConfiguration : public btCollisionConfiguration
-{
-
-protected:
-
- int m_persistentManifoldPoolSize;
-
- btStackAlloc* m_stackAlloc;
- bool m_ownsStackAllocator;
-
- btPoolAllocator* m_persistentManifoldPool;
- bool m_ownsPersistentManifoldPool;
-
-
- btPoolAllocator* m_collisionAlgorithmPool;
- bool m_ownsCollisionAlgorithmPool;
-
- //default simplex/penetration depth solvers
- btVoronoiSimplexSolver* m_simplexSolver;
- btConvexPenetrationDepthSolver* m_pdSolver;
-
- //default CreationFunctions, filling the m_doubleDispatch table
- btCollisionAlgorithmCreateFunc* m_convexConvexCreateFunc;
- btCollisionAlgorithmCreateFunc* m_convexConcaveCreateFunc;
- btCollisionAlgorithmCreateFunc* m_swappedConvexConcaveCreateFunc;
- btCollisionAlgorithmCreateFunc* m_compoundCreateFunc;
- btCollisionAlgorithmCreateFunc* m_swappedCompoundCreateFunc;
- btCollisionAlgorithmCreateFunc* m_emptyCreateFunc;
- btCollisionAlgorithmCreateFunc* m_sphereSphereCF;
-#ifdef USE_BUGGY_SPHERE_BOX_ALGORITHM
- btCollisionAlgorithmCreateFunc* m_sphereBoxCF;
- btCollisionAlgorithmCreateFunc* m_boxSphereCF;
-#endif //USE_BUGGY_SPHERE_BOX_ALGORITHM
-
- btCollisionAlgorithmCreateFunc* m_boxBoxCF;
- btCollisionAlgorithmCreateFunc* m_sphereTriangleCF;
- btCollisionAlgorithmCreateFunc* m_triangleSphereCF;
- btCollisionAlgorithmCreateFunc* m_planeConvexCF;
- btCollisionAlgorithmCreateFunc* m_convexPlaneCF;
-
-public:
-
-
- btDefaultCollisionConfiguration(const btDefaultCollisionConstructionInfo& constructionInfo = btDefaultCollisionConstructionInfo());
-
- virtual ~btDefaultCollisionConfiguration();
-
- ///memory pools
- virtual btPoolAllocator* getPersistentManifoldPool()
- {
- return m_persistentManifoldPool;
- }
-
- virtual btPoolAllocator* getCollisionAlgorithmPool()
- {
- return m_collisionAlgorithmPool;
- }
-
- virtual btStackAlloc* getStackAllocator()
- {
- return m_stackAlloc;
- }
-
-
- virtual btCollisionAlgorithmCreateFunc* getCollisionAlgorithmCreateFunc(int proxyType0,int proxyType1);
-
-
-};
-
-#endif //BT_DEFAULT_COLLISION_CONFIGURATION
-
diff --git a/extern/bullet2/src/BulletCollision/CollisionShapes/btConvexInternalShape.cpp b/extern/bullet2/src/BulletCollision/CollisionShapes/btConvexInternalShape.cpp
deleted file mode 100644
index fb81c8a5bde..00000000000
--- a/extern/bullet2/src/BulletCollision/CollisionShapes/btConvexInternalShape.cpp
+++ /dev/null
@@ -1,78 +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.
-*/
-
-
-#include "btConvexInternalShape.h"
-
-
-btConvexInternalShape::btConvexInternalShape()
-: m_localScaling(btScalar(1.),btScalar(1.),btScalar(1.)),
-m_collisionMargin(CONVEX_DISTANCE_MARGIN)
-{
-}
-
-
-void btConvexInternalShape::setLocalScaling(const btVector3& scaling)
-{
- m_localScaling = scaling.absolute();
-}
-
-
-
-void btConvexInternalShape::getAabbSlow(const btTransform& trans,btVector3&minAabb,btVector3&maxAabb) const
-{
-
- btScalar margin = getMargin();
- for (int i=0;i<3;i++)
- {
- btVector3 vec(btScalar(0.),btScalar(0.),btScalar(0.));
- vec[i] = btScalar(1.);
-
- btVector3 sv = localGetSupportingVertex(vec*trans.getBasis());
-
- btVector3 tmp = trans(sv);
- maxAabb[i] = tmp[i]+margin;
- vec[i] = btScalar(-1.);
- tmp = trans(localGetSupportingVertex(vec*trans.getBasis()));
- minAabb[i] = tmp[i]-margin;
- }
-};
-
-
-btVector3 btConvexInternalShape::localGetSupportingVertex(const btVector3& vec)const
-{
-#ifndef __SPU__
-
- btVector3 supVertex = localGetSupportingVertexWithoutMargin(vec);
-
- if ( getMargin()!=btScalar(0.) )
- {
- btVector3 vecnorm = vec;
- if (vecnorm .length2() < (SIMD_EPSILON*SIMD_EPSILON))
- {
- vecnorm.setValue(btScalar(-1.),btScalar(-1.),btScalar(-1.));
- }
- vecnorm.normalize();
- supVertex+= getMargin() * vecnorm;
- }
- return supVertex;
-
-#else
- return btVector3(0,0,0);
-#endif //__SPU__
-
- }
-
-
diff --git a/extern/bullet2/src/BulletCollision/CollisionShapes/btConvexInternalShape.h b/extern/bullet2/src/BulletCollision/CollisionShapes/btConvexInternalShape.h
deleted file mode 100644
index 9388ccf31f2..00000000000
--- a/extern/bullet2/src/BulletCollision/CollisionShapes/btConvexInternalShape.h
+++ /dev/null
@@ -1,98 +0,0 @@
-
-#ifndef BT_CONVEX_INTERNAL_SHAPE_H
-#define BT_CONVEX_INTERNAL_SHAPE_H
-
-#include "btConvexShape.h"
-
-///The btConvexInternalShape is an internal base class, shared by most convex shape implementations.
-class btConvexInternalShape : public btConvexShape
-{
-
- protected:
-
- //local scaling. collisionMargin is not scaled !
- btVector3 m_localScaling;
-
- btVector3 m_implicitShapeDimensions;
-
- btScalar m_collisionMargin;
-
- btScalar m_padding;
-
-public:
-
- btConvexInternalShape();
-
- virtual ~btConvexInternalShape()
- {
-
- }
-
-
- virtual btVector3 localGetSupportingVertex(const btVector3& vec)const;
-#ifndef __SPU__
- virtual btVector3 localGetSupportingVertexWithoutMargin(const btVector3& vec) const= 0;
-
- //notice that the vectors should be unit length
- virtual void batchedUnitVectorGetSupportingVertexWithoutMargin(const btVector3* vectors,btVector3* supportVerticesOut,int numVectors) const= 0;
-#endif //#ifndef __SPU__
-
- const btVector3& getImplicitShapeDimensions() const
- {
- return m_implicitShapeDimensions;
- }
-
- ///getAabb's default implementation is brute force, expected derived classes to implement a fast dedicated version
- void getAabb(const btTransform& t,btVector3& aabbMin,btVector3& aabbMax) const
- {
- getAabbSlow(t,aabbMin,aabbMax);
- }
-
-
-
- virtual void getAabbSlow(const btTransform& t,btVector3& aabbMin,btVector3& aabbMax) const;
-
-
- virtual void setLocalScaling(const btVector3& scaling);
- virtual const btVector3& getLocalScaling() const
- {
- return m_localScaling;
- }
-
- const btVector3& getLocalScalingNV() const
- {
- return m_localScaling;
- }
-
- virtual void setMargin(btScalar margin)
- {
- m_collisionMargin = margin;
- }
- virtual btScalar getMargin() const
- {
- return m_collisionMargin;
- }
-
- btScalar getMarginNV() const
- {
- return m_collisionMargin;
- }
-
- virtual int getNumPreferredPenetrationDirections() const
- {
- return 0;
- }
-
- virtual void getPreferredPenetrationDirection(int index, btVector3& penetrationVector) const
- {
- (void)penetrationVector;
- (void)index;
- btAssert(0);
- }
-
-
-
-};
-
-
-#endif //BT_CONVEX_INTERNAL_SHAPE_H
diff --git a/extern/bullet2/src/BulletCollision/CollisionShapes/btMaterial.h b/extern/bullet2/src/BulletCollision/CollisionShapes/btMaterial.h
deleted file mode 100644
index 7cb6d5ab6fe..00000000000
--- a/extern/bullet2/src/BulletCollision/CollisionShapes/btMaterial.h
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
-Bullet Continuous Collision Detection and Physics Library
-Copyright (c) 2003-2008 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.
-*/
-
-/// This file was created by Alex Silverman
-
-#ifndef MATERIAL_H
-#define MATERIAL_H
-
-// Material class to be used by btMultimaterialTriangleMeshShape to store triangle properties
-class btMaterial
-{
- // public members so that materials can change due to world events
-public:
- btScalar m_friction;
- btScalar m_restitution;
- int pad[2];
-
- btMaterial(){}
- btMaterial(btScalar fric, btScalar rest) { m_friction = fric; m_restitution = rest; }
-};
-
-#endif // MATERIAL_H \ No newline at end of file
diff --git a/extern/bullet2/src/BulletCollision/CollisionShapes/btMultimaterialTriangleMeshShape.cpp b/extern/bullet2/src/BulletCollision/CollisionShapes/btMultimaterialTriangleMeshShape.cpp
deleted file mode 100644
index fc47e86411d..00000000000
--- a/extern/bullet2/src/BulletCollision/CollisionShapes/btMultimaterialTriangleMeshShape.cpp
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
-Bullet Continuous Collision Detection and Physics Library
-Copyright (c) 2003-2008 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.
-*/
-
-/// This file was created by Alex Silverman
-
-#include "BulletCollision/CollisionShapes/btMultimaterialTriangleMeshShape.h"
-#include "BulletCollision/CollisionShapes/btTriangleIndexVertexMaterialArray.h"
-//#include "BulletCollision/CollisionShapes/btOptimizedBvh.h"
-
-
-///Obtains the material for a specific triangle
-const btMaterial * btMultimaterialTriangleMeshShape::getMaterialProperties(int partID, int triIndex)
-{
- const unsigned char * materialBase = 0;
- int numMaterials;
- PHY_ScalarType materialType;
- int materialStride;
- const unsigned char * triangleMaterialBase = 0;
- int numTriangles;
- int triangleMaterialStride;
- PHY_ScalarType triangleType;
-
- ((btTriangleIndexVertexMaterialArray*)m_meshInterface)->getLockedReadOnlyMaterialBase(&materialBase, numMaterials, materialType, materialStride,
- &triangleMaterialBase, numTriangles, triangleMaterialStride, triangleType, partID);
-
- // return the pointer to the place with the friction for the triangle
- // TODO: This depends on whether it's a moving mesh or not
- // BUG IN GIMPACT
- //return (btScalar*)(&materialBase[triangleMaterialBase[(triIndex-1) * triangleMaterialStride] * materialStride]);
- int * matInd = (int *)(&(triangleMaterialBase[(triIndex * triangleMaterialStride)]));
- btMaterial *matVal = (btMaterial *)(&(materialBase[*matInd * materialStride]));
- return (matVal);
-}
diff --git a/extern/bullet2/src/BulletCollision/CollisionShapes/btMultimaterialTriangleMeshShape.h b/extern/bullet2/src/BulletCollision/CollisionShapes/btMultimaterialTriangleMeshShape.h
deleted file mode 100644
index 2f108020cdf..00000000000
--- a/extern/bullet2/src/BulletCollision/CollisionShapes/btMultimaterialTriangleMeshShape.h
+++ /dev/null
@@ -1,124 +0,0 @@
-/*
-Bullet Continuous Collision Detection and Physics Library
-Copyright (c) 2003-2008 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.
-*/
-
-/// This file was created by Alex Silverman
-
-#ifndef BVH_TRIANGLE_MATERIAL_MESH_SHAPE_H
-#define BVH_TRIANGLE_MATERIAL_MESH_SHAPE_H
-
-#include "btBvhTriangleMeshShape.h"
-#include "btMaterial.h"
-
-///The BvhTriangleMaterialMeshShape extends the btBvhTriangleMeshShape. Its main contribution is the interface into a material array, which allows per-triangle friction and restitution.
-ATTRIBUTE_ALIGNED16(class) btMultimaterialTriangleMeshShape : public btBvhTriangleMeshShape
-{
- btAlignedObjectArray <btMaterial*> m_materialList;
- int ** m_triangleMaterials;
-
-public:
-
- BT_DECLARE_ALIGNED_ALLOCATOR();
-
- btMultimaterialTriangleMeshShape(): btBvhTriangleMeshShape() {}
- btMultimaterialTriangleMeshShape(btStridingMeshInterface* meshInterface, bool useQuantizedAabbCompression, bool buildBvh = true):
- btBvhTriangleMeshShape(meshInterface, useQuantizedAabbCompression, buildBvh)
- {
- btVector3 m_triangle[3];
- const unsigned char *vertexbase;
- int numverts;
- PHY_ScalarType type;
- int stride;
- const unsigned char *indexbase;
- int indexstride;
- int numfaces;
- PHY_ScalarType indicestype;
-
- //m_materialLookup = (int**)(btAlignedAlloc(sizeof(int*) * meshInterface->getNumSubParts(), 16));
-
- for(int i = 0; i < meshInterface->getNumSubParts(); i++)
- {
- m_meshInterface->getLockedReadOnlyVertexIndexBase(
- &vertexbase,
- numverts,
- type,
- stride,
- &indexbase,
- indexstride,
- numfaces,
- indicestype,
- i);
- //m_materialLookup[i] = (int*)(btAlignedAlloc(sizeof(int) * numfaces, 16));
- }
- }
-
- ///optionally pass in a larger bvh aabb, used for quantization. This allows for deformations within this aabb
- btMultimaterialTriangleMeshShape(btStridingMeshInterface* meshInterface, bool useQuantizedAabbCompression,const btVector3& bvhAabbMin,const btVector3& bvhAabbMax, bool buildBvh = true):
- btBvhTriangleMeshShape(meshInterface, useQuantizedAabbCompression, bvhAabbMin, bvhAabbMax, buildBvh)
- {
- btVector3 m_triangle[3];
- const unsigned char *vertexbase;
- int numverts;
- PHY_ScalarType type;
- int stride;
- const unsigned char *indexbase;
- int indexstride;
- int numfaces;
- PHY_ScalarType indicestype;
-
- //m_materialLookup = (int**)(btAlignedAlloc(sizeof(int*) * meshInterface->getNumSubParts(), 16));
-
- for(int i = 0; i < meshInterface->getNumSubParts(); i++)
- {
- m_meshInterface->getLockedReadOnlyVertexIndexBase(
- &vertexbase,
- numverts,
- type,
- stride,
- &indexbase,
- indexstride,
- numfaces,
- indicestype,
- i);
- //m_materialLookup[i] = (int*)(btAlignedAlloc(sizeof(int) * numfaces * 2, 16));
- }
- }
-
- virtual ~btMultimaterialTriangleMeshShape()
- {
-/*
- for(int i = 0; i < m_meshInterface->getNumSubParts(); i++)
- {
- btAlignedFree(m_materialValues[i]);
- m_materialLookup[i] = NULL;
- }
- btAlignedFree(m_materialValues);
- m_materialLookup = NULL;
-*/
- }
- virtual int getShapeType() const
- {
- return MULTIMATERIAL_TRIANGLE_MESH_PROXYTYPE;
- }
-
- //debugging
- virtual const char* getName()const {return "MULTIMATERIALTRIANGLEMESH";}
-
- ///Obtains the material for a specific triangle
- const btMaterial * getMaterialProperties(int partID, int triIndex);
-
-}
-;
-
-#endif //BVH_TRIANGLE_MATERIAL_MESH_SHAPE_H
diff --git a/extern/bullet2/src/BulletCollision/CollisionShapes/btScaledBvhTriangleMeshShape.cpp b/extern/bullet2/src/BulletCollision/CollisionShapes/btScaledBvhTriangleMeshShape.cpp
deleted file mode 100644
index 2b81a02b557..00000000000
--- a/extern/bullet2/src/BulletCollision/CollisionShapes/btScaledBvhTriangleMeshShape.cpp
+++ /dev/null
@@ -1,121 +0,0 @@
-/*
-Bullet Continuous Collision Detection and Physics Library
-Copyright (c) 2003-2008 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 "btScaledBvhTriangleMeshShape.h"
-
-btScaledBvhTriangleMeshShape::btScaledBvhTriangleMeshShape(btBvhTriangleMeshShape* childShape,btVector3 localScaling)
-:m_bvhTriMeshShape(childShape),
-m_localScaling(localScaling)
-{
-
-}
-
-btScaledBvhTriangleMeshShape::~btScaledBvhTriangleMeshShape()
-{
-}
-
-
-class btScaledTriangleCallback : public btTriangleCallback
-{
- btTriangleCallback* m_originalCallback;
-
- btVector3 m_localScaling;
-
-public:
-
- btScaledTriangleCallback(btTriangleCallback* originalCallback,btVector3 localScaling)
- :m_originalCallback(originalCallback),
- m_localScaling(localScaling)
- {
- }
-
- virtual void processTriangle(btVector3* triangle, int partId, int triangleIndex)
- {
- btVector3 newTriangle[3];
- newTriangle[0] = triangle[0]*m_localScaling;
- newTriangle[1] = triangle[1]*m_localScaling;
- newTriangle[2] = triangle[2]*m_localScaling;
- m_originalCallback->processTriangle(&newTriangle[0],partId,triangleIndex);
- }
-};
-
-void btScaledBvhTriangleMeshShape::processAllTriangles(btTriangleCallback* callback,const btVector3& aabbMin,const btVector3& aabbMax) const
-{
- btScaledTriangleCallback scaledCallback(callback,m_localScaling);
-
- btVector3 invLocalScaling(1.f/m_localScaling.getX(),1.f/m_localScaling.getY(),1.f/m_localScaling.getZ());
- btVector3 scaledAabbMin,scaledAabbMax;
-
- ///support negative scaling
- scaledAabbMin[0] = m_localScaling.getX() >= 0. ? aabbMin[0] * invLocalScaling[0] : aabbMax[0] * invLocalScaling[0];
- scaledAabbMin[1] = m_localScaling.getY() >= 0. ? aabbMin[1] * invLocalScaling[1] : aabbMax[1] * invLocalScaling[1];
- scaledAabbMin[2] = m_localScaling.getZ() >= 0. ? aabbMin[2] * invLocalScaling[2] : aabbMax[2] * invLocalScaling[2];
-
- scaledAabbMax[0] = m_localScaling.getX() <= 0. ? aabbMin[0] * invLocalScaling[0] : aabbMax[0] * invLocalScaling[0];
- scaledAabbMax[1] = m_localScaling.getY() <= 0. ? aabbMin[1] * invLocalScaling[1] : aabbMax[1] * invLocalScaling[1];
- scaledAabbMax[2] = m_localScaling.getZ() <= 0. ? aabbMin[2] * invLocalScaling[2] : aabbMax[2] * invLocalScaling[2];
-
-
- m_bvhTriMeshShape->processAllTriangles(&scaledCallback,scaledAabbMin,scaledAabbMax);
-}
-
-
-void btScaledBvhTriangleMeshShape::getAabb(const btTransform& trans,btVector3& aabbMin,btVector3& aabbMax) const
-{
- btVector3 localAabbMin = m_bvhTriMeshShape->getLocalAabbMin();
- btVector3 localAabbMax = m_bvhTriMeshShape->getLocalAabbMax();
-
- btVector3 tmpLocalAabbMin = localAabbMin * m_localScaling;
- btVector3 tmpLocalAabbMax = localAabbMax * m_localScaling;
-
- localAabbMin[0] = (m_localScaling.getX() >= 0.) ? tmpLocalAabbMin[0] : tmpLocalAabbMax[0];
- localAabbMin[1] = (m_localScaling.getY() >= 0.) ? tmpLocalAabbMin[1] : tmpLocalAabbMax[1];
- localAabbMin[2] = (m_localScaling.getZ() >= 0.) ? tmpLocalAabbMin[2] : tmpLocalAabbMax[2];
- localAabbMax[0] = (m_localScaling.getX() <= 0.) ? tmpLocalAabbMin[0] : tmpLocalAabbMax[0];
- localAabbMax[1] = (m_localScaling.getY() <= 0.) ? tmpLocalAabbMin[1] : tmpLocalAabbMax[1];
- localAabbMax[2] = (m_localScaling.getZ() <= 0.) ? tmpLocalAabbMin[2] : tmpLocalAabbMax[2];
-
- btVector3 localHalfExtents = btScalar(0.5)*(localAabbMax-localAabbMin);
- btScalar margin = m_bvhTriMeshShape->getMargin();
- localHalfExtents += btVector3(margin,margin,margin);
- btVector3 localCenter = btScalar(0.5)*(localAabbMax+localAabbMin);
-
- btMatrix3x3 abs_b = trans.getBasis().absolute();
-
- btPoint3 center = trans(localCenter);
-
- btVector3 extent = btVector3(abs_b[0].dot(localHalfExtents),
- abs_b[1].dot(localHalfExtents),
- abs_b[2].dot(localHalfExtents));
- aabbMin = center - extent;
- aabbMax = center + extent;
-
-}
-
-void btScaledBvhTriangleMeshShape::setLocalScaling(const btVector3& scaling)
-{
- m_localScaling = scaling;
-}
-
-const btVector3& btScaledBvhTriangleMeshShape::getLocalScaling() const
-{
- return m_localScaling;
-}
-
-void btScaledBvhTriangleMeshShape::calculateLocalInertia(btScalar mass,btVector3& inertia) const
-{
- ///don't make this a movable object!
-// btAssert(0);
-}
diff --git a/extern/bullet2/src/BulletCollision/CollisionShapes/btScaledBvhTriangleMeshShape.h b/extern/bullet2/src/BulletCollision/CollisionShapes/btScaledBvhTriangleMeshShape.h
deleted file mode 100644
index 0a1ef8ce5cb..00000000000
--- a/extern/bullet2/src/BulletCollision/CollisionShapes/btScaledBvhTriangleMeshShape.h
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
-Bullet Continuous Collision Detection and Physics Library
-Copyright (c) 2003-2008 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 SCALED_BVH_TRIANGLE_MESH_SHAPE_H
-#define SCALED_BVH_TRIANGLE_MESH_SHAPE_H
-
-#include "BulletCollision/CollisionShapes/btBvhTriangleMeshShape.h"
-
-
-///The btScaledBvhTriangleMeshShape allows to instance a scaled version of an existing btBvhTriangleMeshShape.
-///Note that each btBvhTriangleMeshShape still can have its own local scaling, independent from this btScaledBvhTriangleMeshShape 'localScaling'
-ATTRIBUTE_ALIGNED16(class) btScaledBvhTriangleMeshShape : public btConcaveShape
-{
-
-
- btVector3 m_localScaling;
-
- btBvhTriangleMeshShape* m_bvhTriMeshShape;
-
-public:
-
-
- btScaledBvhTriangleMeshShape(btBvhTriangleMeshShape* childShape,btVector3 localScaling);
-
- virtual ~btScaledBvhTriangleMeshShape();
-
- virtual int getShapeType() const
- {
- //use un-used 'FAST_CONCAVE_MESH_PROXYTYPE' for now, later add SCALED_TRIANGLE_MESH_SHAPE_PROXYTYPE to btBroadphaseProxy.h
- return SCALED_TRIANGLE_MESH_SHAPE_PROXYTYPE;
- }
-
- virtual void getAabb(const btTransform& t,btVector3& aabbMin,btVector3& aabbMax) const;
- virtual void setLocalScaling(const btVector3& scaling);
- virtual const btVector3& getLocalScaling() const;
- virtual void calculateLocalInertia(btScalar mass,btVector3& inertia) const;
-
- virtual void processAllTriangles(btTriangleCallback* callback,const btVector3& aabbMin,const btVector3& aabbMax) const;
-
- btBvhTriangleMeshShape* getChildShape()
- {
- return m_bvhTriMeshShape;
- }
-
- const btBvhTriangleMeshShape* getChildShape() const
- {
- return m_bvhTriMeshShape;
- }
-
- //debugging
- virtual const char* getName()const {return "SCALEDBVHTRIANGLEMESH";}
-
-};
-
-#endif //BVH_TRIANGLE_MESH_SHAPE_H
diff --git a/extern/bullet2/src/BulletCollision/CollisionShapes/btShapeHull.cpp b/extern/bullet2/src/BulletCollision/CollisionShapes/btShapeHull.cpp
deleted file mode 100644
index a87b87f1a6f..00000000000
--- a/extern/bullet2/src/BulletCollision/CollisionShapes/btShapeHull.cpp
+++ /dev/null
@@ -1,164 +0,0 @@
-/*
-btbtShapeHull implemented by John McCutchan.
-
-Bullet Continuous Collision Detection and Physics Library
-Copyright (c) 2003-2008 Erwin Coumans http://bulletphysics.com
-
-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 "btShapeHull.h"
-#include "LinearMath/btConvexHull.h"
-
-#define NUM_UNITSPHERE_POINTS 42
-
-static btVector3 btUnitSpherePoints[NUM_UNITSPHERE_POINTS+MAX_PREFERRED_PENETRATION_DIRECTIONS*2] =
-{
- btVector3(btScalar(0.000000) , btScalar(-0.000000),btScalar(-1.000000)),
- btVector3(btScalar(0.723608) , btScalar(-0.525725),btScalar(-0.447219)),
- btVector3(btScalar(-0.276388) , btScalar(-0.850649),btScalar(-0.447219)),
- btVector3(btScalar(-0.894426) , btScalar(-0.000000),btScalar(-0.447216)),
- btVector3(btScalar(-0.276388) , btScalar(0.850649),btScalar(-0.447220)),
- btVector3(btScalar(0.723608) , btScalar(0.525725),btScalar(-0.447219)),
- btVector3(btScalar(0.276388) , btScalar(-0.850649),btScalar(0.447220)),
- btVector3(btScalar(-0.723608) , btScalar(-0.525725),btScalar(0.447219)),
- btVector3(btScalar(-0.723608) , btScalar(0.525725),btScalar(0.447219)),
- btVector3(btScalar(0.276388) , btScalar(0.850649),btScalar(0.447219)),
- btVector3(btScalar(0.894426) , btScalar(0.000000),btScalar(0.447216)),
- btVector3(btScalar(-0.000000) , btScalar(0.000000),btScalar(1.000000)),
- btVector3(btScalar(0.425323) , btScalar(-0.309011),btScalar(-0.850654)),
- btVector3(btScalar(-0.162456) , btScalar(-0.499995),btScalar(-0.850654)),
- btVector3(btScalar(0.262869) , btScalar(-0.809012),btScalar(-0.525738)),
- btVector3(btScalar(0.425323) , btScalar(0.309011),btScalar(-0.850654)),
- btVector3(btScalar(0.850648) , btScalar(-0.000000),btScalar(-0.525736)),
- btVector3(btScalar(-0.525730) , btScalar(-0.000000),btScalar(-0.850652)),
- btVector3(btScalar(-0.688190) , btScalar(-0.499997),btScalar(-0.525736)),
- btVector3(btScalar(-0.162456) , btScalar(0.499995),btScalar(-0.850654)),
- btVector3(btScalar(-0.688190) , btScalar(0.499997),btScalar(-0.525736)),
- btVector3(btScalar(0.262869) , btScalar(0.809012),btScalar(-0.525738)),
- btVector3(btScalar(0.951058) , btScalar(0.309013),btScalar(0.000000)),
- btVector3(btScalar(0.951058) , btScalar(-0.309013),btScalar(0.000000)),
- btVector3(btScalar(0.587786) , btScalar(-0.809017),btScalar(0.000000)),
- btVector3(btScalar(0.000000) , btScalar(-1.000000),btScalar(0.000000)),
- btVector3(btScalar(-0.587786) , btScalar(-0.809017),btScalar(0.000000)),
- btVector3(btScalar(-0.951058) , btScalar(-0.309013),btScalar(-0.000000)),
- btVector3(btScalar(-0.951058) , btScalar(0.309013),btScalar(-0.000000)),
- btVector3(btScalar(-0.587786) , btScalar(0.809017),btScalar(-0.000000)),
- btVector3(btScalar(-0.000000) , btScalar(1.000000),btScalar(-0.000000)),
- btVector3(btScalar(0.587786) , btScalar(0.809017),btScalar(-0.000000)),
- btVector3(btScalar(0.688190) , btScalar(-0.499997),btScalar(0.525736)),
- btVector3(btScalar(-0.262869) , btScalar(-0.809012),btScalar(0.525738)),
- btVector3(btScalar(-0.850648) , btScalar(0.000000),btScalar(0.525736)),
- btVector3(btScalar(-0.262869) , btScalar(0.809012),btScalar(0.525738)),
- btVector3(btScalar(0.688190) , btScalar(0.499997),btScalar(0.525736)),
- btVector3(btScalar(0.525730) , btScalar(0.000000),btScalar(0.850652)),
- btVector3(btScalar(0.162456) , btScalar(-0.499995),btScalar(0.850654)),
- btVector3(btScalar(-0.425323) , btScalar(-0.309011),btScalar(0.850654)),
- btVector3(btScalar(-0.425323) , btScalar(0.309011),btScalar(0.850654)),
- btVector3(btScalar(0.162456) , btScalar(0.499995),btScalar(0.850654))
-};
-
-btShapeHull::btShapeHull (const btConvexShape* shape)
-{
- m_shape = shape;
- m_vertices.clear ();
- m_indices.clear();
- m_numIndices = 0;
-}
-
-btShapeHull::~btShapeHull ()
-{
- m_indices.clear();
- m_vertices.clear ();
-}
-
-bool
-btShapeHull::buildHull (btScalar /*margin*/)
-{
- int numSampleDirections = NUM_UNITSPHERE_POINTS;
- {
- int numPDA = m_shape->getNumPreferredPenetrationDirections();
- if (numPDA)
- {
- for (int i=0;i<numPDA;i++)
- {
- btVector3 norm;
- m_shape->getPreferredPenetrationDirection(i,norm);
- btUnitSpherePoints[numSampleDirections] = norm;
- numSampleDirections++;
- }
- }
- }
-
- btVector3 supportPoints[NUM_UNITSPHERE_POINTS+MAX_PREFERRED_PENETRATION_DIRECTIONS*2];
- int i;
- for (i = 0; i < numSampleDirections; i++)
- {
- supportPoints[i] = m_shape->localGetSupportingVertex(btUnitSpherePoints[i]);
- }
-
- HullDesc hd;
- hd.mFlags = QF_TRIANGLES;
- hd.mVcount = static_cast<unsigned int>(numSampleDirections);
-
-#ifdef BT_USE_DOUBLE_PRECISION
- hd.mVertices = &supportPoints[0];
- hd.mVertexStride = sizeof(btVector3);
-#else
- hd.mVertices = &supportPoints[0];
- hd.mVertexStride = sizeof (btVector3);
-#endif
-
- HullLibrary hl;
- HullResult hr;
- if (hl.CreateConvexHull (hd, hr) == QE_FAIL)
- {
- return false;
- }
-
- m_vertices.resize (static_cast<int>(hr.mNumOutputVertices));
-
-
- for (i = 0; i < static_cast<int>(hr.mNumOutputVertices); i++)
- {
- m_vertices[i] = hr.m_OutputVertices[i];
- }
- m_numIndices = hr.mNumIndices;
- m_indices.resize(static_cast<int>(m_numIndices));
- for (i = 0; i < static_cast<int>(m_numIndices); i++)
- {
- m_indices[i] = hr.m_Indices[i];
- }
-
- // free temporary hull result that we just copied
- hl.ReleaseResult (hr);
-
- return true;
-}
-
-int
-btShapeHull::numTriangles () const
-{
- return static_cast<int>(m_numIndices / 3);
-}
-
-int
-btShapeHull::numVertices () const
-{
- return m_vertices.size ();
-}
-
-int
-btShapeHull::numIndices () const
-{
- return static_cast<int>(m_numIndices);
-}
-
diff --git a/extern/bullet2/src/BulletCollision/CollisionShapes/btShapeHull.h b/extern/bullet2/src/BulletCollision/CollisionShapes/btShapeHull.h
deleted file mode 100644
index 583c6b99eb6..00000000000
--- a/extern/bullet2/src/BulletCollision/CollisionShapes/btShapeHull.h
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
-btShapeHull implemented by John McCutchan.
-
-Bullet Continuous Collision Detection and Physics Library
-Copyright (c) 2003-2008 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 _SHAPE_HULL_H
-#define _SHAPE_HULL_H
-
-#include "LinearMath/btAlignedObjectArray.h"
-#include "BulletCollision/CollisionShapes/btConvexShape.h"
-
-
-///The btShapeHull class takes a btConvexShape, builds a simplified convex hull using btConvexHull and provides triangle indices and vertices.
-///It can be useful for to simplify a complex convex object and for visualization of a non-polyhedral convex object.
-///It approximates the convex hull using the supporting vertex of 42 directions.
-class btShapeHull
-{
-public:
- btShapeHull (const btConvexShape* shape);
- ~btShapeHull ();
-
- bool buildHull (btScalar margin);
-
- int numTriangles () const;
- int numVertices () const;
- int numIndices () const;
-
- const btVector3* getVertexPointer() const
- {
- return &m_vertices[0];
- }
- const unsigned int* getIndexPointer() const
- {
- return &m_indices[0];
- }
-
-protected:
- btAlignedObjectArray<btVector3> m_vertices;
- btAlignedObjectArray<unsigned int> m_indices;
- unsigned int m_numIndices;
- const btConvexShape* m_shape;
-};
-
-#endif //_SHAPE_HULL_H
diff --git a/extern/bullet2/src/BulletCollision/CollisionShapes/btTriangleIndexVertexMaterialArray.cpp b/extern/bullet2/src/BulletCollision/CollisionShapes/btTriangleIndexVertexMaterialArray.cpp
deleted file mode 100644
index 492854ff646..00000000000
--- a/extern/bullet2/src/BulletCollision/CollisionShapes/btTriangleIndexVertexMaterialArray.cpp
+++ /dev/null
@@ -1,86 +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.
-*/
-
-///This file was created by Alex Silverman
-
-#include "btTriangleIndexVertexMaterialArray.h"
-
-btTriangleIndexVertexMaterialArray::btTriangleIndexVertexMaterialArray(int numTriangles,int* triangleIndexBase,int triangleIndexStride,
- int numVertices,btScalar* vertexBase,int vertexStride,
- int numMaterials, unsigned char* materialBase, int materialStride,
- int* triangleMaterialsBase, int materialIndexStride) :
-btTriangleIndexVertexArray(numTriangles, triangleIndexBase, triangleIndexStride, numVertices, vertexBase, vertexStride)
-{
- btMaterialProperties mat;
-
- mat.m_numMaterials = numMaterials;
- mat.m_materialBase = materialBase;
- mat.m_materialStride = materialStride;
-#ifdef BT_USE_DOUBLE_PRECISION
- mat.m_materialType = PHY_DOUBLE;
-#else
- mat.m_materialType = PHY_FLOAT;
-#endif
-
- mat.m_numTriangles = numTriangles;
- mat.m_triangleMaterialsBase = (unsigned char *)triangleMaterialsBase;
- mat.m_triangleMaterialStride = materialIndexStride;
- mat.m_triangleType = PHY_INTEGER;
-
- addMaterialProperties(mat);
-}
-
-
-void btTriangleIndexVertexMaterialArray::getLockedMaterialBase(unsigned char **materialBase, int& numMaterials, PHY_ScalarType& materialType, int& materialStride,
- unsigned char ** triangleMaterialBase, int& numTriangles, int& triangleMaterialStride, PHY_ScalarType& triangleType, int subpart)
-{
- btAssert(subpart< getNumSubParts() );
-
- btMaterialProperties& mats = m_materials[subpart];
-
- numMaterials = mats.m_numMaterials;
- (*materialBase) = (unsigned char *) mats.m_materialBase;
-#ifdef BT_USE_DOUBLE_PRECISION
- materialType = PHY_DOUBLE;
-#else
- materialType = PHY_FLOAT;
-#endif
- materialStride = mats.m_materialStride;
-
- numTriangles = mats.m_numTriangles;
- (*triangleMaterialBase) = (unsigned char *)mats.m_triangleMaterialsBase;
- triangleMaterialStride = mats.m_triangleMaterialStride;
- triangleType = mats.m_triangleType;
-}
-
-void btTriangleIndexVertexMaterialArray::getLockedReadOnlyMaterialBase(const unsigned char **materialBase, int& numMaterials, PHY_ScalarType& materialType, int& materialStride,
- const unsigned char ** triangleMaterialBase, int& numTriangles, int& triangleMaterialStride, PHY_ScalarType& triangleType, int subpart)
-{
- btMaterialProperties& mats = m_materials[subpart];
-
- numMaterials = mats.m_numMaterials;
- (*materialBase) = (const unsigned char *) mats.m_materialBase;
-#ifdef BT_USE_DOUBLE_PRECISION
- materialType = PHY_DOUBLE;
-#else
- materialType = PHY_FLOAT;
-#endif
- materialStride = mats.m_materialStride;
-
- numTriangles = mats.m_numTriangles;
- (*triangleMaterialBase) = (const unsigned char *)mats.m_triangleMaterialsBase;
- triangleMaterialStride = mats.m_triangleMaterialStride;
- triangleType = mats.m_triangleType;
-}
diff --git a/extern/bullet2/src/BulletCollision/CollisionShapes/btTriangleIndexVertexMaterialArray.h b/extern/bullet2/src/BulletCollision/CollisionShapes/btTriangleIndexVertexMaterialArray.h
deleted file mode 100644
index 69a2e631458..00000000000
--- a/extern/bullet2/src/BulletCollision/CollisionShapes/btTriangleIndexVertexMaterialArray.h
+++ /dev/null
@@ -1,84 +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.
-*/
-
-///This file was created by Alex Silverman
-
-#ifndef BT_MULTIMATERIAL_TRIANGLE_INDEX_VERTEX_ARRAY_H
-#define BT_MULTIMATERIAL_TRIANGLE_INDEX_VERTEX_ARRAY_H
-
-#include "btTriangleIndexVertexArray.h"
-
-
-ATTRIBUTE_ALIGNED16( struct) btMaterialProperties
-{
- ///m_materialBase ==========> 2 btScalar values make up one material, friction then restitution
- int m_numMaterials;
- const unsigned char * m_materialBase;
- int m_materialStride;
- PHY_ScalarType m_materialType;
- ///m_numTriangles <=========== This exists in the btIndexedMesh object for the same subpart, but since we're
- /// padding the structure, it can be reproduced at no real cost
- ///m_triangleMaterials =====> 1 integer value makes up one entry
- /// eg: m_triangleMaterials[1] = 5; // This will set triangle 2 to use material 5
- int m_numTriangles;
- const unsigned char * m_triangleMaterialsBase;
- int m_triangleMaterialStride;
- ///m_triangleType <========== Automatically set in addMaterialProperties
- PHY_ScalarType m_triangleType;
-};
-
-typedef btAlignedObjectArray<btMaterialProperties> MaterialArray;
-
-///Teh btTriangleIndexVertexMaterialArray is built on TriangleIndexVertexArray
-///The addition of a material array allows for the utilization of the partID and
-///triangleIndex that are returned in the ContactAddedCallback. As with
-///TriangleIndexVertexArray, no duplicate is made of the material data, so it
-///is the users responsibility to maintain the array during the lifetime of the
-///TriangleIndexVertexMaterialArray.
-ATTRIBUTE_ALIGNED16(class) btTriangleIndexVertexMaterialArray : public btTriangleIndexVertexArray
-{
-protected:
- MaterialArray m_materials;
-
-public:
- BT_DECLARE_ALIGNED_ALLOCATOR();
-
- btTriangleIndexVertexMaterialArray()
- {
- }
-
- btTriangleIndexVertexMaterialArray(int numTriangles,int* triangleIndexBase,int triangleIndexStride,
- int numVertices,btScalar* vertexBase,int vertexStride,
- int numMaterials, unsigned char* materialBase, int materialStride,
- int* triangleMaterialsBase, int materialIndexStride);
-
- virtual ~btTriangleIndexVertexMaterialArray() {}
-
- void addMaterialProperties(const btMaterialProperties& mat, PHY_ScalarType triangleType = PHY_INTEGER)
- {
- m_materials.push_back(mat);
- m_materials[m_materials.size()-1].m_triangleType = triangleType;
- }
-
- virtual void getLockedMaterialBase(unsigned char **materialBase, int& numMaterials, PHY_ScalarType& materialType, int& materialStride,
- unsigned char ** triangleMaterialBase, int& numTriangles, int& triangleMaterialStride, PHY_ScalarType& triangleType ,int subpart = 0);
-
- virtual void getLockedReadOnlyMaterialBase(const unsigned char **materialBase, int& numMaterials, PHY_ScalarType& materialType, int& materialStride,
- const unsigned char ** triangleMaterialBase, int& numTriangles, int& triangleMaterialStride, PHY_ScalarType& triangleType, int subpart = 0);
-
-}
-;
-
-#endif //BT_MULTIMATERIAL_TRIANGLE_INDEX_VERTEX_ARRAY_H
diff --git a/extern/bullet2/src/BulletCollision/CollisionShapes/btUniformScalingShape.cpp b/extern/bullet2/src/BulletCollision/CollisionShapes/btUniformScalingShape.cpp
deleted file mode 100644
index ef340286cb0..00000000000
--- a/extern/bullet2/src/BulletCollision/CollisionShapes/btUniformScalingShape.cpp
+++ /dev/null
@@ -1,114 +0,0 @@
-/*
-Bullet Continuous Collision Detection and Physics Library
-Copyright (c) 2003-2007 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 "btUniformScalingShape.h"
-
-btUniformScalingShape::btUniformScalingShape( btConvexShape* convexChildShape,btScalar uniformScalingFactor):
-m_childConvexShape(convexChildShape),
-m_uniformScalingFactor(uniformScalingFactor)
-{
-}
-
-btUniformScalingShape::~btUniformScalingShape()
-{
-}
-
-
-btVector3 btUniformScalingShape::localGetSupportingVertexWithoutMargin(const btVector3& vec)const
-{
- btVector3 tmpVertex;
- tmpVertex = m_childConvexShape->localGetSupportingVertexWithoutMargin(vec);
- return tmpVertex*m_uniformScalingFactor;
-}
-
-void btUniformScalingShape::batchedUnitVectorGetSupportingVertexWithoutMargin(const btVector3* vectors,btVector3* supportVerticesOut,int numVectors) const
-{
- m_childConvexShape->batchedUnitVectorGetSupportingVertexWithoutMargin(vectors,supportVerticesOut,numVectors);
- int i;
- for (i=0;i<numVectors;i++)
- {
- supportVerticesOut[i] = supportVerticesOut[i] * m_uniformScalingFactor;
- }
-}
-
-
-btVector3 btUniformScalingShape::localGetSupportingVertex(const btVector3& vec)const
-{
- btVector3 tmpVertex;
- tmpVertex = m_childConvexShape->localGetSupportingVertex(vec);
- return tmpVertex*m_uniformScalingFactor;
-}
-
-
-void btUniformScalingShape::calculateLocalInertia(btScalar mass,btVector3& inertia) const
-{
-
- ///this linear upscaling is not realistic, but we don't deal with large mass ratios...
- btVector3 tmpInertia;
- m_childConvexShape->calculateLocalInertia(mass,tmpInertia);
- inertia = tmpInertia * m_uniformScalingFactor;
-}
-
-
- ///getAabb's default implementation is brute force, expected derived classes to implement a fast dedicated version
-void btUniformScalingShape::getAabb(const btTransform& t,btVector3& aabbMin,btVector3& aabbMax) const
-{
- m_childConvexShape->getAabb(t,aabbMin,aabbMax);
- btVector3 aabbCenter = (aabbMax+aabbMin)*btScalar(0.5);
- btVector3 scaledAabbHalfExtends = (aabbMax-aabbMin)*btScalar(0.5)*m_uniformScalingFactor;
-
- aabbMin = aabbCenter - scaledAabbHalfExtends;
- aabbMax = aabbCenter + scaledAabbHalfExtends;
-
-}
-
-void btUniformScalingShape::getAabbSlow(const btTransform& t,btVector3& aabbMin,btVector3& aabbMax) const
-{
- m_childConvexShape->getAabbSlow(t,aabbMin,aabbMax);
- btVector3 aabbCenter = (aabbMax+aabbMin)*btScalar(0.5);
- btVector3 scaledAabbHalfExtends = (aabbMax-aabbMin)*btScalar(0.5)*m_uniformScalingFactor;
-
- aabbMin = aabbCenter - scaledAabbHalfExtends;
- aabbMax = aabbCenter + scaledAabbHalfExtends;
-}
-
-void btUniformScalingShape::setLocalScaling(const btVector3& scaling)
-{
- m_childConvexShape->setLocalScaling(scaling);
-}
-
-const btVector3& btUniformScalingShape::getLocalScaling() const
-{
- return m_childConvexShape->getLocalScaling();
-}
-
-void btUniformScalingShape::setMargin(btScalar margin)
-{
- m_childConvexShape->setMargin(margin);
-}
-btScalar btUniformScalingShape::getMargin() const
-{
- return m_childConvexShape->getMargin() * m_uniformScalingFactor;
-}
-
-int btUniformScalingShape::getNumPreferredPenetrationDirections() const
-{
- return m_childConvexShape->getNumPreferredPenetrationDirections();
-}
-
-void btUniformScalingShape::getPreferredPenetrationDirection(int index, btVector3& penetrationVector) const
-{
- m_childConvexShape->getPreferredPenetrationDirection(index,penetrationVector);
-}
diff --git a/extern/bullet2/src/BulletCollision/CollisionShapes/btUniformScalingShape.h b/extern/bullet2/src/BulletCollision/CollisionShapes/btUniformScalingShape.h
deleted file mode 100644
index 1e17fc8e198..00000000000
--- a/extern/bullet2/src/BulletCollision/CollisionShapes/btUniformScalingShape.h
+++ /dev/null
@@ -1,88 +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.
-*/
-
-#ifndef BT_UNIFORM_SCALING_SHAPE_H
-#define BT_UNIFORM_SCALING_SHAPE_H
-
-#include "btConvexShape.h"
-#include "BulletCollision/BroadphaseCollision/btBroadphaseProxy.h" // for the types
-
-///The btUniformScalingShape allows to re-use uniform scaled instances of btConvexShape in a memory efficient way.
-///Istead of using btUniformScalingShape, it is better to use the non-uniform setLocalScaling method on convex shapes that implement it.
-class btUniformScalingShape : public btConvexShape
-{
- btConvexShape* m_childConvexShape;
-
- btScalar m_uniformScalingFactor;
-
- public:
-
- btUniformScalingShape( btConvexShape* convexChildShape, btScalar uniformScalingFactor);
-
- virtual ~btUniformScalingShape();
-
- virtual btVector3 localGetSupportingVertexWithoutMargin(const btVector3& vec)const;
-
- virtual btVector3 localGetSupportingVertex(const btVector3& vec)const;
-
- virtual void batchedUnitVectorGetSupportingVertexWithoutMargin(const btVector3* vectors,btVector3* supportVerticesOut,int numVectors) const;
-
- virtual void calculateLocalInertia(btScalar mass,btVector3& inertia) const;
-
- btScalar getUniformScalingFactor() const
- {
- return m_uniformScalingFactor;
- }
-
- btConvexShape* getChildShape()
- {
- return m_childConvexShape;
- }
-
- const btConvexShape* getChildShape() const
- {
- return m_childConvexShape;
- }
-
- virtual const char* getName()const
- {
- return "UniformScalingShape";
- }
-
- virtual int getShapeType() const { return UNIFORM_SCALING_SHAPE_PROXYTYPE; }
-
-
- ///////////////////////////
-
-
- ///getAabb's default implementation is brute force, expected derived classes to implement a fast dedicated version
- void getAabb(const btTransform& t,btVector3& aabbMin,btVector3& aabbMax) const;
-
- virtual void getAabbSlow(const btTransform& t,btVector3& aabbMin,btVector3& aabbMax) const;
-
- virtual void setLocalScaling(const btVector3& scaling) ;
- virtual const btVector3& getLocalScaling() const ;
-
- virtual void setMargin(btScalar margin);
- virtual btScalar getMargin() const;
-
- virtual int getNumPreferredPenetrationDirections() const;
-
- virtual void getPreferredPenetrationDirection(int index, btVector3& penetrationVector) const;
-
-
-};
-
-#endif //BT_UNIFORM_SCALING_SHAPE_H
diff --git a/extern/bullet2/src/BulletCollision/NarrowPhaseCollision/btGjkEpa2.cpp b/extern/bullet2/src/BulletCollision/NarrowPhaseCollision/btGjkEpa2.cpp
deleted file mode 100644
index ccfc22ee673..00000000000
--- a/extern/bullet2/src/BulletCollision/NarrowPhaseCollision/btGjkEpa2.cpp
+++ /dev/null
@@ -1,943 +0,0 @@
-/*
-Bullet Continuous Collision Detection and Physics Library
-Copyright (c) 2003-2008 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.
-*/
-
-/*
-GJK-EPA collision solver by Nathanael Presson, 2008
-*/
-#include "BulletCollision/CollisionShapes/btConvexInternalShape.h"
-#include "BulletCollision/CollisionShapes/btSphereShape.h"
-#include "btGjkEpa2.h"
-
-#if defined(DEBUG) || defined (_DEBUG)
-#include <stdio.h> //for debug printf
-#ifdef __SPU__
-#include <spu_printf.h>
-#define printf spu_printf
-#endif //__SPU__
-#endif
-
-namespace gjkepa2_impl
-{
-
-// Config
-
- /* GJK */
-#define GJK_MAX_ITERATIONS 128
-#define GJK_ACCURARY ((btScalar)0.0001)
-#define GJK_MIN_DISTANCE ((btScalar)0.0001)
-#define GJK_DUPLICATED_EPS ((btScalar)0.0001)
-#define GJK_SIMPLEX2_EPS ((btScalar)0.0)
-#define GJK_SIMPLEX3_EPS ((btScalar)0.0)
-#define GJK_SIMPLEX4_EPS ((btScalar)0.0)
-
- /* EPA */
-#define EPA_MAX_VERTICES 64
-#define EPA_MAX_FACES (EPA_MAX_VERTICES*2)
-#define EPA_MAX_ITERATIONS 255
-#define EPA_ACCURACY ((btScalar)0.0001)
-#define EPA_FALLBACK (10*EPA_ACCURACY)
-#define EPA_PLANE_EPS ((btScalar)0.00001)
-#define EPA_INSIDE_EPS ((btScalar)0.01)
-
-
-// Shorthands
-typedef unsigned int U;
-typedef unsigned char U1;
-
-// MinkowskiDiff
-struct MinkowskiDiff
- {
- const btConvexShape* m_shapes[2];
- btMatrix3x3 m_toshape1;
- btTransform m_toshape0;
- btVector3 (btConvexShape::*Ls)(const btVector3&) const;
- void EnableMargin(bool enable)
- {
- if(enable)
- Ls=&btConvexShape::localGetSupportingVertex;
- else
- Ls=&btConvexShape::localGetSupportingVertexWithoutMargin;
- }
- inline btVector3 Support0(const btVector3& d) const
- {
- return(((m_shapes[0])->*(Ls))(d));
- }
- inline btVector3 Support1(const btVector3& d) const
- {
- return(m_toshape0*((m_shapes[1])->*(Ls))(m_toshape1*d));
- }
- inline btVector3 Support(const btVector3& d) const
- {
- return(Support0(d)-Support1(-d));
- }
- btVector3 Support(const btVector3& d,U index) const
- {
- if(index)
- return(Support1(d));
- else
- return(Support0(d));
- }
- };
-
-typedef MinkowskiDiff tShape;
-
-
-// GJK
-struct GJK
-{
-/* Types */
-struct sSV
- {
- btVector3 d,w;
- };
-struct sSimplex
- {
- sSV* c[4];
- btScalar p[4];
- U rank;
- };
-struct eStatus { enum _ {
- Valid,
- Inside,
- Failed };};
-/* Fields */
-tShape m_shape;
-btVector3 m_ray;
-btScalar m_distance;
-sSimplex m_simplices[2];
-sSV m_store[4];
-sSV* m_free[4];
-U m_nfree;
-U m_current;
-sSimplex* m_simplex;
-eStatus::_ m_status;
-/* Methods */
- GJK()
- {
- Initialize();
- }
-void Initialize()
- {
- m_ray = btVector3(0,0,0);
- m_nfree = 0;
- m_status = eStatus::Failed;
- m_current = 0;
- m_distance = 0;
- }
-eStatus::_ Evaluate(const tShape& shapearg,const btVector3& guess)
- {
- U iterations=0;
- btScalar sqdist=0;
- btScalar alpha=0;
- btVector3 lastw[4];
- U clastw=0;
- /* Initialize solver */
- m_free[0] = &m_store[0];
- m_free[1] = &m_store[1];
- m_free[2] = &m_store[2];
- m_free[3] = &m_store[3];
- m_nfree = 4;
- m_current = 0;
- m_status = eStatus::Valid;
- m_shape = shapearg;
- m_distance = 0;
- /* Initialize simplex */
- m_simplices[0].rank = 0;
- m_ray = guess;
- const btScalar sqrl= m_ray.length2();
- appendvertice(m_simplices[0],sqrl>0?-m_ray:btVector3(1,0,0));
- m_simplices[0].p[0] = 1;
- m_ray = m_simplices[0].c[0]->w;
- sqdist = sqrl;
- lastw[0] =
- lastw[1] =
- lastw[2] =
- lastw[3] = m_ray;
- /* Loop */
- do {
- const U next=1-m_current;
- sSimplex& cs=m_simplices[m_current];
- sSimplex& ns=m_simplices[next];
- /* Check zero */
- const btScalar rl=m_ray.length();
- if(rl<GJK_MIN_DISTANCE)
- {/* Touching or inside */
- m_status=eStatus::Inside;
- break;
- }
- /* Append new vertice in -'v' direction */
- appendvertice(cs,-m_ray);
- const btVector3& w=cs.c[cs.rank-1]->w;
- bool found=false;
- for(U i=0;i<4;++i)
- {
- if((w-lastw[i]).length2()<GJK_DUPLICATED_EPS)
- { found=true;break; }
- }
- if(found)
- {/* Return old simplex */
- removevertice(m_simplices[m_current]);
- break;
- }
- else
- {/* Update lastw */
- lastw[clastw=(clastw+1)&3]=w;
- }
- /* Check for termination */
- const btScalar omega=dot(m_ray,w)/rl;
- alpha=btMax(omega,alpha);
- if(((rl-alpha)-(GJK_ACCURARY*rl))<=0)
- {/* Return old simplex */
- removevertice(m_simplices[m_current]);
- break;
- }
- /* Reduce simplex */
- btScalar weights[4];
- U mask=0;
- switch(cs.rank)
- {
- case 2: sqdist=projectorigin( cs.c[0]->w,
- cs.c[1]->w,
- weights,mask);break;
- case 3: sqdist=projectorigin( cs.c[0]->w,
- cs.c[1]->w,
- cs.c[2]->w,
- weights,mask);break;
- case 4: sqdist=projectorigin( cs.c[0]->w,
- cs.c[1]->w,
- cs.c[2]->w,
- cs.c[3]->w,
- weights,mask);break;
- }
- if(sqdist>=0)
- {/* Valid */
- ns.rank = 0;
- m_ray = btVector3(0,0,0);
- m_current = next;
- for(U i=0,ni=cs.rank;i<ni;++i)
- {
- if(mask&(1<<i))
- {
- ns.c[ns.rank] = cs.c[i];
- ns.p[ns.rank++] = weights[i];
- m_ray += cs.c[i]->w*weights[i];
- }
- else
- {
- m_free[m_nfree++] = cs.c[i];
- }
- }
- if(mask==15) m_status=eStatus::Inside;
- }
- else
- {/* Return old simplex */
- removevertice(m_simplices[m_current]);
- break;
- }
- m_status=((++iterations)<GJK_MAX_ITERATIONS)?m_status:eStatus::Failed;
- } while(m_status==eStatus::Valid);
- m_simplex=&m_simplices[m_current];
- switch(m_status)
- {
- case eStatus::Valid: m_distance=m_ray.length();break;
- case eStatus::Inside: m_distance=0;break;
- }
- return(m_status);
- }
-bool EncloseOrigin()
- {
- switch(m_simplex->rank)
- {
- case 1:
- {
- for(U i=0;i<3;++i)
- {
- btVector3 axis=btVector3(0,0,0);
- axis[i]=1;
- appendvertice(*m_simplex, axis);
- if(EncloseOrigin()) return(true);
- removevertice(*m_simplex);
- appendvertice(*m_simplex,-axis);
- if(EncloseOrigin()) return(true);
- removevertice(*m_simplex);
- }
- }
- break;
- case 2:
- {
- const btVector3 d=m_simplex->c[1]->w-m_simplex->c[0]->w;
- for(U i=0;i<3;++i)
- {
- btVector3 axis=btVector3(0,0,0);
- axis[i]=1;
- const btVector3 p=cross(d,axis);
- if(p.length2()>0)
- {
- appendvertice(*m_simplex, p);
- if(EncloseOrigin()) return(true);
- removevertice(*m_simplex);
- appendvertice(*m_simplex,-p);
- if(EncloseOrigin()) return(true);
- removevertice(*m_simplex);
- }
- }
- }
- break;
- case 3:
- {
- const btVector3 n=cross(m_simplex->c[1]->w-m_simplex->c[0]->w,
- m_simplex->c[2]->w-m_simplex->c[0]->w);
- if(n.length2()>0)
- {
- appendvertice(*m_simplex,n);
- if(EncloseOrigin()) return(true);
- removevertice(*m_simplex);
- appendvertice(*m_simplex,-n);
- if(EncloseOrigin()) return(true);
- removevertice(*m_simplex);
- }
- }
- break;
- case 4:
- {
- if(btFabs(det( m_simplex->c[0]->w-m_simplex->c[3]->w,
- m_simplex->c[1]->w-m_simplex->c[3]->w,
- m_simplex->c[2]->w-m_simplex->c[3]->w))>0)
- return(true);
- }
- break;
- }
- return(false);
- }
-/* Internals */
-void getsupport(const btVector3& d,sSV& sv) const
- {
- sv.d = d/d.length();
- sv.w = m_shape.Support(sv.d);
- }
-void removevertice(sSimplex& simplex)
- {
- m_free[m_nfree++]=simplex.c[--simplex.rank];
- }
-void appendvertice(sSimplex& simplex,const btVector3& v)
- {
- simplex.p[simplex.rank]=0;
- simplex.c[simplex.rank]=m_free[--m_nfree];
- getsupport(v,*simplex.c[simplex.rank++]);
- }
-static btScalar det(const btVector3& a,const btVector3& b,const btVector3& c)
- {
- return( a.y()*b.z()*c.x()+a.z()*b.x()*c.y()-
- a.x()*b.z()*c.y()-a.y()*b.x()*c.z()+
- a.x()*b.y()*c.z()-a.z()*b.y()*c.x());
- }
-static btScalar projectorigin( const btVector3& a,
- const btVector3& b,
- btScalar* w,U& m)
- {
- const btVector3 d=b-a;
- const btScalar l=d.length2();
- if(l>GJK_SIMPLEX2_EPS)
- {
- const btScalar t(l>0?-dot(a,d)/l:0);
- if(t>=1) { w[0]=0;w[1]=1;m=2;return(b.length2()); }
- else if(t<=0) { w[0]=1;w[1]=0;m=1;return(a.length2()); }
- else { w[0]=1-(w[1]=t);m=3;return((a+d*t).length2()); }
- }
- return(-1);
- }
-static btScalar projectorigin( const btVector3& a,
- const btVector3& b,
- const btVector3& c,
- btScalar* w,U& m)
- {
- static const U imd3[]={1,2,0};
- const btVector3* vt[]={&a,&b,&c};
- const btVector3 dl[]={a-b,b-c,c-a};
- const btVector3 n=cross(dl[0],dl[1]);
- const btScalar l=n.length2();
- if(l>GJK_SIMPLEX3_EPS)
- {
- btScalar mindist=-1;
- btScalar subw[2];
- U subm;
- for(U i=0;i<3;++i)
- {
- if(dot(*vt[i],cross(dl[i],n))>0)
- {
- const U j=imd3[i];
- const btScalar subd(projectorigin(*vt[i],*vt[j],subw,subm));
- if((mindist<0)||(subd<mindist))
- {
- mindist = subd;
- m = static_cast<U>(((subm&1)?1<<i:0)+((subm&2)?1<<j:0));
- w[i] = subw[0];
- w[j] = subw[1];
- w[imd3[j]] = 0;
- }
- }
- }
- if(mindist<0)
- {
- const btScalar d=dot(a,n);
- const btScalar s=btSqrt(l);
- const btVector3 p=n*(d/l);
- mindist = p.length2();
- m = 7;
- w[0] = (cross(dl[1],b-p)).length()/s;
- w[1] = (cross(dl[2],c-p)).length()/s;
- w[2] = 1-(w[0]+w[1]);
- }
- return(mindist);
- }
- return(-1);
- }
-static btScalar projectorigin( const btVector3& a,
- const btVector3& b,
- const btVector3& c,
- const btVector3& d,
- btScalar* w,U& m)
- {
- static const U imd3[]={1,2,0};
- const btVector3* vt[]={&a,&b,&c,&d};
- const btVector3 dl[]={a-d,b-d,c-d};
- const btScalar vl=det(dl[0],dl[1],dl[2]);
- const bool ng=(vl*dot(a,cross(b-c,a-b)))<=0;
- if(ng&&(btFabs(vl)>GJK_SIMPLEX4_EPS))
- {
- btScalar mindist=-1;
- btScalar subw[3];
- U subm;
- for(U i=0;i<3;++i)
- {
- const U j=imd3[i];
- const btScalar s=vl*dot(d,cross(dl[i],dl[j]));
- if(s>0)
- {
- const btScalar subd=projectorigin(*vt[i],*vt[j],d,subw,subm);
- if((mindist<0)||(subd<mindist))
- {
- mindist = subd;
- m = static_cast<U>((subm&1?1<<i:0)+
- (subm&2?1<<j:0)+
- (subm&4?8:0));
- w[i] = subw[0];
- w[j] = subw[1];
- w[imd3[j]] = 0;
- w[3] = subw[2];
- }
- }
- }
- if(mindist<0)
- {
- mindist = 0;
- m = 15;
- w[0] = det(c,b,d)/vl;
- w[1] = det(a,c,d)/vl;
- w[2] = det(b,a,d)/vl;
- w[3] = 1-(w[0]+w[1]+w[2]);
- }
- return(mindist);
- }
- return(-1);
- }
-};
-
-// EPA
-struct EPA
-{
-/* Types */
-typedef GJK::sSV sSV;
-struct sFace
- {
- btVector3 n;
- btScalar d;
- btScalar p;
- sSV* c[3];
- sFace* f[3];
- sFace* l[2];
- U1 e[3];
- U1 pass;
- };
-struct sList
- {
- sFace* root;
- U count;
- sList() : root(0),count(0) {}
- };
-struct sHorizon
- {
- sFace* cf;
- sFace* ff;
- U nf;
- sHorizon() : cf(0),ff(0),nf(0) {}
- };
-struct eStatus { enum _ {
- Valid,
- Touching,
- Degenerated,
- NonConvex,
- InvalidHull,
- OutOfFaces,
- OutOfVertices,
- AccuraryReached,
- FallBack,
- Failed };};
-/* Fields */
-eStatus::_ m_status;
-GJK::sSimplex m_result;
-btVector3 m_normal;
-btScalar m_depth;
-sSV m_sv_store[EPA_MAX_VERTICES];
-sFace m_fc_store[EPA_MAX_FACES];
-U m_nextsv;
-sList m_hull;
-sList m_stock;
-/* Methods */
- EPA()
- {
- Initialize();
- }
-
-
- static inline void bind(sFace* fa,U ea,sFace* fb,U eb)
- {
- fa->e[ea]=(U1)eb;fa->f[ea]=fb;
- fb->e[eb]=(U1)ea;fb->f[eb]=fa;
- }
-static inline void append(sList& list,sFace* face)
- {
- face->l[0] = 0;
- face->l[1] = list.root;
- if(list.root) list.root->l[0]=face;
- list.root = face;
- ++list.count;
- }
-static inline void remove(sList& list,sFace* face)
- {
- if(face->l[1]) face->l[1]->l[0]=face->l[0];
- if(face->l[0]) face->l[0]->l[1]=face->l[1];
- if(face==list.root) list.root=face->l[1];
- --list.count;
- }
-
-
-void Initialize()
- {
- m_status = eStatus::Failed;
- m_normal = btVector3(0,0,0);
- m_depth = 0;
- m_nextsv = 0;
- for(U i=0;i<EPA_MAX_FACES;++i)
- {
- append(m_stock,&m_fc_store[EPA_MAX_FACES-i-1]);
- }
- }
-eStatus::_ Evaluate(GJK& gjk,const btVector3& guess)
- {
- GJK::sSimplex& simplex=*gjk.m_simplex;
- if((simplex.rank>1)&&gjk.EncloseOrigin())
- {
-
- /* Clean up */
- while(m_hull.root)
- {
- sFace* f = m_hull.root;
- remove(m_hull,f);
- append(m_stock,f);
- }
- m_status = eStatus::Valid;
- m_nextsv = 0;
- /* Orient simplex */
- if(gjk.det( simplex.c[0]->w-simplex.c[3]->w,
- simplex.c[1]->w-simplex.c[3]->w,
- simplex.c[2]->w-simplex.c[3]->w)<0)
- {
- btSwap(simplex.c[0],simplex.c[1]);
- btSwap(simplex.p[0],simplex.p[1]);
- }
- /* Build initial hull */
- sFace* tetra[]={newface(simplex.c[0],simplex.c[1],simplex.c[2],true),
- newface(simplex.c[1],simplex.c[0],simplex.c[3],true),
- newface(simplex.c[2],simplex.c[1],simplex.c[3],true),
- newface(simplex.c[0],simplex.c[2],simplex.c[3],true)};
- if(m_hull.count==4)
- {
- sFace* best=findbest();
- sFace outer=*best;
- U pass=0;
- U iterations=0;
- bind(tetra[0],0,tetra[1],0);
- bind(tetra[0],1,tetra[2],0);
- bind(tetra[0],2,tetra[3],0);
- bind(tetra[1],1,tetra[3],2);
- bind(tetra[1],2,tetra[2],1);
- bind(tetra[2],2,tetra[3],1);
- m_status=eStatus::Valid;
- for(;iterations<EPA_MAX_ITERATIONS;++iterations)
- {
- if(m_nextsv<EPA_MAX_VERTICES)
- {
- sHorizon horizon;
- sSV* w=&m_sv_store[m_nextsv++];
- bool valid=true;
- best->pass = (U1)(++pass);
- gjk.getsupport(best->n,*w);
- const btScalar wdist=dot(best->n,w->w)-best->d;
- if(wdist>EPA_ACCURACY)
- {
- for(U j=0;(j<3)&&valid;++j)
- {
- valid&=expand( pass,w,
- best->f[j],best->e[j],
- horizon);
- }
- if(valid&&(horizon.nf>=3))
- {
- bind(horizon.cf,1,horizon.ff,2);
- remove(m_hull,best);
- append(m_stock,best);
- best=findbest();
- if(best->p>=outer.p) outer=*best;
- } else { m_status=eStatus::InvalidHull;break; }
- } else { m_status=eStatus::AccuraryReached;break; }
- } else { m_status=eStatus::OutOfVertices;break; }
- }
- const btVector3 projection=outer.n*outer.d;
- m_normal = outer.n;
- m_depth = outer.d;
- m_result.rank = 3;
- m_result.c[0] = outer.c[0];
- m_result.c[1] = outer.c[1];
- m_result.c[2] = outer.c[2];
- m_result.p[0] = cross( outer.c[1]->w-projection,
- outer.c[2]->w-projection).length();
- m_result.p[1] = cross( outer.c[2]->w-projection,
- outer.c[0]->w-projection).length();
- m_result.p[2] = cross( outer.c[0]->w-projection,
- outer.c[1]->w-projection).length();
- const btScalar sum=m_result.p[0]+m_result.p[1]+m_result.p[2];
- m_result.p[0] /= sum;
- m_result.p[1] /= sum;
- m_result.p[2] /= sum;
- return(m_status);
- }
- }
- /* Fallback */
- m_status = eStatus::FallBack;
- m_normal = -guess;
- const btScalar nl=m_normal.length();
- if(nl>0)
- m_normal = m_normal/nl;
- else
- m_normal = btVector3(1,0,0);
- m_depth = 0;
- m_result.rank=1;
- m_result.c[0]=simplex.c[0];
- m_result.p[0]=1;
- return(m_status);
- }
-sFace* newface(sSV* a,sSV* b,sSV* c,bool forced)
- {
- if(m_stock.root)
- {
- sFace* face=m_stock.root;
- remove(m_stock,face);
- append(m_hull,face);
- face->pass = 0;
- face->c[0] = a;
- face->c[1] = b;
- face->c[2] = c;
- face->n = cross(b->w-a->w,c->w-a->w);
- const btScalar l=face->n.length();
- const bool v=l>EPA_ACCURACY;
- face->p = btMin(btMin(
- dot(a->w,cross(face->n,a->w-b->w)),
- dot(b->w,cross(face->n,b->w-c->w))),
- dot(c->w,cross(face->n,c->w-a->w))) /
- (v?l:1);
- face->p = face->p>=-EPA_INSIDE_EPS?0:face->p;
- if(v)
- {
- face->d = dot(a->w,face->n)/l;
- face->n /= l;
- if(forced||(face->d>=-EPA_PLANE_EPS))
- {
- return(face);
- } else m_status=eStatus::NonConvex;
- } else m_status=eStatus::Degenerated;
- remove(m_hull,face);
- append(m_stock,face);
- return(0);
- }
- m_status=m_stock.root?eStatus::OutOfVertices:eStatus::OutOfFaces;
- return(0);
- }
-sFace* findbest()
- {
- sFace* minf=m_hull.root;
- btScalar mind=minf->d*minf->d;
- btScalar maxp=minf->p;
- for(sFace* f=minf->l[1];f;f=f->l[1])
- {
- const btScalar sqd=f->d*f->d;
- if((f->p>=maxp)&&(sqd<mind))
- {
- minf=f;
- mind=sqd;
- maxp=f->p;
- }
- }
- return(minf);
- }
-bool expand(U pass,sSV* w,sFace* f,U e,sHorizon& horizon)
- {
- static const U i1m3[]={1,2,0};
- static const U i2m3[]={2,0,1};
- if(f->pass!=pass)
- {
- const U e1=i1m3[e];
- if((dot(f->n,w->w)-f->d)<-EPA_PLANE_EPS)
- {
- sFace* nf=newface(f->c[e1],f->c[e],w,false);
- if(nf)
- {
- bind(nf,0,f,e);
- if(horizon.cf) bind(horizon.cf,1,nf,2); else horizon.ff=nf;
- horizon.cf=nf;
- ++horizon.nf;
- return(true);
- }
- }
- else
- {
- const U e2=i2m3[e];
- f->pass = (U1)pass;
- if( expand(pass,w,f->f[e1],f->e[e1],horizon)&&
- expand(pass,w,f->f[e2],f->e[e2],horizon))
- {
- remove(m_hull,f);
- append(m_stock,f);
- return(true);
- }
- }
- }
- return(false);
- }
-
-};
-
-//
-static void Initialize( const btConvexShape* shape0,const btTransform& wtrs0,
- const btConvexShape* shape1,const btTransform& wtrs1,
- btGjkEpaSolver2::sResults& results,
- tShape& shape,
- bool withmargins)
-{
-/* Results */
-results.witnesses[0] =
-results.witnesses[1] = btVector3(0,0,0);
-results.status = btGjkEpaSolver2::sResults::Separated;
-/* Shape */
-shape.m_shapes[0] = shape0;
-shape.m_shapes[1] = shape1;
-shape.m_toshape1 = wtrs1.getBasis().transposeTimes(wtrs0.getBasis());
-shape.m_toshape0 = wtrs0.inverseTimes(wtrs1);
-shape.EnableMargin(withmargins);
-}
-
-}
-
-//
-// Api
-//
-
-using namespace gjkepa2_impl;
-
-//
-int btGjkEpaSolver2::StackSizeRequirement()
-{
-return(sizeof(GJK)+sizeof(EPA));
-}
-
-//
-bool btGjkEpaSolver2::Distance( const btConvexShape* shape0,
- const btTransform& wtrs0,
- const btConvexShape* shape1,
- const btTransform& wtrs1,
- const btVector3& guess,
- sResults& results)
-{
-tShape shape;
-Initialize(shape0,wtrs0,shape1,wtrs1,results,shape,false);
-GJK gjk;
-GJK::eStatus::_ gjk_status=gjk.Evaluate(shape,guess);
-if(gjk_status==GJK::eStatus::Valid)
- {
- btVector3 w0=btVector3(0,0,0);
- btVector3 w1=btVector3(0,0,0);
- for(U i=0;i<gjk.m_simplex->rank;++i)
- {
- const btScalar p=gjk.m_simplex->p[i];
- w0+=shape.Support( gjk.m_simplex->c[i]->d,0)*p;
- w1+=shape.Support(-gjk.m_simplex->c[i]->d,1)*p;
- }
- results.witnesses[0] = wtrs0*w0;
- results.witnesses[1] = wtrs0*w1;
- results.normal = w0-w1;
- results.distance = results.normal.length();
- results.normal /= results.distance>GJK_MIN_DISTANCE?results.distance:1;
- return(true);
- }
- else
- {
- results.status = gjk_status==GJK::eStatus::Inside?
- sResults::Penetrating :
- sResults::GJK_Failed ;
- return(false);
- }
-}
-
-//
-bool btGjkEpaSolver2::Penetration( const btConvexShape* shape0,
- const btTransform& wtrs0,
- const btConvexShape* shape1,
- const btTransform& wtrs1,
- const btVector3& guess,
- sResults& results,
- bool usemargins)
-{
-tShape shape;
-Initialize(shape0,wtrs0,shape1,wtrs1,results,shape,usemargins);
-GJK gjk;
-GJK::eStatus::_ gjk_status=gjk.Evaluate(shape,-guess);
-switch(gjk_status)
- {
- case GJK::eStatus::Inside:
- {
- EPA epa;
- EPA::eStatus::_ epa_status=epa.Evaluate(gjk,-guess);
- if(epa_status!=EPA::eStatus::Failed)
- {
- btVector3 w0=btVector3(0,0,0);
- for(U i=0;i<epa.m_result.rank;++i)
- {
- w0+=shape.Support(epa.m_result.c[i]->d,0)*epa.m_result.p[i];
- }
- results.status = sResults::Penetrating;
- results.witnesses[0] = wtrs0*w0;
- results.witnesses[1] = wtrs0*(w0-epa.m_normal*epa.m_depth);
- results.normal = -epa.m_normal;
- results.distance = -epa.m_depth;
- return(true);
- } else results.status=sResults::EPA_Failed;
- }
- break;
- case GJK::eStatus::Failed:
- results.status=sResults::GJK_Failed;
- break;
- }
-return(false);
-}
-
-//
-btScalar btGjkEpaSolver2::SignedDistance(const btVector3& position,
- btScalar margin,
- const btConvexShape* shape0,
- const btTransform& wtrs0,
- sResults& results)
-{
-tShape shape;
-btSphereShape shape1(margin);
-btTransform wtrs1(btQuaternion(0,0,0,1),position);
-Initialize(shape0,wtrs0,&shape1,wtrs1,results,shape,false);
-GJK gjk;
-GJK::eStatus::_ gjk_status=gjk.Evaluate(shape,btVector3(1,1,1));
-if(gjk_status==GJK::eStatus::Valid)
- {
- btVector3 w0=btVector3(0,0,0);
- btVector3 w1=btVector3(0,0,0);
- for(U i=0;i<gjk.m_simplex->rank;++i)
- {
- const btScalar p=gjk.m_simplex->p[i];
- w0+=shape.Support( gjk.m_simplex->c[i]->d,0)*p;
- w1+=shape.Support(-gjk.m_simplex->c[i]->d,1)*p;
- }
- results.witnesses[0] = wtrs0*w0;
- results.witnesses[1] = wtrs0*w1;
- const btVector3 delta= results.witnesses[1]-
- results.witnesses[0];
- const btScalar margin= shape0->getMargin()+
- shape1.getMargin();
- const btScalar length= delta.length();
- results.normal = delta/length;
- results.witnesses[0] += results.normal*margin;
- return(length-margin);
- }
- else
- {
- if(gjk_status==GJK::eStatus::Inside)
- {
- if(Penetration(shape0,wtrs0,&shape1,wtrs1,gjk.m_ray,results))
- {
- const btVector3 delta= results.witnesses[0]-
- results.witnesses[1];
- const btScalar length= delta.length();
- if (length >= SIMD_EPSILON)
- results.normal = delta/length;
- return(-length);
- }
- }
- }
-return(SIMD_INFINITY);
-}
-
-//
-bool btGjkEpaSolver2::SignedDistance(const btConvexShape* shape0,
- const btTransform& wtrs0,
- const btConvexShape* shape1,
- const btTransform& wtrs1,
- const btVector3& guess,
- sResults& results)
-{
-if(!Distance(shape0,wtrs0,shape1,wtrs1,guess,results))
- return(Penetration(shape0,wtrs0,shape1,wtrs1,guess,results,false));
- else
- return(true);
-}
-
-/* Symbols cleanup */
-
-#undef GJK_MAX_ITERATIONS
-#undef GJK_ACCURARY
-#undef GJK_MIN_DISTANCE
-#undef GJK_DUPLICATED_EPS
-#undef GJK_SIMPLEX2_EPS
-#undef GJK_SIMPLEX3_EPS
-#undef GJK_SIMPLEX4_EPS
-
-#undef EPA_MAX_VERTICES
-#undef EPA_MAX_FACES
-#undef EPA_MAX_ITERATIONS
-#undef EPA_ACCURACY
-#undef EPA_FALLBACK
-#undef EPA_PLANE_EPS
-#undef EPA_INSIDE_EPS
diff --git a/extern/bullet2/src/BulletCollision/NarrowPhaseCollision/btGjkEpa2.h b/extern/bullet2/src/BulletCollision/NarrowPhaseCollision/btGjkEpa2.h
deleted file mode 100644
index a55214203d3..00000000000
--- a/extern/bullet2/src/BulletCollision/NarrowPhaseCollision/btGjkEpa2.h
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
-Bullet Continuous Collision Detection and Physics Library
-Copyright (c) 2003-2008 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.
-*/
-
-/*
-GJK-EPA collision solver by Nathanael Presson, 2008
-*/
-#ifndef _68DA1F85_90B7_4bb0_A705_83B4040A75C6_
-#define _68DA1F85_90B7_4bb0_A705_83B4040A75C6_
-#include "BulletCollision/CollisionShapes/btConvexShape.h"
-
-///btGjkEpaSolver contributed under zlib by Nathanael Presson
-struct btGjkEpaSolver2
-{
-struct sResults
- {
- enum eStatus
- {
- Separated, /* Shapes doesnt penetrate */
- Penetrating, /* Shapes are penetrating */
- GJK_Failed, /* GJK phase fail, no big issue, shapes are probably just 'touching' */
- EPA_Failed /* EPA phase fail, bigger problem, need to save parameters, and debug */
- } status;
- btVector3 witnesses[2];
- btVector3 normal;
- btScalar distance;
- };
-
-static int StackSizeRequirement();
-
-static bool Distance( const btConvexShape* shape0,const btTransform& wtrs0,
- const btConvexShape* shape1,const btTransform& wtrs1,
- const btVector3& guess,
- sResults& results);
-
-static bool Penetration(const btConvexShape* shape0,const btTransform& wtrs0,
- const btConvexShape* shape1,const btTransform& wtrs1,
- const btVector3& guess,
- sResults& results,
- bool usemargins=true);
-
-static btScalar SignedDistance( const btVector3& position,
- btScalar margin,
- const btConvexShape* shape,
- const btTransform& wtrs,
- sResults& results);
-
-static bool SignedDistance( const btConvexShape* shape0,const btTransform& wtrs0,
- const btConvexShape* shape1,const btTransform& wtrs1,
- const btVector3& guess,
- sResults& results);
-};
-
-#endif
diff --git a/extern/bullet2/src/BulletDynamics/ConstraintSolver/btSliderConstraint.cpp b/extern/bullet2/src/BulletDynamics/ConstraintSolver/btSliderConstraint.cpp
deleted file mode 100644
index 4128f504bf1..00000000000
--- a/extern/bullet2/src/BulletDynamics/ConstraintSolver/btSliderConstraint.cpp
+++ /dev/null
@@ -1,415 +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.
-*/
-
-/*
-Added by Roman Ponomarev (rponom@gmail.com)
-April 04, 2008
-*/
-
-//-----------------------------------------------------------------------------
-
-#include "btSliderConstraint.h"
-#include "BulletDynamics/Dynamics/btRigidBody.h"
-#include "LinearMath/btTransformUtil.h"
-#include <new>
-
-//-----------------------------------------------------------------------------
-
-void btSliderConstraint::initParams()
-{
- m_lowerLinLimit = btScalar(1.0);
- m_upperLinLimit = btScalar(-1.0);
- m_lowerAngLimit = btScalar(0.);
- m_upperAngLimit = btScalar(0.);
- m_softnessDirLin = SLIDER_CONSTRAINT_DEF_SOFTNESS;
- m_restitutionDirLin = SLIDER_CONSTRAINT_DEF_RESTITUTION;
- m_dampingDirLin = btScalar(0.);
- m_softnessDirAng = SLIDER_CONSTRAINT_DEF_SOFTNESS;
- m_restitutionDirAng = SLIDER_CONSTRAINT_DEF_RESTITUTION;
- m_dampingDirAng = btScalar(0.);
- m_softnessOrthoLin = SLIDER_CONSTRAINT_DEF_SOFTNESS;
- m_restitutionOrthoLin = SLIDER_CONSTRAINT_DEF_RESTITUTION;
- m_dampingOrthoLin = SLIDER_CONSTRAINT_DEF_DAMPING;
- m_softnessOrthoAng = SLIDER_CONSTRAINT_DEF_SOFTNESS;
- m_restitutionOrthoAng = SLIDER_CONSTRAINT_DEF_RESTITUTION;
- m_dampingOrthoAng = SLIDER_CONSTRAINT_DEF_DAMPING;
- m_softnessLimLin = SLIDER_CONSTRAINT_DEF_SOFTNESS;
- m_restitutionLimLin = SLIDER_CONSTRAINT_DEF_RESTITUTION;
- m_dampingLimLin = SLIDER_CONSTRAINT_DEF_DAMPING;
- m_softnessLimAng = SLIDER_CONSTRAINT_DEF_SOFTNESS;
- m_restitutionLimAng = SLIDER_CONSTRAINT_DEF_RESTITUTION;
- m_dampingLimAng = SLIDER_CONSTRAINT_DEF_DAMPING;
-
- m_poweredLinMotor = false;
- m_targetLinMotorVelocity = btScalar(0.);
- m_maxLinMotorForce = btScalar(0.);
- m_accumulatedLinMotorImpulse = btScalar(0.0);
-
- m_poweredAngMotor = false;
- m_targetAngMotorVelocity = btScalar(0.);
- m_maxAngMotorForce = btScalar(0.);
- m_accumulatedAngMotorImpulse = btScalar(0.0);
-
-} // btSliderConstraint::initParams()
-
-//-----------------------------------------------------------------------------
-
-btSliderConstraint::btSliderConstraint()
- :btTypedConstraint(SLIDER_CONSTRAINT_TYPE),
- m_useLinearReferenceFrameA(true)
-{
- initParams();
-} // btSliderConstraint::btSliderConstraint()
-
-//-----------------------------------------------------------------------------
-
-btSliderConstraint::btSliderConstraint(btRigidBody& rbA, btRigidBody& rbB, const btTransform& frameInA, const btTransform& frameInB, bool useLinearReferenceFrameA)
- : btTypedConstraint(SLIDER_CONSTRAINT_TYPE, rbA, rbB)
- , m_frameInA(frameInA)
- , m_frameInB(frameInB),
- m_useLinearReferenceFrameA(useLinearReferenceFrameA)
-{
- initParams();
-} // btSliderConstraint::btSliderConstraint()
-
-//-----------------------------------------------------------------------------
-
-void btSliderConstraint::buildJacobian()
-{
- if(m_useLinearReferenceFrameA)
- {
- buildJacobianInt(m_rbA, m_rbB, m_frameInA, m_frameInB);
- }
- else
- {
- buildJacobianInt(m_rbB, m_rbA, m_frameInB, m_frameInA);
- }
-} // btSliderConstraint::buildJacobian()
-
-//-----------------------------------------------------------------------------
-
-void btSliderConstraint::buildJacobianInt(btRigidBody& rbA, btRigidBody& rbB, const btTransform& frameInA, const btTransform& frameInB)
-{
- //calculate transforms
- m_calculatedTransformA = rbA.getCenterOfMassTransform() * frameInA;
- m_calculatedTransformB = rbB.getCenterOfMassTransform() * frameInB;
- m_realPivotAInW = m_calculatedTransformA.getOrigin();
- m_realPivotBInW = m_calculatedTransformB.getOrigin();
- m_sliderAxis = m_calculatedTransformA.getBasis().getColumn(0); // along X
- m_delta = m_realPivotBInW - m_realPivotAInW;
- m_projPivotInW = m_realPivotAInW + m_sliderAxis.dot(m_delta) * m_sliderAxis;
- m_relPosA = m_projPivotInW - rbA.getCenterOfMassPosition();
- m_relPosB = m_realPivotBInW - rbB.getCenterOfMassPosition();
- btVector3 normalWorld;
- int i;
- //linear part
- for(i = 0; i < 3; i++)
- {
- normalWorld = m_calculatedTransformA.getBasis().getColumn(i);
- new (&m_jacLin[i]) btJacobianEntry(
- rbA.getCenterOfMassTransform().getBasis().transpose(),
- rbB.getCenterOfMassTransform().getBasis().transpose(),
- m_relPosA,
- m_relPosB,
- normalWorld,
- rbA.getInvInertiaDiagLocal(),
- rbA.getInvMass(),
- rbB.getInvInertiaDiagLocal(),
- rbB.getInvMass()
- );
- m_jacLinDiagABInv[i] = btScalar(1.) / m_jacLin[i].getDiagonal();
- m_depth[i] = m_delta.dot(normalWorld);
- }
- testLinLimits();
- // angular part
- for(i = 0; i < 3; i++)
- {
- normalWorld = m_calculatedTransformA.getBasis().getColumn(i);
- new (&m_jacAng[i]) btJacobianEntry(
- normalWorld,
- rbA.getCenterOfMassTransform().getBasis().transpose(),
- rbB.getCenterOfMassTransform().getBasis().transpose(),
- rbA.getInvInertiaDiagLocal(),
- rbB.getInvInertiaDiagLocal()
- );
- }
- testAngLimits();
- btVector3 axisA = m_calculatedTransformA.getBasis().getColumn(0);
- m_kAngle = btScalar(1.0 )/ (rbA.computeAngularImpulseDenominator(axisA) + rbB.computeAngularImpulseDenominator(axisA));
- // clear accumulator for motors
- m_accumulatedLinMotorImpulse = btScalar(0.0);
- m_accumulatedAngMotorImpulse = btScalar(0.0);
-} // btSliderConstraint::buildJacobianInt()
-
-//-----------------------------------------------------------------------------
-
-void btSliderConstraint::solveConstraint(btScalar timeStep)
-{
- m_timeStep = timeStep;
- if(m_useLinearReferenceFrameA)
- {
- solveConstraintInt(m_rbA, m_rbB);
- }
- else
- {
- solveConstraintInt(m_rbB, m_rbA);
- }
-} // btSliderConstraint::solveConstraint()
-
-//-----------------------------------------------------------------------------
-
-void btSliderConstraint::solveConstraintInt(btRigidBody& rbA, btRigidBody& rbB)
-{
- int i;
- // linear
- btVector3 velA = rbA.getVelocityInLocalPoint(m_relPosA);
- btVector3 velB = rbB.getVelocityInLocalPoint(m_relPosB);
- btVector3 vel = velA - velB;
- for(i = 0; i < 3; i++)
- {
- const btVector3& normal = m_jacLin[i].m_linearJointAxis;
- btScalar rel_vel = normal.dot(vel);
- // calculate positional error
- btScalar depth = m_depth[i];
- // get parameters
- btScalar softness = (i) ? m_softnessOrthoLin : (m_solveLinLim ? m_softnessLimLin : m_softnessDirLin);
- btScalar restitution = (i) ? m_restitutionOrthoLin : (m_solveLinLim ? m_restitutionLimLin : m_restitutionDirLin);
- btScalar damping = (i) ? m_dampingOrthoLin : (m_solveLinLim ? m_dampingLimLin : m_dampingDirLin);
- // calcutate and apply impulse
- btScalar normalImpulse = softness * (restitution * depth / m_timeStep - damping * rel_vel) * m_jacLinDiagABInv[i];
- btVector3 impulse_vector = normal * normalImpulse;
- rbA.applyImpulse( impulse_vector, m_relPosA);
- rbB.applyImpulse(-impulse_vector, m_relPosB);
- if(m_poweredLinMotor && (!i))
- { // apply linear motor
- if(m_accumulatedLinMotorImpulse < m_maxLinMotorForce)
- {
- btScalar desiredMotorVel = m_targetLinMotorVelocity;
- btScalar motor_relvel = desiredMotorVel + rel_vel;
- normalImpulse = -motor_relvel * m_jacLinDiagABInv[i];
- // clamp accumulated impulse
- btScalar new_acc = m_accumulatedLinMotorImpulse + btFabs(normalImpulse);
- if(new_acc > m_maxLinMotorForce)
- {
- new_acc = m_maxLinMotorForce;
- }
- btScalar del = new_acc - m_accumulatedLinMotorImpulse;
- if(normalImpulse < btScalar(0.0))
- {
- normalImpulse = -del;
- }
- else
- {
- normalImpulse = del;
- }
- m_accumulatedLinMotorImpulse = new_acc;
- // apply clamped impulse
- impulse_vector = normal * normalImpulse;
- rbA.applyImpulse( impulse_vector, m_relPosA);
- rbB.applyImpulse(-impulse_vector, m_relPosB);
- }
- }
- }
- // angular
- // get axes in world space
- btVector3 axisA = m_calculatedTransformA.getBasis().getColumn(0);
- btVector3 axisB = m_calculatedTransformB.getBasis().getColumn(0);
-
- const btVector3& angVelA = rbA.getAngularVelocity();
- const btVector3& angVelB = rbB.getAngularVelocity();
-
- btVector3 angVelAroundAxisA = axisA * axisA.dot(angVelA);
- btVector3 angVelAroundAxisB = axisB * axisB.dot(angVelB);
-
- btVector3 angAorthog = angVelA - angVelAroundAxisA;
- btVector3 angBorthog = angVelB - angVelAroundAxisB;
- btVector3 velrelOrthog = angAorthog-angBorthog;
- //solve orthogonal angular velocity correction
- btScalar len = velrelOrthog.length();
- if (len > btScalar(0.00001))
- {
- btVector3 normal = velrelOrthog.normalized();
- btScalar denom = rbA.computeAngularImpulseDenominator(normal) + rbB.computeAngularImpulseDenominator(normal);
- velrelOrthog *= (btScalar(1.)/denom) * m_dampingOrthoAng * m_softnessOrthoAng;
- }
- //solve angular positional correction
- btVector3 angularError = axisA.cross(axisB) *(btScalar(1.)/m_timeStep);
- btScalar len2 = angularError.length();
- if (len2>btScalar(0.00001))
- {
- btVector3 normal2 = angularError.normalized();
- btScalar denom2 = rbA.computeAngularImpulseDenominator(normal2) + rbB.computeAngularImpulseDenominator(normal2);
- angularError *= (btScalar(1.)/denom2) * m_restitutionOrthoAng * m_softnessOrthoAng;
- }
- // apply impulse
- rbA.applyTorqueImpulse(-velrelOrthog+angularError);
- rbB.applyTorqueImpulse(velrelOrthog-angularError);
- btScalar impulseMag;
- //solve angular limits
- if(m_solveAngLim)
- {
- impulseMag = (angVelB - angVelA).dot(axisA) * m_dampingLimAng + m_angDepth * m_restitutionLimAng / m_timeStep;
- impulseMag *= m_kAngle * m_softnessLimAng;
- }
- else
- {
- impulseMag = (angVelB - angVelA).dot(axisA) * m_dampingDirAng + m_angDepth * m_restitutionDirAng / m_timeStep;
- impulseMag *= m_kAngle * m_softnessDirAng;
- }
- btVector3 impulse = axisA * impulseMag;
- rbA.applyTorqueImpulse(impulse);
- rbB.applyTorqueImpulse(-impulse);
- //apply angular motor
- if(m_poweredAngMotor)
- {
- if(m_accumulatedAngMotorImpulse < m_maxAngMotorForce)
- {
- btVector3 velrel = angVelAroundAxisA - angVelAroundAxisB;
- btScalar projRelVel = velrel.dot(axisA);
-
- btScalar desiredMotorVel = m_targetAngMotorVelocity;
- btScalar motor_relvel = desiredMotorVel - projRelVel;
-
- btScalar angImpulse = m_kAngle * motor_relvel;
- // clamp accumulated impulse
- btScalar new_acc = m_accumulatedAngMotorImpulse + btFabs(angImpulse);
- if(new_acc > m_maxAngMotorForce)
- {
- new_acc = m_maxAngMotorForce;
- }
- btScalar del = new_acc - m_accumulatedAngMotorImpulse;
- if(angImpulse < btScalar(0.0))
- {
- angImpulse = -del;
- }
- else
- {
- angImpulse = del;
- }
- m_accumulatedAngMotorImpulse = new_acc;
- // apply clamped impulse
- btVector3 motorImp = angImpulse * axisA;
- m_rbA.applyTorqueImpulse(motorImp);
- m_rbB.applyTorqueImpulse(-motorImp);
- }
- }
-} // btSliderConstraint::solveConstraint()
-
-//-----------------------------------------------------------------------------
-
-//-----------------------------------------------------------------------------
-
-void btSliderConstraint::calculateTransforms(void){
- if(m_useLinearReferenceFrameA)
- {
- m_calculatedTransformA = m_rbA.getCenterOfMassTransform() * m_frameInA;
- m_calculatedTransformB = m_rbB.getCenterOfMassTransform() * m_frameInB;
- }
- else
- {
- m_calculatedTransformA = m_rbB.getCenterOfMassTransform() * m_frameInB;
- m_calculatedTransformB = m_rbA.getCenterOfMassTransform() * m_frameInA;
- }
- m_realPivotAInW = m_calculatedTransformA.getOrigin();
- m_realPivotBInW = m_calculatedTransformB.getOrigin();
- m_sliderAxis = m_calculatedTransformA.getBasis().getColumn(0); // along X
- m_delta = m_realPivotBInW - m_realPivotAInW;
- m_projPivotInW = m_realPivotAInW + m_sliderAxis.dot(m_delta) * m_sliderAxis;
- btVector3 normalWorld;
- int i;
- //linear part
- for(i = 0; i < 3; i++)
- {
- normalWorld = m_calculatedTransformA.getBasis().getColumn(i);
- m_depth[i] = m_delta.dot(normalWorld);
- }
-} // btSliderConstraint::calculateTransforms()
-
-//-----------------------------------------------------------------------------
-
-void btSliderConstraint::testLinLimits(void)
-{
- m_solveLinLim = false;
- m_linPos = m_depth[0];
- if(m_lowerLinLimit <= m_upperLinLimit)
- {
- if(m_depth[0] > m_upperLinLimit)
- {
- m_depth[0] -= m_upperLinLimit;
- m_solveLinLim = true;
- }
- else if(m_depth[0] < m_lowerLinLimit)
- {
- m_depth[0] -= m_lowerLinLimit;
- m_solveLinLim = true;
- }
- else
- {
- m_depth[0] = btScalar(0.);
- }
- }
- else
- {
- m_depth[0] = btScalar(0.);
- }
-} // btSliderConstraint::testLinLimits()
-
-//-----------------------------------------------------------------------------
-
-
-void btSliderConstraint::testAngLimits(void)
-{
- m_angDepth = btScalar(0.);
- m_solveAngLim = false;
- if(m_lowerAngLimit <= m_upperAngLimit)
- {
- const btVector3 axisA0 = m_calculatedTransformA.getBasis().getColumn(1);
- const btVector3 axisA1 = m_calculatedTransformA.getBasis().getColumn(2);
- const btVector3 axisB0 = m_calculatedTransformB.getBasis().getColumn(1);
- btScalar rot = btAtan2Fast(axisB0.dot(axisA1), axisB0.dot(axisA0));
- if(rot < m_lowerAngLimit)
- {
- m_angDepth = rot - m_lowerAngLimit;
- m_solveAngLim = true;
- }
- else if(rot > m_upperAngLimit)
- {
- m_angDepth = rot - m_upperAngLimit;
- m_solveAngLim = true;
- }
- }
-} // btSliderConstraint::testAngLimits()
-
-
-//-----------------------------------------------------------------------------
-
-
-
-btVector3 btSliderConstraint::getAncorInA(void)
-{
- btVector3 ancorInA;
- ancorInA = m_realPivotAInW + (m_lowerLinLimit + m_upperLinLimit) * btScalar(0.5) * m_sliderAxis;
- ancorInA = m_rbA.getCenterOfMassTransform().inverse() * ancorInA;
- return ancorInA;
-} // btSliderConstraint::getAncorInA()
-
-//-----------------------------------------------------------------------------
-
-btVector3 btSliderConstraint::getAncorInB(void)
-{
- btVector3 ancorInB;
- ancorInB = m_frameInB.getOrigin();
- return ancorInB;
-} // btSliderConstraint::getAncorInB();
diff --git a/extern/bullet2/src/BulletDynamics/ConstraintSolver/btSliderConstraint.h b/extern/bullet2/src/BulletDynamics/ConstraintSolver/btSliderConstraint.h
deleted file mode 100644
index 580dfa1178d..00000000000
--- a/extern/bullet2/src/BulletDynamics/ConstraintSolver/btSliderConstraint.h
+++ /dev/null
@@ -1,218 +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.
-*/
-
-/*
-Added by Roman Ponomarev (rponom@gmail.com)
-April 04, 2008
-
-TODO:
- - add clamping od accumulated impulse to improve stability
- - add conversion for ODE constraint solver
-*/
-
-#ifndef SLIDER_CONSTRAINT_H
-#define SLIDER_CONSTRAINT_H
-
-//-----------------------------------------------------------------------------
-
-#include "LinearMath/btVector3.h"
-#include "btJacobianEntry.h"
-#include "btTypedConstraint.h"
-
-//-----------------------------------------------------------------------------
-
-class btRigidBody;
-
-//-----------------------------------------------------------------------------
-
-#define SLIDER_CONSTRAINT_DEF_SOFTNESS (btScalar(1.0))
-#define SLIDER_CONSTRAINT_DEF_DAMPING (btScalar(1.0))
-#define SLIDER_CONSTRAINT_DEF_RESTITUTION (btScalar(0.7))
-
-//-----------------------------------------------------------------------------
-
-class btSliderConstraint : public btTypedConstraint
-{
-protected:
- btTransform m_frameInA;
- btTransform m_frameInB;
- // use frameA fo define limits, if true
- bool m_useLinearReferenceFrameA;
- // linear limits
- btScalar m_lowerLinLimit;
- btScalar m_upperLinLimit;
- // angular limits
- btScalar m_lowerAngLimit;
- btScalar m_upperAngLimit;
- // softness, restitution and damping for different cases
- // DirLin - moving inside linear limits
- // LimLin - hitting linear limit
- // DirAng - moving inside angular limits
- // LimAng - hitting angular limit
- // OrthoLin, OrthoAng - against constraint axis
- btScalar m_softnessDirLin;
- btScalar m_restitutionDirLin;
- btScalar m_dampingDirLin;
- btScalar m_softnessDirAng;
- btScalar m_restitutionDirAng;
- btScalar m_dampingDirAng;
- btScalar m_softnessLimLin;
- btScalar m_restitutionLimLin;
- btScalar m_dampingLimLin;
- btScalar m_softnessLimAng;
- btScalar m_restitutionLimAng;
- btScalar m_dampingLimAng;
- btScalar m_softnessOrthoLin;
- btScalar m_restitutionOrthoLin;
- btScalar m_dampingOrthoLin;
- btScalar m_softnessOrthoAng;
- btScalar m_restitutionOrthoAng;
- btScalar m_dampingOrthoAng;
-
- // for interlal use
- bool m_solveLinLim;
- bool m_solveAngLim;
-
- btJacobianEntry m_jacLin[3];
- btScalar m_jacLinDiagABInv[3];
-
- btJacobianEntry m_jacAng[3];
-
- btScalar m_timeStep;
- btTransform m_calculatedTransformA;
- btTransform m_calculatedTransformB;
-
- btVector3 m_sliderAxis;
- btVector3 m_realPivotAInW;
- btVector3 m_realPivotBInW;
- btVector3 m_projPivotInW;
- btVector3 m_delta;
- btVector3 m_depth;
- btVector3 m_relPosA;
- btVector3 m_relPosB;
-
- btScalar m_linPos;
-
- btScalar m_angDepth;
- btScalar m_kAngle;
-
- bool m_poweredLinMotor;
- btScalar m_targetLinMotorVelocity;
- btScalar m_maxLinMotorForce;
- btScalar m_accumulatedLinMotorImpulse;
-
- bool m_poweredAngMotor;
- btScalar m_targetAngMotorVelocity;
- btScalar m_maxAngMotorForce;
- btScalar m_accumulatedAngMotorImpulse;
-
- //------------------------
- void initParams();
-public:
- // constructors
- btSliderConstraint(btRigidBody& rbA, btRigidBody& rbB, const btTransform& frameInA, const btTransform& frameInB ,bool useLinearReferenceFrameA);
- btSliderConstraint();
- // overrides
- virtual void buildJacobian();
- virtual void solveConstraint(btScalar timeStep);
- // access
- const btRigidBody& getRigidBodyA() const { return m_rbA; }
- const btRigidBody& getRigidBodyB() const { return m_rbB; }
- const btTransform & getCalculatedTransformA() const { return m_calculatedTransformA; }
- const btTransform & getCalculatedTransformB() const { return m_calculatedTransformB; }
- const btTransform & getFrameOffsetA() const { return m_frameInA; }
- const btTransform & getFrameOffsetB() const { return m_frameInB; }
- btTransform & getFrameOffsetA() { return m_frameInA; }
- btTransform & getFrameOffsetB() { return m_frameInB; }
- btScalar getLowerLinLimit() { return m_lowerLinLimit; }
- void setLowerLinLimit(btScalar lowerLimit) { m_lowerLinLimit = lowerLimit; }
- btScalar getUpperLinLimit() { return m_upperLinLimit; }
- void setUpperLinLimit(btScalar upperLimit) { m_upperLinLimit = upperLimit; }
- btScalar getLowerAngLimit() { return m_lowerAngLimit; }
- void setLowerAngLimit(btScalar lowerLimit) { m_lowerAngLimit = lowerLimit; }
- btScalar getUpperAngLimit() { return m_upperAngLimit; }
- void setUpperAngLimit(btScalar upperLimit) { m_upperAngLimit = upperLimit; }
- bool getUseLinearReferenceFrameA() { return m_useLinearReferenceFrameA; }
- btScalar getSoftnessDirLin() { return m_softnessDirLin; }
- btScalar getRestitutionDirLin() { return m_restitutionDirLin; }
- btScalar getDampingDirLin() { return m_dampingDirLin ; }
- btScalar getSoftnessDirAng() { return m_softnessDirAng; }
- btScalar getRestitutionDirAng() { return m_restitutionDirAng; }
- btScalar getDampingDirAng() { return m_dampingDirAng; }
- btScalar getSoftnessLimLin() { return m_softnessLimLin; }
- btScalar getRestitutionLimLin() { return m_restitutionLimLin; }
- btScalar getDampingLimLin() { return m_dampingLimLin; }
- btScalar getSoftnessLimAng() { return m_softnessLimAng; }
- btScalar getRestitutionLimAng() { return m_restitutionLimAng; }
- btScalar getDampingLimAng() { return m_dampingLimAng; }
- btScalar getSoftnessOrthoLin() { return m_softnessOrthoLin; }
- btScalar getRestitutionOrthoLin() { return m_restitutionOrthoLin; }
- btScalar getDampingOrthoLin() { return m_dampingOrthoLin; }
- btScalar getSoftnessOrthoAng() { return m_softnessOrthoAng; }
- btScalar getRestitutionOrthoAng() { return m_restitutionOrthoAng; }
- btScalar getDampingOrthoAng() { return m_dampingOrthoAng; }
- void setSoftnessDirLin(btScalar softnessDirLin) { m_softnessDirLin = softnessDirLin; }
- void setRestitutionDirLin(btScalar restitutionDirLin) { m_restitutionDirLin = restitutionDirLin; }
- void setDampingDirLin(btScalar dampingDirLin) { m_dampingDirLin = dampingDirLin; }
- void setSoftnessDirAng(btScalar softnessDirAng) { m_softnessDirAng = softnessDirAng; }
- void setRestitutionDirAng(btScalar restitutionDirAng) { m_restitutionDirAng = restitutionDirAng; }
- void setDampingDirAng(btScalar dampingDirAng) { m_dampingDirAng = dampingDirAng; }
- void setSoftnessLimLin(btScalar softnessLimLin) { m_softnessLimLin = softnessLimLin; }
- void setRestitutionLimLin(btScalar restitutionLimLin) { m_restitutionLimLin = restitutionLimLin; }
- void setDampingLimLin(btScalar dampingLimLin) { m_dampingLimLin = dampingLimLin; }
- void setSoftnessLimAng(btScalar softnessLimAng) { m_softnessLimAng = softnessLimAng; }
- void setRestitutionLimAng(btScalar restitutionLimAng) { m_restitutionLimAng = restitutionLimAng; }
- void setDampingLimAng(btScalar dampingLimAng) { m_dampingLimAng = dampingLimAng; }
- void setSoftnessOrthoLin(btScalar softnessOrthoLin) { m_softnessOrthoLin = softnessOrthoLin; }
- void setRestitutionOrthoLin(btScalar restitutionOrthoLin) { m_restitutionOrthoLin = restitutionOrthoLin; }
- void setDampingOrthoLin(btScalar dampingOrthoLin) { m_dampingOrthoLin = dampingOrthoLin; }
- void setSoftnessOrthoAng(btScalar softnessOrthoAng) { m_softnessOrthoAng = softnessOrthoAng; }
- void setRestitutionOrthoAng(btScalar restitutionOrthoAng) { m_restitutionOrthoAng = restitutionOrthoAng; }
- void setDampingOrthoAng(btScalar dampingOrthoAng) { m_dampingOrthoAng = dampingOrthoAng; }
- void setPoweredLinMotor(bool onOff) { m_poweredLinMotor = onOff; }
- bool getPoweredLinMotor() { return m_poweredLinMotor; }
- void setTargetLinMotorVelocity(btScalar targetLinMotorVelocity) { m_targetLinMotorVelocity = targetLinMotorVelocity; }
- btScalar getTargetLinMotorVelocity() { return m_targetLinMotorVelocity; }
- void setMaxLinMotorForce(btScalar maxLinMotorForce) { m_maxLinMotorForce = maxLinMotorForce; }
- btScalar getMaxLinMotorForce() { return m_maxLinMotorForce; }
- void setPoweredAngMotor(bool onOff) { m_poweredAngMotor = onOff; }
- bool getPoweredAngMotor() { return m_poweredAngMotor; }
- void setTargetAngMotorVelocity(btScalar targetAngMotorVelocity) { m_targetAngMotorVelocity = targetAngMotorVelocity; }
- btScalar getTargetAngMotorVelocity() { return m_targetAngMotorVelocity; }
- void setMaxAngMotorForce(btScalar maxAngMotorForce) { m_maxAngMotorForce = maxAngMotorForce; }
- btScalar getMaxAngMotorForce() { return m_maxAngMotorForce; }
- btScalar getLinearPos() { return m_linPos; }
-
- // access for ODE solver
- bool getSolveLinLimit() { return m_solveLinLim; }
- btScalar getLinDepth() { return m_depth[0]; }
- bool getSolveAngLimit() { return m_solveAngLim; }
- btScalar getAngDepth() { return m_angDepth; }
- // internal
- void buildJacobianInt(btRigidBody& rbA, btRigidBody& rbB, const btTransform& frameInA, const btTransform& frameInB);
- void solveConstraintInt(btRigidBody& rbA, btRigidBody& rbB);
- // shared code used by ODE solver
- void calculateTransforms(void);
- void testLinLimits(void);
- void testAngLimits(void);
- // access for PE Solver
- btVector3 getAncorInA(void);
- btVector3 getAncorInB(void);
-};
-
-//-----------------------------------------------------------------------------
-
-#endif //SLIDER_CONSTRAINT_H
-
diff --git a/extern/bullet2/src/BulletDynamics/Dynamics/btContinuousDynamicsWorld.cpp b/extern/bullet2/src/BulletDynamics/Dynamics/btContinuousDynamicsWorld.cpp
deleted file mode 100644
index 19443adc723..00000000000
--- a/extern/bullet2/src/BulletDynamics/Dynamics/btContinuousDynamicsWorld.cpp
+++ /dev/null
@@ -1,193 +0,0 @@
-/*
-Bullet Continuous Collision Detection and Physics Library
-Copyright (c) 2003-2007 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 "btContinuousDynamicsWorld.h"
-#include "LinearMath/btQuickprof.h"
-
-//collision detection
-#include "BulletCollision/CollisionDispatch/btCollisionDispatcher.h"
-#include "BulletCollision/BroadphaseCollision/btSimpleBroadphase.h"
-#include "BulletCollision/CollisionShapes/btCollisionShape.h"
-#include "BulletCollision/CollisionDispatch/btSimulationIslandManager.h"
-
-//rigidbody & constraints
-#include "BulletDynamics/Dynamics/btRigidBody.h"
-#include "BulletDynamics/ConstraintSolver/btSequentialImpulseConstraintSolver.h"
-#include "BulletDynamics/ConstraintSolver/btContactSolverInfo.h"
-#include "BulletDynamics/ConstraintSolver/btTypedConstraint.h"
-
-
-
-#include <stdio.h>
-
-btContinuousDynamicsWorld::btContinuousDynamicsWorld(btDispatcher* dispatcher,btBroadphaseInterface* pairCache,btConstraintSolver* constraintSolver,btCollisionConfiguration* collisionConfiguration)
-:btDiscreteDynamicsWorld(dispatcher,pairCache,constraintSolver,collisionConfiguration)
-{
-}
-
-btContinuousDynamicsWorld::~btContinuousDynamicsWorld()
-{
-}
-
-
-void btContinuousDynamicsWorld::internalSingleStepSimulation( btScalar timeStep)
-{
-
- startProfiling(timeStep);
-
-
- ///update aabbs information
- updateAabbs();
- //static int frame=0;
-// printf("frame %d\n",frame++);
-
- ///apply gravity, predict motion
- predictUnconstraintMotion(timeStep);
-
- btDispatcherInfo& dispatchInfo = getDispatchInfo();
-
- dispatchInfo.m_timeStep = timeStep;
- dispatchInfo.m_stepCount = 0;
- dispatchInfo.m_debugDraw = getDebugDrawer();
-
- ///perform collision detection
- performDiscreteCollisionDetection();
-
- calculateSimulationIslands();
-
-
- getSolverInfo().m_timeStep = timeStep;
-
-
-
- ///solve contact and other joint constraints
- solveConstraints(getSolverInfo());
-
- ///CallbackTriggers();
- calculateTimeOfImpacts(timeStep);
-
- btScalar toi = dispatchInfo.m_timeOfImpact;
-// if (toi < 1.f)
-// printf("toi = %f\n",toi);
- if (toi < 0.f)
- printf("toi = %f\n",toi);
-
-
- ///integrate transforms
- integrateTransforms(timeStep * toi);
-
- ///update vehicle simulation
- updateVehicles(timeStep);
-
-
- updateActivationState( timeStep );
-
- if(0 != m_internalTickCallback) {
- (*m_internalTickCallback)(this, timeStep);
- }
-}
-
-void btContinuousDynamicsWorld::calculateTimeOfImpacts(btScalar timeStep)
-{
- ///these should be 'temporal' aabbs!
- updateTemporalAabbs(timeStep);
-
- ///'toi' is the global smallest time of impact. However, we just calculate the time of impact for each object individually.
- ///so we handle the case moving versus static properly, and we cheat for moving versus moving
- btScalar toi = 1.f;
-
-
- btDispatcherInfo& dispatchInfo = getDispatchInfo();
- dispatchInfo.m_timeStep = timeStep;
- dispatchInfo.m_timeOfImpact = 1.f;
- dispatchInfo.m_stepCount = 0;
- dispatchInfo.m_dispatchFunc = btDispatcherInfo::DISPATCH_CONTINUOUS;
-
- ///calculate time of impact for overlapping pairs
-
-
- btDispatcher* dispatcher = getDispatcher();
- if (dispatcher)
- dispatcher->dispatchAllCollisionPairs(m_broadphasePairCache->getOverlappingPairCache(),dispatchInfo,m_dispatcher1);
-
- toi = dispatchInfo.m_timeOfImpact;
-
- dispatchInfo.m_dispatchFunc = btDispatcherInfo::DISPATCH_DISCRETE;
-
-}
-
-void btContinuousDynamicsWorld::updateTemporalAabbs(btScalar timeStep)
-{
-
- btVector3 temporalAabbMin,temporalAabbMax;
-
- for ( int i=0;i<m_collisionObjects.size();i++)
- {
- btCollisionObject* colObj = m_collisionObjects[i];
-
- btRigidBody* body = btRigidBody::upcast(colObj);
- if (body)
- {
- body->getCollisionShape()->getAabb(m_collisionObjects[i]->getWorldTransform(),temporalAabbMin,temporalAabbMax);
- const btVector3& linvel = body->getLinearVelocity();
-
- //make the AABB temporal
- btScalar temporalAabbMaxx = temporalAabbMax.getX();
- btScalar temporalAabbMaxy = temporalAabbMax.getY();
- btScalar temporalAabbMaxz = temporalAabbMax.getZ();
- btScalar temporalAabbMinx = temporalAabbMin.getX();
- btScalar temporalAabbMiny = temporalAabbMin.getY();
- btScalar temporalAabbMinz = temporalAabbMin.getZ();
-
- // add linear motion
- btVector3 linMotion = linvel*timeStep;
-
- if (linMotion.x() > 0.f)
- temporalAabbMaxx += linMotion.x();
- else
- temporalAabbMinx += linMotion.x();
- if (linMotion.y() > 0.f)
- temporalAabbMaxy += linMotion.y();
- else
- temporalAabbMiny += linMotion.y();
- if (linMotion.z() > 0.f)
- temporalAabbMaxz += linMotion.z();
- else
- temporalAabbMinz += linMotion.z();
-
- //add conservative angular motion
- btScalar angularMotion(0);// = angvel.length() * GetAngularMotionDisc() * timeStep;
- btVector3 angularMotion3d(angularMotion,angularMotion,angularMotion);
- temporalAabbMin = btVector3(temporalAabbMinx,temporalAabbMiny,temporalAabbMinz);
- temporalAabbMax = btVector3(temporalAabbMaxx,temporalAabbMaxy,temporalAabbMaxz);
-
- temporalAabbMin -= angularMotion3d;
- temporalAabbMax += angularMotion3d;
-
- m_broadphasePairCache->setAabb(body->getBroadphaseHandle(),temporalAabbMin,temporalAabbMax,m_dispatcher1);
- }
- }
-
- //update aabb (of all moved objects)
-
- m_broadphasePairCache->calculateOverlappingPairs(m_dispatcher1);
-
-
-
-}
-
-
-
diff --git a/extern/bullet2/src/BulletDynamics/Dynamics/btContinuousDynamicsWorld.h b/extern/bullet2/src/BulletDynamics/Dynamics/btContinuousDynamicsWorld.h
deleted file mode 100644
index 61c8dea03eb..00000000000
--- a/extern/bullet2/src/BulletDynamics/Dynamics/btContinuousDynamicsWorld.h
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
-Bullet Continuous Collision Detection and Physics Library
-Copyright (c) 2003-2007 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 BT_CONTINUOUS_DYNAMICS_WORLD_H
-#define BT_CONTINUOUS_DYNAMICS_WORLD_H
-
-#include "btDiscreteDynamicsWorld.h"
-
-///btContinuousDynamicsWorld adds optional (per object) continuous collision detection for fast moving objects to the btDiscreteDynamicsWorld.
-///This copes with fast moving objects that otherwise would tunnel/miss collisions.
-///Under construction, don't use yet! Please use btDiscreteDynamicsWorld instead.
-class btContinuousDynamicsWorld : public btDiscreteDynamicsWorld
-{
-
- void updateTemporalAabbs(btScalar timeStep);
-
- public:
-
- btContinuousDynamicsWorld(btDispatcher* dispatcher,btBroadphaseInterface* pairCache,btConstraintSolver* constraintSolver,btCollisionConfiguration* collisionConfiguration);
- virtual ~btContinuousDynamicsWorld();
-
- ///time stepping with calculation of time of impact for selected fast moving objects
- virtual void internalSingleStepSimulation( btScalar timeStep);
-
- virtual void calculateTimeOfImpacts(btScalar timeStep);
-
- virtual btDynamicsWorldType getWorldType() const
- {
- return BT_CONTINUOUS_DYNAMICS_WORLD;
- }
-
-};
-
-#endif //BT_CONTINUOUS_DYNAMICS_WORLD_H
diff --git a/extern/bullet2/src/BulletSoftBody/btSoftBodyRigidBodyCollisionConfiguration.cpp b/extern/bullet2/src/BulletSoftBody/btSoftBodyRigidBodyCollisionConfiguration.cpp
index 53ac2782583..e79dd214e62 100644
--- a/extern/bullet2/src/BulletSoftBody/btSoftBodyRigidBodyCollisionConfiguration.cpp
+++ b/extern/bullet2/src/BulletSoftBody/btSoftBodyRigidBodyCollisionConfiguration.cpp
@@ -62,7 +62,6 @@ btSoftBodyRigidBodyCollisionConfiguration::btSoftBodyRigidBodyCollisionConfigura
collisionAlgorithmMaxElementSize = btMax(collisionAlgorithmMaxElementSize,maxSize2);
if (collisionAlgorithmMaxElementSize > curElemSize)
{
- m_collisionAlgorithmPool->~btPoolAllocator();
btAlignedFree(m_collisionAlgorithmPool);
void* mem = btAlignedAlloc(sizeof(btPoolAllocator),16);
m_collisionAlgorithmPool = new(mem) btPoolAllocator(collisionAlgorithmMaxElementSize,constructionInfo.m_defaultMaxCollisionAlgorithmPoolSize);
diff --git a/extern/bullet2/src/LinearMath/btConvexHull.cpp b/extern/bullet2/src/LinearMath/btConvexHull.cpp
deleted file mode 100644
index b8929a86808..00000000000
--- a/extern/bullet2/src/LinearMath/btConvexHull.cpp
+++ /dev/null
@@ -1,1174 +0,0 @@
-/*
-Stan Melax Convex Hull Computation
-Copyright (c) 2003-2006 Stan Melax http://www.melax.com/
-
-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 <string.h>
-
-#include "btConvexHull.h"
-#include "LinearMath/btAlignedObjectArray.h"
-#include "LinearMath/btMinMax.h"
-#include "LinearMath/btVector3.h"
-
-
-
-template <class T>
-void Swap(T &a,T &b)
-{
- T tmp = a;
- a=b;
- b=tmp;
-}
-
-
-//----------------------------------
-
-class int3
-{
-public:
- int x,y,z;
- int3(){};
- int3(int _x,int _y, int _z){x=_x;y=_y;z=_z;}
- const int& operator[](int i) const {return (&x)[i];}
- int& operator[](int i) {return (&x)[i];}
-};
-
-
-//------- btPlane ----------
-
-
-inline btPlane PlaneFlip(const btPlane &plane){return btPlane(-plane.normal,-plane.dist);}
-inline int operator==( const btPlane &a, const btPlane &b ) { return (a.normal==b.normal && a.dist==b.dist); }
-inline int coplanar( const btPlane &a, const btPlane &b ) { return (a==b || a==PlaneFlip(b)); }
-
-
-//--------- Utility Functions ------
-
-btVector3 PlaneLineIntersection(const btPlane &plane, const btVector3 &p0, const btVector3 &p1);
-btVector3 PlaneProject(const btPlane &plane, const btVector3 &point);
-
-btVector3 ThreePlaneIntersection(const btPlane &p0,const btPlane &p1, const btPlane &p2);
-btVector3 ThreePlaneIntersection(const btPlane &p0,const btPlane &p1, const btPlane &p2)
-{
- btVector3 N1 = p0.normal;
- btVector3 N2 = p1.normal;
- btVector3 N3 = p2.normal;
-
- btVector3 n2n3; n2n3 = N2.cross(N3);
- btVector3 n3n1; n3n1 = N3.cross(N1);
- btVector3 n1n2; n1n2 = N1.cross(N2);
-
- btScalar quotient = (N1.dot(n2n3));
-
- btAssert(btFabs(quotient) > btScalar(0.000001));
-
- quotient = btScalar(-1.) / quotient;
- n2n3 *= p0.dist;
- n3n1 *= p1.dist;
- n1n2 *= p2.dist;
- btVector3 potentialVertex = n2n3;
- potentialVertex += n3n1;
- potentialVertex += n1n2;
- potentialVertex *= quotient;
-
- btVector3 result(potentialVertex.getX(),potentialVertex.getY(),potentialVertex.getZ());
- return result;
-
-}
-
-btScalar DistanceBetweenLines(const btVector3 &ustart, const btVector3 &udir, const btVector3 &vstart, const btVector3 &vdir, btVector3 *upoint=NULL, btVector3 *vpoint=NULL);
-btVector3 TriNormal(const btVector3 &v0, const btVector3 &v1, const btVector3 &v2);
-btVector3 NormalOf(const btVector3 *vert, const int n);
-
-
-btVector3 PlaneLineIntersection(const btPlane &plane, const btVector3 &p0, const btVector3 &p1)
-{
- // returns the point where the line p0-p1 intersects the plane n&d
- static btVector3 dif;
- dif = p1-p0;
- btScalar dn= dot(plane.normal,dif);
- btScalar t = -(plane.dist+dot(plane.normal,p0) )/dn;
- return p0 + (dif*t);
-}
-
-btVector3 PlaneProject(const btPlane &plane, const btVector3 &point)
-{
- return point - plane.normal * (dot(point,plane.normal)+plane.dist);
-}
-
-btVector3 TriNormal(const btVector3 &v0, const btVector3 &v1, const btVector3 &v2)
-{
- // return the normal of the triangle
- // inscribed by v0, v1, and v2
- btVector3 cp=cross(v1-v0,v2-v1);
- btScalar m=cp.length();
- if(m==0) return btVector3(1,0,0);
- return cp*(btScalar(1.0)/m);
-}
-
-
-btScalar DistanceBetweenLines(const btVector3 &ustart, const btVector3 &udir, const btVector3 &vstart, const btVector3 &vdir, btVector3 *upoint, btVector3 *vpoint)
-{
- static btVector3 cp;
- cp = cross(udir,vdir).normalized();
-
- btScalar distu = -dot(cp,ustart);
- btScalar distv = -dot(cp,vstart);
- btScalar dist = (btScalar)fabs(distu-distv);
- if(upoint)
- {
- btPlane plane;
- plane.normal = cross(vdir,cp).normalized();
- plane.dist = -dot(plane.normal,vstart);
- *upoint = PlaneLineIntersection(plane,ustart,ustart+udir);
- }
- if(vpoint)
- {
- btPlane plane;
- plane.normal = cross(udir,cp).normalized();
- plane.dist = -dot(plane.normal,ustart);
- *vpoint = PlaneLineIntersection(plane,vstart,vstart+vdir);
- }
- return dist;
-}
-
-
-
-
-
-
-
-#define COPLANAR (0)
-#define UNDER (1)
-#define OVER (2)
-#define SPLIT (OVER|UNDER)
-#define PAPERWIDTH (btScalar(0.001))
-
-btScalar planetestepsilon = PAPERWIDTH;
-
-
-
-typedef ConvexH::HalfEdge HalfEdge;
-
-ConvexH::ConvexH(int vertices_size,int edges_size,int facets_size)
-{
- vertices.resize(vertices_size);
- edges.resize(edges_size);
- facets.resize(facets_size);
-}
-
-
-int PlaneTest(const btPlane &p, const btVector3 &v);
-int PlaneTest(const btPlane &p, const btVector3 &v) {
- btScalar a = dot(v,p.normal)+p.dist;
- int flag = (a>planetestepsilon)?OVER:((a<-planetestepsilon)?UNDER:COPLANAR);
- return flag;
-}
-
-int SplitTest(ConvexH &convex,const btPlane &plane);
-int SplitTest(ConvexH &convex,const btPlane &plane) {
- int flag=0;
- for(int i=0;i<convex.vertices.size();i++) {
- flag |= PlaneTest(plane,convex.vertices[i]);
- }
- return flag;
-}
-
-class VertFlag
-{
-public:
- unsigned char planetest;
- unsigned char junk;
- unsigned char undermap;
- unsigned char overmap;
-};
-class EdgeFlag
-{
-public:
- unsigned char planetest;
- unsigned char fixes;
- short undermap;
- short overmap;
-};
-class PlaneFlag
-{
-public:
- unsigned char undermap;
- unsigned char overmap;
-};
-class Coplanar{
-public:
- unsigned short ea;
- unsigned char v0;
- unsigned char v1;
-};
-
-
-
-
-
-
-
-
-template<class T>
-int maxdirfiltered(const T *p,int count,const T &dir,btAlignedObjectArray<int> &allow)
-{
- btAssert(count);
- int m=-1;
- for(int i=0;i<count;i++)
- if(allow[i])
- {
- if(m==-1 || dot(p[i],dir)>dot(p[m],dir))
- m=i;
- }
- btAssert(m!=-1);
- return m;
-}
-
-btVector3 orth(const btVector3 &v);
-btVector3 orth(const btVector3 &v)
-{
- btVector3 a=cross(v,btVector3(0,0,1));
- btVector3 b=cross(v,btVector3(0,1,0));
- if (a.length() > b.length())
- {
- return a.normalized();
- } else {
- return b.normalized();
- }
-}
-
-
-template<class T>
-int maxdirsterid(const T *p,int count,const T &dir,btAlignedObjectArray<int> &allow)
-{
- int m=-1;
- while(m==-1)
- {
- m = maxdirfiltered(p,count,dir,allow);
- if(allow[m]==3) return m;
- T u = orth(dir);
- T v = cross(u,dir);
- int ma=-1;
- for(btScalar x = btScalar(0.0) ; x<= btScalar(360.0) ; x+= btScalar(45.0))
- {
- btScalar s = sinf(SIMD_RADS_PER_DEG*(x));
- btScalar c = cosf(SIMD_RADS_PER_DEG*(x));
- int mb = maxdirfiltered(p,count,dir+(u*s+v*c)*btScalar(0.025),allow);
- if(ma==m && mb==m)
- {
- allow[m]=3;
- return m;
- }
- if(ma!=-1 && ma!=mb) // Yuck - this is really ugly
- {
- int mc = ma;
- for(btScalar xx = x-btScalar(40.0) ; xx <= x ; xx+= btScalar(5.0))
- {
- btScalar s = sinf(SIMD_RADS_PER_DEG*(xx));
- btScalar c = cosf(SIMD_RADS_PER_DEG*(xx));
- int md = maxdirfiltered(p,count,dir+(u*s+v*c)*btScalar(0.025),allow);
- if(mc==m && md==m)
- {
- allow[m]=3;
- return m;
- }
- mc=md;
- }
- }
- ma=mb;
- }
- allow[m]=0;
- m=-1;
- }
- btAssert(0);
- return m;
-}
-
-
-
-
-int operator ==(const int3 &a,const int3 &b);
-int operator ==(const int3 &a,const int3 &b)
-{
- for(int i=0;i<3;i++)
- {
- if(a[i]!=b[i]) return 0;
- }
- return 1;
-}
-
-
-int above(btVector3* vertices,const int3& t, const btVector3 &p, btScalar epsilon);
-int above(btVector3* vertices,const int3& t, const btVector3 &p, btScalar epsilon)
-{
- btVector3 n=TriNormal(vertices[t[0]],vertices[t[1]],vertices[t[2]]);
- return (dot(n,p-vertices[t[0]]) > epsilon); // EPSILON???
-}
-int hasedge(const int3 &t, int a,int b);
-int hasedge(const int3 &t, int a,int b)
-{
- for(int i=0;i<3;i++)
- {
- int i1= (i+1)%3;
- if(t[i]==a && t[i1]==b) return 1;
- }
- return 0;
-}
-int hasvert(const int3 &t, int v);
-int hasvert(const int3 &t, int v)
-{
- return (t[0]==v || t[1]==v || t[2]==v) ;
-}
-int shareedge(const int3 &a,const int3 &b);
-int shareedge(const int3 &a,const int3 &b)
-{
- int i;
- for(i=0;i<3;i++)
- {
- int i1= (i+1)%3;
- if(hasedge(a,b[i1],b[i])) return 1;
- }
- return 0;
-}
-
-class Tri;
-
-
-
-class Tri : public int3
-{
-public:
- int3 n;
- int id;
- int vmax;
- btScalar rise;
- Tri(int a,int b,int c):int3(a,b,c),n(-1,-1,-1)
- {
- vmax=-1;
- rise = btScalar(0.0);
- }
- ~Tri()
- {
- }
- int &neib(int a,int b);
-};
-
-
-int &Tri::neib(int a,int b)
-{
- static int er=-1;
- int i;
- for(i=0;i<3;i++)
- {
- int i1=(i+1)%3;
- int i2=(i+2)%3;
- if((*this)[i]==a && (*this)[i1]==b) return n[i2];
- if((*this)[i]==b && (*this)[i1]==a) return n[i2];
- }
- btAssert(0);
- return er;
-}
-void HullLibrary::b2bfix(Tri* s,Tri*t)
-{
- int i;
- for(i=0;i<3;i++)
- {
- int i1=(i+1)%3;
- int i2=(i+2)%3;
- int a = (*s)[i1];
- int b = (*s)[i2];
- btAssert(m_tris[s->neib(a,b)]->neib(b,a) == s->id);
- btAssert(m_tris[t->neib(a,b)]->neib(b,a) == t->id);
- m_tris[s->neib(a,b)]->neib(b,a) = t->neib(b,a);
- m_tris[t->neib(b,a)]->neib(a,b) = s->neib(a,b);
- }
-}
-
-void HullLibrary::removeb2b(Tri* s,Tri*t)
-{
- b2bfix(s,t);
- deAllocateTriangle(s);
-
- deAllocateTriangle(t);
-}
-
-void HullLibrary::checkit(Tri *t)
-{
- (void)t;
-
- int i;
- btAssert(m_tris[t->id]==t);
- for(i=0;i<3;i++)
- {
- int i1=(i+1)%3;
- int i2=(i+2)%3;
- int a = (*t)[i1];
- int b = (*t)[i2];
-
- // release compile fix
- (void)i1;
- (void)i2;
- (void)a;
- (void)b;
-
- btAssert(a!=b);
- btAssert( m_tris[t->n[i]]->neib(b,a) == t->id);
- }
-}
-
-Tri* HullLibrary::allocateTriangle(int a,int b,int c)
-{
- void* mem = btAlignedAlloc(sizeof(Tri),16);
- Tri* tr = new (mem)Tri(a,b,c);
- tr->id = m_tris.size();
- m_tris.push_back(tr);
-
- return tr;
-}
-
-void HullLibrary::deAllocateTriangle(Tri* tri)
-{
- btAssert(m_tris[tri->id]==tri);
- m_tris[tri->id]=NULL;
- tri->~Tri();
- btAlignedFree(tri);
-}
-
-
-void HullLibrary::extrude(Tri *t0,int v)
-{
- int3 t= *t0;
- int n = m_tris.size();
- Tri* ta = allocateTriangle(v,t[1],t[2]);
- ta->n = int3(t0->n[0],n+1,n+2);
- m_tris[t0->n[0]]->neib(t[1],t[2]) = n+0;
- Tri* tb = allocateTriangle(v,t[2],t[0]);
- tb->n = int3(t0->n[1],n+2,n+0);
- m_tris[t0->n[1]]->neib(t[2],t[0]) = n+1;
- Tri* tc = allocateTriangle(v,t[0],t[1]);
- tc->n = int3(t0->n[2],n+0,n+1);
- m_tris[t0->n[2]]->neib(t[0],t[1]) = n+2;
- checkit(ta);
- checkit(tb);
- checkit(tc);
- if(hasvert(*m_tris[ta->n[0]],v)) removeb2b(ta,m_tris[ta->n[0]]);
- if(hasvert(*m_tris[tb->n[0]],v)) removeb2b(tb,m_tris[tb->n[0]]);
- if(hasvert(*m_tris[tc->n[0]],v)) removeb2b(tc,m_tris[tc->n[0]]);
- deAllocateTriangle(t0);
-
-}
-
-Tri* HullLibrary::extrudable(btScalar epsilon)
-{
- int i;
- Tri *t=NULL;
- for(i=0;i<m_tris.size();i++)
- {
- if(!t || (m_tris[i] && t->rise<m_tris[i]->rise))
- {
- t = m_tris[i];
- }
- }
- return (t->rise >epsilon)?t:NULL ;
-}
-
-
-
-
-int4 HullLibrary::FindSimplex(btVector3 *verts,int verts_count,btAlignedObjectArray<int> &allow)
-{
- btVector3 basis[3];
- basis[0] = btVector3( btScalar(0.01), btScalar(0.02), btScalar(1.0) );
- int p0 = maxdirsterid(verts,verts_count, basis[0],allow);
- int p1 = maxdirsterid(verts,verts_count,-basis[0],allow);
- basis[0] = verts[p0]-verts[p1];
- if(p0==p1 || basis[0]==btVector3(0,0,0))
- return int4(-1,-1,-1,-1);
- basis[1] = cross(btVector3( btScalar(1),btScalar(0.02), btScalar(0)),basis[0]);
- basis[2] = cross(btVector3(btScalar(-0.02), btScalar(1), btScalar(0)),basis[0]);
- if (basis[1].length() > basis[2].length())
- {
- basis[1].normalize();
- } else {
- basis[1] = basis[2];
- basis[1].normalize ();
- }
- int p2 = maxdirsterid(verts,verts_count,basis[1],allow);
- if(p2 == p0 || p2 == p1)
- {
- p2 = maxdirsterid(verts,verts_count,-basis[1],allow);
- }
- if(p2 == p0 || p2 == p1)
- return int4(-1,-1,-1,-1);
- basis[1] = verts[p2] - verts[p0];
- basis[2] = cross(basis[1],basis[0]).normalized();
- int p3 = maxdirsterid(verts,verts_count,basis[2],allow);
- if(p3==p0||p3==p1||p3==p2) p3 = maxdirsterid(verts,verts_count,-basis[2],allow);
- if(p3==p0||p3==p1||p3==p2)
- return int4(-1,-1,-1,-1);
- btAssert(!(p0==p1||p0==p2||p0==p3||p1==p2||p1==p3||p2==p3));
- if(dot(verts[p3]-verts[p0],cross(verts[p1]-verts[p0],verts[p2]-verts[p0])) <0) {Swap(p2,p3);}
- return int4(p0,p1,p2,p3);
-}
-
-int HullLibrary::calchullgen(btVector3 *verts,int verts_count, int vlimit)
-{
- if(verts_count <4) return 0;
- if(vlimit==0) vlimit=1000000000;
- int j;
- btVector3 bmin(*verts),bmax(*verts);
- btAlignedObjectArray<int> isextreme;
- isextreme.reserve(verts_count);
- btAlignedObjectArray<int> allow;
- allow.reserve(verts_count);
-
- for(j=0;j<verts_count;j++)
- {
- allow.push_back(1);
- isextreme.push_back(0);
- bmin.setMin (verts[j]);
- bmax.setMax (verts[j]);
- }
- btScalar epsilon = (bmax-bmin).length() * btScalar(0.001);
- btAssert (epsilon != 0.0);
-
-
- int4 p = FindSimplex(verts,verts_count,allow);
- if(p.x==-1) return 0; // simplex failed
-
-
-
- btVector3 center = (verts[p[0]]+verts[p[1]]+verts[p[2]]+verts[p[3]]) / btScalar(4.0); // a valid interior point
- Tri *t0 = allocateTriangle(p[2],p[3],p[1]); t0->n=int3(2,3,1);
- Tri *t1 = allocateTriangle(p[3],p[2],p[0]); t1->n=int3(3,2,0);
- Tri *t2 = allocateTriangle(p[0],p[1],p[3]); t2->n=int3(0,1,3);
- Tri *t3 = allocateTriangle(p[1],p[0],p[2]); t3->n=int3(1,0,2);
- isextreme[p[0]]=isextreme[p[1]]=isextreme[p[2]]=isextreme[p[3]]=1;
- checkit(t0);checkit(t1);checkit(t2);checkit(t3);
-
- for(j=0;j<m_tris.size();j++)
- {
- Tri *t=m_tris[j];
- btAssert(t);
- btAssert(t->vmax<0);
- btVector3 n=TriNormal(verts[(*t)[0]],verts[(*t)[1]],verts[(*t)[2]]);
- t->vmax = maxdirsterid(verts,verts_count,n,allow);
- t->rise = dot(n,verts[t->vmax]-verts[(*t)[0]]);
- }
- Tri *te;
- vlimit-=4;
- while(vlimit >0 && ((te=extrudable(epsilon)) != 0))
- {
- int3 ti=*te;
- int v=te->vmax;
- btAssert(v != -1);
- btAssert(!isextreme[v]); // wtf we've already done this vertex
- isextreme[v]=1;
- //if(v==p0 || v==p1 || v==p2 || v==p3) continue; // done these already
- j=m_tris.size();
- while(j--) {
- if(!m_tris[j]) continue;
- int3 t=*m_tris[j];
- if(above(verts,t,verts[v],btScalar(0.01)*epsilon))
- {
- extrude(m_tris[j],v);
- }
- }
- // now check for those degenerate cases where we have a flipped triangle or a really skinny triangle
- j=m_tris.size();
- while(j--)
- {
- if(!m_tris[j]) continue;
- if(!hasvert(*m_tris[j],v)) break;
- int3 nt=*m_tris[j];
- if(above(verts,nt,center,btScalar(0.01)*epsilon) || cross(verts[nt[1]]-verts[nt[0]],verts[nt[2]]-verts[nt[1]]).length()< epsilon*epsilon*btScalar(0.1) )
- {
- Tri *nb = m_tris[m_tris[j]->n[0]];
- btAssert(nb);btAssert(!hasvert(*nb,v));btAssert(nb->id<j);
- extrude(nb,v);
- j=m_tris.size();
- }
- }
- j=m_tris.size();
- while(j--)
- {
- Tri *t=m_tris[j];
- if(!t) continue;
- if(t->vmax>=0) break;
- btVector3 n=TriNormal(verts[(*t)[0]],verts[(*t)[1]],verts[(*t)[2]]);
- t->vmax = maxdirsterid(verts,verts_count,n,allow);
- if(isextreme[t->vmax])
- {
- t->vmax=-1; // already done that vertex - algorithm needs to be able to terminate.
- }
- else
- {
- t->rise = dot(n,verts[t->vmax]-verts[(*t)[0]]);
- }
- }
- vlimit --;
- }
- return 1;
-}
-
-int HullLibrary::calchull(btVector3 *verts,int verts_count, TUIntArray& tris_out, int &tris_count,int vlimit)
-{
- int rc=calchullgen(verts,verts_count, vlimit) ;
- if(!rc) return 0;
- btAlignedObjectArray<int> ts;
- int i;
-
- for(i=0;i<m_tris.size();i++)
- {
- if(m_tris[i])
- {
- for(int j=0;j<3;j++)
- ts.push_back((*m_tris[i])[j]);
- deAllocateTriangle(m_tris[i]);
- }
- }
- tris_count = ts.size()/3;
- tris_out.resize(ts.size());
-
- for (i=0;i<ts.size();i++)
- {
- tris_out[i] = static_cast<unsigned int>(ts[i]);
- }
- m_tris.resize(0);
-
- return 1;
-}
-
-
-
-
-
-bool HullLibrary::ComputeHull(unsigned int vcount,const btVector3 *vertices,PHullResult &result,unsigned int vlimit)
-{
-
- int tris_count;
- int ret = calchull( (btVector3 *) vertices, (int) vcount, result.m_Indices, tris_count, static_cast<int>(vlimit) );
- if(!ret) return false;
- result.mIndexCount = (unsigned int) (tris_count*3);
- result.mFaceCount = (unsigned int) tris_count;
- result.mVertices = (btVector3*) vertices;
- result.mVcount = (unsigned int) vcount;
- return true;
-
-}
-
-
-void ReleaseHull(PHullResult &result);
-void ReleaseHull(PHullResult &result)
-{
- if ( result.m_Indices.size() )
- {
- result.m_Indices.clear();
- }
-
- result.mVcount = 0;
- result.mIndexCount = 0;
- result.mVertices = 0;
-}
-
-
-//*********************************************************************
-//*********************************************************************
-//******** HullLib header
-//*********************************************************************
-//*********************************************************************
-
-//*********************************************************************
-//*********************************************************************
-//******** HullLib implementation
-//*********************************************************************
-//*********************************************************************
-
-HullError HullLibrary::CreateConvexHull(const HullDesc &desc, // describes the input request
- HullResult &result) // contains the resulst
-{
- HullError ret = QE_FAIL;
-
-
- PHullResult hr;
-
- unsigned int vcount = desc.mVcount;
- if ( vcount < 8 ) vcount = 8;
-
- btAlignedObjectArray<btVector3> vertexSource;
- vertexSource.resize(static_cast<int>(vcount));
-
- btVector3 scale;
-
- unsigned int ovcount;
-
- bool ok = CleanupVertices(desc.mVcount,desc.mVertices, desc.mVertexStride, ovcount, &vertexSource[0], desc.mNormalEpsilon, scale ); // normalize point cloud, remove duplicates!
-
- if ( ok )
- {
-
-
-// if ( 1 ) // scale vertices back to their original size.
- {
- for (unsigned int i=0; i<ovcount; i++)
- {
- btVector3& v = vertexSource[static_cast<int>(i)];
- v[0]*=scale[0];
- v[1]*=scale[1];
- v[2]*=scale[2];
- }
- }
-
- ok = ComputeHull(ovcount,&vertexSource[0],hr,desc.mMaxVertices);
-
- if ( ok )
- {
-
- // re-index triangle mesh so it refers to only used vertices, rebuild a new vertex table.
- btAlignedObjectArray<btVector3> vertexScratch;
- vertexScratch.resize(static_cast<int>(hr.mVcount));
-
- BringOutYourDead(hr.mVertices,hr.mVcount, &vertexScratch[0], ovcount, &hr.m_Indices[0], hr.mIndexCount );
-
- ret = QE_OK;
-
- if ( desc.HasHullFlag(QF_TRIANGLES) ) // if he wants the results as triangle!
- {
- result.mPolygons = false;
- result.mNumOutputVertices = ovcount;
- result.m_OutputVertices.resize(static_cast<int>(ovcount));
- result.mNumFaces = hr.mFaceCount;
- result.mNumIndices = hr.mIndexCount;
-
- result.m_Indices.resize(static_cast<int>(hr.mIndexCount));
-
- memcpy(&result.m_OutputVertices[0], &vertexScratch[0], sizeof(btVector3)*ovcount );
-
- if ( desc.HasHullFlag(QF_REVERSE_ORDER) )
- {
-
- const unsigned int *source = &hr.m_Indices[0];
- unsigned int *dest = &result.m_Indices[0];
-
- for (unsigned int i=0; i<hr.mFaceCount; i++)
- {
- dest[0] = source[2];
- dest[1] = source[1];
- dest[2] = source[0];
- dest+=3;
- source+=3;
- }
-
- }
- else
- {
- memcpy(&result.m_Indices[0], &hr.m_Indices[0], sizeof(unsigned int)*hr.mIndexCount);
- }
- }
- else
- {
- result.mPolygons = true;
- result.mNumOutputVertices = ovcount;
- result.m_OutputVertices.resize(static_cast<int>(ovcount));
- result.mNumFaces = hr.mFaceCount;
- result.mNumIndices = hr.mIndexCount+hr.mFaceCount;
- result.m_Indices.resize(static_cast<int>(result.mNumIndices));
- memcpy(&result.m_OutputVertices[0], &vertexScratch[0], sizeof(btVector3)*ovcount );
-
-// if ( 1 )
- {
- const unsigned int *source = &hr.m_Indices[0];
- unsigned int *dest = &result.m_Indices[0];
- for (unsigned int i=0; i<hr.mFaceCount; i++)
- {
- dest[0] = 3;
- if ( desc.HasHullFlag(QF_REVERSE_ORDER) )
- {
- dest[1] = source[2];
- dest[2] = source[1];
- dest[3] = source[0];
- }
- else
- {
- dest[1] = source[0];
- dest[2] = source[1];
- dest[3] = source[2];
- }
-
- dest+=4;
- source+=3;
- }
- }
- }
- ReleaseHull(hr);
- }
- }
-
- return ret;
-}
-
-
-
-HullError HullLibrary::ReleaseResult(HullResult &result) // release memory allocated for this result, we are done with it.
-{
- if ( result.m_OutputVertices.size())
- {
- result.mNumOutputVertices=0;
- result.m_OutputVertices.clear();
- }
- if ( result.m_Indices.size() )
- {
- result.mNumIndices=0;
- result.m_Indices.clear();
- }
- return QE_OK;
-}
-
-
-static void addPoint(unsigned int &vcount,btVector3 *p,btScalar x,btScalar y,btScalar z)
-{
- // XXX, might be broken
- btVector3& dest = p[vcount];
- dest[0] = x;
- dest[1] = y;
- dest[2] = z;
- vcount++;
-}
-
-btScalar GetDist(btScalar px,btScalar py,btScalar pz,const btScalar *p2);
-btScalar GetDist(btScalar px,btScalar py,btScalar pz,const btScalar *p2)
-{
-
- btScalar dx = px - p2[0];
- btScalar dy = py - p2[1];
- btScalar dz = pz - p2[2];
-
- return dx*dx+dy*dy+dz*dz;
-}
-
-
-
-bool HullLibrary::CleanupVertices(unsigned int svcount,
- const btVector3 *svertices,
- unsigned int stride,
- unsigned int &vcount, // output number of vertices
- btVector3 *vertices, // location to store the results.
- btScalar normalepsilon,
- btVector3& scale)
-{
- if ( svcount == 0 ) return false;
-
- m_vertexIndexMapping.resize(0);
-
-
-#define EPSILON btScalar(0.000001) /* close enough to consider two btScalaring point numbers to be 'the same'. */
-
- vcount = 0;
-
- btScalar recip[3];
-
- if ( scale )
- {
- scale[0] = 1;
- scale[1] = 1;
- scale[2] = 1;
- }
-
- btScalar bmin[3] = { FLT_MAX, FLT_MAX, FLT_MAX };
- btScalar bmax[3] = { -FLT_MAX, -FLT_MAX, -FLT_MAX };
-
- const char *vtx = (const char *) svertices;
-
-// if ( 1 )
- {
- for (unsigned int i=0; i<svcount; i++)
- {
- const btScalar *p = (const btScalar *) vtx;
-
- vtx+=stride;
-
- for (int j=0; j<3; j++)
- {
- if ( p[j] < bmin[j] ) bmin[j] = p[j];
- if ( p[j] > bmax[j] ) bmax[j] = p[j];
- }
- }
- }
-
- btScalar dx = bmax[0] - bmin[0];
- btScalar dy = bmax[1] - bmin[1];
- btScalar dz = bmax[2] - bmin[2];
-
- btVector3 center;
-
- center[0] = dx*btScalar(0.5) + bmin[0];
- center[1] = dy*btScalar(0.5) + bmin[1];
- center[2] = dz*btScalar(0.5) + bmin[2];
-
- if ( dx < EPSILON || dy < EPSILON || dz < EPSILON || svcount < 3 )
- {
-
- btScalar len = FLT_MAX;
-
- if ( dx > EPSILON && dx < len ) len = dx;
- if ( dy > EPSILON && dy < len ) len = dy;
- if ( dz > EPSILON && dz < len ) len = dz;
-
- if ( len == FLT_MAX )
- {
- dx = dy = dz = btScalar(0.01); // one centimeter
- }
- else
- {
- if ( dx < EPSILON ) dx = len * btScalar(0.05); // 1/5th the shortest non-zero edge.
- if ( dy < EPSILON ) dy = len * btScalar(0.05);
- if ( dz < EPSILON ) dz = len * btScalar(0.05);
- }
-
- btScalar x1 = center[0] - dx;
- btScalar x2 = center[0] + dx;
-
- btScalar y1 = center[1] - dy;
- btScalar y2 = center[1] + dy;
-
- btScalar z1 = center[2] - dz;
- btScalar z2 = center[2] + dz;
-
- addPoint(vcount,vertices,x1,y1,z1);
- addPoint(vcount,vertices,x2,y1,z1);
- addPoint(vcount,vertices,x2,y2,z1);
- addPoint(vcount,vertices,x1,y2,z1);
- addPoint(vcount,vertices,x1,y1,z2);
- addPoint(vcount,vertices,x2,y1,z2);
- addPoint(vcount,vertices,x2,y2,z2);
- addPoint(vcount,vertices,x1,y2,z2);
-
- return true; // return cube
-
-
- }
- else
- {
- if ( scale )
- {
- scale[0] = dx;
- scale[1] = dy;
- scale[2] = dz;
-
- recip[0] = 1 / dx;
- recip[1] = 1 / dy;
- recip[2] = 1 / dz;
-
- center[0]*=recip[0];
- center[1]*=recip[1];
- center[2]*=recip[2];
-
- }
-
- }
-
-
-
- vtx = (const char *) svertices;
-
- for (unsigned int i=0; i<svcount; i++)
- {
- const btVector3 *p = (const btVector3 *)vtx;
- vtx+=stride;
-
- btScalar px = p->getX();
- btScalar py = p->getY();
- btScalar pz = p->getZ();
-
- if ( scale )
- {
- px = px*recip[0]; // normalize
- py = py*recip[1]; // normalize
- pz = pz*recip[2]; // normalize
- }
-
-// if ( 1 )
- {
- unsigned int j;
-
- for (j=0; j<vcount; j++)
- {
- /// XXX might be broken
- btVector3& v = vertices[j];
-
- btScalar x = v[0];
- btScalar y = v[1];
- btScalar z = v[2];
-
- btScalar dx = fabsf(x - px );
- btScalar dy = fabsf(y - py );
- btScalar dz = fabsf(z - pz );
-
- if ( dx < normalepsilon && dy < normalepsilon && dz < normalepsilon )
- {
- // ok, it is close enough to the old one
- // now let us see if it is further from the center of the point cloud than the one we already recorded.
- // in which case we keep this one instead.
-
- btScalar dist1 = GetDist(px,py,pz,center);
- btScalar dist2 = GetDist(v[0],v[1],v[2],center);
-
- if ( dist1 > dist2 )
- {
- v[0] = px;
- v[1] = py;
- v[2] = pz;
-
- }
-
- break;
- }
- }
-
- if ( j == vcount )
- {
- btVector3& dest = vertices[vcount];
- dest[0] = px;
- dest[1] = py;
- dest[2] = pz;
- vcount++;
- }
- m_vertexIndexMapping.push_back(j);
- }
- }
-
- // ok..now make sure we didn't prune so many vertices it is now invalid.
-// if ( 1 )
- {
- btScalar bmin[3] = { FLT_MAX, FLT_MAX, FLT_MAX };
- btScalar bmax[3] = { -FLT_MAX, -FLT_MAX, -FLT_MAX };
-
- for (unsigned int i=0; i<vcount; i++)
- {
- const btVector3& p = vertices[i];
- for (int j=0; j<3; j++)
- {
- if ( p[j] < bmin[j] ) bmin[j] = p[j];
- if ( p[j] > bmax[j] ) bmax[j] = p[j];
- }
- }
-
- btScalar dx = bmax[0] - bmin[0];
- btScalar dy = bmax[1] - bmin[1];
- btScalar dz = bmax[2] - bmin[2];
-
- if ( dx < EPSILON || dy < EPSILON || dz < EPSILON || vcount < 3)
- {
- btScalar cx = dx*btScalar(0.5) + bmin[0];
- btScalar cy = dy*btScalar(0.5) + bmin[1];
- btScalar cz = dz*btScalar(0.5) + bmin[2];
-
- btScalar len = FLT_MAX;
-
- if ( dx >= EPSILON && dx < len ) len = dx;
- if ( dy >= EPSILON && dy < len ) len = dy;
- if ( dz >= EPSILON && dz < len ) len = dz;
-
- if ( len == FLT_MAX )
- {
- dx = dy = dz = btScalar(0.01); // one centimeter
- }
- else
- {
- if ( dx < EPSILON ) dx = len * btScalar(0.05); // 1/5th the shortest non-zero edge.
- if ( dy < EPSILON ) dy = len * btScalar(0.05);
- if ( dz < EPSILON ) dz = len * btScalar(0.05);
- }
-
- btScalar x1 = cx - dx;
- btScalar x2 = cx + dx;
-
- btScalar y1 = cy - dy;
- btScalar y2 = cy + dy;
-
- btScalar z1 = cz - dz;
- btScalar z2 = cz + dz;
-
- vcount = 0; // add box
-
- addPoint(vcount,vertices,x1,y1,z1);
- addPoint(vcount,vertices,x2,y1,z1);
- addPoint(vcount,vertices,x2,y2,z1);
- addPoint(vcount,vertices,x1,y2,z1);
- addPoint(vcount,vertices,x1,y1,z2);
- addPoint(vcount,vertices,x2,y1,z2);
- addPoint(vcount,vertices,x2,y2,z2);
- addPoint(vcount,vertices,x1,y2,z2);
-
- return true;
- }
- }
-
- return true;
-}
-
-void HullLibrary::BringOutYourDead(const btVector3* verts,unsigned int vcount, btVector3* overts,unsigned int &ocount,unsigned int *indices,unsigned indexcount)
-{
- btAlignedObjectArray<int>tmpIndices;
- tmpIndices.resize(m_vertexIndexMapping.size());
- int i;
-
- for (i=0;i<m_vertexIndexMapping.size();i++)
- {
- tmpIndices[i] = m_vertexIndexMapping[i];
- }
-
- TUIntArray usedIndices;
- usedIndices.resize(static_cast<int>(vcount));
- memset(&usedIndices[0],0,sizeof(unsigned int)*vcount);
-
- ocount = 0;
-
- for (i=0; i<indexcount; i++)
- {
- unsigned int v = indices[i]; // original array index
-
- btAssert( v >= 0 && v < vcount );
-
- if ( usedIndices[static_cast<int>(v)] ) // if already remapped
- {
- indices[i] = usedIndices[static_cast<int>(v)]-1; // index to new array
- }
- else
- {
-
- indices[i] = ocount; // new index mapping
-
- overts[ocount][0] = verts[v][0]; // copy old vert to new vert array
- overts[ocount][1] = verts[v][1];
- overts[ocount][2] = verts[v][2];
-
- for (int k=0;k<m_vertexIndexMapping.size();k++)
- {
- if (tmpIndices[k]==v)
- m_vertexIndexMapping[k]=ocount;
- }
-
- ocount++; // increment output vert count
-
- btAssert( ocount >=0 && ocount <= vcount );
-
- usedIndices[static_cast<int>(v)] = ocount; // assign new index remapping
-
-
- }
- }
-
-
-}
diff --git a/extern/bullet2/src/LinearMath/btConvexHull.h b/extern/bullet2/src/LinearMath/btConvexHull.h
deleted file mode 100644
index 8c36307dfd6..00000000000
--- a/extern/bullet2/src/LinearMath/btConvexHull.h
+++ /dev/null
@@ -1,245 +0,0 @@
-
-/*
-Stan Melax Convex Hull Computation
-Copyright (c) 2008 Stan Melax http://www.melax.com/
-
-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.
-*/
-
-///includes modifications/improvements by John Ratcliff, see BringOutYourDead below.
-
-#ifndef CD_HULL_H
-#define CD_HULL_H
-
-#include "LinearMath/btVector3.h"
-#include "LinearMath/btAlignedObjectArray.h"
-
-typedef btAlignedObjectArray<unsigned int> TUIntArray;
-
-class HullResult
-{
-public:
- HullResult(void)
- {
- mPolygons = true;
- mNumOutputVertices = 0;
- mNumFaces = 0;
- mNumIndices = 0;
- }
- bool mPolygons; // true if indices represents polygons, false indices are triangles
- unsigned int mNumOutputVertices; // number of vertices in the output hull
- btAlignedObjectArray<btVector3> m_OutputVertices; // array of vertices
- unsigned int mNumFaces; // the number of faces produced
- unsigned int mNumIndices; // the total number of indices
- btAlignedObjectArray<unsigned int> m_Indices; // pointer to indices.
-
-// If triangles, then indices are array indexes into the vertex list.
-// If polygons, indices are in the form (number of points in face) (p1, p2, p3, ..) etc..
-};
-
-enum HullFlag
-{
- QF_TRIANGLES = (1<<0), // report results as triangles, not polygons.
- QF_REVERSE_ORDER = (1<<1), // reverse order of the triangle indices.
- QF_DEFAULT = QF_TRIANGLES
-};
-
-
-class HullDesc
-{
-public:
- HullDesc(void)
- {
- mFlags = QF_DEFAULT;
- mVcount = 0;
- mVertices = 0;
- mVertexStride = sizeof(btVector3);
- mNormalEpsilon = 0.001f;
- mMaxVertices = 4096; // maximum number of points to be considered for a convex hull.
- mMaxFaces = 4096;
- };
-
- HullDesc(HullFlag flag,
- unsigned int vcount,
- const btVector3 *vertices,
- unsigned int stride = sizeof(btVector3))
- {
- mFlags = flag;
- mVcount = vcount;
- mVertices = vertices;
- mVertexStride = stride;
- mNormalEpsilon = btScalar(0.001);
- mMaxVertices = 4096;
- }
-
- bool HasHullFlag(HullFlag flag) const
- {
- if ( mFlags & flag ) return true;
- return false;
- }
-
- void SetHullFlag(HullFlag flag)
- {
- mFlags|=flag;
- }
-
- void ClearHullFlag(HullFlag flag)
- {
- mFlags&=~flag;
- }
-
- unsigned int mFlags; // flags to use when generating the convex hull.
- unsigned int mVcount; // number of vertices in the input point cloud
- const btVector3 *mVertices; // the array of vertices.
- unsigned int mVertexStride; // the stride of each vertex, in bytes.
- btScalar mNormalEpsilon; // the epsilon for removing duplicates. This is a normalized value, if normalized bit is on.
- unsigned int mMaxVertices; // maximum number of vertices to be considered for the hull!
- unsigned int mMaxFaces;
-};
-
-enum HullError
-{
- QE_OK, // success!
- QE_FAIL // failed.
-};
-
-class btPlane
-{
- public:
- btVector3 normal;
- btScalar dist; // distance below origin - the D from plane equasion Ax+By+Cz+D=0
- btPlane(const btVector3 &n,btScalar d):normal(n),dist(d){}
- btPlane():normal(),dist(0){}
-
-};
-
-
-
-class ConvexH
-{
- public:
- class HalfEdge
- {
- public:
- short ea; // the other half of the edge (index into edges list)
- unsigned char v; // the vertex at the start of this edge (index into vertices list)
- unsigned char p; // the facet on which this edge lies (index into facets list)
- HalfEdge(){}
- HalfEdge(short _ea,unsigned char _v, unsigned char _p):ea(_ea),v(_v),p(_p){}
- };
- ConvexH()
- {
- int i;
- i=0;
- }
- ~ConvexH()
- {
- int i;
- i=0;
- }
- btAlignedObjectArray<btVector3> vertices;
- btAlignedObjectArray<HalfEdge> edges;
- btAlignedObjectArray<btPlane> facets;
- ConvexH(int vertices_size,int edges_size,int facets_size);
-};
-
-
-class int4
-{
-public:
- int x,y,z,w;
- int4(){};
- int4(int _x,int _y, int _z,int _w){x=_x;y=_y;z=_z;w=_w;}
- const int& operator[](int i) const {return (&x)[i];}
- int& operator[](int i) {return (&x)[i];}
-};
-
-class PHullResult
-{
-public:
-
- PHullResult(void)
- {
- mVcount = 0;
- mIndexCount = 0;
- mFaceCount = 0;
- mVertices = 0;
- }
-
- unsigned int mVcount;
- unsigned int mIndexCount;
- unsigned int mFaceCount;
- btVector3* mVertices;
- TUIntArray m_Indices;
-};
-
-
-
-///The HullLibrary class can create a convex hull from a collection of vertices, using the ComputeHull method.
-///The btShapeHull class uses this HullLibrary to create a approximate convex mesh given a general (non-polyhedral) convex shape.
-class HullLibrary
-{
-
- btAlignedObjectArray<class Tri*> m_tris;
-
-public:
-
- btAlignedObjectArray<int> m_vertexIndexMapping;
-
-
- HullError CreateConvexHull(const HullDesc& desc, // describes the input request
- HullResult& result); // contains the resulst
- HullError ReleaseResult(HullResult &result); // release memory allocated for this result, we are done with it.
-
-private:
-
- bool ComputeHull(unsigned int vcount,const btVector3 *vertices,PHullResult &result,unsigned int vlimit);
-
- class Tri* allocateTriangle(int a,int b,int c);
- void deAllocateTriangle(Tri*);
- void b2bfix(Tri* s,Tri*t);
-
- void removeb2b(Tri* s,Tri*t);
-
- void checkit(Tri *t);
-
- Tri* extrudable(btScalar epsilon);
-
- int calchull(btVector3 *verts,int verts_count, TUIntArray& tris_out, int &tris_count,int vlimit);
-
- int calchullgen(btVector3 *verts,int verts_count, int vlimit);
-
- int4 FindSimplex(btVector3 *verts,int verts_count,btAlignedObjectArray<int> &allow);
-
- class ConvexH* ConvexHCrop(ConvexH& convex,const btPlane& slice);
-
- void extrude(class Tri* t0,int v);
-
- ConvexH* test_cube();
-
- //BringOutYourDead (John Ratcliff): When you create a convex hull you hand it a large input set of vertices forming a 'point cloud'.
- //After the hull is generated it give you back a set of polygon faces which index the *original* point cloud.
- //The thing is, often times, there are many 'dead vertices' in the point cloud that are on longer referenced by the hull.
- //The routine 'BringOutYourDead' find only the referenced vertices, copies them to an new buffer, and re-indexes the hull so that it is a minimal representation.
- void BringOutYourDead(const btVector3* verts,unsigned int vcount, btVector3* overts,unsigned int &ocount,unsigned int* indices,unsigned indexcount);
-
- bool CleanupVertices(unsigned int svcount,
- const btVector3* svertices,
- unsigned int stride,
- unsigned int &vcount, // output number of vertices
- btVector3* vertices, // location to store the results.
- btScalar normalepsilon,
- btVector3& scale);
-};
-
-
-#endif
-
diff --git a/extern/bullet2/src/LinearMath/btHashMap.h b/extern/bullet2/src/LinearMath/btHashMap.h
deleted file mode 100644
index f883e0e489a..00000000000
--- a/extern/bullet2/src/LinearMath/btHashMap.h
+++ /dev/null
@@ -1,303 +0,0 @@
-#ifndef BT_HASH_MAP_H
-#define BT_HASH_MAP_H
-
-#include "btAlignedObjectArray.h"
-
-const int BT_HASH_NULL=0xffffffff;
-
-template <class Value>
-class btHashKey
-{
- int m_uid;
-public:
-
- btHashKey(int uid)
- :m_uid(uid)
- {
- }
-
- int getUid() const
- {
- return m_uid;
- }
-
- //to our success
- SIMD_FORCE_INLINE unsigned int getHash()const
- {
- int key = m_uid;
- // Thomas Wang's hash
- key += ~(key << 15);
- key ^= (key >> 10);
- key += (key << 3);
- key ^= (key >> 6);
- key += ~(key << 11);
- key ^= (key >> 16);
- return key;
- }
-
- btHashKey getKey(const Value& value) const
- {
- return btHashKey(value.getUid());
- }
-};
-
-
-template <class Value>
-class btHashKeyPtr
-{
- int m_uid;
-public:
-
- btHashKeyPtr(int uid)
- :m_uid(uid)
- {
- }
-
- int getUid() const
- {
- return m_uid;
- }
-
- //to our success
- SIMD_FORCE_INLINE unsigned int getHash()const
- {
- int key = m_uid;
- // Thomas Wang's hash
- key += ~(key << 15);
- key ^= (key >> 10);
- key += (key << 3);
- key ^= (key >> 6);
- key += ~(key << 11);
- key ^= (key >> 16);
- return key;
- }
-
- btHashKeyPtr getKey(const Value& value) const
- {
- return btHashKeyPtr(value->getUid());
- }
-};
-
-///The btHashMap template class implements a generic and lightweight hashmap.
-///A basic sample of how to use btHashMap is located in Demos\BasicDemo\main.cpp
-template <class Key, class Value>
-class btHashMap
-{
-
- btAlignedObjectArray<int> m_hashTable;
- btAlignedObjectArray<int> m_next;
- btAlignedObjectArray<Value> m_valueArray;
-
-
-
- void growTables(const Key& key)
- {
- int newCapacity = m_valueArray.capacity();
-
- if (m_hashTable.size() < newCapacity)
- {
- //grow hashtable and next table
- int curHashtableSize = m_hashTable.size();
-
- m_hashTable.resize(newCapacity);
- m_next.resize(newCapacity);
-
- int i;
-
- for (i= 0; i < newCapacity; ++i)
- {
- m_hashTable[i] = BT_HASH_NULL;
- }
- for (i = 0; i < newCapacity; ++i)
- {
- m_next[i] = BT_HASH_NULL;
- }
-
- for(i=0;i<curHashtableSize;i++)
- {
- const Value& value = m_valueArray[i];
-
- int hashValue = key.getKey(value).getHash() & (m_valueArray.capacity()-1); // New hash value with new mask
- m_next[i] = m_hashTable[hashValue];
- m_hashTable[hashValue] = i;
- }
-
-
- }
- }
-
- public:
-
- void insert(const Key& key, const Value& value) {
- int hash = key.getHash() & (m_valueArray.capacity()-1);
- //don't add it if it is already there
- if (find(key))
- {
- return;
- }
- int count = m_valueArray.size();
- int oldCapacity = m_valueArray.capacity();
- m_valueArray.push_back(value);
- int newCapacity = m_valueArray.capacity();
- if (oldCapacity < newCapacity)
- {
- growTables(key);
- //hash with new capacity
- hash = key.getHash() & (m_valueArray.capacity()-1);
- }
- m_next[count] = m_hashTable[hash];
- m_hashTable[hash] = count;
- }
-
- void remove(const Key& key) {
-
- int hash = key.getHash() & (m_valueArray.capacity()-1);
-
- int pairIndex = findIndex(key);
-
- if (pairIndex ==BT_HASH_NULL)
- {
- return;
- }
-
- // Remove the pair from the hash table.
- int index = m_hashTable[hash];
- btAssert(index != BT_HASH_NULL);
-
- int previous = BT_HASH_NULL;
- while (index != pairIndex)
- {
- previous = index;
- index = m_next[index];
- }
-
- if (previous != BT_HASH_NULL)
- {
- btAssert(m_next[previous] == pairIndex);
- m_next[previous] = m_next[pairIndex];
- }
- else
- {
- m_hashTable[hash] = m_next[pairIndex];
- }
-
- // We now move the last pair into spot of the
- // pair being removed. We need to fix the hash
- // table indices to support the move.
-
- int lastPairIndex = m_valueArray.size() - 1;
-
- // If the removed pair is the last pair, we are done.
- if (lastPairIndex == pairIndex)
- {
- m_valueArray.pop_back();
- return;
- }
-
- // Remove the last pair from the hash table.
- const Value* lastValue = &m_valueArray[lastPairIndex];
- int lastHash = key.getKey(*lastValue).getHash() & (m_valueArray.capacity()-1);
-
- index = m_hashTable[lastHash];
- btAssert(index != BT_HASH_NULL);
-
- previous = BT_HASH_NULL;
- while (index != lastPairIndex)
- {
- previous = index;
- index = m_next[index];
- }
-
- if (previous != BT_HASH_NULL)
- {
- btAssert(m_next[previous] == lastPairIndex);
- m_next[previous] = m_next[lastPairIndex];
- }
- else
- {
- m_hashTable[lastHash] = m_next[lastPairIndex];
- }
-
- // Copy the last pair into the remove pair's spot.
- m_valueArray[pairIndex] = m_valueArray[lastPairIndex];
-
- // Insert the last pair into the hash table
- m_next[pairIndex] = m_hashTable[lastHash];
- m_hashTable[lastHash] = pairIndex;
-
- m_valueArray.pop_back();
-
- }
-
-
- int size() const
- {
- return m_valueArray.size();
- }
-
- const Value* getAtIndex(int index) const
- {
- btAssert(index < m_valueArray.size());
-
- return &m_valueArray[index];
- }
-
- Value* getAtIndex(int index)
- {
- btAssert(index < m_valueArray.size());
-
- return &m_valueArray[index];
- }
-
- Value* operator[](const Key& key) {
- return find(key);
- }
-
- const Value* find(const Key& key) const
- {
- int index = findIndex(key);
- if (index == BT_HASH_NULL)
- {
- return NULL;
- }
- return &m_valueArray[index];
- }
-
- Value* find(const Key& key)
- {
- int index = findIndex(key);
- if (index == BT_HASH_NULL)
- {
- return NULL;
- }
- return &m_valueArray[index];
- }
-
-
- int findIndex(const Key& key) const
- {
- int hash = key.getHash() & (m_valueArray.capacity()-1);
-
- if (hash >= m_hashTable.size())
- {
- return BT_HASH_NULL;
- }
-
- int index = m_hashTable[hash];
- while ((index != BT_HASH_NULL) && (key.getUid() == key.getKey(m_valueArray[index]).getUid()) == false)
- {
- index = m_next[index];
- }
- return index;
- }
-
- void clear()
- {
- m_hashTable.clear();
- m_next.clear();
- m_valueArray.clear();
- }
-
-};
-
-#endif //BT_HASH_MAP_H
diff --git a/extern/bullet2/src/LinearMath/btPoolAllocator.h b/extern/bullet2/src/LinearMath/btPoolAllocator.h
deleted file mode 100644
index 39d2559c747..00000000000
--- a/extern/bullet2/src/LinearMath/btPoolAllocator.h
+++ /dev/null
@@ -1,102 +0,0 @@
-/*
-Copyright (c) 2003-2006 Gino van den Bergen / 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 _BT_POOL_ALLOCATOR_H
-#define _BT_POOL_ALLOCATOR_H
-
-#include "btScalar.h"
-#include "btAlignedAllocator.h"
-
-///The btPoolAllocator class allows to efficiently allocate a large pool of objects, instead of dynamically allocating them separately.
-class btPoolAllocator
-{
- int m_elemSize;
- int m_maxElements;
- int m_freeCount;
- void* m_firstFree;
- unsigned char* m_pool;
-
-public:
-
- btPoolAllocator(int elemSize, int maxElements)
- :m_elemSize(elemSize),
- m_maxElements(maxElements)
- {
- m_pool = (unsigned char*) btAlignedAlloc( static_cast<unsigned int>(m_elemSize*m_maxElements),16);
-
- unsigned char* p = m_pool;
- m_firstFree = p;
- m_freeCount = m_maxElements;
- int count = m_maxElements;
- while (--count) {
- *(void**)p = (p + m_elemSize);
- p += m_elemSize;
- }
- *(void**)p = 0;
- }
-
- ~btPoolAllocator()
- {
- btAlignedFree( m_pool);
- }
-
- int getFreeCount() const
- {
- return m_freeCount;
- }
-
- void* allocate(int size)
- {
- // release mode fix
- (void)size;
- btAssert(!size || size<=m_elemSize);
- btAssert(m_freeCount>0);
- void* result = m_firstFree;
- m_firstFree = *(void**)m_firstFree;
- --m_freeCount;
- return result;
- }
-
- bool validPtr(void* ptr)
- {
- if (ptr) {
- if (((unsigned char*)ptr >= m_pool && (unsigned char*)ptr < m_pool + m_maxElements * m_elemSize))
- {
- return true;
- }
- }
- return false;
- }
-
- void freeMemory(void* ptr)
- {
- if (ptr) {
- btAssert((unsigned char*)ptr >= m_pool && (unsigned char*)ptr < m_pool + m_maxElements * m_elemSize);
-
- *(void**)ptr = m_firstFree;
- m_firstFree = ptr;
- ++m_freeCount;
- }
- }
-
- int getElementSize() const
- {
- return m_elemSize;
- }
-
-
-};
-
-#endif //_BT_POOL_ALLOCATOR_H
diff --git a/intern/elbeem/intern/controlparticles.cpp b/intern/elbeem/intern/controlparticles.cpp
deleted file mode 100644
index 4b496e4a3a2..00000000000
--- a/intern/elbeem/intern/controlparticles.cpp
+++ /dev/null
@@ -1,1461 +0,0 @@
-// --------------------------------------------------------------------------
-//
-// El'Beem - the visual lattice boltzmann freesurface simulator
-// All code distributed as part of El'Beem is covered by the version 2 of the
-// GNU General Public License. See the file COPYING for details.
-//
-// Copyright 2008 Nils Thuerey , Richard Keiser, Mark Pauly, Ulrich Ruede
-//
-// implementation of control particle handling
-//
-// --------------------------------------------------------------------------
-
-// indicator for LBM inclusion
-#include "ntl_geometrymodel.h"
-#include "ntl_world.h"
-#include "solver_class.h"
-#include "controlparticles.h"
-#include "mvmcoords.h"
-#include <zlib.h>
-
-#ifndef sqrtf
-#define sqrtf sqrt
-#endif
-
-// brute force circle test init in initTimeArray
-// replaced by mDebugInit
-//#define CP_FORCECIRCLEINIT 0
-
-
-void ControlParticles::initBlenderTest() {
- mPartSets.clear();
-
- ControlParticleSet cps;
- mPartSets.push_back(cps);
- int setCnt = mPartSets.size()-1;
- ControlParticle p;
-
- // set for time zero
- mPartSets[setCnt].time = 0.;
-
- // add single particle
- p.reset();
- p.pos = LbmVec(0.5, 0.5, -0.5);
- mPartSets[setCnt].particles.push_back(p);
-
- // add second set for animation
- mPartSets.push_back(cps);
- setCnt = mPartSets.size()-1;
- mPartSets[setCnt].time = 0.15;
-
- // insert new position
- p.reset();
- p.pos = LbmVec(-0.5, -0.5, 0.5);
- mPartSets[setCnt].particles.push_back(p);
-
- // applyTrafos();
- initTime(0. , 1.);
-}
-
-// blender control object gets converted to mvm flui control object
-int ControlParticles::initFromObject(ntlGeometryObjModel *model) {
- vector<ntlTriangle> triangles;
- vector<ntlVec3Gfx> vertices;
- vector<ntlVec3Gfx> normals;
-
- /*
- model->loadBobjModel(string(infile));
-
- model->setLoaded(true);
-
- model->setGeoInitId(gid);
-
-
- printf("a animated? %d\n", model->getIsAnimated());
- printf("b animated? %d\n", model->getMeshAnimated());
- */
-
- model->setGeoInitType(FGI_FLUID);
-
- model->getTriangles(mCPSTimeStart, &triangles, &vertices, &normals, 1 );
- // model->applyTransformation(mCPSTimeStart, &vertices, &normals, 0, vertices.size(), true);
-
- // valid mesh?
- if(triangles.size() <= 0) {
- return 0;
- }
-
- ntlRenderGlobals *glob = new ntlRenderGlobals;
- ntlScene *genscene = new ntlScene( glob, false );
- genscene->addGeoClass(model);
- genscene->addGeoObject(model);
- genscene->buildScene(0., false);
- char treeFlag = (1<<(4+model->getGeoInitId()));
-
- ntlTree *tree = new ntlTree(
- 15, 8, // TREEwarning - fixed values for depth & maxtriangles here...
- genscene, treeFlag );
-
- // TODO? use params
- ntlVec3Gfx start,end;
- model->getExtends(start,end);
- /*
- printf("start - x: %f, y: %f, z: %f\n", start[0], start[1], start[2]);
- printf("end - x: %f, y: %f, z: %f\n", end[0], end[1], end[2]);
- printf("mCPSWidth: %f\n");
-*/
- LbmFloat width = mCPSWidth;
- if(width<=LBM_EPSILON) { errMsg("ControlParticles::initFromMVMCMesh","Invalid mCPSWidth! "<<mCPSWidth); width=mCPSWidth=0.1; }
- ntlVec3Gfx org = start+ntlVec3Gfx(width*0.5);
- gfxReal distance = -1.;
- vector<ntlVec3Gfx> inspos;
-
- // printf("distance: %f, width: %f\n", distance, width);
-
- while(org[2]<end[2]) {
- while(org[1]<end[1]) {
- while(org[0]<end[0]) {
- if(checkPointInside(tree, org, distance)) {
- inspos.push_back(org);
- }
- // TODO optimize, use distance
- org[0] += width;
- }
- org[1] += width;
- org[0] = start[0];
- }
- org[2] += width;
- org[1] = start[1];
- }
-
- // printf("inspos.size(): %d\n", inspos.size());
-
- MeanValueMeshCoords mvm;
- mvm.calculateMVMCs(vertices,triangles, inspos, mCPSWeightFac);
- vector<ntlVec3Gfx> ninspos;
- mvm.transfer(vertices, ninspos);
-
- // init first set, check dist
- ControlParticleSet firstcps; //T
- mPartSets.push_back(firstcps);
- mPartSets[mPartSets.size()-1].time = mCPSTimeStart;
- vector<bool> useCP;
-
- for(int i=0; i<(int)inspos.size(); i++) {
- ControlParticle p; p.reset();
- p.pos = vec2L(inspos[i]);
-
- bool usecpv = true;
-
- mPartSets[mPartSets.size()-1].particles.push_back(p);
- useCP.push_back(usecpv);
- }
-
- // init further sets, temporal mesh sampling
- double tsampling = mCPSTimestep;
- // printf("tsampling: %f, ninspos.size(): %d, mCPSTimeEnd: %f\n", tsampling, ninspos.size(), mCPSTimeEnd);
-
- int tcnt=0;
- for(double t=mCPSTimeStart+tsampling; ((t<mCPSTimeEnd) && (ninspos.size()>0.)); t+=tsampling) {
- ControlParticleSet nextcps; //T
- mPartSets.push_back(nextcps);
- mPartSets[mPartSets.size()-1].time = (gfxReal)t;
-
- vertices.clear(); triangles.clear(); normals.clear();
- model->getTriangles(t, &triangles, &vertices, &normals, 1 );
- mvm.transfer(vertices, ninspos);
-
- tcnt++;
- for(size_t i=0; i < ninspos.size(); i++) {
-
- if(useCP[i]) {
- ControlParticle p; p.reset();
- p.pos = vec2L(ninspos[i]);
- mPartSets[mPartSets.size()-1].particles.push_back(p);
- }
- }
- }
-
- model->setGeoInitType(FGI_CONTROL);
-
- delete tree;
- delete genscene;
- delete glob;
-
- // do reverse here
- if(model->getGeoPartSlipValue())
- {
- mirrorTime();
- }
-
- return 1;
-}
-
-
-// init all zero / defaults for a single particle
-void ControlParticle::reset() {
- pos = LbmVec(0.,0.,0.);
- vel = LbmVec(0.,0.,0.);
- influence = 1.;
- size = 1.;
-#ifndef LBMDIM
-#ifdef MAIN_2D
- rotaxis = LbmVec(0.,1.,0.); // SPH xz
-#else // MAIN_2D
- // 3d - roate in xy plane, vortex
- rotaxis = LbmVec(0.,0.,1.);
- // 3d - rotate for wave
- //rotaxis = LbmVec(0.,1.,0.);
-#endif // MAIN_2D
-#else // LBMDIM
- rotaxis = LbmVec(0.,1.,0.); // LBM xy , is swapped afterwards
-#endif // LBMDIM
-
- density = 0.;
- densityWeight = 0.;
- avgVelAcc = avgVel = LbmVec(0.);
- avgVelWeight = 0.;
-}
-
-
-// default preset/empty init
-ControlParticles::ControlParticles() :
- _influenceTangential(0.f),
- _influenceAttraction(0.f),
- _influenceVelocity(0.f),
- _influenceMaxdist(0.f),
- _radiusAtt(1.0f),
- _radiusVel(1.0f),
- _radiusMinMaxd(2.0f),
- _radiusMaxd(3.0f),
- _currTime(-1.0), _currTimestep(1.),
- _initTimeScale(1.),
- _initPartOffset(0.), _initPartScale(1.),
- _initLastPartOffset(0.), _initLastPartScale(1.),
- _initMirror(""),
- _fluidSpacing(1.), _kernelWeight(-1.),
- _charLength(1.), _charLengthInv(1.),
- mvCPSStart(-10000.), mvCPSEnd(10000.),
- mCPSWidth(0.1), mCPSTimestep(0.02), // was 0.05
- mCPSTimeStart(0.), mCPSTimeEnd(0.5), mCPSWeightFac(1.),
- mDebugInit(0)
-{
- _radiusAtt = 0.15f;
- _radiusVel = 0.15f;
- _radiusMinMaxd = 0.16f;
- _radiusMaxd = 0.3;
-
- _influenceAttraction = 0.f;
- _influenceTangential = 0.f;
- _influenceVelocity = 0.f;
- // 3d tests */
-}
-
-
-
-ControlParticles::~ControlParticles() {
- // nothing to do...
-}
-
-LbmFloat ControlParticles::getControlTimStart() {
- if(mPartSets.size()>0) { return mPartSets[0].time; }
- return -1000.;
-}
-LbmFloat ControlParticles::getControlTimEnd() {
- if(mPartSets.size()>0) { return mPartSets[mPartSets.size()-1].time; }
- return -1000.;
-}
-
-// calculate for delta t
-void ControlParticles::setInfluenceVelocity(LbmFloat set, LbmFloat dt) {
- const LbmFloat dtInter = 0.01;
- LbmFloat facFv = 1.-set; //cparts->getInfluenceVelocity();
- // mLevel[mMaxRefine].timestep
- LbmFloat facNv = (LbmFloat)( 1.-pow( (double)facFv, (double)(dt/dtInter)) );
- //errMsg("vwcalc","ts:"<<dt<< " its:"<<(dt/dtInter) <<" fv"<<facFv<<" nv"<<facNv<<" test:"<< pow( (double)(1.-facNv),(double)(dtInter/dt)) );
- _influenceVelocity = facNv;
-}
-
-int ControlParticles::initExampleSet()
-{
- // unused
- return 0;
-}
-
-int ControlParticles::getTotalSize()
-{
- int s=0;
- for(int i=0; i<(int)mPartSets.size(); i++) {
- s+= mPartSets[i].particles.size();
- }
- return s;
-}
-
-// --------------------------------------------------------------------------
-// load positions & timing from text file
-// WARNING - make sure file has unix format, no win/dos linefeeds...
-#define LINE_LEN 100
-int ControlParticles::initFromTextFile(string filename)
-{
- /*
- const bool debugRead = false;
- char line[LINE_LEN];
- line[LINE_LEN-1] = '\0';
- mPartSets.clear();
- if(filename.size()<2) return 0;
-
- // HACK , use "cparts" suffix as old
- // e.g. "cpart2" as new
- if(filename[ filename.size()-1 ]=='s') {
- return initFromTextFileOld(filename);
- }
-
- FILE *infile = fopen(filename.c_str(), "r");
- if(!infile) {
- errMsg("ControlParticles::initFromTextFile","unable to open '"<<filename<<"' " );
- // try to open as gz sequence
- if(initFromBinaryFile(filename)) { return 1; }
- // try mesh MVCM generation
- if(initFromMVCMesh(filename)) { return 1; }
- // failed...
- return 0;
- }
-
- int haveNo = false;
- int haveScale = false;
- int haveTime = false;
- int noParts = -1;
- int partCnt = 0;
- int setCnt = 0;
- //ControlParticle p; p.reset();
- // scale times by constant factor while reading
- LbmFloat timeScale= 1.0;
- int lineCnt = 0;
- bool abortParse = false;
-#define LASTCP mPartSets[setCnt].particles[ mPartSets[setCnt].particles.size()-1 ]
-
- while( (!feof(infile)) && (!abortParse)) {
- lineCnt++;
- fgets(line, LINE_LEN, infile);
-
- //if(debugRead) printf("\nDEBUG%d r '%s'\n",lineCnt, line);
- if(!line) continue;
- size_t len = strlen(line);
-
- // skip empty lines and comments (#,//)
- if(len<1) continue;
- if( (line[0]=='#') || (line[0]=='\n') ) continue;
- if((len>1) && (line[0]=='/' && line[1]=='/')) continue;
-
- // debug remove newline
- if((len>=1)&&(line[len-1]=='\n')) line[len-1]='\0';
-
- switch(line[0]) {
-
- case 'N': { // total number of particles, more for debugging...
- noParts = atoi(line+2);
- if(noParts<=0) {
- errMsg("ControlParticles::initFromTextFile","file '"<<filename<<"' - invalid no of particles "<<noParts);
- mPartSets.clear(); fclose(infile); return 0;
- }
- if(debugRead) printf("CPDEBUG%d no parts '%d'\n",lineCnt, noParts );
- haveNo = true;
- } break;
-
- case 'T': { // global time scale
- timeScale *= (LbmFloat)atof(line+2);
- if(debugRead) printf("ControlParticles::initFromTextFile - line %d , set timescale '%f', org %f\n",lineCnt, timeScale , _initTimeScale);
- if(timeScale==0.) { fprintf(stdout,"ControlParticles::initFromTextFile - line %d ,error: timescale = 0.! reseting to 1 ...\n",lineCnt); timeScale=1.; }
- haveScale = true;
- } break;
-
- case 'I': { // influence settings, overrides others as of now...
- float val = (LbmFloat)atof(line+3);
- const char *setvar = "[invalid]";
- switch(line[1]) {
- //case 'f': { _influenceFalloff = val; setvar = "falloff"; } break;
- case 't': { _influenceTangential = val; setvar = "tangential"; } break;
- case 'a': { _influenceAttraction = val; setvar = "attraction"; } break;
- case 'v': { _influenceVelocity = val; setvar = "velocity"; } break;
- case 'm': { _influenceMaxdist = val; setvar = "maxdist"; } break;
- default:
- fprintf(stdout,"ControlParticles::initFromTextFile (%s) - line %d , invalid influence setting %c, %f\n",filename.c_str() ,lineCnt, line[1], val);
- }
- if(debugRead) printf("CPDEBUG%d set influence '%s'=%f \n",lineCnt, setvar, val);
- } break;
-
- case 'R': { // radius settings, overrides others as of now...
- float val = (LbmFloat)atof(line+3);
- const char *setvar = "[invalid]";
- switch(line[1]) {
- case 'a': { _radiusAtt = val; setvar = "r_attraction"; } break;
- case 'v': { _radiusVel = val; setvar = "r_velocity"; } break;
- case 'm': { _radiusMaxd = val; setvar = "r_maxdist"; } break;
- default:
- fprintf(stdout,"ControlParticles::initFromTextFile (%s) - line %d , invalid influence setting %c, %f\n",filename.c_str() ,lineCnt, line[1], val);
- }
- if(debugRead) printf("CPDEBUG%d set influence '%s'=%f \n",lineCnt, setvar, val);
- } break;
-
- case 'S': { // new particle set at time T
- ControlParticleSet cps;
- mPartSets.push_back(cps);
- setCnt = (int)mPartSets.size()-1;
-
- LbmFloat val = (LbmFloat)atof(line+2);
- mPartSets[setCnt].time = val * timeScale;
- if(debugRead) printf("CPDEBUG%d new set, time '%f', %d\n",lineCnt, mPartSets[setCnt].time, setCnt );
- haveTime = true;
- partCnt = -1;
- } break;
-
- case 'P': // new particle with pos
- case 'n': { // new particle without pos
- if((!haveTime)||(setCnt<0)) { fprintf(stdout,"ControlParticles::initFromTextFile - line %d ,error: set missing!\n",lineCnt); abortParse=true; break; }
- partCnt++;
- if(partCnt>=noParts) {
- if(debugRead) printf("CPDEBUG%d partset done \n",lineCnt);
- haveTime = false;
- } else {
- ControlParticle p; p.reset();
- mPartSets[setCnt].particles.push_back(p);
- }
- }
- // only new part, or new with pos?
- if(line[0] == 'n') break;
-
- // particle properties
-
- case 'p': { // new particle set at time T
- if((!haveTime)||(setCnt<0)||(mPartSets[setCnt].particles.size()<1)) { fprintf(stdout,"ControlParticles::initFromTextFile - line %d ,error|p: particle missing!\n",lineCnt); abortParse=true; break; }
- float px=0.,py=0.,pz=0.;
- if( sscanf(line+2,"%f %f %f",&px,&py,&pz) != 3) {
- fprintf(stdout,"CPDEBUG%d, unable to parse position!\n",lineCnt); abortParse=true; break;
- }
- if(!(finite(px)&&finite(py)&&finite(pz))) { px=py=pz=0.; }
- LASTCP.pos[0] = px;
- LASTCP.pos[1] = py;
- LASTCP.pos[2] = pz;
- if(debugRead) printf("CPDEBUG%d part%d,%d: position %f,%f,%f \n",lineCnt,setCnt,partCnt, px,py,pz);
- } break;
-
- case 's': { // particle size
- if((!haveTime)||(setCnt<0)||(mPartSets[setCnt].particles.size()<1)) { fprintf(stdout,"ControlParticles::initFromTextFile - line %d ,error|s: particle missing!\n",lineCnt); abortParse=true; break; }
- float ps=1.;
- if( sscanf(line+2,"%f",&ps) != 1) {
- fprintf(stdout,"CPDEBUG%d, unable to parse size!\n",lineCnt); abortParse=true; break;
- }
- if(!(finite(ps))) { ps=0.; }
- LASTCP.size = ps;
- if(debugRead) printf("CPDEBUG%d part%d,%d: size %f \n",lineCnt,setCnt,partCnt, ps);
- } break;
-
- case 'i': { // particle influence
- if((!haveTime)||(setCnt<0)||(mPartSets[setCnt].particles.size()<1)) { fprintf(stdout,"ControlParticles::initFromTextFile - line %d ,error|i: particle missing!\n",lineCnt); abortParse=true; break; }
- float pinf=1.;
- if( sscanf(line+2,"%f",&pinf) != 1) {
- fprintf(stdout,"CPDEBUG%d, unable to parse size!\n",lineCnt); abortParse=true; break;
- }
- if(!(finite(pinf))) { pinf=0.; }
- LASTCP.influence = pinf;
- if(debugRead) printf("CPDEBUG%d part%d,%d: influence %f \n",lineCnt,setCnt,partCnt, pinf);
- } break;
-
- case 'a': { // rotation axis
- if((!haveTime)||(setCnt<0)||(mPartSets[setCnt].particles.size()<1)) { fprintf(stdout,"ControlParticles::initFromTextFile - line %d ,error|a: particle missing!\n",lineCnt); abortParse=true; break; }
- float px=0.,py=0.,pz=0.;
- if( sscanf(line+2,"%f %f %f",&px,&py,&pz) != 3) {
- fprintf(stdout,"CPDEBUG%d, unable to parse rotaxis!\n",lineCnt); abortParse=true; break;
- }
- if(!(finite(px)&&finite(py)&&finite(pz))) { px=py=pz=0.; }
- LASTCP.rotaxis[0] = px;
- LASTCP.rotaxis[1] = py;
- LASTCP.rotaxis[2] = pz;
- if(debugRead) printf("CPDEBUG%d part%d,%d: rotaxis %f,%f,%f \n",lineCnt,setCnt,partCnt, px,py,pz);
- } break;
-
-
- default:
- if(debugRead) printf("CPDEBUG%d ignored: '%s'\n",lineCnt, line );
- break;
- }
- }
- if(debugRead && abortParse) printf("CPDEBUG aborted parsing after set... %d\n",(int)mPartSets.size() );
-
- // sanity check
- for(int i=0; i<(int)mPartSets.size(); i++) {
- if( (int)mPartSets[i].particles.size()!=noParts) {
- fprintf(stdout,"ControlParticles::initFromTextFile (%s) - invalid no of particles in set %d, is:%d, shouldbe:%d \n",filename.c_str() ,i,(int)mPartSets[i].particles.size(), noParts);
- mPartSets.clear();
- fclose(infile);
- return 0;
- }
- }
-
- // print stats
- printf("ControlParticles::initFromTextFile (%s): Read %d sets, each %d particles\n",filename.c_str() ,
- (int)mPartSets.size(), noParts );
- if(mPartSets.size()>0) {
- printf("ControlParticles::initFromTextFile (%s): Time: %f,%f\n",filename.c_str() ,mPartSets[0].time, mPartSets[mPartSets.size()-1].time );
- }
-
- // done...
- fclose(infile);
- applyTrafos();
- */
- return 1;
-}
-
-
-int ControlParticles::initFromTextFileOld(string filename)
-{
- /*
- const bool debugRead = false;
- char line[LINE_LEN];
- line[LINE_LEN-1] = '\0';
- mPartSets.clear();
- if(filename.size()<1) return 0;
-
- FILE *infile = fopen(filename.c_str(), "r");
- if(!infile) {
- fprintf(stdout,"ControlParticles::initFromTextFileOld - unable to open '%s'\n",filename.c_str() );
- return 0;
- }
-
- int haveNo = false;
- int haveScale = false;
- int haveTime = false;
- int noParts = -1;
- int coordCnt = 0;
- int partCnt = 0;
- int setCnt = 0;
- ControlParticle p; p.reset();
- // scale times by constant factor while reading
- LbmFloat timeScale= 1.0;
- int lineCnt = 0;
-
- while(!feof(infile)) {
- lineCnt++;
- fgets(line, LINE_LEN, infile);
-
- if(debugRead) printf("\nDEBUG%d r '%s'\n",lineCnt, line);
-
- if(!line) continue;
- size_t len = strlen(line);
-
- // skip empty lines and comments (#,//)
- if(len<1) continue;
- if( (line[0]=='#') || (line[0]=='\n') ) continue;
- if((len>1) && (line[0]=='/' && line[1]=='/')) continue;
-
- // debug remove newline
- if((len>=1)&&(line[len-1]=='\n')) line[len-1]='\0';
-
- // first read no. of particles
- if(!haveNo) {
- noParts = atoi(line);
- if(noParts<=0) {
- fprintf(stdout,"ControlParticles::initFromTextFileOld - invalid no of particles %d\n",noParts);
- mPartSets.clear();
- fclose(infile);
- return 0;
- }
- if(debugRead) printf("DEBUG%d noparts '%d'\n",lineCnt, noParts );
- haveNo = true;
- }
-
- // then read time scale
- else if(!haveScale) {
- timeScale *= (LbmFloat)atof(line);
- if(debugRead) printf("DEBUG%d tsc '%f', org %f\n",lineCnt, timeScale , _initTimeScale);
- haveScale = true;
- }
-
- // then get set time
- else if(!haveTime) {
- ControlParticleSet cps;
- mPartSets.push_back(cps);
- setCnt = (int)mPartSets.size()-1;
-
- LbmFloat val = (LbmFloat)atof(line);
- mPartSets[setCnt].time = val * timeScale;
- if(debugRead) printf("DEBUG%d time '%f', %d\n",lineCnt, mPartSets[setCnt].time, setCnt );
- haveTime = true;
- }
-
- // default read all parts
- else {
- LbmFloat val = (LbmFloat)atof(line);
- if(debugRead) printf("DEBUG: l%d s%d,particle%d '%f' %d,%d/%d\n",lineCnt,(int)mPartSets.size(),(int)mPartSets[setCnt].particles.size(), val ,coordCnt,partCnt,noParts);
- p.pos[coordCnt] = val;
- coordCnt++;
- if(coordCnt>=3) {
- mPartSets[setCnt].particles.push_back(p);
- p.reset();
- coordCnt=0;
- partCnt++;
- }
- if(partCnt>=noParts) {
- partCnt = 0;
- haveTime = false;
- }
- //if(debugRead) printf("DEBUG%d par2 %d,%d/%d\n",lineCnt, coordCnt,partCnt,noParts);
- }
- //read pos, vel ...
- }
-
- // sanity check
- for(int i=0; i<(int)mPartSets.size(); i++) {
- if( (int)mPartSets[i].particles.size()!=noParts) {
- fprintf(stdout,"ControlParticles::initFromTextFileOld - invalid no of particles in set %d, is:%d, shouldbe:%d \n",i,(int)mPartSets[i].particles.size(), noParts);
- mPartSets.clear();
- fclose(infile);
- return 0;
- }
- }
- // print stats
- printf("ControlParticles::initFromTextFileOld: Read %d sets, each %d particles\n",
- (int)mPartSets.size(), noParts );
- if(mPartSets.size()>0) {
- printf("ControlParticles::initFromTextFileOld: Time: %f,%f\n",mPartSets[0].time, mPartSets[mPartSets.size()-1].time );
- }
-
- // done...
- fclose(infile);
- applyTrafos();
- */
- return 1;
-}
-
-// load positions & timing from gzipped binary file
-int ControlParticles::initFromBinaryFile(string filename) {
- mPartSets.clear();
- if(filename.size()<1) return 0;
- int fileNotFound=0;
- int fileFound=0;
- char ofile[256];
-
- for(int set=0; ((set<10000)&&(fileNotFound<10)); set++) {
- snprintf(ofile,256,"%s%04d.gz",filename.c_str(),set);
- //errMsg("ControlParticle::initFromBinaryFile","set"<<set<<" notf"<<fileNotFound<<" ff"<<fileFound);
-
- gzFile gzf;
- gzf = gzopen(ofile, "rb");
- if (!gzf) {
- //errMsg("ControlParticles::initFromBinaryFile","Unable to open file for reading '"<<ofile<<"' ");
- fileNotFound++;
- continue;
- }
- fileNotFound=0;
- fileFound++;
-
- ControlParticleSet cps;
- mPartSets.push_back(cps);
- int setCnt = (int)mPartSets.size()-1;
- //LbmFloat val = (LbmFloat)atof(line+2);
- mPartSets[setCnt].time = (gfxReal)set;
-
- int totpart = 0;
- gzread(gzf, &totpart, sizeof(totpart));
-
- for(int a=0; a<totpart; a++) {
- int ptype=0;
- float psize=0.0;
- ntlVec3Gfx ppos,pvel;
- gzread(gzf, &ptype, sizeof( ptype ));
- gzread(gzf, &psize, sizeof( float ));
-
- for(int j=0; j<3; j++) { gzread(gzf, &ppos[j], sizeof( float )); }
- for(int j=0; j<3; j++) { gzread(gzf, &pvel[j], sizeof( float )); }
-
- ControlParticle p;
- p.reset();
- p.pos = vec2L(ppos);
- mPartSets[setCnt].particles.push_back(p);
- }
-
- gzclose(gzf);
- //errMsg("ControlParticle::initFromBinaryFile","Read set "<<ofile<<", #"<<mPartSets[setCnt].particles.size() ); // DEBUG
- } // sets
-
- if(fileFound==0) return 0;
- applyTrafos();
- return 1;
-}
-
-int globCPIProblems =0;
-bool ControlParticles::checkPointInside(ntlTree *tree, ntlVec3Gfx org, gfxReal &distance) {
- // warning - stripped down version of geoInitCheckPointInside
- const int globGeoInitDebug = 0;
- const int flags = FGI_FLUID;
- org += ntlVec3Gfx(0.0001);
- ntlVec3Gfx dir = ntlVec3Gfx(1.0, 0.0, 0.0);
- int OId = -1;
- ntlRay ray(org, dir, 0, 1.0, NULL);
- bool done = false;
- bool inside = false;
- int mGiObjInside = 0;
- LbmFloat mGiObjDistance = -1.0;
- LbmFloat giObjFirstHistSide = 0;
-
- // if not inside, return distance to first hit
- gfxReal firstHit=-1.0;
- int firstOId = -1;
- if(globGeoInitDebug) errMsg("IIIstart"," isect "<<org);
-
- while(!done) {
- // find first inside intersection
- ntlTriangle *triIns = NULL;
- distance = -1.0;
- ntlVec3Gfx normal(0.0);
- tree->intersectX(ray,distance,normal, triIns, flags, true);
- if(triIns) {
- ntlVec3Gfx norg = ray.getOrigin() + ray.getDirection()*distance;
- LbmFloat orientation = dot(normal, dir);
- OId = triIns->getObjectId();
- if(orientation<=0.0) {
- // outside hit
- normal *= -1.0;
- mGiObjInside++;
- if(giObjFirstHistSide==0) giObjFirstHistSide = 1;
- if(globGeoInitDebug) errMsg("IIO"," oid:"<<OId<<" org"<<org<<" norg"<<norg<<" orient:"<<orientation);
- } else {
- // inside hit
- mGiObjInside++;
- if(mGiObjDistance<0.0) mGiObjDistance = distance;
- if(globGeoInitDebug) errMsg("III"," oid:"<<OId<<" org"<<org<<" norg"<<norg<<" orient:"<<orientation);
- if(giObjFirstHistSide==0) giObjFirstHistSide = -1;
- }
- norg += normal * getVecEpsilon();
- ray = ntlRay(norg, dir, 0, 1.0, NULL);
- // remember first hit distance, in case we're not
- // inside anything
- if(firstHit<0.0) {
- firstHit = distance;
- firstOId = OId;
- }
- } else {
- // no more intersections... return false
- done = true;
- }
- }
-
- distance = -1.0;
- if(mGiObjInside>0) {
- bool mess = false;
- if((mGiObjInside%2)==1) {
- if(giObjFirstHistSide != -1) mess=true;
- } else {
- if(giObjFirstHistSide != 1) mess=true;
- }
- if(mess) {
- // ?
- //errMsg("IIIproblem","At "<<org<<" obj inside:"<<mGiObjInside<<" firstside:"<<giObjFirstHistSide );
- globCPIProblems++;
- mGiObjInside++; // believe first hit side...
- }
- }
-
- if(globGeoInitDebug) errMsg("CHIII"," ins="<<mGiObjInside<<" t"<<mGiObjDistance<<" d"<<distance);
- if(((mGiObjInside%2)==1)&&(mGiObjDistance>0.0)) {
- if( (distance<0.0) || // first intersection -> good
- ((distance>0.0)&&(distance>mGiObjDistance)) // more than one intersection -> use closest one
- ) {
- distance = mGiObjDistance;
- OId = 0;
- inside = true;
- }
- }
-
- if(!inside) {
- distance = firstHit;
- OId = firstOId;
- }
- if(globGeoInitDebug) errMsg("CHIII","ins"<<inside<<" fh"<<firstHit<<" fo"<<firstOId<<" - h"<<distance<<" o"<<OId);
-
- return inside;
-}
-int ControlParticles::initFromMVCMesh(string filename) {
- myTime_t mvmstart = getTime();
- ntlGeometryObjModel *model = new ntlGeometryObjModel();
- int gid=1;
- char infile[256];
- vector<ntlTriangle> triangles;
- vector<ntlVec3Gfx> vertices;
- vector<ntlVec3Gfx> normals;
- snprintf(infile,256,"%s.bobj.gz", filename.c_str() );
- model->loadBobjModel(string(infile));
- model->setLoaded(true);
- model->setGeoInitId(gid);
- model->setGeoInitType(FGI_FLUID);
- debMsgStd("ControlParticles::initFromMVMCMesh",DM_MSG,"infile:"<<string(infile) ,4);
-
- //getTriangles(double t, vector<ntlTriangle> *triangles, vector<ntlVec3Gfx> *vertices, vector<ntlVec3Gfx> *normals, int objectId );
- model->getTriangles(mCPSTimeStart, &triangles, &vertices, &normals, 1 );
- debMsgStd("ControlParticles::initFromMVMCMesh",DM_MSG," tris:"<<triangles.size()<<" verts:"<<vertices.size()<<" norms:"<<normals.size() , 2);
-
- // valid mesh?
- if(triangles.size() <= 0) {
- return 0;
- }
-
- ntlRenderGlobals *glob = new ntlRenderGlobals;
- ntlScene *genscene = new ntlScene( glob, false );
- genscene->addGeoClass(model);
- genscene->addGeoObject(model);
- genscene->buildScene(0., false);
- char treeFlag = (1<<(4+gid));
-
- ntlTree *tree = new ntlTree(
- 15, 8, // TREEwarning - fixed values for depth & maxtriangles here...
- genscene, treeFlag );
-
- // TODO? use params
- ntlVec3Gfx start,end;
- model->getExtends(start,end);
-
- LbmFloat width = mCPSWidth;
- if(width<=LBM_EPSILON) { errMsg("ControlParticles::initFromMVMCMesh","Invalid mCPSWidth! "<<mCPSWidth); width=mCPSWidth=0.1; }
- ntlVec3Gfx org = start+ntlVec3Gfx(width*0.5);
- gfxReal distance = -1.;
- vector<ntlVec3Gfx> inspos;
- int approxmax = (int)( ((end[0]-start[0])/width)*((end[1]-start[1])/width)*((end[2]-start[2])/width) );
-
- debMsgStd("ControlParticles::initFromMVMCMesh",DM_MSG,"start"<<start<<" end"<<end<<" w="<<width<<" maxp:"<<approxmax, 5);
- while(org[2]<end[2]) {
- while(org[1]<end[1]) {
- while(org[0]<end[0]) {
- if(checkPointInside(tree, org, distance)) {
- inspos.push_back(org);
- //inspos.push_back(org+ntlVec3Gfx(width));
- //inspos.push_back(start+end*0.5);
- }
- // TODO optimize, use distance
- org[0] += width;
- }
- org[1] += width;
- org[0] = start[0];
- }
- org[2] += width;
- org[1] = start[1];
- }
- debMsgStd("ControlParticles::initFromMVMCMesh",DM_MSG,"points: "<<inspos.size()<<" initproblems: "<<globCPIProblems,5 );
-
- MeanValueMeshCoords mvm;
- mvm.calculateMVMCs(vertices,triangles, inspos, mCPSWeightFac);
- vector<ntlVec3Gfx> ninspos;
- mvm.transfer(vertices, ninspos);
-
- // init first set, check dist
- ControlParticleSet firstcps; //T
- mPartSets.push_back(firstcps);
- mPartSets[mPartSets.size()-1].time = (gfxReal)0.;
- vector<bool> useCP;
- bool debugPos=false;
-
- for(int i=0; i<(int)inspos.size(); i++) {
- ControlParticle p; p.reset();
- p.pos = vec2L(inspos[i]);
- //errMsg("COMP "," "<<inspos[i]<<" vs "<<ninspos[i] );
- double cpdist = norm(inspos[i]-ninspos[i]);
- bool usecpv = true;
- if(debugPos) errMsg("COMP "," "<<cpdist<<usecpv);
-
- mPartSets[mPartSets.size()-1].particles.push_back(p);
- useCP.push_back(usecpv);
- }
-
- // init further sets, temporal mesh sampling
- double tsampling = mCPSTimestep;
- int totcnt = (int)( (mCPSTimeEnd-mCPSTimeStart)/tsampling ), tcnt=0;
- for(double t=mCPSTimeStart+tsampling; ((t<mCPSTimeEnd) && (ninspos.size()>0.)); t+=tsampling) {
- ControlParticleSet nextcps; //T
- mPartSets.push_back(nextcps);
- mPartSets[mPartSets.size()-1].time = (gfxReal)t;
-
- vertices.clear(); triangles.clear(); normals.clear();
- model->getTriangles(t, &triangles, &vertices, &normals, 1 );
- mvm.transfer(vertices, ninspos);
- if(tcnt%(totcnt/10)==1) debMsgStd("MeanValueMeshCoords::calculateMVMCs",DM_MSG,"Transferring animation, frame: "<<tcnt<<"/"<<totcnt,5 );
- tcnt++;
- for(int i=0; i<(int)ninspos.size(); i++) {
- if(debugPos) errMsg("COMP "," "<<norm(inspos[i]-ninspos[i]) );
- if(useCP[i]) {
- ControlParticle p; p.reset();
- p.pos = vec2L(ninspos[i]);
- mPartSets[mPartSets.size()-1].particles.push_back(p);
- }
- }
- }
-
- applyTrafos();
-
- myTime_t mvmend = getTime();
- debMsgStd("ControlParticle::initFromMVMCMesh",DM_MSG,"t:"<<getTimeString(mvmend-mvmstart)<<" ",7 );
- delete tree;
- delete genscene;
- delete glob;
-//exit(1); // DEBUG
- return 1;
-}
-
-#define TRISWAP(v,a,b) { LbmFloat tmp = (v)[b]; (v)[b]=(v)[a]; (v)[a]=tmp; }
-#define TRISWAPALL(v,a,b) { \
- TRISWAP( (v).pos ,a,b ); \
- TRISWAP( (v).vel ,a,b ); \
- TRISWAP( (v).rotaxis ,a,b ); }
-
-// helper function for LBM 2D -> swap Y and Z components everywhere
-void ControlParticles::swapCoords(int a, int b) {
- //return;
- for(int i=0; i<(int)mPartSets.size(); i++) {
- for(int j=0; j<(int)mPartSets[i].particles.size(); j++) {
- TRISWAPALL( mPartSets[i].particles[j],a,b );
- }
- }
-}
-
-// helper function for LBM 2D -> mirror time
-void ControlParticles::mirrorTime() {
- LbmFloat maxtime = mPartSets[mPartSets.size()-1].time;
- const bool debugTimeswap = false;
-
- for(int i=0; i<(int)mPartSets.size(); i++) {
- mPartSets[i].time = maxtime - mPartSets[i].time;
- }
-
- for(int i=0; i<(int)mPartSets.size()/2; i++) {
- ControlParticleSet cps = mPartSets[i];
- if(debugTimeswap) errMsg("TIMESWAP", " s"<<i<<","<<mPartSets[i].time<<" and s"<<(mPartSets.size()-1-i)<<","<< mPartSets[mPartSets.size()-1-i].time <<" mt:"<<maxtime );
- mPartSets[i] = mPartSets[mPartSets.size()-1-i];
- mPartSets[mPartSets.size()-1-i] = cps;
- }
-
- for(int i=0; i<(int)mPartSets.size(); i++) {
- if(debugTimeswap) errMsg("TIMESWAP", "done: s"<<i<<","<<mPartSets[i].time<<" "<<mPartSets[i].particles.size() );
- }
-}
-
-// apply init transformations
-void ControlParticles::applyTrafos() {
- // apply trafos
- for(int i=0; i<(int)mPartSets.size(); i++) {
- mPartSets[i].time *= _initTimeScale;
- /*for(int j=0; j<(int)mPartSets[i].particles.size(); j++) {
- for(int k=0; k<3; k++) {
- mPartSets[i].particles[j].pos[k] *= _initPartScale[k];
- mPartSets[i].particles[j].pos[k] += _initPartOffset[k];
- }
- } now done in initarray */
- }
-
- // mirror coords...
- for(int l=0; l<(int)_initMirror.length(); l++) {
- switch(_initMirror[l]) {
- case 'X':
- case 'x':
- //printf("ControlParticles::applyTrafos - mirror x\n");
- swapCoords(1,2);
- break;
- case 'Y':
- case 'y':
- //printf("ControlParticles::applyTrafos - mirror y\n");
- swapCoords(0,2);
- break;
- case 'Z':
- case 'z':
- //printf("ControlParticles::applyTrafos - mirror z\n");
- swapCoords(0,1);
- break;
- case 'T':
- case 't':
- //printf("ControlParticles::applyTrafos - mirror time\n");
- mirrorTime();
- break;
- case ' ':
- case '-':
- case '\n':
- break;
- default:
- //printf("ControlParticles::applyTrafos - mirror unknown %c !?\n", _initMirror[l] );
- break;
- }
- }
-
- // reset 2d positions
-#if (CP_PROJECT2D==1) && ( defined(MAIN_2D) || LBMDIM==2 )
- for(size_t j=0; j<mPartSets.size(); j++)
- for(size_t i=0; i<mPartSets[j].particles.size(); i++) {
- // DEBUG
- mPartSets[j].particles[i].pos[1] = 0.f;
- }
-#endif
-
-#if defined(LBMDIM)
- //? if( (getenv("ELBEEM_CPINFILE")) || (getenv("ELBEEM_CPOUTFILE")) ){
- // gui control test, don swap...
- //? } else {
- //? swapCoords(1,2); // LBM 2D -> swap Y and Z components everywhere
- //? }
-#endif
-
- initTime(0.f, 0.f);
-}
-
-#undef TRISWAP
-
-// --------------------------------------------------------------------------
-// init for a given time
-void ControlParticles::initTime(LbmFloat t, LbmFloat dt)
-{
- //fprintf(stdout, "CPINITTIME init %f\n",t);
- _currTime = t;
- if(mPartSets.size()<1) return;
-
- // init zero velocities
- initTimeArray(t, _particles);
-
- // calculate velocities from prev. timestep?
- if(dt>0.) {
- _currTimestep = dt;
- std::vector<ControlParticle> prevparts;
- initTimeArray(t-dt, prevparts);
- LbmFloat invdt = 1.0/dt;
- for(size_t j=0; j<_particles.size(); j++) {
- ControlParticle &p = _particles[j];
- ControlParticle &prevp = prevparts[j];
- for(int k=0; k<3; k++) {
- p.pos[k] *= _initPartScale[k];
- p.pos[k] += _initPartOffset[k];
- prevp.pos[k] *= _initLastPartScale[k];
- prevp.pos[k] += _initLastPartOffset[k];
- }
- p.vel = (p.pos - prevp.pos)*invdt;
- }
-
- if(0) {
- LbmVec avgvel(0.);
- for(size_t j=0; j<_particles.size(); j++) {
- avgvel += _particles[j].vel;
- }
- avgvel /= (LbmFloat)_particles.size();
- //fprintf(stdout," AVGVEL %f,%f,%f \n",avgvel[0],avgvel[1],avgvel[2]); // DEBUG
- }
- }
-}
-
-// helper, init given array
-void ControlParticles::initTimeArray(LbmFloat t, std::vector<ControlParticle> &parts) {
- if(mPartSets.size()<1) return;
-
- if(parts.size()!=mPartSets[0].particles.size()) {
- //fprintf(stdout,"PRES \n");
- parts.resize(mPartSets[0].particles.size());
- // TODO reset all?
- for(size_t j=0; j<parts.size(); j++) {
- parts[j].reset();
- }
- }
- if(parts.size()<1) return;
-
- // debug inits
- if(mDebugInit==1) {
- // hard coded circle init
- for(size_t j=0; j<mPartSets[0].particles.size(); j++) {
- ControlParticle p = mPartSets[0].particles[j];
- // remember old
- p.density = parts[j].density;
- p.densityWeight = parts[j].densityWeight;
- p.avgVel = parts[j].avgVel;
- p.avgVelAcc = parts[j].avgVelAcc;
- p.avgVelWeight = parts[j].avgVelWeight;
- LbmVec ppos(0.); { // DEBUG
- const float tscale=10.;
- const float tprevo = 0.33;
- const LbmVec toff(50,50,0);
- const LbmVec oscale(30,30,0);
- ppos[0] = cos(tscale* t - tprevo*(float)j + M_PI -0.1) * oscale[0] + toff[0];
- ppos[1] = -sin(tscale* t - tprevo*(float)j + M_PI -0.1) * oscale[1] + toff[1];
- ppos[2] = toff[2]; } // DEBUG
- p.pos = ppos;
- parts[j] = p;
- //errMsg("ControlParticle::initTimeArray","j:"<<j<<" p:"<<parts[j].pos );
- }
- return;
- }
- else if(mDebugInit==2) {
- // hard coded spiral init
- const float tscale=-10.;
- const float tprevo = 0.33;
- LbmVec toff(50,0,-50);
- const LbmVec oscale(20,20,0);
- toff[2] += 30. * t +30.;
- for(size_t j=0; j<mPartSets[0].particles.size(); j++) {
- ControlParticle p = mPartSets[0].particles[j];
- // remember old
- p.density = parts[j].density;
- p.densityWeight = parts[j].densityWeight;
- p.avgVel = parts[j].avgVel;
- p.avgVelAcc = parts[j].avgVelAcc;
- p.avgVelWeight = parts[j].avgVelWeight;
- LbmVec ppos(0.);
- ppos[1] = toff[2];
- LbmFloat zscal = (ppos[1]+100.)/200.;
- ppos[0] = cos(tscale* t - tprevo*(float)j + M_PI -0.1) * oscale[0]*zscal + toff[0];
- ppos[2] = -sin(tscale* t - tprevo*(float)j + M_PI -0.1) * oscale[1]*zscal + toff[1];
- p.pos = ppos;
- parts[j] = p;
-
- toff[2] += 0.25;
- }
- return;
- }
-
- // use first set
- if((t<=mPartSets[0].time)||(mPartSets.size()==1)) {
- //fprintf(stdout,"PINI %f \n", t);
- //parts = mPartSets[0].particles;
- const int i=0;
- for(size_t j=0; j<mPartSets[i].particles.size(); j++) {
- ControlParticle p = mPartSets[i].particles[j];
- // remember old
- p.density = parts[j].density;
- p.densityWeight = parts[j].densityWeight;
- p.avgVel = parts[j].avgVel;
- p.avgVelAcc = parts[j].avgVelAcc;
- p.avgVelWeight = parts[j].avgVelWeight;
- parts[j] = p;
- }
- return;
- }
-
- for(int i=0; i<(int)mPartSets.size()-1; i++) {
- if((mPartSets[i].time<=t) && (mPartSets[i+1].time>t)) {
- LbmFloat d = mPartSets[i+1].time-mPartSets[i].time;
- LbmFloat f = (t-mPartSets[i].time)/d;
- LbmFloat omf = 1.0f - f;
-
- for(size_t j=0; j<mPartSets[i].particles.size(); j++) {
- ControlParticle *src1=&mPartSets[i ].particles[j];
- ControlParticle *src2=&mPartSets[i+1].particles[j];
- ControlParticle &p = parts[j];
- // do linear interpolation
- p.pos = src1->pos * omf + src2->pos *f;
- p.vel = LbmVec(0.); // reset, calculated later on src1->vel * omf + src2->vel *f;
- p.rotaxis = src1->rotaxis * omf + src2->rotaxis *f;
- p.influence = src1->influence * omf + src2->influence *f;
- p.size = src1->size * omf + src2->size *f;
- // dont modify: density, densityWeight
- }
- }
- }
-
- // after last?
- if(t>=mPartSets[ mPartSets.size() -1 ].time) {
- //parts = mPartSets[ mPartSets.size() -1 ].particles;
- const int i= (int)mPartSets.size() -1;
- for(size_t j=0; j<mPartSets[i].particles.size(); j++) {
- ControlParticle p = mPartSets[i].particles[j];
- // restore
- p.density = parts[j].density;
- p.densityWeight = parts[j].densityWeight;
- p.avgVel = parts[j].avgVel;
- p.avgVelAcc = parts[j].avgVelAcc;
- p.avgVelWeight = parts[j].avgVelWeight;
- parts[j] = p;
- }
- }
-}
-
-
-
-
-// --------------------------------------------------------------------------
-
-#define DEBUG_MODVEL 0
-
-// recalculate
-void ControlParticles::calculateKernelWeight() {
- const bool debugKernel = true;
-
- // calculate kernel area with respect to particlesize/cellsize
- LbmFloat kernelw = -1.;
- LbmFloat kernelnorm = -1.;
- LbmFloat krad = (_radiusAtt*0.75); // FIXME use real cone approximation...?
- //krad = (_influenceFalloff*1.);
-#if (CP_PROJECT2D==1) && (defined(MAIN_2D) || LBMDIM==2)
- kernelw = CP_PI*krad*krad;
- kernelnorm = 1.0 / (_fluidSpacing * _fluidSpacing);
-#else // 2D
- kernelw = CP_PI*krad*krad*krad* (4./3.);
- kernelnorm = 1.0 / (_fluidSpacing * _fluidSpacing * _fluidSpacing);
-#endif // MAIN_2D
-
- if(debugKernel) debMsgStd("ControlParticles::calculateKernelWeight",DM_MSG,"kw"<<kernelw<<", norm"<<
- kernelnorm<<", w*n="<<(kernelw*kernelnorm)<<", rad"<<krad<<", sp"<<_fluidSpacing<<" ", 7);
- LbmFloat kernelws = kernelw*kernelnorm;
- _kernelWeight = kernelws;
- if(debugKernel) debMsgStd("ControlParticles::calculateKernelWeight",DM_MSG,"influence f="<<_radiusAtt<<" t="<<
- _influenceTangential<<" a="<<_influenceAttraction<<" v="<<_influenceVelocity<<" kweight="<<_kernelWeight, 7);
- if(_kernelWeight<=0.) {
- errMsg("ControlParticles::calculateKernelWeight", "invalid kernel! "<<_kernelWeight<<", resetting");
- _kernelWeight = 1.;
- }
-}
-
-void
-ControlParticles::prepareControl(LbmFloat simtime, LbmFloat dt, ControlParticles *motion) {
- debMsgStd("ControlParticle::prepareControl",DM_MSG," simtime="<<simtime<<" dt="<<dt<<" ", 5);
-
- //fprintf(stdout,"PREPARE \n");
- LbmFloat avgdw = 0.;
- for(size_t i=0; i<_particles.size(); i++) {
- ControlParticle *cp = &_particles[i];
-
- if(this->getInfluenceAttraction()<0.) {
- cp->density=
- cp->densityWeight = 1.0;
- continue;
- }
-
- // normalize by kernel
- //cp->densityWeight = (1.0 - (cp->density / _kernelWeight)); // store last
-#if (CP_PROJECT2D==1) && (defined(MAIN_2D) || LBMDIM==2)
- cp->densityWeight = (1.0 - (cp->density / (_kernelWeight*cp->size*cp->size) )); // store last
-#else // 2D
- cp->densityWeight = (1.0 - (cp->density / (_kernelWeight*cp->size*cp->size*cp->size) )); // store last
-#endif // MAIN_2D
-
- if(i<10) debMsgStd("ControlParticle::prepareControl",DM_MSG,"kernelDebug i="<<i<<" densWei="<<cp->densityWeight<<" 1/kw"<<(1.0/_kernelWeight)<<" cpdensity="<<cp->density, 9 );
- if(cp->densityWeight<0.) cp->densityWeight=0.;
- if(cp->densityWeight>1.) cp->densityWeight=1.;
-
- avgdw += cp->densityWeight;
- // reset for next step
- cp->density = 0.;
-
- if(cp->avgVelWeight>0.) {
- cp->avgVel = cp->avgVelAcc/cp->avgVelWeight;
- cp->avgVelWeight = 0.;
- cp->avgVelAcc = LbmVec(0.,0.,0.);
- }
- }
- //if(debugKernel) for(size_t i=0; i<_particles.size(); i++) { ControlParticle *cp = &_particles[i]; fprintf(stdout,"A %f,%f \n",cp->density,cp->densityWeight); }
- avgdw /= (LbmFloat)(_particles.size());
- //if(motion) { printf("ControlParticle::kernel: avgdw:%f, kw%f, sp%f \n", avgdw, _kernelWeight, _fluidSpacing); }
-
- //if((simtime>=0.) && (simtime != _currTime))
- initTime(simtime, dt);
-
- if((motion) && (motion->getSize()>0)){
- ControlParticle *motionp = motion->getParticle(0);
- //printf("ControlParticle::prepareControl motion: pos[%f,%f,%f] vel[%f,%f,%f] \n", motionp->pos[0], motionp->pos[1], motionp->pos[2], motionp->vel[0], motionp->vel[1], motionp->vel[2] );
- for(size_t i=0; i<_particles.size(); i++) {
- ControlParticle *cp = &_particles[i];
- cp->pos = cp->pos + motionp->pos;
- cp->vel = cp->vel + motionp->vel;
- cp->size = cp->size * motionp->size;
- cp->influence = cp->size * motionp->influence;
- }
- }
-
- // reset to radiusAtt by default
- if(_radiusVel==0.) _radiusVel = _radiusAtt;
- if(_radiusMinMaxd==0.) _radiusMinMaxd = _radiusAtt;
- if(_radiusMaxd==0.) _radiusMaxd = 2.*_radiusAtt;
- // has to be radiusVel<radiusAtt<radiusMinMaxd<radiusMaxd
- if(_radiusVel>_radiusAtt) _radiusVel = _radiusAtt;
- if(_radiusAtt>_radiusMinMaxd) _radiusAtt = _radiusMinMaxd;
- if(_radiusMinMaxd>_radiusMaxd) _radiusMinMaxd = _radiusMaxd;
-
- //printf("ControlParticle::radii vel:%f att:%f min:%f max:%f \n", _radiusVel,_radiusAtt,_radiusMinMaxd,_radiusMaxd);
- // prepareControl done
-}
-
-void ControlParticles::finishControl(std::vector<ControlForces> &forces, LbmFloat iatt, LbmFloat ivel, LbmFloat imaxd) {
-
- //const LbmFloat iatt = this->getInfluenceAttraction() * this->getCurrTimestep();
- //const LbmFloat ivel = this->getInfluenceVelocity();
- //const LbmFloat imaxd = this->getInfluenceMaxdist() * this->getCurrTimestep();
- // prepare for usage
- iatt *= this->getCurrTimestep();
- ivel *= 1.; // not necessary!
- imaxd *= this->getCurrTimestep();
-
- // skip when size=0
- for(int i=0; i<(int)forces.size(); i++) {
- if(DEBUG_MODVEL) fprintf(stdout, "CPFORGF %d , wf:%f,f:%f,%f,%f , v:%f,%f,%f \n",i, forces[i].weightAtt, forces[i].forceAtt[0],forces[i].forceAtt[1],forces[i].forceAtt[2], forces[i].forceVel[0], forces[i].forceVel[1], forces[i].forceVel[2] );
- LbmFloat cfweight = forces[i].weightAtt; // always normalize
- if((cfweight!=0.)&&(iatt!=0.)) {
- // multiple kernels, normalize - note this does not normalize in d>r/2 region
- if(ABS(cfweight)>1.) { cfweight = 1.0/cfweight; }
- // multiply iatt afterwards to allow stronger force
- cfweight *= iatt;
- forces[i].forceAtt *= cfweight;
- } else {
- forces[i].weightAtt = 0.;
- forces[i].forceAtt = LbmVec(0.);
- }
-
- if( (cfweight==0.) && (imaxd>0.) && (forces[i].maxDistance>0.) ) {
- forces[i].forceMaxd *= imaxd;
- } else {
- forces[i].maxDistance= 0.;
- forces[i].forceMaxd = LbmVec(0.);
- }
-
- LbmFloat cvweight = forces[i].weightVel; // always normalize
- if(cvweight>0.) {
- forces[i].forceVel /= cvweight;
- forces[i].compAv /= cvweight;
- // now modify cvweight, and write back
- // important, cut at 1 - otherwise strong vel. influences...
- if(cvweight>1.) { cvweight = 1.; }
- // thus cvweight is in the range of 0..influenceVelocity, currently not normalized by numCParts
- cvweight *= ivel;
- if(cvweight<0.) cvweight=0.; if(cvweight>1.) cvweight=1.;
- // LBM, FIXME todo use relaxation factor
- //pvel = (cvel*0.5 * cvweight) + (pvel * (1.0-cvweight));
- forces[i].weightVel = cvweight;
-
- //errMsg("COMPAV","i"<<i<<" compav"<<forces[i].compAv<<" forcevel"<<forces[i].forceVel<<" ");
- } else {
- forces[i].weightVel = 0.;
- if(forces[i].maxDistance==0.) forces[i].forceVel = LbmVec(0.);
- forces[i].compAvWeight = 0.;
- forces[i].compAv = LbmVec(0.);
- }
- if(DEBUG_MODVEL) fprintf(stdout, "CPFINIF %d , wf:%f,f:%f,%f,%f , v:%f,%f,%f \n",i, forces[i].weightAtt, forces[i].forceAtt[0],forces[i].forceAtt[1],forces[i].forceAtt[2], forces[i].forceVel[0],forces[i].forceVel[1],forces[i].forceVel[2] );
- }
-
- // unused...
- if(DEBUG_MODVEL) fprintf(stdout,"MFC iatt:%f,%f ivel:%f,%f ifmd:%f,%f \n", iatt,_radiusAtt, ivel,_radiusVel, imaxd, _radiusMaxd);
- //for(size_t i=0; i<_particles.size(); i++) { ControlParticle *cp = &_particles[i]; fprintf(stdout," %f,%f,%f ",cp->density,cp->densityWeight, (1.0 - (12.0*cp->densityWeight))); }
- //fprintf(stdout,"\n\nCP DONE \n\n\n");
-}
-
-
-// --------------------------------------------------------------------------
-// calculate forces at given position, and modify velocity
-// according to timestep
-void ControlParticles::calculateCpInfluenceOpt(ControlParticle *cp, LbmVec fluidpos, LbmVec fluidvel, ControlForces *force, LbmFloat fillFactor) {
- // dont reset, only add...
- // test distance, simple squared distance reject
- const LbmFloat cpfo = _radiusAtt*cp->size;
-
- LbmVec posDelta;
- if(DEBUG_MODVEL) fprintf(stdout, "CP at %f,%f,%f bef fw:%f, f:%f,%f,%f , vw:%f, v:%f,%f,%f \n",fluidpos[0],fluidpos[1],fluidpos[2], force->weightAtt, force->forceAtt[0], force->forceAtt[1], force->forceAtt[2], force->weightVel, force->forceVel[0], force->forceVel[1], force->forceVel[2]);
- posDelta = cp->pos - fluidpos;
-#if LBMDIM==2 && (CP_PROJECT2D==1)
- posDelta[2] = 0.; // project to xy plane, z-velocity should already be gone...
-#endif
-
- const LbmFloat distsqr = posDelta[0]*posDelta[0]+posDelta[1]*posDelta[1]+posDelta[2]*posDelta[2];
- if(DEBUG_MODVEL) fprintf(stdout, " Pd at %f,%f,%f d%f \n",posDelta[0],posDelta[1],posDelta[2], distsqr);
- // cut at influence=0.5 , scaling not really makes sense
- if(cpfo*cpfo < distsqr) {
- /*if(cp->influence>0.5) {
- if(force->weightAtt == 0.) {
- if(force->maxDistance*force->maxDistance > distsqr) {
- const LbmFloat dis = sqrtf((float)distsqr);
- const LbmFloat sc = dis-cpfo;
- force->maxDistance = dis;
- force->forceMaxd = (posDelta)*(sc/dis);
- }
- } } */
- return;
- }
- force->weightAtt += 1e-6; // for distance
- force->maxDistance = 0.; // necessary for SPH?
-
- const LbmFloat pdistance = MAGNITUDE(posDelta);
- LbmFloat pdistinv = 0.;
- if(ABS(pdistance)>0.) pdistinv = 1./pdistance;
- posDelta *= pdistinv;
-
- LbmFloat falloffAtt = 0.; //CPKernel::kernel(cpfo * 1.0, pdistance);
- const LbmFloat qac = pdistance / cpfo ;
- if (qac < 1.0){ // return 0.;
- if(qac < 0.5) falloffAtt = 1.0f;
- else falloffAtt = (1.0f - qac) * 2.0f;
- }
-
- // vorticity force:
- // - //LbmVec forceVort;
- // - //CROSS(forceVort, posDelta, cp->rotaxis);
- // - //NORMALIZE(forceVort);
- // - if(falloffAtt>1.0) falloffAtt=1.0;
-
-#if (CP_PROJECT2D==1) && (defined(MAIN_2D) || LBMDIM==2)
- // fillFactor *= 2.0 *0.75 * pdistance; // 2d>3d sampling
-#endif // (CP_PROJECT2D==1) && (defined(MAIN_2D) || LBMDIM==2)
-
- LbmFloat signum = getInfluenceAttraction() > 0.0 ? 1.0 : -1.0;
- cp->density += falloffAtt * fillFactor;
- force->forceAtt += posDelta *cp->densityWeight *cp->influence *signum;
- force->weightAtt += falloffAtt*cp->densityWeight *cp->influence;
-
- LbmFloat falloffVel = 0.; //CPKernel::kernel(cpfo * 1.0, pdistance);
- const LbmFloat cpfv = _radiusVel*cp->size;
- if(cpfv*cpfv < distsqr) { return; }
- const LbmFloat qvc = pdistance / cpfo ;
- //if (qvc < 1.0){
- //if(qvc < 0.5) falloffVel = 1.0f;
- //else falloffVel = (1.0f - qvc) * 2.0f;
- //}
- falloffVel = 1.-qvc;
-
- LbmFloat pvWeight; // = (1.0-cp->densityWeight) * _currTimestep * falloffVel;
- pvWeight = falloffVel *cp->influence; // std, without density influence
- //pvWeight *= (1.0-cp->densityWeight); // use inverse density weight
- //pvWeight *= cp->densityWeight; // test, use density weight
- LbmVec modvel(0.);
- modvel += cp->vel * pvWeight;
- //pvWeight = 1.; modvel = partVel; // DEBUG!?
-
- if(pvWeight>0.) {
- force->forceVel += modvel;
- force->weightVel += pvWeight;
-
- cp->avgVelWeight += falloffVel;
- cp->avgVel += fluidvel;
- }
- if(DEBUG_MODVEL) fprintf(stdout, "CP at %f,%f,%f aft fw:%f, f:%f,%f,%f , vw:%f, v:%f,%f,%f \n",fluidpos[0],fluidpos[1],fluidpos[2], force->weightAtt, force->forceAtt[0], force->forceAtt[1], force->forceAtt[2], force->weightVel, force->forceVel[0], force->forceVel[1], force->forceVel[2]);
- return;
-}
-
-void ControlParticles::calculateMaxdForce(ControlParticle *cp, LbmVec fluidpos, ControlForces *force) {
- if(force->weightAtt != 0.) return; // maxd force off
- if(cp->influence <= 0.5) return; // ignore
-
- LbmVec posDelta;
- //if(DEBUG_MODVEL) fprintf(stdout, "CP at %f,%f,%f bef fw:%f, f:%f,%f,%f , vw:%f, v:%f,%f,%f \n",fluidpos[0],fluidpos[1],fluidpos[2], force->weightAtt, force->forceAtt[0], force->forceAtt[1], force->forceAtt[2], force->weightVel, force->forceVel[0], force->forceVel[1], force->forceVel[2]);
- posDelta = cp->pos - fluidpos;
-#if LBMDIM==2 && (CP_PROJECT2D==1)
- posDelta[2] = 0.; // project to xy plane, z-velocity should already be gone...
-#endif
-
- // dont reset, only add...
- // test distance, simple squared distance reject
- const LbmFloat distsqr = posDelta[0]*posDelta[0]+posDelta[1]*posDelta[1]+posDelta[2]*posDelta[2];
-
- // closer cp found
- if(force->maxDistance*force->maxDistance < distsqr) return;
-
- const LbmFloat dmin = _radiusMinMaxd*cp->size;
- if(distsqr<dmin*dmin) return; // inside min
- const LbmFloat dmax = _radiusMaxd*cp->size;
- if(distsqr>dmax*dmax) return; // outside
-
-
- if(DEBUG_MODVEL) fprintf(stdout, " Pd at %f,%f,%f d%f \n",posDelta[0],posDelta[1],posDelta[2], distsqr);
- // cut at influence=0.5 , scaling not really makes sense
- const LbmFloat dis = sqrtf((float)distsqr);
- //const LbmFloat sc = dis - dmin;
- const LbmFloat sc = (dis-dmin)/(dmax-dmin); // scale from 0-1
- force->maxDistance = dis;
- force->forceMaxd = (posDelta/dis) * sc;
- //debug errMsg("calculateMaxdForce","pos"<<fluidpos<<" dis"<<dis<<" sc"<<sc<<" dmin"<<dmin<<" maxd"<< force->maxDistance <<" fmd"<<force->forceMaxd );
- return;
-}
-
diff --git a/intern/elbeem/intern/controlparticles.h b/intern/elbeem/intern/controlparticles.h
deleted file mode 100644
index 712dfc40273..00000000000
--- a/intern/elbeem/intern/controlparticles.h
+++ /dev/null
@@ -1,301 +0,0 @@
-// --------------------------------------------------------------------------
-//
-// El'Beem - the visual lattice boltzmann freesurface simulator
-// All code distributed as part of El'Beem is covered by the version 2 of the
-// GNU General Public License. See the file COPYING for details.
-//
-// Copyright 2008 Nils Thuerey , Richard Keiser, Mark Pauly, Ulrich Ruede
-//
-// control particle classes
-//
-// --------------------------------------------------------------------------
-
-#ifndef CONTROLPARTICLES_H
-#define CONTROLPARTICLES_H
-
-#include "ntl_geometrymodel.h"
-
-// indicator for LBM inclusion
-//#ifndef LBMDIM
-
-//#include <NxFoundation.h>
-//#include <vector>
-//class MultisphGUI;
-//#define NORMALIZE(a) a.normalize()
-//#define MAGNITUDE(a) a.magnitude()
-//#define CROSS(a,b,c) a.cross(b,c)
-//#define ABS(a) (a>0. ? (a) : -(a))
-//#include "cpdefines.h"
-
-//#else // LBMDIM
-
-// use compatibility defines
-//#define NORMALIZE(a) normalize(a)
-//#define MAGNITUDE(a) norm(a)
-//#define CROSS(a,b,c) a=cross(b,c)
-
-//#endif // LBMDIM
-
-#define MAGNITUDE(a) norm(a)
-
-// math.h compatibility
-#define CP_PI ((LbmFloat)3.14159265358979323846)
-
-// project 2d test cases onto plane?
-// if not, 3d distance is used for 2d sim as well
-#define CP_PROJECT2D 1
-
-
-// default init for mincpdist, ControlForces::maxDistance
-#define CPF_MAXDINIT 10000.
-
-// storage of influence for a fluid cell/particle in lbm/sph
-class ControlForces
-{
-public:
- ControlForces() { };
- ~ControlForces() {};
-
- // attraction force
- LbmFloat weightAtt;
- LbmVec forceAtt;
- // velocity influence
- LbmFloat weightVel;
- LbmVec forceVel;
- // maximal distance influence,
- // first is max. distance to first control particle
- // second attraction strength
- LbmFloat maxDistance;
- LbmVec forceMaxd;
-
- LbmFloat compAvWeight;
- LbmVec compAv;
-
- void resetForces() {
- weightAtt = weightVel = 0.;
- maxDistance = CPF_MAXDINIT;
- forceAtt = forceVel = forceMaxd = LbmVec(0.,0.,0.);
- compAvWeight=0.; compAv=LbmVec(0.);
- };
-};
-
-
-// single control particle
-class ControlParticle
-{
-public:
- ControlParticle() { reset(); };
- ~ControlParticle() {};
-
- // control parameters
-
- // position
- LbmVec pos;
- // size (influences influence radius)
- LbmFloat size;
- // overall strength of influence
- LbmFloat influence;
- // rotation axis
- LbmVec rotaxis;
-
- // computed values
-
- // velocity
- LbmVec vel;
- // computed density
- LbmFloat density;
- LbmFloat densityWeight;
-
- LbmVec avgVel;
- LbmVec avgVelAcc;
- LbmFloat avgVelWeight;
-
- // init all zero / defaults
- void reset();
-};
-
-
-// container for a particle configuration at time t
-class ControlParticleSet
-{
-public:
-
- // time of particle set
- LbmFloat time;
- // particle positions
- std::vector<ControlParticle> particles;
-
-};
-
-
-// container & management of control particles
-class ControlParticles
-{
-public:
- ControlParticles();
- ~ControlParticles();
-
- // reset datastructures for next influence step
- // if motion object is given, particle 1 of second system is used for overall
- // position and speed offset
- void prepareControl(LbmFloat simtime, LbmFloat dt, ControlParticles *motion);
- // post control operations
- void finishControl(std::vector<ControlForces> &forces, LbmFloat iatt, LbmFloat ivel, LbmFloat imaxd);
- // recalculate
- void calculateKernelWeight();
-
- // calculate forces at given position, and modify velocity
- // according to timestep (from initControl)
- void calculateCpInfluenceOpt (ControlParticle *cp, LbmVec fluidpos, LbmVec fluidvel, ControlForces *force, LbmFloat fillFactor);
- void calculateMaxdForce (ControlParticle *cp, LbmVec fluidpos, ControlForces *force);
-
- // no. of particles
- inline int getSize() { return (int)_particles.size(); }
- int getTotalSize();
- // get particle [i]
- inline ControlParticle* getParticle(int i){ return &_particles[i]; }
-
- // set influence parameters
- void setInfluenceTangential(LbmFloat set) { _influenceTangential=set; }
- void setInfluenceAttraction(LbmFloat set) { _influenceAttraction=set; }
- void setInfluenceMaxdist(LbmFloat set) { _influenceMaxdist=set; }
- // calculate for delta t
- void setInfluenceVelocity(LbmFloat set, LbmFloat dt);
- // get influence parameters
- inline LbmFloat getInfluenceAttraction() { return _influenceAttraction; }
- inline LbmFloat getInfluenceTangential() { return _influenceTangential; }
- inline LbmFloat getInfluenceVelocity() { return _influenceVelocity; }
- inline LbmFloat getInfluenceMaxdist() { return _influenceMaxdist; }
- inline LbmFloat getCurrTimestep() { return _currTimestep; }
-
- void setRadiusAtt(LbmFloat set) { _radiusAtt=set; }
- inline LbmFloat getRadiusAtt() { return _radiusAtt; }
- void setRadiusVel(LbmFloat set) { _radiusVel=set; }
- inline LbmFloat getRadiusVel() { return _radiusVel; }
- void setRadiusMaxd(LbmFloat set) { _radiusMaxd=set; }
- inline LbmFloat getRadiusMaxd() { return _radiusMaxd; }
- void setRadiusMinMaxd(LbmFloat set) { _radiusMinMaxd=set; }
- inline LbmFloat getRadiusMinMaxd() { return _radiusMinMaxd; }
-
- LbmFloat getControlTimStart();
- LbmFloat getControlTimEnd();
-
- // set/get characteristic length (and inverse)
- void setCharLength(LbmFloat set) { _charLength=set; _charLengthInv=1./_charLength; }
- inline LbmFloat getCharLength() { return _charLength;}
- inline LbmFloat getCharLengthInv() { return _charLengthInv;}
-
- // set init parameters
- void setInitTimeScale(LbmFloat set) { _initTimeScale = set; };
- void setInitMirror(string set) { _initMirror = set; };
- string getInitMirror() { return _initMirror; };
-
- void setLastOffset(LbmVec set) { _initLastPartOffset = set; };
- void setLastScale(LbmVec set) { _initLastPartScale = set; };
- void setOffset(LbmVec set) { _initPartOffset = set; };
- void setScale(LbmVec set) { _initPartScale = set; };
-
- // set/get cps params
- void setCPSWith(LbmFloat set) { mCPSWidth = set; };
- void setCPSTimestep(LbmFloat set) { mCPSTimestep = set; };
- void setCPSTimeStart(LbmFloat set) { mCPSTimeStart = set; };
- void setCPSTimeEnd(LbmFloat set) { mCPSTimeEnd = set; };
- void setCPSMvmWeightFac(LbmFloat set) { mCPSWeightFac = set; };
-
- LbmFloat getCPSWith() { return mCPSWidth; };
- LbmFloat getCPSTimestep() { return mCPSTimestep; };
- LbmFloat getCPSTimeStart() { return mCPSTimeStart; };
- LbmFloat getCPSTimeEnd() { return mCPSTimeEnd; };
- LbmFloat getCPSMvmWeightFac() { return mCPSWeightFac; };
-
- void setDebugInit(int set) { mDebugInit = set; };
-
- // set init parameters
- void setFluidSpacing(LbmFloat set) { _fluidSpacing = set; };
-
- // load positions & timing from text file
- int initFromTextFile(string filename);
- int initFromTextFileOld(string filename);
- // load positions & timing from gzipped binary file
- int initFromBinaryFile(string filename);
- int initFromMVCMesh(string filename);
- // init an example test case
- int initExampleSet();
-
- // init for a given time
- void initTime(LbmFloat t, LbmFloat dt);
-
- // blender test init
- void initBlenderTest();
-
- int initFromObject(ntlGeometryObjModel *model);
-
-protected:
- // sets influence params
- friend class MultisphGUI;
-
- // tangential and attraction influence
- LbmFloat _influenceTangential, _influenceAttraction;
- // direct velocity influence
- LbmFloat _influenceVelocity;
- // maximal distance influence
- LbmFloat _influenceMaxdist;
-
- // influence radii
- LbmFloat _radiusAtt, _radiusVel, _radiusMinMaxd, _radiusMaxd;
-
- // currently valid time & timestep
- LbmFloat _currTime, _currTimestep;
- // all particles
- std::vector<ControlParticle> _particles;
-
- // particle sets
- std::vector<ControlParticleSet> mPartSets;
-
- // additional parameters for initing particles
- LbmFloat _initTimeScale;
- LbmVec _initPartOffset;
- LbmVec _initPartScale;
- LbmVec _initLastPartOffset;
- LbmVec _initLastPartScale;
- // mirror particles for loading?
- string _initMirror;
-
- // row spacing paramter, e.g. use for approximation of kernel area/volume
- LbmFloat _fluidSpacing;
- // save current kernel weight
- LbmFloat _kernelWeight;
- // charateristic length in world coordinates for normalizatioon of forces
- LbmFloat _charLength, _charLengthInv;
-
-
- /*! do ani mesh CPS */
- void calculateCPS(string filename);
- //! ani mesh cps params
- ntlVec3Gfx mvCPSStart, mvCPSEnd;
- gfxReal mCPSWidth, mCPSTimestep;
- gfxReal mCPSTimeStart, mCPSTimeEnd;
- gfxReal mCPSWeightFac;
-
- int mDebugInit;
-
-
-protected:
- // apply init transformations
- void applyTrafos();
-
- // helper function for init -> swap components everywhere
- void swapCoords(int a,int b);
- // helper function for init -> mirror time
- void mirrorTime();
-
- // helper, init given array
- void initTimeArray(LbmFloat t, std::vector<ControlParticle> &parts);
-
- bool checkPointInside(ntlTree *tree, ntlVec3Gfx org, gfxReal &distance);
-};
-
-
-
-#endif
-
diff --git a/intern/elbeem/intern/elbeem_control.cpp b/intern/elbeem/intern/elbeem_control.cpp
deleted file mode 100644
index 800167baf73..00000000000
--- a/intern/elbeem/intern/elbeem_control.cpp
+++ /dev/null
@@ -1,25 +0,0 @@
-/******************************************************************************
- *
- * El'Beem - Free Surface Fluid Simulation with the Lattice Boltzmann Method
- * All code distributed as part of El'Beem is covered by the version 2 of the
- * GNU General Public License. See the file COPYING for details.
- * Copyright 2003-2006 Nils Thuerey
- *
- * Control API header
- */
-
-#include "elbeem.h"
-#include "elbeem_control.h"
-
-// add mesh as fluidsim object
-int elbeemControlAddSet(struct elbeemControl*) {
-
- return 0;
-}
-
-int elbeemControlComputeMesh(struct elbeemMesh*) {
-
-
- return 0;
-}
-
diff --git a/intern/elbeem/intern/elbeem_control.h b/intern/elbeem/intern/elbeem_control.h
deleted file mode 100644
index 70a58feda89..00000000000
--- a/intern/elbeem/intern/elbeem_control.h
+++ /dev/null
@@ -1,62 +0,0 @@
-/******************************************************************************
- *
- * El'Beem - Free Surface Fluid Simulation with the Lattice Boltzmann Method
- * All code distributed as part of El'Beem is covered by the version 2 of the
- * GNU General Public License. See the file COPYING for details.
- * Copyright 2003-2006 Nils Thuerey
- *
- * Control API header
- */
-#ifndef ELBEEMCONTROL_API_H
-#define ELBEEMCONTROL_API_H
-
-// a single control particle set
-typedef struct elbeemControl {
- /* influence forces */
- float influenceAttraction;
- float *channelInfluenceAttraction;
- float channelSizeInfluenceAttraction;
-
- float influenceVelocity;
- float *channelInfluenceVelocity;
- float channelSizeInfluenceVelocity;
-
- float influenceMaxdist;
- float *channelInfluenceMaxdist;
- float channelSizeInfluenceMaxdist;
-
- /* influence force radii */
- float radiusAttraction;
- float *channelRadiusAttraction;
- float channelSizeRadiusAttraction;
-
- float radiusVelocity;
- float *channelRadiusVelocity;
- float channelSizeRadiusVelocity;
-
- float radiusMindist;
- float *channelRadiusMindist;
- float channelSizeRadiusMindist;
- float radiusMaxdist;
- float *channelRadiusMaxdist;
- float channelSizeRadiusMaxdist;
-
- /* control particle positions/scale */
- float offset[3];
- float *channelOffset;
- float channelSizeOffset;
-
- float scale[3];
- float *channelScale;
- float channelSizeScale;
-
-} elbeemControl;
-
-
-// add mesh as fluidsim object
-int elbeemControlAddSet(struct elbeemControl*);
-
-// sample & track mesh control particles, TODO add return type...
-int elbeemControlComputeMesh(struct elbeemMesh*);
-
-#endif // ELBEEMCONTROL_API_H
diff --git a/intern/elbeem/intern/mvmcoords.cpp b/intern/elbeem/intern/mvmcoords.cpp
deleted file mode 100644
index 03f6482ae84..00000000000
--- a/intern/elbeem/intern/mvmcoords.cpp
+++ /dev/null
@@ -1,193 +0,0 @@
-/******************************************************************************
- *
-// El'Beem - the visual lattice boltzmann freesurface simulator
-// All code distributed as part of El'Beem is covered by the version 2 of the
-// GNU General Public License. See the file COPYING for details.
-//
-// Copyright 2008 Nils Thuerey , Richard Keiser, Mark Pauly, Ulrich Ruede
-//
- *
- * Mean Value Mesh Coords class
- *
- *****************************************************************************/
-
-#include "mvmcoords.h"
-#include <algorithm>
-using std::vector;
-
-void MeanValueMeshCoords::clear()
-{
- mVertices.resize(0);
- mNumVerts = 0;
-}
-
-void MeanValueMeshCoords::calculateMVMCs(vector<ntlVec3Gfx> &reference_vertices, vector<ntlTriangle> &tris,
- vector<ntlVec3Gfx> &points, gfxReal numweights)
-{
- clear();
- mvmTransferPoint tds;
- int mem = 0;
- int i = 0;
-
- mNumVerts = (int)reference_vertices.size();
-
- for (vector<ntlVec3Gfx>::iterator iter = points.begin(); iter != points.end(); ++iter, ++i) {
- /*
- if(i%(points.size()/10)==1) debMsgStd("MeanValueMeshCoords::calculateMVMCs",DM_MSG,"Computing weights, points: "<<i<<"/"<<points.size(),5 );
- */
- tds.lastpos = *iter;
- tds.weights.resize(0); // clear
- computeWeights(reference_vertices, tris, tds, numweights);
- mem += (int)tds.weights.size();
- mVertices.push_back(tds);
- }
- int mbmem = mem * sizeof(mvmFloat) / (1024*1024);
- debMsgStd("MeanValueMeshCoords::calculateMVMCs",DM_MSG,"vertices:"<<mNumVerts<<" points:"<<points.size()<<" weights:"<<mem<<", wmem:"<<mbmem<<"MB ",7 );
-}
-
-// from: mean value coordinates for closed triangular meshes
-// attention: fails if a point is exactly (or very close) to a vertex
-void MeanValueMeshCoords::computeWeights(vector<ntlVec3Gfx> &reference_vertices, vector<ntlTriangle>& tris,
- mvmTransferPoint& tds, gfxReal numweights)
-{
- const bool mvmFullDebug=false;
- //const ntlVec3Gfx cEPS = 1.0e-6;
- const mvmFloat cEPS = 1.0e-14;
-
- //mvmFloat d[3], s[3], phi[3],c[3];
- ntlVec3d u[3],c,d,s,phi;
- int indices[3];
-
- for (int i = 0; i < (int)reference_vertices.size(); ++i) {
- tds.weights.push_back(mvmIndexWeight(i, 0.0));
- }
-
- // for each triangle
- //for (vector<ntlTriangle>::iterator iter = tris.begin(); iter != tris.end();) {
- for(int t=0; t<(int)tris.size(); t++) {
-
- for (int i = 0; i < 3; ++i) { //, ++iter) {
- indices[i] = tris[t].getPoints()[i];
- u[i] = vec2D(reference_vertices[ indices[i] ]-tds.lastpos);
- d[i] = normalize(u[i]); //.normalize();
- //assert(d[i] != 0.);
- if(mvmFullDebug) errMsg("MeanValueMeshCoords::computeWeights","t"<<t<<" i"<<indices[i] //<<" lp"<<tds.lastpos
- <<" v"<<reference_vertices[indices[i]]<<" u"<<u[i]<<" ");
- // on vertex!
- //? if(d[i]<=0.) continue;
- }
- //for (int i = 0; i < 3; ++i) { errMsg("III"," "<<i <<" i"<<indices[i]<<reference_vertices[ indices[i] ] ); }
-
- // arcsin is not needed, see paper
- phi[0] = 2.*asin( (mvmFloat)(0.5* norm(u[1]-u[2]) ) );
- phi[1] = 2.*asin( (mvmFloat)(0.5* norm(u[0]-u[2]) ) );
- phi[2] = 2.*asin( (mvmFloat)(0.5* norm(u[0]-u[1]) ) );
- mvmFloat h = (phi[0] + phi[1] + phi[2])*0.5;
- if (M_PI-h < cEPS) {
- if(mvmFullDebug) errMsg("MeanValueMeshCoords::computeWeights","point on triangle");
- tds.weights.resize(0);
- tds.weights.push_back( mvmIndexWeight(indices[0], sin(phi[0])*d[1]*d[2]));
- tds.weights.push_back( mvmIndexWeight(indices[1], sin(phi[1])*d[0]*d[2]));
- tds.weights.push_back( mvmIndexWeight(indices[2], sin(phi[2])*d[1]*d[0]));
- break;
- }
- mvmFloat sinh = 2.*sin(h);
- c[0] = (sinh*sin(h-phi[0]))/(sin(phi[1])*sin(phi[2]))-1.;
- c[1] = (sinh*sin(h-phi[1]))/(sin(phi[0])*sin(phi[2]))-1.;
- c[2] = (sinh*sin(h-phi[2]))/(sin(phi[0])*sin(phi[1]))-1.;
- if(mvmFullDebug) errMsg("MeanValueMeshCoords::computeWeights","c="<<c<<" phi="<<phi<<" d="<<d);
- //if (c[0] > 1. || c[0] < 0. || c[1] > 1. || c[1] < 0. || c[2] > 1. || c[2] < 0.) continue;
-
- s[0] = sqrt((float)(1.-c[0]*c[0]));
- s[1] = sqrt((float)(1.-c[1]*c[1]));
- s[2] = sqrt((float)(1.-c[2]*c[2]));
-
- if(mvmFullDebug) errMsg("MeanValueMeshCoords::computeWeights","s");
- if (s[0] <= cEPS || s[1] <= cEPS || s[2] <= cEPS) {
- //MSG("position lies outside the triangle on the same plane -> ignore it");
- continue;
- }
- const mvmFloat u0x = u[0][0];
- const mvmFloat u0y = u[0][1];
- const mvmFloat u0z = u[0][2];
- const mvmFloat u1x = u[1][0];
- const mvmFloat u1y = u[1][1];
- const mvmFloat u1z = u[1][2];
- const mvmFloat u2x = u[2][0];
- const mvmFloat u2y = u[2][1];
- const mvmFloat u2z = u[2][2];
- mvmFloat det = u0x*u1y*u2z - u0x*u1z*u2y + u0y*u1z*u2x - u0y*u1x*u2z + u0z*u1x*u2y - u0z*u1y*u2x;
- //assert(det != 0.);
- if (det < 0.) {
- s[0] = -s[0];
- s[1] = -s[1];
- s[2] = -s[2];
- }
-
- tds.weights[indices[0]].weight += (phi[0]-c[1]*phi[2]-c[2]*phi[1])/(d[0]*sin(phi[1])*s[2]);
- tds.weights[indices[1]].weight += (phi[1]-c[2]*phi[0]-c[0]*phi[2])/(d[1]*sin(phi[2])*s[0]);
- tds.weights[indices[2]].weight += (phi[2]-c[0]*phi[1]-c[1]*phi[0])/(d[2]*sin(phi[0])*s[1]);
- if(mvmFullDebug) { errMsg("MeanValueMeshCoords::computeWeights","i"<<indices[0]<<" o"<<tds.weights[indices[0]].weight);
- errMsg("MeanValueMeshCoords::computeWeights","i"<<indices[1]<<" o"<<tds.weights[indices[1]].weight);
- errMsg("MeanValueMeshCoords::computeWeights","i"<<indices[2]<<" o"<<tds.weights[indices[2]].weight);
- errMsg("MeanValueMeshCoords::computeWeights","\n\n\n"); }
- }
-
- //sort weights
- if((numweights>0.)&& (numweights<1.) ) {
- //if( ((int)tds.weights.size() > maxNumWeights) && (maxNumWeights > 0) ) {
- int maxNumWeights = (int)(tds.weights.size()*numweights);
- if(maxNumWeights<=0) maxNumWeights = 1;
- std::sort(tds.weights.begin(), tds.weights.end(), std::greater<mvmIndexWeight>());
- // only use maxNumWeights-th largest weights
- tds.weights.resize(maxNumWeights);
- }
-
- // normalize weights
- mvmFloat totalWeight = 0.;
- for (vector<mvmIndexWeight>::const_iterator witer = tds.weights.begin();
- witer != tds.weights.end(); ++witer) {
- totalWeight += witer->weight;
- }
- mvmFloat invTotalWeight;
- if (totalWeight == 0.) {
- if(mvmFullDebug) errMsg("MeanValueMeshCoords::computeWeights","totalWeight == 0");
- invTotalWeight = 0.0;
- } else {
- invTotalWeight = 1.0/totalWeight;
- }
-
- for (vector<mvmIndexWeight>::iterator viter = tds.weights.begin();
- viter != tds.weights.end(); ++viter) {
- viter->weight *= invTotalWeight;
- //assert(finite(viter->weight) != 0);
- if(!finite(viter->weight)) viter->weight=0.;
- }
-}
-
-void MeanValueMeshCoords::transfer(vector<ntlVec3Gfx> &vertices, vector<ntlVec3Gfx>& displacements)
-{
- displacements.resize(0);
-
- //debMsgStd("MeanValueMeshCoords::transfer",DM_MSG,"vertices:"<<mNumVerts<<" curr_verts:"<<vertices.size()<<" ",7 );
- if((int)vertices.size() != mNumVerts) {
- errMsg("MeanValueMeshCoords::transfer","Different no of verts: "<<vertices.size()<<" vs "<<mNumVerts);
- return;
- }
-
- for (vector<mvmTransferPoint>::iterator titer = mVertices.begin(); titer != mVertices.end(); ++titer) {
- mvmTransferPoint &tds = *titer;
- ntlVec3Gfx newpos(0.0);
-
- for (vector<mvmIndexWeight>::iterator witer = tds.weights.begin();
- witer != tds.weights.end(); ++witer) {
- newpos += vertices[witer->index] * witer->weight;
- //errMsg("transfer","np"<<newpos<<" v"<<vertices[witer->index]<<" w"<< witer->weight);
- }
-
- displacements.push_back(newpos);
- //displacements.push_back(newpos - tds.lastpos);
- //tds.lastpos = newpos;
- }
-}
-
diff --git a/intern/elbeem/intern/mvmcoords.h b/intern/elbeem/intern/mvmcoords.h
deleted file mode 100644
index 889f5058a09..00000000000
--- a/intern/elbeem/intern/mvmcoords.h
+++ /dev/null
@@ -1,89 +0,0 @@
-/******************************************************************************
- *
-// El'Beem - the visual lattice boltzmann freesurface simulator
-// All code distributed as part of El'Beem is covered by the version 2 of the
-// GNU General Public License. See the file COPYING for details.
-//
-// Copyright 2008 Nils Thuerey , Richard Keiser, Mark Pauly, Ulrich Ruede
-//
- *
- * Mean Value Mesh Coords class
- *
- *****************************************************************************/
-
-#ifndef MVMCOORDS_H
-#define MVMCOORDS_H
-
-#include "utilities.h"
-#include "ntl_ray.h"
-#include <vector>
-#define mvmFloat double
-
-#ifdef WIN32
-#ifndef FREE_WINDOWS
-#include "float.h"
-#define isnan(n) _isnan(n)
-#define finite _finite
-#endif
-#endif
-
-#ifdef sun
-#include "ieeefp.h"
-#endif
-
-// weight and triangle index
-class mvmIndexWeight {
- public:
-
- mvmIndexWeight() : weight(0.0) {}
-
- mvmIndexWeight(int const& i, mvmFloat const& w) :
- weight(w), index(i) {}
-
- // for sorting
- bool operator> (mvmIndexWeight const& w) const { return this->weight > w.weight; }
- bool operator< (mvmIndexWeight const& w) const { return this->weight < w.weight; }
-
- mvmFloat weight;
- int index;
-};
-
-// transfer point with weights
-class mvmTransferPoint {
- public:
- //! position of transfer point
- ntlVec3Gfx lastpos;
- //! triangle weights
- std::vector<mvmIndexWeight> weights;
-};
-
-
-//! compute mvmcs
-class MeanValueMeshCoords {
-
- public:
-
- MeanValueMeshCoords() {}
- ~MeanValueMeshCoords() {
- clear();
- }
-
- void clear();
-
- void calculateMVMCs(std::vector<ntlVec3Gfx> &reference_vertices,
- std::vector<ntlTriangle> &tris, std::vector<ntlVec3Gfx> &points, gfxReal numweights);
-
- void transfer(std::vector<ntlVec3Gfx> &vertices, std::vector<ntlVec3Gfx>& displacements);
-
- protected:
-
- void computeWeights(std::vector<ntlVec3Gfx> &reference_vertices,
- std::vector<ntlTriangle> &tris, mvmTransferPoint& tds, gfxReal numweights);
-
- std::vector<mvmTransferPoint> mVertices;
- int mNumVerts;
-
-};
-
-#endif
-
diff --git a/intern/elbeem/intern/solver_control.cpp b/intern/elbeem/intern/solver_control.cpp
deleted file mode 100644
index d3f5598e6dc..00000000000
--- a/intern/elbeem/intern/solver_control.cpp
+++ /dev/null
@@ -1,1020 +0,0 @@
-/******************************************************************************
- *
- * El'Beem - the visual lattice boltzmann freesurface simulator
- * All code distributed as part of El'Beem is covered by the version 2 of the
- * GNU General Public License. See the file COPYING for details.
- *
- * Copyright 2003-2008 Nils Thuerey
- *
- * control extensions
- *
- *****************************************************************************/
-#include "solver_class.h"
-#include "solver_relax.h"
-#include "particletracer.h"
-
-#include "solver_control.h"
-
-#include "controlparticles.h"
-
-#include "elbeem.h"
-
-#include "ntl_geometrymodel.h"
-
-/******************************************************************************
- * LbmControlData control set
- *****************************************************************************/
-
-LbmControlSet::LbmControlSet() :
- mCparts(NULL), mCpmotion(NULL), mContrPartFile(""), mCpmotionFile(""),
- mcForceAtt(0.), mcForceVel(0.), mcForceMaxd(0.),
- mcRadiusAtt(0.), mcRadiusVel(0.), mcRadiusMind(0.), mcRadiusMaxd(0.),
- mcCpScale(1.), mcCpOffset(0.)
-{
-}
-LbmControlSet::~LbmControlSet() {
- if(mCparts) delete mCparts;
- if(mCpmotion) delete mCpmotion;
-}
-void LbmControlSet::initCparts() {
- mCparts = new ControlParticles();
- mCpmotion = new ControlParticles();
-}
-
-
-
-/******************************************************************************
- * LbmControlData control
- *****************************************************************************/
-
-LbmControlData::LbmControlData() :
- mSetForceStrength(0.),
- mCons(),
- mCpUpdateInterval(8), // DG: was 16 --> causes problems (big sphere after some time), unstable
- mCpOutfile(""),
- mCpForces(), mCpKernel(), mMdKernel(),
- mDiffVelCon(1.),
- mDebugCpscale(0.),
- mDebugVelScale(0.),
- mDebugCompavScale(0.),
- mDebugAttScale(0.),
- mDebugMaxdScale(0.),
- mDebugAvgVelScale(0.)
-{
-}
-
-LbmControlData::~LbmControlData()
-{
- while (!mCons.empty()) {
- delete mCons.back(); mCons.pop_back();
- }
-}
-
-
-void LbmControlData::parseControldataAttrList(AttributeList *attr) {
- // controlpart vars
- mSetForceStrength = attr->readFloat("tforcestrength", mSetForceStrength,"LbmControlData", "mSetForceStrength", false);
- //errMsg("tforcestrength set to "," "<<mSetForceStrength);
- mCpUpdateInterval = attr->readInt("controlparticle_updateinterval", mCpUpdateInterval,"LbmControlData","mCpUpdateInterval", false);
- // tracer output file
- mCpOutfile = attr->readString("controlparticle_outfile",mCpOutfile,"LbmControlData","mCpOutfile", false);
- if(getenv("ELBEEM_CPOUTFILE")) {
- string outfile(getenv("ELBEEM_CPOUTFILE"));
- mCpOutfile = outfile;
- debMsgStd("LbmControlData::parseAttrList",DM_NOTIFY,"Using envvar ELBEEM_CPOUTFILE to set mCpOutfile to "<<outfile<<","<<mCpOutfile,7);
- }
-
- for(int cpii=0; cpii<10; cpii++) {
- string suffix("");
- //if(cpii>0)
- { suffix = string("0"); suffix[0]+=cpii; }
- LbmControlSet *cset;
- cset = new LbmControlSet();
- cset->initCparts();
-
- cset->mContrPartFile = attr->readString("controlparticle"+suffix+"_file",cset->mContrPartFile,"LbmControlData","cset->mContrPartFile", false);
- if((cpii==0) && (getenv("ELBEEM_CPINFILE")) ) {
- string infile(getenv("ELBEEM_CPINFILE"));
- cset->mContrPartFile = infile;
- debMsgStd("LbmControlData::parseAttrList",DM_NOTIFY,"Using envvar ELBEEM_CPINFILE to set mContrPartFile to "<<infile<<","<<cset->mContrPartFile,7);
- }
-
- LbmFloat cpvort=0.;
- cset->mcRadiusAtt = attr->readChannelSinglePrecFloat("controlparticle"+suffix+"_radiusatt", 0., "LbmControlData","mcRadiusAtt" );
- cset->mcRadiusVel = attr->readChannelSinglePrecFloat("controlparticle"+suffix+"_radiusvel", 0., "LbmControlData","mcRadiusVel" );
- cset->mcRadiusVel = attr->readChannelSinglePrecFloat("controlparticle"+suffix+"_radiusvel", 0., "LbmControlData","mcRadiusVel" );
- cset->mCparts->setRadiusAtt(cset->mcRadiusAtt.get(0.));
- cset->mCparts->setRadiusVel(cset->mcRadiusVel.get(0.));
-
- // WARNING currently only for first set
- //if(cpii==0) {
- cset->mcForceAtt = attr->readChannelSinglePrecFloat("controlparticle"+suffix+"_attraction", 0. , "LbmControlData","cset->mcForceAtt", false);
- cset->mcForceVel = attr->readChannelSinglePrecFloat("controlparticle"+suffix+"_velocity", 0. , "LbmControlData","mcForceVel", false);
- cset->mcForceMaxd = attr->readChannelSinglePrecFloat("controlparticle"+suffix+"_maxdist", 0. , "LbmControlData","mcForceMaxd", false);
- cset->mCparts->setInfluenceAttraction(cset->mcForceAtt.get(0.) );
- // warning - stores temprorarily, value converted to dt dep. factor
- cset->mCparts->setInfluenceVelocity(cset->mcForceVel.get(0.) , 0.01 ); // dummy dt
- cset->mCparts->setInfluenceMaxdist(cset->mcForceMaxd.get(0.) );
- cpvort = attr->readFloat("controlparticle"+suffix+"_vorticity", cpvort, "LbmControlData","cpvort", false);
- cset->mCparts->setInfluenceTangential(cpvort);
-
- cset->mcRadiusMind = attr->readChannelSinglePrecFloat("controlparticle"+suffix+"_radiusmin", cset->mcRadiusMind.get(0.), "LbmControlData","mcRadiusMind", false);
- cset->mcRadiusMaxd = attr->readChannelSinglePrecFloat("controlparticle"+suffix+"_radiusmax", cset->mcRadiusMind.get(0.), "LbmControlData","mcRadiusMaxd", false);
- cset->mCparts->setRadiusMinMaxd(cset->mcRadiusMind.get(0.));
- cset->mCparts->setRadiusMaxd(cset->mcRadiusMaxd.get(0.));
- //}
-
- // now local...
- //LbmVec cpOffset(0.), cpScale(1.);
- LbmFloat cpTimescale = 1.;
- string cpMirroring("");
-
- //cset->mcCpOffset = attr->readChannelVec3f("controlparticle"+suffix+"_offset", ntlVec3f(0.),"LbmControlData","mcCpOffset", false);
- //cset->mcCpScale = attr->readChannelVec3f("controlparticle"+suffix+"_scale", ntlVec3f(1.), "LbmControlData","mcCpScale", false);
- cset->mcCpOffset = attr->readChannelVec3f("controlparticle"+suffix+"_offset", ntlVec3f(0.),"LbmControlData","mcCpOffset", false);
- cset->mcCpScale = attr->readChannelVec3f("controlparticle"+suffix+"_scale", ntlVec3f(1.), "LbmControlData","mcCpScale", false);
- cpTimescale = attr->readFloat("controlparticle"+suffix+"_timescale", cpTimescale, "LbmControlData","cpTimescale", false);
- cpMirroring = attr->readString("controlparticle"+suffix+"_mirror", cpMirroring, "LbmControlData","cpMirroring", false);
-
- LbmFloat cpsWidth = cset->mCparts->getCPSWith();
- cpsWidth = attr->readFloat("controlparticle"+suffix+"_cpswidth", cpsWidth, "LbmControlData","cpsWidth", false);
- LbmFloat cpsDt = cset->mCparts->getCPSTimestep();
- cpsDt = attr->readFloat("controlparticle"+suffix+"_cpstimestep", cpsDt, "LbmControlData","cpsDt", false);
- LbmFloat cpsTstart = cset->mCparts->getCPSTimeStart();
- cpsTstart = attr->readFloat("controlparticle"+suffix+"_cpststart", cpsTstart, "LbmControlData","cpsTstart", false);
- LbmFloat cpsTend = cset->mCparts->getCPSTimeEnd();
- cpsTend = attr->readFloat("controlparticle"+suffix+"_cpstend", cpsTend, "LbmControlData","cpsTend", false);
- LbmFloat cpsMvmfac = cset->mCparts->getCPSMvmWeightFac();
- cpsMvmfac = attr->readFloat("controlparticle"+suffix+"_cpsmvmfac", cpsMvmfac, "LbmControlData","cpsMvmfac", false);
- cset->mCparts->setCPSWith(cpsWidth);
- cset->mCparts->setCPSTimestep(cpsDt);
- cset->mCparts->setCPSTimeStart(cpsTstart);
- cset->mCparts->setCPSTimeEnd(cpsTend);
- cset->mCparts->setCPSMvmWeightFac(cpsMvmfac);
-
- cset->mCparts->setOffset( vec2L(cset->mcCpOffset.get(0.)) );
- cset->mCparts->setScale( vec2L(cset->mcCpScale.get(0.)) );
- cset->mCparts->setInitTimeScale( cpTimescale );
- cset->mCparts->setInitMirror( cpMirroring );
-
- int mDebugInit = 0;
- mDebugInit = attr->readInt("controlparticle"+suffix+"_debuginit", mDebugInit,"LbmControlData","mDebugInit", false);
- cset->mCparts->setDebugInit(mDebugInit);
-
- // motion particle settings
- LbmVec mcpOffset(0.), mcpScale(1.);
- LbmFloat mcpTimescale = 1.;
- string mcpMirroring("");
-
- cset->mCpmotionFile = attr->readString("cpmotion"+suffix+"_file",cset->mCpmotionFile,"LbmControlData","mCpmotionFile", false);
- mcpTimescale = attr->readFloat("cpmotion"+suffix+"_timescale", mcpTimescale, "LbmControlData","mcpTimescale", false);
- mcpMirroring = attr->readString("cpmotion"+suffix+"_mirror", mcpMirroring, "LbmControlData","mcpMirroring", false);
- mcpOffset = vec2L( attr->readVec3d("cpmotion"+suffix+"_offset", vec2P(mcpOffset),"LbmControlData","cpOffset", false) );
- mcpScale = vec2L( attr->readVec3d("cpmotion"+suffix+"_scale", vec2P(mcpScale), "LbmControlData","cpScale", false) );
-
- cset->mCpmotion->setOffset( vec2L(mcpOffset) );
- cset->mCpmotion->setScale( vec2L(mcpScale) );
- cset->mCpmotion->setInitTimeScale( mcpTimescale );
- cset->mCpmotion->setInitMirror( mcpMirroring );
-
- if(cset->mContrPartFile.length()>1) {
- errMsg("LbmControlData","Using control particle set "<<cpii<<" file:"<<cset->mContrPartFile<<" cpmfile:"<<cset->mCpmotionFile<<" mirr:'"<<cset->mCpmotion->getInitMirror()<<"' " );
- mCons.push_back( cset );
- } else {
- delete cset;
- }
- }
-
- // debug, testing - make sure theres at least an empty set
- if(mCons.size()<1) {
- mCons.push_back( new LbmControlSet() );
- mCons[0]->initCparts();
- }
-
- // take from first set
- for(int cpii=1; cpii<(int)mCons.size(); cpii++) {
- mCons[cpii]->mCparts->setRadiusMinMaxd( mCons[0]->mCparts->getRadiusMinMaxd() );
- mCons[cpii]->mCparts->setRadiusMaxd( mCons[0]->mCparts->getRadiusMaxd() );
- mCons[cpii]->mCparts->setInfluenceAttraction( mCons[0]->mCparts->getInfluenceAttraction() );
- mCons[cpii]->mCparts->setInfluenceTangential( mCons[0]->mCparts->getInfluenceTangential() );
- mCons[cpii]->mCparts->setInfluenceVelocity( mCons[0]->mCparts->getInfluenceVelocity() , 0.01 ); // dummy dt
- mCons[cpii]->mCparts->setInfluenceMaxdist( mCons[0]->mCparts->getInfluenceMaxdist() );
- }
-
- // invert for usage in relax macro
- mDiffVelCon = 1.-attr->readFloat("cpdiffvelcon", mDiffVelCon, "LbmControlData","mDiffVelCon", false);
-
- mDebugCpscale = attr->readFloat("cpdebug_cpscale", mDebugCpscale, "LbmControlData","mDebugCpscale", false);
- mDebugMaxdScale = attr->readFloat("cpdebug_maxdscale", mDebugMaxdScale, "LbmControlData","mDebugMaxdScale", false);
- mDebugAttScale = attr->readFloat("cpdebug_attscale", mDebugAttScale, "LbmControlData","mDebugAttScale", false);
- mDebugVelScale = attr->readFloat("cpdebug_velscale", mDebugVelScale, "LbmControlData","mDebugVelScale", false);
- mDebugCompavScale = attr->readFloat("cpdebug_compavscale", mDebugCompavScale, "LbmControlData","mDebugCompavScale", false);
- mDebugAvgVelScale = attr->readFloat("cpdebug_avgvelsc", mDebugAvgVelScale, "LbmControlData","mDebugAvgVelScale", false);
-}
-
-
-void
-LbmFsgrSolver::initCpdata()
-{
- // enable for cps via env. vars
- //if( (getenv("ELBEEM_CPINFILE")) || (getenv("ELBEEM_CPOUTFILE")) ){ mUseTestdata=1; }
-
-
- // manually switch on! if this is zero, nothing is done...
- mpControl->mSetForceStrength = this->mTForceStrength = 1.;
- mpControl->mCons.clear();
-
- // init all control fluid objects
- int numobjs = (int)(mpGiObjects->size());
- for(int o=0; o<numobjs; o++) {
- ntlGeometryObjModel *obj = (ntlGeometryObjModel *)(*mpGiObjects)[o];
- if(obj->getGeoInitType() & FGI_CONTROL) {
- // add new control set per object
- LbmControlSet *cset;
-
- cset = new LbmControlSet();
- cset->initCparts();
-
- // dont load any file
- cset->mContrPartFile = string("");
-
- cset->mcForceAtt = obj->getCpsAttrFStr();
- cset->mcRadiusAtt = obj->getCpsAttrFRad();
- cset->mcForceVel = obj->getCpsVelFStr();
- cset->mcRadiusVel = obj->getCpsVelFRad();
-
- cset->mCparts->setCPSTimeStart(obj->getCpsTimeStart());
- cset->mCparts->setCPSTimeEnd(obj->getCpsTimeEnd());
-
- if(obj->getCpsQuality() > LBM_EPSILON)
- cset->mCparts->setCPSWith(1.0 / obj->getCpsQuality());
-
- // this value can be left at 0.5:
- cset->mCparts->setCPSMvmWeightFac(0.5);
-
- mpControl->mCons.push_back( cset );
- mpControl->mCons[mpControl->mCons.size()-1]->mCparts->initFromObject(obj);
- }
- }
-
- // NT blender integration manual test setup
- if(0) {
- // manually switch on! if this is zero, nothing is done...
- mpControl->mSetForceStrength = this->mTForceStrength = 1.;
- mpControl->mCons.clear();
-
- // add new set
- LbmControlSet *cset;
-
- cset = new LbmControlSet();
- cset->initCparts();
- // dont load any file
- cset->mContrPartFile = string("");
-
- // set radii for attraction & velocity forces
- // set strength of the forces
- // don't set directly! but use channels:
- // mcForceAtt, mcForceVel, mcForceMaxd, mcRadiusAtt, mcRadiusVel, mcRadiusMind, mcRadiusMaxd etc.
-
- // wrong: cset->mCparts->setInfluenceAttraction(1.15); cset->mCparts->setRadiusAtt(1.5);
- // right, e.g., to init some constant values:
- cset->mcForceAtt = AnimChannel<float>(0.2);
- cset->mcRadiusAtt = AnimChannel<float>(0.75);
- cset->mcForceVel = AnimChannel<float>(0.2);
- cset->mcRadiusVel = AnimChannel<float>(0.75);
-
- // this value can be left at 0.5:
- cset->mCparts->setCPSMvmWeightFac(0.5);
-
- mpControl->mCons.push_back( cset );
-
- // instead of reading from file (cset->mContrPartFile), manually init some particles
- mpControl->mCons[0]->mCparts->initBlenderTest();
-
- // other values that might be interesting to change:
- //cset->mCparts->setCPSTimestep(0.02);
- //cset->mCparts->setCPSTimeStart(0.);
- //cset->mCparts->setCPSTimeEnd(1.);
-
- //mpControl->mDiffVelCon = 1.; // more rigid velocity control, 0 (default) allows more turbulence
- }
-
- // control particle -------------------------------------------------------------------------------------
-
- // init cppf stage, use set 0!
- if(mCppfStage>0) {
- if(mpControl->mCpOutfile.length()<1) mpControl->mCpOutfile = string("cpout"); // use getOutFilename !?
- char strbuf[100];
- const char *cpFormat = "_d%dcppf%d";
-
- // initial coarse stage, no input
- if(mCppfStage==1) {
- mpControl->mCons[0]->mContrPartFile = "";
- } else {
- // read from prev stage
- snprintf(strbuf,100, cpFormat ,LBMDIM,mCppfStage-1);
- mpControl->mCons[0]->mContrPartFile = mpControl->mCpOutfile;
- mpControl->mCons[0]->mContrPartFile += strbuf;
- mpControl->mCons[0]->mContrPartFile += ".cpart2";
- }
-
- snprintf(strbuf,100, cpFormat ,LBMDIM,mCppfStage);
- mpControl->mCpOutfile += strbuf;
- } // */
-
- for(int cpssi=0; cpssi<(int)mpControl->mCons.size(); cpssi++) {
- ControlParticles *cparts = mpControl->mCons[cpssi]->mCparts;
- ControlParticles *cpmotion = mpControl->mCons[cpssi]->mCpmotion;
-
- // now set with real dt
- cparts->setInfluenceVelocity( mpControl->mCons[cpssi]->mcForceVel.get(0.), mLevel[mMaxRefine].timestep);
- cparts->setCharLength( mLevel[mMaxRefine].nodeSize );
- cparts->setCharLength( mLevel[mMaxRefine].nodeSize );
- errMsg("LbmControlData","CppfStage "<<mCppfStage<<" in:"<<mpControl->mCons[cpssi]->mContrPartFile<<
- " out:"<<mpControl->mCpOutfile<<" cl:"<< cparts->getCharLength() );
-
- // control particle test init
- if(mpControl->mCons[cpssi]->mCpmotionFile.length()>=1) cpmotion->initFromTextFile(mpControl->mCons[cpssi]->mCpmotionFile);
- // not really necessary...
- //? cparts->setFluidSpacing( mLevel[mMaxRefine].nodeSize ); // use grid coords!?
- //? cparts->calculateKernelWeight();
- //? debMsgStd("LbmFsgrSolver::initCpdata",DM_MSG,"ControlParticles - motion inited: "<<cparts->getSize() ,10);
-
- // ensure both are on for env. var settings
- // when no particles, but outfile enabled, initialize
- const int lev = mMaxRefine;
- if((mpParticles) && (mpControl->mCpOutfile.length()>=1) && (cpssi==0)) {
- // check if auto num
- if( (mpParticles->getNumInitialParticles()<=1) &&
- (mpParticles->getNumParticles()<=1) ) { // initParticles done afterwards anyway
- int tracers = 0;
- const int workSet = mLevel[lev].setCurr;
- FSGR_FORIJK_BOUNDS(lev) {
- if(RFLAG(lev,i,j,k, workSet)&(CFFluid)) tracers++;
- }
- if(LBMDIM==3) tracers /= 8;
- else tracers /= 4;
- mpParticles->setNumInitialParticles(tracers);
- mpParticles->setDumpTextFile(mpControl->mCpOutfile);
- debMsgStd("LbmFsgrSolver::initCpdata",DM_MSG,"ControlParticles - set tracers #"<<tracers<<", actual #"<<mpParticles->getNumParticles() ,10);
- }
- if(mpParticles->getDumpTextInterval()<=0.) {
- mpParticles->setDumpTextInterval(mLevel[lev].timestep * mLevel[lev].lSizex);
- debMsgStd("LbmFsgrSolver::initCpdata",DM_MSG,"ControlParticles - dump delta t not set, using dti="<< mpParticles->getDumpTextInterval()<<", sim dt="<<mLevel[lev].timestep, 5 );
- }
- mpParticles->setDumpParts(true); // DEBUG? also dump as particle system
- }
-
- if(mpControl->mCons[cpssi]->mContrPartFile.length()>=1) cparts->initFromTextFile(mpControl->mCons[cpssi]->mContrPartFile);
- cparts->setFluidSpacing( mLevel[lev].nodeSize ); // use grid coords!?
- cparts->calculateKernelWeight();
- debMsgStd("LbmFsgrSolver::initCpdata",DM_MSG,"ControlParticles mCons"<<cpssi<<" - inited, parts:"<<cparts->getTotalSize()<<","<<cparts->getSize()<<" dt:"<<mpParam->getTimestep()<<" control time:"<<cparts->getControlTimStart()<<" to "<<cparts->getControlTimEnd() ,10);
- } // cpssi
-
- if(getenv("ELBEEM_CPINFILE")) {
- this->mTForceStrength = 1.0;
- }
- this->mTForceStrength = mpControl->mSetForceStrength;
- if(mpControl->mCpOutfile.length()>=1) mpParticles->setDumpTextFile(mpControl->mCpOutfile);
-
- // control particle init end -------------------------------------------------------------------------------------
-
- // make sure equiv to solver init
- if(this->mTForceStrength>0.) { \
- mpControl->mCpForces.resize( mMaxRefine+1 );
- for(int lev = 0; lev<=mMaxRefine; lev++) {
- LONGINT rcellSize = (mLevel[lev].lSizex*mLevel[lev].lSizey*mLevel[lev].lSizez);
- debMsgStd("LbmFsgrSolver::initControl",DM_MSG,"mCpForces init, lev="<<lev<<" rcs:"<<(int)(rcellSize+4)<<","<<(rcellSize*sizeof(ControlForces)/(1024*1024)), 9 );
- mpControl->mCpForces[lev].resize( (int)(rcellSize+4) );
- //for(int i=0 ;i<rcellSize; i++) mpControl->mCpForces.push_back( ControlForces() );
- for(int i=0 ;i<rcellSize; i++) mpControl->mCpForces[lev][i].resetForces();
- }
- } // on?
-
- debMsgStd("LbmFsgrSolver::initCpdata",DM_MSG,"ControlParticles #mCons "<<mpControl->mCons.size()<<" done", 6);
-}
-
-
-#define CPODEBUG 0
-//define CPINTER ((int)(mpControl->mCpUpdateInterval))
-
-#define KERN(x,y,z) mpControl->mCpKernel[ (((z)*cpkarWidth + (y))*cpkarWidth + (x)) ]
-#define MDKERN(x,y,z) mpControl->mMdKernel[ (((z)*mdkarWidth + (y))*mdkarWidth + (x)) ]
-
-#define BOUNDCHECK(x,low,high) ( ((x)<low) ? low : (((x)>high) ? high : (x) ) )
-#define BOUNDSKIP(x,low,high) ( ((x)<low) || ((x)>high) )
-
-void
-LbmFsgrSolver::handleCpdata()
-{
- myTime_t cpstart = getTime();
- int cpChecks=0;
- int cpInfs=0;
- //debMsgStd("ControlData::handleCpdata",DM_MSG,"called... "<<this->mTForceStrength,1);
-
- // add cp influence
- if((true) && (this->mTForceStrength>0.)) {
- // ok continue...
- } // on off
- else {
- return;
- }
-
- // check if we have control objects
- if(mpControl->mCons.size()==0)
- return;
-
- if((mpControl->mCpUpdateInterval<1) || (this->mStepCnt%mpControl->mCpUpdateInterval==0)) {
- // do full reinit later on...
- }
- else if(this->mStepCnt>mpControl->mCpUpdateInterval) {
- // only reinit new cells
- // TODO !? remove loop dependance!?
-#define NOFORCEENTRY(lev, i,j,k) (LBMGET_FORCE(lev, i,j,k).maxDistance==CPF_MAXDINIT)
- // interpolate missing
- for(int lev=0; lev<=mMaxRefine; lev++) {
- FSGR_FORIJK_BOUNDS(lev) {
- if( (RFLAG(lev,i,j,k, mLevel[lev].setCurr)) & (CFFluid|CFInter) )
- //if( (RFLAG(lev,i,j,k, mLevel[lev].setCurr)) & (CFInter) )
- //if(0)
- { // only check new inter? RFLAG?check
- if(NOFORCEENTRY(lev, i,j,k)) {
- //errMsg("CP","FE_MISSING at "<<PRINT_IJK<<" f"<<LBMGET_FORCE(lev, i,j,k).weightAtt<<" md"<<LBMGET_FORCE(lev, i,j,k).maxDistance );
-
- LbmFloat nbs=0.;
- ControlForces vals;
- vals.resetForces(); vals.maxDistance = 0.;
- for(int l=1; l<this->cDirNum; l++) {
- int ni=i+this->dfVecX[l], nj=j+this->dfVecY[l], nk=k+this->dfVecZ[l];
- //errMsg("CP","FE_MISSING check "<<PRINT_VEC(ni,nj,nk)<<" f"<<LBMGET_FORCE(lev, ni,nj,nk).weightAtt<<" md"<<LBMGET_FORCE(lev, ni,nj,nk).maxDistance );
- if(!NOFORCEENTRY(lev, ni,nj,nk)) {
- //? vals.weightAtt += LBMGET_FORCE(lev, ni,nj,nk).weightAtt;
- //? vals.forceAtt += LBMGET_FORCE(lev, ni,nj,nk).forceAtt;
- vals.maxDistance += LBMGET_FORCE(lev, ni,nj,nk).maxDistance;
- vals.forceMaxd += LBMGET_FORCE(lev, ni,nj,nk).forceMaxd;
- vals.weightVel += LBMGET_FORCE(lev, ni,nj,nk).weightVel;
- vals.forceVel += LBMGET_FORCE(lev, ni,nj,nk).forceVel;
- // ignore att/compAv/avgVel here for now
- nbs += 1.;
- }
- }
- if(nbs>0.) {
- nbs = 1./nbs;
- //? LBMGET_FORCE(lev, i,j,k).weightAtt = vals.weightAtt*nbs;
- //? LBMGET_FORCE(lev, i,j,k).forceAtt = vals.forceAtt*nbs;
- LBMGET_FORCE(lev, i,j,k).maxDistance = vals.maxDistance*nbs;
- LBMGET_FORCE(lev, i,j,k).forceMaxd = vals.forceMaxd*nbs;
- LBMGET_FORCE(lev, i,j,k).weightVel = vals.weightVel*nbs;
- LBMGET_FORCE(lev, i,j,k).forceVel = vals.forceVel*nbs;
- }
- /*ControlForces *ff = &LBMGET_FORCE(lev, i,j,k); // DEBUG
- errMsg("CP","FE_MISSING rec at "<<PRINT_IJK // DEBUG
- <<" w:"<<ff->weightAtt<<" wa:" <<PRINT_VEC( ff->forceAtt[0],ff->forceAtt[1],ff->forceAtt[2] )
- <<" v:"<<ff->weightVel<<" wv:" <<PRINT_VEC( ff->forceVel[0],ff->forceVel[1],ff->forceVel[2] )
- <<" v:"<<ff->maxDistance<<" wv:" <<PRINT_VEC( ff->forceMaxd[0],ff->forceMaxd[1],ff->forceMaxd[2] ) ); // DEBUG */
- // else errMsg("CP","FE_MISSING rec at "<<PRINT_IJK<<" failed!"); // DEBUG
-
- }
- }
- }} // ijk, lev
-
- // mStepCnt > mpControl->mCpUpdateInterval
- return;
- } else {
- // nothing to do ...
- return;
- }
-
- // reset
- for(int lev=0; lev<=mMaxRefine; lev++) {
- FSGR_FORIJK_BOUNDS(lev) { LBMGET_FORCE(lev,i,j,k).resetForces(); }
- }
- // do setup for coarsest level
- const int coarseLev = 0;
- const int fineLev = mMaxRefine;
-
- // init for current time
- for(int cpssi=0; cpssi<(int)mpControl->mCons.size(); cpssi++) {
- ControlParticles *cparts = mpControl->mCons[cpssi]->mCparts;
- LbmControlSet *cset = mpControl->mCons[cpssi];
-
- cparts->setRadiusAtt(cset->mcRadiusAtt.get(mSimulationTime));
- cparts->setRadiusVel(cset->mcRadiusVel.get(mSimulationTime));
- cparts->setInfluenceAttraction(cset->mcForceAtt.get(mSimulationTime) );
- cparts->setInfluenceMaxdist(cset->mcForceMaxd.get(mSimulationTime) );
- cparts->setRadiusMinMaxd(cset->mcRadiusMind.get(mSimulationTime));
- cparts->setRadiusMaxd(cset->mcRadiusMaxd.get(mSimulationTime));
- cparts->calculateKernelWeight(); // always necessary!?
- cparts->setOffset( vec2L(cset->mcCpOffset.get(mSimulationTime)) );
- cparts->setScale( vec2L(cset->mcCpScale.get(mSimulationTime)) );
-
- cparts->setInfluenceVelocity( cset->mcForceVel.get(mSimulationTime), mLevel[fineLev].timestep );
- cparts->setLastOffset( vec2L(cset->mcCpOffset.get(mSimulationTime-mLevel[fineLev].timestep)) );
- cparts->setLastScale( vec2L(cset->mcCpScale.get(mSimulationTime-mLevel[fineLev].timestep)) );
-
- }
-
- // check actual values
- LbmFloat iatt = ABS(mpControl->mCons[0]->mCparts->getInfluenceAttraction());
- LbmFloat ivel = mpControl->mCons[0]->mCparts->getInfluenceVelocity();
- LbmFloat imaxd = mpControl->mCons[0]->mCparts->getInfluenceMaxdist();
- //errMsg("FINCIT","iatt="<<iatt<<" ivel="<<ivel<<" imaxd="<<imaxd);
- for(int cpssi=1; cpssi<(int)mpControl->mCons.size(); cpssi++) {
- LbmFloat iatt2 = ABS(mpControl->mCons[cpssi]->mCparts->getInfluenceAttraction());
- LbmFloat ivel2 = mpControl->mCons[cpssi]->mCparts->getInfluenceVelocity();
- LbmFloat imaxd2 = mpControl->mCons[cpssi]->mCparts->getInfluenceMaxdist();
-
- // we allow negative attraction force here!
- if(iatt2 > iatt) iatt = iatt2;
-
- if(ivel2 >ivel) ivel = ivel2;
- if(imaxd2>imaxd) imaxd= imaxd2;
- //errMsg("FINCIT"," "<<cpssi<<" iatt2="<<iatt2<<" ivel2="<<ivel2<<" imaxd2="<<imaxd<<" NEW "<<" iatt="<<iatt<<" ivel="<<ivel<<" imaxd="<<imaxd);
- }
-
- if(iatt==0. && ivel==0. && imaxd==0.) {
- debMsgStd("ControlData::initControl",DM_MSG,"Skipped, all zero...",4);
- return;
- }
- //iatt = mpControl->mCons[1]->mCparts->getInfluenceAttraction(); //ivel = mpControl->mCons[1]->mCparts->getInfluenceVelocity(); //imaxd = mpControl->mCons[1]->mCparts->getInfluenceMaxdist(); // TTTTTT
-
- // do control setup
- for(int cpssi=0; cpssi<(int)mpControl->mCons.size(); cpssi++) {
- ControlParticles *cparts = mpControl->mCons[cpssi]->mCparts;
- ControlParticles *cpmotion = mpControl->mCons[cpssi]->mCpmotion;
-
- // TEST!?
- bool radmod = false;
- const LbmFloat minRadSize = mLevel[coarseLev].nodeSize * 1.5;
- if((cparts->getRadiusAtt()>0.) && (cparts->getRadiusAtt()<minRadSize) && (!radmod) ) {
- LbmFloat radfac = minRadSize / cparts->getRadiusAtt(); radmod=true;
- debMsgStd("ControlData::initControl",DM_MSG,"Modified radii att, fac="<<radfac, 7);
- cparts->setRadiusAtt(cparts->getRadiusAtt()*radfac);
- cparts->setRadiusVel(cparts->getRadiusVel()*radfac);
- cparts->setRadiusMaxd(cparts->getRadiusMaxd()*radfac);
- cparts->setRadiusMinMaxd(cparts->getRadiusMinMaxd()*radfac);
- } else if((cparts->getRadiusVel()>0.) && (cparts->getRadiusVel()<minRadSize) && (!radmod) ) {
- LbmFloat radfac = minRadSize / cparts->getRadiusVel();
- debMsgStd("ControlData::initControl",DM_MSG,"Modified radii vel, fac="<<radfac, 7);
- cparts->setRadiusVel(cparts->getRadiusVel()*radfac);
- cparts->setRadiusMaxd(cparts->getRadiusMaxd()*radfac);
- cparts->setRadiusMinMaxd(cparts->getRadiusMinMaxd()*radfac);
- } else if((cparts->getRadiusMaxd()>0.) && (cparts->getRadiusMaxd()<minRadSize) && (!radmod) ) {
- LbmFloat radfac = minRadSize / cparts->getRadiusMaxd();
- debMsgStd("ControlData::initControl",DM_MSG,"Modified radii maxd, fac="<<radfac, 7);
- cparts->setRadiusMaxd(cparts->getRadiusMaxd()*radfac);
- cparts->setRadiusMinMaxd(cparts->getRadiusMinMaxd()*radfac);
- }
- if(radmod) {
- debMsgStd("ControlData::initControl",DM_MSG,"Modified radii: att="<<
- cparts->getRadiusAtt()<<", vel=" << cparts->getRadiusVel()<<", maxd=" <<
- cparts->getRadiusMaxd()<<", mind=" << cparts->getRadiusMinMaxd() ,5);
- }
-
- cpmotion->prepareControl( mSimulationTime+((LbmFloat)mpControl->mCpUpdateInterval)*(mpParam->getTimestep()), mpParam->getTimestep(), NULL );
- cparts->prepareControl( mSimulationTime+((LbmFloat)mpControl->mCpUpdateInterval)*(mpParam->getTimestep()), mpParam->getTimestep(), cpmotion );
- }
-
- // do control...
- for(int lev=0; lev<=mMaxRefine; lev++) {
- LbmFloat levVolume = 1.;
- LbmFloat levForceScale = 1.;
- for(int ll=lev; ll<mMaxRefine; ll++) {
- if(LBMDIM==3) levVolume *= 8.;
- else levVolume *= 4.;
- levForceScale *= 2.;
- }
- errMsg("LbmFsgrSolver::handleCpdata","levVolume="<<levVolume<<" levForceScale="<<levForceScale );
- //todo: scale velocity, att by level timestep!?
-
- for(int cpssi=0; cpssi<(int)mpControl->mCons.size(); cpssi++) {
- ControlParticles *cparts = mpControl->mCons[cpssi]->mCparts;
- // ControlParticles *cpmotion = mpControl->mCons[cpssi]->mCpmotion;
-
- // if control set is not active skip it
- if((cparts->getControlTimStart() > mSimulationTime) || (cparts->getControlTimEnd() < mLastSimTime))
- {
- continue;
- }
-
- const LbmFloat velLatticeScale = mLevel[lev].timestep/mLevel[lev].nodeSize;
- LbmFloat gsx = ((mvGeoEnd[0]-mvGeoStart[0])/(LbmFloat)mLevel[lev].lSizex);
- LbmFloat gsy = ((mvGeoEnd[1]-mvGeoStart[1])/(LbmFloat)mLevel[lev].lSizey);
- LbmFloat gsz = ((mvGeoEnd[2]-mvGeoStart[2])/(LbmFloat)mLevel[lev].lSizez);
-#if LBMDIM==2
- gsz = gsx;
-#endif
- LbmFloat goffx = mvGeoStart[0];
- LbmFloat goffy = mvGeoStart[1];
- LbmFloat goffz = mvGeoStart[2];
-
- //const LbmFloat cpwIncFac = 2.0;
- // max to two thirds of domain size
- const int cpw = MIN( mLevel[lev].lSizex/3, MAX( (int)( cparts->getRadiusAtt() /gsx) +1 , 2) ); // normal kernel, att,vel
- const int cpkarWidth = 2*cpw+1;
- mpControl->mCpKernel.resize(cpkarWidth* cpkarWidth* cpkarWidth);
- ControlParticle cpt; cpt.reset();
- cpt.pos = LbmVec( (gsx*(LbmFloat)cpw)+goffx, (gsy*(LbmFloat)cpw)+goffy, (gsz*(LbmFloat)cpw)+goffz ); // optimize?
- cpt.density = 0.5; cpt.densityWeight = 0.5;
-#if LBMDIM==3
- for(int k= 0; k<cpkarWidth; ++k) {
-#else // LBMDIM==3
- { int k = cpw;
-#endif
- for(int j= 0; j<cpkarWidth; ++j)
- for(int i= 0; i<cpkarWidth; ++i) {
- KERN(i,j,k).resetForces();
- //LbmFloat dx = i-cpw; LbmFloat dy = j-cpw; LbmFloat dz = k-cpw;
- //LbmVec dv = ( LbmVec(dx,dy,dz) );
- //LbmFloat dl = norm( dv ); //LbmVec dir = dv / dl;
- LbmVec pos = LbmVec( (gsx*(LbmFloat)i)+goffx, (gsy*(LbmFloat)j)+goffy, (gsz*(LbmFloat)k)+goffz ); // optimize?
- cparts->calculateCpInfluenceOpt( &cpt, pos, LbmVec(0,0,0), &KERN(i,j,k) ,1. );
- /*if((CPODEBUG)&&(k==cpw)) errMsg("kern"," at "<<PRINT_IJK<<" pos"<<pos<<" cpp"<<cpt.pos
- <<" wf:"<<KERN(i,j,k).weightAtt<<" wa:"<< PRINT_VEC( KERN(i,j,k).forceAtt[0],KERN(i,j,k).forceAtt[1],KERN(i,j,k).forceAtt[2] )
- <<" wf:"<<KERN(i,j,k).weightVel<<" wa:"<< PRINT_VEC( KERN(i,j,k).forceVel[0],KERN(i,j,k).forceVel[1],KERN(i,j,k).forceVel[2] )
- <<" wf:"<<KERN(i,j,k).maxDistance<<" wa:"<< PRINT_VEC( KERN(i,j,k).forceMaxd[0],KERN(i,j,k).forceMaxd[1],KERN(i,j,k).forceMaxd[2] ) ); // */
- KERN(i,j,k).weightAtt *= 2.;
- KERN(i,j,k).forceAtt *= 2.;
- //KERN(i,j,k).forceAtt[1] *= 2.; KERN(i,j,k).forceAtt[2] *= 2.;
- KERN(i,j,k).weightVel *= 2.;
- KERN(i,j,k).forceVel *= 2.;
- //KERN(i,j,k).forceVel[1] *= 2.; KERN(i,j,k).forceVel[2] *= 2.;
- }
- }
-
- if(CPODEBUG) errMsg("cpw"," = "<<cpw<<" f"<< cparts->getRadiusAtt()<<" gsx"<<gsx<<" kpw"<<cpkarWidth); // DEBUG
- // first cp loop - add att and vel forces
- for(int cppi=0; cppi<cparts->getSize(); cppi++) {
- ControlParticle *cp = cparts->getParticle(cppi);
- if(cp->influence<=0.) continue;
- const int cpi = (int)( (cp->pos[0]-goffx)/gsx );
- const int cpj = (int)( (cp->pos[1]-goffy)/gsy );
- int cpk = (int)( (cp->pos[2]-goffz)/gsz );
- /*if( ((LBMDIM==3)&&(BOUNDSKIP(cpk - cpwsm, getForZMinBnd(), getForZMaxBnd(lev) ))) ||
- ((LBMDIM==3)&&(BOUNDSKIP(cpk + cpwsm, getForZMinBnd(), getForZMaxBnd(lev) ))) ||
- BOUNDSKIP(cpj - cpwsm, 0, mLevel[lev].lSizey ) ||
- BOUNDSKIP(cpj + cpwsm, 0, mLevel[lev].lSizey ) ||
- BOUNDSKIP(cpi - cpwsm, 0, mLevel[lev].lSizex ) ||
- BOUNDSKIP(cpi + cpwsm, 0, mLevel[lev].lSizex ) ) {
- continue;
- } // */
- int is,ie,js,je,ks,ke;
- ks = BOUNDCHECK(cpk - cpw, getForZMinBnd(), getForZMaxBnd(lev) );
- ke = BOUNDCHECK(cpk + cpw, getForZMinBnd(), getForZMaxBnd(lev) );
- js = BOUNDCHECK(cpj - cpw, 0, mLevel[lev].lSizey );
- je = BOUNDCHECK(cpj + cpw, 0, mLevel[lev].lSizey );
- is = BOUNDCHECK(cpi - cpw, 0, mLevel[lev].lSizex );
- ie = BOUNDCHECK(cpi + cpw, 0, mLevel[lev].lSizex );
- if(LBMDIM==2) { cpk = 0; ks = 0; ke = 1; }
- if(CPODEBUG) errMsg("cppft","i"<<cppi<<" cpw"<<cpw<<" gpos"<<PRINT_VEC(cpi,cpj,cpk)<<" i:"<<is<<","<<ie<<" j:"<<js<<","<<je<<" k:"<<ks<<","<<ke<<" "); // DEBUG
- cpInfs++;
-
- for(int k= ks; k<ke; ++k) {
- for(int j= js; j<je; ++j) {
-
- CellFlagType *pflag = &RFLAG(lev,is,j,k, mLevel[lev].setCurr);
- ControlForces *kk = &KERN( is-cpi+cpw, j-cpj+cpw, k-cpk+cpw);
- ControlForces *ff = &LBMGET_FORCE(lev,is,j,k);
- pflag--; kk--; ff--;
-
- for(int i= is; i<ie; ++i) {
- // first cp loop (att,vel)
- pflag++; kk++; ff++;
-
- //add weight for bnd cells
- const LbmFloat pwforce = kk->weightAtt;
- // control particle mod,
- // dont add multiple CFFluid fsgr boundaries
- if(lev==mMaxRefine) {
- //if( ( ((*pflag)&(CFFluid )) && (lev==mMaxRefine) ) ||
- //( ((*pflag)&(CFGrNorm)) && (lev <mMaxRefine) ) ) {
- if((*pflag)&(CFFluid|CFUnused)) {
- // check not fromcoarse?
- cp->density += levVolume* kk->weightAtt; // old CFFluid
- } else if( (*pflag) & (CFEmpty) ) {
- cp->density -= levVolume* 0.5;
- } else { //if( ((*pflag) & (CFBnd)) ) {
- cp->density -= levVolume* 0.2; // penalty
- }
- } else {
- //if((*pflag)&(CFGrNorm)) {
- //cp->density += levVolume* kk->weightAtt; // old CFFluid
- //}
- }
- //else if(!((*pflag) & (CFUnused)) ) { cp->density -= levVolume* 0.2; } // penalty
-
- if( (*pflag) & (CFFluid|CFInter) ) // RFLAG_check
- {
-
- cpChecks++;
- //const LbmFloat pwforce = kk->weightAtt;
- LbmFloat pwvel = kk->weightVel;
- if((pwforce==0.)&&(pwvel==0.)) { continue; }
- ff->weightAtt += 1e-6; // for distance
-
- if(pwforce>0.) {
- ff->weightAtt += pwforce *cp->densityWeight *cp->influence;
- ff->forceAtt += kk->forceAtt *levForceScale *cp->densityWeight *cp->influence;
-
- // old fill handling here
- const int workSet =mLevel[lev].setCurr;
- LbmFloat ux=0., uy=0., uz=0.;
- FORDF1{
- const LbmFloat dfn = QCELL(lev, i,j,k, workSet, l);
- ux += (this->dfDvecX[l]*dfn);
- uy += (this->dfDvecY[l]*dfn);
- uz += (this->dfDvecZ[l]*dfn);
- }
- // control particle mod
- cp->avgVelWeight += levVolume*pwforce;
- cp->avgVelAcc += LbmVec(ux,uy,uz) * levVolume*pwforce;
- }
-
- if(pwvel>0.) {
- // TODO make switch? vel.influence depends on density weight...
- // (reduced lowering with 0.75 factor)
- pwvel *= cp->influence *(1.-0.75*cp->densityWeight);
- // control particle mod
- // todo use Omega instead!?
- ff->forceVel += cp->vel*levVolume*pwvel * velLatticeScale; // levVolume?
- ff->weightVel += levVolume*pwvel; // levVolume?
- ff->compAv += cp->avgVel*levVolume*pwvel; // levVolume?
- ff->compAvWeight += levVolume*pwvel; // levVolume?
- }
-
- if(CPODEBUG) errMsg("cppft","i"<<cppi<<" at "<<PRINT_IJK<<" kern:"<<
- PRINT_VEC(i-cpi+cpw, j-cpj+cpw, k-cpk+cpw )
- //<<" w:"<<ff->weightAtt<<" wa:"
- //<<PRINT_VEC( ff->forceAtt[0],ff->forceAtt[1],ff->forceAtt[2] )
- //<<" v:"<<ff->weightVel<<" wv:"
- //<<PRINT_VEC( ff->forceVel[0],ff->forceVel[1],ff->forceVel[2] )
- //<<" v:"<<ff->maxDistance<<" wv:"
- //<<PRINT_VEC( ff->forceMaxd[0],ff->forceMaxd[1],ff->forceMaxd[2] )
- );
- } // celltype
-
- } // ijk
- } // ijk
- } // ijk
- } // cpi, end first cp loop (att,vel)
- debMsgStd("LbmFsgrSolver::handleCpdata",DM_MSG,"Force cpgrid "<<cpssi<<" generated checks:"<<cpChecks<<" infs:"<<cpInfs ,9);
- } //cpssi
- } // lev
-
- // second loop
- for(int lev=0; lev<=mMaxRefine; lev++) {
- LbmFloat levVolume = 1.;
- LbmFloat levForceScale = 1.;
- for(int ll=lev; ll<mMaxRefine; ll++) {
- if(LBMDIM==3) levVolume *= 8.;
- else levVolume *= 4.;
- levForceScale *= 2.;
- }
- // prepare maxd forces
- for(int cpssi=0; cpssi<(int)mpControl->mCons.size(); cpssi++) {
- ControlParticles *cparts = mpControl->mCons[cpssi]->mCparts;
-
- // WARNING copied from above!
- const LbmFloat velLatticeScale = mLevel[lev].timestep/mLevel[lev].nodeSize;
- LbmFloat gsx = ((mvGeoEnd[0]-mvGeoStart[0])/(LbmFloat)mLevel[lev].lSizex);
- LbmFloat gsy = ((mvGeoEnd[1]-mvGeoStart[1])/(LbmFloat)mLevel[lev].lSizey);
- LbmFloat gsz = ((mvGeoEnd[2]-mvGeoStart[2])/(LbmFloat)mLevel[lev].lSizez);
-#if LBMDIM==2
- gsz = gsx;
-#endif
- LbmFloat goffx = mvGeoStart[0];
- LbmFloat goffy = mvGeoStart[1];
- LbmFloat goffz = mvGeoStart[2];
-
- //const LbmFloat cpwIncFac = 2.0;
- const int mdw = MIN( mLevel[lev].lSizex/2, MAX( (int)( cparts->getRadiusMaxd() /gsx) +1 , 2) ); // wide kernel, md
- const int mdkarWidth = 2*mdw+1;
- mpControl->mMdKernel.resize(mdkarWidth* mdkarWidth* mdkarWidth);
- ControlParticle cpt; cpt.reset();
- cpt.density = 0.5; cpt.densityWeight = 0.5;
- cpt.pos = LbmVec( (gsx*(LbmFloat)mdw)+goffx, (gsy*(LbmFloat)mdw)+goffy, (gsz*(LbmFloat)mdw)+goffz ); // optimize?
-#if LBMDIM==3
- for(int k= 0; k<mdkarWidth; ++k) {
-#else // LBMDIM==3
- { int k = mdw;
-#endif
- for(int j= 0; j<mdkarWidth; ++j)
- for(int i= 0; i<mdkarWidth; ++i) {
- MDKERN(i,j,k).resetForces();
- LbmVec pos = LbmVec( (gsx*(LbmFloat)i)+goffx, (gsy*(LbmFloat)j)+goffy, (gsz*(LbmFloat)k)+goffz ); // optimize?
- cparts->calculateMaxdForce( &cpt, pos, &MDKERN(i,j,k) );
- }
- }
-
- // second cpi loop, maxd forces
- if(cparts->getInfluenceMaxdist()>0.) {
- for(int cppi=0; cppi<cparts->getSize(); cppi++) {
- ControlParticle *cp = cparts->getParticle(cppi);
- if(cp->influence<=0.) continue;
- const int cpi = (int)( (cp->pos[0]-goffx)/gsx );
- const int cpj = (int)( (cp->pos[1]-goffy)/gsy );
- int cpk = (int)( (cp->pos[2]-goffz)/gsz );
-
- int is,ie,js,je,ks,ke;
- ks = BOUNDCHECK(cpk - mdw, getForZMinBnd(), getForZMaxBnd(lev) );
- ke = BOUNDCHECK(cpk + mdw, getForZMinBnd(), getForZMaxBnd(lev) );
- js = BOUNDCHECK(cpj - mdw, 0, mLevel[lev].lSizey );
- je = BOUNDCHECK(cpj + mdw, 0, mLevel[lev].lSizey );
- is = BOUNDCHECK(cpi - mdw, 0, mLevel[lev].lSizex );
- ie = BOUNDCHECK(cpi + mdw, 0, mLevel[lev].lSizex );
- if(LBMDIM==2) { cpk = 0; ks = 0; ke = 1; }
- if(CPODEBUG) errMsg("cppft","i"<<cppi<<" mdw"<<mdw<<" gpos"<<PRINT_VEC(cpi,cpj,cpk)<<" i:"<<is<<","<<ie<<" j:"<<js<<","<<je<<" k:"<<ks<<","<<ke<<" "); // DEBUG
- cpInfs++;
-
- for(int k= ks; k<ke; ++k)
- for(int j= js; j<je; ++j) {
- CellFlagType *pflag = &RFLAG(lev,is-1,j,k, mLevel[lev].setCurr);
- for(int i= is; i<ie; ++i) {
- // second cpi loop, maxd forces
- pflag++;
- if( (*pflag) & (CFFluid|CFInter) ) // RFLAG_check
- {
- cpChecks++;
- ControlForces *ff = &LBMGET_FORCE(lev,i,j,k);
- if(ff->weightAtt == 0.) {
- ControlForces *kk = &MDKERN( i-cpi+mdw, j-cpj+mdw, k-cpk+mdw);
- const LbmFloat pmdf = kk->maxDistance;
- if((ff->maxDistance > pmdf) || (ff->maxDistance<0.))
- ff->maxDistance = pmdf;
- ff->forceMaxd = kk->forceMaxd;
- // todo use Omega instead!?
- ff->forceVel = cp->vel* velLatticeScale;
- }
- } // celltype
- } } // ijk
- } // cpi, md loop
- } // maxd inf>0 */
-
-
- debMsgStd("ControlData::initControl",DM_MSG,"Maxd cpgrid "<<cpssi<<" generated checks:"<<cpChecks<<" infs:"<<cpInfs ,9);
- } //cpssi
-
- // normalize, only done once for the whole array
- mpControl->mCons[0]->mCparts->finishControl( mpControl->mCpForces[lev], iatt,ivel,imaxd );
-
- } // lev loop
-
- myTime_t cpend = getTime();
- debMsgStd("ControlData::handleCpdata",DM_MSG,"Time for cpgrid generation:"<< getTimeString(cpend-cpstart)<<", checks:"<<cpChecks<<" infs:"<<cpInfs<<" " ,8);
-
- // warning, may return before
-}
-
-#if LBM_USE_GUI==1
-
-#define USE_GLUTILITIES
-#include "../gui/gui_utilities.h"
-
-void LbmFsgrSolver::cpDebugDisplay(int dispset)
-{
- for(int cpssi=0; cpssi<(int)mpControl->mCons.size(); cpssi++) {
- ControlParticles *cparts = mpControl->mCons[cpssi]->mCparts;
- //ControlParticles *cpmotion = mpControl->mCons[cpssi]->mCpmotion;
- // display cp parts
- const bool cpCubes = false;
- const bool cpDots = true;
- const bool cpCpdist = true;
- const bool cpHideIna = true;
- glShadeModel(GL_FLAT);
- glDisable( GL_LIGHTING ); // dont light lines
-
- // dot influence
- if((mpControl->mDebugCpscale>0.) && cpDots) {
- glPointSize(mpControl->mDebugCpscale * 8.);
- glBegin(GL_POINTS);
- for(int i=0; i<cparts->getSize(); i++) {
- if((cpHideIna)&&( (cparts->getParticle(i)->influence<=0.) || (cparts->getParticle(i)->size<=0.) )) continue;
- ntlVec3Gfx org( vec2G(cparts->getParticle(i)->pos ) );
- //LbmFloat halfsize = 0.5;
- LbmFloat scale = cparts->getParticle(i)->densityWeight;
- //glColor4f( scale,scale,scale,scale );
- glColor4f( 0.,scale,0.,scale );
- glVertex3f( org[0],org[1],org[2] );
- //errMsg("lbmDebugDisplay","CP "<<i<<" at "<<org); // DEBUG
- }
- glEnd();
- }
-
- // cp positions
- if((mpControl->mDebugCpscale>0.) && cpDots) {
- glPointSize(mpControl->mDebugCpscale * 3.);
- glBegin(GL_POINTS);
- glColor3f( 0,1,0 );
- }
- for(int i=0; i<cparts->getSize(); i++) {
- if((cpHideIna)&&( (cparts->getParticle(i)->influence<=0.) || (cparts->getParticle(i)->size<=0.) )) continue;
- ntlVec3Gfx org( vec2G(cparts->getParticle(i)->pos ) );
- LbmFloat halfsize = 0.5;
- LbmFloat scale = cparts->getRadiusAtt() * cparts->getParticle(i)->densityWeight;
- if(cpCubes){ glLineWidth( 1 );
- glColor3f( 1,1,1 );
- ntlVec3Gfx s = org-(halfsize * (scale));
- ntlVec3Gfx e = org+(halfsize * (scale));
- drawCubeWire( s,e ); }
- if((mpControl->mDebugCpscale>0.) && cpDots) {
- glVertex3f( org[0],org[1],org[2] );
- }
- }
- if(cpDots) glEnd();
-
- if(mpControl->mDebugAvgVelScale>0.) {
- const float scale = mpControl->mDebugAvgVelScale;
-
- glColor3f( 1.0,1.0,1 );
- glBegin(GL_LINES);
- for(int i=0; i<cparts->getSize(); i++) {
- if((cpHideIna)&&( (cparts->getParticle(i)->influence<=0.) || (cparts->getParticle(i)->size<=0.) )) continue;
- ntlVec3Gfx org( vec2G(cparts->getParticle(i)->pos ) );
-
- //errMsg("CPAVGVEL","i"<<i<<" pos"<<org<<" av"<<cparts->getParticle(i)->avgVel);// DEBUG
- float dx = cparts->getParticle(i)->avgVel[0];
- float dy = cparts->getParticle(i)->avgVel[1];
- float dz = cparts->getParticle(i)->avgVel[2];
- dx *= scale; dy *= scale; dz *= scale;
- glVertex3f( org[0],org[1],org[2] );
- glVertex3f( org[0]+dx,org[1]+dy,org[2]+dz );
- }
- glEnd();
- } // */
-
- if( (LBMDIM==2) && (cpCpdist) ) {
-
- // debug, for use of e.g. LBMGET_FORCE LbmControlData *mpControl = this;
-# define TESTGET_FORCE(lev,i,j,k) mpControl->mCpForces[lev][ ((k*mLevel[lev].lSizey)+j)*mLevel[lev].lSizex+i ]
-
- glBegin(GL_LINES);
- //const int lev=0;
- for(int lev=0; lev<=mMaxRefine; lev++) {
- FSGR_FORIJK_BOUNDS(lev) {
- LbmVec pos = LbmVec(
- ((mvGeoEnd[0]-mvGeoStart[0])/(LbmFloat)mLevel[lev].lSizex) * ((LbmFloat)i+0.5) + mvGeoStart[0],
- ((mvGeoEnd[1]-mvGeoStart[1])/(LbmFloat)mLevel[lev].lSizey) * ((LbmFloat)j+0.5) + mvGeoStart[1],
- ((mvGeoEnd[2]-mvGeoStart[2])/(LbmFloat)mLevel[lev].lSizez) * ((LbmFloat)k+0.5) + mvGeoStart[2] );
- if(LBMDIM==2) pos[2] = ((mvGeoEnd[2]-mvGeoStart[2])*0.5 + mvGeoStart[2]);
-
- if((mpControl->mDebugMaxdScale>0.) && (TESTGET_FORCE(lev,i,j,k).weightAtt<=0.) )
- if(TESTGET_FORCE(lev,i,j,k).maxDistance>=0.)
- if(TESTGET_FORCE(lev,i,j,k).maxDistance<CPF_MAXDINIT ) {
- const float scale = mpControl->mDebugMaxdScale*10001.;
- float dx = TESTGET_FORCE(lev,i,j,k).forceMaxd[0];
- float dy = TESTGET_FORCE(lev,i,j,k).forceMaxd[1];
- float dz = TESTGET_FORCE(lev,i,j,k).forceMaxd[2];
- dx *= scale; dy *= scale; dz *= scale;
- glColor3f( 0,1,0 );
- glVertex3f( pos[0],pos[1],pos[2] );
- glVertex3f( pos[0]+dx,pos[1]+dy,pos[2]+dz );
- } // */
- if((mpControl->mDebugAttScale>0.) && (TESTGET_FORCE(lev,i,j,k).weightAtt>0.)) {
- const float scale = mpControl->mDebugAttScale*100011.;
- float dx = TESTGET_FORCE(lev,i,j,k).forceAtt[0];
- float dy = TESTGET_FORCE(lev,i,j,k).forceAtt[1];
- float dz = TESTGET_FORCE(lev,i,j,k).forceAtt[2];
- dx *= scale; dy *= scale; dz *= scale;
- glColor3f( 1,0,0 );
- glVertex3f( pos[0],pos[1],pos[2] );
- glVertex3f( pos[0]+dx,pos[1]+dy,pos[2]+dz );
- } // */
- // why check maxDistance?
- if((mpControl->mDebugVelScale>0.) && (TESTGET_FORCE(lev,i,j,k).maxDistance+TESTGET_FORCE(lev,i,j,k).weightVel>0.)) {
- float scale = mpControl->mDebugVelScale*1.;
- float wvscale = TESTGET_FORCE(lev,i,j,k).weightVel;
- float dx = TESTGET_FORCE(lev,i,j,k).forceVel[0];
- float dy = TESTGET_FORCE(lev,i,j,k).forceVel[1];
- float dz = TESTGET_FORCE(lev,i,j,k).forceVel[2];
- scale *= wvscale;
- dx *= scale; dy *= scale; dz *= scale;
- glColor3f( 0.2,0.2,1 );
- glVertex3f( pos[0],pos[1],pos[2] );
- glVertex3f( pos[0]+dx,pos[1]+dy,pos[2]+dz );
- } // */
- if((mpControl->mDebugCompavScale>0.) && (TESTGET_FORCE(lev,i,j,k).compAvWeight>0.)) {
- const float scale = mpControl->mDebugCompavScale*1.;
- float dx = TESTGET_FORCE(lev,i,j,k).compAv[0];
- float dy = TESTGET_FORCE(lev,i,j,k).compAv[1];
- float dz = TESTGET_FORCE(lev,i,j,k).compAv[2];
- dx *= scale; dy *= scale; dz *= scale;
- glColor3f( 0.2,0.2,1 );
- glVertex3f( pos[0],pos[1],pos[2] );
- glVertex3f( pos[0]+dx,pos[1]+dy,pos[2]+dz );
- } // */
- } // att,maxd
- }
- glEnd();
- }
- } // cpssi
-
- //fprintf(stderr,"BLA\n");
- glEnable( GL_LIGHTING ); // dont light lines
- glShadeModel(GL_SMOOTH);
-}
-
-#else // LBM_USE_GUI==1
-void LbmFsgrSolver::cpDebugDisplay(int dispset) { }
-#endif // LBM_USE_GUI==1
-
-
diff --git a/intern/elbeem/intern/solver_control.h b/intern/elbeem/intern/solver_control.h
deleted file mode 100644
index 57112b365ce..00000000000
--- a/intern/elbeem/intern/solver_control.h
+++ /dev/null
@@ -1,182 +0,0 @@
-/******************************************************************************
- *
- * El'Beem - the visual lattice boltzmann freesurface simulator
- * All code distributed as part of El'Beem is covered by the version 2 of the
- * GNU General Public License. See the file COPYING for details.
- * Copyright 2003-2006 Nils Thuerey
- *
- * testing extensions
- *
- *****************************************************************************/
-
-
-#ifndef LBM_TESTCLASS_H
-#define LBM_TESTCLASS_H
-
-//class IsoSurface;
-class ParticleObject;
-class ControlParticles;
-class ControlForces;
-
-//#define NUMGRIDS 2
-//#define MAXNUMSWS 10
-
-// farfield modes
-#define FARF_3DONLY -1
-#define FARF_BOTH 0
-#define FARF_SWEONLY 1
-// dont reuse 3d vars/init
-#define FARF_SEPSWE 2
-
-// relaxation macros for solver_relax.h
-
-// WARNING has to match controlparts.h
-#define CPF_ENTRIES 12
-#define CPF_FORCE 0
-#define CPF_VELWEIGHT 3
-#define CPF_VELOCITY 4
-#define CPF_FORCEWEIGHT 7
-#define CPF_MINCPDIST 8
-#define CPF_MINCPDIR 9
-
-#include "controlparticles.h"
-
-#include "ntl_geometrymodel.h"
-
-// get force entry, set=0 is unused anyway
-#define LBMGET_FORCE(lev, i,j,k) mpControl->mCpForces[lev][ (LBMGI(lev,i,j,k,0)) ]
-
-// debug mods off...
-// same as in src/solver_relax.h!
-#define __PRECOLLIDE_MODS(rho,ux,uy,uz, grav) \
- ux += (grav)[0]; \
- uy += (grav)[1]; \
- uz += (grav)[2];
-
-//void testMaxdmod(int i, int j,int k, LbmFloat &ux,LbmFloat &uy,LbmFloat &uz,ControlForces &ff);
-#if LBMDIM==3
-#define MAXDGRAV \
- if(myforce->forceMaxd[0]*ux+myforce->forceMaxd[1]*uy<LBM_EPSILON) { \
- ux = v2w*myforce->forceVel[0]+ v2wi*ux; \
- uy = v2w*myforce->forceVel[1]+ v2wi*uy; } \
- /* movement inverse to g? */ \
- if((uz>LBM_EPSILON)&&(uz>myforce->forceVel[2])) { \
- uz = v2w*myforce->forceVel[2]+ v2wi*uz; }
-#else // LBMDIM==3
-#define MAXDGRAV \
- if(myforce->forceMaxd[0]*ux<LBM_EPSILON) { \
- ux = v2w*myforce->forceVel[0]+ v2wi*ux; } \
- /* movement inverse to g? */ \
- if((uy>LBM_EPSILON)&&(uy>myforce->forceVel[1])) { \
- uy = v2w*myforce->forceVel[1]+ v2wi*uy; }
-#endif // LBMDIM==3
-
-// debug modifications of collide vars (testing)
-// requires: lev,i,j,k
-#define PRECOLLIDE_MODS(rho,ux,uy,uz, grav) \
- LbmFloat attforce = 1.; \
- if(this->mTForceStrength>0.) { \
- ControlForces* myforce = &LBMGET_FORCE(lev,i,j,k); \
- const LbmFloat vf = myforce->weightAtt;\
- const LbmFloat vw = myforce->weightVel;\
- if(vf!=0.) { attforce = MAX(0., 1.-vf); /* TODO FIXME? use ABS(vf) for repulsion force? */ \
- ux += myforce->forceAtt[0]; \
- uy += myforce->forceAtt[1]; \
- uz += myforce->forceAtt[2]; \
- \
- } else if(( myforce->maxDistance>0.) && ( myforce->maxDistance<CPF_MAXDINIT)) {\
- const LbmFloat v2w = mpControl->mCons[0]->mCparts->getInfluenceMaxdist() * \
- (myforce->maxDistance-mpControl->mCons[0]->mCparts->getRadiusMinMaxd()) / (mpControl->mCons[0]->mCparts->getRadiusMaxd()-mpControl->mCons[0]->mCparts->getRadiusMinMaxd()); \
- const LbmFloat v2wi = 1.-v2w; \
- if(v2w>0.){ MAXDGRAV; \
- /* errMsg("ERRMDTT","at "<<PRINT_IJK<<" maxd="<<myforce->maxDistance<<", newu"<<PRINT_VEC(ux,uy,uz)<<", org"<<PRINT_VEC(oux,ouy,ouz)<<", fv"<<myforce->forceVel<<" " ); */ \
- }\
- } \
- if(vw>0.) { \
- const LbmFloat vwi = 1.-vw;\
- const LbmFloat vwd = mpControl->mDiffVelCon;\
- ux += vw*(myforce->forceVel[0]-myforce->compAv[0] + vwd*(myforce->compAv[0]-ux) ); \
- uy += vw*(myforce->forceVel[1]-myforce->compAv[1] + vwd*(myforce->compAv[1]-uy) ); \
- uz += vw*(myforce->forceVel[2]-myforce->compAv[2] + vwd*(myforce->compAv[2]-uz) ); \
- /* TODO test!? modify smooth vel by influence of force for each lbm step, to account for force update only each N steps */ \
- myforce->compAv = (myforce->forceVel*vw+ myforce->compAv*vwi); \
- } \
- } \
- ux += (grav)[0]*attforce; \
- uy += (grav)[1]*attforce; \
- uz += (grav)[2]*attforce; \
- /* end PRECOLLIDE_MODS */
-
-#define TEST_IF_CHECK \
- if((!iffilled)&&(LBMGET_FORCE(lev,i,j,k).weightAtt!=0.)) { \
- errMsg("TESTIFFILL"," at "<<PRINT_IJK<<" "<<mass<<" "<<rho); \
- iffilled = true; \
- if(mass<rho*1.0) mass = rho*1.0; myfrac = 1.0; \
- }
-
-
-// a single set of control particles and params
-class LbmControlSet {
- public:
- LbmControlSet();
- ~LbmControlSet();
- void initCparts();
-
- // control particles
- ControlParticles *mCparts;
- // control particle overall motion (for easier manual generation)
- ControlParticles *mCpmotion;
- // cp data file
- string mContrPartFile;
- string mCpmotionFile;
- // cp debug displau
- LbmFloat mDebugCpscale, mDebugVelScale, mDebugCompavScale, mDebugAttScale, mDebugMaxdScale, mDebugAvgVelScale;
-
- // params
- AnimChannel<float> mcForceAtt;
- AnimChannel<float> mcForceVel;
- AnimChannel<float> mcForceMaxd;
-
- AnimChannel<float> mcRadiusAtt;
- AnimChannel<float> mcRadiusVel;
- AnimChannel<float> mcRadiusMind;
- AnimChannel<float> mcRadiusMaxd;
-
- AnimChannel<ntlVec3f> mcCpScale;
- AnimChannel<ntlVec3f> mcCpOffset;
-};
-
-
-
-// main control data storage
-class LbmControlData
-{
- public:
- LbmControlData();
- virtual ~LbmControlData();
-
- // control data
-
- // contorl params
- void parseControldataAttrList(AttributeList *attr);
-
- // control strength, set for solver interface
- LbmFloat mSetForceStrength;
- // cp vars
- std::vector<LbmControlSet*> mCons;
- // update interval
- int mCpUpdateInterval;
- // output
- string mCpOutfile;
- // control particle precomputed influence
- std::vector< std::vector<ControlForces> > mCpForces;
- std::vector<ControlForces> mCpKernel;
- std::vector<ControlForces> mMdKernel;
- // activate differential velcon
- LbmFloat mDiffVelCon;
-
- // cp debug displau
- LbmFloat mDebugCpscale, mDebugVelScale, mDebugCompavScale, mDebugAttScale, mDebugMaxdScale, mDebugAvgVelScale;
-};
-
-#endif // LBM_TESTCLASS_H
diff --git a/intern/guardedalloc/BLO_sys_types.h b/intern/guardedalloc/BLO_sys_types.h
deleted file mode 100644
index 5ed3117c890..00000000000
--- a/intern/guardedalloc/BLO_sys_types.h
+++ /dev/null
@@ -1,125 +0,0 @@
-/**
- * $Id$
- *
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- * A platform-independent definition of [u]intXX_t
- * Plus the accompanying header include for htonl/ntohl
- *
- * This file includes <sys/types.h> to define [u]intXX_t types, where
- * XX can be 8, 16, 32 or 64. Unfortunately, not all systems have this
- * file.
- * - Windows uses __intXX compiler-builtin types. These are signed,
- * so we have to flip the signs.
- * For these rogue platforms, we make the typedefs ourselves.
- *
- */
-
-/*
-// DG: original BLO_sys_types.h is in source/blender/blenkernel
-// but is not allowed be accessed here because of bad-level-call
-*/
-
-#ifndef BLO_SYS_TYPES_H
-#define BLO_SYS_TYPES_H
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#if defined(_WIN32) && !defined(FREE_WINDOWS)
-
-/* The __intXX are built-in types of the visual complier! So we don't
- * need to include anything else here. */
-
-typedef signed __int8 int8_t;
-typedef signed __int16 int16_t;
-typedef signed __int32 int32_t;
-typedef signed __int64 int64_t;
-
-typedef unsigned __int8 uint8_t;
-typedef unsigned __int16 uint16_t;
-typedef unsigned __int32 uint32_t;
-typedef unsigned __int64 uint64_t;
-
-#ifndef _INTPTR_T_DEFINED
-#ifdef _WIN64
-typedef __int64 intptr_t;
-#else
-typedef long intptr_t;
-#endif
-#define _INTPTR_T_DEFINED
-#endif
-
-#ifndef _UINTPTR_T_DEFINED
-#ifdef _WIN64
-typedef unsigned __int64 uintptr_t;
-#else
-typedef unsigned long uintptr_t;
-#endif
-#define _UINTPTR_T_DEFINED
-#endif
-
-#elif defined(__linux__)
-
- /* Linux-i386, Linux-Alpha, Linux-ppc */
-#include <stdint.h>
-
-#elif defined (__APPLE__)
-
-#include <inttypes.h>
-
-#elif defined(FREE_WINDOWS)
-
-#include <stdint.h>
-
-#else
-
- /* FreeBSD, Irix, Solaris */
-#include <sys/types.h>
-
-#endif /* ifdef platform for types */
-
-#ifdef _WIN32
-#ifndef htonl
-#define htonl(x) correctByteOrder(x)
-#endif
-#ifndef ntohl
-#define ntohl(x) correctByteOrder(x)
-#endif
-#elif defined (__FreeBSD__) || defined (__OpenBSD__)
-#include <sys/param.h>
-#elif defined (__APPLE__)
-#include <sys/types.h>
-#else /* irix sun linux */
-#include <netinet/in.h>
-#endif /* ifdef platform for htonl/ntohl */
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* eof */
-
diff --git a/intern/opennl/superlu/BLO_sys_types.h b/intern/opennl/superlu/BLO_sys_types.h
deleted file mode 100644
index 411a8582f96..00000000000
--- a/intern/opennl/superlu/BLO_sys_types.h
+++ /dev/null
@@ -1,127 +0,0 @@
-/**
- * $Id$
- *
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- * A platform-independent definition of [u]intXX_t
- * Plus the accompanying header include for htonl/ntohl
- *
- * This file includes <sys/types.h> to define [u]intXX_t types, where
- * XX can be 8, 16, 32 or 64. Unfortunately, not all systems have this
- * file.
- * - Windows uses __intXX compiler-builtin types. These are signed,
- * so we have to flip the signs.
- * For these rogue platforms, we make the typedefs ourselves.
- *
- */
-
-/*
-// DG: original BLO_sys_types.h is in source/blender/blenkernel
-// but is not allowed be accessed here because of bad-level-call
-*/
-
-#ifndef BLO_SYS_TYPES_H
-#define BLO_SYS_TYPES_H
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#if defined(_WIN32) && !defined(FREE_WINDOWS)
-
-/* The __intXX are built-in types of the visual complier! So we don't
- * need to include anything else here. */
-
-
-typedef signed __int8 int8_t;
-typedef signed __int16 int16_t;
-typedef signed __int32 int32_t;
-typedef signed __int64 int64_t;
-
-typedef unsigned __int8 uint8_t;
-typedef unsigned __int16 uint16_t;
-typedef unsigned __int32 uint32_t;
-typedef unsigned __int64 uint64_t;
-
-#ifndef _INTPTR_T_DEFINED
-#ifdef _WIN64
-typedef __int64 intptr_t;
-#else
-typedef long intptr_t;
-#endif
-#define _INTPTR_T_DEFINED
-#endif
-
-#ifndef _UINTPTR_T_DEFINED
-#ifdef _WIN64
-typedef unsigned __int64 uintptr_t;
-#else
-typedef unsigned long uintptr_t;
-#endif
-#define _UINTPTR_T_DEFINED
-#endif
-
-#elif defined(__linux__)
-
- /* Linux-i386, Linux-Alpha, Linux-ppc */
-#include <stdint.h>
-
-#elif defined (__APPLE__)
-
-#include <inttypes.h>
-
-#elif defined(FREE_WINDOWS)
-
-#include <stdint.h>
-
-#else
-
- /* FreeBSD, Irix, Solaris */
-#include <sys/types.h>
-
-#endif /* ifdef platform for types */
-
-
-#ifdef _WIN32
-#ifndef htonl
-#define htonl(x) correctByteOrder(x)
-#endif
-#ifndef ntohl
-#define ntohl(x) correctByteOrder(x)
-#endif
-#elif defined (__FreeBSD__) || defined (__OpenBSD__)
-#include <sys/param.h>
-#elif defined (__APPLE__)
-#include <sys/types.h>
-#else /* irix sun linux */
-#include <netinet/in.h>
-#endif /* ifdef platform for htonl/ntohl */
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* eof */
-
diff --git a/release/Makefile b/release/Makefile
index 43a369d8f77..f440e2dface 100644
--- a/release/Makefile
+++ b/release/Makefile
@@ -57,12 +57,6 @@ ifeq ($(OS),$(findstring $(OS), "freebsd irix linux openbsd solaris"))
NOPLUGINS?=true
endif
endif
- # don"t build plugins on irix if using gcc
- ifeq ($(OS), irix)
- ifeq ($(IRIX_USE_GCC), true)
- NOPLUGINS?=true
- endif
- endif
endif
ifeq ($(OS),windows)
diff --git a/release/VERSION b/release/VERSION
index 1c593e17dae..e72716a7902 100644
--- a/release/VERSION
+++ b/release/VERSION
@@ -1 +1 @@
-2.48
+2.46
diff --git a/release/datafiles/blenderbuttons b/release/datafiles/blenderbuttons
index 6993840e51f..a4834091692 100644
--- a/release/datafiles/blenderbuttons
+++ b/release/datafiles/blenderbuttons
Binary files differ
diff --git a/release/datafiles/datatoc.c b/release/datafiles/datatoc.c
index 46b935c7fd6..2e24a0f92ef 100644
--- a/release/datafiles/datatoc.c
+++ b/release/datafiles/datatoc.c
@@ -35,7 +35,7 @@ int main(int argc, char**argv) {
FILE *fpin, *fpout;
char cname[256];
char sizest[256];
- size_t size;
+ long size;
int i;
if (argc<1) {
diff --git a/release/datafiles/preview.blend b/release/datafiles/preview.blend
index 78ced06bba9..9e09d579b2b 100644
--- a/release/datafiles/preview.blend
+++ b/release/datafiles/preview.blend
Binary files differ
diff --git a/release/datafiles/splash.jpg b/release/datafiles/splash.jpg
index c65b2f37e87..6a1bd28d509 100644
--- a/release/datafiles/splash.jpg
+++ b/release/datafiles/splash.jpg
Binary files differ
diff --git a/release/plugins/sequence/dnr.c b/release/plugins/sequence/dnr.c
index b6a99de0622..7e7c168750e 100644
--- a/release/plugins/sequence/dnr.c
+++ b/release/plugins/sequence/dnr.c
@@ -110,9 +110,9 @@ static void doit(unsigned char * src_, unsigned char * dst_,
unsigned char * dst = dst_;
while (count--) {
- *dst = table[(*src++ << 8) | *dst]; dst++;
- *dst = table[(*src++ << 8) | *dst]; dst++;
- *dst = table[(*src++ << 8) | *dst]; dst++;
+ *dst++ = table[(*src++ << 8) | *dst];
+ *dst++ = table[(*src++ << 8) | *dst];
+ *dst++ = table[(*src++ << 8) | *dst];
*dst++ = *src++;
}
diff --git a/release/scripts/DirectX8Exporter.py b/release/scripts/DirectX8Exporter.py
index b8bdae4de2b..01212545f77 100644
--- a/release/scripts/DirectX8Exporter.py
+++ b/release/scripts/DirectX8Exporter.py
@@ -7,7 +7,7 @@
# Tooltip: 'Export to DirectX text file format format for XNA Animation Component Library.'
"""
__author__ = "vertex color exporting feature is added by mnemoto (original:minahito (original:Arben (Ben) Omari))"
-__url__ = ("blender.org", "blenderartists.org", "Adjuster's site http://sunday-lab.blogspot.com/, Author's site http://www.omariben.too.it","Adjuster's site http://ex.homeunix.net/")
+__url__ = ("blender", "elysiun", "Adjuster's site http://sunday-lab.blogspot.com/, Author's site http://www.omariben.too.it","Adjuster's site http://ex.homeunix.net/")
__version__ = "3.1"
__bpydoc__ = """\
diff --git a/release/scripts/animation_bake_constraints.py b/release/scripts/animation_bake_constraints.py
index 16855828460..8a416c3c488 100644
--- a/release/scripts/animation_bake_constraints.py
+++ b/release/scripts/animation_bake_constraints.py
@@ -155,7 +155,7 @@ usrObjectNamePrefix= ""
# if that armature had bones (spine, neck, arm) and the bone prefix was "a."
# the bones and IPO curves will be (a.spine, a.neck, a.arm)
-R2D = 18/3.141592653589793 # radian to grad
+R2D = 18/3.1415 # radian to grad
BLENDER_VERSION = Blender.Get('version')
# Gets the current scene, there can be many scenes in 1 blend file.
@@ -602,7 +602,7 @@ def bakeObject(ob): #bakes the core object locrot and assigns the Ipo to a Clone
if ob != None:
# Clone the object - duplicate it, clean the clone, and create an ipo curve for the clone
myob = duplicateLinked(ob) #clone it
- myob.setName(usrObjectNamePrefix + ob.getName())
+ myob.name= usrObjectNamePrefix + ob.getName()
removeConstraintsOb(myob) #my object is a free man
deLinkOb('Ipo',myob) #kids, it's not nice to share. you've been lied to
if ob.getType() != ARMATURE: # baking armatures is based on bones, not object
diff --git a/release/scripts/bpymodules/BPyImage.py b/release/scripts/bpymodules/BPyImage.py
index 504e4ee29ba..2c342ddec39 100644
--- a/release/scripts/bpymodules/BPyImage.py
+++ b/release/scripts/bpymodules/BPyImage.py
@@ -79,7 +79,7 @@ def addSlash(path):
return path + sys.sep
-def comprehensiveImageLoad(imagePath, filePath, PLACE_HOLDER= True, RECURSIVE=True, VERBOSE=False, CONVERT_CALLBACK=None):
+def comprehensiveImageLoad(imagePath, filePath, PLACE_HOLDER= True, RECURSIVE=True, VERBOSE=False):
'''
imagePath: The image filename
If a path precedes it, this will be searched as well.
@@ -93,30 +93,13 @@ def comprehensiveImageLoad(imagePath, filePath, PLACE_HOLDER= True, RECURSIVE=Tr
RECURSIVE: If True, directories will be recursivly searched.
Be carefull with this if you have files in your root directory because it may take a long time.
-
- CASE_INSENSITIVE: for non win32 systems, find the correct case for the file.
-
- CONVERT_CALLBACK: a function that takes an existing path and returns a new one.
- Use this when loading image formats blender may not support, the CONVERT_CALLBACK
- can take the path for a GIF (for example), convert it to a PNG and return the PNG's path.
- For formats blender can read, simply return the path that is given.
'''
- # VERBOSE = True
-
if VERBOSE: print 'img:', imagePath, 'file:', filePath
-
- if os == None and CASE_INSENSITIVE:
- CASE_INSENSITIVE = True
-
# When we have the file load it with this. try/except niceness.
def imageLoad(path):
#if path.endswith('\\') or path.endswith('/'):
# raise 'INVALID PATH'
-
- if CONVERT_CALLBACK:
- path = CONVERT_CALLBACK(path)
-
try:
img = bpy.data.images.new(filename=path)
if VERBOSE: print '\t\tImage loaded "%s"' % path
diff --git a/release/scripts/bpymodules/BPyMathutils.py b/release/scripts/bpymodules/BPyMathutils.py
index bfa1dcc3c61..27736b4169e 100644
--- a/release/scripts/bpymodules/BPyMathutils.py
+++ b/release/scripts/bpymodules/BPyMathutils.py
@@ -225,5 +225,15 @@ from math import pi, sin, cos, sqrt
def angleToLength(angle):
# Alredy accounted for
- if angle < 0.000001: return 1.0
- else: return abs(1.0 / cos(pi*angle/180));
+ if angle < 0.000001:
+ return 1.0
+
+ angle = 2*pi*angle/360
+ x,y = cos(angle), sin(angle)
+ # print "YX", x,y
+ # 0 d is hoz to the right.
+ # 90d is vert upward.
+ fac=1/x
+ x=x*fac
+ y=y*fac
+ return sqrt((x*x)+(y*y))
diff --git a/release/scripts/bpymodules/BPyMesh.py b/release/scripts/bpymodules/BPyMesh.py
index 6bbfaa463d0..415c2a12c69 100644
--- a/release/scripts/bpymodules/BPyMesh.py
+++ b/release/scripts/bpymodules/BPyMesh.py
@@ -479,7 +479,7 @@ def pickMeshRayFaceWeight(me, orig, rdir):
w0 = (l1+l2)
w1 = (l0+l2)
- w2 = (l1+l0)
+ w2 = (l1+l2)
totw= w0 + w1 + w2
w0=w0/totw
diff --git a/release/scripts/bpymodules/BPySys.py b/release/scripts/bpymodules/BPySys.py
index a2d2120ebff..594264fad84 100644
--- a/release/scripts/bpymodules/BPySys.py
+++ b/release/scripts/bpymodules/BPySys.py
@@ -12,63 +12,3 @@ def cleanName(name):
for ch in invalid: name = name.replace(ch, '_')
return name
-def caseInsensitivePath(path, RET_FOUND=False):
- '''
- Get a case insensitive path on a case sensitive system
-
- RET_FOUND is for internal use only, to avoid too many calls to os.path.exists
- # Example usage
- getCaseInsensitivePath('/hOmE/mE/sOmEpAtH.tXt')
- '''
- import os # todo, what happens with no os?
-
- if os==None:
- if RET_FOUND: ret = path, True
- else: ret = path
- return ret
-
- if path=='' or os.path.exists(path):
- if RET_FOUND: ret = path, True
- else: ret = path
- return ret
-
- f = os.path.basename(path) # f may be a directory or a file
- d = os.path.dirname(path)
-
- suffix = ''
- if not f: # dir ends with a slash?
- if len(d) < len(path):
- suffix = path[:len(path)-len(d)]
-
- f = os.path.basename(d)
- d = os.path.dirname(d)
-
- if not os.path.exists(d):
- d, found = caseInsensitivePath(d, True)
-
- if not found:
- if RET_FOUND: ret = path, False
- else: ret = path
- return ret
-
- # at this point, the directory exists but not the file
-
- try: # we are expecting 'd' to be a directory, but it could be a file
- files = os.listdir(d)
- except:
- if RET_FOUND: ret = path, False
- else: ret = path
-
- f_low = f.lower()
-
- try: f_nocase = [fl for fl in files if fl.lower() == f_low][0]
- except: f_nocase = None
-
- if f_nocase:
- if RET_FOUND: ret = os.path.join(d, f_nocase) + suffix, True
- else: ret = os.path.join(d, f_nocase) + suffix
- return ret
- else:
- if RET_FOUND: ret = path, False
- else: ret = path
- return ret # cant find the right one, just return the path as is. \ No newline at end of file
diff --git a/release/scripts/bpymodules/BPyTextPlugin.py b/release/scripts/bpymodules/BPyTextPlugin.py
deleted file mode 100644
index cd5a085de37..00000000000
--- a/release/scripts/bpymodules/BPyTextPlugin.py
+++ /dev/null
@@ -1,814 +0,0 @@
-"""The BPyTextPlugin Module
-
-Use get_cached_descriptor(txt) to retrieve information about the script held in
-the txt Text object.
-
-Use print_cache_for(txt) to print the information to the console.
-
-Use line, cursor = current_line(txt) to get the logical line and cursor position
-
-Use get_targets(line, cursor) to find out what precedes the cursor:
- aaa.bbb.cc|c.ddd -> ['aaa', 'bbb', 'cc']
-
-Use resolve_targets(txt, targets) to turn a target list into a usable object if
-one is found to match.
-"""
-
-import bpy, sys, os
-import __builtin__, tokenize
-from Blender.sys import time
-from tokenize import generate_tokens, TokenError, \
- COMMENT, DEDENT, INDENT, NAME, NEWLINE, NL, STRING, NUMBER
-
-class Definition:
- """Describes a definition or defined object through its name, line number
- and docstring. This is the base class for definition based descriptors.
- """
-
- def __init__(self, name, lineno, doc=''):
- self.name = name
- self.lineno = lineno
- self.doc = doc
-
-class ScriptDesc:
- """Describes a script through lists of further descriptor objects (classes,
- defs, vars) and dictionaries to built-in types (imports). If a script has
- not been fully parsed, its incomplete flag will be set. The time of the last
- parse is held by the time field and the name of the text object from which
- it was parsed, the name field.
- """
-
- def __init__(self, name, imports, classes, defs, vars, incomplete=False):
- self.name = name
- self.imports = imports
- self.classes = classes
- self.defs = defs
- self.vars = vars
- self.incomplete = incomplete
- self.parse_due = 0
-
- def set_delay(self, delay):
- self.parse_due = time() + delay
-
-class ClassDesc(Definition):
- """Describes a class through lists of further descriptor objects (defs and
- vars). The name of the class is held by the name field and the line on
- which it is defined is held in lineno.
- """
-
- def __init__(self, name, parents, defs, vars, lineno, doc=''):
- Definition.__init__(self, name, lineno, doc)
- self.parents = parents
- self.defs = defs
- self.vars = vars
-
-class FunctionDesc(Definition):
- """Describes a function through its name and list of parameters (name,
- params) and the line on which it is defined (lineno).
- """
-
- def __init__(self, name, params, lineno, doc=''):
- Definition.__init__(self, name, lineno, doc)
- self.params = params
-
-class VarDesc(Definition):
- """Describes a variable through its name and type (if ascertainable) and the
- line on which it is defined (lineno). If no type can be determined, type
- will equal None.
- """
-
- def __init__(self, name, type, lineno):
- Definition.__init__(self, name, lineno)
- self.type = type # None for unknown (supports: dict/list/str)
-
-# Context types
-CTX_UNSET = -1
-CTX_NORMAL = 0
-CTX_SINGLE_QUOTE = 1
-CTX_DOUBLE_QUOTE = 2
-CTX_COMMENT = 3
-
-# Python keywords
-KEYWORDS = ['and', 'del', 'from', 'not', 'while', 'as', 'elif', 'global',
- 'or', 'with', 'assert', 'else', 'if', 'pass', 'yield',
- 'break', 'except', 'import', 'print', 'class', 'exec', 'in',
- 'raise', 'continue', 'finally', 'is', 'return', 'def', 'for',
- 'lambda', 'try' ]
-
-# Module file extensions
-MODULE_EXTS = ['.py', '.pyc', '.pyo', '.pyw', '.pyd']
-
-ModuleType = type(__builtin__)
-NoneScriptDesc = ScriptDesc('', dict(), dict(), dict(), dict(), True)
-
-_modules = {}
-_modules_updated = 0
-_parse_cache = dict()
-
-def _load_module_names():
- """Searches the sys.path for module files and lists them, along with
- sys.builtin_module_names, in the global dict _modules.
- """
-
- global _modules
-
- for n in sys.builtin_module_names:
- _modules[n] = None
- for p in sys.path:
- if p == '': p = os.curdir
- if not os.path.isdir(p): continue
- for f in os.listdir(p):
- for ext in MODULE_EXTS:
- if f.endswith(ext):
- _modules[f[:-len(ext)]] = None
- break
-
-_load_module_names()
-
-def _trim_doc(doc):
- """Trims the quotes from a quoted STRING token (eg. "'''text'''" -> "text")
- """
-
- l = len(doc)
- i = 0
- while i < l/2 and (doc[i] == "'" or doc[i] == '"'):
- i += 1
- return doc[i:-i]
-
-def resolve_targets(txt, targets):
- """Attempts to return a useful object for the locally or externally defined
- entity described by targets. If the object is local (defined in txt), a
- Definition instance is returned. If the object is external (imported or
- built in), the object itself is returned. If no object can be found, None is
- returned.
- """
-
- count = len(targets)
- if count==0: return None
-
- obj = None
- local = None
- i = 1
-
- desc = get_cached_descriptor(txt)
- b = targets[0].find('(')
- if b==-1: b = None # Trick to let us use [:b] and get the whole string
-
- if desc.classes.has_key(targets[0][:b]):
- local = desc.classes[targets[0][:b]]
- elif desc.defs.has_key(targets[0]):
- local = desc.defs[targets[0]]
- elif desc.vars.has_key(targets[0]):
- obj = desc.vars[targets[0]].type
-
- if local:
- while i < count:
- b = targets[i].find('(')
- if b==-1: b = None
- if hasattr(local, 'classes') and local.classes.has_key(targets[i][:b]):
- local = local.classes[targets[i][:b]]
- elif hasattr(local, 'defs') and local.defs.has_key(targets[i]):
- local = local.defs[targets[i]]
- elif hasattr(local, 'vars') and local.vars.has_key(targets[i]):
- obj = local.vars[targets[i]].type
- local = None
- i += 1
- break
- else:
- local = None
- break
- i += 1
-
- if local: return local
-
- if not obj:
- if desc.imports.has_key(targets[0]):
- obj = desc.imports[targets[0]]
- else:
- builtins = get_builtins()
- if builtins.has_key(targets[0]):
- obj = builtins[targets[0]]
-
- while obj and i < count:
- if hasattr(obj, targets[i]):
- obj = getattr(obj, targets[i])
- else:
- obj = None
- break
- i += 1
-
- return obj
-
-def get_cached_descriptor(txt, force_parse=0):
- """Returns the cached ScriptDesc for the specified Text object 'txt'. If the
- script has not been parsed in the last 'period' seconds it will be reparsed
- to obtain this descriptor.
-
- Specifying TP_AUTO for the period (default) will choose a period based on the
- size of the Text object. Larger texts are parsed less often.
- """
-
- global _parse_cache
-
- parse = True
- key = hash(txt)
- if not force_parse and _parse_cache.has_key(key):
- desc = _parse_cache[key]
- if desc.parse_due > time():
- parse = desc.incomplete
-
- if parse:
- desc = parse_text(txt)
-
- return desc
-
-def parse_text(txt):
- """Parses an entire script's text and returns a ScriptDesc instance
- containing information about the script.
-
- If the text is not a valid Python script (for example if brackets are left
- open), parsing may fail to complete. However, if this occurs, no exception
- is thrown. Instead the returned ScriptDesc instance will have its incomplete
- flag set and information processed up to this point will still be accessible.
- """
-
- start_time = time()
- txt.reset()
- tokens = generate_tokens(txt.readline) # Throws TokenError
-
- curl, cursor = txt.getCursorPos()
- linen = curl + 1 # Token line numbers are one-based
-
- imports = dict()
- imp_step = 0
-
- classes = dict()
- cls_step = 0
-
- defs = dict()
- def_step = 0
-
- vars = dict()
- var1_step = 0
- var2_step = 0
- var3_step = 0
- var_accum = dict()
- var_forflag = False
-
- indent = 0
- prev_type = -1
- prev_text = ''
- incomplete = False
-
- while True:
- try:
- type, text, start, end, line = tokens.next()
- except StopIteration:
- break
- except (TokenError, IndentationError):
- incomplete = True
- break
-
- # Skip all comments and line joining characters
- if type == COMMENT or type == NL:
- continue
-
- #################
- ## Indentation ##
- #################
-
- if type == INDENT:
- indent += 1
- elif type == DEDENT:
- indent -= 1
-
- #########################
- ## Module importing... ##
- #########################
-
- imp_store = False
-
- # Default, look for 'from' or 'import' to start
- if imp_step == 0:
- if text == 'from':
- imp_tmp = []
- imp_step = 1
- elif text == 'import':
- imp_from = None
- imp_tmp = []
- imp_step = 2
-
- # Found a 'from', create imp_from in form '???.???...'
- elif imp_step == 1:
- if text == 'import':
- imp_from = '.'.join(imp_tmp)
- imp_tmp = []
- imp_step = 2
- elif type == NAME:
- imp_tmp.append(text)
- elif text != '.':
- imp_step = 0 # Invalid syntax
-
- # Found 'import', imp_from is populated or None, create imp_name
- elif imp_step == 2:
- if text == 'as':
- imp_name = '.'.join(imp_tmp)
- imp_step = 3
- elif type == NAME or text == '*':
- imp_tmp.append(text)
- elif text != '.':
- imp_name = '.'.join(imp_tmp)
- imp_symb = imp_name
- imp_store = True
-
- # Found 'as', change imp_symb to this value and go back to step 2
- elif imp_step == 3:
- if type == NAME:
- imp_symb = text
- else:
- imp_store = True
-
- # Both imp_name and imp_symb have now been populated so we can import
- if imp_store:
-
- # Handle special case of 'import *'
- if imp_name == '*':
- parent = get_module(imp_from)
- imports.update(parent.__dict__)
-
- else:
- # Try importing the name as a module
- try:
- if imp_from:
- module = get_module(imp_from +'.'+ imp_name)
- else:
- module = get_module(imp_name)
- except (ImportError, ValueError, AttributeError, TypeError):
- # Try importing name as an attribute of the parent
- try:
- module = __import__(imp_from, globals(), locals(), [imp_name])
- imports[imp_symb] = getattr(module, imp_name)
- except (ImportError, ValueError, AttributeError, TypeError):
- pass
- else:
- imports[imp_symb] = module
-
- # More to import from the same module?
- if text == ',':
- imp_tmp = []
- imp_step = 2
- else:
- imp_step = 0
-
- ###################
- ## Class parsing ##
- ###################
-
- # If we are inside a class then def and variable parsing should be done
- # for the class. Otherwise the definitions are considered global
-
- # Look for 'class'
- if cls_step == 0:
- if text == 'class':
- cls_name = None
- cls_lineno = start[0]
- cls_indent = indent
- cls_step = 1
-
- # Found 'class', look for cls_name followed by '(' parents ')'
- elif cls_step == 1:
- if not cls_name:
- if type == NAME:
- cls_name = text
- cls_sline = False
- cls_parents = dict()
- cls_defs = dict()
- cls_vars = dict()
- elif type == NAME:
- if classes.has_key(text):
- parent = classes[text]
- cls_parents[text] = parent
- cls_defs.update(parent.defs)
- cls_vars.update(parent.vars)
- elif text == ':':
- cls_step = 2
-
- # Found 'class' name ... ':', now check if it's a single line statement
- elif cls_step == 2:
- if type == NEWLINE:
- cls_sline = False
- else:
- cls_sline = True
- cls_doc = ''
- cls_step = 3
-
- elif cls_step == 3:
- if not cls_doc and type == STRING:
- cls_doc = _trim_doc(text)
- if cls_sline:
- if type == NEWLINE:
- classes[cls_name] = ClassDesc(cls_name, cls_parents, cls_defs, cls_vars, cls_lineno, cls_doc)
- cls_step = 0
- else:
- if type == DEDENT and indent <= cls_indent:
- classes[cls_name] = ClassDesc(cls_name, cls_parents, cls_defs, cls_vars, cls_lineno, cls_doc)
- cls_step = 0
-
- #################
- ## Def parsing ##
- #################
-
- # Look for 'def'
- if def_step == 0:
- if text == 'def':
- def_name = None
- def_lineno = start[0]
- def_step = 1
-
- # Found 'def', look for def_name followed by '('
- elif def_step == 1:
- if type == NAME:
- def_name = text
- def_params = []
- elif def_name and text == '(':
- def_step = 2
-
- # Found 'def' name '(', now identify the parameters upto ')'
- # TODO: Handle ellipsis '...'
- elif def_step == 2:
- if type == NAME:
- def_params.append(text)
- elif text == ':':
- def_step = 3
-
- # Found 'def' ... ':', now check if it's a single line statement
- elif def_step == 3:
- if type == NEWLINE:
- def_sline = False
- else:
- def_sline = True
- def_doc = ''
- def_step = 4
-
- elif def_step == 4:
- if type == STRING:
- def_doc = _trim_doc(text)
- newdef = None
- if def_sline:
- if type == NEWLINE:
- newdef = FunctionDesc(def_name, def_params, def_lineno, def_doc)
- else:
- if type == NAME:
- newdef = FunctionDesc(def_name, def_params, def_lineno, def_doc)
- if newdef:
- if cls_step > 0: # Parsing a class
- cls_defs[def_name] = newdef
- else:
- defs[def_name] = newdef
- def_step = 0
-
- ##########################
- ## Variable assignation ##
- ##########################
-
- if cls_step > 0: # Parsing a class
- # Look for 'self.???'
- if var1_step == 0:
- if text == 'self':
- var1_step = 1
- elif var1_step == 1:
- if text == '.':
- var_name = None
- var1_step = 2
- else:
- var1_step = 0
- elif var1_step == 2:
- if type == NAME:
- var_name = text
- if cls_vars.has_key(var_name):
- var_step = 0
- else:
- var1_step = 3
- elif var1_step == 3:
- if text == '=':
- var1_step = 4
- elif text != ',':
- var1_step = 0
- elif var1_step == 4:
- var_type = None
- if type == NUMBER:
- close = end[1]
- if text.find('.') != -1: var_type = float
- else: var_type = int
- elif type == STRING:
- close = end[1]
- var_type = str
- elif text == '[':
- close = line.find(']', end[1])
- var_type = list
- elif text == '(':
- close = line.find(')', end[1])
- var_type = tuple
- elif text == '{':
- close = line.find('}', end[1])
- var_type = dict
- elif text == 'dict':
- close = line.find(')', end[1])
- var_type = dict
- if var_type and close+1 < len(line):
- if line[close+1] != ' ' and line[close+1] != '\t':
- var_type = None
- cls_vars[var_name] = VarDesc(var_name, var_type, start[0])
- var1_step = 0
-
- elif def_step > 0: # Parsing a def
- # Look for 'global ???[,???]'
- if var2_step == 0:
- if text == 'global':
- var2_step = 1
- elif var2_step == 1:
- if type == NAME:
- if not vars.has_key(text):
- vars[text] = VarDesc(text, None, start[0])
- elif text != ',' and type != NL:
- var2_step == 0
-
- else: # In global scope
- if var3_step == 0:
- # Look for names
- if text == 'for':
- var_accum = dict()
- var_forflag = True
- elif text == '=' or (var_forflag and text == 'in'):
- var_forflag = False
- var3_step = 1
- elif type == NAME:
- if prev_text != '.' and not vars.has_key(text):
- var_accum[text] = VarDesc(text, None, start[0])
- elif not text in [',', '(', ')', '[', ']']:
- var_accum = dict()
- var_forflag = False
- elif var3_step == 1:
- if len(var_accum) != 1:
- var_type = None
- vars.update(var_accum)
- else:
- var_name = var_accum.keys()[0]
- var_type = None
- if type == NUMBER:
- if text.find('.') != -1: var_type = float
- else: var_type = int
- elif type == STRING: var_type = str
- elif text == '[': var_type = list
- elif text == '(': var_type = tuple
- elif text == '{': var_type = dict
- vars[var_name] = VarDesc(var_name, var_type, start[0])
- var3_step = 0
-
- #######################
- ## General utilities ##
- #######################
-
- prev_type = type
- prev_text = text
-
- desc = ScriptDesc(txt.name, imports, classes, defs, vars, incomplete)
- desc.set_delay(10 * (time()-start_time) + 0.05)
-
- global _parse_cache
- _parse_cache[hash(txt)] = desc
- return desc
-
-def get_modules(since=1):
- """Returns the set of built-in modules and any modules that have been
- imported into the system upto 'since' seconds ago.
- """
-
- global _modules, _modules_updated
-
- t = time()
- if _modules_updated < t - since:
- _modules.update(sys.modules)
- _modules_updated = t
- return _modules.keys()
-
-def suggest_cmp(x, y):
- """Use this method when sorting a list of suggestions.
- """
-
- return cmp(x[0].upper(), y[0].upper())
-
-def get_module(name):
- """Returns the module specified by its name. The module itself is imported
- by this method and, as such, any initialization code will be executed.
- """
-
- mod = __import__(name)
- components = name.split('.')
- for comp in components[1:]:
- mod = getattr(mod, comp)
- return mod
-
-def type_char(v):
- """Returns the character used to signify the type of a variable. Use this
- method to identify the type character for an item in a suggestion list.
-
- The following values are returned:
- 'm' if the parameter is a module
- 'f' if the parameter is callable
- 'v' if the parameter is variable or otherwise indeterminable
-
- """
-
- if isinstance(v, ModuleType):
- return 'm'
- elif callable(v):
- return 'f'
- else:
- return 'v'
-
-def get_context(txt):
- """Establishes the context of the cursor in the given Blender Text object
-
- Returns one of:
- CTX_NORMAL - Cursor is in a normal context
- CTX_SINGLE_QUOTE - Cursor is inside a single quoted string
- CTX_DOUBLE_QUOTE - Cursor is inside a double quoted string
- CTX_COMMENT - Cursor is inside a comment
-
- """
-
- l, cursor = txt.getCursorPos()
- lines = txt.asLines(0, l+1)
-
- # FIXME: This method is too slow in large files for it to be called as often
- # as it is. So for lines below the 1000th line we do this... (quorn)
- if l > 1000: return CTX_NORMAL
-
- # Detect context (in string or comment)
- in_str = CTX_NORMAL
- for line in lines:
- if l == 0:
- end = cursor
- else:
- end = len(line)
- l -= 1
-
- # Comments end at new lines
- if in_str == CTX_COMMENT:
- in_str = CTX_NORMAL
-
- for i in range(end):
- if in_str == 0:
- if line[i] == "'": in_str = CTX_SINGLE_QUOTE
- elif line[i] == '"': in_str = CTX_DOUBLE_QUOTE
- elif line[i] == '#': in_str = CTX_COMMENT
- else:
- if in_str == CTX_SINGLE_QUOTE:
- if line[i] == "'":
- in_str = CTX_NORMAL
- # In again if ' escaped, out again if \ escaped, and so on
- for a in range(i-1, -1, -1):
- if line[a] == '\\': in_str = 1-in_str
- else: break
- elif in_str == CTX_DOUBLE_QUOTE:
- if line[i] == '"':
- in_str = CTX_NORMAL
- # In again if " escaped, out again if \ escaped, and so on
- for a in range(i-1, -1, -1):
- if line[i-a] == '\\': in_str = 2-in_str
- else: break
-
- return in_str
-
-def current_line(txt):
- """Extracts the Python script line at the cursor in the Blender Text object
- provided and cursor position within this line as the tuple pair (line,
- cursor).
- """
-
- lineindex, cursor = txt.getCursorPos()
- lines = txt.asLines()
- line = lines[lineindex]
-
- # Join previous lines to this line if spanning
- i = lineindex - 1
- while i > 0:
- earlier = lines[i].rstrip()
- if earlier.endswith('\\'):
- line = earlier[:-1] + ' ' + line
- cursor += len(earlier)
- i -= 1
-
- # Join later lines while there is an explicit joining character
- i = lineindex
- while i < len(lines)-1 and lines[i].rstrip().endswith('\\'):
- later = lines[i+1].strip()
- line = line + ' ' + later[:-1]
- i += 1
-
- return line, cursor
-
-def get_targets(line, cursor):
- """Parses a period separated string of valid names preceding the cursor and
- returns them as a list in the same order.
- """
-
- brk = 0
- targets = []
- j = cursor
- i = j-1
- while i >= 0:
- if line[i] == ')': brk += 1
- elif brk:
- if line[i] == '(': brk -= 1
- else:
- if line[i] == '.':
- targets.insert(0, line[i+1:j]); j=i
- elif not (line[i].isalnum() or line[i] == '_' or line[i] == '.'):
- break
- i -= 1
- targets.insert(0, line[i+1:j])
- return targets
-
-def get_defs(txt):
- """Returns a dictionary which maps definition names in the source code to
- a list of their parameter names.
-
- The line 'def doit(one, two, three): print one' for example, results in the
- mapping 'doit' : [ 'one', 'two', 'three' ]
- """
-
- return get_cached_descriptor(txt).defs
-
-def get_vars(txt):
- """Returns a dictionary of variable names found in the specified Text
- object. This method locates all names followed directly by an equal sign:
- 'a = ???' or indirectly as part of a tuple/list assignment or inside a
- 'for ??? in ???:' block.
- """
-
- return get_cached_descriptor(txt).vars
-
-def get_imports(txt):
- """Returns a dictionary which maps symbol names in the source code to their
- respective modules.
-
- The line 'from Blender import Text as BText' for example, results in the
- mapping 'BText' : <module 'Blender.Text' (built-in)>
-
- Note that this method imports the modules to provide this mapping as as such
- will execute any initilization code found within.
- """
-
- return get_cached_descriptor(txt).imports
-
-def get_builtins():
- """Returns a dictionary of built-in modules, functions and variables."""
-
- return __builtin__.__dict__
-
-
-#################################
-## Debugging utility functions ##
-#################################
-
-def print_cache_for(txt, period=sys.maxint):
- """Prints out the data cached for a given Text object. If no period is
- given the text will not be reparsed and the cached version will be returned.
- Otherwise if the period has expired the text will be reparsed.
- """
-
- desc = get_cached_descriptor(txt, period)
- print '================================================'
- print 'Name:', desc.name, '('+str(hash(txt))+')'
- print '------------------------------------------------'
- print 'Defs:'
- for name, ddesc in desc.defs.items():
- print ' ', name, ddesc.params, ddesc.lineno
- print ' ', ddesc.doc
- print '------------------------------------------------'
- print 'Vars:'
- for name, vdesc in desc.vars.items():
- print ' ', name, vdesc.type, vdesc.lineno
- print '------------------------------------------------'
- print 'Imports:'
- for name, item in desc.imports.items():
- print ' ', name.ljust(15), item
- print '------------------------------------------------'
- print 'Classes:'
- for clsnme, clsdsc in desc.classes.items():
- print ' *********************************'
- print ' Name:', clsnme
- print ' ', clsdsc.doc
- print ' ---------------------------------'
- print ' Defs:'
- for name, ddesc in clsdsc.defs.items():
- print ' ', name, ddesc.params, ddesc.lineno
- print ' ', ddesc.doc
- print ' ---------------------------------'
- print ' Vars:'
- for name, vdesc in clsdsc.vars.items():
- print ' ', name, vdesc.type, vdesc.lineno
- print ' *********************************'
- print '================================================'
diff --git a/release/scripts/bpymodules/dxfLibrary.py b/release/scripts/bpymodules/dxfLibrary.py
deleted file mode 100644
index 96caa50cc41..00000000000
--- a/release/scripts/bpymodules/dxfLibrary.py
+++ /dev/null
@@ -1,715 +0,0 @@
-#dxfLibrary.py : provides functions for generating DXF files
-# --------------------------------------------------------------------------
-__version__ = "v1.28beta - 2008.12.13"
-__author__ = "Stani Michiels(Stani), Remigiusz Fiedler(migius)"
-__license__ = "GPL"
-__url__ = "http://wiki.blender.org/index.php/Scripts/Manual/Export/autodesk_dxf"
-__bpydoc__ ="""The library to export geometry data to DXF format r12 version.
-
-Copyright %s
-Version %s
-License %s
-Homepage %s
-
-See the homepage for documentation.
-Dedicated thread on BlenderArtists: http://blenderartists.org/forum/showthread.php?t=136439
-
-IDEAs:
--
-
-TODO:
-- add support for SPLINEs
-
-History
-v1.28 - 2008.12.13 by Steeve/BlenderArtists
-- bugfix for EXTMIN/EXTMAX to suit Cycas-CAD
-v1.27 - 2008.10.07 by migius
-- beautifying output code: keys whitespace prefix
-- refactoring DXF-strings format: NewLine moved to the end of
-v1.26 - 2008.10.05 by migius
-- modif POLYLINE to support POLYFACE
-v1.25 - 2008.09.28 by migius
-- modif FACE class for r12
-v1.24 - 2008.09.27 by migius
-- modif POLYLINE class for r12
-- changing output format from r9 to r12(AC1009)
-v1.1 (20/6/2005) by www.stani.be/python/sdxf
-- Python library to generate dxf drawings
-______________________________________________________________
-""" % (__author__,__version__,__license__,__url__)
-
-# --------------------------------------------------------------------------
-# DXF Library: copyright (C) 2005 by Stani Michiels (AKA Stani)
-# 2008 modif by Remigiusz Fiedler (AKA migius)
-# --------------------------------------------------------------------------
-# ***** BEGIN GPL LICENSE BLOCK *****
-#
-# This program is free software; you can redistribute it and/or
-# modify it under the terms of the GNU General Public License
-# as published by the Free Software Foundation; either version 2
-# of the License, or (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software Foundation,
-# Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
-#
-# ***** END GPL LICENCE BLOCK *****
-
-
-#import Blender
-#from Blender import Mathutils, Window, Scene, sys, Draw
-#import BPyMessages
-
-try:
- import copy
- #from struct import pack
-except:
- copy = None
-
-####1) Private (only for developpers)
-_HEADER_POINTS=['insbase','extmin','extmax']
-
-#---helper functions-----------------------------------
-def _point(x,index=0):
- """Convert tuple to a dxf point"""
- #print 'deb: _point=', x #-------------
- return '\n'.join([' %s\n%s'%((i+1)*10+index,x[i]) for i in range(len(x))])
-
-def _points(plist):
- """Convert a list of tuples to dxf points"""
- out = '\n'.join([_point(plist[i],i)for i in range(len(plist))])
- #print 'deb: points=\n', out #-------------------
- return out
-
-#---base classes----------------------------------------
-class _Call:
- """Makes a callable class."""
- def copy(self):
- """Returns a copy."""
- return copy.deepcopy(self)
-
- def __call__(self,**attrs):
- """Returns a copy with modified attributes."""
- copied=self.copy()
- for attr in attrs:setattr(copied,attr,attrs[attr])
- return copied
-
-#-------------------------------------------------------
-class _Entity(_Call):
- """Base class for _common group codes for entities."""
- def __init__(self,color=None,extrusion=None,layer='0',
- lineType=None,lineTypeScale=None,lineWeight=None,
- thickness=None,parent=None):
- """None values will be omitted."""
- self.color = color
- self.extrusion = extrusion
- self.layer = layer
- self.lineType = lineType
- self.lineTypeScale = lineTypeScale
- self.lineWeight = lineWeight
- self.thickness = thickness
- self.parent = parent
-
- def _common(self):
- """Return common group codes as a string."""
- if self.parent:parent=self.parent
- else:parent=self
- result =''
- if parent.layer!=None: result+=' 8\n%s\n'%parent.layer
- if parent.color!=None: result+=' 62\n%s\n'%parent.color
- if parent.extrusion!=None: result+='%s\n'%_point(parent.extrusion,200)
- if parent.lineType!=None: result+=' 6\n%s\n'%parent.lineType
- #TODO: if parent.lineWeight!=None: result+='370\n%s\n'%parent.lineWeight
- if parent.lineTypeScale!=None: result+=' 48\n%s\n'%parent.lineTypeScale
- if parent.thickness!=None: result+=' 39\n%s\n'%parent.thickness
- return result
-
-#--------------------------
-class _Entities:
- """Base class to deal with composed objects."""
- def __dxf__(self):
- return []
-
- def __str__(self):
- return ''.join([str(x) for x in self.__dxf__()])
-
-#--------------------------
-class _Collection(_Call):
- """Base class to expose entities methods to main object."""
- def __init__(self,entities=[]):
- self.entities=copy.copy(entities)
- #link entities methods to drawing
- for attr in dir(self.entities):
- if attr[0]!='_':
- attrObject=getattr(self.entities,attr)
- if callable(attrObject):
- setattr(self,attr,attrObject)
-
-####2) Constants
-#---color values
-BYBLOCK=0
-BYLAYER=256
-
-#---block-type flags (bit coded values, may be combined):
-ANONYMOUS =1 # This is an anonymous block generated by hatching, associative dimensioning, other internal operations, or an application
-NON_CONSTANT_ATTRIBUTES =2 # This block has non-constant attribute definitions (this bit is not set if the block has any attribute definitions that are constant, or has no attribute definitions at all)
-XREF =4 # This block is an external reference (xref)
-XREF_OVERLAY =8 # This block is an xref overlay
-EXTERNAL =16 # This block is externally dependent
-RESOLVED =32 # This is a resolved external reference, or dependent of an external reference (ignored on input)
-REFERENCED =64 # This definition is a referenced external reference (ignored on input)
-
-#---mtext flags
-#attachment point
-TOP_LEFT = 1
-TOP_CENTER = 2
-TOP_RIGHT = 3
-MIDDLE_LEFT = 4
-MIDDLE_CENTER = 5
-MIDDLE_RIGHT = 6
-BOTTOM_LEFT = 7
-BOTTOM_CENTER = 8
-BOTTOM_RIGHT = 9
-#drawing direction
-LEFT_RIGHT = 1
-TOP_BOTTOM = 3
-BY_STYLE = 5 #the flow direction is inherited from the associated text style
-#line spacing style (optional):
-AT_LEAST = 1 #taller characters will override
-EXACT = 2 #taller characters will not override
-
-#---polyline flags
-CLOSED =1 # This is a closed polyline (or a polygon mesh closed in the M direction)
-CURVE_FIT =2 # Curve-fit vertices have been added
-SPLINE_FIT =4 # Spline-fit vertices have been added
-POLYLINE_3D =8 # This is a 3D polyline
-POLYGON_MESH =16 # This is a 3D polygon mesh
-CLOSED_N =32 # The polygon mesh is closed in the N direction
-POLYFACE_MESH =64 # The polyline is a polyface mesh
-CONTINOUS_LINETYPE_PATTERN =128 # The linetype pattern is generated continuously around the vertices of this polyline
-
-#---text flags
-#horizontal
-LEFT = 0
-CENTER = 1
-RIGHT = 2
-ALIGNED = 3 #if vertical alignment = 0
-MIDDLE = 4 #if vertical alignment = 0
-FIT = 5 #if vertical alignment = 0
-#vertical
-BASELINE = 0
-BOTTOM = 1
-MIDDLE = 2
-TOP = 3
-
-####3) Classes
-#---entitities -----------------------------------------------
-#--------------------------
-class Arc(_Entity):
- """Arc, angles in degrees."""
- def __init__(self,center=(0,0,0),radius=1,
- startAngle=0.0,endAngle=90,**common):
- """Angles in degrees."""
- _Entity.__init__(self,**common)
- self.center=center
- self.radius=radius
- self.startAngle=startAngle
- self.endAngle=endAngle
- def __str__(self):
- return ' 0\nARC\n%s%s\n 40\n%s\n 50\n%s\n 51\n%s\n'%\
- (self._common(),_point(self.center),
- self.radius,self.startAngle,self.endAngle)
-
-#-----------------------------------------------
-class Circle(_Entity):
- """Circle"""
- def __init__(self,center=(0,0,0),radius=1,**common):
- _Entity.__init__(self,**common)
- self.center=center
- self.radius=radius
- def __str__(self):
- return ' 0\nCIRCLE\n%s%s\n 40\n%s\n'%\
- (self._common(),_point(self.center),self.radius)
-
-#-----------------------------------------------
-class Face(_Entity):
- """3dface"""
- def __init__(self,points,**common):
- _Entity.__init__(self,**common)
- while len(points)<4: #fix for r12 format
- points.append(points[-1])
- self.points=points
-
- def __str__(self):
- out = ' 0\n3DFACE\n%s%s\n' %(self._common(),_points(self.points))
- #print 'deb:out=', out #-------------------
- return out
-
-#-----------------------------------------------
-class Insert(_Entity):
- """Block instance."""
- def __init__(self,name,point=(0,0,0),
- xscale=None,yscale=None,zscale=None,
- cols=None,colspacing=None,rows=None,rowspacing=None,
- rotation=None,
- **common):
- _Entity.__init__(self,**common)
- self.name=name
- self.point=point
- self.xscale=xscale
- self.yscale=yscale
- self.zscale=zscale
- self.cols=cols
- self.colspacing=colspacing
- self.rows=rows
- self.rowspacing=rowspacing
- self.rotation=rotation
-
- def __str__(self):
- result=' 0\nINSERT\n 2\n%s\n%s\n%s\n'%\
- (self.name,self._common(),_point(self.point))
- if self.xscale!=None:result+=' 41\n%s\n'%self.xscale
- if self.yscale!=None:result+=' 42\n%s\n'%self.yscale
- if self.zscale!=None:result+=' 43\n%s\n'%self.zscale
- if self.rotation:result+=' 50\n%s\n'%self.rotation
- if self.cols!=None:result+=' 70\n%s\n'%self.cols
- if self.colspacing!=None:result+=' 44\n%s\n'%self.colspacing
- if self.rows!=None:result+=' 71\n%s\n'%self.rows
- if self.rowspacing!=None:result+=' 45\n%s\n'%self.rowspacing
- return result
-
-#-----------------------------------------------
-class Line(_Entity):
- """Line"""
- def __init__(self,points,**common):
- _Entity.__init__(self,**common)
- self.points=points
- def __str__(self):
- return ' 0\nLINE\n%s%s\n' %(
- self._common(), _points(self.points))
-
-
-#-----------------------------------------------
-class PolyLine(_Entity):
- def __init__(self,points,org_point=[0,0,0],flag=0,width=None,**common):
- _Entity.__init__(self,**common)
- self.points=points
- self.org_point=org_point
- self.flag=flag
- if self.flag==64:
- self.points=points[0]
- self.faces=points[1]
- self.p_count=len(self.points)
- self.f_count=len(self.faces)
- self.width=width
-
- def __str__(self):
- result= ' 0\nPOLYLINE\n%s 70\n%s\n' %(self._common(),self.flag)
- #print 'deb: self._common()', self._common() #----------
- result+=' 66\n1\n'
- result+='%s\n' %_point(self.org_point)
- if self.flag==64:
- result+=' 71\n%s\n' %self.p_count
- result+=' 72\n%s\n' %self.f_count
- for point in self.points:
- result+=' 0\nVERTEX\n'
- result+=' 8\n%s\n' %self.layer
- result+='%s\n' %_point(point)
- if self.flag==64: result+=' 70\n192\n'
- if self.width: result+=' 40\n%s\n 41\n%s\n' %(self.width,self.width)
- if self.flag==64:
- for face in self.faces:
- result+=' 0\nVERTEX\n'
- result+=' 8\n%s\n' %self.layer
- result+='%s\n' %_point(self.org_point)
- result+=' 70\n128\n'
- result+=' 71\n%s\n' %face[0]
- result+=' 72\n%s\n' %face[1]
- result+=' 73\n%s\n' %face[2]
- if len(face)==4: result+=' 74\n%s\n' %face[3]
- result+=' 0\nSEQEND\n'
- result+=' 8\n%s\n' %self.layer
- return result
-
-#-----------------------------------------------
-class Point(_Entity):
- """Point."""
- def __init__(self,points=None,**common):
- _Entity.__init__(self,**common)
- self.points=points
- def __str__(self): #TODO:
- return ' 0\nPOINT\n%s%s\n' %(self._common(),
- _points(self.points)
- )
-
-#-----------------------------------------------
-class Solid(_Entity):
- """Colored solid fill."""
- def __init__(self,points=None,**common):
- _Entity.__init__(self,**common)
- self.points=points
- def __str__(self):
- return ' 0\nSOLID\n%s%s\n' %(self._common(),
- _points(self.points[:2]+[self.points[3],self.points[2]])
- )
-
-
-#-----------------------------------------------
-class Text(_Entity):
- """Single text line."""
- def __init__(self,text='',point=(0,0,0),alignment=None,
- flag=None,height=1,justifyhor=None,justifyver=None,
- rotation=None,obliqueAngle=None,style=None,xscale=None,**common):
- _Entity.__init__(self,**common)
- self.text=text
- self.point=point
- self.alignment=alignment
- self.flag=flag
- self.height=height
- self.justifyhor=justifyhor
- self.justifyver=justifyver
- self.rotation=rotation
- self.obliqueAngle=obliqueAngle
- self.style=style
- self.xscale=xscale
- def __str__(self):
- result= ' 0\nTEXT\n%s%s\n 40\n%s\n 1\n%s\n'%\
- (self._common(),_point(self.point),self.height,self.text)
- if self.rotation: result+=' 50\n%s\n'%self.rotation
- if self.xscale: result+=' 41\n%s\n'%self.xscale
- if self.obliqueAngle: result+=' 51\n%s\n'%self.obliqueAngle
- if self.style: result+=' 7\n%s\n'%self.style
- if self.flag: result+=' 71\n%s\n'%self.flag
- if self.justifyhor: result+=' 72\n%s\n'%self.justifyhor
- #TODO: if self.alignment: result+='%s\n'%_point(self.alignment,1)
- if self.justifyver: result+=' 73\n%s\n'%self.justifyver
- return result
-
-#-----------------------------------------------
-class Mtext(Text):
- """Surrogate for mtext, generates some Text instances."""
- def __init__(self,text='',point=(0,0,0),width=250,spacingFactor=1.5,down=0,spacingWidth=None,**options):
- Text.__init__(self,text=text,point=point,**options)
- if down:spacingFactor*=-1
- self.spacingFactor=spacingFactor
- self.spacingWidth=spacingWidth
- self.width=width
- self.down=down
- def __str__(self):
- texts=self.text.replace('\r\n','\n').split('\n')
- if not self.down:texts.reverse()
- result=''
- x=y=0
- if self.spacingWidth:spacingWidth=self.spacingWidth
- else:spacingWidth=self.height*self.spacingFactor
- for text in texts:
- while text:
- result+='%s\n'%Text(text[:self.width],
- point=(self.point[0]+x*spacingWidth,
- self.point[1]+y*spacingWidth,
- self.point[2]),
- alignment=self.alignment,flag=self.flag,height=self.height,
- justifyhor=self.justifyhor,justifyver=self.justifyver,
- rotation=self.rotation,obliqueAngle=self.obliqueAngle,
- style=self.style,xscale=self.xscale,parent=self
- )
- text=text[self.width:]
- if self.rotation:x+=1
- else:y+=1
- return result[1:]
-
-#-----------------------------------------------
-##class _Mtext(_Entity):
-## """Mtext not functioning for minimal dxf."""
-## def __init__(self,text='',point=(0,0,0),attachment=1,
-## charWidth=None,charHeight=1,direction=1,height=100,rotation=0,
-## spacingStyle=None,spacingFactor=None,style=None,width=100,
-## xdirection=None,**common):
-## _Entity.__init__(self,**common)
-## self.text=text
-## self.point=point
-## self.attachment=attachment
-## self.charWidth=charWidth
-## self.charHeight=charHeight
-## self.direction=direction
-## self.height=height
-## self.rotation=rotation
-## self.spacingStyle=spacingStyle
-## self.spacingFactor=spacingFactor
-## self.style=style
-## self.width=width
-## self.xdirection=xdirection
-## def __str__(self):
-## input=self.text
-## text=''
-## while len(input)>250:
-## text+='3\n%s\n'%input[:250]
-## input=input[250:]
-## text+='1\n%s\n'%input
-## result= '0\nMTEXT\n%s\n%s\n40\n%s\n41\n%s\n71\n%s\n72\n%s%s\n43\n%s\n50\n%s\n'%\
-## (self._common(),_point(self.point),self.charHeight,self.width,
-## self.attachment,self.direction,text,
-## self.height,
-## self.rotation)
-## if self.style:result+='7\n%s\n'%self.style
-## if self.xdirection:result+='%s\n'%_point(self.xdirection,1)
-## if self.charWidth:result+='42\n%s\n'%self.charWidth
-## if self.spacingStyle:result+='73\n%s\n'%self.spacingStyle
-## if self.spacingFactor:result+='44\n%s\n'%self.spacingFactor
-## return result
-
-#---tables ---------------------------------------------------
-#-----------------------------------------------
-class Block(_Collection):
- """Use list methods to add entities, eg append."""
- def __init__(self,name,layer='0',flag=0,base=(0,0,0),entities=[]):
- self.entities=copy.copy(entities)
- _Collection.__init__(self,entities)
- self.layer=layer
- self.name=name
- self.flag=0
- self.base=base
- def __str__(self): #TODO:
- e=''.join([str(x)for x in self.entities])
- return ' 0\nBLOCK\n 8\n%s\n 2\n%s\n 70\n%s\n%s\n 3\n%s\n%s 0\nENDBLK\n'%\
- (self.layer,self.name.upper(),self.flag,_point(self.base),self.name.upper(),e)
-
-#-----------------------------------------------
-class Layer(_Call):
- """Layer"""
- def __init__(self,name='pydxf',color=7,lineType='continuous',flag=64):
- self.name=name
- self.color=color
- self.lineType=lineType
- self.flag=flag
- def __str__(self):
- return ' 0\nLAYER\n 2\n%s\n 70\n%s\n 62\n%s\n 6\n%s\n'%\
- (self.name.upper(),self.flag,self.color,self.lineType)
-
-#-----------------------------------------------
-class LineType(_Call):
- """Custom linetype"""
- def __init__(self,name='continuous',description='Solid line',elements=[],flag=64):
- # TODO: Implement lineType elements
- self.name=name
- self.description=description
- self.elements=copy.copy(elements)
- self.flag=flag
- def __str__(self):
- return ' 0\nLTYPE\n 2\n%s\n 70\n%s\n 3\n%s\n 72\n65\n 73\n%s\n 40\n0.0\n'%\
- (self.name.upper(),self.flag,self.description,len(self.elements))
-
-#-----------------------------------------------
-class Style(_Call):
- """Text style"""
- def __init__(self,name='standard',flag=0,height=0,widthFactor=40,obliqueAngle=50,
- mirror=0,lastHeight=1,font='arial.ttf',bigFont=''):
- self.name=name
- self.flag=flag
- self.height=height
- self.widthFactor=widthFactor
- self.obliqueAngle=obliqueAngle
- self.mirror=mirror
- self.lastHeight=lastHeight
- self.font=font
- self.bigFont=bigFont
- def __str__(self):
- return ' 0\nSTYLE\n 2\n%s\n 70\n%s\n 40\n%s\n 41\n%s\n 50\n%s\n 71\n%s\n 42\n%s\n 3\n%s\n 4\n%s\n'%\
- (self.name.upper(),self.flag,self.flag,self.widthFactor,
- self.obliqueAngle,self.mirror,self.lastHeight,
- self.font.upper(),self.bigFont.upper())
-
-#-----------------------------------------------
-class View(_Call):
- def __init__(self,name,flag=0,width=1,height=1,center=(0.5,0.5),
- direction=(0,0,1),target=(0,0,0),lens=50,
- frontClipping=0,backClipping=0,twist=0,mode=0):
- self.name=name
- self.flag=flag
- self.width=width
- self.height=height
- self.center=center
- self.direction=direction
- self.target=target
- self.lens=lens
- self.frontClipping=frontClipping
- self.backClipping=backClipping
- self.twist=twist
- self.mode=mode
- def __str__(self):
- return ' 0\nVIEW\n 2\n%s\n 70\n%s\n 40\n%s\n%s\n 41\n%s\n%s\n%s\n 42\n%s\n 43\n%s\n 44\n%s\n 50\n%s\n 71\n%s\n'%\
- (self.name,self.flag,self.height,_point(self.center),self.width,
- _point(self.direction,1),_point(self.target,2),self.lens,
- self.frontClipping,self.backClipping,self.twist,self.mode)
-
-#-----------------------------------------------
-def ViewByWindow(name,leftBottom=(0,0),rightTop=(1,1),**options):
- width=abs(rightTop[0]-leftBottom[0])
- height=abs(rightTop[1]-leftBottom[1])
- center=((rightTop[0]+leftBottom[0])*0.5,(rightTop[1]+leftBottom[1])*0.5)
- return View(name=name,width=width,height=height,center=center,**options)
-
-#---drawing
-#-----------------------------------------------
-class Drawing(_Collection):
- """Dxf drawing. Use append or any other list methods to add objects."""
- def __init__(self,insbase=(0.0,0.0,0.0),extmin=(0.0,0.0,0.0),extmax=(0.0,0.0,0.0),
- layers=[Layer()],linetypes=[LineType()],styles=[Style()],blocks=[],
- views=[],entities=None,fileName='test.dxf'):
- # TODO: replace list with None,arial
- if not entities:
- entities=[]
- _Collection.__init__(self,entities)
- self.insbase=insbase
- self.extmin=extmin
- self.extmax=extmax
- self.layers=copy.copy(layers)
- self.linetypes=copy.copy(linetypes)
- self.styles=copy.copy(styles)
- self.views=copy.copy(views)
- self.blocks=copy.copy(blocks)
- self.fileName=fileName
- #private
- #self.acadver='9\n$ACADVER\n1\nAC1006\n'
- self.acadver=' 9\n$ACADVER\n 1\nAC1009\n'
- """DXF AutoCAD-Release format codes
- AC1021 2008, 2007
- AC1018 2006, 2005, 2004
- AC1015 2002, 2000i, 2000
- AC1014 R14,14.01
- AC1012 R13
- AC1009 R12,11
- AC1006 R10
- AC1004 R9
- AC1002 R2.6
- AC1.50 R2.05
- """
-
- def _name(self,x):
- """Helper function for self._point"""
- return ' 9\n$%s\n' %x.upper()
-
- def _point(self,name,x):
- """Point setting from drawing like extmin,extmax,..."""
- return '%s%s' %(self._name(name),_point(x))
-
- def _section(self,name,x):
- """Sections like tables,blocks,entities,..."""
- if x: xstr=''.join(x)
- else: xstr=''
- return ' 0\nSECTION\n 2\n%s\n%s 0\nENDSEC\n'%(name.upper(),xstr)
-
- def _table(self,name,x):
- """Tables like ltype,layer,style,..."""
- if x: xstr=''.join(x)
- else: xstr=''
- return ' 0\nTABLE\n 2\n%s\n 70\n%s\n%s 0\nENDTAB\n'%(name.upper(),len(x),xstr)
-
- def __str__(self):
- """Returns drawing as dxf string."""
- header=[self.acadver]+[self._point(attr,getattr(self,attr))+'\n' for attr in _HEADER_POINTS]
- header=self._section('header',header)
-
- tables=[self._table('ltype',[str(x) for x in self.linetypes]),
- self._table('layer',[str(x) for x in self.layers]),
- self._table('style',[str(x) for x in self.styles]),
- self._table('view',[str(x) for x in self.views]),
- ]
- tables=self._section('tables',tables)
-
- blocks=self._section('blocks',[str(x) for x in self.blocks])
-
- entities=self._section('entities',[str(x) for x in self.entities])
-
- all=''.join([header,tables,blocks,entities,' 0\nEOF\n'])
- return all
-
- def saveas(self,fileName):
- self.fileName=fileName
- self.save()
-
- def save(self):
- test=open(self.fileName,'w')
- test.write(str(self))
- test.close()
-
-
-#---extras
-#-----------------------------------------------
-class Rectangle(_Entity):
- """Rectangle, creates lines."""
- def __init__(self,point=(0,0,0),width=1,height=1,solid=None,line=1,**common):
- _Entity.__init__(self,**common)
- self.point=point
- self.width=width
- self.height=height
- self.solid=solid
- self.line=line
- def __str__(self):
- result=''
- points=[self.point,(self.point[0]+self.width,self.point[1],self.point[2]),
- (self.point[0]+self.width,self.point[1]+self.height,self.point[2]),
- (self.point[0],self.point[1]+self.height,self.point[2]),self.point]
- if self.solid:
- result+= Solid(points=points[:-1],parent=self.solid)
- if self.line:
- for i in range(4):
- result+= Line(points=[points[i],points[i+1]],parent=self)
- return result[1:]
-
-#-----------------------------------------------
-class LineList(_Entity):
- """Like polyline, but built of individual lines."""
- def __init__(self,points=[],org_point=[0,0,0],closed=0,**common):
- _Entity.__init__(self,**common)
- self.closed=closed
- self.points=copy.copy(points)
- def __str__(self):
- if self.closed:points=self.points+[self.points[0]]
- else: points=self.points
- result=''
- for i in range(len(points)-1):
- result+= Line(points=[points[i],points[i+1]],parent=self)
- return result[1:]
-
-#-----------------------------------------------------
-def test():
- #Blocks
- b=Block('test')
- b.append(Solid(points=[(0,0,0),(1,0,0),(1,1,0),(0,1,0)],color=1))
- b.append(Arc(center=(1,0,0),color=2))
-
- #Drawing
- d=Drawing()
- #tables
- d.blocks.append(b) #table blocks
- d.styles.append(Style()) #table styles
- d.views.append(View('Normal')) #table view
- d.views.append(ViewByWindow('Window',leftBottom=(1,0),rightTop=(2,1))) #idem
-
- #entities
- d.append(Circle(center=(1,1,0),color=3))
- d.append(Face(points=[(0,0,0),(1,0,0),(1,1,0),(0,1,0)],color=4))
- d.append(Insert('test',point=(3,3,3),cols=5,colspacing=2))
- d.append(Line(points=[(0,0,0),(1,1,1)]))
- d.append(Mtext('Click on Ads\nmultiple lines with mtext',point=(1,1,1),color=5,rotation=90))
- d.append(Text('Please donate!',point=(3,0,1)))
- d.append(Rectangle(point=(2,2,2),width=4,height=3,color=6,solid=Solid(color=2)))
- d.append(Solid(points=[(4,4,0),(5,4,0),(7,8,0),(9,9,0)],color=3))
- d.append(PolyLine(points=[(1,1,1),(2,1,1),(2,2,1),(1,2,1)],closed=1,color=1))
-
- #d.saveas('c:\\test.dxf')
- d.saveas('test.dxf')
-
-
-#-----------------------------------------------------
-if __name__=='__main__':
- if not copy:
- Draw.PupMenu('Error%t|This script requires a full python install')
- main()
- \ No newline at end of file
diff --git a/release/scripts/bvh_import.py b/release/scripts/bvh_import.py
index 5cdd8a71231..2093ac109f7 100644
--- a/release/scripts/bvh_import.py
+++ b/release/scripts/bvh_import.py
@@ -231,7 +231,7 @@ def read_bvh(file_path, GLOBAL_SCALE=1.0):
bvh_nodes_list= bvh_nodes.values()
- while lineIdx < len(file_lines):
+ while lineIdx < len(file_lines) -1:
line= file_lines[lineIdx]
for bvh_node in bvh_nodes_list:
#for bvh_node in bvh_nodes_serial:
@@ -726,7 +726,7 @@ def load_bvh_ui(file, PREF_UI= True):
Blender.Window.WaitCursor(1)
# Get the BVH data and act on it.
t1= Blender.sys.time()
- print '\tparsing bvh...',
+ print '\tpassing bvh...',
bvh_nodes= read_bvh(file, IMPORT_SCALE)
print '%.4f' % (Blender.sys.time()-t1)
t1= Blender.sys.time()
diff --git a/release/scripts/c3d_import.py b/release/scripts/c3d_import.py
index bfe691c394c..ca4f8cd79e9 100644
--- a/release/scripts/c3d_import.py
+++ b/release/scripts/c3d_import.py
@@ -1,5 +1,5 @@
#!BPY
-# -*- coding: latin-1 -*-
+
"""
Name: 'Motion Capture (.c3d)...'
Blender: 246
diff --git a/release/scripts/config.py b/release/scripts/config.py
index cbf8e272b91..4251bad8654 100644
--- a/release/scripts/config.py
+++ b/release/scripts/config.py
@@ -246,10 +246,6 @@ information about how to fix this.
fields = fields[2].split()
if len(fields) > 1:
fname = fields[1].split(sep)[-1]
- i = 1
- while not fname.endswith('.py'):
- i += 1
- fname = "%s %s" % (fname, fields[i])
ALL_SCRIPTS[fname] = (menuname, group_len - 1)
return True
diff --git a/release/scripts/console.py b/release/scripts/console.py
index 0e46f41f581..9a18c724d47 100644
--- a/release/scripts/console.py
+++ b/release/scripts/console.py
@@ -67,8 +67,6 @@ __FONT_SIZE__ = 2 # index for the list above, normal default.
global __CONSOLE_LINE_OFFSET__
__CONSOLE_LINE_OFFSET__ = 0
-cmdBuffer = [] # dosnt need to be global
-
'''
# Generic Blender functions
def getActScriptWinRect():
@@ -161,13 +159,19 @@ def include(filename):
return compile(filedata, filename, 'exec')
# Writes command line data to a blender text file.
-def writeCmdData(type):
+def writeCmdData(cmdLineList, type):
+ if type == 3:
+ typeList = [0,1,2, 3, None] # all
+ else:
+ typeList = [type] # so we can use athe lists 'in' methiod
+
newText = Text.New('command_output.py', 1)
- if type == 3: newText.write('\n'.join( [ myCmd.cmd for myCmd in cmdBuffer ] ))
- else: newText.write('\n'.join( [ myCmd.cmd for myCmd in cmdBuffer if myCmd.type is type] ))
+ for myCmd in cmdLineList:
+ if myCmd.type in typeList: # user input
+ newText.write('%s\n' % myCmd.cmd)
Draw.PupMenu('%s written' % newText.name)
-def insertCmdData():
+def insertCmdData(cmdBuffer):
texts = list(bpy.data.texts)
textNames = [tex.name for tex in texts]
if textNames:
@@ -333,6 +337,7 @@ def handle_event(evt, val):
# Insert Char into the cammand line
def insCh(ch): # Instert a char
+ global cmdBuffer
global cursor
# Later account for a cursor variable
cmdBuffer[-1].cmd = ('%s%s%s' % ( cmdBuffer[-1].cmd[:cursor], ch, cmdBuffer[-1].cmd[cursor:]))
@@ -341,7 +346,7 @@ def handle_event(evt, val):
# Define Complex Key Actions #
#------------------------------------------------------------------------------#
def actionEnterKey():
- global histIndex, cursor
+ global histIndex, cursor, cmdBuffer
def getIndent(string):
# Gather white space to add in the previous line
@@ -407,20 +412,14 @@ def handle_event(evt, val):
# Clear the output based on __LINE_HISTORY__
if len(cmdBuffer) > __LINE_HISTORY__:
- cmdBuffer[:__LINE_HISTORY__] = []
+ cmdBuffer = cmdBuffer[-__LINE_HISTORY__:]
histIndex = cursor = -1 # Reset cursor and history
def actionUpKey():
- global histIndex
+ global histIndex, cmdBuffer
if abs(histIndex)+1 >= len(cmdBuffer):
histIndex = -1
-
- # When wrapping allow 1 plank lines
- if cmdBuffer[-1].cmd != ' ':
- cmdBuffer[-1].cmd = ' '
- return
-
histIndex_orig = histIndex
histIndex -= 1
@@ -432,15 +431,9 @@ def handle_event(evt, val):
cmdBuffer[-1].cmd = cmdBuffer[histIndex].cmd
def actionDownKey():
- global histIndex
+ global histIndex, cmdBuffer
if histIndex >= -2:
histIndex = -len(cmdBuffer)
-
- # When wrapping allow 1 plank lines
- if cmdBuffer[-1].cmd != ' ':
- cmdBuffer[-1].cmd = ' '
- return
-
histIndex_orig = histIndex
histIndex += 1
while (cmdBuffer[histIndex].type != 0 and histIndex != -2) or \
@@ -453,18 +446,18 @@ def handle_event(evt, val):
def actionRightMouse():
global __FONT_SIZE__
- choice = Draw.PupMenu('Console Menu%t|Write Input Data (white)|Write Output Data (blue)|Write Error Data (red)|Write All Text|%l|Insert Blender text|%l|Font Size|%l|Clear Output|Quit')
+ choice = Draw.PupMenu('Console Menu%t|Write Input Data (white)|Write Output Data (blue)|Write Error Data (red)|Write All Text|%l|Insert Blender text|%l|Font Size|%l|Quit')
if choice == 1:
- writeCmdData(0) # type 0 user
+ writeCmdData(cmdBuffer, 0) # type 0 user
elif choice == 2:
- writeCmdData(1) # type 1 user output
+ writeCmdData(cmdBuffer, 1) # type 1 user output
elif choice == 3:
- writeCmdData(2) # type 2 errors
+ writeCmdData(cmdBuffer, 2) # type 2 errors
elif choice == 4:
- writeCmdData(3) # All
+ writeCmdData(cmdBuffer, 3) # All
elif choice == 6:
- insertCmdData() # Insert text from Blender and run it.
+ insertCmdData(cmdBuffer) # Insert text from Blender and run it.
elif choice == 8:
# Fontsize.
font_choice = Draw.PupMenu('Font Size%t|Large|Normal|Small|Tiny')
@@ -478,10 +471,8 @@ def handle_event(evt, val):
elif font_choice == 4:
__FONT_SIZE__ = 0
Draw.Redraw()
- elif choice == 10: # Clear all output
- cmdBuffer[:] = [cmd for cmd in cmdBuffer if cmd.type == 0] # keep user input
- Draw.Redraw()
- elif choice == 11: # Exit
+
+ elif choice == 10: # Exit
Draw.Exit()
@@ -792,6 +783,7 @@ __CONSOLE_VAR_DICT__ = {} # Initialize var dict
# Print Startup lines, add __bpydoc__ to the console startup.
+cmdBuffer = []
for l in __bpydoc__.split('<br>'):
cmdBuffer.append( cmdLine(l, 1, None) )
@@ -835,19 +827,12 @@ def include_console(includeFile):
def standard_imports():
# Write local to global __CONSOLE_VAR_DICT__ for reuse,
-
- exec('%s%s' % ('__CONSOLE_VAR_DICT__["bpy"]=', 'bpy'))
- exec('%s%s' % ('__CONSOLE_VAR_DICT__["Blender"]=', 'Blender'))
-
for ls in (dir(), dir(Blender)):
for __TMP_VAR_NAME__ in ls:
# Execute the local > global coversion.
exec('%s%s' % ('__CONSOLE_VAR_DICT__[__TMP_VAR_NAME__]=', __TMP_VAR_NAME__))
- # Add dummy imports to input so output scripts to a text file work as expected
- cmdBuffer.append(cmdLine('import bpy', 0, 1))
- cmdBuffer.append(cmdLine('import Blender', 0, 1)) # pretend we have been executed, as we kindof have.
- cmdBuffer.append(cmdLine('from Blender import *', 0, 1))
+ exec('%s%s' % ('__CONSOLE_VAR_DICT__["bpy"]=', 'bpy'))
if scriptDir and console_autoexec:
include_console(console_autoexec) # pass the blender module
diff --git a/release/scripts/export_dxf.py b/release/scripts/export_dxf.py
deleted file mode 100644
index 061e29b81c7..00000000000
--- a/release/scripts/export_dxf.py
+++ /dev/null
@@ -1,407 +0,0 @@
-#!BPY
-
-"""
- Name: 'Autodesk DXF (.dxf)'
- Blender: 247
- Group: 'Export'
- Tooltip: 'Export geometry to DXF-r12 (Drawing eXchange Format).'
-"""
-
-__version__ = "v1.27beta - 2008.10.07"
-__author__ = "Remigiusz Fiedler (AKA migius)"
-__license__ = "GPL"
-__url__ = "http://wiki.blender.org/index.php/Scripts/Manual/Export/autodesk_dxf"
-__bpydoc__ ="""The script exports Blender geometry to DXF format r12 version.
-
-Version %s
-Copyright %s
-License %s
-
-extern dependances: dxfLibrary.py
-
-See the homepage for documentation.
-url: %s
-
-IDEAs:
- - correct normals for POLYLINE-POLYFACE via proper point-order
- - HPGL output for 2d and flattened 3d content
-
-TODO:
-- optimize back-faces removal (probably needs matrix transform)
-- optimize POLYFACE routine: remove double-vertices
-- optimize POLYFACE routine: remove unused vertices
-- support hierarchies: groups, instances, parented structures
-- support 210-code (3d orientation vector)
-- presets for architectural scales
-- write drawing extends for automatic view positioning in CAD
-
-History
-v1.27 - 2008.10.07 by migius
-- exclude Stani's DXF-Library to extern module
-v1.26 - 2008.10.05 by migius
-- add "hidden mode" substitut: back-faces removal
-- add support for mesh ->POLYFACE
-- optimized code for "Flat" procedure
-v1.25 - 2008.09.28 by migius
-- modif FACE class for r12
-- add mesh-polygon -> Bezier-curve converter (Yorik's code)
-- add support for curves ->POLYLINEs
-- add "3d-View to Flat" - geometry projection to XY-plane
-v1.24 - 2008.09.27 by migius
-- add start UI with preferences
-- modif POLYLINE class for r12
-- changing output format from r9 to r12(AC1009)
-v1.23 - 2008.09.26 by migius
-- add finish message-box
-v1.22 - 2008.09.26 by migius
-- add support for curves ->LINEs
-- add support for mesh-edges ->LINEs
-v1.21 - 2008.06.04 by migius
-- initial adaptation for Blender
-v1.1 (20/6/2005) by Stani Michiels www.stani.be/python/sdxf
-- Python library to generate dxf drawings
-______________________________________________________________
-""" % (__author__,__version__,__license__,__url__)
-
-# --------------------------------------------------------------------------
-# Script copyright (C) 2008 Remigiusz Fiedler (AKA migius)
-# --------------------------------------------------------------------------
-# ***** BEGIN GPL LICENSE BLOCK *****
-#
-# This program is free software; you can redistribute it and/or
-# modify it under the terms of the GNU General Public License
-# as published by the Free Software Foundation; either version 2
-# of the License, or (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software Foundation,
-# Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
-#
-# ***** END GPL LICENCE BLOCK *****
-
-
-import Blender
-from Blender import Mathutils, Window, Scene, sys, Draw
-import BPyMessages
-
-#import dxfLibrary
-#reload(dxfLibrary)
-from dxfLibrary import *
-
-
-#-----------------------------------------------------
-def hidden_status(faces, mx_n):
- #print 'HIDDEN_MODE: caution! not full implemented yet'
- ok_faces = []
- ok_edges = []
- #sort out back-faces = with normals pointed away from camera
- for f in faces:
- #print 'deb: face=', f #---------
- # get its normal-vector in localCS
- vec_normal = f.no.copy()
- #print 'deb: vec_normal=', vec_normal #------------------
- #must be transfered to camera/view-CS
- vec_normal *= mx_n
- #vec_normal *= mb.rotationPart()
- #print 'deb:2vec_normal=', vec_normal #------------------
- #vec_normal *= mw0.rotationPart()
- #print 'deb:3vec_normal=', vec_normal, '\n' #------------------
-
- # normal must point the Z direction-hemisphere
- if vec_normal[2] > 0.0 :
- ok_faces.append(f.index)
- for key in f.edge_keys:
- #this test can be done faster with set()
- if key not in ok_edges:
- ok_edges.append(key)
- #print 'deb: amount of visible faces=', len(ok_faces) #---------
- #print 'deb: visible faces=', ok_faces #---------
- #print 'deb: amount of visible edges=', len(ok_edges) #---------
- #print 'deb: visible edges=', ok_edges #---------
- return ok_faces, ok_edges
-
-
-#-----------------------------------------------------
-def projected_co(vec, mw):
- # convert the world coordinates of vector to screen coordinates
- #co = vec.co.copy().resize4D()
- co = vec.copy().resize4D()
- co[3] = 1.0
- sc = co * mw
- #print 'deb: viewprojection=', sc #---------
- return [sc[0],sc[1],0.0]
-
-
-#--------not used---------------------------------------------
-def flatten(points, mw):
- for i,v in enumerate(points):
- v = projected_co(v, mw)
- points[i]=v
- #print 'deb: flatten points=', points #---------
- return points
-
-#-----------------------------------------------------
-def exportMesh(ob, mx, mx_n):
- entities = []
- me = ob.getData(mesh=1)
- #me.transform(mx)
- # above is eventualy faster, but bad, cause
- # directly transforms origin geometry and write back rounding errors
- me_verts = me.verts[:] #we dont want manipulate origin data
- #print 'deb: me_verts=', me_verts #---------
- #me.transform(mx_inv) #counterpart to - back to the origin state
- for v in me_verts:
- v.co *= mx
- faces=[]
- edges=[]
- if HIDDEN_MODE:
- ok_faces, ok_edges = hidden_status(me.faces, mx_n)
-
- #if (not FLATTEN) and len(me.faces)>0 and ONLYFACES:
- if ONLYFACES:
- if POLYFACES: #export 3D as POLYFACEs
- allpoints = []
- allfaces = []
- allpoints = [v.co[:3] for v in me_verts]
- for f in me.faces:
- #print 'deb: face=', f #---------
- if not HIDDEN_MODE or \
- (HIDDEN_MODE and f.index in ok_faces):
- if 1:
- points = f.verts
- face = [p.index+1 for p in points]
- #print 'deb: face=', face #---------
- allfaces.append(face)
- else: #bad, cause create multiple vertex instances
- points = f.verts
- points = [ me_verts[p.index].co[:3] for p in points]
- #points = [p.co[:3] for p in points]
- #print 'deb: points=', points #---------
- index = len(allpoints)+1
- face = [index+i for i in range(len(points))]
- allpoints.extend(points)
- allfaces.append(face)
- if allpoints and allfaces:
- #print 'deb: allpoints=', allpoints #---------
- #print 'deb: allfaces=', allfaces #---------
- dxfPOLYFACE = PolyLine([allpoints, allfaces], flag=64)
- entities.append(dxfPOLYFACE)
- else: #export 3D as 3DFACEs
- for f in me.faces:
- #print 'deb: face=', f #---------
- if not HIDDEN_MODE or \
- (HIDDEN_MODE and f.index in ok_faces):
- points = f.verts
- points = [ me_verts[p.index].co[:3] for p in points]
- #points = [p.co[:3] for p in points]
- #print 'deb: points=', points #---------
- dxfFACE = Face(points)
- entities.append(dxfFACE)
-
- else: #export 3D as LINEs
- if HIDDEN_MODE and len(me.faces)!=0:
- for e in ok_edges:
- points = [ me_verts[key].co[:3] for key in e]
- dxfLINE = Line(points)
- entities.append(dxfLINE)
-
- else:
- for e in me.edges:
- #print 'deb: edge=', e #---------
- points=[]
- #points = [e.v1.co*mx, e.v2.co*mx]
- points = [ me_verts[key].co[:3] for key in e.key]
- #print 'deb: points=', points #---------
- dxfLINE = Line(points)
- entities.append(dxfLINE)
- return entities
-
-
-#-----------------------------------------------------
-def exportCurve(ob, mx):
- entities = []
- curve = ob.getData()
- for cur in curve:
- #print 'deb: START cur=', cur #--------------
- if 1: #not cur.isNurb():
- #print 'deb: START points' #--------------
- points = []
- org_point = [0.0,0.0,0.0]
- for point in cur:
- #print 'deb: point=', point #---------
- if cur.isNurb():
- vec = point[0:3]
- else:
- point = point.getTriple()
- #print 'deb: point=', point #---------
- vec = point[1]
- #print 'deb: vec=', vec #---------
- pkt = Mathutils.Vector(vec) * mx
- #print 'deb: pkt=', pkt #---------
- #pkt *= SCALE_FACTOR
- if 0: #FLATTEN:
- pkt = projected_co(pkt, mw)
- points.append(pkt)
- if cur.isCyclic(): closed = 1
- else: closed = 0
- if len(points)>1:
- #print 'deb: points', points #--------------
- if POLYLINES: dxfPLINE = PolyLine(points,org_point,closed)
- else: dxfPLINE = LineList(points,org_point,closed)
- entities.append(dxfPLINE)
- return entities
-
-#-----------------------------------------------------
-def do_export(sel_group, filepath):
- Window.WaitCursor(1)
- t = sys.time()
-
- #init Drawing ---------------------
- d=Drawing()
- #add Tables -----------------
- #d.blocks.append(b) #table blocks
- d.styles.append(Style()) #table styles
- d.views.append(View('Normal')) #table view
- d.views.append(ViewByWindow('Window',leftBottom=(1,0),rightTop=(2,1))) #idem
-
- #add Entities --------------------
- something_ready = False
- #ViewVector = Mathutils.Vector(Window.GetViewVector())
- #print 'deb: ViewVector=', ViewVector #------------------
- mw0 = Window.GetViewMatrix()
- #mw0 = Window.GetPerspMatrix() #TODO: how get it working?
- mw = mw0.copy()
- if FLATTEN:
- m0 = Mathutils.Matrix()
- m0[2][2]=0.0
- mw *= m0 #flatten ViewMatrix
-
- for ob in sel_group:
- entities = []
- mx = ob.matrix.copy()
- mb = mx.copy()
- #print 'deb: mb =\n', mb #---------
- #print 'deb: mw0 =\n', mw0 #---------
- mx_n = mx.rotationPart() * mw0.rotationPart() #trans-matrix for normal_vectors
- if SCALE_FACTOR!=1.0: mx *= SCALE_FACTOR
- if FLATTEN: mx *= mw
-
- #mx_inv = mx.copy().invert()
- #print 'deb: mx =\n', mx #---------
- #print 'deb: mx_inv=\n', mx_inv #---------
-
- if (ob.type == 'Mesh'):
- entities = exportMesh(ob, mx, mx_n)
- elif (ob.type == 'Curve'):
- entities = exportCurve(ob, mx)
-
- for e in entities:
- d.append(e)
- something_ready = True
-
- if something_ready:
- d.saveas(filepath)
- Window.WaitCursor(0)
- #Draw.PupMenu('DXF Exporter: job finished')
- print 'exported to %s' % filepath
- print 'finished in %.2f seconds' % (sys.time()-t)
- else:
- Window.WaitCursor(0)
- print "Abort: selected objects dont mach choosen export option, nothing exported!"
- Draw.PupMenu('DXF Exporter: nothing exported!|selected objects dont mach choosen export option!')
-
-#----globals------------------------------------------
-ONLYSELECTED = True
-POLYLINES = True
-ONLYFACES = False
-POLYFACES = 1
-FLATTEN = 0
-HIDDEN_MODE = False #filter out hidden lines
-SCALE_FACTOR = 1.0 #optional, can be done later in CAD too
-
-
-
-#-----------------------------------------------------
-def dxf_export_ui(filepath):
- global ONLYSELECTED,\
- POLYLINES,\
- ONLYFACES,\
- POLYFACES,\
- FLATTEN,\
- HIDDEN_MODE,\
- SCALE_FACTOR
-
- print '\n\nDXF-Export %s -----------------------' %__version__
- #filepath = 'blend_test.dxf'
- # Dont overwrite
- if not BPyMessages.Warning_SaveOver(filepath):
- print 'Aborted by user: nothing exported'
- return
- #test():return
-
-
- PREF_ONLYSELECTED= Draw.Create(ONLYSELECTED)
- PREF_POLYLINES= Draw.Create(POLYLINES)
- PREF_ONLYFACES= Draw.Create(ONLYFACES)
- PREF_POLYFACES= Draw.Create(POLYFACES)
- PREF_FLATTEN= Draw.Create(FLATTEN)
- PREF_HIDDEN_MODE= Draw.Create(HIDDEN_MODE)
- PREF_SCALE_FACTOR= Draw.Create(SCALE_FACTOR)
- PREF_HELP= Draw.Create(0)
- block = [\
- ("only selected", PREF_ONLYSELECTED, "export only selected geometry"),\
- ("global Scale:", PREF_SCALE_FACTOR, 0.001, 1000, "set global Scale factor for exporting geometry"),\
- ("only faces", PREF_ONLYFACES, "from mesh-objects export only faces, otherwise only edges"),\
- ("write POLYFACE", PREF_POLYFACES, "export mesh to POLYFACE, otherwise to 3DFACEs"),\
- ("write POLYLINEs", PREF_POLYLINES, "export curve to POLYLINE, otherwise to LINEs"),\
- ("3D-View to Flat", PREF_FLATTEN, "flatten geometry according current 3d-View"),\
- ("Hidden Mode", PREF_HIDDEN_MODE, "filter out hidden lines"),\
- #(''),\
- ("online Help", PREF_HELP, "calls DXF-Exporter Manual Page on Wiki.Blender.org"),\
- ]
-
- if not Draw.PupBlock("DXF-Exporter %s" %__version__[:10], block): return
-
- if PREF_HELP.val!=0:
- try:
- import webbrowser
- webbrowser.open('http://wiki.blender.org/index.php?title=Scripts/Manual/Export/autodesk_dxf')
- except:
- Draw.PupMenu('DXF Exporter: %t|no connection to manual-page on Blender-Wiki! try:|\
-http://wiki.blender.org/index.php?title=Scripts/Manual/Export/autodesk_dxf')
- return
-
- ONLYSELECTED = PREF_ONLYSELECTED.val
- POLYLINES = PREF_POLYLINES.val
- ONLYFACES = PREF_ONLYFACES.val
- POLYFACES = PREF_POLYFACES.val
- FLATTEN = PREF_FLATTEN.val
- HIDDEN_MODE = PREF_HIDDEN_MODE.val
- SCALE_FACTOR = PREF_SCALE_FACTOR.val
-
- sce = Scene.GetCurrent()
- if ONLYSELECTED: sel_group = sce.objects.selected
- else: sel_group = sce.objects
-
- if sel_group: do_export(sel_group, filepath)
- else:
- print "Abort: selection was empty, no object to export!"
- Draw.PupMenu('DXF Exporter: nothing exported!|empty selection!')
- # Timing the script is a good way to be aware on any speed hits when scripting
-
-
-
-#-----------------------------------------------------
-if __name__=='__main__':
- #main()
- if not copy:
- Draw.PupMenu('Error%t|This script requires a full python install')
- Window.FileSelector(dxf_export_ui, 'EXPORT DXF', sys.makename(ext='.dxf'))
-
-
- \ No newline at end of file
diff --git a/release/scripts/export_fbx.py b/release/scripts/export_fbx.py
index ce17f78c5e2..2d8859aa8fb 100644
--- a/release/scripts/export_fbx.py
+++ b/release/scripts/export_fbx.py
@@ -66,6 +66,8 @@ import BPyMesh
import BPySys
import BPyMessages
+import sys
+
## This was used to make V, but faster not to do all that
##valid = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_,.()[]{}'
##v = range(255)
@@ -182,19 +184,7 @@ def sane_texname(data): return sane_name(data, sane_name_mapping_tex)
def sane_takename(data): return sane_name(data, sane_name_mapping_take)
def sane_groupname(data): return sane_name(data, sane_name_mapping_group)
-def derived_paths(fname_orig, basepath, FORCE_CWD=False):
- '''
- fname_orig - blender path, can be relative
- basepath - fname_rel will be relative to this
- FORCE_CWD - dont use the basepath, just add a ./ to the filename.
- use when we know the file will be in the basepath.
- '''
- fname = Blender.sys.expandpath(fname_orig)
- fname_strip = strip_path(fname)
- if FORCE_CWD: fname_rel = '.' + Blender.sys.sep + fname_strip
- else: fname_rel = Blender.sys.relpath(fname, basepath)
- if fname_rel.startswith('//'): fname_rel = '.' + Blender.sys.sep + fname_rel[2:]
- return fname, fname_strip, fname_rel
+
def mat4x4str(mat):
@@ -352,8 +342,6 @@ def write(filename, batch_objects = None, \
# end batch support
- # Use this for working out paths relative to the export location
- basepath = Blender.sys.dirname(filename)
# ----------------------------------------------
# storage classes
@@ -1153,9 +1141,10 @@ def write(filename, batch_objects = None, \
Property: "Width", "int", "",0
Property: "Height", "int", "",0''')
if tex:
- fname, fname_strip, fname_rel = derived_paths(tex.filename, basepath, EXP_IMAGE_COPY)
+ fname = tex.filename
+ fname_strip = strip_path(fname)
else:
- fname = fname_strip = fname_rel = ''
+ fname = fname_strip = ''
file.write('\n\t\t\tProperty: "Path", "charptr", "", "%s"' % fname_strip)
@@ -1174,7 +1163,7 @@ def write(filename, batch_objects = None, \
file.write('\n\t\tFilename: "%s"' % fname_strip)
if fname_strip: fname_strip = '/' + fname_strip
- file.write('\n\t\tRelativeFilename: "%s"' % fname_rel) # make relative
+ file.write('\n\t\tRelativeFilename: "fbx%s"' % fname_strip) # make relative
file.write('\n\t}')
@@ -1213,14 +1202,13 @@ def write(filename, batch_objects = None, \
}''')
file.write('\n\t\tMedia: "Video::%s"' % texname)
-
if tex:
- fname, fname_strip, fname_rel = derived_paths(tex.filename, basepath, EXP_IMAGE_COPY)
+ fname = tex.filename
+ file.write('\n\t\tFileName: "%s"' % strip_path(fname))
+ file.write('\n\t\tRelativeFilename: "fbx/%s"' % strip_path(fname)) # need some make relative command
else:
- fname = fname_strip = fname_rel = ''
-
- file.write('\n\t\tFileName: "%s"' % fname_strip)
- file.write('\n\t\tRelativeFilename: "%s"' % fname_rel) # need some make relative command
+ file.write('\n\t\tFileName: ""')
+ file.write('\n\t\tRelativeFilename: "fbx"')
file.write('''
ModelUVTranslation: 0,0
@@ -2670,7 +2658,7 @@ Takes: {''')
# copy images if enabled
if EXP_IMAGE_COPY:
- copy_images( basepath, [ tex[1] for tex in textures if tex[1] != None ])
+ copy_images( Blender.sys.dirname(filename), [ tex[1] for tex in textures if tex[1] != None ])
print 'export finished in %.4f sec.' % (Blender.sys.time() - start_time)
return True
@@ -2899,7 +2887,7 @@ def fbx_ui():
def write_ui():
# globals
- GLOBALS['EVENT'] = EVENT_REDRAW
+ GLOBALS['EVENT'] = 2
#GLOBALS['MOUSE'] = Window.GetMouseCoords()
GLOBALS['MOUSE'] = [i/2 for i in Window.GetScreenSize()]
GLOBALS['FILENAME'] = ''
@@ -2941,6 +2929,13 @@ def write_ui():
GLOBALS['_YROT90'] = Draw.Create(False)
GLOBALS['_ZROT90'] = Draw.Create(False)
+ # horrible ugly hack so tooltips draw, dosnt always work even
+ # Fixed in Draw.UIBlock for 2.45rc2, but keep this until 2.45 is released
+ Window.SetKeyQualifiers(0)
+ while Window.GetMouseButtons(): Blender.sys.sleep(10)
+ for i in xrange(100): Window.QHandle(i)
+ # END HORRID HACK
+
# best not do move the cursor
# Window.SetMouseCoords(*[i/2 for i in Window.GetScreenSize()])
@@ -2964,7 +2959,7 @@ def write_ui():
#fbx_ui_write('/test.fbx')
break
- Draw.UIBlock(fbx_ui, 0)
+ Draw.UIBlock(fbx_ui)
# GLOBALS.clear()
diff --git a/release/scripts/export_m3g.py b/release/scripts/export_m3g.py
index c74e7acbcd3..86ac03cc407 100644
--- a/release/scripts/export_m3g.py
+++ b/release/scripts/export_m3g.py
@@ -11,7 +11,7 @@ Tooltip: 'Export to M3G'
#
# Source: http://www.nelson-games.de/bl2m3g/source
#
-# $Id$
+# $Id: m3g_export.py,v 0.1 2005/04/19 12:25 gerhardv Exp gerhardv $
#
# Author: Gerhard Völkl
#
diff --git a/release/scripts/export_obj.py b/release/scripts/export_obj.py
index 9feb02638c3..8e7374f02b5 100644
--- a/release/scripts/export_obj.py
+++ b/release/scripts/export_obj.py
@@ -2,14 +2,14 @@
"""
Name: 'Wavefront (.obj)...'
-Blender: 248
+Blender: 243
Group: 'Export'
Tooltip: 'Save a Wavefront OBJ File'
"""
__author__ = "Campbell Barton, Jiri Hnidek"
-__url__ = ['http://wiki.blender.org/index.php/Scripts/Manual/Export/wavefront_obj', 'www.blender.org', 'blenderartists.org']
-__version__ = "1.2"
+__url__ = ['www.blender.org', 'blenderartists.org']
+__version__ = "1.1"
__bpydoc__ = """\
This script is an exporter to OBJ file format.
@@ -185,7 +185,7 @@ def write(filename, objects,\
EXPORT_TRI=False, EXPORT_EDGES=False, EXPORT_NORMALS=False, EXPORT_NORMALS_HQ=False,\
EXPORT_UV=True, EXPORT_MTL=True, EXPORT_COPY_IMAGES=False,\
EXPORT_APPLY_MODIFIERS=True, EXPORT_ROTX90=True, EXPORT_BLEN_OBS=True,\
-EXPORT_GROUP_BY_OB=False, EXPORT_GROUP_BY_MAT=False, EXPORT_KEEP_VERT_ORDER=False):
+EXPORT_GROUP_BY_OB=False, EXPORT_GROUP_BY_MAT=False, EXPORT_MORPH_TARGET=False):
'''
Basic write function. The context and options must be alredy set
This can be accessed externaly
@@ -322,7 +322,7 @@ EXPORT_GROUP_BY_OB=False, EXPORT_GROUP_BY_MAT=False, EXPORT_KEEP_VERT_ORDER=Fal
# Sort by Material, then images
# so we dont over context switch in the obj file.
- if EXPORT_KEEP_VERT_ORDER:
+ if EXPORT_MORPH_TARGET:
pass
elif faceuv:
try: faces.sort(key = lambda a: (a.mat, a.image, a.smooth))
@@ -535,31 +535,23 @@ def write_ui(filename):
if not BPyMessages.Warning_SaveOver(filename):
return
- global EXPORT_APPLY_MODIFIERS, EXPORT_ROTX90, EXPORT_TRI, EXPORT_EDGES,\
- EXPORT_NORMALS, EXPORT_NORMALS_HQ, EXPORT_UV,\
- EXPORT_MTL, EXPORT_SEL_ONLY, EXPORT_ALL_SCENES,\
- EXPORT_ANIMATION, EXPORT_COPY_IMAGES, EXPORT_BLEN_OBS,\
- EXPORT_GROUP_BY_OB, EXPORT_GROUP_BY_MAT, EXPORT_KEEP_VERT_ORDER
-
- EXPORT_APPLY_MODIFIERS = Draw.Create(0)
+ EXPORT_APPLY_MODIFIERS = Draw.Create(1)
EXPORT_ROTX90 = Draw.Create(1)
EXPORT_TRI = Draw.Create(0)
EXPORT_EDGES = Draw.Create(1)
EXPORT_NORMALS = Draw.Create(0)
- EXPORT_NORMALS_HQ = Draw.Create(0)
+ EXPORT_NORMALS_HQ = Draw.Create(1)
EXPORT_UV = Draw.Create(1)
EXPORT_MTL = Draw.Create(1)
EXPORT_SEL_ONLY = Draw.Create(1)
EXPORT_ALL_SCENES = Draw.Create(0)
EXPORT_ANIMATION = Draw.Create(0)
EXPORT_COPY_IMAGES = Draw.Create(0)
- EXPORT_BLEN_OBS = Draw.Create(0)
+ EXPORT_BLEN_OBS = Draw.Create(1)
EXPORT_GROUP_BY_OB = Draw.Create(0)
EXPORT_GROUP_BY_MAT = Draw.Create(0)
- EXPORT_KEEP_VERT_ORDER = Draw.Create(1)
+ EXPORT_MORPH_TARGET = Draw.Create(0)
- # Old UI
- '''
# removed too many options are bad!
# Get USER Options
@@ -571,7 +563,7 @@ def write_ui(filename):
('Object Prefs...'),\
('Apply Modifiers', EXPORT_APPLY_MODIFIERS, 'Use transformed mesh data from each object. May break vert order for morph targets.'),\
('Rotate X90', EXPORT_ROTX90 , 'Rotate on export so Blenders UP is translated into OBJs UP'),\
- ('Keep Vert Order', EXPORT_KEEP_VERT_ORDER, 'Keep vert and face order, disables some other options.'),\
+ ('Morph Target', EXPORT_MORPH_TARGET, 'Keep vert and face order, disables some other options.'),\
('Extra Data...'),\
('Edges', EXPORT_EDGES, 'Edges not connected to faces.'),\
('Normals', EXPORT_NORMALS, 'Export vertex normal data (Ignored on import).'),\
@@ -588,124 +580,12 @@ def write_ui(filename):
if not Draw.PupBlock('Export...', pup_block):
return
- '''
- # BEGIN ALTERNATIVE UI *******************
- if True:
-
- EVENT_NONE = 0
- EVENT_EXIT = 1
- EVENT_REDRAW = 2
- EVENT_EXPORT = 3
-
- GLOBALS = {}
- GLOBALS['EVENT'] = EVENT_REDRAW
- #GLOBALS['MOUSE'] = Window.GetMouseCoords()
- GLOBALS['MOUSE'] = [i/2 for i in Window.GetScreenSize()]
-
- def obj_ui_set_event(e,v):
- GLOBALS['EVENT'] = e
-
- def do_split(e,v):
- global EXPORT_BLEN_OBS, EXPORT_GROUP_BY_OB, EXPORT_GROUP_BY_MAT, EXPORT_APPLY_MODIFIERS, KEEP_VERT_ORDER
- if EXPORT_BLEN_OBS.val or EXPORT_GROUP_BY_OB.val or EXPORT_GROUP_BY_MAT.val or EXPORT_APPLY_MODIFIERS.val:
- EXPORT_KEEP_VERT_ORDER.val = 0
- else:
- EXPORT_KEEP_VERT_ORDER.val = 1
-
- def do_vertorder(e,v):
- global EXPORT_BLEN_OBS, EXPORT_GROUP_BY_OB, EXPORT_GROUP_BY_MAT, EXPORT_APPLY_MODIFIERS, KEEP_VERT_ORDER
- if EXPORT_KEEP_VERT_ORDER.val:
- EXPORT_BLEN_OBS.val = EXPORT_GROUP_BY_OB.val = EXPORT_GROUP_BY_MAT.val = EXPORT_APPLY_MODIFIERS.val = 0
- else:
- if not (EXPORT_BLEN_OBS.val or EXPORT_GROUP_BY_OB.val or EXPORT_GROUP_BY_MAT.val or EXPORT_APPLY_MODIFIERS.val):
- EXPORT_KEEP_VERT_ORDER.val = 1
-
- def do_help(e,v):
- url = __url__[0]
- print 'Trying to open web browser with documentation at this address...'
- print '\t' + url
-
- try:
- import webbrowser
- webbrowser.open(url)
- except:
- print '...could not open a browser window.'
-
- def obj_ui():
- ui_x, ui_y = GLOBALS['MOUSE']
-
- # Center based on overall pup size
- ui_x -= 165
- ui_y -= 110
-
- global EXPORT_APPLY_MODIFIERS, EXPORT_ROTX90, EXPORT_TRI, EXPORT_EDGES,\
- EXPORT_NORMALS, EXPORT_NORMALS_HQ, EXPORT_UV,\
- EXPORT_MTL, EXPORT_SEL_ONLY, EXPORT_ALL_SCENES,\
- EXPORT_ANIMATION, EXPORT_COPY_IMAGES, EXPORT_BLEN_OBS,\
- EXPORT_GROUP_BY_OB, EXPORT_GROUP_BY_MAT, EXPORT_KEEP_VERT_ORDER
-
- Draw.Label('Context...', ui_x+9, ui_y+209, 220, 20)
- Draw.BeginAlign()
- EXPORT_SEL_ONLY = Draw.Toggle('Selection Only', EVENT_NONE, ui_x+9, ui_y+189, 110, 20, EXPORT_SEL_ONLY.val, 'Only export objects in visible selection. Else export whole scene.')
- EXPORT_ALL_SCENES = Draw.Toggle('All Scenes', EVENT_NONE, ui_x+119, ui_y+189, 110, 20, EXPORT_ALL_SCENES.val, 'Each scene as a separate OBJ file.')
- EXPORT_ANIMATION = Draw.Toggle('Animation', EVENT_NONE, ui_x+229, ui_y+189, 110, 20, EXPORT_ANIMATION.val, 'Each frame as a numbered OBJ file.')
- Draw.EndAlign()
-
-
- Draw.Label('Output Options...', ui_x+9, ui_y+159, 220, 20)
- Draw.BeginAlign()
- EXPORT_APPLY_MODIFIERS = Draw.Toggle('Apply Modifiers', EVENT_REDRAW, ui_x+9, ui_y+140, 110, 20, EXPORT_APPLY_MODIFIERS.val, 'Use transformed mesh data from each object. May break vert order for morph targets.', do_split)
- EXPORT_ROTX90 = Draw.Toggle('Rotate X90', EVENT_NONE, ui_x+119, ui_y+140, 110, 20, EXPORT_ROTX90.val, 'Rotate on export so Blenders UP is translated into OBJs UP')
- EXPORT_COPY_IMAGES = Draw.Toggle('Copy Images', EVENT_NONE, ui_x+229, ui_y+140, 110, 20, EXPORT_COPY_IMAGES.val, 'Copy image files to the export directory, never overwrite.')
- Draw.EndAlign()
-
-
- Draw.Label('Export...', ui_x+9, ui_y+109, 220, 20)
- Draw.BeginAlign()
- EXPORT_EDGES = Draw.Toggle('Edges', EVENT_NONE, ui_x+9, ui_y+90, 50, 20, EXPORT_EDGES.val, 'Edges not connected to faces.')
- EXPORT_TRI = Draw.Toggle('Triangulate', EVENT_NONE, ui_x+59, ui_y+90, 70, 20, EXPORT_TRI.val, 'Triangulate quads.')
- Draw.EndAlign()
- Draw.BeginAlign()
- EXPORT_MTL = Draw.Toggle('Materials', EVENT_NONE, ui_x+139, ui_y+90, 70, 20, EXPORT_MTL.val, 'Write a separate MTL file with the OBJ.')
- EXPORT_UV = Draw.Toggle('UVs', EVENT_NONE, ui_x+209, ui_y+90, 31, 20, EXPORT_UV.val, 'Export texface UV coords.')
- Draw.EndAlign()
- Draw.BeginAlign()
- EXPORT_NORMALS = Draw.Toggle('Normals', EVENT_NONE, ui_x+250, ui_y+90, 59, 20, EXPORT_NORMALS.val, 'Export vertex normal data (Ignored on import).')
- EXPORT_NORMALS_HQ = Draw.Toggle('HQ', EVENT_NONE, ui_x+309, ui_y+90, 31, 20, EXPORT_NORMALS_HQ.val, 'Calculate high quality normals for rendering.')
- Draw.EndAlign()
-
-
- Draw.Label('Blender Objects as OBJ:', ui_x+9, ui_y+59, 220, 20)
- Draw.BeginAlign()
- EXPORT_BLEN_OBS = Draw.Toggle('Objects', EVENT_REDRAW, ui_x+9, ui_y+39, 60, 20, EXPORT_BLEN_OBS.val, 'Export blender objects as "OBJ objects".', do_split)
- EXPORT_GROUP_BY_OB = Draw.Toggle('Groups', EVENT_REDRAW, ui_x+69, ui_y+39, 60, 20, EXPORT_GROUP_BY_OB.val, 'Export blender objects as "OBJ Groups".', do_split)
- EXPORT_GROUP_BY_MAT = Draw.Toggle('Material Groups', EVENT_REDRAW, ui_x+129, ui_y+39, 100, 20, EXPORT_GROUP_BY_MAT.val, 'Group by materials.', do_split)
- Draw.EndAlign()
-
- EXPORT_KEEP_VERT_ORDER = Draw.Toggle('Keep Vert Order', EVENT_REDRAW, ui_x+239, ui_y+39, 100, 20, EXPORT_KEEP_VERT_ORDER.val, 'Keep vert and face order, disables some other options. Use for morph targets.', do_vertorder)
-
- Draw.BeginAlign()
- Draw.PushButton('Online Help', EVENT_REDRAW, ui_x+9, ui_y+9, 110, 20, 'Load the wiki page for this script', do_help)
- Draw.PushButton('Cancel', EVENT_EXIT, ui_x+119, ui_y+9, 110, 20, '', obj_ui_set_event)
- Draw.PushButton('Export', EVENT_EXPORT, ui_x+229, ui_y+9, 110, 20, 'Export with these settings', obj_ui_set_event)
- Draw.EndAlign()
-
-
- # hack so the toggle buttons redraw. this is not nice at all
- while GLOBALS['EVENT'] not in (EVENT_EXIT, EVENT_EXPORT):
- Draw.UIBlock(obj_ui, 0)
-
- if GLOBALS['EVENT'] != EVENT_EXPORT:
- return
-
- # END ALTERNATIVE UI *********************
-
-
- if EXPORT_KEEP_VERT_ORDER.val:
+ if EXPORT_MORPH_TARGET.val:
EXPORT_BLEN_OBS.val = False
EXPORT_GROUP_BY_OB.val = False
EXPORT_GROUP_BY_MAT.val = False
+ EXPORT_GROUP_BY_MAT.val = False
EXPORT_APPLY_MODIFIERS.val = False
Window.EditMode(0)
@@ -726,7 +606,7 @@ def write_ui(filename):
EXPORT_BLEN_OBS = EXPORT_BLEN_OBS.val
EXPORT_GROUP_BY_OB = EXPORT_GROUP_BY_OB.val
EXPORT_GROUP_BY_MAT = EXPORT_GROUP_BY_MAT.val
- EXPORT_KEEP_VERT_ORDER = EXPORT_KEEP_VERT_ORDER.val
+ EXPORT_MORPH_TARGET = EXPORT_MORPH_TARGET.val
@@ -776,7 +656,7 @@ def write_ui(filename):
EXPORT_NORMALS_HQ, EXPORT_UV, EXPORT_MTL,\
EXPORT_COPY_IMAGES, EXPORT_APPLY_MODIFIERS,\
EXPORT_ROTX90, EXPORT_BLEN_OBS,\
- EXPORT_GROUP_BY_OB, EXPORT_GROUP_BY_MAT, EXPORT_KEEP_VERT_ORDER)
+ EXPORT_GROUP_BY_OB, EXPORT_GROUP_BY_MAT, EXPORT_MORPH_TARGET)
Blender.Set('curframe', orig_frame)
diff --git a/release/scripts/flt_dofedit.py b/release/scripts/flt_dofedit.py
deleted file mode 100644
index 36e8e4d2501..00000000000
--- a/release/scripts/flt_dofedit.py
+++ /dev/null
@@ -1,835 +0,0 @@
-#!BPY
-
-"""
-Name: 'FLT DOF Editor'
-Blender: 240
-Group: 'Misc'
-Tooltip: 'Degree of Freedom editor for FLT nodes'
-"""
-
-__author__ = "Geoffrey Bantle"
-__version__ = "1.0 11/21/07"
-__email__ = ('scripts', 'Author, ')
-__url__ = ('blender', 'blenderartists.org')
-
-__bpydoc__ ="""\
-This script provides tools for working with OpenFlight databases in Blender. OpenFlight is a
-registered trademark of MultiGen-Paradigm, Inc.
-
-Feature overview and more availible at:
-http://wiki.blender.org/index.php/Scripts/Manual/FLTools
-"""
-
-# --------------------------------------------------------------------------
-# flt_palettemanager.py version 0.1 2005/04/08
-# --------------------------------------------------------------------------
-# ***** BEGIN GPL LICENSE BLOCK *****
-#
-# Copyright (C) 2007: Blender Foundation
-#
-# This program is free software; you can redistribute it and/or
-# modify it under the terms of the GNU General Public License
-# as published by the Free Software Foundation; either version 2
-# of the License, or (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software Foundation,
-# Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
-#
-# ***** END GPL LICENCE BLOCK *****
-# --------------------------------------------------------------------------
-
-import Blender.Draw as Draw
-from Blender.BGL import *
-import Blender
-import flt_properties
-reload(flt_properties)
-from flt_properties import *
-
-#event codes
-evcode = {
- "DOF_MAKE" : 100,
- "DOF_UPDATE" : 138,
- "DOF_DELETE" : 101,
- "DOF_TRANSX" : 102,
- "DOF_TRANSY" : 103,
- "DOF_TRANSZ" : 104,
- "DOF_ROTX" : 105,
- "DOF_ROTY" : 106,
- "DOF_ROTZ" : 107,
- "DOF_SCALEX" : 108,
- "DOF_SCALEY" : 109,
- "DOF_SCALEZ" : 110,
- "DOF_MIN_TRANSX" : 111,
- "DOF_MIN_TRANSY" : 112,
- "DOF_MIN_TRANSZ" : 113,
- "DOF_MIN_ROTX" : 114,
- "DOF_MIN_ROTY" : 115,
- "DOF_MIN_ROTZ" : 116,
- "DOF_MIN_SCALEX" : 117,
- "DOF_MIN_SCALEY" : 118,
- "DOF_MIN_SCALEZ" : 119,
- "DOF_MAX_TRANSX" : 120,
- "DOF_MAX_TRANSY" : 121,
- "DOF_MAX_TRANSZ" : 122,
- "DOF_MAX_ROTX" : 123,
- "DOF_MAX_ROTY" : 124,
- "DOF_MAX_ROTZ" : 125,
- "DOF_MAX_SCALEX" : 126,
- "DOF_MAX_SCALEY" : 127,
- "DOF_MAX_SCALEZ" : 128,
- "DOF_STEP_TRANSX" : 129,
- "DOF_STEP_TRANSY" : 130,
- "DOF_STEP_TRANSZ" : 131,
- "DOF_STEP_ROTX" : 132,
- "DOF_STEP_ROTY" : 133,
- "DOF_STEP_ROTZ" : 134,
- "DOF_STEP_SCALEX" : 135,
- "DOF_STEP_SCALEY" : 136,
- "DOF_STEP_SCALEZ" : 137
-}
-
-#system
-DOF_MAKE = None
-DOF_UPDATE = None
-DOF_DELETE = None
-
-#toggle buttons
-DOF_TRANSX = None
-DOF_TRANSY = None
-DOF_TRANSZ = None
-DOF_ROTX = None
-DOF_ROTY = None
-DOF_ROTZ = None
-DOF_SCALEX = None
-DOF_SCALEY = None
-DOF_SCALEZ = None
-
-#Minimums
-DOF_MIN_TRANSX = None
-DOF_MIN_TRANSY = None
-DOF_MIN_TRANSZ = None
-DOF_MIN_ROTX = None
-DOF_MIN_ROTY = None
-DOF_MIN_ROTZ = None
-DOF_MIN_SCALEX = None
-DOF_MIN_SCALEY = None
-DOF_MIN_SCALEZ = None
-
-#maximums
-DOF_MAX_TRANSX = None
-DOF_MAX_TRANSY = None
-DOF_MAX_TRANSZ = None
-DOF_MAX_ROTX = None
-DOF_MAX_ROTY = None
-DOF_MAX_ROTZ = None
-DOF_MAX_SCALEX = None
-DOF_MAX_SCALEY = None
-DOF_MAX_SCALEZ = None
-
-#step
-DOF_STEP_TRANSX = None
-DOF_STEP_TRANSY = None
-DOF_STEP_TRANSZ = None
-DOF_STEP_ROTX = None
-DOF_STEP_ROTY = None
-DOF_STEP_ROTZ = None
-DOF_STEP_SCALEX = None
-DOF_STEP_SCALEY = None
-DOF_STEP_SCALEZ = None
-
-#labels
-DOF_ROTSTRING = None
-DOF_TRANSTRING = None
-DOF_SCALESTRING = None
-DOF_EDITLABEL = None
-
-#make ID props easier/morereadable
-zmin = '14d!ZMIN'
-zmax = '15d!ZMAX'
-zcur = '16d!ZCUR'
-zstep = '17d!ZSTEP'
-ymin = '18d!YMIN'
-ymax = '19d!YMAX'
-ycur = '20d!YCUR'
-ystep = '21d!YSTEP'
-xmin = '22d!XMIN'
-xmax = '23d!XMAX'
-xcur = '24d!XCUR'
-xstep = '25d!XSTEP'
-pitchmin = '26d!PITCH-MIN'
-pitchmax = '27d!PITCH-MAX'
-pitchcur = '28d!PITCH-CUR'
-pitchstep = '29d!PITCH-STEP'
-rollmin = '30d!ROLL-MIN'
-rollmax = '31d!ROLL-MAX'
-rollcur = '32d!ROLL-CUR'
-rollstep = '33d!ROLL-STEP'
-yawmin = '34d!YAW-MIN'
-yawmax = '35d!YAW-MAX'
-yawcur = '36d!YAW-CUR'
-yawstep = '37d!YAW-STEP'
-zscalemin = '38d!ZSIZE-MIN'
-zscalemax = '39d!ZSIZE-MAX'
-zscalecur = '40d!ZSIZE-CUR'
-zscalestep = '41d!ZSIZE-STEP'
-yscalemin = '42d!YSIZE-MIN'
-yscalemax = '43d!YSIZE-MAX'
-yscalecur = '44d!YSIZE-CUR'
-yscalestep = '45d!YSIZE-STEP'
-xscalemin = '46d!XSIZE-MIN'
-xscalemax = '47d!XSIZE-MAX'
-xscalecur = '48d!XSIZE-CUR'
-xscalestep = '49d!XSIZE-STEP'
-
-
-
-def update_state():
- state = dict()
- state["activeScene"] = Blender.Scene.GetCurrent()
- state["activeObject"] = state["activeScene"].objects.active
- if state["activeObject"] and not state["activeObject"].sel:
- state["activeObject"] = None
- state["activeMesh"] = None
- if state["activeObject"] and state["activeObject"].type == 'Mesh':
- state["activeMesh"] = state["activeObject"].getData(mesh=True)
-
-
- state["activeFace"] = None
- if state["activeMesh"]:
- if state["activeMesh"].faceUV and state["activeMesh"].activeFace != None:
- state["activeFace"] = state["activeMesh"].faces[state["activeMesh"].activeFace]
-
-
- #update editmode
- state["editmode"] = Blender.Window.EditMode()
-
- return state
-
-def idprops_append(object, typecode, props):
- object.properties["FLT"] = dict()
- object.properties["FLT"]['type'] = typecode
- for prop in props:
- object.properties["FLT"][prop] = props[prop]
- object.properties["FLT"]['3t8!id'] = object.name
-
-def idprops_kill():
- state = update_state()
- if state["activeObject"] and state["activeObject"].properties.has_key('FLT'):
- state["activeObject"].properties.pop('FLT')
-
-def idprops_copy(source):
- state = update_state()
- if source.properties.has_key('FLT'):
- for object in state["activeScene"].objects:
- if object.sel and object != source and (state["activeScene"].Layers & object.Layers):
- idprops_kill(object)
- object.properties['FLT'] = dict()
- for key in source.properties['FLT']:
- object.properties['FLT'][key] = source.properties['FLT'][key]
-
-def select_by_typecode(typecode):
- state = update_state()
-
- for object in state["activeScene"].objects:
- if object.properties.has_key('FLT') and object.properties['FLT']['type'] == typecode and state["activeScene"].Layers & object.Layers:
- object.select(1)
-
-def DOF_get_frame():
- state = update_state()
-
- if not state["activeObject"] and not id_props_type(state["activeObject"], 14):
- return
-
- #Warning! assumes 1 BU == 10 meters.
- #do origin
- state["activeObject"].properties['FLT']['5d!ORIGX'] = state["activeObject"].getLocation('worldspace')[0]*10.0
- state["activeObject"].properties['FLT']['6d!ORIGY'] = state["activeObject"].getLocation('worldspace')[1]*10.0
- state["activeObject"].properties['FLT']['7d!ORIGZ'] = state["activeObject"].getLocation('worldspace')[2]*10.0
- #do X axis
- x = Blender.Mathutils.Vector(1.0,0.0,0.0)
- x = x * state["activeObject"].getMatrix('worldspace')
- x = x * 10.0
- state["activeObject"].properties['FLT']['8d!XAXIS-X'] = x[0]
- state["activeObject"].properties['FLT']['9d!XAXIS-Y'] = x[1]
- state["activeObject"].properties['FLT']['10d!XAXIS-Z'] = x[2]
- #do X/Y plane
- x = Blender.Mathutils.Vector(0.0,1.0,0.0)
- x.normalize()
- x = x * state["activeObject"].getMatrix('worldspace')
- x = x * 10.0
- state["activeObject"].properties['FLT']['11d!XYPLANE-X'] = x[0]
- state["activeObject"].properties['FLT']['12d!XYPLANE-Y'] = x[1]
- state["activeObject"].properties['FLT']['13d!XZPLANE-Z'] = x[2]
-
-def idprops_type(object, typecode):
- if object.properties.has_key('FLT') and object.properties['FLT'].has_key('type') and object.properties['FLT']['type'] == typecode:
- return True
- return False
-
-#ui type code
-def get_prop(typecode, prop):
-
- state = update_state()
- if state["activeObject"] and idprops_type(state["activeObject"], typecode):
- props = state["activeObject"].properties['FLT']
- else:
- props = flt_properties.FLTDOF
-
- return props[prop]
-
-def set_prop(typecode, prop, value):
- state = update_state()
- if state["activeObject"] and idprops_type(state["activeObject"],typecode):
- state["activeObject"].properties['FLT'][prop] = value
-
-lockxtrans = (1 << 31)
-lockytrans = (1 << 30)
-lockztrans = (1 << 29)
-lockxrot = (1 << 28)
-lockyrot = (1 << 27)
-lockzrot = (1 << 26)
-lockxscale = (1 << 25)
-lockyscale = (1 << 24)
-lockzscale = (1 << 23)
-
-def get_lockmask(mask):
- state = update_state()
- if state["activeObject"]:
- flag = get_prop(14,'50I!FLAG')
- if flag & mask:
- return True
- return False
-
-def set_lockmask(mask):
- state = update_state()
- if state["activeObject"] and idprops_type(state["activeObject"], 14):
- oldvalue = state["activeObject"].properties['FLT']['50I!FLAG']
- oldvalue = struct.unpack('>I', struct.pack('>i', oldvalue))[0]
- oldvalue |= mask
- state["activeObject"].properties['FLT']['50I!FLAG'] = struct.unpack('>i', struct.pack(">I", oldvalue))[0]
-
-def clear_lockmask(mask):
- state = update_state()
- if state["activeObject"] and idprops_type(state["activeObject"], 14):
- oldvalue = state["activeObject"].properties['FLT']['50I!FLAG']
- oldvalue = struct.unpack('>I', struct.pack('>i', oldvalue))[0]
- oldvalue &= ~mask
- state["activeObject"].properties['FLT']['50I!FLAG'] = struct.unpack('>i',struct.pack('>I',oldvalue))[0]
-
-
-def create_dof():
- state = update_state()
- actobj = state["activeObject"]
- if actobj and not idprops_type(actobj, 14):
- idprops_kill()
- idprops_append(actobj,14, flt_properties.FLTDOF)
- DOF_get_frame()
-
-
-def event(evt,val):
- if evt == Draw.ESCKEY:
- Draw.Exit()
-
-def but_event(evt):
- global DOF_MAKE
- global DOF_UPDATE
- global DOF_DELETE
-
- global DOF_TRANSX
- global DOF_TRANSY
- global DOF_TRANSZ
- global DOF_ROTX
- global DOF_ROTY
- global DOF_ROTZ
- global DOF_SCALEX
- global DOF_SCALEY
- global DOF_SCALEZ
-
- global DOF_MIN_TRANSX
- global DOF_MIN_TRANSY
- global DOF_MIN_TRANSZ
- global DOF_MIN_ROTX
- global DOF_MIN_ROTY
- global DOF_MIN_ROTZ
- global DOF_MIN_SCALEX
- global DOF_MIN_SCALEY
- global DOF_MIN_SCALEZ
-
- global DOF_MAX_TRANSX
- global DOF_MAX_TRANSY
- global DOF_MAX_TRANSZ
- global DOF_MAX_ROTX
- global DOF_MAX_ROTY
- global DOF_MAX_ROTZ
- global DOF_MAX_SCALEX
- global DOF_MAX_SCALEY
- global DOF_MAX_SCALEZ
-
- global DOF_STEP_TRANSX
- global DOF_STEP_TRANSY
- global DOF_STEP_TRANSZ
- global DOF_STEP_ROTX
- global DOF_STEP_ROTY
- global DOF_STEP_ROTZ
- global DOF_STEP_SCALEX
- global DOF_STEP_SCALEY
- global DOF_STEP_SCALEZ
-
- #labels
- global DOF_ROTSTRING
- global DOF_TRANSTRING
- global DOF_SCALESTRING
-
-
- #masks
- global lockxtrans
- global lockytrans
- global lockztrans
- global lockxrot
- global lockyrot
- global lockzrot
- global lockxscale
- global lockyscale
- global lockzscale
-
- global zmin
- global zmax
- global zcur
- global zstep
- global ymin
- global ymax
- global ycur
- global ystep
- global xmin
- global xmax
- global xcur
- global xstep
- global pitchmin
- global pitchmax
- global pitchcur
- global pitchstep
- global rollmin
- global rollmax
- global rollcur
- global rollstep
- global yawmin
- global yawmax
- global yawcur
- global yawstep
- global zscalemin
- global zscalemax
- global zscalecur
- global zscalestep
- global yscalemin
- global yscalemax
- global yscalecur
- global yscalestep
- global xscalemin
- global xscalemax
- global xscalecur
- global xscalestep
-
-
-
- #do "system" events
- if evt == evcode["DOF_MAKE"]:
- create_dof()
-
- if evt == evcode["DOF_UPDATE"]:
- DOF_get_frame()
-
- if evt == evcode["DOF_DELETE"]:
- idprops_kill()
- #do translation lock events
- if evt == evcode["DOF_TRANSX"]:
- if DOF_TRANSX.val == True:
- set_lockmask(lockxtrans)
- else:
- clear_lockmask(lockxtrans)
-
- if evt == evcode["DOF_TRANSY"]:
- if DOF_TRANSY.val == True:
- set_lockmask(lockytrans)
- else:
- clear_lockmask(lockytrans)
-
- if evt == evcode["DOF_TRANSZ"]:
- if DOF_TRANSZ.val == True:
- set_lockmask(lockztrans)
- else:
- clear_lockmask(lockztrans)
-
-
- #do rotation lock events
- if evt == evcode["DOF_ROTX"]:
- if DOF_ROTX.val == True:
- set_lockmask(lockxrot)
- else:
- clear_lockmask(lockxrot)
-
- if evt == evcode["DOF_ROTY"]:
- if DOF_ROTY.val == True:
- set_lockmask(lockyrot)
- else:
- clear_lockmask(lockyrot)
-
- if evt == evcode["DOF_ROTZ"]:
- if DOF_ROTZ.val == True:
- set_lockmask(lockzrot)
- else:
- clear_lockmask(lockzrot)
-
- #do scale lock events
- if evt == evcode["DOF_SCALEX"]:
- if DOF_SCALEX.val == True:
- set_lockmask(lockxscale)
- else:
- clear_lockmask(lockxscale)
-
- if evt == evcode["DOF_SCALEY"]:
- if DOF_SCALEY.val == True:
- set_lockmask(lockyscale)
- else:
- clear_lockmask(lockyscale)
-
- if evt == evcode["DOF_SCALEZ"]:
- if DOF_SCALEZ.val == True:
- set_lockmask(lockzscale)
- else:
- clear_lockmask(lockzscale)
-
-
- #do translation buttons
- if evt == evcode["DOF_MIN_TRANSX"]:
- set_prop(14, xmin, DOF_MIN_TRANSX.val)
- if evt == evcode["DOF_MAX_TRANSX"]:
- set_prop(14,xmax, DOF_MAX_TRANSX.val)
- if evt == evcode["DOF_STEP_TRANSX"]:
- set_prop(14,xstep, DOF_STEP_TRANSX.val)
-
- if evt == evcode["DOF_MIN_TRANSY"]:
- set_prop(14, ymin, DOF_MIN_TRANSY.val)
- if evt == evcode["DOF_MAX_TRANSY"]:
- set_prop(14,ymax, DOF_MAX_TRANSY.val)
- if evt == evcode["DOF_STEP_TRANSY"]:
- set_prop(14,ystep, DOF_STEP_TRANSY.val)
-
- if evt == evcode["DOF_MIN_TRANSZ"]:
- set_prop(14, zmin, DOF_MIN_TRANSZ.val)
- if evt == evcode["DOF_MAX_TRANSZ"]:
- set_prop(14, zmax, DOF_MAX_TRANSZ.val)
- if evt == evcode["DOF_STEP_TRANSZ"]:
- set_prop(14, zstep, DOF_STEP_TRANSZ.val)
-
- #do rotation buttons
- if evt == evcode["DOF_MIN_ROTX"]:
- set_prop(14, pitchmin, DOF_MIN_ROTX.val)
- if evt == evcode["DOF_MAX_ROTX"]:
- set_prop(14, pitchmax, DOF_MAX_ROTX.val)
- if evt == evcode["DOF_STEP_ROTX"]:
- set_prop(14, pitchstep, DOF_STEP_ROTX.val)
-
- if evt == evcode["DOF_MIN_ROTY"]:
- set_prop(14, rollmin, DOF_MIN_ROTY.val)
- if evt == evcode["DOF_MAX_ROTY"]:
- set_prop(14, rollmax, DOF_MAX_ROTY.val)
- if evt == evcode["DOF_STEP_ROTY"]:
- set_prop(14, rollstep, DOF_STEP_ROTY.val)
-
- if evt == evcode["DOF_MIN_ROTZ"]:
- set_prop(14, yawmin, DOF_MIN_ROTZ.val)
- if evt == evcode["DOF_MAX_ROTZ"]:
- set_prop(14, yawmax, DOF_MAX_ROTZ.val)
- if evt == evcode["DOF_STEP_ROTZ"]:
- set_prop(14, yawstep, DOF_STEP_ROTZ.val)
-
- #do scale buttons
- if evt == evcode["DOF_MIN_SCALEX"]:
- set_prop(14, xscalemin, DOF_MIN_SCALEX.val)
- if evt == evcode["DOF_MAX_SCALEX"]:
- set_prop(14, xscalemax, DOF_MAX_SCALEX.val)
- if evt == evcode["DOF_STEP_SCALEX"]:
- set_prop(14, xscalestep, DOF_STEP_SCALEX.val)
-
- if evt == evcode["DOF_MIN_SCALEY"]:
- set_prop(14, yscalemin, DOF_MIN_SCALEY.val)
- if evt == evcode["DOF_MAX_SCALEY"]:
- set_prop(14, yscalemax, DOF_MAX_SCALEY.val)
- if evt == evcode["DOF_STEP_SCALEY"]:
- set_prop(14, yscalestep, DOF_STEP_SCALEY.val)
-
- if evt == evcode["DOF_MIN_SCALEZ"]:
- set_prop(14, zscalemin, DOF_MIN_SCALEZ.val)
- if evt == evcode["DOF_MAX_SCALEZ"]:
- set_prop(14, zscalemax, DOF_MAX_SCALEZ.val)
- if evt == evcode["DOF_STEP_SCALEZ"]:
- set_prop(14, zscalestep, DOF_STEP_SCALEZ.val)
-
-
- Draw.Redraw(1)
- Blender.Window.RedrawAll()
-
-def draw_propsheet(x,y):
- #UI buttons
- global DOF_MAKE
- global DOF_UPDATE
- global DOF_DELETE
-
- global DOF_TRANSX
- global DOF_TRANSY
- global DOF_TRANSZ
- global DOF_ROTX
- global DOF_ROTY
- global DOF_ROTZ
- global DOF_SCALEX
- global DOF_SCALEY
- global DOF_SCALEZ
-
- global DOF_MIN_TRANSX
- global DOF_MIN_TRANSY
- global DOF_MIN_TRANSZ
- global DOF_MIN_ROTX
- global DOF_MIN_ROTY
- global DOF_MIN_ROTZ
- global DOF_MIN_SCALEX
- global DOF_MIN_SCALEY
- global DOF_MIN_SCALEZ
-
- global DOF_MAX_TRANSX
- global DOF_MAX_TRANSY
- global DOF_MAX_TRANSZ
- global DOF_MAX_ROTX
- global DOF_MAX_ROTY
- global DOF_MAX_ROTZ
- global DOF_MAX_SCALEX
- global DOF_MAX_SCALEY
- global DOF_MAX_SCALEZ
-
- global DOF_STEP_TRANSX
- global DOF_STEP_TRANSY
- global DOF_STEP_TRANSZ
- global DOF_STEP_ROTX
- global DOF_STEP_ROTY
- global DOF_STEP_ROTZ
- global DOF_STEP_SCALEX
- global DOF_STEP_SCALEY
- global DOF_STEP_SCALEZ
-
- #labels
- global DOF_ROTSTRING
- global DOF_TRANSTRING
- global DOF_SCALESTRING
- global DOF_EDITLABEL
-
- #masks
- global lockxtrans
- global lockytrans
- global lockztrans
- global lockxrot
- global lockyrot
- global lockzrot
- global lockxscale
- global lockyscale
- global lockzscale
-
- global zmin
- global zmax
- global zcur
- global zstep
- global ymin
- global ymax
- global ycur
- global ystep
- global xmin
- global xmax
- global xcur
- global xstep
- global pitchmin
- global pitchmax
- global pitchcur
- global pitchstep
- global rollmin
- global rollmax
- global rollcur
- global rollstep
- global yawmin
- global yawmax
- global yawcur
- global yawstep
- global zscalemin
- global zscalemax
- global zscalecur
- global zscalestep
- global yscalemin
- global yscalemax
- global yscalecur
- global yscalestep
- global xscalemin
- global xscalemax
- global xscalecur
- global xscalestep
-
-
- global evcode
-
- state = update_state()
-
- row_height = 20
- toggle_width = 50
- input_width = 100
- pad = 10
- origx = x
- origy = (row_height * 15) + (pad * 15)
-
-
- #editor label
- x = origx
- y = origy
- #y = y - (row_height + pad)
- DOF_EDITLABEL = Blender.Draw.Label("FLT Degree of Freedom Editor", x, y, 200, row_height)
-
-
- #draw Translation limits
- x = origx
- y = y- (row_height + pad)
- DOF_TRANSTRING = Blender.Draw.Label("Translation Limits", x, y, input_width, row_height)
-
-
- #X limits
- x = origx
- y = y- (row_height + pad)
- DOF_TRANSX = Blender.Draw.Toggle("LimX", evcode["DOF_TRANSX"], x, y, toggle_width, row_height, get_lockmask(lockxtrans), "")
- x = x + (toggle_width + pad)
- DOF_MIN_TRANSX = Blender.Draw.Number("MinX", evcode["DOF_MIN_TRANSX"], x, y, input_width, row_height,get_prop(14,xmin), -1000000.0, 1000000.0, "")
- x = x + (input_width + pad)
- DOF_MAX_TRANSX = Blender.Draw.Number("MaxX", evcode["DOF_MAX_TRANSX"], x, y, input_width, row_height,get_prop(14,xmax), -1000000.0, 1000000.0, "")
- x = x + (input_width + pad)
- DOF_STEP_TRANSX = Blender.Draw.Number("StepX", evcode["DOF_STEP_TRANSX"], x, y, input_width, row_height,get_prop(14,xstep), -1000000.0, 1000000.0, "")
-
- #Y limits
- x = origx
- y = y- (row_height + pad)
- DOF_TRANSY = Blender.Draw.Toggle("LimY", evcode["DOF_TRANSY"], x, y, toggle_width, row_height, get_lockmask(lockytrans), "")
- x = x + (toggle_width + pad)
- DOF_MIN_TRANSY = Blender.Draw.Number("MinY", evcode["DOF_MIN_TRANSY"], x, y, input_width, row_height, get_prop(14,ymin), -1000000.0, 1000000.0, "")
- x = x + (input_width + pad)
- DOF_MAX_TRANSY = Blender.Draw.Number("MaxY", evcode["DOF_MAX_TRANSY"], x, y, input_width, row_height, get_prop(14,ymax), -1000000.0, 1000000.0, "")
- x = x + (input_width + pad)
- DOF_STEP_TRANSY = Blender.Draw.Number("StepY", evcode["DOF_STEP_TRANSY"], x, y, input_width, row_height, get_prop(14,ystep), -1000000.0, 1000000.0, "")
-
- #Z limits
- x = origx
- y = y- (row_height + pad)
- DOF_TRANSZ = Blender.Draw.Toggle("LimZ", evcode["DOF_TRANSZ"], x, y, toggle_width, row_height, get_lockmask(lockztrans), "")
- x = x + (toggle_width + pad)
- DOF_MIN_TRANSZ = Blender.Draw.Number("MinZ", evcode["DOF_MIN_TRANSZ"], x, y, input_width, row_height, get_prop(14,zmin), -1000000.0, 1000000.0, "")
- x = x + (input_width + pad)
- DOF_MAX_TRANSZ = Blender.Draw.Number("MaxZ", evcode["DOF_MAX_TRANSZ"], x, y, input_width, row_height, get_prop(14,zmax), -1000000.0, 1000000.0, "")
- x = x + (input_width + pad)
- DOF_STEP_TRANSZ = Blender.Draw.Number("StepZ", evcode["DOF_STEP_TRANSZ"], x, y, input_width, row_height, get_prop(14,zstep), -1000000.0, 1000000.0, "")
-
- #draw Rotation limits
- x = origx
- y = y- (row_height + pad)
- DOF_ROTSTRING = Blender.Draw.Label("Rotation Limits", x, y, input_width, row_height)
-
- #draw Rotation limits
- #X limits
- x = origx
- y = y- (row_height + pad)
- DOF_ROTX = Blender.Draw.Toggle("LimX", evcode["DOF_ROTX"], x, y, toggle_width, row_height, get_lockmask(lockxrot), "")
- x = x + (toggle_width + pad)
- DOF_MIN_ROTX = Blender.Draw.Number("MinX", evcode["DOF_MIN_ROTX"], x, y, input_width, row_height, get_prop(14,pitchmin), -1000000.0, 1000000.0, "")
- x = x + (input_width + pad)
- DOF_MAX_ROTX = Blender.Draw.Number("MaxX", evcode["DOF_MAX_ROTX"], x, y, input_width, row_height, get_prop(14,pitchmax), -1000000.0, 1000000.0, "")
- x = x + (input_width + pad)
- DOF_STEP_ROTX = Blender.Draw.Number("StepX", evcode["DOF_STEP_ROTX"], x, y, input_width, row_height, get_prop(14,pitchstep), -1000000.0, 1000000.0, "")
-
- #Y limits
- x = origx
- y = y- (row_height + pad)
- DOF_ROTY = Blender.Draw.Toggle("LimY", evcode["DOF_ROTY"], x, y, toggle_width, row_height, get_lockmask(lockyrot), "")
- x = x + (toggle_width + pad)
- DOF_MIN_ROTY = Blender.Draw.Number("MinY", evcode["DOF_MIN_ROTY"], x, y, input_width, row_height, get_prop(14,rollmin), -1000000.0, 1000000.0, "")
- x = x + (input_width + pad)
- DOF_MAX_ROTY = Blender.Draw.Number("MaxY", evcode["DOF_MAX_ROTY"], x, y, input_width, row_height, get_prop(14,rollmax), -1000000.0, 1000000.0, "")
- x = x + (input_width + pad)
- DOF_STEP_ROTY = Blender.Draw.Number("StepY", evcode["DOF_STEP_ROTY"], x, y, input_width, row_height, get_prop(14,rollstep), -1000000.0, 1000000.0, "")
-
- #Z limits
- x = origx
- y = y- (row_height + pad)
- DOF_ROTZ = Blender.Draw.Toggle("LimZ", evcode["DOF_ROTZ"], x, y, toggle_width, row_height, get_lockmask(lockzrot), "")
- x = x + (toggle_width + pad)
- DOF_MIN_ROTZ = Blender.Draw.Number("MinZ", evcode["DOF_MIN_ROTZ"], x, y, input_width, row_height, get_prop(14, yawmin), -1000000.0, 1000000.0, "")
- x = x + (input_width + pad)
- DOF_MAX_ROTZ = Blender.Draw.Number("MaxZ", evcode["DOF_MAX_ROTZ"], x, y, input_width, row_height, get_prop(14, yawmax), -1000000.0, 1000000.0, "")
- x = x + (input_width + pad)
- DOF_STEP_ROTZ = Blender.Draw.Number("StepZ", evcode["DOF_STEP_ROTZ"], x, y, input_width, row_height, get_prop(14, yawstep), -1000000.0, 1000000.0, "")
-
-
- #draw Scale limits
- x = origx
- y = y- (row_height + pad)
- DOF_SCALESTRING = Blender.Draw.Label("Scale Limits", x, y, input_width, row_height)
-
- #draw Scale limits
- #X limits
- x = origx
- y = y- (row_height + pad)
- DOF_SCALEX = Blender.Draw.Toggle("LimX", evcode["DOF_SCALEX"], x, y, toggle_width, row_height, get_lockmask(lockxscale), "")
- x = x + (toggle_width + pad)
- DOF_MIN_SCALEX = Blender.Draw.Number("MinX", evcode["DOF_MIN_SCALEX"], x, y, input_width, row_height, get_prop(14, xscalemin), -1000000.0, 1000000.0, "")
- x = x + (input_width + pad)
- DOF_MAX_SCALEX = Blender.Draw.Number("MaxX", evcode["DOF_MAX_SCALEX"], x, y, input_width, row_height, get_prop(14, xscalemax), -1000000.0, 1000000.0, "")
- x = x + (input_width + pad)
- DOF_STEP_SCALEX = Blender.Draw.Number("StepX", evcode["DOF_STEP_SCALEX"], x, y, input_width, row_height, get_prop(14, xscalestep), -1000000.0, 1000000.0, "")
-
- #Y limits
- x = origx
- y = y- (row_height + pad)
- DOF_SCALEY = Blender.Draw.Toggle("LimY", evcode["DOF_SCALEY"], x, y, toggle_width, row_height, get_lockmask(lockyscale), "")
- x = x + (toggle_width + pad)
- DOF_MIN_SCALEY = Blender.Draw.Number("MinY", evcode["DOF_MIN_SCALEY"], x, y, input_width, row_height, get_prop(14, yscalemin), -1000000.0, 1000000.0, "")
- x = x + (input_width + pad)
- DOF_MAX_SCALEY = Blender.Draw.Number("MaxY", evcode["DOF_MAX_SCALEY"], x, y, input_width, row_height, get_prop(14, yscalemax), -1000000.0, 1000000.0, "")
- x = x + (input_width + pad)
- DOF_STEP_SCALEY = Blender.Draw.Number("StepY", evcode["DOF_STEP_SCALEY"], x, y, input_width, row_height, get_prop(14, yscalestep), -1000000.0, 1000000.0, "")
-
- #Z limits
- x = origx
- y = y- (row_height + pad)
- DOF_SCALEZ = Blender.Draw.Toggle("LimZ", evcode["DOF_SCALEZ"], x, y, toggle_width, row_height, get_lockmask(lockzscale), "")
- x = x + (toggle_width + pad)
- DOF_MIN_SCALEZ = Blender.Draw.Number("MinZ", evcode["DOF_MIN_SCALEZ"], x, y, input_width, row_height, get_prop(14, zscalemin), -1000000.0, 1000000.0, "")
- x = x + (input_width + pad)
- DOF_MAX_SCALEZ = Blender.Draw.Number("MaxZ", evcode["DOF_MAX_SCALEZ"], x, y, input_width, row_height, get_prop(14, zscalemax), -1000000.0, 1000000.0, "")
- x = x + (input_width + pad)
- DOF_STEP_SCALEZ = Blender.Draw.Number("StepZ", evcode["DOF_STEP_SCALEZ"], x, y, input_width, row_height, get_prop(14, zscalestep), -1000000.0, 1000000.0, "")
-
- #System
- x = origx
- y = y - (row_height + (pad)*3)
- DOF_MAKE = Blender.Draw.PushButton("Make DOF", evcode["DOF_MAKE"], x, y, input_width, row_height, "Make a Dof Node out of Active Object")
- x = x + (input_width + pad)
- DOF_UPDATE = Blender.Draw.PushButton("Grab Loc/Rot", evcode["DOF_UPDATE"], x, y, input_width, row_height, "Update the Dof Node position/orientation")
- x = x + (input_width + pad)
- DOF_DELETE = Blender.Draw.PushButton("Delete DOF", evcode["DOF_DELETE"], x, y, input_width, row_height, "Delete the Dof Node properties")
-
-
-
-
-def gui():
- #draw the propsheet/toolbox.
- psheety = 800
- #psheetx = psheety + 10
- draw_propsheet(20,psheety)
-
-Draw.Register(gui,event,but_event)
- \ No newline at end of file
diff --git a/release/scripts/flt_lodedit.py b/release/scripts/flt_lodedit.py
deleted file mode 100644
index 58319b9e525..00000000000
--- a/release/scripts/flt_lodedit.py
+++ /dev/null
@@ -1,502 +0,0 @@
-#!BPY
-
-"""
-Name: 'FLT LOD Editor'
-Blender: 240
-Group: 'Misc'
-Tooltip: 'Level of Detail Edtior for FLT nodes'
-"""
-
-__author__ = "Geoffrey Bantle"
-__version__ = "1.0 11/21/07"
-__email__ = ('scripts', 'Author, ')
-__url__ = ('blender', 'blenderartists.org')
-
-__bpydoc__ ="""\
-This script provides tools for working with OpenFlight databases in Blender. OpenFlight is a
-registered trademark of MultiGen-Paradigm, Inc.
-
-Feature overview and more availible at:
-http://wiki.blender.org/index.php/Scripts/Manual/FLTools
-"""
-
-# --------------------------------------------------------------------------
-# flt_palettemanager.py version 0.1 2005/04/08
-# --------------------------------------------------------------------------
-# ***** BEGIN GPL LICENSE BLOCK *****
-#
-# Copyright (C) 2007: Blender Foundation
-#
-# This program is free software; you can redistribute it and/or
-# modify it under the terms of the GNU General Public License
-# as published by the Free Software Foundation; either version 2
-# of the License, or (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software Foundation,
-# Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
-#
-# ***** END GPL LICENCE BLOCK *****
-# --------------------------------------------------------------------------
-
-import Blender.Draw as Draw
-from Blender.BGL import *
-import Blender
-import flt_properties
-reload(flt_properties)
-from flt_properties import *
-
-#event codes
-evcode = {
- "LOD_MAKE" : 100,
- "LOD_DELETE" : 101,
- "LOD_CALC_CENTER" : 102,
- "LOD_GRAB_CENTER" : 103,
- "LOD_X" : 104,
- "LOD_Y" : 105,
- "LOD_Z" : 106,
- "LOD_FREEZE" : 107,
- "LOD_SIG" : 108,
- "LOD_IN" : 109,
- "LOD_OUT" : 110,
- "LOD_TRANS" : 111,
- "LOD_PREVIOUS" : 112
-}
-
-
-#system
-LOD_MAKE = None #PushButton
-LOD_DELETE = None #PushButton
-LOD_CALC_CENTER = None #PushButton
-LOD_GRAB_CENTER = None #Pushbutton
-LOD_FREEZE = None #Toggle
-LOD_PREVIOUS = None #Toggle
-
-LOD_X = None #Input
-LOD_Y = None #Input
-LOD_Z = None #Input
-
-LOD_SIG = None #Input
-LOD_IN = None #Input
-LOD_OUT = None #Input
-LOD_TRANS = None #Input
-
-#labels
-LOD_EDITLABEL = None
-LOD_SWITCHLABEL = None
-LOD_CENTERLABEL = None
-
-LOD_XLABEL = None
-LOD_YLABEL = None
-LOD_ZLABEL = None
-LOD_SIGLABEL = None
-LOD_INLABEL = None
-LOD_OUTLABEL = None
-LOD_TRANSLABEL = None
-
-
-#ID Props
-switch_in = '5d!switch in'
-switch_out = '6d!switch out'
-xco = '10d!X co'
-yco = '11d!Y co'
-zco = '12d!Z co'
-trans = '13d!Transition'
-sig_size = '14d!Sig Size'
-
-#Flags
-lodflag = '9I!flags'
-previous_mask = (1 << 31)
-freeze_mask = (1 << 29)
-
-def update_state():
- state = dict()
- state["activeScene"] = Blender.Scene.GetCurrent()
- state["activeObject"] = state["activeScene"].objects.active
- if state["activeObject"] and not state["activeObject"].sel:
- state["activeObject"] = None
- state["activeMesh"] = None
- if state["activeObject"] and state["activeObject"].type == 'Mesh':
- state["activeMesh"] = state["activeObject"].getData(mesh=True)
-
- state["activeFace"] = None
- if state["activeMesh"]:
- if state["activeMesh"].faceUV and state["activeMesh"].activeFace != None:
- state["activeFace"] = state["activeMesh"].faces[state["activeMesh"].activeFace]
-
-
- #update editmode
- state["editmode"] = Blender.Window.EditMode()
-
- return state
-
-def idprops_append(object, typecode, props):
- object.properties["FLT"] = dict()
- object.properties["FLT"]['type'] = typecode
- for prop in props:
- object.properties["FLT"][prop] = props[prop]
- object.properties["FLT"]['3t8!id'] = object.name
-
-def idprops_kill():
- state = update_state()
- if state["activeObject"] and state["activeObject"].properties.has_key('FLT'):
- state["activeObject"].properties.pop('FLT')
-
-def idprops_copy(source):
- state = update_state()
- if source.properties.has_key('FLT'):
- for object in state["activeScene"].objects:
- if object.sel and object != source and (state["activeScene"].Layers & object.Layers):
- idprops_kill(object)
- object.properties['FLT'] = dict()
- for key in source.properties['FLT']:
- object.properties['FLT'][key] = source.properties['FLT'][key]
-
-def select_by_typecode(typecode):
- state = update_state()
-
- for object in state["activeScene"].objects:
- if object.properties.has_key('FLT') and object.properties['FLT']['type'] == typecode and state["activeScene"].Layers & object.Layers:
- object.select(1)
-
-def idprops_type(object, typecode):
- if object.properties.has_key('FLT') and object.properties['FLT'].has_key('type') and object.properties['FLT']['type'] == typecode:
- return True
- return False
-
-#ui type code
-def get_prop(typecode, prop):
-
- state = update_state()
- if state["activeObject"] and idprops_type(state["activeObject"], typecode):
- props = state["activeObject"].properties['FLT']
- else:
- props = flt_properties.FLTLOD
-
- return props[prop]
-
-def set_prop(typecode, prop, value):
- state = update_state()
- if state["activeObject"] and idprops_type(state["activeObject"],typecode):
- state["activeObject"].properties['FLT'][prop] = value
-
-
-
-def get_lockmask(mask):
- global lodflag
- state = update_state()
- if state["activeObject"]:
- flag = get_prop(73,lodflag)
- if flag & mask:
- return True
- return False
-
-def set_lockmask(mask):
- state = update_state()
- if state["activeObject"] and idprops_type(state["activeObject"], 73):
- oldvalue = state["activeObject"].properties['FLT'][lodflag]
- oldvalue = struct.unpack('>I', struct.pack('>i', oldvalue))[0]
- oldvalue |= mask
- state["activeObject"].properties['FLT'][lodflag] = struct.unpack('>i', struct.pack(">I", oldvalue))[0]
-
-def clear_lockmask(mask):
- state = update_state()
- if state["activeObject"] and idprops_type(state["activeObject"], 73):
- oldvalue = state["activeObject"].properties['FLT'][lodflag]
- oldvalue = struct.unpack('>I', struct.pack('>i', oldvalue))[0]
- oldvalue &= ~mask
- state["activeObject"].properties['FLT'][lodflag] = struct.unpack('>i',struct.pack('>I',oldvalue))[0]
-
-def findchildren(object):
- state = update_state()
- children = list()
- for candidate in state["activeScene"].objects:
- if candidate.parent == object:
- children.append(candidate)
- retlist = list(children)
- for child in children:
- retlist = retlist + findchildren(child)
- return retlist
-
-def get_object_center(object):
- bbox = object.getBoundBox(1)
- average = Blender.Mathutils.Vector(0.0, 0.0, 0.0)
-
- for point in bbox:
- average[0] += point[0]
- average[1] += point[1]
- average[2] += point[2]
-
- average[0] = average[0] / 8.0
- average[1] = average[1] / 8.0
- average[2] = average[2] / 8.0
-
- return average
-
-
-def calc_center():
-
- global xco
- global yco
- global zco
-
- state = update_state()
- if state["activeObject"] and idprops_type(state["activeObject"], 73):
- average = Blender.Mathutils.Vector(0.0, 0.0, 0.0)
- children = findchildren(state["activeObject"]) #get children objects
- if children:
- for child in children:
- center = get_object_center(child)
- average[0] += center[0]
- average[1] += center[1]
- average[2] += center[2]
-
- average[0] = average[0] / len(children)
- average[1] = average[1] / len(children)
- average[2] = average[2] / len(children)
-
- set_prop(73, xco, average[0])
- set_prop(73, yco, average[1])
- set_prop(73, zco, average[2])
-
-
-def grab_center():
-
- global xco
- global yco
- global zco
-
- state = update_state()
- if state["activeObject"] and idprops_type(state["activeObject"], 73):
- center = Blender.Window.GetCursorPos()
-
- set_prop(73, xco, center[0])
- set_prop(73, yco, center[1])
- set_prop(73, zco, center[2])
-
-
-def create_lod():
- state = update_state()
- actobj = state["activeObject"]
- if actobj and not idprops_type(actobj, 73):
- idprops_kill()
- idprops_append(actobj,73, flt_properties.FLTLOD)
- calc_center()
-
-
-
-def event(evt,val):
- if evt == Draw.ESCKEY:
- Draw.Exit()
-
-def but_event(evt):
-
- global LOD_MAKE
- global LOD_DELETE
- global LOD_CALC_CENTER
- global LOD_GRAB_CENTER
- global LOD_FREEZE
- global LOD_PREVIOUS
- global LOD_X
- global LOD_Y
- global LOD_Z
- global LOD_SIG
- global LOD_IN
- global LOD_OUT
- global LOD_TRANS
-
- global switch_in
- global switch_out
- global xco
- global yco
- global zco
- global trans
- global sig_size
-
- global lodflag
- global previous_mask
- global freeze_mask
-
- global evcode
-
- #do "system" events
- if evt == evcode["LOD_MAKE"]:
- create_lod()
-
- if evt == evcode["LOD_CALC_CENTER"]:
- calc_center()
-
- if evt == evcode["LOD_DELETE"]:
- idprops_kill()
-
- if evt == evcode["LOD_GRAB_CENTER"]:
- grab_center()
-
- #do mask events
- if evt == evcode["LOD_FREEZE"]:
- if LOD_FREEZE.val == True:
- set_lockmask(freeze_mask)
- else:
- clear_lockmask(freeze_mask)
-
- if evt == evcode["LOD_PREVIOUS"]:
- if LOD_PREVIOUS.val == True:
- set_lockmask(previous_mask)
- else:
- clear_lockmask(previous_mask)
-
- #do input events
- if evt == evcode["LOD_X"]:
- set_prop(73, xco, LOD_X.val)
- if evt == evcode["LOD_Y"]:
- set_prop(73, yco, LOD_Y.val)
- if evt == evcode["LOD_Z"]:
- set_prop(73, zco, LOD_Z.val)
- if evt == evcode["LOD_SIG"]:
- set_prop(73, sig_size, LOD_SIG.val)
- if evt == evcode["LOD_IN"]:
- set_prop(73, switch_in, LOD_IN.val)
- if evt == evcode["LOD_OUT"]:
- set_prop(73, switch_out, LOD_OUT.val)
- if evt == evcode["LOD_TRANS"]:
- set_prop(73, trans, LOD_TRANS.val)
-
-
- Draw.Redraw(1)
- Blender.Window.RedrawAll()
-
-def draw_propsheet(x,y):
-
- global LOD_MAKE
- global LOD_DELETE
- global LOD_CALC_CENTER
- global LOD_GRAB_CENTER
- global LOD_FREEZE
- global LOD_PREVIOUS
- global LOD_X
- global LOD_Y
- global LOD_Z
- global LOD_SIG
- global LOD_IN
- global LOD_OUT
- global LOD_TRANS
-
- #labels
- global LOD_EDITLABEL
- global LOD_SWITCHLABEL
- global LOD_CENTERLABEL
- global LOD_XLABEL
- global LOD_YLABEL
- global LOD_ZLABEL
- global LOD_SIGLABEL
- global LOD_INLABEL
- global LOD_OUTLABEL
- global LOD_TRANSLABEL
-
-
- global switch_in
- global switch_out
- global xco
- global yco
- global zco
- global trans
- global sig_size
-
- global lodflag
- global previous_mask
- global freeze_mask
-
- global evcode
-
-
- global evcode
-
- state = update_state()
-
- label_width = 100
- row_height = 20
- toggle_width = 50
- input_width = 100
- pad = 10
- origx = x
- origy = (row_height * 16) + (pad * 16)
-
-
- #editor label
- x = origx
- y = origy
- LOD_EDITLABEL = Blender.Draw.Label("FLT Level of Detail Editor", x, y, 250, row_height)
-
-
- #Center inputs
- x = origx
- y = y- (row_height + pad)
- LOD_CENTERLABEL = Blender.Draw.Label("LOD center", x, y, label_width, row_height)
- y = y- (row_height + pad)
- LOD_XLABEL = Blender.Draw.Label("X Coordinate", x, y, label_width, row_height)
- x = origx + (label_width + pad)
- LOD_X = Blender.Draw.Number("", evcode["LOD_X"], x, y, input_width, row_height,get_prop(73,xco), -1000000.0, 1000000.0, "")
- x = origx
- y = y- (row_height + pad)
- LOD_YLABEL = Blender.Draw.Label("Y Coordinate", x, y, label_width, row_height)
- x = origx + (label_width + pad)
- LOD_Y = Blender.Draw.Number("", evcode["LOD_Y"], x, y, input_width, row_height,get_prop(73,yco), -1000000.0, 1000000.0, "")
- x = origx
- y = y- (row_height + pad)
- LOD_ZLABEL = Blender.Draw.Label("Z Coordinate", x, y, label_width, row_height)
- x = origx + (label_width + pad)
- LOD_Z = Blender.Draw.Number("", evcode["LOD_Z"], x, y, input_width, row_height,get_prop(73,zco), -1000000.0, 1000000.0, "")
-
-
- #Switch inputs
- x = origx
- y = y- (row_height + pad)
- LOD_SWITCHLABEL = Blender.Draw.Label("Switch Settings", x, y, input_width, row_height)
- y = y- (row_height + pad)
- LOD_SIGLABEL = Blender.Draw.Label("Significant Size", x, y, label_width, row_height)
- x = origx + (label_width + pad)
- LOD_SIG = Blender.Draw.Number("", evcode["LOD_SIG"], x, y, input_width, row_height, get_prop(73,sig_size), -1000000.0, 1000000.0, "")
- x = origx
- y = y- (row_height + pad)
- LOD_INLABEL = Blender.Draw.Label("Switch In", x, y, label_width, row_height)
- x = origx + (label_width + pad)
- LOD_IN = Blender.Draw.Number("", evcode["LOD_IN"], x, y, input_width, row_height, get_prop(73,switch_in), -1000000.0, 1000000.0, "")
- x = origx
- y = y- (row_height + pad)
- LOD_OUTLABEL = Blender.Draw.Label("Switch Out", x, y, label_width, row_height)
- x = origx + (label_width + pad)
- LOD_OUT = Blender.Draw.Number("", evcode["LOD_OUT"], x, y, input_width, row_height, get_prop(73,switch_out), -1000000.0, 1000000.0, "")
- x = origx
- y = y- (row_height + pad)
- LOD_TRANSLABEL = Blender.Draw.Label("Transition", x, y, label_width, row_height)
- x = origx + (label_width + pad)
- LOD_TRANS = Blender.Draw.Number("", evcode["LOD_TRANS"], x, y, input_width, row_height, get_prop(73,trans), -1000000.0, 1000000.0, "")
-
-
- x = origx
- y = y - (row_height + pad)
- LOD_MAKE = Blender.Draw.PushButton("Make LOD", evcode["LOD_MAKE"], x, y, input_width + label_width + pad, row_height, "Make a LOD Node out of Active Object")
- y = y - (row_height + pad)
- LOD_DELETE = Blender.Draw.PushButton("Delete LOD", evcode["LOD_DELETE"], x, y, input_width + label_width + pad, row_height, "Delete the LOD Node properties")
- y = y - (row_height + pad)
- LOD_CALC_CENTER = Blender.Draw.PushButton("Calculate Center", evcode["LOD_CALC_CENTER"], x, y, input_width + label_width + pad, row_height, "Calculate the center of this LOD")
- y = y - (row_height + pad)
- LOD_GRAB_CENTER = Blender.Draw.PushButton("Grab Center", evcode["LOD_GRAB_CENTER"], x, y, input_width + label_width + pad, row_height, "Grab center from 3d cursor")
- y = y - (row_height + pad)
- LOD_FREEZE = Blender.Draw.Toggle("Freeze Center", evcode["LOD_FREEZE"], x, y, input_width + label_width + pad, row_height, get_lockmask(freeze_mask), "")
- y = y - (row_height + pad)
- LOD_PREVIOUS = Blender.Draw.Toggle("Previous Range", evcode["LOD_PREVIOUS"], x, y, input_width + label_width + pad, row_height, get_lockmask(previous_mask), "")
-
-def gui():
- #draw the propsheet/toolbox.
- psheety = 800
- #psheetx = psheety + 10
- draw_propsheet(20,psheety)
-
-Draw.Register(gui,event,but_event)
- \ No newline at end of file
diff --git a/release/scripts/flt_properties.py b/release/scripts/flt_properties.py
index 4c841e9c0c0..bc7c972ca66 100644
--- a/release/scripts/flt_properties.py
+++ b/release/scripts/flt_properties.py
@@ -197,10 +197,7 @@ def write_prop(fw,type,value,length):
elif type == 'i':
fw.write_int(value)
elif type == 'I':
- #NOTE!:
- #there is no unsigned int type in python, but we can only store signed ints in ID props
- newvalue = struct.unpack('>I', struct.pack('>i', value))[0]
- fw.write_uint(newvalue)
+ fw.write_uint(value)
elif type == 'd':
fw.write_double(value)
elif type == 'f':
@@ -270,16 +267,16 @@ FLTObjectDisplay = [10]
FLTLOD = {
'3t8!id' : 'L',
'4i!reserved' : 0,
- '5d!switch in' : 0.0,
- '6d!switch out' : 0.0,
+ '5d!switch in' : 0,
+ '6d!switch out' : 0,
'7s!sfx ID1' : 0,
'8s!sfx ID2' : 0,
'9I!flags' : 0,
- '10d!X co' : 0.0,
- '11d!Y co' : 0.0,
- '12d!Z co' : 0.0,
- '13d!Transition' : 0.0,
- '14d!Sig Size' : 0.0
+ '10d!X co' : 0,
+ '11d!Y co' : 0,
+ '12d!Z co' : 0,
+ '13d!Transition' : 0,
+ '14d!Sig Size' : 0
}
FLTLODDisplay = [4]
diff --git a/release/scripts/help_browser.py b/release/scripts/help_browser.py
index b27e266f368..696dfd3ca2b 100644
--- a/release/scripts/help_browser.py
+++ b/release/scripts/help_browser.py
@@ -448,19 +448,11 @@ def parse_help_info(script):
def parse_script_line(l):
- tip = 'No tooltip'
try:
pieces = l.split("'")
name = pieces[1].replace('...','')
- data = pieces[2].strip().split()
- version = data[0]
- userdir = data[-1]
- fname = data[1]
- i = 1
- while not fname.endswith('.py'):
- i += 1
- fname = '%s %s' % (fname, data[i])
- if len(pieces) > 3: tip = pieces[3]
+ version, fname, userdir = pieces[2].strip().split()
+ tip = pieces[3]
except:
return None
diff --git a/release/scripts/hotkeys.py b/release/scripts/hotkeys.py
index 187cba964bc..929132933ec 100644
--- a/release/scripts/hotkeys.py
+++ b/release/scripts/hotkeys.py
@@ -128,21 +128,17 @@ hotkeys={
['RMB hold down', 'Popup menu'],
['Alt-RMB', 'Object Mode :Select but in a displayed list of objects located under the mouse cursor'],
['Alt-RMB', 'Edit Mode: Select EDGES LOOP '],
-['Alt-Ctrl-RMB', 'Edit Mode: Select FACES LOOP'],
-['Alt-Ctrl-RMB', 'UV Image Editor: Select face'],
+['Alt+Ctrl-RMB', 'Edit Mode: Select FACES LOOP'],
+['Alt+Ctrl-RMB', 'UV Image Editor: Select face'],
['Shift-RMB', 'Add/subtract to/from selection'],
['Wheel', 'Zoom view'],
['Transformations:', ''],
['Drag+Ctrl', 'Step adjustment'],
-['Drag+Ctrl-Shift', 'Small step adjustment (Transform Widget : first select the axe or axes with LBM alone)'],
+['Drag+Ctrl+Shift', 'Small step adjustment (Transform Widget : first select the axe or axes with LBM alone)'],
['Drag+Shift', 'Fine adjustment (Transform Widget : first select the axe or axes with LBM alone)'],
['LMB', 'Confirm transformation'],
['MMB', 'Toggle optional transform feature'],
['RMB', 'Abort transformation'],
-['LMB', 'Grease Pencil: when "Draw Mode On", draw new stroke'],
-['RMB', 'Grease Pencil: when "Draw Mode On", eraser tool for stroke segments'],
-['Shift-LMB', 'Grease Pencil: draw new stroke'],
-['Alt-RMB', 'Grease Pencil: eraser tool for stroke segments'],
['.', '...']
],
@@ -232,7 +228,7 @@ hotkeys={
['Home', 'OutLiner Windows, Show hierarchy'],
['PgUp', 'Edit Mode and Proportionnal Editing Tools, increase influence'],
['PgUp', 'Strip Editor, Move Down'],
-['PgUp', 'TimeLine: Jump to next marker'],
+['PgUn', 'TimeLine: Jump to next marker'],
['PgUp', 'IPO: Select next keyframe'],
['Ctrl-PgUp', 'IPO: Select and jump to next keyframe'],
['Ctrl-PgUn', 'TimeLine: Jump to next key'],
@@ -250,6 +246,7 @@ hotkeys={
['Alt-Up', 'Blender in Fullscreen mode'],
['Ctrl-Left', 'Previous screen'],
['Ctrl-Right', 'Next screen'],
+['Ctrl-Alt-C', 'Object Mode : Add Constraint'],
['Ctrl-Down', 'Maximize window toggle'],
['Ctrl-Up', 'Maximize window toggle'],
['Shift-Arrow', 'Toggle first frame/ last frame'],
@@ -267,10 +264,8 @@ hotkeys={
['Alt-A', 'Play animation in current window'],
['Ctrl-A', 'Apply objects size/rotation to object data'],
['Ctrl-A', 'Text Editor: Select all'],
-['Ctrl-ALT-A', '3D-View: Armature Edit mode, align selected bones to active bone'],
['Shift-A', 'Sequencer: Add menu'],
['Shift-A', '3D-View: Add menu'],
-['Shift-A', 'Sculpt Mode: Keep the brush center anchored to the initial location'],
['Shift-ALT-A', 'Play animation in all windows'],
['Shift-CTRL-A', 'Apply lattice / Make dupliverts real'],
['Shift-CTRL-A', 'Apply Deform '],
@@ -280,13 +275,13 @@ hotkeys={
"B":[
['B', 'Border select'],
['BB', 'Circle select'],
-['Alt-B', 'Object Mode: Select visible view section in 3D space'],
+['Alt+B', 'Object Mode: Select visible view section in 3D space'],
['Shift-B', 'Set render border (in active camera view)'],
-['Ctrl-Alt-B', 'Object Mode: in 3D view, Bake (on an image in the uv editor window) the selected Meshes'], #243
-['Ctrl-Alt-B', 'Object Mode: in 3D view, Bake Full render of selected Meshes'], #243
-['Ctrl-Alt-B', 'Object Mode: in 3D view, Bake Ambient Occlusion of selected Meshes'], #243
-['Ctrl-Alt-B', 'Object Mode: in 3D view, Bake Normals of the selected Meshes'], #243
-['Ctrl-Alt-B', 'Object Mode: in 3D view, Bake Texture Only of selected Meshes'], #243
+['Ctrl-Alt+B', 'Object Mode: in 3D view, Bake (on an image in the uv editor window) the selected Meshes'], #243
+['Ctrl-Alt+B', 'Object Mode: in 3D view, Bake Full render of selected Meshes'], #243
+['Ctrl-Alt+B', 'Object Mode: in 3D view, Bake Ambient Occlusion of selected Meshes'], #243
+['Ctrl-Alt+B', 'Object Mode: in 3D view, Bake Normals of the selected Meshes'], #243
+['Ctrl-Alt+B', 'Object Mode: in 3D view, Bake Texture Only of selected Meshes'], #243
['.', '...']
],
@@ -300,12 +295,11 @@ hotkeys={
['C', 'NODE window : Show cyclic referencies'], #243
['Alt-C', 'Object Mode: Convert menu'],
['Alt-C', 'Text Editor: Copy '],
-['Ctrl-Alt-C', 'Object Mode : Add Constraint'],
['Ctrl-Shift-C', 'Text Editor: Copy selection to clipboard'],
['Ctrl-C', 'Copy menu (Copy properties of active to selected objects)'],
['Ctrl-C', 'UV Image Editor: Stick UVs to mesh vertex'],
['Ctrl-C','ARMATURE : posemode, Copy pose attributes'],
-['Ctrl-Alt-C',' ARMATURE : posemode, add constraint to new empty object.'],
+['Ctrl+Alt-C',' ARMATURE : posemode, add constraint to new empty object.'],
['Shift-C', 'Center and zoom view on selected objects'],
['Shift-C', 'UV Image Editor: Stick local UVs to mesh vertex'],
['.', '...']
@@ -399,11 +393,9 @@ hotkeys={
],
"I":[
-['I', 'Insert Keyframe menu'],
-['Alt-I','Delete Keyframe menu'],
-['Ctrl-I','Select Inverse'],
-['Shift-I','ARMATURE : add IK constraint'],
-['Ctrl-Alt-I','ARMATURE : posemode, remove IK constraints.'],
+['I', 'Keyframe menu'],
+['Alt-I','ARMATURE : posemode, remove IK constraints.'],
+['Ctrl-I','ARMATURE : add IK constraint'],
['.', '...']
],
@@ -441,10 +433,6 @@ hotkeys={
['Ctrl-L', 'Make links menu (for instance : to scene...)'],
['Shift-L', 'Select links menu'],
['Shift-L', 'NODE window: Select linked to '], #243
-['Ctrl-L', 'POSELIB: browse poses'],
-['Shift-L', 'POSELIB: add/replace pose'],
-['Ctrl-Shift-L', 'POSELIB: rename pose'],
-['Alt-L', 'POSELIB: remove pose'],
['.', '...']
],
@@ -495,8 +483,8 @@ hotkeys={
"P":[
['P', 'Object Mode: Start realtime engine'],
['P', 'Edit mode: Seperate vertices to new object'],
-['Shift-P', 'Edit mode: Push-Pull'],
-['Shift-P', 'Object mode: Add a preview window in the D window'],
+['shift-P', 'Edit mode: Push-Pull'],
+['shift-P', 'Object mode: Add a preview window in the D window'],
['P', 'UV Image Editor: Pin selected vertices. Pinned vertices will stay in place on the UV editor when executing an LSCM unwrap.'],
['Alt-P', 'Clear parent relationship'],
['Alt-P', 'UV Image Editor: Unpin UVs'],
@@ -505,7 +493,6 @@ hotkeys={
['Ctrl-Shift-P', 'Make active object parent of selected object without inverse'],
['Ctrl-P', 'Edit mode: Make active vertex parent of selected object'],
['Ctrl-P', 'ARMATURE : editmode, make bone parent.'],
-['Ctrl-Alt-P', 'ARMATURE: edimode, separate bones to new object'],
['.', '...']
],
@@ -554,7 +541,6 @@ hotkeys={
['Alt-Shift-S,','Text editor : Select the line '],
['Ctrl-Alt-G', 'MANIPULATOR (transform widget): set in Size Mode'],
['Shift-S', 'Cursor/Grid snap menu'],
-['Shift-S', 'Sculpt Mode: Smooth Stroke.'],
['Shift-S+1', 'VIDEO SEQUENCE editor : jump to the current frame '],
['.', '...']
],
@@ -570,7 +556,7 @@ hotkeys={
['Alt-T', 'Clear tracking of object'],
['Ctrl-T', 'Make selected object track active object'],
['Ctrl-T', 'Edit Mode: Convert to triangles'],
-['Ctrl-Alt-T', 'Benchmark'],
+['Ctrl-ALT-T', 'Benchmark'],
['.', '...']
],
@@ -608,18 +594,9 @@ hotkeys={
"W":[
['W', 'Edit Mode: Specials menu'],
['W', 'Edit Mode: Specials menu, ARMATURE 1 Subdivide'],
-['W', 'Edit Mode: Specials menu, ARMATURE 2 Subdivide Multi'],
-['W', 'Edit Mode: Specials menu, ARMATURE 3 Switch Direction'],
-['W', 'Edit Mode: Specials menu, ARMATURE 4 Flip Left-Right Name'],
-['W', 'Edit Mode: Specials menu, ARMATURE 5 AutoName Left-Right'],
-['W', 'Edit Mode: Specials menu, ARMATURE 6 AutoName Front-Back'],
-['W', 'Edit Mode: Specials menu, ARMATURE 7 AutoName Top-Bottom'],
+['W', 'Edit Mode: Specials menu, ARMATURE 2 Flip Left-Right Name'],
['W', 'Edit Mode: Specials menu, CURVE 1 Subdivide'],
['W', 'Edit Mode: Specials menu, CURVE 2 Swich Direction'],
-['W', 'Edit Mode: Specials menu, CURVE 3 Set Goal Weight'],
-['W', 'Edit Mode: Specials menu, CURVE 4 Set Radius'],
-['W', 'Edit Mode: Specials menu, CURVE 5 Smooth'],
-['W', 'Edit Mode: Specials menu, CURVE 6 Smooth Radius'],
['W', 'Edit Mode: Specials menu, MESH 1 Subdivide'],
['W', 'Edit Mode: Specials menu, MESH 2 Subdivide Multi'],
['W', 'Edit Mode: Specials menu, MESH 3 Subdivide Multi Fractal'],
@@ -647,6 +624,7 @@ hotkeys={
['WY', 'UV Image Editor: Weld/Align Y axis'],
['Ctrl-W', 'Save current file'] ,
['Shift-W', 'Warp/bend selected vertices around cursor'],
+['alt-W', 'Export in videoscape format'],
['.', '...']
],
@@ -657,7 +635,6 @@ hotkeys={
['X', 'IPO : Remove marker'],
['X', 'NODE window : delete'], #243
['Alt-X', 'Text Editor : Cut '],
-['Alt-X', 'Grease Pencil: Delete menu'],
['Ctrl-X', 'Restore default state (Erase all)'],
['.', '...']
],
diff --git a/release/scripts/image_auto_layout.py b/release/scripts/image_auto_layout.py
index c6f97a25434..19ee396c3b1 100644
--- a/release/scripts/image_auto_layout.py
+++ b/release/scripts/image_auto_layout.py
@@ -265,8 +265,8 @@ def consolidate_mesh_images(mesh_list, scn, PREF_IMAGE_PATH, PREF_IMAGE_SIZE, PR
render_context.setRenderWinSize(100)
render_context.setImageType(Render.PNG)
render_context.enableExtensions(True)
- render_context.enablePremultiply() # No alpha needed.
- render_context.enableRGBAColor()
+ render_context.enableSky() # No alpha needed.
+ render_context.enableRGBColor()
render_context.threads = 2
#Render.EnableDispView() # Broken??
@@ -275,9 +275,8 @@ def consolidate_mesh_images(mesh_list, scn, PREF_IMAGE_PATH, PREF_IMAGE_SIZE, PR
render_mat= B.Material.New()
render_mat.mode |= B.Material.Modes.SHADELESS
render_mat.mode |= B.Material.Modes.TEXFACE
- render_mat.mode |= B.Material.Modes.ZTRANSP
- render_mat.setAlpha(0.0)
-
+
+
render_me= B.Mesh.New()
render_me.verts.extend([Vector(0,0,0)]) # Stupid, dummy vert, preverts errors. when assigning UV's/
render_ob= B.Object.New('Mesh')
diff --git a/release/scripts/image_edit.py b/release/scripts/image_edit.py
index cae40b74097..a7132a4f986 100644
--- a/release/scripts/image_edit.py
+++ b/release/scripts/image_edit.py
@@ -1,6 +1,6 @@
#!BPY
"""
-Name: 'Edit Externally'
+Name: 'Edit Externaly'
Blender: 242a
Group: 'Image'
Tooltip: 'Open in an application for editing. (hold Shift to configure)'
@@ -9,23 +9,22 @@ Tooltip: 'Open in an application for editing. (hold Shift to configure)'
__author__ = "Campbell Barton"
__url__ = ["blender", "blenderartists.org"]
__version__ = "1.0"
+
__bpydoc__ = """\
This script opens the current image in an external application for editing.
-Usage:
+Useage:
Choose an image for editing in the UV/Image view.
-To configure the application to open the image with, hold Shift as you
-click on this menu item.
+To configure the application to open the image with, hold Shift as you click on
+this menu item.
-For first time users try running the default application for your
-operating system. If the application does not open you can type in
-the full path. You can choose that the last entered application will
-be saved as a default.
+For first time users try running the default application for your operating system.
+If the application does not open you can type in the full path.
+You can choose that the last entered application will be saved as a default.
-* Note, default commants for opening an image are "start" for win32
-and "open" for macos. This will use the system default associated
-application.
+* Note, default commants for opening an image are "start" for win32 and "open" for macos.
+This will use the system default assosiated application.
"""
# ***** BEGIN GPL LICENSE BLOCK *****
@@ -49,36 +48,17 @@ application.
# ***** END GPL LICENCE BLOCK *****
# --------------------------------------------------------------------------
-import Blender
-from Blender import Image, sys, Draw, Registry
try:
- import subprocess
+ import os
import sys as py_sys
platform = py_sys.platform
except:
- Draw.PupMenu('Error: Recent version of Python not installed.')
- subprocess=None
+ Draw.PupMenu('Error, python not installed')
+ os=None
-def os_run(appstring, filename):
- '''
- Run the app, take into account different python versions etc
- looks like python 2.6 wants a list for
- '''
-
- # evil trick, temp replace spaces so we can allow spaces in filenames
- # also allows multiple instances of %f
- appstring = appstring.replace(' ', '\t')
- appstring = appstring.replace('%f', filename)
- appstring = appstring.split('\t')
-
- print ' '.join(appstring)
-
- try: # only python 2.6 wants a list?
- p = subprocess.Popen(appstring)
- except:
- p = subprocess.Popen(' '.join(appstring))
-
+import Blender
+from Blender import Image, sys, Draw, Registry
def edit_extern(image=None):
@@ -86,7 +66,7 @@ def edit_extern(image=None):
image = Image.GetCurrent()
if not image: # Image is None
- Draw.PupMenu('ERROR: Please select active Image.')
+ Draw.PupMenu('ERROR: You must select an active Image.')
return
if image.packed:
Draw.PupMenu('ERROR: Image is packed, unpack before editing.')
@@ -114,19 +94,16 @@ def edit_extern(image=None):
if new_text:
pupblock.append('first time, set path.')
if platform == 'win32':
- # Example of path to popular image editor... ;-)
- # appstring = '"C:\\Program Files\\Adobe\\Photoshop CS\\photoshop.exe" "%f"'
- # Have to add "cmd /c" to make sure we're using Windows shell.
- appstring = 'cmd /c start "" /B "%f"'
+ appstring = 'start "" /B "%f"'
elif platform == 'darwin':
appstring = 'open "%f"'
else:
- appstring = 'gimp %f'
+ appstring = 'gimp-remote "%f"'
appstring_but = Draw.Create(appstring)
save_default_but = Draw.Create(0)
- pupblock.append(('editor: ', appstring_but, 0, 99, 'Path to application, %f will be replaced with the image path.'))
+ pupblock.append(('editor: ', appstring_but, 0, 48, 'Path to application, %f will be replaced with the image path.'))
pupblock.append(('Set Default', save_default_but, 'Store this path in the blender registry.'))
# Only configure if Shift is held,
@@ -141,18 +118,19 @@ def edit_extern(image=None):
Registry.SetKey('ExternalImageEditor', {'path':appstring}, True)
if appstring.find('%f') == -1:
- Draw.PupMenu('ERROR: No filename specified! ("%f")')
+ Draw.PupMenu('ERROR: The comment you entered did not contain the filename ("%f")')
return
# -------------------------------
- os_run(appstring, imageFileName)
-
+ appstring = appstring.replace('%f', imageFileName)
+ print '\tediting image with command "%s"' % appstring
+ os.system(appstring)
def main():
edit_extern()
-if __name__ == '__main__' and subprocess:
- main()
+if __name__ == '__main__' and os != None:
+ main() \ No newline at end of file
diff --git a/release/scripts/import_dxf.py b/release/scripts/import_dxf.py
index 6a1981bb262..bb0119a9a81 100644
--- a/release/scripts/import_dxf.py
+++ b/release/scripts/import_dxf.py
@@ -7,7 +7,7 @@ Group: 'Import'
Tooltip: 'Import for DXF geometry data (Drawing eXchange Format).'
"""
__author__ = 'Kitsu(Ed Blake) & migius(Remigiusz Fiedler)'
-__version__ = '1.12 - 2008.11.16 by migius'
+__version__ = '1.12 - 2008.08.03 by migius'
__url__ = ["http://blenderartists.org/forum/showthread.php?t=84319",
"http://wiki.blender.org/index.php/Scripts/Manual/Import/DXF-3D"]
__email__ = ["migius(at)4d-vectors.de","Kitsune_e(at)yahoo.com"]
@@ -111,9 +111,6 @@ History:
-- support ortho mode for VIEWs and VPORTs as cameras
- v1.12 - 2008.11.16 by migius
- d1 remove try_finally: cause not supported in python <2.5
- d1 add Bezier curves bevel radius support (default 1.0)
v1.12 - 2008.08.03 by migius
c2 warningfix: relocating of globals: layersmap, oblist
c2 modif UI: buttons newScene+targetLayer moved to start panel
@@ -302,7 +299,7 @@ History:
import Blender
from Blender import *
#from Blender.Mathutils import Vector, Matrix
-#import bpy #not used yet
+import bpy
#import BPyMessages
from dxfReader import readDXF
@@ -314,7 +311,7 @@ from math import *
try:
import os
- if os.name != 'mac':
+ if os.name:# != 'mac':
import psyco
psyco.log(Blender.Get('tempdir')+"/blender.log-psyco")
#psyco.log()
@@ -323,7 +320,7 @@ try:
psyco.profile(0.2)
#print 'psyco imported'
except ImportError:
- print 'psyco not imported'
+ #print 'psyco not imported'
pass
#try: Curve.orderU
@@ -349,7 +346,7 @@ THIN_RESOLUTION = 8 #(4-64) thin_cylinder arc_resolution - number of segments
MIN_THICK = MIN_DIST * 10.0 #minimal thickness by forced thickness
MIN_WIDTH = MIN_DIST * 10.0 #minimal width by forced width
TRIM_LIMIT = 3.0 #limit for triming of polylines-wide-segments (values:0.0 - 5.0)
-ELEVATION = 0.0 #standard elevation = coordinate Z value
+ELEVATION = 0.0 #standard elevation = coordinate Z
BYBLOCK = 0
BYLAYER = 256
@@ -820,7 +817,6 @@ class Line: #-----------------------------------------------------------------
curve.append(BezTriple.New(points[1]))
for point in curve:
point.handleTypes = [VECT, VECT]
- point.radius = 1.0
curve.flagU = 0 # 0 sets the curve not cyclic=open
c.setResolu(settings.var['curve_res'])
c.update() #important for handles calculation
@@ -1345,11 +1341,9 @@ class Polyline: #--------------------------------------------------------------
nurbs_points.append(pkt)
firstpoint = nurbs_points[0]
curve = pline.appendNurb(firstpoint)
- curve.setType(4) # set curve_type NURBS
- print 'deb: dir(curve):', dir(curve[-1]) #----------------
+ curve.setType(4) # set curvetype NURBS
for point in nurbs_points[1:]:
curve.append(point)
- #TODO: what is the trick for bevel radius? curve[-1].radius = 1.0
if self.closed:
curve.flagU = 1+0 # Set curve cyclic=close and uni
else:
@@ -1365,7 +1359,6 @@ class Polyline: #--------------------------------------------------------------
curve.append(BezTriple.New(p))
for point in curve:
point.handleTypes = [AUTO, AUTO]
- point.radius = 1.0
if self.closed:
curve.flagU = 1 # Set curve cyclic=close
else:
@@ -1387,7 +1380,6 @@ class Polyline: #--------------------------------------------------------------
curve.append(BezTriple.New(p))
for point in curve:
point.handleTypes = [AUTO, AUTO]
- point.radius = 1.0
#curve.setType(1) #Bezier curve
if self.closed:
curve.flagU = 5 #1 # Set curve cyclic=close
@@ -1400,7 +1392,6 @@ class Polyline: #--------------------------------------------------------------
p0h1 = [p0h1[i]+begtangent[i] for i in range(3)]
curve.__setitem__(0,BezTriple.New(p0h1+p0+p0h2))
curve[0].handleTypes = [FREE, ALIGN] #remi--todo-----
- curve[0].radius = 1.0
if endtangent:
#print 'deb:polyline2dCurve.draw curve[-1].vec:', curve[-1].vec #-----
#print 'deb:polyline2dCurve.draw endtangent:', endtangent #-----
@@ -1410,7 +1401,6 @@ class Polyline: #--------------------------------------------------------------
curve.__setitem__(-1,BezTriple.New(p0h1+p0+p0h2))
#print 'deb:polyline2dCurve.draw curve[-1].vec:', curve[-1].vec #-----
curve[-1].handleTypes = [ALIGN, FREE] #remi--todo-----
- curve[-1].radius = 1.0
@@ -1430,16 +1420,13 @@ class Polyline: #--------------------------------------------------------------
if i == 0: curve = pline.appendNurb(BezTriple.New(verts[0]))
else: curve.append(BezTriple.New(verts[0]))
curve[-1].handleTypes = [VECT, VECT] #--todo--calculation of bezier-tangents
- curve[-1].radius = 1.0
for p in verts[1:]:
curve.append(BezTriple.New(p))
curve[-1].handleTypes = [AUTO, AUTO]
- curve[-1].radius = 1.0
else:
if i == 0: curve = pline.appendNurb(BezTriple.New(point1.loc))
else: curve.append(BezTriple.New(point1.loc))
curve[-1].handleTypes = [VECT, VECT] #--todo--calculation of bezier-tangents
- curve[-1].radius = 1.0
elif True: #----- optimised Bezier-Handles calculation --------------------------------
#print 'deb:drawPlineCurve: i:', i #---------
@@ -1459,12 +1446,10 @@ class Polyline: #--------------------------------------------------------------
if i == 0: curve = pline.appendNurb(BezTriple.New(VectorTriples[0]))
else: curve.append(BezTriple.New(VectorTriples[0]))
curve[-1].handleTypes = [prevHandleType, FREE]
- curve[-1].radius = 1.0
for p in VectorTriples[1:-1]:
curve.append(BezTriple.New(p))
curve[-1].handleTypes = [FREE, FREE]
- curve[-1].radius = 1.0
prevHandleVect = VectorTriples[-1][:3]
prevHandleType = FREE
@@ -1477,13 +1462,11 @@ class Polyline: #--------------------------------------------------------------
curve.append(BezTriple.New(VectorTriples))
curve[-1].handleTypes = [FREE, VECT]
prevHandleType = VECT
- curve[-1].radius = 1.0
else:
if i == 0: curve = pline.appendNurb(BezTriple.New(point1.loc))
else: curve.append(BezTriple.New(point1.loc))
curve[-1].handleTypes = [VECT, VECT]
- curve[-1].radius = 1.0
-
+
#print 'deb:drawPlineCurve: curve[-1].vec[0]', curve[-1].vec[0] #----------
@@ -1503,12 +1486,10 @@ class Polyline: #--------------------------------------------------------------
curve.__setitem__(0,BezTriple.New(p0h1+p0+p0h2))
curve[0].handleTypes = [FREE,prevHandleType2]
- curve[0].radius = 1.0
#print 'deb:drawPlineCurve:closed curve[0].vec:', curve[0].vec #----------
#print 'deb:drawPlineCurve:closed curve[0].handleTypes:', curve[0].handleTypes #----------
else:
curve[0].handleTypes[0] = VECT
- curve[0].radius = 1.0
else:
curve.flagU = 0 # Set curve not cyclic=open
@@ -2196,10 +2177,9 @@ DXF: X value; APP: 3D point, Y and Z values of control points (in WCS) (one entr
self.ctrlpk_len = getit(obj, 73, 0) # Number of control points
self.fit_pk_len = getit(obj, 74, 0) # Number of fit points (if any)
- #TODO: import SPLINE as Bezier curve directly, possible?
#print 'deb:Spline self.fit_pk_len=', self.fit_pk_len #------------------------
#self.fit_pk_len = 0 # temp for debug
- if self.fit_pk_len and settings.var['splines_as']==5:
+ if self.fit_pk_len and 'spline_as'==5:
self.spline = False
self.curved = True
else:
@@ -2695,7 +2675,6 @@ class Circle: #----------------------------------------------------------------
curve.append(BezTriple.New(p))
for point in curve:
point.handleTypes = [FREE, FREE]
- point.radius = 1.0
else: # standard version
c = Curve.New(obname) # create new curve data
p1 = (0, -radius, 0)
@@ -2714,7 +2693,6 @@ class Circle: #----------------------------------------------------------------
curve.append(p4)
for point in curve:
point.handleTypes = [AUTO, AUTO]
- point.radius = 1.0
curve.flagU = 1 # 1 sets the curve cyclic=closed
if settings.var['fill_on']:
@@ -2915,7 +2893,6 @@ class Arc: #-----------------------------------------------------------------
curve.append(BezTriple.New(p))
for point in curve:
point.handleTypes = [FREE, FREE]
- point.radius = 1.0
curve.flagU = 0 # 0 sets the curve not cyclic=open
arc.setResolu(settings.var['curve_res'])
@@ -3472,7 +3449,6 @@ class Ellipse: #---------------------------------------------------------------
curve.append(BezTriple.New(p))
for point in curve:
point.handleTypes = [FREE, FREE]
- point.radius = 1.0
curve.flagU = 1 # 0 sets the curve not cyclic=open
if settings.var['fill_on']:
arc.setFlag(6) # 2+4 set top and button caps
@@ -3483,7 +3459,6 @@ class Ellipse: #---------------------------------------------------------------
curve.append(BezTriple.New(p))
for point in curve:
point.handleTypes = [FREE, FREE]
- point.radius = 1.0
curve.flagU = 0 # 0 sets the curve not cyclic=open
arc.setResolu(settings.var['curve_res'])
@@ -4422,7 +4397,8 @@ def analyzeDXF(dxfFile): #---------------------------------------
Draw.PupMenu('DXF importer: report saved in INF-file:%t|' + '\'%s\'' %infFile)
except:
Draw.PupMenu('DXF importer: ERROR by writing report in INF-file:%t|' + '\'%s\'' %infFile)
- #finally: f.close()
+ finally:
+ f.close()
@@ -4441,8 +4417,7 @@ def main(dxfFile): #---------------#############################-----------
global cur_COUNTER #counter for progress_bar
cur_COUNTER = 0
- #try:
- if 1:
+ try:
#print "Getting settings..."
global GUI_A, GUI_B, g_scale_as
if not GUI_A['g_scale_on'].val:
@@ -4525,7 +4500,7 @@ def main(dxfFile): #---------------#############################-----------
#settings.write(message)
if UI_MODE: Draw.PupMenu('DXF importer: Done!|finished in %.4f sec.' % time_text)
- #finally:
+ finally:
# restore state even if things didn't work
#print 'deb:drawEntities finally!' #-----------------------
Window.WaitCursor(False)
@@ -5215,7 +5190,6 @@ def drawCurveCircle(circle): #--- no more used --------------------------------
curve.append(p4)
for point in curve:
point.handleTypes = [AUTO, AUTO]
- point.radius = 1.0
curve.flagU = 1 # Set curve cyclic
c.update()
@@ -5257,7 +5231,6 @@ def drawCurveArc(self): #---- only for ELLIPSE --------------------------------
curve.append(p4)
for point in curve:
point.handleTypes = [AUTO, AUTO]
- point.radius = 1.0
curve.flagU = 1 # Set curve cyclic
a.update()
@@ -5297,12 +5270,12 @@ GUI_B = {} # GUI-buttons dictionary for drawingTypes
# settings default, initialize ------------------------
points_as_menu = "convert to: %t|empty %x1|mesh.vertex %x2|thin sphere %x3|thin box %x4|*curve.vertex %x5"
-lines_as_menu = "convert to: %t|*edge %x1|mesh %x2|*thin cylinder %x3|thin box %x4|Bezier-curve %x5|*NURBS-curve %x6"
+lines_as_menu = "convert to: %t|*edge %x1|mesh %x2|*thin cylinder %x3|thin box %x4|Bezier-curve %x5|NURBS-curve %x6"
mlines_as_menu = "convert to: %t|*edge %x1|*mesh %x2|*thin cylinder %x3|*thin box %x|*curve %x5"
plines_as_menu = "convert to: %t|*edge %x1|mesh %x2|*thin cylinder %x3|*thin box %x4|Bezier-curve %x5|NURBS-curve %x6"
-splines_as_menu = "convert to: %t|mesh %x2|*thin cylinder %x3|*thin box %x4|*Bezier-curve %x5|NURBS-curve %x6"
+splines_as_menu = "convert to: %t|mesh %x2|*thin cylinder %x3|*thin box %x4|Bezier-curve %x5|NURBS-curve %x6"
plines3_as_menu = "convert to: %t|*edge %x1|mesh %x2|*thin cylinder %x3|*thin box %x4|Bezier-curve %x5|NURBS-curve %x6"
-plmesh_as_menu = "convert to: %t|*edge %x1|mesh %x2|*NURBS-surface %x6"
+plmesh_as_menu = "convert to: %t|*edge %x1|mesh %x2|NURBS-surface %x6"
solids_as_menu = "convert to: %t|*edge %x1|mesh %x2"
blocks_as_menu = "convert to: %t|dupliGroup %x1|*real.Group %x2|*exploded %x3"
texts_as_menu = "convert to: %t|text %x1|*mesh %x2|*curve %x5"
@@ -5483,9 +5456,11 @@ def saveConfig(): #--todo-----------------------------------------------
else:
#if BPyMessages.Warning_SaveOver(iniFile): #<- remi find it too abstarct
if sys.exists(iniFile):
- f = file(iniFile, 'r')
- header_str = f.readline()
- f.close()
+ try:
+ f = file(iniFile, 'r')
+ try: header_str = f.readline()
+ finally: f.close()
+ except: pass
if header_str.startswith(INIFILE_HEADER[0:13]):
if Draw.PupMenu(' OK ? %t|SAVE OVER: ' + '\'%s\'' %iniFile) == 1:
save_ok = True
@@ -5505,9 +5480,10 @@ def saveConfig(): #--todo-----------------------------------------------
output_str = '{\n'.join(output_str.split('{'))
try:
f = file(iniFile, 'w')
- f.write(INIFILE_HEADER + '\n# this is a comment line\n')
- f.write(output_str)
- f.close()
+ try:
+ f.write(INIFILE_HEADER + '\n# this is a comment line\n')
+ f.write(output_str)
+ finally: f.close()
#Draw.PupMenu('DXF importer: INI-file: Done!%t|config-data saved in ' + '\'%s\'' %iniFile)
except:
Draw.PupMenu('DXF importer: INI-file: Error!%t|failure by writing to ' + '\'%s\'|no config-data saved!' %iniFile)
@@ -5532,22 +5508,25 @@ def loadConfig(): #remi--todo-----------------------------------------------
update_RegistryKey('iniFileName', iniFile)
#print 'deb:loadConfig iniFile: ', iniFile #----------------------
if iniFile.lower().endswith(INIFILE_EXTENSION) and sys.exists(iniFile):
- f = file(iniFile, 'r')
- header_str = f.readline()
- if header_str.startswith(INIFILE_HEADER):
- data_str = f.read()
- f.close()
- #print 'deb:loadConfig data_str from %s: \n' %iniFile , data_str #-----------------
- data = eval(data_str)
- for k, v in data[0].iteritems():
- try: GUI_A[k].val = v
- except: GUI_A[k] = Draw.Create(v)
- for k, v in data[1].iteritems():
- try: GUI_B[k].val = v
- except: GUI_B[k] = Draw.Create(v)
- else:
- f.close()
- Draw.PupMenu('DXF importer: INI-file: Alert!%t|no valid header in INI-file: ' + '\'%s\'' %iniFile)
+ try:
+ f = file(iniFile, 'r')
+ try:
+ header_str = f.readline()
+ if header_str.startswith(INIFILE_HEADER):
+ data_str = f.read()
+ f.close()
+ #print 'deb:loadConfig data_str from %s: \n' %iniFile , data_str #-----------------
+ data = eval(data_str)
+ for k, v in data[0].iteritems():
+ try: GUI_A[k].val = v
+ except: GUI_A[k] = Draw.Create(v)
+ for k, v in data[1].iteritems():
+ try: GUI_B[k].val = v
+ except: GUI_B[k] = Draw.Create(v)
+ else:
+ Draw.PupMenu('DXF importer: INI-file: Alert!%t|no valid header in INI-file: ' + '\'%s\'' %iniFile)
+ finally: f.close()
+ except: pass
else:
Draw.PupMenu('DXF importer: INI-file: Alert!%t|no valid INI-file selected!')
print "DXF importer: Alert!: no valid INI-file selected."
diff --git a/release/scripts/import_lightwave_motion.py b/release/scripts/import_lightwave_motion.py
index 20c87dfd5c6..c242a9f6bd3 100644
--- a/release/scripts/import_lightwave_motion.py
+++ b/release/scripts/import_lightwave_motion.py
@@ -22,7 +22,7 @@ Be sure to set the framerate correctly
"""
-# $Id$
+# $Id: export_lightwave_motion.py 9924 2007-01-27 02:15:14Z campbellbarton $
# --------------------------------------------------------------------------
# ***** BEGIN GPL LICENSE BLOCK *****
#
diff --git a/release/scripts/import_obj.py b/release/scripts/import_obj.py
index 3aad0800cf7..e5bdc796e16 100644
--- a/release/scripts/import_obj.py
+++ b/release/scripts/import_obj.py
@@ -2,14 +2,14 @@
"""
Name: 'Wavefront (.obj)...'
-Blender: 248
+Blender: 242
Group: 'Import'
Tooltip: 'Load a Wavefront OBJ File, Shift: batch import all dir.'
"""
__author__= "Campbell Barton", "Jiri Hnidek"
-__url__= ['http://wiki.blender.org/index.php/Scripts/Manual/Import/wavefront_obj', 'blender.org', 'blenderartists.org']
-__version__= "2.1"
+__url__= ["blender.org", "blenderartists.org"]
+__version__= "2.0"
__bpydoc__= """\
This script imports a Wavefront OBJ files to Blender.
@@ -182,7 +182,7 @@ def create_materials(filepath, material_libs, unique_materials, unique_material_
else:
#print '\t\tloading mtl: "%s"' % mtlpath
context_material= None
- mtl= open(mtlpath, 'rU')
+ mtl= open(mtlpath)
for line in mtl: #.xreadlines():
if line.startswith('newmtl'):
context_material_name= line_value(line.split())
@@ -194,7 +194,7 @@ def create_materials(filepath, material_libs, unique_materials, unique_material_
elif context_material:
# we need to make a material to assign properties to it.
line_split= line.split()
- line_lower= line.lower().lstrip()
+ line_lower= line.lower()
if line_lower.startswith('ka'):
context_material.setMirCol((float(line_split[1]), float(line_split[2]), float(line_split[3])))
elif line_lower.startswith('kd'):
@@ -588,7 +588,7 @@ def load_obj(filepath, CLAMP_SIZE= 0.0, CREATE_FGONS= True, CREATE_SMOOTH_GROUPS
print '\tpassing obj file "%s"...' % filepath,
time_sub= sys.time()
- file= open(filepath, 'rU')
+ file= open(filepath, 'r')
for line in file: #.xreadlines():
if line.startswith('v '):
@@ -756,22 +756,19 @@ def load_obj_ui(filepath, BATCH_LOAD= False):
if BPyMessages.Error_NoFile(filepath):
return
- global CREATE_SMOOTH_GROUPS, CREATE_FGONS, CREATE_EDGES, SPLIT_OBJECTS, SPLIT_GROUPS, SPLIT_MATERIALS, CLAMP_SIZE, IMAGE_SEARCH, KEEP_VERT_ORDER
CREATE_SMOOTH_GROUPS= Draw.Create(0)
CREATE_FGONS= Draw.Create(1)
CREATE_EDGES= Draw.Create(1)
- SPLIT_OBJECTS= Draw.Create(0)
- SPLIT_GROUPS= Draw.Create(0)
- SPLIT_MATERIALS= Draw.Create(0)
+ SPLIT_OBJECTS= Draw.Create(1)
+ SPLIT_GROUPS= Draw.Create(1)
+ SPLIT_MATERIALS= Draw.Create(1)
+ MORPH_TARGET= Draw.Create(0)
CLAMP_SIZE= Draw.Create(10.0)
IMAGE_SEARCH= Draw.Create(1)
- KEEP_VERT_ORDER= Draw.Create(1)
# Get USER Options
- # Note, Works but not pretty, instead use a more complicated GUI
- '''
pup_block= [\
'Import...',\
('Smooth Groups', CREATE_SMOOTH_GROUPS, 'Surround smooth groups by sharp edges'),\
@@ -782,7 +779,7 @@ def load_obj_ui(filepath, BATCH_LOAD= False):
('Group', SPLIT_GROUPS, 'Import OBJ Groups into Blender Objects'),\
('Material', SPLIT_MATERIALS, 'Import each material into a seperate mesh (Avoids > 16 per mesh error)'),\
'Options...',\
- ('Keep Vert Order', KEEP_VERT_ORDER, 'Keep vert and face order, disables some other options.'),\
+ ('Morph Target', MORPH_TARGET, 'Keep vert and face order, disables some other options.'),\
('Clamp Scale:', CLAMP_SIZE, 0.0, 1000.0, 'Clamp the size to this maximum (Zero to Disable)'),\
('Image Search', IMAGE_SEARCH, 'Search subdirs for any assosiated images (Warning, may be slow)'),\
]
@@ -790,106 +787,10 @@ def load_obj_ui(filepath, BATCH_LOAD= False):
if not Draw.PupBlock('Import OBJ...', pup_block):
return
- if KEEP_VERT_ORDER.val:
+ if MORPH_TARGET.val:
SPLIT_OBJECTS.val = False
SPLIT_GROUPS.val = False
SPLIT_MATERIALS.val = False
- '''
-
-
-
- # BEGIN ALTERNATIVE UI *******************
- if True:
-
- EVENT_NONE = 0
- EVENT_EXIT = 1
- EVENT_REDRAW = 2
- EVENT_IMPORT = 3
-
- GLOBALS = {}
- GLOBALS['EVENT'] = EVENT_REDRAW
- #GLOBALS['MOUSE'] = Window.GetMouseCoords()
- GLOBALS['MOUSE'] = [i/2 for i in Window.GetScreenSize()]
-
- def obj_ui_set_event(e,v):
- GLOBALS['EVENT'] = e
-
- def do_split(e,v):
- global SPLIT_OBJECTS, SPLIT_GROUPS, SPLIT_MATERIALS, KEEP_VERT_ORDER
- if SPLIT_OBJECTS.val or SPLIT_GROUPS.val or SPLIT_MATERIALS.val:
- KEEP_VERT_ORDER.val = 0
- else:
- KEEP_VERT_ORDER.val = 1
-
- def do_vertorder(e,v):
- global SPLIT_OBJECTS, SPLIT_GROUPS, SPLIT_MATERIALS, KEEP_VERT_ORDER
- if KEEP_VERT_ORDER.val:
- SPLIT_OBJECTS.val = SPLIT_GROUPS.val = SPLIT_MATERIALS.val = 0
- else:
- if not (SPLIT_OBJECTS.val or SPLIT_GROUPS.val or SPLIT_MATERIALS.val):
- KEEP_VERT_ORDER.val = 1
-
- def do_help(e,v):
- url = __url__[0]
- print 'Trying to open web browser with documentation at this address...'
- print '\t' + url
-
- try:
- import webbrowser
- webbrowser.open(url)
- except:
- print '...could not open a browser window.'
-
- def obj_ui():
- ui_x, ui_y = GLOBALS['MOUSE']
-
- # Center based on overall pup size
- ui_x -= 165
- ui_y -= 90
-
- global CREATE_SMOOTH_GROUPS, CREATE_FGONS, CREATE_EDGES, SPLIT_OBJECTS, SPLIT_GROUPS, SPLIT_MATERIALS, CLAMP_SIZE, IMAGE_SEARCH, KEEP_VERT_ORDER
-
- Draw.Label('Import...', ui_x+9, ui_y+159, 220, 21)
- Draw.BeginAlign()
- CREATE_SMOOTH_GROUPS = Draw.Toggle('Smooth Groups', EVENT_NONE, ui_x+9, ui_y+139, 110, 20, CREATE_SMOOTH_GROUPS.val, 'Surround smooth groups by sharp edges')
- CREATE_FGONS = Draw.Toggle('NGons as FGons', EVENT_NONE, ui_x+119, ui_y+139, 110, 20, CREATE_FGONS.val, 'Import faces with more then 4 verts as fgons')
- CREATE_EDGES = Draw.Toggle('Lines as Edges', EVENT_NONE, ui_x+229, ui_y+139, 110, 20, CREATE_EDGES.val, 'Import lines and faces with 2 verts as edges')
- Draw.EndAlign()
-
- Draw.Label('Separate objects by OBJ...', ui_x+9, ui_y+110, 220, 20)
- Draw.BeginAlign()
- SPLIT_OBJECTS = Draw.Toggle('Object', EVENT_REDRAW, ui_x+9, ui_y+89, 70, 21, SPLIT_OBJECTS.val, 'Import OBJ Objects into Blender Objects', do_split)
- SPLIT_GROUPS = Draw.Toggle('Group', EVENT_REDRAW, ui_x+79, ui_y+89, 70, 21, SPLIT_GROUPS.val, 'Import OBJ Groups into Blender Objects', do_split)
- SPLIT_MATERIALS = Draw.Toggle('Material', EVENT_REDRAW, ui_x+149, ui_y+89, 70, 21, SPLIT_MATERIALS.val, 'Import each material into a seperate mesh (Avoids > 16 per mesh error)', do_split)
- Draw.EndAlign()
-
- # Only used for user feedback
- KEEP_VERT_ORDER = Draw.Toggle('Keep Vert Order', EVENT_REDRAW, ui_x+229, ui_y+89, 110, 21, KEEP_VERT_ORDER.val, 'Keep vert and face order, disables split options, enable for morph targets', do_vertorder)
-
- Draw.Label('Options...', ui_x+9, ui_y+60, 211, 20)
- CLAMP_SIZE = Draw.Number('Clamp Scale: ', EVENT_NONE, ui_x+9, ui_y+39, 211, 21, CLAMP_SIZE.val, 0.0, 1000.0, 'Clamp the size to this maximum (Zero to Disable)')
- IMAGE_SEARCH = Draw.Toggle('Image Search', EVENT_NONE, ui_x+229, ui_y+39, 110, 21, IMAGE_SEARCH.val, 'Search subdirs for any assosiated images (Warning, may be slow)')
- Draw.BeginAlign()
- Draw.PushButton('Online Help', EVENT_REDRAW, ui_x+9, ui_y+9, 110, 21, 'Load the wiki page for this script', do_help)
- Draw.PushButton('Cancel', EVENT_EXIT, ui_x+119, ui_y+9, 110, 21, '', obj_ui_set_event)
- Draw.PushButton('Import', EVENT_IMPORT, ui_x+229, ui_y+9, 110, 21, 'Import with these settings', obj_ui_set_event)
- Draw.EndAlign()
-
-
- # hack so the toggle buttons redraw. this is not nice at all
- while GLOBALS['EVENT'] not in (EVENT_EXIT, EVENT_IMPORT):
- Draw.UIBlock(obj_ui, 0)
-
- if GLOBALS['EVENT'] != EVENT_IMPORT:
- return
-
- # END ALTERNATIVE UI *********************
-
-
-
-
-
-
Window.WaitCursor(1)
@@ -958,7 +859,7 @@ else:
os.system('find /fe/obj -iname "*.obj" > /tmp/temp3ds_list')
print '...Done'
- file= open('/tmp/temp3ds_list', 'rU')
+ file= open('/tmp/temp3ds_list', 'r')
lines= file.readlines()
file.close()
diff --git a/release/scripts/import_web3d.py b/release/scripts/import_web3d.py
deleted file mode 100755
index 7542afcb5b9..00000000000
--- a/release/scripts/import_web3d.py
+++ /dev/null
@@ -1,2506 +0,0 @@
-#!BPY
-"""
-Name: 'X3D & VRML97 (.x3d / wrl)...'
-Blender: 248
-Group: 'Import'
-Tooltip: 'Load an X3D or VRML97 file'
-"""
-
-# ***** BEGIN GPL LICENSE BLOCK *****
-#
-# (C) Copyright 2008 Paravizion
-# Written by Campbell Barton aka Ideasman42
-#
-# This program is free software; you can redistribute it and/or
-# modify it under the terms of the GNU General Public License
-# as published by the Free Software Foundation; either version 2
-# of the License, or (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software Foundation,
-# Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
-#
-# ***** END GPL LICENCE BLOCK *****
-# --------------------------------------------------------------------------
-
-__author__ = "Campbell Barton"
-__url__ = ['www.blender.org', 'blenderartists.org', 'http://wiki.blender.org/index.php/Scripts/Manual/Import/X3D_VRML97']
-__version__ = "0.1"
-
-__bpydoc__ = """\
-This script is an importer for the X3D and VRML97 file formats.
-"""
-
-DEBUG = False
-
-# This should work without a blender at all
-try:
- from Blender.sys import exists
-except:
- from os.path import exists
-
-def baseName(path):
- return path.split('/')[-1].split('\\')[-1]
-
-def dirName(path):
- return path[:-len(baseName(path))]
-
-def imageConvertCompat(path):
-
- try: import os
- except:
- return path
-
- if path.endswith('.gif'):
- path_to = path[:-3] + 'png'
-
- '''
- if exists(path_to):
- return path_to
- '''
- # print '\n'+path+'\n'+path_to+'\n'
- os.system('convert "%s" "%s"' % (path, path_to)) # for now just hope we have image magick
-
- if exists(path_to):
- return path_to
-
- return path
-
-# notes
-# transform are relative
-# order dosnt matter for loc/size/rot
-# right handed rotation
-# angles are in radians
-# rotation first defines axis then ammount in radians
-
-
-
-# =============================== VRML Spesific
-
-
-def vrmlFormat(data):
- '''
- Keep this as a valid vrml file, but format in a way we can pradict.
- '''
- # Strip all commends - # not in strings - warning multiline strings are ignored.
- def strip_comment(l):
- #l = ' '.join(l.split())
- l = l.strip()
-
- if l.startswith('#'):
- return ''
-
- i = l.find('#')
-
- if i==-1:
- return l
-
- # Most cases accounted for! if we have a comment at the end of the line do this...
- #j = l.find('url "')
- j = l.find('"')
-
- if j == -1: # simple no strings
- return l[:i].strip()
-
- q = False
- for i,c in enumerate(l):
- if c == '"':
- q = not q # invert
-
- elif c == '#':
- if q==False:
- return l[:i-1]
-
- return l
-
- data = '\n'.join([strip_comment(l) for l in data.split('\n') ]) # remove all whitespace
-
- EXTRACT_STRINGS = True # only needed when strings or filesnames containe ,[]{} chars :/
-
- if EXTRACT_STRINGS:
-
- # We need this so we can detect URL's
- data = '\n'.join([' '.join(l.split()) for l in data.split('\n')]) # remove all whitespace
-
- string_ls = []
-
- #search = 'url "'
- search = '"'
-
- ok = True
- last_i = 0
- while ok:
- ok = False
- i = data.find(search, last_i)
- if i != -1:
-
- start = i + len(search) # first char after end of search
- end = data.find('"', start)
- if end != -1:
- item = data[start:end]
- string_ls.append( item )
- data = data[:start] + data[end:]
- ok = True # keep looking
-
- last_i = end - len(item) + 1
- # print last_i, item, '|' + data[last_i] + '|'
-
- # done with messy extracting strings part
-
-
-
- # Bad, dont take strings into account
- '''
- data = data.replace('#', '\n#')
- data = '\n'.join([ll for l in data.split('\n') for ll in (l.strip(),) if not ll.startswith('#')]) # remove all whitespace
- '''
- data = data.replace('{', '\n{\n')
- data = data.replace('}', '\n}\n')
- data = data.replace('[', '\n[\n')
- data = data.replace(']', '\n]\n')
- data = data.replace(',', ' , ') # make sure comma's seperate
-
- if EXTRACT_STRINGS:
- # add strings back in
-
- search = '"' # fill in these empty strings
-
- ok = True
- last_i = 0
- while ok:
- ok = False
- i = data.find(search + '"', last_i)
-
- if i != -1:
- start = i + len(search) # first char after end of search
- item = string_ls.pop(0)
- data = data[:start] + item + data[start:]
-
- last_i = start + len(item)
-
- ok = True
-
-
- # More annoying obscure cases where USE or DEF are placed on a newline
- # data = data.replace('\nDEF ', ' DEF ')
- # data = data.replace('\nUSE ', ' USE ')
-
- data = '\n'.join([' '.join(l.split()) for l in data.split('\n')]) # remove all whitespace
-
- # Better to parse the file accounting for multiline arrays
- '''
- data = data.replace(',\n', ' , ') # remove line endings with commas
- data = data.replace(']', '\n]\n') # very very annoying - but some comma's are at the end of the list, must run this again.
- '''
-
- return [l for l in data.split('\n') if l]
-
-NODE_NORMAL = 1 # {}
-NODE_ARRAY = 2 # []
-NODE_REFERENCE = 3 # USE foobar
-# NODE_PROTO = 4 #
-
-lines = []
-
-def getNodePreText(i, words):
- # print lines[i]
- use_node = False
- while len(words) < 5:
-
- if i>=len(lines):
- break
- '''
- elif lines[i].startswith('PROTO'):
- return NODE_PROTO, i+1
- '''
- elif lines[i]=='{':
- # words.append(lines[i]) # no need
- # print "OK"
- return NODE_NORMAL, i+1
- elif lines[i].count('"') % 2 != 0: # odd number of quotes? - part of a string.
- # print 'ISSTRING'
- break
- else:
- new_words = lines[i].split()
- if 'USE' in new_words:
- use_node = True
-
- words.extend(new_words)
- i += 1
-
- # Check for USE node - no {
- # USE #id - should always be on the same line.
- if use_node:
- # print 'LINE', i, words[:words.index('USE')+2]
- words[:] = words[:words.index('USE')+2]
- if lines[i] == '{' and lines[i+1] == '}':
- # USE sometimes has {} after it anyway
- i+=2
- return NODE_REFERENCE, i
-
- # print "error value!!!", words
- return 0, -1
-
-def is_nodeline(i, words):
-
- if not lines[i][0].isalpha():
- return 0, 0
-
- #if lines[i].startswith('field'):
- # return 0, 0
-
- # Is this a prototype??
- if lines[i].startswith('PROTO'):
- words[:] = lines[i].split()
- return NODE_NORMAL, i+1 # TODO - assumes the next line is a '[\n', skip that
- '''
- proto_type, new_i = is_protoline(i, words, proto_field_defs)
- if new_i != -1:
- return proto_type, new_i
- '''
-
- # Simple "var [" type
- if lines[i+1] == '[':
- if lines[i].count('"') % 2 == 0:
- words[:] = lines[i].split()
- return NODE_ARRAY, i+2
-
- node_type, new_i = getNodePreText(i, words)
-
- if not node_type:
- if DEBUG: print "not node_type", lines[i]
- return 0, 0
-
- # Ok, we have a { after some values
- # Check the values are not fields
- for i, val in enumerate(words):
- if i != 0 and words[i-1] in ('DEF', 'USE'):
- # ignore anything after DEF, it is a ID and can contain any chars.
- pass
- elif val[0].isalpha() and val not in ('TRUE', 'FALSE'):
- pass
- else:
- # There is a number in one of the values, therefor we are not a node.
- return 0, 0
-
- #if node_type==NODE_REFERENCE:
- # print words, "REF_!!!!!!!"
- return node_type, new_i
-
-def is_numline(i):
- '''
- Does this line start with a number?
- '''
-
- # Works but too slow.
- '''
- l = lines[i]
- for w in l.split():
- if w==',':
- pass
- else:
- try:
- float(w)
- return True
-
- except:
- return False
-
- return False
- '''
-
- l = lines[i]
-
- line_start = 0
-
- if l.startswith(', '):
- line_start += 2
-
- line_end = len(l)-1
- line_end_new = l.find(' ', line_start) # comma's always have a space before them
-
- if line_end_new != -1:
- line_end = line_end_new
-
- try:
- float(l[line_start:line_end]) # works for a float or int
- return True
- except:
- return False
-
-
-class vrmlNode(object):
- __slots__ = 'id', 'fields', 'proto_node', 'proto_field_defs', 'proto_fields', 'node_type', 'parent', 'children', 'parent', 'array_data', 'reference', 'lineno', 'filename', 'blendObject', 'DEF_NAMESPACE', 'ROUTE_IPO_NAMESPACE', 'PROTO_NAMESPACE', 'x3dNode'
- def __init__(self, parent, node_type, lineno):
- self.id = None
- self.node_type = node_type
- self.parent = parent
- self.blendObject = None
- self.x3dNode = None # for x3d import only
- if parent:
- parent.children.append(self)
-
- self.lineno = lineno
-
- # This is only set from the root nodes.
- # Having a filename also denotes a root node
- self.filename = None
- self.proto_node = None # proto field definition eg: "field SFColor seatColor .6 .6 .1"
-
- # Store in the root node because each inline file needs its own root node and its own namespace
- self.DEF_NAMESPACE = None
- self.ROUTE_IPO_NAMESPACE = None
- '''
- self.FIELD_NAMESPACE = None
- '''
-
-
- self.PROTO_NAMESPACE = None
-
- self.reference = None
-
- if node_type==NODE_REFERENCE:
- # For references, only the parent and ID are needed
- # the reference its self is assigned on parsing
- return
-
- self.fields = [] # fields have no order, in some cases rool level values are not unique so dont use a dict
-
- self.proto_field_defs = [] # proto field definition eg: "field SFColor seatColor .6 .6 .1"
- self.proto_fields = [] # proto field usage "diffuseColor IS seatColor"
- self.children = []
- self.array_data = [] # use for arrays of data - should only be for NODE_ARRAY types
-
-
- # Only available from the root node
- '''
- def getFieldDict(self):
- if self.FIELD_NAMESPACE != None:
- return self.FIELD_NAMESPACE
- else:
- return self.parent.getFieldDict()
- '''
- def getProtoDict(self):
- if self.PROTO_NAMESPACE != None:
- return self.PROTO_NAMESPACE
- else:
- return self.parent.getProtoDict()
-
- def getDefDict(self):
- if self.DEF_NAMESPACE != None:
- return self.DEF_NAMESPACE
- else:
- return self.parent.getDefDict()
-
- def getRouteIpoDict(self):
- if self.ROUTE_IPO_NAMESPACE != None:
- return self.ROUTE_IPO_NAMESPACE
- else:
- return self.parent.getRouteIpoDict()
-
- def setRoot(self, filename):
- self.filename = filename
- # self.FIELD_NAMESPACE = {}
- self.DEF_NAMESPACE = {}
- self.ROUTE_IPO_NAMESPACE = {}
- self.PROTO_NAMESPACE = {}
-
- def isRoot(self):
- if self.filename == None:
- return False
- else:
- return True
-
- def getFilename(self):
- if self.filename:
- return self.filename
- elif self.parent:
- return self.parent.getFilename()
- else:
- return None
-
- def getRealNode(self):
- if self.reference:
- return self.reference
- else:
- return self
-
- def getSpec(self):
- self_real = self.getRealNode()
- try:
- return self_real.id[-1] # its possible this node has no spec
- except:
- return None
-
- def getPrefix(self):
- if self.id:
- return self.id[0]
- return None
-
- def getSpecialTypeName(self, typename):
- self_real = self.getRealNode()
- try: return self_real.id[ list(self_real.id).index(typename)+1 ]
- except: return None
-
-
- def getDefName(self):
- return self.getSpecialTypeName('DEF')
-
- def getProtoName(self):
- return self.getSpecialTypeName('PROTO')
-
- def getChildrenBySpec(self, node_spec): # spec could be Transform, Shape, Appearance
- self_real = self.getRealNode()
- # using getSpec functions allows us to use the spec of USE children that dont have their spec in their ID
- if type(node_spec) == str:
- return [child for child in self_real.children if child.getSpec()==node_spec]
- else:
- # Check inside a list of optional types
- return [child for child in self_real.children if child.getSpec() in node_spec]
-
- def getChildBySpec(self, node_spec): # spec could be Transform, Shape, Appearance
- # Use in cases where there is only ever 1 child of this type
- ls = self.getChildrenBySpec(node_spec)
- if ls: return ls[0]
- else: return None
-
- def getChildrenByName(self, node_name): # type could be geometry, children, appearance
- self_real = self.getRealNode()
- return [child for child in self_real.children if child.id if child.id[0]==node_name]
-
- def getChildByName(self, node_name):
- self_real = self.getRealNode()
- for child in self_real.children:
- if child.id and child.id[0]==node_name: # and child.id[-1]==node_spec:
- return child
-
- def getSerialized(self, results, ancestry):
- ''' Return this node and all its children in a flat list '''
- ancestry = ancestry[:] # always use a copy
-
- # self_real = self.getRealNode()
-
- results.append((self, tuple(ancestry)))
- ancestry.append(self)
- for child in self.getRealNode().children:
- if child not in ancestry:
- # We dont want to load proto's, they are only references
- # We could enforce this elsewhere
-
- # Only add this in a very special case
- # where the parent of this object is not the real parent
- # - In this case we have added the proto as a child to a node instancing it.
- # This is a bit arbitary, but its how Proto's are done with this importer.
- if child.getProtoName() == None:
- child.getSerialized(results, ancestry)
- else:
-
- if DEBUG: print 'getSerialized() is proto:', child.getProtoName(), self.getSpec()
- if child.getProtoName()==self.getSpec():
- if DEBUG: "FoundProto!"
- child.getSerialized(results, ancestry)
-
- return results
-
- def searchNodeTypeID(self, node_spec, results):
- self_real = self.getRealNode()
- # print self.lineno, self.id
- if self_real.id and self_real.id[-1]==node_spec: # use last element, could also be only element
- results.append(self_real)
- for child in self_real.children:
- child.searchNodeTypeID(node_spec, results)
- return results
-
- def getFieldName(self, field, ancestry, AS_CHILD=False):
- self_real = self.getRealNode() # incase we're an instance
-
- for f in self_real.fields:
- # print f
- if f and f[0] == field:
- # print '\tfound field', f
-
- if len(f)>=3 and f[1] == 'IS': # eg: 'diffuseColor IS legColor'
- field_id = f[2]
-
- # print "\n\n\n\n\n\nFOND IS!!!"
- f_proto_lookup = None
- f_proto_child_lookup = None
- i = len(ancestry)
- while i:
- i -= 1
- node = ancestry[i]
- node = node.getRealNode()
-
- # proto settings are stored in "self.proto_node"
- if node.proto_node:
- # Get the default value from the proto, this can be overwridden by the proto instace
- # 'field SFColor legColor .8 .4 .7'
- if AS_CHILD:
- for child in node.proto_node.children:
- #if child.id and len(child.id) >= 3 and child.id[2]==field_id:
- if child.id and ('point' in child.id or 'points' in child.id):
- f_proto_child_lookup = child
-
- else:
- for f_def in node.proto_node.proto_field_defs:
- if len(f_def) >= 4:
- if f_def[0]=='field' and f_def[2]==field_id:
- f_proto_lookup = f_def[3:]
-
- # Node instance, Will be 1 up from the proto-node in the ancestry list. but NOT its parent.
- # This is the setting as defined by the instance, including this setting is optional,
- # and will override the default PROTO value
- # eg: 'legColor 1 0 0'
- if AS_CHILD:
- for child in node.children:
- if child.id and child.id[0]==field_id:
- f_proto_child_lookup = child
- else:
- for f_def in node.fields:
- if len(f_def) >= 2:
- if f_def[0]==field_id:
- if DEBUG: print "getFieldName(), found proto", f_def
- f_proto_lookup = f_def[1:]
-
-
- if AS_CHILD:
- if f_proto_child_lookup:
- if DEBUG:
- print "getFieldName() - AS_CHILD=True, child found"
- print f_proto_child_lookup
- return f_proto_child_lookup
- else:
- return f_proto_lookup
- else:
- if AS_CHILD:
- return None
- else:
- # Not using a proto
- return f[1:]
-
- # print '\tfield not found', field
-
-
- # See if this is a proto name
- if AS_CHILD:
- child_array = None
- for child in self_real.children:
- if child.id and len(child.id) == 1 and child.id[0] == field:
- return child
-
- return None
-
- def getFieldAsInt(self, field, default, ancestry):
- self_real = self.getRealNode() # incase we're an instance
-
- f = self_real.getFieldName(field, ancestry)
- if f==None: return default
- if ',' in f: f = f[:f.index(',')] # strip after the comma
-
- if len(f) != 1:
- print '\t"%s" wrong length for int conversion for field "%s"' % (f, field)
- return default
-
- try:
- return int(f[0])
- except:
- print '\tvalue "%s" could not be used as an int for field "%s"' % (f[0], field)
- return default
-
- def getFieldAsFloat(self, field, default, ancestry):
- self_real = self.getRealNode() # incase we're an instance
-
- f = self_real.getFieldName(field, ancestry)
- if f==None: return default
- if ',' in f: f = f[:f.index(',')] # strip after the comma
-
- if len(f) != 1:
- print '\t"%s" wrong length for float conversion for field "%s"' % (f, field)
- return default
-
- try:
- return float(f[0])
- except:
- print '\tvalue "%s" could not be used as a float for field "%s"' % (f[0], field)
- return default
-
- def getFieldAsFloatTuple(self, field, default, ancestry):
- self_real = self.getRealNode() # incase we're an instance
-
- f = self_real.getFieldName(field, ancestry)
- if f==None: return default
- # if ',' in f: f = f[:f.index(',')] # strip after the comma
-
- if len(f) < 1:
- print '"%s" wrong length for float tuple conversion for field "%s"' % (f, field)
- return default
-
- ret = []
- for v in f:
- if v != ',':
- try: ret.append(float(v))
- except: break # quit of first non float, perhaps its a new field name on the same line? - if so we are going to ignore it :/ TODO
- # print ret
-
- if ret:
- return ret
- if not ret:
- print '\tvalue "%s" could not be used as a float tuple for field "%s"' % (f, field)
- return default
-
- def getFieldAsBool(self, field, default, ancestry):
- self_real = self.getRealNode() # incase we're an instance
-
- f = self_real.getFieldName(field, ancestry)
- if f==None: return default
- if ',' in f: f = f[:f.index(',')] # strip after the comma
-
- if len(f) != 1:
- print '\t"%s" wrong length for bool conversion for field "%s"' % (f, field)
- return default
-
- if f[0].upper()=='"TRUE"' or f[0].upper()=='TRUE':
- return True
- elif f[0].upper()=='"FALSE"' or f[0].upper()=='FALSE':
- return False
- else:
- print '\t"%s" could not be used as a bool for field "%s"' % (f[1], field)
- return default
-
- def getFieldAsString(self, field, default, ancestry):
- self_real = self.getRealNode() # incase we're an instance
-
- f = self_real.getFieldName(field, ancestry)
- if f==None: return default
- if len(f) < 1:
- print '\t"%s" wrong length for string conversion for field "%s"' % (f, field)
- return default
-
- if len(f) > 1:
- # String may contain spaces
- st = ' '.join(f)
- else:
- st = f[0]
-
- # X3D HACK
- if self.x3dNode:
- return st
-
- if st[0]=='"' and st[-1]=='"':
- return st[1:-1]
- else:
- print '\tvalue "%s" could not be used as a string for field "%s"' % (f[0], field)
- return default
-
- def getFieldAsArray(self, field, group, ancestry):
- '''
- For this parser arrays are children
- '''
- self_real = self.getRealNode() # incase we're an instance
-
- child_array = self_real.getFieldName(field, ancestry, True)
-
- #if type(child_array)==list: # happens occasionaly
- # array_data = child_array
-
- if child_array==None:
-
- # For x3d, should work ok with vrml too
- # for x3d arrays are fields, vrml they are nodes, annoying but not tooo bad.
- data_split = self.getFieldName(field, ancestry)
- if not data_split:
- return []
- array_data = ' '.join(data_split)
- if array_data == None:
- return []
-
- array_data = array_data.replace(',', ' ')
- data_split = array_data.split()
- try:
- array_data = [int(val) for val in data_split]
- except:
- try:
- array_data = [float(val) for val in data_split]
- except:
- print '\tWarning, could not parse array data from field'
- array_data = []
- else:
- # print child_array
- # Normal vrml
- array_data = child_array.array_data
-
-
- # print 'array_data', array_data
-
- if group==-1 or len(array_data)==0:
- return array_data
-
- # We want a flat list
- flat = True
- for item in array_data:
- if type(item) == list:
- flat = False
- break
-
- # make a flat array
- if flat:
- flat_array = array_data # we are alredy flat.
- else:
- flat_array = []
-
- def extend_flat(ls):
- for item in ls:
- if type(item)==list: extend_flat(item)
- else: flat_array.append(item)
-
- extend_flat(array_data)
-
-
- # We requested a flat array
- if group == 0:
- return flat_array
-
- new_array = []
- sub_array = []
-
- for item in flat_array:
- sub_array.append(item)
- if len(sub_array)==group:
- new_array.append(sub_array)
- sub_array = []
-
- if sub_array:
- print '\twarning, array was not aligned to requested grouping', group, 'remaining value', sub_array
-
- return new_array
-
- def getFieldAsStringArray(self, field, ancestry):
- '''
- Get a list of strings
- '''
- self_real = self.getRealNode() # incase we're an instance
-
- child_array = None
- for child in self_real.children:
- if child.id and len(child.id) == 1 and child.id[0] == field:
- child_array = child
- break
- if not child_array:
- return []
-
- # each string gets its own list, remove ""'s
- try:
- new_array = [f[0][1:-1] for f in child_array.fields]
- except:
- print '\twarning, string array could not be made'
- new_array = []
-
- return new_array
-
-
- def getLevel(self):
- # Ignore self_real
- level = 0
- p = self.parent
- while p:
- level +=1
- p = p.parent
- if not p: break
-
- return level
-
- def __repr__(self):
- level = self.getLevel()
- ind = ' ' * level
- if self.node_type==NODE_REFERENCE:
- brackets = ''
- elif self.node_type==NODE_NORMAL:
- brackets = '{}'
- else:
- brackets = '[]'
-
- if brackets:
- text = ind + brackets[0] + '\n'
- else:
- text = ''
-
- text += ind + 'ID: ' + str(self.id) + ' ' + str(level) + (' lineno %d\n' % self.lineno)
-
- if self.node_type==NODE_REFERENCE:
- text += ind + "(reference node)\n"
- return text
-
- if self.proto_node:
- text += ind + 'PROTO NODE...\n'
- text += str(self.proto_node)
- text += ind + 'PROTO NODE_DONE\n'
-
- text += ind + 'FIELDS:' + str(len(self.fields)) + '\n'
-
- for i,item in enumerate(self.fields):
- text += ind + 'FIELD:\n'
- text += ind + str(item) +'\n'
-
- text += ind + 'PROTO_FIELD_DEFS:' + str(len(self.proto_field_defs)) + '\n'
-
- for i,item in enumerate(self.proto_field_defs):
- text += ind + 'PROTO_FIELD:\n'
- text += ind + str(item) +'\n'
-
- text += ind + 'ARRAY: ' + str(len(self.array_data)) + ' ' + str(self.array_data) + '\n'
- #text += ind + 'ARRAY: ' + str(len(self.array_data)) + '[...] \n'
-
- text += ind + 'CHILDREN: ' + str(len(self.children)) + '\n'
- for i, child in enumerate(self.children):
- text += ind + ('CHILD%d:\n' % i)
- text += str(child)
-
- text += '\n' + ind + brackets[1]
-
- return text
-
- def parse(self, i, IS_PROTO_DATA=False):
- new_i = self.__parse(i, IS_PROTO_DATA)
-
- # print self.id, self.getFilename()
-
- # If we were an inline then try load the file
- if self.node_type == NODE_NORMAL and self.getSpec() == 'Inline':
-
-
- ancestry = [] # Warning! - PROTO's using this wont work at all.
- url = self.getFieldAsString('url', None, ancestry)
- del ancestry
-
- if url != None:
- urls = []
- urls.append( url )
- urls.append( BPySys.caseInsensitivePath(urls[-1]) )
-
- urls.append( dirName(self.getFilename()) + baseName(url) )
- urls.append( BPySys.caseInsensitivePath(urls[-1]) )
-
- try:
- url = [url for url in urls if exists(url)][0]
- url_found = True
- except:
- url_found = False
-
- if not url_found:
- print '\tWarning: Inline URL could not be found:', url
- else:
- if url==self.getFilename():
- print '\tWarning: cant Inline yourself recursively:', url
- else:
-
- try:
- data = gzipOpen(url)
- except:
- print '\tWarning: cant open the file:', url
- data = None
-
- if data:
- # Tricky - inline another VRML
- print '\tLoading Inline:"%s"...' % url
-
- # Watch it! - backup lines
- lines_old = lines[:]
-
-
- lines[:] = vrmlFormat( data )
-
- lines.insert(0, '{')
- lines.insert(0, 'root_node____')
- lines.append('}')
- '''
- ff = open('/root/test.txt', 'w')
- ff.writelines([l+'\n' for l in lines])
- '''
-
- child = vrmlNode(self, NODE_NORMAL, -1)
- child.setRoot(url) # initialized dicts
- child.parse(0)
-
- # Watch it! - restore lines
- lines[:] = lines_old
-
-
- return new_i
-
- def __parse(self, i, IS_PROTO_DATA=False):
- '''
- print 'parsing at', i,
- print i, self.id, self.lineno
- '''
- l = lines[i]
-
- if l=='[':
- # An anonymous list
- self.id = None
- i+=1
- else:
- words = []
-
- node_type, new_i = is_nodeline(i, words)
- if not node_type: # fail for parsing new node.
- print "Failed to parse new node"
- raise ValueError
-
- if self.node_type==NODE_REFERENCE:
- # Only assign the reference and quit
- key = words[words.index('USE')+1]
- self.id = (words[0],)
-
- self.reference = self.getDefDict()[key]
- return new_i
-
- self.id = tuple(words)
-
- # fill in DEF/USE
- key = self.getDefName()
- if key != None:
- self.getDefDict()[ key ] = self
-
- key = self.getProtoName()
- proto_dict = self.getProtoDict()
- if key != None:
- proto_dict[ key ] = self
-
- # Parse the proto nodes fields
- self.proto_node = vrmlNode(self, NODE_ARRAY, new_i)
- new_i = self.proto_node.parse(new_i)
-
- self.children.remove(self.proto_node)
-
- # print self.proto_node
-
- new_i += 1 # skip past the {
-
-
- else: # If we're a proto instance, add the proto node as our child.
- spec = self.getSpec()
- try:
- self.children.append( proto_dict[spec] )
- #pass
- except:
- pass
-
- del spec
-
- del proto_dict, key
-
- i = new_i
-
- # print self.id
- ok = True
- while ok:
- l = lines[i]
- # print '\tDEBUG:', i, self.node_type, l
- if l=='':
- i+=1
- continue
-
- if l=='}':
- if self.node_type != NODE_NORMAL: # also ends proto nodes, we may want a type for these too.
- print 'wrong node ending, expected an } ' + str(i) + ' ' + str(self.node_type)
- raise ValueError
- ### print "returning", i
- return i+1
- if l==']':
- if self.node_type != NODE_ARRAY:
- print 'wrong node ending, expected a ] ' + str(i) + ' ' + str(self.node_type)
- raise ValueError
- ### print "returning", i
- return i+1
-
- node_type, new_i = is_nodeline(i, [])
- if node_type: # check text\n{
- child = vrmlNode(self, node_type, i)
- i = child.parse(i)
-
- elif l=='[': # some files have these anonymous lists
- child = vrmlNode(self, NODE_ARRAY, i)
- i = child.parse(i)
-
- elif is_numline(i):
- l_split = l.split(',')
-
- values = None
- # See if each item is a float?
-
- for num_type in (int, float):
- try:
- values = [num_type(v) for v in l_split ]
- break
- except:
- pass
-
-
- try:
- values = [[num_type(v) for v in segment.split()] for segment in l_split ]
- break
- except:
- pass
-
- if values == None: # dont parse
- values = l_split
-
- # This should not extend over multiple lines however it is possible
- # print self.array_data
- if values:
- self.array_data.extend( values )
- i+=1
- else:
- words = l.split()
- if len(words) > 2 and words[1] == 'USE':
- vrmlNode(self, NODE_REFERENCE, i)
- else:
-
- # print "FIELD", i, l
- #
- #words = l.split()
- ### print '\t\ttag', i
- # this is a tag/
- # print words, i, l
- value = l
- # print i
- # javastrips can exist as values.
- quote_count = l.count('"')
- if quote_count % 2: # odd number?
- # print 'MULTILINE'
- while 1:
- i+=1
- l = lines[i]
- quote_count = l.count('"')
- if quote_count % 2: # odd number?
- value += '\n'+ l[:l.rfind('"')]
- break # assume
- else:
- value += '\n'+ l
-
- value_all = value.split()
-
- def iskey(k):
- if k[0] != '"' and k[0].isalpha() and k.upper() not in ('TRUE', 'FALSE'):
- return True
- return False
-
- def split_fields(value):
- '''
- key 0.0 otherkey 1,2,3 opt1 opt1 0.0
- -> [key 0.0], [otherkey 1,2,3], [opt1 opt1 0.0]
- '''
- field_list = []
- field_context = []
-
- for j in xrange(len(value)):
- if iskey(value[j]):
- if field_context:
- # this IS a key but the previous value was not a key, ot it was a defined field.
- if (not iskey(field_context[-1])) or ((len(field_context)==3 and field_context[1]=='IS')):
- field_list.append(field_context)
-
- field_context = [value[j]]
- else:
- # The last item was not a value, multiple keys are needed in some cases.
- field_context.append(value[j])
- else:
- # Is empty, just add this on
- field_context.append(value[j])
- else:
- # Add a value to the list
- field_context.append(value[j])
-
- if field_context:
- field_list.append(field_context)
-
- return field_list
-
-
- for value in split_fields(value_all):
- # Split
-
- if value[0]=='field':
- # field SFFloat creaseAngle 4
- self.proto_field_defs.append(value)
- else:
- self.fields.append(value)
- i+=1
-
-def gzipOpen(path):
- try: import gzip
- except: gzip = None
-
- data = None
- if gzip:
- try: data = gzip.open(path, 'r').read()
- except: pass
- else:
- print '\tNote, gzip module could not be imported, compressed files will fail to load'
-
- if data==None:
- try: data = open(path, 'rU').read()
- except: pass
-
- return data
-
-def vrml_parse(path):
- '''
- Sets up the root node and returns it so load_web3d() can deal with the blender side of things.
- Return root (vrmlNode, '') or (None, 'Error String')
- '''
- data = gzipOpen(path)
-
- if data==None:
- return None, 'Failed to open file: ' + path
-
- # Stripped above
- lines[:] = vrmlFormat( data )
-
- lines.insert(0, '{')
- lines.insert(0, 'dymmy_node')
- lines.append('}')
- # Use for testing our parsed output, so we can check on line numbers.
-
-
- ff = open('/root/test.txt', 'w')
- ff.writelines([l+'\n' for l in lines])
- ff.close()
-
-
- # Now evaluate it
- node_type, new_i = is_nodeline(0, [])
- if not node_type:
- return None, 'Error: VRML file has no starting Node'
-
- # Trick to make sure we get all root nodes.
- lines.insert(0, '{')
- lines.insert(0, 'root_node____') # important the name starts with an ascii char
- lines.append('}')
-
- root = vrmlNode(None, NODE_NORMAL, -1)
- root.setRoot(path) # we need to set the root so we have a namespace and know the path incase of inlineing
-
- # Parse recursively
- root.parse(0)
-
- # This prints a load of text
- if DEBUG:
- print root
-
- return root, ''
-
-
-# ====================== END VRML
-
-
-
-# ====================== X3d Support
-
-# Sane as vrml but replace the parser
-class x3dNode(vrmlNode):
- def __init__(self, parent, node_type, x3dNode):
- vrmlNode.__init__(self, parent, node_type, -1)
- self.x3dNode = x3dNode
-
- def parse(self, IS_PROTO_DATA=False):
- # print self.x3dNode.tagName
-
- define = self.x3dNode.getAttributeNode('DEF')
- if define:
- self.getDefDict()[define.value] = self
- else:
- use = self.x3dNode.getAttributeNode('USE')
- if use:
- try:
- self.reference = self.getDefDict()[use.value]
- self.node_type = NODE_REFERENCE
- except:
- print '\tWarning: reference', use.value, 'not found'
- self.parent.children.remove(self)
-
- return
-
- for x3dChildNode in self.x3dNode.childNodes:
- if x3dChildNode.nodeType in (x3dChildNode.TEXT_NODE, x3dChildNode.COMMENT_NODE, x3dChildNode.CDATA_SECTION_NODE):
- continue
-
- node_type = NODE_NORMAL
- # print x3dChildNode, dir(x3dChildNode)
- if x3dChildNode.getAttributeNode('USE'):
- node_type = NODE_REFERENCE
-
- child = x3dNode(self, node_type, x3dChildNode)
- child.parse()
-
- # TODO - x3d Inline
-
- def getSpec(self):
- return self.x3dNode.tagName # should match vrml spec
-
- def getDefName(self):
- data = self.x3dNode.getAttributeNode('DEF')
- if data: data.value
- return None
-
- # Other funcs operate from vrml, but this means we can wrap XML fields, still use nice utility funcs
- # getFieldAsArray getFieldAsBool etc
- def getFieldName(self, field):
- self_real = self.getRealNode() # incase we're an instance
- field_xml = self.x3dNode.getAttributeNode(field)
- if field_xml:
- value = field_xml.value
-
- # We may want to edit. for x3d spesific stuff
- # Sucks a bit to return the field name in the list but vrml excepts this :/
- return value.split()
- else:
- return None
-
-def x3d_parse(path):
- '''
- Sets up the root node and returns it so load_web3d() can deal with the blender side of things.
- Return root (x3dNode, '') or (None, 'Error String')
- '''
-
- try:
- import xml.dom.minidom
- except:
- return None, 'Error, import XML parsing module (xml.dom.minidom) failed, install python'
-
- '''
- try: doc = xml.dom.minidom.parse(path)
- except: return None, 'Could not parse this X3D file, XML error'
- '''
-
- # Could add a try/except here, but a console error is more useful.
- data = gzipOpen(path)
-
- if data==None:
- return None, 'Failed to open file: ' + path
-
- doc = xml.dom.minidom.parseString(data)
-
-
- try:
- x3dnode = doc.getElementsByTagName('X3D')[0]
- except:
- return None, 'Not a valid x3d document, cannot import'
-
- root = x3dNode(None, NODE_NORMAL, x3dnode)
- root.setRoot(path) # so images and Inline's we load have a relative path
- root.parse()
-
- return root, ''
-
-
-
-## f = open('/_Cylinder.wrl', 'r')
-# f = open('/fe/wrl/Vrml/EGS/TOUCHSN.WRL', 'r')
-# vrml_parse('/fe/wrl/Vrml/EGS/TOUCHSN.WRL')
-#vrml_parse('/fe/wrl/Vrml/EGS/SCRIPT.WRL')
-'''
-
-import os
-files = os.popen('find /fe/wrl -iname "*.wrl"').readlines()
-files.sort()
-tot = len(files)
-for i, f in enumerate(files):
- #if i < 801:
- # continue
-
- f = f.strip()
- print f, i, tot
- vrml_parse(f)
-'''
-
-# NO BLENDER CODE ABOVE THIS LINE.
-# -----------------------------------------------------------------------------------
-import bpy
-import BPyImage
-import BPySys
-reload(BPySys)
-reload(BPyImage)
-import Blender
-from Blender import Texture, Material, Mathutils, Mesh, Types, Window
-from Blender.Mathutils import TranslationMatrix
-from Blender.Mathutils import RotationMatrix
-from Blender.Mathutils import Vector
-from Blender.Mathutils import Matrix
-
-RAD_TO_DEG = 57.29578
-
-GLOBALS = {'CIRCLE_DETAIL':16}
-
-def translateRotation(rot):
- ''' axis, angle '''
- return RotationMatrix(rot[3]*RAD_TO_DEG, 4, 'r', Vector(rot[:3]))
-
-def translateScale(sca):
- mat = Matrix() # 4x4 default
- mat[0][0] = sca[0]
- mat[1][1] = sca[1]
- mat[2][2] = sca[2]
- return mat
-
-def translateTransform(node, ancestry):
- cent = node.getFieldAsFloatTuple('center', None, ancestry) # (0.0, 0.0, 0.0)
- rot = node.getFieldAsFloatTuple('rotation', None, ancestry) # (0.0, 0.0, 1.0, 0.0)
- sca = node.getFieldAsFloatTuple('scale', None, ancestry) # (1.0, 1.0, 1.0)
- scaori = node.getFieldAsFloatTuple('scaleOrientation', None, ancestry) # (0.0, 0.0, 1.0, 0.0)
- tx = node.getFieldAsFloatTuple('translation', None, ancestry) # (0.0, 0.0, 0.0)
-
- if cent:
- cent_mat = TranslationMatrix(Vector(cent)).resize4x4()
- cent_imat = cent_mat.copy().invert()
- else:
- cent_mat = cent_imat = None
-
- if rot: rot_mat = translateRotation(rot)
- else: rot_mat = None
-
- if sca: sca_mat = translateScale(sca)
- else: sca_mat = None
-
- if scaori:
- scaori_mat = translateRotation(scaori)
- scaori_imat = scaori_mat.copy().invert()
- else:
- scaori_mat = scaori_imat = None
-
- if tx: tx_mat = TranslationMatrix(Vector(tx)).resize4x4()
- else: tx_mat = None
-
- new_mat = Matrix()
-
- mats = [tx_mat, cent_mat, rot_mat, scaori_mat, sca_mat, scaori_imat, cent_imat]
- for mtx in mats:
- if mtx:
- new_mat = mtx * new_mat
-
- return new_mat
-
-def translateTexTransform(node, ancestry):
- cent = node.getFieldAsFloatTuple('center', None, ancestry) # (0.0, 0.0)
- rot = node.getFieldAsFloat('rotation', None, ancestry) # 0.0
- sca = node.getFieldAsFloatTuple('scale', None, ancestry) # (1.0, 1.0)
- tx = node.getFieldAsFloatTuple('translation', None, ancestry) # (0.0, 0.0)
-
-
- if cent:
- # cent is at a corner by default
- cent_mat = TranslationMatrix(Vector(cent).resize3D()).resize4x4()
- cent_imat = cent_mat.copy().invert()
- else:
- cent_mat = cent_imat = None
-
- if rot: rot_mat = RotationMatrix(rot*RAD_TO_DEG, 4, 'z') # translateRotation(rot)
- else: rot_mat = None
-
- if sca: sca_mat = translateScale((sca[0], sca[1], 0.0))
- else: sca_mat = None
-
- if tx: tx_mat = TranslationMatrix(Vector(tx).resize3D()).resize4x4()
- else: tx_mat = None
-
- new_mat = Matrix()
-
- # as specified in VRML97 docs
- mats = [cent_imat, sca_mat, rot_mat, cent_mat, tx_mat]
-
- for mtx in mats:
- if mtx:
- new_mat = mtx * new_mat
-
- return new_mat
-
-
-
-def getFinalMatrix(node, mtx, ancestry):
-
- transform_nodes = [node_tx for node_tx in ancestry if node_tx.getSpec() == 'Transform']
- if node.getSpec()=='Transform':
- transform_nodes.append(node)
- transform_nodes.reverse()
-
- if mtx==None:
- mtx = Matrix()
-
- for node_tx in transform_nodes:
- mat = translateTransform(node_tx, ancestry)
- mtx = mtx * mat
-
- return mtx
-
-def importMesh_IndexedFaceSet(geom, bpyima, ancestry):
- # print geom.lineno, geom.id, vrmlNode.DEF_NAMESPACE.keys()
-
- ccw = geom.getFieldAsBool('ccw', True, ancestry)
- ifs_colorPerVertex = geom.getFieldAsBool('colorPerVertex', True, ancestry) # per vertex or per face
- ifs_normalPerVertex = geom.getFieldAsBool('normalPerVertex', True, ancestry)
-
- # This is odd how point is inside Coordinate
-
- # VRML not x3d
- #coord = geom.getChildByName('coord') # 'Coordinate'
-
- coord = geom.getChildBySpec('Coordinate') # works for x3d and vrml
-
- if coord: ifs_points = coord.getFieldAsArray('point', 3, ancestry)
- else: coord = []
-
- if not coord:
- print '\tWarnint: IndexedFaceSet has no points'
- return None, ccw
-
- ifs_faces = geom.getFieldAsArray('coordIndex', 0, ancestry)
-
- coords_tex = None
- if ifs_faces: # In rare cases this causes problems - no faces but UVs???
-
- # WORKS - VRML ONLY
- # coords_tex = geom.getChildByName('texCoord')
- coords_tex = geom.getChildBySpec('TextureCoordinate')
-
- if coords_tex:
- ifs_texpoints = coords_tex.getFieldAsArray('point', 2, ancestry)
- ifs_texfaces = geom.getFieldAsArray('texCoordIndex', 0, ancestry)
-
- if not ifs_texpoints:
- # IF we have no coords, then dont bother
- coords_tex = None
-
-
- # WORKS - VRML ONLY
- # vcolor = geom.getChildByName('color')
- vcolor = geom.getChildBySpec('Color')
- vcolor_spot = None # spot color when we dont have an array of colors
- if vcolor:
- # float to char
- ifs_vcol = [[int(c*256) for c in col] for col in vcolor.getFieldAsArray('color', 3, ancestry)]
- ifs_color_index = geom.getFieldAsArray('colorIndex', 0, ancestry)
-
- if not ifs_vcol:
- vcolor_spot = [int(c*256) for c in vcolor.getFieldAsFloatTuple('color', [], ancestry)]
-
- # Convert faces into somthing blender can use
- edges = []
-
- # All lists are aligned!
- faces = []
- faces_uv = [] # if ifs_texfaces is empty then the faces_uv will match faces exactly.
- faces_orig_index = [] # for ngons, we need to know our original index
-
- if coords_tex and ifs_texfaces:
- do_uvmap = True
- else:
- do_uvmap = False
-
- # current_face = [0] # pointer anyone
-
- def add_face(face, fuvs, orig_index):
- l = len(face)
- if l==3 or l==4:
- faces.append(face)
- # faces_orig_index.append(current_face[0])
- if do_uvmap:
- faces_uv.append(fuvs)
-
- faces_orig_index.append(orig_index)
- elif l==2: edges.append(face)
- elif l>4:
- for i in xrange(2, len(face)):
- faces.append([face[0], face[i-1], face[i]])
- if do_uvmap:
- faces_uv.append([fuvs[0], fuvs[i-1], fuvs[i]])
- faces_orig_index.append(orig_index)
- else:
- # faces with 1 verts? pfft!
- # still will affect index ordering
- pass
-
- face = []
- fuvs = []
- orig_index = 0
- for i, fi in enumerate(ifs_faces):
- # ifs_texfaces and ifs_faces should be aligned
- if fi != -1:
- # face.append(int(fi)) # in rare cases this is a float
- # EEKADOODLE!!!
- # Annoyance where faces that have a zero index vert get rotated. This will then mess up UVs and VColors
- face.append(int(fi)+1) # in rare cases this is a float, +1 because of stupid EEKADOODLE :/
-
- if do_uvmap:
- if i >= len(ifs_texfaces):
- print '\tWarning: UV Texface index out of range'
- fuvs.append(ifs_texfaces[0])
- else:
- fuvs.append(ifs_texfaces[i])
- else:
- add_face(face, fuvs, orig_index)
- face = []
- if do_uvmap:
- fuvs = []
- orig_index += 1
-
- add_face(face, fuvs, orig_index)
- del add_face # dont need this func anymore
-
- bpymesh = bpy.data.meshes.new()
-
- bpymesh.verts.extend([(0,0,0)]) # EEKADOODLE
- bpymesh.verts.extend(ifs_points)
-
- # print len(ifs_points), faces, edges, ngons
-
- try:
- bpymesh.faces.extend(faces, smooth=True, ignoreDups=True)
- except KeyError:
- print "one or more vert indicies out of range. corrupt file?"
- #for f in faces:
- # bpymesh.faces.extend(faces, smooth=True)
-
- bpymesh.calcNormals()
-
- if len(bpymesh.faces) != len(faces):
- print '\tWarning: adding faces did not work! file is invalid, not adding UVs or vcolors'
- return bpymesh, ccw
-
- # Apply UVs if we have them
- if not do_uvmap:
- faces_uv = faces # fallback, we didnt need a uvmap in the first place, fallback to the face/vert mapping.
- if coords_tex:
- #print ifs_texpoints
- # print geom
- bpymesh.faceUV = True
- for i,f in enumerate(bpymesh.faces):
- f.image = bpyima
- fuv = faces_uv[i] # uv indicies
- for j,uv in enumerate(f.uv):
- # print fuv, j, len(ifs_texpoints)
- try:
- uv[:] = ifs_texpoints[fuv[j]]
- except:
- print '\tWarning: UV Index out of range'
- uv[:] = ifs_texpoints[0]
-
- elif bpyima and len(bpymesh.faces):
- # Oh Bugger! - we cant really use blenders ORCO for for texture space since texspace dosnt rotate.
- # we have to create VRML's coords as UVs instead.
-
- # VRML docs
- '''
- If the texCoord field is NULL, a default texture coordinate mapping is calculated using the local
- coordinate system bounding box of the shape. The longest dimension of the bounding box defines the S coordinates,
- and the next longest defines the T coordinates. If two or all three dimensions of the bounding box are equal,
- ties shall be broken by choosing the X, Y, or Z dimension in that order of preference.
- The value of the S coordinate ranges from 0 to 1, from one end of the bounding box to the other.
- The T coordinate ranges between 0 and the ratio of the second greatest dimension of the bounding box to the greatest dimension.
- '''
-
- # Note, S,T == U,V
- # U gets longest, V gets second longest
- xmin, ymin, zmin = ifs_points[0]
- xmax, ymax, zmax = ifs_points[0]
- for co in ifs_points:
- x,y,z = co
- if x < xmin: xmin = x
- if y < ymin: ymin = y
- if z < zmin: zmin = z
-
- if x > xmax: xmax = x
- if y > ymax: ymax = y
- if z > zmax: zmax = z
-
- xlen = xmax - xmin
- ylen = ymax - ymin
- zlen = zmax - zmin
-
- depth_min = xmin, ymin, zmin
- depth_list = [xlen, ylen, zlen]
- depth_sort = depth_list[:]
- depth_sort.sort()
-
- depth_idx = [depth_list.index(val) for val in depth_sort]
-
- axis_u = depth_idx[-1]
- axis_v = depth_idx[-2] # second longest
-
- # Hack, swap these !!! TODO - Why swap??? - it seems to work correctly but should not.
- # axis_u,axis_v = axis_v,axis_u
-
- min_u = depth_min[axis_u]
- min_v = depth_min[axis_v]
- depth_u = depth_list[axis_u]
- depth_v = depth_list[axis_v]
-
- depth_list[axis_u]
-
- if axis_u == axis_v:
- # This should be safe because when 2 axies have the same length, the lower index will be used.
- axis_v += 1
-
- bpymesh.faceUV = True
-
- # HACK !!! - seems to be compatible with Cosmo though.
- depth_v = depth_u = max(depth_v, depth_u)
-
- for f in bpymesh.faces:
- f.image = bpyima
- fuv = f.uv
-
- for i,v in enumerate(f):
- co = v.co
- fuv[i][:] = (co[axis_u]-min_u) / depth_u, (co[axis_v]-min_v) / depth_v
-
- # Add vcote
- if vcolor:
- # print ifs_vcol
- bpymesh.vertexColors = True
-
- for f in bpymesh.faces:
- fcol = f.col
- if ifs_colorPerVertex:
- fv = f.verts
- for i,c in enumerate(fcol):
- color_index = fv[i].index # color index is vert index
- if ifs_color_index:
- try:
- color_index = ifs_color_index[color_index]
- except:
- print '\tWarning: per vertex color index out of range'
- continue
-
- if len(ifs_vcol) < color_index:
- c.r, c.g, c.b = ifs_vcol[color_index]
- else:
- #print '\tWarning: per face color index out of range'
- pass
- else:
- if vcolor_spot: # use 1 color, when ifs_vcol is []
- for c in fcol:
- c.r, c.g, c.b = vcolor_spot
- else:
- color_index = faces_orig_index[f.index] # color index is face index
- #print color_index, ifs_color_index
- if ifs_color_index:
- if color_index <= len(ifs_color_index):
- print '\tWarning: per face color index out of range'
- color_index = 0
- else:
- color_index = ifs_color_index[color_index]
-
-
- col = ifs_vcol[color_index]
- for i,c in enumerate(fcol):
- try:
- c.r, c.g, c.b = col
- except:
- pass # incase its not between 0 and 255
-
- bpymesh.verts.delete([0,]) # EEKADOODLE
-
- return bpymesh, ccw
-
-def importMesh_IndexedLineSet(geom, ancestry):
- # VRML not x3d
- #coord = geom.getChildByName('coord') # 'Coordinate'
- coord = geom.getChildBySpec('Coordinate') # works for x3d and vrml
- if coord: points = coord.getFieldAsArray('point', 3, ancestry)
- else: points = []
-
- if not points:
- print '\tWarning: IndexedLineSet had no points'
- return None
-
- ils_lines = geom.getFieldAsArray('coordIndex', 0, ancestry)
-
- lines = []
- line = []
-
- for il in ils_lines:
- if il==-1:
- lines.append(line)
- line = []
- else:
- line.append(int(il))
- lines.append(line)
-
- # vcolor = geom.getChildByName('color') # blender dosnt have per vertex color
-
- bpycurve = bpy.data.curves.new('IndexedCurve', 'Curve')
- bpycurve.setFlag(1)
-
- w=t=1
-
- curve_index = 0
-
- for line in lines:
- if not line:
- continue
- co = points[line[0]]
- bpycurve.appendNurb([co[0], co[1], co[2], w, t])
- bpycurve[curve_index].type= 0 # Poly Line
-
- for il in line[1:]:
- co = points[il]
- bpycurve.appendPoint(curve_index, [co[0], co[1], co[2], w])
-
-
- curve_index += 1
-
- return bpycurve
-
-
-def importMesh_PointSet(geom, ancestry):
- # VRML not x3d
- #coord = geom.getChildByName('coord') # 'Coordinate'
- coord = geom.getChildBySpec('Coordinate') # works for x3d and vrml
- if coord: points = coord.getFieldAsArray('point', 3, ancestry)
- else: points = []
-
- # vcolor = geom.getChildByName('color') # blender dosnt have per vertex color
-
- bpymesh = bpy.data.meshes.new()
- bpymesh.verts.extend(points)
- bpymesh.calcNormals() # will just be dummy normals
- return bpymesh
-
-GLOBALS['CIRCLE_DETAIL'] = 12
-
-MATRIX_Z_TO_Y = RotationMatrix(90, 4, 'x')
-
-def importMesh_Sphere(geom, ancestry):
- # bpymesh = bpy.data.meshes.new()
- diameter = geom.getFieldAsFloat('radius', 0.5, ancestry) * 2 # * 2 for the diameter
- bpymesh = Mesh.Primitives.UVsphere(GLOBALS['CIRCLE_DETAIL'], GLOBALS['CIRCLE_DETAIL'], diameter)
- bpymesh.transform(MATRIX_Z_TO_Y)
- return bpymesh
-
-def importMesh_Cylinder(geom, ancestry):
- # bpymesh = bpy.data.meshes.new()
- diameter = geom.getFieldAsFloat('radius', 1.0, ancestry) * 2 # * 2 for the diameter
- height = geom.getFieldAsFloat('height', 2, ancestry)
- bpymesh = Mesh.Primitives.Cylinder(GLOBALS['CIRCLE_DETAIL'], diameter, height)
- bpymesh.transform(MATRIX_Z_TO_Y)
-
- # Warning - Rely in the order Blender adds verts
- # not nice design but wont change soon.
-
- bottom = geom.getFieldAsBool('bottom', True, ancestry)
- side = geom.getFieldAsBool('side', True, ancestry)
- top = geom.getFieldAsBool('top', True, ancestry)
-
- if not top: # last vert is top center of tri fan.
- bpymesh.verts.delete([(GLOBALS['CIRCLE_DETAIL']+GLOBALS['CIRCLE_DETAIL'])+1])
-
- if not bottom: # second last vert is bottom of triangle fan
- bpymesh.verts.delete([GLOBALS['CIRCLE_DETAIL']+GLOBALS['CIRCLE_DETAIL']])
-
- if not side:
- # remove all quads
- bpymesh.faces.delete(1, [f for f in bpymesh.faces if len(f)==4])
-
- return bpymesh
-
-def importMesh_Cone(geom, ancestry):
- # bpymesh = bpy.data.meshes.new()
- diameter = geom.getFieldAsFloat('bottomRadius', 1.0, ancestry) * 2 # * 2 for the diameter
- height = geom.getFieldAsFloat('height', 2, ancestry)
- bpymesh = Mesh.Primitives.Cone(GLOBALS['CIRCLE_DETAIL'], diameter, height)
- bpymesh.transform(MATRIX_Z_TO_Y)
-
- # Warning - Rely in the order Blender adds verts
- # not nice design but wont change soon.
-
- bottom = geom.getFieldAsBool('bottom', True, ancestry)
- side = geom.getFieldAsBool('side', True, ancestry)
-
- if not bottom: # last vert is on the bottom
- bpymesh.verts.delete([GLOBALS['CIRCLE_DETAIL']+1])
- if not side: # second last vert is on the pointy bit of the cone
- bpymesh.verts.delete([GLOBALS['CIRCLE_DETAIL']])
-
- return bpymesh
-
-def importMesh_Box(geom, ancestry):
- # bpymesh = bpy.data.meshes.new()
-
- size = geom.getFieldAsFloatTuple('size', (2.0, 2.0, 2.0), ancestry)
- bpymesh = Mesh.Primitives.Cube(1.0)
-
- # Scale the box to the size set
- scale_mat = Matrix([size[0],0,0], [0, size[1], 0], [0, 0, size[2]])
- bpymesh.transform(scale_mat.resize4x4())
-
- return bpymesh
-
-def importShape(node, ancestry):
- vrmlname = node.getDefName()
- if not vrmlname: vrmlname = 'Shape'
-
- # works 100% in vrml, but not x3d
- #appr = node.getChildByName('appearance') # , 'Appearance'
- #geom = node.getChildByName('geometry') # , 'IndexedFaceSet'
-
- # Works in vrml and x3d
- appr = node.getChildBySpec('Appearance')
- geom = node.getChildBySpec(['IndexedFaceSet', 'IndexedLineSet', 'PointSet', 'Sphere', 'Box', 'Cylinder', 'Cone'])
-
- # For now only import IndexedFaceSet's
- if geom:
- bpymat = None
- bpyima = None
- texmtx = None
-
- depth = 0 # so we can set alpha face flag later
-
- if appr:
-
- #mat = appr.getChildByName('material') # 'Material'
- #ima = appr.getChildByName('texture') # , 'ImageTexture'
- #if ima and ima.getSpec() != 'ImageTexture':
- # print '\tWarning: texture type "%s" is not supported' % ima.getSpec()
- # ima = None
- # textx = appr.getChildByName('textureTransform')
-
- mat = appr.getChildBySpec('Material')
- ima = appr.getChildBySpec('ImageTexture')
-
- textx = appr.getChildBySpec('TextureTransform')
-
- if textx:
- texmtx = translateTexTransform(textx, ancestry)
-
-
-
- # print mat, ima
- if mat or ima:
-
- if not mat:
- mat = ima # This is a bit dumb, but just means we use default values for all
-
- # all values between 0.0 and 1.0, defaults from VRML docs
- bpymat = bpy.data.materials.new()
- bpymat.amb = mat.getFieldAsFloat('ambientIntensity', 0.2, ancestry)
- bpymat.rgbCol = mat.getFieldAsFloatTuple('diffuseColor', [0.8, 0.8, 0.8], ancestry)
-
- # NOTE - blender dosnt support emmisive color
- # Store in mirror color and approximate with emit.
- emit = mat.getFieldAsFloatTuple('emissiveColor', [0.0, 0.0, 0.0], ancestry)
- bpymat.mirCol = emit
- bpymat.emit = (emit[0]+emit[1]+emit[2])/3.0
-
- bpymat.hard = int(1+(510*mat.getFieldAsFloat('shininess', 0.2, ancestry))) # 0-1 -> 1-511
- bpymat.specCol = mat.getFieldAsFloatTuple('specularColor', [0.0, 0.0, 0.0], ancestry)
- bpymat.alpha = 1.0 - mat.getFieldAsFloat('transparency', 0.0, ancestry)
- if bpymat.alpha < 0.999:
- bpymat.mode |= Material.Modes.ZTRANSP
-
-
- if ima:
-
- ima_url = ima.getFieldAsString('url', None, ancestry)
-
- if ima_url==None:
- try: ima_url = ima.getFieldAsStringArray('url', None, ancestry)[0] # in some cases we get a list of images.
- except: ima_url = None
-
- if ima_url==None:
- print "\twarning, image with no URL, this is odd"
- else:
- bpyima= BPyImage.comprehensiveImageLoad(ima_url, dirName(node.getFilename()), PLACE_HOLDER= False, RECURSIVE= False, CONVERT_CALLBACK= imageConvertCompat)
- if bpyima:
- texture= bpy.data.textures.new()
- texture.setType('Image')
- texture.image = bpyima
-
- # Adds textures for materials (rendering)
- try: depth = bpyima.depth
- except: depth = -1
-
- if depth == 32:
- # Image has alpha
- bpymat.setTexture(0, texture, Texture.TexCo.UV, Texture.MapTo.COL | Texture.MapTo.ALPHA)
- texture.setImageFlags('MipMap', 'InterPol', 'UseAlpha')
- bpymat.mode |= Material.Modes.ZTRANSP
- bpymat.alpha = 0.0
- else:
- bpymat.setTexture(0, texture, Texture.TexCo.UV, Texture.MapTo.COL)
-
- ima_repS = ima.getFieldAsBool('repeatS', True, ancestry)
- ima_repT = ima.getFieldAsBool('repeatT', True, ancestry)
-
- # To make this work properly we'd need to scale the UV's too, better to ignore th
- # texture.repeat = max(1, ima_repS * 512), max(1, ima_repT * 512)
-
- if not ima_repS: bpyima.clampX = True
- if not ima_repT: bpyima.clampY = True
-
- bpydata = None
- geom_spec = geom.getSpec()
- ccw = True
- if geom_spec == 'IndexedFaceSet':
- bpydata, ccw = importMesh_IndexedFaceSet(geom, bpyima, ancestry)
- elif geom_spec == 'IndexedLineSet':
- bpydata = importMesh_IndexedLineSet(geom, ancestry)
- elif geom_spec == 'PointSet':
- bpydata = importMesh_PointSet(geom, ancestry)
- elif geom_spec == 'Sphere':
- bpydata = importMesh_Sphere(geom, ancestry)
- elif geom_spec == 'Box':
- bpydata = importMesh_Box(geom, ancestry)
- elif geom_spec == 'Cylinder':
- bpydata = importMesh_Cylinder(geom, ancestry)
- elif geom_spec == 'Cone':
- bpydata = importMesh_Cone(geom, ancestry)
- else:
- print '\tWarning: unsupported type "%s"' % geom_spec
- return
-
- if bpydata:
- vrmlname = vrmlname + geom_spec
-
- bpydata.name = vrmlname
-
- bpyob = node.blendObject = bpy.data.scenes.active.objects.new(bpydata)
-
- if type(bpydata) == Types.MeshType:
- is_solid = geom.getFieldAsBool('solid', True, ancestry)
- creaseAngle = geom.getFieldAsFloat('creaseAngle', None, ancestry)
-
- if creaseAngle != None:
- bpydata.maxSmoothAngle = 1+int(min(79, creaseAngle * RAD_TO_DEG))
- bpydata.mode |= Mesh.Modes.AUTOSMOOTH
-
- # Only ever 1 material per shape
- if bpymat: bpydata.materials = [bpymat]
-
- if bpydata.faceUV:
-
- if depth==32: # set the faces alpha flag?
- transp = Mesh.FaceTranspModes.ALPHA
- for f in bpydata.faces:
- f.transp = transp
-
- if texmtx:
- # Apply texture transform?
- uv_copy = Vector()
- for f in bpydata.faces:
- for uv in f.uv:
- uv_copy.x = uv.x
- uv_copy.y = uv.y
-
- uv.x, uv.y = (uv_copy * texmtx)[0:2]
- # Done transforming the texture
-
-
- # Must be here and not in IndexedFaceSet because it needs an object for the flip func. Messy :/
- if not ccw: bpydata.flipNormals()
-
-
- # else could be a curve for example
-
-
-
- # Can transform data or object, better the object so we can instance the data
- #bpymesh.transform(getFinalMatrix(node))
- bpyob.setMatrix( getFinalMatrix(node, None, ancestry) )
-
-
-def importLamp_PointLight(node, ancestry):
- vrmlname = node.getDefName()
- if not vrmlname: vrmlname = 'PointLight'
-
- # ambientIntensity = node.getFieldAsFloat('ambientIntensity', 0.0, ancestry) # TODO
- # attenuation = node.getFieldAsFloatTuple('attenuation', (1.0, 0.0, 0.0), ancestry) # TODO
- color = node.getFieldAsFloatTuple('color', (1.0, 1.0, 1.0), ancestry)
- intensity = node.getFieldAsFloat('intensity', 1.0, ancestry) # max is documented to be 1.0 but some files have higher.
- location = node.getFieldAsFloatTuple('location', (0.0, 0.0, 0.0), ancestry)
- # is_on = node.getFieldAsBool('on', True, ancestry) # TODO
- radius = node.getFieldAsFloat('radius', 100.0, ancestry)
-
- bpylamp = bpy.data.lamps.new()
- bpylamp.setType('Lamp')
- bpylamp.energy = intensity
- bpylamp.dist = radius
- bpylamp.col = color
-
- mtx = TranslationMatrix(Vector(location))
-
- return bpylamp, mtx
-
-def importLamp_DirectionalLight(node, ancestry):
- vrmlname = node.getDefName()
- if not vrmlname: vrmlname = 'DirectLight'
-
- # ambientIntensity = node.getFieldAsFloat('ambientIntensity', 0.0) # TODO
- color = node.getFieldAsFloatTuple('color', (1.0, 1.0, 1.0), ancestry)
- direction = node.getFieldAsFloatTuple('direction', (0.0, 0.0, -1.0), ancestry)
- intensity = node.getFieldAsFloat('intensity', 1.0, ancestry) # max is documented to be 1.0 but some files have higher.
- # is_on = node.getFieldAsBool('on', True, ancestry) # TODO
-
- bpylamp = bpy.data.lamps.new(vrmlname)
- bpylamp.setType('Sun')
- bpylamp.energy = intensity
- bpylamp.col = color
-
- # lamps have their direction as -z, yup
- mtx = Vector(direction).toTrackQuat('-z', 'y').toMatrix().resize4x4()
-
- return bpylamp, mtx
-
-# looks like default values for beamWidth and cutOffAngle were swapped in VRML docs.
-
-def importLamp_SpotLight(node, ancestry):
- vrmlname = node.getDefName()
- if not vrmlname: vrmlname = 'SpotLight'
-
- # ambientIntensity = geom.getFieldAsFloat('ambientIntensity', 0.0, ancestry) # TODO
- # attenuation = geom.getFieldAsFloatTuple('attenuation', (1.0, 0.0, 0.0), ancestry) # TODO
- beamWidth = node.getFieldAsFloat('beamWidth', 1.570796, ancestry) * RAD_TO_DEG # max is documented to be 1.0 but some files have higher.
- color = node.getFieldAsFloatTuple('color', (1.0, 1.0, 1.0), ancestry)
- cutOffAngle = node.getFieldAsFloat('cutOffAngle', 0.785398, ancestry) * RAD_TO_DEG # max is documented to be 1.0 but some files have higher.
- direction = node.getFieldAsFloatTuple('direction', (0.0, 0.0, -1.0), ancestry)
- intensity = node.getFieldAsFloat('intensity', 1.0, ancestry) # max is documented to be 1.0 but some files have higher.
- location = node.getFieldAsFloatTuple('location', (0.0, 0.0, 0.0), ancestry)
- # is_on = node.getFieldAsBool('on', True, ancestry) # TODO
- radius = node.getFieldAsFloat('radius', 100.0, ancestry)
-
- bpylamp = bpy.data.lamps.new(vrmlname)
- bpylamp.setType('Spot')
- bpylamp.energy = intensity
- bpylamp.dist = radius
- bpylamp.col = color
- bpylamp.spotSize = cutOffAngle
- if beamWidth > cutOffAngle:
- bpylamp.spotBlend = 0.0
- else:
- if cutOffAngle==0.0: #@#$%^&*(!!! - this should never happen
- bpylamp.spotBlend = 0.5
- else:
- bpylamp.spotBlend = beamWidth / cutOffAngle
-
- # Convert
-
- # lamps have their direction as -z, y==up
- mtx = Vector(direction).toTrackQuat('-z', 'y').toMatrix().resize4x4() * TranslationMatrix(Vector(location))
-
- return bpylamp, mtx
-
-
-def importLamp(node, spec, ancestry):
- if spec=='PointLight':
- bpylamp,mtx = importLamp_PointLight(node, ancestry)
- elif spec=='DirectionalLight':
- bpylamp,mtx = importLamp_DirectionalLight(node, ancestry)
- elif spec=='SpotLight':
- bpylamp,mtx = importLamp_SpotLight(node, ancestry)
- else:
- print "Error, not a lamp"
- raise ValueError
-
- bpyob = node.blendObject = bpy.data.scenes.active.objects.new(bpylamp)
- bpyob.setMatrix( getFinalMatrix(node, mtx, ancestry) )
-
-
-def importViewpoint(node, ancestry):
- name = node.getDefName()
- if not name: name = 'Viewpoint'
-
- fieldOfView = node.getFieldAsFloat('fieldOfView', 0.785398, ancestry) * RAD_TO_DEG # max is documented to be 1.0 but some files have higher.
- # jump = node.getFieldAsBool('jump', True, ancestry)
- orientation = node.getFieldAsFloatTuple('orientation', (0.0, 0.0, 1.0, 0.0), ancestry)
- position = node.getFieldAsFloatTuple('position', (0.0, 0.0, 0.0), ancestry)
- description = node.getFieldAsString('description', '', ancestry)
-
- bpycam = bpy.data.cameras.new(name)
-
- bpycam.angle = fieldOfView
-
- mtx = translateRotation(orientation) * TranslationMatrix(Vector(position))
-
-
- bpyob = node.blendObject = bpy.data.scenes.active.objects.new(bpycam)
- bpyob.setMatrix( getFinalMatrix(node, mtx, ancestry) )
-
-
-def importTransform(node, ancestry):
- name = node.getDefName()
- if not name: name = 'Transform'
-
- bpyob = node.blendObject = bpy.data.scenes.active.objects.new('Empty', name) # , name)
- bpyob.setMatrix( getFinalMatrix(node, None, ancestry) )
-
-
-#def importTimeSensor(node):
-
-
-def translatePositionInterpolator(node, ipo, ancestry):
- key = node.getFieldAsArray('key', 0, ancestry)
- keyValue = node.getFieldAsArray('keyValue', 3, ancestry)
-
- try:
- loc_x = ipo.addCurve('LocX')
- loc_y = ipo.addCurve('LocY')
- loc_z = ipo.addCurve('LocZ')
- except ValueError:
- return
-
- loc_x.interpolation = loc_y.interpolation = loc_z.interpolation = Blender.IpoCurve.InterpTypes.LINEAR
-
- for i, time in enumerate(key):
- try: x,y,z = keyValue[i]
- except: continue
-
- loc_x.append((time,x))
- loc_y.append((time,y))
- loc_z.append((time,z))
-
-def translateOrientationInterpolator(node, ipo, ancestry):
- key = node.getFieldAsArray('key', 0, ancestry)
- keyValue = node.getFieldAsArray('keyValue', 4, ancestry)
-
- try:
- rot_x = ipo.addCurve('RotX')
- rot_y = ipo.addCurve('RotY')
- rot_z = ipo.addCurve('RotZ')
- except ValueError:
- return
-
- rot_x.interpolation = rot_y.interpolation = rot_z.interpolation = Blender.IpoCurve.InterpTypes.LINEAR
-
- for i, time in enumerate(key):
- try: x,y,z,w = keyValue[i]
- except: continue
-
- mtx = translateRotation((x,y,z,w))
- eul = mtx.toEuler()
- rot_x.append((time,eul.x/10.0))
- rot_y.append((time,eul.y/10.0))
- rot_z.append((time,eul.z/10.0))
-
-# Untested!
-def translateScalarInterpolator(node, ipo, ancestry):
- key = node.getFieldAsArray('key', 0, ancestry)
- keyValue = node.getFieldAsArray('keyValue', 4, ancestry)
-
- try:
- sca_x = ipo.addCurve('ScaleX')
- sca_y = ipo.addCurve('ScaleY')
- sca_z = ipo.addCurve('ScaleZ')
- except ValueError:
- return
-
- sca_x.interpolation = sca_y.interpolation = sca_z.interpolation = Blender.IpoCurve.InterpTypes.LINEAR
-
- for i, time in enumerate(key):
- try: x,y,z = keyValue[i]
- except: continue
- sca_x.append((time,x/10.0))
- sca_y.append((time,y/10.0))
- sca_z.append((time,z/10.0))
-
-def translateTimeSensor(node, ipo, ancestry):
- '''
- Apply a time sensor to an IPO, VRML has many combinations of loop/start/stop/cycle times
- to give different results, for now just do the basics
- '''
-
- time_cu = ipo.addCurve('Time')
- time_cu.interpolation = Blender.IpoCurve.InterpTypes.LINEAR
-
- cycleInterval = node.getFieldAsFloat('cycleInterval', None, ancestry)
-
- startTime = node.getFieldAsFloat('startTime', 0.0, ancestry)
- stopTime = node.getFieldAsFloat('stopTime', 250.0, ancestry)
-
- if cycleInterval != None:
- stopTime = startTime+cycleInterval
-
- loop = node.getFieldAsBool('loop', False, ancestry)
-
- time_cu.append((1+startTime, 0.0))
- time_cu.append((1+stopTime, 1.0/10.0))# anoying, the UI uses /10
-
-
- if loop:
- time_cu.extend = Blender.IpoCurve.ExtendTypes.CYCLIC # or - EXTRAP, CYCLIC_EXTRAP, CONST,
-
-
-def importRoute(node, ancestry):
- '''
- Animation route only at the moment
- '''
-
- if not hasattr(node, 'fields'):
- return
-
- routeIpoDict = node.getRouteIpoDict()
-
- def getIpo(id):
- try: ipo = routeIpoDict[id]
- except: ipo = routeIpoDict[id] = bpy.data.ipos.new('web3d_ipo', 'Object')
- return ipo
-
- # for getting definitions
- defDict = node.getDefDict()
- '''
- Handles routing nodes to eachother
-
-ROUTE vpPI.value_changed TO champFly001.set_position
-ROUTE vpOI.value_changed TO champFly001.set_orientation
-ROUTE vpTs.fraction_changed TO vpPI.set_fraction
-ROUTE vpTs.fraction_changed TO vpOI.set_fraction
-ROUTE champFly001.bindTime TO vpTs.set_startTime
- '''
-
- #from_id, from_type = node.id[1].split('.')
- #to_id, to_type = node.id[3].split('.')
-
- #value_changed
- set_position_node = None
- set_orientation_node = None
- time_node = None
-
- for field in node.fields:
- if field and field[0]=='ROUTE':
- try:
- from_id, from_type = field[1].split('.')
- to_id, to_type = field[3].split('.')
- except:
- print "Warning, invalid ROUTE", field
- continue
-
- if from_type == 'value_changed':
- if to_type == 'set_position':
- ipo = getIpo(to_id)
- set_data_from_node = defDict[from_id]
- translatePositionInterpolator(set_data_from_node, ipo, ancestry)
-
- if to_type in ('set_orientation', 'rotation'):
- ipo = getIpo(to_id)
- set_data_from_node = defDict[from_id]
- translateOrientationInterpolator(set_data_from_node, ipo, ancestry)
-
- if to_type == 'set_scale':
- ipo = getIpo(to_id)
- set_data_from_node = defDict[from_id]
- translateScalarInterpolator(set_data_from_node, ipo, ancestry)
-
- elif from_type =='bindTime':
- ipo = getIpo(from_id)
- time_node = defDict[to_id]
- translateTimeSensor(time_node, ipo, ancestry)
-
-
-
-
-def load_web3d(path, PREF_FLAT=False, PREF_CIRCLE_DIV=16, HELPER_FUNC = None):
-
- # Used when adding blender primitives
- GLOBALS['CIRCLE_DETAIL'] = PREF_CIRCLE_DIV
-
- #root_node = vrml_parse('/_Cylinder.wrl')
- if path.lower().endswith('.x3d'):
- root_node, msg = x3d_parse(path)
- else:
- root_node, msg = vrml_parse(path)
-
- if not root_node:
- if Blender.mode == 'background':
- print msg
- else:
- Blender.Draw.PupMenu(msg)
- return
-
-
- # fill with tuples - (node, [parents-parent, parent])
- all_nodes = root_node.getSerialized([], [])
-
- for node, ancestry in all_nodes:
- #if 'castle.wrl' not in node.getFilename():
- # continue
-
- spec = node.getSpec()
- '''
- prefix = node.getPrefix()
- if prefix=='PROTO':
- pass
- el
- '''
- if spec=='Shape':
- importShape(node, ancestry)
- elif spec in ('PointLight', 'DirectionalLight', 'SpotLight'):
- importLamp(node, spec, ancestry)
- elif spec=='Viewpoint':
- importViewpoint(node, ancestry)
- elif spec=='Transform':
- # Only use transform nodes when we are not importing a flat object hierarchy
- if PREF_FLAT==False:
- importTransform(node, ancestry)
- '''
- # These are delt with later within importRoute
- elif spec=='PositionInterpolator':
- ipo = bpy.data.ipos.new('web3d_ipo', 'Object')
- translatePositionInterpolator(node, ipo)
- '''
-
- else:
- # Note, include this function so the VRML/X3D importer can be extended
- # by an external script.
- if HELPER_FUNC:
- HELPER_FUNC(node, ancestry)
-
-
-
- # After we import all nodes, route events - anim paths
- for node, ancestry in all_nodes:
- importRoute(node, ancestry)
-
- for node, ancestry in all_nodes:
- if node.isRoot():
- # we know that all nodes referenced from will be in
- # routeIpoDict so no need to run node.getDefDict() for every node.
- routeIpoDict = node.getRouteIpoDict()
- defDict = node.getDefDict()
-
- for key, ipo in routeIpoDict.iteritems():
-
- # Assign anim curves
- node = defDict[key]
- if node.blendObject==None: # Add an object if we need one for animation
- node.blendObject = bpy.data.scenes.active.objects.new('Empty', 'AnimOb') # , name)
-
- node.blendObject.setIpo(ipo)
-
-
-
- # Add in hierarchy
- if PREF_FLAT==False:
- child_dict = {}
- for node, ancestry in all_nodes:
- if node.blendObject:
- blendObject = None
-
- # Get the last parent
- i = len(ancestry)
- while i:
- i-=1
- blendObject = ancestry[i].blendObject
- if blendObject:
- break
-
- if blendObject:
- # Parent Slow, - 1 liner but works
- # blendObject.makeParent([node.blendObject], 0, 1)
-
- # Parent FAST
- try: child_dict[blendObject].append(node.blendObject)
- except: child_dict[blendObject] = [node.blendObject]
-
- # Parent FAST
- for parent, children in child_dict.iteritems():
- parent.makeParent(children, 0, 1)
-
- # update deps
- bpy.data.scenes.active.update(1)
- del child_dict
-
-
-def load_ui(path):
- Draw = Blender.Draw
- PREF_HIERARCHY= Draw.Create(0)
- PREF_CIRCLE_DIV= Draw.Create(16)
-
- # Get USER Options
- pup_block= [\
- 'Import...',\
- ('Hierarchy', PREF_HIERARCHY, 'Import transform nodes as empties to create a parent/child hierarchy'),\
- ('Circle Div:', PREF_CIRCLE_DIV, 3, 128, 'Number of divisions to use for circular primitives')
- ]
-
- if not Draw.PupBlock('Import X3D/VRML...', pup_block):
- return
-
- Window.WaitCursor(1)
-
- load_web3d(path,\
- (not PREF_HIERARCHY.val),\
- PREF_CIRCLE_DIV.val,\
- )
-
- Window.WaitCursor(0)
-
-
-if __name__ == '__main__':
- Window.FileSelector(load_ui, 'Import X3D/VRML97')
-
-
-# Testing stuff
-
-# load_web3d('/test.x3d')
-# load_web3d('/_Cylinder.x3d')
-
-# Testing below
-# load_web3d('m:\\root\\Desktop\\_Cylinder.wrl')
-# load_web3d('/_Cylinder.wrl')
-# load_web3d('/fe/wrl/Vrml/EGS/BCKGD.WRL')
-
-# load_web3d('/fe/wrl/Vrml/EGS/GRNDPLNE.WRL')
-# load_web3d('/fe/wrl/Vrml/EGS/INDEXFST.WRL')
-# load_web3d('/fe/wrl/panel1c.wrl')
-# load_web3d('/test.wrl')
-# load_web3d('/fe/wrl/dulcimer.wrl')
-# load_web3d('/fe/wrl/rccad/Ju-52.wrl') # Face index out of range
-# load_web3d('/fe/wrl/16lat.wrl') # spotlight
-# load_web3d('/fe/wrl/Vrml/EGS/FOG.WRL') # spotlight
-# load_web3d('/fe/wrl/Vrml/EGS/LOD.WRL') # vcolor per face
-
-# load_web3d('/fe/wrl/new/daybreak_final.wrl') # no faces in mesh, face duplicate error
-# load_web3d('/fe/wrl/new/earth.wrl')
-# load_web3d('/fe/wrl/new/hendrix.ei.dtu.dk/vrml/talairach/fourd/TalaDruryRight.wrl') # define/use fields
-# load_web3d('/fe/wrl/new/imac.wrl') # extrusion and define/use fields, face index is a float somehow
-# load_web3d('/fe/wrl/new/www.igs.net/~mascott/vrml/vrml2/mcastle.wrl')
-# load_web3d('/fe/wrl/new/www.igs.net/~mascott/vrml/vrml2/tower.wrl')
-# load_web3d('/fe/wrl/new/www.igs.net/~mascott/vrml/vrml2/temple.wrl')
-# load_web3d('/fe/wrl/brain.wrl') # field define test 'a IS b'
-# load_web3d('/fe/wrl/new/coaster.wrl') # fields that are confusing to read.
-
-# X3D
-
-# load_web3d('/fe/x3d/www.web3d.org/x3d/content/examples/Basic/StudentProjects/PlayRoom.x3d') # invalid UVs
-
-
-
-def test():
- import os
-
- files = os.popen('find /fe/wrl -iname "*.wrl"').readlines()
- # files = os.popen('find /fe/x3d -iname "*.x3d"').readlines()
- # files = os.popen('find /fe/x3d/X3dExamplesSavage -iname "*.x3d"').readlines()
-
- files.sort()
- tot = len(files)
- for i, f in enumerate(files):
- #if i < 126 or i > 1000000:
- # continue
-
- if i != 1068:
- continue
-
- #if i != 12686:
- # continue
-
- f = f.strip()
- print f, i, tot
- sce = bpy.data.scenes.new(str(i) + '_' + f.split('/')[-1])
- bpy.data.scenes.active = sce
- # Window.
- load_web3d(f, PREF_FLAT=True)
- \ No newline at end of file
diff --git a/release/scripts/lightwave_import.py b/release/scripts/lightwave_import.py
index 6d02467cef8..2049fbd2380 100644
--- a/release/scripts/lightwave_import.py
+++ b/release/scripts/lightwave_import.py
@@ -106,12 +106,6 @@ try:
except:
struct= chunk= cStringIO= None
-# python 2.3 has no reversed() iterator. this will only work on lists and tuples
-try:
- reversed
-except:
- def reversed(l): return l[::-1]
-
### # Debuggin disabled in release.
### # do a search replace to enabe debug prints
### DEBUG = False
diff --git a/release/scripts/mesh_cleanup.py b/release/scripts/mesh_cleanup.py
index 27adca335cb..608201acb98 100644
--- a/release/scripts/mesh_cleanup.py
+++ b/release/scripts/mesh_cleanup.py
@@ -121,29 +121,25 @@ def rem_unused_materials(me):
material_users= dict( [(i,0) for i in xrange(len_materials)] )
for f in me.faces:
- f_mat = f.mat
# Make sure the face index isnt too big. this happens sometimes.
- if f_mat >= len_materials:
- f_mat = f.mat = 0
- material_users[f_mat] += 1
+ if f.mat >= len_materials:
+ f.mat=0
+ material_users[f.mat] += 1
- # mat_idx_subtract= 0
- # reindex_mapping= dict( [(i,0) for i in xrange(len_materials)] )
-
- reindex_mapping_ls = range(len_materials)
- for i in range(len_materials-1, -1, -1):
+ mat_idx_subtract= 0
+ reindex_mapping= dict( [(i,0) for i in xrange(len_materials)] )
+ i= len_materials
+ while i:
+ i-=1
+
if material_users[i] == 0:
- del reindex_mapping_ls[i]
- del materials[i]
+ mat_idx_subtract+=1
+ reindex_mapping[i]= mat_idx_subtract
+ materials.pop(i)
rem_materials+=1
- reindex_mapping= {}
-
- for i, mat in enumerate(reindex_mapping_ls):
- reindex_mapping[mat] = i
-
for f in me.faces:
- f.mat= reindex_mapping[f.mat]
+ f.mat= f.mat - reindex_mapping[f.mat]
me.materials= materials
return rem_materials
@@ -453,4 +449,4 @@ def main():
if __name__ == '__main__':
- main() \ No newline at end of file
+ main()
diff --git a/release/scripts/mesh_edges2curves.py b/release/scripts/mesh_edges2curves.py
index 670165dda51..006bdf10b49 100644
--- a/release/scripts/mesh_edges2curves.py
+++ b/release/scripts/mesh_edges2curves.py
@@ -112,7 +112,7 @@ def mesh2polys():
Window.EditMode(0)
me = meshOb.getData(mesh=1)
polygons= polysFromMesh(me)
- w = 1.0
+ w=t=1
cu= Curve.New()
cu.name = me.name
cu.setFlag(1)
@@ -128,7 +128,7 @@ def mesh2polys():
vIdx= 0
v= poly[vIdx]
- cu.appendNurb((v.co.x, v.co.y, v.co.z, w))
+ cu.appendNurb([v.co.x, v.co.y, v.co.z, w, t])
vIdx += 1
cu[i].type= 0 # Poly Line
@@ -139,7 +139,7 @@ def mesh2polys():
# Add all the points in the polyline.
while vIdx<len(poly):
v= poly[vIdx]
- cu.appendPoint(i, (v.co.x, v.co.y, v.co.z, w))
+ cu.appendPoint(i, [v.co.x, v.co.y, v.co.z, w])
vIdx+=1
i+=1
Window.WaitCursor(0)
diff --git a/release/scripts/ms3d_import_ascii.py b/release/scripts/ms3d_import_ascii.py
deleted file mode 100644
index d8c22a1ec99..00000000000
--- a/release/scripts/ms3d_import_ascii.py
+++ /dev/null
@@ -1,479 +0,0 @@
-#!BPY
-"""
-Name: 'MilkShape3D ASCII (.txt)...'
-Blender: 245
-Group: 'Import'
-Tooltip: 'Import from a MilkShape3D ASCII file format (.txt)'
-"""
-#
-# Author: Markus Ilmola
-# Email: markus.ilmola@pp.inet.fi
-#
-# This program is free software; you can redistribute it and/or
-# modify it under the terms of the GNU General Public License
-# as published by the Free Software Foundation; either version 2
-# of the License, or (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
-#
-
-# import needed stuff
-import os.path
-import re
-import math
-from math import *
-import Blender
-from Blender import Mathutils
-from Blender.Mathutils import *
-
-
-
-# Converts ms3d euler angles to a rotation matrix
-def RM(a):
- sy = sin(a[2])
- cy = cos(a[2])
- sp = sin(a[1])
- cp = cos(a[1])
- sr = sin(a[0])
- cr = cos(a[0])
- return Matrix([cp*cy, cp*sy, -sp], [sr*sp*cy+cr*-sy, sr*sp*sy+cr*cy, sr*cp],[cr*sp*cy+-sr*-sy, cr*sp*sy+-sr*cy, cr*cp])
-
-
-# Converts ms3d euler angles to a quaternion
-def RQ(a):
- angle = a[2] * 0.5;
- sy = sin(angle);
- cy = cos(angle);
- angle = a[1] * 0.5;
- sp = sin(angle);
- cp = cos(angle);
- angle = a[0] * 0.5;
- sr = sin(angle);
- cr = cos(angle);
- return Quaternion(cr*cp*cy+sr*sp*sy, sr*cp*cy-cr*sp*sy, cr*sp*cy+sr*cp*sy, cr*cp*sy-sr*sp*cy)
-
-
-# takes a texture filename and tries to load it
-def loadImage(path, filename):
- image = None
- try:
- image = Blender.Image.Load(os.path.abspath(filename))
- except IOError:
- print "Warning: Failed to load image: " + filename + ". Trying short path instead...\n"
- try:
- image = Blender.Image.Load(os.path.dirname(path) + "/" + os.path.basename(filename))
- except IOError:
- print "Warning: Failed to load image: " + os.path.basename(filename) + "!\n"
- return image
-
-
-
-# returns the next non-empty, non-comment line from the file
-def getNextLine(file):
- ready = False
- while ready==False:
- line = file.readline()
- if len(line)==0:
- print "Warning: End of file reached."
- return line
- ready = True
- line = line.strip()
- if len(line)==0 or line.isspace():
- ready = False
- if len(line)>=2 and line[0]=='/' and line[1]=='/':
- ready = False
- return line
-
-
-
-# imports a MilkShape3D ascii file to the current scene
-def import_ms3d_ascii(path):
- # limits
- MAX_NUMMESHES = 1000
- MAX_NUMVERTS = 100000
- MAX_NUMNORMALS = 100000
- MAX_NUMTRIS = 100000
- MAX_NUMMATS = 16
- MAX_NUMBONES = 100
- MAX_NUMPOSKEYS = 1000
- MAX_NUMROTKEYS = 1000
-
- # get scene
- scn = Blender.Scene.GetCurrent()
- if scn==None:
- return "No scene to import to!"
-
- # open the file
- try:
- file = open(path, 'r')
- except IOError:
- return "Failed to open the file!"
-
- # Read frame info
- try:
- lines = getNextLine(file).split()
- if len(lines) != 2 or lines[0] != "Frames:":
- raise ValueError
- lines = getNextLine(file).split()
- if len(lines) != 2 or lines[0] != "Frame:":
- raise ValueError
- except ValueError:
- return "Frame information is invalid!"
-
- # Create the mesh
- meshOb = Blender.Object.New('Mesh', "MilkShape3D Object")
- mesh = Blender.Mesh.New("MilkShape3D Mesh")
- meshOb.link(mesh)
- scn.objects.link(meshOb)
-
- # read the number of meshes
- try:
- lines = getNextLine(file).split()
- if len(lines)!=2 or lines[0]!="Meshes:":
- raise ValueError
- numMeshes = int(lines[1])
- if numMeshes < 0 or numMeshes > MAX_NUMMESHES:
- raise ValueError
- except ValueError:
- return "Number of meshes is invalid!"
-
- # read meshes
- vertBase = 0
- faceBase = 0
- boneIds = []
- for i in range(numMeshes):
- # read name, flags and material
- try:
- lines = re.findall(r'\".*\"|[^ ]+', getNextLine(file))
- if len(lines)!=3:
- raise ValueError
- material = int(lines[2])
- except ValueError:
- return "Name, flags or material in mesh " + str(i+1) + " are invalid!"
-
- # read the number of vertices
- try:
- numVerts = int(getNextLine(file))
- if numVerts < 0 or numVerts > MAX_NUMVERTS:
- raise ValueError
- except ValueError:
- return "Number of vertices in mesh " + str(i+1) + " is invalid!"
-
- # read vertices
- coords = []
- uvs = []
- for j in xrange(numVerts):
- try:
- lines = getNextLine(file).split()
- if len(lines)!=7:
- raise ValueError
- coords.append([float(lines[1]), float(lines[2]), float(lines[3])])
- uvs.append([float(lines[4]), 1-float(lines[5])])
- boneIds.append(int(lines[6]))
- except ValueError:
- return "Vertex " + str(j+1) + " in mesh " + str(i+1) + " is invalid!"
- mesh.verts.extend(coords)
-
- # read number of normals
- try:
- numNormals = int(getNextLine(file))
- if numNormals < 0 or numNormals > MAX_NUMNORMALS:
- raise ValueError
- except ValueError:
- return "Number of normals in mesh " + str(i+1) + " is invalid!"
-
- # read normals
- normals = []
- for j in xrange(numNormals):
- try:
- lines = getNextLine(file).split()
- if len(lines)!=3:
- raise ValueError
- normals.append([float(lines[0]), float(lines[1]), float(lines[2])])
- except ValueError:
- return "Normal " + str(j+1) + " in mesh " + str(i+1) + " is invalid!"
-
- # read the number of triangles
- try:
- numTris = int(getNextLine(file))
- if numTris < 0 or numTris > MAX_NUMTRIS:
- raise ValueError
- except ValueError:
- return "Number of triangles in mesh " + str(i+1) + " is invalid!"
-
- # read triangles
- faces = []
- for j in xrange(numTris):
- # read the triangle
- try:
- lines = getNextLine(file).split()
- if len(lines)!=8:
- raise ValueError
- v1 = int(lines[1])
- v2 = int(lines[2])
- v3 = int(lines[3])
- faces.append([v1+vertBase, v2+vertBase, v3+vertBase])
- except ValueError:
- return "Triangle " + str(j+1) + " in mesh " + str(i+1) + " is invalid!"
- mesh.faces.extend(faces)
-
- # set texture coordinates and material
- for j in xrange(faceBase, len(mesh.faces)):
- face = mesh.faces[j]
- face.uv = [Vector(uvs[face.verts[0].index-vertBase]), Vector(uvs[face.verts[1].index-vertBase]), Vector(uvs[face.verts[2].index-vertBase])]
- if material>=0:
- face.mat = material
-
- # increase vertex and face base
- vertBase = len(mesh.verts)
- faceBase = len(mesh.faces)
-
- # read the number of materials
- try:
- lines = getNextLine(file).split()
- if len(lines)!=2 or lines[0]!="Materials:":
- raise ValueError
- numMats = int(lines[1])
- if numMats < 0 or numMats > MAX_NUMMATS:
- raise ValueError
- except ValueError:
- return "Number of materials is invalid!"
-
- # read the materials
- for i in range(numMats):
- # read name
- name = getNextLine(file)[1:-1]
-
- # create the material
- mat = Blender.Material.New(name)
- mesh.materials += [mat]
-
- # read ambient color
- try:
- lines = getNextLine(file).split()
- if len(lines)!=4:
- raise ValueError
- amb = (float(lines[0])+float(lines[1])+float(lines[2]))/3
- mat.setAmb(amb)
- except ValueError:
- return "Ambient color in material " + str(i+1) + " is invalid!"
-
- # read diffuse color
- try:
- lines = getNextLine(file).split()
- if len(lines)!=4:
- raise ValueError
- mat.setRGBCol([float(lines[0]), float(lines[1]), float(lines[2])])
- except ValueError:
- return "Diffuse color in material " + str(i+1) + " is invalid!"
-
- # read specular color
- try:
- lines = getNextLine(file).split()
- if len(lines)!=4:
- raise ValueError
- mat.setSpecCol([float(lines[0]), float(lines[1]), float(lines[2])])
- except ValueError:
- return "Specular color in material " + str(i+1) + " is invalid!"
-
- # read emissive color
- try:
- lines = getNextLine(file).split()
- if len(lines)!=4:
- raise ValueError
- emit = (float(lines[0])+float(lines[1])+float(lines[2]))/3
- mat.setEmit(emit)
- except ValueError:
- return "Emissive color in material " + str(i+1) + " is invalid!"
-
- # read shininess
- try:
- shi = float(getNextLine(file))
- #mat.setHardness(int(shi))
- except ValueError:
- return "Shininess in material " + str(i+1) + " is invalid!"
-
- # read transparency
- try:
- alpha = float(getNextLine(file))
- mat.setAlpha(alpha)
- if alpha < 1:
- mat.mode |= Blender.Material.Modes.ZTRANSP
- except ValueError:
- return "Transparency in material " + str(i+1) + " is invalid!"
-
- # read texturemap
- texturemap = getNextLine(file)[1:-1]
- if len(texturemap)>0:
- colorTexture = Blender.Texture.New(name + "_texture")
- colorTexture.setType('Image')
- colorTexture.setImage(loadImage(path, texturemap))
- mat.setTexture(0, colorTexture, Blender.Texture.TexCo.UV, Blender.Texture.MapTo.COL)
-
- # read alphamap
- alphamap = getNextLine(file)[1:-1]
- if len(alphamap)>0:
- alphaTexture = Blender.Texture.New(name + "_alpha")
- alphaTexture.setType('Image')
- alphaTexture.setImage(loadImage(path, alphamap))
- mat.setTexture(1, alphaTexture, Blender.Texture.TexCo.UV, Blender.Texture.MapTo.ALPHA)
-
- # read the number of bones
- try:
- lines = getNextLine(file).split()
- if len(lines)!=2 or lines[0]!="Bones:":
- raise ValueError
- numBones = int(lines[1])
- if numBones < 0 or numBones > MAX_NUMBONES:
- raise ValueError
- except:
- return "Number of bones is invalid!"
-
- # create the armature
- armature = None
- armOb = None
- if numBones > 0:
- armOb = Blender.Object.New('Armature', "MilkShape3D Skeleton")
- armature = Blender.Armature.New("MilkShape3D Skeleton")
- armature.drawType = Blender.Armature.STICK
- armOb.link(armature)
- scn.objects.link(armOb)
- armOb.makeParentDeform([meshOb])
- armature.makeEditable()
-
- # read bones
- posKeys = {}
- rotKeys = {}
- for i in range(numBones):
- # read name
- name = getNextLine(file)[1:-1]
-
- # create the bone
- bone = Blender.Armature.Editbone()
- armature.bones[name] = bone
-
- # read parent
- parent = getNextLine(file)[1:-1]
- if len(parent)>0:
- bone.parent = armature.bones[parent]
-
- # read position and rotation
- try:
- lines = getNextLine(file).split()
- if len(lines) != 7:
- raise ValueError
- pos = [float(lines[1]), float(lines[2]), float(lines[3])]
- rot = [float(lines[4]), float(lines[5]), float(lines[6])]
- except ValueError:
- return "Invalid position or orientation in a bone!"
-
- # set position and orientation
- if bone.hasParent():
- bone.head = Vector(pos) * bone.parent.matrix + bone.parent.head
- bone.tail = bone.head + Vector([1,0,0])
- tempM = RM(rot) * bone.parent.matrix
- tempM.transpose;
- bone.matrix = tempM
- else:
- bone.head = Vector(pos)
- bone.tail = bone.head + Vector([1,0,0])
- bone.matrix = RM(rot)
-
- # Create vertex group for this bone
- mesh.addVertGroup(name)
- vgroup = []
- for index, v in enumerate(boneIds):
- if v==i:
- vgroup.append(index)
- mesh.assignVertsToGroup(name, vgroup, 1.0, 1)
-
- # read the number of position key frames
- try:
- numPosKeys = int(getNextLine(file))
- if numPosKeys < 0 or numPosKeys > MAX_NUMPOSKEYS:
- raise ValueError
- except ValueError:
- return "Invalid number of position key frames!"
-
- # read position key frames
- posKeys[name] = []
- for j in range(numPosKeys):
- # read time and position
- try:
- lines = getNextLine(file).split()
- if len(lines) != 4:
- raise ValueError
- time = float(lines[0])
- pos = [float(lines[1]), float(lines[2]), float(lines[3])]
- posKeys[name].append([time, pos])
- except ValueError:
- return "Invalid position key frame!"
-
- # read the number of rotation key frames
- try:
- numRotKeys = int(getNextLine(file))
- if numRotKeys < 0 or numRotKeys > MAX_NUMROTKEYS:
- raise ValueError
- except ValueError:
- return "Invalid number of rotation key frames!"
-
- # read rotation key frames
- rotKeys[name] = []
- for j in range(numRotKeys):
- # read time and rotation
- try:
- lines = getNextLine(file).split()
- if len(lines) != 4:
- raise ValueError
- time = float(lines[0])
- rot = [float(lines[1]), float(lines[2]), float(lines[3])]
- rotKeys[name].append([time, rot])
- except ValueError:
- return "Invalid rotation key frame!"
-
- # create action and pose
- action = None
- pose = None
- if armature != None:
- armature.update()
- pose = armOb.getPose()
- action = armOb.getAction()
- if not action:
- action = Blender.Armature.NLA.NewAction()
- action.setActive(armOb)
-
- # create animation key frames
- for name, pbone in pose.bones.items():
- # create position keys
- for key in posKeys[name]:
- pbone.loc = Vector(key[1])
- pbone.insertKey(armOb, int(key[0]+0.5), Blender.Object.Pose.LOC, True)
-
- # create rotation keys
- for key in rotKeys[name]:
- pbone.quat = RQ(key[1])
- pbone.insertKey(armOb, int(key[0]+0.5), Blender.Object.Pose.ROT, True)
-
- # set the imported object to be the selected one
- scn.objects.selected = []
- meshOb.sel= 1
- Blender.Redraw()
-
- # The import was a succes!
- return ""
-
-
-# load the model
-def fileCallback(filename):
- error = import_ms3d_ascii(filename)
- if error!="":
- Blender.Draw.PupMenu("An error occured during import: " + error + "|Not all data might have been imported succesfully.", 2)
-
-Blender.Window.FileSelector(fileCallback, 'Import')
diff --git a/release/scripts/object_drop.py b/release/scripts/object_drop.py
index f4803e62d98..63a0bd574fb 100644
--- a/release/scripts/object_drop.py
+++ b/release/scripts/object_drop.py
@@ -216,7 +216,7 @@ def main():
# hack so the toggle buttons redraw. this is not nice at all
while GLOBALS['EVENT'] == EVENT_REDRAW:
- Draw.UIBlock(terain_clamp_ui, 0)
+ Draw.UIBlock(terain_clamp_ui)
if __name__ == '__main__':
main()
diff --git a/release/scripts/object_find.py b/release/scripts/object_find.py
index f12af07e3e4..0cfd6ad1d92 100644
--- a/release/scripts/object_find.py
+++ b/release/scripts/object_find.py
@@ -61,20 +61,8 @@ def get_object_images(ob):
me.activeUVLayer = orig_uvlayer
-
- # Now get material images
- for mat in me.materials:
- if mat:
- for mtex in mat.getTextures():
- if mtex:
- tex = mtex.tex
- i = tex.getImage()
- if i: unique_images[i.name] = i
-
return unique_images.values()
-
-
# Todo, support other object types, materials
return []
@@ -130,7 +118,7 @@ def main():
def activate(ob, scn):
bpy.data.scenes.active = scn
scn.objects.selected = []
- scn.Layers = ob.Layers & (1<<20)-1
+ scn.Layers = ob.Layers
ob.sel = 1
def name_cmp(name_search, name_found):
@@ -207,13 +195,11 @@ def main():
activate(ob, scn)
return
if NAME_TEXTURE:
- for mtex in mat.getTextures():
- if mtex:
- tex = mtex.tex
- if tex:
- if name_cmp(NAME_TEXTURE, tex.name):
- activate(ob, scn)
- return
+ for tex in mat.getTextures():
+ if tex:
+ if name_cmp(NAME_MATERIAL, tex.name):
+ activate(ob, scn)
+ return
Draw.PupMenu('No Objects Found')
diff --git a/release/scripts/ply_export.py b/release/scripts/ply_export.py
index 46d08050302..19a4a60674e 100644
--- a/release/scripts/ply_export.py
+++ b/release/scripts/ply_export.py
@@ -143,10 +143,10 @@ def file_callback(filename):
normal_key = rvec3d(normal)
if faceUV:
- uvcoord= uv[j][0], 1.0-uv[j][1]
+ uvcoord= tuple(uv[j])
uvcoord_key = rvec2d(uvcoord)
elif vertexUV:
- uvcoord= v.uvco[0], 1.0-v.uvco[1]
+ uvcoord= tuple(v.uvco)
uvcoord_key = rvec2d(uvcoord)
if vertexColors: color= col[j].r, col[j].g, col[j].b
@@ -209,8 +209,8 @@ def file_callback(filename):
for j, v in enumerate(f):
if f.smooth: normal= rvec3d(v.no)
else: normal= no
- if faceUV: uvcoord= rvec2d((uv[j][0], 1.0-uv[j][1]))
- elif vertexUV: uvcoord= rvec2d((v.uvco[0], 1.0-v.uvco[1]))
+ if faceUV: uvcoord= rvec2d(uv[j])
+ elif vertexUV: uvcoord= rvec2d(v.uvco)
if vertexColors: color= col[j].r, col[j].g, col[j].b
file.write('%d ' % vdict[v.index][normal, uvcoord, color])
diff --git a/release/scripts/ply_import.py b/release/scripts/ply_import.py
index 302e21a0a43..6b96777102a 100644
--- a/release/scripts/ply_import.py
+++ b/release/scripts/ply_import.py
@@ -2,13 +2,13 @@
"""
Name: 'Stanford PLY (*.ply)...'
-Blender: 248
+Blender: 241
Group: 'Import'
Tip: 'Import a Stanford PLY file'
"""
__author__ = 'Bruce Merry'
-__version__ = '0.93'
+__version__ = '0.92'
__bpydoc__ = """\
This script imports Stanford PLY files into Blender. It supports per-vertex
normals, and per-face colours and texture coordinates.
@@ -35,20 +35,20 @@ Run this script from "File->Import" and select the desired PLY file.
# Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
-# 20th Oct 2008, 0.93 - Updated by Campbell Barton AKA ideasman42, use Mesh rather then NMesh, dont import normals, vcolors work again.
-# Updated by Campbell Barton AKA Ideasman42, 10% faster code.
+# Updated by Campbell Barton AKA Ideasman, 10% faster code.
# Portions of this code are taken from mod_meshtools.py in Blender
# 2.32.
import Blender
try:
- import re, struct
+ import re, struct, StringIO
except:
struct= None
-class element_spec(object):
- __slots__ = 'name', 'count', 'properties'
+class element_spec:
+ name = ''
+ count = 0
def __init__(self, name, count):
self.name = name
self.count = count
@@ -64,8 +64,10 @@ class element_spec(object):
if p.name == name: return i
return -1
-class property_spec(object):
- __slots__ = 'name', 'list_type', 'numeric_type'
+class property_spec:
+ name = ''
+ list_type = ''
+ numeric_type = ''
def __init__(self, name, list_type, numeric_type):
self.name = name
self.list_type = list_type
@@ -115,17 +117,14 @@ class property_spec(object):
else:
return self.read_format(format, 1, self.numeric_type, stream)[0]
-class object_spec(object):
- __slots__ = 'specs'
+class object_spec:
'A list of element_specs'
- def __init__(self):
- self.specs = []
-
+ specs = []
+
def load(self, format, stream):
return dict([(i.name,[i.load(format, stream) for j in xrange(i.count) ]) for i in self.specs])
'''
- # Longhand for above LC
answer = {}
for i in self.specs:
answer[i.name] = []
@@ -177,7 +176,7 @@ def read(filename):
if (len(tokens) < 3):
print 'Invalid format line'
return None
- if (tokens[1] not in format_specs): # .keys()): # keys is implicit
+ if (tokens[1] not in format_specs.keys()):
print 'Unknown format', tokens[1]
return None
if (tokens[2] != version):
@@ -210,132 +209,115 @@ def read(filename):
return (obj_spec, obj);
-def load_ply(filename):
+
+def add_face(vertices, varr, indices, uvindices, colindices):
+ face = Blender.NMesh.Face([varr[i] for i in indices])
+ for index in indices:
+ vertex = vertices[index];
+
+ if uvindices:
+ face.uv.append((vertex[uvindices[0]], 1.0 - vertex[uvindices[1]]))
+ face.mode &= ~Blender.NMesh.FaceModes.TEX
+ if colindices:
+ if not uvindices: face.uv.append((0, 0)) # Force faceUV
+ face.col.append(Blender.NMesh.Col(vertex[colindices[0]], vertex[colindices[1]], vertex[colindices[2]], 255))
+ face.mode &= ~Blender.NMesh.FaceModes.TEX
+ return face
+
+def filesel_callback(filename):
t = Blender.sys.time()
- obj_spec, obj = read(filename)
+ (obj_spec, obj) = read(filename)
if obj == None:
print 'Invalid file'
return
-
- uvindices = colindices = None
- # noindices = None # Ignore normals
-
+ vmap = {}
+ varr = []
+ uvindices = None
+ noindices = None
+ colindices = None
for el in obj_spec.specs:
if el.name == 'vertex':
vindices = vindices_x, vindices_y, vindices_z = (el.index('x'), el.index('y'), el.index('z'))
- # noindices = (el.index('nx'), el.index('ny'), el.index('nz'))
- # if -1 in noindices: noindices = None
- uvindices = (el.index('s'), el.index('t'))
- if -1 in uvindices: uvindices = None
- colindices = (el.index('red'), el.index('green'), el.index('blue'))
- if -1 in colindices: colindices = None
+ if el.index('nx') >= 0 and el.index('ny') >= 0 and el.index('nz') >= 0:
+ noindices = (el.index('nx'), el.index('ny'), el.index('nz'))
+ if el.index('s') >= 0 and el.index('t') >= 0:
+ uvindices = (el.index('s'), el.index('t'))
+ if el.index('red') >= 0 and el.index('green') and el.index('blue') >= 0:
+ colindices = (el.index('red'), el.index('green'), el.index('blue'))
elif el.name == 'face':
findex = el.index('vertex_indices')
-
- mesh_faces = []
- mesh_uvs = []
- mesh_colors = []
-
- def add_face(vertices, indices, uvindices, colindices):
- mesh_faces.append(indices)
- if uvindices: mesh_uvs.append([ (vertices[index][uvindices[0]], 1.0 - vertices[index][uvindices[1]]) for index in indices])
- if colindices: mesh_colors.append([ (vertices[index][colindices[0]], vertices[index][colindices[1]], vertices[index][colindices[2]]) for index in indices])
-
-
- if uvindices or colindices:
- # If we have Cols or UVs then we need to check the face order.
- add_face_simple = add_face
- # EVIL EEKADOODLE - face order annoyance.
- def add_face(vertices, indices, uvindices, colindices):
- if len(indices)==4:
- if indices[2]==0 or indices[3]==0:
- indices= indices[2], indices[3], indices[0], indices[1]
- elif len(indices)==3:
- if indices[2]==0:
- indices= indices[1], indices[2], indices[0]
-
- add_face_simple(vertices, indices, uvindices, colindices)
+
+ mesh = Blender.NMesh.GetRaw()
+ NMVert = Blender.NMesh.Vert
+ for v in obj['vertex']:
+
+ if noindices > 0:
+ x,y,z,nx,ny,nz = vkey =\
+ (v[vindices_x], v[vindices_y], v[vindices_z],\
+ v[noindices[0]], v[noindices[1]], v[noindices[2]])
+ else:
+ x,y,z = vkey = (v[vindices_x], v[vindices_y], v[vindices_z])
+ #if not vmap.has_key(vkey):
+ try: # try uses 1 less dict lookup
+ varr.append(vmap[vkey])
+ except:
+ nmv = NMVert(vkey[0], vkey[1], vkey[2])
+ mesh.verts.append(nmv)
+ if noindices > 0:
+ nmv.no[0] = vkey[3]
+ nmv.no[1] = vkey[4]
+ nmv.no[2] = vkey[5]
+ vmap[vkey] = nmv
+ varr.append(vmap[vkey])
verts = obj['vertex']
if 'face' in obj:
for f in obj['face']:
ind = f[findex]
- len_ind = len(ind)
- if len_ind <= 4:
- add_face(verts, ind, uvindices, colindices)
+ nind = len(ind)
+ if nind <= 4:
+ mesh.faces.append(add_face(verts, varr, ind, uvindices, colindices))
else:
- # Fan fill the face
- for j in xrange(len_ind - 2):
- add_face(verts, (ind[0], ind[j + 1], ind[j + 2]), uvindices, colindices)
-
- mesh = Blender.Mesh.New()
-
- mesh.verts.extend([(v[vindices_x], v[vindices_y], v[vindices_z]) for v in obj['vertex']])
-
- if mesh_faces:
- mesh.faces.extend(mesh_faces, smooth=True, ignoreDups=True)
-
- if uvindices or colindices:
- if uvindices: mesh.faceUV = True
- if colindices: mesh.vertexColors = True
-
- for i, f in enumerate(mesh.faces):
- if uvindices:
- ply_uv = mesh_uvs[i]
- for j, uv in enumerate(f.uv):
- uv[:] = ply_uv[j]
-
- if colindices:
- ply_col = mesh_colors[i]
- for j, col in enumerate(f.col):
- col.r, col.g, col.b = ply_col[j]
+ for j in xrange(nind - 2):
+ mesh.faces.append(add_face(verts, varr, (ind[0], ind[j + 1], ind[j + 2]), uvindices, colindices))
+
- mesh.calcNormals()
+ del obj # Reclaim memory
+ '''
+ if noindices:
+ normals = 1
+ else:
+ normals = 0
+ '''
objname = Blender.sys.splitext(Blender.sys.basename(filename))[0]
scn= Blender.Scene.GetCurrent()
scn.objects.selected = []
mesh.name= objname
- scn.objects.active = scn.objects.new(mesh)
+ scn.objects.new(mesh)
Blender.Redraw()
Blender.Window.DrawProgressBar(1.0, '')
- print '\nSuccessfully imported "%s" in %.3f sec' % (filename, Blender.sys.time()-t)
+ print '\nSuccessfully imported ' + Blender.sys.basename(filename) + ' ' + str(Blender.sys.time()-t)
+
+
+
def main():
if not struct:
- msg = 'This importer requires a full python install'
- if Blender.mode == 'background': print msg
- else: Blender.Draw.PupMenu(msg)
+ Blender.Draw.PupMenu('This importer requires a full python install')
return
- Blender.Window.FileSelector(load_ply, 'Import PLY', '*.ply')
+ Blender.Window.FileSelector(filesel_callback, 'Import PLY', '*.ply')
if __name__=='__main__':
main()
-'''
-import bpy
-import os
-files = os.popen('find /fe/ply -iname "*.ply"').readlines()
-files.sort()
-tot = len(files)
-for i, f in enumerate(files):
- if i < 26 or i > 1000000:
- continue
- #if i != 12686:
- # continue
-
- f = f.strip()
- print f, i, tot
- sce = bpy.data.scenes.new(f.split('/')[-1])
- bpy.data.scenes.active = sce
- # Window.
- load_ply(f)
-''' \ No newline at end of file
+
+
diff --git a/release/scripts/render_save_layers.py b/release/scripts/render_save_layers.py
index c91fcce7948..ad1265be50c 100644
--- a/release/scripts/render_save_layers.py
+++ b/release/scripts/render_save_layers.py
@@ -45,7 +45,7 @@ from Blender import Scene
sce = Scene.GetCurrent()
rend = sce.render
-# default filename: filename + scenename + '_renderlayer.py' in user's scripts dir:
+# default filename: theme's name + '_theme.py' in user's scripts dir:
default_fname = Blender.Get("scriptsdir")
if not default_fname:
default_fname = Blender.Get("uscriptsdir")
@@ -81,10 +81,10 @@ Remember to also set author, version and possibly url(s) above. You can also
define an __email__ tag, check some bundled script's source for examples.
\"\"\"
-# This script was automatically generated by the render_save_layers.py bpython script.
+# This script was automatically generated by the save_theme.py bpython script.
# By default, these generated scripts are released as Public Domain, but you
# are free to change the license of the scripts you generate with
-# render_save_layers.py before releasing them.
+# save_theme.py before releasing them.
import Blender
from Blender import Scene
diff --git a/release/scripts/scripttemplate_gamelogic.py b/release/scripts/scripttemplate_gamelogic.py
deleted file mode 100644
index 7184d7e424f..00000000000
--- a/release/scripts/scripttemplate_gamelogic.py
+++ /dev/null
@@ -1,94 +0,0 @@
-#!BPY
-"""
-Name: 'GameLogic Example'
-Blender: 245
-Group: 'ScriptTemplate'
-Tooltip: 'Script template with examples of how to use game logic'
-"""
-
-from Blender import Window
-import bpy
-
-script_data = \
-'''
-# GameLogic has been added to the global namespace no need to import
-
-# for keyboard event comparison
-# import GameKeys
-
-# support for Vector(), Matrix() types and advanced functions like AngleBetweenVecs(v1,v2) and RotationMatrix(...)
-# import Mathutils
-
-# for functions like getWindowWidth(), getWindowHeight()
-# import Rasterizer
-
-def main():
- cont = GameLogic.getCurrentController()
-
- # The KX_GameObject that owns this controller.
- own = cont.getOwner()
-
- # for scripts that deal with spacial logic
- own_pos = own.getPosition()
-
-
- # Some example functions, remove to write your own script.
- # check for a positive sensor, will run on any object without errors.
- print 'Logic info for KX_GameObject', own.getName()
- input = False
-
- for sens in cont.getSensors():
- # The sensor can be on another object, we may want to use it
- own_sens = sens.getOwner()
- print ' sensor:', sens.getName(),
- if sens.isPositive():
- print '(true)'
- input = True
- else:
- print '(false)'
-
- for actu in cont.getActuators():
- # The actuator can be on another object, we may want to use it
- own_actu = actu.getOwner()
- print ' actuator:', sens.getName()
-
- # This runs the actuator or turns it off
- # note that actuators will continue to run unless explicitly turned off.
- if input:
- GameLogic.addActiveActuator(actu, True)
- else:
- GameLogic.addActiveActuator(actu, False)
-
- # Its also good practice to get sensors and actuators by names
- # so any changes to their order wont break the script.
-
- # sens_key = cont.getSensor('key_sensor')
- # actu_motion = cont.getActuator('motion')
-
-
- # Loop through all other objects in the scene
- sce = GameLogic.getCurrentScene()
- print 'Scene Objects:', sce.getName()
- for ob in sce.getObjectList():
- print ' ', ob.getName(), ob.getPosition()
-
-
- # Example where collision objects are checked for their properties
- # adding to our objects "life" property
- """
- actu_collide = cont.getSensor('collision_sens')
- for ob in actu_collide.getHitObjectList():
- # Check to see the object has this property
- if hasattr(ob, 'life'):
- own.life += ob.life
- ob.life = 0
- print own.life
- """
-
-main()
-'''
-
-new_text = bpy.data.texts.new('gamelogic_example.py')
-new_text.write(script_data)
-bpy.data.texts.active = new_text
-Window.RedrawAll()
diff --git a/release/scripts/scripttemplate_gamelogic_basic.py b/release/scripts/scripttemplate_gamelogic_basic.py
deleted file mode 100644
index 1584659d317..00000000000
--- a/release/scripts/scripttemplate_gamelogic_basic.py
+++ /dev/null
@@ -1,33 +0,0 @@
-#!BPY
-"""
-Name: 'GameLogic Template'
-Blender: 245
-Group: 'ScriptTemplate'
-Tooltip: 'Basic template for new game logic scripts'
-"""
-
-from Blender import Window
-import bpy
-
-script_data = \
-'''
-def main():
-
- cont = GameLogic.getCurrentController()
- own = cont.getOwner()
-
- sens = cont.getSensor('mySensor')
- actu = cont.getActuator('myActuator')
-
- if sens.isPositive():
- GameLogic.addActiveActuator(actu, True)
- else:
- GameLogic.addActiveActuator(actu, False)
-
-main()
-'''
-
-new_text = bpy.data.texts.new('gamelogic_simple.py')
-new_text.write(script_data)
-bpy.data.texts.active = new_text
-Window.RedrawAll()
diff --git a/release/scripts/scripttemplate_ipo_gen.py b/release/scripts/scripttemplate_ipo_gen.py
index a333b4f20bf..791eaed2c6b 100644
--- a/release/scripts/scripttemplate_ipo_gen.py
+++ b/release/scripts/scripttemplate_ipo_gen.py
@@ -1,9 +1,9 @@
#!BPY
"""
-Name: 'IPO Example'
+Name: 'Camera/Object Example'
Blender: 245
Group: 'ScriptTemplate'
-Tooltip: 'Script template for setting the IPO'
+Tooltip: 'Script template for setting the camera direction'
"""
from Blender import Window
diff --git a/release/scripts/scripttemplate_text_plugin.py b/release/scripts/scripttemplate_text_plugin.py
deleted file mode 100644
index 4ae562736d3..00000000000
--- a/release/scripts/scripttemplate_text_plugin.py
+++ /dev/null
@@ -1,69 +0,0 @@
-#!BPY
-"""
-Name: 'Text Plugin'
-Blender: 246
-Group: 'ScriptTemplate'
-Tooltip: 'Add a new text for writing a text plugin'
-"""
-
-from Blender import Window
-import bpy
-
-script_data = \
-'''#!BPY
-"""
-Name: 'My Plugin Script'
-Blender: 246
-Group: 'TextPlugin'
-Shortcut: 'Ctrl+Alt+U'
-Tooltip: 'Put some useful info here'
-"""
-
-# Add a licence here if you wish to re-distribute, we recommend the GPL
-
-from Blender import Window, sys
-import BPyTextPlugin, bpy
-
-def my_script_util(txt):
- # This function prints out statistical information about a script
-
- desc = BPyTextPlugin.get_cached_descriptor(txt)
- print '---------------------------------------'
- print 'Script Name:', desc.name
- print 'Classes:', len(desc.classes)
- print ' ', desc.classes.keys()
- print 'Functions:', len(desc.defs)
- print ' ', desc.defs.keys()
- print 'Variables:', len(desc.vars)
- print ' ', desc.vars.keys()
-
-def main():
-
- # Gets the active text object, there can be many in one blend file.
- txt = bpy.data.texts.active
-
- # Silently return if the script has been run with no active text
- if not txt:
- return
-
- # Text plug-ins should run quickly so we time it here
- Window.WaitCursor(1)
- t = sys.time()
-
- # Run our utility function
- my_script_util(txt)
-
- # Timing the script is a good way to be aware on any speed hits when scripting
- print 'Plugin script finished in %.2f seconds' % (sys.time()-t)
- Window.WaitCursor(0)
-
-
-# This lets you import the script without running it
-if __name__ == '__main__':
- main()
-'''
-
-new_text = bpy.data.texts.new('textplugin_template.py')
-new_text.write(script_data)
-bpy.data.texts.active = new_text
-Window.RedrawAll()
diff --git a/release/scripts/sysinfo.py b/release/scripts/sysinfo.py
index 3a671e7221e..9f24885829c 100644
--- a/release/scripts/sysinfo.py
+++ b/release/scripts/sysinfo.py
@@ -94,8 +94,6 @@ output = Blender.Text.New(output_filename)
output.write(header + "\n\n")
-output.write("%s\n\n" % Blender.Get('buildinfo'))
-
output.write("Platform: %s\n========\n\n" % sys.platform)
output.write("Python:\n======\n\n")
diff --git a/release/scripts/textplugin_functiondocs.py b/release/scripts/textplugin_functiondocs.py
deleted file mode 100644
index 41c8d4842a0..00000000000
--- a/release/scripts/textplugin_functiondocs.py
+++ /dev/null
@@ -1,64 +0,0 @@
-#!BPY
-"""
-Name: 'Function Documentation | Ctrl I'
-Blender: 246
-Group: 'TextPlugin'
-Shortcut: 'Ctrl+I'
-Tooltip: 'Attempts to display documentation about the function preceding the cursor.'
-"""
-
-# Only run if we have the required modules
-try:
- import bpy
- from BPyTextPlugin import *
-except ImportError:
- OK = False
-else:
- OK = True
-
-def main():
- txt = bpy.data.texts.active
- if not txt:
- return
-
- (line, c) = current_line(txt)
-
- # Check we are in a normal context
- if get_context(txt) != CTX_NORMAL:
- return
-
- # Identify the name under the cursor
- llen = len(line)
- while c<llen and (line[c].isalnum() or line[c]=='_'):
- c += 1
-
- targets = get_targets(line, c)
-
- # If no name under cursor, look backward to see if we're in function parens
- if len(targets) == 0 or targets[0] == '':
- # Look backwards for first '(' without ')'
- b = 0
- found = False
- for i in range(c-1, -1, -1):
- if line[i] == ')': b += 1
- elif line[i] == '(':
- b -= 1
- if b < 0:
- found = True
- c = i
- break
- if found: targets = get_targets(line, c)
- if len(targets) == 0 or targets[0] == '':
- return
-
- obj = resolve_targets(txt, targets)
- if not obj: return
-
- if isinstance(obj, Definition): # Local definition
- txt.showDocs(obj.doc)
- elif hasattr(obj, '__doc__') and obj.__doc__:
- txt.showDocs(obj.__doc__)
-
-# Check we are running as a script and not imported as a module
-if __name__ == "__main__" and OK:
- main()
diff --git a/release/scripts/textplugin_imports.py b/release/scripts/textplugin_imports.py
deleted file mode 100644
index ec608243c2b..00000000000
--- a/release/scripts/textplugin_imports.py
+++ /dev/null
@@ -1,91 +0,0 @@
-#!BPY
-"""
-Name: 'Import Complete|Space'
-Blender: 246
-Group: 'TextPlugin'
-Shortcut: 'Space'
-Tooltip: 'Lists modules when import or from is typed'
-"""
-
-# Only run if we have the required modules
-try:
- import bpy, sys
- from BPyTextPlugin import *
-except ImportError:
- OK = False
-else:
- OK = True
-
-def main():
- txt = bpy.data.texts.active
- if not txt:
- return
-
- line, c = current_line(txt)
-
- # Check we are in a normal context
- if get_context(txt) != CTX_NORMAL:
- return
-
- pos = line.rfind('from ', 0, c)
-
- # No 'from' found
- if pos == -1:
- # Check instead for straight 'import xxxx'
- pos2 = line.rfind('import ', 0, c)
- if pos2 != -1:
- pos2 += 7
- for i in range(pos2, c):
- if line[i]==',' or (line[i]==' ' and line[i-1]==','):
- pos2 = i+1
- elif not line[i].isalnum() and line[i] != '_':
- return
- items = [(m, 'm') for m in get_modules()]
- items.sort(cmp = suggest_cmp)
- txt.suggest(items, line[pos2:c].strip())
- return
-
- # Found 'from xxxxx' before cursor
- immediate = True
- pos += 5
- for i in range(pos, c):
- if not line[i].isalnum() and line[i] != '_' and line[i] != '.':
- immediate = False
- break
-
- # Immediate 'from' followed by at most a module name
- if immediate:
- items = [(m, 'm') for m in get_modules()]
- items.sort(cmp = suggest_cmp)
- txt.suggest(items, line[pos:c])
- return
-
- # Found 'from' earlier, suggest import if not already there
- pos2 = line.rfind('import ', pos, c)
-
- # No 'import' found after 'from' so suggest it
- if pos2 == -1:
- txt.suggest([('import', 'k')], '')
- return
-
- # Immediate 'import' before cursor and after 'from...'
- for i in range(pos2+7, c):
- if line[i]==',' or (line[i]==' ' and line[i-1]==','):
- pass
- elif not line[i].isalnum() and line[i] != '_':
- return
- between = line[pos:pos2-1].strip()
- try:
- mod = get_module(between)
- except ImportError:
- return
-
- items = [('*', 'k')]
- for (k,v) in mod.__dict__.items():
- items.append((k, type_char(v)))
- items.sort(cmp = suggest_cmp)
- txt.suggest(items, '')
-
-# Check we are running as a script and not imported as a module
-if __name__ == "__main__" and OK:
- main()
diff --git a/release/scripts/textplugin_membersuggest.py b/release/scripts/textplugin_membersuggest.py
deleted file mode 100644
index 7c0de78b704..00000000000
--- a/release/scripts/textplugin_membersuggest.py
+++ /dev/null
@@ -1,90 +0,0 @@
-#!BPY
-"""
-Name: 'Member Suggest | .'
-Blender: 246
-Group: 'TextPlugin'
-Shortcut: 'Period'
-Tooltip: 'Lists members of the object preceding the cursor in the current text space'
-"""
-
-# Only run if we have the required modules
-try:
- import bpy
- from BPyTextPlugin import *
-except ImportError:
- OK = False
-else:
- OK = True
-
-def main():
- txt = bpy.data.texts.active
- if not txt:
- return
-
- (line, c) = current_line(txt)
-
- # Check we are in a normal context
- if get_context(txt) != CTX_NORMAL:
- return
-
- targets = get_targets(line, c)
-
- if targets[0] == '': # Check if we are looking at a constant [] {} '' etc.
- i = c - len('.'.join(targets)) - 1
- if i >= 0:
- if line[i] == '"' or line[i] == "'":
- targets[0] = 'str'
- elif line[i] == '}':
- targets[0] = 'dict'
- elif line[i] == ']': # Could be array elem x[y] or list [y]
- i = line.rfind('[', 0, i) - 1
- while i >= 0:
- if line[i].isalnum() or line[i] == '_':
- break
- elif line[i] != ' ' and line[i] != '\t':
- i = -1
- break
- i -= 1
- if i < 0:
- targets[0] = 'list'
-
- obj = resolve_targets(txt, targets[:-1])
- if not obj:
- return
-
- items = []
-
- if isinstance(obj, VarDesc):
- obj = obj.type
-
- if isinstance(obj, Definition): # Locally defined
- if hasattr(obj, 'classes'):
- items.extend([(s, 'f') for s in obj.classes.keys()])
- if hasattr(obj, 'defs'):
- items.extend([(s, 'f') for s in obj.defs.keys()])
- if hasattr(obj, 'vars'):
- items.extend([(s, 'v') for s in obj.vars.keys()])
-
- else: # Otherwise we have an imported or builtin object
- try:
- attr = obj.__dict__.keys()
- except AttributeError:
- attr = dir(obj)
- else:
- if not attr: attr = dir(obj)
-
- for k in attr:
- try:
- v = getattr(obj, k)
- except (AttributeError, TypeError): # Some attributes are not readable
- pass
- else:
- items.append((k, type_char(v)))
-
- if items != []:
- items.sort(cmp = suggest_cmp)
- txt.suggest(items, targets[-1])
-
-# Check we are running as a script and not imported as a module
-if __name__ == "__main__" and OK:
- main()
diff --git a/release/scripts/textplugin_outliner.py b/release/scripts/textplugin_outliner.py
deleted file mode 100644
index 3879a2819a5..00000000000
--- a/release/scripts/textplugin_outliner.py
+++ /dev/null
@@ -1,142 +0,0 @@
-#!BPY
-"""
-Name: 'Code Outline | Ctrl T'
-Blender: 246
-Group: 'TextPlugin'
-Shortcut: 'Ctrl+T'
-Tooltip: 'Provides a menu for jumping to class and functions definitions.'
-"""
-
-# Only run if we have the required modules
-try:
- import bpy
- from BPyTextPlugin import *
- from Blender import Draw
-except ImportError:
- OK = False
-else:
- OK = True
-
-def make_menu(items, eventoffs):
- n = len(items)
- if n < 20:
- return [(items[i], i+1+eventoffs) for i in range(len(items))]
-
- letters = []
- check = 'abcdefghijklmnopqrstuvwxyz_' # Names cannot start 0-9
- for c in check:
- for item in items:
- if item[0].lower() == c:
- letters.append(c)
- break
-
- entries = {}
- i = 0
- for item in items:
- i += 1
- c = item[0].lower()
- entries.setdefault(c, []).append((item, i+eventoffs))
-
- subs = []
- for c in letters:
- subs.append((c, entries[c]))
-
- return subs
-
-def find_word(txt, word):
- i = 0
- txt.reset()
- while True:
- try:
- line = txt.readline()
- except StopIteration:
- break
- c = line.find(word)
- if c != -1:
- txt.setCursorPos(i, c)
- break
- i += 1
-
-def main():
- txt = bpy.data.texts.active
- if not txt:
- return
-
- # Identify word under cursor
- if get_context(txt) == CTX_NORMAL:
- line, c = current_line(txt)
- start = c-1
- end = c
- while start >= 0:
- if not line[start].lower() in 'abcdefghijklmnopqrstuvwxyz0123456789_':
- break
- start -= 1
- while end < len(line):
- if not line[end].lower() in 'abcdefghijklmnopqrstuvwxyz0123456789_':
- break
- end += 1
- word = line[start+1:end]
- if word in KEYWORDS:
- word = None
- else:
- word = None
-
- script = get_cached_descriptor(txt)
- items = []
- desc = None
-
- tmp = script.classes.keys()
- tmp.sort(cmp = suggest_cmp)
- class_menu = make_menu(tmp, len(items))
- class_menu_length = len(tmp)
- items.extend(tmp)
-
- tmp = script.defs.keys()
- tmp.sort(cmp = suggest_cmp)
- defs_menu = make_menu(tmp, len(items))
- defs_menu_length = len(tmp)
- items.extend(tmp)
-
- tmp = script.vars.keys()
- tmp.sort(cmp = suggest_cmp)
- vars_menu = make_menu(tmp, len(items))
- vars_menu_length = len(tmp)
- items.extend(tmp)
-
- menu = [('Script %t', 0),
- ('Classes', class_menu),
- ('Functions', defs_menu),
- ('Variables', vars_menu)]
- if word:
- menu.extend([None, ('Locate', [(word, -10)])])
-
- i = Draw.PupTreeMenu(menu)
- if i == -1:
- return
-
- # Chosen to search for word under cursor
- if i == -10:
- if script.classes.has_key(word):
- desc = script.classes[word]
- elif script.defs.has_key(word):
- desc = script.defs[word]
- elif script.vars.has_key(word):
- desc = script.vars[word]
- else:
- find_word(txt, word)
- return
- else:
- i -= 1
- if i < class_menu_length:
- desc = script.classes[items[i]]
- elif i < class_menu_length + defs_menu_length:
- desc = script.defs[items[i]]
- elif i < class_menu_length + defs_menu_length + vars_menu_length:
- desc = script.vars[items[i]]
-
- if desc:
- txt.setCursorPos(desc.lineno-1, 0)
-
-# Check we are running as a script and not imported as a module
-if __name__ == "__main__" and OK:
- main()
diff --git a/release/scripts/textplugin_suggest.py b/release/scripts/textplugin_suggest.py
deleted file mode 100644
index d8122212d3b..00000000000
--- a/release/scripts/textplugin_suggest.py
+++ /dev/null
@@ -1,94 +0,0 @@
-#!BPY
-"""
-Name: 'Suggest All | Ctrl Space'
-Blender: 246
-Group: 'TextPlugin'
-Shortcut: 'Ctrl+Space'
-Tooltip: 'Performs suggestions based on the context of the cursor'
-"""
-
-# Only run if we have the required modules
-try:
- import bpy
- from BPyTextPlugin import *
-except ImportError:
- OK = False
-else:
- OK = True
-
-def check_membersuggest(line, c):
- pos = line.rfind('.', 0, c)
- if pos == -1:
- return False
- for s in line[pos+1:c]:
- if not s.isalnum() and s != '_':
- return False
- return True
-
-def check_imports(line, c):
- pos = line.rfind('import ', 0, c)
- if pos > -1:
- for s in line[pos+7:c]:
- if not s.isalnum() and s != '_':
- return False
- return True
- pos = line.rfind('from ', 0, c)
- if pos > -1:
- for s in line[pos+5:c]:
- if not s.isalnum() and s != '_':
- return False
- return True
- return False
-
-def main():
- txt = bpy.data.texts.active
- if not txt:
- return
-
- line, c = current_line(txt)
-
- # Check we are in a normal context
- if get_context(txt) != CTX_NORMAL:
- return
-
- # Check the character preceding the cursor and execute the corresponding script
-
- if check_membersuggest(line, c):
- import textplugin_membersuggest
- textplugin_membersuggest.main()
- return
-
- elif check_imports(line, c):
- import textplugin_imports
- textplugin_imports.main()
- return
-
- # Otherwise we suggest globals, keywords, etc.
- list = []
- targets = get_targets(line, c)
- desc = get_cached_descriptor(txt)
-
- for k in KEYWORDS:
- list.append((k, 'k'))
-
- for k, v in get_builtins().items():
- list.append((k, type_char(v)))
-
- for k, v in desc.imports.items():
- list.append((k, type_char(v)))
-
- for k, v in desc.classes.items():
- list.append((k, 'f'))
-
- for k, v in desc.defs.items():
- list.append((k, 'f'))
-
- for k, v in desc.vars.items():
- list.append((k, 'v'))
-
- list.sort(cmp = suggest_cmp)
- txt.suggest(list, targets[-1])
-
-# Check we are running as a script and not imported as a module
-if __name__ == "__main__" and OK:
- main()
diff --git a/release/scripts/textplugin_templates.py b/release/scripts/textplugin_templates.py
deleted file mode 100644
index 8f949563ac0..00000000000
--- a/release/scripts/textplugin_templates.py
+++ /dev/null
@@ -1,123 +0,0 @@
-#!BPY
-"""
-Name: 'Template Completion | Tab'
-Blender: 246
-Group: 'TextPlugin'
-Shortcut: 'Tab'
-Tooltip: 'Completes templates based on the text preceding the cursor'
-"""
-
-# Only run if we have the required modules
-try:
- import bpy
- from BPyTextPlugin import *
- from Blender import Text
-except ImportError:
- OK = False
-else:
- OK = True
-
-templates = {
- 'ie':
- 'if ${1:cond}:\n'
- '\t${2}\n'
- 'else:\n'
- '\t${3}\n',
- 'iei':
- 'if ${1:cond}:\n'
- '\t${2}\n'
- 'elif:\n'
- '\t${3}\n'
- 'else:\n'
- '\t${4}\n',
- 'def':
- 'def ${1:name}(${2:params}):\n'
- '\t"""(${2}) - ${3:comment}"""\n'
- '\t${4}',
- 'cls':
- 'class ${1:name}(${2:parent}):\n'
- '\t"""${3:docs}"""\n'
- '\t\n'
- '\tdef __init__(self, ${4:params}):\n'
- '\t\t"""Creates a new ${1}"""\n'
- '\t\t${5}',
- 'class':
- 'class ${1:name}(${2:parent}):\n'
- '\t"""${3:docs}"""\n'
- '\t\n'
- '\tdef __init__(self, ${4:params}):\n'
- '\t\t"""Creates a new ${1}"""\n'
- '\t\t${5}'
-}
-
-def main():
- txt = bpy.data.texts.active
- if not txt:
- return
-
- row, c = txt.getCursorPos()
- line = txt.asLines(row, row+1)[0]
- indent=0
- while indent<c and (line[indent]==' ' or line[indent]=='\t'):
- indent += 1
-
- # Check we are in a normal context
- if get_context(txt) != CTX_NORMAL:
- return
-
- targets = get_targets(line, c-1);
- if len(targets) != 1: return
-
- color = (0, 192, 32)
-
- for trigger, template in templates.items():
- if trigger != targets[0]: continue
- inserts = {}
- txt.delete(-len(trigger)-1)
- y, x = txt.getCursorPos()
- first = None
-
- # Insert template text and parse for insertion points
- count = len(template); i = 0
- while i < count:
- if i<count-1 and template[i]=='$' and template[i+1]=='{':
- i += 2
- e = template.find('}', i)
- item = template[i:e].split(':')
- if len(item)<2: item.append('')
- if not inserts.has_key(item[0]):
- inserts[item[0]] = (item[1], [(x, y)])
- else:
- inserts[item[0]][1].append((x, y))
- item[1] = inserts[item[0]][0]
- if not first: first = (item[1], x, y)
- txt.insert(item[1])
- x += len(item[1])
- i = e
- else:
- txt.insert(template[i])
- if template[i] == '\n':
- txt.insert(line[:indent])
- y += 1
- x = indent
- else:
- x += 1
- i += 1
-
- # Insert markers at insertion points
- for id, (text, points) in inserts.items():
- for x, y in points:
- txt.setCursorPos(y, x)
- txt.setSelectPos(y, x+len(text))
- txt.markSelection((hash(text)+int(id)) & 0xFFFF, color,
- Text.TMARK_TEMP | Text.TMARK_EDITALL)
- if first:
- text, x, y = first
- txt.setCursorPos(y, x)
- txt.setSelectPos(y, x+len(text))
- break
-
-
-# Check we are running as a script and not imported as a module
-if __name__ == "__main__" and OK:
- main()
diff --git a/release/scripts/uvcalc_lightmap.py b/release/scripts/uvcalc_lightmap.py
index 1433ccbd13a..37423b7197e 100644
--- a/release/scripts/uvcalc_lightmap.py
+++ b/release/scripts/uvcalc_lightmap.py
@@ -47,12 +47,6 @@ def AngleBetweenVecs(a1,a2):
except:
return 180.0
-# python 2.3 has no reversed() iterator. this will only work on lists and tuples
-try:
- reversed
-except:
- def reversed(l): return l[::-1]
-
class prettyface(object):
__slots__ = 'uv', 'width', 'height', 'children', 'xoff', 'yoff', 'has_parent', 'rot'
def __init__(self, data):
@@ -457,10 +451,7 @@ PREF_MARGIN_DIV= 512):
# Even boxes in groups of 4
for d, boxes in even_dict.items():
if d < max_int_dimension:
- # py 2.3 compat
- try: boxes.sort(key = lambda a: len(a.children))
- except: boxes.sort(lambda a, b: cmp(len(a.children), len(b.children)))
-
+ boxes.sort(key = lambda a: len(a.children))
while len(boxes) >= 4:
# print "bar", len(boxes)
ok = True
diff --git a/release/scripts/vertexpaint_from_material.py b/release/scripts/vertexpaint_from_material.py
index 9668c521f3a..2df5b7e721f 100644
--- a/release/scripts/vertexpaint_from_material.py
+++ b/release/scripts/vertexpaint_from_material.py
@@ -27,7 +27,6 @@ def matcol(mat):
int(mat.R*255),\
int(mat.G*255),\
int(mat.B*255)
- else:
return None
def mat2vcol(PREF_SEL_FACES_ONLY, PREF_ACTOB_ONLY, PREF_MULTIPLY_COLOR):
@@ -48,7 +47,7 @@ def mat2vcol(PREF_SEL_FACES_ONLY, PREF_ACTOB_ONLY, PREF_MULTIPLY_COLOR):
me= ob.getData(mesh=1)
try:
- me.vertexColors=True
+ me.faceUV=True
except: # no faces
continue
diff --git a/release/scripts/vrml97_export.py b/release/scripts/vrml97_export.py
index bd1a35f7c3b..b28c7f5bbdc 100644
--- a/release/scripts/vrml97_export.py
+++ b/release/scripts/vrml97_export.py
@@ -206,7 +206,7 @@ class VRML2Export:
if scene != inlines[0]:
return
else:
- for i in xrange(allinlines):
+ for i in range(allinlines):
nameinline=inlines[i].getName()
if (nameinline not in self.namesStandard) and (i > 0):
self.writeIndented("DEF %s Inline {\n" % \
@@ -219,7 +219,7 @@ class VRML2Export:
def writeScript(self):
textEditor = Blender.Text.Get()
alltext = len(textEditor)
- for i in xrange(alltext):
+ for i in range(alltext):
nametext = textEditor[i].getName()
nlines = textEditor[i].getNLines()
if (self.proto == 1):
@@ -227,14 +227,14 @@ class VRML2Export:
nametext == "proto.txt") and (nlines != None):
nalllines = len(textEditor[i].asLines())
alllines = textEditor[i].asLines()
- for j in xrange(nalllines):
+ for j in range(nalllines):
self.writeIndented(alllines[j] + "\n")
elif (self.proto == 0):
if (nametext == "route" or nametext == "route.js" or \
nametext == "route.txt") and (nlines != None):
nalllines = len(textEditor[i].asLines())
alllines = textEditor[i].asLines()
- for j in xrange(nalllines):
+ for j in range(nalllines):
self.writeIndented(alllines[j] + "\n")
self.writeIndented("\n")
@@ -556,28 +556,31 @@ class VRML2Export:
issmooth = 0
maters = me.materials
- nummats = len(me.materials)
+ nummats = self.getNumMaterials(me)
# Vertex and Face colors trump materials and image textures
if (self.facecolors or self.vcolors):
if nummats > 0:
- self.writeShape(ob, me, 0, None)
+ if maters[0]:
+ self.writeShape(ob, me, 0, None)
+ else:
+ self.writeShape(ob, me, -1, None)
else:
self.writeShape(ob, me, -1, None)
-
- # Do meshes with materials, possibly with image textures
+ # Do meshes with materials, possible with image textures
elif nummats > 0:
- for matnum in xrange(len(maters)):
- images = []
- if me.faceUV:
- images = self.getImages(me, matnum)
- if len(images) > 0:
- for image in images:
- self.writeShape(ob, me, matnum, image)
+ for matnum in range(len(maters)):
+ if maters[matnum]:
+ images = []
+ if me.faceUV:
+ images = self.getImages(me, matnum)
+ if len(images) > 0:
+ for image in images:
+ self.writeShape(ob, me, matnum, image)
+ else:
+ self.writeShape(ob, me, matnum, None)
else:
self.writeShape(ob, me, matnum, None)
- else:
- self.writeShape(ob, me, matnum, None)
else:
if me.faceUV:
images = self.getImages(me, -1)
@@ -605,6 +608,15 @@ class VRML2Export:
imageNames[imName]=1
return images
+ def getNumMaterials(self, me):
+ # Oh silly Blender, why do you sometimes have 'None' as
+ # a member of the me.materials array?
+ num = 0
+ for mat in me.materials:
+ if mat:
+ num = num + 1
+ return num
+
def writeCoordinates(self, me, meshName):
coordName = "coord_%s" % (meshName)
# look up coord name, use it if available
@@ -632,43 +644,20 @@ class VRML2Export:
self.writeIndented("}\n", -1)
self.writeIndented("\n")
- def testShape(self, ob, me, matnum, image):
- if ( (matnum == -1) and (image == None) ):
- if ( len(me.faces) > 0 ):
- return True
- # Check if any faces the material or image
- for face in me.faces:
- if (matnum == -1):
- if (face.image == image):
- return True
- elif (image == None):
- if (face.mat == matnum):
- return True
- else:
- if ((face.image == image) and (face.mat == matnum)):
- return True
-
- return False
-
def writeShape(self, ob, me, matnum, image):
- # matnum == -1 means don't check the face.mat
- # image == None means don't check face.image
-
- if ( not self.testShape(ob, me, matnum, image) ):
- return False
-
+ # Note: at this point it is assumed for matnum!=-1 that the
+ # material in me.materials[matnum] is not equal to 'None'.
+ # Such validation should be performed by the function that
+ # calls this one.
self.writeIndented("Shape {\n",1)
self.writeIndented("appearance Appearance {\n", 1)
if (matnum != -1):
mater = me.materials[matnum]
- if (mater):
- self.writeMaterial(mater, self.cleanStr(mater.name,''))
- if (mater.mode & Blender.Material.Modes['TEXFACE']):
- if image != None:
- self.writeImageTexture(image.name, image.filename)
- else:
- self.writeDefaultMaterial()
+ self.writeMaterial(mater, self.cleanStr(mater.name,''))
+ if (mater.mode & Blender.Material.Modes['TEXFACE']):
+ if image != None:
+ self.writeImageTexture(image.name, image.filename)
else:
if image != None:
self.writeImageTexture(image.name, image.filename)
@@ -679,8 +668,6 @@ class VRML2Export:
self.writeIndented("}\n", -1)
- return True
-
def writeGeometry(self, ob, me, matnum, image):
#-- IndexedFaceSet or IndexedLineSet
@@ -736,7 +723,7 @@ class VRML2Export:
indexStr = ""
if (matnum == -1) or (face.mat == matnum):
if (face.image == image):
- for i in xrange(len(face.verts)):
+ for i in range(len(face.verts)):
uv = face.uv[i]
indexStr += "%s " % (j)
coordStr += "%s %s, " % \
@@ -783,13 +770,13 @@ class VRML2Export:
cols = [None] * len(me.verts)
for face in me.faces:
- for vind in xrange(len(face.v)):
+ for vind in range(len(face.v)):
vertex = face.v[vind]
i = vertex.index
if cols[i] == None:
cols[i] = face.col[vind]
- for i in xrange(len(me.verts)):
+ for i in range(len(me.verts)):
aColor = self.rgbToFS(cols[i])
self.writeUnindented("%s\n" % aColor)
@@ -797,23 +784,6 @@ class VRML2Export:
self.writeIndented("]\n",-1)
self.writeIndented("}\n",-1)
- def writeDefaultMaterial(self):
- matName = "default"
-
- # look up material name, use it if available
- if self.matNames.has_key(matName):
- self.writeIndented("material USE MA_%s\n" % matName)
- self.matNames[matName]+=1
- return;
-
- self.matNames[matName]=1
- self.writeIndented("material DEF MA_%s Material {\n" % matName, 1)
- self.writeIndented("diffuseColor 0.8 0.8 0.8\n")
- self.writeIndented("specularColor 1.0 1.0 1.0\n")
- self.writeIndented("shininess 0.5\n")
- self.writeIndented("transparency 0.0\n")
- self.writeIndented("}\n",-1)
-
def writeMaterial(self, mat, matName):
# look up material name, use it if available
if self.matNames.has_key(matName):
diff --git a/release/scripts/wizard_curve2tree.py b/release/scripts/wizard_curve2tree.py
index 1965f9a5070..eb27f1ca0f5 100644
--- a/release/scripts/wizard_curve2tree.py
+++ b/release/scripts/wizard_curve2tree.py
@@ -61,12 +61,6 @@ def AngleBetweenVecsSafe(a1, a2):
except:
return 180.0
-# Python 2.3 has no reversed.
-try:
- reversed
-except:
- def reversed(l): return l[::-1]
-
# Copied from blender, we could wrap this! - BKE_curve.c
# But probably not toooo bad in python
def forward_diff_bezier(q0, q1, q2, q3, pointlist, steps, axis):
@@ -272,9 +266,7 @@ class tree:
brch.calcData()
# Sort from big to small, so big branches get priority
- # Py 2.3 dosnt have keywords in sort
- try: self.branches_all.sort( key = lambda brch: -brch.bpoints[0].radius )
- except: self.branches_all.sort( lambda brch_a, brch_b: cmp(brch_b.bpoints[0].radius, brch_a.bpoints[0].radius) ) # py2.3
+ self.branches_all.sort( key = lambda brch: -brch.bpoints[0].radius )
def closestBranchPt(self, co):
@@ -1152,8 +1144,7 @@ class tree:
# Try sorting by other properties! this is ok for now
for segments_level_current in segments_level:
- try: segments_level_current.sort( key = lambda seg: -(seg.headCo-seg.tailCo).length )
- except: segments_level_current.sort( lambda a,b: cmp((b.headCo-b.tailCo).length, (a.headCo-a.tailCo).length) ) # py2.3
+ segments_level_current.sort( key = lambda seg: -(seg.headCo-seg.tailCo).length )
for level in xrange(twig_fill_levels):
if len(segments_level) > level:
@@ -1379,23 +1370,18 @@ class tree:
# Get the branches based on our selection method!
if twig_select_mode==0:
- try: branches_sorted.sort( key = lambda brch: brch.getLength())
- except: branches_sorted.sort( lambda a,b: cmp(a.getLength(),a.getLength()) ) # py2.3
+ branches_sorted.sort( key = lambda brch: brch.getLength())
elif twig_select_mode==1:
- try: branches_sorted.sort( key = lambda brch:-brch.getLength())
- except: branches_sorted.sort( lambda a,b: cmp(b.getLength(), a.getLength()) ) # py2.3
+ branches_sorted.sort( key = lambda brch:-brch.getLength())
elif twig_select_mode==2:
- try: branches_sorted.sort( key = lambda brch:brch.getStraightness())
- except: branches_sorted.sort( lambda a,b: cmp(a.getStraightness(), b.getStraightness())) # py2.3
+ branches_sorted.sort( key = lambda brch:brch.getStraightness())
elif twig_select_mode==3:
- try: branches_sorted.sort( key = lambda brch:-brch.getStraightness())
- except: branches_sorted.sort( lambda a,b: cmp(b.getStraightness(), a.getStraightness())) # py2.3
+ branches_sorted.sort( key = lambda brch:-brch.getStraightness())
factor_int = int(len(self.branches_all) * twig_select_factor)
branches_sorted[factor_int:] = [] # remove the last part of the list
- try: branches_sorted.sort( key = lambda brch: len(brch.bpoints))
- except: branches_sorted.sort( lambda a,b: cmp(len(a.bpoints), len(b.bpoints)) ) # py2.3
+ branches_sorted.sort( key = lambda brch: len(brch.bpoints))
branches_new = []
#for i in xrange(ratio_int):
diff --git a/release/text/Python-license.txt b/release/text/Python-license.txt
index b3e8fb53db0..1487c1e9eb3 100644
--- a/release/text/Python-license.txt
+++ b/release/text/Python-license.txt
@@ -1,37 +1,37 @@
-PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2
---------------------------------------------
+PSF LICENSE AGREEMENT FOR PYTHON 2.3
+------------------------------------
1. This LICENSE AGREEMENT is between the Python Software Foundation
("PSF"), and the Individual or Organization ("Licensee") accessing and
-otherwise using this software ("Python") in source or binary form and
-its associated documentation.
+otherwise using Python 2.3 software in source or binary form and its
+associated documentation.
2. Subject to the terms and conditions of this License Agreement, PSF
hereby grants Licensee a nonexclusive, royalty-free, world-wide
license to reproduce, analyze, test, perform and/or display publicly,
-prepare derivative works, distribute, and otherwise use Python
+prepare derivative works, distribute, and otherwise use Python 2.3
alone or in any derivative version, provided, however, that PSF's
License Agreement and PSF's notice of copyright, i.e., "Copyright (c)
-2001, 2002, 2003, 2004, 2005, 2006 Python Software Foundation; All Rights
-Reserved" are retained in Python alone or in any derivative version
-prepared by Licensee.
+2001, 2002, 2003 Python Software Foundation; All Rights Reserved" are
+retained in Python 2.3 alone or in any derivative version prepared by
+Licensee.
3. In the event Licensee prepares a derivative work that is based on
-or incorporates Python or any part thereof, and wants to make
+or incorporates Python 2.3 or any part thereof, and wants to make
the derivative work available to others as provided herein, then
Licensee hereby agrees to include in any such work a brief summary of
-the changes made to Python.
+the changes made to Python 2.3.
-4. PSF is making Python available to Licensee on an "AS IS"
+4. PSF is making Python 2.3 available to Licensee on an "AS IS"
basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND
DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
-FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT
+FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 2.3 WILL NOT
INFRINGE ANY THIRD PARTY RIGHTS.
5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
-FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS
-A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON,
+2.3 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS
+A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 2.3,
OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
6. This License Agreement will automatically terminate upon a material
@@ -43,7 +43,6 @@ Licensee. This License Agreement does not grant permission to use PSF
trademarks or trade name in a trademark sense to endorse or promote
products or services of Licensee, or any third party.
-8. By copying, installing or otherwise using Python, Licensee
+8. By copying, installing or otherwise using Python 2.3, Licensee
agrees to be bound by the terms and conditions of this License
Agreement.
-
diff --git a/release/text/blender.html b/release/text/blender.html
index 30c8f0b0dc2..c7e88fb7064 100644
--- a/release/text/blender.html
+++ b/release/text/blender.html
@@ -7,7 +7,7 @@
</head>
<body>
-<h1 align="center"><a name="top">Blender v2.4x series</a></h1>
+<h1 align="center"><a name="top">Blender v2.3x series</a></h1>
<br>
<ol>
<li><a href="#intro">About</a></li>
@@ -25,19 +25,19 @@
<h2><a name="intro">1. About</a></h2>
-<p>Welcome to the world of <a href="http://www.blender.org">Blender</a>!
+<p>Welcome to the world of <a href="http://www.blender3d.org">Blender</a>!
The program you have now in your hands is a free and fully functional 3D
-modeling, animation, rendering, compositing, video editing and game creation suite. It is available for
+modeling, rendering, animation and game creation suite. It is available for
Unix-based (Linux, Mac OS X, etc.) and Windows systems and has a large
world-wide community.</p>
<p>Blender is free to be applied for any purpose, including commercial usage and
-distribution. It's free and open-source software, released under the GNU GPL
-licence. The full program sources are available on our website.</p>
+distribution. It's open-source software, released under a dual GPL / BL
+licence. The full program sources are available online.</p>
<p>For impatient readers, here the two most important links:</p>
-<a href="http://www.blender.org">www.blender.org</a> the main website<br>
-<a href="http://wiki.blender.org">wiki.blender.org</a> the documentation website<br>
+<a href="http://www.blender.org">www.blender.org</a> the developement/community website<br>
+<a href="http://www.blender3d.org">www.blender3d.org</a> the general website<br>
<p align="right"><a href="#top">back to top</a></p>
@@ -58,7 +58,7 @@ plugins and more.</p>
<p>If you are interested in the development of the program, information for
coders and the CVS repository with the sources can be found at the
-<a href="http://www.blender.org/development/">developer's section of the site.</a></p>
+<a href="http://www.blender.org">developer's site.</a></p>
<h3><a name="start_install">Installation notes:</a></h3>
@@ -108,7 +108,7 @@ it's enough to set a system variable called PYTHON to the full path to the
stand-alone Python executable (to find out execute "import sys; print
sys.executable" inside the stand-alone interpreter, not in Blender). To check
which Python was linked to your Blender binary, execute "import sys; print
-sys.version" at Blender's text editor), it's probably 2.5.something -- only the
+sys.version" at Blender's text editor), it's probably 2.3.something -- only the
two first numbers should have to match with yours.</p>
@@ -130,10 +130,10 @@ Renderman compliant ones. By <strong>animating</strong> the data and rendering
pictures of each successive frame, movie sequences can be created.</p>
<p>In <strong>compositing</strong> a set of techniques is used to add effects
-to rendered images and combine these into a single frame. This is how, for
-example, artists add laser beams, glows and dinosaurs to motion
-pictures. Blender also has builtin
-support for video sequence editing and sound synchronization.</p>
+to movie strips and combine these into a single video. This is how, for
+example, artists add laser beams, glows and dinossaurs to motion
+pictures. Blender is not a specific tool for this purpose, but it has builtin
+support for video sequencing and sound synchronization.</p>
<p>The <strong>game engine</strong> inside Blender lets users create and play
nifty 3d games, complete with 3d graphics, sound, physics and scripted rules.
@@ -158,10 +158,10 @@ yourself for your favorite window manager.</p>
command-line prompt. Try "blender -h" to see all available options.</p>
<p>Blender saves data in its own custom binary format, using ".blend" as
-extension. The default start-up configuration is saved in a file in your home directory called
+extension. The default start-up configuration is saved in a file called
.B.blend. To save your changes to it, click on
<strong>File-&gt;Save Default Settings</strong> or use the Control+u shortcut
-directly.</p>
+directly. To revert to factory defaults, erase the .B.blend file.</p>
<h3><a name="start_1st">First steps:</a></h3>
@@ -173,7 +173,8 @@ syndrome, just relax and <a href="#faq_2">read this part</a> of the F.A.Q. </p>
<p>Hoping the explanations helped, let's start Blender and take a look at it.
At the top header you can see the main menu. Under "File" you'll find entries
to save, load and quit. If <em>someone</em> ever messes with your workspace
-and you can't find your way around: use the menu <strong>File->Load Factory settings</strong>.</p>
+and you can't find your way around: press q to quit. Then erase the .B.blend
+file in your home dir and the program will be back to factory defaults.</p>
<p>Blender's screen is divided in "areas". Each of them has a top or bottom
header and can show any of the available builtin applications (called "spaces",
@@ -264,8 +265,9 @@ each space.</p>
<h2><a name="resources">4. Resources</a></h2>
<ul>
- <li><a href="http://www.blender.org">www.blender.org</a> - the general site, with documentation and downloads</li>
- <li><a href="http://www.blenderartists.org">www.blenderartists.org</a> - the main user community web site</li>
+ <li><a href="http://www.blender3d.org">www.blender3d.org</a> - the general site, with documentation and downloads</li>
+ <li><a href="http://www.elysiun.com">www.elysiun.com</a> - the user community</li>
+ <li><a href="http://www.blender.org">www.blender.org</a> - the developer's site</li>
<li><a href="http://projects.blender.org">projects.blender.org</a> - the project's site</li>
</ul>
@@ -274,15 +276,38 @@ each space.</p>
resources you will need. We can't teach you 3D in these few lines of text,
that would take a lengthy book.</p>
+<p>The Blender Foundation has released a new guide, with hundreds of pages of
+illustrated tutorials. It comes with a CD-ROM that has Blender version 2.32,
+YafRay and many goodies: sample .blend files with models, textures and
+animations, plugins, scripts, documentation, etc. It's an extensive reference
+written by Blender gurus and also a good way to help Blender development.</p>
+
+<p><strong>New</strong>: the new guide's text is now available for download
+online and the second edition of the printed book has also been released.</p>
+
+<p>You can learn more about it at the main Blender site:
+<a href="http://www.blender3d.org">www.blender3d.org</a>. There you'll also
+find news, online documentation like tutorials, the 2.0 guide, the Blender
+Python API Reference for script writers, docs for the newest features added
+to the program, etc. There are also forums, galleries of images and movies,
+games, scripts, plugins, links for many resources and more.</p>
+
+<p>The main Blender community site is elYsiun:
+<a href="http://www.elysiun.com">www.elysiun.com</a>. There's a lot of
+activity in its user forums, where newbie and guru users share tips and tricks,
+show their most recent images, movies and scripts, ask for help and generally
+have a good time.</p>
+
<p>Irc users are invited to try #blenderchat on irc.freenode.net .</p>
<p>There are also local Blender community sites in some countries, that should
-be listed at the Community section of the main site.</p>
+be listed at the links section of the main site.</p>
-<p>If you are a coder wanting to get in touch with Blender development, a good read
-is the "Get Involved" page at <a href="http://www.blender.org/community/get-involved/">www.blender.org</a>. A
+<p>If you are a coder wanting to get in touch with Blender development, the
+developer's site is at <a href="http://www.blender.org">www.blender.org</a>. A
good way to start is to follow the mailing lists for a while and check bug
-reports, to see if you can fix one. On irc.freenode.net: #blendercoders you'll find many active developers, here also the weekly meetings take place.</p>
+reports, to see if you can fix one. On irc.freenode.net: #blendersauce (open channel)
+and #blendercoders (official channel, where also meetings take place).</p>
<h3><a name="resources_xtra">Other useful links</a></h3>
@@ -299,14 +324,17 @@ resource to create, convert and, of course, manipulate texture images.
It is also useful for work with rendered pictures, for example to add 2d text,
logos or to touch-up, apply factory or hand-made effects and compose with other
images.</dd>
-
+ <dt><a href="http://www.wings3d.com">The Wings 3D modeler</a></dt>
+ <dd>A great mesh modeler, with a different approach. Some things are much
+easier to model in Wings, others in Blender, making them a powerful combination
+for experienced users.</dd>
</dl>
<h4>Renderers:</h4>
<dl>
<dt><a href="http://www.yafray.org">YafRay</a></dt>
- <dd>A currently inactive but very impressive program. Blender has builtin
+ <dd>A relatively new and already very impressive program. Blender has builtin
support for it.</dd>
<dt><a href="http://www.povray.org">Povray</a></dt>
<dd>One of the best and most popular renderers in the world. There is a
@@ -356,8 +384,19 @@ buttons and pulldown menus. That means also the 2D options for OpenGL should
work good, something easily ignored or badly tested by 3D card manufacturors, who
target more at the latest SFX features for new 3D games.<br>
In general Blender performs
-very well on 3D cards from renowned brands, such as NVidia, ATI or 3DLabs.</p>
+very well on 3D cards from renowned brands, such as NVidia, ATI or 3DLabs. Recently
+however, new drivers (especially for ATI) have shown that they're dropping basic
+OpenGL support needed for proper menu drawing in Blender. Downgrading drivers then
+always works, but we're also working on rebuilding the (quite old) code for GUI
+drawing to prevent such errors from ever happening again.</p>
+
+<p>Some useful links to check:<br>
+<a href="http://www.blender3d.org/cms/FAQ.194.0.html">The graphics card FAQ</a><br>
+<a href="http://www.blender.org/modules/gfxdatabase/index.php">3D card performance database</a><br>
+
+
+</p>
<h3><a name="trouble_py">Scripts</a></h3>
@@ -368,7 +407,7 @@ one of the submenus there, it refers to a script. Please don't report problems
with scripts to the bug tracker or other normal Blender channels. You should
find the author's site or contact email in the script's text itself, but
usually the Python &amp; Plugins forum at
-<a href="http://www.blenderartists.org">Blenderartists.org</a> is used for posting
+<a href="http://www.elysiun.com">elYsiun</a> is used for posting
announcements, questions, suggestions and bug reports related to scripts. It's
the recommended place to look first, specially if no site was specified at the
script's window or source file(s).</p>
@@ -405,8 +444,8 @@ black rectangle.</p>
<p>Setting texture map input to "uv" in the Material Buttons window is not enough
to assign a texture image and uv data to a mesh. It's necessary to select the mesh,
-enter edit mode, indicate face selection mode (modes can be accessed in the 3d view's header), load an
-image in the UV/Image Editor window and then define a mapping (or unwrapping). Only then
+enter face select mode (modes can be accessed in the 3d view's header), load an
+image in the UV/Image Editor window and then define the mapping. Only then
the mesh will have uv data available for exporting.</p>
<p>If you want the fastest possible access to Blender's functionality, remember
@@ -416,24 +455,23 @@ workspace to your needs.</p>
<h3><a name="faq_2">What's up with the interface?</a></h3>
-<p>Blender uses a couple of innovative paradigms in the UI, not following more common, somewhat standard rules for user
-interfaces. In the past years several of our interface concepts have been adopted in more programs though,
-especially using a configurable non-overlapping subdivision layout and the paradigm to never block the UI from working by
-offering all editors and options in parallel. <br>
-Typically free programs offer easy-to-use interfaces for large audiences. Blender however is, like other high-end 3D tools,
-meant to be a powerful production tool for professionals and 3D enthusiasts, for people who are dedicated to become 3D artists with enough time
-and motivation to master the software. <br>
-This also has its origins in the 90ies, when Blender was born as an in-house studio tool, optimized to speed up daily heavy
-work, and not to please everyone. But it's true that you can consider Blender's interface
-to be not very newbie-friendly. Luckily you only have to learn it once, and once you get the basics it'll feel like 2nd nature!</p>
-
-<p>Blender also has been considerably
-improved since the 2.3x series, exposing most functionality via menus, adding
+<p>Blender does not follow the most common, somewhat standard rules for user
+interfaces -- it doesn't look like most programs do -- which is not necessarily
+a bad thing. There used to be two sides to this: Blender was both a powerful
+production tool for professionals and enthusiasts who dedicated enough time to
+master it and also a nightmare for some newcomers who might have tried one of
+the commercial 3d modelers first. The main reason for this is that
+Blender was born as an in-house studio tool, optimized to speed up daily heavy
+work, not to please everyone. But it's true that in the past the interface
+was far from newbie-friendly.</p>
+
+<p>Hopefully this is not the case anymore: it has been considerably
+improved for the 2.3x series, exposing most functionality via menus, adding
panels, color "themability", tooltips for all buttons and internationalization
support. This is an ongoing effort or, better, a goal to keep the best ideas
in Blender's design while expanding and making it more user-friendly.</p>
-<p><b>Too many buttons!</b></p>
+<p>Too many buttons!</p>
<p>Again, 3D Computer Graphics is a vast and fun field. If you're only
starting, Blender can seem daunting, specially because of all its packed
@@ -465,39 +503,38 @@ play with. A few more months and you'll probably be back asking for more ...
<p>If you ever get the impression that it's not possible to create great
looking or complex works with Blender, rejoice -- you are just plainly
-uninformed, as browsing blender.org galleries and community forums can easily confirm.</p>
+uninformed, as browsing galleries and community forums can easily confirm.</p>
<h3>How does it compare to other 3d programs?</h3>
<p>In short: it takes considerable dedication to become good, no matter which
program you work with, as long as it is good enough not to get in your way.
-Blender has, like the others, its strong and weak points.</p>
+Blender is. And, like the others, has strong and weak points.</p>
<p>Compared to commercial alternatives, Blender misses some features and isn't
as "newbie-friendly". It doesn't come packed with "one-click" or "wizard"
functionality, where you get much faster results in detriment of flexibility
and value. It also isn't bundled with tens of megabytes of sample models,
texture images, tutorials, etc. (which only partly explains how Blender can fit
-in such a small download).</p>
+in a less than 4 MB download).</p>
-<p>Thankfully, these are relatively minor shortcomings. Many of Blender's modeling, animation and
-rendering/compositing features are up-to-par with the industry standards. The pace at which features
+<p>Thankfully, these are not fatal shortcomings. The pace at which features
are being added or polished in Blender is impressive, now that it's a well
-stablished open source project. We get daily feedback from professionals and studios using Blender, and
-results from the Blender Foundation's Open Movie/Game projects such as <a href="http://www.bigbuckbunny.org">Big Buck Bunny</a>
-and <a href="http://www.yofrankie.org">Yo Frankie!</a> have set a reference standard for what a program like Blender can achieve.
- More: through plugins and scripting, many
+stablished open source project. More: through plugins and scripting, many
repetitive or otherwise cumbersome tasks can be made trivial. But plugin and
script authors go further, teaching Blender new tricks, from importers and
exporters to more advanced "applications".</p>
<p>About goodies, there are many places where you can get them (check
-<a href="#resources">resources</a>). Besides the many available Blender books, the main site and
-blenderartists.org are the best ones to start. For free texture
+<a href="#resources">resources</a>). Besides the book, the main site and
+elYsiun are the best ones to start, specially because some resources you
+find spread on the net are not up-to-date with current program versions. This
+doesn't render old tutorials or books useless -- just a little harder to
+follow, sometimes -- but older scripts probably won't work. For free texture
images, a simple search for "free textures" should bring many results, just pay
attention to their licenses if you plan to release your work later.</p>
-<p>Commercial packages might make it easier for newbies to produce nice looking
+<p>Commercial packages can make it easier for newbies to produce nice looking
material, but only another newbie would praise the results. There's a huge
difference between what a skilled artist and someone poking at buttons and
using presets can accomplish.</p>
@@ -505,10 +542,17 @@ using presets can accomplish.</p>
<p>Last but best of all: Blender is open-source, free for all to use, study and
improve.</p>
+
+<h3><a name="faq_4">Something doesn't work, what do I do?</a></h3>
+
+<p>First note again that errors and questions related to specific scripts
+should not be sent to Blender developers or its bug tracker. Then
+<a href="#trouble">read this short section thoroughly</a>, please.</p>
+
<hr>
<p>Thanks for reading, we hope you enjoy Blender!</p>
-<p><font size=-1>Document version 1.1, Sept 2008</font></p>
+<p><font size=-1>Document version 1.01, June 2004</font></p>
<p align="right"><a href="#top">back to top</a></p>
diff --git a/release/text/copyright.txt b/release/text/copyright.txt
index 9f49dd4587a..6082af3033f 100644
--- a/release/text/copyright.txt
+++ b/release/text/copyright.txt
@@ -56,7 +56,7 @@
information, claims of third parties, damages as a result of injury to
any person, or any other loss) arising out of or in connection with the
license granted under this License Agreement or the use of or inability
- to use the Software, even if BF has been advised of the possibility of
+ to use the Software, even if VF has been advised of the possibility of
such damages.
5. User warning and indemnification
diff --git a/release/windows/installer/00.sconsblender.nsi b/release/windows/installer/00.sconsblender.nsi
index 1cb159050fe..c96b188fb02 100644
--- a/release/windows/installer/00.sconsblender.nsi
+++ b/release/windows/installer/00.sconsblender.nsi
@@ -182,11 +182,12 @@ Function MigrateUserSettings
${EndIf}
FunctionEnd
-!define DLL_VER "9.00.21022.8"
+!define DLL_VER "8.00.50727.42"
+!define DLL_VER2 "7.10.3052.4"
-Function LocateCallback_90
- MoreInfo::GetProductVersion "$R9"
- Pop $0
+Function LocateCallback_80
+ MoreInfo::GetProductVersion "$R9"
+ Pop $0
${VersionCompare} "$0" "${DLL_VER}" $R1
@@ -195,7 +196,7 @@ Function LocateCallback_90
StrCmp $R1 1 0 old
old:
StrCmp $R1 2 0 end
- ; Found DLL is older
+ ; Found DLL is older
Call DownloadDLL
end:
@@ -205,14 +206,35 @@ Function LocateCallback_90
FunctionEnd
+Function LocateCallback_71
+ MoreInfo::GetProductVersion "$R9"
+ Pop $0
+
+ ${VersionCompare} "$0" "${DLL_VER2}" $R1
+
+ StrCmp $R1 0 0 new
+ new:
+ StrCmp $R1 1 0 old
+ old:
+ StrCmp $R1 2 0 end
+ ; Found DLL is older
+ Call PythonInstall
+
+ end:
+ StrCpy "$0" StopLocate
+ StrCpy $DLL_found "true"
+ Push "$0"
+
+FunctionEnd
+
Function DownloadDLL
- MessageBox MB_OK "You will need to download the Microsoft Visual C++ 2008 Redistributable Package in order to run Blender. Pressing OK will take you to the download page, please follow the instructions on the page that appears."
- StrCpy $0 "http://www.microsoft.com/downloads/details.aspx?FamilyID=9b2da534-3e03-4391-8a4d-074b9f2bc1bf&DisplayLang=en"
+ MessageBox MB_OK "You will need to download the Microsoft Visual C++ 2005 Redistributable Package in order to run Blender. Pressing OK will take you to the download page, please follow the instructions on the page that appears."
+ StrCpy $0 "http://www.microsoft.com/downloads/details.aspx?familyid=32BC1BEE-A3F9-4C13-9C99-220B62A191EE&displaylang=en"
Call openLinkNewWindow
FunctionEnd
Function PythonInstall
- MessageBox MB_OK "You will need to install python 2.5.2 in order to run blender. Pressing OK will take you to the python.org website."
+ MessageBox MB_OK "You will need to install python 2.5 in order to run blender. Pressing OK will take you to the python.org website."
StrCpy $0 "http://www.python.org"
Call openLinkNewWindow
FunctionEnd
@@ -337,19 +359,19 @@ Section "Blender-VERSION (required)" SecCopyUI
WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\Blender" "UninstallString" '"$INSTDIR\uninstall.exe"'
WriteUninstaller "uninstall.exe"
- IfSilent 0 +2
- Goto silentdone
; Check for msvcr80.dll - give notice to download if not found
MessageBox MB_OK "The installer will now check your system for the required system dlls."
StrCpy $1 $WINDIR
StrCpy $DLL_found "false"
- ${Locate} "$1" "/L=F /M=MSVCR90.DLL /S=0B" "LocateCallback_90"
+ ${Locate} "$1" "/L=F /M=MSVCR80.DLL /S=0B" "LocateCallback_80"
StrCmp $DLL_found "false" 0 +2
Call DownloadDLL
- ReadRegStr $0 HKLM SOFTWARE\Python\PythonCore\2.5\InstallPath ""
- StrCmp $0 "" 0 +2
+ StrCpy $1 $WINDIR
+ StrCpy $DLL_found "false"
+ ${Locate} "$1" "/L=F /M=MSVCR71.DLL /S=0B" "LocateCallback_71"
+ StrCmp $DLL_found "false" 0 +2
Call PythonInstall
-silentdone:
+
SectionEnd
Section "Add Start Menu shortcuts" Section2
@@ -402,7 +424,7 @@ Section "Uninstall"
Delete "$DESKTOP\Blender.lnk"
; remove directories used.
RMDir /r $BLENDERHOME\.blender\locale
- MessageBox MB_YESNO "Erase .blender\scripts folder? (ALL contents will be erased!)" /SD IDYES IDNO Next
+ MessageBox MB_YESNO "Erase .blender\scripts folder? (ALL contents will be erased!)" IDNO Next
RMDir /r $BLENDERHOME\.blender\scripts
RMDir /r $BLENDERHOME\.blender\scripts\bpymodules
RMDir /r $BLENDERHOME\.blender\scripts\bpydata
diff --git a/source/blender/blenkernel/BKE_bullet.h b/source/blender/blenkernel/BKE_bullet.h
deleted file mode 100644
index 1c3bb175d66..00000000000
--- a/source/blender/blenkernel/BKE_bullet.h
+++ /dev/null
@@ -1,43 +0,0 @@
-/**
- *
- * $Id$
- *
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, 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 *****
- */
-#ifndef BKE_BULLET_H
-#define BKE_BULLET_H
-
-struct BulletSoftBody;
-
-
-/* allocates and initializes general main data */
-extern struct BulletSoftBody *bsbNew(void);
-
-/* frees internal data and softbody itself */
-extern void bsbFree(struct BulletSoftBody *sb);
-
-#endif
-
diff --git a/source/blender/blenkernel/BKE_fluidsim.h b/source/blender/blenkernel/BKE_fluidsim.h
deleted file mode 100644
index 4aac5eafa00..00000000000
--- a/source/blender/blenkernel/BKE_fluidsim.h
+++ /dev/null
@@ -1,56 +0,0 @@
-/**
- * BKE_fluidsim.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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, 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 *****
- */
-
-#include "DNA_modifier_types.h"
-#include "DNA_object_fluidsim.h" // N_T
-#include "DNA_object_types.h"
-
-#include "BKE_DerivedMesh.h"
-
-/* old interface */
-FluidsimSettings *fluidsimSettingsNew(Object *srcob);
-
-void initElbeemMesh(Object *ob, int *numVertices, float **vertices, int *numTriangles, int **triangles, int useGlobalCoords, int modifierIndex);
-
-
-/* new fluid-modifier interface */
-void fluidsim_init(FluidsimModifierData *fluidmd);
-void fluidsim_free(FluidsimModifierData *fluidmd);
-
-DerivedMesh *fluidsim_read_cache(Object *ob, DerivedMesh *orgdm, FluidsimModifierData *fluidmd, int framenr, int useRenderParams);
-void fluidsim_read_vel_cache(FluidsimModifierData *fluidmd, DerivedMesh *dm, char *filename);
-DerivedMesh *fluidsimModifier_do(FluidsimModifierData *fluidmd, Object *ob, DerivedMesh *dm, int useRenderParams, int isFinalCalc);
-
-// get bounding box of mesh
-void fluid_get_bb(MVert *mvert, int totvert, float obmat[][4],
- /*RET*/ float start[3], /*RET*/ float size[3] );
-
-
-
diff --git a/source/blender/blenkernel/BKE_multires.h b/source/blender/blenkernel/BKE_multires.h
index df565ddc7fe..8ee1d15d0f3 100644
--- a/source/blender/blenkernel/BKE_multires.h
+++ b/source/blender/blenkernel/BKE_multires.h
@@ -27,42 +27,58 @@
* ***** END GPL LICENSE BLOCK *****
*/
-struct CustomData;
-struct EditMesh;
-struct Multires;
-struct MultiresLevel;
+struct DerivedMesh;
struct Mesh;
+struct MFace;
+struct MultiresModifierData;
struct Object;
-/* Level access */
-struct MultiresLevel *current_level(struct Multires *mr);
-struct MultiresLevel *multires_level_n(struct Multires *mr, int n);
+typedef struct MultiresSubsurf {
+ struct MultiresModifierData *mmd;
+ struct Mesh *me;
+} MultiresSubsurf;
+
+typedef struct IndexNode {
+ struct IndexNode *next, *prev;
+ int index;
+} IndexNode;
+
+void create_vert_face_map(ListBase **map, IndexNode **mem, const struct MFace *mface,
+ const int totvert, const int totface);
+void create_vert_edge_map(ListBase **map, IndexNode **mem, const struct MEdge *medge,
+ const int totvert, const int totedge);
-/* Level control */
-void multires_add_level(struct Object *ob, struct Mesh *me, const char subdiv_type);
-void multires_set_level(struct Object *ob, struct Mesh *me, const int render);
-void multires_free_level(struct MultiresLevel *lvl);
+/* MultiresDM */
+struct Mesh *MultiresDM_get_mesh(struct DerivedMesh *dm);
+struct DerivedMesh *MultiresDM_new(struct MultiresSubsurf *, struct DerivedMesh*, int, int, int);
+void *MultiresDM_get_vertnorm(struct DerivedMesh *);
+void *MultiresDM_get_orco(struct DerivedMesh *);
+struct MVert *MultiresDM_get_subco(struct DerivedMesh *);
+struct ListBase *MultiresDM_get_vert_face_map(struct DerivedMesh *);
+struct ListBase *MultiresDM_get_vert_edge_map(struct DerivedMesh *);
+int *MultiresDM_get_face_offsets(struct DerivedMesh *);
+int MultiresDM_get_totlvl(struct DerivedMesh *);
+int MultiresDM_get_lvl(struct DerivedMesh *);
+void MultiresDM_set_update(struct DerivedMesh *, void (*)(struct DerivedMesh*));
+int *MultiresDM_get_flags(struct DerivedMesh *);
-void multires_edge_level_update(struct Object *ob, struct Mesh *me);
+#define MULTIRES_DM_UPDATE_BLOCK 1
+#define MULTIRES_DM_UPDATE_ALWAYS 2
-void multires_free(struct Multires *mr);
-struct Multires *multires_copy(struct Multires *orig);
-void multires_create(struct Object *ob, struct Mesh *me);
+void multires_force_update(struct Object *ob);
-/* CustomData */
-void multires_delete_layer(struct Mesh *me, struct CustomData *cd, const int type, int n);
-void multires_add_layer(struct Mesh *me, struct CustomData *cd, const int type, const int n);
-void multires_del_lower_customdata(struct Multires *mr, struct MultiresLevel *cr_lvl);
-void multires_to_mcol(struct MultiresColFace *f, MCol mcol[4]);
-/* After adding or removing vcolor layers, run this */
-void multires_load_cols(struct Mesh *me);
+struct DerivedMesh *multires_dm_create_from_derived(struct MultiresModifierData*, struct DerivedMesh*,
+ struct Mesh *, int, int);
-/* Private (used in multires-firstlevel.c) */
-void multires_level_to_mesh(struct Object *ob, struct Mesh *me, const int render);
-void multires_update_levels(struct Mesh *me, const int render);
-void multires_update_first_level(struct Mesh *me, struct EditMesh *em);
-void multires_update_customdata(struct MultiresLevel *lvl1, struct EditMesh *em, struct CustomData *src,
- struct CustomData *dst, const int type);
-void multires_customdata_to_mesh(struct Mesh *me, struct EditMesh *em,
- struct MultiresLevel *lvl, struct CustomData *src,
- struct CustomData *dst, const int type);
+int multiresModifier_switch_level(struct Object *, const int);
+void multiresModifier_join(struct Object *);
+void multiresModifier_del_levels(struct MultiresModifierData *, struct Object *, int direction);
+void multiresModifier_subdivide(struct MultiresModifierData *mmd, struct Object *ob, int distance,
+ int updateblock, int simple);
+void multiresModifier_setLevel(void *mmd_v, void *ob_v);
+int multiresModifier_reshape(struct MultiresModifierData *mmd, struct Object *dst, struct Object *src);
+
+/* Related to the old multires */
+struct Multires;
+void multires_load_old(struct DerivedMesh *, struct Multires *);
+void multires_free(struct Multires*);
diff --git a/source/blender/blenkernel/BKE_sculpt.h b/source/blender/blenkernel/BKE_sculpt.h
index 5d7ed28f561..ec66fca6f38 100644
--- a/source/blender/blenkernel/BKE_sculpt.h
+++ b/source/blender/blenkernel/BKE_sculpt.h
@@ -30,6 +30,8 @@
#ifndef BKE_SCULPT_H
#define BKE_SCULPT_H
+struct MFace;
+struct MVert;
struct NumInput;
struct RadialControl;
struct Scene;
@@ -40,6 +42,13 @@ typedef struct SculptSession {
struct ProjVert *projverts;
struct bglMats *mats;
+
+ int multires;
+ int totvert;
+ int totface;
+ struct MVert *mvert;
+ struct MFace *mface;
+ float *face_normals;
/* An array of lists; array is sized as
large as the number of verts in the mesh,
diff --git a/source/blender/blenkernel/BKE_shrinkwrap.h b/source/blender/blenkernel/BKE_shrinkwrap.h
deleted file mode 100644
index eed22ff9d8e..00000000000
--- a/source/blender/blenkernel/BKE_shrinkwrap.h
+++ /dev/null
@@ -1,150 +0,0 @@
-/**
- * BKE_shrinkwrap.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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, 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 *****
- */
-#ifndef BKE_SHRINKWRAP_H
-#define BKE_SHRINKWRAP_H
-
-/* mesh util */
-//TODO: move this somewhere else
-#include "BKE_customdata.h"
-struct DerivedMesh;
-struct Object;
-struct DerivedMesh *object_get_derived_final(struct Object *ob, CustomDataMask dataMask);
-
-
-/* SpaceTransform stuff */
-/*
- * TODO: move this somewhere else
- *
- * this structs encapsulates all needed data to convert between 2 coordinate spaces
- * (where conversion can be represented by a matrix multiplication)
- *
- * This is used to reduce the number of arguments to pass to functions that need to perform
- * this kind of operation and make it easier for the coder, as he/she doenst needs to recode
- * the matrix calculation.
- *
- * A SpaceTransform is initialized using:
- * space_transform_setup( &data, ob1, ob2 )
- *
- * After that the following calls can be used:
- * space_transform_apply (&data, co); //converts a coordinate in ob1 coords space to the corresponding ob2 coords
- * space_transform_invert(&data, co); //converts a coordinate in ob2 coords space to the corresponding ob1 coords
- *
- * //Same Concept as space_transform_apply and space_transform_invert, but no is normalized after conversion
- * space_transform_apply_normal (&data, &no);
- * space_transform_invert_normal(&data, &no);
- *
- */
-struct Object;
-
-typedef struct SpaceTransform
-{
- float local2target[4][4];
- float target2local[4][4];
-
-} SpaceTransform;
-
-void space_transform_from_matrixs(SpaceTransform *data, float local[][4], float target[][4]);
-#define space_transform_setup(data, local, target) space_transform_from_matrixs(data, (local)->obmat, (target)->obmat)
-
-void space_transform_apply (const SpaceTransform *data, float *co);
-void space_transform_invert(const SpaceTransform *data, float *co);
-
-void space_transform_apply_normal (const SpaceTransform *data, float *no);
-void space_transform_invert_normal(const SpaceTransform *data, float *no);
-
-/* Shrinkwrap stuff */
-#include "BKE_bvhutils.h"
-
-/*
- * Shrinkwrap is composed by a set of functions and options that define the type of shrink.
- *
- * 3 modes are available:
- * - Nearest vertex
- * - Nearest surface
- * - Normal projection
- *
- * ShrinkwrapCalcData encapsulates all needed data for shrinkwrap functions.
- * (So that you dont have to pass an enormous ammount of arguments to functions)
- */
-
-struct Object;
-struct DerivedMesh;
-struct ShrinkwrapModifierData;
-struct MDeformVert;
-struct BVHTree;
-
-
-typedef struct ShrinkwrapCalcData
-{
- ShrinkwrapModifierData *smd; //shrinkwrap modifier data
-
- struct Object *ob; //object we are applying shrinkwrap to
- struct DerivedMesh *original; //mesh before shrinkwrap
-
- float (*vertexCos)[3]; //vertexs being shrinkwraped
- int numVerts;
-
- struct MDeformVert* dvert; //Pointer to mdeform array
- int vgroup; //Vertex group num
-
- struct DerivedMesh *target; //mesh we are shrinking to
- SpaceTransform local2target; //transform to move bettwem local and target space
-
- float keepDist; //Distance to kept from target (units are in local space)
-
-} ShrinkwrapCalcData;
-
-void shrinkwrap_calc_nearest_vertex(ShrinkwrapCalcData *data);
-void shrinkwrap_calc_normal_projection(ShrinkwrapCalcData *data);
-void shrinkwrap_calc_nearest_surface_point(ShrinkwrapCalcData *data);
-
-void shrinkwrapModifier_deform(struct ShrinkwrapModifierData *smd, struct Object *ob, struct DerivedMesh *dm, float (*vertexCos)[3], int numVerts);
-
-/*
- * This function casts a ray in the given BVHTree.. but it takes into consideration the space_transform, that is:
- *
- * if transf was configured with "space_transform_setup( &transf, ob1, ob2 )"
- * then the input (vert, dir, BVHTreeRayHit) must be defined in ob1 coordinates space
- * and the BVHTree must be built in ob2 coordinate space.
- *
- * Thus it provides an easy way to cast the same ray across several trees (where each tree was built on its own coords space)
- */
-int normal_projection_project_vertex(char options, const float *vert, const float *dir, const SpaceTransform *transf, BVHTree *tree, BVHTreeRayHit *hit, BVHTree_RayCastCallback callback, void *userdata);
-
-/*
- * NULL initializers to local data
- */
-#define NULL_ShrinkwrapCalcData {NULL, }
-#define NULL_BVHTreeFromMesh {NULL, }
-#define NULL_BVHTreeRayHit {NULL, }
-#define NULL_BVHTreeNearest {0, }
-
-
-#endif
-
diff --git a/source/blender/blenkernel/BKE_simple_deform.h b/source/blender/blenkernel/BKE_simple_deform.h
deleted file mode 100644
index 161871a64bc..00000000000
--- a/source/blender/blenkernel/BKE_simple_deform.h
+++ /dev/null
@@ -1,39 +0,0 @@
-/**
- * BKE_shrinkwrap.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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, 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 *****
- */
-#ifndef BKE_SIMPLE_DEFORM_H
-#define BKE_SIMPLE_DEFORM_H
-
-struct Object;
-struct DerivedMesh;
-struct SimpleDeformModifierData;
-
-void SimpleDeformModifier_do(SimpleDeformModifierData *smd, struct Object *ob, struct DerivedMesh *dm, float (*vertexCos)[3], int numVerts);
-
-#endif
-
diff --git a/source/blender/blenkernel/BKE_subsurf.h b/source/blender/blenkernel/BKE_subsurf.h
index c3c6b8d9edd..f6dc22f650a 100644
--- a/source/blender/blenkernel/BKE_subsurf.h
+++ b/source/blender/blenkernel/BKE_subsurf.h
@@ -32,6 +32,7 @@ struct Mesh;
struct Object;
struct DerivedMesh;
struct EditMesh;
+struct MultiresSubsurf;
struct SubsurfModifierData;
struct DerivedMesh *subsurf_make_derived_from_derived(
@@ -40,6 +41,13 @@ struct DerivedMesh *subsurf_make_derived_from_derived(
int useRenderParams, float (*vertCos)[3],
int isFinalCalc, int editMode);
+struct DerivedMesh *subsurf_make_derived_from_derived_with_multires(
+ struct DerivedMesh *dm,
+ struct SubsurfModifierData *smd,
+ struct MultiresSubsurf *ms,
+ int useRenderParams, float (*vertCos)[3],
+ int isFinalCalc, int editMode);
+
void subsurf_calculate_limit_positions(Mesh *me, float (*positions_r)[3]);
#endif
diff --git a/source/blender/blenkernel/BKE_suggestions.h b/source/blender/blenkernel/BKE_suggestions.h
deleted file mode 100644
index d58b8f58bf5..00000000000
--- a/source/blender/blenkernel/BKE_suggestions.h
+++ /dev/null
@@ -1,93 +0,0 @@
-/**
- * $Id: $
- *
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
- *
- * The Original Code is Copyright (C) 2008, Blender Foundation
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-#ifndef BKE_SUGGESTIONS_H
-#define BKE_SUGGESTIONS_H
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/* ****************************************************************************
-Suggestions should be added in sorted order although a linear sorting method is
-implemented. The list is then divided up based on the prefix provided by
-update_suggestions:
-
-Example:
- Prefix: ab
- aaa <-- first
- aab
- aba <-- firstmatch
- abb <-- lastmatch
- baa
- bab <-- last
-**************************************************************************** */
-
-struct Text;
-
-typedef struct SuggItem {
- struct SuggItem *prev, *next;
- char *name;
- char type;
-} SuggItem;
-
-typedef struct SuggList {
- SuggItem *first, *last;
- SuggItem *firstmatch, *lastmatch;
- SuggItem *selected;
- int top;
-} SuggList;
-
-/* Free all text tool memory */
-void free_texttools();
-
-/* Used to identify which Text object the current tools should appear against */
-void texttool_text_set_active(Text *text);
-void texttool_text_clear();
-short texttool_text_is_active(Text *text);
-
-/* Suggestions */
-void texttool_suggest_add(const char *name, char type);
-void texttool_suggest_prefix(const char *prefix);
-void texttool_suggest_clear();
-SuggItem *texttool_suggest_first();
-SuggItem *texttool_suggest_last();
-void texttool_suggest_select(SuggItem *sel);
-SuggItem *texttool_suggest_selected();
-int *texttool_suggest_top();
-
-/* Documentation */
-void texttool_docs_show(const char *docs);
-char *texttool_docs_get();
-void texttool_docs_clear();
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif
diff --git a/source/blender/blenkernel/intern/DerivedMesh.c b/source/blender/blenkernel/intern/DerivedMesh.c
index b7f068c936b..968e1afe777 100644
--- a/source/blender/blenkernel/intern/DerivedMesh.c
+++ b/source/blender/blenkernel/intern/DerivedMesh.c
@@ -71,7 +71,6 @@
#include "BKE_material.h"
#include "BKE_modifier.h"
#include "BKE_mesh.h"
-#include "BKE_multires.h"
#include "BKE_object.h"
#include "BKE_subsurf.h"
#include "BKE_texture.h"
@@ -2019,6 +2018,9 @@ CustomDataMask get_viewedit_datamask()
if(G.f & G_VERTEXPAINT || G.f & G_WEIGHTPAINT)
mask |= CD_MASK_MCOL;
+ if(G.f & G_SCULPTMODE)
+ mask |= CD_MASK_MDISPS;
+
return mask;
}
@@ -2806,93 +2808,11 @@ DerivedMesh *mesh_get_derived_deform(Object *ob, CustomDataMask dataMask)
return ob->derivedDeform;
}
-/* Move to multires Pin level, returns a copy of the original vertex coords. */
-float *multires_render_pin(Object *ob, Mesh *me, int *orig_lvl)
-{
- float *vert_copy= NULL;
-
- if(me->mr && !(me->mr->flag & MULTIRES_NO_RENDER)) {
- MultiresLevel *lvl= NULL;
- int i;
-
- /* Make sure all mesh edits are properly stored in the multires data*/
- multires_update_levels(me, 1);
-
- /* Copy the highest level of multires verts */
- *orig_lvl= me->mr->current;
- lvl= multires_level_n(me->mr, BLI_countlist(&me->mr->levels));
- vert_copy= MEM_callocN(sizeof(float)*3*lvl->totvert, "multires vert_copy");
- for(i=0; i<lvl->totvert; ++i)
- VecCopyf(&vert_copy[i*3], me->mr->verts[i].co);
-
- /* Goto the pin level for multires */
- me->mr->newlvl= me->mr->pinlvl;
- multires_set_level(ob, me, 1);
- }
-
- return vert_copy;
-}
-
-/* Propagate the changes to render level - fails if mesh topology changed */
-void multires_render_final(Object *ob, Mesh *me, DerivedMesh **dm, float *vert_copy,
- const int orig_lvl, CustomDataMask dataMask)
-{
- if(me->mr && !(me->mr->flag & MULTIRES_NO_RENDER)) {
- if((*dm)->getNumVerts(*dm) == me->totvert &&
- (*dm)->getNumFaces(*dm) == me->totface) {
- MultiresLevel *lvl= multires_level_n(me->mr, BLI_countlist(&me->mr->levels));
- DerivedMesh *old= NULL;
- MVert *vertdup= NULL;
- int i;
-
- /* Copy the verts into the mesh */
- vertdup= (*dm)->dupVertArray(*dm);
- (*dm)->release(*dm);
- for(i=0; i<me->totvert; ++i)
- me->mvert[i]= vertdup[i];
- /* Free vertdup after use*/
- MEM_freeN(vertdup);
- /* Go to the render level */
- me->mr->newlvl= me->mr->renderlvl;
- multires_set_level(ob, me, 1);
- (*dm)= getMeshDerivedMesh(me, ob, NULL);
-
- /* Some of the data in dm is referenced externally, so make a copy */
- old= *dm;
- (*dm)= CDDM_copy(old);
- old->release(old);
-
- if(dataMask & CD_MASK_ORCO)
- add_orco_dm(ob, NULL, *dm, NULL);
-
- /* Restore the original verts */
- me->mr->newlvl= BLI_countlist(&me->mr->levels);
- multires_set_level(ob, me, 1);
- for(i=0; i<lvl->totvert; ++i)
- VecCopyf(me->mvert[i].co, &vert_copy[i*3]);
- }
-
- if(vert_copy)
- MEM_freeN(vert_copy);
-
- me->mr->newlvl= orig_lvl;
- multires_set_level(ob, me, 1);
- }
-}
-
-/* Multires note - if mesh has multires enabled, mesh is first set to the Pin level,
- where all modifiers are applied, then if the topology hasn't changed, the changes
- from modifiers are propagated up to the Render level. */
DerivedMesh *mesh_create_derived_render(Object *ob, CustomDataMask dataMask)
{
DerivedMesh *final;
- Mesh *me= get_mesh(ob);
- float *vert_copy= NULL;
- int orig_lvl= 0;
- vert_copy= multires_render_pin(ob, me, &orig_lvl);
mesh_calc_modifiers(ob, NULL, NULL, &final, 1, 1, 0, dataMask, -1);
- multires_render_final(ob, me, &final, vert_copy, orig_lvl, dataMask);
return final;
}
@@ -2900,13 +2820,8 @@ DerivedMesh *mesh_create_derived_render(Object *ob, CustomDataMask dataMask)
DerivedMesh *mesh_create_derived_index_render(Object *ob, CustomDataMask dataMask, int index)
{
DerivedMesh *final;
- Mesh *me= get_mesh(ob);
- float *vert_copy= NULL;
- int orig_lvl= 0;
- vert_copy= multires_render_pin(ob, me, &orig_lvl);
mesh_calc_modifiers(ob, NULL, NULL, &final, 1, 1, 0, dataMask, index);
- multires_render_final(ob, me, &final, vert_copy, orig_lvl, dataMask);
return final;
}
@@ -2935,13 +2850,8 @@ DerivedMesh *mesh_create_derived_no_deform_render(Object *ob,
CustomDataMask dataMask)
{
DerivedMesh *final;
- Mesh *me= get_mesh(ob);
- float *vert_copy= NULL;
- int orig_lvl= 0;
- vert_copy= multires_render_pin(ob, me, &orig_lvl);
mesh_calc_modifiers(ob, vertCos, NULL, &final, 1, 0, 0, dataMask, -1);
- multires_render_final(ob, me, &final, vert_copy, orig_lvl, dataMask);
return final;
}
diff --git a/source/blender/blenkernel/intern/bullet.c b/source/blender/blenkernel/intern/bullet.c
deleted file mode 100644
index b389f8c0536..00000000000
--- a/source/blender/blenkernel/intern/bullet.c
+++ /dev/null
@@ -1,96 +0,0 @@
-/*
- *
- * $Id$
- *
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, 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 *****
- */
-
-#include "MEM_guardedalloc.h"
-
-/* types */
-#include "DNA_object_force.h" /* here is the softbody struct */
-
-#include "BKE_bullet.h"
-
-
-/* ************ Object level, exported functions *************** */
-
-/* allocates and initializes general main data */
-BulletSoftBody *bsbNew(void)
-{
- BulletSoftBody *bsb;
-
- bsb= MEM_callocN(sizeof(BulletSoftBody), "bulletsoftbody");
-
- bsb->flag = OB_BSB_BENDING_CONSTRAINTS | OB_BSB_SHAPE_MATCHING | OB_BSB_AERO_VPOINT;
- bsb->linStiff = 0.5f;
- bsb->angStiff = 1.0f;
- bsb->volume = 1.0f;
-
-
- bsb->viterations = 0;
- bsb->piterations = 2;
- bsb->diterations = 0;
- bsb->citerations = 4;
-
- bsb->kSRHR_CL = 0.1f;
- bsb->kSKHR_CL = 1.f;
- bsb->kSSHR_CL = 0.5f;
- bsb->kSR_SPLT_CL = 0.5f;
-
- bsb->kSK_SPLT_CL = 0.5f;
- bsb->kSS_SPLT_CL = 0.5f;
- bsb->kVCF = 1;
- bsb->kDP = 0;
-
- bsb->kDG = 0;
- bsb->kLF = 0;
- bsb->kPR = 0;
- bsb->kVC = 0;
-
- bsb->kDF = 0.2f;
- bsb->kMT = 0.05;
- bsb->kCHR = 1.0f;
- bsb->kKHR = 0.1f;
-
- bsb->kSHR = 1.0f;
- bsb->kAHR = 0.7f;
-
- bsb->collisionflags = 0;
- //bsb->collisionflags = OB_BSB_COL_CL_RS + OB_BSB_COL_CL_SS;
- bsb->numclusteriterations = 64;
-
- return bsb;
-}
-
-/* frees all */
-void bsbFree(BulletSoftBody *bsb)
-{
- /* no internal data yet */
- MEM_freeN(bsb);
-}
-
-
diff --git a/source/blender/blenkernel/intern/cdderivedmesh.c b/source/blender/blenkernel/intern/cdderivedmesh.c
index 2c1b5ced614..7744f807cce 100644
--- a/source/blender/blenkernel/intern/cdderivedmesh.c
+++ b/source/blender/blenkernel/intern/cdderivedmesh.c
@@ -42,6 +42,7 @@
#include "BKE_displist.h"
#include "BKE_global.h"
#include "BKE_mesh.h"
+#include "BKE_multires.h"
#include "BKE_utildefines.h"
#include "BLI_arithb.h"
@@ -52,6 +53,7 @@
#include "DNA_mesh_types.h"
#include "DNA_meshdata_types.h"
+#include "DNA_modifier_types.h"
#include "DNA_object_fluidsim.h"
#include "DNA_object_types.h"
#include "DNA_scene_types.h"
@@ -64,6 +66,7 @@
#include <string.h>
#include <limits.h>
+#include <math.h>
typedef struct {
DerivedMesh dm;
@@ -885,6 +888,7 @@ DerivedMesh *CDDM_from_mesh(Mesh *mesh, Object *ob)
{
CDDerivedMesh *cddm = cdDM_create("CDDM_from_mesh dm");
DerivedMesh *dm = &cddm->dm;
+ CustomDataMask mask = CD_MASK_MESH & (~CD_MASK_MDISPS);
int i, *index, alloctype;
/* this does a referenced copy, the only new layers being ORIGINDEX,
@@ -900,11 +904,11 @@ DerivedMesh *CDDM_from_mesh(Mesh *mesh, Object *ob)
alloctype= CD_REFERENCE;
- CustomData_merge(&mesh->vdata, &dm->vertData, CD_MASK_MESH, alloctype,
+ CustomData_merge(&mesh->vdata, &dm->vertData, mask, alloctype,
mesh->totvert);
- CustomData_merge(&mesh->edata, &dm->edgeData, CD_MASK_MESH, alloctype,
+ CustomData_merge(&mesh->edata, &dm->edgeData, mask, alloctype,
mesh->totedge);
- CustomData_merge(&mesh->fdata, &dm->faceData, CD_MASK_MESH, alloctype,
+ CustomData_merge(&mesh->fdata, &dm->faceData, mask, alloctype,
mesh->totface);
cddm->mvert = CustomData_get_layer(&dm->vertData, CD_MVERT);
@@ -1281,3 +1285,192 @@ MFace *CDDM_get_faces(DerivedMesh *dm)
return ((CDDerivedMesh*)dm)->mface;
}
+/* Multires DerivedMesh, extends CDDM */
+typedef struct MultiresDM {
+ CDDerivedMesh cddm;
+
+ MultiresModifierData *mmd;
+
+ int lvl, totlvl;
+ float (*orco)[3];
+ MVert *subco;
+
+ ListBase *vert_face_map, *vert_edge_map;
+ IndexNode *vert_face_map_mem, *vert_edge_map_mem;
+ int *face_offsets;
+
+ Mesh *me;
+ int flags;
+
+ void (*update)(DerivedMesh*);
+} MultiresDM;
+
+static void MultiresDM_release(DerivedMesh *dm)
+{
+ MultiresDM *mrdm = (MultiresDM*)dm;
+ int mvert_layer;
+
+ /* Before freeing, need to update the displacement map */
+ if(dm->needsFree && !(mrdm->flags & MULTIRES_DM_UPDATE_BLOCK))
+ mrdm->update(dm);
+
+ /* If the MVert data is being used as the sculpt undo store, don't free it */
+ mvert_layer = CustomData_get_layer_index(&dm->vertData, CD_MVERT);
+ if(mvert_layer != -1) {
+ CustomDataLayer *cd = &dm->vertData.layers[mvert_layer];
+ if(cd->data == mrdm->mmd->undo_verts)
+ cd->flag |= CD_FLAG_NOFREE;
+ }
+
+ if(DM_release(dm)) {
+ MEM_freeN(mrdm->subco);
+ MEM_freeN(mrdm->orco);
+ if(mrdm->vert_face_map)
+ MEM_freeN(mrdm->vert_face_map);
+ if(mrdm->vert_face_map_mem)
+ MEM_freeN(mrdm->vert_face_map_mem);
+ if(mrdm->vert_edge_map)
+ MEM_freeN(mrdm->vert_edge_map);
+ if(mrdm->vert_edge_map_mem)
+ MEM_freeN(mrdm->vert_edge_map_mem);
+ if(mrdm->face_offsets)
+ MEM_freeN(mrdm->face_offsets);
+ MEM_freeN(mrdm);
+ }
+}
+
+DerivedMesh *MultiresDM_new(MultiresSubsurf *ms, DerivedMesh *orig, int numVerts, int numEdges, int numFaces)
+{
+ MultiresDM *mrdm = MEM_callocN(sizeof(MultiresDM), "MultiresDM");
+ CDDerivedMesh *cddm = cdDM_create("MultiresDM CDDM");
+ DerivedMesh *dm = NULL;
+
+ mrdm->cddm = *cddm;
+ MEM_freeN(cddm);
+ dm = &mrdm->cddm.dm;
+
+ mrdm->mmd = ms->mmd;
+ mrdm->me = ms->me;
+
+ if(dm) {
+ MDisps *disps;
+ MVert *mvert;
+ int i;
+
+ DM_from_template(dm, orig, numVerts, numEdges, numFaces);
+ CustomData_free_layers(&dm->faceData, CD_MDISPS, numFaces);
+
+ disps = CustomData_get_layer(&orig->faceData, CD_MDISPS);
+ if(disps)
+ CustomData_add_layer(&dm->faceData, CD_MDISPS, CD_REFERENCE, disps, numFaces);
+
+
+ mvert = CustomData_get_layer(&orig->vertData, CD_MVERT);
+ mrdm->orco = MEM_callocN(sizeof(float) * 3 * orig->getNumVerts(orig), "multires orco");
+ for(i = 0; i < orig->getNumVerts(orig); ++i)
+ VecCopyf(mrdm->orco[i], mvert[i].co);
+ }
+ else
+ DM_init(dm, numVerts, numEdges, numFaces);
+
+ CustomData_add_layer(&dm->vertData, CD_MVERT, CD_CALLOC, NULL, numVerts);
+ CustomData_add_layer(&dm->edgeData, CD_MEDGE, CD_CALLOC, NULL, numEdges);
+ CustomData_add_layer(&dm->faceData, CD_MFACE, CD_CALLOC, NULL, numFaces);
+
+ mrdm->cddm.mvert = CustomData_get_layer(&dm->vertData, CD_MVERT);
+ mrdm->cddm.medge = CustomData_get_layer(&dm->edgeData, CD_MEDGE);
+ mrdm->cddm.mface = CustomData_get_layer(&dm->faceData, CD_MFACE);
+
+ mrdm->lvl = ms->mmd->lvl;
+ mrdm->totlvl = ms->mmd->totlvl;
+ mrdm->subco = MEM_callocN(sizeof(MVert)*numVerts, "multires subdivided verts");
+ mrdm->flags = 0;
+
+ dm->release = MultiresDM_release;
+
+ return dm;
+}
+
+Mesh *MultiresDM_get_mesh(DerivedMesh *dm)
+{
+ return ((MultiresDM*)dm)->me;
+}
+
+void *MultiresDM_get_orco(DerivedMesh *dm)
+{
+ return ((MultiresDM*)dm)->orco;
+
+}
+
+MVert *MultiresDM_get_subco(DerivedMesh *dm)
+{
+ return ((MultiresDM*)dm)->subco;
+}
+
+int MultiresDM_get_totlvl(DerivedMesh *dm)
+{
+ return ((MultiresDM*)dm)->totlvl;
+}
+
+int MultiresDM_get_lvl(DerivedMesh *dm)
+{
+ return ((MultiresDM*)dm)->lvl;
+}
+
+void MultiresDM_set_orco(DerivedMesh *dm, float (*orco)[3])
+{
+ ((MultiresDM*)dm)->orco = orco;
+}
+
+void MultiresDM_set_update(DerivedMesh *dm, void (*update)(DerivedMesh*))
+{
+ ((MultiresDM*)dm)->update = update;
+}
+
+ListBase *MultiresDM_get_vert_face_map(DerivedMesh *dm)
+{
+ MultiresDM *mrdm = (MultiresDM*)dm;
+
+ if(!mrdm->vert_face_map)
+ create_vert_face_map(&mrdm->vert_face_map, &mrdm->vert_face_map_mem, mrdm->me->mface,
+ mrdm->me->totvert, mrdm->me->totface);
+
+ return mrdm->vert_face_map;
+}
+
+ListBase *MultiresDM_get_vert_edge_map(DerivedMesh *dm)
+{
+ MultiresDM *mrdm = (MultiresDM*)dm;
+
+ if(!mrdm->vert_edge_map)
+ create_vert_edge_map(&mrdm->vert_edge_map, &mrdm->vert_edge_map_mem, mrdm->me->medge,
+ mrdm->me->totvert, mrdm->me->totedge);
+
+ return mrdm->vert_edge_map;
+}
+
+int *MultiresDM_get_face_offsets(DerivedMesh *dm)
+{
+ MultiresDM *mrdm = (MultiresDM*)dm;
+ int i, accum = 0;
+
+ if(!mrdm->face_offsets) {
+ int len = (int)pow(2, mrdm->lvl - 2) - 1;
+ int area = len * len;
+ int t = 1 + len * 3 + area * 3, q = t + len + area;
+
+ mrdm->face_offsets = MEM_callocN(sizeof(int) * mrdm->me->totface, "mrdm face offsets");
+ for(i = 0; i < mrdm->me->totface; ++i) {
+ mrdm->face_offsets[i] = accum;
+
+ accum += (mrdm->me->mface[i].v4 ? q : t);
+ }
+ }
+
+ return mrdm->face_offsets;
+}
+
+int *MultiresDM_get_flags(DerivedMesh *dm)
+{
+ return &((MultiresDM*)dm)->flags;
+}
diff --git a/source/blender/blenkernel/intern/customdata.c b/source/blender/blenkernel/intern/customdata.c
index 05271aa59a7..d9f76256529 100644
--- a/source/blender/blenkernel/intern/customdata.c
+++ b/source/blender/blenkernel/intern/customdata.c
@@ -34,6 +34,7 @@
#include "BKE_customdata.h"
+#include "BLI_arithb.h"
#include "BLI_blenlib.h"
#include "BLI_linklist.h"
#include "BLI_mempool.h"
@@ -44,6 +45,7 @@
#include "MEM_guardedalloc.h"
+#include <math.h>
#include <string.h>
/* number of layers to add when growing a CustomData object */
@@ -378,6 +380,156 @@ static void layerDefault_origspace_face(void *data, int count)
for(i = 0; i < count; i++)
osf[i] = default_osf;
}
+
+/* Adapted from sculptmode.c */
+static void mdisps_bilinear(float out[3], float (*disps)[3], int st, float u, float v)
+{
+ int x, y, x2, y2;
+ const int st_max = st - 1;
+ float urat, vrat, uopp;
+ float d[4][3], d2[2][3];
+
+ if(u < 0)
+ u = 0;
+ else if(u >= st)
+ u = st_max;
+ if(v < 0)
+ v = 0;
+ else if(v >= st)
+ v = st_max;
+
+ x = floor(u);
+ y = floor(v);
+ x2 = x + 1;
+ y2 = y + 1;
+
+ if(x2 >= st) x2 = st_max;
+ if(y2 >= st) y2 = st_max;
+
+ urat = u - x;
+ vrat = v - y;
+ uopp = 1 - urat;
+
+ VecCopyf(d[0], disps[y * st + x]);
+ VecCopyf(d[1], disps[y * st + x2]);
+ VecCopyf(d[2], disps[y2 * st + x]);
+ VecCopyf(d[3], disps[y2 * st + x2]);
+ VecMulf(d[0], uopp);
+ VecMulf(d[1], urat);
+ VecMulf(d[2], uopp);
+ VecMulf(d[3], urat);
+
+ VecAddf(d2[0], d[0], d[1]);
+ VecAddf(d2[1], d[2], d[3]);
+ VecMulf(d2[0], 1 - vrat);
+ VecMulf(d2[1], vrat);
+
+ VecAddf(out, d2[0], d2[1]);
+}
+
+static void layerSwap_mdisps(void *data, int *ci)
+{
+ MDisps *s = data;
+ float (*d)[3] = NULL;
+ int x, y, st;
+
+ if(!(ci[0] == 2 && ci[1] == 3 && ci[2] == 0 && ci[3] == 1)) return;
+
+ d = MEM_callocN(sizeof(float) * 3 * s->totdisp, "mdisps swap");
+ st = sqrt(s->totdisp);
+
+ for(y = 0; y < st; ++y) {
+ for(x = 0; x < st; ++x) {
+ VecCopyf(d[(st - y - 1) * st + (st - x - 1)], s->disps[y * st + x]);
+ }
+ }
+
+ if(s->disps)
+ MEM_freeN(s->disps);
+ s->disps = d;
+}
+
+static void layerInterp_mdisps(void **sources, float *weights, float *sub_weights,
+ int count, void *dest)
+{
+ MDisps *d = dest;
+ MDisps *s = NULL;
+ int st, stl;
+ int i, x, y;
+ float crn[4][2];
+ float (*sw)[4] = NULL;
+
+ /* Initialize the destination */
+ for(i = 0; i < d->totdisp; ++i) {
+ float z[3] = {0,0,0};
+ VecCopyf(d->disps[i], z);
+ }
+
+ /* For now, some restrictions on the input */
+ if(count != 1 || !sub_weights) return;
+
+ st = sqrt(d->totdisp);
+ stl = st - 1;
+
+ sw = (void*)sub_weights;
+ for(i = 0; i < 4; ++i) {
+ crn[i][0] = 0 * sw[i][0] + stl * sw[i][1] + stl * sw[i][2] + 0 * sw[i][3];
+ crn[i][1] = 0 * sw[i][0] + 0 * sw[i][1] + stl * sw[i][2] + stl * sw[i][3];
+ }
+
+ s = sources[0];
+ for(y = 0; y < st; ++y) {
+ for(x = 0; x < st; ++x) {
+ /* One suspects this code could be cleaner. */
+ float xl = (float)x / (st - 1);
+ float yl = (float)y / (st - 1);
+ float mid1[2] = {crn[0][0] * (1 - xl) + crn[1][0] * xl,
+ crn[0][1] * (1 - xl) + crn[1][1] * xl};
+ float mid2[2] = {crn[3][0] * (1 - xl) + crn[2][0] * xl,
+ crn[3][1] * (1 - xl) + crn[2][1] * xl};
+ float mid3[2] = {mid1[0] * (1 - yl) + mid2[0] * yl,
+ mid1[1] * (1 - yl) + mid2[1] * yl};
+
+ float srcdisp[3];
+
+ mdisps_bilinear(srcdisp, s->disps, st, mid3[0], mid3[1]);
+ VecCopyf(d->disps[y * st + x], srcdisp);
+ }
+ }
+}
+
+static void layerCopy_mdisps(const void *source, void *dest, int count)
+{
+ int i;
+ const MDisps *s = source;
+ MDisps *d = dest;
+
+ for(i = 0; i < count; ++i) {
+ if(s[i].disps) {
+ d[i].disps = MEM_dupallocN(s[i].disps);
+ d[i].totdisp = s[i].totdisp;
+ }
+ else {
+ d[i].disps = NULL;
+ d[i].totdisp = 0;
+ }
+
+ }
+}
+
+static void layerFree_mdisps(void *data, int count, int size)
+{
+ int i;
+ MDisps *d = data;
+
+ for(i = 0; i < count; ++i) {
+ if(d[i].disps)
+ MEM_freeN(d[i].disps);
+ d[i].disps = NULL;
+ d[i].totdisp = 0;
+ }
+}
+
/* --------- */
static void layerDefault_mloopcol(void *data, int count)
@@ -553,23 +705,26 @@ const LayerTypeInfo LAYERTYPEINFO[CD_NUMTYPES] = {
{sizeof(MTexPoly), "MTexPoly", 1, "Face Texture", NULL, NULL, NULL, NULL, NULL},
{sizeof(MLoopUV), "MLoopUV", 1, "UV coord", NULL, NULL, layerInterp_mloopuv, NULL, NULL},
{sizeof(MLoopCol), "MLoopCol", 1, "Col", NULL, NULL, layerInterp_mloopcol, NULL, layerDefault_mloopcol},
- {sizeof(float)*3*4, "", 0, NULL, NULL, NULL, NULL, NULL, NULL}
+ {sizeof(float)*3*4, "", 0, NULL, NULL, NULL, NULL, NULL, NULL},
+ {sizeof(MDisps), "MDisps", 1, NULL, layerCopy_mdisps,
+ layerFree_mdisps, layerInterp_mdisps, layerSwap_mdisps, NULL}
};
const char *LAYERTYPENAMES[CD_NUMTYPES] = {
"CDMVert", "CDMSticky", "CDMDeformVert", "CDMEdge", "CDMFace", "CDMTFace",
"CDMCol", "CDOrigIndex", "CDNormal", "CDFlags","CDMFloatProperty",
- "CDMIntProperty","CDMStringProperty", "CDOrigSpace", "CDOrco", "CDMTexPoly", "CDMLoopUV", "CDMloopCol", "CDTangent"};
+ "CDMIntProperty","CDMStringProperty", "CDOrigSpace", "CDOrco", "CDMTexPoly", "CDMLoopUV",
+ "CDMloopCol", "CDTangent", "CDMDisps"};
const CustomDataMask CD_MASK_BAREMESH =
CD_MASK_MVERT | CD_MASK_MEDGE | CD_MASK_MFACE;
const CustomDataMask CD_MASK_MESH =
CD_MASK_MVERT | CD_MASK_MEDGE | CD_MASK_MFACE |
CD_MASK_MSTICKY | CD_MASK_MDEFORMVERT | CD_MASK_MTFACE | CD_MASK_MCOL |
- CD_MASK_PROP_FLT | CD_MASK_PROP_INT | CD_MASK_PROP_STR;
+ CD_MASK_PROP_FLT | CD_MASK_PROP_INT | CD_MASK_PROP_STR | CD_MASK_MDISPS;
const CustomDataMask CD_MASK_EDITMESH =
CD_MASK_MSTICKY | CD_MASK_MDEFORMVERT | CD_MASK_MTFACE |
- CD_MASK_MCOL|CD_MASK_PROP_FLT | CD_MASK_PROP_INT | CD_MASK_PROP_STR;
+ CD_MASK_MCOL|CD_MASK_PROP_FLT | CD_MASK_PROP_INT | CD_MASK_PROP_STR | CD_MASK_MDISPS;
const CustomDataMask CD_MASK_DERIVEDMESH =
CD_MASK_MSTICKY | CD_MASK_MDEFORMVERT | CD_MASK_MTFACE |
CD_MASK_MCOL | CD_MASK_ORIGINDEX | CD_MASK_PROP_FLT | CD_MASK_PROP_INT |
diff --git a/source/blender/blenkernel/intern/fluidsim.c b/source/blender/blenkernel/intern/fluidsim.c
deleted file mode 100644
index 29c4e0f2fb5..00000000000
--- a/source/blender/blenkernel/intern/fluidsim.c
+++ /dev/null
@@ -1,660 +0,0 @@
-/**
- * fluidsim.c
- *
- *
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, 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 *****
- */
-
-#include "MEM_guardedalloc.h"
-
-#include "DNA_mesh_types.h"
-#include "DNA_meshdata_types.h"
-#include "DNA_object_force.h" // for pointcache
-#include "DNA_particle_types.h"
-#include "DNA_scene_types.h" // N_T
-
-#include "BLI_arithb.h"
-#include "BLI_blenlib.h"
-
-#include "BKE_cdderivedmesh.h"
-#include "BKE_customdata.h"
-#include "BKE_DerivedMesh.h"
-#include "BKE_fluidsim.h"
-#include "BKE_global.h"
-#include "BKE_modifier.h"
-#include "BKE_mesh.h"
-#include "BKE_pointcache.h"
-#include "BKE_utildefines.h"
-
-// headers for fluidsim bobj meshes
-#include <stdlib.h>
-#include "LBM_fluidsim.h"
-#include "elbeem.h"
-#include <zlib.h>
-#include <string.h>
-#include <stdio.h>
-
-/* ************************* fluidsim bobj file handling **************************** */
-
-// -----------------------------------------
-// forward decleration
-// -----------------------------------------
-
-// -----------------------------------------
-
-void fluidsim_init(FluidsimModifierData *fluidmd)
-{
-#ifndef DISABLE_ELBEEM
- if(fluidmd)
- {
- FluidsimSettings *fss = MEM_callocN(sizeof(FluidsimSettings), "fluidsimsettings");
-
- fluidmd->fss = fss;
-
- if(!fss)
- return;
-
- fss->type = OB_FSBND_NOSLIP;
- fss->show_advancedoptions = 0;
-
- fss->resolutionxyz = 50;
- fss->previewresxyz = 25;
- fss->realsize = 0.03;
- fss->guiDisplayMode = 2; // preview
- fss->renderDisplayMode = 3; // render
-
- fss->viscosityMode = 2; // default to water
- fss->viscosityValue = 1.0;
- fss->viscosityExponent = 6;
-
- // dg TODO: change this to []
- fss->gravx = 0.0;
- fss->gravy = 0.0;
- fss->gravz = -9.81;
- fss->animStart = 0.0;
- fss->animEnd = 0.30;
- fss->gstar = 0.005; // used as normgstar
- fss->maxRefine = -1;
- // maxRefine is set according to resolutionxyz during bake
-
- // fluid/inflow settings
- // fss->iniVel --> automatically set to 0
-
- /* elubie: changed this to default to the same dir as the render output
- to prevent saving to C:\ on Windows */
- BLI_strncpy(fss->surfdataPath, btempdir, FILE_MAX);
-
- // first init of bounding box
- // no bounding box needed
-
- // todo - reuse default init from elbeem!
- fss->typeFlags = 0;
- fss->domainNovecgen = 0;
- fss->volumeInitType = 1; // volume
- fss->partSlipValue = 0.0;
-
- fss->generateTracers = 0;
- fss->generateParticles = 0.0;
- fss->surfaceSmoothing = 1.0;
- fss->surfaceSubdivs = 1.0;
- fss->particleInfSize = 0.0;
- fss->particleInfAlpha = 0.0;
-
- // init fluid control settings
- fss->attractforceStrength = 0.2;
- fss->attractforceRadius = 0.75;
- fss->velocityforceStrength = 0.2;
- fss->velocityforceRadius = 0.75;
- fss->cpsTimeStart = fss->animStart;
- fss->cpsTimeEnd = fss->animEnd;
- fss->cpsQuality = 10.0; // 1.0 / 10.0 => means 0.1 width
-
- /*
- BAD TODO: this is done in buttons_object.c in the moment
- Mesh *mesh = ob->data;
- // calculate bounding box
- fluid_get_bb(mesh->mvert, mesh->totvert, ob->obmat, fss->bbStart, fss->bbSize);
- */
-
- // (ab)used to store velocities
- fss->meshSurfNormals = NULL;
-
- fss->lastgoodframe = -1;
-
- fss->flag = 0;
-
- }
-#endif
- return;
-}
-
-void fluidsim_free(FluidsimModifierData *fluidmd)
-{
-#ifndef DISABLE_ELBEEM
- if(fluidmd)
- {
- if(fluidmd->fss->meshSurfNormals)
- {
- MEM_freeN(fluidmd->fss->meshSurfNormals);
- fluidmd->fss->meshSurfNormals = NULL;
- }
- MEM_freeN(fluidmd->fss);
- }
-#endif
- return;
-}
-
-DerivedMesh *fluidsimModifier_do(FluidsimModifierData *fluidmd, Object *ob, DerivedMesh *dm, int useRenderParams, int isFinalCalc)
-{
-#ifndef DISABLE_ELBEEM
- DerivedMesh *result = NULL;
- int framenr;
- FluidsimSettings *fss = NULL;
-
- framenr= (int)G.scene->r.cfra;
-
- // only handle fluidsim domains
- if(fluidmd && fluidmd->fss && (fluidmd->fss->type != OB_FLUIDSIM_DOMAIN))
- return dm;
-
- // sanity check
- if(!fluidmd || (fluidmd && !fluidmd->fss))
- return dm;
-
- fss = fluidmd->fss;
-
- // timescale not supported yet
- // clmd->sim_parms->timescale= timescale;
-
- // support reversing of baked fluid frames here
- if((fss->flag & OB_FLUIDSIM_REVERSE) && (fss->lastgoodframe >= 0))
- {
- framenr = fss->lastgoodframe - framenr + 1;
- CLAMP(framenr, 1, fss->lastgoodframe);
- }
-
- /* try to read from cache */
- if(((fss->lastgoodframe >= framenr) || (fss->lastgoodframe < 0)) && (result = fluidsim_read_cache(ob, dm, fluidmd, framenr, useRenderParams)))
- {
- // fss->lastgoodframe = framenr; // set also in src/fluidsim.c
- return result;
- }
- else
- {
- // display last known good frame
- if(fss->lastgoodframe >= 0)
- {
- if((result = fluidsim_read_cache(ob, dm, fluidmd, fss->lastgoodframe, useRenderParams)))
- {
- return result;
- }
-
- // it was supposed to be a valid frame but it isn't!
- fss->lastgoodframe = framenr - 1;
-
-
- // this could be likely the case when you load an old fluidsim
- if((result = fluidsim_read_cache(ob, dm, fluidmd, fss->lastgoodframe, useRenderParams)))
- {
- return result;
- }
- }
-
- result = CDDM_copy(dm);
-
- if(result)
- {
- return result;
- }
- }
-
- return dm;
-#else
- return NULL;
-#endif
-}
-
-#ifndef DISABLE_ELBEEM
-/* read .bobj.gz file into a fluidsimDerivedMesh struct */
-static DerivedMesh *fluidsim_read_obj(char *filename)
-{
- int wri,i,j;
- float wrf;
- int gotBytes;
- gzFile gzf;
- int numverts = 0, numfaces = 0;
- DerivedMesh *dm = NULL;
- MFace *mface;
- MVert *mvert;
- short *normals;
-
- // ------------------------------------------------
- // get numverts + numfaces first
- // ------------------------------------------------
- gzf = gzopen(filename, "rb");
- if (!gzf)
- {
- return NULL;
- }
-
- // read numverts
- gotBytes = gzread(gzf, &wri, sizeof(wri));
- numverts = wri;
-
- // skip verts
- for(i=0; i<numverts*3; i++)
- {
- gotBytes = gzread(gzf, &wrf, sizeof( wrf ));
- }
-
- // read number of normals
- gotBytes = gzread(gzf, &wri, sizeof(wri));
-
- // skip normals
- for(i=0; i<numverts*3; i++)
- {
- gotBytes = gzread(gzf, &wrf, sizeof( wrf ));
- }
-
- /* get no. of triangles */
- gotBytes = gzread(gzf, &wri, sizeof(wri));
- numfaces = wri;
-
- gzclose( gzf );
- // ------------------------------------------------
-
- if(!numfaces || !numverts)
- return NULL;
-
- gzf = gzopen(filename, "rb");
- if (!gzf)
- {
- return NULL;
- }
-
- dm = CDDM_new(numverts, 0, numfaces);
-
- if(!dm)
- {
- gzclose( gzf );
- return NULL;
- }
-
- // read numverts
- gotBytes = gzread(gzf, &wri, sizeof(wri));
-
- // read vertex position from file
- mvert = CDDM_get_verts(dm);
- for(i=0; i<numverts; i++)
- {
- MVert *mv = &mvert[i];
-
- for(j=0; j<3; j++)
- {
- gotBytes = gzread(gzf, &wrf, sizeof( wrf ));
- mv->co[j] = wrf;
- }
- }
-
- // should be the same as numverts
- gotBytes = gzread(gzf, &wri, sizeof(wri));
- if(wri != numverts)
- {
- if(dm)
- dm->release(dm);
- gzclose( gzf );
- return NULL;
- }
-
- normals = MEM_callocN(sizeof(short) * numverts * 3, "fluid_tmp_normals" );
- if(!normals)
- {
- if(dm)
- dm->release(dm);
- gzclose( gzf );
- return NULL;
- }
-
- // read normals from file (but don't save them yet)
- for(i=0; i<numverts*3; i++)
- {
- gotBytes = gzread(gzf, &wrf, sizeof( wrf ));
- normals[i] = (short)(wrf*32767.0f);
- }
-
- /* read no. of triangles */
- gotBytes = gzread(gzf, &wri, sizeof(wri));
-
- if(wri!=numfaces)
- printf("Fluidsim: error in reading data from file.\n");
-
- // read triangles from file
- mface = CDDM_get_faces(dm);
- for(i=0; i<numfaces; i++)
- {
- int face[4];
- MFace *mf = &mface[i];
-
- gotBytes = gzread(gzf, &(face[0]), sizeof( face[0] ));
- gotBytes = gzread(gzf, &(face[1]), sizeof( face[1] ));
- gotBytes = gzread(gzf, &(face[2]), sizeof( face[2] ));
- face[3] = 0;
-
- // check if 3rd vertex has index 0 (not allowed in blender)
- if(face[2])
- {
- mf->v1 = face[0];
- mf->v2 = face[1];
- mf->v3 = face[2];
- }
- else
- {
- mf->v1 = face[1];
- mf->v2 = face[2];
- mf->v3 = face[0];
- }
- mf->v4 = face[3];
-
- test_index_face(mf, NULL, 0, 3);
- }
-
- gzclose( gzf );
-
- CDDM_calc_edges(dm);
-
- CDDM_apply_vert_normals(dm, (short (*)[3])normals);
- MEM_freeN(normals);
-
- // CDDM_calc_normals(result);
-
- return dm;
-}
-
-DerivedMesh *fluidsim_read_cache(Object *ob, DerivedMesh *orgdm, FluidsimModifierData *fluidmd, int framenr, int useRenderParams)
-{
- int displaymode = 0;
- int curFrame = framenr - 1 /*G.scene->r.sfra*/; /* start with 0 at start frame */
- char targetDir[FILE_MAXFILE+FILE_MAXDIR], targetFile[FILE_MAXFILE+FILE_MAXDIR];
- FluidsimSettings *fss = fluidmd->fss;
- DerivedMesh *dm = NULL;
- MFace *mface;
- int numfaces;
- int mat_nr, flag, i;
-
- if(!useRenderParams) {
- displaymode = fss->guiDisplayMode;
- } else {
- displaymode = fss->renderDisplayMode;
- }
-
- strncpy(targetDir, fss->surfdataPath, FILE_MAXDIR);
-
- // use preview or final mesh?
- if(displaymode==1)
- {
- // just display original object
- return NULL;
- }
- else if(displaymode==2)
- {
- strcat(targetDir,"fluidsurface_preview_####");
- }
- else
- { // 3
- strcat(targetDir,"fluidsurface_final_####");
- }
-
- BLI_convertstringcode(targetDir, G.sce);
- BLI_convertstringframe(targetDir, curFrame); // fixed #frame-no
-
- strcpy(targetFile,targetDir);
- strcat(targetFile, ".bobj.gz");
-
- dm = fluidsim_read_obj(targetFile);
-
- if(!dm)
- {
- // switch, abort background rendering when fluidsim mesh is missing
- const char *strEnvName2 = "BLENDER_ELBEEMBOBJABORT"; // from blendercall.cpp
-
- if(G.background==1) {
- if(getenv(strEnvName2)) {
- int elevel = atoi(getenv(strEnvName2));
- if(elevel>0) {
- printf("Env. var %s set, fluid sim mesh '%s' not found, aborting render...\n",strEnvName2, targetFile);
- exit(1);
- }
- }
- }
-
- // display org. object upon failure which is in dm
- return NULL;
- }
-
- // assign material + flags to new dm
- mface = orgdm->getFaceArray(orgdm);
- mat_nr = mface[0].mat_nr;
- flag = mface[0].flag;
-
- mface = dm->getFaceArray(dm);
- numfaces = dm->getNumFaces(dm);
- for(i=0; i<numfaces; i++)
- {
- mface[i].mat_nr = mat_nr;
- mface[i].flag = flag;
- }
-
- // load vertex velocities, if they exist...
- // TODO? use generate flag as loading flag as well?
- // warning, needs original .bobj.gz mesh loading filename
- if(displaymode==3)
- {
- fluidsim_read_vel_cache(fluidmd, dm, targetFile);
- }
- else
- {
- if(fss->meshSurfNormals)
- MEM_freeN(fss->meshSurfNormals);
-
- fss->meshSurfNormals = NULL;
- }
-
- return dm;
-}
-
-
-/* read zipped fluidsim velocities into the co's of the fluidsimsettings normals struct */
-void fluidsim_read_vel_cache(FluidsimModifierData *fluidmd, DerivedMesh *dm, char *filename)
-{
- int wri, i, j;
- float wrf;
- gzFile gzf;
- FluidsimSettings *fss = fluidmd->fss;
- int len = strlen(filename);
- int totvert = dm->getNumVerts(dm);
- float *velarray = NULL;
-
- // mesh and vverts have to be valid from loading...
-
- if(fss->meshSurfNormals)
- MEM_freeN(fss->meshSurfNormals);
-
- if(len<7)
- {
- return;
- }
-
- if(fss->domainNovecgen>0) return;
-
- // abusing pointer to hold an array of 3d-velocities
- fss->meshSurfNormals = MEM_callocN(sizeof(float)*3*dm->getNumVerts(dm), "Fluidsim_velocities");
- // abusing pointer to hold an INT
- fss->meshSurface = SET_INT_IN_POINTER(totvert);
-
- velarray = (float *)fss->meshSurfNormals;
-
- // .bobj.gz , correct filename
- // 87654321
- filename[len-6] = 'v';
- filename[len-5] = 'e';
- filename[len-4] = 'l';
-
- gzf = gzopen(filename, "rb");
- if (!gzf)
- {
- MEM_freeN(fss->meshSurfNormals);
- fss->meshSurfNormals = NULL;
- return;
- }
-
- gzread(gzf, &wri, sizeof( wri ));
- if(wri != totvert)
- {
- MEM_freeN(fss->meshSurfNormals);
- fss->meshSurfNormals = NULL;
- return;
- }
-
- for(i=0; i<totvert;i++)
- {
- for(j=0; j<3; j++)
- {
- gzread(gzf, &wrf, sizeof( wrf ));
- velarray[3*i + j] = wrf;
- }
- }
-
- gzclose(gzf);
-}
-
-void fluid_get_bb(MVert *mvert, int totvert, float obmat[][4],
- /*RET*/ float start[3], /*RET*/ float size[3] )
-{
- float bbsx=0.0, bbsy=0.0, bbsz=0.0;
- float bbex=1.0, bbey=1.0, bbez=1.0;
- int i;
- float vec[3];
-
- VECCOPY(vec, mvert[0].co);
- Mat4MulVecfl(obmat, vec);
- bbsx = vec[0]; bbsy = vec[1]; bbsz = vec[2];
- bbex = vec[0]; bbey = vec[1]; bbez = vec[2];
-
- for(i = 1; i < totvert; i++) {
- VECCOPY(vec, mvert[i].co);
- Mat4MulVecfl(obmat, vec);
-
- if(vec[0] < bbsx){ bbsx= vec[0]; }
- if(vec[1] < bbsy){ bbsy= vec[1]; }
- if(vec[2] < bbsz){ bbsz= vec[2]; }
- if(vec[0] > bbex){ bbex= vec[0]; }
- if(vec[1] > bbey){ bbey= vec[1]; }
- if(vec[2] > bbez){ bbez= vec[2]; }
- }
-
- // return values...
- if(start) {
- start[0] = bbsx;
- start[1] = bbsy;
- start[2] = bbsz;
- }
- if(size) {
- size[0] = bbex-bbsx;
- size[1] = bbey-bbsy;
- size[2] = bbez-bbsz;
- }
-}
-
-//-------------------------------------------------------------------------------
-// old interface
-//-------------------------------------------------------------------------------
-
-
-
-//-------------------------------------------------------------------------------
-// file handling
-//-------------------------------------------------------------------------------
-
-void initElbeemMesh(struct Object *ob,
- int *numVertices, float **vertices,
- int *numTriangles, int **triangles,
- int useGlobalCoords, int modifierIndex)
-{
- DerivedMesh *dm = NULL;
- MVert *mvert;
- MFace *mface;
- int countTris=0, i, totvert, totface;
- float *verts;
- int *tris;
-
- dm = mesh_create_derived_index_render(ob, CD_MASK_BAREMESH, modifierIndex);
- //dm = mesh_create_derived_no_deform(ob,NULL);
-
- mvert = dm->getVertArray(dm);
- mface = dm->getFaceArray(dm);
- totvert = dm->getNumVerts(dm);
- totface = dm->getNumFaces(dm);
-
- *numVertices = totvert;
- verts = MEM_callocN( totvert*3*sizeof(float), "elbeemmesh_vertices");
- for(i=0; i<totvert; i++) {
- VECCOPY( &verts[i*3], mvert[i].co);
- if(useGlobalCoords) { Mat4MulVecfl(ob->obmat, &verts[i*3]); }
- }
- *vertices = verts;
-
- for(i=0; i<totface; i++) {
- countTris++;
- if(mface[i].v4) { countTris++; }
- }
- *numTriangles = countTris;
- tris = MEM_callocN( countTris*3*sizeof(int), "elbeemmesh_triangles");
- countTris = 0;
- for(i=0; i<totface; i++) {
- int face[4];
- face[0] = mface[i].v1;
- face[1] = mface[i].v2;
- face[2] = mface[i].v3;
- face[3] = mface[i].v4;
-
- tris[countTris*3+0] = face[0];
- tris[countTris*3+1] = face[1];
- tris[countTris*3+2] = face[2];
- countTris++;
- if(face[3]) {
- tris[countTris*3+0] = face[0];
- tris[countTris*3+1] = face[2];
- tris[countTris*3+2] = face[3];
- countTris++;
- }
- }
- *triangles = tris;
-
- dm->release(dm);
-}
-
-#endif // DISABLE_ELBEEM
-
diff --git a/source/blender/blenkernel/intern/mesh.c b/source/blender/blenkernel/intern/mesh.c
index 77b9ea4fa2d..b335d28a031 100644
--- a/source/blender/blenkernel/intern/mesh.c
+++ b/source/blender/blenkernel/intern/mesh.c
@@ -58,7 +58,6 @@
#include "BKE_DerivedMesh.h"
#include "BKE_global.h"
#include "BKE_mesh.h"
-#include "BKE_multires.h"
#include "BKE_subsurf.h"
#include "BKE_displist.h"
#include "BKE_library.h"
@@ -143,8 +142,6 @@ void free_mesh(Mesh *me)
if(me->bb) MEM_freeN(me->bb);
if(me->mselect) MEM_freeN(me->mselect);
-
- if(me->mr) multires_free(me->mr);
}
void copy_dverts(MDeformVert *dst, MDeformVert *src, int copycount)
@@ -232,9 +229,6 @@ Mesh *copy_mesh(Mesh *me)
}
}
- if(me->mr)
- men->mr= multires_copy(me->mr);
-
men->mselect= NULL;
men->bb= MEM_dupallocN(men->bb);
diff --git a/source/blender/blenkernel/intern/modifier.c b/source/blender/blenkernel/intern/modifier.c
index 6bdd395a2ac..8c75f894d45 100644
--- a/source/blender/blenkernel/intern/modifier.c
+++ b/source/blender/blenkernel/intern/modifier.c
@@ -89,6 +89,7 @@
#include "BKE_displist.h"
#include "BKE_fluidsim.h"
#include "BKE_global.h"
+#include "BKE_multires.h"
#include "BKE_lattice.h"
#include "BKE_library.h"
#include "BKE_material.h"
@@ -6168,7 +6169,6 @@ static void particleSystemModifier_deformVerts(
DerivedMesh *dm = derivedData;
ParticleSystemModifierData *psmd= (ParticleSystemModifierData*) md;
ParticleSystem * psys=0;
- Mesh *me;
int needsFree=0;
if(ob->particlesystem.first)
@@ -6176,14 +6176,6 @@ static void particleSystemModifier_deformVerts(
else
return;
- /* multires check */
- if(ob->type == OB_MESH) {
- me= (Mesh*)ob->data;
- if(me->mr && me->mr->current != 1)
- modifier_setError(md,
- "Particles only supported on first multires level.");
- }
-
if(!psys_check_enabled(ob, psys))
return;
@@ -7732,6 +7724,58 @@ static void meshdeformModifier_deformVertsEM(
dm->release(dm);
}
+/* Multires */
+static void multiresModifier_initData(ModifierData *md)
+{
+ MultiresModifierData *mmd = (MultiresModifierData*)md;
+
+ mmd->lvl = mmd->totlvl = 1;
+}
+
+static void multiresModifier_freeData(ModifierData *md)
+{
+ MultiresModifierData *mmd = (MultiresModifierData*)md;
+
+ if(mmd->undo_verts)
+ MEM_freeN(mmd->undo_verts);
+}
+
+static void multiresModifier_copyData(ModifierData *md, ModifierData *target)
+{
+ MultiresModifierData *mmd = (MultiresModifierData*) md;
+ MultiresModifierData *tmmd = (MultiresModifierData*) target;
+
+ tmmd->totlvl = mmd->totlvl;
+ tmmd->lvl = mmd->lvl;
+}
+
+static DerivedMesh *multiresModifier_applyModifier(ModifierData *md, Object *ob, DerivedMesh *dm,
+ int useRenderParams, int isFinalCalc)
+{
+ MultiresModifierData *mmd = (MultiresModifierData*)md;
+ Mesh *me = get_mesh(ob);
+ DerivedMesh *final;
+
+ /* TODO: for now just skip a level1 mesh */
+ if(mmd->lvl == 1)
+ return dm;
+
+ final = multires_dm_create_from_derived(mmd, dm, me, useRenderParams, isFinalCalc);
+ if(mmd->undo_signal && mmd->undo_verts && mmd->undo_verts_tot == final->getNumVerts(final)) {
+ int i;
+ MVert *dst = CDDM_get_verts(final);
+ for(i = 0; i < mmd->undo_verts_tot; ++i) {
+ VecCopyf(dst[i].co, mmd->undo_verts[i].co);
+ }
+ CDDM_calc_normals(final);
+
+ MEM_freeN(mmd->undo_verts);
+ mmd->undo_signal = 0;
+ mmd->undo_verts = NULL;
+ }
+
+ return final;
+}
/* Shrinkwrap */
@@ -8332,6 +8376,14 @@ ModifierTypeInfo *modifierType_getInfo(ModifierType type)
mti->foreachObjectLink = simpledeformModifier_foreachObjectLink;
mti->updateDepgraph = simpledeformModifier_updateDepgraph;
+ mti = INIT_TYPE(Multires);
+ mti->type = eModifierTypeType_Constructive;
+ mti->flags = eModifierTypeFlag_AcceptsMesh | eModifierTypeFlag_RequiresOriginalData;
+ mti->initData = multiresModifier_initData;
+ mti->freeData = multiresModifier_freeData;
+ mti->copyData = multiresModifier_copyData;
+ mti->applyModifier = multiresModifier_applyModifier;
+
typeArrInit = 0;
#undef INIT_TYPE
}
diff --git a/source/blender/blenkernel/intern/multires-firstlevel.c b/source/blender/blenkernel/intern/multires-firstlevel.c
deleted file mode 100644
index 3d417565eb1..00000000000
--- a/source/blender/blenkernel/intern/multires-firstlevel.c
+++ /dev/null
@@ -1,409 +0,0 @@
-/*
- * $Id$
- *
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
- *
- * The Original Code is Copyright (C) 2006 by Nicholas Bishop
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- *
- * Deals with the first-level data in multires (edge flags, weights, and UVs)
- *
- * multires.h
- *
- */
-
-#include "DNA_customdata_types.h"
-#include "DNA_mesh_types.h"
-#include "DNA_meshdata_types.h"
-#include "DNA_object_types.h"
-#include "DNA_scene_types.h"
-
-#include "BIF_editmesh.h"
-
-#include "BKE_customdata.h"
-#include "BKE_global.h"
-#include "BKE_mesh.h"
-#include "BKE_multires.h"
-
-#include "BLI_editVert.h"
-
-#include "MEM_guardedalloc.h"
-
-#include "blendef.h"
-
-#include <string.h>
-
-MDeformVert *subdivide_dverts(MDeformVert *src, MultiresLevel *lvl);
-MTFace *subdivide_mtfaces(MTFace *src, MultiresLevel *lvl);
-void multires_update_edge_flags(Mesh *me, EditMesh *em);
-void eed_to_medge_flag(EditEdge *eed, short *flag, char *crease);
-
-/*********** Generic ***********/
-
-CustomDataMask cdmask(const int type)
-{
- if(type == CD_MDEFORMVERT)
- return CD_MASK_MDEFORMVERT;
- else if(type == CD_MTFACE)
- return CD_MASK_MTFACE;
- return -1;
-}
-
-char type_ok(const int type)
-{
- return (type == CD_MDEFORMVERT) || (type == CD_MTFACE);
-}
-
-/* Copy vdata or fdata from Mesh or EditMesh to Multires. */
-void multires_update_customdata(MultiresLevel *lvl1, EditMesh *em, CustomData *src, CustomData *dst, const int type)
-{
- if(src && dst && type_ok(type)) {
- const int tot= (type == CD_MDEFORMVERT ? lvl1->totvert : lvl1->totface);
- int i;
-
- CustomData_free(dst, tot);
-
- if(CustomData_has_layer(src, type)) {
- if(em) {
- EditVert *eve= G.editMesh->verts.first;
- EditFace *efa= G.editMesh->faces.first;
- CustomData_copy(src, dst, cdmask(type), CD_CALLOC, tot);
- for(i=0; i<tot; ++i) {
- if(type == CD_MDEFORMVERT) {
- CustomData_from_em_block(&G.editMesh->vdata, dst, eve->data, i);
- eve= eve->next;
- }
- else if(type == CD_MTFACE) {
- CustomData_from_em_block(&G.editMesh->fdata, dst, efa->data, i);
- efa= efa->next;
- }
- }
- }
- else
- CustomData_copy(src, dst, cdmask(type), CD_DUPLICATE, tot);
- }
- }
-}
-
-/* Uses subdivide_dverts or subdivide_mtfaces to subdivide src to match lvl_end. Does not free src. */
-void *subdivide_customdata_to_level(void *src, MultiresLevel *lvl_start,
- MultiresLevel *lvl_end, const int type)
-{
- if(src && lvl_start && lvl_end && type_ok(type)) {
- MultiresLevel *lvl;
- void *cr_data= NULL, *pr_data= NULL;
-
- pr_data= src;
- for(lvl= lvl_start; lvl && lvl != lvl_end; lvl= lvl->next) {
- if(type == CD_MDEFORMVERT)
- cr_data= subdivide_dverts(pr_data, lvl);
- else if(type == CD_MTFACE)
- cr_data= subdivide_mtfaces(pr_data, lvl);
-
- /* Free previous subdivision level's data */
- if(lvl != lvl_start) {
- if(type == CD_MDEFORMVERT)
- free_dverts(pr_data, lvl->totvert);
- else if(type == CD_MTFACE)
- MEM_freeN(pr_data);
- }
-
- pr_data= cr_data;
- cr_data= NULL;
- }
-
- return pr_data;
- }
-
- return NULL;
-}
-
-/* Directly copy src into dst (handles both Mesh and EditMesh) */
-void customdata_to_mesh(Mesh *me, EditMesh *em, CustomData *src, CustomData *dst, const int tot, const int type)
-{
- if(me && me->mr && src && dst && type_ok(type)) {
- if(em) {
- int i;
- EditVert *eve= em->verts.first;
- EditFace *efa= em->faces.first;
- CustomData_copy(src, dst, cdmask(type), CD_CALLOC, 0);
-
- for(i=0; i<tot; ++i) {
- if(type == CD_MDEFORMVERT) {
- CustomData_to_em_block(src, dst, i, &eve->data);
- eve= eve->next;
- }
- else if(type == CD_MTFACE) {
- CustomData_to_em_block(src, dst, i, &efa->data);
- efa= efa->next;
- }
- }
- } else {
- CustomData_merge(src, dst, cdmask(type), CD_DUPLICATE, tot);
- }
- }
-}
-
-/* Subdivide vdata or fdata from Multires into either Mesh or EditMesh. */
-void multires_customdata_to_mesh(Mesh *me, EditMesh *em, MultiresLevel *lvl, CustomData *src,
- CustomData *dst, const int type)
-{
- if(me && me->mr && lvl && src && dst && type_ok(type) &&
- CustomData_has_layer(src, type)) {
- const int tot= (type == CD_MDEFORMVERT ? lvl->totvert : lvl->totface);
- if(lvl == me->mr->levels.first) {
- customdata_to_mesh(me, em, src, dst, tot, type);
- }
- else {
- CustomData cdf;
- const int count = CustomData_number_of_layers(src, type);
- int i;
-
- /* Construct a new CustomData containing the subdivided data */
- CustomData_copy(src, &cdf, cdmask(type), CD_ASSIGN, tot);
- for(i=0; i<count; ++i) {
- void *layer= CustomData_get_layer_n(&cdf, type, i);
- CustomData_set_layer_n(&cdf, type, i,
- subdivide_customdata_to_level(layer, me->mr->levels.first, lvl, type));
- }
-
- customdata_to_mesh(me, em, &cdf, dst, tot, type);
- CustomData_free(&cdf, tot);
- }
- }
-}
-
-/* Subdivide the first-level customdata up to cr_lvl, then delete the original data */
-void multires_del_lower_customdata(Multires *mr, MultiresLevel *cr_lvl)
-{
- MultiresLevel *lvl1= mr->levels.first;
- MDeformVert *dverts= NULL;
- CustomData cdf;
- int i;
-
- /* dverts */
- dverts= subdivide_customdata_to_level(CustomData_get(&mr->vdata, 0, CD_MDEFORMVERT),
- lvl1, cr_lvl, CD_MDEFORMVERT);
- if(dverts) {
- CustomData_free_layers(&mr->vdata, CD_MDEFORMVERT, lvl1->totvert);
- CustomData_add_layer(&mr->vdata, CD_MDEFORMVERT, CD_ASSIGN, dverts, cr_lvl->totvert);
- }
-
- /* mtfaces */
- CustomData_copy(&mr->fdata, &cdf, CD_MASK_MTFACE, CD_ASSIGN, cr_lvl->totface);
- for(i=0; i<CustomData_number_of_layers(&mr->fdata, CD_MTFACE); ++i) {
- MTFace *mtfaces=
- subdivide_customdata_to_level(CustomData_get_layer_n(&mr->fdata, CD_MTFACE, i),
- lvl1, cr_lvl, CD_MTFACE);
- if(mtfaces)
- CustomData_set_layer_n(&cdf, CD_MTFACE, i, mtfaces);
- }
-
- CustomData_free(&mr->fdata, lvl1->totface);
- mr->fdata= cdf;
-}
-
-/* Update all special first-level data, if the first-level is active */
-void multires_update_first_level(Mesh *me, EditMesh *em)
-{
- if(me && me->mr && me->mr->current == 1) {
- multires_update_customdata(me->mr->levels.first, em, em ? &em->vdata : &me->vdata,
- &me->mr->vdata, CD_MDEFORMVERT);
- multires_update_customdata(me->mr->levels.first, em, em ? &em->fdata : &me->fdata,
- &me->mr->fdata, CD_MTFACE);
- multires_update_edge_flags(me, em);
- }
-}
-
-/*********** Multires.edge_flags ***********/
-void multires_update_edge_flags(Mesh *me, EditMesh *em)
-{
- MultiresLevel *lvl= me->mr->levels.first;
- EditEdge *eed= NULL;
- int i;
-
- if(em) eed= em->edges.first;
- for(i=0; i<lvl->totedge; ++i) {
- if(em) {
- me->mr->edge_flags[i]= 0;
- eed_to_medge_flag(eed, &me->mr->edge_flags[i], &me->mr->edge_creases[i]);
- eed= eed->next;
- }
- else {
- me->mr->edge_flags[i]= me->medge[i].flag;
- me->mr->edge_creases[i]= me->medge[i].crease;
- }
- }
-}
-
-
-
-/*********** Multires.vdata ***********/
-
-/* MDeformVert */
-
-/* Add each weight from in to out. Scale each weight by w. */
-void multires_add_dvert(MDeformVert *out, const MDeformVert *in, const float w)
-{
- if(out && in) {
- int i, j;
- char found;
-
- for(i=0; i<in->totweight; ++i) {
- found= 0;
- for(j=0; j<out->totweight; ++j) {
- if(out->dw[j].def_nr==in->dw[i].def_nr) {
- out->dw[j].weight += in->dw[i].weight * w;
- found= 1;
- }
- }
- if(!found) {
- MDeformWeight *newdw= MEM_callocN(sizeof(MDeformWeight)*(out->totweight+1),
- "multires dvert");
- if(out->dw) {
- memcpy(newdw, out->dw, sizeof(MDeformWeight)*out->totweight);
- MEM_freeN(out->dw);
- }
-
- out->dw= newdw;
- out->dw[out->totweight].weight= in->dw[i].weight * w;
- out->dw[out->totweight].def_nr= in->dw[i].def_nr;
-
- ++out->totweight;
- }
- }
- }
-}
-
-/* Takes an input array of dverts and subdivides them (linear) using the topology of lvl */
-MDeformVert *subdivide_dverts(MDeformVert *src, MultiresLevel *lvl)
-{
- if(lvl && lvl->next) {
- MDeformVert *out = MEM_callocN(sizeof(MDeformVert)*lvl->next->totvert, "dvert prop array");
- int i, j;
-
- /* Copy lower level */
- for(i=0; i<lvl->totvert; ++i)
- multires_add_dvert(&out[i], &src[i], 1);
- /* Edge verts */
- for(i=0; i<lvl->totedge; ++i) {
- for(j=0; j<2; ++j)
- multires_add_dvert(&out[lvl->totvert+i], &src[lvl->edges[i].v[j]],0.5);
- }
-
- /* Face verts */
- for(i=0; i<lvl->totface; ++i) {
- for(j=0; j<(lvl->faces[i].v[3]?4:3); ++j)
- multires_add_dvert(&out[lvl->totvert + lvl->totedge + i],
- &src[lvl->faces[i].v[j]],
- lvl->faces[i].v[3]?0.25:(1.0f/3.0f));
- }
-
- return out;
- }
-
- return NULL;
-}
-
-
-
-/*********** Multires.fdata ***********/
-
-/* MTFace */
-
-void multires_uv_avg2(float out[2], const float a[2], const float b[2])
-{
- int i;
- for(i=0; i<2; ++i)
- out[i] = (a[i] + b[i]) / 2.0f;
-}
-
-/* Takes an input array of mtfaces and subdivides them (linear) using the topology of lvl */
-MTFace *subdivide_mtfaces(MTFace *src, MultiresLevel *lvl)
-{
- if(lvl && lvl->next) {
- MTFace *out= MEM_callocN(sizeof(MultiresColFace)*lvl->next->totface,"Multirescolfaces");
- int i, j, curf;
-
- for(i=0, curf=0; i<lvl->totface; ++i) {
- const char sides= lvl->faces[i].v[3]?4:3;
- float cntr[2]= {0, 0};
-
- /* Find average uv coord of the current face */
- for(j=0; j<sides; ++j) {
- cntr[0]+= src[i].uv[j][0];
- cntr[1]+= src[i].uv[j][1];
- }
- cntr[0]/= sides;
- cntr[1]/= sides;
-
- for(j=0; j<sides; ++j, ++curf) {
- out[curf]= src[i];
-
- multires_uv_avg2(out[curf].uv[0], src[i].uv[j], src[i].uv[j==0?sides-1:j-1]);
-
- out[curf].uv[1][0]= src[i].uv[j][0];
- out[curf].uv[1][1]= src[i].uv[j][1];
-
- multires_uv_avg2(out[curf].uv[2], src[i].uv[j], src[i].uv[j==sides-1?0:j+1]);
-
- out[curf].uv[3][0]= cntr[0];
- out[curf].uv[3][1]= cntr[1];
- }
- }
-
- return out;
- }
-
- return NULL;
-}
-
-void multires_delete_layer(Mesh *me, CustomData *cd, const int type, int n)
-{
- if(me && me->mr && cd) {
- MultiresLevel *lvl1= me->mr->levels.first;
-
- multires_update_levels(me, 0);
-
- CustomData_set_layer_active(cd, type, n);
- CustomData_free_layer_active(cd, type, lvl1->totface);
-
- multires_level_to_mesh(OBACT, me, 0);
- }
-}
-
-void multires_add_layer(Mesh *me, CustomData *cd, const int type, const int n)
-{
- if(me && me->mr && cd) {
- multires_update_levels(me, 0);
-
- if(CustomData_has_layer(cd, type))
- CustomData_add_layer(cd, type, CD_DUPLICATE, CustomData_get_layer(cd, type),
- current_level(me->mr)->totface);
- else
- CustomData_add_layer(cd, type, CD_DEFAULT, NULL, current_level(me->mr)->totface);
-
- CustomData_set_layer_active(cd, type, n);
- multires_level_to_mesh(OBACT, me, 0);
- }
-}
diff --git a/source/blender/blenkernel/intern/multires.c b/source/blender/blenkernel/intern/multires.c
index 4d312632b1a..43cb796f4b4 100644
--- a/source/blender/blenkernel/intern/multires.c
+++ b/source/blender/blenkernel/intern/multires.c
@@ -32,1278 +32,1566 @@
#include "DNA_key_types.h"
#include "DNA_mesh_types.h"
#include "DNA_meshdata_types.h"
+#include "DNA_modifier_types.h"
#include "DNA_object_types.h"
-#include "DNA_vec_types.h"
-
-#include "BIF_editmesh.h"
+#include "DNA_scene_types.h"
+#include "DNA_view3d_types.h"
#include "BLI_arithb.h"
#include "BLI_blenlib.h"
-#include "BLI_editVert.h"
+#include "BKE_cdderivedmesh.h"
#include "BKE_customdata.h"
#include "BKE_depsgraph.h"
+#include "BKE_DerivedMesh.h"
#include "BKE_global.h"
+#include "BKE_mesh.h"
+#include "BKE_modifier.h"
#include "BKE_multires.h"
+#include "BKE_object.h"
+#include "BKE_subsurf.h"
#include "blendef.h"
-#include "editmesh.h"
#include <math.h>
+#include <string.h>
-/* Returns the active multires level (currently applied to the mesh) */
-MultiresLevel *current_level(Multires *mr)
+void create_vert_face_map(ListBase **map, IndexNode **mem, const MFace *mface, const int totvert, const int totface)
{
- return BLI_findlink(&mr->levels, mr->current - 1);
+ int i,j;
+ IndexNode *node = NULL;
+
+ (*map) = MEM_callocN(sizeof(ListBase) * totvert, "vert face map");
+ (*mem) = MEM_callocN(sizeof(IndexNode) * totface*4, "vert face map mem");
+ node = *mem;
+
+ /* Find the users */
+ for(i = 0; i < totface; ++i){
+ for(j = 0; j < (mface[i].v4?4:3); ++j, ++node) {
+ node->index = i;
+ BLI_addtail(&(*map)[((unsigned int*)(&mface[i]))[j]], node);
+ }
+ }
}
-/* Returns the nth multires level, starting at 1 */
-MultiresLevel *multires_level_n(Multires *mr, int n)
+void create_vert_edge_map(ListBase **map, IndexNode **mem, const MEdge *medge, const int totvert, const int totedge)
{
- if(mr)
- return BLI_findlink(&mr->levels, n - 1);
- else
- return NULL;
+ int i, j;
+ IndexNode *node = NULL;
+
+ (*map) = MEM_callocN(sizeof(ListBase) * totvert, "vert edge map");
+ (*mem) = MEM_callocN(sizeof(IndexNode) * totedge * 2, "vert edge map mem");
+ node = *mem;
+
+ /* Find the users */
+ for(i = 0; i < totedge; ++i){
+ for(j = 0; j < 2; ++j, ++node) {
+ node->index = i;
+ BLI_addtail(&(*map)[((unsigned int*)(&medge[i].v1))[j]], node);
+ }
+ }
}
-/* Free and clear the temporary connectivity data */
-static void multires_free_temp_data(MultiresLevel *lvl)
+/* MULTIRES MODIFIER */
+static const int multires_max_levels = 13;
+static const int multires_quad_tot[] = {4, 9, 25, 81, 289, 1089, 4225, 16641, 66049, 263169, 1050625, 4198401, 16785409};
+static const int multires_side_tot[] = {2, 3, 5, 9, 17, 33, 65, 129, 257, 513, 1025, 2049, 4097};
+
+int multiresModifier_switch_level(Object *ob, const int distance)
{
- if(lvl) {
- if(lvl->edge_boundary_states) MEM_freeN(lvl->edge_boundary_states);
- if(lvl->vert_edge_map) MEM_freeN(lvl->vert_edge_map);
- if(lvl->vert_face_map) MEM_freeN(lvl->vert_face_map);
- if(lvl->map_mem) MEM_freeN(lvl->map_mem);
-
- lvl->edge_boundary_states = NULL;
- lvl->vert_edge_map = lvl->vert_face_map = NULL;
- lvl->map_mem = NULL;
+ ModifierData *md = NULL;
+ MultiresModifierData *mmd = NULL;
+
+ for(md = ob->modifiers.first; md; md = md->next) {
+ if(md->type == eModifierType_Multires)
+ mmd = (MultiresModifierData*)md;
}
-}
-/* Does not actually free lvl itself */
-void multires_free_level(MultiresLevel *lvl)
-{
- if(lvl) {
- if(lvl->faces) MEM_freeN(lvl->faces);
- if(lvl->edges) MEM_freeN(lvl->edges);
- if(lvl->colfaces) MEM_freeN(lvl->colfaces);
-
- multires_free_temp_data(lvl);
+ if(mmd) {
+ mmd->lvl += distance;
+ if(mmd->lvl < 1) mmd->lvl = 1;
+ else if(mmd->lvl > mmd->totlvl) mmd->lvl = mmd->totlvl;
+ DAG_object_flush_update(G.scene, ob, OB_RECALC_DATA);
+ object_handle_update(ob);
+ return 1;
}
+ else
+ return 0;
}
-void multires_free(Multires *mr)
+void multiresModifier_join(Object *ob)
{
- if(mr) {
- MultiresLevel* lvl= mr->levels.first;
-
- /* Free the first-level data */
- if(lvl) {
- CustomData_free(&mr->vdata, lvl->totvert);
- CustomData_free(&mr->fdata, lvl->totface);
- MEM_freeN(mr->edge_flags);
- MEM_freeN(mr->edge_creases);
+ Base *base = NULL;
+ int highest_lvl = 0;
+
+ /* First find the highest level of subdivision */
+ base = FIRSTBASE;
+ while(base) {
+ if(TESTBASELIB_BGMODE(base) && base->object->type==OB_MESH) {
+ ModifierData *md;
+ for(md = base->object->modifiers.first; md; md = md->next) {
+ if(md->type == eModifierType_Multires) {
+ int totlvl = ((MultiresModifierData*)md)->totlvl;
+ if(totlvl > highest_lvl)
+ highest_lvl = totlvl;
+
+ /* Ensure that all updates are processed */
+ multires_force_update(base->object);
+ }
+ }
}
+ base = base->next;
+ }
- while(lvl) {
- multires_free_level(lvl);
- lvl= lvl->next;
- }
+ /* No multires meshes selected */
+ if(highest_lvl == 0)
+ return;
- MEM_freeN(mr->verts);
+ /* Subdivide all the displacements to the highest level */
+ base = FIRSTBASE;
+ while(base) {
+ if(TESTBASELIB_BGMODE(base) && base->object->type==OB_MESH) {
+ ModifierData *md = NULL;
+ MultiresModifierData *mmd = NULL;
- BLI_freelistN(&mr->levels);
+ for(md = base->object->modifiers.first; md; md = md->next) {
+ if(md->type == eModifierType_Multires)
+ mmd = (MultiresModifierData*)md;
+ }
- MEM_freeN(mr);
- }
-}
+ /* If the object didn't have multires enabled, give it a new modifier */
+ if(!mmd) {
+ md = base->object->modifiers.first;
+
+ while(md && modifierType_getInfo(md->type)->type == eModifierTypeType_OnlyDeform)
+ md = md->next;
+
+ mmd = (MultiresModifierData*)modifier_new(eModifierType_Multires);
+ BLI_insertlinkbefore(&base->object->modifiers, md, mmd);
+ }
-static MultiresLevel *multires_level_copy(MultiresLevel *orig)
-{
- if(orig) {
- MultiresLevel *lvl= MEM_dupallocN(orig);
-
- lvl->next= lvl->prev= NULL;
- lvl->faces= MEM_dupallocN(orig->faces);
- lvl->colfaces= MEM_dupallocN(orig->colfaces);
- lvl->edges= MEM_dupallocN(orig->edges);
- lvl->edge_boundary_states = NULL;
- lvl->vert_edge_map= lvl->vert_face_map= NULL;
- lvl->map_mem= NULL;
-
- return lvl;
+ if(mmd)
+ multiresModifier_subdivide(mmd, base->object, highest_lvl - mmd->totlvl, 0, 0);
+ }
+ base = base->next;
}
- return NULL;
}
-Multires *multires_copy(Multires *orig)
+/* Returns 0 on success, 1 if the src's totvert doesn't match */
+int multiresModifier_reshape(MultiresModifierData *mmd, Object *dst, Object *src)
{
- const CustomDataMask vdata_mask= CD_MASK_MDEFORMVERT;
+ Mesh *src_me = get_mesh(src);
+ DerivedMesh *mrdm = dst->derivedFinal;
- if(orig) {
- Multires *mr= MEM_dupallocN(orig);
- MultiresLevel *lvl;
-
- mr->levels.first= mr->levels.last= NULL;
-
- for(lvl= orig->levels.first; lvl; lvl= lvl->next)
- BLI_addtail(&mr->levels, multires_level_copy(lvl));
+ if(mrdm && mrdm->getNumVerts(mrdm) == src_me->totvert) {
+ MVert *mvert = CDDM_get_verts(mrdm);
+ int i;
- mr->verts= MEM_dupallocN(orig->verts);
-
- lvl= mr->levels.first;
- if(lvl) {
- CustomData_copy(&orig->vdata, &mr->vdata, vdata_mask, CD_DUPLICATE, lvl->totvert);
- CustomData_copy(&orig->fdata, &mr->fdata, CD_MASK_MTFACE, CD_DUPLICATE, lvl->totface);
- mr->edge_flags= MEM_dupallocN(orig->edge_flags);
- mr->edge_creases= MEM_dupallocN(orig->edge_creases);
- }
-
- return mr;
- }
- return NULL;
-}
+ for(i = 0; i < src_me->totvert; ++i)
+ VecCopyf(mvert[i].co, src_me->mvert[i].co);
+ mrdm->needsFree = 1;
+ *MultiresDM_get_flags(mrdm) |= MULTIRES_DM_UPDATE_ALWAYS;
+ mrdm->release(mrdm);
+ dst->derivedFinal = NULL;
-static void multires_get_vert(MVert *out, EditVert *eve, MVert *m, int i)
-{
- if(eve) {
- VecCopyf(out->co, eve->co);
- out->flag= 0;
- if(eve->f & SELECT) out->flag |= 1;
- if(eve->h) out->flag |= ME_HIDE;
- eve->tmp.l= i;
+ return 0;
}
- else
- *out= *m;
-}
-void eed_to_medge_flag(EditEdge *eed, short *flag, char *crease)
-{
- if(!eed || !flag) return;
-
- /* Would be nice if EditMesh edge flags could be unified with Mesh flags! */
- *flag= (eed->f & SELECT) | ME_EDGERENDER;
- if(eed->f2<2) *flag |= ME_EDGEDRAW;
- if(eed->f2==0) *flag |= ME_LOOSEEDGE;
- if(eed->sharp) *flag |= ME_SHARP;
- if(eed->seam) *flag |= ME_SEAM;
- if(eed->h & EM_FGON) *flag |= ME_FGON;
- if(eed->h & 1) *flag |= ME_HIDE;
-
- *crease= (char)(255.0*eed->crease);
+ return 1;
}
-static void multires_get_edge(MultiresEdge *e, EditEdge *eed, MEdge *m, short *flag, char *crease)
+static void Mat3FromColVecs(float mat[][3], float v1[3], float v2[3], float v3[3])
{
- if(eed) {
- e->v[0]= eed->v1->tmp.l;
- e->v[1]= eed->v2->tmp.l;
- eed_to_medge_flag(eed, flag, crease);
- } else {
- e->v[0]= m->v1;
- e->v[1]= m->v2;
- *flag= m->flag;
- *crease= m->crease;
- }
+ VecCopyf(mat[0], v1);
+ VecCopyf(mat[1], v2);
+ VecCopyf(mat[2], v3);
}
-static void multires_get_face(MultiresFace *f, CustomData *fdata, int findex, EditFace *efa, MFace *m)
+static DerivedMesh *multires_subdisp_pre(DerivedMesh *mrdm, int distance, int simple)
{
- if(efa) {
- MFace tmp;
- int j;
- tmp.v1= efa->v1->tmp.l;
- tmp.v2= efa->v2->tmp.l;
- tmp.v3= efa->v3->tmp.l;
- tmp.v4= 0;
- if(efa->v4) tmp.v4= efa->v4->tmp.l;
- test_index_face(&tmp, fdata, findex, efa->v4?4:3);
- for(j=0; j<4; ++j) f->v[j]= (&tmp.v1)[j];
-
- /* Flags */
- f->flag= efa->flag;
- if(efa->f & 1) f->flag |= ME_FACE_SEL;
- else f->flag &= ~ME_FACE_SEL;
- if(efa->h) f->flag |= ME_HIDE;
- f->mat_nr= efa->mat_nr;
- } else {
- f->v[0]= m->v1;
- f->v[1]= m->v2;
- f->v[2]= m->v3;
- f->v[3]= m->v4;
- f->flag= m->flag;
- f->mat_nr= m->mat_nr;
- }
+ DerivedMesh *final;
+ SubsurfModifierData smd;
+
+ memset(&smd, 0, sizeof(SubsurfModifierData));
+ smd.levels = distance;
+ if(simple)
+ smd.subdivType = ME_SIMPLE_SUBSURF;
+
+ final = subsurf_make_derived_from_derived_with_multires(mrdm, &smd, NULL, 0, NULL, 0, 0);
+
+ return final;
}
-/* For manipulating vertex colors / uvs */
-static void mcol_to_multires(MultiresColFace *mrf, MCol *mcol)
+static void VecAddUf(float a[3], float b[3])
{
- char i;
- for(i=0; i<4; ++i) {
- mrf->col[i].a= mcol[i].a;
- mrf->col[i].r= mcol[i].r;
- mrf->col[i].g= mcol[i].g;
- mrf->col[i].b= mcol[i].b;
- }
+ a[0] += b[0];
+ a[1] += b[1];
+ a[2] += b[2];
}
-/* 1 <= count <= 4 */
-static void multires_col_avg(MultiresCol *avg, MultiresCol cols[4], char count)
+static void multires_subdisp(DerivedMesh *orig, Mesh *me, DerivedMesh *final, int lvl, int totlvl,
+ int totsubvert, int totsubedge, int totsubface, int addverts)
{
- unsigned i;
- avg->a= avg->r= avg->g= avg->b= 0;
- for(i=0; i<count; ++i) {
- avg->a+= cols[i].a;
- avg->r+= cols[i].r;
- avg->g+= cols[i].g;
- avg->b+= cols[i].b;
+ DerivedMesh *mrdm;
+ MultiresModifierData mmd_sub;
+ MVert *mvs = CDDM_get_verts(final);
+ MVert *mvd, *mvd_f1, *mvs_f1, *mvd_f3, *mvd_f4;
+ MVert *mvd_f2, *mvs_f2, *mvs_e1, *mvd_e1, *mvs_e2;
+ int totvert;
+ int slo1 = multires_side_tot[lvl - 1];
+ int sll = slo1 / 2;
+ int slo2 = multires_side_tot[totlvl - 2];
+ int shi2 = multires_side_tot[totlvl - 1];
+ int skip = multires_side_tot[totlvl - lvl] - 1;
+ int i, j, k;
+
+ mmd_sub.lvl = mmd_sub.totlvl = totlvl;
+ mrdm = multires_dm_create_from_derived(&mmd_sub, orig, me, 0, 0);
+
+ mvd = CDDM_get_verts(mrdm);
+ /* Need to map from ccg to mrdm */
+ totvert = mrdm->getNumVerts(mrdm);
+
+ if(!addverts) {
+ for(i = 0; i < totvert; ++i) {
+ float z[3] = {0,0,0};
+ VecCopyf(mvd[i].co, z);
+ }
}
- avg->a/= count;
- avg->r/= count;
- avg->g/= count;
- avg->b/= count;
-}
-static void multires_col_avg2(MultiresCol *avg, MultiresCol *c1, MultiresCol *c2)
-{
- MultiresCol in[2];
- in[0]= *c1;
- in[1]= *c2;
- multires_col_avg(avg,in,2);
-}
+ /* Load base verts */
+ for(i = 0; i < me->totvert; ++i)
+ VecAddUf(mvd[totvert - me->totvert + i].co, mvs[totvert - me->totvert + i].co);
+
+ mvd_f1 = mvd;
+ mvs_f1 = mvs;
+ mvd_f2 = mvd;
+ mvs_f2 = mvs + totvert - totsubvert;
+ mvs_e1 = mvs + totsubface * (skip-1) * (skip-1);
+
+ for(i = 0; i < me->totface; ++i) {
+ const int end = me->mface[i].v4 ? 4 : 3;
+ int x, y, x2, y2, mov;
+
+ mvd_f1 += 1 + end * (slo2-2); //center+edgecross
+ mvd_f3 = mvd_f4 = mvd_f1;
+
+ for(j = 0; j < end; ++j) {
+ mvd_f1 += (skip/2 - 1) * (slo2 - 2) + (skip/2 - 1);
+ /* Update sub faces */
+ for(y = 0; y < sll; ++y) {
+ for(x = 0; x < sll; ++x) {
+ /* Face center */
+ VecAddUf(mvd_f1->co, mvs_f1->co);
+ mvs_f1 += 1;
+
+ /* Now we hold the center of the subface at mvd_f1
+ and offset it to the edge cross and face verts */
+
+ /* Edge cross */
+ for(k = 0; k < 4; ++k) {
+ if(k == 0) mov = -1;
+ else if(k == 1) mov = slo2 - 2;
+ else if(k == 2) mov = 1;
+ else if(k == 3) mov = -(slo2 - 2);
+
+ for(x2 = 1; x2 < skip/2; ++x2) {
+ VecAddUf((mvd_f1 + mov * x2)->co, mvs_f1->co);
+ ++mvs_f1;
+ }
+ }
-void multires_load_cols(Mesh *me)
-{
- MultiresLevel *lvl= BLI_findlink(&me->mr->levels,me->mr->current-1), *cur;
- EditMesh *em= G.obedit ? G.editMesh : NULL;
- CustomData *src= em ? &em->fdata : &me->fdata;
- EditFace *efa= NULL;
- unsigned i,j;
+ /* Main face verts */
+ for(k = 0; k < 4; ++k) {
+ int movx, movy;
+
+ if(k == 0) { movx = -1; movy = -(slo2 - 2); }
+ else if(k == 1) { movx = slo2 - 2; movy = -1; }
+ else if(k == 2) { movx = 1; movy = slo2 - 2; }
+ else if(k == 3) { movx = -(slo2 - 2); movy = 1; }
+
+ for(y2 = 1; y2 < skip/2; ++y2) {
+ for(x2 = 1; x2 < skip/2; ++x2) {
+ VecAddUf((mvd_f1 + movy * y2 + movx * x2)->co, mvs_f1->co);
+ ++mvs_f1;
+ }
+ }
+ }
+
+ mvd_f1 += skip;
+ }
+ mvd_f1 += (skip - 1) * (slo2 - 2) - 1;
+ }
+ mvd_f1 -= (skip - 1) * (slo2 - 2) - 1 + skip;
+ mvd_f1 += (slo2 - 2) * (skip/2-1) + skip/2-1 + 1;
+ }
- if(!CustomData_has_layer(src, CD_MCOL) && !CustomData_has_layer(src, CD_MTFACE)) return;
+ /* update face center verts */
+ VecAddUf(mvd_f2->co, mvs_f2->co);
- /* Add texcol data */
- for(cur= me->mr->levels.first; cur; cur= cur->next)
- if(!cur->colfaces)
- cur->colfaces= MEM_callocN(sizeof(MultiresColFace)*cur->totface,"ColFaces");
+ mvd_f2 += 1;
+ mvs_f2 += 1;
- me->mr->use_col= CustomData_has_layer(src, CD_MCOL);
+ /* update face edge verts */
+ for(j = 0; j < end; ++j) {
+ MVert *restore;
- if(em) efa= em->faces.first;
- for(i=0; i<lvl->totface; ++i) {
- MultiresColFace *f= &lvl->colfaces[i];
+ /* Super-face edge cross */
+ for(k = 0; k < skip-1; ++k) {
+ VecAddUf(mvd_f2->co, mvs_e1->co);
+ mvd_f2++;
+ mvs_e1++;
+ }
+ for(x = 1; x < sll; ++x) {
+ VecAddUf(mvd_f2->co, mvs_f2->co);
+ mvd_f2++;
+ mvs_f2++;
+
+ for(k = 0; k < skip-1; ++k) {
+ VecAddUf(mvd_f2->co, mvs_e1->co);
+ mvd_f2++;
+ mvs_e1++;
+ }
+ }
- if(me->mr->use_col)
- mcol_to_multires(f, em ? CustomData_em_get(src, efa->data, CD_MCOL) : &me->mcol[i*4]);
-
- if(em) efa= efa->next;
+ restore = mvs_e1;
+ for(y = 0; y < sll - 1; ++y) {
+ for(x = 0; x < sll; ++x) {
+ for(k = 0; k < skip - 1; ++k) {
+ VecAddUf(mvd_f3[(skip-1)+(y*skip) + (x*skip+k)*(slo2-2)].co,
+ mvs_e1->co);
+ ++mvs_e1;
+ }
+ mvs_e1 += skip-1;
+ }
+ }
+
+ mvs_e1 = restore + skip - 1;
+ for(y = 0; y < sll - 1; ++y) {
+ for(x = 0; x < sll; ++x) {
+ for(k = 0; k < skip - 1; ++k) {
+ VecAddUf(mvd_f3[(slo2-2)*(skip-1)+(x*skip)+k + y*skip*(slo2-2)].co,
+ mvs_e1->co);
+ ++mvs_e1;
+ }
+ mvs_e1 += skip - 1;
+ }
+ }
+
+ mvd_f3 += (slo2-2)*(slo2-2);
+ mvs_e1 -= skip - 1;
+ }
+
+ /* update base (2) face verts */
+ for(j = 0; j < end; ++j) {
+ mvd_f2 += (slo2 - 1) * (skip - 1);
+ for(y = 0; y < sll - 1; ++y) {
+ for(x = 0; x < sll - 1; ++x) {
+ VecAddUf(mvd_f2->co, mvs_f2->co);
+ mvd_f2 += skip;
+ ++mvs_f2;
+ }
+ mvd_f2 += (slo2 - 1) * (skip - 1);
+ }
+ mvd_f2 -= (skip - 1);
+ }
}
- /* Update higher levels */
- lvl= lvl->next;
- while(lvl) {
- MultiresColFace *cf= lvl->colfaces;
- for(i=0; i<lvl->prev->totface; ++i) {
- const char sides= lvl->prev->faces[i].v[3]?4:3;
- MultiresCol cntr;
-
- /* Find average color of 4 (or 3 for triangle) verts */
- multires_col_avg(&cntr,lvl->prev->colfaces[i].col,sides);
+ /* edges */
+ mvd_e1 = mvd + totvert - me->totvert - me->totedge * (shi2-2);
+ mvs_e2 = mvs + totvert - me->totvert - me->totedge * (slo1-2);
+ for(i = 0; i < me->totedge; ++i) {
+ for(j = 0; j < skip - 1; ++j) {
+ VecAddUf(mvd_e1->co, mvs_e1->co);
+ mvd_e1++;
+ mvs_e1++;
+ }
+ for(j = 0; j < slo1 - 2; j++) {
+ VecAddUf(mvd_e1->co, mvs_e2->co);
+ mvd_e1++;
+ mvs_e2++;
- for(j=0; j<sides; ++j) {
- MultiresColFace *pf= &lvl->prev->colfaces[i];
-
- multires_col_avg2(&cf->col[0],
- &pf->col[j],
- &pf->col[j==0?sides-1:j-1]);
- cf->col[1]= pf->col[j];
- multires_col_avg2(&cf->col[2],
- &pf->col[j],
- &pf->col[j==sides-1?0:j+1]);
- cf->col[3]= cntr;
-
- ++cf;
+ for(k = 0; k < skip - 1; ++k) {
+ VecAddUf(mvd_e1->co, mvs_e1->co);
+ mvd_e1++;
+ mvs_e1++;
}
}
- lvl= lvl->next;
}
- /* Update lower levels */
- lvl= me->mr->levels.last;
- lvl= lvl->prev;
- while(lvl) {
- unsigned curf= 0;
- for(i=0; i<lvl->totface; ++i) {
- MultiresFace *f= &lvl->faces[i];
- for(j=0; j<(f->v[3]?4:3); ++j) {
- lvl->colfaces[i].col[j]= lvl->next->colfaces[curf].col[1];
- ++curf;
+ final->needsFree = 1;
+ final->release(final);
+ mrdm->needsFree = 1;
+ *MultiresDM_get_flags(mrdm) |= MULTIRES_DM_UPDATE_ALWAYS;
+ mrdm->release(mrdm);
+}
+
+/* direction=1 for delete higher, direction=0 for lower (not implemented yet) */
+void multiresModifier_del_levels(struct MultiresModifierData *mmd, struct Object *ob, int direction)
+{
+ Mesh *me = get_mesh(ob);
+ int distance = mmd->totlvl - mmd->lvl;
+ MDisps *mdisps = CustomData_get_layer(&me->fdata, CD_MDISPS);
+
+ multires_force_update(ob);
+
+ if(mdisps && distance > 0 && direction == 1) {
+ int skip = multires_side_tot[distance] - 1;
+ int st = multires_side_tot[mmd->totlvl - 1];
+ int totdisp = multires_quad_tot[mmd->lvl - 1];
+ int i, j, x, y;
+
+ for(i = 0; i < me->totface; ++i) {
+ float (*disps)[3] = MEM_callocN(sizeof(float) * 3 * totdisp, "multires del disps");
+
+ for(j = 0, y = 0; y < st; y += skip) {
+ for(x = 0; x < st; x += skip) {
+ VecCopyf(disps[j], mdisps[i].disps[y * st + x]);
+ ++j;
+ }
}
+
+ MEM_freeN(mdisps[i].disps);
+ mdisps[i].disps = disps;
+ mdisps[i].totdisp = totdisp;
}
- lvl= lvl->prev;
}
+
+ mmd->totlvl = mmd->lvl;
}
-void multires_create(Object *ob, Mesh *me)
+void multiresModifier_subdivide(MultiresModifierData *mmd, Object *ob, int distance, int updateblock, int simple)
{
- MultiresLevel *lvl;
- EditMesh *em= G.obedit ? G.editMesh : NULL;
- EditVert *eve= NULL;
- EditFace *efa= NULL;
- EditEdge *eed= NULL;
+ DerivedMesh *final = NULL;
+ int totsubvert, totsubface, totsubedge;
+ Mesh *me = get_mesh(ob);
+ MDisps *mdisps;
int i;
-
- lvl= MEM_callocN(sizeof(MultiresLevel), "multires level");
- if(me->pv) mesh_pmv_off(ob, me);
+ if(distance == 0)
+ return;
- me->mr= MEM_callocN(sizeof(Multires), "multires data");
-
- BLI_addtail(&me->mr->levels,lvl);
- me->mr->current= 1;
- me->mr->level_count= 1;
- me->mr->edgelvl= 1;
- me->mr->pinlvl= 1;
- me->mr->renderlvl= 1;
-
- /* Load mesh (or editmesh) into multires data */
-
- /* Load vertices and vdata (MDeformVerts) */
- lvl->totvert= em ? BLI_countlist(&em->verts) : me->totvert;
- me->mr->verts= MEM_callocN(sizeof(MVert)*lvl->totvert,"multires verts");
- multires_update_customdata(me->mr->levels.first, em, em ? &em->vdata : &me->vdata,
- &me->mr->vdata, CD_MDEFORMVERT);
- if(em) eve= em->verts.first;
- for(i=0; i<lvl->totvert; ++i) {
- multires_get_vert(&me->mr->verts[i], eve, &me->mvert[i], i);
- if(em) eve= eve->next;
+ if(mmd->totlvl > multires_max_levels)
+ mmd->totlvl = multires_max_levels;
+ if(mmd->lvl > multires_max_levels)
+ mmd->lvl = multires_max_levels;
+
+ multires_force_update(ob);
+
+ mmd->lvl = mmd->totlvl;
+ mmd->totlvl += distance;
+
+ mdisps = CustomData_get_layer(&me->fdata, CD_MDISPS);
+ if(!mdisps)
+ mdisps = CustomData_add_layer(&me->fdata, CD_MDISPS, CD_DEFAULT, NULL, me->totface);
+
+ if(mdisps->disps && !updateblock && mmd->totlvl > 2) {
+ DerivedMesh *orig, *mrdm;
+ MultiresModifierData mmd_sub;
+
+ orig = CDDM_from_mesh(me, NULL);
+ mmd_sub.lvl = mmd_sub.totlvl = mmd->lvl;
+ mrdm = multires_dm_create_from_derived(&mmd_sub, orig, me, 0, 0);
+ totsubvert = mrdm->getNumVerts(mrdm);
+ totsubedge = mrdm->getNumEdges(mrdm);
+ totsubface = mrdm->getNumFaces(mrdm);
+ orig->needsFree = 1;
+ orig->release(orig);
+
+ final = multires_subdisp_pre(mrdm, distance, simple);
+ mrdm->needsFree = 1;
+ *MultiresDM_get_flags(mrdm) |= MULTIRES_DM_UPDATE_BLOCK;
+ mrdm->release(mrdm);
}
- /* Load faces and fdata (MTFaces) */
- lvl->totface= em ? BLI_countlist(&em->faces) : me->totface;
- lvl->faces= MEM_callocN(sizeof(MultiresFace)*lvl->totface,"multires faces");
- multires_update_customdata(me->mr->levels.first, em, em ? &em->fdata : &me->fdata,
- &me->mr->fdata, CD_MTFACE);
- if(em) efa= em->faces.first;
- for(i=0; i<lvl->totface; ++i) {
- multires_get_face(&lvl->faces[i], &me->mr->fdata, i, efa, &me->mface[i]);
- if(em) efa= efa->next;
+ for(i = 0; i < me->totface; ++i) {
+ const int totdisp = multires_quad_tot[mmd->totlvl - 1];
+ float (*disps)[3] = MEM_callocN(sizeof(float) * 3 * totdisp, "multires disps");
+
+ if(mdisps[i].disps)
+ MEM_freeN(mdisps[i].disps);
+
+ mdisps[i].disps = disps;
+ mdisps[i].totdisp = totdisp;
}
- /* Load edges and edge_flags */
- lvl->totedge= em ? BLI_countlist(&em->edges) : me->totedge;
- lvl->edges= MEM_callocN(sizeof(MultiresEdge)*lvl->totedge,"multires edges");
- me->mr->edge_flags= MEM_callocN(sizeof(short)*lvl->totedge, "multires edge flags");
- me->mr->edge_creases= MEM_callocN(sizeof(short)*lvl->totedge, "multires edge creases");
- if(em) eed= em->edges.first;
- for(i=0; i<lvl->totedge; ++i) {
- multires_get_edge(&lvl->edges[i], eed, &me->medge[i], &me->mr->edge_flags[i], &me->mr->edge_creases[i]);
- if(em) eed= eed->next;
+
+ if(final) {
+ DerivedMesh *orig;
+
+ orig = CDDM_from_mesh(me, NULL);
+
+ multires_subdisp(orig, me, final, mmd->lvl, mmd->totlvl, totsubvert, totsubedge, totsubface, 0);
+
+ orig->needsFree = 1;
+ orig->release(orig);
}
- multires_load_cols(me);
+ mmd->lvl = mmd->totlvl;
}
-typedef struct MultiresMapNode {
- struct MultiresMapNode *next, *prev;
- unsigned Index;
-} MultiresMapNode;
+typedef struct DisplacerEdges {
+ /* DerivedMesh index at the start of each edge (using face x/y directions to define the start) */
+ int base[4];
+ /* 1 if edge moves in the positive x or y direction, -1 otherwise */
+ int dir[4];
+} DisplacerEdges;
+
+typedef struct DisplacerSpill {
+ /* Index of face (in base mesh), -1 for none */
+ int face;
+
+ /* Spill flag */
+ /* 1 = Negative variable axis */
+ /* 2 = Near fixed axis */
+ /* 4 = Flip axes */
+ int f;
+
+ /* Neighboring edges */
+ DisplacerEdges edges;
+} DisplacerSpill;
+
+typedef struct MultiresDisplacer {
+ Mesh *me;
+ MDisps *grid;
+ MFace *face;
+
+ int dm_first_base_vert_index;
+
+ int spacing;
+ int sidetot, interior_st, disp_st;
+ int sidendx;
+ int type;
+ int invert;
+ MVert *subco;
+ int subco_index, face_index;
+ float weight;
+
+ /* Valence for each corner */
+ int valence[4];
-/* Produces temporary connectivity data for the multires lvl */
-static void multires_calc_temp_data(MultiresLevel *lvl)
+ /* Neighboring edges for current face */
+ DisplacerEdges edges_primary;
+
+ /* Neighboring faces */
+ DisplacerSpill spill_x, spill_y;
+
+ int *face_offsets;
+
+ int x, y, ax, ay;
+} MultiresDisplacer;
+
+static int mface_v(MFace *f, int v)
{
- unsigned i, j, emax;
- MultiresMapNode *indexnode= NULL;
+ return v == 0 ? f->v1 : v == 1 ? f->v2 : v == 2 ? f->v3 : v == 3 ? f->v4 : -1;
+}
- lvl->map_mem= MEM_mallocN(sizeof(MultiresMapNode)*(lvl->totedge*2 + lvl->totface*4), "map_mem");
- indexnode= lvl->map_mem;
-
- /* edge map */
- lvl->vert_edge_map= MEM_callocN(sizeof(ListBase)*lvl->totvert,"vert_edge_map");
- for(i=0; i<lvl->totedge; ++i) {
- for(j=0; j<2; ++j, ++indexnode) {
- indexnode->Index= i;
- BLI_addtail(&lvl->vert_edge_map[lvl->edges[i].v[j]], indexnode);
- }
- }
+/* Get the edges (and their directions) */
+static void find_displacer_edges(MultiresDisplacer *d, DerivedMesh *dm, DisplacerEdges *de, MFace *f)
+{
+ ListBase *emap = MultiresDM_get_vert_edge_map(dm);
+ IndexNode *n;
+ int i, end = f->v4 ? 4 : 3;
+ int offset = dm->getNumVerts(dm) - d->me->totvert - d->me->totedge * d->interior_st;
- /* face map */
- lvl->vert_face_map= MEM_callocN(sizeof(ListBase)*lvl->totvert,"vert_face_map");
- for(i=0; i<lvl->totface; ++i){
- for(j=0; j<(lvl->faces[i].v[3]?4:3); ++j, ++indexnode) {
- indexnode->Index= i;
- BLI_addtail(&lvl->vert_face_map[lvl->faces[i].v[j]], indexnode);
- }
- }
+ for(i = 0; i < end; ++i) {
+ int vcur = mface_v(f, i);
+ int vnext = mface_v(f, i == end - 1 ? 0 : i + 1);
- /* edge boundaries */
- emax = (lvl->prev ? (lvl->prev->totedge * 2) : lvl->totedge);
- lvl->edge_boundary_states= MEM_callocN(sizeof(char)*lvl->totedge, "edge_boundary_states");
- for(i=0; i<emax; ++i) {
- MultiresMapNode *n1= lvl->vert_face_map[lvl->edges[i].v[0]].first;
- unsigned total= 0;
+ de->dir[i] = 1;
- lvl->edge_boundary_states[i] = 1;
- while(n1 && lvl->edge_boundary_states[i] == 1) {
- MultiresMapNode *n2= lvl->vert_face_map[lvl->edges[i].v[1]].first;
- while(n2) {
- if(n1->Index == n2->Index) {
- ++total;
-
- if(total > 1) {
- lvl->edge_boundary_states[i] = 0;
- break;
- }
+ for(n = emap[vcur].first; n; n = n->next) {
+ MEdge *e = &d->me->medge[n->index];
+
+ if(e->v1 == vnext || e->v2 == vnext) {
+ de->base[i] = n->index * d->interior_st;
+ if(((i == 0 || i == 1) && e->v1 == vnext) ||
+ ((i == 2 || i == 3) && e->v2 == vnext)) {
+ de->dir[i] = -1;
+ de->base[i] += d->interior_st - 1;
}
-
- n2= n2->next;
+ de->base[i] += offset;
+ break;
}
- n1= n1->next;
}
}
}
-/* CATMULL-CLARK
- ============= */
-
-typedef struct MultiApplyData {
- /* Smooth faces */
- float *corner1, *corner2, *corner3, *corner4;
- char quad;
-
- /* Smooth edges */
- char boundary;
- float edge_face_neighbor_midpoints_accum[3];
- unsigned edge_face_neighbor_midpoints_total;
- float *endpoint1, *endpoint2;
-
- /* Smooth verts */
- /* uses 'char boundary' */
- float *original;
- int edge_count;
- float vert_face_neighbor_midpoints_average[3];
- float vert_edge_neighbor_midpoints_average[3];
- float boundary_edges_average[3];
-} MultiApplyData;
-
-/* Simply averages the four corners of a polygon. */
-static float catmullclark_smooth_face(MultiApplyData *data, const unsigned i)
+/* Returns in out the corners [0-3] that use v1 and v2 */
+void find_face_corners(MFace *f, int v1, int v2, int out[2])
{
- const float total= data->corner1[i]+data->corner2[i]+data->corner3[i];
- return data->quad ? (total+data->corner4[i])/4 : total/3;
+ int i, end = f->v4 ? 4 : 3;
+
+ for(i = 0; i < end; ++i) {
+ int corner = mface_v(f, i);
+ if(corner == v1)
+ out[0] = i;
+ if(corner == v2)
+ out[1] = i;
+ }
}
-static float catmullclark_smooth_edge(MultiApplyData *data, const unsigned i)
+static void multires_displacer_get_spill_faces(MultiresDisplacer *d, DerivedMesh *dm, MFace *mface)
{
- float accum= 0;
- unsigned count= 2;
-
- accum+= data->endpoint1[i] + data->endpoint2[i];
+ ListBase *map = MultiresDM_get_vert_face_map(dm);
+ IndexNode *n1, *n2;
+ int v4 = d->face->v4 ? d->face->v4 : d->face->v1;
+ int crn[2], lv;
+
+ memset(&d->spill_x, 0, sizeof(DisplacerSpill));
+ memset(&d->spill_y, 0, sizeof(DisplacerSpill));
+ d->spill_x.face = d->spill_y.face = -1;
+
+ for(n1 = map[d->face->v3].first; n1; n1 = n1->next) {
+ if(n1->index == d->face_index)
+ continue;
+
+ for(n2 = map[d->face->v2].first; n2; n2 = n2->next) {
+ if(n1->index == n2->index)
+ d->spill_x.face = n1->index;
+ }
+ for(n2 = map[v4].first; n2; n2 = n2->next) {
+ if(n1->index == n2->index)
+ d->spill_y.face = n1->index;
+ }
+ }
- if(!data->boundary) {
- accum+= data->edge_face_neighbor_midpoints_accum[i];
- count+= data->edge_face_neighbor_midpoints_total;
+ if(d->spill_x.face != -1) {
+ /* Neighbor of v2/v3 found, find flip and orientation */
+ find_face_corners(&mface[d->spill_x.face], d->face->v2, d->face->v3, crn);
+ lv = mface[d->spill_x.face].v4 ? 3 : 2;
+
+ if(crn[0] == 0 && crn[1] == lv)
+ d->spill_x.f = 0+2+0;
+ else if(crn[0] == lv && crn[1] == 0)
+ d->spill_x.f = 1+2+0;
+ else if(crn[0] == 1 && crn[1] == 0)
+ d->spill_x.f = 1+2+4;
+ else if(crn[0] == 0 && crn[1] == 1)
+ d->spill_x.f = 0+2+4;
+ else if(crn[0] == 2 && crn[1] == 1)
+ d->spill_x.f = 1+0+0;
+ else if(crn[0] == 1 && crn[1] == 2)
+ d->spill_x.f = 0+0+0;
+ else if(crn[0] == 3 && crn[1] == 2)
+ d->spill_x.f = 0+0+4;
+ else if(crn[0] == 2 && crn[1] == 3)
+ d->spill_x.f = 1+0+4;
+
+ find_displacer_edges(d, dm, &d->spill_x.edges, &mface[d->spill_x.face]);
}
- return accum / count;
+ if(d->spill_y.face != -1) {
+ /* Neighbor of v3/v4 found, find flip and orientation */
+ find_face_corners(&mface[d->spill_y.face], d->face->v3, v4, crn);
+ lv = mface[d->spill_y.face].v4 ? 3 : 2;
+
+ if(crn[0] == 1 && crn[1] == 0)
+ d->spill_y.f = 1+2+0;
+ else if(crn[0] == 0 && crn[1] == 1)
+ d->spill_y.f = 0+2+0;
+ else if(crn[0] == 2 && crn[1] == 1)
+ d->spill_y.f = 1+0+4;
+ else if(crn[0] == 1 && crn[1] == 2)
+ d->spill_y.f = 0+0+4;
+ else if(crn[0] == 3 && crn[1] == 2)
+ d->spill_y.f = 0+0+0;
+ else if(crn[0] == 2 && crn[1] == 3)
+ d->spill_y.f = 1+0+0;
+ else if(crn[0] == 0 && crn[1] == lv)
+ d->spill_y.f = 0+2+4;
+ else if(crn[0] == lv && crn[1] == 0)
+ d->spill_y.f = 1+2+4;
+
+ find_displacer_edges(d, dm, &d->spill_y.edges, &mface[d->spill_y.face]);
+ }
}
-static float catmullclark_smooth_vert(MultiApplyData *data, const unsigned i)
+static void find_corner_valences(MultiresDisplacer *d, DerivedMesh *dm)
{
- if(data->boundary) {
- return data->original[i]*0.75 + data->boundary_edges_average[i]*0.25;
- } else {
- return (data->vert_face_neighbor_midpoints_average[i] +
- 2*data->vert_edge_neighbor_midpoints_average[i] +
- data->original[i]*(data->edge_count-3))/data->edge_count;
- }
-}
+ int i;
+
+ d->valence[3] = -1;
+ /* Set the vertex valence for the corners */
+ for(i = 0; i < (d->face->v4 ? 4 : 3); ++i)
+ d->valence[i] = BLI_countlist(&MultiresDM_get_vert_edge_map(dm)[mface_v(d->face, i)]);
+}
+static void multires_displacer_init(MultiresDisplacer *d, DerivedMesh *dm,
+ const int face_index, const int invert)
+{
+ Mesh *me = MultiresDM_get_mesh(dm);
+
+ d->me = me;
+ d->face = me->mface + face_index;
+ d->face_index = face_index;
+ d->face_offsets = MultiresDM_get_face_offsets(dm);
+ /* Get the multires grid from customdata */
+ d->grid = CustomData_get_layer(&me->fdata, CD_MDISPS);
+ if(d->grid)
+ d->grid += face_index;
+
+ d->spacing = pow(2, MultiresDM_get_totlvl(dm) - MultiresDM_get_lvl(dm));
+ d->sidetot = multires_side_tot[MultiresDM_get_lvl(dm) - 1];
+ d->interior_st = d->sidetot - 2;
+ d->disp_st = multires_side_tot[MultiresDM_get_totlvl(dm) - 1];
+ d->invert = invert;
+
+ multires_displacer_get_spill_faces(d, dm, me->mface);
+ find_displacer_edges(d, dm, &d->edges_primary, d->face);
+ find_corner_valences(d, dm);
+
+ d->dm_first_base_vert_index = dm->getNumVerts(dm) - me->totvert;
+}
-/* Call func count times, passing in[i] as the input and storing the output in out[i] */
-static void multi_apply(float *out, MultiApplyData *data,
- const unsigned count, float (*func)(MultiApplyData *, const unsigned))
+static void multires_displacer_weight(MultiresDisplacer *d, const float w)
{
- unsigned i;
- for(i=0; i<count; ++i)
- out[i]= func(data,i);
+ d->weight = w;
}
-static short multires_vert_is_boundary(MultiresLevel *lvl, unsigned v)
+static void multires_displacer_anchor(MultiresDisplacer *d, const int type, const int side_index)
{
- MultiresMapNode *node= lvl->vert_edge_map[v].first;
- while(node) {
- if(lvl->edge_boundary_states[node->Index])
- return 1;
- node= node->next;
+ d->sidendx = side_index;
+ d->x = d->y = d->sidetot / 2;
+ d->type = type;
+
+ if(type == 2) {
+ if(side_index == 0)
+ d->y -= 1;
+ else if(side_index == 1)
+ d->x += 1;
+ else if(side_index == 2)
+ d->y += 1;
+ else if(side_index == 3)
+ d->x -= 1;
+ }
+ else if(type == 3) {
+ if(side_index == 0) {
+ d->x -= 1;
+ d->y -= 1;
+ }
+ else if(side_index == 1) {
+ d->x += 1;
+ d->y -= 1;
+ }
+ else if(side_index == 2) {
+ d->x += 1;
+ d->y += 1;
+ }
+ else if(side_index == 3) {
+ d->x -= 1;
+ d->y += 1;
+ }
}
- return 0;
-}
-#define GET_FLOAT(array, i, j, stride) (((float*)((char*)(array)+((i)*(stride))))[(j)])
+ d->ax = d->x;
+ d->ay = d->y;
+}
-static void edge_face_neighbor_midpoints_accum(MultiApplyData *data, MultiresLevel *lvl,
- void *array, const char stride, const MultiresEdge *e)
+static void multires_displacer_anchor_edge(MultiresDisplacer *d, int v1, int v2, int x)
{
- ListBase *neighbors1= &lvl->vert_face_map[e->v[0]];
- ListBase *neighbors2= &lvl->vert_face_map[e->v[1]];
- MultiresMapNode *n1, *n2;
- unsigned j,count= 0;
- float *out= data->edge_face_neighbor_midpoints_accum;
-
- out[0]=out[1]=out[2]= 0;
-
- for(n1= neighbors1->first; n1; n1= n1->next) {
- for(n2= neighbors2->first; n2; n2= n2->next) {
- if(n1->Index == n2->Index) {
- for(j=0; j<3; ++j)
- out[j]+= GET_FLOAT(array,lvl->faces[n1->Index].mid,j,stride);
- ++count;
+ d->type = 4;
+
+ if(v1 == d->face->v1) {
+ d->x = 0;
+ d->y = 0;
+ if(v2 == d->face->v2)
+ d->x += x;
+ else if(v2 == d->face->v3) {
+ if(x < d->sidetot / 2)
+ d->y = x;
+ else {
+ d->x = x;
+ d->y = d->sidetot - 1;
}
}
+ else
+ d->y += x;
+ }
+ else if(v1 == d->face->v2) {
+ d->x = d->sidetot - 1;
+ d->y = 0;
+ if(v2 == d->face->v1)
+ d->x -= x;
+ else
+ d->y += x;
+ }
+ else if(v1 == d->face->v3) {
+ d->x = d->sidetot - 1;
+ d->y = d->sidetot - 1;
+ if(v2 == d->face->v2)
+ d->y -= x;
+ else if(v2 == d->face->v1) {
+ if(x < d->sidetot / 2)
+ d->x -= x;
+ else {
+ d->x = 0;
+ d->y -= x;
+ }
+ }
+ else
+ d->x -= x;
+ }
+ else if(v1 == d->face->v4) {
+ d->x = 0;
+ d->y = d->sidetot - 1;
+ if(v2 == d->face->v3)
+ d->x += x;
+ else
+ d->y -= x;
}
-
- data->edge_face_neighbor_midpoints_total= count;
}
-static void vert_face_neighbor_midpoints_average(MultiApplyData *data, MultiresLevel *lvl,
- void *array, const char stride, const unsigned i)
+static void multires_displacer_anchor_vert(MultiresDisplacer *d, const int v)
{
- ListBase *neighbors= &lvl->vert_face_map[i];
- MultiresMapNode *n1;
- unsigned j,count= 0;
- float *out= data->vert_face_neighbor_midpoints_average;
+ const int e = d->sidetot - 1;
- out[0]=out[1]=out[2]= 0;
+ d->type = 5;
- for(n1= neighbors->first; n1; n1= n1->next) {
- for(j=0; j<3; ++j)
- out[j]+= GET_FLOAT(array,lvl->faces[n1->Index].mid,j,stride);
- ++count;
- }
- for(j=0; j<3; ++j) out[j]/= count;
+ d->x = d->y = 0;
+ if(v == d->face->v2)
+ d->x = e;
+ else if(v == d->face->v3)
+ d->x = d->y = e;
+ else if(v == d->face->v4)
+ d->y = e;
}
-static void vert_edge_neighbor_midpoints_average(MultiApplyData *data, MultiresLevel *lvl,
- void *array, const char stride, const unsigned i)
+static void multires_displacer_jump(MultiresDisplacer *d)
{
- ListBase *neighbors= &lvl->vert_edge_map[i];
- MultiresMapNode *n1;
- unsigned j,count= 0;
- float *out= data->vert_edge_neighbor_midpoints_average;
-
- out[0]=out[1]=out[2]= 0;
-
- for(n1= neighbors->first; n1; n1= n1->next) {
- for(j=0; j<3; ++j)
- out[j]+= (GET_FLOAT(array,lvl->edges[n1->Index].v[0],j,stride) +
- GET_FLOAT(array,lvl->edges[n1->Index].v[1],j,stride)) / 2;
- ++count;
+ if(d->sidendx == 0) {
+ d->x -= 1;
+ d->y = d->ay;
+ }
+ else if(d->sidendx == 1) {
+ d->x = d->ax;
+ d->y -= 1;
+ }
+ else if(d->sidendx == 2) {
+ d->x += 1;
+ d->y = d->ay;
+ }
+ else if(d->sidendx == 3) {
+ d->x = d->ax;
+ d->y += 1;
}
- for(j=0; j<3; ++j) out[j]/= count;
}
-static void boundary_edges_average(MultiApplyData *data, MultiresLevel *lvl,
- void *array, const char stride, const unsigned i)
+/* Treating v1 as (0,0) and v3 as (st-1,st-1),
+ returns the index of the vertex at (x,y).
+ If x or y is >= st, wraps over to the adjacent face,
+ or if there is no adjacent face, returns -2. */
+static int multires_index_at_loc(int face_index, int x, int y, MultiresDisplacer *d, DisplacerEdges *de)
{
- ListBase *neighbors= &lvl->vert_edge_map[i];
- MultiresMapNode *n1;
- unsigned j,count= 0;
- float *out= data->boundary_edges_average;
+ int coord_edge = d->sidetot - 1; /* Max value of x/y at edge of grid */
+ int mid = d->sidetot / 2;
+ int lim = mid - 1;
+ int qtot = lim * lim;
+ int base = d->face_offsets[face_index];
+
+ /* Edge spillover */
+ if(x == d->sidetot || y == d->sidetot) {
+ int flags, v_axis, f_axis, lx, ly;
+
+ if(x == d->sidetot && d->spill_x.face != -1) {
+ flags = d->spill_x.f;
+
+ /* Handle triangle seam between v1 and v3 */
+ if(!d->me->mface[d->spill_x.face].v4 &&
+ ((flags == 2 && y >= mid) || (flags == 3 && y < mid)))
+ flags += 2;
+
+ v_axis = (flags & 1) ? d->sidetot - 1 - y : y;
+ f_axis = (flags & 2) ? 1 : d->sidetot - 2;
+ lx = f_axis, ly = v_axis;
+
+ if(flags & 4) {
+ lx = v_axis;
+ ly = f_axis;
+ }
- out[0]=out[1]=out[2]= 0;
-
- for(n1= neighbors->first; n1; n1= n1->next) {
- const MultiresEdge *e= &lvl->edges[n1->Index];
- const unsigned end= e->v[0]==i ? e->v[1] : e->v[0];
-
- if(lvl->edge_boundary_states[n1->Index]) {
- for(j=0; j<3; ++j)
- out[j]+= GET_FLOAT(array,end,j,stride);
- ++count;
+ return multires_index_at_loc(d->spill_x.face, lx, ly, d, &d->spill_x.edges);
+ }
+ else if(y == d->sidetot && d->spill_y.face != -1) {
+ flags = d->spill_y.f;
+
+ /* Handle triangle seam between v1 and v3 */
+ if(!d->me->mface[d->spill_y.face].v4 &&
+ ((flags == 6 && x >= mid) || (flags == 7 && x < mid)))
+ flags = ~flags;
+
+ v_axis = (flags & 1) ? x : d->sidetot - 1 - x;
+ f_axis = (flags & 2) ? 1 : d->sidetot - 2;
+ lx = v_axis, ly = f_axis;
+
+ if(flags & 4) {
+ lx = f_axis;
+ ly = v_axis;
+ }
+
+ return multires_index_at_loc(d->spill_y.face, lx, ly, d, &d->spill_y.edges);
}
+ else
+ return -2;
+ }
+ /* Corners */
+ else if(x == 0 && y == 0)
+ return d->dm_first_base_vert_index + d->face->v1;
+ else if(x == coord_edge && y == 0)
+ return d->dm_first_base_vert_index + d->face->v2;
+ else if(x == coord_edge && y == coord_edge)
+ return d->dm_first_base_vert_index + d->face->v3;
+ else if(x == 0 && y == coord_edge)
+ return d->dm_first_base_vert_index + d->face->v4;
+ /* Edges */
+ else if(x == 0) {
+ if(d->face->v4)
+ return de->base[3] + de->dir[3] * (y - 1);
+ else
+ return de->base[2] + de->dir[2] * (y - 1);
}
- for(j=0; j<3; ++j) out[j]/= count;
+ else if(y == 0)
+ return de->base[0] + de->dir[0] * (x - 1);
+ else if(x == d->sidetot - 1)
+ return de->base[1] + de->dir[1] * (y - 1);
+ else if(y == d->sidetot - 1)
+ return de->base[2] + de->dir[2] * (x - 1);
+ /* Face center */
+ else if(x == mid && y == mid)
+ return base;
+ /* Cross */
+ else if(x == mid && y < mid)
+ return base + (mid - y);
+ else if(y == mid && x > mid)
+ return base + lim + (x - mid);
+ else if(x == mid && y > mid)
+ return base + lim*2 + (y - mid);
+ else if(y == mid && x < mid) {
+ if(d->face->v4)
+ return base + lim*3 + (mid - x);
+ else
+ return base + lim*2 + (mid - x);
+ }
+ /* Quarters */
+ else {
+ int offset = base + lim * (d->face->v4 ? 4 : 3);
+ if(x < mid && y < mid)
+ return offset + ((mid - x - 1)*lim + (mid - y));
+ else if(x > mid && y < mid)
+ return offset + qtot + ((mid - y - 1)*lim + (x - mid));
+ else if(x > mid && y > mid)
+ return offset + qtot*2 + ((x - mid - 1)*lim + (y - mid));
+ else if(x < mid && y > mid)
+ return offset + qtot*3 + ((y - mid - 1)*lim + (mid - x));
+ }
+
+ return -1;
}
-/* END CATMULL-CLARK
- ================= */
-
-/* Update vertex locations and vertex flags */
-static void multires_update_vertices(Mesh *me, EditMesh *em)
+/* Calculate the TS matrix used for applying displacements.
+ Uses the undisplaced subdivided mesh's curvature to find a
+ smoothly normal and tangents. */
+static void calc_disp_mat(MultiresDisplacer *d, float mat[3][3])
{
- MultiresLevel *cr_lvl= current_level(me->mr), *pr_lvl= NULL,
- *last_lvl= me->mr->levels.last;
- vec3f *pr_deltas= NULL, *cr_deltas= NULL, *swap_deltas= NULL;
- EditVert *eve= NULL;
- MultiApplyData data;
- int i, j;
+ int u = multires_index_at_loc(d->face_index, d->x + 1, d->y, d, &d->edges_primary);
+ int v = multires_index_at_loc(d->face_index, d->x, d->y + 1, d, &d->edges_primary);
+ float norm[3], t1[3], t2[3], inv[3][3];
+ MVert *base = d->subco + d->subco_index;
- /* XXX added this to prevent crash, but if it works? (ton) */
- if(me->mr->verts==NULL)
- return;
+ //printf("f=%d, x=%d, y=%d, i=%d, u=%d, v=%d ", d->face_index, d->x, d->y, d->subco_index, u, v);
- /* Prepare deltas */
- pr_deltas= MEM_callocN(sizeof(vec3f)*last_lvl->totvert, "multires deltas 1");
- cr_deltas= MEM_callocN(sizeof(vec3f)*last_lvl->totvert, "multires deltas 2");
-
- /* Calculate initial deltas -- current mesh subtracted from current level*/
- if(em) eve= em->verts.first;
- for(i=0; i<cr_lvl->totvert; ++i) {
- if(em) {
- VecSubf(&cr_deltas[i].x, eve->co, me->mr->verts[i].co);
- eve= eve->next;
- } else
- VecSubf(&cr_deltas[i].x, me->mvert[i].co, me->mr->verts[i].co);
+ norm[0] = base->no[0] / 32767.0f;
+ norm[1] = base->no[1] / 32767.0f;
+ norm[2] = base->no[2] / 32767.0f;
+
+ /* Special handling for vertices of valence 3 */
+ if(d->valence[1] == 3 && d->x == d->sidetot - 1 && d->y == 0)
+ u = -1;
+ else if(d->valence[2] == 3 && d->x == d->sidetot - 1 && d->y == d->sidetot - 1)
+ u = v = -1;
+ else if(d->valence[3] == 3 && d->x == 0 && d->y == d->sidetot - 1)
+ v = -1;
+
+ /* If either u or v is -2, it's on a boundary. In this
+ case, back up by one row/column and use the same
+ vector as the preceeding sub-edge. */
+
+ if(u < 0) {
+ u = multires_index_at_loc(d->face_index, d->x - 1, d->y, d, &d->edges_primary);
+ VecSubf(t1, base->co, d->subco[u].co);
}
+ else
+ VecSubf(t1, d->subco[u].co, base->co);
-
- /* Copy current level's vertex flags and clear the rest */
- if(em) eve= em->verts.first;
- for(i=0; i < last_lvl->totvert; ++i) {
- if(i < cr_lvl->totvert) {
- MVert mvflag;
- multires_get_vert(&mvflag, eve, &me->mvert[i], i);
- if(em) eve= eve->next;
- me->mr->verts[i].flag= mvflag.flag;
- }
- else
- me->mr->verts[i].flag= 0;
+ if(v < 0) {
+ v = multires_index_at_loc(d->face_index, d->x, d->y - 1, d, &d->edges_primary);
+ VecSubf(t2, base->co, d->subco[v].co);
}
+ else
+ VecSubf(t2, d->subco[v].co, base->co);
- /* If already on the highest level, copy current verts (including flags) into current level */
- if(cr_lvl == last_lvl) {
- if(em)
- eve= em->verts.first;
- for(i=0; i<cr_lvl->totvert; ++i) {
- multires_get_vert(&me->mr->verts[i], eve, &me->mvert[i], i);
- if(em) eve= eve->next;
- }
+ //printf("uu=%d, vv=%d\n", u, v);
+
+ Normalize(t1);
+ Normalize(t2);
+ Mat3FromColVecs(mat, t1, t2, norm);
+
+ if(d->invert) {
+ Mat3Inv(inv, mat);
+ Mat3CpyMat3(mat, inv);
}
+}
- /* Update higher levels */
- pr_lvl= BLI_findlink(&me->mr->levels,me->mr->current-1);
- cr_lvl= pr_lvl->next;
- while(cr_lvl) {
- multires_calc_temp_data(pr_lvl);
-
- /* Swap the old/new deltas */
- swap_deltas= pr_deltas;
- pr_deltas= cr_deltas;
- cr_deltas= swap_deltas;
-
- /* Calculate and add new deltas
- ============================ */
- for(i=0; i<pr_lvl->totface; ++i) {
- const MultiresFace *f= &pr_lvl->faces[i];
- data.corner1= &pr_deltas[f->v[0]].x;
- data.corner2= &pr_deltas[f->v[1]].x;
- data.corner3= &pr_deltas[f->v[2]].x;
- data.corner4= &pr_deltas[f->v[3]].x;
- data.quad= f->v[3] ? 1 : 0;
- multi_apply(&cr_deltas[f->mid].x, &data, 3, catmullclark_smooth_face);
-
- for(j=0; j<(data.quad?4:3); ++j)
- me->mr->verts[f->mid].flag |= me->mr->verts[f->v[j]].flag;
- }
+static void multires_displace(MultiresDisplacer *d, float co[3])
+{
+ float disp[3], mat[3][3];
+ float *data;
+ MVert *subco = &d->subco[d->subco_index];
- for(i=0; i<pr_lvl->totedge; ++i) {
- const MultiresEdge *e= &pr_lvl->edges[i];
- data.boundary= pr_lvl->edge_boundary_states[i];
- edge_face_neighbor_midpoints_accum(&data,pr_lvl,cr_deltas,sizeof(vec3f),e);
- data.endpoint1= &pr_deltas[e->v[0]].x;
- data.endpoint2= &pr_deltas[e->v[1]].x;
- multi_apply(&cr_deltas[e->mid].x, &data, 3, catmullclark_smooth_edge);
-
- for(j=0; j<2; ++j)
- me->mr->verts[e->mid].flag |= me->mr->verts[e->v[j]].flag;
- }
+ if(!d->grid || !d->grid->disps) return;
- for(i=0; i<pr_lvl->totvert; ++i) {
- data.boundary= multires_vert_is_boundary(pr_lvl,i);
- data.original= &pr_deltas[i].x;
- data.edge_count= BLI_countlist(&pr_lvl->vert_edge_map[i]);
- if(data.boundary)
- boundary_edges_average(&data,pr_lvl,pr_deltas,sizeof(vec3f),i);
- else {
- vert_face_neighbor_midpoints_average(&data,pr_lvl,cr_deltas,sizeof(vec3f),i);
- vert_edge_neighbor_midpoints_average(&data,pr_lvl,pr_deltas,sizeof(vec3f),i);
- }
- multi_apply(&cr_deltas[i].x, &data, 3, catmullclark_smooth_vert);
- }
+ data = d->grid->disps[(d->y * d->spacing) * d->disp_st + (d->x * d->spacing)];
+
+ if(d->invert)
+ VecSubf(disp, co, subco->co);
+ else
+ VecCopyf(disp, data);
- /* Apply deltas to vertex locations */
- for(i=0; (cr_lvl == last_lvl) && (i < cr_lvl->totvert); ++i) {
- VecAddf(me->mr->verts[i].co,
- me->mr->verts[i].co,
- &cr_deltas[i].x);
- }
- multires_free_temp_data(pr_lvl);
+ /* Apply ts matrix to displacement */
+ calc_disp_mat(d, mat);
+ Mat3MulVecfl(mat, disp);
- pr_lvl= pr_lvl->next;
- cr_lvl= cr_lvl->next;
+ if(d->invert) {
+ VecCopyf(data, disp);
+
+ }
+ else {
+ if(d->type == 4 || d->type == 5)
+ VecMulf(disp, d->weight);
+ VecAddf(co, co, disp);
}
- if(pr_deltas) MEM_freeN(pr_deltas);
- if(cr_deltas) MEM_freeN(cr_deltas);
+ if(d->type == 2) {
+ if(d->sidendx == 0)
+ d->y -= 1;
+ else if(d->sidendx == 1)
+ d->x += 1;
+ else if(d->sidendx == 2)
+ d->y += 1;
+ else if(d->sidendx == 3)
+ d->x -= 1;
+ }
+ else if(d->type == 3) {
+ if(d->sidendx == 0)
+ d->y -= 1;
+ else if(d->sidendx == 1)
+ d->x += 1;
+ else if(d->sidendx == 2)
+ d->y += 1;
+ else if(d->sidendx == 3)
+ d->x -= 1;
+ }
}
-static void multires_update_faces(Mesh *me, EditMesh *em)
+static void multiresModifier_disp_run(DerivedMesh *dm, MVert *subco, int invert)
{
- MultiresLevel *cr_lvl= current_level(me->mr), *pr_lvl= NULL,
- *last_lvl= me->mr->levels.last;
- char *pr_flag_damaged= NULL, *cr_flag_damaged= NULL, *or_flag_damaged= NULL,
- *pr_mat_damaged= NULL, *cr_mat_damaged= NULL, *or_mat_damaged= NULL, *swap= NULL;
- EditFace *efa= NULL;
- unsigned i,j,curf;
-
- /* Find for each face whether flag/mat has changed */
- pr_flag_damaged= MEM_callocN(sizeof(char) * last_lvl->totface, "flag_damaged 1");
- cr_flag_damaged= MEM_callocN(sizeof(char) * last_lvl->totface, "flag_damaged 1");
- pr_mat_damaged= MEM_callocN(sizeof(char) * last_lvl->totface, "mat_damaged 1");
- cr_mat_damaged= MEM_callocN(sizeof(char) * last_lvl->totface, "mat_damaged 1");
- if(em) efa= em->faces.first;
- for(i=0; i<cr_lvl->totface; ++i) {
- MultiresFace mftmp;
- multires_get_face(&mftmp, &me->mr->fdata, i, efa, &me->mface[i]);
- if(cr_lvl->faces[i].flag != mftmp.flag)
- cr_flag_damaged[i]= 1;
- if(cr_lvl->faces[i].mat_nr != mftmp.mat_nr)
- cr_mat_damaged[i]= 1;
-
- /* Update current level */
- cr_lvl->faces[i].flag= mftmp.flag;
- cr_lvl->faces[i].mat_nr= mftmp.mat_nr;
-
- if(em) efa= efa->next;
- }
- or_flag_damaged= MEM_dupallocN(cr_flag_damaged);
- or_mat_damaged= MEM_dupallocN(cr_mat_damaged);
-
- /* Update lower levels */
- cr_lvl= cr_lvl->prev;
- while(cr_lvl) {
- swap= pr_flag_damaged;
- pr_flag_damaged= cr_flag_damaged;
- cr_flag_damaged= swap;
-
- swap= pr_mat_damaged;
- pr_mat_damaged= cr_mat_damaged;
- cr_mat_damaged= swap;
-
- curf= 0;
- for(i=0; i<cr_lvl->totface; ++i) {
- const int sides= cr_lvl->faces[i].v[3] ? 4 : 3;
-
- /* Check damages */
- for(j=0; j<sides; ++j, ++curf) {
- if(pr_flag_damaged[curf]) {
- cr_lvl->faces[i].flag= cr_lvl->next->faces[curf].flag;
- cr_flag_damaged[i]= 1;
- }
- if(pr_mat_damaged[curf]) {
- cr_lvl->faces[i].mat_nr= cr_lvl->next->faces[curf].mat_nr;
- cr_mat_damaged[i]= 1;
- }
+ const int lvl = MultiresDM_get_lvl(dm);
+ const int gridFaces = multires_side_tot[lvl - 2] - 1;
+ const int edgeSize = multires_side_tot[lvl - 1] - 1;
+ MVert *mvert = CDDM_get_verts(dm);
+ MEdge *medge = MultiresDM_get_mesh(dm)->medge;
+ MFace *mface = MultiresDM_get_mesh(dm)->mface;
+ ListBase *map = MultiresDM_get_vert_face_map(dm);
+ Mesh *me = MultiresDM_get_mesh(dm);
+ MultiresDisplacer d;
+ int i, S, x, y;
+
+ d.subco = subco;
+ d.subco_index = 0;
+
+ for(i = 0; i < me->totface; ++i) {
+ const int numVerts = mface[i].v4 ? 4 : 3;
+
+ /* Center */
+ multires_displacer_init(&d, dm, i, invert);
+ multires_displacer_anchor(&d, 1, 0);
+ multires_displace(&d, mvert->co);
+ ++mvert;
+ ++d.subco_index;
+
+ /* Cross */
+ for(S = 0; S < numVerts; ++S) {
+ multires_displacer_anchor(&d, 2, S);
+ for(x = 1; x < gridFaces; ++x) {
+ multires_displace(&d, mvert->co);
+ ++mvert;
+ ++d.subco_index;
}
}
- cr_lvl= cr_lvl->prev;
+ /* Quarters */
+ for(S = 0; S < numVerts; S++) {
+ multires_displacer_anchor(&d, 3, S);
+ for(y = 1; y < gridFaces; y++) {
+ for(x = 1; x < gridFaces; x++) {
+ multires_displace(&d, mvert->co);
+ ++mvert;
+ ++d.subco_index;
+ }
+ multires_displacer_jump(&d);
+ }
+ }
}
-
- /* Clear to original damages */
- if(cr_flag_damaged) MEM_freeN(cr_flag_damaged);
- if(cr_mat_damaged) MEM_freeN(cr_mat_damaged);
- cr_flag_damaged= or_flag_damaged;
- cr_mat_damaged= or_mat_damaged;
-
- /* Update higher levels */
- pr_lvl= current_level(me->mr);
- cr_lvl= pr_lvl->next;
- while(cr_lvl) {
- swap= pr_flag_damaged;
- pr_flag_damaged= cr_flag_damaged;
- cr_flag_damaged= swap;
-
- swap= pr_mat_damaged;
- pr_mat_damaged= cr_mat_damaged;
- cr_mat_damaged= swap;
-
- /* Update faces */
- for(i=0, curf= 0; i<pr_lvl->totface; ++i) {
- const int sides= cr_lvl->prev->faces[i].v[3] ? 4 : 3;
- for(j=0; j<sides; ++j, ++curf) {
- if(pr_flag_damaged[i]) {
- cr_lvl->faces[curf].flag= pr_lvl->faces[i].flag;
- cr_flag_damaged[curf]= 1;
+
+ for(i = 0; i < me->totedge; ++i) {
+ const MEdge *e = &medge[i];
+ for(x = 1; x < edgeSize; ++x) {
+ IndexNode *n1, *n2;
+ int numFaces = 0;
+ for(n1 = map[e->v1].first; n1; n1 = n1->next) {
+ for(n2 = map[e->v2].first; n2; n2 = n2->next) {
+ if(n1->index == n2->index)
+ ++numFaces;
}
- if(pr_mat_damaged[i]) {
- cr_lvl->faces[curf].mat_nr= pr_lvl->faces[i].mat_nr;
- cr_mat_damaged[curf]= 1;
+ }
+ multires_displacer_weight(&d, 1.0f / numFaces);
+ /* TODO: Better to have these loops outside the x loop */
+ for(n1 = map[e->v1].first; n1; n1 = n1->next) {
+ for(n2 = map[e->v2].first; n2; n2 = n2->next) {
+ if(n1->index == n2->index) {
+ multires_displacer_init(&d, dm, n1->index, invert);
+ multires_displacer_anchor_edge(&d, e->v1, e->v2, x);
+ multires_displace(&d, mvert->co);
+ }
}
}
+ ++mvert;
+ ++d.subco_index;
}
-
- pr_lvl= pr_lvl->next;
- cr_lvl= cr_lvl->next;
+ }
+
+ for(i = 0; i < me->totvert; ++i) {
+ IndexNode *n;
+ multires_displacer_weight(&d, 1.0f / BLI_countlist(&map[i]));
+ for(n = map[i].first; n; n = n->next) {
+ multires_displacer_init(&d, dm, n->index, invert);
+ multires_displacer_anchor_vert(&d, i);
+ multires_displace(&d, mvert->co);
+ }
+ ++mvert;
+ ++d.subco_index;
}
- if(pr_flag_damaged) MEM_freeN(pr_flag_damaged);
- if(cr_flag_damaged) MEM_freeN(cr_flag_damaged);
- if(pr_mat_damaged) MEM_freeN(pr_mat_damaged);
- if(cr_mat_damaged) MEM_freeN(cr_mat_damaged);
+ if(!invert)
+ CDDM_calc_normals(dm);
}
-static void multires_update_colors(Mesh *me, EditMesh *em)
+static void multiresModifier_update(DerivedMesh *dm)
{
- MultiresLevel *lvl= BLI_findlink(&me->mr->levels,me->mr->current-1);
- MultiresCol *pr_deltas= NULL, *cr_deltas= NULL;
- CustomData *src= em ? &em->fdata : &me->fdata;
- EditFace *efa= NULL;
- unsigned i,j,curf= 0;
-
- if(me->mr->use_col) {
- /* Calc initial deltas */
- cr_deltas= MEM_callocN(sizeof(MultiresCol)*lvl->totface*4,"initial color/uv deltas");
-
- if(em) efa= em->faces.first;
- for(i=0; i<lvl->totface; ++i) {
- MCol *col= em ? CustomData_em_get(src, efa->data, CD_MCOL) : &me->mcol[i*4];
- for(j=0; j<4; ++j) {
- if(me->mr->use_col) {
- cr_deltas[i*4+j].a= col[j].a - lvl->colfaces[i].col[j].a;
- cr_deltas[i*4+j].r= col[j].r - lvl->colfaces[i].col[j].r;
- cr_deltas[i*4+j].g= col[j].g - lvl->colfaces[i].col[j].g;
- cr_deltas[i*4+j].b= col[j].b - lvl->colfaces[i].col[j].b;
- }
- }
- if(em) efa= efa->next;
- }
-
- /* Update current level */
- if(em) efa= em->faces.first;
- for(i=0; i<lvl->totface; ++i) {
- MultiresColFace *f= &lvl->colfaces[i];
+ Mesh *me;
+ MDisps *mdisps;
- if(me->mr->use_col)
- mcol_to_multires(f, em ? CustomData_em_get(src, efa->data, CD_MCOL) : &me->mcol[i*4]);
-
- if(em) efa= efa->next;
- }
-
- /* Update higher levels */
- lvl= lvl->next;
- while(lvl) {
- /* Set up new deltas, but keep the ones from the previous level */
- if(pr_deltas) MEM_freeN(pr_deltas);
- pr_deltas= cr_deltas;
- cr_deltas= MEM_callocN(sizeof(MultiresCol)*lvl->totface*4,"color deltas");
-
- curf= 0;
- for(i=0; i<lvl->prev->totface; ++i) {
- const char sides= lvl->prev->faces[i].v[3]?4:3;
- MultiresCol cntr;
-
- /* Find average color of 4 (or 3 for triangle) verts */
- multires_col_avg(&cntr,&pr_deltas[i*4],sides);
-
- for(j=0; j<sides; ++j) {
- multires_col_avg2(&cr_deltas[curf*4],
- &pr_deltas[i*4+j],
- &pr_deltas[i*4+(j==0?sides-1:j-1)]);
- cr_deltas[curf*4+1]= pr_deltas[i*4+j];
- multires_col_avg2(&cr_deltas[curf*4+2],
- &pr_deltas[i*4+j],
- &pr_deltas[i*4+(j==sides-1?0:j+1)]);
- cr_deltas[curf*4+3]= cntr;
- ++curf;
- }
- }
+ if(!(G.f & G_SCULPTMODE) && !(*MultiresDM_get_flags(dm) & MULTIRES_DM_UPDATE_ALWAYS)) return;
- for(i=0; i<lvl->totface; ++i) {
- for(j=0; j<4; ++j) {
- lvl->colfaces[i].col[j].a+= cr_deltas[i*4+j].a;
- lvl->colfaces[i].col[j].r+= cr_deltas[i*4+j].r;
- lvl->colfaces[i].col[j].g+= cr_deltas[i*4+j].g;
- lvl->colfaces[i].col[j].b+= cr_deltas[i*4+j].b;
- }
- }
+ me = MultiresDM_get_mesh(dm);
+ mdisps = CustomData_get_layer(&me->fdata, CD_MDISPS);
- lvl= lvl->next;
- }
- if(pr_deltas) MEM_freeN(pr_deltas);
- if(cr_deltas) MEM_freeN(cr_deltas);
+ if(mdisps) {
+ const int lvl = MultiresDM_get_lvl(dm);
+ const int totlvl = MultiresDM_get_totlvl(dm);
- /* Update lower levels */
- lvl= me->mr->levels.last;
- lvl= lvl->prev;
- while(lvl) {
- MultiresColFace *nf= lvl->next->colfaces;
- for(i=0; i<lvl->totface; ++i) {
- MultiresFace *f= &lvl->faces[i];
- for(j=0; j<(f->v[3]?4:3); ++j) {
- lvl->colfaces[i].col[j]= nf->col[1];
- ++nf;
- }
- }
- lvl= lvl->prev;
+ if(lvl < totlvl) {
+ /* Propagate disps upwards */
+ DerivedMesh *final, *subco_dm, *orig;
+ MVert *verts_new = NULL, *cur_lvl_orig_verts = NULL;
+ MultiresModifierData mmd;
+ int i;
+
+ orig = CDDM_from_mesh(me, NULL);
+
+ /* Regenerate the current level's vertex coordinates
+ (includes older displacements but not new sculpts) */
+ mmd.totlvl = totlvl;
+ mmd.lvl = lvl;
+ subco_dm = multires_dm_create_from_derived(&mmd, orig, me, 0, 0);
+ *MultiresDM_get_flags(subco_dm) |= MULTIRES_DM_UPDATE_BLOCK;
+ cur_lvl_orig_verts = CDDM_get_verts(subco_dm);
+
+ /* Subtract the original vertex cos from the new vertex cos */
+ verts_new = CDDM_get_verts(dm);
+ for(i = 0; i < dm->getNumVerts(dm); ++i)
+ VecSubf(verts_new[i].co, verts_new[i].co, cur_lvl_orig_verts[i].co);
+
+ final = multires_subdisp_pre(dm, totlvl - lvl, 0);
+
+ multires_subdisp(orig, me, final, lvl, totlvl, dm->getNumVerts(dm), dm->getNumEdges(dm),
+ dm->getNumFaces(dm), 1);
+
+ subco_dm->release(subco_dm);
+ orig->release(orig);
}
+ else
+ multiresModifier_disp_run(dm, MultiresDM_get_subco(dm), 1);
}
}
-void multires_update_levels(Mesh *me, const int render)
+void multires_force_update(Object *ob)
{
- EditMesh *em= (!render && G.obedit) ? G.editMesh : NULL;
+ if(ob->derivedFinal) {
+ ob->derivedFinal->needsFree =1;
+ ob->derivedFinal->release(ob->derivedFinal);
+ ob->derivedFinal = NULL;
+ }
+}
+
+struct DerivedMesh *multires_dm_create_from_derived(MultiresModifierData *mmd, DerivedMesh *dm, Mesh *me,
+ int useRenderParams, int isFinalCalc)
+{
+ SubsurfModifierData smd;
+ MultiresSubsurf ms;
+ DerivedMesh *result;
+ int i;
+
+ ms.mmd = mmd;
+ ms.me = me;
- multires_update_first_level(me, em);
- multires_update_vertices(me, em);
- multires_update_faces(me, em);
- multires_update_colors(me, em);
+ memset(&smd, 0, sizeof(SubsurfModifierData));
+ smd.levels = smd.renderLevels = mmd->lvl - 1;
+ smd.flags |= eSubsurfModifierFlag_SubsurfUv;
+
+ result = subsurf_make_derived_from_derived_with_multires(dm, &smd, &ms, useRenderParams, NULL, isFinalCalc, 0);
+ for(i = 0; i < result->getNumVerts(result); ++i)
+ MultiresDM_get_subco(result)[i] = CDDM_get_verts(result)[i];
+ multiresModifier_disp_run(result, MultiresDM_get_subco(result), 0);
+ MultiresDM_set_update(result, multiresModifier_update);
+
+ return result;
}
-static void check_colors(Mesh *me)
+/**** Old Multires code ****
+***************************/
+
+/* Does not actually free lvl itself */
+void multires_free_level(MultiresLevel *lvl)
{
- CustomData *src= G.obedit ? &G.editMesh->fdata : &me->fdata;
- const char col= CustomData_has_layer(src, CD_MCOL);
-
- /* Check if vertex colors have been deleted or added */
- if(me->mr->use_col && !col)
- me->mr->use_col= 0;
- else if(!me->mr->use_col && col) {
- me->mr->use_col= 1;
- multires_load_cols(me);
+ if(lvl) {
+ if(lvl->faces) MEM_freeN(lvl->faces);
+ if(lvl->edges) MEM_freeN(lvl->edges);
+ if(lvl->colfaces) MEM_freeN(lvl->colfaces);
}
}
-static unsigned int find_mid_edge(ListBase *vert_edge_map,
- MultiresLevel *lvl,
- const unsigned int v1,
- const unsigned int v2 )
+void multires_free(Multires *mr)
{
- MultiresMapNode *n= vert_edge_map[v1].first;
- while(n) {
- if(lvl->edges[n->Index].v[0]==v2 ||
- lvl->edges[n->Index].v[1]==v2)
- return lvl->edges[n->Index].mid;
+ if(mr) {
+ MultiresLevel* lvl= mr->levels.first;
- n= n->next;
+ /* Free the first-level data */
+ if(lvl) {
+ CustomData_free(&mr->vdata, lvl->totvert);
+ CustomData_free(&mr->fdata, lvl->totface);
+ MEM_freeN(mr->edge_flags);
+ MEM_freeN(mr->edge_creases);
+ }
+
+ while(lvl) {
+ multires_free_level(lvl);
+ lvl= lvl->next;
+ }
+
+ MEM_freeN(mr->verts);
+
+ BLI_freelistN(&mr->levels);
+
+ MEM_freeN(mr);
}
- return -1;
}
-static float clamp_component(const float c)
+static void create_old_vert_face_map(ListBase **map, IndexNode **mem, const MultiresFace *mface,
+ const int totvert, const int totface)
{
- if(c<0) return 0;
- else if(c>255) return 255;
- else return c;
+ int i,j;
+ IndexNode *node = NULL;
+
+ (*map) = MEM_callocN(sizeof(ListBase) * totvert, "vert face map");
+ (*mem) = MEM_callocN(sizeof(IndexNode) * totface*4, "vert face map mem");
+ node = *mem;
+
+ /* Find the users */
+ for(i = 0; i < totface; ++i){
+ for(j = 0; j < (mface[i].v[3]?4:3); ++j, ++node) {
+ node->index = i;
+ BLI_addtail(&(*map)[mface[i].v[j]], node);
+ }
+ }
}
-void multires_to_mcol(MultiresColFace *f, MCol mcol[4])
+static void create_old_vert_edge_map(ListBase **map, IndexNode **mem, const MultiresEdge *medge,
+ const int totvert, const int totedge)
{
- unsigned char j;
- for(j=0; j<4; ++j) {
- mcol->a= clamp_component(f->col[j].a);
- mcol->r= clamp_component(f->col[j].r);
- mcol->g= clamp_component(f->col[j].g);
- mcol->b= clamp_component(f->col[j].b);
- ++mcol;
+ int i,j;
+ IndexNode *node = NULL;
+
+ (*map) = MEM_callocN(sizeof(ListBase) * totvert, "vert edge map");
+ (*mem) = MEM_callocN(sizeof(IndexNode) * totedge*2, "vert edge map mem");
+ node = *mem;
+
+ /* Find the users */
+ for(i = 0; i < totedge; ++i){
+ for(j = 0; j < 2; ++j, ++node) {
+ node->index = i;
+ BLI_addtail(&(*map)[medge[i].v[j]], node);
+ }
}
}
-void multires_level_to_mesh(Object *ob, Mesh *me, const int render)
+static MultiresFace *find_old_face(ListBase *map, MultiresFace *faces, int v1, int v2, int v3, int v4)
{
- MultiresLevel *lvl= BLI_findlink(&me->mr->levels,me->mr->current-1);
- int i;
- EditMesh *em= (!render && G.obedit) ? G.editMesh : NULL;
-
- if(em)
- return;
-
- CustomData_free_layer_active(&me->vdata, CD_MVERT, me->totvert);
- CustomData_free_layer_active(&me->edata, CD_MEDGE, me->totedge);
- CustomData_free_layer_active(&me->fdata, CD_MFACE, me->totface);
- CustomData_free_layer_active(&me->vdata, CD_MDEFORMVERT, me->totvert);
- CustomData_free_layers(&me->fdata, CD_MTFACE, me->totface);
- CustomData_free_layers(&me->fdata, CD_MCOL, me->totface);
-
- me->totvert= lvl->totvert;
- me->totface= lvl->totface;
- me->totedge= lvl->totedge;
+ IndexNode *n1;
+ int v[4] = {v1, v2, v3, v4}, i, j;
- CustomData_add_layer(&me->vdata, CD_MVERT, CD_CALLOC, NULL, me->totvert);
- CustomData_add_layer(&me->edata, CD_MEDGE, CD_CALLOC, NULL, me->totedge);
- CustomData_add_layer(&me->fdata, CD_MFACE, CD_CALLOC, NULL, me->totface);
- mesh_update_customdata_pointers(me);
+ for(n1 = map[v1].first; n1; n1 = n1->next) {
+ int fnd[4] = {0, 0, 0, 0};
- /* Vertices/Edges/Faces */
-
- for(i=0; i<lvl->totvert; ++i) {
- me->mvert[i]= me->mr->verts[i];
- }
- for(i=0; i<lvl->totedge; ++i) {
- me->medge[i].v1= lvl->edges[i].v[0];
- me->medge[i].v2= lvl->edges[i].v[1];
- me->medge[i].flag &= ~ME_HIDE;
- }
- for(i=0; i<lvl->totface; ++i) {
- me->mface[i].v1= lvl->faces[i].v[0];
- me->mface[i].v2= lvl->faces[i].v[1];
- me->mface[i].v3= lvl->faces[i].v[2];
- me->mface[i].v4= lvl->faces[i].v[3];
- me->mface[i].flag= lvl->faces[i].flag;
- me->mface[i].flag &= ~ME_HIDE;
- me->mface[i].mat_nr= lvl->faces[i].mat_nr;
- }
-
- /* Edge flags */
- if(lvl==me->mr->levels.first) {
- for(i=0; i<lvl->totedge; ++i) {
- me->medge[i].flag= me->mr->edge_flags[i];
- me->medge[i].crease= me->mr->edge_creases[i];
- }
- } else {
- MultiresLevel *lvl1= me->mr->levels.first;
- const int last= lvl1->totedge * pow(2, me->mr->current-1);
- for(i=0; i<last; ++i) {
- const int ndx= i / pow(2, me->mr->current-1);
-
- me->medge[i].flag= me->mr->edge_flags[ndx];
- me->medge[i].crease= me->mr->edge_creases[ndx];
+ for(i = 0; i < 4; ++i) {
+ for(j = 0; j < 4; ++j) {
+ if(v[i] == faces[n1->index].v[j])
+ fnd[i] = 1;
+ }
}
+
+ if(fnd[0] && fnd[1] && fnd[2] && fnd[3])
+ return &faces[n1->index];
}
- multires_customdata_to_mesh(me, em, lvl, &me->mr->vdata, em ? &em->vdata : &me->vdata, CD_MDEFORMVERT);
- multires_customdata_to_mesh(me, em, lvl, &me->mr->fdata, em ? &em->fdata : &me->fdata, CD_MTFACE);
+ return NULL;
+}
- /* Colors */
- if(me->mr->use_col) {
- CustomData *src= &me->fdata;
-
- if(me->mr->use_col) me->mcol= CustomData_add_layer(src, CD_MCOL, CD_CALLOC, NULL, me->totface);
-
- for(i=0; i<lvl->totface; ++i) {
- if(me->mr->use_col)
- multires_to_mcol(&lvl->colfaces[i], &me->mcol[i*4]);
+static MultiresEdge *find_old_edge(ListBase *map, MultiresEdge *edges, int v1, int v2)
+{
+ IndexNode *n1, *n2;
+
+ for(n1 = map[v1].first; n1; n1 = n1->next) {
+ for(n2 = map[v2].first; n2; n2 = n2->next) {
+ if(n1->index == n2->index)
+ return &edges[n1->index];
}
-
}
-
- mesh_update_customdata_pointers(me);
-
- multires_edge_level_update(ob,me);
- DAG_object_flush_update(G.scene, ob, OB_RECALC_DATA);
- mesh_calc_normals(me->mvert, me->totvert, me->mface, me->totface, NULL);
+
+ return NULL;
}
-void multires_add_level(Object *ob, Mesh *me, const char subdiv_type)
+static void multires_load_old_edges(ListBase **emap, MultiresLevel *lvl, int *vvmap, int dst, int v1, int v2, int mov)
{
- int i,j, curf, cure;
- MultiresLevel *lvl= NULL;
- MultiApplyData data;
- MVert *oldverts= NULL;
-
- lvl= MEM_callocN(sizeof(MultiresLevel), "multireslevel");
- if(me->pv) mesh_pmv_off(ob, me);
-
- check_colors(me);
- multires_update_levels(me, 0);
-
- ++me->mr->level_count;
- BLI_addtail(&me->mr->levels,lvl);
-
- /* Create vertices
- =============== */
- lvl->totvert= lvl->prev->totvert + lvl->prev->totedge + lvl->prev->totface;
- oldverts= me->mr->verts;
- me->mr->verts= MEM_callocN(sizeof(MVert)*lvl->totvert, "multitres verts");
- /* Copy old verts */
- for(i=0; i<lvl->prev->totvert; ++i)
- me->mr->verts[i]= oldverts[i];
- /* Create new edge verts */
- for(i=0; i<lvl->prev->totedge; ++i) {
- VecMidf(me->mr->verts[lvl->prev->totvert + i].co,
- oldverts[lvl->prev->edges[i].v[0]].co,
- oldverts[lvl->prev->edges[i].v[1]].co);
- lvl->prev->edges[i].mid= lvl->prev->totvert + i;
- }
- /* Create new face verts */
- for(i=0; i<lvl->prev->totface; ++i) {
- lvl->prev->faces[i].mid= lvl->prev->totvert + lvl->prev->totedge + i;
+ int emid = find_old_edge(emap[2], lvl->edges, v1, v2)->mid;
+ vvmap[dst + mov] = emid;
+
+ if(lvl->next->next) {
+ multires_load_old_edges(emap + 1, lvl->next, vvmap, dst + mov, v1, emid, mov / 2);
+ multires_load_old_edges(emap + 1, lvl->next, vvmap, dst + mov, v2, emid, -mov / 2);
}
+}
- multires_calc_temp_data(lvl->prev);
+static void multires_load_old_faces(ListBase **fmap, ListBase **emap, MultiresLevel *lvl, int *vvmap, int dst,
+ int v1, int v2, int v3, int v4, int st2, int st3)
+{
+ int fmid;
+ int emid13, emid14, emid23, emid24;
- /* Create faces
- ============ */
- /* Allocate all the new faces (each triangle creates three, and
- each quad creates four */
- lvl->totface= 0;
- for(i=0; i<lvl->prev->totface; ++i)
- lvl->totface+= lvl->prev->faces[i].v[3] ? 4 : 3;
- lvl->faces= MEM_callocN(sizeof(MultiresFace)*lvl->totface,"multires faces");
+ if(lvl && lvl->next) {
+ fmid = find_old_face(fmap[1], lvl->faces, v1, v2, v3, v4)->mid;
+ vvmap[dst] = fmid;
- curf= 0;
- for(i=0; i<lvl->prev->totface; ++i) {
- const int max= lvl->prev->faces[i].v[3] ? 3 : 2;
-
- for(j=0; j<max+1; ++j) {
- lvl->faces[curf].v[0]= find_mid_edge(lvl->prev->vert_edge_map,lvl->prev,
- lvl->prev->faces[i].v[j],
- lvl->prev->faces[i].v[j==0?max:j-1]);
- lvl->faces[curf].v[1]= lvl->prev->faces[i].v[j];
- lvl->faces[curf].v[2]= find_mid_edge(lvl->prev->vert_edge_map,lvl->prev,
- lvl->prev->faces[i].v[j],
- lvl->prev->faces[i].v[j==max?0:j+1]);
- lvl->faces[curf].v[3]= lvl->prev->totvert + lvl->prev->totedge + i;
- lvl->faces[curf].flag= lvl->prev->faces[i].flag;
- lvl->faces[curf].mat_nr= lvl->prev->faces[i].mat_nr;
-
- ++curf;
- }
- }
+ emid13 = find_old_edge(emap[1], lvl->edges, v1, v3)->mid;
+ emid14 = find_old_edge(emap[1], lvl->edges, v1, v4)->mid;
+ emid23 = find_old_edge(emap[1], lvl->edges, v2, v3)->mid;
+ emid24 = find_old_edge(emap[1], lvl->edges, v2, v4)->mid;
- /* Create edges
- ============ */
- /* Figure out how many edges to allocate */
- lvl->totedge= lvl->prev->totedge*2;
- for(i=0; i<lvl->prev->totface; ++i)
- lvl->totedge+= lvl->prev->faces[i].v[3]?4:3;
- lvl->edges= MEM_callocN(sizeof(MultiresEdge)*lvl->totedge,"multires edges");
-
- for(i=0; i<lvl->prev->totedge; ++i) {
- lvl->edges[i*2].v[0]= lvl->prev->edges[i].v[0];
- lvl->edges[i*2].v[1]= lvl->prev->edges[i].mid;
- lvl->edges[i*2+1].v[0]= lvl->prev->edges[i].mid;
- lvl->edges[i*2+1].v[1]= lvl->prev->edges[i].v[1];
- }
- /* Add edges inside of old polygons */
- curf= 0;
- cure= lvl->prev->totedge*2;
- for(i=0; i<lvl->prev->totface; ++i) {
- for(j=0; j<(lvl->prev->faces[i].v[3]?4:3); ++j) {
- lvl->edges[cure].v[0]= lvl->faces[curf].v[2];
- lvl->edges[cure].v[1]= lvl->faces[curf].v[3];
- ++cure;
- ++curf;
+
+ multires_load_old_faces(fmap + 1, emap + 1, lvl->next, vvmap, dst + st2 * st3 + st3,
+ fmid, v2, emid23, emid24, st2, st3 / 2);
+
+ multires_load_old_faces(fmap + 1, emap + 1, lvl->next, vvmap, dst - st2 * st3 + st3,
+ emid14, emid24, fmid, v4, st2, st3 / 2);
+
+ multires_load_old_faces(fmap + 1, emap + 1, lvl->next, vvmap, dst + st2 * st3 - st3,
+ emid13, emid23, v3, fmid, st2, st3 / 2);
+
+ multires_load_old_faces(fmap + 1, emap + 1, lvl->next, vvmap, dst - st2 * st3 - st3,
+ v1, fmid, emid13, emid14, st2, st3 / 2);
+
+ if(lvl->next->next) {
+ multires_load_old_edges(emap, lvl->next, vvmap, dst, emid24, fmid, st3);
+ multires_load_old_edges(emap, lvl->next, vvmap, dst, emid13, fmid, -st3);
+ multires_load_old_edges(emap, lvl->next, vvmap, dst, emid14, fmid, -st2 * st3);
+ multires_load_old_edges(emap, lvl->next, vvmap, dst, emid23, fmid, st2 * st3);
}
}
+}
- /* Smooth vertices
- =============== */
- for(i=0; i<lvl->prev->totface; ++i) {
- const MultiresFace *f= &lvl->prev->faces[i];
- data.corner1= oldverts[f->v[0]].co;
- data.corner2= oldverts[f->v[1]].co;
- data.corner3= oldverts[f->v[2]].co;
- data.corner4= oldverts[f->v[3]].co;
- data.quad= f->v[3] ? 1 : 0;
- multi_apply(me->mr->verts[f->mid].co, &data, 3, catmullclark_smooth_face);
+/* Loads a multires object stored in the old Multires struct into the new format */
+void multires_load_old(DerivedMesh *dm, Multires *mr)
+{
+ MultiresLevel *lvl, *lvl1;
+ MVert *vsrc, *vdst;
+ int src, dst;
+ int totlvl = MultiresDM_get_totlvl(dm);
+ int st = multires_side_tot[totlvl - 2] - 1;
+ int extedgelen = multires_side_tot[totlvl - 1] - 2;
+ int *vvmap; // inorder for dst, map to src
+ int crossedgelen;
+ int i, j, s, x, totvert, tottri, totquad;
+
+ src = 0;
+ dst = 0;
+ vsrc = mr->verts;
+ vdst = CDDM_get_verts(dm);
+ totvert = dm->getNumVerts(dm);
+ vvmap = MEM_callocN(sizeof(int) * totvert, "multires vvmap");
+
+ lvl1 = mr->levels.first;
+ /* Load base verts */
+ for(i = 0; i < lvl1->totvert; ++i) {
+ vvmap[totvert - lvl1->totvert + i] = src;
+ ++src;
}
- if(subdiv_type == 0) {
- for(i=0; i<lvl->prev->totedge; ++i) {
- const MultiresEdge *e= &lvl->prev->edges[i];
- data.boundary= lvl->prev->edge_boundary_states[i];
- edge_face_neighbor_midpoints_accum(&data,lvl->prev, me->mr->verts, sizeof(MVert),e);
- data.endpoint1= oldverts[e->v[0]].co;
- data.endpoint2= oldverts[e->v[1]].co;
- multi_apply(me->mr->verts[e->mid].co, &data, 3, catmullclark_smooth_edge);
- }
-
- for(i=0; i<lvl->prev->totvert; ++i) {
- data.boundary= multires_vert_is_boundary(lvl->prev,i);
- data.original= oldverts[i].co;
- data.edge_count= BLI_countlist(&lvl->prev->vert_edge_map[i]);
- if(data.boundary)
- boundary_edges_average(&data,lvl->prev, oldverts, sizeof(MVert),i);
- else {
- vert_face_neighbor_midpoints_average(&data,lvl->prev, me->mr->verts,
- sizeof(MVert),i);
- vert_edge_neighbor_midpoints_average(&data,lvl->prev, oldverts,
- sizeof(MVert),i);
- }
- multi_apply(me->mr->verts[i].co, &data, 3, catmullclark_smooth_vert);
+ /* Original edges */
+ dst = totvert - lvl1->totvert - extedgelen * lvl1->totedge;
+ for(i = 0; i < lvl1->totedge; ++i) {
+ int ldst = dst + extedgelen * i;
+ int lsrc = src;
+ lvl = lvl1->next;
+
+ for(j = 2; j <= mr->level_count; ++j) {
+ int base = multires_side_tot[totlvl - j] - 2;
+ int skip = multires_side_tot[totlvl - j + 1] - 1;
+ int st = multires_side_tot[j - 2] - 1;
+
+ for(x = 0; x < st; ++x)
+ vvmap[ldst + base + x * skip] = lsrc + st * i + x;
+
+ lsrc += lvl->totvert - lvl->prev->totvert;
+ lvl = lvl->next;
}
}
- multires_free_temp_data(lvl->prev);
- MEM_freeN(oldverts);
-
- /* Vertex Colors
- ============= */
- curf= 0;
- if(me->mr->use_col) {
- MultiresColFace *cf= MEM_callocN(sizeof(MultiresColFace)*lvl->totface,"Multirescolfaces");
- lvl->colfaces= cf;
- for(i=0; i<lvl->prev->totface; ++i) {
- const char sides= lvl->prev->faces[i].v[3]?4:3;
- MultiresCol cntr;
-
- /* Find average color of 4 (or 3 for triangle) verts */
- multires_col_avg(&cntr,lvl->prev->colfaces[i].col,sides);
-
- for(j=0; j<sides; ++j) {
- multires_col_avg2(&cf->col[0],
- &lvl->prev->colfaces[i].col[j],
- &lvl->prev->colfaces[i].col[j==0?sides-1:j-1]);
- cf->col[1]= lvl->prev->colfaces[i].col[j];
- multires_col_avg2(&cf->col[2],
- &lvl->prev->colfaces[i].col[j],
- &lvl->prev->colfaces[i].col[j==sides-1?0:j+1]);
- cf->col[3]= cntr;
-
- ++cf;
- }
- }
+ /* Center points */
+ dst = 0;
+ for(i = 0; i < lvl1->totface; ++i) {
+ int sides = lvl1->faces[i].v[3] ? 4 : 3;
+
+ vvmap[dst] = src + lvl1->totedge + i;
+ dst += 1 + sides * (st - 1) * st;
}
- me->mr->newlvl= me->mr->level_count;
- me->mr->current= me->mr->newlvl;
- /* Unless the render level has been set to something other than the
- highest level (by the user), increment the render level to match
- the highest available level */
- if(me->mr->renderlvl == me->mr->level_count - 1) me->mr->renderlvl= me->mr->level_count;
- multires_level_to_mesh(ob, me, 0);
-}
+ /* The rest is only for level 3 and up */
+ if(lvl1->next && lvl1->next->next) {
+ ListBase **fmap, **emap;
+ IndexNode **fmem, **emem;
-void multires_set_level(Object *ob, Mesh *me, const int render)
-{
- if(me->pv) mesh_pmv_off(ob, me);
+ /* Face edge cross */
+ tottri = totquad = 0;
+ crossedgelen = multires_side_tot[totlvl - 2] - 2;
+ dst = 0;
+ for(i = 0; i < lvl1->totface; ++i) {
+ int sides = lvl1->faces[i].v[3] ? 4 : 3;
- check_colors(me);
- multires_update_levels(me, render);
+ lvl = lvl1->next->next;
+ ++dst;
- me->mr->current= me->mr->newlvl;
- if(me->mr->current<1) me->mr->current= 1;
- else if(me->mr->current>me->mr->level_count) me->mr->current= me->mr->level_count;
+ for(j = 3; j <= mr->level_count; ++j) {
+ int base = multires_side_tot[totlvl - j] - 2;
+ int skip = multires_side_tot[totlvl - j + 1] - 1;
+ int st = pow(2, j - 2);
+ int st2 = pow(2, j - 3);
+ int lsrc = lvl->prev->totvert;
- multires_level_to_mesh(ob, me, render);
-}
+ /* Skip exterior edge verts */
+ lsrc += lvl1->totedge * st;
-/* Update the edge visibility flags to only show edges on or below the edgelvl */
-void multires_edge_level_update(Object *ob, Mesh *me)
-{
- if(!G.obedit) {
- MultiresLevel *cr_lvl= BLI_findlink(&me->mr->levels,me->mr->current-1);
- MultiresLevel *edge_lvl= BLI_findlink(&me->mr->levels,me->mr->edgelvl-1);
- const int threshold= edge_lvl->totedge * pow(2, me->mr->current - me->mr->edgelvl);
- unsigned i;
-
- for(i=0; i<cr_lvl->totedge; ++i) {
- const int ndx= me->pv ? me->pv->edge_map[i] : i;
- if(ndx != -1) { /* -1= hidden edge */
- if(me->mr->edgelvl >= me->mr->current || i<threshold)
- me->medge[ndx].flag |= ME_EDGEDRAW | ME_EDGERENDER;
- else
- me->medge[ndx].flag &= ~ME_EDGEDRAW & ~ME_EDGERENDER;
+ /* Skip earlier face edge crosses */
+ lsrc += st2 * (tottri * 3 + totquad * 4);
+
+ for(s = 0; s < sides; ++s) {
+ for(x = 0; x < st2; ++x) {
+ vvmap[dst + crossedgelen * (s + 1) - base - x * skip - 1] = lsrc;
+ ++lsrc;
+ }
+ }
+
+ lvl = lvl->next;
}
+
+ dst += sides * (st - 1) * st;
+
+ if(sides == 4) ++totquad;
+ else ++tottri;
+
}
-
- DAG_object_flush_update(G.scene, ob, OB_RECALC_DATA);
+
+ /* calculate vert to edge/face maps for each level (except the last) */
+ fmap = MEM_callocN(sizeof(ListBase*) * (mr->level_count-1), "multires fmap");
+ emap = MEM_callocN(sizeof(ListBase*) * (mr->level_count-1), "multires emap");
+ fmem = MEM_callocN(sizeof(IndexNode*) * (mr->level_count-1), "multires fmem");
+ emem = MEM_callocN(sizeof(IndexNode*) * (mr->level_count-1), "multires emem");
+ lvl = lvl1;
+ for(i = 0; i < mr->level_count - 1; ++i) {
+ create_old_vert_face_map(fmap + i, fmem + i, lvl->faces, lvl->totvert, lvl->totface);
+ create_old_vert_edge_map(emap + i, emem + i, lvl->edges, lvl->totvert, lvl->totedge);
+ lvl = lvl->next;
+ }
+
+ /* Interior face verts */
+ lvl = lvl1->next->next;
+ dst = 0;
+ for(j = 0; j < lvl1->totface; ++j) {
+ int sides = lvl1->faces[j].v[3] ? 4 : 3;
+ int ldst = dst + 1 + sides * (st - 1);
+
+ for(s = 0; s < sides; ++s) {
+ int st2 = multires_side_tot[totlvl - 2] - 2;
+ int st3 = multires_side_tot[totlvl - 3] - 2;
+ int st4 = st3 == 0 ? 1 : (st3 + 1) / 2;
+ int mid = ldst + st2 * st3 + st3;
+ int cv = lvl1->faces[j].v[s];
+ int nv = lvl1->faces[j].v[s == sides - 1 ? 0 : s + 1];
+ int pv = lvl1->faces[j].v[s == 0 ? sides - 1 : s - 1];
+
+ multires_load_old_faces(fmap, emap, lvl1->next, vvmap, mid,
+ vvmap[dst], cv,
+ find_old_edge(emap[0], lvl1->edges, pv, cv)->mid,
+ find_old_edge(emap[0], lvl1->edges, cv, nv)->mid,
+ st2, st4);
+
+ ldst += (st - 1) * (st - 1);
+ }
+
+
+ dst = ldst;
+ }
+
+ lvl = lvl->next;
+
+ for(i = 0; i < mr->level_count - 1; ++i) {
+ MEM_freeN(fmap[i]);
+ MEM_freeN(fmem[i]);
+ MEM_freeN(emap[i]);
+ MEM_freeN(emem[i]);
+ }
+
+ MEM_freeN(fmap);
+ MEM_freeN(emap);
+ MEM_freeN(fmem);
+ MEM_freeN(emem);
}
+
+ /* Transfer verts */
+ for(i = 0; i < totvert; ++i)
+ VecCopyf(vdst[i].co, vsrc[vvmap[i]].co);
+
+ MEM_freeN(vvmap);
}
diff --git a/source/blender/blenkernel/intern/scene.c b/source/blender/blenkernel/intern/scene.c
index 1727edc10fc..486146ad37c 100644
--- a/source/blender/blenkernel/intern/scene.c
+++ b/source/blender/blenkernel/intern/scene.c
@@ -710,7 +710,6 @@ void sculptsession_free(Scene *sce)
}
}
-/* Default curve approximates 0.5 * (cos(pi * x) + 1), with 0 <= x <= 1 */
void sculpt_reset_curve(SculptData *sd)
{
CurveMap *cm = NULL;
@@ -722,21 +721,15 @@ void sculpt_reset_curve(SculptData *sd)
if(cm->curve)
MEM_freeN(cm->curve);
- cm->curve= MEM_callocN(6*sizeof(CurveMapPoint), "curve points");
+ cm->curve= MEM_callocN(3*sizeof(CurveMapPoint), "curve points");
cm->flag &= ~CUMA_EXTEND_EXTRAPOLATE;
- cm->totpoint= 6;
+ cm->totpoint= 3;
cm->curve[0].x= 0;
cm->curve[0].y= 1;
- cm->curve[1].x= 0.1;
- cm->curve[1].y= 0.97553;
- cm->curve[2].x= 0.3;
- cm->curve[2].y= 0.79389;
- cm->curve[3].x= 0.9;
- cm->curve[3].y= 0.02447;
- cm->curve[4].x= 0.7;
- cm->curve[4].y= 0.20611;
- cm->curve[5].x= 1;
- cm->curve[5].y= 0;
+ cm->curve[1].x= 0.33;
+ cm->curve[1].y= 0.33;
+ cm->curve[2].x= 1;
+ cm->curve[2].y= 0;
curvemapping_changed(sd->cumap, 0);
}
diff --git a/source/blender/blenkernel/intern/shrinkwrap.c b/source/blender/blenkernel/intern/shrinkwrap.c
deleted file mode 100644
index ab98fb1f007..00000000000
--- a/source/blender/blenkernel/intern/shrinkwrap.c
+++ /dev/null
@@ -1,599 +0,0 @@
-/**
- * shrinkwrap.c
- *
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
- *
- * The Original Code is Copyright (C) Blender Foundation.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): André Pinto
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-#include <string.h>
-#include <float.h>
-#include <math.h>
-#include <memory.h>
-#include <stdio.h>
-#include <time.h>
-#include <assert.h>
-
-#include "DNA_object_types.h"
-#include "DNA_modifier_types.h"
-#include "DNA_meshdata_types.h"
-#include "DNA_mesh_types.h"
-
-#include "BKE_shrinkwrap.h"
-#include "BKE_DerivedMesh.h"
-#include "BKE_lattice.h"
-#include "BKE_utildefines.h"
-#include "BKE_deform.h"
-#include "BKE_cdderivedmesh.h"
-#include "BKE_displist.h"
-#include "BKE_global.h"
-#include "BKE_subsurf.h"
-
-#include "BLI_arithb.h"
-#include "BLI_kdtree.h"
-#include "BLI_kdopbvh.h"
-
-#include "RE_raytrace.h"
-#include "MEM_guardedalloc.h"
-
-
-/* Util macros */
-#define TO_STR(a) #a
-#define JOIN(a,b) a##b
-
-#define OUT_OF_MEMORY() ((void)printf("Shrinkwrap: Out of memory\n"))
-
-/* Benchmark macros */
-#if !defined(_WIN32) && 0
-
-#include <sys/time.h>
-
-#define BENCH(a) \
- do { \
- double _t1, _t2; \
- struct timeval _tstart, _tend; \
- clock_t _clock_init = clock(); \
- gettimeofday ( &_tstart, NULL); \
- (a); \
- gettimeofday ( &_tend, NULL); \
- _t1 = ( double ) _tstart.tv_sec + ( double ) _tstart.tv_usec/ ( 1000*1000 ); \
- _t2 = ( double ) _tend.tv_sec + ( double ) _tend.tv_usec/ ( 1000*1000 ); \
- printf("%s: %fs (real) %fs (cpu)\n", #a, _t2-_t1, (float)(clock()-_clock_init)/CLOCKS_PER_SEC);\
- } while(0)
-
-#else
-
-#define BENCH(a) (a)
-
-#endif
-
-typedef void ( *Shrinkwrap_ForeachVertexCallback) (DerivedMesh *target, float *co, float *normal);
-
-/* get derived mesh */
-//TODO is anyfunction that does this? returning the derivedFinal witouth we caring if its in edit mode or not?
-DerivedMesh *object_get_derived_final(Object *ob, CustomDataMask dataMask)
-{
- if (ob==G.obedit)
- {
- DerivedMesh *final = NULL;
- editmesh_get_derived_cage_and_final(&final, dataMask);
- return final;
- }
- else
- return mesh_get_derived_final(ob, dataMask);
-}
-
-/* Space transform */
-void space_transform_from_matrixs(SpaceTransform *data, float local[4][4], float target[4][4])
-{
- float itarget[4][4];
- Mat4Invert(itarget, target);
- Mat4MulSerie(data->local2target, itarget, local, 0, 0, 0, 0, 0, 0);
- Mat4Invert(data->target2local, data->local2target);
-}
-
-void space_transform_apply(const SpaceTransform *data, float *co)
-{
- VecMat4MulVecfl(co, ((SpaceTransform*)data)->local2target, co);
-}
-
-void space_transform_invert(const SpaceTransform *data, float *co)
-{
- VecMat4MulVecfl(co, ((SpaceTransform*)data)->target2local, co);
-}
-
-void space_transform_apply_normal(const SpaceTransform *data, float *no)
-{
- Mat4Mul3Vecfl( ((SpaceTransform*)data)->local2target, no);
- Normalize(no); // TODO: could we just determine de scale value from the matrix?
-}
-
-void space_transform_invert_normal(const SpaceTransform *data, float *no)
-{
- Mat4Mul3Vecfl(((SpaceTransform*)data)->target2local, no);
- Normalize(no); // TODO: could we just determine de scale value from the matrix?
-}
-
-/*
- * Returns the squared distance between two given points
- */
-static float squared_dist(const float *a, const float *b)
-{
- float tmp[3];
- VECSUB(tmp, a, b);
- return INPR(tmp, tmp);
-}
-
-/* Main shrinkwrap function */
-void shrinkwrapModifier_deform(ShrinkwrapModifierData *smd, Object *ob, DerivedMesh *dm, float (*vertexCos)[3], int numVerts)
-{
-
- ShrinkwrapCalcData calc = NULL_ShrinkwrapCalcData;
-
- //remove loop dependencies on derived meshs (TODO should this be done elsewhere?)
- if(smd->target == ob) smd->target = NULL;
- if(smd->auxTarget == ob) smd->auxTarget = NULL;
-
-
- //Configure Shrinkwrap calc data
- calc.smd = smd;
- calc.ob = ob;
- calc.original = dm;
- calc.numVerts = numVerts;
- calc.vertexCos = vertexCos;
-
- //DeformVertex
- calc.vgroup = get_named_vertexgroup_num(calc.ob, calc.smd->vgroup_name);
- if(calc.original)
- {
- calc.dvert = calc.original->getVertDataArray(calc.original, CD_MDEFORMVERT);
- }
- else if(calc.ob->type == OB_LATTICE)
- {
- calc.dvert = lattice_get_deform_verts(calc.ob);
- }
-
-
- if(smd->target)
- {
- //TODO currently we need a copy in case object_get_derived_final returns an emDM that does not defines getVertArray or getFace array
- calc.target = CDDM_copy( object_get_derived_final(smd->target, CD_MASK_BAREMESH) );
-
- //TODO there might be several "bugs" on non-uniform scales matrixs.. because it will no longer be nearest surface, not sphere projection
- //because space has been deformed
- space_transform_setup(&calc.local2target, ob, smd->target);
-
- calc.keepDist = smd->keepDist; //TODO: smd->keepDist is in global units.. must change to local
- }
-
-
- //Projecting target defined - lets work!
- if(calc.target)
- {
- switch(smd->shrinkType)
- {
- case MOD_SHRINKWRAP_NEAREST_SURFACE:
- BENCH(shrinkwrap_calc_nearest_surface_point(&calc));
- break;
-
- case MOD_SHRINKWRAP_PROJECT:
- BENCH(shrinkwrap_calc_normal_projection(&calc));
- break;
-
- case MOD_SHRINKWRAP_NEAREST_VERTEX:
- BENCH(shrinkwrap_calc_nearest_vertex(&calc));
- break;
- }
- }
-
- //free memory
- if(calc.target)
- calc.target->release( calc.target );
-}
-
-/*
- * Shrinkwrap to the nearest vertex
- *
- * it builds a kdtree of vertexs we can attach to and then
- * for each vertex performs a nearest vertex search on the tree
- */
-void shrinkwrap_calc_nearest_vertex(ShrinkwrapCalcData *calc)
-{
- int i;
-
- BVHTreeFromMesh treeData = NULL_BVHTreeFromMesh;
- BVHTreeNearest nearest = NULL_BVHTreeNearest;
-
-
- BENCH(bvhtree_from_mesh_verts(&treeData, calc->target, 0.0, 2, 6));
- if(treeData.tree == NULL)
- {
- OUT_OF_MEMORY();
- return;
- }
-
- //Setup nearest
- nearest.index = -1;
- nearest.dist = FLT_MAX;
-
-#pragma omp parallel for default(none) private(i) firstprivate(nearest) shared(treeData,calc) schedule(static)
- for(i = 0; i<calc->numVerts; ++i)
- {
- float *co = calc->vertexCos[i];
- float tmp_co[3];
- float weight = vertexgroup_get_vertex_weight(calc->dvert, i, calc->vgroup);
- if(weight == 0.0f) continue;
-
- VECCOPY(tmp_co, co);
- space_transform_apply(&calc->local2target, tmp_co); //Convert the coordinates to the tree coordinates
-
- //Use local proximity heuristics (to reduce the nearest search)
- //
- //If we already had an hit before.. we assume this vertex is going to have a close hit to that other vertex
- //so we can initiate the "nearest.dist" with the expected value to that last hit.
- //This will lead in prunning of the search tree.
- if(nearest.index != -1)
- nearest.dist = squared_dist(tmp_co, nearest.co);
- else
- nearest.dist = FLT_MAX;
-
- BLI_bvhtree_find_nearest(treeData.tree, tmp_co, &nearest, treeData.nearest_callback, &treeData);
-
-
- //Found the nearest vertex
- if(nearest.index != -1)
- {
- //Adjusting the vertex weight, so that after interpolating it keeps a certain distance from the nearest position
- float dist = sasqrt(nearest.dist);
- if(dist > FLT_EPSILON) weight *= (dist - calc->keepDist)/dist;
-
- //Convert the coordinates back to mesh coordinates
- VECCOPY(tmp_co, nearest.co);
- space_transform_invert(&calc->local2target, tmp_co);
-
- VecLerpf(co, co, tmp_co, weight); //linear interpolation
- }
- }
-
- free_bvhtree_from_mesh(&treeData);
-}
-
-/*
- * This function raycast a single vertex and updates the hit if the "hit" is considered valid.
- * Returns TRUE if "hit" was updated.
- * Opts control whether an hit is valid or not
- * Supported options are:
- * MOD_SHRINKWRAP_CULL_TARGET_FRONTFACE (front faces hits are ignored)
- * MOD_SHRINKWRAP_CULL_TARGET_BACKFACE (back faces hits are ignored)
- */
-int normal_projection_project_vertex(char options, const float *vert, const float *dir, const SpaceTransform *transf, BVHTree *tree, BVHTreeRayHit *hit, BVHTree_RayCastCallback callback, void *userdata)
-{
- float tmp_co[3], tmp_no[3];
- const float *co, *no;
- BVHTreeRayHit hit_tmp;
-
- //Copy from hit (we need to convert hit rays from one space coordinates to the other
- memcpy( &hit_tmp, hit, sizeof(hit_tmp) );
-
- //Apply space transform (TODO readjust dist)
- if(transf)
- {
- VECCOPY( tmp_co, vert );
- space_transform_apply( transf, tmp_co );
- co = tmp_co;
-
- VECCOPY( tmp_no, dir );
- space_transform_apply_normal( transf, tmp_no );
- no = tmp_no;
-
- hit_tmp.dist *= Mat4ToScalef( ((SpaceTransform*)transf)->local2target );
- }
- else
- {
- co = vert;
- no = dir;
- }
-
- hit_tmp.index = -1;
-
- BLI_bvhtree_ray_cast(tree, co, no, 0.0f, &hit_tmp, callback, userdata);
-
- if(hit_tmp.index != -1)
- {
- float dot = INPR( dir, hit_tmp.no);
-
- if(((options & MOD_SHRINKWRAP_CULL_TARGET_FRONTFACE) && dot <= 0.0f)
- || ((options & MOD_SHRINKWRAP_CULL_TARGET_BACKFACE) && dot >= 0.0f))
- return FALSE; //Ignore hit
-
-
- //Inverting space transform (TODO make coeherent with the initial dist readjust)
- if(transf)
- {
- space_transform_invert( transf, hit_tmp.co );
- space_transform_invert_normal( transf, hit_tmp.no );
-
- hit_tmp.dist = VecLenf( (float*)vert, hit_tmp.co );
- }
-
- memcpy(hit, &hit_tmp, sizeof(hit_tmp) );
- return TRUE;
- }
- return FALSE;
-}
-
-
-void shrinkwrap_calc_normal_projection(ShrinkwrapCalcData *calc)
-{
- int i;
-
- //Options about projection direction
- const char use_normal = calc->smd->shrinkOpts;
- float proj_axis[3] = {0.0f, 0.0f, 0.0f};
- MVert *vert = NULL; //Needed in case of vertex normal
- DerivedMesh* ss_mesh = NULL;
-
- //Raycast and tree stuff
- BVHTreeRayHit hit;
- BVHTreeFromMesh treeData = NULL_BVHTreeFromMesh; //target
-
- //auxiliar target
- DerivedMesh * aux_mesh = NULL;
- BVHTreeFromMesh auxData= NULL_BVHTreeFromMesh;
- SpaceTransform local2aux;
-
-do
-{
-
- //Prepare data to retrieve the direction in which we should project each vertex
- if(calc->smd->projAxis == MOD_SHRINKWRAP_PROJECT_OVER_NORMAL)
- {
- //No Mvert information: jump to "free memory and return" part
- if(calc->original == NULL) break;
-
- if(calc->smd->subsurfLevels)
- {
- SubsurfModifierData smd;
- memset(&smd, 0, sizeof(smd));
- smd.subdivType = ME_CC_SUBSURF; //catmull clark
- smd.levels = calc->smd->subsurfLevels; //levels
-
- ss_mesh = subsurf_make_derived_from_derived(calc->original, &smd, FALSE, NULL, 0, 0);
-
- if(ss_mesh)
- {
- vert = ss_mesh->getVertDataArray(ss_mesh, CD_MVERT);
- if(vert)
- {
- //TRICKY: this code assumes subsurface will have the transformed original vertices
- //in their original order at the end of the vert array.
- vert = vert
- + ss_mesh->getNumVerts(ss_mesh)
- - calc->original->getNumVerts(calc->original);
- }
- }
-
- //To make sure we are not letting any memory behind
- assert(smd.emCache == NULL);
- assert(smd.mCache == NULL);
- }
- else
- vert = calc->original->getVertDataArray(calc->original, CD_MVERT);
-
- //Not able to get vert information: jump to "free memory and return" part
- if(vert == NULL) break;
- }
- else
- {
- //The code supports any axis that is a combination of X,Y,Z.. altought currently UI only allows to set the 3 diferent axis
- if(calc->smd->projAxis & MOD_SHRINKWRAP_PROJECT_OVER_X_AXIS) proj_axis[0] = 1.0f;
- if(calc->smd->projAxis & MOD_SHRINKWRAP_PROJECT_OVER_Y_AXIS) proj_axis[1] = 1.0f;
- if(calc->smd->projAxis & MOD_SHRINKWRAP_PROJECT_OVER_Z_AXIS) proj_axis[2] = 1.0f;
-
- Normalize(proj_axis);
-
- //Invalid projection direction: jump to "free memory and return" part
- if(INPR(proj_axis, proj_axis) < FLT_EPSILON) break;
- }
-
- //If the user doesn't allows to project in any direction of projection axis... then theres nothing todo.
- if((use_normal & (MOD_SHRINKWRAP_PROJECT_ALLOW_POS_DIR | MOD_SHRINKWRAP_PROJECT_ALLOW_NEG_DIR)) == 0)
- break; //jump to "free memory and return" part
-
-
- //Build target tree
- BENCH(bvhtree_from_mesh_faces(&treeData, calc->target, calc->keepDist, 4, 6));
- if(treeData.tree == NULL)
- break; //jump to "free memory and return" part
-
-
- //Build auxiliar target
- if(calc->smd->auxTarget)
- {
- space_transform_setup( &local2aux, calc->ob, calc->smd->auxTarget);
-
- aux_mesh = CDDM_copy( object_get_derived_final(calc->smd->auxTarget, CD_MASK_BAREMESH) ); //TODO currently we need a copy in case object_get_derived_final returns an emDM that does not defines getVertArray or getFace array
- if(aux_mesh)
- BENCH(bvhtree_from_mesh_faces(&auxData, aux_mesh, 0.0, 4, 6));
- else
- printf("Auxiliar target finalDerived mesh is null\n");
- }
-
-
- //Now, everything is ready to project the vertexs!
-#pragma omp parallel for private(i,hit) schedule(static)
- for(i = 0; i<calc->numVerts; ++i)
- {
- float *co = calc->vertexCos[i];
- float tmp_co[3], tmp_no[3];
- float lim = 10000.0f; //TODO: we should use FLT_MAX here, but sweepsphere code isnt prepared for that
- float weight = vertexgroup_get_vertex_weight(calc->dvert, i, calc->vgroup);
-
- if(weight == 0.0f) continue;
-
- if(ss_mesh)
- {
- VECCOPY(tmp_co, vert[i].co);
- }
- else
- {
- VECCOPY(tmp_co, co);
- }
-
-
- if(vert)
- NormalShortToFloat(tmp_no, vert[i].no);
- else
- VECCOPY( tmp_no, proj_axis );
-
-
- hit.index = -1;
- hit.dist = lim;
-
-
- //Project over positive direction of axis
- if(use_normal & MOD_SHRINKWRAP_PROJECT_ALLOW_POS_DIR)
- {
-
- if(auxData.tree)
- normal_projection_project_vertex(0, tmp_co, tmp_no, &local2aux, auxData.tree, &hit, auxData.raycast_callback, &auxData);
-
- normal_projection_project_vertex(calc->smd->shrinkOpts, tmp_co, tmp_no, &calc->local2target, treeData.tree, &hit, treeData.raycast_callback, &treeData);
- }
-
- //Project over negative direction of axis
- if(use_normal & MOD_SHRINKWRAP_PROJECT_ALLOW_NEG_DIR)
- {
- float inv_no[3] = { -tmp_no[0], -tmp_no[1], -tmp_no[2] };
-
-
- if(auxData.tree)
- normal_projection_project_vertex(0, tmp_co, inv_no, &local2aux, auxData.tree, &hit, auxData.raycast_callback, &auxData);
-
- normal_projection_project_vertex(calc->smd->shrinkOpts, tmp_co, inv_no, &calc->local2target, treeData.tree, &hit, treeData.raycast_callback, &treeData);
- }
-
-
- if(hit.index != -1)
- {
- VecLerpf(co, co, hit.co, weight);
- }
- }
-
-
-//Simple do{} while(0) structure to allow to easily jump to the "free memory and return" part
-} while(0);
-
- //free data structures
-
- free_bvhtree_from_mesh(&treeData);
- free_bvhtree_from_mesh(&auxData);
-
- if(aux_mesh)
- aux_mesh->release(aux_mesh);
-
- if(ss_mesh)
- ss_mesh->release(ss_mesh);
-}
-
-/*
- * Shrinkwrap moving vertexs to the nearest surface point on the target
- *
- * it builds a BVHTree from the target mesh and then performs a
- * NN matchs for each vertex
- */
-void shrinkwrap_calc_nearest_surface_point(ShrinkwrapCalcData *calc)
-{
- int i;
-
- BVHTreeFromMesh treeData = NULL_BVHTreeFromMesh;
- BVHTreeNearest nearest = NULL_BVHTreeNearest;
-
-
-
- //Create a bvh-tree of the given target
- BENCH(bvhtree_from_mesh_faces( &treeData, calc->target, 0.0, 2, 6));
- if(treeData.tree == NULL)
- {
- OUT_OF_MEMORY();
- return;
- }
-
- //Setup nearest
- nearest.index = -1;
- nearest.dist = FLT_MAX;
-
-
- //Find the nearest vertex
-#pragma omp parallel for default(none) private(i) firstprivate(nearest) shared(calc,treeData) schedule(static)
- for(i = 0; i<calc->numVerts; ++i)
- {
- float *co = calc->vertexCos[i];
- float tmp_co[3];
- float weight = vertexgroup_get_vertex_weight(calc->dvert, i, calc->vgroup);
- if(weight == 0.0f) continue;
-
- //Convert the vertex to tree coordinates
- VECCOPY(tmp_co, co);
- space_transform_apply(&calc->local2target, tmp_co);
-
- //Use local proximity heuristics (to reduce the nearest search)
- //
- //If we already had an hit before.. we assume this vertex is going to have a close hit to that other vertex
- //so we can initiate the "nearest.dist" with the expected value to that last hit.
- //This will lead in prunning of the search tree.
- if(nearest.index != -1)
- nearest.dist = squared_dist(tmp_co, nearest.co);
- else
- nearest.dist = FLT_MAX;
-
- BLI_bvhtree_find_nearest(treeData.tree, tmp_co, &nearest, treeData.nearest_callback, &treeData);
-
- //Found the nearest vertex
- if(nearest.index != -1)
- {
- if(calc->smd->shrinkOpts & MOD_SHRINKWRAP_KEEP_ABOVE_SURFACE)
- {
- //Make the vertex stay on the front side of the face
- VECADDFAC(tmp_co, nearest.co, nearest.no, calc->keepDist);
- }
- else
- {
- //Adjusting the vertex weight, so that after interpolating it keeps a certain distance from the nearest position
- float dist = sasqrt( nearest.dist );
- if(dist > FLT_EPSILON)
- VecLerpf(tmp_co, tmp_co, nearest.co, (dist - calc->keepDist)/dist); //linear interpolation
- else
- VECCOPY( tmp_co, nearest.co );
- }
-
- //Convert the coordinates back to mesh coordinates
- space_transform_invert(&calc->local2target, tmp_co);
- VecLerpf(co, co, tmp_co, weight); //linear interpolation
- }
- }
-
-
- free_bvhtree_from_mesh(&treeData);
-}
-
diff --git a/source/blender/blenkernel/intern/simple_deform.c b/source/blender/blenkernel/intern/simple_deform.c
deleted file mode 100644
index 2978a6f7f01..00000000000
--- a/source/blender/blenkernel/intern/simple_deform.c
+++ /dev/null
@@ -1,256 +0,0 @@
-/**
- * deform_simple.c
- *
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
- *
- * The Original Code is Copyright (C) Blender Foundation.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): André Pinto
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-#include "DNA_object_types.h"
-#include "DNA_modifier_types.h"
-#include "DNA_meshdata_types.h"
-
-#include "BKE_simple_deform.h"
-#include "BKE_DerivedMesh.h"
-#include "BKE_lattice.h"
-#include "BKE_deform.h"
-#include "BKE_utildefines.h"
-#include "BLI_arithb.h"
-#include "BKE_shrinkwrap.h"
-
-#include <string.h>
-#include <math.h>
-
-
-//Clamps/Limits the given coordinate to: limits[0] <= co[axis] <= limits[1]
-//The ammount of clamp is saved on dcut
-static void axis_limit(int axis, const float limits[2], float co[3], float dcut[3])
-{
- float val = co[axis];
- if(limits[0] > val) val = limits[0];
- if(limits[1] < val) val = limits[1];
-
- dcut[axis] = co[axis] - val;
- co[axis] = val;
-}
-
-static void simpleDeform_taper(const float factor, const float dcut[3], float *co)
-{
- float x = co[0], y = co[1], z = co[2];
- float scale = z*factor;
-
- co[0] = x + x*scale;
- co[1] = y + y*scale;
- co[2] = z;
-
- if(dcut)
- {
- co[0] += dcut[0];
- co[1] += dcut[1];
- co[2] += dcut[2];
- }
-}
-
-static void simpleDeform_stretch(const float factor, const float dcut[3], float *co)
-{
- float x = co[0], y = co[1], z = co[2];
- float scale;
-
- scale = (z*z*factor-factor + 1.0);
-
- co[0] = x*scale;
- co[1] = y*scale;
- co[2] = z*(1.0+factor);
-
-
- if(dcut)
- {
- co[0] += dcut[0];
- co[1] += dcut[1];
- co[2] += dcut[2];
- }
-}
-
-static void simpleDeform_twist(const float factor, const float *dcut, float *co)
-{
- float x = co[0], y = co[1], z = co[2];
- float theta, sint, cost;
-
- theta = z*factor;
- sint = sin(theta);
- cost = cos(theta);
-
- co[0] = x*cost - y*sint;
- co[1] = x*sint + y*cost;
- co[2] = z;
-
- if(dcut)
- {
- co[0] += dcut[0];
- co[1] += dcut[1];
- co[2] += dcut[2];
- }
-}
-
-static void simpleDeform_bend(const float factor, const float dcut[3], float *co)
-{
- float x = co[0], y = co[1], z = co[2];
- float theta, sint, cost;
-
- theta = x*factor;
- sint = sin(theta);
- cost = cos(theta);
-
- if(fabs(factor) > 1e-7f)
- {
- co[0] = -(y-1.0f/factor)*sint;
- co[1] = (y-1.0f/factor)*cost + 1.0f/factor;
- co[2] = z;
- }
-
-
- if(dcut)
- {
- co[0] += cost*dcut[0];
- co[1] += sint*dcut[0];
- co[2] += dcut[2];
- }
-
-}
-
-
-/* simple deform modifier */
-void SimpleDeformModifier_do(SimpleDeformModifierData *smd, struct Object *ob, struct DerivedMesh *dm, float (*vertexCos)[3], int numVerts)
-{
- static const float lock_axis[2] = {0.0f, 0.0f};
-
- int i;
- int limit_axis = 0;
- float smd_limit[2], smd_factor;
- SpaceTransform *transf = NULL, tmp_transf;
- void (*simpleDeform_callback)(const float factor, const float dcut[3], float *co) = NULL; //Mode callback
- int vgroup = get_named_vertexgroup_num(ob, smd->vgroup_name);
- MDeformVert *dvert = NULL;
-
- //Safe-check
- if(smd->origin == ob) smd->origin = NULL; //No self references
-
- if(smd->limit[0] < 0.0) smd->limit[0] = 0.0f;
- if(smd->limit[0] > 1.0) smd->limit[0] = 1.0f;
-
- smd->limit[0] = MIN2(smd->limit[0], smd->limit[1]); //Upper limit >= than lower limit
-
- //Calculate matrixs do convert between coordinate spaces
- if(smd->origin)
- {
- transf = &tmp_transf;
-
- if(smd->originOpts & MOD_SIMPLEDEFORM_ORIGIN_LOCAL)
- {
- space_transform_from_matrixs(transf, ob->obmat, smd->origin->obmat);
- }
- else
- {
- Mat4CpyMat4(transf->local2target, smd->origin->obmat);
- Mat4Invert(transf->target2local, transf->local2target);
- }
- }
-
- //Setup vars
- limit_axis = (smd->mode == MOD_SIMPLEDEFORM_MODE_BEND) ? 0 : 2; //Bend limits on X.. all other modes limit on Z
-
- //Update limits if needed
- {
- float lower = FLT_MAX;
- float upper = -FLT_MAX;
-
- for(i=0; i<numVerts; i++)
- {
- float tmp[3];
- VECCOPY(tmp, vertexCos[i]);
-
- if(transf) space_transform_apply(transf, tmp);
-
- lower = MIN2(lower, tmp[limit_axis]);
- upper = MAX2(upper, tmp[limit_axis]);
- }
-
-
- //SMD values are normalized to the BV, calculate the absolut values
- smd_limit[1] = lower + (upper-lower)*smd->limit[1];
- smd_limit[0] = lower + (upper-lower)*smd->limit[0];
-
- smd_factor = smd->factor / MAX2(FLT_EPSILON, smd_limit[1]-smd_limit[0]);
- }
-
-
- if(dm)
- {
- dvert = dm->getVertDataArray(dm, CD_MDEFORMVERT);
- }
- else if(ob->type == OB_LATTICE)
- {
- dvert = lattice_get_deform_verts(ob);
- }
-
-
-
- switch(smd->mode)
- {
- case MOD_SIMPLEDEFORM_MODE_TWIST: simpleDeform_callback = simpleDeform_twist; break;
- case MOD_SIMPLEDEFORM_MODE_BEND: simpleDeform_callback = simpleDeform_bend; break;
- case MOD_SIMPLEDEFORM_MODE_TAPER: simpleDeform_callback = simpleDeform_taper; break;
- case MOD_SIMPLEDEFORM_MODE_STRETCH: simpleDeform_callback = simpleDeform_stretch; break;
- default:
- return; //No simpledeform mode?
- }
-
- for(i=0; i<numVerts; i++)
- {
- float weight = vertexgroup_get_vertex_weight(dvert, i, vgroup);
-
- if(weight != 0.0f)
- {
- float co[3], dcut[3] = {0.0f, 0.0f, 0.0f};
-
- if(transf) space_transform_apply(transf, vertexCos[i]);
-
- VECCOPY(co, vertexCos[i]);
-
- //Apply axis limits
- if(smd->mode != MOD_SIMPLEDEFORM_MODE_BEND) //Bend mode shoulnt have any lock axis
- {
- if(smd->axis & MOD_SIMPLEDEFORM_LOCK_AXIS_X) axis_limit(0, lock_axis, co, dcut);
- if(smd->axis & MOD_SIMPLEDEFORM_LOCK_AXIS_Y) axis_limit(1, lock_axis, co, dcut);
- }
- axis_limit(limit_axis, smd_limit, co, dcut);
-
- simpleDeform_callback(smd_factor, dcut, co); //Apply deform
- VecLerpf(vertexCos[i], vertexCos[i], co, weight); //Use vertex weight has coef of linear interpolation
-
- if(transf) space_transform_invert(transf, vertexCos[i]);
- }
- }
-}
-
-
diff --git a/source/blender/blenkernel/intern/subsurf_ccg.c b/source/blender/blenkernel/intern/subsurf_ccg.c
index f79009e673d..72e1e3cd1ab 100644
--- a/source/blender/blenkernel/intern/subsurf_ccg.c
+++ b/source/blender/blenkernel/intern/subsurf_ccg.c
@@ -49,6 +49,7 @@
#include "BKE_utildefines.h"
#include "BKE_global.h"
#include "BKE_mesh.h"
+#include "BKE_multires.h"
#include "BKE_scene.h"
#include "BKE_subsurf.h"
@@ -472,7 +473,7 @@ static void calc_ss_weights(int gridFaces,
static DerivedMesh *ss_to_cdderivedmesh(CCGSubSurf *ss, int ssFromEditmesh,
int drawInteriorEdges, int useSubsurfUv,
- DerivedMesh *dm)
+ DerivedMesh *dm, MultiresSubsurf *ms)
{
DerivedMesh *result;
int edgeSize = ccgSubSurf_getEdgeSize(ss);
@@ -525,14 +526,21 @@ static DerivedMesh *ss_to_cdderivedmesh(CCGSubSurf *ss, int ssFromEditmesh,
}
ccgFaceIterator_free(fi);
- if(dm) {
- result = CDDM_from_template(dm, ccgSubSurf_getNumFinalVerts(ss),
- ccgSubSurf_getNumFinalEdges(ss),
- ccgSubSurf_getNumFinalFaces(ss));
- } else {
- result = CDDM_new(ccgSubSurf_getNumFinalVerts(ss),
- ccgSubSurf_getNumFinalEdges(ss),
- ccgSubSurf_getNumFinalFaces(ss));
+ if(ms) {
+ result = MultiresDM_new(ms, dm, ccgSubSurf_getNumFinalVerts(ss),
+ ccgSubSurf_getNumFinalEdges(ss),
+ ccgSubSurf_getNumFinalFaces(ss));
+ }
+ else {
+ if(dm) {
+ result = CDDM_from_template(dm, ccgSubSurf_getNumFinalVerts(ss),
+ ccgSubSurf_getNumFinalEdges(ss),
+ ccgSubSurf_getNumFinalFaces(ss));
+ } else {
+ result = CDDM_new(ccgSubSurf_getNumFinalVerts(ss),
+ ccgSubSurf_getNumFinalEdges(ss),
+ ccgSubSurf_getNumFinalFaces(ss));
+ }
}
// load verts
@@ -558,11 +566,12 @@ static DerivedMesh *ss_to_cdderivedmesh(CCGSubSurf *ss, int ssFromEditmesh,
++mvert;
++origIndex;
i++;
-
+
for(S = 0; S < numVerts; S++) {
int prevS = (S - 1 + numVerts) % numVerts;
int nextS = (S + 1) % numVerts;
int otherS = (numVerts == 4) ? (S + 2) % numVerts : 3;
+
for(x = 1; x < gridFaces; x++) {
float w[4];
w[prevS] = weight[x][0][0];
@@ -572,6 +581,7 @@ static DerivedMesh *ss_to_cdderivedmesh(CCGSubSurf *ss, int ssFromEditmesh,
DM_interp_vert_data(dm, result, vertIdx, w, numVerts, i);
VecCopyf(mvert->co,
ccgSubSurf_getFaceGridEdgeData(ss, f, S, x));
+
*origIndex = ORIGINDEX_NONE;
++mvert;
++origIndex;
@@ -583,6 +593,7 @@ static DerivedMesh *ss_to_cdderivedmesh(CCGSubSurf *ss, int ssFromEditmesh,
int prevS = (S - 1 + numVerts) % numVerts;
int nextS = (S + 1) % numVerts;
int otherS = (numVerts == 4) ? (S + 2) % numVerts : 3;
+
for(y = 1; y < gridFaces; y++) {
for(x = 1; x < gridFaces; x++) {
float w[4];
@@ -2566,9 +2577,10 @@ static CCGDerivedMesh *getCCGDerivedMesh(CCGSubSurf *ss,
/***/
-struct DerivedMesh *subsurf_make_derived_from_derived(
+struct DerivedMesh *subsurf_make_derived_from_derived_with_multires(
struct DerivedMesh *dm,
struct SubsurfModifierData *smd,
+ struct MultiresSubsurf *ms,
int useRenderParams, float (*vertCos)[3],
int isFinalCalc, int editMode)
{
@@ -2600,7 +2612,7 @@ struct DerivedMesh *subsurf_make_derived_from_derived(
ss_sync_from_derivedmesh(ss, dm, vertCos, useSimple);
result = ss_to_cdderivedmesh(ss, 0, drawInteriorEdges,
- useSubsurfUv, dm);
+ useSubsurfUv, dm, ms);
ccgSubSurf_free(ss);
@@ -2631,7 +2643,7 @@ struct DerivedMesh *subsurf_make_derived_from_derived(
return ss_to_cdderivedmesh(ss, 0, drawInteriorEdges,
- useSubsurfUv, dm);
+ useSubsurfUv, dm, ms);
/*return (DerivedMesh *)getCCGDerivedMesh(smd->mCache,
drawInteriorEdges,
@@ -2651,7 +2663,7 @@ struct DerivedMesh *subsurf_make_derived_from_derived(
useSubsurfUv, dm);*/
result = ss_to_cdderivedmesh(ss, 0, drawInteriorEdges,
- useSubsurfUv, dm);
+ useSubsurfUv, dm, ms);
ccgSubSurf_free(ss);
@@ -2660,6 +2672,15 @@ struct DerivedMesh *subsurf_make_derived_from_derived(
}
}
+struct DerivedMesh *subsurf_make_derived_from_derived(
+ struct DerivedMesh *dm,
+ struct SubsurfModifierData *smd,
+ int useRenderParams, float (*vertCos)[3],
+ int isFinalCalc, int editMode)
+{
+ return subsurf_make_derived_from_derived_with_multires(dm, smd, NULL, useRenderParams, vertCos, isFinalCalc, editMode);
+}
+
void subsurf_calculate_limit_positions(Mesh *me, float (*positions_r)[3])
{
/* Finds the subsurf limit positions for the verts in a mesh
diff --git a/source/blender/blenkernel/intern/suggestions.c b/source/blender/blenkernel/intern/suggestions.c
deleted file mode 100644
index 6530909336c..00000000000
--- a/source/blender/blenkernel/intern/suggestions.c
+++ /dev/null
@@ -1,254 +0,0 @@
-/**
- * $Id: $
- *
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
- *
- * The Original Code is Copyright (C) 2008, Blender Foundation
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): Ian Thompson.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-#include <stdlib.h>
-#include <string.h>
-#include <ctype.h>
-
-#include "MEM_guardedalloc.h"
-#include "BLI_blenlib.h"
-#include "DNA_text_types.h"
-#include "BKE_text.h"
-#include "BKE_suggestions.h"
-
-/**********************/
-/* Static definitions */
-/**********************/
-
-static Text *activeToolText = NULL;
-static SuggList suggestions = {NULL, NULL, NULL, NULL, NULL};
-static char *documentation = NULL;
-//static int doc_lines = 0;
-
-static int txttl_cmp(const char *first, const char *second, int len) {
- int cmp, i;
- for (cmp=0, i=0; i<len; i++) {
- if ( (cmp= toupper(first[i])-toupper(second[i])) ) {
- break;
- }
- }
- return cmp;
-}
-
-static void txttl_free_suggest() {
- SuggItem *item, *prev;
- for (item = suggestions.last; item; item=prev) {
- prev = item->prev;
- MEM_freeN(item);
- }
- suggestions.first = suggestions.last = NULL;
- suggestions.firstmatch = suggestions.lastmatch = NULL;
- suggestions.selected = NULL;
- suggestions.top = 0;
-}
-
-static void txttl_free_docs() {
- if (documentation) {
- MEM_freeN(documentation);
- documentation = NULL;
- }
-}
-
-/**************************/
-/* General tool functions */
-/**************************/
-
-void free_texttools() {
- txttl_free_suggest();
- txttl_free_docs();
-}
-
-void texttool_text_set_active(Text *text) {
- if (activeToolText == text) return;
- texttool_text_clear();
- activeToolText = text;
-}
-
-void texttool_text_clear() {
- free_texttools();
- activeToolText = NULL;
-}
-
-short texttool_text_is_active(Text *text) {
- return activeToolText==text ? 1 : 0;
-}
-
-/***************************/
-/* Suggestion list methods */
-/***************************/
-
-void texttool_suggest_add(const char *name, char type) {
- SuggItem *newitem, *item;
- int len, cmp;
-
- newitem = MEM_mallocN(sizeof(SuggItem) + strlen(name) + 1, "SuggestionItem");
- if (!newitem) {
- printf("Failed to allocate memory for suggestion.\n");
- return;
- }
-
- newitem->name = (char *) (newitem + 1);
- len = strlen(name);
- strncpy(newitem->name, name, len);
- newitem->name[len] = '\0';
- newitem->type = type;
- newitem->prev = newitem->next = NULL;
-
- /* Perform simple linear search for ordered storage */
- if (!suggestions.first || !suggestions.last) {
- suggestions.first = suggestions.last = newitem;
- } else {
- cmp = -1;
- for (item=suggestions.last; item; item=item->prev) {
- cmp = txttl_cmp(name, item->name, len);
-
- /* Newitem comes after this item, insert here */
- if (cmp >= 0) {
- newitem->prev = item;
- if (item->next)
- item->next->prev = newitem;
- newitem->next = item->next;
- item->next = newitem;
-
- /* At last item, set last pointer here */
- if (item == suggestions.last)
- suggestions.last = newitem;
- break;
- }
- }
- /* Reached beginning of list, insert before first */
- if (cmp < 0) {
- newitem->next = suggestions.first;
- suggestions.first->prev = newitem;
- suggestions.first = newitem;
- }
- }
- suggestions.firstmatch = suggestions.lastmatch = suggestions.selected = NULL;
- suggestions.top= 0;
-}
-
-void texttool_suggest_prefix(const char *prefix) {
- SuggItem *match, *first, *last;
- int cmp, len = strlen(prefix), top = 0;
-
- if (!suggestions.first) return;
- if (len==0) {
- suggestions.selected = suggestions.firstmatch = suggestions.first;
- suggestions.lastmatch = suggestions.last;
- return;
- }
-
- first = last = NULL;
- for (match=suggestions.first; match; match=match->next) {
- cmp = txttl_cmp(prefix, match->name, len);
- if (cmp==0) {
- if (!first) {
- first = match;
- suggestions.top = top;
- }
- } else if (cmp<0) {
- if (!last) {
- last = match->prev;
- break;
- }
- }
- top++;
- }
- if (first) {
- if (!last) last = suggestions.last;
- suggestions.firstmatch = first;
- suggestions.lastmatch = last;
- suggestions.selected = first;
- } else {
- suggestions.firstmatch = NULL;
- suggestions.lastmatch = NULL;
- suggestions.selected = NULL;
- suggestions.top = 0;
- }
-}
-
-void texttool_suggest_clear() {
- txttl_free_suggest();
-}
-
-SuggItem *texttool_suggest_first() {
- return suggestions.firstmatch;
-}
-
-SuggItem *texttool_suggest_last() {
- return suggestions.lastmatch;
-}
-
-void texttool_suggest_select(SuggItem *sel) {
- suggestions.selected = sel;
-}
-
-SuggItem *texttool_suggest_selected() {
- return suggestions.selected;
-}
-
-int *texttool_suggest_top() {
- return &suggestions.top;
-}
-
-/*************************/
-/* Documentation methods */
-/*************************/
-
-void texttool_docs_show(const char *docs) {
- int len;
-
- if (!docs) return;
-
- len = strlen(docs);
-
- if (documentation) {
- MEM_freeN(documentation);
- documentation = NULL;
- }
-
- /* Ensure documentation ends with a '\n' */
- if (docs[len-1] != '\n') {
- documentation = MEM_mallocN(len+2, "Documentation");
- strncpy(documentation, docs, len);
- documentation[len++] = '\n';
- } else {
- documentation = MEM_mallocN(len+1, "Documentation");
- strncpy(documentation, docs, len);
- }
- documentation[len] = '\0';
-}
-
-char *texttool_docs_get() {
- return documentation;
-}
-
-void texttool_docs_clear() {
- txttl_free_docs();
-}
diff --git a/source/blender/blenloader/intern/readfile.c b/source/blender/blenloader/intern/readfile.c
index 6579d2cd4c1..989f80dbc1d 100644
--- a/source/blender/blenloader/intern/readfile.c
+++ b/source/blender/blenloader/intern/readfile.c
@@ -133,6 +133,7 @@
#include "BKE_main.h" // for Main
#include "BKE_mesh.h" // for ME_ defines (patching)
#include "BKE_modifier.h"
+#include "BKE_multires.h"
#include "BKE_node.h" // for tree type defines
#include "BKE_object.h"
#include "BKE_particle.h"
@@ -2847,11 +2848,6 @@ static void direct_link_mesh(FileData *fd, Mesh *mesh)
direct_link_dverts(fd, lvl->totvert, CustomData_get(&mesh->mr->vdata, 0, CD_MDEFORMVERT));
direct_link_customdata(fd, &mesh->mr->fdata, lvl->totface);
- if(mesh->mr->edge_flags)
- mesh->mr->edge_flags= newdataadr(fd, mesh->mr->edge_flags);
- if(mesh->mr->edge_creases)
- mesh->mr->edge_creases= newdataadr(fd, mesh->mr->edge_creases);
-
if(!mesh->mr->edge_flags)
mesh->mr->edge_flags= MEM_callocN(sizeof(short)*lvl->totedge, "Multires Edge Flags");
if(!mesh->mr->edge_creases)
@@ -2864,9 +2860,6 @@ static void direct_link_mesh(FileData *fd, Mesh *mesh)
lvl->faces= newdataadr(fd, lvl->faces);
lvl->edges= newdataadr(fd, lvl->edges);
lvl->colfaces= newdataadr(fd, lvl->colfaces);
- lvl->edge_boundary_states= NULL;
- lvl->vert_face_map = lvl->vert_edge_map = NULL;
- lvl->map_mem= NULL;
}
}
@@ -8018,8 +8011,78 @@ static void do_versions(FileData *fd, Library *lib, Main *main)
sce->toolsettings->imapaint.normal_angle = 80;
}
}
-
-
+
+ /* TODO: should be moved into one of the version blocks once this branch moves to trunk and we can
+ bump the version (or sub-version.) */
+ {
+ Object *ob;
+ int i;
+
+ for(ob = main->object.first; ob; ob = ob->id.next) {
+
+ if(ob->type == OB_MESH) {
+ Mesh *me = newlibadr(fd, lib, ob->data);
+ void *olddata = ob->data;
+ ob->data = me;
+
+ if(me && me->mr) {
+ MultiresLevel *lvl;
+ ModifierData *md;
+ MultiresModifierData *mmd;
+ DerivedMesh *dm, *orig;
+
+ /* Load original level into the mesh */
+ lvl = me->mr->levels.first;
+ CustomData_free_layers(&me->vdata, CD_MVERT, lvl->totvert);
+ CustomData_free_layers(&me->edata, CD_MEDGE, lvl->totedge);
+ CustomData_free_layers(&me->fdata, CD_MFACE, lvl->totface);
+ me->totvert = lvl->totvert;
+ me->totedge = lvl->totedge;
+ me->totface = lvl->totface;
+ me->mvert = CustomData_add_layer(&me->vdata, CD_MVERT, CD_CALLOC, NULL, me->totvert);
+ me->medge = CustomData_add_layer(&me->edata, CD_MEDGE, CD_CALLOC, NULL, me->totedge);
+ me->mface = CustomData_add_layer(&me->fdata, CD_MFACE, CD_CALLOC, NULL, me->totface);
+ memcpy(me->mvert, me->mr->verts, sizeof(MVert) * me->totvert);
+ for(i = 0; i < me->totedge; ++i) {
+ me->medge[i].v1 = lvl->edges[i].v[0];
+ me->medge[i].v2 = lvl->edges[i].v[1];
+ }
+ for(i = 0; i < me->totface; ++i) {
+ me->mface[i].v1 = lvl->faces[i].v[0];
+ me->mface[i].v2 = lvl->faces[i].v[1];
+ me->mface[i].v3 = lvl->faces[i].v[2];
+ me->mface[i].v4 = lvl->faces[i].v[3];
+ }
+
+ /* Add a multires modifier to the object */
+ md = ob->modifiers.first;
+ while(md && modifierType_getInfo(md->type)->type == eModifierTypeType_OnlyDeform)
+ md = md->next;
+ mmd = (MultiresModifierData*)modifier_new(eModifierType_Multires);
+ BLI_insertlinkbefore(&ob->modifiers, md, mmd);
+
+ multiresModifier_subdivide(mmd, ob, me->mr->level_count - 1, 1, 0);
+
+ mmd->lvl = mmd->totlvl;
+ orig = CDDM_from_mesh(me, NULL);
+ dm = multires_dm_create_from_derived(mmd, orig, me, 0, 0);
+
+ multires_load_old(dm, me->mr);
+
+ *MultiresDM_get_flags(dm) |= MULTIRES_DM_UPDATE_ALWAYS;
+ dm->release(dm);
+ orig->release(orig);
+
+ /* Remove the old multires */
+ multires_free(me->mr);
+ me->mr = NULL;
+ }
+
+ ob->data = olddata;
+ }
+ }
+ }
+
/* WATCH IT!!!: pointers from libdata have not been converted yet here! */
/* WATCH IT 2!: Userdef struct init has to be in src/usiblender.c! */
diff --git a/source/blender/blenloader/intern/writefile.c b/source/blender/blenloader/intern/writefile.c
index e06e7eb2d85..9e9f2be7498 100644
--- a/source/blender/blenloader/intern/writefile.c
+++ b/source/blender/blenloader/intern/writefile.c
@@ -829,7 +829,7 @@ static void write_constraint_channels(WriteData *wd, ListBase *chanbase)
}
-static void write_modifiers(WriteData *wd, ListBase *modbase)
+static void write_modifiers(WriteData *wd, ListBase *modbase, int write_undo)
{
ModifierData *md;
@@ -880,10 +880,16 @@ static void write_modifiers(WriteData *wd, ListBase *modbase)
writestruct(wd, DATA, "MDefInfluence", mmd->totinfluence, mmd->dyninfluences);
writedata(wd, DATA, sizeof(int)*mmd->totvert, mmd->dynverts);
}
+ else if (md->type==eModifierType_Multires) {
+ MultiresModifierData *mmd = (MultiresModifierData*) md;
+
+ if(mmd->undo_verts && write_undo)
+ writestruct(wd, DATA, "MVert", mmd->undo_verts_tot, mmd->undo_verts);
+ }
}
}
-static void write_objects(WriteData *wd, ListBase *idbase)
+static void write_objects(WriteData *wd, ListBase *idbase, int write_undo)
{
Object *ob;
@@ -925,7 +931,7 @@ static void write_objects(WriteData *wd, ListBase *idbase)
writestruct(wd, DATA, "BulletSoftBody", 1, ob->bsoft);
write_particlesystems(wd, &ob->particlesystem);
- write_modifiers(wd, &ob->modifiers);
+ write_modifiers(wd, &ob->modifiers, write_undo);
}
ob= ob->id.next;
}
@@ -1123,7 +1129,7 @@ static void write_curves(WriteData *wd, ListBase *idbase)
static void write_dverts(WriteData *wd, int count, MDeformVert *dvlist)
{
if (dvlist) {
- int i;
+ int i;
/* Write the dvert list */
writestruct(wd, DATA, "MDeformVert", count, dvlist);
@@ -1136,6 +1142,19 @@ static void write_dverts(WriteData *wd, int count, MDeformVert *dvlist)
}
}
+static void write_mdisps(WriteData *wd, int count, MDisps *mdlist)
+{
+ if(mdlist) {
+ int i;
+
+ writestruct(wd, DATA, "MDisps", count, mdlist);
+ for(i = 0; i < count; ++i) {
+ if(mdlist[i].disps)
+ writedata(wd, DATA, sizeof(float)*3*mdlist[i].totdisp, mdlist[i].disps);
+ }
+ }
+}
+
static void write_customdata(WriteData *wd, int count, CustomData *data, int partial_type, int partial_count)
{
int i;
@@ -1151,6 +1170,9 @@ static void write_customdata(WriteData *wd, int count, CustomData *data, int par
/* layer types that allocate own memory need special handling */
write_dverts(wd, count, layer->data);
}
+ else if (layer->type == CD_MDISPS) {
+ write_mdisps(wd, count, layer->data);
+ }
else {
CustomData_file_write_info(layer->type, &structname, &structnum);
if (structnum) {
@@ -1171,7 +1193,6 @@ static void write_customdata(WriteData *wd, int count, CustomData *data, int par
static void write_meshs(WriteData *wd, ListBase *idbase)
{
Mesh *mesh;
- MultiresLevel *lvl;
mesh= idbase->first;
while(mesh) {
@@ -1210,29 +1231,6 @@ static void write_meshs(WriteData *wd, ListBase *idbase)
write_customdata(wd, mesh->totface, &mesh->fdata, -1, 0);
}
- /* Multires data */
- writestruct(wd, DATA, "Multires", 1, mesh->mr);
- if(mesh->mr) {
- lvl= mesh->mr->levels.first;
- if(lvl) {
- write_customdata(wd, lvl->totvert, &mesh->mr->vdata, -1, 0);
- write_customdata(wd, lvl->totface, &mesh->mr->fdata, -1, 0);
- writedata(wd, DATA, sizeof(short)*lvl->totedge, mesh->mr->edge_flags);
- writedata(wd, DATA, sizeof(char)*lvl->totedge, mesh->mr->edge_creases);
- }
-
- for(; lvl; lvl= lvl->next) {
- writestruct(wd, DATA, "MultiresLevel", 1, lvl);
- writestruct(wd, DATA, "MultiresFace", lvl->totface, lvl->faces);
- writestruct(wd, DATA, "MultiresEdge", lvl->totedge, lvl->edges);
- writestruct(wd, DATA, "MultiresColFace", lvl->totface, lvl->colfaces);
- }
-
- lvl= mesh->mr->levels.last;
- if(lvl)
- writestruct(wd, DATA, "MVert", lvl->totvert, mesh->mr->verts);
- }
-
/* PMV data */
if(mesh->pv) {
writestruct(wd, DATA, "PartialVisibility", 1, mesh->pv);
@@ -2072,7 +2070,7 @@ static int write_file_handle(int handle, MemFile *compare, MemFile *current, int
write_groups (wd, &G.main->group);
write_armatures(wd, &G.main->armature);
write_actions (wd, &G.main->action);
- write_objects (wd, &G.main->object);
+ write_objects (wd, &G.main->object, (current != NULL));
write_materials(wd, &G.main->mat);
write_textures (wd, &G.main->tex);
write_meshs (wd, &G.main->mesh);
diff --git a/source/blender/gpu/intern/gpu_material.c b/source/blender/gpu/intern/gpu_material.c
index 87703bc73bf..46df003cbbc 100644
--- a/source/blender/gpu/intern/gpu_material.c
+++ b/source/blender/gpu/intern/gpu_material.c
@@ -306,7 +306,7 @@ void GPU_material_bind_uniforms(GPUMaterial *material, float obmat[][4], float v
if(material->dynproperty & DYN_LAMP_VEC) {
VECCOPY(lamp->dynvec, lamp->vec);
Normalize(lamp->dynvec);
- VecNegf(lamp->dynvec);
+ VecMulf(lamp->dynvec, -1.0f);
Mat4Mul3Vecfl(viewmat, lamp->dynvec);
}
diff --git a/source/blender/include/BIF_keyframing.h b/source/blender/include/BIF_keyframing.h
deleted file mode 100644
index dbbe55123e4..00000000000
--- a/source/blender/include/BIF_keyframing.h
+++ /dev/null
@@ -1,131 +0,0 @@
-/**
- * $Id$
- *
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 59 Temple Place * Suite 330, Boston, MA 02111*1307, USA.
- *
- * The Original Code is Copyright (C) 2008, Blender Foundation
- * This is a new part of Blender (with some old code)
- *
- * Contributor(s): Joshua Leung
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-#ifndef BIF_KEYFRAMING_H
-#define BIF_KEYFRAMING_H
-
-struct ListBase;
-struct ID;
-
-struct IpoCurve;
-struct BezTriple;
-
-/* ************ Keyframing Management **************** */
-
-/* Lesser Keyframing API call:
- * Use this when validation of necessary animation data isn't necessary as it already
- * exists, and there is a beztriple that can be directly copied into the array.
- */
-int insert_bezt_icu(struct IpoCurve *icu, struct BezTriple *bezt);
-
-/* Main Keyframing API call:
- * Use this when validation of necessary animation data isn't necessary as it
- * already exists. It will insert a keyframe using the current value being keyframed.
- */
-void insert_vert_icu(struct IpoCurve *icu, float x, float y, short flag);
-
-
-/* flags for use by keyframe creation/deletion calls */
-enum {
- /* used by isnertkey() and insert_vert_icu() */
- INSERTKEY_NEEDED = (1<<0), /* only insert keyframes where they're needed */
- INSERTKEY_MATRIX = (1<<1), /* insert 'visual' keyframes where possible/needed */
- INSERTKEY_FAST = (1<<2), /* don't recalculate handles,etc. after adding key */
- INSERTKEY_FASTR = (1<<3), /* don't realloc mem (or increase count, as array has already been set out) */
- INSERTKEY_REPLACE = (1<<4), /* only replace an existing keyframe (this overrides INSERTKEY_NEEDED) */
-
- /* used by common_*key() functions */
- COMMONKEY_ADDMAP = (1<<10), /* common key: add texture-slot offset bitflag to adrcode before use */
-} eInsertKeyFlags;
-
-/* -------- */
-
-/* Main Keyframing API calls:
- * Use this to create any necessary animation data, and then insert a keyframe
- * using the current value being keyframed, in the relevant place. Returns success.
- */
- // TODO: adapt this for new data-api -> this blocktype, etc. stuff is evil!
-short insertkey(struct ID *id, int blocktype, char *actname, char *constname, int adrcode, short flag);
-
-/* Main Keyframing API call:
- * Use this to delete keyframe on current frame for relevant channel. Will perform checks just in case.
- */
-short deletekey(struct ID *id, int blocktype, char *actname, char *constname, int adrcode, short flag);
-
-
-/* Main Keyframe Management calls:
- * These handle keyframes management from various spaces. They will handle the menus
- * required for each space.
- */
-void common_insertkey(void);
-void common_deletekey(void);
-
-/* ************ Auto-Keyframing ********************** */
-/* Notes:
- * - All the defines for this (User-Pref settings and Per-Scene settings)
- * are defined in DNA_userdef_types.h
- * - Scene settings take presidence over those for userprefs, with old files
- * inheriting userpref settings for the scene settings
- * - "On/Off + Mode" are stored per Scene, but "settings" are currently stored
- * as userprefs
- */
-
-/* Auto-Keying macros for use by various tools */
- /* check if auto-keyframing is enabled (per scene takes presidence) */
-#define IS_AUTOKEY_ON ((G.scene) ? (G.scene->autokey_mode & AUTOKEY_ON) : (U.autokey_mode & AUTOKEY_ON))
- /* check the mode for auto-keyframing (per scene takes presidence) */
-#define IS_AUTOKEY_MODE(mode) ((G.scene) ? (G.scene->autokey_mode == AUTOKEY_MODE_##mode) : (U.autokey_mode == AUTOKEY_MODE_##mode))
- /* check if a flag is set for auto-keyframing (as userprefs only!) */
-#define IS_AUTOKEY_FLAG(flag) (U.autokey_flag & AUTOKEY_FLAG_##flag)
-
-/* ************ Keyframe Checking ******************** */
-
-/* Main Keyframe Checking API call:
- * Checks whether a keyframe exists for the given ID-block one the given frame.
- * - It is recommended to call this method over the other keyframe-checkers directly,
- * in case some detail of the implementation changes...
- * - frame: the value of this is quite often result of frame_to_float(CFRA)
- */
-short id_frame_has_keyframe(struct ID *id, float frame, short filter);
-
-/* filter flags for id_cfra_has_keyframe
- *
- * WARNING: do not alter order of these, as also stored in files
- * (for v3d->keyflags)
- */
-enum {
- /* general */
- ANIMFILTER_LOCAL = (1<<0), /* only include locally available anim data */
- ANIMFILTER_MUTED = (1<<1), /* include muted elements */
- ANIMFILTER_ACTIVE = (1<<2), /* only include active-subelements */
-
- /* object specific */
- ANIMFILTER_NOMAT = (1<<9), /* don't include material keyframes */
- ANIMFILTER_NOSKEY = (1<<10), /* don't include shape keys (for geometry) */
-} eAnimFilterFlags;
-
-#endif /* BIF_KEYFRAMING_H */
diff --git a/source/blender/include/multires.h b/source/blender/include/multires.h
deleted file mode 100644
index e4726c02d7e..00000000000
--- a/source/blender/include/multires.h
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * $Id$
- *
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
- *
- * The Original Code is Copyright (C) 2006 by Nicholas Bishop
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-#ifndef MULTIRES_H
-#define MULTIRES_H
-
-struct CustomData;
-struct EditMesh;
-struct Object;
-struct MDeformVert;
-struct Mesh;
-struct MultiresLevel;
-struct Multires;
-struct uiBlock;
-
-/* For canceling operations that don't work with multires on or on a non-base level */
-int multires_test();
-int multires_level1_test();
-
-void multires_draw_interface(struct uiBlock *block, unsigned short cx, unsigned short cy);
-
-void multires_make(void *ob, void *me);
-void multires_delete(void *ob, void *me);
-void multires_level_to_editmesh(struct Object *ob, struct Mesh *me, const int render);
-void multires_finish_mesh_update(struct Object *ob);
-void multires_subdivide(void *ob, void *me);
-void multires_del_lower(void *ob, void *me);
-void multires_del_higher(void *ob, void *me);
-void multires_set_level_cb(void *ob, void *me);
-void multires_edge_level_update_cb(void *ob, void *me);
-int multires_modifier_warning();
-
-#endif
diff --git a/source/blender/makesdna/DNA_customdata_types.h b/source/blender/makesdna/DNA_customdata_types.h
index e6b18641d2a..f953eab148e 100644
--- a/source/blender/makesdna/DNA_customdata_types.h
+++ b/source/blender/makesdna/DNA_customdata_types.h
@@ -74,7 +74,8 @@ typedef struct CustomData {
#define CD_MLOOPUV 16
#define CD_MLOOPCOL 17
#define CD_TANGENT 18
-#define CD_NUMTYPES 19
+#define CD_MDISPS 19
+#define CD_NUMTYPES 20
/* Bits for CustomDataMask */
#define CD_MASK_MVERT (1 << CD_MVERT)
@@ -96,7 +97,7 @@ typedef struct CustomData {
#define CD_MASK_MLOOPUV (1 << CD_MLOOPUV)
#define CD_MASK_MLOOPCOL (1 << CD_MLOOPCOL)
#define CD_MASK_TANGENT (1 << CD_TANGENT)
-
+#define CD_MASK_MDISPS (1 << CD_MDISPS)
/* CustomData.flag */
diff --git a/source/blender/makesdna/DNA_meshdata_types.h b/source/blender/makesdna/DNA_meshdata_types.h
index fc686a4cc10..fd2f7b25115 100644
--- a/source/blender/makesdna/DNA_meshdata_types.h
+++ b/source/blender/makesdna/DNA_meshdata_types.h
@@ -116,7 +116,14 @@ typedef struct OrigSpaceFace {
float uv[4][2];
} OrigSpaceFace;
-/* Multiresolution modeling */
+typedef struct MDisps {
+ /* Strange bug in SDNA: if disps pointer comes first, it fails to see totdisp */
+ int totdisp;
+ char pad[4];
+ float (*disps)[3];
+} MDisps;
+
+/** Multires structs kept for compatibility with old files **/
typedef struct MultiresCol {
float a, r, g, b;
} MultiresCol;
@@ -142,15 +149,9 @@ typedef struct MultiresLevel {
MultiresColFace *colfaces;
MultiresEdge *edges;
- /* Temporary connectivity data */
- char *edge_boundary_states;
- struct ListBase *vert_edge_map;
- struct ListBase *vert_face_map;
- struct MultiresMapNode *map_mem;
-
unsigned int totvert, totface, totedge, pad;
- /* Kept for compatibility with older files */
+ /* Kept for compatibility with even older files */
MVert *verts;
} MultiresLevel;
@@ -168,6 +169,8 @@ typedef struct Multires {
char *edge_creases;
} Multires;
+/** End Multires **/
+
typedef struct PartialVisibility {
unsigned int *vert_map; /* vert_map[Old Index]= New Index */
int *edge_map; /* edge_map[Old Index]= New Index, -1= hidden */
@@ -265,7 +268,4 @@ typedef struct PartialVisibility {
#define TF_PIN3 64
#define TF_PIN4 128
-/* multires->flag */
-#define MULTIRES_NO_RENDER 1
-
#endif
diff --git a/source/blender/makesdna/DNA_modifier_types.h b/source/blender/makesdna/DNA_modifier_types.h
index ae07434a37f..e726015c0f2 100644
--- a/source/blender/makesdna/DNA_modifier_types.h
+++ b/source/blender/makesdna/DNA_modifier_types.h
@@ -39,6 +39,7 @@ typedef enum ModifierType {
eModifierType_Fluidsim,
eModifierType_Mask,
eModifierType_SimpleDeform,
+ eModifierType_Multires,
NUM_MODIFIER_TYPES
} ModifierType;
@@ -513,6 +514,17 @@ typedef struct ExplodeModifierData {
float protect;
} ExplodeModifierData;
+typedef struct MultiresModifierData {
+ ModifierData modifier;
+
+ struct MVert *undo_verts; /* Store DerivedMesh vertices for multires undo */
+ int undo_verts_tot; /* Length of undo_verts array */
+ char undo_signal; /* If true, signals to replace verts with undo verts */
+
+ char lvl, totlvl;
+ char simple;
+} MultiresModifierData;
+
typedef struct FluidsimModifierData {
ModifierData modifier;
diff --git a/source/blender/python/api2_2x/Mesh.c b/source/blender/python/api2_2x/Mesh.c
index 32ddb464c88..8e9b64059f3 100644
--- a/source/blender/python/api2_2x/Mesh.c
+++ b/source/blender/python/api2_2x/Mesh.c
@@ -87,7 +87,6 @@
#include "constant.h"
#include "gen_utils.h"
#include "gen_library.h"
-#include "multires.h"
/* EXPP Mesh defines */
@@ -7151,19 +7150,20 @@ static int Mesh_setMultires( BPy_Mesh * self, PyObject *value, void *type )
"value out of range" );
switch (GET_INT_FROM_POINTER(type)) {
+#warning "Python needs to be updated to work with the new multires."
case MESH_MULTIRES_LEVEL:
- self->mesh->mr->newlvl = i;
- multires_set_level_cb(self->object, self->mesh);
+ /*self->mesh->mr->newlvl = i;
+ multires_set_level_cb(self->object, self->mesh);*/
break;
case MESH_MULTIRES_EDGE:
- self->mesh->mr->edgelvl = i;
- multires_edge_level_update(self->object, self->mesh);
+ /*self->mesh->mr->edgelvl = i;
+ multires_edge_level_update(self->object, self->mesh);*/
break;
case MESH_MULTIRES_PIN:
- self->mesh->mr->pinlvl = i;
+ /*self->mesh->mr->pinlvl = i;*/
break;
case MESH_MULTIRES_RENDER:
- self->mesh->mr->renderlvl = i;
+ /*self->mesh->mr->renderlvl = i;*/
break;
}
@@ -7172,6 +7172,10 @@ static int Mesh_setMultires( BPy_Mesh * self, PyObject *value, void *type )
static PyObject *Mesh_addMultiresLevel( BPy_Mesh * self, PyObject * args )
{
+ return NULL;
+#warning "Python needs to be updated to work with the new multires."
+
+#if 0
char typenum;
int i, levels = 1;
char *type = NULL;
@@ -7198,6 +7202,7 @@ static PyObject *Mesh_addMultiresLevel( BPy_Mesh * self, PyObject * args )
multires_level_to_editmesh(self->object, self->mesh, 0);
multires_finish_mesh_update(self->object);
Py_RETURN_NONE;
+#endif
}
/* end multires */
@@ -8050,14 +8055,14 @@ static int Mesh_setFlag( BPy_Mesh * self, PyObject *value, void *type )
if( !param ) {
if ( mesh->mr ) {
- multires_delete(self->object, mesh);
+ /*multires_delete(self->object, mesh);*/
}
} else {
if ( !mesh->mr ) {
if (mesh->key)
return EXPP_ReturnIntError( PyExc_RuntimeError,
"Cannot enable multires for a mesh with shape keys" );
- multires_make(self->object, mesh);
+ /*multires_make(self->object, mesh);*/
}
}
return 0;
diff --git a/source/blender/render/intern/include/render_types.h b/source/blender/render/intern/include/render_types.h
index 1768b052b54..34553208574 100644
--- a/source/blender/render/intern/include/render_types.h
+++ b/source/blender/render/intern/include/render_types.h
@@ -505,7 +505,6 @@ typedef struct LampRen {
#define R_LAMPHALO 8
#define R_GLOB_NOPUNOFLIP 16
#define R_NEED_TANGENT 32
-#define R_SKIP_MULTIRES 64
#define R_BAKE_TRACE 128
#define R_BAKING 256
diff --git a/source/blender/render/intern/source/convertblender.c b/source/blender/render/intern/source/convertblender.c
index 4e4e27fe286..c4f173546f2 100644
--- a/source/blender/render/intern/source/convertblender.c
+++ b/source/blender/render/intern/source/convertblender.c
@@ -100,7 +100,6 @@
#include "IMB_imbuf_types.h"
#include "envmap.h"
-#include "multires.h"
#include "occlusion.h"
#include "render_types.h"
#include "rendercore.h"
@@ -3078,13 +3077,6 @@ static void init_render_mesh(Render *re, ObjectRen *obr, int timeoffset)
if(need_orco)
mask |= CD_MASK_ORCO;
- if(me->mr) {
- if(re->flag & R_SKIP_MULTIRES)
- me->mr->flag |= MULTIRES_NO_RENDER;
- else
- me->mr->flag &= ~MULTIRES_NO_RENDER;
- }
-
dm= mesh_create_derived_render(ob, mask);
if(dm==NULL) return; /* in case duplicated object fails? */
@@ -5431,8 +5423,6 @@ void RE_Database_Baking(Render *re, Scene *scene, int type, Object *actob)
re->flag |= R_GLOB_NOPUNOFLIP;
re->flag |= R_BAKING;
re->excludeob= actob;
- if(type == RE_BAKE_LIGHT)
- re->flag |= R_SKIP_MULTIRES;
if(actob)
re->flag |= R_BAKE_TRACE;
diff --git a/source/blender/src/buttons_editing.c b/source/blender/src/buttons_editing.c
index 7ba6f122d39..70ba43e756e 100644
--- a/source/blender/src/buttons_editing.c
+++ b/source/blender/src/buttons_editing.c
@@ -178,7 +178,6 @@
#include "RE_render_ext.h" // make_sticky
#include "butspace.h" // own module
-#include "multires.h"
#include "reeb.h"
@@ -740,14 +739,7 @@ static void delete_customdata_layer(void *data1, void *data2)
masklayerdata = data->layers[CustomData_get_mask_layer_index(data, type)].data;
CustomData_set_layer_active(data, type, layer - &data->layers[index]);
- /* Multires is handled seperately because the display data is separate
- from the data stored in multires */
- if(me && me->mr) {
- multires_delete_layer(me, &me->mr->fdata, type, layer - &data->layers[index]);
- multires_level_to_editmesh(OBACT, me, 0);
- multires_finish_mesh_update(OBACT);
- }
- else if(G.obedit) {
+ if(G.obedit) {
EM_free_data_layer(data, type);
}
else if(me) {
@@ -1415,10 +1407,6 @@ static void modifiers_applyModifier(void *obv, void *mdv)
}
if (ob->type==OB_MESH) {
- if(me->mr && multires_modifier_warning()) {
- error("Modifier changes topology; cannot apply with multires active");
- return;
- }
if(me->key) {
error("Modifier cannot be applied to Mesh with Shape Keys");
return;
@@ -1426,12 +1414,20 @@ static void modifiers_applyModifier(void *obv, void *mdv)
mesh_pmv_off(ob, me);
+ /* Multires: ensure that recent sculpting is applied */
+ if(md->type == eModifierType_Multires)
+ multires_force_update(ob);
+
dm = mesh_create_derived_for_modifier(ob, md);
if (!dm) {
error("Modifier is disabled or returned error, skipping apply");
return;
}
+ /* Multires: remove MDisps from the DerivedMesh */
+ if(md->type == eModifierType_Multires)
+ CustomData_free_layers(&dm->faceData, CD_MDISPS, me->totface);
+
DM_to_mesh(dm, me);
converted = 1;
@@ -1728,6 +1724,52 @@ void modifiers_explodeDelVg(void *arg1, void *arg2)
emd->vgroup = 0;
}
+static void multiresModifier_subdivide_button(void *mmd_v, void *ob_v)
+{
+ MultiresModifierData *mmd = mmd_v;
+
+ if(mmd && ob_v) {
+ multiresModifier_subdivide(mmd, ob_v, 1, 0, mmd->simple);
+ BIF_undo_push("Multires subdivide");
+ }
+}
+
+static void multiresModifier_reshape_button(void *mmd_v, void *ob_v)
+{
+ MultiresModifierData *mmd = mmd_v;
+ if(mmd && ob_v) {
+ Base *base = FIRSTBASE;
+ Object *ob2 = NULL;
+
+ while(base) {
+ if(base->object != ob_v && base->object->type == OB_MESH) {
+ ob2 = base->object;
+ break;
+ }
+ base = base->next;
+ }
+
+ if(ob2) {
+ if(multiresModifier_reshape(mmd, ob_v, ob2))
+ error("Vertex count mismatch");
+ else
+ BIF_undo_push("Multires reshape");
+ }
+ else
+ error("Second mesh selection required");
+ }
+}
+
+static void multiresModifier_del_higher_button(void *mmd_v, void *ob_v)
+{
+ MultiresModifierData *mmd = mmd_v;
+
+ if(mmd && ob_v) {
+ multiresModifier_del_levels(mmd, ob_v, 1);
+ BIF_undo_push("Delete higher");
+ }
+}
+
static int modifier_is_fluid_particles(ModifierData *md) {
if(md->type == eModifierType_ParticleSystem) {
if(((ParticleSystemModifierData *)md)->psys->part->type == PART_FLUID)
@@ -1918,7 +1960,10 @@ static void draw_modifier(uiBlock *block, Object *ob, ModifierData *md, int *xco
if(smd->mode == MOD_SIMPLEDEFORM_MODE_STRETCH
|| smd->mode == MOD_SIMPLEDEFORM_MODE_TAPER )
height += 19;
- }
+ } else if (md->type==eModifierType_Multires) {
+ height = 94;
+ }
+
/* roundbox 4 free variables: corner-rounding, nop, roundbox type, shade */
uiDefBut(block, ROUNDBOX, 0, "", x-10, y-height-2, width, height-2, NULL, 5.0, 0.0, 12, 40, "");
@@ -2645,7 +2690,24 @@ static void draw_modifier(uiBlock *block, Object *ob, ModifierData *md, int *xco
uiDefButBitC(block, TOG, MOD_SIMPLEDEFORM_LOCK_AXIS_X, B_MODIFIER_RECALC, "Loc X", lx, (cy-=19),buttonWidth/2,19, &smd->axis, 0, 0, 0, 0, "Disallow changes on the X coordinate");
uiDefButBitC(block, TOG, MOD_SIMPLEDEFORM_LOCK_AXIS_Y, B_MODIFIER_RECALC, "Loc Y", lx+(buttonWidth/2), (cy),buttonWidth/2,19, &smd->axis, 0, 0, 0, 0, "Disallow changes on the Y coordinate");
}
- }
+ } else if (md->type==eModifierType_Multires) {
+ MultiresModifierData *mmd = (MultiresModifierData*) md;
+ char subsurfmenu[]= "Subsurf Type%t|Catmull-Clark%x0|Simple Subdiv.%x1";
+ uiBut *but;
+
+ but = uiDefBut(block,BUT,B_MODIFIER_RECALC,"Subdivide", lx,(cy-=19),buttonWidth,19,0,0,0,0,0,"Increase the resolution of displacements");
+ uiButSetFunc(but, multiresModifier_subdivide_button, mmd, ob);
+
+ uiDefButC(block, MENU, B_NOP, subsurfmenu, lx, (cy-=19), buttonWidth, 19, &mmd->simple, 0, 0, 0, 0, "Selects type of subdivision algorithm.");
+
+ uiDefButC(block,NUM,B_MODIFIER_RECALC,"Level: ",lx,(cy-=19),buttonWidth,19, &mmd->lvl, 1.0, mmd->totlvl, 0,0,"");
+
+ uiBlockBeginAlign(block);
+ but = uiDefBut(block,BUT,B_MODIFIER_RECALC,"Reshape", lx,(cy-=24),buttonWidth/2,19,0,0,0,0,0,"Copy vertices from another selected mesh into the current level");
+ uiButSetFunc(but, multiresModifier_reshape_button, mmd, ob);
+ but = uiDefBut(block,BUT,B_MODIFIER_RECALC,"Del Higher", lx+buttonWidth/2,cy,buttonWidth/2,19,0,0,0,0,0,"Copy vertices from another selected mesh into the current level");
+ uiButSetFunc(but, multiresModifier_del_higher_button, mmd, ob);
+ }
uiBlockEndAlign(block);
@@ -4922,8 +4984,6 @@ void do_meshbuts(unsigned short event)
shadeMeshMCol(ob, me);
}
- if (me->mr) multires_load_cols(me);
-
DAG_object_flush_update(G.scene, ob, OB_RECALC_DATA);
BIF_undo_push("New Vertex Color");
allqueue(REDRAWVIEW3D, 0);
@@ -4952,13 +5012,7 @@ void do_meshbuts(unsigned short event)
break;
case B_NEWTFACE:
- if(me && me->mr) {
- layernum= CustomData_number_of_layers(&me->fdata, CD_MTFACE);
- multires_add_layer(me, &me->mr->fdata, CD_MTFACE, layernum);
- multires_level_to_editmesh(ob, me, 0);
- multires_finish_mesh_update(ob);
- }
- else if(G.obedit) {
+ if(G.obedit) {
layernum= CustomData_number_of_layers(&em->fdata, CD_MTFACE);
EM_add_data_layer(&em->fdata, CD_MTFACE);
CustomData_set_layer_active(&em->fdata, CD_MTFACE, layernum);
@@ -4989,10 +5043,6 @@ void do_meshbuts(unsigned short event)
CustomData_set_layer_active(fdata, CD_MTFACE, acttface-1);
mesh_update_customdata_pointers(me);
- /* Update first-level face data in multires */
- if(me && me->mr && me->mr->current != 1)
- CustomData_set_layer_active(&me->mr->fdata, CD_MTFACE, acttface-1);
-
DAG_object_flush_update(G.scene, ob, OB_RECALC_DATA);
BIF_undo_push("Set Active UV Texture");
allqueue(REDRAWVIEW3D, 0);
@@ -6096,16 +6146,14 @@ void do_fpaintbuts(unsigned short event)
allqueue(REDRAWBUTSEDIT, 0);
break;
case B_CLR_WPAINT:
- if(!multires_level1_test()) {
- defGroup = BLI_findlink(&ob->defbase, ob->actdef-1);
- if(defGroup) {
- Mesh *me= ob->data;
- int a;
- for(a=0; a<me->totvert; a++)
- remove_vert_defgroup (ob, defGroup, a);
- allqueue(REDRAWVIEW3D, 0);
- DAG_object_flush_update(G.scene, ob, OB_RECALC_DATA);
- }
+ defGroup = BLI_findlink(&ob->defbase, ob->actdef-1);
+ if(defGroup) {
+ Mesh *me= ob->data;
+ int a;
+ for(a=0; a<me->totvert; a++)
+ remove_vert_defgroup (ob, defGroup, a);
+ allqueue(REDRAWVIEW3D, 0);
+ DAG_object_flush_update(G.scene, ob, OB_RECALC_DATA);
}
break;
case B_SCULPT_TEXBROWSE:
@@ -6642,73 +6690,6 @@ static void editing_panel_mesh_uvautocalculation(void)
uiBlockEndAlign(block);
}
-void editing_panel_mesh_multires()
-{
- uiBlock *block;
- uiBut *but;
- Object *ob= OBACT;
- Mesh *me= get_mesh(ob);
- int cx= 100, cy= 0;
-
- block= uiNewBlock(&curarea->uiblocks, "editing_panel_mesh_multires", UI_EMBOSS, UI_HELV, curarea->win);
- if(uiNewPanel(curarea, block, "Multires", "Editing", 500, 0, 318, 204)==0) return;
-
- uiSetButLock(object_data_is_libdata(ob), ERROR_LIBDATA_MESSAGE);
-
- if(!me->mr) {
- but= uiDefBut(block,BUT,B_NOP,"Add Multires", cx,cy,268,19,0,0,0,0,0,"Allow editing of the mesh at multiple subdivision levels (disables distructive mesh editing)");
- uiButSetFunc(but,multires_make,ob,me);
- } else {
- char subsurfmenu[]= "Subsurf Type%t|Catmull-Clark%x0|Simple Subdiv.%x1";
-
- but= uiDefBut(block,BUT,B_NOP,"Apply Multires", cx,cy,268,19,0,0,0,0,0,"Apply current multires level to mesh and the delete other levels");
- uiButSetFunc(but,multires_delete,ob,me);
- cy-= 24;
-
- uiBlockBeginAlign(block);
- but= uiDefBut(block,BUT,B_NOP,"Add Level", cx,cy,134,19,0,0,0,0,0,"Add a new level of subdivision at the end of the chain");
- uiButSetFunc(but, multires_subdivide, ob, me);
- uiDefButC(block, MENU, B_NOP, subsurfmenu, cx + 134, cy, 134, 19, &G.scene->toolsettings->multires_subdiv_type, 0, 0, 0, 0, "Selects type of subdivision algorithm.");
- cy-= 20;
-
- if(me->mr->level_count>1) {
- but= uiDefBut(block,BUT,B_NOP,"Del Lower", cx,cy,134,19,0,0,0,0,0,"Remove all levels of subdivision below the current one");
- uiButSetFunc(but,multires_del_lower,ob,me);
- but= uiDefBut(block,BUT,B_NOP,"Del Higher", cx+134,cy,134,19,0,0,0,0,0,"Remove all levels of subdivision above the current one");
- uiButSetFunc(but,multires_del_higher,ob,me);
- cy-= 20;
-
- but= uiDefButC(block,NUM,B_NOP,"Level: ",cx,cy,268,19,(char *)&me->mr->newlvl,1.0,me->mr->level_count,0,0,"");
- uiButSetFunc(but,multires_set_level_cb, ob, me);
- cy-= 20;
-
- but= uiDefButC(block,NUM,B_NOP,"Edges: ",cx,cy,268,19,(char *)&me->mr->edgelvl,1.0,me->mr->level_count,0,0,"Set level of edges to display");
- uiButSetFunc(but,multires_edge_level_update_cb,ob,me);
- cy-= 20;
- uiBlockEndAlign(block);
-
- cy-= 5;
- uiDefBut(block,LABEL,B_NOP,"Rendering",cx,cy,100,19,0,0,0,0,0,"");
- cy-= 20;
-
- uiBlockBeginAlign(block);
- uiDefButC(block,NUM,B_NOP,"Pin: ",cx,cy,268,19,(char *)&me->mr->pinlvl,1.0,me->mr->level_count,0,0,"Set level to apply modifiers to during render");
- cy-= 20;
-
- uiDefButC(block,NUM,B_NOP,"Render: ",cx,cy,268,19,(char *)&me->mr->renderlvl,1.0,me->mr->level_count,0,0,"Set level to render");
- cy-= 20;
-
- if(multires_modifier_warning()) {
- char *tip= "One or more modifiers are enabled that modify mesh topology";
- uiDefIconBut(block,LABEL,B_NOP,ICON_ERROR, cx,cy,20,20, 0,0,0,0,0, tip);
- uiDefBut(block,LABEL,B_NOP, "Cannot use render level", cx+20,cy,180,19, 0,0,0,0,0, tip);
- }
- }
- }
-
- uiBlockEndAlign(block);
-}
-
void particle_edit_buttons(uiBlock *block)
{
Object *ob=OBACT;
@@ -6850,7 +6831,6 @@ void editing_panels()
editing_panel_mesh_type(ob, ob->data);
editing_panel_modifiers(ob);
editing_panel_shapes(ob);
- editing_panel_mesh_multires();
/* modes */
if(G.obedit) {
editing_panel_mesh_tools(ob, ob->data);
@@ -6868,11 +6848,10 @@ void editing_panels()
editing_panel_mesh_texface();
}
else if(G.f & G_SCULPTMODE) {
- uiNewPanelTabbed("Multires", "Editing");
editing_panel_sculpting_tools();
- uiNewPanelTabbed("Multires", "Editing");
+ uiNewPanelTabbed("Sculpt", "Editing");
editing_panel_sculpting_brush();
- uiNewPanelTabbed("Multires", "Editing");
+ uiNewPanelTabbed("Sculpt", "Editing");
editing_panel_sculpting_textures();
} else {
if(G.f & (G_VERTEXPAINT | G_TEXTUREPAINT | G_WEIGHTPAINT) ) {
diff --git a/source/blender/src/drawview.c b/source/blender/src/drawview.c
index 44b61c816a5..553cc92e4ac 100644
--- a/source/blender/src/drawview.c
+++ b/source/blender/src/drawview.c
@@ -153,9 +153,7 @@
#include "BSE_time.h"
#include "BSE_view.h"
-#ifndef DISABLE_PYTHON
#include "BPY_extern.h"
-#endif
#include "RE_render_ext.h"
@@ -167,13 +165,9 @@
#include "RE_pipeline.h" // make_stars
-#include "reeb.h"
-
#include "GPU_draw.h"
#include "GPU_material.h"
-#include "multires.h"
-
/* For MULTISAMPLE_ARB #define.
Note that older systems like irix
may not have this, and will need a #ifdef
@@ -975,8 +969,7 @@ void backdrawview3d(int test)
int m;
#endif
- if( G.f & G_VERTEXPAINT || G.f & G_WEIGHTPAINT );
- else if ((G.f & G_TEXTUREPAINT) && G.scene->toolsettings && (G.scene->toolsettings->imapaint.flag & IMAGEPAINT_PROJECT_DISABLE)==0);
+ if(G.f & G_VERTEXPAINT || G.f & G_WEIGHTPAINT || G.f & G_TEXTUREPAINT);
else if(G.obedit && G.vd->drawtype>OB_WIRE && (G.vd->flag & V3D_ZBUF_SELECT));
else {
G.vd->flag &= ~V3D_NEEDBACKBUFDRAW;
@@ -3243,8 +3236,6 @@ void drawview3dspace(ScrArea *sa, void *spacedata)
BIF_drawPropCircle(); // only editmode and particles have proportional edit
BIF_drawSnap();
}
-
- REEB_draw();
if(G.scene->radio) RAD_drawall(v3d->drawtype>=OB_SOLID);
@@ -3310,12 +3301,7 @@ void drawview3dspace(ScrArea *sa, void *spacedata)
fdrawXORcirc((float)c[0], (float)c[1], (float)pset->brush[pset->brushtype].size);
}
}
- if(!G.obedit && OBACT && G.f&G_TEXTUREPAINT && area_is_active_area(v3d->area) && G.scene->toolsettings->imapaint.brush){
- short c[2];
- getmouseco_areawin(c);
- fdrawXORcirc((float)c[0], (float)c[1], (float)G.scene->toolsettings->imapaint.brush->size/2);
- }
-
+
if(v3d->persp>1) drawviewborder();
if(v3d->flag2 & V3D_FLYMODE) drawviewborder_flymode();
@@ -3362,7 +3348,6 @@ void drawview3dspace(ScrArea *sa, void *spacedata)
}
}
-#ifndef DISABLE_PYTHON
/* run any view3d draw handler script links */
if (sa->scriptlink.totscript)
BPY_do_spacehandlers(sa, 0, 0, SPACEHANDLER_VIEW3D_DRAW);
@@ -3372,7 +3357,7 @@ void drawview3dspace(ScrArea *sa, void *spacedata)
!during_script()) {
BPY_do_pyscript((ID *)G.scene, SCRIPT_REDRAW);
}
-#endif
+
}
void drawview3d_render(struct View3D *v3d, float viewmat[][4], int winx, int winy, float winmat[][4], int shadow)
diff --git a/source/blender/src/editdeform.c b/source/blender/src/editdeform.c
index 8a07a4fddff..db41f807f07 100644
--- a/source/blender/src/editdeform.c
+++ b/source/blender/src/editdeform.c
@@ -67,7 +67,6 @@
#include "butspace.h"
#include "mydevice.h"
#include "editmesh.h"
-#include "multires.h"
#ifdef HAVE_CONFIG_H
#include <config.h>
@@ -699,8 +698,6 @@ void assign_verts_defgroup (void)
MDeformVert *dvert;
int i, done;
- if(multires_level1_test()) return;
-
ob= G.obedit;
if (!ob)
@@ -859,8 +856,6 @@ void remove_verts_defgroup (int allverts)
bDeformGroup *dg, *eg;
int i;
- if(multires_level1_test()) return;
-
ob= G.obedit;
if (!ob)
@@ -929,8 +924,6 @@ void remove_verts_defgroups(int allverts)
Object *ob;
int actdef, defCount;
- if (multires_level1_test()) return;
-
ob= G.obedit;
if (ob == NULL) return;
diff --git a/source/blender/src/editface.c b/source/blender/src/editface.c
index 53fb6dbffb1..18f72667960 100644
--- a/source/blender/src/editface.c
+++ b/source/blender/src/editface.c
@@ -60,7 +60,6 @@
#include "BKE_displist.h"
#include "BKE_global.h"
#include "BKE_mesh.h"
-#include "BKE_multires.h"
#include "BKE_object.h"
#include "BKE_texture.h"
#include "BKE_utildefines.h"
@@ -646,14 +645,8 @@ void default_uv(float uv[][2], float size)
void make_tfaces(Mesh *me)
{
if(!me->mtface) {
- if(me->mr) {
- multires_add_layer(me, &me->mr->fdata, CD_MTFACE,
- CustomData_number_of_layers(&me->fdata, CD_MTFACE));
- }
- else {
- me->mtface= CustomData_add_layer(&me->fdata, CD_MTFACE, CD_DEFAULT,
- NULL, me->totface);
- }
+ me->mtface= CustomData_add_layer(&me->fdata, CD_MTFACE, CD_DEFAULT,
+ NULL, me->totface);
}
}
diff --git a/source/blender/src/editkey.c b/source/blender/src/editkey.c
index dbabf9d19fb..ebc2698fe1f 100644
--- a/source/blender/src/editkey.c
+++ b/source/blender/src/editkey.c
@@ -600,27 +600,22 @@ void insert_curvekey(Curve *cu, short rel)
void insert_shapekey(Object *ob)
{
- if(get_mesh(ob) && get_mesh(ob)->mr) {
- error("Cannot create shape keys on a multires mesh.");
- }
- else {
- Key *key;
-
- if(ob->type==OB_MESH) insert_meshkey(ob->data, 1);
- else if ELEM(ob->type, OB_CURVE, OB_SURF) insert_curvekey(ob->data, 1);
- else if(ob->type==OB_LATTICE) insert_lattkey(ob->data, 1);
-
- key= ob_get_key(ob);
- ob->shapenr= BLI_countlist(&key->block);
-
- BIF_undo_push("Add Shapekey");
- allspace(REMAKEIPO, 0);
- allqueue(REDRAWIPO, 0);
- allqueue(REDRAWACTION, 0);
- allqueue(REDRAWNLA, 0);
- allqueue(REDRAWBUTSOBJECT, 0);
- allqueue(REDRAWBUTSEDIT, 0);
- }
+ Key *key;
+
+ if(ob->type==OB_MESH) insert_meshkey(ob->data, 1);
+ else if ELEM(ob->type, OB_CURVE, OB_SURF) insert_curvekey(ob->data, 1);
+ else if(ob->type==OB_LATTICE) insert_lattkey(ob->data, 1);
+
+ key= ob_get_key(ob);
+ ob->shapenr= BLI_countlist(&key->block);
+
+ BIF_undo_push("Add Shapekey");
+ allspace(REMAKEIPO, 0);
+ allqueue(REDRAWIPO, 0);
+ allqueue(REDRAWACTION, 0);
+ allqueue(REDRAWNLA, 0);
+ allqueue(REDRAWBUTSOBJECT, 0);
+ allqueue(REDRAWBUTSEDIT, 0);
}
void delete_key(Object *ob)
diff --git a/source/blender/src/editmesh.c b/source/blender/src/editmesh.c
index a573ea85ca8..136f28b62d5 100644
--- a/source/blender/src/editmesh.c
+++ b/source/blender/src/editmesh.c
@@ -108,7 +108,6 @@
#include "LBM_fluidsim.h"
-#include "multires.h"
#include "mydevice.h"
#include "blendef.h"
@@ -894,6 +893,9 @@ void make_editMesh()
}
#endif
+ /* Needed if multires mesh has been changed but updates haven't been stored yet */
+ multires_force_update(G.obedit);
+
/* because of reload */
free_editMesh(em);
@@ -1552,8 +1554,6 @@ void separate_material(void)
unsigned char curr_mat;
Mesh *me;
- if(multires_test()) return;
-
me= get_mesh(G.obedit);
if(me->key) {
error("Can't separate with vertex keys");
@@ -1595,7 +1595,6 @@ void separate_mesh(void)
#endif
TEST_EDITMESH
- if(multires_test()) return;
waitcursor(1);
@@ -1783,7 +1782,6 @@ void separate_mesh_loose(void)
}
TEST_EDITMESH
- if(multires_test()) return;
waitcursor(1);
/* we are going to abuse the system as follows:
@@ -1990,11 +1988,6 @@ typedef struct EditSelectionC{
int index;
}EditSelectionC;
-typedef struct EM_MultiresUndo {
- int users;
- Multires *mr;
-} EM_MultiresUndo;
-
typedef struct UndoMesh {
EditVertC *verts;
EditEdgeC *edges;
@@ -2005,7 +1998,6 @@ typedef struct UndoMesh {
RetopoPaintData *retopo_paint_data;
char retopo_mode;
CustomData vdata, edata, fdata;
- EM_MultiresUndo *mru;
} UndoMesh;
/* for callbacks */
@@ -2022,14 +2014,6 @@ static void free_undoMesh(void *umv)
CustomData_free(&um->vdata, um->totvert);
CustomData_free(&um->edata, um->totedge);
CustomData_free(&um->fdata, um->totface);
- if(um->mru) {
- --um->mru->users;
- if(um->mru->users==0) {
- multires_free(um->mru->mr);
- um->mru->mr= NULL;
- MEM_freeN(um->mru);
- }
- }
MEM_freeN(um);
}
@@ -2129,25 +2113,6 @@ static void *editMesh_to_undoMesh(void)
um->retopo_paint_data= retopo_paint_data_copy(em->retopo_paint_data);
um->retopo_mode= G.scene->toolsettings->retopo_mode;
- {
- Multires *mr= get_mesh(G.obedit)->mr;
- UndoMesh *prev= undo_editmode_get_prev(G.obedit);
-
- um->mru= NULL;
-
- if(mr) {
- if(prev && prev->mru && prev->mru->mr && prev->mru->mr->current == mr->current) {
- um->mru= prev->mru;
- ++um->mru->users;
- }
- else {
- um->mru= MEM_callocN(sizeof(EM_MultiresUndo), "EM_MultiresUndo");
- um->mru->users= 1;
- um->mru->mr= multires_copy(mr);
- }
- }
- }
-
return um;
}
@@ -2268,13 +2233,6 @@ static void undoMesh_to_editMesh(void *umv)
retopo_queue_updates(G.vd);
retopo_paint_view_update(G.vd);
}
-
- {
- Mesh *me= get_mesh(G.obedit);
- multires_free(me->mr);
- me->mr= NULL;
- if(um->mru && um->mru->mr) me->mr= multires_copy(um->mru->mr);
- }
}
diff --git a/source/blender/src/editmesh_add.c b/source/blender/src/editmesh_add.c
index 16a5b049da2..0e7017b714b 100644
--- a/source/blender/src/editmesh_add.c
+++ b/source/blender/src/editmesh_add.c
@@ -84,7 +84,6 @@
#include "BSE_edit.h"
#include "blendef.h"
-#include "multires.h"
#include "mydevice.h"
#include "editmesh.h"
@@ -159,7 +158,6 @@ void add_click_mesh(void)
int done= 0;
TEST_EDITMESH
- if(multires_test()) return;
INIT_MINMAX(min, max);
@@ -660,7 +658,6 @@ void addedgeface_mesh(void)
short amount=0;
if( (G.vd->lay & G.obedit->lay)==0 ) return;
- if(multires_test()) return;
/* how many selected ? */
if(G.scene->selectmode & SCE_SELECT_EDGE) {
@@ -820,7 +817,6 @@ void adduplicate_mesh(void)
{
TEST_EDITMESH
- if(multires_test()) return;
waitcursor(1);
@@ -1333,8 +1329,6 @@ void add_primitiveMesh(int type)
if ELEM(curarea->spacetype, SPACE_VIEW3D, SPACE_INFO); else return;
if(G.vd==0) return;
- if (G.obedit && G.obedit->type==OB_MESH && multires_test()) return;
-
/* if editmode exists for other type, it exits */
check_editmode(OB_MESH);
diff --git a/source/blender/src/editmesh_mods.c b/source/blender/src/editmesh_mods.c
index 3dbbe7d7336..1fefce55ad9 100644
--- a/source/blender/src/editmesh_mods.c
+++ b/source/blender/src/editmesh_mods.c
@@ -103,7 +103,6 @@ editmesh_mods.c, UI level access, no geometry changes
#include "RE_render_ext.h" /* externtex */
-#include "multires.h"
#include "mydevice.h"
#include "blendef.h"
@@ -134,9 +133,7 @@ void EM_select_mirrored(void)
void EM_automerge(int update) {
int len;
if ((G.scene->automerge) &&
- (G.obedit && G.obedit->type==OB_MESH) &&
- (((Mesh*)G.obedit->data)->mr==NULL)
- ) {
+ (G.obedit && G.obedit->type==OB_MESH)) {
len = removedoublesflag(1, 1, G.scene->toolsettings->doublimit);
if (len) {
G.totvert -= len; /* saves doing a countall */
@@ -3569,8 +3566,6 @@ void editmesh_mark_seam(int clear)
EditMesh *em= G.editMesh;
EditEdge *eed;
- if(multires_level1_test()) return;
-
/* auto-enable seams drawing */
if(clear==0) {
if(!(G.f & G_DRAWSEAMS)) {
@@ -3618,8 +3613,6 @@ void editmesh_mark_sharp(int set)
}
#endif
- if(multires_level1_test()) return;
-
if(set) {
eed= em->edges.first;
while(eed) {
diff --git a/source/blender/src/editmesh_tools.c b/source/blender/src/editmesh_tools.c
index 76f1443616f..827db085fd9 100644
--- a/source/blender/src/editmesh_tools.c
+++ b/source/blender/src/editmesh_tools.c
@@ -101,7 +101,6 @@ editmesh_tool.c: UI called tools for editmesh, geometry changes here, otherwise
#include "BSE_edit.h"
#include "blendef.h"
-#include "multires.h"
#include "mydevice.h"
#include "editmesh.h"
@@ -157,8 +156,6 @@ void convert_to_triface(int direction)
EditFace *efa, *efan, *next;
float fac;
- if(multires_test()) return;
-
efa= em->faces.last;
while(efa) {
next= efa->prev;
@@ -215,9 +212,6 @@ int removedoublesflag(short flag, short automerge, float limit) /* return amoun
struct facesort *vlsortblock, *vsb, *vsb1;
int a, b, test, amount;
- if(multires_test()) return 0;
-
-
/* flag 128 is cleared, count */
/* Normal non weld operation */
@@ -524,8 +518,6 @@ void xsortvert_flag(int flag)
ListBase tbase;
int i, amount = BLI_countlist(&em->verts);
- if(multires_test()) return;
-
sortblock = MEM_callocN(sizeof(xvertsort)*amount,"xsort");
for (i=0,eve=em->verts.first; eve; i++,eve=eve->next)
if(eve->f & flag)
@@ -567,8 +559,6 @@ void hashvert_flag(int flag)
ListBase tbase;
int amount, a, b;
- if(multires_test()) return;
-
/* count */
eve= em->verts.first;
amount= 0;
@@ -630,7 +620,6 @@ void extrude_mesh(void)
short nr, transmode= 0;
TEST_EDITMESH
- if(multires_test()) return;
if(G.scene->selectmode & SCE_SELECT_VERTEX) {
if(G.totvertsel==0) nr= 0;
@@ -703,9 +692,7 @@ void extrude_mesh(void)
void split_mesh(void)
{
-
TEST_EDITMESH
- if(multires_test()) return;
if(okee(" Split ")==0) return;
@@ -738,7 +725,6 @@ void extrude_repeat_mesh(int steps, float offs)
short a;
TEST_EDITMESH
- if(multires_test()) return;
/* dvec */
dvec[0]= G.vd->persinv[2][0];
@@ -781,7 +767,6 @@ void spin_mesh(int steps, float degr, float *dvec, int mode)
short a,ok;
TEST_EDITMESH
- if(multires_test()) return;
/* imat and center and size */
Mat3CpyMat4(bmat, G.obedit->obmat);
@@ -867,7 +852,6 @@ void screw_mesh(int steps, int turns)
float dvec[3], nor[3];
TEST_EDITMESH
- if(multires_test()) return;
/* clear flags */
eve= em->verts.first;
@@ -981,7 +965,6 @@ void delete_mesh(void)
char *str="Erase";
TEST_EDITMESH
- if(multires_test()) return;
event= pupmenu("Erase %t|Vertices%x10|Edges%x1|Faces%x2|All%x3|Edges & Faces%x4|Only Faces%x5|Edge Loop%x6");
if(event<1) return;
@@ -1129,7 +1112,6 @@ void fill_mesh(void)
short ok;
if(G.obedit==0 || (G.obedit->type!=OB_MESH)) return;
- if(multires_test()) return;
waitcursor(1);
@@ -2429,8 +2411,6 @@ void esubdivideflag(int flag, float rad, int beauty, int numcuts, int seltype)
int i, j, edgecount, touchcount, facetype,hold;
ModifierData *md= G.obedit->modifiers.first;
- if(multires_test()) return;
-
//Set faces f1 to 0 cause we need it later
for(ef=em->faces.first;ef;ef = ef->next) ef->f1 = 0;
for(eve=em->verts.first; eve; eve=eve->next) {
@@ -2991,8 +2971,6 @@ void beauty_fill(void)
float len1, len2, len3, len4, len5, len6, opp1, opp2, fac1, fac2;
int totedge, ok, notbeauty=8, onedone, vindex[4];
- if(multires_test()) return;
-
/* - all selected edges with two faces
* - find the faces: store them in edges (using datablock)
* - per edge: - test convex
@@ -3303,9 +3281,6 @@ void join_triangles(void)
float limit = G.scene->toolsettings->jointrilimit;
int i, ok, totedge=0, totseledge=0, complexedges, vindex[4];
- /*test for multi-resolution data*/
- if(multires_test()) return;
-
/*if we take a long time on very dense meshes we want waitcursor to display*/
waitcursor(1);
@@ -4111,8 +4086,6 @@ static void bevel_mesh(float bsize, int allfaces)
int a, b, c;
float limit= 0.001f;
- if(multires_test()) return;
-
waitcursor(1);
removedoublesflag(1, 0, limit);
@@ -6469,8 +6442,6 @@ int collapseEdges(void)
mergecount = 0;
- if(multires_test()) return 0;
-
build_edgecollection(&allcollections);
groupcount = BLI_countlist(&allcollections);
@@ -6530,8 +6501,6 @@ int merge_firstlast(int first, int uvmerge)
EditVert *eve,*mergevert;
EditSelection *ese;
- if(multires_test()) return 0;
-
/* do sanity check in mergemenu in edit.c ?*/
if(first == 0){
ese = G.editMesh->selected.last;
@@ -6566,8 +6535,6 @@ int merge_target(int target, int uvmerge)
{
EditVert *eve;
- if(multires_test()) return 0;
-
if(target) snap_sel_to_curs();
else snap_to_center();
diff --git a/source/blender/src/editobject.c b/source/blender/src/editobject.c
index 4a70e89dd07..d70efa465d5 100644
--- a/source/blender/src/editobject.c
+++ b/source/blender/src/editobject.c
@@ -1800,9 +1800,6 @@ void exit_editmode(int flag) /* freedata==0 at render, 1= freedata, 2= do undo b
/* for example; displist make is different in editmode */
if(freedata) G.obedit= NULL;
- if(ob->type==OB_MESH && get_mesh(ob)->mr)
- multires_edge_level_update(ob, get_mesh(ob));
-
/* also flush ob recalc, doesn't take much overhead, but used for particles */
DAG_object_flush_update(G.scene, ob, OB_RECALC_OB|OB_RECALC_DATA);
diff --git a/source/blender/src/editsima.c b/source/blender/src/editsima.c
index 7fc76dd5202..f06fa5eaa6b 100644
--- a/source/blender/src/editsima.c
+++ b/source/blender/src/editsima.c
@@ -105,7 +105,6 @@
#include "RE_pipeline.h"
#include "blendef.h"
-#include "multires.h"
#include "mydevice.h"
#include "editmesh.h"
@@ -132,7 +131,6 @@ int is_uv_tface_editing_allowed_silent(void)
{
if(!EM_texFaceCheck()) return 0;
if(G.sima->mode!=SI_TEXTURE) return 0;
- if(multires_level1_test()) return 0;
return 1;
}
diff --git a/source/blender/src/header_view3d.c b/source/blender/src/header_view3d.c
index 60c5854f1a5..8b613b3990c 100644
--- a/source/blender/src/header_view3d.c
+++ b/source/blender/src/header_view3d.c
@@ -131,7 +131,6 @@
#endif
#include "blendef.h"
-#include "multires.h"
#include "mydevice.h"
#include "butspace.h"
@@ -2792,10 +2791,8 @@ void do_view3d_edit_mesh_edgesmenu(void *arg, int event)
editmesh_mark_seam(1);
break;
case 9: /* Crease SubSurf */
- if(!multires_level1_test()) {
- initTransform(TFM_CREASE, CTX_EDGE);
- Transform();
- }
+ initTransform(TFM_CREASE, CTX_EDGE);
+ Transform();
break;
case 10: /* Rotate Edge */
edge_rotate_selected(2);
@@ -2828,10 +2825,8 @@ void do_view3d_edit_mesh_edgesmenu(void *arg, int event)
DAG_object_flush_update(G.scene, G.obedit, OB_RECALC_DATA);
break;
case 17: /* Adjust Bevel Weight */
- if(!multires_level1_test()) {
- initTransform(TFM_BWEIGHT, CTX_EDGE);
- Transform();
- }
+ initTransform(TFM_BWEIGHT, CTX_EDGE);
+ Transform();
break;
}
allqueue(REDRAWVIEW3D, 0);
diff --git a/source/blender/src/keyframing.c b/source/blender/src/keyframing.c
deleted file mode 100644
index d9c729e7df6..00000000000
--- a/source/blender/src/keyframing.c
+++ /dev/null
@@ -1,2104 +0,0 @@
-/**
- * $Id$
- *
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
- *
- * The Original Code is Copyright (C) 2008, Blender Foundation
- * This is a new part of Blender (with some old code)
- *
- * Contributor(s): Joshua Leung
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-#include <stdio.h>
-#include <string.h>
-#include <stdlib.h>
-#include <stddef.h>
-#include <math.h>
-
-#ifdef HAVE_CONFIG_H
-#include <config.h>
-#endif
-
-#include "MEM_guardedalloc.h"
-
-#include "BLI_arithb.h"
-#include "BLI_blenlib.h"
-#include "BLI_dynstr.h"
-
-#include "DNA_listBase.h"
-#include "DNA_ID.h"
-#include "DNA_action_types.h"
-#include "DNA_armature_types.h"
-#include "DNA_camera_types.h"
-#include "DNA_constraint_types.h"
-#include "DNA_curve_types.h"
-#include "DNA_ipo_types.h"
-#include "DNA_key_types.h"
-#include "DNA_lamp_types.h"
-#include "DNA_object_types.h"
-#include "DNA_material_types.h"
-#include "DNA_screen_types.h"
-#include "DNA_scene_types.h"
-#include "DNA_space_types.h"
-#include "DNA_texture_types.h"
-#include "DNA_userdef_types.h"
-#include "DNA_vec_types.h"
-#include "DNA_view3d_types.h"
-#include "DNA_world_types.h"
-
-#include "BKE_global.h"
-#include "BKE_utildefines.h"
-#include "BKE_blender.h"
-#include "BKE_main.h"
-#include "BKE_action.h"
-#include "BKE_armature.h"
-#include "BKE_constraint.h"
-#include "BKE_curve.h"
-#include "BKE_depsgraph.h"
-#include "BKE_ipo.h"
-#include "BKE_key.h"
-#include "BKE_object.h"
-#include "BKE_material.h"
-
-#include "BIF_keyframing.h"
-#include "BIF_butspace.h"
-#include "BIF_editaction.h"
-#include "BIF_editkey.h"
-#include "BIF_interface.h"
-#include "BIF_mywindow.h"
-#include "BIF_poseobject.h"
-#include "BIF_screen.h"
-#include "BIF_space.h"
-#include "BIF_toolbox.h"
-#include "BIF_toets.h"
-
-#include "BSE_editipo.h"
-#include "BSE_node.h"
-#include "BSE_time.h"
-#include "BSE_view.h"
-
-#include "blendef.h"
-
-#include "PIL_time.h" /* sleep */
-#include "mydevice.h"
-
-/* ************************************************** */
-/* LOCAL TYPES AND DEFINES */
-
-/* -------------- Keying Sets ------------------- */
-
-/* keying set - a set of channels that will be keyframed together */
-// TODO: move this to a header to allow custom sets someday?
-typedef struct bKeyingSet {
- /* callback func to consider if keyingset should be included
- * (by default, if this is undefined, item will be shown)
- */
- short (*include_cb)(struct bKeyingSet *, const char *);
-
- char name[48]; /* name of keyingset */
- int blocktype; /* blocktype that all channels belong to */ // in future, this may be eliminated
- short flag; /* flags to use when setting keyframes */
-
- short chan_num; /* number of channels to insert keyframe in */
- short adrcodes[32]; /* adrcodes for channels to insert keys for (ideally would be variable-len, but limit of 32 will suffice) */
-} bKeyingSet;
-
-/* keying set context - an array of keying sets and the number of them */
-typedef struct bKeyingContext {
- bKeyingSet *keyingsets; /* array containing the keyingsets of interest */
- bKeyingSet *lastused; /* item that was chosen last time*/
- int tot; /* number of keyingsets in */
-} bKeyingContext;
-
-
-/* ----------- Common KeyData Sources ------------ */
-
-/* temporary struct to gather data combos to keyframe */
-typedef struct bCommonKeySrc {
- struct bCommonKeySrc *next, *prev;
-
- /* general data/destination-source settings */
- ID *id; /* id-block this comes from */
- char *actname; /* name of action channel */
- char *constname; /* name of constraint channel */
-
- /* general destination source settings */
- Ipo *ipo; /* ipo-block that id-block has (optional) */
- bAction *act; /* action-block that id-block has (optional) */
-
- /* pose-level settings */
- bPoseChannel *pchan; /* pose channel */
-
- /* buttons-window settings */
- int map; /* offset to apply to certain adrcodes */
-} bCommonKeySrc;
-
-/* ************************************************** */
-/* KEYFRAME INSERTION */
-
-/* -------------- BezTriple Insertion -------------------- */
-
-/* threshold for inserting keyframes - threshold here should be good enough for now, but should become userpref */
-#define BEZT_INSERT_THRESH 0.00001
-
-/* Binary search algorithm for finding where to insert BezTriple. (for use by insert_bezt_icu)
- * Returns the index to insert at (data already at that index will be offset if replace is 0)
- */
-static int binarysearch_bezt_index (BezTriple array[], float frame, int arraylen, short *replace)
-{
- int start=0, end=arraylen;
- int loopbreaker= 0, maxloop= arraylen * 2;
-
- /* initialise replace-flag first */
- *replace= 0;
-
- /* sneaky optimisations (don't go through searching process if...):
- * - keyframe to be added is to be added out of current bounds
- * - keyframe to be added would replace one of the existing ones on bounds
- */
- if ((arraylen <= 0) || (array == NULL)) {
- printf("Warning: binarysearch_bezt_index encountered invalid array \n");
- return 0;
- }
- else {
- /* check whether to add before/after/on */
- float framenum;
-
- /* 'First' Keyframe (when only one keyframe, this case is used) */
- framenum= array[0].vec[1][0];
- if (IS_EQT(frame, framenum, BEZT_INSERT_THRESH)) {
- *replace = 1;
- return 0;
- }
- else if (frame < framenum)
- return 0;
-
- /* 'Last' Keyframe */
- framenum= array[(arraylen-1)].vec[1][0];
- if (IS_EQT(frame, framenum, BEZT_INSERT_THRESH)) {
- *replace= 1;
- return (arraylen - 1);
- }
- else if (frame > framenum)
- return arraylen;
- }
-
-
- /* most of the time, this loop is just to find where to put it
- * 'loopbreaker' is just here to prevent infinite loops
- */
- for (loopbreaker=0; (start <= end) && (loopbreaker < maxloop); loopbreaker++) {
- /* compute and get midpoint */
- int mid = (start + end) / 2;
- float midfra= array[mid].vec[1][0];
-
- /* check if exactly equal to midpoint */
- if (IS_EQT(frame, midfra, BEZT_INSERT_THRESH)) {
- *replace = 1;
- return mid;
- }
-
- /* repeat in upper/lower half */
- if (frame > midfra)
- start= mid + 1;
- else if (frame < midfra)
- end= mid - 1;
- }
-
- /* print error if loop-limit exceeded */
- if (loopbreaker == (maxloop-1)) {
- printf("Error: binarysearch_bezt_index was taking too long \n");
-
- // include debug info
- printf("\tround = %d: start = %d, end = %d, arraylen = %d \n", loopbreaker, start, end, arraylen);
- }
-
- /* not found, so return where to place it */
- return start;
-}
-
-/* This function adds a given BezTriple to an IPO-Curve. It will allocate
- * memory for the array if needed, and will insert the BezTriple into a
- * suitable place in chronological order.
- *
- * NOTE: any recalculate of the IPO-Curve that needs to be done will need to
- * be done by the caller.
- */
-int insert_bezt_icu (IpoCurve *icu, BezTriple *bezt)
-{
- BezTriple *newb;
- int i= 0;
-
- if (icu->bezt == NULL) {
- icu->bezt= MEM_callocN(sizeof(BezTriple), "beztriple");
- *(icu->bezt)= *bezt;
- icu->totvert= 1;
- }
- else {
- short replace = -1;
- i = binarysearch_bezt_index(icu->bezt, bezt->vec[1][0], icu->totvert, &replace);
-
- if (replace) {
- /* sanity check: 'i' may in rare cases exceed arraylen */
- if ((i >= 0) && (i < icu->totvert))
- *(icu->bezt + i) = *bezt;
- }
- else {
- /* add new */
- newb= MEM_callocN((icu->totvert+1)*sizeof(BezTriple), "beztriple");
-
- /* add the beztriples that should occur before the beztriple to be pasted (originally in ei->icu) */
- if (i > 0)
- memcpy(newb, icu->bezt, i*sizeof(BezTriple));
-
- /* add beztriple to paste at index i */
- *(newb + i)= *bezt;
-
- /* add the beztriples that occur after the beztriple to be pasted (originally in icu) */
- if (i < icu->totvert)
- memcpy(newb+i+1, icu->bezt+i, (icu->totvert-i)*sizeof(BezTriple));
-
- /* replace (+ free) old with new */
- MEM_freeN(icu->bezt);
- icu->bezt= newb;
-
- icu->totvert++;
- }
- }
-
- /* we need to return the index, so that some tools which do post-processing can
- * detect where we added the BezTriple in the array
- */
- return i;
-}
-
-/* This function is a wrapper for insert_bezt_icu, and should be used when
- * adding a new keyframe to a curve, when the keyframe doesn't exist anywhere
- * else yet.
- *
- * 'fast' - is only for the python API where importing BVH's would take an extreamly long time.
- */
-void insert_vert_icu (IpoCurve *icu, float x, float y, short fast)
-{
- BezTriple beztr;
- int a, h1, h2;
-
- /* set all three points, for nicer start position */
- memset(&beztr, 0, sizeof(BezTriple));
- beztr.vec[0][0]= x;
- beztr.vec[0][1]= y;
- beztr.vec[1][0]= x;
- beztr.vec[1][1]= y;
- beztr.vec[2][0]= x;
- beztr.vec[2][1]= y;
- beztr.hide= IPO_BEZ;
- beztr.f1= beztr.f2= beztr.f3= SELECT;
- beztr.h1= beztr.h2= HD_AUTO;
-
- /* add temp beztriple to keyframes */
- a= insert_bezt_icu(icu, &beztr);
- if (!fast) calchandles_ipocurve(icu);
-
- /* set handletype */
- if (icu->totvert > 2) {
- BezTriple *bezt;
-
- h1= h2= HD_AUTO;
- bezt= (icu->bezt + a);
-
- if (a > 0) h1= (bezt-1)->h2;
- if (a < icu->totvert-1) h2= (bezt+1)->h1;
-
- bezt->h1= h1;
- bezt->h2= h2;
-
- if (!fast) calchandles_ipocurve(icu);
- }
-}
-
-/* ------------------- Get Data ------------------------ */
-
-/* Get pointer to use to get values from */
-// FIXME: this should not be possible with Data-API
-static void *get_context_ipo_poin (ID *id, int blocktype, char *actname, char *constname, IpoCurve *icu, int *vartype)
-{
- switch (blocktype) {
- case ID_PO: /* posechannel */
- if (GS(id->name)==ID_OB) {
- Object *ob= (Object *)id;
- bPoseChannel *pchan= get_pose_channel(ob->pose, actname);
-
- if (pchan) {
- *vartype= IPO_FLOAT;
- return get_pchan_ipo_poin(pchan, icu->adrcode);
- }
- }
- break;
-
- case ID_CO: /* constraint */
- if ((GS(id->name)==ID_OB) && (constname && constname[0])) {
- Object *ob= (Object *)id;
- bConstraint *con;
-
- /* assume that we only want the influence (as only used for Constraint Channels) */
- if ((ob->ipoflag & OB_ACTION_OB) && !strcmp(actname, "Object")) {
- for (con= ob->constraints.first; con; con= con->next) {
- if (strcmp(constname, con->name)==0) {
- *vartype= IPO_FLOAT;
- return &con->enforce;
- }
- }
- }
- else if (ob->pose) {
- bPoseChannel *pchan= get_pose_channel(ob->pose, actname);
-
- if (pchan) {
- for (con= pchan->constraints.first; con; con= con->next) {
- if (strcmp(constname, con->name)==0) {
- *vartype= IPO_FLOAT;
- return &con->enforce;
- }
- }
- }
- }
- }
- break;
-
- case ID_OB: /* object */
- /* hack: layer channels for object need to be keyed WITHOUT localview flag...
- * tsk... tsk... why must we just dump bitflags upon users :/
- */
- if ((GS(id->name)==ID_OB) && (icu->adrcode==OB_LAY)) {
- Object *ob= (Object *)id;
- static int layer = 0;
-
- /* init layer to be the object's layer var, then remove local view from it */
- layer = ob->lay;
- layer &= 0xFFFFFF;
- *vartype= IPO_INT_BIT;
-
- /* return pointer to this static var
- * - assumes that this pointer won't be stored for use later, so may not be threadsafe
- * if multiple keyframe calls are made, but that is unlikely to happen in the near future
- */
- return (void *)(&layer);
- }
- /* no break here for other ob channel-types - as they can be done normally */
-
- default: /* normal data-source */
- return get_ipo_poin(id, icu, vartype);
- }
-
- /* not valid... */
- return NULL;
-}
-
-
-/* -------------- 'Smarter' Keyframing Functions -------------------- */
-/* return codes for new_key_needed */
-enum {
- KEYNEEDED_DONTADD = 0,
- KEYNEEDED_JUSTADD,
- KEYNEEDED_DELPREV,
- KEYNEEDED_DELNEXT
-} eKeyNeededStatus;
-
-/* This helper function determines whether a new keyframe is needed */
-/* Cases where keyframes should not be added:
- * 1. Keyframe to be added bewteen two keyframes with similar values
- * 2. Keyframe to be added on frame where two keyframes are already situated
- * 3. Keyframe lies at point that intersects the linear line between two keyframes
- */
-static short new_key_needed (IpoCurve *icu, float cFrame, float nValue)
-{
- BezTriple *bezt=NULL, *prev=NULL;
- int totCount, i;
- float valA = 0.0f, valB = 0.0f;
-
- /* safety checking */
- if (icu == NULL) return KEYNEEDED_JUSTADD;
- totCount= icu->totvert;
- if (totCount == 0) return KEYNEEDED_JUSTADD;
-
- /* loop through checking if any are the same */
- bezt= icu->bezt;
- for (i=0; i<totCount; i++) {
- float prevPosi=0.0f, prevVal=0.0f;
- float beztPosi=0.0f, beztVal=0.0f;
-
- /* get current time+value */
- beztPosi= bezt->vec[1][0];
- beztVal= bezt->vec[1][1];
-
- if (prev) {
- /* there is a keyframe before the one currently being examined */
-
- /* get previous time+value */
- prevPosi= prev->vec[1][0];
- prevVal= prev->vec[1][1];
-
- /* keyframe to be added at point where there are already two similar points? */
- if (IS_EQ(prevPosi, cFrame) && IS_EQ(beztPosi, cFrame) && IS_EQ(beztPosi, prevPosi)) {
- return KEYNEEDED_DONTADD;
- }
-
- /* keyframe between prev+current points ? */
- if ((prevPosi <= cFrame) && (cFrame <= beztPosi)) {
- /* is the value of keyframe to be added the same as keyframes on either side ? */
- if (IS_EQ(prevVal, nValue) && IS_EQ(beztVal, nValue) && IS_EQ(prevVal, beztVal)) {
- return KEYNEEDED_DONTADD;
- }
- else {
- float realVal;
-
- /* get real value of curve at that point */
- realVal= eval_icu(icu, cFrame);
-
- /* compare whether it's the same as proposed */
- if (IS_EQ(realVal, nValue))
- return KEYNEEDED_DONTADD;
- else
- return KEYNEEDED_JUSTADD;
- }
- }
-
- /* new keyframe before prev beztriple? */
- if (cFrame < prevPosi) {
- /* A new keyframe will be added. However, whether the previous beztriple
- * stays around or not depends on whether the values of previous/current
- * beztriples and new keyframe are the same.
- */
- if (IS_EQ(prevVal, nValue) && IS_EQ(beztVal, nValue) && IS_EQ(prevVal, beztVal))
- return KEYNEEDED_DELNEXT;
- else
- return KEYNEEDED_JUSTADD;
- }
- }
- else {
- /* just add a keyframe if there's only one keyframe
- * and the new one occurs before the exisiting one does.
- */
- if ((cFrame < beztPosi) && (totCount==1))
- return KEYNEEDED_JUSTADD;
- }
-
- /* continue. frame to do not yet passed (or other conditions not met) */
- if (i < (totCount-1)) {
- prev= bezt;
- bezt++;
- }
- else
- break;
- }
-
- /* Frame in which to add a new-keyframe occurs after all other keys
- * -> If there are at least two existing keyframes, then if the values of the
- * last two keyframes and the new-keyframe match, the last existing keyframe
- * gets deleted as it is no longer required.
- * -> Otherwise, a keyframe is just added. 1.0 is added so that fake-2nd-to-last
- * keyframe is not equal to last keyframe.
- */
- bezt= (icu->bezt + (icu->totvert - 1));
- valA= bezt->vec[1][1];
-
- if (prev)
- valB= prev->vec[1][1];
- else
- valB= bezt->vec[1][1] + 1.0f;
-
- if (IS_EQ(valA, nValue) && IS_EQ(valA, valB))
- return KEYNEEDED_DELPREV;
- else
- return KEYNEEDED_JUSTADD;
-}
-
-/* ------------------ 'Visual' Keyframing Functions ------------------ */
-
-/* internal status codes for visualkey_can_use */
-enum {
- VISUALKEY_NONE = 0,
- VISUALKEY_LOC,
- VISUALKEY_ROT
-};
-
-/* This helper function determines if visual-keyframing should be used when
- * inserting keyframes for the given channel. As visual-keyframing only works
- * on Object and Pose-Channel blocks, this should only get called for those
- * blocktypes, when using "standard" keying but 'Visual Keying' option in Auto-Keying
- * settings is on.
- */
-static short visualkey_can_use (ID *id, int blocktype, char *actname, char *constname, int adrcode)
-{
- Object *ob= NULL;
- bConstraint *con= NULL;
- short searchtype= VISUALKEY_NONE;
-
- /* validate data */
- if ((id == NULL) || (GS(id->name)!=ID_OB) || !(ELEM(blocktype, ID_OB, ID_PO)))
- return 0;
-
- /* get first constraint and determine type of keyframe constraints to check for*/
- ob= (Object *)id;
-
- if (blocktype == ID_OB) {
- con= ob->constraints.first;
-
- if (ELEM3(adrcode, OB_LOC_X, OB_LOC_Y, OB_LOC_Z))
- searchtype= VISUALKEY_LOC;
- else if (ELEM3(adrcode, OB_ROT_X, OB_ROT_Y, OB_ROT_Z))
- searchtype= VISUALKEY_ROT;
- }
- else if (blocktype == ID_PO) {
- bPoseChannel *pchan= get_pose_channel(ob->pose, actname);
- con= pchan->constraints.first;
-
- if (ELEM3(adrcode, AC_LOC_X, AC_LOC_Y, AC_LOC_Z))
- searchtype= VISUALKEY_LOC;
- else if (ELEM4(adrcode, AC_QUAT_W, AC_QUAT_X, AC_QUAT_Y, AC_QUAT_Z))
- searchtype= VISUALKEY_ROT;
- }
-
- /* only search if a searchtype and initial constraint are available */
- if (searchtype && con) {
- for (; con; con= con->next) {
- /* only consider constraint if it is not disabled, and has influence */
- if (con->flag & CONSTRAINT_DISABLE) continue;
- if (con->enforce == 0.0f) continue;
-
- /* some constraints may alter these transforms */
- switch (con->type) {
- /* multi-transform constraints */
- case CONSTRAINT_TYPE_CHILDOF:
- return 1;
- case CONSTRAINT_TYPE_TRANSFORM:
- return 1;
- case CONSTRAINT_TYPE_FOLLOWPATH:
- return 1;
- case CONSTRAINT_TYPE_KINEMATIC:
- return 1;
-
- /* single-transform constraits */
- case CONSTRAINT_TYPE_TRACKTO:
- if (searchtype==VISUALKEY_ROT) return 1;
- break;
- case CONSTRAINT_TYPE_ROTLIMIT:
- if (searchtype==VISUALKEY_ROT) return 1;
- break;
- case CONSTRAINT_TYPE_LOCLIMIT:
- if (searchtype==VISUALKEY_LOC) return 1;
- break;
- case CONSTRAINT_TYPE_ROTLIKE:
- if (searchtype==VISUALKEY_ROT) return 1;
- break;
- case CONSTRAINT_TYPE_DISTLIMIT:
- if (searchtype==VISUALKEY_LOC) return 1;
- break;
- case CONSTRAINT_TYPE_LOCLIKE:
- if (searchtype==VISUALKEY_LOC) return 1;
- break;
- case CONSTRAINT_TYPE_LOCKTRACK:
- if (searchtype==VISUALKEY_ROT) return 1;
- break;
- case CONSTRAINT_TYPE_MINMAX:
- if (searchtype==VISUALKEY_LOC) return 1;
- break;
-
- default:
- break;
- }
- }
- }
-
- /* when some condition is met, this function returns, so here it can be 0 */
- return 0;
-}
-
-/* This helper function extracts the value to use for visual-keyframing
- * In the event that it is not possible to perform visual keying, try to fall-back
- * to using the poin method. Assumes that all data it has been passed is valid.
- */
-static float visualkey_get_value (ID *id, int blocktype, char *actname, char *constname, int adrcode, IpoCurve *icu)
-{
- Object *ob;
- void *poin = NULL;
- int index, vartype;
-
- /* validate situtation */
- if ((id==NULL) || (GS(id->name)!=ID_OB) || (ELEM(blocktype, ID_OB, ID_PO)==0))
- return 0.0f;
-
- /* get object */
- ob= (Object *)id;
-
- /* only valid for objects or posechannels */
- if (blocktype == ID_OB) {
- /* parented objects are not supported, as the effects of the parent
- * are included in the matrix, which kindof beats the point
- */
- if (ob->parent == NULL) {
- /* only Location or Rotation keyframes are supported now */
- if (ELEM3(adrcode, OB_LOC_X, OB_LOC_Y, OB_LOC_Z)) {
- /* assumes that OB_LOC_Z > OB_LOC_Y > OB_LOC_X */
- index= adrcode - OB_LOC_X;
-
- return ob->obmat[3][index];
- }
- else if (ELEM3(adrcode, OB_ROT_X, OB_ROT_Y, OB_ROT_Z)) {
- float eul[3];
-
- /* assumes that OB_ROT_Z > OB_ROT_Y > OB_ROT_X */
- index= adrcode - OB_ROT_X;
-
- Mat4ToEul(ob->obmat, eul);
- return eul[index]*(5.72958f);
- }
- }
- }
- else if (blocktype == ID_PO) {
- bPoseChannel *pchan;
- float tmat[4][4];
-
- /* get data to use */
- pchan= get_pose_channel(ob->pose, actname);
-
- /* Although it is not strictly required for this particular space conversion,
- * arg1 must not be null, as there is a null check for the other conversions to
- * be safe. Therefore, the active object is passed here, and in many cases, this
- * will be what owns the pose-channel that is getting this anyway.
- */
- Mat4CpyMat4(tmat, pchan->pose_mat);
- constraint_mat_convertspace(ob, pchan, tmat, CONSTRAINT_SPACE_POSE, CONSTRAINT_SPACE_LOCAL);
-
- /* Loc, Rot/Quat keyframes are supported... */
- if (ELEM3(adrcode, AC_LOC_X, AC_LOC_Y, AC_LOC_Z)) {
- /* assumes that AC_LOC_Z > AC_LOC_Y > AC_LOC_X */
- index= adrcode - AC_LOC_X;
-
- /* only use for non-connected bones */
- if ((pchan->bone->parent) && !(pchan->bone->flag & BONE_CONNECTED))
- return tmat[3][index];
- else if (pchan->bone->parent == NULL)
- return tmat[3][index];
- }
- else if (ELEM4(adrcode, AC_QUAT_W, AC_QUAT_X, AC_QUAT_Y, AC_QUAT_Z)) {
- float trimat[3][3], quat[4];
-
- /* assumes that AC_QUAT_Z > AC_QUAT_Y > AC_QUAT_X > AC_QUAT_W */
- index= adrcode - AC_QUAT_W;
-
- Mat3CpyMat4(trimat, tmat);
- Mat3ToQuat_is_ok(trimat, quat);
-
- return quat[index];
- }
- }
-
- /* as the function hasn't returned yet, try reading from poin */
- poin= get_context_ipo_poin(id, blocktype, actname, constname, icu, &vartype);
- if (poin)
- return read_ipo_poin(poin, vartype);
- else
- return 0.0;
-}
-
-
-/* ------------------------- Insert Key API ------------------------- */
-
-/* Main Keyframing API call:
- * Use this when validation of necessary animation data isn't necessary as it
- * already exists. It will insert a keyframe using the current value being keyframed.
- *
- * The flag argument is used for special settings that alter the behaviour of
- * the keyframe insertion. These include the 'visual' keyframing modes, quick refresh,
- * and extra keyframe filtering.
- */
-short insertkey (ID *id, int blocktype, char *actname, char *constname, int adrcode, short flag)
-{
- IpoCurve *icu;
-
- /* get ipo-curve */
- icu= verify_ipocurve(id, blocktype, actname, constname, NULL, adrcode, 1);
-
- /* only continue if we have an ipo-curve to add keyframe to */
- if (icu) {
- float cfra = frame_to_float(CFRA);
- float curval= 0.0f;
-
- /* apply special time tweaking */
- if (GS(id->name) == ID_OB) {
- Object *ob= (Object *)id;
-
- /* apply NLA-scaling (if applicable) */
- if (actname && actname[0])
- cfra= get_action_frame(ob, cfra);
-
- /* ancient time-offset cruft */
- if ( (ob->ipoflag & OB_OFFS_OB) && (give_timeoffset(ob)) ) {
- /* actually frametofloat calc again! */
- cfra-= give_timeoffset(ob)*G.scene->r.framelen;
- }
- }
-
- /* obtain value to give keyframe */
- if ( (flag & INSERTKEY_MATRIX) &&
- (visualkey_can_use(id, blocktype, actname, constname, adrcode)) )
- {
- /* visual-keying is only available for object and pchan datablocks, as
- * it works by keyframing using a value extracted from the final matrix
- * instead of using the kt system to extract a value.
- */
- curval= visualkey_get_value(id, blocktype, actname, constname, adrcode, icu);
- }
- else {
- void *poin;
- int vartype;
-
- /* get pointer to data to read from */
- poin = get_context_ipo_poin(id, blocktype, actname, constname, icu, &vartype);
- if (poin == NULL) {
- printf("Insert Key: No pointer to variable obtained \n");
- return 0;
- }
-
- /* use kt's read_poin function to extract value (kt->read_poin should
- * exist in all cases, but it never hurts to check)
- */
- curval= read_ipo_poin(poin, vartype);
- }
-
- /* only insert keyframes where they are needed */
- if (flag & INSERTKEY_NEEDED) {
- short insert_mode;
-
- /* check whether this curve really needs a new keyframe */
- insert_mode= new_key_needed(icu, cfra, curval);
-
- /* insert new keyframe at current frame */
- if (insert_mode)
- insert_vert_icu(icu, cfra, curval, (flag & INSERTKEY_FAST));
-
- /* delete keyframe immediately before/after newly added */
- switch (insert_mode) {
- case KEYNEEDED_DELPREV:
- delete_icu_key(icu, icu->totvert-2, 1);
- break;
- case KEYNEEDED_DELNEXT:
- delete_icu_key(icu, 1, 1);
- break;
- }
-
- /* only return success if keyframe added */
- if (insert_mode)
- return 1;
- }
- else {
- /* just insert keyframe */
- insert_vert_icu(icu, cfra, curval, (flag & INSERTKEY_FAST));
-
- /* return success */
- return 1;
- }
- }
-
- /* return failure */
- return 0;
-}
-
-
-/* ************************************************** */
-/* KEYFRAME DELETION */
-
-/* Main Keyframing API call:
- * Use this when validation of necessary animation data isn't necessary as it
- * already exists. It will delete a keyframe at the current frame.
- *
- * The flag argument is used for special settings that alter the behaviour of
- * the keyframe deletion. These include the quick refresh options.
- */
-short deletekey (ID *id, int blocktype, char *actname, char *constname, int adrcode, short flag)
-{
- Ipo *ipo;
- IpoCurve *icu;
-
- /* get ipo-curve
- * Note: here is one of the places where we don't want new ipo + ipo-curve added!
- * so 'add' var must be 0
- */
- ipo= verify_ipo(id, blocktype, actname, constname, NULL, 0);
- icu= verify_ipocurve(id, blocktype, actname, constname, NULL, adrcode, 0);
-
- /* only continue if we have an ipo-curve to remove keyframes from */
- if (icu) {
- float cfra = frame_to_float(CFRA);
- short found = -1;
- int i;
-
- /* apply special time tweaking */
- if (GS(id->name) == ID_OB) {
- Object *ob= (Object *)id;
-
- /* apply NLA-scaling (if applicable) */
- if (actname && actname[0])
- cfra= get_action_frame(ob, cfra);
-
- /* ancient time-offset cruft */
- if ( (ob->ipoflag & OB_OFFS_OB) && (give_timeoffset(ob)) ) {
- /* actually frametofloat calc again! */
- cfra-= give_timeoffset(ob)*G.scene->r.framelen;
- }
- }
-
- /* try to find index of beztriple to get rid of */
- i = binarysearch_bezt_index(icu->bezt, cfra, icu->totvert, &found);
- if (found) {
- /* delete the key at the index (will sanity check + do recalc afterwards ) */
- delete_icu_key(icu, i, 1);
-
- /* Only delete curve too if there isn't an ipo-driver still hanging around on an empty curve */
- if (icu->totvert==0 && icu->driver==NULL) {
- BLI_remlink(&ipo->curve, icu);
- free_ipo_curve(icu);
- }
-
- /* return success */
- return 1;
- }
- }
-
- /* return failure */
- return 0;
-}
-
-/* ************************************************** */
-/* COMMON KEYFRAME MANAGEMENT (common_insertkey/deletekey) */
-
-/* mode for common_modifykey */
-enum {
- COMMONKEY_MODE_INSERT = 0,
- COMMONKEY_MODE_DELETE,
-} eCommonModifyKey_Modes;
-
-/* ------------- KeyingSet Defines ------------ */
-/* Note: these must all be named with the defks_* prefix, otherwise the template macro will not work! */
-
-/* macro for defining keyingset contexts */
-#define KSC_TEMPLATE(ctx_name) {&defks_##ctx_name[0], NULL, sizeof(defks_##ctx_name)/sizeof(bKeyingSet)}
-
-/* --- */
-
-/* check if option not available for deleting keys */
-static short incl_non_del_keys (bKeyingSet *ks, const char mode[])
-{
- /* as optimisation, assume that it is sufficient to check only first letter
- * of mode (int comparison should be faster than string!)
- */
- //if (strcmp(mode, "Delete")==0)
- if (mode && mode[0]=='D')
- return 0;
-
- return 1;
-}
-
-/* Object KeyingSets ------ */
-
-/* check if include shapekey entry */
-static short incl_v3d_ob_shapekey (bKeyingSet *ks, const char mode[])
-{
- Object *ob= (G.obedit)? (G.obedit) : (OBACT);
- char *newname= NULL;
-
- if(ob==NULL)
- return 0;
-
- /* not available for delete mode */
- if (strcmp(mode, "Delete")==0)
- return 0;
-
- /* check if is geom object that can get shapekeys */
- switch (ob->type) {
- /* geometry? */
- case OB_MESH: newname= "Mesh"; break;
- case OB_CURVE: newname= "Curve"; break;
- case OB_SURF: newname= "Surface"; break;
- case OB_LATTICE: newname= "Lattice"; break;
-
- /* not geometry! */
- default:
- return 0;
- }
-
- /* if ks is shapekey entry (this could be callled for separator before too!) */
- if (ks->flag == -3)
- sprintf(ks->name, newname);
-
- /* if it gets here, it's ok */
- return 1;
-}
-
-/* array for object keyingset defines */
-bKeyingSet defks_v3d_object[] =
-{
- /* include_cb, name, blocktype, flag, chan_num, adrcodes */
- {NULL, "Loc", ID_OB, 0, 3, {OB_LOC_X,OB_LOC_Y,OB_LOC_Z}},
- {NULL, "Rot", ID_OB, 0, 3, {OB_ROT_X,OB_ROT_Y,OB_ROT_Z}},
- {NULL, "Scale", ID_OB, 0, 3, {OB_SIZE_X,OB_SIZE_Y,OB_SIZE_Z}},
-
- {NULL, "%l", 0, -1, 0, {0}}, // separator
-
- {NULL, "LocRot", ID_OB, 0, 6,
- {OB_LOC_X,OB_LOC_Y,OB_LOC_Z,
- OB_ROT_X,OB_ROT_Y,OB_ROT_Z}},
-
- {NULL, "LocScale", ID_OB, 0, 6,
- {OB_LOC_X,OB_LOC_Y,OB_LOC_Z,
- OB_SIZE_X,OB_SIZE_Y,OB_SIZE_Z}},
-
- {NULL, "LocRotScale", ID_OB, 0, 9,
- {OB_LOC_X,OB_LOC_Y,OB_LOC_Z,
- OB_ROT_X,OB_ROT_Y,OB_ROT_Z,
- OB_SIZE_X,OB_SIZE_Y,OB_SIZE_Z}},
-
- {NULL, "RotScale", ID_OB, 0, 6,
- {OB_ROT_X,OB_ROT_Y,OB_ROT_Z,
- OB_SIZE_X,OB_SIZE_Y,OB_SIZE_Z}},
-
- {incl_non_del_keys, "%l", 0, -1, 0, {0}}, // separator
-
- {incl_non_del_keys, "VisualLoc", ID_OB, INSERTKEY_MATRIX, 3, {OB_LOC_X,OB_LOC_Y,OB_LOC_Z}},
- {incl_non_del_keys, "VisualRot", ID_OB, INSERTKEY_MATRIX, 3, {OB_ROT_X,OB_ROT_Y,OB_ROT_Z}},
-
- {incl_non_del_keys, "VisualLocRot", ID_OB, INSERTKEY_MATRIX, 6,
- {OB_LOC_X,OB_LOC_Y,OB_LOC_Z,
- OB_ROT_X,OB_ROT_Y,OB_ROT_Z}},
-
- {NULL, "%l", 0, -1, 0, {0}}, // separator
-
- {NULL, "Layer", ID_OB, 0, 1, {OB_LAY}}, // icky option...
- {NULL, "Available", ID_OB, -2, 0, {0}},
-
- {incl_v3d_ob_shapekey, "%l%l", 0, -1, 0, {0}}, // separator (linked to shapekey entry)
- {incl_v3d_ob_shapekey, "<ShapeKey>", ID_OB, -3, 0, {0}}
-};
-
-/* PoseChannel KeyingSets ------ */
-
-/* array for posechannel keyingset defines */
-bKeyingSet defks_v3d_pchan[] =
-{
- /* include_cb, name, blocktype, flag, chan_num, adrcodes */
- {NULL, "Loc", ID_PO, 0, 3, {AC_LOC_X,AC_LOC_Y,AC_LOC_Z}},
- {NULL, "Rot", ID_PO, 0, 4, {AC_QUAT_W,AC_QUAT_X,AC_QUAT_Y,AC_QUAT_Z}},
- {NULL, "Scale", ID_PO, 0, 3, {AC_SIZE_X,AC_SIZE_Y,AC_SIZE_Z}},
-
- {NULL, "%l", 0, -1, 0, {0}}, // separator
-
- {NULL, "LocRot", ID_PO, 0, 7,
- {AC_LOC_X,AC_LOC_Y,AC_LOC_Z,AC_QUAT_W,
- AC_QUAT_X,AC_QUAT_Y,AC_QUAT_Z}},
-
- {NULL, "LocScale", ID_PO, 0, 6,
- {AC_LOC_X,AC_LOC_Y,AC_LOC_Z,
- AC_SIZE_X,AC_SIZE_Y,AC_SIZE_Z}},
-
- {NULL, "LocRotScale", ID_PO, 0, 10,
- {AC_LOC_X,AC_LOC_Y,AC_LOC_Z,AC_QUAT_W,AC_QUAT_X,
- AC_QUAT_Y,AC_QUAT_Z,AC_SIZE_X,AC_SIZE_Y,AC_SIZE_Z}},
-
- {NULL, "RotScale", ID_PO, 0, 7,
- {AC_QUAT_W,AC_QUAT_X,AC_QUAT_Y,AC_QUAT_Z,
- AC_SIZE_X,AC_SIZE_Y,AC_SIZE_Z}},
-
- {incl_non_del_keys, "%l", 0, -1, 0, {0}}, // separator
-
- {incl_non_del_keys, "VisualLoc", ID_PO, INSERTKEY_MATRIX, 3, {AC_LOC_X,AC_LOC_Y,AC_LOC_Z}},
- {incl_non_del_keys, "VisualRot", ID_PO, INSERTKEY_MATRIX, 4, {AC_QUAT_W,AC_QUAT_X,AC_QUAT_Y,AC_QUAT_Z}},
-
- {incl_non_del_keys, "VisualLocRot", ID_PO, INSERTKEY_MATRIX, 7,
- {AC_LOC_X,AC_LOC_Y,AC_LOC_Z,AC_QUAT_W,
- AC_QUAT_X,AC_QUAT_Y,AC_QUAT_Z}},
-
- {NULL, "%l", 0, -1, 0, {0}}, // separator
-
- {NULL, "Available", ID_PO, -2, 0, {0}}
-};
-
-/* Material KeyingSets ------ */
-
-/* array for material keyingset defines */
-bKeyingSet defks_buts_shading_mat[] =
-{
- /* include_cb, name, blocktype, flag, chan_num, adrcodes */
- {NULL, "RGB", ID_MA, 0, 3, {MA_COL_R,MA_COL_G,MA_COL_B}},
- {NULL, "Alpha", ID_MA, 0, 1, {MA_ALPHA}},
- {NULL, "Halo Size", ID_MA, 0, 1, {MA_HASIZE}},
- {NULL, "Mode", ID_MA, 0, 1, {MA_MODE}}, // evil bitflags
-
- {NULL, "%l", 0, -1, 0, {0}}, // separator
-
- {NULL, "All Color", ID_MA, 0, 18,
- {MA_COL_R,MA_COL_G,MA_COL_B,
- MA_ALPHA,MA_HASIZE, MA_MODE,
- MA_SPEC_R,MA_SPEC_G,MA_SPEC_B,
- MA_REF,MA_EMIT,MA_AMB,MA_SPEC,MA_HARD,
- MA_MODE,MA_TRANSLU,MA_ADD}},
-
- {NULL, "All Mirror", ID_MA, 0, 5,
- {MA_RAYM,MA_FRESMIR,MA_FRESMIRI,
- MA_FRESTRA,MA_FRESTRAI}},
-
- {NULL, "%l", 0, -1, 0, {0}}, // separator
-
- {NULL, "Ofs", ID_MA, COMMONKEY_ADDMAP, 3, {MAP_OFS_X,MAP_OFS_Y,MAP_OFS_Z}},
- {NULL, "Size", ID_MA, COMMONKEY_ADDMAP, 3, {MAP_SIZE_X,MAP_SIZE_Y,MAP_SIZE_Z}},
-
- {NULL, "All Mapping", ID_MA, COMMONKEY_ADDMAP, 14,
- {MAP_OFS_X,MAP_OFS_Y,MAP_OFS_Z,
- MAP_SIZE_X,MAP_SIZE_Y,MAP_SIZE_Z,
- MAP_R,MAP_G,MAP_B,MAP_DVAR,
- MAP_COLF,MAP_NORF,MAP_VARF,MAP_DISP}},
-
- {NULL, "%l", 0, -1, 0, {0}}, // separator
-
- {NULL, "Available", ID_MA, -2, 0, {0}}
-};
-
-/* World KeyingSets ------ */
-
-/* array for world keyingset defines */
-bKeyingSet defks_buts_shading_wo[] =
-{
- /* include_cb, name, blocktype, flag, chan_num, adrcodes */
- {NULL, "Zenith RGB", ID_WO, 0, 3, {WO_ZEN_R,WO_ZEN_G,WO_ZEN_B}},
- {NULL, "Horizon RGB", ID_WO, 0, 3, {WO_HOR_R,WO_HOR_G,WO_HOR_B}},
-
- {NULL, "%l", 0, -1, 0, {0}}, // separator
-
- {NULL, "Mist", ID_WO, 0, 4, {WO_MISI,WO_MISTDI,WO_MISTSTA,WO_MISTHI}},
- {NULL, "Stars", ID_WO, 0, 5, {WO_STAR_R,WO_STAR_G,WO_STAR_B,WO_STARDIST,WO_STARSIZE}},
-
-
- {NULL, "%l", 0, -1, 0, {0}}, // separator
-
- {NULL, "Ofs", ID_WO, COMMONKEY_ADDMAP, 3, {MAP_OFS_X,MAP_OFS_Y,MAP_OFS_Z}},
- {NULL, "Size", ID_WO, COMMONKEY_ADDMAP, 3, {MAP_SIZE_X,MAP_SIZE_Y,MAP_SIZE_Z}},
-
- {NULL, "All Mapping", ID_WO, COMMONKEY_ADDMAP, 14,
- {MAP_OFS_X,MAP_OFS_Y,MAP_OFS_Z,
- MAP_SIZE_X,MAP_SIZE_Y,MAP_SIZE_Z,
- MAP_R,MAP_G,MAP_B,MAP_DVAR,
- MAP_COLF,MAP_NORF,MAP_VARF,MAP_DISP}},
-
- {NULL, "%l", 0, -1, 0, {0}}, // separator
-
- {NULL, "Available", ID_WO, -2, 0, {0}}
-};
-
-/* Lamp KeyingSets ------ */
-
-/* array for lamp keyingset defines */
-bKeyingSet defks_buts_shading_la[] =
-{
- /* include_cb, name, blocktype, flag, chan_num, adrcodes */
- {NULL, "RGB", ID_LA, 0, 3, {LA_COL_R,LA_COL_G,LA_COL_B}},
- {NULL, "Energy", ID_LA, 0, 1, {LA_ENERGY}},
- {NULL, "Spot Size", ID_LA, 0, 1, {LA_SPOTSI}},
-
- {NULL, "%l", 0, -1, 0, {0}}, // separator
-
- {NULL, "Ofs", ID_LA, COMMONKEY_ADDMAP, 3, {MAP_OFS_X,MAP_OFS_Y,MAP_OFS_Z}},
- {NULL, "Size", ID_LA, COMMONKEY_ADDMAP, 3, {MAP_SIZE_X,MAP_SIZE_Y,MAP_SIZE_Z}},
-
- {NULL, "All Mapping", ID_LA, COMMONKEY_ADDMAP, 14,
- {MAP_OFS_X,MAP_OFS_Y,MAP_OFS_Z,
- MAP_SIZE_X,MAP_SIZE_Y,MAP_SIZE_Z,
- MAP_R,MAP_G,MAP_B,MAP_DVAR,
- MAP_COLF,MAP_NORF,MAP_VARF,MAP_DISP}},
-
- {NULL, "%l", 0, -1, 0, {0}}, // separator
-
- {NULL, "Available", ID_LA, -2, 0, {0}}
-};
-
-/* Texture KeyingSets ------ */
-
-/* array for texture keyingset defines */
-bKeyingSet defks_buts_shading_tex[] =
-{
- /* include_cb, name, blocktype, flag, chan_num, adrcodes */
- {NULL, "Clouds", ID_TE, 0, 5,
- {TE_NSIZE,TE_NDEPTH,TE_NTYPE,
- TE_MG_TYP,TE_N_BAS1}},
-
- {NULL, "Marble", ID_TE, 0, 7,
- {TE_NSIZE,TE_NDEPTH,TE_NTYPE,
- TE_TURB,TE_MG_TYP,TE_N_BAS1,TE_N_BAS2}},
-
- {NULL, "Stucci", ID_TE, 0, 5,
- {TE_NSIZE,TE_NTYPE,TE_TURB,
- TE_MG_TYP,TE_N_BAS1}},
-
- {NULL, "Wood", ID_TE, 0, 6,
- {TE_NSIZE,TE_NTYPE,TE_TURB,
- TE_MG_TYP,TE_N_BAS1,TE_N_BAS2}},
-
- {NULL, "Magic", ID_TE, 0, 2, {TE_NDEPTH,TE_TURB}},
-
- {NULL, "Blend", ID_TE, 0, 1, {TE_MG_TYP}},
-
- {NULL, "Musgrave", ID_TE, 0, 6,
- {TE_MG_TYP,TE_MGH,TE_MG_LAC,
- TE_MG_OCT,TE_MG_OFF,TE_MG_GAIN}},
-
- {NULL, "Voronoi", ID_TE, 0, 9,
- {TE_VNW1,TE_VNW2,TE_VNW3,TE_VNW4,
- TE_VNMEXP,TE_VN_DISTM,TE_VN_COLT,
- TE_ISCA,TE_NSIZE}},
-
- {NULL, "Distorted Noise", ID_TE, 0, 4,
- {TE_MG_OCT,TE_MG_OFF,TE_MG_GAIN,TE_DISTA}},
-
- {NULL, "Color Filter", ID_TE, 0, 5,
- {TE_COL_R,TE_COL_G,TE_COL_B,TE_BRIGHT,TE_CONTRA}},
-
- {NULL, "%l", 0, -1, 0, {0}}, // separator
-
- {NULL, "Available", ID_TE, -2, 0, {0}}
-};
-
-/* Object Buttons KeyingSets ------ */
-
-/* check if include particles entry */
-static short incl_buts_ob (bKeyingSet *ks, const char mode[])
-{
- Object *ob= OBACT;
- /* only if object is mesh type */
-
- if(ob==NULL) return 0;
- return (ob->type == OB_MESH);
-}
-
-/* array for texture keyingset defines */
-bKeyingSet defks_buts_object[] =
-{
- /* include_cb, name, blocktype, flag, chan_num, adrcodes */
- {incl_buts_ob, "Surface Damping", ID_OB, 0, 1, {OB_PD_SDAMP}},
- {incl_buts_ob, "Random Damping", ID_OB, 0, 1, {OB_PD_RDAMP}},
- {incl_buts_ob, "Permeability", ID_OB, 0, 1, {OB_PD_PERM}},
-
- {NULL, "%l", 0, -1, 0, {0}}, // separator
-
- {NULL, "Force Strength", ID_OB, 0, 1, {OB_PD_FSTR}},
- {NULL, "Force Falloff", ID_OB, 0, 1, {OB_PD_FFALL}},
-
- {NULL, "%l", 0, -1, 0, {0}}, // separator
-
- {NULL, "Available", ID_OB, -2, 0, {0}} // this will include ob-transforms too!
-};
-
-/* Camera Buttons KeyingSets ------ */
-
-/* check if include internal-renderer entry */
-static short incl_buts_cam1 (bKeyingSet *ks, const char mode[])
-{
- /* only if renderer is internal renderer */
- return (G.scene->r.renderer==R_INTERN);
-}
-
-/* check if include external-renderer entry */
-static short incl_buts_cam2 (bKeyingSet *ks, const char mode[])
-{
- /* only if renderer is internal renderer */
- return (G.scene->r.renderer!=R_INTERN);
-}
-
-/* array for camera keyingset defines */
-bKeyingSet defks_buts_cam[] =
-{
- /* include_cb, name, blocktype, flag, chan_num, adrcodes */
- {NULL, "Lens", ID_CA, 0, 1, {CAM_LENS}},
- {NULL, "Clipping", ID_CA, 0, 2, {CAM_STA,CAM_END}},
- {NULL, "Focal Distance", ID_CA, 0, 1, {CAM_YF_FDIST}},
-
- {NULL, "%l", 0, -1, 0, {0}}, // separator
-
-
- {incl_buts_cam2, "Aperture", ID_CA, 0, 1, {CAM_YF_APERT}},
- {incl_buts_cam1, "Viewplane Shift", ID_CA, 0, 2, {CAM_SHIFT_X,CAM_SHIFT_Y}},
-
- {NULL, "%l", 0, -1, 0, {0}}, // separator
-
- {NULL, "Available", ID_CA, -2, 0, {0}}
-};
-
-/* --- */
-
-/* Keying Context Defines - Must keep in sync with enumeration (eKS_Contexts) */
-bKeyingContext ks_contexts[] =
-{
- KSC_TEMPLATE(v3d_object),
- KSC_TEMPLATE(v3d_pchan),
-
- KSC_TEMPLATE(buts_shading_mat),
- KSC_TEMPLATE(buts_shading_wo),
- KSC_TEMPLATE(buts_shading_la),
- KSC_TEMPLATE(buts_shading_tex),
-
- KSC_TEMPLATE(buts_object),
- KSC_TEMPLATE(buts_cam)
-};
-
-/* Keying Context Enumeration - Must keep in sync with definitions*/
-typedef enum eKS_Contexts {
- KSC_V3D_OBJECT = 0,
- KSC_V3D_PCHAN,
-
- KSC_BUTS_MAT,
- KSC_BUTS_WO,
- KSC_BUTS_LA,
- KSC_BUTS_TEX,
-
- KSC_BUTS_OB,
- KSC_BUTS_CAM,
-
- /* make sure this last one remains untouched! */
- KSC_TOT_TYPES
-} eKS_Contexts;
-
-
-/* ---------------- KeyingSet Tools ------------------- */
-
-/* helper for commonkey_context_get() - get keyingsets for 3d-view */
-static void commonkey_context_getv3d (ListBase *sources, bKeyingContext **ksc)
-{
- Object *ob;
- IpoCurve *icu;
-
- if ((OBACT) && (OBACT->flag & OB_POSEMODE)) {
- bPoseChannel *pchan;
-
- /* pose-level */
- ob= OBACT;
- *ksc= &ks_contexts[KSC_V3D_PCHAN];
- set_pose_keys(ob); /* sets pchan->flag to POSE_KEY if bone selected, and clears if not */
-
- /* loop through posechannels */
- for (pchan=ob->pose->chanbase.first; pchan; pchan=pchan->next) {
- if (pchan->flag & POSE_KEY) {
- bCommonKeySrc *cks;
-
- /* add new keyframing destination */
- cks= MEM_callocN(sizeof(bCommonKeySrc), "bCommonKeySrc");
- BLI_addtail(sources, cks);
-
- /* set id-block to key to, and action */
- cks->id= (ID *)ob;
- cks->act= ob->action;
-
- /* set pchan */
- cks->pchan= pchan;
- cks->actname= pchan->name;
- }
- }
- }
- else {
- Base *base;
-
- /* object-level */
- *ksc= &ks_contexts[KSC_V3D_OBJECT];
-
- /* loop through bases */
- for (base= FIRSTBASE; base; base= base->next) {
- if (TESTBASELIB(base)) {
- bCommonKeySrc *cks;
-
- /* add new keyframing destination */
- cks= MEM_callocN(sizeof(bCommonKeySrc), "bCommonKeySrc");
- BLI_addtail(sources, cks);
-
- /* set id-block to key to */
- ob= base->object;
- cks->id= (ID *)ob;
-
- /* when ob's keyframes are in an action, default to using 'Object' as achan name */
- if (ob->ipoflag & OB_ACTION_OB)
- cks->actname= "Object";
-
- /* set ipo-flags */
- // TODO: add checks for lib-linked data
- if ((ob->ipo) || (ob->action)) {
- if (ob->ipo) {
- cks->ipo= ob->ipo;
- }
- else {
- bActionChannel *achan;
-
- cks->act= ob->action;
- achan= get_action_channel(ob->action, cks->actname);
-
- if (achan && achan->ipo)
- cks->ipo= achan->ipo;
- }
- /* cks->ipo can be NULL while editing */
- if(cks->ipo) {
- /* deselect all ipo-curves */
- for (icu= cks->ipo->curve.first; icu; icu= icu->next) {
- icu->flag &= ~IPO_SELECT;
- }
- }
- }
- }
- }
- }
-}
-
-/* helper for commonkey_context_get() - get keyingsets for buttons window */
-static void commonkey_context_getsbuts (ListBase *sources, bKeyingContext **ksc)
-{
- bCommonKeySrc *cks;
-
- /* check on tab-type */
- switch (G.buts->mainb) {
- case CONTEXT_SHADING: /* ------------- Shading buttons ---------------- */
- /* subtabs include "Material", "Texture", "Lamp", "World"*/
- switch (G.buts->tab[CONTEXT_SHADING]) {
- case TAB_SHADING_MAT: /* >------------- Material Tab -------------< */
- {
- Material *ma= editnode_get_active_material(G.buts->lockpoin);
-
- if (ma) {
- /* add new keyframing destination */
- cks= MEM_callocN(sizeof(bCommonKeySrc), "bCommonKeySrc");
- BLI_addtail(sources, cks);
-
- /* set data */
- cks->id= (ID *)ma;
- cks->ipo= ma->ipo;
- cks->map= texchannel_to_adrcode(ma->texact);
-
- /* set keyingsets */
- *ksc= &ks_contexts[KSC_BUTS_MAT];
- return;
- }
- }
- break;
- case TAB_SHADING_WORLD: /* >------------- World Tab -------------< */
- {
- World *wo= G.buts->lockpoin;
-
- if (wo) {
- /* add new keyframing destination */
- cks= MEM_callocN(sizeof(bCommonKeySrc), "bCommonKeySrc");
- BLI_addtail(sources, cks);
-
- /* set data */
- cks->id= (ID *)wo;
- cks->ipo= wo->ipo;
- cks->map= texchannel_to_adrcode(wo->texact);
-
- /* set keyingsets */
- *ksc= &ks_contexts[KSC_BUTS_WO];
- return;
- }
- }
- break;
- case TAB_SHADING_LAMP: /* >------------- Lamp Tab -------------< */
- {
- Lamp *la= G.buts->lockpoin;
-
- if (la) {
- /* add new keyframing destination */
- cks= MEM_callocN(sizeof(bCommonKeySrc), "bCommonKeySrc");
- BLI_addtail(sources, cks);
-
- /* set data */
- cks->id= (ID *)la;
- cks->ipo= la->ipo;
- cks->map= texchannel_to_adrcode(la->texact);
-
- /* set keyingsets */
- *ksc= &ks_contexts[KSC_BUTS_LA];
- return;
- }
- }
- break;
- case TAB_SHADING_TEX: /* >------------- Texture Tab -------------< */
- {
- Tex *tex= G.buts->lockpoin;
-
- if (tex) {
- /* add new keyframing destination */
- cks= MEM_callocN(sizeof(bCommonKeySrc), "bCommonKeySrc");
- BLI_addtail(sources, cks);
-
- /* set data */
- cks->id= (ID *)tex;
- cks->ipo= tex->ipo;
-
- /* set keyingsets */
- *ksc= &ks_contexts[KSC_BUTS_TEX];
- return;
- }
- }
- break;
- }
- break;
-
- case CONTEXT_OBJECT: /* ------------- Object buttons ---------------- */
- {
- Object *ob= OBACT;
-
- if (ob) {
- /* add new keyframing destination */
- cks= MEM_callocN(sizeof(bCommonKeySrc), "bCommonKeySrc");
- BLI_addtail(sources, cks);
-
- /* set id-block to key to */
- cks->id= (ID *)ob;
- cks->ipo= ob->ipo;
-
- /* set keyingsets */
- *ksc= &ks_contexts[KSC_BUTS_OB];
- return;
- }
- }
- break;
-
- case CONTEXT_EDITING: /* ------------- Editing buttons ---------------- */
- {
- Object *ob= OBACT;
-
- if ((ob) && (ob->type==OB_CAMERA) && (G.buts->lockpoin)) { /* >---------------- camera buttons ---------------< */
- Camera *ca= G.buts->lockpoin;
-
- /* add new keyframing destination */
- cks= MEM_callocN(sizeof(bCommonKeySrc), "bCommonKeySrc");
- BLI_addtail(sources, cks);
-
- /* set id-block to key to */
- cks->id= (ID *)ca;
- cks->ipo= ca->ipo;
-
- /* set keyingsets */
- *ksc= &ks_contexts[KSC_BUTS_CAM];
- return;
- }
- }
- break;
- }
-
- /* if nothing happened... */
- *ksc= NULL;
-}
-
-
-/* get keyingsets for appropriate context */
-static void commonkey_context_get (ScrArea *sa, short mode, ListBase *sources, bKeyingContext **ksc)
-{
- /* check view type */
- switch (sa->spacetype) {
- /* 3d view - first one tested as most often used */
- case SPACE_VIEW3D:
- {
- commonkey_context_getv3d(sources, ksc);
- }
- break;
-
- /* buttons view */
- case SPACE_BUTS:
- {
- commonkey_context_getsbuts(sources, ksc);
- }
- break;
-
- /* spaces with their own methods */
- case SPACE_IPO:
- if (mode == COMMONKEY_MODE_INSERT)
- insertkey_editipo();
- return;
- case SPACE_ACTION:
- if (mode == COMMONKEY_MODE_INSERT)
- insertkey_action();
- return;
-
- /* timeline view - keyframe buttons */
- case SPACE_TIME:
- {
- ScrArea *sab;
- int bigarea= 0;
-
- /* try to find largest 3d-view available
- * (mostly of the time, this is what when user will want this,
- * as it's a standard feature in all other apps)
- */
- sab= find_biggest_area_of_type(SPACE_VIEW3D);
- if (sab) {
- commonkey_context_getv3d(sources, ksc);
- return;
- }
-
- /* if not found, sab is now NULL, so perform own biggest area test */
- for (sa= G.curscreen->areabase.first; sa; sa= sa->next) {
- int area= sa->winx * sa->winy;
-
- if (sa->spacetype != SPACE_TIME) {
- if ( (!sab) || (area > bigarea) ) {
- sab= sa;
- bigarea= area;
- }
- }
- }
-
- /* use whichever largest area was found (it shouldn't be a time window) */
- if (sab)
- commonkey_context_get(sab, mode, sources, ksc);
- }
- break;
- }
-}
-
-/* flush updates after all operations */
-static void commonkey_context_finish (ListBase *sources)
-{
- /* check view type */
- switch (curarea->spacetype) {
- /* 3d view - first one tested as most often used */
- case SPACE_VIEW3D:
- {
- /* either pose or object level */
- if (OBACT && (OBACT->pose)) {
- Object *ob= OBACT;
-
- /* recalculate ipo handles, etc. */
- if (ob->action)
- remake_action_ipos(ob->action);
-
- /* recalculate bone-paths on adding new keyframe? */
- // TODO: currently, there is no setting to turn this on/off globally
- if (ob->pose->flag & POSE_RECALCPATHS)
- pose_recalculate_paths(ob);
- }
- else {
- bCommonKeySrc *cks;
-
- /* loop over bases (as seen in sources) */
- for (cks= sources->first; cks; cks= cks->next) {
- Object *ob= (Object *)cks->id;
-
- /* simply set recalc flag */
- ob->recalc |= OB_RECALC_OB;
- }
- }
- }
- break;
- }
-}
-
-/* flush refreshes after undo */
-static void commonkey_context_refresh (void)
-{
- /* check view type */
- switch (curarea->spacetype) {
- /* 3d view - first one tested as most often used */
- case SPACE_VIEW3D:
- {
- /* do refreshes */
- DAG_scene_flush_update(G.scene, screen_view3d_layers(), 0);
-
- allspace(REMAKEIPO, 0);
- allqueue(REDRAWVIEW3D, 0);
- allqueue(REDRAWMARKER, 0);
- }
- break;
-
- /* buttons window */
- case SPACE_BUTS:
- {
- allspace(REMAKEIPO, 0);
- allqueue(REDRAWVIEW3D, 0);
- allqueue(REDRAWMARKER, 0);
- }
- break;
- }
-}
-
-/* --- */
-
-/* Build menu-string of available keying-sets (allocates memory for string)
- * NOTE: mode must not be longer than 64 chars
- */
-static char *build_keyingsets_menu (bKeyingContext *ksc, const char mode[48])
-{
- DynStr *pupds= BLI_dynstr_new();
- bKeyingSet *ks;
- char buf[64];
- char *str;
- int i, n;
-
- /* add title first */
- BLI_snprintf(buf, 64, "%s Key %%t|", mode);
- BLI_dynstr_append(pupds, buf);
-
- /* loop through keyingsets, adding them */
- for (ks=ksc->keyingsets, i=0, n=1; i < ksc->tot; ks++, i++, n++) {
- /* check if keyingset can be used */
- if (ks->flag == -1) {
- /* optional separator? */
- if (ks->include_cb) {
- if (ks->include_cb(ks, mode)) {
- BLI_snprintf( buf, 64, "%s%s", ks->name, ((n < ksc->tot)?"|":"") );
- BLI_dynstr_append(pupds, buf);
- }
- }
- else {
- BLI_snprintf( buf, 64, "%%l%s", ((n < ksc->tot)?"|":"") );
- BLI_dynstr_append(pupds, buf);
- }
- }
- else if ( (ks->include_cb==NULL) || (ks->include_cb(ks, mode)) ) {
- /* entry can be included */
- BLI_dynstr_append(pupds, ks->name);
-
- /* check if special "shapekey" entry */
- if (ks->flag == -3)
- BLI_snprintf( buf, 64, "%%x0%s", ((n < ksc->tot)?"|":"") );
- else
- BLI_snprintf( buf, 64, "%%x%d%s", n, ((n < ksc->tot)?"|":"") );
- BLI_dynstr_append(pupds, buf);
- }
- }
-
- /* convert to normal MEM_malloc'd string */
- str= BLI_dynstr_get_cstring(pupds);
- BLI_dynstr_free(pupds);
-
- return str;
-}
-
-/* Get the keying set that was chosen by the user from the menu */
-static bKeyingSet *get_keyingset_fromcontext (bKeyingContext *ksc, short index)
-{
- /* check if index is valid */
- if (ELEM(NULL, ksc, ksc->keyingsets))
- return NULL;
- if ((index < 1) || (index > ksc->tot))
- return NULL;
-
- /* index starts from 1, and should directly correspond to keyingset in array */
- return (bKeyingSet *)(ksc->keyingsets + (index - 1));
-}
-
-/* ---------------- Keyframe Management API -------------------- */
-
-/* Display a menu for handling the insertion of keyframes based on the active view */
-// TODO: add back an option for repeating last keytype
-void common_modifykey (short mode)
-{
- ListBase dsources = {NULL, NULL};
- bKeyingContext *ksc= NULL;
- bCommonKeySrc *cks;
- bKeyingSet *ks = NULL;
- char *menustr, buf[64];
- short menu_nr;
-
- /* check if mode is valid */
- if (ELEM(mode, COMMONKEY_MODE_INSERT, COMMONKEY_MODE_DELETE)==0)
- return;
-
- /* delegate to other functions or get keyingsets to use
- * - if the current area doesn't have its own handling, there will be data returned...
- */
- commonkey_context_get(curarea, mode, &dsources, &ksc);
-
- /* check that there is data to operate on */
- if (ELEM(NULL, dsources.first, ksc)) {
- BLI_freelistN(&dsources);
- return;
- }
-
- /* get menu and process it */
- if (mode == COMMONKEY_MODE_DELETE)
- menustr= build_keyingsets_menu(ksc, "Delete");
- else
- menustr= build_keyingsets_menu(ksc, "Insert");
- menu_nr= pupmenu(menustr);
- if (menustr) MEM_freeN(menustr);
-
- /* no item selected or shapekey entry? */
- if (menu_nr < 1) {
- /* free temp sources */
- BLI_freelistN(&dsources);
-
- /* check if insert new shapekey */
- if ((menu_nr == 0) && (mode == COMMONKEY_MODE_INSERT))
- insert_shapekey(OBACT);
- else
- ksc->lastused= NULL;
-
- return;
- }
- else {
- /* try to get keyingset */
- ks= get_keyingset_fromcontext(ksc, menu_nr);
-
- if (ks == NULL) {
- BLI_freelistN(&dsources);
- return;
- }
- }
-
- /* loop over each destination, applying the keying set */
- for (cks= dsources.first; cks; cks= cks->next) {
- short success= 0;
-
- /* special hacks for 'available' option */
- if (ks->flag == -2) {
- IpoCurve *icu= NULL, *icn= NULL;
-
- /* get first IPO-curve */
- if (cks->act && cks->actname) {
- bActionChannel *achan= get_action_channel(cks->act, cks->actname);
-
- // FIXME: what about constraint channels?
- if (achan && achan->ipo)
- icu= achan->ipo->curve.first;
- }
- else if(cks->ipo)
- icu= cks->ipo->curve.first;
-
- /* we get adrcodes directly from IPO curves (see method below...) */
- for (; icu; icu= icn) {
- short flag;
-
- /* get next ipo-curve in case current is deleted */
- icn= icu->next;
-
- /* insert mode or delete mode */
- if (mode == COMMONKEY_MODE_DELETE) {
- /* local flags only add on to global flags */
- flag = 0;
-
- /* delete keyframe */
- success += deletekey(cks->id, ks->blocktype, cks->actname, cks->constname, icu->adrcode, flag);
- }
- else {
- /* local flags only add on to global flags */
- flag = ks->flag;
- if (IS_AUTOKEY_FLAG(AUTOMATKEY)) flag |= INSERTKEY_MATRIX;
- if (IS_AUTOKEY_FLAG(INSERTNEEDED)) flag |= INSERTKEY_NEEDED;
- // if (IS_AUTOKEY_MODE(EDITKEYS)) flag |= INSERTKEY_REPLACE;
-
- /* insert keyframe */
- success += insertkey(cks->id, ks->blocktype, cks->actname, cks->constname, icu->adrcode, flag);
- }
- }
- }
- else {
- int i;
-
- /* loop over channels available in keyingset */
- for (i=0; i < ks->chan_num; i++) {
- short flag, adrcode;
-
- /* get adrcode
- * - certain adrcodes (for MTEX channels need special offsets) // BAD CRUFT!!!
- */
- adrcode= ks->adrcodes[i];
- if (ELEM3(ks->blocktype, ID_MA, ID_LA, ID_WO) && (ks->flag & COMMONKEY_ADDMAP)) {
- switch (adrcode) {
- case MAP_OFS_X: case MAP_OFS_Y: case MAP_OFS_Z:
- case MAP_SIZE_X: case MAP_SIZE_Y: case MAP_SIZE_Z:
- case MAP_R: case MAP_G: case MAP_B: case MAP_DVAR:
- case MAP_COLF: case MAP_NORF: case MAP_VARF: case MAP_DISP:
- adrcode += cks->map;
- break;
- }
- }
-
- /* insert mode or delete mode */
- if (mode == COMMONKEY_MODE_DELETE) {
- /* local flags only add on to global flags */
- flag = 0;
- //flag &= ~COMMONKEY_ADDMAP;
-
- /* delete keyframe */
- success += deletekey(cks->id, ks->blocktype, cks->actname, cks->constname, adrcode, flag);
- }
- else {
- /* local flags only add on to global flags */
- flag = ks->flag;
- if (IS_AUTOKEY_FLAG(AUTOMATKEY)) flag |= INSERTKEY_MATRIX;
- if (IS_AUTOKEY_FLAG(INSERTNEEDED)) flag |= INSERTKEY_NEEDED;
- // if (IS_AUTOKEY_MODE(EDITKEYS)) flag |= INSERTKEY_REPLACE;
- flag &= ~COMMONKEY_ADDMAP;
-
- /* insert keyframe */
- success += insertkey(cks->id, ks->blocktype, cks->actname, cks->constname, adrcode, flag);
- }
- }
- }
-
- /* special handling for some key-sources */
- if (success) {
- /* set pose recalc-paths flag */
- if (cks->pchan) {
- Object *ob= (Object *)cks->id;
- bPoseChannel *pchan= cks->pchan;
-
- /* set flag to trigger path recalc */
- if (pchan->path)
- ob->pose->flag |= POSE_RECALCPATHS;
-
- /* clear unkeyed flag (it doesn't matter if it's set or not) */
- if (pchan->bone)
- pchan->bone->flag &= ~BONE_UNKEYED;
- }
- }
- }
-
- /* apply post-keying flushes for this data sources */
- commonkey_context_finish(&dsources);
- ksc->lastused= ks;
-
- /* free temp data */
- BLI_freelistN(&dsources);
-
- /* undo pushes */
- if (mode == COMMONKEY_MODE_DELETE)
- BLI_snprintf(buf, 64, "Delete %s Key", ks->name);
- else
- BLI_snprintf(buf, 64, "Insert %s Key", ks->name);
- BIF_undo_push(buf);
-
- /* queue updates for contexts */
- commonkey_context_refresh();
-}
-
-/* ---- */
-
-/* used to insert keyframes from any view */
-void common_insertkey (void)
-{
- common_modifykey(COMMONKEY_MODE_INSERT);
-}
-
-/* used to insert keyframes from any view */
-void common_deletekey (void)
-{
- common_modifykey(COMMONKEY_MODE_DELETE);
-}
-
-/* ************************************************** */
-/* KEYFRAME DETECTION */
-
-/* --------------- API/Per-Datablock Handling ------------------- */
-
-/* Checks whether an IPO-block has a keyframe for a given frame
- * Since we're only concerned whether a keyframe exists, we can simply loop until a match is found...
- */
-short ipo_frame_has_keyframe (Ipo *ipo, float frame, short filter)
-{
- IpoCurve *icu;
-
- /* can only find if there is data */
- if (ipo == NULL)
- return 0;
-
- /* if only check non-muted, check if muted */
- if ((filter & ANIMFILTER_MUTED) || (ipo->muteipo))
- return 0;
-
- /* loop over IPO-curves, using binary-search to try to find matches
- * - this assumes that keyframes are only beztriples
- */
- for (icu= ipo->curve.first; icu; icu= icu->next) {
- /* only check if there are keyframes (currently only of type BezTriple) */
- if (icu->bezt) {
- /* we either include all regardless of muting, or only non-muted */
- if ((filter & ANIMFILTER_MUTED) || (icu->flag & IPO_MUTE)==0) {
- short replace = -1;
- int i = binarysearch_bezt_index(icu->bezt, frame, icu->totvert, &replace);
-
- /* binarysearch_bezt_index will set replace to be 0 or 1
- * - obviously, 1 represents a match
- */
- if (replace) {
- /* sanity check: 'i' may in rare cases exceed arraylen */
- if ((i >= 0) && (i < icu->totvert))
- return 1;
- }
- }
- }
- }
-
- /* nothing found */
- return 0;
-}
-
-/* Checks whether an action-block has a keyframe for a given frame
- * Since we're only concerned whether a keyframe exists, we can simply loop until a match is found...
- */
-short action_frame_has_keyframe (bAction *act, float frame, short filter)
-{
- bActionChannel *achan;
-
- /* error checking */
- if (act == NULL)
- return 0;
-
- /* check thorugh action-channels for match */
- for (achan= act->chanbase.first; achan; achan= achan->next) {
- /* we either include all regardless of muting, or only non-muted
- * - here we include 'hidden' channels in the muted definition
- */
- if ((filter & ANIMFILTER_MUTED) || (achan->flag & ACHAN_HIDDEN)==0) {
- if (ipo_frame_has_keyframe(achan->ipo, frame, filter))
- return 1;
- }
- }
-
- /* nothing found */
- return 0;
-}
-
-/* Checks whether an Object has a keyframe for a given frame */
-short object_frame_has_keyframe (Object *ob, float frame, short filter)
-{
- /* error checking */
- if (ob == NULL)
- return 0;
-
- /* check for an action - actions take priority over normal IPO's */
- if (ob->action) {
- float aframe;
-
- /* apply nla-action scaling if needed */
- if ((ob->nlaflag & OB_NLA_OVERRIDE) && (ob->nlastrips.first))
- aframe= get_action_frame(ob, frame);
- else
- aframe= frame;
-
- /* priority check here goes to pose-channel checks (for armatures) */
- if ((ob->pose) && (ob->flag & OB_POSEMODE)) {
- /* only relevant check here is to only show active... */
- if (filter & ANIMFILTER_ACTIVE) {
- bPoseChannel *pchan= get_active_posechannel(ob);
- bActionChannel *achan= (pchan) ? get_action_channel(ob->action, pchan->name) : NULL;
-
- /* since we're only interested in whether the selected one has any keyframes... */
- return (achan && ipo_frame_has_keyframe(achan->ipo, aframe, filter));
- }
- }
-
- /* for everything else, just use the standard test (only return if success) */
- if (action_frame_has_keyframe(ob->action, aframe, filter))
- return 1;
- }
- else if (ob->ipo) {
- /* only return if success */
- if (ipo_frame_has_keyframe(ob->ipo, frame, filter))
- return 1;
- }
-
- /* try shapekey keyframes (if available, and allowed by filter) */
- if ( !(filter & ANIMFILTER_LOCAL) && !(filter & ANIMFILTER_NOSKEY) ) {
- Key *key= ob_get_key(ob);
-
- /* shapekeys can have keyframes ('Relative Shape Keys')
- * or depend on time (old 'Absolute Shape Keys')
- */
-
- /* 1. test for relative (with keyframes) */
- if (id_frame_has_keyframe((ID *)key, frame, filter))
- return 1;
-
- /* 2. test for time */
- // TODO... yet to be implemented (this feature may evolve before then anyway)
- }
-
- /* try materials */
- if ( !(filter & ANIMFILTER_LOCAL) && !(filter & ANIMFILTER_NOMAT) ) {
- /* if only active, then we can skip a lot of looping */
- if (filter & ANIMFILTER_ACTIVE) {
- Material *ma= give_current_material(ob, (ob->actcol + 1));
-
- /* we only retrieve the active material... */
- if (id_frame_has_keyframe((ID *)ma, frame, filter))
- return 1;
- }
- else {
- int a;
-
- /* loop over materials */
- for (a=0; a<ob->totcol; a++) {
- Material *ma= give_current_material(ob, a+1);
-
- if (id_frame_has_keyframe((ID *)ma, frame, filter))
- return 1;
- }
- }
- }
-
- /* nothing found */
- return 0;
-}
-
-/* --------------- API ------------------- */
-
-/* Checks whether a keyframe exists for the given ID-block one the given frame */
-short id_frame_has_keyframe (ID *id, float frame, short filter)
-{
- /* error checking */
- if (id == NULL)
- return 0;
-
- /* check for a valid id-type */
- switch (GS(id->name)) {
- /* animation data-types */
- case ID_IP: /* ipo */
- return ipo_frame_has_keyframe((Ipo *)id, frame, filter);
- case ID_AC: /* action */
- return action_frame_has_keyframe((bAction *)id, frame, filter);
-
- case ID_OB: /* object */
- return object_frame_has_keyframe((Object *)id, frame, filter);
-
- case ID_MA: /* material */
- {
- Material *ma= (Material *)id;
-
- /* currently, material's only have an ipo-block */
- return ipo_frame_has_keyframe(ma->ipo, frame, filter);
- }
- break;
-
- case ID_KE: /* shapekey */
- {
- Key *key= (Key *)id;
-
- /* currently, shapekey's only have an ipo-block */
- return ipo_frame_has_keyframe(key->ipo, frame, filter);
- }
- break;
- }
-
- /* no keyframe found */
- return 0;
-}
-
-/* ************************************************** */
diff --git a/source/blender/src/meshtools.c b/source/blender/src/meshtools.c
index 66a484eb903..de68449b8ea 100644
--- a/source/blender/src/meshtools.c
+++ b/source/blender/src/meshtools.c
@@ -72,6 +72,7 @@ void sort_faces(void);
#include "BKE_main.h"
#include "BKE_mesh.h"
#include "BKE_material.h"
+#include "BKE_multires.h"
#include "BKE_object.h"
#include "BKE_utildefines.h"
@@ -128,7 +129,7 @@ int join_mesh(void)
MFace *mface = NULL, *mfacemain;
float imat[4][4], cmat[4][4];
int a, b, totcol, totedge=0, totvert=0, totface=0, ok=0, vertofs, map[MAXMAT];
- int i, j, index, haskey=0, hasmulti=0, edgeofs, faceofs;
+ int i, j, index, haskey=0, edgeofs, faceofs;
bDeformGroup *dg, *odg;
MDeformVert *dvert;
CustomData vdata, edata, fdata;
@@ -179,10 +180,6 @@ int join_mesh(void)
haskey= 1;
break;
}
- if(me->mr) {
- hasmulti= 1;
- break;
- }
}
}
base= base->next;
@@ -192,10 +189,6 @@ int join_mesh(void)
error("Can't join meshes with vertex keys");
return 0;
}
- if(hasmulti) {
- error("Can't join meshes with Multires");
- return 0;
- }
/* that way the active object is always selected */
if(ok==0) return 0;
@@ -268,6 +261,9 @@ int join_mesh(void)
base= base->next;
}
+ /* For multires, need to unify the modifiers to ensure displacements aren't destroyed */
+ multiresModifier_join(ob);
+
me= ob->data;
memset(&vdata, 0, sizeof(vdata));
diff --git a/source/blender/src/multires.c b/source/blender/src/multires.c
deleted file mode 100644
index 64edfb5f6cc..00000000000
--- a/source/blender/src/multires.c
+++ /dev/null
@@ -1,431 +0,0 @@
-/*
- * $Id$
- *
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
- *
- * The Original Code is Copyright (C) 2006 by Nicholas Bishop
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- *
- * Implements the multiresolution modeling tools.
- *
- * multires.h
- *
- */
-
-#include "MEM_guardedalloc.h"
-
-#include "BLI_blenlib.h"
-#include "BLI_arithb.h"
-
-#include "DNA_key_types.h"
-#include "DNA_mesh_types.h"
-#include "DNA_meshdata_types.h"
-#include "DNA_modifier_types.h"
-#include "DNA_object_types.h"
-#include "DNA_scene_types.h"
-#include "DNA_vec_types.h"
-#include "DNA_view3d_types.h"
-
-#include "BKE_customdata.h"
-#include "BKE_depsgraph.h"
-#include "BKE_global.h"
-#include "BKE_key.h"
-#include "BKE_mesh.h"
-#include "BKE_modifier.h"
-#include "BKE_multires.h"
-#include "BKE_object.h"
-
-#include "BIF_editmesh.h"
-#include "BIF_screen.h"
-#include "BIF_space.h"
-#include "BIF_toolbox.h"
-
-#include "BDR_editobject.h"
-#include "BDR_sculptmode.h"
-
-#include "BLI_editVert.h"
-
-#include "BSE_edit.h"
-#include "BSE_view.h"
-
-#include "IMB_imbuf.h"
-#include "IMB_imbuf_types.h"
-
-#include "blendef.h"
-#include "editmesh.h"
-#include "multires.h"
-#include "mydevice.h"
-#include "parametrizer.h"
-
-#include <math.h>
-
-void multires_calc_temp_data(struct MultiresLevel *lvl);
-
-int multires_test()
-{
- Mesh *me= get_mesh(OBACT);
- if(me && me->mr) {
- error("Unable to complete action with multires enabled.");
- return 1;
- }
- return 0;
-}
-int multires_level1_test()
-{
- Mesh *me= get_mesh(OBACT);
- if(me && me->mr && me->mr->current != 1) {
- error("Operation only available for multires level 1.");
- return 1;
- }
- return 0;
-}
-
-/* Sculptmode */
-
-void multires_check_state()
-{
- if(G.f & G_SCULPTMODE && !G.obedit)
- sculptmode_correct_state();
-}
-
-static void medge_flag_to_eed(const short flag, const char crease, EditEdge *eed)
-{
- if(!eed) return;
-
- if(flag & ME_SEAM) eed->seam= 1;
- if(flag & ME_SHARP) eed->sharp = 1;
- if(flag & SELECT) eed->f |= SELECT;
- if(flag & ME_FGON) eed->h= EM_FGON;
- if(flag & ME_HIDE) eed->h |= 1;
-
- eed->crease= ((float)crease)/255.0;
-}
-
-void multires_level_to_editmesh(Object *ob, Mesh *me, const int render)
-{
- MultiresLevel *lvl= BLI_findlink(&me->mr->levels,me->mr->current-1);
- int i;
- EditMesh *em= (!render && G.obedit) ? G.editMesh : NULL;
- EditVert **eves= NULL;
- EditEdge *eed= NULL;
-
- if(em) {
- /* Remove editmesh elements */
- free_editMesh(em);
-
- eves= MEM_callocN(sizeof(EditVert*)*lvl->totvert, "editvert pointers");
-
- /* Vertices/Edges/Faces */
- for(i=0; i<lvl->totvert; ++i) {
- eves[i]= addvertlist(me->mr->verts[i].co, NULL);
- if(me->mr->verts[i].flag & 1) eves[i]->f |= SELECT;
- if(me->mr->verts[i].flag & ME_HIDE) eves[i]->h= 1;
- eves[i]->data= NULL;
- }
- for(i=0; i<lvl->totedge; ++i) {
- addedgelist(eves[lvl->edges[i].v[0]], eves[lvl->edges[i].v[1]], NULL);
- }
- for(i=0; i<lvl->totface; ++i) {
- EditVert *eve4= lvl->faces[i].v[3] ? eves[lvl->faces[i].v[3]] : NULL;
- EditFace *efa= addfacelist(eves[lvl->faces[i].v[0]], eves[lvl->faces[i].v[1]],
- eves[lvl->faces[i].v[2]], eve4, NULL, NULL);
- efa->flag= lvl->faces[i].flag & ~ME_HIDE;
- efa->mat_nr= lvl->faces[i].mat_nr;
- if(lvl->faces[i].flag & ME_FACE_SEL)
- efa->f |= SELECT;
- if(lvl->faces[i].flag & ME_HIDE) efa->h= 1;
- efa->data= NULL;
- }
-
- /* Edge flags */
- eed= em->edges.first;
- if(lvl==me->mr->levels.first) {
- for(i=0; i<lvl->totedge; ++i) {
- medge_flag_to_eed(me->mr->edge_flags[i], me->mr->edge_creases[i], eed);
- eed= eed->next;
- }
- } else {
- MultiresLevel *lvl1= me->mr->levels.first;
- const int last= lvl1->totedge * pow(2, me->mr->current-1);
- for(i=0; i<last; ++i) {
- const int ndx= i / pow(2, me->mr->current-1);
-
- medge_flag_to_eed(me->mr->edge_flags[ndx], me->mr->edge_creases[ndx], eed);
- eed= eed->next;
- }
- }
-
- eed= em->edges.first;
- for(i=0, eed= em->edges.first; i<lvl->totedge; ++i, eed= eed->next) {
- eed->h= me->mr->verts[lvl->edges[i].v[0]].flag & ME_HIDE ||
- me->mr->verts[lvl->edges[i].v[1]].flag & ME_HIDE;
- }
-
- EM_select_flush();
-
- multires_customdata_to_mesh(me, em, lvl, &me->mr->vdata, em ? &em->vdata : &me->vdata, CD_MDEFORMVERT);
- multires_customdata_to_mesh(me, em, lvl, &me->mr->fdata, em ? &em->fdata : &me->fdata, CD_MTFACE);
-
- /* Colors */
- if(me->mr->use_col) {
- MCol c[4];
- EditFace *efa= NULL;
- CustomData *src= &em->fdata;
-
- if(me->mr->use_col) EM_add_data_layer(src, CD_MCOL);
- efa= em->faces.first;
-
- for(i=0; i<lvl->totface; ++i) {
- if(me->mr->use_col) {
- multires_to_mcol(&lvl->colfaces[i], c);
- CustomData_em_set(src, efa->data, CD_MCOL, c);
- }
- efa= efa->next;
- }
-
- }
-
- mesh_update_customdata_pointers(me);
-
- MEM_freeN(eves);
- DAG_object_flush_update(G.scene, ob, OB_RECALC_DATA);
- recalc_editnormals();
- }
-}
-
-void multires_make(void *ob, void *me_v)
-{
- Mesh *me= me_v;
- Key *key;
-
- /* Check for shape keys */
- key= me->key;
- if(key) {
- int ret= okee("Adding multires will delete all shape keys, proceed?");
- if(ret) {
- free_key(key);
- me->key= NULL;
- } else
- return;
- }
-
- waitcursor(1);
-
- multires_check_state();
-
- multires_create(ob, me);
-
- allqueue(REDRAWBUTSEDIT, 0);
- BIF_undo_push("Make multires");
- waitcursor(0);
-}
-
-void multires_delete(void *ob, void *me_v)
-{
- Mesh *me= me_v;
- multires_free(me->mr);
- me->mr= NULL;
-
- multires_check_state();
-
- allqueue(REDRAWBUTSEDIT, 0);
-
- BIF_undo_push("Apply multires");
-}
-
-/* Make sure that all level indices are clipped to [1, mr->level_count] */
-void multires_clip_levels(Multires *mr)
-{
- if(mr) {
- const int cnt = mr->level_count;
-
- if(mr->current < 1) mr->current = 1;
- if(mr->edgelvl < 1) mr->edgelvl = 1;
- if(mr->pinlvl < 1) mr->pinlvl = 1;
- if(mr->renderlvl < 1) mr->renderlvl = 1;
-
- if(mr->current > cnt) mr->current = cnt;
- if(mr->edgelvl > cnt) mr->edgelvl = cnt;
- if(mr->pinlvl > cnt) mr->pinlvl = cnt;
- if(mr->renderlvl > cnt) mr->renderlvl = cnt;
- }
-}
-
-/* Delete all multires levels beneath current level. Subdivide special
- first-level data up to the new lowest level. */
-void multires_del_lower(void *ob, void *me)
-{
- Multires *mr= ((Mesh*)me)->mr;
- MultiresLevel *lvl1= mr->levels.first, *cr_lvl= current_level(mr);
- MultiresLevel *lvl= NULL, *lvlprev= NULL;
- short *edgeflags= NULL;
- char *edgecreases= NULL;
- int i, last;
-
- if(cr_lvl == lvl1) return;
-
- multires_check_state();
-
- /* Subdivide the edge flags to the current level */
- edgeflags= MEM_callocN(sizeof(short)*current_level(mr)->totedge, "Multires Edge Flags");
- edgecreases= MEM_callocN(sizeof(char)*current_level(mr)->totedge, "Multires Edge Creases");
- last= lvl1->totedge * pow(2, mr->current-1);
- for(i=0; i<last; ++i) {
- edgeflags[i] = mr->edge_flags[(int)(i / pow(2, mr->current-1))];
- edgecreases[i] = mr->edge_creases[(int)(i / pow(2, mr->current-1))];
- }
- MEM_freeN(mr->edge_flags);
- MEM_freeN(mr->edge_creases);
- mr->edge_flags= edgeflags;
- mr->edge_creases= edgecreases;
-
- multires_del_lower_customdata(mr, cr_lvl);
-
- lvl= cr_lvl->prev;
- while(lvl) {
- lvlprev= lvl->prev;
-
- multires_free_level(lvl);
- BLI_freelinkN(&mr->levels, lvl);
-
- mr->current-= 1;
- mr->level_count-= 1;
-
- lvl= lvlprev;
- }
- mr->newlvl= mr->current;
-
- multires_clip_levels(mr);
-
- allqueue(REDRAWBUTSEDIT, 0);
-
- BIF_undo_push("Multires delete lower");
-}
-
-void multires_del_higher(void *ob, void *me)
-{
- Multires *mr= ((Mesh*)me)->mr;
- MultiresLevel *lvl= BLI_findlink(&mr->levels,mr->current-1);
- MultiresLevel *lvlnext;
-
- multires_check_state();
-
- lvl= lvl->next;
- while(lvl) {
- lvlnext= lvl->next;
-
- multires_free_level(lvl);
- BLI_freelinkN(&mr->levels,lvl);
-
- mr->level_count-= 1;
-
- lvl= lvlnext;
- }
-
- multires_clip_levels(mr);
-
- allqueue(REDRAWBUTSEDIT, 0);
-
- BIF_undo_push("Multires delete higher");
-}
-
-void multires_finish_mesh_update(Object *ob)
-{
- /* friendly check for background render */
- if(G.background==0) {
- object_handle_update(ob);
- countall();
-
- if(G.vd && G.vd->depths) G.vd->depths->damaged= 1;
- allqueue(REDRAWVIEW3D, 0);
- allqueue(REDRAWIMAGE, 0);
- }
-}
-
-void multires_subdivide(void *ob_v, void *me_v)
-{
- Mesh *me = me_v;
-
- multires_check_state();
-
- if(CustomData_number_of_layers(G.obedit ? &G.editMesh->fdata : &me->fdata, CD_MCOL) > 1) {
- int ret= okee("Adding a level will delete all but the active vertex color layer, proceed?");
- if(!ret)
- return;
- }
-
- waitcursor(1);
- multires_add_level(ob_v, me, G.scene->toolsettings->multires_subdiv_type);
- multires_level_to_editmesh(ob_v, me, 0);
- multires_finish_mesh_update(ob_v);
-
- allqueue(REDRAWBUTSEDIT, 0);
- BIF_undo_push("Add multires level");
- waitcursor(0);
-}
-
-void multires_set_level_cb(void *ob, void *me)
-{
- waitcursor(1);
-
- multires_check_state();
-
- multires_set_level(ob, me, 0);
- multires_level_to_editmesh(ob, me, 0);
- multires_finish_mesh_update(ob);
-
- if(G.obedit || G.f & G_SCULPTMODE)
- BIF_undo_push("Multires set level");
-
- allqueue(REDRAWBUTSEDIT, 0);
-
- waitcursor(0);
-}
-
-void multires_edge_level_update_cb(void *ob_v, void *me_v)
-{
- multires_edge_level_update(ob_v, me_v);
- allqueue(REDRAWVIEW3D, 0);
-}
-
-int multires_modifier_warning()
-{
- ModifierData *md;
-
- for(md= modifiers_getVirtualModifierList(OBACT); md; md= md->next) {
- if(md->mode & eModifierMode_Render) {
- switch(md->type) {
- case eModifierType_Subsurf:
- case eModifierType_Build:
- case eModifierType_Mirror:
- case eModifierType_Decimate:
- case eModifierType_Boolean:
- case eModifierType_Array:
- case eModifierType_EdgeSplit:
- return 1;
- }
- }
- }
-
- return 0;
-}
diff --git a/source/blender/src/sculptmode.c b/source/blender/src/sculptmode.c
index c534a8b3cab..4e740c34af5 100644
--- a/source/blender/src/sculptmode.c
+++ b/source/blender/src/sculptmode.c
@@ -65,6 +65,7 @@
#include "BKE_main.h"
#include "BKE_mesh.h"
#include "BKE_modifier.h"
+#include "BKE_multires.h"
#include "BKE_sculpt.h"
#include "BKE_texture.h"
#include "BKE_utildefines.h"
@@ -91,7 +92,6 @@
#include "IMB_imbuf_types.h"
#include "blendef.h"
-#include "multires.h"
#include "mydevice.h"
#include "RE_render_ext.h"
@@ -113,13 +113,6 @@
*
*/
-/* Used by vertex_users to store face indices in a list */
-typedef struct IndexNode {
- struct IndexNode* next,* prev;
- int Index;
-} IndexNode;
-
-
/* ActiveData stores an Index into the mvert array of Mesh, plus Fade, which
stores how far the vertex is from the brush center, scaled to the range [0,1]. */
typedef struct ActiveData {
@@ -222,22 +215,21 @@ static void calc_vertex_users()
SculptSession *ss= sculpt_session();
int i,j;
IndexNode *node= NULL;
- Mesh *me= get_mesh(OBACT);
sculpt_vertexusers_free(ss);
/* For efficiency, use vertex_users_mem as a memory pool (may be larger
than necessary if mesh has triangles, but only one alloc is needed.) */
- ss->vertex_users= MEM_callocN(sizeof(ListBase) * me->totvert, "vertex_users");
- ss->vertex_users_size= me->totvert;
- ss->vertex_users_mem= MEM_callocN(sizeof(IndexNode)*me->totface*4, "vertex_users_mem");
+ ss->vertex_users= MEM_callocN(sizeof(ListBase) * ss->totvert, "vertex_users");
+ ss->vertex_users_size= ss->totvert;
+ ss->vertex_users_mem= MEM_callocN(sizeof(IndexNode)*ss->totface*4, "vertex_users_mem");
node= ss->vertex_users_mem;
/* Find the users */
- for(i=0; i<me->totface; ++i){
- for(j=0; j<(me->mface[i].v4?4:3); ++j, ++node) {
- node->Index=i;
- BLI_addtail(&ss->vertex_users[((unsigned int*)(&me->mface[i]))[j]], node);
+ for(i=0; i<ss->totface; ++i){
+ for(j=0; j<(ss->mface[i].v4?4:3); ++j, ++node) {
+ node->index=i;
+ BLI_addtail(&ss->vertex_users[((unsigned int*)(&ss->mface[i]))[j]], node);
}
}
}
@@ -456,7 +448,6 @@ static void add_norm_if(float view_vec[3], float out[3], float out_flip[3], cons
vertices */
void calc_area_normal(float out[3], const BrushAction *a, const float *outdir, const ListBase* active_verts)
{
- Mesh *me = get_mesh(OBACT);
ActiveData *node = active_verts->first;
SculptData *sd = sculpt_data();
const int view = sd->brush_type==DRAW_BRUSH ? sculptmode_brush()->view : 0;
@@ -470,7 +461,7 @@ void calc_area_normal(float out[3], const BrushAction *a, const float *outdir, c
}
else {
for(; node; node = node->next)
- add_norm_if(((BrushAction*)a)->symm.out, out, out_flip, me->mvert[node->Index].no);
+ add_norm_if(((BrushAction*)a)->symm.out, out, out_flip, sd->session->mvert[node->Index].no);
}
if (out[0]==0.0 && out[1]==0.0 && out[2]==0.0) {
@@ -488,9 +479,8 @@ void calc_area_normal(float out[3], const BrushAction *a, const float *outdir, c
Normalize(out);
}
-void do_draw_brush(const BrushAction *a, const ListBase* active_verts)
+void do_draw_brush(SculptSession *ss, const BrushAction *a, const ListBase* active_verts)
{
- Mesh *me= get_mesh(OBACT);
float area_normal[3];
ActiveData *node= active_verts->first;
@@ -499,7 +489,7 @@ void do_draw_brush(const BrushAction *a, const ListBase* active_verts)
sculpt_axislock(area_normal);
while(node){
- float *co= me->mvert[node->Index].co;
+ float *co= ss->mvert[node->Index].co;
const float val[3]= {co[0]+area_normal[0]*node->Fade*a->scale[0],
co[1]+area_normal[1]*node->Fade*a->scale[1],
@@ -514,10 +504,8 @@ void do_draw_brush(const BrushAction *a, const ListBase* active_verts)
/* For the smooth brush, uses the neighboring vertices around vert to calculate
a smoothed location for vert. Skips corner vertices (used by only one
polygon.) */
-vec3f neighbor_average(const int vert)
+vec3f neighbor_average(SculptSession *ss, const int vert)
{
- SculptSession *ss= sculpt_session();
- Mesh *me= get_mesh(OBACT);
int i, skip= -1, total=0;
IndexNode *node= ss->vertex_users[vert].first;
vec3f avg= {0,0,0};
@@ -526,12 +514,12 @@ vec3f neighbor_average(const int vert)
/* Don't modify corner vertices */
if(ncount==1) {
- VecCopyf(&avg.x, me->mvert[vert].co);
+ VecCopyf(&avg.x, ss->mvert[vert].co);
return avg;
}
while(node){
- f= &me->mface[node->Index];
+ f= &ss->mface[node->index];
if(f->v4) {
skip= (f->v1==vert?2:
@@ -542,7 +530,7 @@ vec3f neighbor_average(const int vert)
for(i=0; i<(f->v4?4:3); ++i) {
if(i != skip && (ncount!=2 || BLI_countlist(&ss->vertex_users[(&f->v1)[i]]) <= 2)) {
- VecAddf(&avg.x,&avg.x,me->mvert[(&f->v1)[i]].co);
+ VecAddf(&avg.x, &avg.x, ss->mvert[(&f->v1)[i]].co);
++total;
}
}
@@ -556,19 +544,18 @@ vec3f neighbor_average(const int vert)
avg.z/= total;
}
else
- VecCopyf(&avg.x, me->mvert[vert].co);
+ VecCopyf(&avg.x, ss->mvert[vert].co);
return avg;
}
-void do_smooth_brush(const BrushAction *a, const ListBase* active_verts)
+void do_smooth_brush(SculptSession *ss, const BrushAction *a, const ListBase* active_verts)
{
ActiveData *node= active_verts->first;
- Mesh *me= get_mesh(OBACT);
while(node){
- float *co= me->mvert[node->Index].co;
- const vec3f avg= neighbor_average(node->Index);
+ float *co= ss->mvert[node->Index].co;
+ const vec3f avg= neighbor_average(ss, node->Index);
const float val[3]= {co[0]+(avg.x-co[0])*node->Fade,
co[1]+(avg.y-co[1])*node->Fade,
co[2]+(avg.z-co[2])*node->Fade};
@@ -577,13 +564,12 @@ void do_smooth_brush(const BrushAction *a, const ListBase* active_verts)
}
}
-void do_pinch_brush(const BrushAction *a, const ListBase* active_verts)
+void do_pinch_brush(SculptSession *ss, const BrushAction *a, const ListBase* active_verts)
{
- Mesh *me= get_mesh(OBACT);
ActiveData *node= active_verts->first;
while(node) {
- float *co= me->mvert[node->Index].co;
+ float *co= ss->mvert[node->Index].co;
const float val[3]= {co[0]+(a->symm.center_3d[0]-co[0])*node->Fade,
co[1]+(a->symm.center_3d[1]-co[1])*node->Fade,
co[2]+(a->symm.center_3d[2]-co[2])*node->Fade};
@@ -592,9 +578,8 @@ void do_pinch_brush(const BrushAction *a, const ListBase* active_verts)
}
}
-void do_grab_brush(BrushAction *a)
+void do_grab_brush(SculptSession *ss, BrushAction *a)
{
- Mesh *me= get_mesh(OBACT);
ActiveData *node= a->grab_active_verts[a->symm.index].first;
float add[3];
float grab_delta[3];
@@ -603,7 +588,7 @@ void do_grab_brush(BrushAction *a)
sculpt_axislock(grab_delta);
while(node) {
- float *co= me->mvert[node->Index].co;
+ float *co= ss->mvert[node->Index].co;
VecCopyf(add, grab_delta);
VecMulf(add, node->Fade);
@@ -615,9 +600,8 @@ void do_grab_brush(BrushAction *a)
}
-void do_layer_brush(BrushAction *a, const ListBase *active_verts)
+void do_layer_brush(SculptSession *ss, BrushAction *a, const ListBase *active_verts)
{
- Mesh *me= get_mesh(OBACT);
float area_normal[3];
ActiveData *node= active_verts->first;
const float bstr= brush_strength(a);
@@ -629,7 +613,7 @@ void do_layer_brush(BrushAction *a, const ListBase *active_verts)
if((bstr > 0 && *disp < bstr) ||
(bstr < 0 && *disp > bstr)) {
- float *co= me->mvert[node->Index].co;
+ float *co= ss->mvert[node->Index].co;
*disp+= node->Fade;
@@ -653,15 +637,14 @@ void do_layer_brush(BrushAction *a, const ListBase *active_verts)
}
}
-void do_inflate_brush(const BrushAction *a, const ListBase *active_verts)
+void do_inflate_brush(SculptSession *ss, const BrushAction *a, const ListBase *active_verts)
{
ActiveData *node= active_verts->first;
float add[3];
- Mesh *me= get_mesh(OBACT);
while(node) {
- float *co= me->mvert[node->Index].co;
- short *no= me->mvert[node->Index].no;
+ float *co= ss->mvert[node->Index].co;
+ short *no= ss->mvert[node->Index].no;
add[0]= no[0]/ 32767.0f;
add[1]= no[1]/ 32767.0f;
@@ -678,7 +661,7 @@ void do_inflate_brush(const BrushAction *a, const ListBase *active_verts)
}
}
-void calc_flatten_center(Mesh *me, ActiveData *node, float co[3])
+void calc_flatten_center(SculptSession *ss, ActiveData *node, float co[3])
{
ActiveData *outer[FLATTEN_SAMPLE_SIZE];
int i;
@@ -697,23 +680,22 @@ void calc_flatten_center(Mesh *me, ActiveData *node, float co[3])
co[0] = co[1] = co[2] = 0.0f;
for(i = 0; i < FLATTEN_SAMPLE_SIZE; ++i)
- VecAddf(co, co, me->mvert[outer[i]->Index].co);
+ VecAddf(co, co, ss->mvert[outer[i]->Index].co);
VecMulf(co, 1.0f / FLATTEN_SAMPLE_SIZE);
}
-void do_flatten_brush(const BrushAction *a, const ListBase *active_verts)
+void do_flatten_brush(SculptSession *ss, const BrushAction *a, const ListBase *active_verts)
{
- Mesh *me= get_mesh(OBACT);
ActiveData *node= active_verts->first;
/* area_normal and cntr define the plane towards which vertices are squashed */
float area_normal[3];
float cntr[3];
calc_area_normal(area_normal, a, a->symm.out, active_verts);
- calc_flatten_center(me, node, cntr);
+ calc_flatten_center(ss, node, cntr);
while(node){
- float *co= me->mvert[node->Index].co;
+ float *co= ss->mvert[node->Index].co;
float p1[3], sub1[3], sub2[3], intr[3], val[3];
/* Find the intersection between squash-plane and vertex (along the area normal) */
@@ -906,7 +888,6 @@ void sculpt_add_damaged_rect(BrushAction *a)
{
short p[2];
RectNode *rn= MEM_mallocN(sizeof(RectNode),"RectNode");
- Mesh *me= get_mesh(OBACT);
SculptSession *ss = sculpt_session();
const float radius = a->radius > a->prev_radius ? a->radius : a->prev_radius;
unsigned i;
@@ -921,7 +902,7 @@ void sculpt_add_damaged_rect(BrushAction *a)
BLI_addtail(&sculpt_session()->damaged_rects, rn);
/* Update insides */
- for(i=0; i<me->totvert; ++i) {
+ for(i=0; i<ss->totvert; ++i) {
if(!ss->projverts[i].inside) {
if(ss->projverts[i].co[0] > rn->r.xmin && ss->projverts[i].co[1] > rn->r.ymin &&
ss->projverts[i].co[0] < rn->r.xmax && ss->projverts[i].co[1] < rn->r.ymax) {
@@ -979,10 +960,11 @@ void do_brush_action(BrushAction *a)
/* Build a list of all vertices that are potentially within the brush's
area of influence. Only do this once for the grab brush. */
if((sd->brush_type != GRAB_BRUSH) || a->firsttime) {
- for(i=0; i<me->totvert; ++i) {
+ for(i=0; i<ss->totvert; ++i) {
/* Projverts.inside provides a rough bounding box */
- if(ss->projverts[i].inside) {
- vert= ss->vertexcosnos ? &ss->vertexcosnos[i*6] : me->mvert[i].co;
+ if(ss->multires || ss->projverts[i].inside) {
+ //vert= ss->vertexcosnos ? &ss->vertexcosnos[i*6] : a->verts[i].co;
+ vert= ss->mvert[i].co;
av_dist= VecLenf(a->symm.center_3d, vert);
if(av_dist < a->size_3d) {
adata= (ActiveData*)MEM_mallocN(sizeof(ActiveData), "ActiveData");
@@ -1007,30 +989,30 @@ void do_brush_action(BrushAction *a)
/* Apply one type of brush action */
switch(G.scene->sculptdata.brush_type){
case DRAW_BRUSH:
- do_draw_brush(a, &active_verts);
+ do_draw_brush(ss, a, &active_verts);
break;
case SMOOTH_BRUSH:
- do_smooth_brush(a, &active_verts);
+ do_smooth_brush(ss, a, &active_verts);
break;
case PINCH_BRUSH:
- do_pinch_brush(a, &active_verts);
+ do_pinch_brush(ss, a, &active_verts);
break;
case INFLATE_BRUSH:
- do_inflate_brush(a, &active_verts);
+ do_inflate_brush(ss, a, &active_verts);
break;
case GRAB_BRUSH:
- do_grab_brush(a);
+ do_grab_brush(ss, a);
break;
case LAYER_BRUSH:
- do_layer_brush(a, &active_verts);
+ do_layer_brush(ss, a, &active_verts);
break;
case FLATTEN_BRUSH:
- do_flatten_brush(a, &active_verts);
+ do_flatten_brush(ss, a, &active_verts);
break;
}
/* Copy the modified vertices from mesh to the active key */
- if(keyblock) {
+ if(keyblock && !ss->multires) {
float *co= keyblock->data;
if(co) {
if(sd->brush_type == GRAB_BRUSH)
@@ -1044,7 +1026,7 @@ void do_brush_action(BrushAction *a)
}
}
- if(ss->vertexcosnos)
+ if(ss->vertexcosnos && !ss->multires)
BLI_freelistN(&active_verts);
else {
if(sd->brush_type != GRAB_BRUSH)
@@ -1090,64 +1072,70 @@ void do_symmetrical_brush_actions(BrushAction *a, short co[2], short pr_co[2])
a->symm = orig;
}
-void add_face_normal(vec3f *norm, const MFace* face)
+void add_face_normal(vec3f *norm, MVert *mvert, const MFace* face, float *fn)
{
- Mesh *me= get_mesh(OBACT);
-
- vec3f c= {me->mvert[face->v1].co[0],me->mvert[face->v1].co[1],me->mvert[face->v1].co[2]};
- vec3f b= {me->mvert[face->v2].co[0],me->mvert[face->v2].co[1],me->mvert[face->v2].co[2]};
- vec3f a= {me->mvert[face->v3].co[0],me->mvert[face->v3].co[1],me->mvert[face->v3].co[2]};
+ vec3f c= {mvert[face->v1].co[0],mvert[face->v1].co[1],mvert[face->v1].co[2]};
+ vec3f b= {mvert[face->v2].co[0],mvert[face->v2].co[1],mvert[face->v2].co[2]};
+ vec3f a= {mvert[face->v3].co[0],mvert[face->v3].co[1],mvert[face->v3].co[2]};
vec3f s1, s2;
+ float final[3];
VecSubf(&s1.x,&a.x,&b.x);
VecSubf(&s2.x,&c.x,&b.x);
- norm->x+= s1.y * s2.z - s1.z * s2.y;
- norm->y+= s1.z * s2.x - s1.x * s2.z;
- norm->z+= s1.x * s2.y - s1.y * s2.x;
+ final[0] = s1.y * s2.z - s1.z * s2.y;
+ final[1] = s1.z * s2.x - s1.x * s2.z;
+ final[2] = s1.x * s2.y - s1.y * s2.x;
+
+ if(fn)
+ VecCopyf(fn, final);
+
+ norm->x+= final[0];
+ norm->y+= final[1];
+ norm->z+= final[2];
}
-void update_damaged_vert(Mesh *me, ListBase *lb)
+void update_damaged_vert(ListBase *lb, BrushAction *a)
{
ActiveData *vert;
+ SculptSession *ss = sculpt_session();
for(vert= lb->first; vert; vert= vert->next) {
vec3f norm= {0,0,0};
IndexNode *face= sculpt_session()->vertex_users[vert->Index].first;
while(face){
- add_face_normal(&norm,&me->mface[face->Index]);
+ float *fn = NULL;
+ if(ss->face_normals)
+ fn = &ss->face_normals[face->index*3];
+ add_face_normal(&norm, ss->mvert, &ss->mface[face->index], fn);
face= face->next;
}
Normalize(&norm.x);
- me->mvert[vert->Index].no[0]=norm.x*32767;
- me->mvert[vert->Index].no[1]=norm.y*32767;
- me->mvert[vert->Index].no[2]=norm.z*32767;
+ ss->mvert[vert->Index].no[0]=norm.x*32767;
+ ss->mvert[vert->Index].no[1]=norm.y*32767;
+ ss->mvert[vert->Index].no[2]=norm.z*32767;
}
}
void calc_damaged_verts(ListBase *damaged_verts, BrushAction *a)
{
- Mesh *me= get_mesh(OBACT);
int i;
for(i=0; i<8; ++i)
- update_damaged_vert(me, &a->grab_active_verts[i]);
+ update_damaged_vert(&a->grab_active_verts[i], a);
- update_damaged_vert(me, damaged_verts);
+ update_damaged_vert(damaged_verts, a);
BLI_freelistN(damaged_verts);
damaged_verts->first = damaged_verts->last = NULL;
}
void projverts_clear_inside(SculptSession *ss)
{
- Mesh *me = get_mesh(OBACT);
- if(me) {
- int i;
- for(i = 0; i < me->totvert; ++i)
- ss->projverts[i].inside = 0;
- }
+ int i;
+ for(i = 0; i < ss->totvert; ++i)
+ ss->projverts[i].inside = 0;
}
BrushData *sculptmode_brush(void)
@@ -1226,6 +1214,7 @@ void sculptmode_update_tex()
static void init_brushaction(BrushAction *a, short *mouse, short *pr_mouse)
{
SculptData *sd = sculpt_data();
+ SculptSession *ss = sculpt_session();
const float mouse_depth = get_depth(mouse[0], mouse[1]);
float brush_edge_loc[3], zero_loc[3], oldloc[3];
ModifierData *md;
@@ -1312,31 +1301,28 @@ static void init_brushaction(BrushAction *a, short *mouse, short *pr_mouse)
VecSubf(a->symm.grab_delta, gcenter, oldloc);
}
else if(sd->brush_type == LAYER_BRUSH) {
- Mesh *me= get_mesh(OBACT);
-
if(!a->layer_disps)
- a->layer_disps= MEM_callocN(sizeof(float)*me->totvert,"Layer disps");
+ a->layer_disps= MEM_callocN(sizeof(float)*ss->totvert,"Layer disps");
}
if(sd->brush_type == LAYER_BRUSH || anchored) {
- Mesh *me= get_mesh(OBACT);
unsigned i;
if(!a->mesh_store) {
- a->mesh_store= MEM_mallocN(sizeof(vec3f) * me->totvert, "Sculpt mesh store");
- for(i = 0; i < me->totvert; ++i)
- VecCopyf(&a->mesh_store[i].x, me->mvert[i].co);
+ a->mesh_store= MEM_mallocN(sizeof(vec3f) * ss->totvert, "Sculpt mesh store");
+ for(i = 0; i < ss->totvert; ++i)
+ VecCopyf(&a->mesh_store[i].x, ss->mvert[i].co);
}
if(anchored && a->layer_disps)
- memset(a->layer_disps, 0, sizeof(float) * me->totvert);
+ memset(a->layer_disps, 0, sizeof(float) * ss->totvert);
if(anchored && !a->orig_norms) {
- a->orig_norms= MEM_mallocN(sizeof(short) * 3 * me->totvert, "Sculpt orig norm");
- for(i = 0; i < me->totvert; ++i) {
- a->orig_norms[i][0] = me->mvert[i].no[0];
- a->orig_norms[i][1] = me->mvert[i].no[1];
- a->orig_norms[i][2] = me->mvert[i].no[2];
+ a->orig_norms= MEM_mallocN(sizeof(short) * 3 * ss->totvert, "Sculpt orig norm");
+ for(i = 0; i < ss->totvert; ++i) {
+ a->orig_norms[i][0] = ss->mvert[i].no[0];
+ a->orig_norms[i][1] = ss->mvert[i].no[1];
+ a->orig_norms[i][2] = ss->mvert[i].no[2];
}
}
}
@@ -1472,20 +1458,72 @@ void sculptmode_selectbrush_menu(void)
void sculptmode_update_all_projverts(float *vertcosnos)
{
SculptSession *ss = sculpt_session();
- Mesh *me= get_mesh(OBACT);
unsigned i;
if(!ss->projverts)
- ss->projverts = MEM_mallocN(sizeof(ProjVert)*me->totvert,"ProjVerts");
+ ss->projverts = MEM_mallocN(sizeof(ProjVert)*ss->totvert,"ProjVerts");
- for(i=0; i<me->totvert; ++i) {
- project(vertcosnos ? &vertcosnos[i * 6] : me->mvert[i].co, ss->projverts[i].co);
+ for(i=0; i<ss->totvert; ++i) {
+ project(vertcosnos ? &vertcosnos[i * 6] : ss->mvert[i].co, ss->projverts[i].co);
ss->projverts[i].inside= 0;
}
}
-void sculptmode_draw_wires(SculptSession *ss, int only_damaged, Mesh *me)
+/* Checks whether full update mode (slower) needs to be used to work with modifiers */
+char sculpt_modifiers_active(Object *ob)
{
+ ModifierData *md;
+
+ for(md= modifiers_getVirtualModifierList(ob); md; md= md->next) {
+ if(md->mode & eModifierMode_Realtime && md->type != eModifierType_Multires)
+ return 1;
+ }
+
+ return 0;
+}
+
+/* Sculpt mode handles multires differently from regular meshes, but only if
+ it's the last modifier on the stack and it is not on the first level */
+struct MultiresModifierData *sculpt_multires_active(Object *ob)
+{
+ ModifierData *md;
+
+ for(md= modifiers_getVirtualModifierList(OBACT); md; md= md->next) {
+ if(md->type == eModifierType_Multires && !md->next) {
+ MultiresModifierData *mmd = (MultiresModifierData*)md;
+ if(mmd->lvl != 1)
+ return mmd;
+ }
+ }
+
+ return NULL;
+}
+
+static void sculpt_update_mesh_elements(SculptSession *ss, Object *ob)
+{
+ if(sculpt_multires_active(ob)) {
+ DerivedMesh *dm = mesh_get_derived_final(OBACT, CD_MASK_BAREMESH);
+ ss->multires = 1;
+ ss->totvert = dm->getNumVerts(dm);
+ ss->totface = dm->getNumFaces(dm);
+ ss->mvert = dm->getVertDataArray(dm, CD_MVERT);
+ ss->mface = dm->getFaceDataArray(dm, CD_MFACE);
+ ss->face_normals = dm->getFaceDataArray(dm, CD_NORMAL);
+ }
+ else {
+ Mesh *me = get_mesh(ob);
+ ss->multires = 0;
+ ss->totvert = me->totvert;
+ ss->totface = me->totface;
+ ss->mvert = me->mvert;
+ ss->mface = me->mface;
+ ss->face_normals = NULL;
+ }
+}
+
+void sculptmode_draw_wires(SculptSession *ss, int only_damaged)
+{
+ Mesh *me = get_mesh(OBACT);
int i;
bglPolygonOffset(1.0);
@@ -1507,10 +1545,11 @@ void sculptmode_draw_wires(SculptSession *ss, int only_damaged, Mesh *me)
void sculptmode_draw_mesh(int only_damaged)
{
- Mesh *me= get_mesh(OBACT);
int i, j, dt, drawCurrentMat = 1, matnr= -1;
SculptSession *ss = sculpt_session();
+ sculpt_update_mesh_elements(ss, OBACT);
+
persp(PERSP_VIEW);
mymultmatrix(OBACT->obmat);
glEnable(GL_DEPTH_TEST);
@@ -1520,15 +1559,15 @@ void sculptmode_draw_mesh(int only_damaged)
glShadeModel(GL_SMOOTH);
- glVertexPointer(3, GL_FLOAT, sizeof(MVert), &me->mvert[0].co);
- glNormalPointer(GL_SHORT, sizeof(MVert), &me->mvert[0].no);
+ glVertexPointer(3, GL_FLOAT, sizeof(MVert), &ss->mvert[0].co);
+ glNormalPointer(GL_SHORT, sizeof(MVert), &ss->mvert[0].no);
dt= MIN2(G.vd->drawtype, OBACT->dt);
if(dt==OB_WIRE)
glColorMask(0,0,0,0);
- for(i=0; i<me->totface; ++i) {
- MFace *f= &me->mface[i];
+ for(i=0; i<ss->totface; ++i) {
+ MFace *f= &ss->mface[i];
char inside= 0;
int new_matnr= f->mat_nr + 1;
@@ -1557,7 +1596,7 @@ void sculptmode_draw_mesh(int only_damaged)
glColorMask(1,1,1,1);
if(dt==OB_WIRE || (OBACT->dtx & OB_DRAWWIRE))
- sculptmode_draw_wires(ss, only_damaged, me);
+ sculptmode_draw_wires(ss, only_damaged);
glDisable(GL_DEPTH_TEST);
}
@@ -1573,24 +1612,13 @@ void sculptmode_correct_state(void)
if(!sculpt_session()->vertex_users) calc_vertex_users();
}
-/* Checks whether full update mode (slower) needs to be used to work with modifiers */
-char sculpt_modifiers_active(Object *ob)
-{
- ModifierData *md;
-
- for(md= modifiers_getVirtualModifierList(ob); md; md= md->next) {
- if(md->mode & eModifierMode_Realtime)
- return 1;
- }
-
- return 0;
-}
-
void sculpt(void)
{
SculptData *sd= sculpt_data();
SculptSession *ss= sculpt_session();
Object *ob= OBACT;
+ Mesh *me;
+ MultiresModifierData *mmd = NULL;
/* lastSigMouse is for the rake, to store the last place the mouse movement was significant */
short mouse[2], mvalo[2], lastSigMouse[2],firsttime=1, mousebut;
short modifier_calculations= 0;
@@ -1627,8 +1655,11 @@ void sculpt(void)
ss->damaged_verts.first = ss->damaged_verts.last = NULL;
ss->vertexcosnos = NULL;
+ mmd = sculpt_multires_active(ob);
+ sculpt_update_mesh_elements(ss, ob);
+
/* Check that vertex users are up-to-date */
- if(ob != active_ob || !ss->vertex_users || ss->vertex_users_size != get_mesh(ob)->totvert) {
+ if(ob != active_ob || !ss->vertex_users || ss->vertex_users_size != ss->totvert) {
sculpt_vertexusers_free(ss);
calc_vertex_users();
if(ss->projverts)
@@ -1681,7 +1712,9 @@ void sculpt(void)
/* For raking, get the original angle*/
offsetRot=sculpt_tex_angle();
-
+
+ me = get_mesh(OBACT);
+
while (get_mbut() & mousebut) {
getmouseco_areawin(mouse);
/* If rake, and the mouse has moved over 10 pixels (euclidean) (prevents jitter) then get the new angle */
@@ -1707,15 +1740,13 @@ void sculpt(void)
if(G.scene->sculptdata.brush_type != GRAB_BRUSH) {
if(anchored) {
- Mesh *me = get_mesh(ob);
-
/* Restore the mesh before continuing with anchored stroke */
if(a->mesh_store) {
- for(i = 0; i < me->totvert; ++i) {
- VecCopyf(me->mvert[i].co, &a->mesh_store[i].x);
- me->mvert[i].no[0] = a->orig_norms[i][0];
- me->mvert[i].no[1] = a->orig_norms[i][1];
- me->mvert[i].no[2] = a->orig_norms[i][2];
+ for(i = 0; i < ss->totvert; ++i) {
+ VecCopyf(ss->mvert[i].co, &a->mesh_store[i].x);
+ ss->mvert[i].no[0] = a->orig_norms[i][0];
+ ss->mvert[i].no[1] = a->orig_norms[i][1];
+ ss->mvert[i].no[2] = a->orig_norms[i][2];
}
}
@@ -1736,7 +1767,7 @@ void sculpt(void)
unproject(sd->pivot, mouse[0], mouse[1], a->depth);
}
- if(modifier_calculations || ob_get_keyblock(ob))
+ if((!ss->multires && modifier_calculations) || ob_get_keyblock(ob))
DAG_object_flush_update(G.scene, ob, OB_RECALC_DATA);
if(modifier_calculations || sd->brush_type == GRAB_BRUSH || !(sd->flags & SCULPT_DRAW_FAST)) {
@@ -1802,6 +1833,14 @@ void sculpt(void)
MEM_freeN(a);
sculpt_stroke_free();
+ if(mmd) {
+ if(mmd->undo_verts && mmd->undo_verts != ss->mvert)
+ MEM_freeN(mmd->undo_verts);
+
+ mmd->undo_verts = ss->mvert;
+ mmd->undo_verts_tot = ss->totvert;
+ }
+
sculpt_undo_push(G.scene->sculptdata.brush_type);
if(G.vd->depths) G.vd->depths->damaged= 1;
@@ -1834,13 +1873,16 @@ static void sculpt_undo_push(const short brush_type)
void set_sculptmode(void)
{
if(G.f & G_SCULPTMODE) {
- Mesh *me= get_mesh(OBACT);
+ Object *ob = OBACT;
+ Mesh *me= get_mesh(ob);
+
+ multires_force_update(ob);
G.f &= ~G_SCULPTMODE;
sculptsession_free(G.scene);
if(me && me->pv)
- mesh_pmv_off(OBACT, me);
+ mesh_pmv_off(ob, me);
}
else {
G.f |= G_SCULPTMODE;
diff --git a/source/blender/src/space.c b/source/blender/src/space.c
index bba58840566..6970a0c59ff 100644
--- a/source/blender/src/space.c
+++ b/source/blender/src/space.c
@@ -176,7 +176,6 @@
#include "mydevice.h"
#include "blendef.h"
#include "datatoc.h"
-#include "multires.h"
#include "BIF_transform.h"
@@ -1456,7 +1455,7 @@ static void winqreadview3dspace(ScrArea *sa, void *spacedata, BWinEvent *evt)
SculptData *sd= sculpt_data();
SculptSession *ss= sculpt_session();
BrushData *br= sculptmode_brush();
- Mesh *me= get_mesh(OBACT);
+ Object *ob = OBACT;
char update_prop= 0;
if(U.flag & USER_NONUMPAD) {
@@ -1604,16 +1603,11 @@ static void winqreadview3dspace(ScrArea *sa, void *spacedata, BWinEvent *evt)
break;
/* Multires */
case PAGEUPKEY:
- if(me && me->mr) {
- me->mr->newlvl= ((Mesh*)ob->data)->mr->current+1;
- multires_set_level_cb(ob, ob->data);
- }
- break;
case PAGEDOWNKEY:
- if(me && me->mr) {
- me->mr->newlvl= ((Mesh*)ob->data)->mr->current-1;
- multires_set_level_cb(ob, ob->data);
- }
+ if(multiresModifier_switch_level(ob, (event == PAGEUPKEY ? 1 : -1)))
+ BIF_undo_push("Multires switch level");
+ allqueue(REDRAWBUTSEDIT, 0);
+ allqueue(REDRAWVIEW3D, 0);
break;
/* Partial Visibility */
case HKEY:
@@ -2066,8 +2060,7 @@ static void winqreadview3dspace(ScrArea *sa, void *spacedata, BWinEvent *evt)
seam_mark_clear_tface(0);
}
else if (G.qual==LR_SHIFTKEY) {
- if (G.obedit && G.obedit->type==OB_MESH &&
- !multires_level1_test()) {
+ if (G.obedit && G.obedit->type==OB_MESH) {
initTransform(TFM_CREASE, CTX_EDGE);
Transform();
}
@@ -2076,8 +2069,7 @@ static void winqreadview3dspace(ScrArea *sa, void *spacedata, BWinEvent *evt)
}
}
else if (G.qual == (LR_CTRLKEY|LR_SHIFTKEY)) {
- if (G.obedit && G.obedit->type==OB_MESH &&
- !multires_level1_test()) {
+ if (G.obedit && G.obedit->type==OB_MESH) {
if (G.scene->selectmode & SCE_SELECT_VERTEX) {
initTransform(TFM_BWEIGHT, CTX_NONE);
}
diff --git a/source/blender/src/usiblender.c b/source/blender/src/usiblender.c
index 16c26336b89..e280078e61d 100644
--- a/source/blender/src/usiblender.c
+++ b/source/blender/src/usiblender.c
@@ -78,6 +78,7 @@
#include "BKE_global.h"
#include "BKE_main.h"
#include "BKE_mball.h"
+#include "BKE_multires.h"
#include "BKE_node.h"
#include "BKE_packedFile.h"
#include "BKE_suggestions.h"
@@ -946,10 +947,16 @@ void BIF_write_file(char *target)
if(G.obedit) {
exit_editmode(0); /* 0 = no free data */
}
+
+ if(G.f & G_SCULPTMODE) {
+ Object *ob = OBACT;
+ multires_force_update(ob);
+ }
+
if (G.fileflags & G_AUTOPACK) {
packAll();
}
-
+
waitcursor(1); // exit_editmode sets cursor too
do_history(di);
diff --git a/source/blender/src/vpaint.c b/source/blender/src/vpaint.c
index 8da5e1b2572..a3affb55eb8 100644
--- a/source/blender/src/vpaint.c
+++ b/source/blender/src/vpaint.c
@@ -71,7 +71,6 @@
#include "BKE_global.h"
#include "BKE_mesh.h"
#include "BKE_modifier.h"
-#include "BKE_multires.h"
#include "BKE_object.h"
#include "BKE_utildefines.h"
@@ -93,7 +92,6 @@
#include "BSE_trans_types.h"
#include "BSE_view.h"
-#include "multires.h"
#include "mydevice.h"
#include "blendef.h"
@@ -252,8 +250,6 @@ void make_vertexcol(int shade) /* single ob */
else
memset(me->mcol, 255, 4*sizeof(MCol)*me->totface);
- if (me->mr) multires_load_cols(me);
-
DAG_object_flush_update(G.scene, ob, OB_RECALC_DATA);
allqueue(REDRAWBUTSEDIT, 0);
@@ -1094,7 +1090,6 @@ void weight_paint(void)
if((G.f & G_WEIGHTPAINT)==0) return;
if(G.obedit) return;
- if(multires_level1_test()) return;
ob= OBACT;
if(!ob || ob->id.lib) return;
diff --git a/source/gameengine/BlenderRoutines/BL_KetsjiEmbedStart.cpp b/source/gameengine/BlenderRoutines/BL_KetsjiEmbedStart.cpp
index f046942af75..7de3056e382 100644
--- a/source/gameengine/BlenderRoutines/BL_KetsjiEmbedStart.cpp
+++ b/source/gameengine/BlenderRoutines/BL_KetsjiEmbedStart.cpp
@@ -70,7 +70,6 @@
#include "DNA_view3d_types.h"
#include "DNA_screen_types.h"
#include "BKE_global.h"
-#include "BKE_utildefines.h"
#include "BIF_screen.h"
#include "BIF_scrarea.h"
@@ -80,9 +79,6 @@
#include "DNA_scene_types.h"
/***/
-#include "GPU_extensions.h"
-#include "Value.h"
-
#ifdef __cplusplus
extern "C" {
#endif
@@ -94,10 +90,33 @@ void update_for_newframe();
static BlendFileData *load_game_data(char *filename) {
BlendReadError error;
- BlendFileData *bfd= BLO_read_from_file(filename, &error);
+ //this doesn't work anymore for relative paths, so use BLO_read_from_memory instead
+ //BlendFileData *bfd= BLO_read_from_file(filename, &error);
+ FILE* file = fopen(filename,"rb");
+ BlendFileData *bfd = 0;
+ if (file)
+ {
+ fseek(file, 0L, SEEK_END);
+ int len= ftell(file);
+ fseek(file, 0L, SEEK_SET);
+ char* filebuffer= new char[len];//MEM_mallocN(len, "text_buffer");
+ int sizeread = fread(filebuffer,len,1,file);
+ if (sizeread==1){
+ bfd = BLO_read_from_memory(filebuffer, len, &error);
+ } else {
+ error = BRE_UNABLE_TO_READ;
+ }
+ fclose(file);
+ // the memory is not released in BLO_read_from_memory, must do it here
+ delete filebuffer;
+ } else {
+ error = BRE_UNABLE_TO_OPEN;
+ }
+
if (!bfd) {
printf("Loading %s failed: %s\n", filename, BLO_bre_as_string(error));
}
+
return bfd;
}
@@ -112,20 +131,15 @@ extern "C" void StartKetsjiShell(struct ScrArea *area,
Main* blenderdata = maggie1;
char* startscenename = scenename;
- char pathname[FILE_MAXDIR+FILE_MAXFILE], oldsce[FILE_MAXDIR+FILE_MAXFILE];
+ char pathname[160];
+ strcpy (pathname, blenderdata->name);
STR_String exitstring = "";
BlendFileData *bfd= NULL;
- BLI_strncpy(pathname, blenderdata->name, sizeof(pathname));
- BLI_strncpy(oldsce, G.sce, sizeof(oldsce));
- setGamePythonPath(G.sce);
-
// 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 */
-
+
bgl::InitExtensions(true);
do
@@ -140,7 +154,10 @@ extern "C" void StartKetsjiShell(struct ScrArea *area,
bool frameRate = (SYS_GetCommandLineInt(syshandle, "show_framerate", 0) != 0);
bool game2ipo = (SYS_GetCommandLineInt(syshandle, "game2ipo", 0) != 0);
bool displaylists = (SYS_GetCommandLineInt(syshandle, "displaylists", 0) != 0);
- bool nodepwarnings = (SYS_GetCommandLineInt(syshandle, "ignore_deprecation_warnings", 0) != 0);
+ bool usemat = false, useglslmat = false;
+
+ if(GLEW_ARB_multitexture && GLEW_VERSION_1_1)
+ usemat = (SYS_GetCommandLineInt(syshandle, "blender_material", 0) != 0);
// create the canvas, rasterizer and rendertools
RAS_ICanvas* canvas = new KX_BlenderCanvas(area);
@@ -167,13 +184,6 @@ extern "C" void StartKetsjiShell(struct ScrArea *area,
NG_NetworkDeviceInterface* networkdevice = new
NG_LoopBackNetworkDeviceInterface();
- //
- SYS_SystemHandle hSystem = SYS_GetSystem();
- bool noaudio = SYS_GetCommandLineInt(hSystem,"noaudio",0);
-
- if (noaudio)/*(noaudio) intrr: disable game engine audio (openal) */
- SND_DeviceManager::SetDeviceType(snd_e_dummydevice);
-
// get an audiodevice
SND_DeviceManager::Subscribe();
SND_IAudioDevice* audiodevice = SND_DeviceManager::Instance();
@@ -197,23 +207,11 @@ extern "C" void StartKetsjiShell(struct ScrArea *area,
ketsjiengine->SetUseFixedTime(usefixed);
ketsjiengine->SetTimingDisplay(frameRate, profile, properties);
- CValue::SetDeprecationWarnings(nodepwarnings);
-
-
- //lock frame and camera enabled - storing global values
- int tmp_lay= G.scene->lay;
- Object *tmp_camera = G.scene->camera;
-
- if (G.vd->scenelock==0){
- G.scene->lay= v3d->lay;
- G.scene->camera= v3d->camera;
- }
-
+
// some blender stuff
MT_CmMatrix4x4 projmat;
MT_CmMatrix4x4 viewmat;
- float camzoom;
int i;
for (i = 0; i < 16; i++)
@@ -227,13 +225,8 @@ extern "C" void StartKetsjiShell(struct ScrArea *area,
projmat.setElem(i, projmat_linear[i]);
}
- if(v3d->persp==V3D_CAMOB) {
- camzoom = (1.41421 + (v3d->camzoom / 50.0));
- camzoom *= camzoom;
- }
- else
- camzoom = 2.0;
-
+ float camzoom = (1.41421 + (v3d->camzoom / 50.0));
+ camzoom *= camzoom;
camzoom = 4.0 / camzoom;
ketsjiengine->SetDrawType(v3d->drawtype);
@@ -248,14 +241,9 @@ extern "C" void StartKetsjiShell(struct ScrArea *area,
char basedpath[240];
// base the actuator filename with respect
// to the original file working directory
-
if (exitstring != "")
strcpy(basedpath, exitstring.Ptr());
- // 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_convertstringcode(basedpath, pathname);
bfd = load_game_data(basedpath);
@@ -276,11 +264,6 @@ extern "C" void StartKetsjiShell(struct ScrArea *area,
{
blenderdata = bfd->main;
startscenename = bfd->curscene->id.name + 2;
-
- if(blenderdata) {
- BLI_strncpy(G.sce, blenderdata->name, sizeof(G.sce));
- BLI_strncpy(pathname, blenderdata->name, sizeof(pathname));
- }
}
// else forget it, we can't find it
else
@@ -324,7 +307,6 @@ extern "C" void StartKetsjiShell(struct ScrArea *area,
ketsjiengine->SetCameraOverrideUseOrtho((v3d->persp == V3D_ORTHO));
ketsjiengine->SetCameraOverrideProjectionMatrix(projmat);
ketsjiengine->SetCameraOverrideViewMatrix(viewmat);
- ketsjiengine->SetCameraOverrideClipping(v3d->near, v3d->far);
}
// create a scene converter, create and convert the startingscene
@@ -333,42 +315,27 @@ extern "C" void StartKetsjiShell(struct ScrArea *area,
sceneconverter->addInitFromFrame=false;
if (always_use_expand_framing)
sceneconverter->SetAlwaysUseExpandFraming(true);
-
- bool usemat = false, useglslmat = false;
-
- if(GLEW_ARB_multitexture && GLEW_VERSION_1_1)
- usemat = true;
-
- if(GPU_extensions_minimum_support())
- useglslmat = true;
- else if(G.fileflags & G_FILE_GAME_MAT_GLSL)
- usemat = false;
-
- if(usemat && (G.fileflags & G_FILE_GAME_MAT))
+
+ if(usemat)
sceneconverter->SetMaterials(true);
- if(useglslmat && (G.fileflags & G_FILE_GAME_MAT_GLSL))
+ if(useglslmat)
sceneconverter->SetGLSLMaterials(true);
KX_Scene* startscene = new KX_Scene(keyboarddevice,
mousedevice,
networkdevice,
audiodevice,
- startscenename,
- blscene);
+ startscenename);
// some python things
PyObject* dictionaryobject = initGamePythonScripting("Ketsji", psl_Lowest);
ketsjiengine->SetPythonDictionary(dictionaryobject);
initRasterizer(rasterizer, canvas);
- PyObject *gameLogic = initGameLogic(ketsjiengine, startscene);
- PyDict_SetItemString(PyModule_GetDict(gameLogic), "globalDict", pyGlobalDict); // Same as importing the module.
- PyObject *gameLogic_keys = PyDict_Keys(PyModule_GetDict(gameLogic));
+ PyObject *gameLogic = initGameLogic(startscene);
PyDict_SetItemString(dictionaryobject, "GameLogic", gameLogic); // Same as importing the module.
-
initGameKeys();
initPythonConstraintBinding();
initMathutils();
- initVideoTexture();
if (sceneconverter)
{
@@ -395,7 +362,6 @@ extern "C" void StartKetsjiShell(struct ScrArea *area,
ketsjiengine->SetAnimFrameRate( (((double) blscene->r.frs_sec) / blscene->r.frs_sec_base) );
// the mainloop
- printf("\nBlender Game Engine Started\n\n");
while (!exitrequested)
{
// first check if we want to exit
@@ -431,10 +397,8 @@ extern "C" void StartKetsjiShell(struct ScrArea *area,
mousedevice->ConvertBlenderEvent(event,val);
}
}
- printf("\nBlender Game Engine Finished\n\n");
exitstring = ketsjiengine->GetExitString();
-
-
+
// when exiting the mainloop
// Clears the dictionary by hand:
@@ -442,20 +406,7 @@ extern "C" void StartKetsjiShell(struct ScrArea *area,
// 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
- int listIndex;
- PyObject *gameLogic_keys_new = PyDict_Keys(PyModule_GetDict(gameLogic));
- for (listIndex=0; listIndex < PyList_Size(gameLogic_keys_new); 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;
+ PyDict_Clear(PyModule_GetDict(gameLogic));
ketsjiengine->StopEngine();
exitGamePythonScripting();
@@ -466,16 +417,7 @@ extern "C" void StartKetsjiShell(struct ScrArea *area,
delete sceneconverter;
sceneconverter = NULL;
}
-
- Py_DECREF(gameLogic_keys);
- gameLogic_keys = NULL;
- }
- //lock frame and camera enabled - restoring global values
- if (G.vd->scenelock==0){
- G.scene->lay= tmp_lay;
- G.scene->camera= tmp_camera;
}
-
// set the cursor back to normal
canvas->SetMouseState(RAS_ICanvas::MOUSE_NORMAL);
@@ -528,8 +470,6 @@ extern "C" void StartKetsjiShell(struct ScrArea *area,
if (bfd) BLO_blendfiledata_free(bfd);
- BLI_strncpy(G.sce, oldsce, sizeof(G.sce));
-
// Release Python's GIL
PyGILState_Release(gilstate);
}
@@ -545,10 +485,10 @@ extern "C" void StartKetsjiShellSimulation(struct ScrArea *area,
Main* blenderdata = maggie;
char* startscenename = scenename;
- char pathname[FILE_MAXDIR+FILE_MAXFILE];
+ char pathname[160];
+ strcpy (pathname, maggie->name);
STR_String exitstring = "";
-
- BLI_strncpy(pathname, blenderdata->name, sizeof(pathname));
+ BlendFileData *bfd= NULL;
// Acquire Python's GIL (global interpreter lock)
// so we can safely run Python code and API calls
@@ -605,19 +545,24 @@ extern "C" void StartKetsjiShellSimulation(struct ScrArea *area,
// create the ketsjiengine
KX_KetsjiEngine* ketsjiengine = new KX_KetsjiEngine(kxsystem);
- Scene *blscene = NULL;
+ int i;
- blscene = (Scene*) maggie->scene.first;
- for (Scene *sce= (Scene*) maggie->scene.first; sce; sce= (Scene*) sce->id.next)
+ Scene *blscene = NULL;
+ if (!bfd)
{
- if (startscenename == (sce->id.name+2))
+ blscene = (Scene*) maggie->scene.first;
+ for (Scene *sce= (Scene*) maggie->scene.first; sce; sce= (Scene*) sce->id.next)
{
- blscene = sce;
- break;
+ if (startscenename == (sce->id.name+2))
+ {
+ blscene = sce;
+ break;
+ }
}
+ } else {
+ blscene = bfd->curscene;
}
-
- int cframe = 1, startFrame;
+ int cframe,startFrame;
if (blscene)
{
cframe=blscene->r.cfra;
@@ -648,19 +593,16 @@ extern "C" void StartKetsjiShellSimulation(struct ScrArea *area,
mousedevice,
networkdevice,
audiodevice,
- startscenename,
- blscene);
-
+ startscenename);
// some python things
PyObject* dictionaryobject = initGamePythonScripting("Ketsji", psl_Lowest);
ketsjiengine->SetPythonDictionary(dictionaryobject);
initRasterizer(rasterizer, canvas);
- PyObject *gameLogic = initGameLogic(ketsjiengine, startscene);
+ PyObject *gameLogic = initGameLogic(startscene);
PyDict_SetItemString(dictionaryobject, "GameLogic", gameLogic); // Same as importing the module
initGameKeys();
initPythonConstraintBinding();
initMathutils();
- initVideoTexture();
if (sceneconverter)
{
@@ -738,6 +680,7 @@ extern "C" void StartKetsjiShellSimulation(struct ScrArea *area,
SND_DeviceManager::Unsubscribe();
} while (exitrequested == KX_EXIT_REQUEST_RESTART_GAME || exitrequested == KX_EXIT_REQUEST_START_OTHER_GAME);
+ if (bfd) BLO_blendfiledata_free(bfd);
// Release Python's GIL
PyGILState_Release(gilstate);
diff --git a/source/gameengine/BlenderRoutines/CMakeLists.txt b/source/gameengine/BlenderRoutines/CMakeLists.txt
index 340a1ae310b..1d72fb9cde1 100644
--- a/source/gameengine/BlenderRoutines/CMakeLists.txt
+++ b/source/gameengine/BlenderRoutines/CMakeLists.txt
@@ -31,7 +31,6 @@ SET(INC
../../../intern/SoundSystem
../../../source/blender/misc
../../../source/blender/blenloader
- ../../../source/blender/gpu
../../../extern/bullet2/src
../../../extern/solid
../../../extern/glew/include
diff --git a/source/gameengine/BlenderRoutines/KX_BlenderGL.cpp b/source/gameengine/BlenderRoutines/KX_BlenderGL.cpp
index 54d1eb7e011..da52be56d1b 100644
--- a/source/gameengine/BlenderRoutines/KX_BlenderGL.cpp
+++ b/source/gameengine/BlenderRoutines/KX_BlenderGL.cpp
@@ -26,6 +26,7 @@
* ***** END GPL LICENSE BLOCK *****
*/
+#include "GL/glew.h"
#include "KX_BlenderGL.h"
#ifdef HAVE_CONFIG_H
@@ -92,6 +93,80 @@ void BL_SwapBuffers()
myswapbuffers();
}
+void BL_RenderText(int mode,const char* textstr,int textlen,struct MTFace* tface,
+ unsigned int *col,float v1[3],float v2[3],float v3[3],float v4[3])
+{
+ Image* ima;
+
+ if(mode & TF_BMFONT) {
+ //char string[MAX_PROPSTRING];
+ int characters, index, character;
+ float centerx, centery, sizex, sizey, transx, transy, movex, movey, advance;
+
+// bProperty *prop;
+
+ // string = "Frank van Beek";
+
+ characters = textlen;
+
+ ima = (struct Image*) tface->tpage;
+ if (ima == NULL) {
+ characters = 0;
+ }
+
+ /* When OBCOL flag is on the color is set in IndexPrimitives_3DText */
+ if (tface->mode & TF_OBCOL) { /* Color has been set */
+ col= NULL;
+ } else {
+ if(!col) glColor3f(1.0f, 1.0f, 1.0f);
+ }
+
+ glPushMatrix();
+ for (index = 0; index < characters; index++) {
+ // lets calculate offset stuff
+ character = textstr[index];
+
+ // space starts at offset 1
+ // character = character - ' ' + 1;
+
+ matrixGlyph((ImBuf *)ima->ibufs.first, character, & centerx, &centery, &sizex, &sizey, &transx, &transy, &movex, &movey, &advance);
+
+ glBegin(GL_POLYGON);
+ // printf(" %c %f %f %f %f\n", character, tface->uv[0][0], tface->uv[0][1], );
+ // glTexCoord2f((tface->uv[0][0] - centerx) * sizex + transx, (tface->uv[0][1] - centery) * sizey + transy);
+ glTexCoord2f((tface->uv[0][0] - centerx) * sizex + transx, (tface->uv[0][1] - centery) * sizey + transy);
+
+ if(col) spack(col[0]);
+ // glVertex3fv(v1);
+ glVertex3f(sizex * v1[0] + movex, sizey * v1[1] + movey, v1[2]);
+
+ glTexCoord2f((tface->uv[1][0] - centerx) * sizex + transx, (tface->uv[1][1] - centery) * sizey + transy);
+ if(col) spack(col[1]);
+ // glVertex3fv(v2);
+ glVertex3f(sizex * v2[0] + movex, sizey * v2[1] + movey, v2[2]);
+
+ glTexCoord2f((tface->uv[2][0] - centerx) * sizex + transx, (tface->uv[2][1] - centery) * sizey + transy);
+ if(col) spack(col[2]);
+ // glVertex3fv(v3);
+ glVertex3f(sizex * v3[0] + movex, sizey * v3[1] + movey, v3[2]);
+
+ if(v4) {
+ // glTexCoord2f((tface->uv[3][0] - centerx) * sizex + transx, 1.0 - (1.0 - tface->uv[3][1]) * sizey - transy);
+ glTexCoord2f((tface->uv[3][0] - centerx) * sizex + transx, (tface->uv[3][1] - centery) * sizey + transy);
+ if(col) spack(col[3]);
+ // glVertex3fv(v4);
+ glVertex3f(sizex * v4[0] + movex, sizey * v4[1] + movey, v4[2]);
+ }
+ glEnd();
+
+ glTranslatef(advance, 0.0, 0.0);
+ }
+ glPopMatrix();
+
+ }
+}
+
+
void DisableForText()
{
if(glIsEnabled(GL_BLEND)) glDisable(GL_BLEND);
@@ -102,28 +177,16 @@ void DisableForText()
glDisable(GL_COLOR_MATERIAL);
}
- if(GLEW_ARB_multitexture) {
- for(int i=0; i<MAXTEX; i++) {
+ if(GLEW_ARB_multitexture)
+ for(int i=0; i<MAXTEX; i++)
glActiveTextureARB(GL_TEXTURE0_ARB+i);
- if(GLEW_ARB_texture_cube_map)
- if(glIsEnabled(GL_TEXTURE_CUBE_MAP_ARB))
- glDisable(GL_TEXTURE_CUBE_MAP_ARB);
-
- if(glIsEnabled(GL_TEXTURE_2D))
- glDisable(GL_TEXTURE_2D);
- }
-
- glActiveTextureARB(GL_TEXTURE0_ARB);
- }
- else {
- if(GLEW_ARB_texture_cube_map)
- if(glIsEnabled(GL_TEXTURE_CUBE_MAP_ARB))
- glDisable(GL_TEXTURE_CUBE_MAP_ARB);
+ if(GLEW_ARB_texture_cube_map)
+ if(glIsEnabled(GL_TEXTURE_CUBE_MAP_ARB))
+ glDisable(GL_TEXTURE_CUBE_MAP_ARB);
- if(glIsEnabled(GL_TEXTURE_2D))
- glDisable(GL_TEXTURE_2D);
- }
+ if(glIsEnabled(GL_TEXTURE_2D))
+ glDisable(GL_TEXTURE_2D);
}
void BL_print_gamedebug_line(char* text, int xco, int yco, int width, int height)
diff --git a/source/gameengine/BlenderRoutines/KX_BlenderGL.h b/source/gameengine/BlenderRoutines/KX_BlenderGL.h
index b891a7343c2..c8e0d47afb6 100644
--- a/source/gameengine/BlenderRoutines/KX_BlenderGL.h
+++ b/source/gameengine/BlenderRoutines/KX_BlenderGL.h
@@ -46,6 +46,9 @@ void BL_HideMouse();
void BL_NormalMouse();
void BL_WaitMouse();
+void BL_RenderText(int mode,const char* textstr,int textlen,struct MTFace* tface,
+ unsigned int *col,float v1[3],float v2[3],float v3[3],float v4[3]);
+
void BL_print_gamedebug_line(char* text, int xco, int yco, int width, int height);
void BL_print_gamedebug_line_padded(char* text, int xco, int yco, int width, int height);
diff --git a/source/gameengine/BlenderRoutines/KX_BlenderRenderTools.cpp b/source/gameengine/BlenderRoutines/KX_BlenderRenderTools.cpp
index 1797d6c1a0f..e4eff163d5b 100644
--- a/source/gameengine/BlenderRoutines/KX_BlenderRenderTools.cpp
+++ b/source/gameengine/BlenderRoutines/KX_BlenderRenderTools.cpp
@@ -26,6 +26,8 @@
* ***** END GPL LICENSE BLOCK *****
*/
+#include "KX_BlenderRenderTools.h"
+
#include "GL/glew.h"
#include "RAS_IRenderTools.h"
@@ -34,22 +36,23 @@
#include "RAS_ICanvas.h"
#include "RAS_GLExtensionManager.h"
+// next two includes/dependencies come from the shadow feature
+// it needs the gameobject and the sumo physics scene for a raycast
#include "KX_GameObject.h"
+
#include "KX_PolygonMaterial.h"
#include "KX_BlenderMaterial.h"
-#include "KX_RayCast.h"
-#include "KX_IPhysicsController.h"
-
-#include "PHY_IPhysicsEnvironment.h"
-
-#include "STR_String.h"
-#include "GPU_draw.h"
+#include "Value.h"
#include "KX_BlenderGL.h" // for text printing
-#include "KX_BlenderRenderTools.h"
+#include "STR_String.h"
+#include "RAS_BucketManager.h" // for polymaterial (needed for textprinting)
-unsigned int KX_BlenderRenderTools::m_numgllights;
+#include "KX_RayCast.h"
+#include "KX_IPhysicsController.h"
+#include "PHY_IPhysicsEnvironment.h"
+#include "KX_Scene.h"
KX_BlenderRenderTools::KX_BlenderRenderTools()
{
@@ -58,98 +61,81 @@ KX_BlenderRenderTools::KX_BlenderRenderTools()
m_numgllights = 8;
}
-KX_BlenderRenderTools::~KX_BlenderRenderTools()
-{
-}
-
-void KX_BlenderRenderTools::BeginFrame(RAS_IRasterizer* rasty)
-{
- m_clientobject = NULL;
- m_lastlightlayer = -1;
- m_lastlighting = false;
- DisableOpenGLLights();
-}
-
-void KX_BlenderRenderTools::EndFrame(RAS_IRasterizer* rasty)
-{
-}
-
-/* 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. */
+/**
+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 KX_BlenderRenderTools::ProcessLighting(int layer, const MT_Transform& viewmat)
+int KX_BlenderRenderTools::ProcessLighting(int layer)
{
- if(m_lastlightlayer == layer)
- return;
-
- m_lastlightlayer = layer;
-
- bool enable = false;
+
+ int result = false;
- if (layer >= 0)
+ if (layer < 0)
+ {
+ DisableOpenGLLights();
+ result = false;
+ } else
{
if (m_clientobject)
{
if (layer == RAS_LIGHT_OBJECT_LAYER)
+ {
layer = static_cast<KX_GameObject*>(m_clientobject)->GetLayer();
-
- enable = applyLights(layer, viewmat);
+ }
+ if (applyLights(layer))
+ {
+ EnableOpenGLLights();
+ result = true;
+ } else
+ {
+ DisableOpenGLLights();
+ result = false;
+ }
}
}
-
- if(enable)
- EnableOpenGLLights();
- else
- DisableOpenGLLights();
-}
-
-void KX_BlenderRenderTools::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, true);
- if (GLEW_EXT_separate_specular_color || GLEW_VERSION_1_2)
- glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
+ return result;
+
- m_lastlighting = true;
}
-void KX_BlenderRenderTools::DisableOpenGLLights()
+
+void KX_BlenderRenderTools::BeginFrame(RAS_IRasterizer* rasty)
{
- if(m_lastlighting == false)
- return;
+ m_clientobject = NULL;
+ m_lastblenderobject = NULL;
+ m_lastblenderlights = false;
+ m_lastlayer = -1;
+ m_lastlighting = false;
+ m_modified = true;
+ DisableOpenGLLights();
- glDisable(GL_LIGHTING);
- glDisable(GL_COLOR_MATERIAL);
- m_lastlighting = false;
}
-
-void KX_BlenderRenderTools::SetClientObject(RAS_IRasterizer *rasty, void* obj)
+void KX_BlenderRenderTools::SetClientObject(void* obj)
{
if (m_clientobject != obj)
{
- bool ccw = (obj == NULL || !((KX_GameObject*)obj)->IsNegativeScaling());
- rasty->SetFrontFace(ccw);
-
+ if (obj == NULL || !((KX_GameObject*)obj)->IsNegativeScaling())
+ {
+ glFrontFace(GL_CCW);
+ } else
+ {
+ glFrontFace(GL_CW);
+ }
m_clientobject = obj;
+ m_modified = true;
}
}
-bool KX_BlenderRenderTools::RayHit(KX_ClientObjectInfo* client, KX_RayCast* result, void * const data)
+bool KX_BlenderRenderTools::RayHit(KX_ClientObjectInfo* client, MT_Point3& hit_point, MT_Vector3& hit_normal, void * const data)
{
double* const oglmatrix = (double* const) data;
- MT_Point3 resultpoint(result->m_hitPoint);
- MT_Vector3 resultnormal(result->m_hitNormal);
+ MT_Point3 resultpoint(hit_point);
+ MT_Vector3 resultnormal(hit_normal);
MT_Vector3 left(oglmatrix[0],oglmatrix[1],oglmatrix[2]);
MT_Vector3 dir = -(left.cross(resultnormal)).safe_normalized();
left = (dir.cross(resultnormal)).safe_normalized();
@@ -196,7 +182,7 @@ void KX_BlenderRenderTools::applyTransform(RAS_IRasterizer* rasty,double* oglmat
MT_Vector3 dir = (campos - objpos).safe_normalized();
MT_Vector3 up(0,0,1.0);
- KX_GameObject* gameobj = (KX_GameObject*)m_clientobject;
+ KX_GameObject* gameobj = (KX_GameObject*) this->m_clientobject;
// get scaling of halo object
MT_Vector3 size = gameobj->GetSGNode()->GetLocalScale();
@@ -232,7 +218,7 @@ void KX_BlenderRenderTools::applyTransform(RAS_IRasterizer* rasty,double* oglmat
{
// 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;
+ KX_GameObject *gameobj = (KX_GameObject*) this->m_clientobject;
MT_Vector3 direction = MT_Vector3(0,0,-1);
direction.normalize();
@@ -250,8 +236,9 @@ void KX_BlenderRenderTools::applyTransform(RAS_IRasterizer* rasty,double* oglmat
if (parent)
parent->Release();
- KX_RayCast::Callback<KX_BlenderRenderTools> callback(this, physics_controller, oglmatrix);
- if (!KX_RayCast::RayTest(physics_environment, frompoint, topoint, callback))
+ MT_Point3 resultpoint;
+ MT_Vector3 resultnormal;
+ if (!KX_RayCast::RayTest(physics_controller, physics_environment, frompoint, topoint, resultpoint, resultnormal, KX_RayCast::Callback<KX_BlenderRenderTools>(this, oglmatrix)))
{
// couldn't find something to cast the shadow on...
glMultMatrixd(oglmatrix);
@@ -266,29 +253,13 @@ void KX_BlenderRenderTools::applyTransform(RAS_IRasterizer* rasty,double* oglmat
}
-void KX_BlenderRenderTools::RenderText2D(RAS_TEXT_RENDER_MODE mode,
- const char* text,
- int xco,
- int yco,
- int width,
- int height)
-{
- STR_String tmpstr(text);
-
- if(mode == RAS_IRenderTools::RAS_TEXT_PADDED)
- BL_print_gamedebug_line_padded(tmpstr.Ptr(), xco, yco, width, height);
- else
- BL_print_gamedebug_line(tmpstr.Ptr(), xco, yco, width, height);
-}
-
-/* Render Text renders text into a (series of) polygon, using a texture font,
- * Each character consists of one polygon (one quad or two triangles) */
-
-void KX_BlenderRenderTools::RenderText(
- int mode,
- RAS_IPolyMaterial* polymat,
- float v1[3], float v2[3], float v3[3], float v4[3], int glattrib)
+/**
+Render Text renders text into a (series of) polygon, using a texture font,
+Each character consists of one polygon (one quad or two triangles)
+*/
+void KX_BlenderRenderTools::RenderText(int mode,RAS_IPolyMaterial* polymat,float v1[3],float v2[3],float v3[3],float v4[3])
{
+
STR_String mytext = ((CValue*)m_clientobject)->GetPropertyText("Text");
const unsigned int flag = polymat->GetFlag();
@@ -305,9 +276,67 @@ void KX_BlenderRenderTools::RenderText(
col = blenderpoly->GetMCol();
}
- GPU_render_text(tface, mode, mytext, mytext.Length(), col, v1, v2, v3, v4, glattrib);
+ BL_RenderText( mode,mytext,mytext.Length(),tface,col,v1,v2,v3,v4);
+
+}
+
+
+
+KX_BlenderRenderTools::~KX_BlenderRenderTools()
+{
+};
+
+
+void KX_BlenderRenderTools::EndFrame(RAS_IRasterizer* rasty)
+{
}
+
+
+void KX_BlenderRenderTools::DisableOpenGLLights()
+{
+ glDisable(GL_LIGHTING);
+ glDisable(GL_COLOR_MATERIAL);
+}
+
+
+void KX_BlenderRenderTools::EnableOpenGLLights()
+{
+ glEnable(GL_LIGHTING);
+
+ glEnable(GL_COLOR_MATERIAL);
+ glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
+ glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, true);
+ if (GLEW_EXT_separate_specular_color || GLEW_VERSION_1_2)
+ glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
+
+}
+
+
+/**
+ * Rendering text using 2D bitmap functionality.
+ */
+void KX_BlenderRenderTools::RenderText2D(RAS_TEXT_RENDER_MODE mode,
+ const char* text,
+ int xco,
+ int yco,
+ int width,
+ int height)
+{
+ switch (mode) {
+ case RAS_IRenderTools::RAS_TEXT_PADDED: {
+ STR_String tmpstr(text);
+ BL_print_gamedebug_line_padded(tmpstr.Ptr(),xco,yco,width,height);
+ break;
+ }
+ default: {
+ STR_String tmpstr(text);
+ BL_print_gamedebug_line(tmpstr.Ptr(),xco,yco,width,height);
+ }
+ }
+}
+
+
void KX_BlenderRenderTools::PushMatrix()
{
@@ -320,13 +349,14 @@ void KX_BlenderRenderTools::PopMatrix()
}
-int KX_BlenderRenderTools::applyLights(int objectlayer, const MT_Transform& viewmat)
+
+int KX_BlenderRenderTools::applyLights(int objectlayer)
{
- // taken from blender source, incompatibility between Blender Object / GameObject
- float glviewmat[16];
+// taken from blender source, incompatibility between Blender Object / GameObject
+
unsigned int count;
float vec[4];
-
+
vec[3]= 1.0;
for(count=0; count<m_numgllights; count++)
@@ -334,11 +364,9 @@ int KX_BlenderRenderTools::applyLights(int objectlayer, const MT_Transform& view
//std::vector<struct RAS_LightObject*> m_lights;
std::vector<struct RAS_LightObject*>::iterator lit = m_lights.begin();
-
- viewmat.getValue(glviewmat);
glPushMatrix();
- glLoadMatrixf(glviewmat);
+ glLoadMatrixf(m_viewmat);
for (lit = m_lights.begin(), count = 0; !(lit==m_lights.end()) && count < m_numgllights; ++lit)
{
RAS_LightObject* lightdata = (*lit);
@@ -406,6 +434,7 @@ int KX_BlenderRenderTools::applyLights(int objectlayer, const MT_Transform& view
glEnable((GLenum)(GL_LIGHT0+count));
count++;
+
}
}
glPopMatrix();
@@ -414,6 +443,22 @@ int KX_BlenderRenderTools::applyLights(int objectlayer, const MT_Transform& view
}
+
+
+RAS_IPolyMaterial* KX_BlenderRenderTools::CreateBlenderPolyMaterial(
+ const STR_String &texname,
+ bool ba,const STR_String& matname,int tile,int tilexrep,int tileyrep,int mode,bool transparant,bool zsort, int lightlayer
+ ,bool bIsTriangle,void* clientobject,void* tface)
+{
+ assert(!"Deprecated");
+/* return new KX_BlenderPolyMaterial(
+
+ texname,
+ ba,matname,tile,tilexrep,tileyrep,mode,transparant,zsort, lightlayer
+ ,bIsTriangle,clientobject,(struct MTFace*)tface);*/
+ return NULL;
+}
+
void KX_BlenderRenderTools::MotionBlur(RAS_IRasterizer* rasterizer)
{
int state = rasterizer->GetMotionBlurState();
@@ -447,3 +492,4 @@ void KX_BlenderRenderTools::Render2DFilters(RAS_ICanvas* canvas)
m_filtermanager.RenderFilters(canvas);
}
+unsigned int KX_BlenderRenderTools::m_numgllights;
diff --git a/source/gameengine/BlenderRoutines/KX_BlenderRenderTools.h b/source/gameengine/BlenderRoutines/KX_BlenderRenderTools.h
index a7618462c9b..8abce1b8c3e 100644
--- a/source/gameengine/BlenderRoutines/KX_BlenderRenderTools.h
+++ b/source/gameengine/BlenderRoutines/KX_BlenderRenderTools.h
@@ -26,7 +26,6 @@
*
* ***** END GPL LICENSE BLOCK *****
*/
-
#ifndef __KX_BLENDERRENDERTOOLS
#define __KX_BLENDERRENDERTOOLS
@@ -38,54 +37,67 @@
#include "RAS_IRenderTools.h"
struct KX_ClientObjectInfo;
-class KX_RayCast;
-/* BlenderRenderTools are a set of tools to apply 2D/3D graphics effects, which
- * are not part of the (polygon) Rasterizer. Effects like 2D text, 3D (polygon)
- * text, lighting.
- *
- * Most of this code is duplicated in GPC_RenderTools, so this should be
- * moved to some common location to avoid duplication. */
+/**
+BlenderRenderTools are a set of tools to apply 2D/3D graphics effects, which are not
+part of the (polygon) Rasterizer.
+Effects like 2D text, 3D (polygon) text, lighting.
+*/
class KX_BlenderRenderTools : public RAS_IRenderTools
{
- int m_lastlightlayer;
+ bool m_lastblenderlights;
+ void* m_lastblenderobject;
+ int m_lastlayer;
bool m_lastlighting;
static unsigned int m_numgllights;
-
+
+
public:
+
KX_BlenderRenderTools();
virtual ~KX_BlenderRenderTools();
- void EndFrame(RAS_IRasterizer* rasty);
- void BeginFrame(RAS_IRasterizer* rasty);
-
- void EnableOpenGLLights();
+ virtual void EndFrame(class RAS_IRasterizer* rasty);
+ virtual void BeginFrame(class RAS_IRasterizer* rasty);
void DisableOpenGLLights();
- void ProcessLighting(int layer, const MT_Transform& viewmat);
+ void EnableOpenGLLights();
+ int ProcessLighting(int layer);
- void RenderText2D(RAS_TEXT_RENDER_MODE mode,
+ virtual void RenderText2D(RAS_TEXT_RENDER_MODE mode,
const char* text,
int xco,
int yco,
int width,
int height);
- void RenderText(int mode,
+ virtual void RenderText(int mode,
class RAS_IPolyMaterial* polymat,
float v1[3],
float v2[3],
float v3[3],
- float v4[3],
- int glattrib);
-
- void applyTransform(RAS_IRasterizer* rasty, double* oglmatrix, int objectdrawmode);
- int applyLights(int objectlayer, const MT_Transform& viewmat);
-
- void PushMatrix();
- void PopMatrix();
-
- bool RayHit(KX_ClientObjectInfo* client, class KX_RayCast* result, void * const data);
- bool NeedRayCast(KX_ClientObjectInfo*) { return true; }
+ float v4[3]);
+ void applyTransform(class RAS_IRasterizer* rasty,
+ double* oglmatrix,
+ int objectdrawmode );
+ int applyLights(int objectlayer);
+ virtual void PushMatrix();
+ virtual void PopMatrix();
+
+ virtual class RAS_IPolyMaterial* CreateBlenderPolyMaterial(const STR_String &texname,
+ bool ba,
+ const STR_String& matname,
+ int tile,
+ int tilexrep,
+ int tileyrep,
+ int mode,
+ bool transparant,
+ bool zsort,
+ int lightlayer,
+ bool bIsTriangle,
+ void* clientobject,
+ void* tface);
+
+ bool RayHit(KX_ClientObjectInfo* client, MT_Point3& hit_point, MT_Vector3& hit_normal, void * const data);
virtual void MotionBlur(RAS_IRasterizer* rasterizer);
@@ -93,7 +105,8 @@ public:
virtual void Render2DFilters(RAS_ICanvas* canvas);
- virtual void SetClientObject(RAS_IRasterizer *rasty, void* obj);
+ virtual void SetClientObject(void* obj);
+
};
#endif //__KX_BLENDERRENDERTOOLS
diff --git a/source/gameengine/BlenderRoutines/Makefile b/source/gameengine/BlenderRoutines/Makefile
index c2f19ae1d8a..a7394158a20 100644
--- a/source/gameengine/BlenderRoutines/Makefile
+++ b/source/gameengine/BlenderRoutines/Makefile
@@ -35,7 +35,6 @@ include nan_compile.mk
CCFLAGS += $(LEVEL_1_CPP_WARNINGS)
-CPPFLAGS += -I$(NAN_GLEW)/include
CPPFLAGS += -I$(NAN_SUMO)/include -I$(NAN_SOLID)/include
CPPFLAGS += -I$(NAN_SOLID)
CPPFLAGS += -I$(NAN_STRING)/include
@@ -55,7 +54,6 @@ CPPFLAGS += -I../../blender/blenkernel
CPPFLAGS += -I../../blender/render/extern/include
CPPFLAGS += -I../../blender/blenloader
CPPFLAGS += -I../../blender/blenkernel
-CPPFLAGS += -I../../blender/gpu
CPPFLAGS += -I../Converter
CPPFLAGS += -I../Expressions
CPPFLAGS += -I../GameLogic
@@ -74,5 +72,9 @@ ifeq ($(OS),windows)
CPPFLAGS += -I../../blender
endif
+ifeq ($(WITH_BF_GLEXT),true)
+ CPPFLAGS += -DWITH_GLEXT
+endif
+
CPPFLAGS += -I$(NAN_PYTHON)/include/python$(NAN_PYTHON_VERSION)
diff --git a/source/gameengine/BlenderRoutines/SConscript b/source/gameengine/BlenderRoutines/SConscript
index 78adbc83d9b..327f4798e04 100644
--- a/source/gameengine/BlenderRoutines/SConscript
+++ b/source/gameengine/BlenderRoutines/SConscript
@@ -15,7 +15,7 @@ incs += ' #source/gameengine/SceneGraph #source/gameengine/Physics/common'
incs += ' #source/gameengine/Physics/Bullet #source/gameengine/Physics/Sumo'
incs += ' #source/gameengine/Physics/Sumo/Fuzzics/include #source/gameengine/Network/LoopBackNetwork'
incs += ' #intern/SoundSystem #source/blender/misc #source/blender/blenloader'
-incs += ' #extern/glew/include #source/blender/gpu'
+incs += ' #extern/glew/include'
incs += ' ' + env['BF_PYTHON_INC']
incs += ' ' + env['BF_SOLID_INC']
@@ -26,4 +26,7 @@ cxxflags = []
if env['OURPLATFORM']=='win32-vc':
cxxflags.append ('/GR')
+if env['WITH_BF_GLEXT'] == 1:
+ env['CPPFLAGS'].append('-DWITH_GLEXT')
+
env.BlenderLib ( 'bf_bloutines', sources, Split(incs), [], libtype=['game', 'game2', 'player'], priority=[0, 0, 55] , compileflags=cxxflags)
diff --git a/source/gameengine/CMakeLists.txt b/source/gameengine/CMakeLists.txt
index 3ea788791e2..93de588ba00 100644
--- a/source/gameengine/CMakeLists.txt
+++ b/source/gameengine/CMakeLists.txt
@@ -40,7 +40,6 @@ SUBDIRS(
SceneGraph
Physics/Bullet
Physics/Sumo
- VideoTexture
)
IF(WITH_PLAYER)
diff --git a/source/gameengine/Converter/BL_ActionActuator.cpp b/source/gameengine/Converter/BL_ActionActuator.cpp
index 4d748948c27..2ee8b54a014 100644
--- a/source/gameengine/Converter/BL_ActionActuator.cpp
+++ b/source/gameengine/Converter/BL_ActionActuator.cpp
@@ -50,7 +50,6 @@
#include "MT_Matrix4x4.h"
#include "BKE_utildefines.h"
#include "FloatValue.h"
-#include "PyObjectPlus.h"
#ifdef HAVE_CONFIG_H
#include <config.h>
@@ -59,11 +58,11 @@
BL_ActionActuator::~BL_ActionActuator()
{
if (m_pose)
- game_free_pose(m_pose);
+ free_pose(m_pose);
if (m_userpose)
- game_free_pose(m_userpose);
+ free_pose(m_userpose);
if (m_blendpose)
- game_free_pose(m_blendpose);
+ free_pose(m_blendpose);
}
void BL_ActionActuator::ProcessReplica(){
@@ -152,8 +151,6 @@ bool BL_ActionActuator::Update(double curtime, bool frame)
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 !
@@ -448,28 +445,28 @@ PyParentObject BL_ActionActuator::Parents[] = {
};
PyMethodDef BL_ActionActuator::Methods[] = {
- {"setAction", (PyCFunction) BL_ActionActuator::sPySetAction, METH_VARARGS, (PY_METHODCHAR)SetAction_doc},
- {"setStart", (PyCFunction) BL_ActionActuator::sPySetStart, METH_VARARGS, (PY_METHODCHAR)SetStart_doc},
- {"setEnd", (PyCFunction) BL_ActionActuator::sPySetEnd, METH_VARARGS, (PY_METHODCHAR)SetEnd_doc},
- {"setBlendin", (PyCFunction) BL_ActionActuator::sPySetBlendin, METH_VARARGS, (PY_METHODCHAR)SetBlendin_doc},
- {"setPriority", (PyCFunction) BL_ActionActuator::sPySetPriority, METH_VARARGS, (PY_METHODCHAR)SetPriority_doc},
- {"setFrame", (PyCFunction) BL_ActionActuator::sPySetFrame, METH_VARARGS, (PY_METHODCHAR)SetFrame_doc},
- {"setProperty", (PyCFunction) BL_ActionActuator::sPySetProperty, METH_VARARGS, (PY_METHODCHAR)SetProperty_doc},
- {"setFrameProperty", (PyCFunction) BL_ActionActuator::sPySetFrameProperty, METH_VARARGS, (PY_METHODCHAR)SetFrameProperty_doc},
- {"setBlendtime", (PyCFunction) BL_ActionActuator::sPySetBlendtime, METH_VARARGS, (PY_METHODCHAR)SetBlendtime_doc},
-
- {"getAction", (PyCFunction) BL_ActionActuator::sPyGetAction, METH_VARARGS, (PY_METHODCHAR)GetAction_doc},
- {"getStart", (PyCFunction) BL_ActionActuator::sPyGetStart, METH_VARARGS, (PY_METHODCHAR)GetStart_doc},
- {"getEnd", (PyCFunction) BL_ActionActuator::sPyGetEnd, METH_VARARGS, (PY_METHODCHAR)GetEnd_doc},
- {"getBlendin", (PyCFunction) BL_ActionActuator::sPyGetBlendin, METH_VARARGS, (PY_METHODCHAR)GetBlendin_doc},
- {"getPriority", (PyCFunction) BL_ActionActuator::sPyGetPriority, METH_VARARGS, (PY_METHODCHAR)GetPriority_doc},
- {"getFrame", (PyCFunction) BL_ActionActuator::sPyGetFrame, METH_VARARGS, (PY_METHODCHAR)GetFrame_doc},
- {"getProperty", (PyCFunction) BL_ActionActuator::sPyGetProperty, METH_VARARGS, (PY_METHODCHAR)GetProperty_doc},
- {"getFrameProperty", (PyCFunction) BL_ActionActuator::sPyGetFrameProperty, METH_VARARGS, (PY_METHODCHAR)GetFrameProperty_doc},
- {"setChannel", (PyCFunction) BL_ActionActuator::sPySetChannel, METH_VARARGS, (PY_METHODCHAR)SetChannel_doc},
+ {"setAction", (PyCFunction) BL_ActionActuator::sPySetAction, METH_VARARGS, SetAction_doc},
+ {"setStart", (PyCFunction) BL_ActionActuator::sPySetStart, METH_VARARGS, SetStart_doc},
+ {"setEnd", (PyCFunction) BL_ActionActuator::sPySetEnd, METH_VARARGS, SetEnd_doc},
+ {"setBlendin", (PyCFunction) BL_ActionActuator::sPySetBlendin, METH_VARARGS, SetBlendin_doc},
+ {"setPriority", (PyCFunction) BL_ActionActuator::sPySetPriority, METH_VARARGS, SetPriority_doc},
+ {"setFrame", (PyCFunction) BL_ActionActuator::sPySetFrame, METH_VARARGS, SetFrame_doc},
+ {"setProperty", (PyCFunction) BL_ActionActuator::sPySetProperty, METH_VARARGS, SetProperty_doc},
+ {"setFrameProperty", (PyCFunction) BL_ActionActuator::sPySetFrameProperty, METH_VARARGS, SetFrameProperty_doc},
+ {"setBlendtime", (PyCFunction) BL_ActionActuator::sPySetBlendtime, METH_VARARGS, SetBlendtime_doc},
+
+ {"getAction", (PyCFunction) BL_ActionActuator::sPyGetAction, METH_VARARGS, GetAction_doc},
+ {"getStart", (PyCFunction) BL_ActionActuator::sPyGetStart, METH_VARARGS, GetStart_doc},
+ {"getEnd", (PyCFunction) BL_ActionActuator::sPyGetEnd, METH_VARARGS, GetEnd_doc},
+ {"getBlendin", (PyCFunction) BL_ActionActuator::sPyGetBlendin, METH_VARARGS, GetBlendin_doc},
+ {"getPriority", (PyCFunction) BL_ActionActuator::sPyGetPriority, METH_VARARGS, GetPriority_doc},
+ {"getFrame", (PyCFunction) BL_ActionActuator::sPyGetFrame, METH_VARARGS, GetFrame_doc},
+ {"getProperty", (PyCFunction) BL_ActionActuator::sPyGetProperty, METH_VARARGS, GetProperty_doc},
+ {"getFrameProperty", (PyCFunction) BL_ActionActuator::sPyGetFrameProperty, METH_VARARGS, GetFrameProperty_doc},
+ {"setChannel", (PyCFunction) BL_ActionActuator::sPySetChannel, METH_VARARGS, SetChannel_doc},
// {"getChannel", (PyCFunction) BL_ActionActuator::sPyGetChannel, METH_VARARGS},
- {"getType", (PyCFunction) BL_ActionActuator::sPyGetType, METH_VARARGS, (PY_METHODCHAR)GetType_doc},
- {"setType", (PyCFunction) BL_ActionActuator::sPySetType, METH_VARARGS, (PY_METHODCHAR)SetType_doc},
+ {"getType", (PyCFunction) BL_ActionActuator::sPyGetType, METH_VARARGS, GetType_doc},
+ {"setType", (PyCFunction) BL_ActionActuator::sPySetType, METH_VARARGS, SetType_doc},
{"getContinue", (PyCFunction) BL_ActionActuator::sPyGetContinue, METH_NOARGS, 0},
{"setContinue", (PyCFunction) BL_ActionActuator::sPySetContinue, METH_O, 0},
{NULL,NULL} //Sentinel
@@ -480,21 +477,28 @@ PyObject* BL_ActionActuator::_getattr(const STR_String& attr) {
}
/* setStart */
-const char BL_ActionActuator::GetAction_doc[] =
+char BL_ActionActuator::GetAction_doc[] =
"getAction()\n"
"\tReturns a string containing the name of the current action.\n";
PyObject* BL_ActionActuator::PyGetAction(PyObject* self,
PyObject* args,
PyObject* kwds) {
+ PyObject *result;
+
if (m_action){
- return PyString_FromString(m_action->id.name+2);
+ result = Py_BuildValue("s", m_action->id.name+2);
}
- Py_RETURN_NONE;
+ else{
+ Py_INCREF(Py_None);
+ result = Py_None;
+ }
+
+ return result;
}
/* getProperty */
-const char BL_ActionActuator::GetProperty_doc[] =
+char BL_ActionActuator::GetProperty_doc[] =
"getProperty()\n"
"\tReturns the name of the property to be used in FromProp mode.\n";
@@ -509,7 +513,7 @@ PyObject* BL_ActionActuator::PyGetProperty(PyObject* self,
}
/* getProperty */
-const char BL_ActionActuator::GetFrameProperty_doc[] =
+char BL_ActionActuator::GetFrameProperty_doc[] =
"getFrameProperty()\n"
"\tReturns the name of the property, that is set to the current frame number.\n";
@@ -524,7 +528,7 @@ PyObject* BL_ActionActuator::PyGetFrameProperty(PyObject* self,
}
/* getFrame */
-const char BL_ActionActuator::GetFrame_doc[] =
+char BL_ActionActuator::GetFrame_doc[] =
"getFrame()\n"
"\tReturns the current frame number.\n";
@@ -539,7 +543,7 @@ PyObject* BL_ActionActuator::PyGetFrame(PyObject* self,
}
/* getEnd */
-const char BL_ActionActuator::GetEnd_doc[] =
+char BL_ActionActuator::GetEnd_doc[] =
"getEnd()\n"
"\tReturns the last frame of the action.\n";
@@ -554,7 +558,7 @@ PyObject* BL_ActionActuator::PyGetEnd(PyObject* self,
}
/* getStart */
-const char BL_ActionActuator::GetStart_doc[] =
+char BL_ActionActuator::GetStart_doc[] =
"getStart()\n"
"\tReturns the starting frame of the action.\n";
@@ -569,7 +573,7 @@ PyObject* BL_ActionActuator::PyGetStart(PyObject* self,
}
/* getBlendin */
-const char BL_ActionActuator::GetBlendin_doc[] =
+char BL_ActionActuator::GetBlendin_doc[] =
"getBlendin()\n"
"\tReturns the number of interpolation animation frames to be\n"
"\tgenerated when this actuator is triggered.\n";
@@ -585,7 +589,7 @@ PyObject* BL_ActionActuator::PyGetBlendin(PyObject* self,
}
/* getPriority */
-const char BL_ActionActuator::GetPriority_doc[] =
+char BL_ActionActuator::GetPriority_doc[] =
"getPriority()\n"
"\tReturns the priority for this actuator. Actuators with lower\n"
"\tPriority numbers will override actuators with higher numbers.\n";
@@ -601,7 +605,7 @@ PyObject* BL_ActionActuator::PyGetPriority(PyObject* self,
}
/* setAction */
-const char BL_ActionActuator::SetAction_doc[] =
+char BL_ActionActuator::SetAction_doc[] =
"setAction(action, (reset))\n"
"\t - action : The name of the action to set as the current action.\n"
"\t - reset : Optional parameter indicating whether to reset the\n"
@@ -636,11 +640,12 @@ PyObject* BL_ActionActuator::PySetAction(PyObject* self,
return NULL;
}
- Py_RETURN_NONE;
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* setStart */
-const char BL_ActionActuator::SetStart_doc[] =
+char BL_ActionActuator::SetStart_doc[] =
"setStart(start)\n"
"\t - start : Specifies the starting frame of the animation.\n";
@@ -657,11 +662,12 @@ PyObject* BL_ActionActuator::PySetStart(PyObject* self,
return NULL;
}
- Py_RETURN_NONE;
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* setEnd */
-const char BL_ActionActuator::SetEnd_doc[] =
+char BL_ActionActuator::SetEnd_doc[] =
"setEnd(end)\n"
"\t - end : Specifies the ending frame of the animation.\n";
@@ -678,11 +684,12 @@ PyObject* BL_ActionActuator::PySetEnd(PyObject* self,
return NULL;
}
- Py_RETURN_NONE;
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* setBlendin */
-const char BL_ActionActuator::SetBlendin_doc[] =
+char BL_ActionActuator::SetBlendin_doc[] =
"setBlendin(blendin)\n"
"\t - blendin : Specifies the number of frames of animation to generate\n"
"\t when making transitions between actions.\n";
@@ -700,11 +707,12 @@ PyObject* BL_ActionActuator::PySetBlendin(PyObject* self,
return NULL;
}
- Py_RETURN_NONE;
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* setBlendtime */
-const char BL_ActionActuator::SetBlendtime_doc[] =
+char BL_ActionActuator::SetBlendtime_doc[] =
"setBlendtime(blendtime)\n"
"\t - blendtime : Allows the script to directly modify the internal timer\n"
"\t used when generating transitions between actions. This\n"
@@ -727,11 +735,12 @@ PyObject* BL_ActionActuator::PySetBlendtime(PyObject* self,
return NULL;
}
- Py_RETURN_NONE;
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* setPriority */
-const char BL_ActionActuator::SetPriority_doc[] =
+char BL_ActionActuator::SetPriority_doc[] =
"setPriority(priority)\n"
"\t - priority : Specifies the new priority. Actuators will lower\n"
"\t priority numbers will override actuators with higher\n"
@@ -750,11 +759,12 @@ PyObject* BL_ActionActuator::PySetPriority(PyObject* self,
return NULL;
}
- Py_RETURN_NONE;
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* setFrame */
-const char BL_ActionActuator::SetFrame_doc[] =
+char BL_ActionActuator::SetFrame_doc[] =
"setFrame(frame)\n"
"\t - frame : Specifies the new current frame for the animation\n";
@@ -775,11 +785,12 @@ PyObject* BL_ActionActuator::PySetFrame(PyObject* self,
return NULL;
}
- Py_RETURN_NONE;
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* setProperty */
-const char BL_ActionActuator::SetProperty_doc[] =
+char BL_ActionActuator::SetProperty_doc[] =
"setProperty(prop)\n"
"\t - prop : A string specifying the property name to be used in\n"
"\t FromProp playback mode.\n";
@@ -797,11 +808,12 @@ PyObject* BL_ActionActuator::PySetProperty(PyObject* self,
return NULL;
}
- Py_RETURN_NONE;
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* setFrameProperty */
-const char BL_ActionActuator::SetFrameProperty_doc[] =
+char BL_ActionActuator::SetFrameProperty_doc[] =
"setFrameProperty(prop)\n"
"\t - prop : A string specifying the property of the frame set up update.\n";
@@ -818,7 +830,8 @@ PyObject* BL_ActionActuator::PySetFrameProperty(PyObject* self,
return NULL;
}
- Py_RETURN_NONE;
+ Py_INCREF(Py_None);
+ return Py_None;
}
/*
@@ -835,12 +848,13 @@ PyObject* BL_ActionActuator::PyGetChannel(PyObject* self,
return NULL;
}
- Py_RETURN_NONE;
+ Py_INCREF(Py_None);
+ return Py_None;
}
*/
/* setChannel */
-const char BL_ActionActuator::SetChannel_doc[] =
+char BL_ActionActuator::SetChannel_doc[] =
"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"
@@ -920,11 +934,12 @@ PyObject* BL_ActionActuator::PySetChannel(PyObject* self,
}
}
- Py_RETURN_NONE;
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* getType */
-const char BL_ActionActuator::GetType_doc[] =
+char BL_ActionActuator::GetType_doc[] =
"getType()\n"
"\tReturns the operation mode of the actuator.\n";
PyObject* BL_ActionActuator::PyGetType(PyObject* self,
@@ -934,7 +949,7 @@ PyObject* BL_ActionActuator::PyGetType(PyObject* self,
}
/* setType */
-const char BL_ActionActuator::SetType_doc[] =
+char BL_ActionActuator::SetType_doc[] =
"setType(mode)\n"
"\t - mode: Play (0), Flipper (2), LoopStop (3), LoopEnd (4) or Property (6)\n"
"\tSet the operation mode of the actuator.\n";
diff --git a/source/gameengine/Converter/BL_ArmatureObject.cpp b/source/gameengine/Converter/BL_ArmatureObject.cpp
index d2001212f7d..09f1d9d4d87 100644
--- a/source/gameengine/Converter/BL_ArmatureObject.cpp
+++ b/source/gameengine/Converter/BL_ArmatureObject.cpp
@@ -45,6 +45,7 @@
#include <config.h>
#endif
+
BL_ArmatureObject::BL_ArmatureObject(
void* sgReplicationInfo,
SG_Callbacks callbacks,
@@ -52,21 +53,16 @@ BL_ArmatureObject::BL_ArmatureObject(
: KX_GameObject(sgReplicationInfo,callbacks),
m_objArma(armature),
- m_framePose(NULL),
- m_lastframe(0.0),
+ m_mrdPose(NULL),
+ m_lastframe(0.),
m_activeAct(NULL),
- m_activePriority(999),
- m_lastapplyframe(0.0)
+ m_activePriority(999)
{
m_armature = get_armature(m_objArma);
-
- /* we make a copy of blender object's pose, and then always swap it with
- * the original pose before calling into blender functions, to deal with
- * replica's or other objects using the same blender object */
- m_pose = NULL;
- game_copy_pose(&m_pose, m_objArma->pose);
+ m_pose = m_objArma->pose;
}
+
CValue* BL_ArmatureObject::GetReplica()
{
BL_ArmatureObject* replica = new BL_ArmatureObject(*this);
@@ -82,37 +78,34 @@ void BL_ArmatureObject::ProcessReplica(BL_ArmatureObject *replica)
{
KX_GameObject::ProcessReplica(replica);
- replica->m_pose = NULL;
- game_copy_pose(&replica->m_pose, m_pose);
}
BL_ArmatureObject::~BL_ArmatureObject()
{
- if (m_pose)
- game_free_pose(m_pose);
+ if (m_mrdPose)
+ free_pose(m_mrdPose);
}
+/* note, you can only call this for exisiting Armature objects, and not mix it with other Armatures */
+/* there is only 1 unique Pose per Armature */
void BL_ArmatureObject::ApplyPose()
{
- m_armpose = m_objArma->pose;
- m_objArma->pose = m_pose;
-
- if(m_lastapplyframe != m_lastframe) {
- where_is_pose(m_objArma);
- m_lastapplyframe = m_lastframe;
+ if (m_pose) {
+ // copy to armature object
+ if (m_objArma->pose != m_pose)/* This should never happen but it does - Campbell */
+ extract_pose_from_pose(m_objArma->pose, m_pose);
+
+ // is this needed anymore?
+ //if (!m_mrdPose)
+ // copy_pose (&m_mrdPose, m_pose, 0);
+ //else
+ // extract_pose_from_pose(m_mrdPose, m_pose);
}
}
-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;
+ m_pose = pose;
}
bool BL_ArmatureObject::SetActiveAction(BL_ActionActuator *act, short priority, double curtime)
@@ -121,15 +114,10 @@ bool BL_ArmatureObject::SetActiveAction(BL_ActionActuator *act, short priority,
m_activePriority = 9999;
m_lastframe= curtime;
m_activeAct = NULL;
- // remember the pose at the start of the frame
- m_framePose = m_pose;
}
if (priority<=m_activePriority)
{
- if (priority<m_activePriority)
- // this action overwrites the previous ones, start from initial pose to cancel their effects
- m_pose = m_framePose;
if (m_activeAct && (m_activeAct!=act))
m_activeAct->SetBlendTime(0.0); /* Reset the blend timer */
m_activeAct = act;
@@ -161,13 +149,13 @@ void BL_ArmatureObject::GetPose(bPose **pose)
a crash and memory leakage when
&BL_ActionActuator::m_pose is freed
*/
- game_copy_pose(pose, m_pose);
+ int copy_constraint_channels_hack = 1;
+ copy_pose(pose, m_pose, copy_constraint_channels_hack);
}
else {
if (*pose == m_pose)
// no need to copy if the pointers are the same
return;
-
extract_pose_from_pose(*pose, m_pose);
}
}
@@ -177,10 +165,21 @@ void BL_ArmatureObject::GetMRDPose(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)
- game_copy_pose(pose, m_pose);
+ // is this needed anymore?
+ //if (!m_mrdPose){
+ // copy_pose (&m_mrdPose, m_pose, 0);
+ //}
+
+ if (!*pose) {
+ // must duplicate the constraints too otherwise we have corruption in free_pose_channels()
+ // because it will free the blender constraints.
+ // Ideally, blender should rememeber that the constraints were not copied so that
+ // free_pose_channels() would not free them.
+ copy_pose(pose, m_objArma->pose, 1);
+ }
else
- extract_pose_from_pose(*pose, m_pose);
+ extract_pose_from_pose(*pose, m_objArma->pose);
+
}
short BL_ArmatureObject::GetActivePriority()
@@ -193,17 +192,17 @@ double BL_ArmatureObject::GetLastFrame()
return m_lastframe;
}
-bool BL_ArmatureObject::GetBoneMatrix(Bone* bone, MT_Matrix4x4& matrix)
+bool BL_ArmatureObject::GetBoneMatrix(Bone* bone, MT_Matrix4x4& matrix) const
{
- bPoseChannel *pchan;
+ Object* par_arma = m_objArma;
+ where_is_pose(par_arma);
+ bPoseChannel *pchan= get_pose_channel(par_arma->pose, bone->name);
- ApplyPose();
- pchan = get_pose_channel(m_objArma->pose, bone->name);
- if(pchan)
+ if(pchan) {
matrix.setValue(&pchan->pose_mat[0][0]);
- RestorePose();
-
- return (pchan != NULL);
+ return true;
+ }
+ return false;
}
float BL_ArmatureObject::GetBoneLength(Bone* bone) const
diff --git a/source/gameengine/Converter/BL_ArmatureObject.h b/source/gameengine/Converter/BL_ArmatureObject.h
index d68e37d9e37..752bd5eb365 100644
--- a/source/gameengine/Converter/BL_ArmatureObject.h
+++ b/source/gameengine/Converter/BL_ArmatureObject.h
@@ -59,10 +59,7 @@ public:
void GetMRDPose(struct bPose **pose);
void GetPose(struct bPose **pose);
void SetPose (struct bPose *pose);
-
void ApplyPose();
- void RestorePose();
-
bool SetActiveAction(class BL_ActionActuator *act, short priority, double curtime);
struct bArmature * GetArmature() { return m_armature; }
@@ -72,7 +69,7 @@ public:
/// Retrieve the pose matrix for the specified bone.
/// Returns true on success.
- bool GetBoneMatrix(Bone* bone, MT_Matrix4x4& matrix);
+ bool GetBoneMatrix(Bone* bone, MT_Matrix4x4& matrix) const;
/// Returns the bone length. The end of the bone is in the local y direction.
float GetBoneLength(Bone* bone) const;
@@ -82,13 +79,10 @@ protected:
Object *m_objArma;
struct bArmature *m_armature;
struct bPose *m_pose;
- struct bPose *m_armpose;
- struct bPose *m_framePose;
+ struct bPose *m_mrdPose;
double m_lastframe;
class BL_ActionActuator *m_activeAct;
short m_activePriority;
-
- double m_lastapplyframe;
};
#endif
diff --git a/source/gameengine/Converter/BL_BlenderDataConversion.cpp b/source/gameengine/Converter/BL_BlenderDataConversion.cpp
index 9c699b67b28..a6337403cd1 100644
--- a/source/gameengine/Converter/BL_BlenderDataConversion.cpp
+++ b/source/gameengine/Converter/BL_BlenderDataConversion.cpp
@@ -129,7 +129,6 @@
#include "DNA_sound_types.h"
#include "DNA_key_types.h"
#include "DNA_armature_types.h"
-#include "DNA_object_force.h"
#include "MEM_guardedalloc.h"
#include "BKE_utildefines.h"
@@ -309,7 +308,7 @@ static void GetRGB(short type,
typedef struct MTF_localLayer
{
MTFace *face;
- const char *name;
+ char *name;
}MTF_localLayer;
// ------------------------------------
@@ -378,7 +377,6 @@ BL_Material* ConvertMaterial(
material->texname[i] = material->img[i]->id.name;
material->flag[i] |= ( tface->transp &TF_ALPHA )?USEALPHA:0;
material->flag[i] |= ( tface->transp &TF_ADD )?CALCALPHA:0;
- material->flag[i] |= MIPMAP;
if(material->img[i]->flag & IMA_REFLECT)
material->mapping[i].mapping |= USEREFL;
@@ -603,6 +601,7 @@ BL_Material* ConvertMaterial(
(tface->mode & TF_INVISIBLE)
)?POLY_VIS:0;
+ material->ras_mode |= ( (tface->mode & TF_DYNAMIC)!= 0 )?COLLIDER:0;
material->transp = tface->transp;
material->tile = tface->tile;
material->mode = tface->mode;
@@ -618,7 +617,7 @@ BL_Material* ConvertMaterial(
}
else {
// nothing at all
- material->ras_mode |= (POLY_VIS| (validmat?0:USE_LIGHT));
+ material->ras_mode |= (COLLIDER|POLY_VIS| (validmat?0:USE_LIGHT));
material->mode = default_face_mode;
material->transp = TF_SOLID;
material->tile = 0;
@@ -628,19 +627,13 @@ BL_Material* ConvertMaterial(
if(validmat && (mat->mode & MA_ZTRA) && (material->transp == TF_SOLID))
material->transp = TF_ALPHA;
- // always zsort alpha + add
- if((material->transp == TF_ALPHA || material->transp == TF_ADD || texalpha) && (material->transp != TF_CLIP)) {
+ // always zsort alpha + add
+ if((material->transp == TF_ALPHA || material->transp == TF_ADD || texalpha)
+ && (material->transp != TF_CLIP)) {
material->ras_mode |= ALPHA;
material->ras_mode |= (material->mode & TF_ALPHASORT)? ZSORT: 0;
}
- // collider or not?
- material->ras_mode |= (material->mode & TF_DYNAMIC)? COLLIDER: 0;
-
- // these flags are irrelevant at this point, remove so they
- // don't hurt material bucketing
- material->mode &= ~(TF_DYNAMIC|TF_ALPHASORT|TF_TEX);
-
// get uv sets
if(validmat)
{
@@ -651,7 +644,6 @@ BL_Material* ConvertMaterial(
for (int vind = 0; vind<material->num_enabled; vind++)
{
BL_Mapping &map = material->mapping[vind];
-
if (map.uvCoName.IsEmpty())
isFirstSet = false;
else
@@ -681,7 +673,7 @@ BL_Material* ConvertMaterial(
isFirstSet = false;
uvName = layer.name;
}
- else if(strcmp(layer.name, uvName) != 0)
+ else
{
uv2[0] = uvSet[0]; uv2[1] = uvSet[1];
uv2[2] = uvSet[2]; uv2[3] = uvSet[3];
@@ -710,6 +702,7 @@ BL_Material* ConvertMaterial(
material->SetConversionUV(uvName, uv);
material->SetConversionUV2(uv2Name, uv2);
+ material->ras_mode |= (mface->v4==0)?TRIANGLE:0;
if(validmat)
material->matname =(mat->id.name);
@@ -744,8 +737,7 @@ RAS_MeshObject* BL_ConvertMesh(Mesh* mesh, Object* blenderobj, RAS_IRenderTools*
}
// Determine if we need to make a skinned mesh
- if (mesh->dvert || mesh->key || ((blenderobj->gameflag & OB_SOFT_BODY) != 0))
- {
+ if (mesh->dvert || mesh->key) {
meshobj = new BL_SkinMeshObject(mesh, lightlayer);
skinMesh = true;
}
@@ -775,7 +767,7 @@ RAS_MeshObject* BL_ConvertMesh(Mesh* mesh, Object* blenderobj, RAS_IRenderTools*
}
meshobj->SetName(mesh->id.name);
- meshobj->m_sharedvertex_map.resize(totvert);
+ meshobj->m_xyz_index_to_vertex_index_mapping.resize(totvert);
for (int f=0;f<totface;f++,mface++)
{
@@ -785,9 +777,9 @@ RAS_MeshObject* BL_ConvertMesh(Mesh* mesh, Object* blenderobj, RAS_IRenderTools*
MT_Point2 uv20(0.0,0.0),uv21(0.0,0.0),uv22(0.0,0.0),uv23(0.0,0.0);
unsigned int rgb0,rgb1,rgb2,rgb3 = 0;
+ MT_Vector3 no0, no1, no2, no3;
MT_Point3 pt0, pt1, pt2, pt3;
- MT_Vector3 no0(0,0,0), no1(0,0,0), no2(0,0,0), no3(0,0,0);
- MT_Vector4 tan0(0,0,0,0), tan1(0,0,0,0), tan2(0,0,0,0), tan3(0,0,0,0);
+ MT_Vector4 tan0, tan1, tan2, tan3;
/* get coordinates, normals and tangents */
pt0 = MT_Point3(mvert[mface->v1].co);
@@ -809,6 +801,8 @@ RAS_MeshObject* BL_ConvertMesh(Mesh* mesh, Object* blenderobj, RAS_IRenderTools*
NormalShortToFloat(n3, mvert[mface->v4].no);
no3 = n3;
}
+ else
+ no3 = MT_Vector3(0.0, 0.0, 0.0);
}
else {
float fno[3];
@@ -836,7 +830,7 @@ RAS_MeshObject* BL_ConvertMesh(Mesh* mesh, Object* blenderobj, RAS_IRenderTools*
ma = give_current_material(blenderobj, mface->mat_nr+1);
{
- bool visible = true;
+ bool polyvisible = true;
RAS_IPolyMaterial* polymat = NULL;
BL_Material *bl_mat = NULL;
@@ -851,7 +845,7 @@ RAS_MeshObject* BL_ConvertMesh(Mesh* mesh, Object* blenderobj, RAS_IRenderTools*
bl_mat->material_index = (int)mface->mat_nr;
- visible = ((bl_mat->ras_mode & POLY_VIS)!=0);
+ polyvisible = ((bl_mat->ras_mode & POLY_VIS)!=0);
collider = ((bl_mat->ras_mode & COLLIDER)!=0);
/* vertex colors and uv's were stored in bl_mat temporarily */
@@ -868,7 +862,7 @@ RAS_MeshObject* BL_ConvertMesh(Mesh* mesh, Object* blenderobj, RAS_IRenderTools*
uv22 = uv[2]; uv23 = uv[3];
/* then the KX_BlenderMaterial */
- polymat = new KX_BlenderMaterial(scene, bl_mat, skinMesh, lightlayer);
+ polymat = new KX_BlenderMaterial(scene, bl_mat, skinMesh, lightlayer, blenderobj );
}
else {
/* do Texture Face materials */
@@ -892,7 +886,7 @@ RAS_MeshObject* BL_ConvertMesh(Mesh* mesh, Object* blenderobj, RAS_IRenderTools*
tile = tface->tile;
mode = tface->mode;
- visible = !((mface->flag & ME_HIDE)||(tface->mode & TF_INVISIBLE));
+ polyvisible = !((mface->flag & ME_HIDE)||(tface->mode & TF_INVISIBLE));
uv0 = MT_Point2(tface->uv[0]);
uv1 = MT_Point2(tface->uv[1]);
@@ -946,13 +940,15 @@ RAS_MeshObject* BL_ConvertMesh(Mesh* mesh, Object* blenderobj, RAS_IRenderTools*
rgb3 = KX_rgbaint2uint_new(color);
}
+ bool istriangle = (mface->v4==0);
+
// only zsort alpha + add
bool alpha = (transp == TF_ALPHA || transp == TF_ADD);
bool zsort = (mode & TF_ALPHASORT)? alpha: 0;
polymat = new KX_PolygonMaterial(imastr, ma,
tile, tilexrep, tileyrep,
- mode, transp, alpha, zsort, lightlayer, tface, (unsigned int*)mcol);
+ mode, transp, alpha, zsort, lightlayer, istriangle, blenderobj, tface, (unsigned int*)mcol);
if (ma) {
polymat->m_specular = MT_Vector3(ma->specr, ma->specg, ma->specb)*ma->spec;
@@ -965,9 +961,6 @@ RAS_MeshObject* BL_ConvertMesh(Mesh* mesh, Object* blenderobj, RAS_IRenderTools*
}
}
- /* mark face as flat, so vertices are split */
- bool flat = (mface->flag & ME_SMOOTH) == 0;
-
// 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;
@@ -988,19 +981,49 @@ RAS_MeshObject* BL_ConvertMesh(Mesh* mesh, Object* blenderobj, RAS_IRenderTools*
polymat = bucket->GetPolyMaterial();
}
- int nverts = (mface->v4)? 4: 3;
- RAS_Polygon *poly = meshobj->AddPolygon(bucket, nverts);
-
- poly->SetVisible(visible);
- poly->SetCollider(collider);
- //poly->SetEdgeCode(mface->edcode);
-
- meshobj->AddVertex(poly,0,pt0,uv0,uv20,tan0,rgb0,no0,flat,mface->v1);
- meshobj->AddVertex(poly,1,pt1,uv1,uv21,tan1,rgb1,no1,flat,mface->v2);
- meshobj->AddVertex(poly,2,pt2,uv2,uv22,tan2,rgb2,no2,flat,mface->v3);
+ int nverts = mface->v4?4:3;
+ int vtxarray = meshobj->FindVertexArray(nverts,polymat);
+ RAS_Polygon* poly = new RAS_Polygon(bucket,polyvisible,nverts,vtxarray);
+
+ bool flat;
+
+ if (skinMesh) {
+ /* If the face is set to solid, all fnors are the same */
+ if (mface->flag & ME_SMOOTH)
+ flat = false;
+ else
+ flat = true;
+ }
+ else
+ flat = false;
+ poly->SetVertex(0,meshobj->FindOrAddVertex(vtxarray,pt0,uv0,uv20,tan0,rgb0,no0,flat,polymat,mface->v1));
+ poly->SetVertex(1,meshobj->FindOrAddVertex(vtxarray,pt1,uv1,uv21,tan1,rgb1,no1,flat,polymat,mface->v2));
+ poly->SetVertex(2,meshobj->FindOrAddVertex(vtxarray,pt2,uv2,uv22,tan2,rgb2,no2,flat,polymat,mface->v3));
if (nverts==4)
- meshobj->AddVertex(poly,3,pt3,uv3,uv23,tan3,rgb3,no3,flat,mface->v4);
+ poly->SetVertex(3,meshobj->FindOrAddVertex(vtxarray,pt3,uv3,uv23,tan3,rgb3,no3,flat,polymat,mface->v4));
+
+ meshobj->AddPolygon(poly);
+ if (poly->IsCollider())
+ {
+ RAS_TriangleIndex idx;
+ idx.m_index[0] = mface->v1;
+ idx.m_index[1] = mface->v2;
+ idx.m_index[2] = mface->v3;
+ idx.m_collider = collider;
+ meshobj->m_triangle_indices.push_back(idx);
+ if (nverts==4)
+ {
+ idx.m_index[0] = mface->v1;
+ idx.m_index[1] = mface->v3;
+ idx.m_index[2] = mface->v4;
+ idx.m_collider = collider;
+ meshobj->m_triangle_indices.push_back(idx);
+ }
+ }
+
+// poly->SetVisibleWireframeEdges(mface->edcode);
+ poly->SetCollider(collider);
}
if (tface)
@@ -1016,12 +1039,13 @@ RAS_MeshObject* BL_ConvertMesh(Mesh* mesh, Object* blenderobj, RAS_IRenderTools*
layer.face++;
}
}
- meshobj->m_sharedvertex_map.clear();
+ meshobj->m_xyz_index_to_vertex_index_mapping.clear();
+ meshobj->UpdateMaterialList();
// pre calculate texture generation
- for(list<RAS_MeshMaterial>::iterator mit = meshobj->GetFirstMaterial();
+ for(RAS_MaterialBucket::Set::iterator mit = meshobj->GetFirstMaterial();
mit != meshobj->GetLastMaterial(); ++ mit) {
- mit->m_bucket->GetPolyMaterial()->OnConstruction();
+ (*mit)->GetPolyMaterial()->OnConstruction();
}
if (layers)
@@ -1281,10 +1305,6 @@ void BL_CreatePhysicsObjectNew(KX_GameObject* gameobj,
//int userigidbody = SYS_GetCommandLineInt(syshandle,"norigidbody",0);
//bool bRigidBody = (userigidbody == 0);
- // object has physics representation?
- if (!(blenderobject->gameflag & OB_COLLISION))
- return;
-
// get Root Parent of blenderobject
struct Object* parent= blenderobject->parent;
while(parent && parent->parent) {
@@ -1316,97 +1336,19 @@ void BL_CreatePhysicsObjectNew(KX_GameObject* gameobj,
objprop.m_isCompoundChild = isCompoundChild;
objprop.m_hasCompoundChildren = (blenderobject->gameflag & OB_CHILD) != 0;
- objprop.m_margin = blenderobject->margin;
- // ACTOR is now a separate feature
- objprop.m_isactor = (blenderobject->gameflag & OB_ACTOR)!=0;
- objprop.m_dyna = (blenderobject->gameflag & OB_DYNAMIC) != 0;
- objprop.m_softbody = (blenderobject->gameflag & OB_SOFT_BODY) != 0;
- objprop.m_angular_rigidbody = (blenderobject->gameflag & OB_RIGID_BODY) != 0;
-
- if (objprop.m_softbody)
+
+ if ((objprop.m_isactor = (blenderobject->gameflag & OB_ACTOR)!=0))
{
- ///for game soft bodies
- if (blenderobject->bsoft)
- {
- objprop.m_gamesoftFlag = blenderobject->bsoft->flag;
- ///////////////////
- objprop.m_soft_linStiff = blenderobject->bsoft->linStiff;
- objprop.m_soft_angStiff = blenderobject->bsoft->angStiff; /* angular stiffness 0..1 */
- objprop.m_soft_volume= blenderobject->bsoft->volume; /* volume preservation 0..1 */
-
- objprop.m_soft_viterations= blenderobject->bsoft->viterations; /* Velocities solver iterations */
- objprop.m_soft_piterations= blenderobject->bsoft->piterations; /* Positions solver iterations */
- objprop.m_soft_diterations= blenderobject->bsoft->diterations; /* Drift solver iterations */
- objprop.m_soft_citerations= blenderobject->bsoft->citerations; /* Cluster solver iterations */
-
- objprop.m_soft_kSRHR_CL= blenderobject->bsoft->kSRHR_CL; /* Soft vs rigid hardness [0,1] (cluster only) */
- objprop.m_soft_kSKHR_CL= blenderobject->bsoft->kSKHR_CL; /* Soft vs kinetic hardness [0,1] (cluster only) */
- objprop.m_soft_kSSHR_CL= blenderobject->bsoft->kSSHR_CL; /* Soft vs soft hardness [0,1] (cluster only) */
- objprop.m_soft_kSR_SPLT_CL= blenderobject->bsoft->kSR_SPLT_CL; /* Soft vs rigid impulse split [0,1] (cluster only) */
-
- objprop.m_soft_kSK_SPLT_CL= blenderobject->bsoft->kSK_SPLT_CL; /* Soft vs rigid impulse split [0,1] (cluster only) */
- objprop.m_soft_kSS_SPLT_CL= blenderobject->bsoft->kSS_SPLT_CL; /* Soft vs rigid impulse split [0,1] (cluster only) */
- objprop.m_soft_kVCF= blenderobject->bsoft->kVCF; /* Velocities correction factor (Baumgarte) */
- objprop.m_soft_kDP= blenderobject->bsoft->kDP; /* Damping coefficient [0,1] */
-
- objprop.m_soft_kDG= blenderobject->bsoft->kDG; /* Drag coefficient [0,+inf] */
- objprop.m_soft_kLF= blenderobject->bsoft->kLF; /* Lift coefficient [0,+inf] */
- objprop.m_soft_kPR= blenderobject->bsoft->kPR; /* Pressure coefficient [-inf,+inf] */
- objprop.m_soft_kVC= blenderobject->bsoft->kVC; /* Volume conversation coefficient [0,+inf] */
-
- objprop.m_soft_kDF= blenderobject->bsoft->kDF; /* Dynamic friction coefficient [0,1] */
- objprop.m_soft_kMT= blenderobject->bsoft->kMT; /* Pose matching coefficient [0,1] */
- objprop.m_soft_kCHR= blenderobject->bsoft->kCHR; /* Rigid contacts hardness [0,1] */
- objprop.m_soft_kKHR= blenderobject->bsoft->kKHR; /* Kinetic contacts hardness [0,1] */
-
- objprop.m_soft_kSHR= blenderobject->bsoft->kSHR; /* Soft contacts hardness [0,1] */
- objprop.m_soft_kAHR= blenderobject->bsoft->kAHR; /* Anchors hardness [0,1] */
- objprop.m_soft_collisionflags= blenderobject->bsoft->collisionflags; /* Vertex/Face or Signed Distance Field(SDF) or Clusters, Soft versus Soft or Rigid */
- objprop.m_soft_numclusteriterations= blenderobject->bsoft->numclusteriterations; /* number of iterations to refine collision clusters*/
-
- } else
- {
- objprop.m_gamesoftFlag = OB_BSB_BENDING_CONSTRAINTS | OB_BSB_SHAPE_MATCHING | OB_BSB_AERO_VPOINT;
-
- objprop.m_soft_linStiff = 0.5;;
- objprop.m_soft_angStiff = 1.f; /* angular stiffness 0..1 */
- objprop.m_soft_volume= 1.f; /* volume preservation 0..1 */
-
-
- objprop.m_soft_viterations= 0;
- objprop.m_soft_piterations= 1;
- objprop.m_soft_diterations= 0;
- objprop.m_soft_citerations= 4;
-
- objprop.m_soft_kSRHR_CL= 0.1f;
- objprop.m_soft_kSKHR_CL= 1.f;
- objprop.m_soft_kSSHR_CL= 0.5;
- objprop.m_soft_kSR_SPLT_CL= 0.5f;
-
- objprop.m_soft_kSK_SPLT_CL= 0.5f;
- objprop.m_soft_kSS_SPLT_CL= 0.5f;
- objprop.m_soft_kVCF= 1;
- objprop.m_soft_kDP= 0;
-
- objprop.m_soft_kDG= 0;
- objprop.m_soft_kLF= 0;
- objprop.m_soft_kPR= 0;
- objprop.m_soft_kVC= 0;
-
- objprop.m_soft_kDF= 0.2f;
- objprop.m_soft_kMT= 0.05f;
- objprop.m_soft_kCHR= 1.0f;
- objprop.m_soft_kKHR= 0.1f;
-
- objprop.m_soft_kSHR= 1.f;
- objprop.m_soft_kAHR= 0.7f;
- objprop.m_soft_collisionflags= OB_BSB_COL_SDF_RS + OB_BSB_COL_VF_SS;
- objprop.m_soft_numclusteriterations= 16;
- }
+ objprop.m_dyna = (blenderobject->gameflag & OB_DYNAMIC) != 0;
+ objprop.m_angular_rigidbody = (blenderobject->gameflag & OB_RIGID_BODY) != 0;
+ objprop.m_ghost = (blenderobject->gameflag & OB_GHOST) != 0;
+ objprop.m_disableSleeping = (blenderobject->gameflag & OB_COLLISION_RESPONSE) != 0;//abuse the OB_COLLISION_RESPONSE flag
+ } else {
+ objprop.m_dyna = false;
+ objprop.m_angular_rigidbody = false;
+ objprop.m_ghost = false;
+ objprop.m_disableSleeping = false;
}
-
- objprop.m_ghost = (blenderobject->gameflag & OB_GHOST) != 0;
- objprop.m_disableSleeping = (blenderobject->gameflag & OB_COLLISION_RESPONSE) != 0;//abuse the OB_COLLISION_RESPONSE flag
//mmm, for now, taks this for the size of the dynamicobject
// Blender uses inertia for radius of dynamic object
objprop.m_radius = blenderobject->inertia;
@@ -1414,12 +1356,6 @@ void BL_CreatePhysicsObjectNew(KX_GameObject* gameobj,
objprop.m_dynamic_parent=NULL;
objprop.m_isdeformable = ((blenderobject->gameflag2 & 2)) != 0;
objprop.m_boundclass = objprop.m_dyna?KX_BOUNDSPHERE:KX_BOUNDMESH;
-
- if ((blenderobject->gameflag & OB_SOFT_BODY) && !(blenderobject->gameflag & OB_BOUNDS))
- {
- objprop.m_boundclass = KX_BOUNDMESH;
- }
-
KX_BoxBounds bb;
my_get_local_bounds(blenderobject,objprop.m_boundobject.box.m_center,bb.m_extends);
if (blenderobject->gameflag & OB_BOUNDS)
@@ -1554,9 +1490,14 @@ static KX_LightObject *gamelight_from_blamp(Object *ob, Lamp *la, unsigned int l
lightobj.m_type = RAS_LightObject::LIGHT_NORMAL;
}
- gamelight = new KX_LightObject(kxscene, KX_Scene::m_callbacks, rendertools,
- lightobj, converter->GetGLSLMaterials());
-
+#ifdef BLENDER_GLSL
+ if(converter->GetGLSLMaterials())
+ GPU_lamp_from_blender(ob, la);
+
+ gamelight = new KX_LightObject(kxscene, KX_Scene::m_callbacks, rendertools, lightobj, ob->gpulamp);
+#else
+ gamelight = new KX_LightObject(kxscene, KX_Scene::m_callbacks, rendertools, lightobj, NULL);
+#endif
BL_ConvertLampIpos(la, gamelight, converter);
return gamelight;
@@ -1593,7 +1534,7 @@ static KX_GameObject *gameobject_from_blenderobject(
gamelight->AddRef();
kxscene->GetLightList()->Add(gamelight);
-
+
break;
}
@@ -1645,20 +1586,20 @@ static KX_GameObject *gameobject_from_blenderobject(
// not that we can have shape keys without dvert!
BL_ShapeDeformer *dcont = new BL_ShapeDeformer((BL_DeformableGameObject*)gameobj,
ob, (BL_SkinMeshObject*)meshobj);
- ((BL_DeformableGameObject*)gameobj)->SetDeformer(dcont);
+ ((BL_DeformableGameObject*)gameobj)->m_pDeformer = dcont;
if (bHasArmature)
dcont->LoadShapeDrivers(ob->parent);
} else if (bHasArmature) {
BL_SkinDeformer *dcont = new BL_SkinDeformer((BL_DeformableGameObject*)gameobj,
ob, (BL_SkinMeshObject*)meshobj);
- ((BL_DeformableGameObject*)gameobj)->SetDeformer(dcont);
+ ((BL_DeformableGameObject*)gameobj)->m_pDeformer = 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, (BL_SkinMeshObject*)meshobj);
- ((BL_DeformableGameObject*)gameobj)->SetDeformer(dcont);
+ ((BL_DeformableGameObject*)gameobj)->m_pDeformer = dcont;
}
MT_Point3 min = MT_Point3(center) - MT_Vector3(extents);
@@ -1693,8 +1634,6 @@ static KX_GameObject *gameobject_from_blenderobject(
gameobj->SetPhysicsEnvironment(kxscene->GetPhysicsEnvironment());
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;
}
@@ -1704,6 +1643,20 @@ struct parentChildLink {
SG_Node* m_gamechildnode;
};
+ /**
+ * Find the specified scene by name, or the first
+ * scene if nothing matches (shouldn't happen).
+ */
+static struct Scene *GetSceneForName(struct Main *maggie, const STR_String& scenename) {
+ Scene *sce;
+
+ for (sce= (Scene*) maggie->scene.first; sce; sce= (Scene*) sce->id.next)
+ if (scenename == (sce->id.name+2))
+ return sce;
+
+ return (Scene*) maggie->scene.first;
+}
+
#include "DNA_constraint_types.h"
#include "BIF_editconstraint.h"
@@ -1802,7 +1755,7 @@ void BL_ConvertBlenderObjects(struct Main* maggie,
)
{
- Scene *blenderscene = converter->GetBlenderSceneForName(scenename);
+ Scene *blenderscene = GetSceneForName(maggie, scenename);
// for SETLOOPER
Scene *sce;
Base *base;
@@ -1993,22 +1946,10 @@ void BL_ConvertBlenderObjects(struct Main* maggie,
//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 scale(x.length(), y.length(), z.length());
- if (!MT_fuzzyZero(scale[0]))
- x /= scale[0];
- if (!MT_fuzzyZero(scale[1]))
- y /= scale[1];
- if (!MT_fuzzyZero(scale[2]))
- z /= scale[2];
- ori.setColumn(0, x);
- ori.setColumn(1, y);
- ori.setColumn(2, z);
- parentinversenode->SetLocalOrientation(ori);
- parentinversenode->SetLocalScale(scale);
+ MT_Matrix3x3 inverseOrientation(parinvtrans.getRotation());
+ parentinversenode->SetLocalOrientation(inverseOrientation);
+ MT_Matrix3x3 scale(inverseOrientation.transposed()*parinvtrans.getBasis());
+ parentinversenode->SetLocalScale(MT_Vector3(scale[0][0], scale[1][1], scale[2][2]));
parentinversenode->AddChild(gameobj->GetSGNode());
}
@@ -2037,7 +1978,7 @@ void BL_ConvertBlenderObjects(struct Main* maggie,
//tf.Add(gameobj->GetSGNode());
gameobj->NodeUpdateGS(0,true);
- gameobj->AddMeshUser();
+ gameobj->Bucketize();
}
else
@@ -2188,24 +2129,7 @@ void BL_ConvertBlenderObjects(struct Main* maggie,
float* fl = (float*) blenderobject->parentinv;
MT_Transform parinvtrans(fl);
parentinversenode->SetLocalPosition(parinvtrans.getOrigin());
-
- // 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 scale(x.length(), y.length(), z.length());
- if (!MT_fuzzyZero(scale[0]))
- x /= scale[0];
- if (!MT_fuzzyZero(scale[1]))
- y /= scale[1];
- if (!MT_fuzzyZero(scale[2]))
- z /= scale[2];
- ori.setColumn(0, x);
- ori.setColumn(1, y);
- ori.setColumn(2, z);
- parentinversenode->SetLocalOrientation(ori);
- parentinversenode->SetLocalScale(scale);
+ parentinversenode->SetLocalOrientation(parinvtrans.getBasis());
parentinversenode->AddChild(gameobj->GetSGNode());
}
@@ -2234,7 +2158,8 @@ void BL_ConvertBlenderObjects(struct Main* maggie,
//tf.Add(gameobj->GetSGNode());
gameobj->NodeUpdateGS(0,true);
- gameobj->AddMeshUser();
+ gameobj->Bucketize();
+
}
else
{
@@ -2276,16 +2201,16 @@ void BL_ConvertBlenderObjects(struct Main* maggie,
for(oit=allblobj.begin(); oit!=allblobj.end(); oit++)
{
Object* blenderobj = *oit;
- if (blenderobj->type==OB_MESH) {
+ if (blenderobj->type==OB_MESH){
Mesh *me = (Mesh*)blenderobj->data;
if (me->dvert){
- BL_DeformableGameObject *obj = (BL_DeformableGameObject*)converter->FindGameObject(blenderobj);
+ KX_GameObject *obj = converter->FindGameObject(blenderobj);
if (obj && blenderobj->parent && blenderobj->parent->type==OB_ARMATURE && blenderobj->partype==PARSKEL){
KX_GameObject *par = converter->FindGameObject(blenderobj->parent);
- if (par && obj->GetDeformer())
- ((BL_SkinDeformer*)obj->GetDeformer())->SetArmature((BL_ArmatureObject*) par);
+ if (par)
+ ((BL_SkinDeformer*)(((BL_DeformableGameObject*)obj)->m_pDeformer))->SetArmature((BL_ArmatureObject*) par);
}
}
}
@@ -2299,41 +2224,6 @@ void BL_ConvertBlenderObjects(struct Main* maggie,
{
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 = (CListValue*)childobj->PyGetChildrenRecursive(childobj);
- childrenlist->Add(childobj->AddRef());
- for ( i=0;i<childrenlist->GetCount();i++)
- {
- KX_GameObject* obj = static_cast<KX_GameObject*>(childrenlist->GetValue(i));
- if (templist->RemoveValue(obj))
- obj->Release();
- if (sumolist->RemoveValue(obj))
- obj->Release();
- if (logicbrick_conversionlist->RemoveValue(obj))
- obj->Release();
- }
- childrenlist->Release();
- // now destroy recursively
- kxscene->RemoveObject(childobj);
- continue;
- }
-
switch (blenderchild->partype)
{
case PARVERT1:
@@ -2354,11 +2244,8 @@ void BL_ConvertBlenderObjects(struct Main* maggie,
{
// parent this to a bone
Bone *parent_bone = get_named_bone(get_armature(blenderchild->parent), blenderchild->parsubstr);
-
- if(parent_bone) {
- KX_BoneParentRelation *bone_parent_relation = KX_BoneParentRelation::New(parent_bone);
- pcit->m_gamechildnode->SetParentRelation(bone_parent_relation);
- }
+ KX_BoneParentRelation *bone_parent_relation = KX_BoneParentRelation::New(parent_bone);
+ pcit->m_gamechildnode->SetParentRelation(bone_parent_relation);
break;
}
@@ -2373,7 +2260,12 @@ void BL_ConvertBlenderObjects(struct Main* maggie,
break;
}
- parentobj-> GetSGNode()->AddChild(pcit->m_gamechildnode);
+ struct Object* blenderparent = blenderchild->parent;
+ KX_GameObject* parentobj = converter->FindGameObject(blenderparent);
+ if (parentobj)
+ {
+ parentobj-> GetSGNode()->AddChild(pcit->m_gamechildnode);
+ }
}
vec_parent_child.clear();
@@ -2478,7 +2370,7 @@ void BL_ConvertBlenderObjects(struct Main* maggie,
(float)dat->pivY,(float)dat->pivZ,
(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(),dat->flag);
+ (float)axis2.x(),(float)axis2.y(),(float)axis2.z());
if (constraintId)
{
//if it is a generic 6DOF constraint, set all the limits accordingly
@@ -2558,7 +2450,7 @@ void BL_ConvertBlenderObjects(struct Main* maggie,
struct Object* blenderobj = converter->FindBlenderObject(gameobj);
int layerMask = (groupobj.find(blenderobj) == groupobj.end()) ? activeLayerBitInfo : 0;
bool isInActiveLayer = (blenderobj->lay & layerMask)!=0;
- BL_ConvertSensors(blenderobj,gameobj,logicmgr,kxscene,ketsjiEngine,keydev,executePriority,layerMask,isInActiveLayer,canvas,converter);
+ BL_ConvertSensors(blenderobj,gameobj,logicmgr,kxscene,keydev,executePriority,layerMask,isInActiveLayer,canvas,converter);
// set the init state to all objects
gameobj->SetInitState((blenderobj->init_state)?blenderobj->init_state:blenderobj->state);
}
@@ -2590,10 +2482,5 @@ void BL_ConvertBlenderObjects(struct Main* maggie,
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_DeformableGameObject.cpp b/source/gameengine/Converter/BL_DeformableGameObject.cpp
index e2610d2b405..d23274324ee 100644
--- a/source/gameengine/Converter/BL_DeformableGameObject.cpp
+++ b/source/gameengine/Converter/BL_DeformableGameObject.cpp
@@ -41,14 +41,12 @@ BL_DeformableGameObject::~BL_DeformableGameObject()
delete m_pDeformer; // __NLA : Temporary until we decide where to put this
}
-void BL_DeformableGameObject::ProcessReplica(KX_GameObject* replica)
+void BL_DeformableGameObject::ProcessReplica(KX_GameObject* replica)
{
- BL_MeshDeformer *deformer;
KX_GameObject::ProcessReplica(replica);
- if (m_pDeformer) {
- deformer = (BL_MeshDeformer*)m_pDeformer->GetReplica(replica);
- ((BL_DeformableGameObject*)replica)->m_pDeformer = deformer;
+ if (m_pDeformer){
+ ((BL_DeformableGameObject*)replica)->m_pDeformer = m_pDeformer->GetReplica();
}
}
diff --git a/source/gameengine/Converter/BL_DeformableGameObject.h b/source/gameengine/Converter/BL_DeformableGameObject.h
index 126a1fcb1e7..315ad18c42c 100644
--- a/source/gameengine/Converter/BL_DeformableGameObject.h
+++ b/source/gameengine/Converter/BL_DeformableGameObject.h
@@ -83,21 +83,9 @@ public:
return (m_pDeformer) ? ((BL_MeshDeformer*)m_pDeformer)->GetMesh()->key : NULL;
}
- virtual void SetDeformer(class RAS_Deformer* deformer)
- {
- m_pDeformer = deformer;
- }
- virtual class RAS_Deformer* GetDeformer()
- {
- return m_pDeformer;
- }
-
public:
-
+ RAS_Deformer *m_pDeformer;
protected:
-
- RAS_Deformer *m_pDeformer;
-
class BL_ShapeActionActuator *m_activeAct;
double m_lastframe;
Object* m_blendobj;
diff --git a/source/gameengine/Converter/BL_MeshDeformer.cpp b/source/gameengine/Converter/BL_MeshDeformer.cpp
index fa3b8185fe2..39d66a90e92 100644
--- a/source/gameengine/Converter/BL_MeshDeformer.cpp
+++ b/source/gameengine/Converter/BL_MeshDeformer.cpp
@@ -50,26 +50,26 @@
bool BL_MeshDeformer::Apply(RAS_IPolyMaterial*)
{
- size_t i;
+ size_t i, j;
float *co;
// 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();
+ for(RAS_MaterialBucket::Set::iterator mit = m_pMeshObject->GetFirstMaterial();
mit != m_pMeshObject->GetLastMaterial(); ++ mit) {
- if(!mit->m_slots[(void*)m_gameobj])
- continue;
+ RAS_IPolyMaterial *mat = (*mit)->GetPolyMaterial();
- RAS_MeshSlot *slot = *mit->m_slots[(void*)m_gameobj];
- RAS_MeshSlot::iterator it;
+ vecVertexArray& vertexarrays = m_pMeshObject->GetVertexCache(mat);
+
+ // For each array
+ for (i=0; i<vertexarrays.size(); i++){
+ KX_VertexArray& vertexarray = (*vertexarrays[i]);
- // 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];
+ for (j=0; j<vertexarray.size(); j++){
+ RAS_TexVert& v = vertexarray[j];
co = m_bmesh->mvert[v.getOrigIndex()].co;
v.SetXYZ(MT_Point3(co));
}
@@ -90,17 +90,7 @@ BL_MeshDeformer::~BL_MeshDeformer()
delete [] m_transverts;
if (m_transnors)
delete [] m_transnors;
-}
-
-void BL_MeshDeformer::Relink(GEN_Map<class GEN_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!
@@ -111,41 +101,41 @@ void BL_MeshDeformer::RecalcNormals()
* 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;
+ size_t i, j;
/* 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();
+ for(RAS_MaterialBucket::Set::iterator mit = m_pMeshObject->GetFirstMaterial();
mit != m_pMeshObject->GetLastMaterial(); ++ mit) {
- if(!mit->m_slots[(void*)m_gameobj])
- continue;
+ RAS_IPolyMaterial *mat = (*mit)->GetPolyMaterial();
- RAS_MeshSlot *slot = *mit->m_slots[(void*)m_gameobj];
+ const vecIndexArrays& indexarrays = m_pMeshObject->GetIndexCache(mat);
+ vecVertexArray& vertexarrays = m_pMeshObject->GetVertexCache(mat);
- for(slot->begin(it); !slot->end(it); slot->next(it)) {
- int nvert = (int)it.array->m_type;
+ for (i=0; i<indexarrays.size(); i++) {
+ KX_VertexArray& vertexarray = (*vertexarrays[i]);
+ const KX_IndexArray& indexarray = (*indexarrays[i]);
+ int nvert = mat->UsesTriangles()? 3: 4;
- 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]];
+ for(j=0; j<indexarray.size(); j+=nvert) {
+ RAS_TexVert& v1 = vertexarray[indexarray[j]];
+ RAS_TexVert& v2 = vertexarray[indexarray[j+1]];
+ RAS_TexVert& v3 = vertexarray[indexarray[j+2]];
RAS_TexVert *v4 = NULL;
- const float *co1 = v1.getXYZ();
- const float *co2 = v2.getXYZ();
- const float *co3 = v3.getXYZ();
+ const float *co1 = v1.getLocalXYZ();
+ const float *co2 = v2.getLocalXYZ();
+ const float *co3 = v3.getLocalXYZ();
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 = v4->getXYZ();
+ v4 = &vertexarray[indexarray[j+3]];
+ co4 = v4->getLocalXYZ();
n1[0]= co1[0]-co3[0];
n1[1]= co1[1]-co3[1];
@@ -184,7 +174,7 @@ void BL_MeshDeformer::RecalcNormals()
}
/* in case of flat - just assign, the vertices are split */
- if(v1.getFlag() & RAS_TexVert::FLAT) {
+ if(v1.getFlag() & TV_CALCFACENORMAL) {
v1.SetNormal(fnor);
v2.SetNormal(fnor);
v3.SetNormal(fnor);
@@ -196,18 +186,19 @@ void BL_MeshDeformer::RecalcNormals()
}
/* assign smooth vertex normals */
- for(mit = m_pMeshObject->GetFirstMaterial();
+ for(RAS_MaterialBucket::Set::iterator mit = m_pMeshObject->GetFirstMaterial();
mit != m_pMeshObject->GetLastMaterial(); ++ mit) {
- if(!mit->m_slots[(void*)m_gameobj])
- continue;
+ RAS_IPolyMaterial *mat = (*mit)->GetPolyMaterial();
- RAS_MeshSlot *slot = *mit->m_slots[(void*)m_gameobj];
+ vecVertexArray& vertexarrays = m_pMeshObject->GetVertexCache(mat);
- for(slot->begin(it); !slot->end(it); slot->next(it)) {
- for(i=it.startvertex; i<it.endvertex; i++) {
- RAS_TexVert& v = it.vertex[i];
+ for (i=0; i<vertexarrays.size(); i++) {
+ KX_VertexArray& vertexarray = (*vertexarrays[i]);
+
+ for(j=0; j<vertexarray.size(); j++) {
+ RAS_TexVert& v = vertexarray[j];
- if(!(v.getFlag() & RAS_TexVert::FLAT))
+ if(!(v.getFlag() & TV_CALCFACENORMAL))
v.SetNormal(m_transnors[v.getOrigIndex()]); //.safe_normalized()
}
}
@@ -228,4 +219,4 @@ void BL_MeshDeformer::VerifyStorage()
m_tvtot = m_bmesh->totvert;
}
}
-
+
diff --git a/source/gameengine/Converter/BL_MeshDeformer.h b/source/gameengine/Converter/BL_MeshDeformer.h
index 8de59c1cdf3..e9f7f0b192f 100644
--- a/source/gameengine/Converter/BL_MeshDeformer.h
+++ b/source/gameengine/Converter/BL_MeshDeformer.h
@@ -47,7 +47,7 @@ class BL_MeshDeformer : public RAS_Deformer
public:
void VerifyStorage();
void RecalcNormals();
- virtual void Relink(GEN_Map<class GEN_HashedPtr, void*>*map);
+ virtual void Relink(GEN_Map<class GEN_HashedPtr, void*>*map){};
BL_MeshDeformer(BL_DeformableGameObject *gameobj,
struct Object* obj,
class BL_SkinMeshObject *meshobj ):
@@ -64,10 +64,9 @@ public:
virtual void SetSimulatedTime(double time){};
virtual bool Apply(class RAS_IPolyMaterial *mat);
virtual bool Update(void){ return false; };
- virtual RAS_Deformer* GetReplica(class KX_GameObject* replica){return NULL;};
+ virtual RAS_Deformer* GetReplica(){return NULL;};
struct Mesh* GetMesh() { return m_bmesh; };
// virtual void InitDeform(double time){};
-
protected:
class BL_SkinMeshObject* m_pMeshObject;
struct Mesh* m_bmesh;
diff --git a/source/gameengine/Converter/BL_ShapeActionActuator.cpp b/source/gameengine/Converter/BL_ShapeActionActuator.cpp
index 46f3141be29..242d648b062 100644
--- a/source/gameengine/Converter/BL_ShapeActionActuator.cpp
+++ b/source/gameengine/Converter/BL_ShapeActionActuator.cpp
@@ -49,8 +49,6 @@
#include "BLI_arithb.h"
#include "MT_Matrix4x4.h"
#include "BKE_utildefines.h"
-#include "FloatValue.h"
-#include "PyObjectPlus.h"
#ifdef HAVE_CONFIG_H
#include <config.h>
@@ -136,6 +134,7 @@ void BL_ShapeActionActuator::BlendShape(Key* key, float srcweight)
{
vector<float>::const_iterator it;
float dstweight;
+ int i;
KeyBlock *kb;
dstweight = 1.0F - srcweight;
@@ -156,8 +155,6 @@ bool BL_ShapeActionActuator::Update(double curtime, bool frame)
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 !
@@ -343,18 +340,6 @@ bool BL_ShapeActionActuator::Update(double curtime, bool frame)
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;
@@ -448,26 +433,24 @@ PyParentObject BL_ShapeActionActuator::Parents[] = {
};
PyMethodDef BL_ShapeActionActuator::Methods[] = {
- {"setAction", (PyCFunction) BL_ShapeActionActuator::sPySetAction, METH_VARARGS, (PY_METHODCHAR)SetAction_doc},
- {"setStart", (PyCFunction) BL_ShapeActionActuator::sPySetStart, METH_VARARGS, (PY_METHODCHAR)SetStart_doc},
- {"setEnd", (PyCFunction) BL_ShapeActionActuator::sPySetEnd, METH_VARARGS, (PY_METHODCHAR)SetEnd_doc},
- {"setBlendin", (PyCFunction) BL_ShapeActionActuator::sPySetBlendin, METH_VARARGS, (PY_METHODCHAR)SetBlendin_doc},
- {"setPriority", (PyCFunction) BL_ShapeActionActuator::sPySetPriority, METH_VARARGS, (PY_METHODCHAR)SetPriority_doc},
- {"setFrame", (PyCFunction) BL_ShapeActionActuator::sPySetFrame, METH_VARARGS, (PY_METHODCHAR)SetFrame_doc},
- {"setProperty", (PyCFunction) BL_ShapeActionActuator::sPySetProperty, METH_VARARGS, (PY_METHODCHAR)SetProperty_doc},
- {"setFrameProperty", (PyCFunction) BL_ShapeActionActuator::sPySetFrameProperty, METH_VARARGS, (PY_METHODCHAR)SetFrameProperty_doc},
- {"setBlendtime", (PyCFunction) BL_ShapeActionActuator::sPySetBlendtime, METH_VARARGS, (PY_METHODCHAR)SetBlendtime_doc},
-
- {"getAction", (PyCFunction) BL_ShapeActionActuator::sPyGetAction, METH_NOARGS, (PY_METHODCHAR)GetAction_doc},
- {"getStart", (PyCFunction) BL_ShapeActionActuator::sPyGetStart, METH_NOARGS, (PY_METHODCHAR)GetStart_doc},
- {"getEnd", (PyCFunction) BL_ShapeActionActuator::sPyGetEnd, METH_NOARGS, (PY_METHODCHAR)GetEnd_doc},
- {"getBlendin", (PyCFunction) BL_ShapeActionActuator::sPyGetBlendin, METH_NOARGS, (PY_METHODCHAR)GetBlendin_doc},
- {"getPriority", (PyCFunction) BL_ShapeActionActuator::sPyGetPriority, METH_NOARGS, (PY_METHODCHAR)GetPriority_doc},
- {"getFrame", (PyCFunction) BL_ShapeActionActuator::sPyGetFrame, METH_NOARGS, (PY_METHODCHAR)GetFrame_doc},
- {"getProperty", (PyCFunction) BL_ShapeActionActuator::sPyGetProperty, METH_NOARGS, (PY_METHODCHAR)GetProperty_doc},
- {"getFrameProperty", (PyCFunction) BL_ShapeActionActuator::sPyGetFrameProperty, METH_NOARGS, (PY_METHODCHAR)GetFrameProperty_doc},
- {"getType", (PyCFunction) BL_ShapeActionActuator::sPyGetType, METH_NOARGS, (PY_METHODCHAR)GetType_doc},
- {"setType", (PyCFunction) BL_ShapeActionActuator::sPySetType, METH_NOARGS, (PY_METHODCHAR)SetType_doc},
+ {"setAction", (PyCFunction) BL_ShapeActionActuator::sPySetAction, METH_VARARGS, SetAction_doc},
+ {"setStart", (PyCFunction) BL_ShapeActionActuator::sPySetStart, METH_VARARGS, SetStart_doc},
+ {"setEnd", (PyCFunction) BL_ShapeActionActuator::sPySetEnd, METH_VARARGS, SetEnd_doc},
+ {"setBlendin", (PyCFunction) BL_ShapeActionActuator::sPySetBlendin, METH_VARARGS, SetBlendin_doc},
+ {"setPriority", (PyCFunction) BL_ShapeActionActuator::sPySetPriority, METH_VARARGS, SetPriority_doc},
+ {"setFrame", (PyCFunction) BL_ShapeActionActuator::sPySetFrame, METH_VARARGS, SetFrame_doc},
+ {"setProperty", (PyCFunction) BL_ShapeActionActuator::sPySetProperty, METH_VARARGS, SetProperty_doc},
+ {"setBlendtime", (PyCFunction) BL_ShapeActionActuator::sPySetBlendtime, METH_VARARGS, SetBlendtime_doc},
+
+ {"getAction", (PyCFunction) BL_ShapeActionActuator::sPyGetAction, METH_NOARGS, GetAction_doc},
+ {"getStart", (PyCFunction) BL_ShapeActionActuator::sPyGetStart, METH_NOARGS, GetStart_doc},
+ {"getEnd", (PyCFunction) BL_ShapeActionActuator::sPyGetEnd, METH_NOARGS, GetEnd_doc},
+ {"getBlendin", (PyCFunction) BL_ShapeActionActuator::sPyGetBlendin, METH_NOARGS, GetBlendin_doc},
+ {"getPriority", (PyCFunction) BL_ShapeActionActuator::sPyGetPriority, METH_NOARGS, GetPriority_doc},
+ {"getFrame", (PyCFunction) BL_ShapeActionActuator::sPyGetFrame, METH_NOARGS, GetFrame_doc},
+ {"getProperty", (PyCFunction) BL_ShapeActionActuator::sPyGetProperty, METH_NOARGS, GetProperty_doc},
+ {"getType", (PyCFunction) BL_ShapeActionActuator::sPyGetType, METH_NOARGS, GetType_doc},
+ {"setType", (PyCFunction) BL_ShapeActionActuator::sPySetType, METH_NOARGS, SetType_doc},
{NULL,NULL} //Sentinel
};
@@ -476,19 +459,26 @@ PyObject* BL_ShapeActionActuator::_getattr(const STR_String& attr) {
}
/* setStart */
-const char BL_ShapeActionActuator::GetAction_doc[] =
+char BL_ShapeActionActuator::GetAction_doc[] =
"getAction()\n"
"\tReturns a string containing the name of the current action.\n";
PyObject* BL_ShapeActionActuator::PyGetAction(PyObject* self) {
+ PyObject *result;
+
if (m_action){
- return PyString_FromString(m_action->id.name+2);
+ result = Py_BuildValue("s", m_action->id.name+2);
+ }
+ else{
+ Py_INCREF(Py_None);
+ result = Py_None;
}
- Py_RETURN_NONE;
+
+ return result;
}
/* getProperty */
-const char BL_ShapeActionActuator::GetProperty_doc[] =
+char BL_ShapeActionActuator::GetProperty_doc[] =
"getProperty()\n"
"\tReturns the name of the property to be used in FromProp mode.\n";
@@ -501,7 +491,7 @@ PyObject* BL_ShapeActionActuator::PyGetProperty(PyObject* self) {
}
/* getFrame */
-const char BL_ShapeActionActuator::GetFrame_doc[] =
+char BL_ShapeActionActuator::GetFrame_doc[] =
"getFrame()\n"
"\tReturns the current frame number.\n";
@@ -514,7 +504,7 @@ PyObject* BL_ShapeActionActuator::PyGetFrame(PyObject* self) {
}
/* getEnd */
-const char BL_ShapeActionActuator::GetEnd_doc[] =
+char BL_ShapeActionActuator::GetEnd_doc[] =
"getEnd()\n"
"\tReturns the last frame of the action.\n";
@@ -527,7 +517,7 @@ PyObject* BL_ShapeActionActuator::PyGetEnd(PyObject* self) {
}
/* getStart */
-const char BL_ShapeActionActuator::GetStart_doc[] =
+char BL_ShapeActionActuator::GetStart_doc[] =
"getStart()\n"
"\tReturns the starting frame of the action.\n";
@@ -540,7 +530,7 @@ PyObject* BL_ShapeActionActuator::PyGetStart(PyObject* self) {
}
/* getBlendin */
-const char BL_ShapeActionActuator::GetBlendin_doc[] =
+char BL_ShapeActionActuator::GetBlendin_doc[] =
"getBlendin()\n"
"\tReturns the number of interpolation animation frames to be\n"
"\tgenerated when this actuator is triggered.\n";
@@ -554,7 +544,7 @@ PyObject* BL_ShapeActionActuator::PyGetBlendin(PyObject* self) {
}
/* getPriority */
-const char BL_ShapeActionActuator::GetPriority_doc[] =
+char BL_ShapeActionActuator::GetPriority_doc[] =
"getPriority()\n"
"\tReturns the priority for this actuator. Actuators with lower\n"
"\tPriority numbers will override actuators with higher numbers.\n";
@@ -568,7 +558,7 @@ PyObject* BL_ShapeActionActuator::PyGetPriority(PyObject* self) {
}
/* setAction */
-const char BL_ShapeActionActuator::SetAction_doc[] =
+char BL_ShapeActionActuator::SetAction_doc[] =
"setAction(action, (reset))\n"
"\t - action : The name of the action to set as the current action.\n"
"\t Should be an action with Shape channels.\n"
@@ -601,14 +591,16 @@ PyObject* BL_ShapeActionActuator::PySetAction(PyObject* self,
}
}
else {
+ PyErr_SetString(PyExc_TypeError, "Invalid arguments");
return NULL;
}
- Py_RETURN_NONE;
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* setStart */
-const char BL_ShapeActionActuator::SetStart_doc[] =
+char BL_ShapeActionActuator::SetStart_doc[] =
"setStart(start)\n"
"\t - start : Specifies the starting frame of the animation.\n";
@@ -622,14 +614,16 @@ PyObject* BL_ShapeActionActuator::PySetStart(PyObject* self,
m_startframe = start;
}
else {
+ PyErr_SetString(PyExc_TypeError, "Invalid arguments");
return NULL;
}
- Py_RETURN_NONE;
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* setEnd */
-const char BL_ShapeActionActuator::SetEnd_doc[] =
+char BL_ShapeActionActuator::SetEnd_doc[] =
"setEnd(end)\n"
"\t - end : Specifies the ending frame of the animation.\n";
@@ -643,14 +637,16 @@ PyObject* BL_ShapeActionActuator::PySetEnd(PyObject* self,
m_endframe = end;
}
else {
+ PyErr_SetString(PyExc_TypeError, "Invalid arguments");
return NULL;
}
- Py_RETURN_NONE;
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* setBlendin */
-const char BL_ShapeActionActuator::SetBlendin_doc[] =
+char BL_ShapeActionActuator::SetBlendin_doc[] =
"setBlendin(blendin)\n"
"\t - blendin : Specifies the number of frames of animation to generate\n"
"\t when making transitions between actions.\n";
@@ -665,14 +661,16 @@ PyObject* BL_ShapeActionActuator::PySetBlendin(PyObject* self,
m_blendin = blendin;
}
else {
+ PyErr_SetString(PyExc_TypeError, "Invalid arguments");
return NULL;
}
- Py_RETURN_NONE;
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* setBlendtime */
-const char BL_ShapeActionActuator::SetBlendtime_doc[] =
+char BL_ShapeActionActuator::SetBlendtime_doc[] =
"setBlendtime(blendtime)\n"
"\t - blendtime : Allows the script to directly modify the internal timer\n"
"\t used when generating transitions between actions. This\n"
@@ -692,14 +690,16 @@ PyObject* BL_ShapeActionActuator::PySetBlendtime(PyObject* self,
m_blendframe = m_blendin;
}
else {
+ PyErr_SetString(PyExc_TypeError, "Invalid arguments");
return NULL;
}
- Py_RETURN_NONE;
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* setPriority */
-const char BL_ShapeActionActuator::SetPriority_doc[] =
+char BL_ShapeActionActuator::SetPriority_doc[] =
"setPriority(priority)\n"
"\t - priority : Specifies the new priority. Actuators will lower\n"
"\t priority numbers will override actuators with higher\n"
@@ -715,28 +715,16 @@ PyObject* BL_ShapeActionActuator::PySetPriority(PyObject* self,
m_priority = priority;
}
else {
+ PyErr_SetString(PyExc_TypeError, "Invalid arguments");
return NULL;
}
- Py_RETURN_NONE;
-}
-
-/* getProperty */
-const char BL_ShapeActionActuator::GetFrameProperty_doc[] =
-"getFrameProperty()\n"
-"\tReturns the name of the property, that is set to the current frame number.\n";
-
-PyObject* BL_ShapeActionActuator::PyGetFrameProperty(PyObject* self) {
- PyObject *result;
-
- result = Py_BuildValue("s", (const char *)m_framepropname);
-
- return result;
+ Py_INCREF(Py_None);
+ return Py_None;
}
-
/* setFrame */
-const char BL_ShapeActionActuator::SetFrame_doc[] =
+char BL_ShapeActionActuator::SetFrame_doc[] =
"setFrame(frame)\n"
"\t - frame : Specifies the new current frame for the animation\n";
@@ -754,14 +742,16 @@ PyObject* BL_ShapeActionActuator::PySetFrame(PyObject* self,
m_localtime=m_endframe;
}
else {
+ PyErr_SetString(PyExc_TypeError, "Invalid arguments");
return NULL;
}
- Py_RETURN_NONE;
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* setProperty */
-const char BL_ShapeActionActuator::SetProperty_doc[] =
+char BL_ShapeActionActuator::SetProperty_doc[] =
"setProperty(prop)\n"
"\t - prop : A string specifying the property name to be used in\n"
"\t FromProp playback mode.\n";
@@ -776,35 +766,16 @@ PyObject* BL_ShapeActionActuator::PySetProperty(PyObject* self,
m_propname = string;
}
else {
+ PyErr_SetString(PyExc_TypeError, "Invalid arguments");
return NULL;
}
- Py_RETURN_NONE;
-}
-
-/* setFrameProperty */
-const char BL_ShapeActionActuator::SetFrameProperty_doc[] =
-"setFrameProperty(prop)\n"
-"\t - prop : A string specifying the property of the frame set up update.\n";
-
-PyObject* BL_ShapeActionActuator::PySetFrameProperty(PyObject* self,
- PyObject* args,
- PyObject* kwds) {
- char *string;
-
- if (PyArg_ParseTuple(args,"s",&string))
- {
- m_framepropname = string;
- }
- else {
- return NULL;
- }
-
- Py_RETURN_NONE;
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* getType */
-const char BL_ShapeActionActuator::GetType_doc[] =
+char BL_ShapeActionActuator::GetType_doc[] =
"getType()\n"
"\tReturns the operation mode of the actuator.\n";
PyObject* BL_ShapeActionActuator::PyGetType(PyObject* self) {
@@ -812,7 +783,7 @@ PyObject* BL_ShapeActionActuator::PyGetType(PyObject* self) {
}
/* setType */
-const char BL_ShapeActionActuator::SetType_doc[] =
+char BL_ShapeActionActuator::SetType_doc[] =
"setType(mode)\n"
"\t - mode: Play (0), Flipper (2), LoopStop (3), LoopEnd (4) or Property (6)\n"
"\tSet the operation mode of the actuator.\n";
@@ -822,6 +793,7 @@ PyObject* BL_ShapeActionActuator::PySetType(PyObject* self,
short typeArg;
if (!PyArg_ParseTuple(args, "h", &typeArg)) {
+ PyErr_SetString(PyExc_TypeError, "Invalid arguments");
return NULL;
}
diff --git a/source/gameengine/Converter/BL_ShapeActionActuator.h b/source/gameengine/Converter/BL_ShapeActionActuator.h
index 30b2d41fc67..a9b9ad8fa86 100644
--- a/source/gameengine/Converter/BL_ShapeActionActuator.h
+++ b/source/gameengine/Converter/BL_ShapeActionActuator.h
@@ -42,7 +42,6 @@ public:
Py_Header;
BL_ShapeActionActuator(SCA_IObject* gameobj,
const STR_String& propname,
- const STR_String& framepropname,
float starttime,
float endtime,
struct bAction *action,
@@ -67,7 +66,6 @@ public:
m_playtype(playtype),
m_priority(priority),
m_action(action),
- m_framepropname(framepropname),
m_propname(propname)
{
};
@@ -86,7 +84,6 @@ public:
KX_PYMETHOD_DOC(BL_ShapeActionActuator,SetEnd);
KX_PYMETHOD_DOC(BL_ShapeActionActuator,SetFrame);
KX_PYMETHOD_DOC(BL_ShapeActionActuator,SetProperty);
- KX_PYMETHOD_DOC(BL_ShapeActionActuator,SetFrameProperty);
KX_PYMETHOD_DOC(BL_ShapeActionActuator,SetBlendtime);
KX_PYMETHOD_DOC(BL_ShapeActionActuator,SetChannel);
@@ -97,7 +94,6 @@ public:
KX_PYMETHOD_DOC_NOARGS(BL_ShapeActionActuator,GetEnd);
KX_PYMETHOD_DOC_NOARGS(BL_ShapeActionActuator,GetFrame);
KX_PYMETHOD_DOC_NOARGS(BL_ShapeActionActuator,GetProperty);
- KX_PYMETHOD_DOC_NOARGS(BL_ShapeActionActuator,GetFrameProperty);
// KX_PYMETHOD(BL_ActionActuator,GetChannel);
KX_PYMETHOD_DOC_NOARGS(BL_ShapeActionActuator,GetType);
KX_PYMETHOD_DOC(BL_ShapeActionActuator,SetType);
@@ -130,7 +126,6 @@ protected:
short m_priority;
struct bAction *m_action;
STR_String m_propname;
- STR_String m_framepropname;
vector<float> m_blendshape;
};
diff --git a/source/gameengine/Converter/BL_ShapeDeformer.cpp b/source/gameengine/Converter/BL_ShapeDeformer.cpp
index fc6498579ad..b2e54539b19 100644
--- a/source/gameengine/Converter/BL_ShapeDeformer.cpp
+++ b/source/gameengine/Converter/BL_ShapeDeformer.cpp
@@ -68,7 +68,7 @@ BL_ShapeDeformer::~BL_ShapeDeformer()
{
};
-RAS_Deformer *BL_ShapeDeformer::GetReplica(class KX_GameObject* replica)
+RAS_Deformer *BL_ShapeDeformer::GetReplica()
{
BL_ShapeDeformer *result;
@@ -109,10 +109,12 @@ bool BL_ShapeDeformer::ExecuteShapeDrivers(void)
vector<IpoCurve*>::iterator it;
void *poin;
int type;
-
// the shape drivers use the bone matrix as input. Must
// update the matrix now
+ Object* par_arma = m_armobj->GetArmatureObject();
m_armobj->ApplyPose();
+ where_is_pose( par_arma );
+ PoseApplied(true);
for (it=m_shapeDrivers.begin(); it!=m_shapeDrivers.end(); it++) {
// no need to set a specific time: this curve has a driver
@@ -122,10 +124,7 @@ bool BL_ShapeDeformer::ExecuteShapeDrivers(void)
if (poin)
write_ipo_poin(poin, type, icu->curval);
}
-
ForceUpdate();
- m_armobj->RestorePose();
-
return true;
}
return false;
diff --git a/source/gameengine/Converter/BL_ShapeDeformer.h b/source/gameengine/Converter/BL_ShapeDeformer.h
index 90b9f5caea1..5f0188e3a42 100644
--- a/source/gameengine/Converter/BL_ShapeDeformer.h
+++ b/source/gameengine/Converter/BL_ShapeDeformer.h
@@ -43,6 +43,17 @@ struct IpoCurve;
class BL_ShapeDeformer : public BL_SkinDeformer
{
public:
+ virtual void Relink(GEN_Map<class GEN_HashedPtr, void*>*map)
+ {
+ void **h_obj = (*map)[m_gameobj];
+ if (h_obj){
+ m_gameobj = (BL_DeformableGameObject*)(*h_obj);
+ }
+ else
+ m_gameobj=NULL;
+ // relink the underlying skin deformer
+ BL_SkinDeformer::Relink(map);
+ };
BL_ShapeDeformer(BL_DeformableGameObject *gameobj,
Object *bmeshobj,
BL_SkinMeshObject *mesh)
@@ -66,7 +77,7 @@ public:
};
virtual void ProcessReplica();
- virtual RAS_Deformer *GetReplica(class KX_GameObject* replica);
+ virtual RAS_Deformer *GetReplica();
virtual ~BL_ShapeDeformer();
bool Update (void);
diff --git a/source/gameengine/Converter/BL_SkinDeformer.cpp b/source/gameengine/Converter/BL_SkinDeformer.cpp
index d8563763954..f96c40c098f 100644
--- a/source/gameengine/Converter/BL_SkinDeformer.cpp
+++ b/source/gameengine/Converter/BL_SkinDeformer.cpp
@@ -99,26 +99,9 @@ BL_SkinDeformer::~BL_SkinDeformer()
m_armobj->Release();
}
-void BL_SkinDeformer::Relink(GEN_Map<class GEN_HashedPtr, void*>*map)
-{
- if (m_armobj) {
- void **h_obj = (*map)[m_armobj];
-
- if (h_obj)
- SetArmature( (BL_ArmatureObject*)(*h_obj) );
- else
- m_armobj=NULL;
- }
-
- BL_MeshDeformer::Relink(map);
-}
-
bool BL_SkinDeformer::Apply(RAS_IPolyMaterial *mat)
{
- RAS_MeshSlot::iterator it;
- RAS_MeshMaterial *mmat;
- RAS_MeshSlot *slot;
- size_t i;
+ size_t i, j;
// update the vertex in m_transverts
Update();
@@ -127,18 +110,16 @@ bool BL_SkinDeformer::Apply(RAS_IPolyMaterial *mat)
// 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(mat);
- if(!mmat->m_slots[(void*)m_gameobj])
- return true;
+ vecVertexArray& vertexarrays = m_pMeshObject->GetVertexCache(mat);
- slot = *mmat->m_slots[(void*)m_gameobj];
+ // For each array
+ for (i=0; i<vertexarrays.size(); i++) {
+ KX_VertexArray& vertexarray = (*vertexarrays[i]);
- // for each array
- for(slot->begin(it); !slot->end(it); slot->next(it)) {
- // for each vertex
+ // 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];
+ for (j=0; j<vertexarray.size(); j++) {
+ RAS_TexVert& v = vertexarray[j];
v.SetXYZ(m_transverts[v.getOrigIndex()]);
}
}
@@ -146,7 +127,7 @@ bool BL_SkinDeformer::Apply(RAS_IPolyMaterial *mat)
return true;
}
-RAS_Deformer *BL_SkinDeformer::GetReplica(class KX_GameObject* replica)
+RAS_Deformer *BL_SkinDeformer::GetReplica()
{
BL_SkinDeformer *result;
@@ -166,10 +147,14 @@ bool BL_SkinDeformer::Update(void)
/* See if the armature has been updated for this frame */
if (PoseUpdated()){
float obmat[4][4]; // the original object matrice
-
+
/* XXX note: where_is_pose() (from BKE_armature.h) calculates all matrices needed to start deforming */
/* but it requires the blender object pointer... */
Object* par_arma = m_armobj->GetArmatureObject();
+ if (!PoseApplied()){
+ m_armobj->ApplyPose();
+ where_is_pose( par_arma );
+ }
/* store verts locally */
VerifyStorage();
@@ -178,8 +163,6 @@ bool BL_SkinDeformer::Update(void)
for (int v =0; v<m_bmesh->totvert; v++)
VECCOPY(m_transverts[v], m_bmesh->mvert[v].co);
- m_armobj->ApplyPose();
-
// save matrix first
Mat4CpyMat4(obmat, m_objMesh->obmat);
// set reference matrix
@@ -196,13 +179,11 @@ bool BL_SkinDeformer::Update(void)
/* Update the current frame */
m_lastArmaUpdate=m_armobj->GetLastFrame();
-
- m_armobj->RestorePose();
-
+ /* reset for next frame */
+ PoseApplied(false);
/* indicate that the m_transverts and normals are up to date */
return true;
}
-
return false;
}
diff --git a/source/gameengine/Converter/BL_SkinDeformer.h b/source/gameengine/Converter/BL_SkinDeformer.h
index f87860021c6..d3fc5ae2a81 100644
--- a/source/gameengine/Converter/BL_SkinDeformer.h
+++ b/source/gameengine/Converter/BL_SkinDeformer.h
@@ -50,7 +50,17 @@ class BL_SkinDeformer : public BL_MeshDeformer
{
public:
// void SetArmatureController (BL_ArmatureController *cont);
- virtual void Relink(GEN_Map<class GEN_HashedPtr, void*>*map);
+ virtual void Relink(GEN_Map<class GEN_HashedPtr, void*>*map)
+ {
+ if (m_armobj){
+ void **h_obj = (*map)[m_armobj];
+ if (h_obj){
+ SetArmature( (BL_ArmatureObject*)(*h_obj) );
+ }
+ else
+ m_armobj=NULL;
+ }
+ }
void SetArmature (class BL_ArmatureObject *armobj);
BL_SkinDeformer(BL_DeformableGameObject *gameobj,
@@ -67,10 +77,14 @@ public:
BL_ArmatureObject* arma = NULL);
virtual void ProcessReplica();
- virtual RAS_Deformer *GetReplica(class KX_GameObject* replica);
+ virtual RAS_Deformer *GetReplica();
virtual ~BL_SkinDeformer();
bool Update (void);
bool Apply (class RAS_IPolyMaterial *polymat);
+ bool PoseApplied()
+ { return m_poseApplied; }
+ void PoseApplied(bool applied)
+ { m_poseApplied = applied; }
bool PoseUpdated(void)
{
if (m_armobj && m_lastArmaUpdate!=m_armobj->GetLastFrame()) {
diff --git a/source/gameengine/Converter/BL_SkinMeshObject.cpp b/source/gameengine/Converter/BL_SkinMeshObject.cpp
index eb3f9d0588d..fa215df1e1c 100644
--- a/source/gameengine/Converter/BL_SkinMeshObject.cpp
+++ b/source/gameengine/Converter/BL_SkinMeshObject.cpp
@@ -28,69 +28,42 @@
* Deformer that supports armature skinning
*/
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
#ifdef WIN32
#pragma warning (disable:4786) // get rid of stupid stl-visual compiler debug warning
#endif //WIN32
-
-#include "MEM_guardedalloc.h"
-
-#include "DNA_key_types.h"
-#include "DNA_mesh_types.h"
-#include "DNA_meshdata_types.h"
-
-#include "RAS_BucketManager.h"
#include "RAS_IPolygonMaterial.h"
-
-#include "KX_GameObject.h"
-
#include "BL_SkinMeshObject.h"
#include "BL_DeformableGameObject.h"
+#include "DNA_mesh_types.h"
+#include "DNA_meshdata_types.h"
+#include "KX_GameObject.h"
+#include "RAS_BucketManager.h"
-BL_SkinMeshObject::BL_SkinMeshObject(Mesh* mesh, int lightlayer)
- : RAS_MeshObject (mesh, lightlayer)
-{
- m_bDeformed = true;
-
- 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);
- }
-}
-
-BL_SkinMeshObject::~BL_SkinMeshObject()
+//void BL_SkinMeshObject::Bucketize(double* oglmatrix,void* clientobj,bool useObjectColor,const MT_Vector4& rgbavec,RAS_BucketManager* bucketmgr)
+void BL_SkinMeshObject::Bucketize(double* oglmatrix,void* clientobj,bool useObjectColor,const MT_Vector4& rgbavec)
{
- if (m_mesh && m_mesh->key)
- {
- KeyBlock *kb;
- // remove the weight cache to avoid memory leak
- for(kb= (KeyBlock*)m_mesh->key->block.first; kb; kb= (KeyBlock*)kb->next) {
- if(kb->weights)
- MEM_freeN(kb->weights);
- kb->weights= NULL;
- }
- }
-}
-void BL_SkinMeshObject::UpdateBuckets(void* clientobj,double* oglmatrix,bool useObjectColor,const MT_Vector4& rgbavec, bool visible, bool culled)
-{
- list<RAS_MeshMaterial>::iterator it;
- list<RAS_MeshSlot*>::iterator sit;
+ KX_MeshSlot ms;
+ ms.m_clientObj = clientobj;
+ ms.m_mesh = this;
+ ms.m_OpenGLMatrix = oglmatrix;
+ ms.m_bObjectColor = useObjectColor;
+ ms.m_RGBAcolor = rgbavec;
+ ms.m_pDeformer = ((BL_DeformableGameObject*)clientobj)->m_pDeformer;
+
+ for (RAS_MaterialBucket::Set::iterator it = m_materials.begin();it!=m_materials.end();it++)
+ {
- for(it = m_materials.begin();it!=m_materials.end();++it) {
- if(!it->m_slots[clientobj])
- continue;
+ RAS_MaterialBucket* materialbucket = (*it);
- RAS_MeshSlot *slot = *it->m_slots[clientobj];
- slot->m_pDeformer = ((BL_DeformableGameObject*)clientobj)->GetDeformer();
+// KX_ArrayOptimizer* oa = GetArrayOptimizer(materialbucket->GetPolyMaterial());
+ materialbucket->SetMeshSlot(ms);
}
- RAS_MeshObject::UpdateBuckets(clientobj, oglmatrix, useObjectColor, rgbavec, visible, culled);
}
static int get_def_index(Object* ob, const char* vgroup)
@@ -101,7 +74,6 @@ static int get_def_index(Object* ob, const char* vgroup)
for (curdef = (bDeformGroup*)ob->defbase.first; curdef; curdef=(bDeformGroup*)curdef->next, index++)
if (!strcmp(curdef->name, vgroup))
return index;
-
return -1;
}
diff --git a/source/gameengine/Converter/BL_SkinMeshObject.h b/source/gameengine/Converter/BL_SkinMeshObject.h
index 8544a2b958c..c21fb64204b 100644
--- a/source/gameengine/Converter/BL_SkinMeshObject.h
+++ b/source/gameengine/Converter/BL_SkinMeshObject.h
@@ -33,27 +33,62 @@
#ifdef WIN32
#pragma warning (disable:4786) // get rid of stupid stl-visual compiler debug warning
#endif //WIN32
-
+#include "MEM_guardedalloc.h"
#include "RAS_MeshObject.h"
#include "RAS_Deformer.h"
#include "RAS_IPolygonMaterial.h"
#include "BL_MeshDeformer.h"
+#include "DNA_mesh_types.h"
+#include "DNA_key_types.h"
+#include "DNA_meshdata_types.h"
+
class BL_SkinMeshObject : public RAS_MeshObject
{
+
+// enum { BUCKET_MAX_INDICES = 16384};//2048};//8192};
+// enum { BUCKET_MAX_TRIANGLES = 4096};
+
protected:
vector<int> m_cacheWeightIndex;
public:
- BL_SkinMeshObject(Mesh* mesh, int lightlayer);
- ~BL_SkinMeshObject();
+ void Bucketize(double* oglmatrix,void* clientobj,bool useObjectColor,const MT_Vector4& rgbavec);
+// void Bucketize(double* oglmatrix,void* clientobj,bool useObjectColor,const MT_Vector4& rgbavec,class RAS_BucketManager* bucketmgr);
+
+ BL_SkinMeshObject(Mesh* mesh, int lightlayer) : RAS_MeshObject (mesh, lightlayer)
+ {
+ m_class = 1;
+ 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);
+ }
+ };
- void UpdateBuckets(void* clientobj, double* oglmatrix,
- bool useObjectColor, const MT_Vector4& rgbavec, bool visible, bool culled);
+ virtual ~BL_SkinMeshObject()
+ {
+ if (m_mesh && m_mesh->key)
+ {
+ KeyBlock *kb;
+ // remove the weight cache to avoid memory leak
+ for(kb= (KeyBlock*)m_mesh->key->block.first; kb; kb= (KeyBlock*)kb->next) {
+ if(kb->weights)
+ MEM_freeN(kb->weights);
+ kb->weights= NULL;
+ }
+ }
+ };
// for shape keys,
void CheckWeightCache(struct Object* obj);
+
};
#endif
diff --git a/source/gameengine/Converter/CMakeLists.txt b/source/gameengine/Converter/CMakeLists.txt
index 217bdb30907..adb7304b10e 100644
--- a/source/gameengine/Converter/CMakeLists.txt
+++ b/source/gameengine/Converter/CMakeLists.txt
@@ -64,7 +64,6 @@ SET(INC
../../../source/gameengine/Network/LoopBackNetwork
../../../source/blender/misc
../../../source/blender/blenloader
- ../../../source/blender/gpu
../../../extern/bullet2/src
../../../extern/solid
${PYTHON_INC}
diff --git a/source/gameengine/Converter/KX_BlenderScalarInterpolator.cpp b/source/gameengine/Converter/KX_BlenderScalarInterpolator.cpp
index 4d79febb7b4..f58d60b026a 100644
--- a/source/gameengine/Converter/KX_BlenderScalarInterpolator.cpp
+++ b/source/gameengine/Converter/KX_BlenderScalarInterpolator.cpp
@@ -28,10 +28,13 @@
#include "KX_BlenderScalarInterpolator.h"
-extern "C" {
-#include "DNA_ipo_types.h"
-#include "BKE_ipo.h"
-}
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+extern "C" int IPO_GetChannels(struct Ipo *ipo, short *channels);
+extern "C" float IPO_GetFloatValue(struct Ipo *ipo, /*IPO_Channel*/ short channel, float ctime);
+
static const int BL_MAX_CHANNELS = 32;
@@ -39,7 +42,7 @@ float BL_ScalarInterpolator::GetValue(float currentTime) const {
return IPO_GetFloatValue(m_blender_ipo, m_channel, currentTime);
}
-
+typedef short IPO_Channel;
BL_InterpolatorList::BL_InterpolatorList(struct Ipo *ipo) {
IPO_Channel channels[BL_MAX_CHANNELS];
diff --git a/source/gameengine/Converter/KX_BlenderSceneConverter.cpp b/source/gameengine/Converter/KX_BlenderSceneConverter.cpp
index 7eec93dc402..de91bce2ab1 100644
--- a/source/gameengine/Converter/KX_BlenderSceneConverter.cpp
+++ b/source/gameengine/Converter/KX_BlenderSceneConverter.cpp
@@ -184,21 +184,20 @@ bool KX_BlenderSceneConverter::TryAndLoadNewFile()
return result;
}
-Scene *KX_BlenderSceneConverter::GetBlenderSceneForName(const STR_String& name)
-{
- Scene *sce;
+
/**
* Find the specified scene by name, or the first
* scene if nothing matches (shouldn't happen).
*/
+static struct Scene *GetSceneForName2(struct Main *maggie, const STR_String& scenename) {
+ Scene *sce;
- for (sce= (Scene*) m_maggie->scene.first; sce; sce= (Scene*) sce->id.next)
- if (name == (sce->id.name+2))
+ for (sce= (Scene*) maggie->scene.first; sce; sce= (Scene*) sce->id.next)
+ if (scenename == (sce->id.name+2))
return sce;
- return (Scene*)m_maggie->scene.first;
-
+ return (Scene*) maggie->scene.first;
}
#include "KX_PythonInit.h"
@@ -246,11 +245,6 @@ struct BlenderDebugDraw : public btIDebugDraw
{
return m_debugMode;
}
- ///todo: find out if Blender can do this
- virtual void draw3dText(const btVector3& location,const char* textString)
- {
-
- }
};
@@ -264,7 +258,7 @@ void KX_BlenderSceneConverter::ConvertScene(const STR_String& scenename,
class RAS_ICanvas* canvas)
{
//find out which physics engine
- Scene *blenderscene = GetBlenderSceneForName(scenename);
+ Scene *blenderscene = GetSceneForName2(m_maggie, scenename);
e_PhysicsEngine physics_engine = UseBullet;
// hook for registration function during conversion.
@@ -501,17 +495,7 @@ void KX_BlenderSceneConverter::RegisterGameObject(
void KX_BlenderSceneConverter::UnregisterGameObject(
KX_GameObject *gameobject)
{
- CHashedPtr gptr(gameobject);
- struct Object **bobp= m_map_gameobject_to_blender[gptr];
- 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);
- m_map_gameobject_to_blender.remove(gptr);
- }
+ m_map_gameobject_to_blender.remove(CHashedPtr(gameobject));
}
@@ -660,13 +644,13 @@ extern "C"
{
Ipo *add_ipo( char *name, int idcode );
char *getIpoCurveName( IpoCurve * icu );
- struct IpoCurve *verify_ipocurve(struct ID *, short, char *, char *, char *, int, short);
+ struct IpoCurve *verify_ipocurve(struct ID *, short, char *, char *, char *, int);
void testhandles_ipocurve(struct IpoCurve *icu);
- void insert_vert_icu(struct IpoCurve *, float, float, short);
void Mat3ToEul(float tmat[][3], float *eul);
+
}
-IpoCurve* findIpoCurve(IpoCurve* first, const char* searchName)
+IpoCurve* findIpoCurve(IpoCurve* first,char* searchName)
{
IpoCurve* icu1;
for( icu1 = first; icu1; icu1 = icu1->next )
@@ -834,7 +818,7 @@ void KX_BlenderSceneConverter::WritePhysicsObjectToAnimationIpo(int frameNumber)
KX_GameObject* gameObj = (KX_GameObject*)parentList->GetValue(g);
if (gameObj->IsDynamic())
{
- //KX_IPhysicsController* physCtrl = gameObj->GetPhysicsController();
+ KX_IPhysicsController* physCtrl = gameObj->GetPhysicsController();
Object* blenderObject = FindBlenderObject(gameObj);
if (blenderObject)
@@ -862,7 +846,7 @@ void KX_BlenderSceneConverter::WritePhysicsObjectToAnimationIpo(int frameNumber)
- //const MT_Vector3& scale = gameObj->NodeGetWorldScaling();
+ const MT_Vector3& scale = gameObj->NodeGetWorldScaling();
const MT_Point3& position = gameObj->NodeGetWorldPosition();
Ipo* ipo = blenderObject->ipo;
@@ -873,27 +857,27 @@ void KX_BlenderSceneConverter::WritePhysicsObjectToAnimationIpo(int frameNumber)
IpoCurve *icu1 = findIpoCurve((IpoCurve *)ipo->curve.first,"LocX");
if (!icu1)
- icu1 = verify_ipocurve(&blenderObject->id, ipo->blocktype, NULL, NULL, NULL, OB_LOC_X, 1);
+ icu1 = verify_ipocurve(&blenderObject->id, ipo->blocktype, NULL, NULL, NULL, OB_LOC_X);
icu1 = findIpoCurve((IpoCurve *)ipo->curve.first,"LocY");
if (!icu1)
- icu1 = verify_ipocurve(&blenderObject->id, ipo->blocktype, NULL, NULL, NULL, OB_LOC_Y, 1);
+ icu1 = verify_ipocurve(&blenderObject->id, ipo->blocktype, NULL, NULL, NULL, OB_LOC_Y);
icu1 = findIpoCurve((IpoCurve *)ipo->curve.first,"LocZ");
if (!icu1)
- icu1 = verify_ipocurve(&blenderObject->id, ipo->blocktype, NULL, NULL, NULL, OB_LOC_Z, 1);
+ icu1 = verify_ipocurve(&blenderObject->id, ipo->blocktype, NULL, NULL, NULL, OB_LOC_Z);
icu1 = findIpoCurve((IpoCurve *)ipo->curve.first,"RotX");
if (!icu1)
- icu1 = verify_ipocurve(&blenderObject->id, ipo->blocktype, NULL, NULL, NULL, OB_ROT_X, 1);
+ icu1 = verify_ipocurve(&blenderObject->id, ipo->blocktype, NULL, NULL, NULL, OB_ROT_X);
icu1 = findIpoCurve((IpoCurve *)ipo->curve.first,"RotY");
if (!icu1)
- icu1 = verify_ipocurve(&blenderObject->id, ipo->blocktype, NULL, NULL, NULL, OB_ROT_Y, 1);
+ icu1 = verify_ipocurve(&blenderObject->id, ipo->blocktype, NULL, NULL, NULL, OB_ROT_Y);
icu1 = findIpoCurve((IpoCurve *)ipo->curve.first,"RotZ");
if (!icu1)
- icu1 = verify_ipocurve(&blenderObject->id, ipo->blocktype, NULL, NULL, NULL, OB_ROT_Z, 1);
+ icu1 = verify_ipocurve(&blenderObject->id, ipo->blocktype, NULL, NULL, NULL, OB_ROT_Z);
@@ -990,7 +974,7 @@ void KX_BlenderSceneConverter::TestHandlesPhysicsObjectToAnimationIpo()
KX_GameObject* gameObj = (KX_GameObject*)parentList->GetValue(g);
if (gameObj->IsDynamic())
{
- //KX_IPhysicsController* physCtrl = gameObj->GetPhysicsController();
+ KX_IPhysicsController* physCtrl = gameObj->GetPhysicsController();
Object* blenderObject = FindBlenderObject(gameObj);
if (blenderObject)
@@ -1018,8 +1002,8 @@ void KX_BlenderSceneConverter::TestHandlesPhysicsObjectToAnimationIpo()
- //const MT_Vector3& scale = gameObj->NodeGetWorldScaling();
- //const MT_Point3& position = gameObj->NodeGetWorldPosition();
+ const MT_Vector3& scale = gameObj->NodeGetWorldScaling();
+ const MT_Point3& position = gameObj->NodeGetWorldPosition();
Ipo* ipo = blenderObject->ipo;
if (ipo)
@@ -1029,27 +1013,27 @@ void KX_BlenderSceneConverter::TestHandlesPhysicsObjectToAnimationIpo()
IpoCurve *icu1 = findIpoCurve((IpoCurve *)ipo->curve.first,"LocX");
if (!icu1)
- icu1 = verify_ipocurve(&blenderObject->id, ipo->blocktype, NULL, NULL, NULL, OB_LOC_X, 1);
+ icu1 = verify_ipocurve(&blenderObject->id, ipo->blocktype, NULL, NULL, NULL, OB_LOC_X);
icu1 = findIpoCurve((IpoCurve *)ipo->curve.first,"LocY");
if (!icu1)
- icu1 = verify_ipocurve(&blenderObject->id, ipo->blocktype, NULL, NULL, NULL, OB_LOC_Y, 1);
+ icu1 = verify_ipocurve(&blenderObject->id, ipo->blocktype, NULL, NULL, NULL, OB_LOC_Y);
icu1 = findIpoCurve((IpoCurve *)ipo->curve.first,"LocZ");
if (!icu1)
- icu1 = verify_ipocurve(&blenderObject->id, ipo->blocktype, NULL, NULL, NULL, OB_LOC_Z, 1);
+ icu1 = verify_ipocurve(&blenderObject->id, ipo->blocktype, NULL, NULL, NULL, OB_LOC_Z);
icu1 = findIpoCurve((IpoCurve *)ipo->curve.first,"RotX");
if (!icu1)
- icu1 = verify_ipocurve(&blenderObject->id, ipo->blocktype, NULL, NULL, NULL, OB_ROT_X, 1);
+ icu1 = verify_ipocurve(&blenderObject->id, ipo->blocktype, NULL, NULL, NULL, OB_ROT_X);
icu1 = findIpoCurve((IpoCurve *)ipo->curve.first,"RotY");
if (!icu1)
- icu1 = verify_ipocurve(&blenderObject->id, ipo->blocktype, NULL, NULL, NULL, OB_ROT_Y, 1);
+ icu1 = verify_ipocurve(&blenderObject->id, ipo->blocktype, NULL, NULL, NULL, OB_ROT_Y);
icu1 = findIpoCurve((IpoCurve *)ipo->curve.first,"RotZ");
if (!icu1)
- icu1 = verify_ipocurve(&blenderObject->id, ipo->blocktype, NULL, NULL, NULL, OB_ROT_Z, 1);
+ icu1 = verify_ipocurve(&blenderObject->id, ipo->blocktype, NULL, NULL, NULL, OB_ROT_Z);
diff --git a/source/gameengine/Converter/KX_BlenderSceneConverter.h b/source/gameengine/Converter/KX_BlenderSceneConverter.h
index 2317e952a0a..e5d6ccc5caf 100644
--- a/source/gameengine/Converter/KX_BlenderSceneConverter.h
+++ b/source/gameengine/Converter/KX_BlenderSceneConverter.h
@@ -45,7 +45,6 @@ class BL_Material;
struct IpoCurve;
struct Main;
struct SpaceIpo;
-struct Scene;
class KX_BlenderSceneConverter : public KX_ISceneConverter
{
@@ -152,7 +151,6 @@ public:
virtual void SetGLSLMaterials(bool val);
virtual bool GetGLSLMaterials();
- struct Scene* GetBlenderSceneForName(const STR_String& name);
};
#endif //__KX_BLENDERSCENECONVERTER_H
diff --git a/source/gameengine/Converter/KX_ConvertActuators.cpp b/source/gameengine/Converter/KX_ConvertActuators.cpp
index 4f152acc918..53ac730d203 100644
--- a/source/gameengine/Converter/KX_ConvertActuators.cpp
+++ b/source/gameengine/Converter/KX_ConvertActuators.cpp
@@ -74,8 +74,6 @@
#include "BKE_text.h"
#include "BLI_blenlib.h"
-#define FILE_MAX 240 // repeated here to avoid dependency from BKE_utildefines.h
-
#include "KX_NetworkMessageActuator.h"
#ifdef WIN32
@@ -210,12 +208,10 @@ void BL_ConvertActuators(char* maggiename,
if (blenderobject->type==OB_MESH){
bActionActuator* actact = (bActionActuator*) bact->data;
STR_String propname = (actact->name ? actact->name : "");
- STR_String propframe = (actact->frameProp ? actact->frameProp : "");
BL_ShapeActionActuator* tmpbaseact = new BL_ShapeActionActuator(
gameobj,
propname,
- propframe,
actact->sta,
actact->end,
actact->act,
@@ -235,8 +231,7 @@ void BL_ConvertActuators(char* maggiename,
{
bIpoActuator* ipoact = (bIpoActuator*) bact->data;
bool ipochild = (ipoact->flag & ACT_IPOCHILD) !=0;
- STR_String propname = ipoact->name;
- STR_String frameProp = ipoact->frameProp;
+ STR_String propname = ( ipoact->name ? ipoact->name : "");
// first bit?
bool ipo_as_force = (ipoact->flag & ACT_IPOFORCE);
bool local = (ipoact->flag & ACT_IPOLOCAL);
@@ -245,7 +240,6 @@ void BL_ConvertActuators(char* maggiename,
KX_IpoActuator* tmpbaseact = new KX_IpoActuator(
gameobj,
propname ,
- frameProp,
ipoact->sta,
ipoact->end,
ipochild,
@@ -291,19 +285,15 @@ void BL_ConvertActuators(char* maggiename,
STR_String toPropName = (msgAct->toPropName
? (char*) msgAct->toPropName
: "");
- /* BGE Wants "OB" prefix */
- if (toPropName != "")
- toPropName = "OB" + toPropName;
-
- /**
- * Get the Message Subject to send.
+ /**
+ * Get the Message Subject to send.
*/
STR_String subject = (msgAct->subject
? (char*) msgAct->subject
: "");
- /**
- * Get the bodyType
+ /**
+ * Get the bodyType
*/
int bodyType = msgAct->bodyType;
@@ -365,26 +355,22 @@ void BL_ConvertActuators(char* maggiename,
if (soundActuatorType != KX_SoundActuator::KX_SOUNDACT_NODEF)
{
- SND_Scene* soundscene = scene->GetSoundScene();
- STR_String samplename = "";
- bool sampleisloaded = false;
+ SND_SoundObject* sndobj = NULL;
- if (soundact->sound) {
- /* Need to convert the samplename into absolute path
- * before checking if its loaded */
- char fullpath[FILE_MAX];
+ if (soundact->sound)
+ {
+ SND_Scene* soundscene = scene->GetSoundScene();
+ STR_String samplename = soundact->sound->name;
- /* dont modify soundact->sound->name, only change a copy */
- BLI_strncpy(fullpath, soundact->sound->name, sizeof(fullpath));
- BLI_convertstringcode(fullpath, maggiename);
- samplename = fullpath;
+ bool sampleisloaded = false;
/* let's see if the sample was already loaded */
if (soundscene->IsSampleLoaded(samplename))
{
sampleisloaded = true;
}
- else {
+ else
+ {
/* if not, make it so */
PackedFile* pf = soundact->sound->newpackedfile;
@@ -397,33 +383,21 @@ void BL_ConvertActuators(char* maggiename,
/* or else load it from disk */
else
{
- if (soundscene->LoadSample(samplename, NULL, 0) > -1) {
+ /* but we need to convert the samplename into absolute pathname first */
+ BLI_convertstringcode(soundact->sound->name, maggiename);
+ samplename = soundact->sound->name;
+
+ /* and now we can load it */
+ if (soundscene->LoadSample(samplename, NULL, 0) > -1)
sampleisloaded = true;
- }
- else {
- std::cout << "WARNING: Sound actuator \"" << bact->name <<
- "\" from object \"" << blenderobject->id.name+2 <<
- "\" failed to load sample." << std::endl;
- }
}
}
- } else {
- std::cout << "WARNING: Sound actuator \"" << bact->name <<
- "\" from object \"" << blenderobject->id.name+2 <<
- "\" has no sound datablock." << std::endl;
- }
-
- /* Note, allowing actuators for sounds that are not there was added since 2.47
- * This is because python may expect the actuator and raise an exception if it dosnt find it
- * better just to add a dummy sound actuator. */
- SND_SoundObject* sndobj = NULL;
- if (sampleisloaded)
- {
- /* setup the SND_SoundObject */
- sndobj = new SND_SoundObject();
- sndobj->SetSampleName(samplename.Ptr());
- sndobj->SetObjectName(bact->name);
- if (soundact->sound) {
+
+ if (sampleisloaded)
+ {
+ sndobj = new SND_SoundObject();
+ sndobj->SetSampleName(samplename.Ptr());
+ sndobj->SetObjectName(bact->name);
sndobj->SetRollOffFactor(soundact->sound->attenuation);
sndobj->SetGain(soundact->sound->volume);
sndobj->SetPitch(exp((soundact->sound->pitch / 12.0) * log(2.0)));
@@ -436,9 +410,8 @@ void BL_ConvertActuators(char* maggiename,
else
sndobj->SetLoopMode(SND_LOOP_NORMAL);
}
- else {
+ else
sndobj->SetLoopMode(SND_LOOP_OFF);
- }
if (soundact->sound->flags & SOUND_FLAGS_PRIORITY)
sndobj->SetHighPriority(true);
@@ -449,30 +422,22 @@ void BL_ConvertActuators(char* maggiename,
sndobj->Set3D(true);
else
sndobj->Set3D(false);
- }
- else {
- /* dummy values for a NULL sound
- * see editsound.c - defaults are unlikely to change soon */
- sndobj->SetRollOffFactor(1.0);
- sndobj->SetGain(1.0);
- sndobj->SetPitch(1.0);
- sndobj->SetLoopMode(SND_LOOP_OFF);
- sndobj->SetHighPriority(false);
- sndobj->Set3D(false);
+
+ KX_SoundActuator* tmpsoundact =
+ new KX_SoundActuator(gameobj,
+ sndobj,
+ scene->GetSoundScene(), // needed for replication!
+ soundActuatorType,
+ startFrame,
+ stopFrame);
+
+ tmpsoundact->SetName(bact->name);
+ baseact = tmpsoundact;
+ soundscene->AddObject(sndobj);
+ } else {
+ std::cout << "WARNING: Sound actuator " << bact->name << " failed to load sample." << std::endl;
}
}
- KX_SoundActuator* tmpsoundact =
- new KX_SoundActuator(gameobj,
- sndobj,
- scene->GetSoundScene(), // needed for replication!
- soundActuatorType,
- startFrame,
- stopFrame);
-
- tmpsoundact->SetName(bact->name);
- baseact = tmpsoundact;
- if (sndobj)
- soundscene->AddObject(sndobj);
}
break;
}
@@ -575,26 +540,13 @@ void BL_ConvertActuators(char* maggiename,
// 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);
- }
- }
- MT_Vector3 linvelvec (
- KX_BLENDERTRUNC(editobact->linVelocity[0]),
+ if (editobact->ob && !(editobact->ob->lay & activeLayerBitInfo))
+ originalval = converter->FindGameObject(editobact->ob);
+
+ MT_Vector3 linvelvec ( KX_BLENDERTRUNC(editobact->linVelocity[0]),
KX_BLENDERTRUNC(editobact->linVelocity[1]),
KX_BLENDERTRUNC(editobact->linVelocity[2]));
-
- MT_Vector3 angvelvec (
- KX_BLENDERTRUNC(editobact->angVelocity[0]),
- KX_BLENDERTRUNC(editobact->angVelocity[1]),
- KX_BLENDERTRUNC(editobact->angVelocity[2]));
-
+
KX_SCA_AddObjectActuator* tmpaddact =
new KX_SCA_AddObjectActuator(
gameobj,
@@ -602,9 +554,7 @@ void BL_ConvertActuators(char* maggiename,
editobact->time,
scene,
linvelvec.getValue(),
- (editobact->localflag & ACT_EDOB_LOCAL_LINV)!=0,
- angvelvec.getValue(),
- (editobact->localflag & ACT_EDOB_LOCAL_ANGV)!=0
+ editobact->localflag!=0
);
//editobact->ob to gameobj
@@ -725,40 +675,6 @@ void BL_ConvertActuators(char* maggiename,
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:
@@ -920,16 +836,6 @@ void BL_ConvertActuators(char* maggiename,
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;
- }
default:
; /* flag error */
}
@@ -1016,9 +922,10 @@ void BL_ConvertActuators(char* maggiename,
bVisibilityActuator *vis_act = (bVisibilityActuator *) bact->data;
KX_VisibilityActuator * tmp_vis_act = NULL;
bool v = ((vis_act->flag & ACT_VISIBILITY_INVISIBLE) != 0);
- bool recursive = ((vis_act->flag & ACT_VISIBILITY_RECURSIVE) != 0);
- tmp_vis_act = new KX_VisibilityActuator(gameobj, !v, recursive);
+ tmp_vis_act =
+ new KX_VisibilityActuator(gameobj,
+ !v);
baseact = tmp_vis_act;
}
@@ -1117,7 +1024,7 @@ void BL_ConvertActuators(char* maggiename,
{
bParentActuator *parAct = (bParentActuator *) bact->data;
int mode = KX_ParentActuator::KX_PARENT_NODEF;
- KX_GameObject *tmpgob = NULL;
+ KX_GameObject *tmpgob;
switch(parAct->type)
{
diff --git a/source/gameengine/Converter/KX_ConvertProperties.cpp b/source/gameengine/Converter/KX_ConvertProperties.cpp
index dfbc6f0c48d..aae8752671f 100644
--- a/source/gameengine/Converter/KX_ConvertProperties.cpp
+++ b/source/gameengine/Converter/KX_ConvertProperties.cpp
@@ -132,10 +132,6 @@ void BL_ConvertProperties(Object* object,KX_GameObject* gameobj,SCA_TimeEventMan
prop = prop->next;
}
- // check if state needs to be debugged
- if (object->scaflag & OB_DEBUGSTATE)
- {
- // reserve name for object state
- scene->AddDebugProperty(gameobj,STR_String("__state__"));
- }
+
+
}
diff --git a/source/gameengine/Converter/KX_ConvertSensors.cpp b/source/gameengine/Converter/KX_ConvertSensors.cpp
index 13b7f43195d..5e433bb821b 100644
--- a/source/gameengine/Converter/KX_ConvertSensors.cpp
+++ b/source/gameengine/Converter/KX_ConvertSensors.cpp
@@ -65,7 +65,6 @@ probably misplaced */
#include "SCA_JoystickSensor.h"
#include "KX_NetworkMessageSensor.h"
#include "SCA_ActuatorSensor.h"
-#include "SCA_DelaySensor.h"
#include "SCA_PropertySensor.h"
@@ -92,7 +91,6 @@ void BL_ConvertSensors(struct Object* blenderobject,
class KX_GameObject* gameobj,
SCA_LogicManager* logicmgr,
KX_Scene* kxscene,
- KX_KetsjiEngine* kxengine,
SCA_IInputDevice* keydev,
int & executePriority,
int activeLayerBitInfo,
@@ -283,22 +281,6 @@ void BL_ConvertSensors(struct Object* blenderobject,
break;
}
- case SENS_DELAY:
- {
- // we can reuse the Always event manager for the delay sensor
- SCA_EventManager* eventmgr = logicmgr->FindEventManager(SCA_EventManager::ALWAYS_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);
@@ -433,8 +415,8 @@ void BL_ConvertSensors(struct Object* blenderobject,
{
gamesensor = new SCA_KeyboardSensor(eventmgr,
gReverseKeyTranslateTable[blenderkeybdsensor->key],
- gReverseKeyTranslateTable[blenderkeybdsensor->qual],
- gReverseKeyTranslateTable[blenderkeybdsensor->qual2],
+ blenderkeybdsensor->qual,
+ blenderkeybdsensor->qual2,
(blenderkeybdsensor->type == SENS_ALL_KEYS),
blenderkeybdsensor->targetName,
blenderkeybdsensor->toggleName,
@@ -509,7 +491,6 @@ void BL_ConvertSensors(struct Object* blenderobject,
trackfocus,
canvas,
kxscene,
- kxengine,
gameobj);
}
} else {
@@ -635,7 +616,6 @@ void BL_ConvertSensors(struct Object* blenderobject,
if (eventmgr)
{
bool bFindMaterial = (blenderraysensor->mode & SENS_COLLISION_MATERIAL);
- bool bXRay = (blenderraysensor->mode & SENS_RAY_XRAY);
STR_String checkname = (bFindMaterial? blenderraysensor->matname : blenderraysensor->propname);
@@ -648,7 +628,6 @@ void BL_ConvertSensors(struct Object* blenderobject,
gameobj,
checkname,
bFindMaterial,
- bXRay,
distance,
axis,
kxscene);
@@ -685,6 +664,7 @@ void BL_ConvertSensors(struct Object* blenderobject,
int axis =0;
int axisf =0;
int button =0;
+ int buttonf =0;
int hat =0;
int hatf =0;
int prec =0;
@@ -699,6 +679,7 @@ void BL_ConvertSensors(struct Object* blenderobject,
break;
case SENS_JOY_BUTTON:
button = bjoy->button;
+ buttonf = bjoy->buttonf;
joysticktype = SCA_JoystickSensor::KX_JOYSENSORMODE_BUTTON;
break;
case SENS_JOY_HAT:
@@ -713,13 +694,11 @@ void BL_ConvertSensors(struct Object* blenderobject,
gamesensor = new SCA_JoystickSensor(
eventmgr,
gameobj,
- bjoy->joyindex,
joysticktype,
axis,axisf,
prec,
- button,
- hat,hatf,
- (bjoy->flag & SENS_JOY_ANY_EVENT));
+ button,buttonf,
+ hat,hatf);
}
else
{
@@ -762,33 +741,12 @@ void BL_ConvertSensors(struct Object* blenderobject,
for (int i=0;i<sens->totlinks;i++)
{
bController* linkedcont = (bController*) sens->links[i];
- if (linkedcont) {
- SCA_IController* gamecont = converter->FindGameController(linkedcont);
+ 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);
+ if (gamecont) {
+ logicmgr->RegisterToSensor(gamecont,gamesensor);
}
}
- // 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();
diff --git a/source/gameengine/Converter/KX_ConvertSensors.h b/source/gameengine/Converter/KX_ConvertSensors.h
index b18ffc10a2a..73da51f47f0 100644
--- a/source/gameengine/Converter/KX_ConvertSensors.h
+++ b/source/gameengine/Converter/KX_ConvertSensors.h
@@ -33,7 +33,6 @@ void BL_ConvertSensors(struct Object* blenderobject,
class KX_GameObject* gameobj,
class SCA_LogicManager* logicmgr,
class KX_Scene* kxscene,
- class KX_KetsjiEngine* kxengine,
class SCA_IInputDevice* keydev,
int & executePriority ,
int activeLayerBitInfo,
diff --git a/source/gameengine/Converter/Makefile b/source/gameengine/Converter/Makefile
index 4dd63e428bd..f312fc13221 100644
--- a/source/gameengine/Converter/Makefile
+++ b/source/gameengine/Converter/Makefile
@@ -51,7 +51,6 @@ CPPFLAGS += -I../../blender/include
CPPFLAGS += -I../../blender/blenlib
CPPFLAGS += -I../../blender/blenkernel
CPPFLAGS += -I../../blender/render/extern/include
-CPPFLAGS += -I../../blender/gpu
CPPFLAGS += -I$(NAN_GUARDEDALLOC)/include
CPPFLAGS += -I../Expressions -I../Rasterizer -I../GameLogic
CPPFLAGS += -I../Ketsji -I../BlenderRoutines -I../SceneGraph
diff --git a/source/gameengine/Converter/SConscript b/source/gameengine/Converter/SConscript
index 3be352c568b..f5e382b471e 100644
--- a/source/gameengine/Converter/SConscript
+++ b/source/gameengine/Converter/SConscript
@@ -16,7 +16,7 @@ incs += ' #source/gameengine/Expressions #source/gameengine/Network #source/game
incs += ' #source/gameengine/Physics/common #source/gameengine/Physics/Bullet #source/gameengine/Physics/BlOde'
incs += ' #source/gameengine/Physics/Dummy #source/gameengine/Physics/Sumo'
incs += ' #source/gameengine/Physics/Sumo/Fuzzics/include #source/gameengine/Network/LoopBackNetwork'
-incs += ' #source/blender/misc #source/blender/blenloader #source/blender/gpu'
+incs += ' #source/blender/misc #source/blender/blenloader'
incs += ' ' + env['BF_PYTHON_INC']
incs += ' ' + env['BF_SOLID_INC']
diff --git a/source/gameengine/Expressions/InputParser.cpp b/source/gameengine/Expressions/InputParser.cpp
index 32a9de32e21..24033dd21a2 100644
--- a/source/gameengine/Expressions/InputParser.cpp
+++ b/source/gameengine/Expressions/InputParser.cpp
@@ -631,8 +631,7 @@ void CParser::SetContext(CValue* context)
PyObject* CParserPyMake(PyObject* ignored,PyObject* args)
{
char* txt;
- if (!PyArg_ParseTuple(args,"s",&txt))
- return NULL;
+ Py_Try(PyArg_ParseTuple(args,"s",&txt));
CParser parser;
CExpression* expr = parser.ProcessText(txt);
CValue* val = expr->Calculate();
@@ -642,7 +641,7 @@ PyObject* CParserPyMake(PyObject* ignored,PyObject* args)
static PyMethodDef CParserMethods[] =
{
- { "calc", CParserPyMake , METH_VARARGS},
+ { "calc", CParserPyMake , Py_NEWARGS},
{ NULL,NULL} // Sentinel
};
diff --git a/source/gameengine/Expressions/ListValue.cpp b/source/gameengine/Expressions/ListValue.cpp
index 9ffdbb1223c..bbf58a8a06e 100644
--- a/source/gameengine/Expressions/ListValue.cpp
+++ b/source/gameengine/Expressions/ListValue.cpp
@@ -43,7 +43,7 @@ PyObject* listvalue_buffer_item(PyObject* list,Py_ssize_t index)
return ((CListValue*) list)->GetValue(index)->AddRef();
}
- PyErr_SetString(PyExc_IndexError, "Python ListIndex out of range");
+ Py_Error(PyExc_IndexError, "Python ListIndex out of range");
return NULL;
}
@@ -130,10 +130,9 @@ listvalue_buffer_concat(PyObject * self, PyObject * other)
}
}
- if (error) {
- PyErr_SetString(PyExc_SystemError, "Python Error: couldn't add one or more items to a list");
- return NULL;
- }
+ if (error)
+ Py_Error(PyExc_SystemError, "Python Error: couldn't add one or more items to a list");
+
} else
{
@@ -156,8 +155,8 @@ listvalue_buffer_concat(PyObject * self, PyObject * other)
listval->Add(objval);
} else
{
- PyErr_SetString(PyExc_SystemError, "Python Error: couldn't add item to a list");
- return NULL;
+ Py_Error(PyExc_SystemError, "Python Error: couldn't add item to a list");
+ // bad luck
}
}
}
diff --git a/source/gameengine/Expressions/Makefile b/source/gameengine/Expressions/Makefile
index 6736149bbcd..e9c02eedcf2 100644
--- a/source/gameengine/Expressions/Makefile
+++ b/source/gameengine/Expressions/Makefile
@@ -36,7 +36,6 @@ include nan_compile.mk
CCFLAGS += $(LEVEL_1_CPP_WARNINGS)
CPPFLAGS += -I$(NAN_PYTHON)/include/python$(NAN_PYTHON_VERSION)
-CPPFLAGS += -I../../blender/makesdna
CPPFLAGS += -I$(NAN_STRING)/include
CPPFLAGS += -I$(NAN_MOTO)/include
diff --git a/source/gameengine/Expressions/PyObjectPlus.cpp b/source/gameengine/Expressions/PyObjectPlus.cpp
index c31587628b0..aabcd6cb71d 100644
--- a/source/gameengine/Expressions/PyObjectPlus.cpp
+++ b/source/gameengine/Expressions/PyObjectPlus.cpp
@@ -94,7 +94,7 @@ PyObjectPlus::PyObjectPlus(PyTypeObject *T) // constructor
* PyObjectPlus Methods -- Every class, even the abstract one should have a Methods
------------------------------*/
PyMethodDef PyObjectPlus::Methods[] = {
- {"isA", (PyCFunction) sPy_isA, METH_VARARGS},
+ {"isA", (PyCFunction) sPy_isA, Py_NEWARGS},
{NULL, NULL} /* Sentinel */
};
@@ -119,7 +119,6 @@ PyObject *PyObjectPlus::_getattr(const STR_String& attr)
int PyObjectPlus::_delattr(const STR_String& attr)
{
- PyErr_SetString(PyExc_AttributeError, "attribute cant be deleted");
return 1;
}
@@ -127,451 +126,7 @@ int PyObjectPlus::_setattr(const STR_String& attr, PyObject *value)
{
//return PyObject::_setattr(attr,value);
//cerr << "Unknown attribute" << endl;
- PyErr_SetString(PyExc_AttributeError, "attribute cant be set");
- return 1;
-}
-
-PyObject *PyObjectPlus::_getattr_self(const PyAttributeDef attrlist[], void *self, const STR_String &attr)
-{
- const PyAttributeDef *attrdef;
- for (attrdef=attrlist; attrdef->m_name != NULL; attrdef++)
- {
- if (attr == attrdef->m_name)
- {
- if (attrdef->m_type == KX_PYATTRIBUTE_TYPE_DUMMY)
- {
- // fake attribute, ignore
- return NULL;
- }
- char *ptr = reinterpret_cast<char*>(self)+attrdef->m_offset;
- if (attrdef->m_length > 1)
- {
- PyObject* resultlist = PyList_New(attrdef->m_length);
- for (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_SetItem(resultlist,i,PyInt_FromLong(*val));
- break;
- }
- case KX_PYATTRIBUTE_TYPE_SHORT:
- {
- short int *val = reinterpret_cast<short int*>(ptr);
- ptr += sizeof(short int);
- PyList_SetItem(resultlist,i,PyInt_FromLong(*val));
- break;
- }
- case KX_PYATTRIBUTE_TYPE_INT:
- {
- int *val = reinterpret_cast<int*>(ptr);
- ptr += sizeof(int);
- PyList_SetItem(resultlist,i,PyInt_FromLong(*val));
- break;
- }
- case KX_PYATTRIBUTE_TYPE_FLOAT:
- {
- float *val = reinterpret_cast<float*>(ptr);
- ptr += sizeof(float);
- PyList_SetItem(resultlist,i,PyFloat_FromDouble(*val));
- break;
- }
- default:
- // no support for array of complex data
- return NULL;
- }
- }
- return resultlist;
- }
- else
- {
- switch (attrdef->m_type) {
- case KX_PYATTRIBUTE_TYPE_BOOL:
- {
- bool *val = reinterpret_cast<bool*>(ptr);
- return PyInt_FromLong(*val);
- }
- case KX_PYATTRIBUTE_TYPE_SHORT:
- {
- short int *val = reinterpret_cast<short int*>(ptr);
- return PyInt_FromLong(*val);
- }
- case KX_PYATTRIBUTE_TYPE_INT:
- {
- int *val = reinterpret_cast<int*>(ptr);
- return PyInt_FromLong(*val);
- }
- case KX_PYATTRIBUTE_TYPE_FLOAT:
- {
- float *val = reinterpret_cast<float*>(ptr);
- return PyFloat_FromDouble(*val);
- }
- case KX_PYATTRIBUTE_TYPE_STRING:
- {
- STR_String *val = reinterpret_cast<STR_String*>(ptr);
- return PyString_FromString(*val);
- }
- default:
- return NULL;
- }
- }
- }
- }
- return NULL;
-}
-
-int PyObjectPlus::_setattr_self(const PyAttributeDef attrlist[], void *self, const STR_String &attr, PyObject *value)
-{
- const PyAttributeDef *attrdef;
- void *undoBuffer = NULL;
- void *sourceBuffer = NULL;
- size_t bufferSize = 0;
-
- for (attrdef=attrlist; attrdef->m_name != NULL; attrdef++)
- {
- if (attr == attrdef->m_name)
- {
- if (attrdef->m_access == KX_PYATTRIBUTE_RO ||
- attrdef->m_type == KX_PYATTRIBUTE_TYPE_DUMMY)
- {
- PyErr_SetString(PyExc_AttributeError, "property is read-only");
- return 1;
- }
- char *ptr = reinterpret_cast<char*>(self)+attrdef->m_offset;
- if (attrdef->m_length > 1)
- {
- if (!PySequence_Check(value))
- {
- PyErr_SetString(PyExc_TypeError, "expected a sequence");
- return 1;
- }
- if (PySequence_Size(value) != attrdef->m_length)
- {
- PyErr_SetString(PyExc_TypeError, "incorrect number of elements in sequence");
- return 1;
- }
- switch (attrdef->m_type)
- {
- case KX_PYATTRIBUTE_TYPE_BOOL:
- bufferSize = sizeof(bool);
- break;
- case KX_PYATTRIBUTE_TYPE_SHORT:
- bufferSize = sizeof(short int);
- break;
- case KX_PYATTRIBUTE_TYPE_INT:
- bufferSize = sizeof(int);
- break;
- case KX_PYATTRIBUTE_TYPE_FLOAT:
- bufferSize = sizeof(float);
- break;
- default:
- // should not happen
- PyErr_SetString(PyExc_AttributeError, "Unsupported attribute type, report to blender.org");
- return 1;
- }
- // 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++)
- {
- PyObject *item = PySequence_GetItem(value, i); /* new ref */
- // we can decrement the reference immediately, the reference count
- // is at least 1 because the item is part of an array
- Py_DECREF(item);
- switch (attrdef->m_type)
- {
- case KX_PYATTRIBUTE_TYPE_BOOL:
- {
- bool *var = reinterpret_cast<bool*>(ptr);
- ptr += sizeof(bool);
- if (PyInt_Check(item))
- {
- *var = (PyInt_AsLong(item) != 0);
- }
- else if (PyBool_Check(item))
- {
- *var = (item == Py_True);
- }
- else
- {
- PyErr_SetString(PyExc_TypeError, "expected an integer or a bool");
- goto UNDO_AND_ERROR;
- }
- break;
- }
- case KX_PYATTRIBUTE_TYPE_SHORT:
- {
- short int *var = reinterpret_cast<short int*>(ptr);
- ptr += sizeof(short int);
- if (PyInt_Check(item))
- {
- long val = PyInt_AsLong(item);
- if (val < attrdef->m_imin || val > attrdef->m_imax)
- {
- PyErr_SetString(PyExc_ValueError, "item value out of range");
- goto UNDO_AND_ERROR;
- }
- *var = (short int)val;
- }
- else
- {
- PyErr_SetString(PyExc_TypeError, "expected an integer");
- goto UNDO_AND_ERROR;
- }
- break;
- }
- case KX_PYATTRIBUTE_TYPE_INT:
- {
- int *var = reinterpret_cast<int*>(ptr);
- ptr += sizeof(int);
- if (PyInt_Check(item))
- {
- long val = PyInt_AsLong(item);
- if (val < attrdef->m_imin || val > attrdef->m_imax)
- {
- PyErr_SetString(PyExc_ValueError, "item value out of range");
- goto UNDO_AND_ERROR;
- }
- *var = (int)val;
- }
- else
- {
- PyErr_SetString(PyExc_TypeError, "expected an integer");
- goto UNDO_AND_ERROR;
- }
- break;
- }
- case KX_PYATTRIBUTE_TYPE_FLOAT:
- {
- float *var = reinterpret_cast<float*>(ptr);
- ptr += sizeof(float);
- if (PyFloat_Check(item))
- {
- double val = PyFloat_AsDouble(item);
- if (val < attrdef->m_fmin || val > attrdef->m_fmax)
- {
- PyErr_SetString(PyExc_ValueError, "item value out of range");
- goto UNDO_AND_ERROR;
- }
- *var = (float)val;
- }
- else
- {
- PyErr_SetString(PyExc_TypeError, "expected a float");
- goto UNDO_AND_ERROR;
- }
- break;
- }
- default:
- // should not happen
- PyErr_SetString(PyExc_AttributeError, "attribute type check error, report to blender.org");
- goto UNDO_AND_ERROR;
- }
- }
- // no error, call check function if any
- if (attrdef->m_function != NULL)
- {
- if ((*attrdef->m_function)(self) != 0)
- {
- // post check returned an error, restore values
- UNDO_AND_ERROR:
- if (undoBuffer)
- {
- memcpy(sourceBuffer, undoBuffer, bufferSize);
- free(undoBuffer);
- }
- return 1;
- }
- }
- if (undoBuffer)
- free(undoBuffer);
- return 0;
- }
- else // simple attribute value
- {
-
- if (attrdef->m_function != NULL)
- {
- // 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_INT:
- bufferSize = sizeof(int);
- break;
- case KX_PYATTRIBUTE_TYPE_FLOAT:
- bufferSize = sizeof(float);
- break;
- case KX_PYATTRIBUTE_TYPE_STRING:
- sourceBuffer = reinterpret_cast<STR_String*>(ptr)->Ptr();
- if (sourceBuffer)
- bufferSize = strlen(reinterpret_cast<char*>(sourceBuffer))+1;
- break;
- default:
- PyErr_SetString(PyExc_AttributeError, "unknown attribute type, report to blender.org");
- return 1;
- }
- 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 (PyInt_Check(value))
- {
- *var = (PyInt_AsLong(value) != 0);
- }
- else if (PyBool_Check(value))
- {
- *var = (value == Py_True);
- }
- else
- {
- PyErr_SetString(PyExc_TypeError, "expected an integer or a bool");
- goto FREE_AND_ERROR;
- }
- break;
- }
- case KX_PYATTRIBUTE_TYPE_SHORT:
- {
- short int *var = reinterpret_cast<short int*>(ptr);
- if (PyInt_Check(value))
- {
- long val = PyInt_AsLong(value);
- if (val < attrdef->m_imin || val > attrdef->m_imax)
- {
- PyErr_SetString(PyExc_ValueError, "value out of range");
- goto FREE_AND_ERROR;
- }
- *var = (short int)val;
- }
- else
- {
- PyErr_SetString(PyExc_TypeError, "expected an integer");
- goto FREE_AND_ERROR;
- }
- break;
- }
- case KX_PYATTRIBUTE_TYPE_INT:
- {
- int *var = reinterpret_cast<int*>(ptr);
- if (PyInt_Check(value))
- {
- long val = PyInt_AsLong(value);
- if (val < attrdef->m_imin || val > attrdef->m_imax)
- {
- PyErr_SetString(PyExc_ValueError, "value out of range");
- goto FREE_AND_ERROR;
- }
- *var = (int)val;
- }
- else
- {
- PyErr_SetString(PyExc_TypeError, "expected an integer");
- goto FREE_AND_ERROR;
- }
- break;
- }
- case KX_PYATTRIBUTE_TYPE_FLOAT:
- {
- float *var = reinterpret_cast<float*>(ptr);
- if (PyFloat_Check(value))
- {
- double val = PyFloat_AsDouble(value);
- if (val < attrdef->m_fmin || val > attrdef->m_fmax)
- {
- PyErr_SetString(PyExc_ValueError, "value out of range");
- goto FREE_AND_ERROR;
- }
- *var = (float)val;
- }
- else
- {
- PyErr_SetString(PyExc_TypeError, "expected a float");
- goto FREE_AND_ERROR;
- }
- break;
- }
- case KX_PYATTRIBUTE_TYPE_STRING:
- {
- STR_String *var = reinterpret_cast<STR_String*>(ptr);
- if (PyString_Check(value))
- {
- char *val = PyString_AsString(value);
- if (strlen(val) < attrdef->m_imin || strlen(val) > attrdef->m_imax)
- {
- PyErr_SetString(PyExc_ValueError, "string length out of range");
- goto FREE_AND_ERROR;
- }
- *var = val;
- }
- else
- {
- PyErr_SetString(PyExc_TypeError, "expected a string");
- goto FREE_AND_ERROR;
- }
- break;
- }
- default:
- // should not happen
- PyErr_SetString(PyExc_AttributeError, "unknown attribute type, report to blender.org");
- goto FREE_AND_ERROR;
- }
- }
- // check if post processing is needed
- if (attrdef->m_function != NULL)
- {
- if ((*attrdef->m_function)(self) != 0)
- {
- // restore value
- 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);
- return 1;
- }
- }
- if (undoBuffer)
- free(undoBuffer);
- return 0;
- }
- }
- return -1;
+ return 1;
}
/*------------------------------
@@ -579,8 +134,7 @@ int PyObjectPlus::_setattr_self(const PyAttributeDef attrlist[], void *self, con
------------------------------*/
PyObject *PyObjectPlus::_repr(void)
{
- PyErr_SetString(PyExc_SystemError, "Representation not overridden by object.");
- return NULL;
+ Py_Error(PyExc_SystemError, "Representation not overridden by object.");
}
/*------------------------------
@@ -610,12 +164,11 @@ bool PyObjectPlus::isA(const char *mytypename) // check typename of each parent
PyObject *PyObjectPlus::Py_isA(PyObject *args) // Python wrapper for isA
{
char *mytypename;
- if (!PyArg_ParseTuple(args, "s", &mytypename))
- return NULL;
+ Py_Try(PyArg_ParseTuple(args, "s", &mytypename));
if(isA(mytypename))
- Py_RETURN_TRUE;
+ {Py_INCREF(Py_True); return Py_True;}
else
- Py_RETURN_FALSE;
+ {Py_INCREF(Py_False); return Py_False;};
}
#endif //NO_EXP_PYTHON_EMBEDDING
diff --git a/source/gameengine/Expressions/PyObjectPlus.h b/source/gameengine/Expressions/PyObjectPlus.h
index 016fa293d73..2bcb604dd23 100644
--- a/source/gameengine/Expressions/PyObjectPlus.h
+++ b/source/gameengine/Expressions/PyObjectPlus.h
@@ -43,39 +43,25 @@
* Python defines
------------------------------*/
-/*
- Py_RETURN_NONE
- Python 2.4 macro.
- defined here until we switch to 2.4
- also in api2_2x/gen_utils.h
-*/
-#ifndef Py_RETURN_NONE
-#define Py_RETURN_NONE return Py_BuildValue("O", Py_None)
-#endif
-#ifndef Py_RETURN_FALSE
-#define Py_RETURN_FALSE return PyBool_FromLong(0)
-#endif
-#ifndef Py_RETURN_TRUE
-#define Py_RETURN_TRUE return PyBool_FromLong(1)
-#endif
-
-/* for pre Py 2.5 */
-#if PY_VERSION_HEX < 0x02050000
-typedef int Py_ssize_t;
-#define PY_SSIZE_T_MAX INT_MAX
-#define PY_SSIZE_T_MIN INT_MIN
-#define PY_METHODCHAR char *
-#else
-/* Py 2.5 and later */
-#define intargfunc ssizeargfunc
-#define intintargfunc ssizessizeargfunc
-#define PY_METHODCHAR const char *
-#endif
-
// some basic python macros
+#define Py_NEWARGS 1
#define Py_Return { Py_INCREF(Py_None); return Py_None;}
+static inline PyObject* Py_Success(bool truth)
+{
+ if (truth)
+ {
+ Py_INCREF(Py_True);
+ return Py_True;
+ }
+ Py_INCREF(Py_False);
+ return Py_False;
+}
-static inline void Py_Fatal(const char *M) {
+#define Py_Error(E, M) {PyErr_SetString(E, M); return NULL;}
+#define Py_Try(F) {if (!(F)) return NULL;}
+#define Py_Assert(A,E,M) {if (!(A)) {PyErr_SetString(E, M); return NULL;}}
+
+static inline void Py_Fatal(char *M) {
//cout << M << endl;
exit(-1);
};
@@ -86,7 +72,6 @@ static inline void Py_Fatal(const char *M) {
public: \
static PyTypeObject Type; \
static PyMethodDef Methods[]; \
- static PyAttributeDef Attributes[]; \
static PyParentObject Parents[]; \
virtual PyTypeObject *GetType(void) {return &Type;}; \
virtual PyParentObject *GetParents(void) {return Parents;}
@@ -132,12 +117,6 @@ static inline void Py_Fatal(const char *M) {
return ((class_name*) self)->Py##method_name(self, args, kwds); \
}; \
-#define KX_PYMETHOD_VARARGS(class_name, method_name) \
- PyObject* Py##method_name(PyObject* self, PyObject* args); \
- static PyObject* sPy##method_name( PyObject* self, PyObject* args) { \
- return ((class_name*) self)->Py##method_name(self, args); \
- }; \
-
#define KX_PYMETHOD_NOARGS(class_name, method_name) \
PyObject* Py##method_name(PyObject* self); \
static PyObject* sPy##method_name( PyObject* self) { \
@@ -155,28 +134,21 @@ static inline void Py_Fatal(const char *M) {
static PyObject* sPy##method_name( PyObject* self, PyObject* args, PyObject* kwds) { \
return ((class_name*) self)->Py##method_name(self, args, kwds); \
}; \
- static const char method_name##_doc[]; \
-
-#define KX_PYMETHOD_DOC_VARARGS(class_name, method_name) \
- PyObject* Py##method_name(PyObject* self, PyObject* args); \
- static PyObject* sPy##method_name( PyObject* self, PyObject* args) { \
- return ((class_name*) self)->Py##method_name(self, args); \
- }; \
- static const char method_name##_doc[]; \
+ static char method_name##_doc[]; \
#define KX_PYMETHOD_DOC_O(class_name, method_name) \
PyObject* Py##method_name(PyObject* self, PyObject* value); \
static PyObject* sPy##method_name( PyObject* self, PyObject* value) { \
return ((class_name*) self)->Py##method_name(self, value); \
}; \
- static const char method_name##_doc[]; \
+ static char method_name##_doc[]; \
#define KX_PYMETHOD_DOC_NOARGS(class_name, method_name) \
PyObject* Py##method_name(PyObject* self); \
static PyObject* sPy##method_name( PyObject* self) { \
return ((class_name*) self)->Py##method_name(self); \
}; \
- static const char method_name##_doc[]; \
+ static char method_name##_doc[]; \
/* The line above should remain empty */
@@ -184,130 +156,15 @@ static inline void Py_Fatal(const char *M) {
* Method table macro (with doc)
*/
#define KX_PYMETHODTABLE(class_name, method_name) \
- {#method_name , (PyCFunction) class_name::sPy##method_name, METH_VARARGS, (PY_METHODCHAR)class_name::method_name##_doc}
-
-#define KX_PYMETHODTABLE_O(class_name, method_name) \
- {#method_name , (PyCFunction) class_name::sPy##method_name, METH_O, (PY_METHODCHAR)class_name::method_name##_doc}
-
-#define KX_PYMETHODTABLE_NOARGS(class_name, method_name) \
- {#method_name , (PyCFunction) class_name::sPy##method_name, METH_NOARGS, (PY_METHODCHAR)class_name::method_name##_doc}
+ {#method_name , (PyCFunction) class_name::sPy##method_name, METH_VARARGS, 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; \
+char class_name::method_name##_doc[] = doc_string; \
PyObject* class_name::Py##method_name(PyObject*, PyObject* args, PyObject*)
-#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*, 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*, 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(PyObject*)
-
-/**
- * Attribute management
- */
-enum KX_PYATTRIBUTE_TYPE {
- KX_PYATTRIBUTE_TYPE_BOOL,
- KX_PYATTRIBUTE_TYPE_SHORT,
- KX_PYATTRIBUTE_TYPE_INT,
- KX_PYATTRIBUTE_TYPE_FLOAT,
- KX_PYATTRIBUTE_TYPE_STRING,
- KX_PYATTRIBUTE_TYPE_DUMMY,
-};
-
-enum KX_PYATTRIBUTE_ACCESS {
- KX_PYATTRIBUTE_RW,
- KX_PYATTRIBUTE_RO
-};
-
-typedef int (*KX_PYATTRIBUTE_FUNCTION)(void *self);
-
-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
- int m_imax; // maximum value in case of integer attributes
- float m_fmin; // minimum value in case of float attributes
- float m_fmax; // maximum value in case of float attributes
- size_t m_offset; // position of field in structure
- size_t m_length; // length of array, 1=simple attribute
- KX_PYATTRIBUTE_FUNCTION m_function; // 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;
- } m_typeCheck;
-} PyAttributeDef;
-
-#define KX_PYATTRIBUTE_DUMMY(name) \
- { name, KX_PYATTRIBUTE_TYPE_DUMMY, KX_PYATTRIBUTE_RO, 0, 0, 0.f, 0.f, 0, 1, NULL, {NULL, NULL, NULL, NULL, NULL} }
-
-#define KX_PYATTRIBUTE_BOOL_RW(name,object,field) \
- { name, KX_PYATTRIBUTE_TYPE_BOOL, KX_PYATTRIBUTE_RW, 0, 1, 0.f, 0.f, offsetof(object,field), 1, NULL, {&((object *)0)->field, 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, offsetof(object,field), 1, &object::function, {&((object *)0)->field, 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, offsetof(object,field), 1, NULL, {&((object *)0)->field, NULL, NULL, NULL, NULL} }
-
-#define KX_PYATTRIBUTE_SHORT_RW(name,min,max,object,field) \
- { name, KX_PYATTRIBUTE_TYPE_SHORT, KX_PYATTRIBUTE_RW, min, max, 0.f, 0.f, offsetof(object,field), 1, NULL, {NULL, &((object *)0)->field, NULL, NULL, NULL} }
-#define KX_PYATTRIBUTE_SHORT_RW_CHECK(name,min,max,object,field,function) \
- { name, KX_PYATTRIBUTE_TYPE_SHORT, KX_PYATTRIBUTE_RW, min, max, 0.f, 0.f, offsetof(object,field), 1, &object::function, {NULL, &((object *)0)->field, 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, offsetof(object,field), 1, NULL, {NULL, &((object *)0)->field, NULL, NULL, NULL} }
-#define KX_PYATTRIBUTE_SHORT_ARRAY_RW(name,min,max,object,field,length) \
- { name, KX_PYATTRIBUTE_TYPE_SHORT, KX_PYATTRIBUTE_RW, min, max, 0.f, 0.f, offsetof(object,field), length, NULL, {NULL, &((object *)0)->field, NULL, NULL, NULL} }
-#define KX_PYATTRIBUTE_SHORT_ARRAY_RW_CHECK(name,min,max,object,field,length,function) \
- { name, KX_PYATTRIBUTE_TYPE_SHORT, KX_PYATTRIBUTE_RW, min, max, 0.f, 0.f, offsetof(object,field), length, &object::function, {NULL, &((object *)0)->field, 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, offsetof(object,field), length, NULL, {NULL, &((object *)0)->field, NULL, NULL, NULL} }
-
-#define KX_PYATTRIBUTE_INT_RW(name,min,max,object,field) \
- { name, KX_PYATTRIBUTE_TYPE_INT, KX_PYATTRIBUTE_RW, min, max, 0.f, 0.f, offsetof(object,field), 1, NULL, {NULL, NULL, &((object *)0)->field, NULL, NULL} }
-#define KX_PYATTRIBUTE_INT_RW_CHECK(name,min,max,object,field,function) \
- { name, KX_PYATTRIBUTE_TYPE_INT, KX_PYATTRIBUTE_RW, min, max, 0.f, 0.f, offsetof(object,field), 1, &object::function, {NULL, NULL, &((object *)0)->field, NULL, NULL} }
-#define KX_PYATTRIBUTE_INT_RO(name,object,field) \
- { name, KX_PYATTRIBUTE_TYPE_INT, KX_PYATTRIBUTE_RO, 0, 0, 0.f, 0.f, offsetof(object,field), 1, NULL, {NULL, NULL, &((object *)0)->field, NULL, NULL} }
-#define KX_PYATTRIBUTE_INT_ARRAY_RW(name,min,max,object,field,length) \
- { name, KX_PYATTRIBUTE_TYPE_INT, KX_PYATTRIBUTE_RW, min, max, 0.f, 0.f, offsetof(object,field), length, NULL, {NULL, NULL, &((object *)0)->field, NULL, NULL} }
-#define KX_PYATTRIBUTE_INT_ARRAY_RW_CHECK(name,min,max,object,field,length,function) \
- { name, KX_PYATTRIBUTE_TYPE_INT, KX_PYATTRIBUTE_RW, min, max, 0.f, 0.f, offsetof(object,field), length, &object::function, {NULL, NULL, &((object *)0)->field, 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, offsetof(object,field), length, NULL, {NULL, NULL, &((object *)0)->field, NULL, NULL} }
-
-#define KX_PYATTRIBUTE_FLOAT_RW(name,min,max,object,field) \
- { name, KX_PYATTRIBUTE_TYPE_FLOAT, KX_PYATTRIBUTE_RW, 0, 0, min, max, offsetof(object,field), 1, NULL, {NULL, NULL, NULL, &((object *)0)->field, 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, offsetof(object,field), 1, &object::function, {NULL, NULL, NULL, &((object *)0)->field, NULL} }
-#define KX_PYATTRIBUTE_FLOAT_RO(name,object,field) \
- { name, KX_PYATTRIBUTE_TYPE_FLOAT, KX_PYATTRIBUTE_RO, 0, 0, 0.f, 0.f, offsetof(object,field), 1, NULL, {NULL, NULL, NULL, &((object *)0)->field, NULL} }
-#define KX_PYATTRIBUTE_FLOAT_ARRAY_RW(name,min,max,object,field,length) \
- { name, KX_PYATTRIBUTE_TYPE_FLOAT, KX_PYATTRIBUTE_RW, 0, 0, min, max, offsetof(object,field), length, NULL, {NULL, NULL, NULL, &((object *)0)->field, 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, offsetof(object,field), length, &object::function, {NULL, NULL, NULL, &((object *)0)->field, 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, offsetof(object,field), length, NULL, {NULL, NULL, NULL, &((object *)0)->field, NULL} }
-
-#define KX_PYATTRIBUTE_STRING_RW(name,min,max,object,field) \
- { name, KX_PYATTRIBUTE_TYPE_STRING, KX_PYATTRIBUTE_RW, min, max, 0.f, 0.f, offsetof(object,field), 1, NULL, {NULL, NULL, NULL, NULL, &((object *)0)->field} }
-#define KX_PYATTRIBUTE_STRING_RW_CHECK(name,min,max,object,field,function) \
- { name, KX_PYATTRIBUTE_TYPE_STRING, KX_PYATTRIBUTE_RW, min, max, 0.f, 0.f, offsetof(object,field), 1, &object::function, {NULL, NULL, NULL, NULL, &((object *)0)->field} }
-#define KX_PYATTRIBUTE_STRING_RO(name,object,field) \
- { name, KX_PYATTRIBUTE_TYPE_STRING, KX_PYATTRIBUTE_RO, 0, 0, 0.f, 0.f, offsetof(object,field), 1 , NULL, {NULL, NULL, NULL, NULL, &((object *)0)->field} }
/*------------------------------
* PyObjectPlus
@@ -339,8 +196,6 @@ public:
{
return ((PyObjectPlus*) PyObj)->_getattr(STR_String(attr));
}
- static PyObject *_getattr_self(const PyAttributeDef attrlist[], void *self, const STR_String &attr);
- static int _setattr_self(const PyAttributeDef attrlist[], void *self, const STR_String &attr, PyObject *value);
virtual int _delattr(const STR_String& attr);
virtual int _setattr(const STR_String& attr, PyObject *value); // _setattr method
diff --git a/source/gameengine/Expressions/Value.cpp b/source/gameengine/Expressions/Value.cpp
index f2b5569c76e..b4694740679 100644
--- a/source/gameengine/Expressions/Value.cpp
+++ b/source/gameengine/Expressions/Value.cpp
@@ -32,7 +32,6 @@
//////////////////////////////////////////////////////////////////////
double CValue::m_sZeroVec[3] = {0.0,0.0,0.0};
-bool CValue::m_ignore_deprecation_warnings(false);
#ifndef NO_EXP_PYTHON_EMBEDDING
@@ -159,14 +158,15 @@ PyParentObject CValue::Parents[] = {
};
PyMethodDef CValue::Methods[] = {
-// { "printHello", (PyCFunction) CValue::sPyPrintHello, METH_VARARGS},
- { "getName", (PyCFunction) CValue::sPyGetName, METH_NOARGS},
+// { "printHello", (PyCFunction) CValue::sPyPrintHello, Py_NEWARGS},
+ { "getName", (PyCFunction) CValue::sPyGetName, Py_NEWARGS},
{NULL,NULL} //Sentinel
};
-PyObject* CValue::PyGetName(PyObject* self)
+PyObject* CValue::PyGetName(PyObject* self,PyObject* args,PyObject* kwds)
{
- return PyString_FromString(this->GetName());
+ PyObject* pyname = PyString_FromString(this->GetName());
+ return pyname;
}
/*#define CVALUE_DEBUG*/
@@ -392,23 +392,16 @@ float CValue::GetPropertyNumber(const STR_String& inName,float defnumber)
bool CValue::RemoveProperty(const STR_String & inName)
{
// Check if there are properties at all which can be removed
- if (m_pNamedPropertyArray) {
- CValue* val = GetProperty(inName);
- if (NULL != val)
- {
- val->Release();
- m_pNamedPropertyArray->erase(inName);
- return true;
- }
- }
-
- char err[128];
- if (m_pNamedPropertyArray)
- sprintf(err, "attribute \"%s\" dosnt exist", inName.ReadPtr());
- else
- sprintf(err, "attribute \"%s\" dosnt exist (no property array)", inName.ReadPtr());
-
- PyErr_SetString(PyExc_AttributeError, err);
+ if (m_pNamedPropertyArray == NULL)
+ return false;
+
+ CValue* val = GetProperty(inName);
+ if (NULL != val)
+ {
+ val->Release();
+ m_pNamedPropertyArray->erase(inName);
+ return true;
+ }
return false;
}
@@ -669,7 +662,7 @@ CValue* CValue::FindIdentifier(const STR_String& identifiername)
static PyMethodDef CValueMethods[] =
{
- //{ "new", CValue::PyMake , METH_VARARGS},
+ //{ "new", CValue::PyMake , Py_NEWARGS},
{ NULL,NULL} // Sentinel
};
@@ -763,8 +756,7 @@ CValue* CValue::ConvertPythonToValue(PyObject* pyobj)
int CValue::_delattr(const STR_String& attr)
{
- if (!RemoveProperty(attr)) /* sets error */
- return 1;
+ RemoveProperty(attr);
return 0;
}
@@ -814,8 +806,9 @@ PyObject* CValue::ConvertKeysToPython( void )
PyObject* CValue::PyMake(PyObject* ignored,PyObject* args)
{
- //if (!PyArg_ParseTuple(args,"s",&name)) return NULL;
- Py_RETURN_NONE;//new CValue();
+ //Py_Try(PyArg_ParseTuple(args,"s",&name));
+ Py_INCREF(Py_None);
+ return Py_None;//new CValue();
}
*/
@@ -850,15 +843,4 @@ void CValue::SetValue(CValue* newval)
}
///////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
-/* deprecation warning management */
-void CValue::SetDeprecationWarnings(bool ignoreDeprecationWarnings)
-{
- m_ignore_deprecation_warnings = ignoreDeprecationWarnings;
-}
-
-void CValue::ShowDeprecationWarning(const char* old_way,const char* new_way)
-{
- if (!m_ignore_deprecation_warnings)
- printf("Method %s is deprecated, please use %s instead.\n", old_way, new_way);
-}
diff --git a/source/gameengine/Expressions/Value.h b/source/gameengine/Expressions/Value.h
index 56a4991af27..bcf231cf4f0 100644
--- a/source/gameengine/Expressions/Value.h
+++ b/source/gameengine/Expressions/Value.h
@@ -255,7 +255,7 @@ public:
virtual PyObject* ConvertKeysToPython( void );
- KX_PYMETHOD_NOARGS(CValue,GetName);
+ KX_PYMETHOD(CValue,GetName);
#else
CValue();
@@ -318,10 +318,6 @@ public:
STR_String op2str(VALUE_OPERATOR op);
- /** enable/disable display of deprecation warnings */
- static void SetDeprecationWarnings(bool ignoreDeprecationWarnings);
- /** Shows a deprecation warning */
- static void ShowDeprecationWarning(const char* method,const char* prop);
// setting / getting flags
inline void SetSelected(bool bSelected) { m_ValFlags.Selected = bSelected; }
@@ -353,7 +349,6 @@ private:
ValueFlags m_ValFlags; // Frequently used flags in a bitfield (low memoryusage)
int m_refcount; // Reference Counter
static double m_sZeroVec[3];
- static bool m_ignore_deprecation_warnings;
};
diff --git a/source/gameengine/GameLogic/Joystick/SCA_Joystick.cpp b/source/gameengine/GameLogic/Joystick/SCA_Joystick.cpp
index e8e29fb2769..18d7b6ffcd0 100644
--- a/source/gameengine/GameLogic/Joystick/SCA_Joystick.cpp
+++ b/source/gameengine/GameLogic/Joystick/SCA_Joystick.cpp
@@ -24,18 +24,14 @@
*
* ***** END GPL LICENSE BLOCK *****
*/
-#ifndef DISABLE_SDL
#include <SDL.h>
-#endif
-
-#include <stdio.h>
#include "SCA_Joystick.h"
#include "SCA_JoystickPrivate.h"
-SCA_Joystick::SCA_Joystick(short int index)
+
+SCA_Joystick::SCA_Joystick()
:
- m_joyindex(index),
m_axis10(0),
m_axis11(0),
m_axis20(0),
@@ -44,100 +40,106 @@ SCA_Joystick::SCA_Joystick(short int index)
m_buttonnum(-2),
m_hatdir(-2),
m_isinit(0),
- m_istrig_axis(0),
- m_istrig_button(0),
- m_istrig_hat(0),
- m_axismax(-1),
- m_buttonmax(-1),
- m_hatmax(-1)
+ m_istrig(0)
{
-#ifndef DISABLE_SDL
m_private = new PrivateData();
-#endif
}
SCA_Joystick::~SCA_Joystick()
{
-#ifndef DISABLE_SDL
delete m_private;
-#endif
}
-SCA_Joystick *SCA_Joystick::m_instance[JOYINDEX_MAX];
+SCA_Joystick *SCA_Joystick::m_instance = NULL;
int SCA_Joystick::m_refCount = 0;
-SCA_Joystick *SCA_Joystick::GetInstance( short int joyindex )
+SCA_Joystick *SCA_Joystick::GetInstance()
{
-#ifdef DISABLE_SDL
- return NULL;
-#else
- if (joyindex < 0 || joyindex >= JOYINDEX_MAX) {
- echo("Error-invalid joystick index: " << joyindex);
- return NULL;
- }
-
- if (m_refCount == 0)
+ if (m_instance == 0)
{
- int i;
- // do this once only
- if(SDL_InitSubSystem(SDL_INIT_JOYSTICK | SDL_INIT_VIDEO ) == -1 ){
- echo("Error-Initializing-SDL: " << SDL_GetError());
- return NULL;
- }
- for (i=0; i<JOYINDEX_MAX; i++) {
- m_instance[i] = new SCA_Joystick(i);
- m_instance[i]->CreateJoystickDevice();
- }
+ m_instance = new SCA_Joystick();
+ m_instance->CreateJoystickDevice();
m_refCount = 1;
}
else
{
m_refCount++;
}
- return m_instance[joyindex];
-#endif
+ return m_instance;
}
void SCA_Joystick::ReleaseInstance()
{
if (--m_refCount == 0)
{
-#ifndef DISABLE_SDL
- int i;
- for (i=0; i<JOYINDEX_MAX; i++) {
- if (m_instance[i]) {
- m_instance[i]->DestroyJoystickDevice();
- delete m_instance[i];
+ DestroyJoystickDevice();
+ delete m_instance;
+ m_instance = NULL;
+ }
+}
+
+
+bool SCA_Joystick::CreateJoystickDevice()
+{
+ bool init = false;
+ init = pCreateJoystickDevice();
+ return init;
+}
+
+
+void SCA_Joystick::DestroyJoystickDevice()
+{
+ if(m_isinit)
+ pDestroyJoystickDevice();
+}
+
+
+void SCA_Joystick::HandleEvents()
+{
+ if(m_isinit)
+ {
+ if(SDL_PollEvent(&m_private->m_event))
+ {
+ switch(m_private->m_event.type)
+ {
+ case SDL_JOYAXISMOTION:
+ HANDLE_AXISMOTION(OnAxisMotion);
+ break;
+ case SDL_JOYHATMOTION:
+ HANDLE_HATMOTION(OnHatMotion);
+ break;
+ case SDL_JOYBUTTONUP:
+ HANDLE_BUTTONUP(OnButtonUp);
+ break;
+ case SDL_JOYBUTTONDOWN:
+ HANDLE_BUTTONDOWN(OnButtonDown);
+ break;
+ case SDL_JOYBALLMOTION:
+ HANDLE_BALLMOTION(OnBallMotion);
+ break;
+ default:
+ HANDLE_NOEVENT(OnNothing);
+ break;
}
- m_instance[i]= NULL;
}
-
- SDL_QuitSubSystem(SDL_INIT_JOYSTICK | SDL_INIT_VIDEO );
-#endif
}
}
+
void SCA_Joystick::cSetPrecision(int val)
{
m_prec = val;
}
-bool SCA_Joystick::aAnyAxisIsPositive(int axis)
-{
- bool result;
- int res = pAxisTest(axis);
- res > m_prec? result = true: result = false;
- return result;
-}
-
bool SCA_Joystick::aRightAxisIsPositive(int axis)
{
bool result;
int res = pGetAxis(axis,1);
res > m_prec? result = true: result = false;
+ m_istrig = result;
return result;
}
@@ -147,6 +149,7 @@ bool SCA_Joystick::aUpAxisIsPositive(int axis)
bool result;
int res = pGetAxis(axis,0);
res < -m_prec? result = true : result = false;
+ m_istrig = result;
return result;
}
@@ -156,6 +159,7 @@ bool SCA_Joystick::aLeftAxisIsPositive(int axis)
bool result;
int res = pGetAxis(axis,1);
res < -m_prec ? result = true : result = false;
+ m_istrig = result;
return result;
}
@@ -165,40 +169,26 @@ bool SCA_Joystick::aDownAxisIsPositive(int axis)
bool result;
int res = pGetAxis(axis,0);
res > m_prec ? result = true:result = false;
+ m_istrig = result;
return result;
}
-bool SCA_Joystick::aAnyButtonPressIsPositive(void)
-{
- return (m_buttonnum==-2) ? false : true;
-}
-
-bool SCA_Joystick::aAnyButtonReleaseIsPositive(void)
-{
- return (m_buttonnum==-2) ? true : false;
-}
bool SCA_Joystick::aButtonPressIsPositive(int button)
{
-#ifdef DISABLE_SDL
- return false;
-#else
bool result;
SDL_JoystickGetButton(m_private->m_joystick, button)? result = true:result = false;
+ m_istrig = result;
return result;
-#endif
}
bool SCA_Joystick::aButtonReleaseIsPositive(int button)
{
-#ifdef DISABLE_SDL
- return false;
-#else
bool result;
SDL_JoystickGetButton(m_private->m_joystick, button)? result = false : result = true;
+ m_istrig = result;
return result;
-#endif
}
@@ -207,9 +197,27 @@ bool SCA_Joystick::aHatIsPositive(int dir)
bool result;
int res = pGetHat(dir);
res == dir? result = true : result = false;
+ m_istrig = result;
return result;
}
+
+int SCA_Joystick::pGetButtonPress(int button)
+{
+ if(button == m_buttonnum)
+ return m_buttonnum;
+ return -2;
+}
+
+
+int SCA_Joystick::pGetButtonRelease(int button)
+{
+ if(button == m_buttonnum)
+ return m_buttonnum;
+ return -2;
+}
+
+
int SCA_Joystick::pGetHat(int direction)
{
if(direction == m_hatdir){
@@ -218,121 +226,174 @@ int SCA_Joystick::pGetHat(int direction)
return 0;
}
+
+bool SCA_Joystick::GetJoyAxisMotion()
+{
+ bool result = false;
+ if(m_isinit){
+ if(SDL_PollEvent(&m_private->m_event)){
+ switch(m_private->m_event.type)
+ {
+ case SDL_JOYAXISMOTION:
+ result = true;
+ break;
+ }
+ }
+ }
+ return result;
+}
+
+
+bool SCA_Joystick::GetJoyButtonPress()
+{
+ bool result = false;
+ if(m_isinit){
+ if(SDL_PollEvent(&m_private->m_event)){
+ switch(m_private->m_event.type)
+ {
+ case SDL_JOYBUTTONDOWN:
+ result = true;
+ break;
+ }
+ }
+ }
+ return result;
+}
+
+
+bool SCA_Joystick::GetJoyButtonRelease()
+{
+ bool result = false;
+ if(m_isinit)
+ {
+ if(SDL_PollEvent(&m_private->m_event)){
+ switch(m_private->m_event.type)
+ {
+ case SDL_JOYBUTTONUP:
+ result = true;
+ break;
+ }
+ }
+ }
+ return result;
+}
+
+
+bool SCA_Joystick::GetJoyHatMotion()
+{
+ bool result = false;
+ if(m_isinit){
+ if(SDL_PollEvent(&m_private->m_event)){
+ switch(m_private->m_event.type)
+ {
+ case SDL_JOYHATMOTION:
+ result = true;
+ break;
+ }
+ }
+ }
+ return 0;
+}
+
+
int SCA_Joystick::GetNumberOfAxes()
{
- return m_axismax;
+ int number;
+ if(m_isinit){
+ if(m_private->m_joystick){
+ number = SDL_JoystickNumAxes(m_private->m_joystick);
+ return number;
+ }
+ }
+ return -1;
}
int SCA_Joystick::GetNumberOfButtons()
{
- return m_buttonmax;
+ int number;
+ if(m_isinit){
+ if(m_private->m_joystick){
+ number = SDL_JoystickNumButtons(m_private->m_joystick);
+ return number;
+ }
+ }
+ return -1;
}
int SCA_Joystick::GetNumberOfHats()
{
- return m_hatmax;
+ int number;
+ if(m_isinit){
+ if(m_private->m_joystick){
+ number = SDL_JoystickNumHats(m_private->m_joystick);
+ return number;
+ }
+ }
+ return -1;
}
-bool SCA_Joystick::CreateJoystickDevice(void)
+bool SCA_Joystick::pCreateJoystickDevice()
{
-#ifdef DISABLE_SDL
- return false;
-#else
if(m_isinit == false){
- if (m_joyindex>=SDL_NumJoysticks()) {
- // don't print a message, because this is done anyway
- //echo("Joystick-Error: " << SDL_NumJoysticks() << " avaiable joystick(s)");
+ if(SDL_InitSubSystem(SDL_INIT_JOYSTICK | SDL_INIT_VIDEO ) == -1 ){
+ echo("Error-Initializing-SDL: " << SDL_GetError());
+ return false;
+ }
+ if(SDL_NumJoysticks() > 0){
+ for(int i=0; i<SDL_NumJoysticks();i++){
+ m_private->m_joystick = SDL_JoystickOpen(i);
+ SDL_JoystickEventState(SDL_ENABLE);
+ m_numjoys = i;
+ }
+ echo("Joystick-initialized");
+ m_isinit = true;
+ return true;
+ }else{
+ echo("Joystick-Error: " << SDL_NumJoysticks() << " avaiable joystick(s)");
return false;
}
-
- m_private->m_joystick = SDL_JoystickOpen(m_joyindex);
- SDL_JoystickEventState(SDL_ENABLE);
- m_isinit = true;
-
- 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);
}
- return true;
-#endif
+ return false;
}
-void SCA_Joystick::DestroyJoystickDevice(void)
+void SCA_Joystick::pDestroyJoystickDevice()
{
-#ifndef DISABLE_SDL
- if (m_isinit){
- if(SDL_JoystickOpened(m_joyindex)){
- echo("Closing-joystick " << m_joyindex);
+ echo("Closing-");
+ for(int i=0; i<SDL_NumJoysticks(); i++){
+ if(SDL_JoystickOpened(i)){
SDL_JoystickClose(m_private->m_joystick);
}
- m_isinit = false;
}
-#endif
+ SDL_QuitSubSystem(SDL_INIT_JOYSTICK | SDL_INIT_VIDEO );
}
-int SCA_Joystick::Connected(void)
-{
-#ifndef DISABLE_SDL
- if (m_isinit && SDL_JoystickOpened(m_joyindex))
- return 1;
-#endif
- return 0;
-}
void SCA_Joystick::pFillAxes()
{
-#ifndef DISABLE_SDL
- if(m_axismax == 1){
+ if(GetNumberOfAxes() == 1){
m_axis10 = SDL_JoystickGetAxis(m_private->m_joystick, 0);
m_axis11 = SDL_JoystickGetAxis(m_private->m_joystick, 1);
- }else if(m_axismax > 1){
+ }else if(GetNumberOfAxes() > 1){
m_axis10 = SDL_JoystickGetAxis(m_private->m_joystick, 0);
m_axis11 = SDL_JoystickGetAxis(m_private->m_joystick, 1);
m_axis20 = SDL_JoystickGetAxis(m_private->m_joystick, 2);
m_axis21 = SDL_JoystickGetAxis(m_private->m_joystick, 3);
}else{
- m_axis10 = m_axis11 = m_axis20 = m_axis21 = 0;
+ m_axis10 = 0;m_axis11 = 0;
+ m_axis20 = 0;m_axis21 = 0;
}
-#endif
}
int SCA_Joystick::pGetAxis(int axisnum, int udlr)
{
-#ifndef DISABLE_SDL
if(axisnum == 1 && udlr == 1)return m_axis10; //u/d
if(axisnum == 1 && udlr == 0)return m_axis11; //l/r
if(axisnum == 2 && udlr == 0)return m_axis20; //...
if(axisnum == 2 && udlr == 1)return m_axis21;
-#endif
- return 0;
-}
-
-int SCA_Joystick::pAxisTest(int axisnum)
-{
-#ifndef DISABLE_SDL
- short i1,i2;
- if(axisnum == 1) {
- i1 = m_axis10; i2 = m_axis11;
- }
- else if(axisnum == 2) {
- i1 = m_axis20; i2 = m_axis21;
- }
- /* long winded way to do
- * return MAX2(abs(i1), abs(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
return 0;
-#endif
}
diff --git a/source/gameengine/GameLogic/Joystick/SCA_Joystick.h b/source/gameengine/GameLogic/Joystick/SCA_Joystick.h
index 8335d5538ad..1e853070b09 100644
--- a/source/gameengine/GameLogic/Joystick/SCA_Joystick.h
+++ b/source/gameengine/GameLogic/Joystick/SCA_Joystick.h
@@ -1,39 +1,72 @@
/**
+
* ***** BEGIN GPL LICENSE BLOCK *****
+
*
+
* This program is free software; you can redistribute it and/or
+
* modify it under the terms of the GNU General Public License
+
* as published by the Free Software Foundation; either version 2
+
* of the License, or (at your option) any later version.
+
+
+
+
*
+
* This program is distributed in the hope that it will be useful,
+
* but WITHOUT ANY WARRANTY; without even the implied warranty of
+
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+
* GNU General Public License for more details.
+
*
+
* You should have received a copy of the GNU General Public License
+
* along with this program; if not, write to the Free Software Foundation,
+
* Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
*
+
* The 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 *****
+
*/
#ifndef _SCA_JOYSTICK_H_
+
#define _SCA_JOYSTICK_H_
+
+
#include "SCA_JoystickDefines.h"
-#ifndef DISABLE_SDL
-#include "SDL.h"
-#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.
@@ -43,147 +76,235 @@
class SCA_Joystick
{
- static SCA_Joystick *m_instance[JOYINDEX_MAX];
+ static SCA_Joystick *m_instance;
static int m_refCount;
class PrivateData;
-#ifndef DISABLE_SDL
+
PrivateData *m_private;
-#endif
+
int m_joyindex;
+ /*!
+
+ * the number of avail joysticks
+
+ */
+
+ int m_numjoys;
+
/*
+
*support for 2 axes
+
*/
int m_axis10,m_axis11;
+
int m_axis20,m_axis21;
- /*
+ /*
+
* Precision or range of the axes
+
*/
+
int m_prec;
/*
+
* multiple axis values stored here
+
*/
+
int m_axisnum;
+
int m_axisvalue;
/*
+
* max # of axes avail
+
*/
+
/*disabled
+
int m_axismax;
+
*/
/*
+
* button values stored here
+
*/
+
int m_buttonnum;
/*
+
* max # of buttons avail
+
*/
-
- int m_axismax;
+
int m_buttonmax;
- int m_hatmax;
-
- /*
+
+ /*
+
* hat values stored here
+
*/
+
int m_hatnum;
+
int m_hatdir;
/*
* max # of hats avail
+
disabled
+
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;
-#ifndef DISABLE_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);
- void OnBallMotion(SDL_Event *sdl_event){}
-#endif
+ /* is triggered */
+
+ bool m_istrig;
+
/*
+
* Open the joystick
+
*/
- bool CreateJoystickDevice(void);
+
+ bool pCreateJoystickDevice(void);
/*
+
* Close the joystick
+
*/
- void DestroyJoystickDevice(void);
+
+ void pDestroyJoystickDevice(void);
+
+
+
+ /*
+
+ * event callbacks
+
+ */
+
+ void OnAxisMotion(void);
+
+ void OnHatMotion(void);
+
+ void OnButtonUp(void);
+
+ void OnButtonDown(void);
+
+ void OnNothing(void);
+
+ void OnBallMotion(void){}
/*
+
* fills the axis mnember values
+
*/
+
void pFillAxes(void);
+
+
+
void pFillButtons(void);
/*
+
* returns m_axis10,m_axis11...
+
+ */
+
+ int pGetAxis(int axisnum, int udlr);
+
+ /*
+
+ * gets the current button
+
*/
- int pAxisTest(int axisnum);
+ int pGetButtonPress(int button);
+
/*
- * returns m_axis10,m_axis11...
+
+ * returns if no button is pressed
+
*/
- int pGetAxis(int axisnum, int udlr);
+
+ int pGetButtonRelease(int button);
/*
+
* gets the current hat direction
+
*/
+
int pGetHat(int direction);
- SCA_Joystick(short int index);
+ SCA_Joystick();
~SCA_Joystick();
+ bool CreateJoystickDevice(void);
+
+ void DestroyJoystickDevice(void);
+
+
public:
- static SCA_Joystick *GetInstance( short int joyindex );
- static void HandleEvents( void );
+ static SCA_Joystick *GetInstance();
+
void ReleaseInstance();
+ void HandleEvents();
+
/*
+
*/
- bool aAnyAxisIsPositive(int axis);
+
bool aUpAxisIsPositive(int axis);
+
bool aDownAxisIsPositive(int axis);
+
bool aLeftAxisIsPositive(int axis);
+
bool aRightAxisIsPositive(int axis);
- bool aAnyButtonPressIsPositive(void);
- bool aAnyButtonReleaseIsPositive(void);
bool aButtonPressIsPositive(int button);
+
bool aButtonReleaseIsPositive(int button);
+
bool aHatIsPositive(int dir);
/*
+
* precision is default '3200' which is overridden by input
+
*/
void cSetPrecision(int val);
+
+
int GetAxis10(void){
return m_axis10;
@@ -191,57 +312,80 @@ public:
}
int GetAxis11(void){
+
return m_axis11;
+
}
int GetAxis20(void){
+
return m_axis20;
+
}
int GetAxis21(void){
+
return m_axis21;
+
}
int GetButton(void){
+
return m_buttonnum;
+
}
int GetHat(void){
+
return m_hatdir;
+
}
int GetThreshold(void){
+
return m_prec;
- }
- bool IsTrigAxis(void){
- return m_istrig_axis;
}
-
- bool IsTrigButton(void){
- return m_istrig_button;
+
+ bool IsTrig(void){
+
+ return m_istrig;
+
}
+
- bool IsTrigHat(void){
- return m_istrig_hat;
- }
/*
+
+ * returns true if an event is being processed
+
+ */
+
+ bool GetJoyAxisMotion(void);
+
+ bool GetJoyButtonPress(void);
+
+ bool GetJoyButtonRelease(void);
+
+ bool GetJoyHatMotion(void);
+
+ /*
+
* returns the # of...
+
*/
int GetNumberOfAxes(void);
+
int GetNumberOfButtons(void);
+
int GetNumberOfHats(void);
+
- /*
- * Test if the joystick is connected
- */
- int Connected(void);
+
};
-#ifndef DISABLE_SDL
-void Joystick_HandleEvents( void );
-#endif
+
+
#endif
diff --git a/source/gameengine/GameLogic/Joystick/SCA_JoystickDefines.h b/source/gameengine/GameLogic/Joystick/SCA_JoystickDefines.h
index 73ffe1406d9..15a421188b9 100644
--- a/source/gameengine/GameLogic/Joystick/SCA_JoystickDefines.h
+++ b/source/gameengine/GameLogic/Joystick/SCA_JoystickDefines.h
@@ -38,6 +38,12 @@
#define echo(x) std::cout << x << std::endl;
#endif
-#define JOYINDEX_MAX 8
+/* function callbacks */
+#define HANDLE_AXISMOTION(fn) ((fn)(), 0L)
+#define HANDLE_HATMOTION(fn) ((fn)(), 0L)
+#define HANDLE_BUTTONUP(fn) ((fn)(), 0L)
+#define HANDLE_BUTTONDOWN(fn) ((fn)(), 0L)
+#define HANDLE_BALLMOTION(fn) ((fn)(), 0L)
+#define HANDLE_NOEVENT(fn) ((fn)(), 0L)
#endif
diff --git a/source/gameengine/GameLogic/Joystick/SCA_JoystickEvents.cpp b/source/gameengine/GameLogic/Joystick/SCA_JoystickEvents.cpp
index 73ca288861d..ab523470e21 100644
--- a/source/gameengine/GameLogic/Joystick/SCA_JoystickEvents.cpp
+++ b/source/gameengine/GameLogic/Joystick/SCA_JoystickEvents.cpp
@@ -24,100 +24,47 @@
*
* ***** END GPL LICENSE BLOCK *****
*/
-#ifndef DISABLE_SDL
#include <SDL.h>
-#endif
-
#include "SCA_Joystick.h"
#include "SCA_JoystickPrivate.h"
-#ifndef DISABLE_SDL
-void SCA_Joystick::OnAxisMotion(SDL_Event* sdl_event)
+
+void SCA_Joystick::OnAxisMotion(void)
{
pFillAxes();
- m_axisnum = sdl_event->jaxis.axis;
- m_axisvalue = sdl_event->jaxis.value;
- m_istrig_axis = 1;
+ m_axisnum = m_private->m_event.jaxis.axis;
+ m_axisvalue = m_private->m_event.jaxis.value;
+ m_istrig = 1;
}
-void SCA_Joystick::OnHatMotion(SDL_Event* sdl_event)
+void SCA_Joystick::OnHatMotion(void)
{
- m_hatdir = sdl_event->jhat.value;
- m_hatnum = sdl_event->jhat.hat;
- m_istrig_hat = 1;
+ m_hatdir = m_private->m_event.jhat.value;
+ m_hatnum = m_private->m_event.jhat.hat;
+ m_istrig = 1;
}
-void SCA_Joystick::OnButtonUp(SDL_Event* sdl_event)
+
+void SCA_Joystick::OnButtonUp(void)
{
- m_istrig_button = 1;
-
- /* this is needed for the "all events" option
- * so we know if there are no buttons pressed */
- int i;
- for (i=0; i<m_buttonmax; i++) {
- if (SDL_JoystickGetButton(m_private->m_joystick, i)) {
- m_buttonnum = i;
- return;
- }
- }
m_buttonnum = -2;
}
-void SCA_Joystick::OnButtonDown(SDL_Event* sdl_event)
+void SCA_Joystick::OnButtonDown(void)
{
- if(sdl_event->jbutton.button >= 0 || sdl_event->jbutton.button <= m_buttonmax)
+ m_buttonmax = GetNumberOfButtons();
+ if(m_private->m_event.jbutton.button >= 1 || m_private->m_event.jbutton.button <= m_buttonmax)
{
- m_istrig_button = 1;
- m_buttonnum = sdl_event->jbutton.button;
+ m_istrig = 1;
+ m_buttonnum = m_private->m_event.jbutton.button;
}
}
-void SCA_Joystick::OnNothing(SDL_Event* sdl_event)
+void SCA_Joystick::OnNothing(void)
{
- m_istrig_axis = m_istrig_button = m_istrig_hat = 0;
-}
-
-/* only handle events for 1 joystick */
-
-void SCA_Joystick::HandleEvents(void)
-{
- SDL_Event sdl_event;
-
- int i;
- for (i=0; i<JOYINDEX_MAX; i++) {
- if(SCA_Joystick::m_instance[i])
- SCA_Joystick::m_instance[i]->OnNothing(&sdl_event);
- }
-
- if(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? */
- 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;
- case SDL_JOYBALLMOTION:
- SCA_Joystick::m_instance[sdl_event.jball.which]->OnBallMotion(&sdl_event);
- break;
- default:
- printf("SCA_Joystick::HandleEvents, Unknown SDL event, this should not happen\n");
- break;
- }
- }
+ m_istrig = 0;
}
-#endif
diff --git a/source/gameengine/GameLogic/Joystick/SCA_JoystickPrivate.h b/source/gameengine/GameLogic/Joystick/SCA_JoystickPrivate.h
index acbbcae9cd7..23fad3cd55d 100644
--- a/source/gameengine/GameLogic/Joystick/SCA_JoystickPrivate.h
+++ b/source/gameengine/GameLogic/Joystick/SCA_JoystickPrivate.h
@@ -29,11 +29,14 @@
#define __SCA_JOYSTICKPRIVATE_H__
#include "SCA_Joystick.h"
-#ifndef DISABLE_SDL
class SCA_Joystick::PrivateData
{
public:
/*
+ * SDL events structure
+ */
+ SDL_Event m_event;
+ /*
* The Joystick
*/
SDL_Joystick* m_joystick;
@@ -44,5 +47,3 @@ public:
}
};
#endif
-
-#endif
diff --git a/source/gameengine/GameLogic/Makefile b/source/gameengine/GameLogic/Makefile
index 355ece6e8bd..b3eae5d67dc 100644
--- a/source/gameengine/GameLogic/Makefile
+++ b/source/gameengine/GameLogic/Makefile
@@ -42,7 +42,6 @@ CPPFLAGS += -I../Expressions
CPPFLAGS += -I../Rasterizer
CPPFLAGS += -I$(NAN_STRING)/include
CPPFLAGS += -I$(NAN_MOTO)/include
-CPPFLAGS += -I../../blender/makesdna
CPPFLAGS += -I$(NAN_PYTHON)/include/python$(NAN_PYTHON_VERSION)
CPPFLAGS += $(NAN_SDLCFLAGS)
diff --git a/source/gameengine/GameLogic/SCA_2DFilterActuator.cpp b/source/gameengine/GameLogic/SCA_2DFilterActuator.cpp
index 9ec4ea00337..96a770a553f 100644
--- a/source/gameengine/GameLogic/SCA_2DFilterActuator.cpp
+++ b/source/gameengine/GameLogic/SCA_2DFilterActuator.cpp
@@ -23,8 +23,8 @@ SCA_2DFilterActuator::SCA_2DFilterActuator(
: SCA_IActuator(gameobj, T),
m_type(type),
m_flag(flag),
- m_float_arg(float_arg),
m_int_arg(int_arg),
+ m_float_arg(float_arg),
m_rasterizer(rasterizer),
m_rendertools(rendertools)
{
@@ -64,11 +64,13 @@ bool SCA_2DFilterActuator::Update()
if( m_type == RAS_2DFilterManager::RAS_2DFILTER_MOTIONBLUR )
{
if(!m_flag)
+ {
m_rasterizer->EnableMotionBlur(m_float_arg);
+ }
else
+ {
m_rasterizer->DisableMotionBlur();
-
- return false;
+ }
}
else if(m_type < RAS_2DFilterManager::RAS_2DFILTER_NUMBER_OF_FILTERS)
{
diff --git a/source/gameengine/GameLogic/SCA_ActuatorSensor.cpp b/source/gameengine/GameLogic/SCA_ActuatorSensor.cpp
index 5ad28dbf329..099cb8eebd0 100644
--- a/source/gameengine/GameLogic/SCA_ActuatorSensor.cpp
+++ b/source/gameengine/GameLogic/SCA_ActuatorSensor.cpp
@@ -149,61 +149,38 @@ PyParentObject SCA_ActuatorSensor::Parents[] = {
};
PyMethodDef SCA_ActuatorSensor::Methods[] = {
- //Deprecated functions ------>
- {"getActuator", (PyCFunction) SCA_ActuatorSensor::sPyGetActuator, METH_NOARGS, (PY_METHODCHAR)GetActuator_doc},
- {"setActuator", (PyCFunction) SCA_ActuatorSensor::sPySetActuator, METH_VARARGS, (PY_METHODCHAR)SetActuator_doc},
- //<----- Deprecated
+ {"getActuator", (PyCFunction) SCA_ActuatorSensor::sPyGetActuator, METH_NOARGS, GetActuator_doc},
+ {"setActuator", (PyCFunction) SCA_ActuatorSensor::sPySetActuator, METH_VARARGS, SetActuator_doc},
{NULL,NULL} //Sentinel
};
PyObject* SCA_ActuatorSensor::_getattr(const STR_String& attr) {
- if (attr == "actuator") {
- return PyString_FromString(m_checkactname);
- }
_getattr_up(SCA_ISensor); /* implicit return! */
}
-int SCA_ActuatorSensor::_setattr(const STR_String& attr, PyObject *value) {
- if (PyString_Check(value)) {
- char* sval = PyString_AsString(value);
- if (attr == "actuator") {
- SCA_IActuator* act = GetParent()->FindActuator(STR_String(sval));
- if (act) {
- m_checkactname = sval;
- m_actuator = act;
- return 0;
- }
- PyErr_SetString(PyExc_AttributeError, "string does not correspond to an actuator");
- return 1;
- }
- }
- return SCA_ISensor::_setattr(attr, value);
-}
-
/* 3. getActuator */
-const char SCA_ActuatorSensor::GetActuator_doc[] =
+char SCA_ActuatorSensor::GetActuator_doc[] =
"getActuator()\n"
"\tReturn the Actuator with which the sensor operates.\n";
PyObject* SCA_ActuatorSensor::PyGetActuator(PyObject* self)
{
- ShowDeprecationWarning("getActuator()", "the actuator property");
return PyString_FromString(m_checkactname);
}
/* 4. setActuator */
-const char SCA_ActuatorSensor::SetActuator_doc[] =
+char SCA_ActuatorSensor::SetActuator_doc[] =
"setActuator(name)\n"
"\t- name: string\n"
"\tSets the Actuator with which to operate. If there is no Actuator\n"
"\tof this name, the call is ignored.\n";
PyObject* SCA_ActuatorSensor::PySetActuator(PyObject* self, PyObject* args, PyObject* kwds)
{
- ShowDeprecationWarning("setActuator()", "the actuator property");
/* We should query whether the name exists. Or should we create a prop */
/* on the fly? */
char *actNameArg = NULL;
if (!PyArg_ParseTuple(args, "s", &actNameArg)) {
+ PyErr_SetString(PyExc_TypeError, "Invalid arguments");
return NULL;
}
diff --git a/source/gameengine/GameLogic/SCA_ActuatorSensor.h b/source/gameengine/GameLogic/SCA_ActuatorSensor.h
index 4fe4700602c..a71145f6852 100644
--- a/source/gameengine/GameLogic/SCA_ActuatorSensor.h
+++ b/source/gameengine/GameLogic/SCA_ActuatorSensor.h
@@ -62,7 +62,6 @@ public:
/* --------------------------------------------------------------------- */
virtual PyObject* _getattr(const STR_String& attr);
- virtual int _setattr(const STR_String& attr, PyObject *value);
/* 3. setProperty */
KX_PYMETHOD_DOC(SCA_ActuatorSensor,SetActuator);
diff --git a/source/gameengine/GameLogic/SCA_DelaySensor.cpp b/source/gameengine/GameLogic/SCA_DelaySensor.cpp
deleted file mode 100644
index 362483b58a2..00000000000
--- a/source/gameengine/GameLogic/SCA_DelaySensor.cpp
+++ /dev/null
@@ -1,302 +0,0 @@
-/**
- * Delay trigger
- *
- * $Id$
- *
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-#ifdef HAVE_CONFIG_H
-#include <config.h>
-#endif
-
-#ifdef WIN32
-// 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_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,
- PyTypeObject* T)
- : SCA_ISensor(gameobj,eventmgr, T),
- m_delay(delay),
- m_duration(duration),
- m_repeat(repeat)
-{
- 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...
- CValue::AddDataToReplica(replica);
-
- return replica;
-}
-
-
-
-bool SCA_DelaySensor::IsPositiveTrigger()
-{
- return (m_invert ? !m_lastResult : m_lastResult);
-}
-
-bool SCA_DelaySensor::Evaluate(CValue* event)
-{
- 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;
-}
-
-/* ------------------------------------------------------------------------- */
-/* Python functions */
-/* ------------------------------------------------------------------------- */
-
-/* Integration hooks ------------------------------------------------------- */
-PyTypeObject SCA_DelaySensor::Type = {
- PyObject_HEAD_INIT(&PyType_Type)
- 0,
- "SCA_DelaySensor",
- sizeof(SCA_DelaySensor),
- 0,
- PyDestructor,
- 0,
- __getattr,
- __setattr,
- 0, //&MyPyCompare,
- __repr,
- 0, //&cvalue_as_number,
- 0,
- 0,
- 0,
- 0
-};
-
-PyParentObject SCA_DelaySensor::Parents[] = {
- &SCA_DelaySensor::Type,
- &SCA_ISensor::Type,
- &SCA_ILogicBrick::Type,
- &CValue::Type,
- NULL
-};
-
-PyMethodDef SCA_DelaySensor::Methods[] = {
- //Deprecated functions ------>
- /* setProperty */
- {"setDelay", (PyCFunction) SCA_DelaySensor::sPySetDelay, METH_VARARGS, (PY_METHODCHAR)SetDelay_doc},
- {"setDuration", (PyCFunction) SCA_DelaySensor::sPySetDuration, METH_VARARGS, (PY_METHODCHAR)SetDuration_doc},
- {"setRepeat", (PyCFunction) SCA_DelaySensor::sPySetRepeat, METH_VARARGS, (PY_METHODCHAR)SetRepeat_doc},
- /* getProperty */
- {"getDelay", (PyCFunction) SCA_DelaySensor::sPyGetDelay, METH_NOARGS, (PY_METHODCHAR)GetDelay_doc},
- {"getDuration", (PyCFunction) SCA_DelaySensor::sPyGetDuration, METH_NOARGS, (PY_METHODCHAR)GetDuration_doc},
- {"getRepeat", (PyCFunction) SCA_DelaySensor::sPyGetRepeat, METH_NOARGS, (PY_METHODCHAR)GetRepeat_doc},
- //<----- Deprecated
- {NULL,NULL} //Sentinel
-};
-
-PyObject* SCA_DelaySensor::_getattr(const STR_String& attr) {
- if (attr == "delay") {
- return PyInt_FromLong(m_delay);
- }
- if (attr == "duration") {
- return PyInt_FromLong(m_duration);
- }
- if (attr == "repeat") {
- return PyInt_FromLong(m_repeat);
- }
- _getattr_up(SCA_ISensor);
-}
-
-int SCA_DelaySensor::_setattr(const STR_String& attr, PyObject *value) {
- if (PyInt_Check(value)) {
- int ival = PyInt_AsLong(value);
- if (attr == "delay") {
- if (ival < 0) {
- PyErr_SetString(PyExc_ValueError, "Delay cannot be negative");
- return 1;
- }
- m_delay = ival;
- return 0;
- }
- if (attr == "duration") {
- if (ival < 0) {
- PyErr_SetString(PyExc_ValueError, "Duration cannot be negative");
- return 1;
- }
- m_duration = ival;
- return 0;
- }
- if (attr == "repeat") {
- m_repeat = (ival != 0);
- return 0;
- }
- }
- return SCA_ISensor::_setattr(attr, value);
-}
-
-
-const char SCA_DelaySensor::SetDelay_doc[] =
-"setDelay(delay)\n"
-"\t- delay: length of the initial OFF period as number of frame\n"
-"\t 0 for immediate trigger\n"
-"\tSet the initial delay before the positive trigger\n";
-PyObject* SCA_DelaySensor::PySetDelay(PyObject* self, PyObject* args, PyObject* kwds)
-{
- ShowDeprecationWarning("setDelay()", "the delay property");
- int delay;
-
- if(!PyArg_ParseTuple(args, "i", &delay)) {
- return NULL;
- }
- if (delay < 0) {
- PyErr_SetString(PyExc_ValueError, "Delay cannot be negative");
- return NULL;
- }
- m_delay = delay;
- Py_Return;
-}
-
-const char SCA_DelaySensor::SetDuration_doc[] =
-"setDuration(duration)\n"
-"\t- duration: length of the ON period in number of frame after the initial off period\n"
-"\t 0 for no ON period\n"
-"\tSet the duration of the ON pulse after initial delay.\n"
-"\tIf > 0, a negative trigger is fired at the end of the ON pulse.\n";
-PyObject* SCA_DelaySensor::PySetDuration(PyObject* self, PyObject* args, PyObject* kwds)
-{
- ShowDeprecationWarning("setDuration()", "the duration property");
- int duration;
-
- if(!PyArg_ParseTuple(args, "i", &duration)) {
- return NULL;
- }
- if (duration < 0) {
- PyErr_SetString(PyExc_ValueError, "Duration cannot be negative");
- return NULL;
- }
- m_duration = duration;
- Py_Return;
-}
-
-const char SCA_DelaySensor::SetRepeat_doc[] =
-"setRepeat(repeat)\n"
-"\t- repeat: 1 if the initial OFF-ON cycle should be repeated indefinately\n"
-"\t 0 if the initial OFF-ON cycle should run only once\n"
-"\tSet the sensor repeat mode\n";
-PyObject* SCA_DelaySensor::PySetRepeat(PyObject* self, PyObject* args, PyObject* kwds)
-{
- ShowDeprecationWarning("setRepeat()", "the repeat property");
- int repeat;
-
- if(!PyArg_ParseTuple(args, "i", &repeat)) {
- return NULL;
- }
- m_repeat = (repeat != 0);
- Py_Return;
-}
-
-const char SCA_DelaySensor::GetDelay_doc[] =
-"getDelay()\n"
-"\tReturn the delay parameter value\n";
-PyObject* SCA_DelaySensor::PyGetDelay(PyObject* self)
-{
- ShowDeprecationWarning("getDelay()", "the delay property");
- return PyInt_FromLong(m_delay);
-}
-
-const char SCA_DelaySensor::GetDuration_doc[] =
-"getDuration()\n"
-"\tReturn the duration parameter value\n";
-PyObject* SCA_DelaySensor::PyGetDuration(PyObject* self)
-{
- ShowDeprecationWarning("getDuration()", "the duration property");
- return PyInt_FromLong(m_duration);
-}
-
-const char SCA_DelaySensor::GetRepeat_doc[] =
-"getRepeat()\n"
-"\tReturn the repeat parameter value\n";
-PyObject* SCA_DelaySensor::PyGetRepeat(PyObject* self)
-{
- ShowDeprecationWarning("getRepeat()", "the repeat property");
- return BoolToPyArg(m_repeat);
-}
-
-/* eof */
diff --git a/source/gameengine/GameLogic/SCA_DelaySensor.h b/source/gameengine/GameLogic/SCA_DelaySensor.h
deleted file mode 100644
index ff3afe16542..00000000000
--- a/source/gameengine/GameLogic/SCA_DelaySensor.h
+++ /dev/null
@@ -1,78 +0,0 @@
-/**
- * SCA_DelaySensor.h
- *
- * $Id$
- *
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
- *
- * The Original Code is Copyright (C) 2001-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_DELAYSENSOR
-#define __KX_DELAYSENSOR
-#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,
- PyTypeObject* T =&Type);
- virtual ~SCA_DelaySensor();
- virtual CValue* GetReplica();
- virtual bool Evaluate(CValue* event);
- virtual bool IsPositiveTrigger();
- virtual void Init();
-
-
- /* --------------------------------------------------------------------- */
- /* Python interface ---------------------------------------------------- */
- /* --------------------------------------------------------------------- */
-
- virtual PyObject* _getattr(const STR_String& attr);
- virtual int _setattr(const STR_String& attr, PyObject *value);
-
- /* setProperty */
- KX_PYMETHOD_DOC(SCA_DelaySensor,SetDelay);
- KX_PYMETHOD_DOC(SCA_DelaySensor,SetDuration);
- KX_PYMETHOD_DOC(SCA_DelaySensor,SetRepeat);
- /* getProperty */
- KX_PYMETHOD_DOC_NOARGS(SCA_DelaySensor,GetDelay);
- KX_PYMETHOD_DOC_NOARGS(SCA_DelaySensor,GetDuration);
- KX_PYMETHOD_DOC_NOARGS(SCA_DelaySensor,GetRepeat);
-
-};
-
-#endif //__KX_ALWAYSSENSOR
-
diff --git a/source/gameengine/GameLogic/SCA_IController.cpp b/source/gameengine/GameLogic/SCA_IController.cpp
index 0bd20117f31..8f156cc63e7 100644
--- a/source/gameengine/GameLogic/SCA_IController.cpp
+++ b/source/gameengine/GameLogic/SCA_IController.cpp
@@ -188,8 +188,6 @@ void SCA_IController::ApplyState(unsigned int state)
for (sensit = m_linkedsensors.begin();!(sensit==m_linkedsensors.end());++sensit)
{
(*sensit)->IncLink();
- // remember that this controller just activated that sensor
- (*sensit)->AddNewController(this);
}
SetActive(true);
}
diff --git a/source/gameengine/GameLogic/SCA_ILogicBrick.cpp b/source/gameengine/GameLogic/SCA_ILogicBrick.cpp
index 515b485061d..e73358bc1e8 100644
--- a/source/gameengine/GameLogic/SCA_ILogicBrick.cpp
+++ b/source/gameengine/GameLogic/SCA_ILogicBrick.cpp
@@ -27,7 +27,6 @@
*/
#include "SCA_ILogicBrick.h"
-#include "PyObjectPlus.h"
#ifdef HAVE_CONFIG_H
#include <config.h>
@@ -247,7 +246,7 @@ PyParentObject SCA_ILogicBrick::Parents[] = {
PyMethodDef SCA_ILogicBrick::Methods[] = {
{"getOwner", (PyCFunction) SCA_ILogicBrick::sPyGetOwner, METH_NOARGS},
- {"getExecutePriority", (PyCFunction) SCA_ILogicBrick::sPyGetExecutePriority, METH_NOARGS},
+ {"getExecutePriority", (PyCFunction) SCA_ILogicBrick::sPySetExecutePriority, METH_NOARGS},
{"setExecutePriority", (PyCFunction) SCA_ILogicBrick::sPySetExecutePriority, METH_VARARGS},
{NULL,NULL} //Sentinel
};
@@ -272,7 +271,8 @@ PyObject* SCA_ILogicBrick::PyGetOwner(PyObject* self)
}
printf("ERROR: Python scriptblock without owner\n");
- Py_RETURN_NONE; //Int_FromLong(IsPositiveTrigger());
+ Py_INCREF(Py_None);
+ return Py_None;//Int_FromLong(IsPositiveTrigger());
}
diff --git a/source/gameengine/GameLogic/SCA_ISensor.cpp b/source/gameengine/GameLogic/SCA_ISensor.cpp
index 6e46c8504bb..2dc49924062 100644
--- a/source/gameengine/GameLogic/SCA_ISensor.cpp
+++ b/source/gameengine/GameLogic/SCA_ISensor.cpp
@@ -32,8 +32,6 @@
#include "SCA_ISensor.h"
#include "SCA_EventManager.h"
#include "SCA_LogicManager.h"
-// needed for IsTriggered()
-#include "SCA_PythonController.h"
#ifdef HAVE_CONFIG_H
#include <config.h>
@@ -134,16 +132,76 @@ void SCA_ISensor::DecLink() {
}
if (!m_links)
{
- // sensor is detached from all controllers, remove it from manager
+ // sensor is detached from all controllers, initialize it so that it
+ // is fresh as at startup when it is reattached again.
UnregisterToManager();
+ Init();
}
}
+/* python integration */
+
+PyTypeObject SCA_ISensor::Type = {
+ PyObject_HEAD_INIT(&PyType_Type)
+ 0,
+ "SCA_ISensor",
+ sizeof(SCA_ISensor),
+ 0,
+ PyDestructor,
+ 0,
+ __getattr,
+ __setattr,
+ 0, //&MyPyCompare,
+ __repr,
+ 0, //&cvalue_as_number,
+ 0,
+ 0,
+ 0,
+ 0
+};
+
+PyParentObject SCA_ISensor::Parents[] = {
+ &SCA_ISensor::Type,
+ &SCA_ILogicBrick::Type,
+ &CValue::Type,
+ NULL
+};
+PyMethodDef SCA_ISensor::Methods[] = {
+ {"isPositive", (PyCFunction) SCA_ISensor::sPyIsPositive,
+ METH_VARARGS, IsPositive_doc},
+ {"getUsePosPulseMode", (PyCFunction) SCA_ISensor::sPyGetUsePosPulseMode,
+ METH_NOARGS, GetUsePosPulseMode_doc},
+ {"setUsePosPulseMode", (PyCFunction) SCA_ISensor::sPySetUsePosPulseMode,
+ METH_VARARGS, SetUsePosPulseMode_doc},
+ {"getFrequency", (PyCFunction) SCA_ISensor::sPyGetFrequency,
+ METH_NOARGS, GetFrequency_doc},
+ {"setFrequency", (PyCFunction) SCA_ISensor::sPySetFrequency,
+ METH_VARARGS, SetFrequency_doc},
+ {"getUseNegPulseMode", (PyCFunction) SCA_ISensor::sPyGetUseNegPulseMode,
+ METH_NOARGS, GetUseNegPulseMode_doc},
+ {"setUseNegPulseMode", (PyCFunction) SCA_ISensor::sPySetUseNegPulseMode,
+ METH_VARARGS, SetUseNegPulseMode_doc},
+ {"getInvert", (PyCFunction) SCA_ISensor::sPyGetInvert,
+ METH_NOARGS, GetInvert_doc},
+ {"setInvert", (PyCFunction) SCA_ISensor::sPySetInvert,
+ METH_VARARGS, SetInvert_doc},
+ {"getLevel", (PyCFunction) SCA_ISensor::sPyGetLevel,
+ METH_NOARGS, GetLevel_doc},
+ {"setLevel", (PyCFunction) SCA_ISensor::sPySetLevel,
+ METH_VARARGS, SetLevel_doc},
+ {NULL,NULL} //Sentinel
+};
+
+
+PyObject*
+SCA_ISensor::_getattr(const STR_String& attr)
+{
+ _getattr_up(SCA_ILogicBrick);
+}
+
+
void SCA_ISensor::RegisterToManager()
{
- // sensor is just activated, initialize it
- Init();
- m_newControllers.erase(m_newControllers.begin(), m_newControllers.end());
m_eventmgr->RegisterSensor(this);
}
@@ -161,9 +219,6 @@ void SCA_ISensor::Activate(class SCA_LogicManager* logicmgr, CValue* event)
bool result = this->Evaluate(event);
if (result) {
logicmgr->AddActivatedSensor(this);
- // reset these counters so that pulse are synchronized with transition
- m_pos_ticks = 0;
- m_neg_ticks = 0;
} else
{
/* First, the pulsing behaviour, if pulse mode is
@@ -192,75 +247,40 @@ void SCA_ISensor::Activate(class SCA_LogicManager* logicmgr, CValue* event)
}
}
}
- if (!m_newControllers.empty())
- {
- if (!IsActive() && 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 (std::vector<SCA_IController*>::iterator ci=m_newControllers.begin();
- ci != m_newControllers.end(); ci++)
- {
- logicmgr->AddTriggeredController(*ci, this);
- }
- }
- // clear the list. Instead of using clear, which also release the memory,
- // use erase, which keeps the memory available for next time.
- m_newControllers.erase(m_newControllers.begin(), m_newControllers.end());
- }
}
}
-/* ----------------------------------------------- */
-/* Python Functions */
-/* ----------------------------------------------- */
-//Deprecated Functions ------>
-const char SCA_ISensor::IsPositive_doc[] =
+/* Python functions: */
+char SCA_ISensor::IsPositive_doc[] =
"isPositive()\n"
-"\tReturns whether the sensor is in an active state.\n";
-PyObject* SCA_ISensor::PyIsPositive(PyObject* self)
+"\tReturns whether the sensor is registered a positive event.\n";
+PyObject* SCA_ISensor::PyIsPositive(PyObject* self, PyObject* args, PyObject* kwds)
{
- ShowDeprecationWarning("isPositive()", "the read-only positive property");
int retval = IsPositiveTrigger();
return PyInt_FromLong(retval);
}
-const char SCA_ISensor::IsTriggered_doc[] =
-"isTriggered()\n"
-"\tReturns whether the sensor has triggered the current controller.\n";
-PyObject* SCA_ISensor::PyIsTriggered(PyObject* self)
-{
- ShowDeprecationWarning("isTriggered()", "the read-only triggered property");
- // check with the current controller
- int retval = 0;
- if (SCA_PythonController::m_sCurrentController)
- retval = SCA_PythonController::m_sCurrentController->IsTriggered(this);
- return PyInt_FromLong(retval);
-}
-
/**
* getUsePulseMode: getter for the pulse mode (KX_TRUE = on)
*/
-const char SCA_ISensor::GetUsePosPulseMode_doc[] =
+char SCA_ISensor::GetUsePosPulseMode_doc[] =
"getUsePosPulseMode()\n"
"\tReturns whether positive pulse mode is active.\n";
PyObject* SCA_ISensor::PyGetUsePosPulseMode(PyObject* self)
{
- ShowDeprecationWarning("getUsePosPulseMode()", "the usePosPulseMode property");
return BoolToPyArg(m_pos_pulsemode);
}
/**
* setUsePulseMode: setter for the pulse mode (KX_TRUE = on)
*/
-const char SCA_ISensor::SetUsePosPulseMode_doc[] =
+char SCA_ISensor::SetUsePosPulseMode_doc[] =
"setUsePosPulseMode(pulse?)\n"
"\t - pulse? : Pulse when a positive event occurs?\n"
"\t (KX_TRUE, KX_FALSE)\n"
"\tSet whether to do pulsing when positive pulses occur.\n";
PyObject* SCA_ISensor::PySetUsePosPulseMode(PyObject* self, PyObject* args, PyObject* kwds)
{
- ShowDeprecationWarning("setUsePosPulseMode()", "the usePosPulseMode property");
int pyarg = 0;
if(!PyArg_ParseTuple(args, "i", &pyarg)) { return NULL; }
m_pos_pulsemode = PyArgToBool(pyarg);
@@ -270,26 +290,24 @@ PyObject* SCA_ISensor::PySetUsePosPulseMode(PyObject* self, PyObject* args, PyOb
/**
* getFrequency: getter for the pulse mode interval
*/
-const char SCA_ISensor::GetFrequency_doc[] =
+char SCA_ISensor::GetFrequency_doc[] =
"getFrequency()\n"
"\tReturns the frequency of the updates in pulse mode.\n" ;
PyObject* SCA_ISensor::PyGetFrequency(PyObject* self)
{
- ShowDeprecationWarning("getFrequency()", "the frequency property");
return PyInt_FromLong(m_pulse_frequency);
}
/**
* setFrequency: setter for the pulse mode (KX_TRUE = on)
*/
-const char SCA_ISensor::SetFrequency_doc[] =
+char SCA_ISensor::SetFrequency_doc[] =
"setFrequency(pulse_frequency)\n"
"\t- pulse_frequency: The frequency of the updates in pulse mode (integer)"
"\tSet the frequency of the updates in pulse mode.\n"
"\tIf the frequency is negative, it is set to 0.\n" ;
PyObject* SCA_ISensor::PySetFrequency(PyObject* self, PyObject* args, PyObject* kwds)
{
- ShowDeprecationWarning("setFrequency()", "the frequency property");
int pulse_frequencyArg = 0;
if(!PyArg_ParseTuple(args, "i", &pulse_frequencyArg)) {
@@ -307,29 +325,27 @@ PyObject* SCA_ISensor::PySetFrequency(PyObject* self, PyObject* args, PyObject*
}
-const char SCA_ISensor::GetInvert_doc[] =
+char SCA_ISensor::GetInvert_doc[] =
"getInvert()\n"
"\tReturns whether or not pulses from this sensor are inverted.\n" ;
PyObject* SCA_ISensor::PyGetInvert(PyObject* self)
{
- ShowDeprecationWarning("getInvert()", "the invert property");
return BoolToPyArg(m_invert);
}
-const char SCA_ISensor::SetInvert_doc[] =
+char SCA_ISensor::SetInvert_doc[] =
"setInvert(invert?)\n"
"\t- invert?: Invert the event-values? (KX_TRUE, KX_FALSE)\n"
"\tSet whether to invert pulses.\n";
PyObject* SCA_ISensor::PySetInvert(PyObject* self, PyObject* args, PyObject* kwds)
{
- ShowDeprecationWarning("setInvert()", "the invert property");
int pyarg = 0;
if(!PyArg_ParseTuple(args, "i", &pyarg)) { return NULL; }
m_invert = PyArgToBool(pyarg);
Py_Return;
}
-const char SCA_ISensor::GetLevel_doc[] =
+char SCA_ISensor::GetLevel_doc[] =
"getLevel()\n"
"\tReturns whether this sensor is a level detector or a edge detector.\n"
"\tIt makes a difference only in case of logic state transition (state actuator).\n"
@@ -338,189 +354,40 @@ const char SCA_ISensor::GetLevel_doc[] =
"\tA edge detector will wait for a state change before generating a pulse.\n";
PyObject* SCA_ISensor::PyGetLevel(PyObject* self)
{
- ShowDeprecationWarning("getLevel()", "the level property");
return BoolToPyArg(m_level);
}
-const char SCA_ISensor::SetLevel_doc[] =
+char SCA_ISensor::SetLevel_doc[] =
"setLevel(level?)\n"
"\t- level?: Detect level instead of edge? (KX_TRUE, KX_FALSE)\n"
"\tSet whether to detect level or edge transition when entering a state.\n";
PyObject* SCA_ISensor::PySetLevel(PyObject* self, PyObject* args, PyObject* kwds)
{
- ShowDeprecationWarning("setLevel()", "the level property");
int pyarg = 0;
if(!PyArg_ParseTuple(args, "i", &pyarg)) { return NULL; }
m_level = PyArgToBool(pyarg);
Py_Return;
}
-const char SCA_ISensor::GetUseNegPulseMode_doc[] =
+char SCA_ISensor::GetUseNegPulseMode_doc[] =
"getUseNegPulseMode()\n"
"\tReturns whether negative pulse mode is active.\n";
PyObject* SCA_ISensor::PyGetUseNegPulseMode(PyObject* self)
{
- ShowDeprecationWarning("getUseNegPulseMode()", "the useNegPulseMode property");
return BoolToPyArg(m_neg_pulsemode);
}
-const char SCA_ISensor::SetUseNegPulseMode_doc[] =
+char SCA_ISensor::SetUseNegPulseMode_doc[] =
"setUseNegPulseMode(pulse?)\n"
"\t - pulse? : Pulse when a negative event occurs?\n"
"\t (KX_TRUE, KX_FALSE)\n"
"\tSet whether to do pulsing when negative pulses occur.\n";
PyObject* SCA_ISensor::PySetUseNegPulseMode(PyObject* self, PyObject* args, PyObject* kwds)
{
- ShowDeprecationWarning("setUseNegPulseMode()", "the useNegPulseMode property");
int pyarg = 0;
if(!PyArg_ParseTuple(args, "i", &pyarg)) { return NULL; }
m_neg_pulsemode = PyArgToBool(pyarg);
Py_Return;
}
-//<------Deprecated
-
-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();
- Py_Return;
-}
-
-/* ----------------------------------------------- */
-/* Python Integration Hooks */
-/* ----------------------------------------------- */
-
-PyTypeObject SCA_ISensor::Type = {
- PyObject_HEAD_INIT(&PyType_Type)
- 0,
- "SCA_ISensor",
- sizeof(SCA_ISensor),
- 0,
- PyDestructor,
- 0,
- __getattr,
- __setattr,
- 0, //&MyPyCompare,
- __repr,
- 0, //&cvalue_as_number,
- 0,
- 0,
- 0,
- 0
-};
-
-PyParentObject SCA_ISensor::Parents[] = {
- &SCA_ISensor::Type,
- &SCA_ILogicBrick::Type,
- &CValue::Type,
- NULL
-};
-PyMethodDef SCA_ISensor::Methods[] = {
- //Deprecated functions ----->
- {"isPositive", (PyCFunction) SCA_ISensor::sPyIsPositive,
- METH_NOARGS, (PY_METHODCHAR)IsPositive_doc},
- {"isTriggered", (PyCFunction) SCA_ISensor::sPyIsTriggered,
- METH_VARARGS, (PY_METHODCHAR)IsTriggered_doc},
- {"getUsePosPulseMode", (PyCFunction) SCA_ISensor::sPyGetUsePosPulseMode,
- METH_NOARGS, (PY_METHODCHAR)GetUsePosPulseMode_doc},
- {"setUsePosPulseMode", (PyCFunction) SCA_ISensor::sPySetUsePosPulseMode,
- METH_VARARGS, (PY_METHODCHAR)SetUsePosPulseMode_doc},
- {"getFrequency", (PyCFunction) SCA_ISensor::sPyGetFrequency,
- METH_NOARGS, (PY_METHODCHAR)GetFrequency_doc},
- {"setFrequency", (PyCFunction) SCA_ISensor::sPySetFrequency,
- METH_VARARGS, (PY_METHODCHAR)SetFrequency_doc},
- {"getUseNegPulseMode", (PyCFunction) SCA_ISensor::sPyGetUseNegPulseMode,
- METH_NOARGS, (PY_METHODCHAR)GetUseNegPulseMode_doc},
- {"setUseNegPulseMode", (PyCFunction) SCA_ISensor::sPySetUseNegPulseMode,
- METH_VARARGS, (PY_METHODCHAR)SetUseNegPulseMode_doc},
- {"getInvert", (PyCFunction) SCA_ISensor::sPyGetInvert,
- METH_NOARGS, (PY_METHODCHAR)GetInvert_doc},
- {"setInvert", (PyCFunction) SCA_ISensor::sPySetInvert,
- METH_VARARGS, (PY_METHODCHAR)SetInvert_doc},
- {"getLevel", (PyCFunction) SCA_ISensor::sPyGetLevel,
- METH_NOARGS, (PY_METHODCHAR)GetLevel_doc},
- {"setLevel", (PyCFunction) SCA_ISensor::sPySetLevel,
- METH_VARARGS, (PY_METHODCHAR)SetLevel_doc},
- //<----- Deprecated
- KX_PYMETHODTABLE_NOARGS(SCA_ISensor, reset),
- {NULL,NULL} //Sentinel
-};
-
-PyObject*
-SCA_ISensor::_getattr(const STR_String& attr)
-{
- if (attr == "usePosPulseMode")
- return PyInt_FromLong(m_pos_pulsemode);
- if (attr == "useNegPulseMode")
- return PyInt_FromLong(m_neg_pulsemode);
- if (attr == "frequency")
- return PyInt_FromLong(m_pulse_frequency);
- if (attr == "invert")
- return PyInt_FromLong(m_invert);
- if (attr == "level")
- return PyInt_FromLong(m_level);
- if (attr == "triggered")
- {
- int retval = 0;
- if (SCA_PythonController::m_sCurrentController)
- retval = SCA_PythonController::m_sCurrentController->IsTriggered(this);
- return PyInt_FromLong(retval);
- }
- if (attr == "positive")
- {
- int retval = IsPositiveTrigger();
- return PyInt_FromLong(retval);
- }
-
- _getattr_up(SCA_ILogicBrick);
-}
-
-int SCA_ISensor::_setattr(const STR_String& attr, PyObject *value)
-{
- if (attr == "triggered")
- PyErr_SetString(PyExc_AttributeError, "attribute \"triggered\" is read only");
- if (attr == "positive")
- PyErr_SetString(PyExc_AttributeError, "attribute \"positive\" is read only");
-
- if (PyInt_Check(value))
- {
- int val = PyInt_AsLong(value);
- if (attr == "usePosPulseMode")
- {
- m_pos_pulsemode = (val != 0);
- return 0;
- }
-
- if (attr == "useNegPulseMode")
- {
- m_neg_pulsemode = (val != 0);
- return 0;
- }
-
- if (attr == "invert")
- {
- m_invert = (val != 0);
- return 0;
- }
-
- if (attr == "level")
- {
- m_level = (val != 0);
- return 0;
- }
-
- if (attr == "frequency")
- {
- if (val < 0)
- val = 0;
- m_pulse_frequency = val;
- return 0;
- }
- }
-
- return SCA_ILogicBrick::_setattr(attr, value);
-}
/* eof */
diff --git a/source/gameengine/GameLogic/SCA_ISensor.h b/source/gameengine/GameLogic/SCA_ISensor.h
index 1b57c4621e4..d5dabbce3ee 100644
--- a/source/gameengine/GameLogic/SCA_ISensor.h
+++ b/source/gameengine/GameLogic/SCA_ISensor.h
@@ -34,8 +34,6 @@
#include "SCA_ILogicBrick.h"
-#include <vector>
-
/**
* Interface Class for all logic Sensors. Implements
* pulsemode,pulsefrequency */
@@ -75,9 +73,9 @@ class SCA_ISensor : public SCA_ILogicBrick
/** number of connections to controller */
int m_links;
- /** list of controllers that have just activated this sensor because of a state change */
- std::vector<class SCA_IController*> m_newControllers;
-
+ /** Pass the activation on to the logic manager.*/
+ void SignalActivation(class SCA_LogicManager* logicmgr);
+
public:
SCA_ISensor(SCA_IObject* gameobj,
class SCA_EventManager* eventmgr,
@@ -93,7 +91,8 @@ public:
virtual bool Evaluate(CValue* event) = 0;
virtual bool IsPositiveTrigger();
virtual void Init();
-
+
+ virtual PyObject* _getattr(const STR_String& attr);
virtual CValue* GetReplica()=0;
/** Set parameters for the pulsing behaviour.
@@ -115,8 +114,8 @@ public:
/** set the level detection on or off */
void SetLevel(bool lvl);
- virtual void RegisterToManager();
- virtual void UnregisterToManager();
+ void RegisterToManager();
+ void UnregisterToManager();
virtual float GetNumber();
@@ -129,8 +128,6 @@ public:
/** Resume sensing. */
void Resume();
- void AddNewController(class SCA_IController* controller)
- { m_newControllers.push_back(controller); }
void ClrLink()
{ m_links = 0; }
void IncLink()
@@ -140,13 +137,7 @@ public:
{ return !m_links; }
/* Python functions: */
-
- virtual PyObject* _getattr(const STR_String& attr);
- virtual int _setattr(const STR_String& attr, PyObject *value);
-
- //Deprecated functions ----->
- KX_PYMETHOD_DOC_NOARGS(SCA_ISensor,IsPositive);
- KX_PYMETHOD_DOC_NOARGS(SCA_ISensor,IsTriggered);
+ KX_PYMETHOD_DOC(SCA_ISensor,IsPositive);
KX_PYMETHOD_DOC_NOARGS(SCA_ISensor,GetUsePosPulseMode);
KX_PYMETHOD_DOC(SCA_ISensor,SetUsePosPulseMode);
KX_PYMETHOD_DOC_NOARGS(SCA_ISensor,GetFrequency);
@@ -157,8 +148,7 @@ public:
KX_PYMETHOD_DOC(SCA_ISensor,SetInvert);
KX_PYMETHOD_DOC_NOARGS(SCA_ISensor,GetLevel);
KX_PYMETHOD_DOC(SCA_ISensor,SetLevel);
- //<------
- KX_PYMETHOD_DOC_NOARGS(SCA_ISensor,reset);
+
};
#endif //__SCA_ISENSOR
diff --git a/source/gameengine/GameLogic/SCA_JoystickManager.cpp b/source/gameengine/GameLogic/SCA_JoystickManager.cpp
index f3ce549a637..8ff28ba0b51 100644
--- a/source/gameengine/GameLogic/SCA_JoystickManager.cpp
+++ b/source/gameengine/GameLogic/SCA_JoystickManager.cpp
@@ -40,49 +40,35 @@ SCA_JoystickManager::SCA_JoystickManager(class SCA_LogicManager* logicmgr)
: SCA_EventManager(JOY_EVENTMGR),
m_logicmgr(logicmgr)
{
- int i;
- for (i=0; i<JOYINDEX_MAX; i++) {
- m_joystick[i] = SCA_Joystick::GetInstance( i );
- }
+ m_joystick = SCA_Joystick::GetInstance();
}
SCA_JoystickManager::~SCA_JoystickManager()
{
- int i;
- for (i=0; i<JOYINDEX_MAX; i++) {
- if(m_joystick[i])
- m_joystick[i]->ReleaseInstance();
- }
+ m_joystick->ReleaseInstance();
}
void SCA_JoystickManager::NextFrame(double curtime,double deltatime)
{
- if (m_sensors.size()==0) {
- return;
- }
- else {
- set<SCA_ISensor*>::iterator it;
-#ifndef DISABLE_SDL
- SCA_Joystick::HandleEvents(); /* Handle all SDL Joystick events */
-#endif
- for (it = m_sensors.begin(); it != m_sensors.end(); it++)
+ set<SCA_ISensor*>::iterator it;
+ for (it = m_sensors.begin(); it != m_sensors.end(); it++)
+ {
+ SCA_JoystickSensor* joysensor = (SCA_JoystickSensor*)(*it);
+ if(!joysensor->IsSuspended())
{
- SCA_JoystickSensor* joysensor = (SCA_JoystickSensor*)(*it);
- if(!joysensor->IsSuspended())
- {
- joysensor->Activate(m_logicmgr, NULL);
- }
+ m_joystick->HandleEvents();
+ joysensor->Activate(m_logicmgr, NULL);
}
}
}
-SCA_Joystick *SCA_JoystickManager::GetJoystickDevice( short int joyindex)
+SCA_Joystick *SCA_JoystickManager::GetJoystickDevice()
{
/*
*Return the instance of SCA_Joystick for use
*/
- return m_joystick[joyindex];
+ return m_joystick;
}
diff --git a/source/gameengine/GameLogic/SCA_JoystickManager.h b/source/gameengine/GameLogic/SCA_JoystickManager.h
index d3a7ac95bea..f2bb27965fa 100644
--- a/source/gameengine/GameLogic/SCA_JoystickManager.h
+++ b/source/gameengine/GameLogic/SCA_JoystickManager.h
@@ -40,12 +40,12 @@ class SCA_JoystickManager : public SCA_EventManager
/**
* SDL Joystick Class Instance
*/
- SCA_Joystick *m_joystick[JOYINDEX_MAX];
+ SCA_Joystick *m_joystick;
public:
SCA_JoystickManager(class SCA_LogicManager* logicmgr);
virtual ~SCA_JoystickManager();
virtual void NextFrame(double curtime,double deltatime);
- SCA_Joystick* GetJoystickDevice(short int joyindex);
+ SCA_Joystick* GetJoystickDevice(void);
};
diff --git a/source/gameengine/GameLogic/SCA_JoystickSensor.cpp b/source/gameengine/GameLogic/SCA_JoystickSensor.cpp
index ce9058448ac..3fb439eb25b 100644
--- a/source/gameengine/GameLogic/SCA_JoystickSensor.cpp
+++ b/source/gameengine/GameLogic/SCA_JoystickSensor.cpp
@@ -30,11 +30,8 @@
#include "SCA_EventManager.h"
#include "SCA_LogicManager.h"
-#include "PyObjectPlus.h"
-
#include <iostream>
-
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
@@ -42,29 +39,28 @@
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,
+ int button, int buttonf,
+ int hat, int hatf,
PyTypeObject* T )
:SCA_ISensor(gameobj,eventmgr,T),
m_pJoystickMgr(eventmgr),
m_axis(axis),
m_axisf(axisf),
m_button(button),
+ m_buttonf(buttonf),
m_hat(hat),
m_hatf(hatf),
m_precision(prec),
- m_joymode(joymode),
- m_joyindex(joyindex),
- m_bAllEvents(allevents)
+ m_joymode(joymode)
{
/*
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 << " button flag "<< m_buttonf << std::endl;
std::cout << " hat " << m_hat << std::endl;
std::cout << " hat flag " << m_hatf << std::endl;
*/
@@ -74,7 +70,6 @@ std::cout << " hat flag " << m_hatf << std::endl;
void SCA_JoystickSensor::Init()
{
m_istrig=(m_invert)?1:0;
- m_istrig_prev=0;
m_reset = true;
}
@@ -104,13 +99,10 @@ bool SCA_JoystickSensor::IsPositiveTrigger()
bool SCA_JoystickSensor::Evaluate(CValue* event)
{
- SCA_Joystick *js = m_pJoystickMgr->GetJoystickDevice(m_joyindex);
+ SCA_Joystick *js = m_pJoystickMgr->GetJoystickDevice();
bool result = false;
bool reset = m_reset && m_level;
- if(js==NULL) /* no joystick - dont do anything */
- return false;
-
m_reset = false;
switch(m_joymode)
{
@@ -123,25 +115,10 @@ bool SCA_JoystickSensor::Evaluate(CValue* event)
m_axisf == 3 == down
numberof== m_axis -- max 2
*/
-
- if (!js->IsTrigAxis() && !reset) /* No events from SDL? - dont bother */
- return false;
-
js->cSetPrecision(m_precision);
- if (m_bAllEvents) {
- if(js->aAnyAxisIsPositive(m_axis)){
- m_istrig = 1;
- result = true;
- }else{
- if(m_istrig){
- m_istrig = 0;
- result = true;
- }
- }
- }
- else if(m_axisf == 1){
+ if(m_axisf == 1){
if(js->aUpAxisIsPositive(m_axis)){
- m_istrig = 1;
+ m_istrig =1;
result = true;
}else{
if(m_istrig){
@@ -150,7 +127,7 @@ bool SCA_JoystickSensor::Evaluate(CValue* event)
}
}
}
- else if(m_axisf == 3){
+ if(m_axisf == 3){
if(js->aDownAxisIsPositive(m_axis)){
m_istrig = 1;
result = true;
@@ -161,7 +138,7 @@ bool SCA_JoystickSensor::Evaluate(CValue* event)
}
}
}
- else if(m_axisf == 2){
+ if(m_axisf == 2){
if(js->aLeftAxisIsPositive(m_axis)){
m_istrig = 1;
result = true;
@@ -172,7 +149,7 @@ bool SCA_JoystickSensor::Evaluate(CValue* event)
}
}
}
- else if(m_axisf == 0){
+ if(m_axisf == 0){
if(js->aRightAxisIsPositive(m_axis)){
m_istrig = 1;
result = true;
@@ -188,20 +165,32 @@ bool SCA_JoystickSensor::Evaluate(CValue* event)
case KX_JOYSENSORMODE_BUTTON:
{
/* what is what!
+ pressed = m_buttonf == 0
+ released = m_buttonf == 1
m_button = the actual button in question
*/
- if (!js->IsTrigButton() && !reset) /* No events from SDL? - dont 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;
+ if(m_buttonf == 0){
+ if(js->aButtonPressIsPositive(m_button)){
+ m_istrig = 1;
result = true;
+ }else {
+ if(m_istrig){
+ m_istrig = 0;
+ result = true;
+ }
}
}
+ if(m_buttonf == 1){
+ if(js->aButtonReleaseIsPositive(m_button)){
+ m_istrig = 1;
+ result = true;
+ }else {
+ if(m_istrig){
+ m_istrig = 0;
+ result = true;
+ }
+ }
+ }
break;
}
case KX_JOYSENSORMODE_HAT:
@@ -210,10 +199,6 @@ bool SCA_JoystickSensor::Evaluate(CValue* event)
numberof = m_hat -- max 2
direction= m_hatf -- max 12
*/
-
- if (!js->IsTrigHat() && !reset) /* No events from SDL? - dont bother */
- return false;
-
if(m_hat == 1){
if(js->aHatIsPositive(m_hatf)){
m_istrig = 1;
@@ -236,6 +221,19 @@ bool SCA_JoystickSensor::Evaluate(CValue* event)
}
}
}
+ /*
+ if(m_hat == 3){
+ if(js->aHatIsPositive(m_hatf)){
+ m_istrig = 1;
+ result = true;
+ }else{
+ if(m_istrig){
+ m_istrig = 0;
+ result = true;
+ }
+ }
+ }
+ */
break;
}
/* test for ball anyone ?*/
@@ -243,20 +241,11 @@ bool SCA_JoystickSensor::Evaluate(CValue* event)
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(!js->IsTrig()){
+ m_istrig = 0;
}
-
if (reset)
result = true;
-
return result;
}
@@ -304,122 +293,45 @@ PyParentObject SCA_JoystickSensor::Parents[] = {
PyMethodDef SCA_JoystickSensor::Methods[] = {
- //Deprecated functions ------>
- {"getIndex", (PyCFunction) SCA_JoystickSensor::sPyGetIndex, METH_NOARGS, (PY_METHODCHAR)GetIndex_doc},
- {"setIndex", (PyCFunction) SCA_JoystickSensor::sPySetIndex, METH_O, (PY_METHODCHAR)SetIndex_doc},
- {"getAxis", (PyCFunction) SCA_JoystickSensor::sPyGetAxis, METH_NOARGS, (PY_METHODCHAR)GetAxis_doc},
- {"setAxis", (PyCFunction) SCA_JoystickSensor::sPySetAxis, METH_VARARGS, (PY_METHODCHAR)SetAxis_doc},
- {"getAxisValue", (PyCFunction) SCA_JoystickSensor::sPyGetAxisValue, METH_NOARGS, (PY_METHODCHAR)GetAxisValue_doc},
- {"getThreshold", (PyCFunction) SCA_JoystickSensor::sPyGetThreshold, METH_NOARGS, (PY_METHODCHAR)GetThreshold_doc},
- {"setThreshold", (PyCFunction) SCA_JoystickSensor::sPySetThreshold, METH_VARARGS, (PY_METHODCHAR)SetThreshold_doc},
- {"getButton", (PyCFunction) SCA_JoystickSensor::sPyGetButton, METH_NOARGS, (PY_METHODCHAR)GetButton_doc},
- {"setButton", (PyCFunction) SCA_JoystickSensor::sPySetButton, METH_O, (PY_METHODCHAR)SetButton_doc},
- {"getHat", (PyCFunction) SCA_JoystickSensor::sPyGetHat, METH_NOARGS, (PY_METHODCHAR)GetHat_doc},
- {"setHat", (PyCFunction) SCA_JoystickSensor::sPySetHat, METH_VARARGS, (PY_METHODCHAR)SetHat_doc},
- {"getNumAxes", (PyCFunction) SCA_JoystickSensor::sPyNumberOfAxes, METH_NOARGS, (PY_METHODCHAR)NumberOfAxes_doc},
- {"getNumButtons",(PyCFunction) SCA_JoystickSensor::sPyNumberOfButtons,METH_NOARGS, (PY_METHODCHAR)NumberOfButtons_doc},
- {"getNumHats", (PyCFunction) SCA_JoystickSensor::sPyNumberOfHats, METH_NOARGS, (PY_METHODCHAR)NumberOfHats_doc},
- {"isConnected", (PyCFunction) SCA_JoystickSensor::sPyConnected, METH_NOARGS, (PY_METHODCHAR)Connected_doc},
- {"getButtonValue",(PyCFunction) SCA_JoystickSensor::sPyGetButtonValue, METH_NOARGS,(PY_METHODCHAR)GetButtonValue_doc},
- //<----- Deprecated
- {"getButtonActiveList",(PyCFunction) SCA_JoystickSensor::sPyGetButtonActiveList, METH_NOARGS,(PY_METHODCHAR)GetButtonActiveList_doc},
- {"getButtonStatus",(PyCFunction) SCA_JoystickSensor::sPyGetButtonStatus, METH_VARARGS,(PY_METHODCHAR)GetButtonStatus_doc},
+ {"getAxis", (PyCFunction) SCA_JoystickSensor::sPyGetAxis, METH_NOARGS, GetAxis_doc},
+ {"setAxis", (PyCFunction) SCA_JoystickSensor::sPySetAxis, METH_VARARGS, SetAxis_doc},
+ {"getAxisValue", (PyCFunction) SCA_JoystickSensor::sPyGetRealAxis, METH_NOARGS, GetRealAxis_doc},
+ {"getThreshold", (PyCFunction) SCA_JoystickSensor::sPyGetThreshold, METH_NOARGS, GetThreshold_doc},
+ {"setThreshold", (PyCFunction) SCA_JoystickSensor::sPySetThreshold, METH_VARARGS, SetThreshold_doc},
+ {"getButton", (PyCFunction) SCA_JoystickSensor::sPyGetButton, METH_NOARGS, GetButton_doc},
+ {"setButton", (PyCFunction) SCA_JoystickSensor::sPySetButton, METH_VARARGS, SetButton_doc},
+ {"getHat", (PyCFunction) SCA_JoystickSensor::sPyGetHat, METH_NOARGS, GetHat_doc},
+ {"setHat", (PyCFunction) SCA_JoystickSensor::sPySetHat, METH_VARARGS, SetHat_doc},
+ {"getNumAxes", (PyCFunction) SCA_JoystickSensor::sPyNumberOfAxes, METH_NOARGS, NumberOfAxes_doc},
+ {"getNumButtons",(PyCFunction) SCA_JoystickSensor::sPyNumberOfButtons,METH_NOARGS, NumberOfButtons_doc},
+ {"getNumHats", (PyCFunction) SCA_JoystickSensor::sPyNumberOfHats, METH_NOARGS, NumberOfHats_doc},
{NULL,NULL} //Sentinel
};
-PyAttributeDef SCA_JoystickSensor::Attributes[] = {
- KX_PYATTRIBUTE_SHORT_RW("index",0,JOYINDEX_MAX-1,SCA_JoystickSensor,m_joyindex),
- KX_PYATTRIBUTE_INT_RW("threshold",0,32768,SCA_JoystickSensor,m_precision),
- KX_PYATTRIBUTE_INT_RW("button",0,100,SCA_JoystickSensor,m_button),
- KX_PYATTRIBUTE_INT_ARRAY_RW_CHECK("axis",0,3,SCA_JoystickSensor,m_axis,2,CheckAxis),
- KX_PYATTRIBUTE_INT_ARRAY_RW_CHECK("hat",0,12,SCA_JoystickSensor,m_hat,2,CheckHat),
- // dummy attributes will just be read-only in _setattr
- // you still need to defined them in _getattr
- KX_PYATTRIBUTE_DUMMY("axisPosition"),
- KX_PYATTRIBUTE_DUMMY("numAxis"),
- KX_PYATTRIBUTE_DUMMY("numButtons"),
- KX_PYATTRIBUTE_DUMMY("numHats"),
- KX_PYATTRIBUTE_DUMMY("connected"),
- { NULL } //Sentinel
-};
PyObject* SCA_JoystickSensor::_getattr(const STR_String& attr) {
- SCA_Joystick *joy = m_pJoystickMgr->GetJoystickDevice(m_joyindex);
- if (attr == "axisPosition") {
- if(joy)
- return Py_BuildValue("[iiii]", joy->GetAxis10(), joy->GetAxis11(), joy->GetAxis20(), joy->GetAxis21());
- else
- return Py_BuildValue("[iiii]", 0, 0, 0, 0);
- }
- if (attr == "numAxis") {
- return PyInt_FromLong( joy ? joy->GetNumberOfAxes() : 0 );
- }
- if (attr == "numButtons") {
- return PyInt_FromLong( joy ? joy->GetNumberOfButtons() : 0 );
- }
- if (attr == "numHats") {
- return PyInt_FromLong( joy ? joy->GetNumberOfHats() : 0 );
- }
- if (attr == "connected") {
- return PyBool_FromLong( joy ? joy->Connected() : 0 );
- }
- PyObject* object = _getattr_self(Attributes, this, attr);
- if (object != NULL)
- return object;
_getattr_up(SCA_ISensor);
}
-int SCA_JoystickSensor::_setattr(const STR_String& attr, PyObject *value)
-{
- int ret = _setattr_self(Attributes, this, attr, value);
- if (ret >= 0)
- return ret;
- return SCA_ISensor::_setattr(attr, value);
-}
-
-
-/* get index ---------------------------------------------------------- */
-const char SCA_JoystickSensor::GetIndex_doc[] =
-"getIndex\n"
-"\tReturns the joystick index to use.\n";
-PyObject* SCA_JoystickSensor::PyGetIndex( PyObject* self ) {
- ShowDeprecationWarning("getIndex()", "the index property");
- return PyInt_FromLong(m_joyindex);
-}
-
-
-/* set index ---------------------------------------------------------- */
-const char SCA_JoystickSensor::SetIndex_doc[] =
-"setIndex\n"
-"\tSets the joystick index to use.\n";
-PyObject* SCA_JoystickSensor::PySetIndex( PyObject* self, PyObject* value ) {
- ShowDeprecationWarning("setIndex()", "the index property");
- int index = PyInt_AsLong( value ); /* -1 on error, will raise an error in this case */
- if (index < 0 || index >= JOYINDEX_MAX) {
- PyErr_SetString(PyExc_ValueError, "joystick index out of range or not an int");
- return NULL;
- }
-
- m_joyindex = index;
- Py_RETURN_NONE;
-}
/* get axis ---------------------------------------------------------- */
-const char SCA_JoystickSensor::GetAxis_doc[] =
+char SCA_JoystickSensor::GetAxis_doc[] =
"getAxis\n"
-"\tReturns the current axis this sensor reacts to.\n";
-PyObject* SCA_JoystickSensor::PyGetAxis( PyObject* self) {
- ShowDeprecationWarning("getAxis()", "the axis property");
+"\tReturns the current state of the axis.\n";
+PyObject* SCA_JoystickSensor::PyGetAxis( PyObject* self,
+ PyObject* args,
+ PyObject* kwds) {
return Py_BuildValue("[ii]",m_axis, m_axisf);
}
/* set axis ---------------------------------------------------------- */
-const char SCA_JoystickSensor::SetAxis_doc[] =
+char SCA_JoystickSensor::SetAxis_doc[] =
"setAxis\n"
-"\tSets the current axis this sensor reacts to.\n";
-PyObject* SCA_JoystickSensor::PySetAxis( PyObject* self, PyObject* args ) {
- ShowDeprecationWarning("setAxis()", "the axis property");
+"\tSets the current state of the axis.\n";
+PyObject* SCA_JoystickSensor::PySetAxis( PyObject* self,
+ PyObject* args,
+ PyObject* kwds) {
int axis,axisflag;
if(!PyArg_ParseTuple(args, "ii", &axis, &axisflag)){
@@ -427,183 +339,145 @@ PyObject* SCA_JoystickSensor::PySetAxis( PyObject* self, PyObject* args ) {
}
m_axis = axis;
m_axisf = axisflag;
- Py_RETURN_NONE;
+ Py_Return;
}
/* get axis value ----------------------------------------------------- */
-const char SCA_JoystickSensor::GetAxisValue_doc[] =
+char SCA_JoystickSensor::GetRealAxis_doc[] =
"getAxisValue\n"
-"\tReturns a list of the values for the current state of each axis.\n";
-PyObject* SCA_JoystickSensor::PyGetAxisValue( PyObject* self) {
- ShowDeprecationWarning("getAxisValue()", "the axisPosition property");
- SCA_Joystick *joy = m_pJoystickMgr->GetJoystickDevice(m_joyindex);
- if(joy)
- return Py_BuildValue("[iiii]", joy->GetAxis10(), joy->GetAxis11(), joy->GetAxis20(), joy->GetAxis21());
- else
- return Py_BuildValue("[iiii]", 0, 0, 0, 0);
+"\tReturns a list of the values for each axis .\n";
+PyObject* SCA_JoystickSensor::PyGetRealAxis( PyObject* self,
+ PyObject* args,
+ PyObject* kwds) {
+ int a,b,c,d;
+ SCA_Joystick *joy = m_pJoystickMgr->GetJoystickDevice();
+ a = joy->GetAxis10();
+ b = joy->GetAxis11();
+ c = joy->GetAxis20();
+ d = joy->GetAxis21();
+ return Py_BuildValue("[iiii]",a,b,c,d);
}
/* get threshold ----------------------------------------------------- */
-const char SCA_JoystickSensor::GetThreshold_doc[] =
+char SCA_JoystickSensor::GetThreshold_doc[] =
"getThreshold\n"
"\tReturns the threshold of the axis.\n";
-PyObject* SCA_JoystickSensor::PyGetThreshold( PyObject* self) {
- ShowDeprecationWarning("getThreshold()", "the threshold property");
- return PyInt_FromLong(m_precision);
+PyObject* SCA_JoystickSensor::PyGetThreshold( PyObject* self,
+ PyObject* args,
+ PyObject* kwds) {
+ return Py_BuildValue("i", m_precision);
}
/* set threshold ----------------------------------------------------- */
-const char SCA_JoystickSensor::SetThreshold_doc[] =
+char SCA_JoystickSensor::SetThreshold_doc[] =
"setThreshold\n"
"\tSets the threshold of the axis.\n";
-PyObject* SCA_JoystickSensor::PySetThreshold( PyObject* self, PyObject* args ) {
- ShowDeprecationWarning("setThreshold()", "the threshold property");
+PyObject* SCA_JoystickSensor::PySetThreshold( PyObject* self,
+ PyObject* args,
+ PyObject* kwds) {
int thresh;
if(!PyArg_ParseTuple(args, "i", &thresh)){
return NULL;
}
m_precision = thresh;
- Py_RETURN_NONE;
+ Py_Return;
}
+
/* get button -------------------------------------------------------- */
-const char SCA_JoystickSensor::GetButton_doc[] =
+char SCA_JoystickSensor::GetButton_doc[] =
"getButton\n"
-"\tReturns the current button this sensor is checking.\n";
-PyObject* SCA_JoystickSensor::PyGetButton( PyObject* self) {
- ShowDeprecationWarning("getButton()", "the button property");
- return PyInt_FromLong(m_button);
+"\tReturns the currently pressed button.\n";
+PyObject* SCA_JoystickSensor::PyGetButton( PyObject* self,
+ PyObject* args,
+ PyObject* kwds) {
+ return Py_BuildValue("[ii]",m_button, m_buttonf);
}
+
/* set button -------------------------------------------------------- */
-const char SCA_JoystickSensor::SetButton_doc[] =
+char SCA_JoystickSensor::SetButton_doc[] =
"setButton\n"
"\tSets the button the sensor reacts to.\n";
-PyObject* SCA_JoystickSensor::PySetButton( PyObject* self, PyObject* value ) {
- ShowDeprecationWarning("setButton()", "the button property");
- int button = PyInt_AsLong(value);
- if(button==-1 && PyErr_Occurred()) {
- PyErr_SetString(PyExc_ValueError, "expected an int");
+PyObject* SCA_JoystickSensor::PySetButton( PyObject* self,
+ PyObject* args,
+ PyObject* kwds) {
+ int button,buttonflag;
+ if(!PyArg_ParseTuple(args, "ii", &button, &buttonflag)){
return NULL;
}
m_button = button;
- Py_RETURN_NONE;
-}
-
-/* get button value -------------------------------------------------- */
-const char SCA_JoystickSensor::GetButtonValue_doc[] =
-"getButtonValue\n"
-"\tReturns a list containing the indicies of the current pressed state of each button.\n";
-PyObject* SCA_JoystickSensor::PyGetButtonValue( PyObject* self) {
- ShowDeprecationWarning("getButtonValue()", "getButtonActiveList");
- return PyGetButtonActiveList(self);
-}
-
-/* get button active list -------------------------------------------------- */
-const char SCA_JoystickSensor::GetButtonActiveList_doc[] =
-"getButtonActiveList\n"
-"\tReturns a list containing the indicies of the button currently pressed.\n";
-PyObject* SCA_JoystickSensor::PyGetButtonActiveList( PyObject* self) {
- SCA_Joystick *joy = m_pJoystickMgr->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 = PyInt_FromLong(i);
- PyList_Append(ls, value);
- Py_DECREF(value);
- }
- }
- }
- return ls;
+ m_buttonf = buttonflag;
+ Py_Return;
}
-/* 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* self, PyObject* args ) {
- SCA_Joystick *joy = m_pJoystickMgr->GetJoystickDevice(m_joyindex);
- PyObject *value;
- int index;
-
- if(!PyArg_ParseTuple(args, "i", &index)){
- return NULL;
- }
- if(joy && index >= 0 && index < joy->GetNumberOfButtons()) {
- return PyBool_FromLong(joy->aButtonPressIsPositive(index) ? 1 : 0);
- }
- return PyBool_FromLong(0);
-}
/* get hat ----------------------------------------------------------- */
-const char SCA_JoystickSensor::GetHat_doc[] =
+char SCA_JoystickSensor::GetHat_doc[] =
"getHat\n"
"\tReturns the current direction of the hat.\n";
-PyObject* SCA_JoystickSensor::PyGetHat( PyObject* self ) {
- ShowDeprecationWarning("getHat()", "the hat property");
+PyObject* SCA_JoystickSensor::PyGetHat( PyObject* self,
+ PyObject* args,
+ PyObject* kwds) {
return Py_BuildValue("[ii]",m_hat, m_hatf);
}
/* set hat ----------------------------------------------------------- */
-const char SCA_JoystickSensor::SetHat_doc[] =
+char SCA_JoystickSensor::SetHat_doc[] =
"setHat\n"
"\tSets the hat the sensor reacts to.\n";
-PyObject* SCA_JoystickSensor::PySetHat( PyObject* self, PyObject* args ) {
- ShowDeprecationWarning("setHat()", "the hat property");
+PyObject* SCA_JoystickSensor::PySetHat( PyObject* self,
+ PyObject* args,
+ PyObject* kwds) {
int hat,hatflag;
if(!PyArg_ParseTuple(args, "ii", &hat, &hatflag)){
return NULL;
}
m_hat = hat;
m_hatf = hatflag;
- Py_RETURN_NONE;
+ Py_Return;
}
/* get # of ----------------------------------------------------- */
-const char SCA_JoystickSensor::NumberOfAxes_doc[] =
+char SCA_JoystickSensor::NumberOfAxes_doc[] =
"getNumAxes\n"
"\tReturns the number of axes .\n";
-PyObject* SCA_JoystickSensor::PyNumberOfAxes( PyObject* self ) {
- ShowDeprecationWarning("getNumAxes()", "the numAxis property");
- SCA_Joystick *joy = m_pJoystickMgr->GetJoystickDevice(m_joyindex);
- // when the joystick is null their is 0 exis still. dumb but scripters should use isConnected()
- return PyInt_FromLong( joy ? joy->GetNumberOfAxes() : 0 );
+PyObject* SCA_JoystickSensor::PyNumberOfAxes( PyObject* self,
+ PyObject* args,
+ PyObject* kwds) {
+ int num;
+ SCA_Joystick *joy = m_pJoystickMgr->GetJoystickDevice();
+ num = joy->GetNumberOfAxes();
+ return Py_BuildValue("i",num);
}
-const char SCA_JoystickSensor::NumberOfButtons_doc[] =
+char SCA_JoystickSensor::NumberOfButtons_doc[] =
"getNumButtons\n"
"\tReturns the number of buttons .\n";
-PyObject* SCA_JoystickSensor::PyNumberOfButtons( PyObject* self ) {
- ShowDeprecationWarning("getNumButtons()", "the numButtons property");
- SCA_Joystick *joy = m_pJoystickMgr->GetJoystickDevice(m_joyindex);
- return PyInt_FromLong( joy ? joy->GetNumberOfButtons() : 0 );
+PyObject* SCA_JoystickSensor::PyNumberOfButtons( PyObject* self,
+ PyObject* args,
+ PyObject* kwds) {
+ int num;
+ SCA_Joystick *joy = m_pJoystickMgr->GetJoystickDevice();
+ num = joy->GetNumberOfButtons();
+ return Py_BuildValue("i",num);
}
-const char SCA_JoystickSensor::NumberOfHats_doc[] =
+char SCA_JoystickSensor::NumberOfHats_doc[] =
"getNumHats\n"
"\tReturns the number of hats .\n";
-PyObject* SCA_JoystickSensor::PyNumberOfHats( PyObject* self ) {
- ShowDeprecationWarning("getNumHats()", "the numHats property");
- SCA_Joystick *joy = m_pJoystickMgr->GetJoystickDevice(m_joyindex);
- return PyInt_FromLong( joy ? joy->GetNumberOfHats() : 0 );
-}
-
-const char SCA_JoystickSensor::Connected_doc[] =
-"getConnected\n"
-"\tReturns True if a joystick is connected at this joysticks index.\n";
-PyObject* SCA_JoystickSensor::PyConnected( PyObject* self ) {
- ShowDeprecationWarning("getConnected()", "the connected property");
- SCA_Joystick *joy = m_pJoystickMgr->GetJoystickDevice(m_joyindex);
- return PyBool_FromLong( joy ? joy->Connected() : 0 );
+PyObject* SCA_JoystickSensor::PyNumberOfHats( PyObject* self,
+ PyObject* args,
+ PyObject* kwds) {
+ int num;
+ SCA_Joystick *joy = m_pJoystickMgr->GetJoystickDevice();
+ num = joy->GetNumberOfHats();
+ return Py_BuildValue("i",num);
}
diff --git a/source/gameengine/GameLogic/SCA_JoystickSensor.h b/source/gameengine/GameLogic/SCA_JoystickSensor.h
index 25103b3c6bc..69068da6494 100644
--- a/source/gameengine/GameLogic/SCA_JoystickSensor.h
+++ b/source/gameengine/GameLogic/SCA_JoystickSensor.h
@@ -37,11 +37,11 @@ class SCA_JoystickSensor :public SCA_ISensor
class SCA_JoystickManager* m_pJoystickMgr;
/**
- * Axis 1-or-2, MUST be followed by m_axisf
+ * Axis 1-or-2
*/
int m_axis;
/**
- * Axis flag to find direction, MUST be an int
+ * Axis flag to find direction
*/
int m_axisf;
/**
@@ -53,11 +53,11 @@ class SCA_JoystickSensor :public SCA_ISensor
*/
int m_buttonf;
/**
- * The actual hat. MUST be followed by m_hatf
+ * The actual hat
*/
int m_hat;
/**
- * Flag to find direction 0-11, MUST be an int
+ * Flag to find direction 1-12
*/
int m_hatf;
/**
@@ -69,24 +69,9 @@ class SCA_JoystickSensor :public SCA_ISensor
*/
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,
@@ -100,11 +85,10 @@ class SCA_JoystickSensor :public SCA_ISensor
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,
+ int button, int buttonf,
+ int hat, int hatf,
PyTypeObject* T=&Type );
virtual ~SCA_JoystickSensor();
virtual CValue* GetReplica();
@@ -113,62 +97,28 @@ public:
virtual bool IsPositiveTrigger();
virtual void Init();
- short int GetJoyIndex(void){
- return m_joyindex;
- }
-
/* --------------------------------------------------------------------- */
/* Python interface ---------------------------------------------------- */
/* --------------------------------------------------------------------- */
virtual PyObject* _getattr(const STR_String& attr);
- virtual int _setattr(const STR_String& attr, PyObject *value);
- /* Joystick Index */
- KX_PYMETHOD_DOC_NOARGS(SCA_JoystickSensor,GetIndex);
- KX_PYMETHOD_DOC_O(SCA_JoystickSensor,SetIndex);
/* Axes*/
- KX_PYMETHOD_DOC_NOARGS(SCA_JoystickSensor,GetAxis);
- KX_PYMETHOD_DOC_VARARGS(SCA_JoystickSensor,SetAxis);
- KX_PYMETHOD_DOC_NOARGS(SCA_JoystickSensor,GetAxisValue);
- KX_PYMETHOD_DOC_NOARGS(SCA_JoystickSensor,GetThreshold);
- KX_PYMETHOD_DOC_VARARGS(SCA_JoystickSensor,SetThreshold);
+ KX_PYMETHOD_DOC(SCA_JoystickSensor,GetAxis);
+ KX_PYMETHOD_DOC(SCA_JoystickSensor,SetAxis);
+ KX_PYMETHOD_DOC(SCA_JoystickSensor,GetRealAxis);
+ KX_PYMETHOD_DOC(SCA_JoystickSensor,GetThreshold);
+ KX_PYMETHOD_DOC(SCA_JoystickSensor,SetThreshold);
/* Buttons */
- KX_PYMETHOD_DOC_NOARGS(SCA_JoystickSensor,GetButton);
- KX_PYMETHOD_DOC_O(SCA_JoystickSensor,SetButton);
- KX_PYMETHOD_DOC_NOARGS(SCA_JoystickSensor,GetButtonValue);
- KX_PYMETHOD_DOC_NOARGS(SCA_JoystickSensor,GetButtonActiveList);
- KX_PYMETHOD_DOC_VARARGS(SCA_JoystickSensor,GetButtonStatus);
+ KX_PYMETHOD_DOC(SCA_JoystickSensor,GetButton);
+ KX_PYMETHOD_DOC(SCA_JoystickSensor,SetButton);
/* Hats */
- KX_PYMETHOD_DOC_NOARGS(SCA_JoystickSensor,GetHat);
- KX_PYMETHOD_DOC_VARARGS(SCA_JoystickSensor,SetHat);
+ KX_PYMETHOD_DOC(SCA_JoystickSensor,GetHat);
+ KX_PYMETHOD_DOC(SCA_JoystickSensor,SetHat);
/* number of */
- KX_PYMETHOD_DOC_NOARGS(SCA_JoystickSensor,NumberOfAxes);
- KX_PYMETHOD_DOC_NOARGS(SCA_JoystickSensor,NumberOfButtons);
- KX_PYMETHOD_DOC_NOARGS(SCA_JoystickSensor,NumberOfHats);
- KX_PYMETHOD_DOC_NOARGS(SCA_JoystickSensor,Connected);
-
- /* attribute check */
- static int CheckAxis(void *self)
- {
- SCA_JoystickSensor* sensor = reinterpret_cast<SCA_JoystickSensor*>(self);
- if (sensor->m_axis < 1 || sensor->m_axis > 2)
- {
- PyErr_SetString(PyExc_ValueError, "axis number must be 1 or 2");
- return 1;
- }
- return 0;
- }
- static int CheckHat(void *self)
- {
- SCA_JoystickSensor* sensor = reinterpret_cast<SCA_JoystickSensor*>(self);
- if (sensor->m_hat < 1 || sensor->m_hat > 2)
- {
- PyErr_SetString(PyExc_ValueError, "hat number must be 1 or 2");
- return 1;
- }
- return 0;
- }
+ KX_PYMETHOD_DOC(SCA_JoystickSensor,NumberOfAxes);
+ KX_PYMETHOD_DOC(SCA_JoystickSensor,NumberOfButtons);
+ KX_PYMETHOD_DOC(SCA_JoystickSensor,NumberOfHats);
};
diff --git a/source/gameengine/GameLogic/SCA_KeyboardSensor.cpp b/source/gameengine/GameLogic/SCA_KeyboardSensor.cpp
index a05f9ae9879..a7a6fa93db4 100644
--- a/source/gameengine/GameLogic/SCA_KeyboardSensor.cpp
+++ b/source/gameengine/GameLogic/SCA_KeyboardSensor.cpp
@@ -122,10 +122,6 @@ bool SCA_KeyboardSensor::Evaluate(CValue* eventval)
{
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 = m_pKeyboardMgr->GetInputDevice();
// cerr << "SCA_KeyboardSensor::Eval event, sensing for "<< m_hotkey << " at device " << inputdev << "\n";
@@ -206,43 +202,7 @@ bool SCA_KeyboardSensor::Evaluate(CValue* eventval)
(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;
- }
- }
- 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;
- }
- }
- /* done reading qualifiers */
-
+
if (inevent.m_status == SCA_InputEvent::KX_NO_INPUTSTATUS)
{
if (m_val == 1)
@@ -280,33 +240,7 @@ bool SCA_KeyboardSensor::Evaluate(CValue* eventval)
}
}
}
-
- /* Modify the key state based on qual(s)
- * Tested carefuly. dont 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;
@@ -545,28 +479,52 @@ void SCA_KeyboardSensor::LogKeystrokes(void)
/* ------------------------------------------------------------------------- */
-/* Python Functions */
+/* Python functions : specific */
/* ------------------------------------------------------------------------- */
-//Deprecated ----->
+
+PyObject* SCA_KeyboardSensor::PySetAllMode(PyObject* self,
+ PyObject* args,
+ PyObject* kwds)
+{
+ bool allkeys;
+
+ if (!PyArg_ParseTuple(args, "i", &allkeys))
+ {
+ return NULL;
+ }
+
+ m_bAllKeys = allkeys;
+ Py_Return
+}
+
+
+
+PyObject* SCA_KeyboardSensor::sPySetAllMode(PyObject* self,
+ PyObject* args,
+ PyObject* kwds)
+{
+// printf("sPyIsPositive\n");
+ return ((SCA_KeyboardSensor*) self)->PyIsPositive(self, args, kwds);
+}
+
+
/** 1. GetKey : check which key this sensor looks at */
-const char SCA_KeyboardSensor::GetKey_doc[] =
+char SCA_KeyboardSensor::GetKey_doc[] =
"getKey()\n"
"\tReturn the code of the key this sensor is listening to.\n" ;
PyObject* SCA_KeyboardSensor::PyGetKey(PyObject* self, PyObject* args, PyObject* kwds)
{
- ShowDeprecationWarning("getKey()", "the key property");
return PyInt_FromLong(m_hotkey);
}
/** 2. SetKey: change the key to look at */
-const char SCA_KeyboardSensor::SetKey_doc[] =
+char SCA_KeyboardSensor::SetKey_doc[] =
"setKey(keycode)\n"
"\t- keycode: any code from GameKeys\n"
"\tSet the key this sensor should listen to.\n" ;
PyObject* SCA_KeyboardSensor::PySetKey(PyObject* self, PyObject* args, PyObject* kwds)
{
- ShowDeprecationWarning("setKey()", "the key property");
int keyCode;
if(!PyArg_ParseTuple(args, "i", &keyCode)) {
@@ -581,24 +539,22 @@ PyObject* SCA_KeyboardSensor::PySetKey(PyObject* self, PyObject* args, PyObject*
}
/** 3. GetHold1 : set the first bucky bit */
-const char SCA_KeyboardSensor::GetHold1_doc[] =
+char SCA_KeyboardSensor::GetHold1_doc[] =
"getHold1()\n"
"\tReturn the code of the first key modifier to the key this \n"
"\tsensor is listening to.\n" ;
PyObject* SCA_KeyboardSensor::PyGetHold1(PyObject* self, PyObject* args, PyObject* kwds)
{
- ShowDeprecationWarning("getHold1()", "the hold1 property");
return PyInt_FromLong(m_qual);
}
/** 4. SetHold1: change the first bucky bit */
-const char SCA_KeyboardSensor::SetHold1_doc[] =
+char SCA_KeyboardSensor::SetHold1_doc[] =
"setHold1(keycode)\n"
"\t- keycode: any code from GameKeys\n"
"\tSet the first modifier to the key this sensor should listen to.\n" ;
PyObject* SCA_KeyboardSensor::PySetHold1(PyObject* self, PyObject* args, PyObject* kwds)
{
- ShowDeprecationWarning("setHold1()", "the hold1 property");
int keyCode;
if(!PyArg_ParseTuple(args, "i", &keyCode)) {
@@ -613,24 +569,22 @@ PyObject* SCA_KeyboardSensor::PySetHold1(PyObject* self, PyObject* args, PyObjec
}
/** 5. GetHold2 : get the second bucky bit */
-const char SCA_KeyboardSensor::GetHold2_doc[] =
+char SCA_KeyboardSensor::GetHold2_doc[] =
"getHold2()\n"
"\tReturn the code of the second key modifier to the key this \n"
"\tsensor is listening to.\n" ;
PyObject* SCA_KeyboardSensor::PyGetHold2(PyObject* self, PyObject* args, PyObject* kwds)
{
- ShowDeprecationWarning("getHold2()", "the hold2 property");
return PyInt_FromLong(m_qual2);
}
/** 6. SetHold2: change the second bucky bit */
-const char SCA_KeyboardSensor::SetHold2_doc[] =
+char SCA_KeyboardSensor::SetHold2_doc[] =
"setHold2(keycode)\n"
"\t- keycode: any code from GameKeys\n"
"\tSet the first modifier to the key this sensor should listen to.\n" ;
PyObject* SCA_KeyboardSensor::PySetHold2(PyObject* self, PyObject* args, PyObject* kwds)
{
- ShowDeprecationWarning("setHold2()", "the hold2 property");
int keyCode;
if(!PyArg_ParseTuple(args, "i", &keyCode)) {
@@ -645,14 +599,12 @@ PyObject* SCA_KeyboardSensor::PySetHold2(PyObject* self, PyObject* args, PyObjec
}
-const char SCA_KeyboardSensor::GetPressedKeys_doc[] =
+char SCA_KeyboardSensor::GetPressedKeys_doc[] =
"getPressedKeys()\n"
"\tGet a list of pressed keys that have either been pressed, or just released this frame.\n" ;
PyObject* SCA_KeyboardSensor::PyGetPressedKeys(PyObject* self, PyObject* args, PyObject* kwds)
{
- ShowDeprecationWarning("getPressedKeys()", "getEventList()");
-
SCA_IInputDevice* inputdev = m_pKeyboardMgr->GetInputDevice();
int num = inputdev->GetNumJustEvents();
@@ -687,14 +639,12 @@ PyObject* SCA_KeyboardSensor::PyGetPressedKeys(PyObject* self, PyObject* args, P
-const char SCA_KeyboardSensor::GetCurrentlyPressedKeys_doc[] =
+char SCA_KeyboardSensor::GetCurrentlyPressedKeys_doc[] =
"getCurrentlyPressedKeys()\n"
"\tGet a list of keys that are currently pressed.\n" ;
PyObject* SCA_KeyboardSensor::PyGetCurrentlyPressedKeys(PyObject* self, PyObject* args, PyObject* kwds)
{
-ShowDeprecationWarning("getCurrentlyPressedKeys()", "getEventList()");
-
SCA_IInputDevice* inputdev = m_pKeyboardMgr->GetInputDevice();
int num = inputdev->GetNumActiveEvents();
@@ -727,54 +677,9 @@ SCA_IInputDevice* inputdev = m_pKeyboardMgr->GetInputDevice();
Py_Return;
}
-//<---- Deprecated
-
-KX_PYMETHODDEF_DOC_NOARGS(SCA_KeyboardSensor, getEventList,
-"getEventList()\n"
-"\tGet the list of the keyboard events in this frame.\n")
-{
- SCA_IInputDevice* inputdev = m_pKeyboardMgr->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_SetItem(keypair,0,PyInt_FromLong(i));
- PyList_SetItem(keypair,1,PyInt_FromLong(inevent.m_status));
- PyList_Append(resultlist,keypair);
- }
- }
- return resultlist;
-}
-
-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 (PyInt_Check(value))
- {
- int keycode = PyInt_AsLong(value);
-
- if ((keycode < SCA_IInputDevice::KX_BEGINKEY)
- || (keycode > SCA_IInputDevice::KX_ENDKEY)){
- PyErr_SetString(PyExc_AttributeError, "invalid keycode specified!");
- return NULL;
- }
-
- SCA_IInputDevice* inputdev = m_pKeyboardMgr->GetInputDevice();
- const SCA_InputEvent & inevent = inputdev->GetEventValue((SCA_IInputDevice::KX_EnumInputs) keycode);
- return PyInt_FromLong(inevent.m_status);
- }
-
- Py_Return;
-}
/* ------------------------------------------------------------------------- */
-/* Python Integration Hooks */
+/* Python functions : integration hooks */
/* ------------------------------------------------------------------------- */
PyTypeObject SCA_KeyboardSensor::Type = {
@@ -805,44 +710,23 @@ PyParentObject SCA_KeyboardSensor::Parents[] = {
};
PyMethodDef SCA_KeyboardSensor::Methods[] = {
- //Deprecated functions ------>
- {"getKey", (PyCFunction) SCA_KeyboardSensor::sPyGetKey, METH_VARARGS, (PY_METHODCHAR)GetKey_doc},
- {"setKey", (PyCFunction) SCA_KeyboardSensor::sPySetKey, METH_VARARGS, (PY_METHODCHAR)SetKey_doc},
- {"getHold1", (PyCFunction) SCA_KeyboardSensor::sPyGetHold1, METH_VARARGS, (PY_METHODCHAR)GetHold1_doc},
- {"setHold1", (PyCFunction) SCA_KeyboardSensor::sPySetHold1, METH_VARARGS, (PY_METHODCHAR)SetHold1_doc},
- {"getHold2", (PyCFunction) SCA_KeyboardSensor::sPyGetHold2, METH_VARARGS, (PY_METHODCHAR)GetHold2_doc},
- {"setHold2", (PyCFunction) SCA_KeyboardSensor::sPySetHold2, METH_VARARGS, (PY_METHODCHAR)SetHold2_doc},
- {"getPressedKeys", (PyCFunction) SCA_KeyboardSensor::sPyGetPressedKeys, METH_VARARGS, (PY_METHODCHAR)GetPressedKeys_doc},
- {"getCurrentlyPressedKeys", (PyCFunction) SCA_KeyboardSensor::sPyGetCurrentlyPressedKeys, METH_VARARGS, (PY_METHODCHAR)GetCurrentlyPressedKeys_doc},
- //<----- Deprecated
- KX_PYMETHODTABLE_NOARGS(SCA_KeyboardSensor, getEventList),
- KX_PYMETHODTABLE_O(SCA_KeyboardSensor, getKeyStatus),
- {NULL,NULL} //Sentinel
-};
-
-PyAttributeDef SCA_KeyboardSensor::Attributes[] = {
- KX_PYATTRIBUTE_BOOL_RW("useAllKeys",SCA_KeyboardSensor,m_bAllKeys),
- KX_PYATTRIBUTE_INT_RW("key",0,1000,SCA_KeyboardSensor,m_hotkey),
- KX_PYATTRIBUTE_SHORT_RW("hold1",0,1000,SCA_KeyboardSensor,m_qual),
- KX_PYATTRIBUTE_SHORT_RW("hold2",0,1000,SCA_KeyboardSensor,m_qual2),
- KX_PYATTRIBUTE_STRING_RW("toggleProperty",0,100,SCA_KeyboardSensor,m_toggleprop),
- KX_PYATTRIBUTE_STRING_RW("targetProperty",0,100,SCA_KeyboardSensor,m_targetprop),
- { NULL } //Sentinel
+ {"getKey", (PyCFunction) SCA_KeyboardSensor::sPyGetKey, METH_VARARGS, GetKey_doc},
+ {"setKey", (PyCFunction) SCA_KeyboardSensor::sPySetKey, METH_VARARGS, SetKey_doc},
+ {"getHold1", (PyCFunction) SCA_KeyboardSensor::sPyGetHold1, METH_VARARGS, GetHold1_doc},
+ {"setHold1", (PyCFunction) SCA_KeyboardSensor::sPySetHold1, METH_VARARGS, SetHold1_doc},
+ {"getHold2", (PyCFunction) SCA_KeyboardSensor::sPyGetHold2, METH_VARARGS, GetHold2_doc},
+ {"setHold2", (PyCFunction) SCA_KeyboardSensor::sPySetHold2, METH_VARARGS, SetHold2_doc},
+// {"getUseAllKeys", (PyCFunction) SCA_KeyboardSensor::sPyGetUseAllKeys, METH_VARARGS, GetUseAllKeys_doc},
+// {"setUseAllKeys", (PyCFunction) SCA_KeyboardSensor::sPySetUseAllKeys, METH_VARARGS, SetUseAllKeys_doc},
+ {"getPressedKeys", (PyCFunction) SCA_KeyboardSensor::sPyGetPressedKeys, METH_VARARGS, GetPressedKeys_doc},
+ {"getCurrentlyPressedKeys", (PyCFunction) SCA_KeyboardSensor::sPyGetCurrentlyPressedKeys, METH_VARARGS, GetCurrentlyPressedKeys_doc},
+// {"getKeyEvents", (PyCFunction) SCA_KeyboardSensor::sPyGetKeyEvents, METH_VARARGS, GetKeyEvents_doc},
+ {NULL,NULL} //Sentinel
};
PyObject*
SCA_KeyboardSensor::_getattr(const STR_String& attr)
{
- PyObject* object = _getattr_self(Attributes, this, attr);
- if (object != NULL)
- return object;
_getattr_up(SCA_ISensor);
}
-int SCA_KeyboardSensor::_setattr(const STR_String& attr, PyObject *value)
-{
- int ret = _setattr_self(Attributes, this, attr, value);
- if (ret >= 0)
- return ret;
- return SCA_ISensor::_setattr(attr, value);
-}
diff --git a/source/gameengine/GameLogic/SCA_KeyboardSensor.h b/source/gameengine/GameLogic/SCA_KeyboardSensor.h
index 4efbe9366cc..b86f6931d27 100644
--- a/source/gameengine/GameLogic/SCA_KeyboardSensor.h
+++ b/source/gameengine/GameLogic/SCA_KeyboardSensor.h
@@ -127,9 +127,15 @@ public:
/* --------------------------------------------------------------------- */
virtual PyObject* _getattr(const STR_String& attr);
- virtual int _setattr(const STR_String& attr, PyObject *value);
- //Deprecated functions ----->
+
+ PyObject* PySetAllMode(PyObject* self,
+ PyObject* args,
+ PyObject* kwds);
+ static PyObject* sPySetAllMode(PyObject* self,
+ PyObject* args,
+ PyObject* kwds);
+
/** 1. GetKey : check which key this sensor looks at */
KX_PYMETHOD_DOC(SCA_KeyboardSensor,GetKey);
/** 2. SetKey: change the key to look at */
@@ -146,12 +152,6 @@ public:
KX_PYMETHOD_DOC(SCA_KeyboardSensor,GetPressedKeys);
/** 9. GetCurrrentlyPressedKeys: */
KX_PYMETHOD_DOC(SCA_KeyboardSensor,GetCurrentlyPressedKeys);
- // <------
-
- // KeyEvents:
- KX_PYMETHOD_DOC_NOARGS(SCA_KeyboardSensor,getEventList);
- // KeyStatus:
- KX_PYMETHOD_DOC_O(SCA_KeyboardSensor,getKeyStatus);
};
#endif //__KX_KEYBOARDSENSOR
diff --git a/source/gameengine/GameLogic/SCA_LogicManager.cpp b/source/gameengine/GameLogic/SCA_LogicManager.cpp
index b584b37180f..91e66aea359 100644
--- a/source/gameengine/GameLogic/SCA_LogicManager.cpp
+++ b/source/gameengine/GameLogic/SCA_LogicManager.cpp
@@ -33,7 +33,6 @@
#include "SCA_IController.h"
#include "SCA_IActuator.h"
#include "SCA_EventManager.h"
-#include "SCA_PythonController.h"
#include <set>
#ifdef HAVE_CONFIG_H
@@ -233,6 +232,8 @@ void SCA_LogicManager::BeginFrame(double curtime, double fixedtime)
// for this frame, look up for activated sensors, and build the collection of triggered controllers
// int numsensors = this->m_activatedsensors.size(); /*unused*/
+ set<SmartControllerPtr> triggeredControllerSet;
+
for (vector<SCA_ISensor*>::const_iterator is=m_activatedsensors.begin();
!(is==m_activatedsensors.end());is++)
{
@@ -243,28 +244,19 @@ void SCA_LogicManager::BeginFrame(double curtime, double fixedtime)
{
SCA_IController* contr = *c;//controllerarray->at(c);
if (contr->IsActive())
- {
- m_triggeredControllerSet.insert(SmartControllerPtr(contr,0));
- // So that the controller knows which sensor has activited it.
- // Only needed for the python controller though.
- if (contr->GetType() == &SCA_PythonController::Type)
- {
- SCA_PythonController* pythonController = (SCA_PythonController*)contr;
- pythonController->AddTriggeredSensor(sensor);
- }
- }
+ triggeredControllerSet.insert(SmartControllerPtr(contr,0));
}
//sensor->SetActive(false);
}
// int numtriggered = triggeredControllerSet.size(); /*unused*/
- for (set<SmartControllerPtr>::iterator tit=m_triggeredControllerSet.begin();
- !(tit==m_triggeredControllerSet.end());tit++)
+ for (set<SmartControllerPtr>::iterator tit=triggeredControllerSet.begin();
+ !(tit==triggeredControllerSet.end());tit++)
{
(*tit)->Trigger(this);
}
- m_triggeredControllerSet.clear();
+ triggeredControllerSet.clear();
}
@@ -390,17 +382,6 @@ void SCA_LogicManager::AddActivatedSensor(SCA_ISensor* sensor)
}
}
-void SCA_LogicManager::AddTriggeredController(SCA_IController* controller, SCA_ISensor* sensor)
-{
- m_triggeredControllerSet.insert(SmartControllerPtr(controller,0));
- // so that the controller knows which sensor has activited it
- // only needed for python controller
- if (controller->GetType() == &SCA_PythonController::Type)
- {
- SCA_PythonController* pythonController = (SCA_PythonController*)controller;
- pythonController->AddTriggeredSensor(sensor);
- }
-}
void SCA_LogicManager::AddActiveActuator(SCA_IActuator* actua,CValue* event)
diff --git a/source/gameengine/GameLogic/SCA_LogicManager.h b/source/gameengine/GameLogic/SCA_LogicManager.h
index 50383879d8f..e0d3d506702 100644
--- a/source/gameengine/GameLogic/SCA_LogicManager.h
+++ b/source/gameengine/GameLogic/SCA_LogicManager.h
@@ -99,7 +99,6 @@ class SCA_LogicManager
vector<class SCA_ISensor*> m_activatedsensors;
set<class SmartActuatorPtr> m_activeActuators;
- set<class SmartControllerPtr> m_triggeredControllerSet;
map<SCA_ISensor*,controllerlist > m_sensorcontrollermapje;
@@ -128,7 +127,6 @@ public:
void EndFrame();
void AddActivatedSensor(SCA_ISensor* sensor);
void AddActiveActuator(SCA_IActuator* sensor,class CValue* event);
- void AddTriggeredController(SCA_IController* controller, SCA_ISensor* sensor);
SCA_EventManager* FindEventManager(int eventmgrtype);
void RemoveGameObject(const STR_String& gameobjname);
diff --git a/source/gameengine/GameLogic/SCA_MouseSensor.cpp b/source/gameengine/GameLogic/SCA_MouseSensor.cpp
index 14d9c898980..2298ddb0743 100644
--- a/source/gameengine/GameLogic/SCA_MouseSensor.cpp
+++ b/source/gameengine/GameLogic/SCA_MouseSensor.cpp
@@ -25,7 +25,7 @@
*
* The Original Code is: all of this file.
*
- * Contributor(s): José I. Romero (cleanup and fixes)
+ * Contributor(s): none yet.
*
* ***** END GPL LICENSE BLOCK *****
*/
@@ -59,54 +59,41 @@ SCA_MouseSensor::SCA_MouseSensor(SCA_MouseManager* eventmgr,
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. */
-}
-
-int 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) {
+ switch (m_mousemode) {
case KX_MOUSESENSORMODE_LEFTBUTTON:
- sensor->m_hotkey = SCA_IInputDevice::KX_LEFTMOUSE;
+ m_hotkey = SCA_IInputDevice::KX_LEFTMOUSE;
break;
case KX_MOUSESENSORMODE_MIDDLEBUTTON:
- sensor->m_hotkey = SCA_IInputDevice::KX_MIDDLEMOUSE;
+ m_hotkey = SCA_IInputDevice::KX_MIDDLEMOUSE;
break;
case KX_MOUSESENSORMODE_RIGHTBUTTON:
- sensor->m_hotkey = SCA_IInputDevice::KX_RIGHTMOUSE;
+ m_hotkey = SCA_IInputDevice::KX_RIGHTMOUSE;
break;
case KX_MOUSESENSORMODE_WHEELUP:
- sensor->m_hotkey = SCA_IInputDevice::KX_WHEELUPMOUSE;
+ m_hotkey = SCA_IInputDevice::KX_WHEELUPMOUSE;
break;
case KX_MOUSESENSORMODE_WHEELDOWN:
- sensor->m_hotkey = SCA_IInputDevice::KX_WHEELDOWNMOUSE;
+ m_hotkey = SCA_IInputDevice::KX_WHEELDOWNMOUSE;
break;
default:
; /* ignore, no hotkey */
}
- // return value is used in _setattr(),
- // 0=attribute checked ok (see Attributes array definition)
- return 0;
+ 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. */
}
+
+
CValue* SCA_MouseSensor::GetReplica()
{
SCA_MouseSensor* replica = new SCA_MouseSensor(*this);
@@ -150,6 +137,15 @@ bool SCA_MouseSensor::Evaluate(CValue* event)
bool reset = m_reset && m_level;
SCA_IInputDevice* mousedev = m_pMouseMgr->GetInputDevice();
+
+
+// SCA_ILogicBrick::RegisterEvent(event);
+// if (m_mousemode == KX_MOUSESENSORMODE_MOVEMENT) cout << "\nChecking for movement...";
+//CValue* val = event->GetProperty("val");
+
+ /* both MOUSEX and MOUSEY. Treat all of these as key-presses. */
+ /* So, treat KX_MOUSESENSORMODE_POSITION as */
+ /* KX_MOUSESENSORMODE_POSITIONX || KX_MOUSESENSORMODE_POSITIONY */
m_reset = false;
switch (m_mousemode) {
case KX_MOUSESENSORMODE_LEFTBUTTON:
@@ -159,34 +155,42 @@ bool SCA_MouseSensor::Evaluate(CValue* event)
case KX_MOUSESENSORMODE_WHEELDOWN:
{
const SCA_InputEvent& event = mousedev->GetEventValue(m_hotkey);
- switch (event.m_status){
- case SCA_InputEvent::KX_JUSTACTIVATED:
+ if (event.m_status == 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)
+ } else
+ {
+ if (event.m_status == SCA_InputEvent::KX_JUSTRELEASED)
{
m_val = 0;
result = true;
+ } else
+ {
+ if (event.m_status == SCA_InputEvent::KX_ACTIVE)
+ {
+ if (m_val == 0)
+ {
+ m_val = 1;
+ if (m_level)
+ {
+ result = true;
+ }
+ }
+ } else
+ {
+ 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);
@@ -194,26 +198,27 @@ bool SCA_MouseSensor::Evaluate(CValue* event)
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)
+ 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 )
+ } else
{
- m_val = 0;
- result = true;
- }
- else //KX_NO_IMPUTSTATUS
- {
- if (m_val == 1)
+ if (eventX.m_status == SCA_InputEvent::KX_JUSTRELEASED ||
+ eventY.m_status == SCA_InputEvent::KX_JUSTRELEASED )
{
m_val = 0;
result = true;
+ } else
+ {
+ if (m_val == 1)
+ {
+ m_val = 0;
+ result = true;
+ }
}
}
-
break;
}
default:
@@ -238,67 +243,18 @@ void SCA_MouseSensor::setY(short y)
bool SCA_MouseSensor::isValid(SCA_MouseSensor::KX_MOUSESENSORMODE m)
{
- return ((m > KX_MOUSESENSORMODE_NODEF) && (m < KX_MOUSESENSORMODE_MAX));
-}
-
-/* ------------------------------------------------------------------------- */
-/* Python functions */
-/* ------------------------------------------------------------------------- */
+ bool res = false;
-//Deprecated functions ------>
-/* get x position ---------------------------------------------------------- */
-const char SCA_MouseSensor::GetXPosition_doc[] =
-"getXPosition\n"
-"\tReturns the x-coordinate of the mouse sensor, in frame coordinates.\n"
-"\tThe lower-left corner is the origin. The coordinate is given in\n"
-"\tpixels\n";
-PyObject* SCA_MouseSensor::PyGetXPosition(PyObject* self,
- PyObject* args,
- PyObject* kwds) {
- ShowDeprecationWarning("getXPosition()", "the position property");
- return PyInt_FromLong(m_x);
-}
-
-/* get y position ---------------------------------------------------------- */
-const char SCA_MouseSensor::GetYPosition_doc[] =
-"getYPosition\n"
-"\tReturns the y-coordinate of the mouse sensor, in frame coordinates.\n"
-"\tThe lower-left corner is the origin. The coordinate is given in\n"
-"\tpixels\n";
-PyObject* SCA_MouseSensor::PyGetYPosition(PyObject* self,
- PyObject* args,
- PyObject* kwds) {
- ShowDeprecationWarning("getYPosition()", "the position property");
- return PyInt_FromLong(m_y);
-}
-//<----- Deprecated
-
-KX_PYMETHODDEF_DOC_O(SCA_MouseSensor, getButtonStatus,
-"getButtonStatus(button)\n"
-"\tGet the given button's status (KX_NO_INPUTSTATUS, KX_JUSTACTIVATED, KX_ACTIVE or KX_JUSTRELEASED).\n")
-{
- if (PyInt_Check(value))
- {
- int button = PyInt_AsLong(value);
-
- if ((button < SCA_IInputDevice::KX_LEFTMOUSE)
- || (button > SCA_IInputDevice::KX_MIDDLEMOUSE)){
- PyErr_SetString(PyExc_ValueError, "invalid button specified!");
- return NULL;
- }
-
- SCA_IInputDevice* mousedev = m_pMouseMgr->GetInputDevice();
- const SCA_InputEvent& event = mousedev->GetEventValue((SCA_IInputDevice::KX_EnumInputs) button);
- return PyInt_FromLong(event.m_status);
- }
+ res = ((m > KX_MOUSESENSORMODE_NODEF) && (m < KX_MOUSESENSORMODE_MAX));
- Py_Return;
+ return res;
}
/* ------------------------------------------------------------------------- */
-/* Python Integration Hooks */
+/* Python functions */
/* ------------------------------------------------------------------------- */
+/* Integration hooks ------------------------------------------------------- */
PyTypeObject SCA_MouseSensor::Type = {
PyObject_HEAD_INIT(&PyType_Type)
0,
@@ -327,34 +283,37 @@ PyParentObject SCA_MouseSensor::Parents[] = {
};
PyMethodDef SCA_MouseSensor::Methods[] = {
- //Deprecated functions ------>
- {"getXPosition", (PyCFunction) SCA_MouseSensor::sPyGetXPosition, METH_VARARGS, (PY_METHODCHAR)GetXPosition_doc},
- {"getYPosition", (PyCFunction) SCA_MouseSensor::sPyGetYPosition, METH_VARARGS, (PY_METHODCHAR)GetYPosition_doc},
- //<----- Deprecated
- KX_PYMETHODTABLE_O(SCA_MouseSensor, getButtonStatus),
+ {"getXPosition", (PyCFunction) SCA_MouseSensor::sPyGetXPosition, METH_VARARGS, GetXPosition_doc},
+ {"getYPosition", (PyCFunction) SCA_MouseSensor::sPyGetYPosition, METH_VARARGS, GetYPosition_doc},
{NULL,NULL} //Sentinel
};
-PyAttributeDef SCA_MouseSensor::Attributes[] = {
- KX_PYATTRIBUTE_SHORT_RW_CHECK("mode",KX_MOUSESENSORMODE_NODEF,KX_MOUSESENSORMODE_MAX-1,SCA_MouseSensor,m_mousemode,UpdateHotkey),
- KX_PYATTRIBUTE_SHORT_ARRAY_RO("position",SCA_MouseSensor,m_x,2),
- { NULL } //Sentinel
-};
-
-PyObject* SCA_MouseSensor::_getattr(const STR_String& attr)
-{
- PyObject* object = _getattr_self(Attributes, this, attr);
- if (object != NULL)
- return object;
+PyObject* SCA_MouseSensor::_getattr(const STR_String& attr) {
_getattr_up(SCA_ISensor);
}
-int SCA_MouseSensor::_setattr(const STR_String& attr, PyObject *value)
-{
- int ret = _setattr_self(Attributes, this, attr, value);
- if (ret >= 0)
- return ret;
- return SCA_ISensor::_setattr(attr, value);
+/* get x position ---------------------------------------------------------- */
+char SCA_MouseSensor::GetXPosition_doc[] =
+"getXPosition\n"
+"\tReturns the x-coordinate of the mouse sensor, in frame coordinates.\n"
+"\tThe lower-left corner is the origin. The coordinate is given in\n"
+"\tpixels\n";
+PyObject* SCA_MouseSensor::PyGetXPosition(PyObject* self,
+ PyObject* args,
+ PyObject* kwds) {
+ return PyInt_FromLong(m_x);
+}
+
+/* get y position ---------------------------------------------------------- */
+char SCA_MouseSensor::GetYPosition_doc[] =
+"getYPosition\n"
+"\tReturns the y-coordinate of the mouse sensor, in frame coordinates.\n"
+"\tThe lower-left corner is the origin. The coordinate is given in\n"
+"\tpixels\n";
+PyObject* SCA_MouseSensor::PyGetYPosition(PyObject* self,
+ PyObject* args,
+ PyObject* kwds) {
+ return PyInt_FromLong(m_y);
}
/* eof */
diff --git a/source/gameengine/GameLogic/SCA_MouseSensor.h b/source/gameengine/GameLogic/SCA_MouseSensor.h
index 58ee96c8856..26a1c5e3fd2 100644
--- a/source/gameengine/GameLogic/SCA_MouseSensor.h
+++ b/source/gameengine/GameLogic/SCA_MouseSensor.h
@@ -24,7 +24,7 @@
*
* The Original Code is: all of this file.
*
- * Contributor(s): José I. Romero (cleanup and fixes)
+ * Contributor(s): none yet.
*
* ***** END GPL LICENSE BLOCK *****
*/
@@ -58,7 +58,7 @@ class SCA_MouseSensor : public SCA_ISensor
SCA_IInputDevice::KX_EnumInputs m_hotkey;
/**
- * valid x coordinate, MUST be followed by y coordinate
+ * valid x coordinate
*/
short m_x;
@@ -87,8 +87,6 @@ class SCA_MouseSensor : public SCA_ISensor
bool isValid(KX_MOUSESENSORMODE);
- static int UpdateHotkey(void *self);
-
SCA_MouseSensor(class SCA_MouseManager* keybdmgr,
int startx,int starty,
short int mousemode,
@@ -110,17 +108,11 @@ class SCA_MouseSensor : public SCA_ISensor
/* --------------------------------------------------------------------- */
virtual PyObject* _getattr(const STR_String& attr);
- virtual int _setattr(const STR_String& attr, PyObject *value);
- //Deprecated functions ----->
/* read x-coordinate */
KX_PYMETHOD_DOC(SCA_MouseSensor,GetXPosition);
/* read y-coordinate */
KX_PYMETHOD_DOC(SCA_MouseSensor,GetYPosition);
- //<----- deprecated
-
- // get button status
- KX_PYMETHOD_DOC_O(SCA_MouseSensor,getButtonStatus);
};
diff --git a/source/gameengine/GameLogic/SCA_PropertyActuator.cpp b/source/gameengine/GameLogic/SCA_PropertyActuator.cpp
index f8509fe380e..7062f2cef6a 100644
--- a/source/gameengine/GameLogic/SCA_PropertyActuator.cpp
+++ b/source/gameengine/GameLogic/SCA_PropertyActuator.cpp
@@ -245,57 +245,25 @@ PyParentObject SCA_PropertyActuator::Parents[] = {
};
PyMethodDef SCA_PropertyActuator::Methods[] = {
- //Deprecated functions ------>
- {"setProperty", (PyCFunction) SCA_PropertyActuator::sPySetProperty, METH_VARARGS, (PY_METHODCHAR)SetProperty_doc},
- {"getProperty", (PyCFunction) SCA_PropertyActuator::sPyGetProperty, METH_VARARGS, (PY_METHODCHAR)GetProperty_doc},
- {"setValue", (PyCFunction) SCA_PropertyActuator::sPySetValue, METH_VARARGS, (PY_METHODCHAR)SetValue_doc},
- {"getValue", (PyCFunction) SCA_PropertyActuator::sPyGetValue, METH_VARARGS, (PY_METHODCHAR)GetValue_doc},
- //<----- Deprecated
+ {"setProperty", (PyCFunction) SCA_PropertyActuator::sPySetProperty, METH_VARARGS, SetProperty_doc},
+ {"getProperty", (PyCFunction) SCA_PropertyActuator::sPyGetProperty, METH_VARARGS, GetProperty_doc},
+ {"setValue", (PyCFunction) SCA_PropertyActuator::sPySetValue, METH_VARARGS, SetValue_doc},
+ {"getValue", (PyCFunction) SCA_PropertyActuator::sPyGetValue, METH_VARARGS, GetValue_doc},
{NULL,NULL} //Sentinel
};
PyObject* SCA_PropertyActuator::_getattr(const STR_String& attr) {
- if (attr == "property") {
- return PyString_FromString(m_propname);
- }
- if (attr == "value") {
- return PyString_FromString(m_exprtxt);
- }
_getattr_up(SCA_IActuator);
}
-int SCA_PropertyActuator::_setattr(const STR_String& attr, PyObject *value) {
- if (PyString_Check(value)) {
- char* sval = PyString_AsString(value);
- if (attr == "property") {
- CValue* prop = GetParent()->FindIdentifier(sval);
- bool error = prop->IsError();
- prop->Release();
- if (!prop->IsError()) {
- m_propname = sval;
- return 0;
- } else {
- PyErr_SetString(PyExc_ValueError, "string does not correspond to a property");
- return 1;
- }
- }
- if (attr == "value") {
- m_exprtxt = sval;
- return 0;
- }
- }
- return SCA_IActuator::_setattr(attr, value);
-}
-
/* 1. setProperty */
-const char SCA_PropertyActuator::SetProperty_doc[] =
+char SCA_PropertyActuator::SetProperty_doc[] =
"setProperty(name)\n"
"\t- name: string\n"
"\tSet the property on which to operate. If there is no property\n"
"\tof this name, the call is ignored.\n";
PyObject* SCA_PropertyActuator::PySetProperty(PyObject* self, PyObject* args, PyObject* kwds)
{
- ShowDeprecationWarning("setProperty()", "the 'property' property");
/* Check whether the name exists first ! */
char *nameArg;
if (!PyArg_ParseTuple(args, "s", &nameArg)) {
@@ -315,17 +283,16 @@ PyObject* SCA_PropertyActuator::PySetProperty(PyObject* self, PyObject* args, Py
}
/* 2. getProperty */
-const char SCA_PropertyActuator::GetProperty_doc[] =
+char SCA_PropertyActuator::GetProperty_doc[] =
"getProperty(name)\n"
"\tReturn the property on which the actuator operates.\n";
PyObject* SCA_PropertyActuator::PyGetProperty(PyObject* self, PyObject* args, PyObject* kwds)
{
- ShowDeprecationWarning("getProperty()", "the 'property' property");
return PyString_FromString(m_propname);
}
/* 3. setValue */
-const char SCA_PropertyActuator::SetValue_doc[] =
+char SCA_PropertyActuator::SetValue_doc[] =
"setValue(value)\n"
"\t- value: string\n"
"\tSet the value with which the actuator operates. If the value\n"
@@ -333,7 +300,6 @@ const char SCA_PropertyActuator::SetValue_doc[] =
"\t action is ignored.\n";
PyObject* SCA_PropertyActuator::PySetValue(PyObject* self, PyObject* args, PyObject* kwds)
{
- ShowDeprecationWarning("setValue()", "the value property");
char *valArg;
if(!PyArg_ParseTuple(args, "s", &valArg)) {
return NULL;
@@ -345,12 +311,11 @@ PyObject* SCA_PropertyActuator::PySetValue(PyObject* self, PyObject* args, PyObj
}
/* 4. getValue */
-const char SCA_PropertyActuator::GetValue_doc[] =
+char SCA_PropertyActuator::GetValue_doc[] =
"getValue()\n"
"\tReturns the value with which the actuator operates.\n";
PyObject* SCA_PropertyActuator::PyGetValue(PyObject* self, PyObject* args, PyObject* kwds)
{
- ShowDeprecationWarning("getValue()", "the value property");
return PyString_FromString(m_exprtxt);
}
diff --git a/source/gameengine/GameLogic/SCA_PropertyActuator.h b/source/gameengine/GameLogic/SCA_PropertyActuator.h
index cdfeee4c67d..1e435684572 100644
--- a/source/gameengine/GameLogic/SCA_PropertyActuator.h
+++ b/source/gameengine/GameLogic/SCA_PropertyActuator.h
@@ -86,7 +86,6 @@ public:
/* --------------------------------------------------------------------- */
virtual PyObject* _getattr(const STR_String& attr);
- virtual int _setattr(const STR_String& attr, PyObject *value);
// python wrapped methods
KX_PYMETHOD_DOC(SCA_PropertyActuator,SetProperty);
diff --git a/source/gameengine/GameLogic/SCA_PropertySensor.cpp b/source/gameengine/GameLogic/SCA_PropertySensor.cpp
index 19ee85207bb..c50c011cc63 100644
--- a/source/gameengine/GameLogic/SCA_PropertySensor.cpp
+++ b/source/gameengine/GameLogic/SCA_PropertySensor.cpp
@@ -333,77 +333,30 @@ PyParentObject SCA_PropertySensor::Parents[] = {
};
PyMethodDef SCA_PropertySensor::Methods[] = {
- //Deprecated functions ------>
- {"getType", (PyCFunction) SCA_PropertySensor::sPyGetType, METH_VARARGS, (PY_METHODCHAR)GetType_doc},
- {"setType", (PyCFunction) SCA_PropertySensor::sPySetType, METH_VARARGS, (PY_METHODCHAR)SetType_doc},
- {"getProperty", (PyCFunction) SCA_PropertySensor::sPyGetProperty, METH_VARARGS, (PY_METHODCHAR)GetProperty_doc},
- {"setProperty", (PyCFunction) SCA_PropertySensor::sPySetProperty, METH_VARARGS, (PY_METHODCHAR)SetProperty_doc},
- {"getValue", (PyCFunction) SCA_PropertySensor::sPyGetValue, METH_VARARGS, (PY_METHODCHAR)GetValue_doc},
- {"setValue", (PyCFunction) SCA_PropertySensor::sPySetValue, METH_VARARGS, (PY_METHODCHAR)SetValue_doc},
- //<----- Deprecated
+ {"getType", (PyCFunction) SCA_PropertySensor::sPyGetType, METH_VARARGS, GetType_doc},
+ {"setType", (PyCFunction) SCA_PropertySensor::sPySetType, METH_VARARGS, SetType_doc},
+ {"getProperty", (PyCFunction) SCA_PropertySensor::sPyGetProperty, METH_VARARGS, GetProperty_doc},
+ {"setProperty", (PyCFunction) SCA_PropertySensor::sPySetProperty, METH_VARARGS, SetProperty_doc},
+ {"getValue", (PyCFunction) SCA_PropertySensor::sPyGetValue, METH_VARARGS, GetValue_doc},
+ {"setValue", (PyCFunction) SCA_PropertySensor::sPySetValue, METH_VARARGS, SetValue_doc},
{NULL,NULL} //Sentinel
};
PyObject* SCA_PropertySensor::_getattr(const STR_String& attr) {
- if (attr == "type") {
- return PyInt_FromLong(m_checktype);
- }
- if (attr == "property") {
- return PyString_FromString(m_checkpropname);
- }
- if (attr == "value") {
- return PyString_FromString(m_checkpropval);
- }
_getattr_up(SCA_ISensor); /* implicit return! */
}
-int SCA_PropertySensor::_setattr(const STR_String& attr, PyObject *value) {
- if (PyInt_Check(value)) {
- int ival = PyInt_AsLong(value);
- if (attr == "type") {
- if ((ival <= KX_PROPSENSOR_NODEF) || (ival >= KX_PROPSENSOR_MAX)) {
- PyErr_SetString(PyExc_ValueError, "type out of range");
- return 1;
- }
- m_checktype = ival;
- }
- return 0;
- }
- if (PyString_Check(value)) {
- char* sval = PyString_AsString(value);
- if (attr == "property") {
- CValue *prop = FindIdentifier(STR_String(sval));
- bool error = prop->IsError();
- prop->Release();
- if (error) {
- PyErr_SetString(PyExc_ValueError, "string does not correspond to a property");
- return 1;
- }
- m_checkpropname = sval;
- } else if (attr == "value") {
- if (!validValueForProperty(sval, m_checkpropname)) {
- PyErr_SetString(PyExc_ValueError, "string does not represent a suitable value for the property");
- return 1;
- }
- m_checkpropval = sval;
- }
- return 0;
- }
- return SCA_ISensor::_setattr(attr, value);
-}
-
/* 1. getType */
-const char SCA_PropertySensor::GetType_doc[] =
+char SCA_PropertySensor::GetType_doc[] =
"getType()\n"
"\tReturns the type of check this sensor performs.\n";
PyObject* SCA_PropertySensor::PyGetType(PyObject* self, PyObject* args, PyObject* kwds)
{
- ShowDeprecationWarning("getType()", "the type property");
return PyInt_FromLong(m_checktype);
}
/* 2. setType */
-const char SCA_PropertySensor::SetType_doc[] =
+char SCA_PropertySensor::SetType_doc[] =
"setType(type)\n"
"\t- type: KX_PROPSENSOR_EQUAL, KX_PROPSENSOR_NOTEQUAL,\n"
"\t KX_PROPSENSOR_INTERVAL, KX_PROPSENSOR_CHANGED,\n"
@@ -411,7 +364,6 @@ const char SCA_PropertySensor::SetType_doc[] =
"\tSet the type of check to perform.\n";
PyObject* SCA_PropertySensor::PySetType(PyObject* self, PyObject* args, PyObject* kwds)
{
- ShowDeprecationWarning("setType()", "the type property");
int typeArg;
if (!PyArg_ParseTuple(args, "i", &typeArg)) {
@@ -427,24 +379,22 @@ PyObject* SCA_PropertySensor::PySetType(PyObject* self, PyObject* args, PyObject
}
/* 3. getProperty */
-const char SCA_PropertySensor::GetProperty_doc[] =
+char SCA_PropertySensor::GetProperty_doc[] =
"getProperty()\n"
"\tReturn the property with which the sensor operates.\n";
PyObject* SCA_PropertySensor::PyGetProperty(PyObject* self, PyObject* args, PyObject* kwds)
{
- ShowDeprecationWarning("getProperty()", "the 'property' property");
return PyString_FromString(m_checkpropname);
}
/* 4. setProperty */
-const char SCA_PropertySensor::SetProperty_doc[] =
+char SCA_PropertySensor::SetProperty_doc[] =
"setProperty(name)\n"
"\t- name: string\n"
"\tSets the property with which to operate. If there is no property\n"
"\tof this name, the call is ignored.\n";
PyObject* SCA_PropertySensor::PySetProperty(PyObject* self, PyObject* args, PyObject* kwds)
{
- ShowDeprecationWarning("setProperty()", "the 'property' property");
/* We should query whether the name exists. Or should we create a prop */
/* on the fly? */
char *propNameArg = NULL;
@@ -464,17 +414,16 @@ PyObject* SCA_PropertySensor::PySetProperty(PyObject* self, PyObject* args, PyOb
}
/* 5. getValue */
-const char SCA_PropertySensor::GetValue_doc[] =
+char SCA_PropertySensor::GetValue_doc[] =
"getValue()\n"
"\tReturns the value with which the sensor operates.\n";
PyObject* SCA_PropertySensor::PyGetValue(PyObject* self, PyObject* args, PyObject* kwds)
{
- ShowDeprecationWarning("getValue()", "the value property");
return PyString_FromString(m_checkpropval);
}
/* 6. setValue */
-const char SCA_PropertySensor::SetValue_doc[] =
+char SCA_PropertySensor::SetValue_doc[] =
"setValue(value)\n"
"\t- value: string\n"
"\tSet the value with which the sensor operates. If the value\n"
@@ -482,7 +431,6 @@ const char SCA_PropertySensor::SetValue_doc[] =
"\t action is ignored.\n";
PyObject* SCA_PropertySensor::PySetValue(PyObject* self, PyObject* args, PyObject* kwds)
{
- ShowDeprecationWarning("setValue()", "the value property");
/* Here, we need to check whether the value is 'valid' for this property.*/
/* We know that the property exists, or is NULL. */
char *propValArg = NULL;
diff --git a/source/gameengine/GameLogic/SCA_PropertySensor.h b/source/gameengine/GameLogic/SCA_PropertySensor.h
index 81203c78f9d..6871cb3afdc 100644
--- a/source/gameengine/GameLogic/SCA_PropertySensor.h
+++ b/source/gameengine/GameLogic/SCA_PropertySensor.h
@@ -90,7 +90,6 @@ public:
/* --------------------------------------------------------------------- */
virtual PyObject* _getattr(const STR_String& attr);
- virtual int _setattr(const STR_String& attr, PyObject *value);
/* 1. getType */
KX_PYMETHOD_DOC(SCA_PropertySensor,GetType);
diff --git a/source/gameengine/GameLogic/SCA_PythonController.cpp b/source/gameengine/GameLogic/SCA_PythonController.cpp
index e879481a444..cd1b029fc34 100644
--- a/source/gameengine/GameLogic/SCA_PythonController.cpp
+++ b/source/gameengine/GameLogic/SCA_PythonController.cpp
@@ -33,11 +33,8 @@
#include "SCA_LogicManager.h"
#include "SCA_ISensor.h"
#include "SCA_IActuator.h"
-#include "PyObjectPlus.h"
#include "compile.h"
#include "eval.h"
-#include <algorithm>
-
#ifdef HAVE_CONFIG_H
#include <config.h>
@@ -142,16 +139,8 @@ void SCA_PythonController::SetDictionary(PyObject* pythondictionary)
m_pythondictionary = PyDict_Copy(pythondictionary); /* new reference */
}
-int SCA_PythonController::IsTriggered(class SCA_ISensor* sensor)
-{
- if (std::find(m_triggeredSensors.begin(), m_triggeredSensors.end(), sensor) !=
- m_triggeredSensors.end())
- return 1;
- return 0;
-}
-
#if 0
-static const char* sPyGetCurrentController__doc__;
+static char* sPyGetCurrentController__doc__;
#endif
@@ -162,7 +151,7 @@ PyObject* SCA_PythonController::sPyGetCurrentController(PyObject* self)
}
#if 0
-static const char* sPyAddActiveActuator__doc__;
+static char* sPyAddActiveActuator__doc__;
#endif
PyObject* SCA_PythonController::sPyAddActiveActuator(
@@ -199,9 +188,9 @@ PyObject* SCA_PythonController::sPyAddActiveActuator(
}
-const char* SCA_PythonController::sPyGetCurrentController__doc__ = "getCurrentController()";
-const char* SCA_PythonController::sPyAddActiveActuator__doc__= "addActiveActuator(actuator,bool)";
-const char SCA_PythonController::GetActuators_doc[] = "getActuator";
+char* SCA_PythonController::sPyGetCurrentController__doc__ = "getCurrentController()";
+char* SCA_PythonController::sPyAddActiveActuator__doc__= "addActiveActuator(actuator,bool)";
+char SCA_PythonController::GetActuators_doc[] = "getActuator";
PyTypeObject SCA_PythonController::Type = {
PyObject_HEAD_INIT(&PyType_Type)
@@ -229,15 +218,13 @@ PyParentObject SCA_PythonController::Parents[] = {
NULL
};
PyMethodDef SCA_PythonController::Methods[] = {
- {"getActuators", (PyCFunction) SCA_PythonController::sPyGetActuators, METH_NOARGS, (PY_METHODCHAR)SCA_PythonController::GetActuators_doc},
- {"getActuator", (PyCFunction) SCA_PythonController::sPyGetActuator, METH_O, (PY_METHODCHAR)SCA_PythonController::GetActuator_doc},
- {"getSensors", (PyCFunction) SCA_PythonController::sPyGetSensors, METH_NOARGS, (PY_METHODCHAR)SCA_PythonController::GetSensors_doc},
- {"getSensor", (PyCFunction) SCA_PythonController::sPyGetSensor, METH_O, (PY_METHODCHAR)SCA_PythonController::GetSensor_doc},
- {"setScript", (PyCFunction) SCA_PythonController::sPySetScript, METH_O},
- //Deprecated functions ------>
+ {"getActuators", (PyCFunction) SCA_PythonController::sPyGetActuators, METH_NOARGS, SCA_PythonController::GetActuators_doc},
+ {"getActuator", (PyCFunction) SCA_PythonController::sPyGetActuator, METH_O, SCA_PythonController::GetActuator_doc},
+ {"getSensors", (PyCFunction) SCA_PythonController::sPyGetSensors, METH_NOARGS, SCA_PythonController::GetSensors_doc},
+ {"getSensor", (PyCFunction) SCA_PythonController::sPyGetSensor, METH_O, SCA_PythonController::GetSensor_doc},
{"getScript", (PyCFunction) SCA_PythonController::sPyGetScript, METH_NOARGS},
+ {"setScript", (PyCFunction) SCA_PythonController::sPySetScript, METH_O},
{"getState", (PyCFunction) SCA_PythonController::sPyGetState, METH_NOARGS},
- //<----- Deprecated
{NULL,NULL} //Sentinel
};
@@ -261,17 +248,9 @@ void SCA_PythonController::Trigger(SCA_LogicManager* logicmgr)
{
// didn't compile, so instead of compile, complain
// something is wrong, tell the user what went wrong
- printf("Python compile error from controller \"%s\": \n", GetName().Ptr());
+ printf("PYTHON SCRIPT ERROR:\n");
//PyRun_SimpleString(m_scriptText.Ptr());
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 free'd, after blender
- * has alredy dealocated the pointer */
- PySys_SetObject( "last_traceback", Py_None);
- PyErr_Clear(); /* just to be sure */
-
return;
}
m_bModified=false;
@@ -306,16 +285,8 @@ void SCA_PythonController::Trigger(SCA_LogicManager* logicmgr)
else
{
// something is wrong, tell the user what went wrong
- printf("Python script error from controller \"%s\": \n", GetName().Ptr());
+ printf("PYTHON SCRIPT ERROR:\n");
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 free'd, after blender
- * has alredy dealocated the pointer */
- PySys_SetObject( "last_traceback", Py_None);
- PyErr_Clear(); /* just to be sure */
-
//PyRun_SimpleString(m_scriptText.Ptr());
}
@@ -323,7 +294,7 @@ void SCA_PythonController::Trigger(SCA_LogicManager* logicmgr)
// something in this dictionary and crash?
PyDict_Clear(excdict);
Py_DECREF(excdict);
- m_triggeredSensors.erase(m_triggeredSensors.begin(), m_triggeredSensors.end());
+
m_sCurrentController = NULL;
}
@@ -331,27 +302,9 @@ void SCA_PythonController::Trigger(SCA_LogicManager* logicmgr)
PyObject* SCA_PythonController::_getattr(const STR_String& attr)
{
- if (attr == "script") {
- return PyString_FromString(m_scriptText);
- }
- if (attr == "state") {
- return PyInt_FromLong(m_statemask);
- }
_getattr_up(SCA_IController);
}
-int SCA_PythonController::_setattr(const STR_String& attr, PyObject *value)
-{
- if (attr == "script") {
- PyErr_SetString(PyExc_AttributeError, "script is read only, use setScript() to update the script");
- return 1;
- }
- if (attr == "state") {
- PyErr_SetString(PyExc_AttributeError, "state is read only");
- return 1;
- }
- return SCA_IController::_setattr(attr, value);
-}
PyObject* SCA_PythonController::PyGetActuators(PyObject* self)
@@ -365,7 +318,7 @@ PyObject* SCA_PythonController::PyGetActuators(PyObject* self)
return resultlist;
}
-const char SCA_PythonController::GetSensor_doc[] =
+char SCA_PythonController::GetSensor_doc[] =
"GetSensor (char sensorname) return linked sensor that is named [sensorname]\n";
PyObject*
SCA_PythonController::PyGetSensor(PyObject* self, PyObject* value)
@@ -395,7 +348,7 @@ SCA_PythonController::PyGetSensor(PyObject* self, PyObject* value)
-const char SCA_PythonController::GetActuator_doc[] =
+char SCA_PythonController::GetActuator_doc[] =
"GetActuator (char sensorname) return linked actuator that is named [actuatorname]\n";
PyObject*
SCA_PythonController::PyGetActuator(PyObject* self, PyObject* value)
@@ -424,7 +377,7 @@ SCA_PythonController::PyGetActuator(PyObject* self, PyObject* value)
}
-const char SCA_PythonController::GetSensors_doc[] = "getSensors returns a list of all attached sensors";
+char SCA_PythonController::GetSensors_doc[] = "getSensors returns a list of all attached sensors";
PyObject*
SCA_PythonController::PyGetSensors(PyObject* self)
{
@@ -440,7 +393,6 @@ SCA_PythonController::PyGetSensors(PyObject* self)
/* 1. getScript */
PyObject* SCA_PythonController::PyGetScript(PyObject* self)
{
- ShowDeprecationWarning("getScript()", "the script property");
return PyString_FromString(m_scriptText);
}
@@ -464,7 +416,6 @@ PyObject* SCA_PythonController::PySetScript(PyObject* self, PyObject* value)
/* 1. getScript */
PyObject* SCA_PythonController::PyGetState(PyObject* self)
{
- ShowDeprecationWarning("getState()", "the state property");
return PyInt_FromLong(m_statemask);
}
diff --git a/source/gameengine/GameLogic/SCA_PythonController.h b/source/gameengine/GameLogic/SCA_PythonController.h
index 1918cc488d8..39b6c68c359 100644
--- a/source/gameengine/GameLogic/SCA_PythonController.h
+++ b/source/gameengine/GameLogic/SCA_PythonController.h
@@ -36,8 +36,6 @@
#include "SCA_LogicManager.h"
#include "BoolValue.h"
-#include <vector>
-
class SCA_IObject;
class SCA_PythonController : public SCA_IController
{
@@ -49,7 +47,6 @@ class SCA_PythonController : public SCA_IController
STR_String m_scriptText;
STR_String m_scriptName;
PyObject* m_pythondictionary;
- std::vector<class SCA_ISensor*> m_triggeredSensors;
public:
static SCA_PythonController* m_sCurrentController; // protected !!!
@@ -67,17 +64,13 @@ class SCA_PythonController : public SCA_IController
void SetScriptText(const STR_String& text);
void SetScriptName(const STR_String& name);
void SetDictionary(PyObject* pythondictionary);
- void AddTriggeredSensor(class SCA_ISensor* sensor)
- { m_triggeredSensors.push_back(sensor); }
- int IsTriggered(class SCA_ISensor* sensor);
- static const char* sPyGetCurrentController__doc__;
+ static char* sPyGetCurrentController__doc__;
static PyObject* sPyGetCurrentController(PyObject* self);
- static const char* sPyAddActiveActuator__doc__;
+ static char* sPyAddActiveActuator__doc__;
static PyObject* sPyAddActiveActuator(PyObject* self,
PyObject* args);
virtual PyObject* _getattr(const STR_String& attr);
- virtual int _setattr(const STR_String& attr, PyObject *value);
KX_PYMETHOD_DOC_NOARGS(SCA_PythonController,GetSensors);
KX_PYMETHOD_DOC_NOARGS(SCA_PythonController,GetActuators);
diff --git a/source/gameengine/GameLogic/SCA_RandomActuator.cpp b/source/gameengine/GameLogic/SCA_RandomActuator.cpp
index 8dd405c3d82..0a1ac2d0668 100644
--- a/source/gameengine/GameLogic/SCA_RandomActuator.cpp
+++ b/source/gameengine/GameLogic/SCA_RandomActuator.cpp
@@ -339,92 +339,38 @@ PyParentObject SCA_RandomActuator::Parents[] = {
};
PyMethodDef SCA_RandomActuator::Methods[] = {
- //Deprecated functions ------>
- {"setSeed", (PyCFunction) SCA_RandomActuator::sPySetSeed, METH_VARARGS, (PY_METHODCHAR)SetSeed_doc},
- {"getSeed", (PyCFunction) SCA_RandomActuator::sPyGetSeed, METH_VARARGS, (PY_METHODCHAR)GetSeed_doc},
- {"getPara1", (PyCFunction) SCA_RandomActuator::sPyGetPara1, METH_VARARGS, (PY_METHODCHAR)GetPara1_doc},
- {"getPara2", (PyCFunction) SCA_RandomActuator::sPyGetPara2, METH_VARARGS, (PY_METHODCHAR)GetPara2_doc},
- {"getDistribution", (PyCFunction) SCA_RandomActuator::sPyGetDistribution, METH_VARARGS, (PY_METHODCHAR)GetDistribution_doc},
- {"setProperty", (PyCFunction) SCA_RandomActuator::sPySetProperty, METH_VARARGS, (PY_METHODCHAR)SetProperty_doc},
- {"getProperty", (PyCFunction) SCA_RandomActuator::sPyGetProperty, METH_VARARGS, (PY_METHODCHAR)GetProperty_doc},
- //<----- Deprecated
- {"setBoolConst", (PyCFunction) SCA_RandomActuator::sPySetBoolConst, METH_VARARGS, (PY_METHODCHAR)SetBoolConst_doc},
- {"setBoolUniform", (PyCFunction) SCA_RandomActuator::sPySetBoolUniform, METH_VARARGS, (PY_METHODCHAR)SetBoolUniform_doc},
- {"setBoolBernouilli",(PyCFunction) SCA_RandomActuator::sPySetBoolBernouilli, METH_VARARGS, (PY_METHODCHAR)SetBoolBernouilli_doc},
- {"setIntConst", (PyCFunction) SCA_RandomActuator::sPySetIntConst, METH_VARARGS, (PY_METHODCHAR)SetIntConst_doc},
- {"setIntUniform", (PyCFunction) SCA_RandomActuator::sPySetIntUniform, METH_VARARGS, (PY_METHODCHAR)SetIntUniform_doc},
- {"setIntPoisson", (PyCFunction) SCA_RandomActuator::sPySetIntPoisson, METH_VARARGS, (PY_METHODCHAR)SetIntPoisson_doc},
- {"setFloatConst", (PyCFunction) SCA_RandomActuator::sPySetFloatConst, METH_VARARGS, (PY_METHODCHAR)SetFloatConst_doc},
- {"setFloatUniform", (PyCFunction) SCA_RandomActuator::sPySetFloatUniform, METH_VARARGS, (PY_METHODCHAR)SetFloatUniform_doc},
- {"setFloatNormal", (PyCFunction) SCA_RandomActuator::sPySetFloatNormal, METH_VARARGS, (PY_METHODCHAR)SetFloatNormal_doc},
- {"setFloatNegativeExponential", (PyCFunction) SCA_RandomActuator::sPySetFloatNegativeExponential, METH_VARARGS, (PY_METHODCHAR)SetFloatNegativeExponential_doc},
+ {"setSeed", (PyCFunction) SCA_RandomActuator::sPySetSeed, METH_VARARGS, SetSeed_doc},
+ {"getSeed", (PyCFunction) SCA_RandomActuator::sPyGetSeed, METH_VARARGS, GetSeed_doc},
+ {"getPara1", (PyCFunction) SCA_RandomActuator::sPyGetPara1, METH_VARARGS, GetPara1_doc},
+ {"getPara2", (PyCFunction) SCA_RandomActuator::sPyGetPara2, METH_VARARGS, GetPara2_doc},
+ {"getDistribution", (PyCFunction) SCA_RandomActuator::sPyGetDistribution, METH_VARARGS, GetDistribution_doc},
+ {"setProperty", (PyCFunction) SCA_RandomActuator::sPySetProperty, METH_VARARGS, SetProperty_doc},
+ {"getProperty", (PyCFunction) SCA_RandomActuator::sPyGetProperty, METH_VARARGS, GetProperty_doc},
+ {"setBoolConst", (PyCFunction) SCA_RandomActuator::sPySetBoolConst, METH_VARARGS, SetBoolConst_doc},
+ {"setBoolUniform", (PyCFunction) SCA_RandomActuator::sPySetBoolUniform, METH_VARARGS, SetBoolUniform_doc},
+ {"setBoolBernouilli",(PyCFunction) SCA_RandomActuator::sPySetBoolBernouilli, METH_VARARGS, SetBoolBernouilli_doc},
+ {"setIntConst", (PyCFunction) SCA_RandomActuator::sPySetIntConst, METH_VARARGS, SetIntConst_doc},
+ {"setIntUniform", (PyCFunction) SCA_RandomActuator::sPySetIntUniform, METH_VARARGS, SetIntUniform_doc},
+ {"setIntPoisson", (PyCFunction) SCA_RandomActuator::sPySetIntPoisson, METH_VARARGS, SetIntPoisson_doc},
+ {"setFloatConst", (PyCFunction) SCA_RandomActuator::sPySetFloatConst, METH_VARARGS, SetFloatConst_doc},
+ {"setFloatUniform", (PyCFunction) SCA_RandomActuator::sPySetFloatUniform, METH_VARARGS, SetFloatUniform_doc},
+ {"setFloatNormal", (PyCFunction) SCA_RandomActuator::sPySetFloatNormal, METH_VARARGS, SetFloatNormal_doc},
+ {"setFloatNegativeExponential", (PyCFunction) SCA_RandomActuator::sPySetFloatNegativeExponential, METH_VARARGS, SetFloatNegativeExponential_doc},
{NULL,NULL} //Sentinel
};
PyObject* SCA_RandomActuator::_getattr(const STR_String& attr) {
- if (attr == "seed") {
- return PyInt_FromLong(m_base->GetSeed());
- }
- if (attr == "para1") {
- return PyFloat_FromDouble(m_parameter1);
- }
- if (attr == "para2") {
- return PyFloat_FromDouble(m_parameter2);
- }
- if (attr == "distribution") {
- return PyInt_FromLong(m_distribution);
- }
- if (attr == "property") {
- return PyString_FromString(m_propname);
- }
_getattr_up(SCA_IActuator);
}
-int SCA_RandomActuator::_setattr(const STR_String& attr, PyObject *value)
-{
- if (attr == "para1") {
- PyErr_SetString(PyExc_AttributeError, "para1 is read only");
- }
- if (attr == "para2") {
- PyErr_SetString(PyExc_AttributeError, "para2 is read only");
- }
- if (attr == "distribution") {
- PyErr_SetString(PyExc_AttributeError, "distribution is read only");
- }
- if (PyInt_Check(value)) {
- int ival = PyInt_AsLong(value);
- if (attr == "seed") {
- m_base->SetSeed(ival);
- }
- return 0;
- }
- if (PyString_Check(value)) {
- char* sval = PyString_AsString(value);
- if (attr == "property") {
- CValue* prop = GetParent()->FindIdentifier(sval);
- bool error = prop->IsError();
- prop->Release();
- if (!prop->IsError()) {
- m_propname = sval;
- return 0;
- } else {
- PyErr_SetString(PyExc_ValueError, "string does not correspond to a property");
- return 1;
- }
- }
- }
- return SCA_IActuator::_setattr(attr, value);
-}
-
/* 1. setSeed */
-const char SCA_RandomActuator::SetSeed_doc[] =
+char SCA_RandomActuator::SetSeed_doc[] =
"setSeed(seed)\n"
"\t- seed: integer\n"
"\tSet the initial seed of the generator. Equal seeds produce\n"
"\tequal series. If the seed is 0, the generator will produce\n"
"\tthe same value on every call.\n";
PyObject* SCA_RandomActuator::PySetSeed(PyObject* self, PyObject* args, PyObject* kwds) {
- ShowDeprecationWarning("setSeed()", "the seed property");
long seedArg;
if(!PyArg_ParseTuple(args, "i", &seedArg)) {
return NULL;
@@ -435,54 +381,49 @@ PyObject* SCA_RandomActuator::PySetSeed(PyObject* self, PyObject* args, PyObject
Py_Return;
}
/* 2. getSeed */
-const char SCA_RandomActuator::GetSeed_doc[] =
+char SCA_RandomActuator::GetSeed_doc[] =
"getSeed()\n"
"\tReturns the initial seed of the generator. Equal seeds produce\n"
"\tequal series.\n";
PyObject* SCA_RandomActuator::PyGetSeed(PyObject* self, PyObject* args, PyObject* kwds) {
- ShowDeprecationWarning("getSeed()", "the seed property");
return PyInt_FromLong(m_base->GetSeed());
}
/* 4. getPara1 */
-const char SCA_RandomActuator::GetPara1_doc[] =
+char SCA_RandomActuator::GetPara1_doc[] =
"getPara1()\n"
"\tReturns the first parameter of the active distribution. Refer\n"
"\tto the documentation of the generator types for the meaning\n"
"\tof this value.";
PyObject* SCA_RandomActuator::PyGetPara1(PyObject* self, PyObject* args, PyObject* kwds) {
- ShowDeprecationWarning("getPara1()", "the para1 property");
return PyFloat_FromDouble(m_parameter1);
}
/* 6. getPara2 */
-const char SCA_RandomActuator::GetPara2_doc[] =
+char SCA_RandomActuator::GetPara2_doc[] =
"getPara2()\n"
"\tReturns the first parameter of the active distribution. Refer\n"
"\tto the documentation of the generator types for the meaning\n"
"\tof this value.";
PyObject* SCA_RandomActuator::PyGetPara2(PyObject* self, PyObject* args, PyObject* kwds) {
- ShowDeprecationWarning("getPara2()", "the para2 property");
return PyFloat_FromDouble(m_parameter2);
}
/* 8. getDistribution */
-const char SCA_RandomActuator::GetDistribution_doc[] =
+char SCA_RandomActuator::GetDistribution_doc[] =
"getDistribution()\n"
"\tReturns the type of the active distribution.\n";
PyObject* SCA_RandomActuator::PyGetDistribution(PyObject* self, PyObject* args, PyObject* kwds) {
- ShowDeprecationWarning("getDistribution()", "the distribution property");
return PyInt_FromLong(m_distribution);
}
/* 9. setProperty */
-const char SCA_RandomActuator::SetProperty_doc[] =
+char SCA_RandomActuator::SetProperty_doc[] =
"setProperty(name)\n"
"\t- name: string\n"
"\tSet the property to which the random value is assigned. If the \n"
"\tgenerator and property types do not match, the assignment is ignored.\n";
PyObject* SCA_RandomActuator::PySetProperty(PyObject* self, PyObject* args, PyObject* kwds) {
- ShowDeprecationWarning("setProperty()", "the 'property' property");
char *nameArg;
if (!PyArg_ParseTuple(args, "s", &nameArg)) {
return NULL;
@@ -500,17 +441,16 @@ PyObject* SCA_RandomActuator::PySetProperty(PyObject* self, PyObject* args, PyOb
Py_Return;
}
/* 10. getProperty */
-const char SCA_RandomActuator::GetProperty_doc[] =
+char SCA_RandomActuator::GetProperty_doc[] =
"getProperty(name)\n"
"\tReturn the property to which the random value is assigned. If the \n"
"\tgenerator and property types do not match, the assignment is ignored.\n";
PyObject* SCA_RandomActuator::PyGetProperty(PyObject* self, PyObject* args, PyObject* kwds) {
- ShowDeprecationWarning("getProperty()", "the 'property' property");
return PyString_FromString(m_propname);
}
/* 11. setBoolConst */
-const char SCA_RandomActuator::SetBoolConst_doc[] =
+char SCA_RandomActuator::SetBoolConst_doc[] =
"setBoolConst(value)\n"
"\t- value: 0 or 1\n"
"\tSet this generator to produce a constant boolean value.\n";
@@ -523,12 +463,14 @@ PyObject* SCA_RandomActuator::PySetBoolConst(PyObject* self,
}
m_distribution = KX_RANDOMACT_BOOL_CONST;
- m_parameter1 = (paraArg) ? 1.0 : 0.0;
+ if (paraArg) {
+ m_parameter1 = 1;
+ }
Py_Return;
}
/* 12. setBoolUniform, */
-const char SCA_RandomActuator::SetBoolUniform_doc[] =
+char SCA_RandomActuator::SetBoolUniform_doc[] =
"setBoolUniform()\n"
"\tSet this generator to produce true and false, each with 50%% chance of occuring\n";
PyObject* SCA_RandomActuator::PySetBoolUniform(PyObject* self,
@@ -540,7 +482,7 @@ PyObject* SCA_RandomActuator::PySetBoolUniform(PyObject* self,
Py_Return;
}
/* 13. setBoolBernouilli, */
-const char SCA_RandomActuator::SetBoolBernouilli_doc[] =
+char SCA_RandomActuator::SetBoolBernouilli_doc[] =
"setBoolBernouilli(value)\n"
"\t- value: a float between 0 and 1\n"
"\tReturn false value * 100%% of the time.\n";
@@ -558,7 +500,7 @@ PyObject* SCA_RandomActuator::PySetBoolBernouilli(PyObject* self,
Py_Return;
}
/* 14. setIntConst,*/
-const char SCA_RandomActuator::SetIntConst_doc[] =
+char SCA_RandomActuator::SetIntConst_doc[] =
"setIntConst(value)\n"
"\t- value: integer\n"
"\tAlways return value\n";
@@ -576,7 +518,7 @@ PyObject* SCA_RandomActuator::PySetIntConst(PyObject* self,
Py_Return;
}
/* 15. setIntUniform,*/
-const char SCA_RandomActuator::SetIntUniform_doc[] =
+char SCA_RandomActuator::SetIntUniform_doc[] =
"setIntUniform(lower_bound, upper_bound)\n"
"\t- lower_bound: integer\n"
"\t- upper_bound: integer\n"
@@ -597,7 +539,7 @@ PyObject* SCA_RandomActuator::PySetIntUniform(PyObject* self,
Py_Return;
}
/* 16. setIntPoisson, */
-const char SCA_RandomActuator::SetIntPoisson_doc[] =
+char SCA_RandomActuator::SetIntPoisson_doc[] =
"setIntPoisson(value)\n"
"\t- value: float\n"
"\tReturn a Poisson-distributed number. This performs a series\n"
@@ -617,7 +559,7 @@ PyObject* SCA_RandomActuator::PySetIntPoisson(PyObject* self,
Py_Return;
}
/* 17. setFloatConst,*/
-const char SCA_RandomActuator::SetFloatConst_doc[] =
+char SCA_RandomActuator::SetFloatConst_doc[] =
"setFloatConst(value)\n"
"\t- value: float\n"
"\tAlways return value\n";
@@ -635,7 +577,7 @@ PyObject* SCA_RandomActuator::PySetFloatConst(PyObject* self,
Py_Return;
}
/* 18. setFloatUniform, */
-const char SCA_RandomActuator::SetFloatUniform_doc[] =
+char SCA_RandomActuator::SetFloatUniform_doc[] =
"setFloatUniform(lower_bound, upper_bound)\n"
"\t- lower_bound: float\n"
"\t- upper_bound: float\n"
@@ -656,7 +598,7 @@ PyObject* SCA_RandomActuator::PySetFloatUniform(PyObject* self,
Py_Return;
}
/* 19. setFloatNormal, */
-const char SCA_RandomActuator::SetFloatNormal_doc[] =
+char SCA_RandomActuator::SetFloatNormal_doc[] =
"setFloatNormal(mean, standard_deviation)\n"
"\t- mean: float\n"
"\t- standard_deviation: float\n"
@@ -677,7 +619,7 @@ PyObject* SCA_RandomActuator::PySetFloatNormal(PyObject* self,
Py_Return;
}
/* 20. setFloatNegativeExponential, */
-const char SCA_RandomActuator::SetFloatNegativeExponential_doc[] =
+char SCA_RandomActuator::SetFloatNegativeExponential_doc[] =
"setFloatNegativeExponential(half_life)\n"
"\t- half_life: float\n"
"\tReturn negative-exponentially distributed numbers. The half-life 'time'\n"
diff --git a/source/gameengine/GameLogic/SCA_RandomActuator.h b/source/gameengine/GameLogic/SCA_RandomActuator.h
index 2fc14f9a0b7..f6da0595d1a 100644
--- a/source/gameengine/GameLogic/SCA_RandomActuator.h
+++ b/source/gameengine/GameLogic/SCA_RandomActuator.h
@@ -97,7 +97,6 @@ class SCA_RandomActuator : public SCA_IActuator
/* --------------------------------------------------------------------- */
virtual PyObject* _getattr(const STR_String& attr);
- virtual int _setattr(const STR_String& attr, PyObject *value);
/* 1. setSeed */
KX_PYMETHOD_DOC(SCA_RandomActuator,SetSeed);
diff --git a/source/gameengine/GameLogic/SCA_RandomSensor.cpp b/source/gameengine/GameLogic/SCA_RandomSensor.cpp
index 202fd6382e6..3626522e49a 100644
--- a/source/gameengine/GameLogic/SCA_RandomSensor.cpp
+++ b/source/gameengine/GameLogic/SCA_RandomSensor.cpp
@@ -154,9 +154,9 @@ PyParentObject SCA_RandomSensor::Parents[] = {
};
PyMethodDef SCA_RandomSensor::Methods[] = {
- {"setSeed", (PyCFunction) SCA_RandomSensor::sPySetSeed, METH_VARARGS, (PY_METHODCHAR)SetSeed_doc},
- {"getSeed", (PyCFunction) SCA_RandomSensor::sPyGetSeed, METH_VARARGS, (PY_METHODCHAR)GetSeed_doc},
- {"getLastDraw", (PyCFunction) SCA_RandomSensor::sPyGetLastDraw, METH_VARARGS, (PY_METHODCHAR)GetLastDraw_doc},
+ {"setSeed", (PyCFunction) SCA_RandomSensor::sPySetSeed, METH_VARARGS, SetSeed_doc},
+ {"getSeed", (PyCFunction) SCA_RandomSensor::sPyGetSeed, METH_VARARGS, GetSeed_doc},
+ {"getLastDraw", (PyCFunction) SCA_RandomSensor::sPyGetLastDraw, METH_VARARGS, GetLastDraw_doc},
{NULL,NULL} //Sentinel
};
@@ -165,7 +165,7 @@ PyObject* SCA_RandomSensor::_getattr(const STR_String& attr) {
}
/* 1. setSeed */
-const char SCA_RandomSensor::SetSeed_doc[] =
+char SCA_RandomSensor::SetSeed_doc[] =
"setSeed(seed)\n"
"\t- seed: integer\n"
"\tSet the initial seed of the generator. Equal seeds produce\n"
@@ -183,7 +183,7 @@ PyObject* SCA_RandomSensor::PySetSeed(PyObject* self, PyObject* args, PyObject*
}
/* 2. getSeed */
-const char SCA_RandomSensor::GetSeed_doc[] =
+char SCA_RandomSensor::GetSeed_doc[] =
"getSeed()\n"
"\tReturns the initial seed of the generator. Equal seeds produce\n"
"\tequal series.\n";
@@ -192,7 +192,7 @@ PyObject* SCA_RandomSensor::PyGetSeed(PyObject* self, PyObject* args, PyObject*
}
/* 3. getLastDraw */
-const char SCA_RandomSensor::GetLastDraw_doc[] =
+char SCA_RandomSensor::GetLastDraw_doc[] =
"getLastDraw()\n"
"\tReturn the last value that was drawn.\n";
PyObject* SCA_RandomSensor::PyGetLastDraw(PyObject* self, PyObject* args, PyObject* kwds) {
diff --git a/source/gameengine/GameLogic/SConscript b/source/gameengine/GameLogic/SConscript
index b4e2159dc22..1ca884f6dec 100644
--- a/source/gameengine/GameLogic/SConscript
+++ b/source/gameengine/GameLogic/SConscript
@@ -8,13 +8,6 @@ incs += ' #/source/gameengine/Expressions #/intern/moto/include'
incs += ' #/source/gameengine/Rasterizer'
incs += ' ' + env['BF_PYTHON_INC']
+incs += ' ' + env['BF_SDL_INC']
-
-defs = ''
-
-if env['WITH_BF_SDL']:
- incs += ' ' + env['BF_SDL_INC']
-else:
- defs += ' DISABLE_SDL'
-
-env.BlenderLib ( 'bf_logic', sources, Split(incs), Split(defs), libtype=['game','player'], priority=[30, 110] )
+env.BlenderLib ( 'bf_logic', sources, Split(incs), [], libtype=['game','player'], priority=[30, 110] )
diff --git a/source/gameengine/GamePlayer/CMakeLists.txt b/source/gameengine/GamePlayer/CMakeLists.txt
index fc5912155cf..ff1040bfb40 100644
--- a/source/gameengine/GamePlayer/CMakeLists.txt
+++ b/source/gameengine/GamePlayer/CMakeLists.txt
@@ -25,7 +25,3 @@
# ***** END GPL LICENSE BLOCK *****
SUBDIRS(common ghost)
-
-IF(WITH_WEBPLUGIN)
- SUBDIRS(xembed)
-ENDIF(WITH_WEBPLUGIN)
diff --git a/source/gameengine/GamePlayer/common/CMakeLists.txt b/source/gameengine/GamePlayer/common/CMakeLists.txt
index 0c6c4179e2d..e26f8b9d69a 100644
--- a/source/gameengine/GamePlayer/common/CMakeLists.txt
+++ b/source/gameengine/GamePlayer/common/CMakeLists.txt
@@ -30,6 +30,7 @@ SET(SRC
GPC_Engine.cpp
GPC_KeyboardDevice.cpp
GPC_MouseDevice.cpp
+ GPC_PolygonMaterial.cpp
GPC_RawImage.cpp
GPC_RawLoadDotBlendArray.cpp
GPC_RawLogoArrays.cpp
@@ -68,7 +69,6 @@ SET(INC
../../../../source/gameengine/GamePlayer/ghost
../../../../source/blender/misc
../../../../source/blender/blenloader
- ../../../../source/blender/gpu
../../../../extern/glew/include
${PYTHON_INC}
${SOLID_INC}
diff --git a/source/gameengine/GamePlayer/common/GPC_RawImage.cpp b/source/gameengine/GamePlayer/common/GPC_RawImage.cpp
index e6e97cbdfd3..a9cfb0a9366 100644
--- a/source/gameengine/GamePlayer/common/GPC_RawImage.cpp
+++ b/source/gameengine/GamePlayer/common/GPC_RawImage.cpp
@@ -45,7 +45,7 @@ GPC_RawImage::GPC_RawImage()
bool GPC_RawImage::Load(
- const char *srcName,
+ char *srcName,
int destWidth, int destHeight,
TImageAlignment alignment, int offsetX, int offsetY)
{
diff --git a/source/gameengine/GamePlayer/common/GPC_RawImage.h b/source/gameengine/GamePlayer/common/GPC_RawImage.h
index 49a3043bffc..17c00d2fcc3 100644
--- a/source/gameengine/GamePlayer/common/GPC_RawImage.h
+++ b/source/gameengine/GamePlayer/common/GPC_RawImage.h
@@ -61,7 +61,7 @@ public:
* @param offsetX Amount of horzontal offset applied to the resource image.
* @param offsetY Amount of vertical offset applied to the resource image.
*/
- virtual bool Load(const char *srcName,
+ virtual bool Load(char *srcName,
int destWidth, int destHeight,
TImageAlignment alignment = alignTopLeft,
int offsetX = 0, int offsetY = 0);
diff --git a/source/gameengine/GamePlayer/common/GPC_RenderTools.cpp b/source/gameengine/GamePlayer/common/GPC_RenderTools.cpp
index 78d8eaf2aa3..8b828393c67 100644
--- a/source/gameengine/GamePlayer/common/GPC_RenderTools.cpp
+++ b/source/gameengine/GamePlayer/common/GPC_RenderTools.cpp
@@ -27,256 +27,141 @@
* ***** END GPL LICENSE BLOCK *****
*/
+#include <assert.h>
+
+#ifdef WIN32
+#pragma warning (disable : 4786)
+#include <windows.h>
+#endif
+
#include "GL/glew.h"
+#include <iostream>
+
+#include "GPC_RenderTools.h"
+
#include "RAS_IRenderTools.h"
#include "RAS_IRasterizer.h"
#include "RAS_LightObject.h"
#include "RAS_ICanvas.h"
#include "RAS_GLExtensionManager.h"
+// next two includes/dependencies come from the shadow feature
+// it needs the gameobject and the sumo physics scene for a raycast
#include "KX_GameObject.h"
-#include "KX_PolygonMaterial.h"
-#include "KX_BlenderMaterial.h"
-#include "KX_RayCast.h"
-#include "KX_IPhysicsController.h"
-#include "PHY_IPhysicsEnvironment.h"
+#include "GPC_PolygonMaterial.h"
+#include "KX_PolygonMaterial.h"
+#include "Value.h"
+//#include "KX_BlenderGL.h" // for text printing
+//#include "KX_BlenderClientObject.h"
#include "STR_String.h"
-
-#include "GPU_draw.h"
-
-#include "BKE_bmfont.h" // for text printing
+#include "RAS_BucketManager.h" // for polymaterial (needed for textprinting)
+
+
+// Blender includes
+/* This list includes only data type definitions */
+#include "DNA_object_types.h"
+#include "DNA_material_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 "BKE_global.h"
+#include "BKE_image.h"
+#include "BKE_bmfont.h"
#include "BKE_bmfont_types.h"
+#include "BKE_main.h"
-#include "GPC_RenderTools.h"
+#include "IMB_imbuf_types.h"
+// End of Blender includes
-unsigned int GPC_RenderTools::m_numgllights;
+#include "KX_Scene.h"
+#include "KX_RayCast.h"
+#include "KX_IPhysicsController.h"
+#include "PHY_IPhysicsEnvironment.h"
+#include "KX_BlenderMaterial.h"
GPC_RenderTools::GPC_RenderTools()
{
m_font = BMF_GetFont(BMF_kHelvetica10);
-
glGetIntegerv(GL_MAX_LIGHTS, (GLint*) &m_numgllights);
if (m_numgllights < 8)
m_numgllights = 8;
}
+
GPC_RenderTools::~GPC_RenderTools()
{
}
-void GPC_RenderTools::BeginFrame(RAS_IRasterizer* rasty)
-{
- m_clientobject = NULL;
- m_lastlightlayer = -1;
- m_lastlighting = false;
- DisableOpenGLLights();
-}
void GPC_RenderTools::EndFrame(RAS_IRasterizer* rasty)
{
}
-/* 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 GPC_RenderTools::ProcessLighting(int layer, const MT_Transform& viewmat)
+void GPC_RenderTools::BeginFrame(RAS_IRasterizer* rasty)
{
- if(m_lastlightlayer == layer)
- return;
+ m_clientobject=NULL;
+ m_modified=true;
+ DisableOpenGLLights();
- m_lastlightlayer = layer;
+}
- bool enable = false;
+int GPC_RenderTools::ProcessLighting(int layer)
+{
+ int result = false;
- if (layer >= 0)
+ if (layer < 0)
+ {
+ DisableOpenGLLights();
+ result = false;
+ } else
{
if (m_clientobject)
- {
- if (layer == RAS_LIGHT_OBJECT_LAYER)
- layer = static_cast<KX_GameObject*>(m_clientobject)->GetLayer();
-
- enable = applyLights(layer, viewmat);
+ {
+ if (applyLights(layer))
+ {
+ EnableOpenGLLights();
+ result = true;
+ } else
+ {
+ DisableOpenGLLights();
+ result = false;
+ }
}
}
-
- if(enable)
- EnableOpenGLLights();
- else
- DisableOpenGLLights();
+ return result;
}
void GPC_RenderTools::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, true);
+ glColorMaterial(GL_FRONT_AND_BACK,GL_DIFFUSE);
if (GLEW_EXT_separate_specular_color || GLEW_VERSION_1_2)
glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
-
- m_lastlighting = true;
-}
-
-void GPC_RenderTools::DisableOpenGLLights()
-{
- if(m_lastlighting == false)
- return;
-
- glDisable(GL_LIGHTING);
- glDisable(GL_COLOR_MATERIAL);
-
- m_lastlighting = false;
-}
-
-
-void GPC_RenderTools::SetClientObject(RAS_IRasterizer *rasty, void* obj)
-{
- if (m_clientobject != obj)
- {
- bool ccw = (obj == NULL || !((KX_GameObject*)obj)->IsNegativeScaling());
- rasty->SetFrontFace(ccw);
-
- m_clientobject = obj;
- }
-}
-
-bool GPC_RenderTools::RayHit(KX_ClientObjectInfo* client, KX_RayCast* result, void * const data)
-{
- double* const oglmatrix = (double* const) data;
- MT_Point3 resultpoint(result->m_hitPoint);
- 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
-
- double 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};
- glTranslated(resultpoint[0],resultpoint[1],resultpoint[2]);
- //glMultMatrixd(oglmatrix);
- glMultMatrixd(maat);
- return true;
}
-void GPC_RenderTools::applyTransform(RAS_IRasterizer* rasty,double* 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 GPC_RenderTools::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.0 , 0.0 , 0.0)
- // 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 = rasty->GetCameraPosition();
- MT_Vector3 dir = (campos - objpos).safe_normalized();
- MT_Vector3 up(0,0,1.0);
-
- KX_GameObject* gameobj = (KX_GameObject*) this->m_clientobject;
- // get scaling of halo object
- MT_Vector3 size = gameobj->GetSGNode()->GetLocalScale();
-
- 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 = (left.cross(up)).normalized();
-
- // we have calculated the row vectors, now we keep
- // local scaling into account:
-
- left *= size[0];
- dir *= size[1];
- up *= size[2];
- double 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};
- glTranslated(objpos[0],objpos[1],objpos[2]);
- glMultMatrixd(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*) this->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();
- KX_IPhysicsController* physics_controller = gameobj->GetPhysicsController();
-
- KX_GameObject *parent = gameobj->GetParent();
- if (!physics_controller && parent)
- physics_controller = parent->GetPhysicsController();
- if (parent)
- parent->Release();
-
- KX_RayCast::Callback<GPC_RenderTools> callback(this, physics_controller, oglmatrix);
- if (!KX_RayCast::RayTest(physics_environment, frompoint, topoint, callback))
- {
- // couldn't find something to cast the shadow on...
- glMultMatrixd(oglmatrix);
- }
- } else
- {
-
- // 'normal' object
- glMultMatrixd(oglmatrix);
- }
- }
-}
-
-
-void GPC_RenderTools::RenderText2D(RAS_TEXT_RENDER_MODE mode,
- const char* text,
- int xco,
- int yco,
- int width,
- int height)
+void GPC_RenderTools::RenderText2D(RAS_TEXT_RENDER_MODE mode,
+ const char* text,
+ int xco,
+ int yco,
+ int width,
+ int height)
{
STR_String tmpstr(text);
int lines;
@@ -349,19 +234,21 @@ void GPC_RenderTools::RenderText2D(RAS_TEXT_RENDER_MODE mode,
glDisable(GL_LIGHTING);
}
-/* Render Text renders text into a (series of) polygon, using a texture font,
- * Each character consists of one polygon (one quad or two triangles) */
-
+/**
+ * Copied from KX_BlenderRenderTools.cpp in KX_blenderhook
+ * Renders text into a (series of) polygon(s), using a texture font,
+ * Each character consists of one polygon (one quad or two triangles)
+ */
void GPC_RenderTools::RenderText(
int mode,
RAS_IPolyMaterial* polymat,
- float v1[3], float v2[3], float v3[3], float v4[3], int glattrib)
+ float v1[3], float v2[3], float v3[3], float v4[3])
{
STR_String mytext = ((CValue*)m_clientobject)->GetPropertyText("Text");
const unsigned int flag = polymat->GetFlag();
struct MTFace* tface = 0;
- unsigned int *col = 0;
+ unsigned int* col = 0;
if(flag & RAS_BLENDERMAT) {
KX_BlenderMaterial *bl_mat = static_cast<KX_BlenderMaterial*>(polymat);
@@ -372,29 +259,110 @@ void GPC_RenderTools::RenderText(
tface = blenderpoly->GetMTFace();
col = blenderpoly->GetMCol();
}
-
- GPU_render_text(tface, mode, mytext, mytext.Length(), col, v1, v2, v3, v4, glattrib);
+
+ BL_RenderText(mode, mytext, mytext.Length(), tface, col, v1, v2, v3, v4);
}
-void GPC_RenderTools::PushMatrix()
+
+/**
+ * Copied from KX_BlenderGL.cpp in KX_blenderhook
+ */
+void GPC_RenderTools::BL_RenderText(
+ int mode,
+ const char* textstr,
+ int textlen,
+ struct MTFace* tface,
+ unsigned int* col,
+ float v1[3],float v2[3],float v3[3],float v4[3])
{
- glPushMatrix();
+ struct Image* ima;
+
+ if (mode & TF_BMFONT) {
+ //char string[MAX_PROPSTRING];
+// float tmat[4][4];
+ int characters, index, character;
+ float centerx, centery, sizex, sizey, transx, transy, movex, movey, advance;
+
+// bProperty *prop;
+
+ // string = "Frank van Beek";
+
+ characters = textlen;
+
+ ima = (struct Image*) tface->tpage;
+ if (ima == NULL) {
+ characters = 0;
+ }
+
+ if(!col) glColor3f(1.0f, 1.0f, 1.0f);
+
+ glPushMatrix();
+ for (index = 0; index < characters; index++) {
+ // lets calculate offset stuff
+ character = textstr[index];
+
+ // space starts at offset 1
+ // character = character - ' ' + 1;
+
+ matrixGlyph((ImBuf *)ima->ibufs.first, character, & centerx, &centery, &sizex, &sizey, &transx, &transy, &movex, &movey, &advance);
+
+ glBegin(GL_POLYGON);
+ // printf(" %c %f %f %f %f\n", character, tface->uv[0][0], tface->uv[0][1], );
+ // glTexCoord2f((tface->uv[0][0] - centerx) * sizex + transx, (tface->uv[0][1] - centery) * sizey + transy);
+ glTexCoord2f((tface->uv[0][0] - centerx) * sizex + transx, (tface->uv[0][1] - centery) * sizey + transy);
+
+ if(col) BL_spack(col[0]);
+ // glVertex3fv(v1);
+ glVertex3f(sizex * v1[0] + movex, sizey * v1[1] + movey, v1[2]);
+
+ glTexCoord2f((tface->uv[1][0] - centerx) * sizex + transx, (tface->uv[1][1] - centery) * sizey + transy);
+ if(col) BL_spack(col[1]);
+ // glVertex3fv(v2);
+ glVertex3f(sizex * v2[0] + movex, sizey * v2[1] + movey, v2[2]);
+
+ glTexCoord2f((tface->uv[2][0] - centerx) * sizex + transx, (tface->uv[2][1] - centery) * sizey + transy);
+ if(col) BL_spack(col[2]);
+ // glVertex3fv(v3);
+ glVertex3f(sizex * v3[0] + movex, sizey * v3[1] + movey, v3[2]);
+
+ if(v4) {
+ // glTexCoord2f((tface->uv[3][0] - centerx) * sizex + transx, 1.0 - (1.0 - tface->uv[3][1]) * sizey - transy);
+ glTexCoord2f((tface->uv[3][0] - centerx) * sizex + transx, (tface->uv[3][1] - centery) * sizey + transy);
+ if(col) BL_spack(col[3]);
+ // glVertex3fv(v4);
+ glVertex3f(sizex * v4[0] + movex, sizey * v4[1] + movey, v4[2]);
+ }
+ glEnd();
+
+ glTranslatef(advance, 0.0, 0.0);
+ }
+ glPopMatrix();
+
+ }
}
-void GPC_RenderTools::PopMatrix()
+
+RAS_IPolyMaterial* GPC_RenderTools::CreateBlenderPolyMaterial(
+ const STR_String &texname,
+ bool ba,const STR_String& matname,int tile,int tilexrep,int tileyrep,int mode,bool transparant, bool zsort,
+ int lightlayer,bool bIsTriangle,void* clientobject,void* tface)
{
- glPopMatrix();
+ assert(!"Deprecated");
+/* return new GPC_PolygonMaterial(texname, ba,matname,tile,tilexrep,tileyrep,
+ mode,transparant,zsort,lightlayer,bIsTriangle,clientobject,tface);
+ */
+ return NULL;
}
-int GPC_RenderTools::applyLights(int objectlayer, const MT_Transform& viewmat)
+int GPC_RenderTools::applyLights(int objectlayer)
{
- // taken from blender source, incompatibility between Blender Object / GameObject
- float glviewmat[16];
- unsigned int count;
- float vec[4];
+// taken from blender source, incompatibility between Blender Object / GameObject
+ int count;
+ float vec[4];
+
vec[3]= 1.0;
for(count=0; count<m_numgllights; count++)
@@ -403,20 +371,23 @@ int GPC_RenderTools::applyLights(int objectlayer, const MT_Transform& viewmat)
//std::vector<struct RAS_LightObject*> m_lights;
std::vector<struct RAS_LightObject*>::iterator lit = m_lights.begin();
- viewmat.getValue(glviewmat);
- glPushMatrix();
- glLoadMatrixf(glviewmat);
for (lit = m_lights.begin(), count = 0; !(lit==m_lights.end()) && count < m_numgllights; ++lit)
{
RAS_LightObject* lightdata = (*lit);
if (lightdata->m_layer & objectlayer)
{
+
+ glPushMatrix();
+ glLoadMatrixf(m_viewmat);
+
+
vec[0] = (*(lightdata->m_worldmatrix))(0,3);
vec[1] = (*(lightdata->m_worldmatrix))(1,3);
vec[2] = (*(lightdata->m_worldmatrix))(2,3);
vec[3] = 1;
+
if(lightdata->m_type==RAS_LightObject::LIGHT_SUN) {
vec[0] = (*(lightdata->m_worldmatrix))(0,2);
@@ -472,16 +443,142 @@ int GPC_RenderTools::applyLights(int objectlayer, const MT_Transform& viewmat)
}
glLightfv((GLenum)(GL_LIGHT0+count), GL_SPECULAR, vec);
glEnable((GLenum)(GL_LIGHT0+count));
-
+
count++;
+
+ glPopMatrix();
}
}
- glPopMatrix();
return count;
}
+void GPC_RenderTools::SetClientObject(void* obj)
+{
+ if (m_clientobject != obj)
+ {
+ if (obj == NULL || !((KX_GameObject*)obj)->IsNegativeScaling())
+ {
+ glFrontFace(GL_CCW);
+ } else
+ {
+ glFrontFace(GL_CW);
+ }
+ m_clientobject = obj;
+ m_modified = true;
+ }
+}
+
+bool GPC_RenderTools::RayHit(KX_ClientObjectInfo* client, MT_Point3& hit_point, MT_Vector3& hit_normal, void * const data)
+{
+ double* const oglmatrix = (double* const) data;
+ MT_Point3 resultpoint(hit_point);
+ MT_Vector3 resultnormal(hit_normal);
+ 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
+
+ double 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};
+ glTranslated(resultpoint[0],resultpoint[1],resultpoint[2]);
+ //glMultMatrixd(oglmatrix);
+ glMultMatrixd(maat);
+ return true;
+}
+
+void GPC_RenderTools::applyTransform(RAS_IRasterizer* rasty,double* oglmatrix,int objectdrawmode )
+{
+ 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.0 , 0.0 , 0.0)
+ // 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 = rasty->GetCameraPosition();
+ MT_Vector3 dir = (campos - objpos).safe_normalized();
+ MT_Vector3 up(0,0,1.0);
+
+ KX_GameObject* gameobj = (KX_GameObject*) this->m_clientobject;
+ // get scaling of halo object
+ MT_Vector3 size = gameobj->GetSGNode()->GetLocalScale();
+
+ 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 = (left.cross(up)).normalized();
+
+ // we have calculated the row vectors, now we keep
+ // local scaling into account:
+
+ left *= size[0];
+ dir *= size[1];
+ up *= size[2];
+ double 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};
+ glTranslated(objpos[0],objpos[1],objpos[2]);
+ glMultMatrixd(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*) this->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();
+ KX_IPhysicsController* physics_controller = gameobj->GetPhysicsController();
+
+ KX_GameObject *parent = gameobj->GetParent();
+ if (!physics_controller && parent)
+ physics_controller = parent->GetPhysicsController();
+ if (parent)
+ parent->Release();
+
+ MT_Point3 resultpoint;
+ MT_Vector3 resultnormal;
+ if (!KX_RayCast::RayTest(physics_controller, physics_environment, frompoint, topoint, resultpoint, resultnormal, KX_RayCast::Callback<GPC_RenderTools>(this, oglmatrix)))
+ {
+ // couldn't find something to cast the shadow on...
+ glMultMatrixd(oglmatrix);
+ }
+ } else
+ {
+
+ // 'normal' object
+ glMultMatrixd(oglmatrix);
+ }
+ }
+}
+
void GPC_RenderTools::MotionBlur(RAS_IRasterizer* rasterizer)
{
int state = rasterizer->GetMotionBlurState();
@@ -512,6 +609,7 @@ void GPC_RenderTools::Update2DFilter(vector<STR_String>& propNames, void* gameOb
void GPC_RenderTools::Render2DFilters(RAS_ICanvas* canvas)
{
- m_filtermanager.RenderFilters(canvas);
+ m_filtermanager.RenderFilters( canvas);
}
+unsigned int GPC_RenderTools::m_numgllights;
diff --git a/source/gameengine/GamePlayer/common/GPC_RenderTools.h b/source/gameengine/GamePlayer/common/GPC_RenderTools.h
index 382956e73ea..8fae3d2b305 100644
--- a/source/gameengine/GamePlayer/common/GPC_RenderTools.h
+++ b/source/gameengine/GamePlayer/common/GPC_RenderTools.h
@@ -31,67 +31,114 @@
#define __GPC_RENDERTOOLS_H
#ifdef WIN32
-// don't show stl-warnings
-#pragma warning (disable:4786)
-#include <windows.h>
+ #include <windows.h>
#endif // WIN32
+#include "GL/glew.h"
+
#include "RAS_IRenderTools.h"
#include "BMF_Api.h"
struct KX_ClientObjectInfo;
-class KX_RayCast;
-/* BlenderRenderTools are a set of tools to apply 2D/3D graphics effects, which
- * are not part of the (polygon) Rasterizer. Effects like 2D text, 3D (polygon)
- * text, lighting.
- *
- * Most of this code is duplicated in KX_BlenderRenderTools, so this should be
- * moved to some common location to avoid duplication. */
class GPC_RenderTools : public RAS_IRenderTools
{
- int m_lastlightlayer;
- bool m_lastlighting;
- static unsigned int m_numgllights;
-
- BMF_Font* m_font;
-
public:
- GPC_RenderTools();
- virtual ~GPC_RenderTools();
-
- void EndFrame(RAS_IRasterizer* rasty);
- void BeginFrame(RAS_IRasterizer* rasty);
-
- void EnableOpenGLLights();
- void DisableOpenGLLights();
- void ProcessLighting(int layer, const MT_Transform& viewmat);
-
- /* @attention mode is ignored here */
- void RenderText2D(RAS_TEXT_RENDER_MODE mode,
- const char* text,
- int xco,
- int yco,
- int width,
- int height);
- void RenderText(int mode,
- class RAS_IPolyMaterial* polymat,
- float v1[3],
- float v2[3],
- float v3[3],
- float v4[3],
- int glattrib);
-
- void applyTransform(RAS_IRasterizer* rasty, double* oglmatrix, int objectdrawmode);
- int applyLights(int objectlayer, const MT_Transform& viewmat);
-
- void PushMatrix();
- void PopMatrix();
-
- bool RayHit(KX_ClientObjectInfo* client, KX_RayCast* result, void * const data);
- bool NeedRayCast(KX_ClientObjectInfo* client) { return true; }
+ GPC_RenderTools();
+ virtual ~GPC_RenderTools();
+
+ virtual void EndFrame(RAS_IRasterizer* rasty);
+ virtual void BeginFrame(RAS_IRasterizer* rasty);
+
+ void DisableOpenGLLights()
+ {
+ glDisable(GL_LIGHTING);
+ glDisable(GL_COLOR_MATERIAL);
+ }
+
+ void EnableOpenGLLights();
+
+ int ProcessLighting(int layer);
+
+ void Perspective(int a, int width, int height, float mat[4][4], float viewmat[4][4])
+ {
+ if(a== 0)
+ {
+ glMatrixMode(GL_PROJECTION);
+ glMatrixMode(GL_MODELVIEW);
+ glLoadIdentity();
+ }
+ else
+ {
+ if(a== 1)
+ {
+ glMatrixMode(GL_PROJECTION);
+ glMatrixMode(GL_MODELVIEW);
+ }
+ }
+ }
+
+ /**
+ * @attention mode is ignored here
+ */
+ virtual void RenderText2D(
+ RAS_TEXT_RENDER_MODE mode,
+ const char* text,
+ int xco,
+ int yco,
+ int width,
+ int height);
+
+ /**
+ * Renders text into a (series of) polygon(s), using a texture font,
+ * Each character consists of one polygon (one quad or two triangles)
+ */
+ virtual void RenderText(
+ int mode,
+ RAS_IPolyMaterial* polymat,
+ float v1[3],
+ float v2[3],
+ float v3[3],
+ float v4[3]);
+
+ void Render(RAS_IRasterizer* rasty,double* oglmatrix,int objectdrawmode)
+ {
+ glPopMatrix();
+ glPushMatrix();
+ glMultMatrixd(oglmatrix);
+ }
+
+ void applyTransform(RAS_IRasterizer* rasty, double* oglmatrix, int objectdrawmode);
+
+ virtual void PushMatrix()
+ {
+ glPushMatrix();
+ }
+
+ virtual void PopMatrix()
+ {
+ glPopMatrix();
+ }
+
+ virtual class RAS_IPolyMaterial* CreateBlenderPolyMaterial(
+ const STR_String &texname,
+ bool ba,
+ const STR_String& matname,
+ int tile,
+ int tilexrep,int tileyrep,
+ int mode,
+ bool transparant,
+ bool zsort,
+ int lightlayer,
+ bool bIsTriangle,
+ void* clientobject,
+ void* tface);
+
+ int applyLights(int objectlayer);
+
+ bool RayHit(KX_ClientObjectInfo* client, MT_Point3& hit_point, MT_Vector3& hit_normal, void * const data);
virtual void MotionBlur(RAS_IRasterizer* rasterizer);
@@ -99,7 +146,28 @@ public:
virtual void Render2DFilters(RAS_ICanvas* canvas);
- virtual void SetClientObject(RAS_IRasterizer *rasty, void* obj);
+ virtual void SetClientObject(void* obj);
+
+protected:
+ /**
+ * Copied from KX_BlenderGL.cpp in KX_blenderhook
+ */
+ void BL_RenderText(
+ int mode,
+ const char* textstr,
+ int textlen,
+ struct MTFace* tface,
+ unsigned int* col,
+ float v1[3],float v2[3],float v3[3],float v4[3]);
+ void BL_spack(unsigned int ucol)
+ {
+ char *cp = (char *)&ucol;
+ glColor3ub(cp[3], cp[2], cp[1]);
+ }
+
+
+ BMF_Font* m_font;
+ static unsigned int m_numgllights;
};
#endif // __GPC_RENDERTOOLS_H
diff --git a/source/gameengine/GamePlayer/common/Makefile b/source/gameengine/GamePlayer/common/Makefile
index 6a12e659be6..19d792ddbdb 100644
--- a/source/gameengine/GamePlayer/common/Makefile
+++ b/source/gameengine/GamePlayer/common/Makefile
@@ -43,7 +43,6 @@ CPPFLAGS += -I../../../blender/blenloader
CPPFLAGS += -I../../../blender/blenlib
CPPFLAGS += -I../../../blender/imbuf
CPPFLAGS += -I../../../blender/makesdna
-CPPFLAGS += -I../../../blender/gpu
CPPFLAGS += -I../../../kernel/gen_system
CPPFLAGS += -I$(NAN_GUARDEDALLOC)/include
@@ -73,6 +72,10 @@ CPPFLAGS += -I../../../gameengine/Rasterizer/RAS_OpenGLRasterizer
CPPFLAGS += -I../../../gameengine/Physics/Sumo
CPPFLAGS += -I../../../gameengine/Physics/common
+ifeq ($(WITH_BF_GLEXT),true)
+ CPPFLAGS += -DWITH_GLEXT
+endif
+
###############################
SOURCEDIR = source/gameengine/GamePlayer/common
diff --git a/source/gameengine/GamePlayer/common/SConscript b/source/gameengine/GamePlayer/common/SConscript
index 30f20a670d3..3b2367d2592 100644
--- a/source/gameengine/GamePlayer/common/SConscript
+++ b/source/gameengine/GamePlayer/common/SConscript
@@ -8,6 +8,7 @@ source_files = ['bmfont.cpp',
'GPC_Engine.cpp',
'GPC_KeyboardDevice.cpp',
'GPC_MouseDevice.cpp',
+ 'GPC_PolygonMaterial.cpp',
'GPC_RawImage.cpp',
'GPC_RawLoadDotBlendArray.cpp',
'GPC_RawLogoArrays.cpp',
@@ -45,7 +46,6 @@ incs = ['.',
'#source/gameengine/GamePlayer/ghost',
'#source/blender/misc',
'#source/blender/blenloader',
- '#source/blender/gpu',
'#extern/glew/include']
#This is all plugin stuff!
diff --git a/source/gameengine/GamePlayer/common/unix/GPU_PolygonMaterial.h b/source/gameengine/GamePlayer/common/unix/GPU_PolygonMaterial.h
index e5ed7f39811..fee729a84ac 100644
--- a/source/gameengine/GamePlayer/common/unix/GPU_PolygonMaterial.h
+++ b/source/gameengine/GamePlayer/common/unix/GPU_PolygonMaterial.h
@@ -37,9 +37,9 @@ class GPU_PolygonMaterial : public BP_PolygonMaterial
public:
GPUPolygonMaterial(const STR_String& texname, bool ba,const STR_String& matname,
int tile, int tileXrep, int tileYrep, int mode, int transparant,
- int lightlayer,,void* tpage) :
+ int lightlayer,bool bIsTriangle,void* clientobject,void* tpage) :
BP_PolygonMaterial(texname, ba,matname, tile, tileXrep, tileYrep,
- mode, transparant, lightlayer),
+ mode, transparant, lightlayer, bIsTriangle, clientobject),
m_tface(tpage)
{
}
diff --git a/source/gameengine/GamePlayer/common/unix/Makefile b/source/gameengine/GamePlayer/common/unix/Makefile
index 3d44a41afee..a2bdb7225a0 100644
--- a/source/gameengine/GamePlayer/common/unix/Makefile
+++ b/source/gameengine/GamePlayer/common/unix/Makefile
@@ -35,7 +35,6 @@ include nan_compile.mk
CCFLAGS += $(LEVEL_1_CPP_WARNINGS)
-CPPFLAGS += -I$(NAN_GLEW)/include
CPPFLAGS += -I$(OPENGL_HEADERS)
CPPFLAGS += -I$(NAN_STRING)/include
diff --git a/source/gameengine/GamePlayer/ghost/CMakeLists.txt b/source/gameengine/GamePlayer/ghost/CMakeLists.txt
index a3cd8296da3..d9f0675001f 100644
--- a/source/gameengine/GamePlayer/ghost/CMakeLists.txt
+++ b/source/gameengine/GamePlayer/ghost/CMakeLists.txt
@@ -64,15 +64,10 @@ SET(INC
../../../../source/gameengine/GamePlayer/common
../../../../source/blender/misc
../../../../source/blender/blenloader
- ../../../../source/blender/gpu
../../../../extern/solid
../../../../extern/glew/include
${PYTHON_INC}
)
-IF(WITH_FFMPEG)
- ADD_DEFINITIONS(-DWITH_FFMPEG)
-ENDIF(WITH_FFMPEG)
-
BLENDERLIB_NOLIST(gp_ghost "${SRC}" "${INC}")
#env.BlenderLib (libname='gp_ghost', sources=source_files, includes = incs, defines = [], libtype='player',priority=0, compileflags=cflags)
diff --git a/source/gameengine/GamePlayer/ghost/GPG_Application.cpp b/source/gameengine/GamePlayer/ghost/GPG_Application.cpp
index e858c852b70..7be3b94d8ae 100644
--- a/source/gameengine/GamePlayer/ghost/GPG_Application.cpp
+++ b/source/gameengine/GamePlayer/ghost/GPG_Application.cpp
@@ -38,7 +38,6 @@
#endif
#include "GL/glew.h"
-#include "GPU_extensions.h"
#include "GPG_Application.h"
@@ -57,7 +56,6 @@ extern "C"
#include "BLO_readfile.h"
#include "BKE_global.h"
#include "BKE_main.h"
-#include "IMB_imbuf.h"
#include "DNA_scene_types.h"
#ifdef __cplusplus
}
@@ -100,15 +98,15 @@ extern "C"
#include "GHOST_IWindow.h"
#include "GHOST_Rect.h"
+
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),
+GPG_Application::GPG_Application(GHOST_ISystem* system, struct Main* maggie, STR_String startSceneName)
+ : m_startSceneName(startSceneName),
+ m_maggie(maggie),
m_exitRequested(0),
m_system(system),
m_mainWindow(0),
@@ -116,7 +114,6 @@ GPG_Application::GPG_Application(GHOST_ISystem* system)
m_cursor(GHOST_kStandardCursorFirstCursor),
m_engineInitialized(0),
m_engineRunning(0),
- m_isEmbedded(false),
m_ketsjiengine(0),
m_kxsystem(0),
m_keyboard(0),
@@ -128,9 +125,7 @@ GPG_Application::GPG_Application(GHOST_ISystem* system)
m_networkdevice(0),
m_audiodevice(0),
m_blendermat(0),
- m_blenderglslmat(0),
- m_pyGlobalDictString(0),
- m_pyGlobalDictString_Length(0)
+ m_blenderglslmat(0)
{
fSystem = system;
}
@@ -139,28 +134,21 @@ GPG_Application::GPG_Application(GHOST_ISystem* 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)
+bool GPG_Application::SetGameEngineData(struct Main* maggie, STR_String startSceneName)
{
bool result = false;
- if (maggie != NULL && scene != NULL)
+ if (maggie != NULL && startSceneName != "")
{
- G.scene = scene;
+ G.scene = (Scene*)maggie->scene.first;
m_maggie = maggie;
- m_startSceneName = scene->id.name+2;
- m_startScene = scene;
+ m_startSceneName = startSceneName;
result = true;
}
@@ -332,26 +320,6 @@ bool GPG_Application::startWindow(STR_String& title,
return success;
}
-bool GPG_Application::startEmbeddedWindow(STR_String& title,
- const GHOST_TEmbedderWindowID parentWindow,
- const bool stereoVisual,
- const int stereoMode) {
-
- m_mainWindow = fSystem->createWindow(title, 0, 0, 0, 0, GHOST_kWindowStateNormal,
- GHOST_kDrawingContextTypeOpenGL, stereoVisual, 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(
@@ -510,7 +478,7 @@ bool GPG_Application::initEngine(GHOST_IWindow* window, const int stereoMode)
{
if (!m_engineInitialized)
{
- GPU_extensions_init();
+ glewInit();
bgl::InitExtensions(true);
// get and set the preferences
@@ -529,17 +497,13 @@ bool GPG_Application::initEngine(GHOST_IWindow* window, const int stereoMode)
bool fixed_framerate= (SYS_GetCommandLineInt(syshandle, "fixed_framerate", fixedFr) != 0);
bool frameRate = (SYS_GetCommandLineInt(syshandle, "show_framerate", 0) != 0);
- bool useLists = (SYS_GetCommandLineInt(syshandle, "displaylists", G.fileflags & G_FILE_DISPLAY_LISTS) != 0);
- bool nodepwarnings = (SYS_GetCommandLineInt(syshandle, "ignore_deprecation_warnings", 0) != 0);
-
- if(GLEW_ARB_multitexture && GLEW_VERSION_1_1)
- m_blendermat = (SYS_GetCommandLineInt(syshandle, "blender_material", 1) != 0);
-
- if(GPU_extensions_minimum_support())
- m_blenderglslmat = (SYS_GetCommandLineInt(syshandle, "blender_glsl_material", 1) != 0);
- else if(G.fileflags & G_FILE_GAME_MAT_GLSL)
- m_blendermat = false;
+ bool useLists = (SYS_GetCommandLineInt(syshandle, "displaylists", G.fileflags & G_FILE_DIAPLAY_LISTS) != 0);
+ if(GLEW_ARB_multitexture && GLEW_VERSION_1_1) {
+ int gameflag =(G.fileflags & G_FILE_GAME_MAT);
+ m_blendermat = (SYS_GetCommandLineInt(syshandle, "blender_material", gameflag) != 0);
+ }
+
// create the canvas, rasterizer and rendertools
m_canvas = new GPG_Canvas(window);
if (!m_canvas)
@@ -605,8 +569,6 @@ bool GPG_Application::initEngine(GHOST_IWindow* window, const int stereoMode)
m_ketsjiengine->SetAudioDevice(m_audiodevice);
m_ketsjiengine->SetTimingDisplay(frameRate, false, false);
- CValue::SetDeprecationWarnings(nodepwarnings);
-
m_ketsjiengine->SetUseFixedTime(fixed_framerate);
m_ketsjiengine->SetTimingDisplay(frameRate, profile, properties);
@@ -664,38 +626,33 @@ bool GPG_Application::startEngine(void)
{
STR_String startscenename = m_startSceneName.Ptr();
m_ketsjiengine->SetSceneConverter(m_sceneconverter);
-
+
// if (always_use_expand_framing)
// sceneconverter->SetAlwaysUseExpandFraming(true);
- if(m_blendermat && (G.fileflags & G_FILE_GAME_MAT))
+ if(m_blendermat)
m_sceneconverter->SetMaterials(true);
- if(m_blenderglslmat && (G.fileflags & G_FILE_GAME_MAT_GLSL))
+ if(m_blenderglslmat)
m_sceneconverter->SetGLSLMaterials(true);
KX_Scene* startscene = new KX_Scene(m_keyboard,
m_mouse,
m_networkdevice,
m_audiodevice,
- startscenename,
- m_startScene);
+ startscenename);
// some python things
PyObject* dictionaryobject = initGamePlayerPythonScripting("Ketsji", psl_Lowest);
m_ketsjiengine->SetPythonDictionary(dictionaryobject);
initRasterizer(m_rasterizer, m_canvas);
- PyObject *gameLogic = initGameLogic(m_ketsjiengine, startscene);
- PyDict_SetItemString(dictionaryobject, "GameLogic", gameLogic); // Same as importing the module
+ PyDict_SetItemString(dictionaryobject, "GameLogic", initGameLogic(startscene)); // Same as importing the module
initGameKeys();
initPythonConstraintBinding();
initMathutils();
-#ifdef WITH_FFMPEG
- initVideoTexture();
-#endif
- // 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);
-
+
+
+
+
m_sceneconverter->ConvertScene(
startscenename,
startscene,
@@ -731,16 +688,6 @@ bool GPG_Application::startEngine(void)
void GPG_Application::stopEngine()
{
- // 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);
-
// when exiting the mainloop
exitGamePythonScripting();
m_ketsjiengine->StopEngine();
@@ -807,12 +754,6 @@ void GPG_Application::exitEngine()
m_canvas = 0;
}
- libtiff_exit();
-#ifdef WITH_QUICKTIME
- quicktime_exit();
-#endif
- GPU_extensions_exit();
-
m_exitRequested = 0;
m_engineInitialized = false;
}
@@ -892,7 +833,7 @@ bool GPG_Application::handleKey(GHOST_IEvent* event, bool isDown)
GHOST_TEventKeyData* keyData = static_cast<GHOST_TEventKeyData*>(eventData);
//no need for this test
//if (fSystem->getFullScreen()) {
- if (keyData->key == GHOST_kKeyEsc && !m_keyboard->m_hookesc && !m_isEmbedded) {
+ if (keyData->key == GHOST_kKeyEsc && !m_keyboard->m_hookesc) {
m_exitRequested = KX_EXIT_REQUEST_OUTSIDE;
}
//}
diff --git a/source/gameengine/GamePlayer/ghost/GPG_Application.h b/source/gameengine/GamePlayer/ghost/GPG_Application.h
index 38408f919b4..17f5add8b19 100644
--- a/source/gameengine/GamePlayer/ghost/GPG_Application.h
+++ b/source/gameengine/GamePlayer/ghost/GPG_Application.h
@@ -50,19 +50,17 @@ 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(GHOST_ISystem* system, struct Main* maggie, STR_String startSceneName);
~GPG_Application(void);
- bool SetGameEngineData(struct Main* maggie, struct Scene* scene);
+ bool SetGameEngineData(struct Main* maggie,STR_String startSceneName);
bool startWindow(STR_String& title, int windowLeft, int windowTop, int windowWidth, int windowHeight,
const bool stereoVisual, const int stereoMode);
bool startFullScreen(int width, int height, int bpp, int frequency, const bool stereoVisual, const int stereoMode);
- bool startEmbeddedWindow(STR_String& title, const GHOST_TEmbedderWindowID parent_window, const bool stereoVisual, const int stereoMode);
#ifdef WIN32
bool startScreenSaverFullScreen(int width, int height, int bpp, int frequency, const bool stereoVisual, const int stereoMode);
bool startScreenSaverPreview(HWND parentWindow, const bool stereoVisual, const int stereoMode);
@@ -102,7 +100,6 @@ protected:
/* The game data */
STR_String m_startSceneName;
- struct Scene* m_startScene;
struct Main* m_maggie;
/* Exit state. */
@@ -121,8 +118,6 @@ protected:
bool m_engineInitialized;
/** Engine state. */
bool m_engineRunning;
- /** Running on embedded window */
- bool m_isEmbedded;
/** the gameengine itself */
KX_KetsjiEngine* m_ketsjiengine;
@@ -147,12 +142,6 @@ protected:
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;
+
};
diff --git a/source/gameengine/GamePlayer/ghost/GPG_ghost.cpp b/source/gameengine/GamePlayer/ghost/GPG_ghost.cpp
index 70272d57357..8222e5c8bac 100644
--- a/source/gameengine/GamePlayer/ghost/GPG_ghost.cpp
+++ b/source/gameengine/GamePlayer/ghost/GPG_ghost.cpp
@@ -44,7 +44,6 @@
#endif // __APPLE__
#include "GEN_messaging.h"
#include "KX_KetsjiEngine.h"
-#include "KX_PythonInit.h"
/**********************************
* Begin Blender include block
@@ -53,31 +52,25 @@
extern "C"
{
#endif // __cplusplus
-#include "MEM_guardedalloc.h"
-#include "BKE_blender.h"
#include "BKE_global.h"
#include "BKE_icons.h"
-#include "BKE_node.h"
#include "BLI_blenlib.h"
#include "DNA_scene_types.h"
#include "BLO_readfile.h"
#include "BLO_readblenfile.h"
-#include "IMB_imbuf.h"
int GHOST_HACK_getFirstFile(char buf[]);
#ifdef __cplusplus
}
#endif // __cplusplus
-
-#include "GPU_draw.h"
-
/**********************************
* End Blender include block
**********************************/
#include "SYS_System.h"
#include "GPG_Application.h"
+#include "GPC_PolygonMaterial.h"
#include "GHOST_ISystem.h"
#include "RAS_IRasterizer.h"
@@ -153,19 +146,20 @@ static BOOL scr_saver_init(int argc, char **argv)
#endif /* WIN32 */
-void usage(const char* program)
+void usage(char* program)
{
- const char * consoleoption;
+ char * consoleoption;
#ifdef _WIN32
consoleoption = "-c ";
#else
consoleoption = "";
#endif
- printf("usage: %s [-w l t w h] %s[-g gamengineoptions] "
+ printf("usage: %s [-w [-p l t w h]] %s[-g gamengineoptions] "
"[-s stereomode] filename.blend\n", program, consoleoption);
printf(" -h: Prints this command summary\n");
printf(" -w: display in a window\n");
+ printf(" -p: specify window position\n");
printf(" l = window left coordinate\n");
printf(" t = window top coordinate\n");
printf(" w = window width\n");
@@ -182,30 +176,24 @@ void usage(const char* program)
printf(" anaglyph (Red-Blue glasses)\n");
printf(" vinterlace (Vertical interlace for autostereo display)\n");
printf(" depending on the type of stereo you want\n");
-#ifndef _WIN32
- printf(" -i: parent windows ID \n");
-#endif
#ifdef _WIN32
printf(" -c: keep console window open\n");
#endif
- printf(" -d: turn debugging on\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 0 Ignore deprecation warnings\n");
+ printf(" -g: game engine options:\n");
+ printf(" Name Default Description\n");
+ printf(" ----------------------------------------\n");
+ printf(" fixedtime 0 Do the same timestep each frame \"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("\n");
- printf("example: %s -w 10 10 320 200 -g noaudio c:\\loadtest.blend\n", program);
+ printf("example: %s -p 10 10 320 200 -g noaudio c:\\loadtest.blend\n", program);
printf("example: %s -g show_framerate = 0 c:\\loadtest.blend\n", program);
}
-static void get_filename(int argc, char **argv, char *filename)
-{
+char *get_filename(int argc, char **argv) {
#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.
@@ -213,18 +201,22 @@ static void get_filename(int argc, char **argv, char *filename)
*/
int srclen = ::strlen(argv[0]);
int len = 0;
- char *gamefile = NULL;
+ char *filename = NULL;
- filename[0] = '\0';
-
if (argc > 1) {
if (BLI_exists(argv[argc-1])) {
- BLI_strncpy(filename, argv[argc-1], FILE_MAXDIR + FILE_MAXFILE);
+ len = ::strlen(argv[argc-1]);
+ filename = new char [len + 1];
+ ::strcpy(filename, argv[argc-1]);
+ return(filename);
}
if (::strncmp(argv[argc-1], "-psn_", 5)==0) {
static char firstfilebuf[512];
if (GHOST_HACK_getFirstFile(firstfilebuf)) {
- BLI_strncpy(filename, firstfilebuf, FILE_MAXDIR + FILE_MAXFILE);
+ len = ::strlen(firstfilebuf);
+ filename = new char [len + 1];
+ ::strcpy(filename, firstfilebuf);
+ return(filename);
}
}
}
@@ -232,26 +224,23 @@ static void get_filename(int argc, char **argv, char *filename)
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");
+ filename = new char [len + 1];
+ ::strcpy(filename, argv[0]);
+ ::strcpy(filename + srclen, "Resources/game.blend");
//::printf("looking for file: %s\n", filename);
- if (BLI_exists(gamefile))
- BLI_strncpy(filename, gamefile, FILE_MAXDIR + FILE_MAXFILE);
-
- delete gamefile;
+ if (BLI_exists(filename)) {
+ return (filename);
+ }
}
+ return(NULL);
#else
- filename[0] = '\0';
-
- if(argc > 1)
- BLI_strncpy(filename, argv[argc-1], FILE_MAXDIR + FILE_MAXFILE);
+ return (argc>1)?argv[argc-1]:NULL;
#endif // !_APPLE
}
-static BlendFileData *load_game_data(char *progname, char *filename = NULL, char *relativename = NULL) {
+static BlendFileData *load_game_data(char *progname, char *filename = NULL) {
BlendReadError error;
BlendFileData *bfd = NULL;
@@ -293,7 +282,7 @@ int main(int argc, char** argv)
bool fullScreenParFound = false;
bool windowParFound = false;
bool closeConsole = true;
- RAS_IRasterizer::StereoMode stereomode = RAS_IRasterizer::RAS_STEREO_NOSTEREO;
+ RAS_IRasterizer::StereoMode stereomode;
bool stereoWindow = false;
bool stereoParFound = false;
int windowLeft = 100;
@@ -304,10 +293,7 @@ int main(int argc, char** argv)
GHOST_TUns32 fullScreenHeight= 0;
int fullScreenBpp = 32;
int fullScreenFrequency = 60;
- GHOST_TEmbedderWindowID parentWindow = 0;
-
-
#ifdef __linux__
#ifdef __alpha__
signal (SIGFPE, SIG_IGN);
@@ -335,18 +321,8 @@ int main(int argc, char** argv)
::DisposeNibReference(nibRef);
*/
#endif // __APPLE__
-
- init_nodesystem();
- initglobals();
-
GEN_init_messaging_system();
-
-#ifdef WITH_QUICKTIME
- quicktime_init();
-#endif
-
- libtiff_init();
// Parse command line options
#ifndef NDEBUG
@@ -425,12 +401,6 @@ int main(int argc, char** argv)
}
}
break;
-
- case 'd':
- i++;
- G.f |= G_DEBUG; /* std output printf's */
- MEM_set_memory_debug();
- break;
case 'p':
// Parse window position and size options
@@ -483,16 +453,6 @@ int main(int argc, char** argv)
usage(argv[0]);
return 0;
break;
-#ifndef _WIN32
- case 'i':
- i++;
- if ( (i + 1) < argc )
- parentWindow = atoi(argv[i++]);
-#ifndef NDEBUG
- printf("XWindows ID = %d\n", parentWindow);
-#endif //NDEBUG
-
-#endif // _WIN32
case 'c':
i++;
closeConsole = false;
@@ -563,19 +523,21 @@ int main(int argc, char** argv)
return 0;
}
+ if (!stereoParFound) stereomode = RAS_IRasterizer::RAS_STEREO_NOSTEREO;
+
#ifdef WIN32
if (scr_saver_mode != SCREEN_SAVER_MODE_CONFIGURATION)
#endif
{
#ifdef __APPLE__
//SYS_WriteCommandLineInt(syshandle, "show_framerate", 1);
- //SYS_WriteCommandLineInt(syshandle, "nomipmap", 1);
+ SYS_WriteCommandLineInt(syshandle, "nomipmap", 1);
//fullScreen = false; // Can't use full screen
#endif
if (SYS_GetCommandLineInt(syshandle, "nomipmap", 0))
{
- GPU_set_mipmap(0);
+ GPC_PolygonMaterial::SetMipMappingEnabled(0);
}
// Create the system
@@ -597,15 +559,11 @@ int main(int argc, char** argv)
{
int exitcode = KX_EXIT_REQUEST_NO_REQUEST;
STR_String exitstring = "";
- GPG_Application app(system);
+ GPG_Application app(system, NULL, exitstring);
bool firstTimeRunning = true;
- char filename[FILE_MAXDIR + FILE_MAXFILE];
- char pathname[FILE_MAXDIR + FILE_MAXFILE];
+ char *filename = get_filename(argc, argv);
char *titlename;
-
- get_filename(argc, argv, filename);
- if(filename[0])
- BLI_convertstringcwd(filename);
+ char pathname[160];
do
{
@@ -617,7 +575,8 @@ int main(int argc, char** argv)
{
char basedpath[240];
- // base the actuator filename relative to the last file
+ // base the actuator filename with respect
+ // to the original file working directory
strcpy(basedpath, exitstring.Ptr());
BLI_convertstringcode(basedpath, pathname);
@@ -636,7 +595,7 @@ int main(int argc, char** argv)
}
else
{
- bfd = load_game_data(bprogname, filename[0]? filename: NULL);
+ bfd = load_game_data(argv[0], filename);
}
//::printf("game data loaded from %s\n", filename);
@@ -658,10 +617,8 @@ int main(int argc, char** argv)
#endif // WIN32
Main *maggie = bfd->main;
Scene *scene = bfd->curscene;
- G.main = maggie;
-
- if (firstTimeRunning)
- G.fileflags = bfd->fileflags;
+ char *startscenename = scene->id.name + 2;
+ G.fileflags = bfd->fileflags;
//Seg Fault; icon.c gIcons == 0
BKE_icons_init(1);
@@ -698,16 +655,17 @@ int main(int argc, char** argv)
}
// GPG_Application app (system, maggie, startscenename);
- app.SetGameEngineData(maggie, scene);
+ app.SetGameEngineData(maggie, startscenename);
- BLI_strncpy(pathname, maggie->name, sizeof(pathname));
- BLI_strncpy(G.sce, maggie->name, sizeof(G.sce));
-
if (firstTimeRunning)
{
- setGamePythonPath(G.sce);
firstTimeRunning = false;
+ // set the filename only the first time as in KetsjiEmbedded
+ strcpy (pathname, maggie->name);
+ // also copy here (used by GameLogic.getBaseDirectory)
+ strcpy (G.sce, maggie->name);
+
if (fullScreen)
{
#ifdef WIN32
@@ -765,10 +723,7 @@ int main(int argc, char** argv)
else
#endif
{
- if (parentWindow != 0)
- app.startEmbeddedWindow(title, parentWindow, stereoWindow, stereomode);
- else
- app.startWindow(title, windowLeft, windowTop, windowWidth, windowHeight,
+ app.startWindow(title, windowLeft, windowTop, windowWidth, windowHeight,
stereoWindow, stereomode);
}
}
@@ -795,8 +750,13 @@ int main(int argc, char** argv)
}
}
app.StopGameEngine();
-
BLO_blendfiledata_free(bfd);
+
+#ifdef __APPLE__
+ if (filename) {
+ delete [] filename;
+ }
+#endif // __APPLE__
}
} while (exitcode == KX_EXIT_REQUEST_RESTART_GAME || exitcode == KX_EXIT_REQUEST_START_OTHER_GAME);
}
@@ -812,8 +772,6 @@ int main(int argc, char** argv)
}
}
- free_nodesystem();
-
return error ? -1 : 0;
}
diff --git a/source/gameengine/GamePlayer/ghost/Makefile b/source/gameengine/GamePlayer/ghost/Makefile
index 5f90d804611..13940ac3fc8 100644
--- a/source/gameengine/GamePlayer/ghost/Makefile
+++ b/source/gameengine/GamePlayer/ghost/Makefile
@@ -41,7 +41,6 @@ CPPFLAGS += -I$(OPENGL_HEADERS)
CPPFLAGS += -I$(NAN_STRING)/include
CPPFLAGS += -I$(NAN_BMFONT)/include
CPPFLAGS += -I$(NAN_SOUNDSYSTEM)/include
-CPPFLAGS += -I$(NAN_GUARDEDALLOC)/include
CPPFLAGS += -I../../GamePlayer/common
@@ -70,7 +69,6 @@ CPPFLAGS += -I../../../blender/blenloader
CPPFLAGS += -I../../../blender/imbuf
CPPFLAGS += -I../../../blender/makesdna
CPPFLAGS += -I../../../blender/readblenfile
-CPPFLAGS += -I../../../blender/gpu
CPPFLAGS += -I../../../gameengine/BlenderRoutines
@@ -82,6 +80,7 @@ CPPFLAGS += -I$(NAN_STRING)/include
CPPFLAGS += -I$(NAN_GHOST)/include
CPPFLAGS += -I$(NAN_PYTHON)/include/python$(NAN_PYTHON_VERSION)
-ifeq ($(WITH_FFMPEG), true)
- CPPFLAGS += -DWITH_FFMPEG
+ifeq ($(WITH_BF_GLEXT),true)
+ CPPFLAGS += -DWITH_GLEXT
endif
+
diff --git a/source/gameengine/GamePlayer/ghost/SConscript b/source/gameengine/GamePlayer/ghost/SConscript
index 4f1324b3938..f3cce6c7443 100644
--- a/source/gameengine/GamePlayer/ghost/SConscript
+++ b/source/gameengine/GamePlayer/ghost/SConscript
@@ -40,7 +40,6 @@ incs = ['.',
'#source/gameengine/GamePlayer/common',
'#source/blender/misc',
'#source/blender/blenloader',
- '#source/blender/gpu',
'#extern/glew/include']
incs += Split(env['BF_PYTHON_INC'])
@@ -49,8 +48,8 @@ cflags = []
if env['OURPLATFORM']=='win32-vc':
cflags = ['/GR']
-defs = ''
-if env['WITH_BF_FFMPEG']:
- defs += ' WITH_FFMPEG'
+if env['WITH_BF_GLEXT'] == 1:
+ env['CPPFLAGS'].append('-DWITH_GLEXT')
-env.BlenderLib (libname='gp_ghost', sources=source_files, includes = incs, defines = Split(defs), libtype='player',priority=0, compileflags=cflags)
+
+env.BlenderLib (libname='gp_ghost', sources=source_files, includes = incs, defines = [], libtype='player',priority=0, compileflags=cflags)
diff --git a/source/gameengine/Ketsji/BL_BlenderShader.cpp b/source/gameengine/Ketsji/BL_BlenderShader.cpp
index 8ec463be6ff..a9a0771936c 100644
--- a/source/gameengine/Ketsji/BL_BlenderShader.cpp
+++ b/source/gameengine/Ketsji/BL_BlenderShader.cpp
@@ -9,64 +9,108 @@
#include "BL_BlenderShader.h"
#include "BL_Material.h"
+#ifdef BLENDER_GLSL
#include "GPU_extensions.h"
#include "GPU_material.h"
+#endif
#include "RAS_BucketManager.h"
#include "RAS_MeshObject.h"
#include "RAS_IRasterizer.h"
+ /* this is evil, but we need the scene to create materials with
+ * lights from the correct scene .. */
+static struct Scene *GetSceneForName(const STR_String& scenename)
+{
+ Scene *sce;
+
+ for (sce= (Scene*)G.main->scene.first; sce; sce= (Scene*)sce->id.next)
+ if (scenename == (sce->id.name+2))
+ return sce;
+
+ return (Scene*)G.main->scene.first;
+}
+
+bool BL_BlenderShader::Ok()
+{
+#ifdef BLENDER_GLSL
+ VerifyShader();
+
+ return (mMat && mMat->gpumaterial);
+#else
+ return 0;
+#endif
+}
+
BL_BlenderShader::BL_BlenderShader(KX_Scene *scene, struct Material *ma, int lightlayer)
:
+#ifdef BLENDER_GLSL
mScene(scene),
mMat(ma),
+ mGPUMat(NULL),
+#endif
+ mBound(false),
mLightLayer(lightlayer)
{
- mBlenderScene = scene->GetBlenderScene();
+#ifdef BLENDER_GLSL
+ mBlenderScene = GetSceneForName(scene->GetName());
mBlendMode = GPU_BLEND_SOLID;
- if(mMat)
+ if(mMat) {
GPU_material_from_blender(mBlenderScene, mMat);
+ mGPUMat = mMat->gpumaterial;
+ }
+#endif
}
BL_BlenderShader::~BL_BlenderShader()
{
- if(mMat && GPU_material_from_blender(mBlenderScene, mMat))
- GPU_material_unbind(GPU_material_from_blender(mBlenderScene, mMat));
-}
-
-bool BL_BlenderShader::Ok()
-{
- return VerifyShader();
+#ifdef BLENDER_GLSL
+ if(mMat && mMat->gpumaterial)
+ GPU_material_unbind(mMat->gpumaterial);
+#endif
}
bool BL_BlenderShader::VerifyShader()
{
- if(mMat)
- return (GPU_material_from_blender(mBlenderScene, mMat) != 0);
- else
- return false;
+#ifdef BLENDER_GLSL
+ if(mMat && !mMat->gpumaterial)
+ GPU_material_from_blender(mBlenderScene, mMat);
+
+ mGPUMat = mMat->gpumaterial;
+
+ return (mMat && mGPUMat);
+#else
+ return false;
+#endif
}
-void BL_BlenderShader::SetProg(bool enable, double time)
+void BL_BlenderShader::SetProg(bool enable)
{
+#ifdef BLENDER_GLSL
if(VerifyShader()) {
- if(enable)
- GPU_material_bind(GPU_material_from_blender(mBlenderScene, mMat), mLightLayer, ~0, time);
- else
- GPU_material_unbind(GPU_material_from_blender(mBlenderScene, mMat));
+ if(enable) {
+ GPU_material_bind(mGPUMat, mLightLayer);
+ mBound = true;
+ }
+ else {
+ GPU_material_unbind(mGPUMat);
+ mBound = false;
+ }
}
+#endif
}
int BL_BlenderShader::GetAttribNum()
{
+#ifdef BLENDER_GLSL
GPUVertexAttribs attribs;
int i, enabled = 0;
if(!VerifyShader())
return enabled;
- GPU_material_vertex_attributes(GPU_material_from_blender(mBlenderScene, mMat), &attribs);
+ GPU_material_vertex_attributes(mGPUMat, &attribs);
for(i = 0; i < attribs.totlayer; i++)
if(attribs.layer[i].glindex+1 > enabled)
@@ -76,23 +120,24 @@ int BL_BlenderShader::GetAttribNum()
enabled = BL_MAX_ATTRIB;
return enabled;
+#else
+ return 0;
+#endif
}
void BL_BlenderShader::SetAttribs(RAS_IRasterizer* ras, const BL_Material *mat)
{
+#ifdef BLENDER_GLSL
GPUVertexAttribs attribs;
- GPUMaterial *gpumat;
int i, attrib_num;
ras->SetAttribNum(0);
if(!VerifyShader())
return;
-
- gpumat = GPU_material_from_blender(mBlenderScene, mMat);
if(ras->GetDrawingMode() == RAS_IRasterizer::KX_TEXTURED) {
- GPU_material_vertex_attributes(gpumat, &attribs);
+ GPU_material_vertex_attributes(mGPUMat, &attribs);
attrib_num = GetAttribNum();
ras->SetTexCoordNum(0);
@@ -123,37 +168,44 @@ void BL_BlenderShader::SetAttribs(RAS_IRasterizer* ras, const BL_Material *mat)
else
ras->SetAttrib(RAS_IRasterizer::RAS_TEXCO_DISABLE, attribs.layer[i].glindex);
}
+
+ ras->EnableTextures(true);
}
+ else
+ ras->EnableTextures(false);
+#endif
}
-void BL_BlenderShader::Update(const RAS_MeshSlot & ms, RAS_IRasterizer* rasty )
+void BL_BlenderShader::Update( const KX_MeshSlot & ms, RAS_IRasterizer* rasty )
{
+#ifdef BLENDER_GLSL
float obmat[4][4], viewmat[4][4], viewinvmat[4][4], obcol[4];
- GPUMaterial *gpumat;
- gpumat = GPU_material_from_blender(mBlenderScene, mMat);
+ VerifyShader();
- if(!gpumat || !GPU_material_bound(gpumat))
+ if(!mGPUMat) // || !mBound)
return;
MT_Matrix4x4 model;
model.setValue(ms.m_OpenGLMatrix);
- const MT_Matrix4x4& view = rasty->GetViewMatrix();
- const MT_Matrix4x4& viewinv = rasty->GetViewInvMatrix();
+ MT_Matrix4x4 view;
+ rasty->GetViewMatrix(view);
- // note: getValue gives back column major as needed by OpenGL
model.getValue((float*)obmat);
view.getValue((float*)viewmat);
- viewinv.getValue((float*)viewinvmat);
+
+ view.invert();
+ view.getValue((float*)viewinvmat);
if(ms.m_bObjectColor)
ms.m_RGBAcolor.getValue((float*)obcol);
else
obcol[0]= obcol[1]= obcol[2]= obcol[3]= 1.0f;
- GPU_material_bind_uniforms(gpumat, obmat, viewmat, viewinvmat, obcol);
+ GPU_material_bind_uniforms(mGPUMat, obmat, viewmat, viewinvmat, obcol);
- mBlendMode = GPU_material_blend_mode(gpumat, obcol);
+ mBlendMode = GPU_material_blend_mode(mGPUMat, obcol);
+#endif
}
int BL_BlenderShader::GetBlendMode()
@@ -163,8 +215,12 @@ int BL_BlenderShader::GetBlendMode()
bool BL_BlenderShader::Equals(BL_BlenderShader *blshader)
{
+#ifdef BLENDER_GLSL
/* to avoid unneeded state switches */
- return (blshader && mMat == blshader->mMat && mLightLayer == blshader->mLightLayer);
+ return (blshader && mGPUMat == blshader->mGPUMat && mLightLayer == blshader->mLightLayer);
+#else
+ return true;
+#endif
}
// eof
diff --git a/source/gameengine/Ketsji/BL_BlenderShader.h b/source/gameengine/Ketsji/BL_BlenderShader.h
index 5c1f59f94ad..da9765dafa4 100644
--- a/source/gameengine/Ketsji/BL_BlenderShader.h
+++ b/source/gameengine/Ketsji/BL_BlenderShader.h
@@ -2,7 +2,9 @@
#ifndef __BL_GPUSHADER_H__
#define __BL_GPUSHADER_H__
+#ifdef BLENDER_GLSL
#include "GPU_material.h"
+#endif
#include "MT_Matrix4x4.h"
#include "MT_Matrix3x3.h"
@@ -27,9 +29,13 @@ class BL_Material;
class BL_BlenderShader
{
private:
+#ifdef BLENDER_GLSL
KX_Scene *mScene;
struct Scene *mBlenderScene;
struct Material *mMat;
+ GPUMaterial *mGPUMat;
+#endif
+ bool mBound;
int mLightLayer;
int mBlendMode;
@@ -40,11 +46,11 @@ public:
virtual ~BL_BlenderShader();
bool Ok();
- void SetProg(bool enable, double time=0.0);
+ void SetProg(bool enable);
int GetAttribNum();
void SetAttribs(class RAS_IRasterizer* ras, const BL_Material *mat);
- void Update(const class RAS_MeshSlot & ms, class RAS_IRasterizer* rasty);
+ void Update(const class KX_MeshSlot & ms, class RAS_IRasterizer* rasty);
int GetBlendMode();
bool Equals(BL_BlenderShader *blshader);
diff --git a/source/gameengine/Ketsji/BL_Material.h b/source/gameengine/Ketsji/BL_Material.h
index 0eaa234566c..dcb66ea2579 100644
--- a/source/gameengine/Ketsji/BL_Material.h
+++ b/source/gameengine/Ketsji/BL_Material.h
@@ -18,9 +18,9 @@ struct EnvMap;
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
+ we will go for three, which should be enough
*/
-#define MAXTEX 8 //match in RAS_TexVert & RAS_OpenGLRasterizer
+#define MAXTEX 3 //match in RAS_TexVert & RAS_OpenGLRasterizer
// different mapping modes
class BL_Mapping
@@ -139,7 +139,7 @@ enum BL_ras_mode
COLLIDER=2,
ZSORT=4,
ALPHA=8,
- // TRIANGLE=16,
+ TRIANGLE=16,
USE_LIGHT=32,
WIRE=64
};
diff --git a/source/gameengine/Ketsji/BL_Shader.cpp b/source/gameengine/Ketsji/BL_Shader.cpp
index 80892764089..f6f9a29b0e2 100644
--- a/source/gameengine/Ketsji/BL_Shader.cpp
+++ b/source/gameengine/Ketsji/BL_Shader.cpp
@@ -433,7 +433,7 @@ void BL_Shader::SetProg(bool enable)
}
}
-void BL_Shader::Update( const RAS_MeshSlot & ms, RAS_IRasterizer* rasty )
+void BL_Shader::Update( const KX_MeshSlot & ms, RAS_IRasterizer* rasty )
{
if(!Ok() || !mPreDef.size())
return;
@@ -445,7 +445,8 @@ void BL_Shader::Update( const RAS_MeshSlot & ms, RAS_IRasterizer* rasty )
{
MT_Matrix4x4 model;
model.setValue(ms.m_OpenGLMatrix);
- const MT_Matrix4x4& view = rasty->GetViewMatrix();
+ MT_Matrix4x4 view;
+ rasty->GetViewMatrix(view);
if(mAttr==SHD_TANGENT)
ms.m_mesh->SetMeshModified(true);
@@ -524,15 +525,13 @@ void BL_Shader::Update( const RAS_MeshSlot & ms, RAS_IRasterizer* rasty )
}
case VIEWMATRIX_INVERSE:
{
- MT_Matrix4x4 viewinv = view;
- viewinv.invert();
+ view.invert();
SetUniform(uni->mLoc, view);
break;
}
case VIEWMATRIX_INVERSETRANSPOSE:
{
- MT_Matrix4x4 viewinv = view;
- viewinv.invert();
+ view.invert();
SetUniform(uni->mLoc, view, true);
break;
}
@@ -671,7 +670,6 @@ void BL_Shader::SetUniform(int uniform, const MT_Matrix4x4& vec, bool transpose)
)
{
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);
}
@@ -848,7 +846,8 @@ KX_PYMETHODDEF_DOC( BL_Shader, getFragmentProg ,"getFragmentProg( )" )
KX_PYMETHODDEF_DOC( BL_Shader, validate, "validate()")
{
if(mError) {
- Py_RETURN_NONE;
+ Py_INCREF(Py_None);
+ return Py_None;
}
if(mShader==0) {
PyErr_Format(PyExc_TypeError, "invalid shader object");
@@ -878,10 +877,11 @@ KX_PYMETHODDEF_DOC( BL_Shader, validate, "validate()")
KX_PYMETHODDEF_DOC( BL_Shader, setSampler, "setSampler(name, index)" )
{
if(mError) {
- Py_RETURN_NONE;
+ Py_INCREF(Py_None);
+ return Py_None;
}
- const char *uniform="";
+ char *uniform="";
int index=-1;
if(PyArg_ParseTuple(args, "si", &uniform, &index))
{
@@ -900,7 +900,7 @@ KX_PYMETHODDEF_DOC( BL_Shader, setSampler, "setSampler(name, index)" )
//else
// spit("Invalid texture sample index: " << index);
}
- Py_RETURN_NONE;
+ Py_Return;
}
return NULL;
}
@@ -919,10 +919,11 @@ KX_PYMETHODDEF_DOC( BL_Shader, setNumberOfPasses, "setNumberOfPasses( max-pass )
KX_PYMETHODDEF_DOC( BL_Shader, setUniform1f, "setUniform1f(name, fx)" )
{
if(mError) {
- Py_RETURN_NONE;
+ Py_INCREF(Py_None);
+ return Py_None;
}
- const char *uniform="";
+ char *uniform="";
float value=0;
if(PyArg_ParseTuple(args, "sf", &uniform, &value ))
{
@@ -944,9 +945,10 @@ KX_PYMETHODDEF_DOC( BL_Shader, setUniform1f, "setUniform1f(name, fx)" )
KX_PYMETHODDEF_DOC( BL_Shader, setUniform2f , "setUniform2f(name, fx, fy)")
{
if(mError) {
- Py_RETURN_NONE;
+ Py_INCREF(Py_None);
+ return Py_None;
}
- const char *uniform="";
+ char *uniform="";
float array[2]={ 0,0 };
if(PyArg_ParseTuple(args, "sff", &uniform, &array[0],&array[1] ))
{
@@ -968,9 +970,10 @@ KX_PYMETHODDEF_DOC( BL_Shader, setUniform2f , "setUniform2f(name, fx, fy)")
KX_PYMETHODDEF_DOC( BL_Shader, setUniform3f, "setUniform3f(name, fx,fy,fz) ")
{
if(mError) {
- Py_RETURN_NONE;
+ Py_INCREF(Py_None);
+ return Py_None;
}
- const char *uniform="";
+ char *uniform="";
float array[3]={0,0,0};
if(PyArg_ParseTuple(args, "sfff", &uniform, &array[0],&array[1],&array[2]))
{
@@ -993,9 +996,10 @@ KX_PYMETHODDEF_DOC( BL_Shader, setUniform3f, "setUniform3f(name, fx,fy,fz) ")
KX_PYMETHODDEF_DOC( BL_Shader, setUniform4f, "setUniform4f(name, fx,fy,fz, fw) ")
{
if(mError) {
- Py_RETURN_NONE;
+ Py_INCREF(Py_None);
+ return Py_None;
}
- const char *uniform="";
+ char *uniform="";
float array[4]={0,0,0,0};
if(PyArg_ParseTuple(args, "sffff", &uniform, &array[0],&array[1],&array[2], &array[3]))
{
@@ -1017,9 +1021,10 @@ KX_PYMETHODDEF_DOC( BL_Shader, setUniform4f, "setUniform4f(name, fx,fy,fz, fw) "
KX_PYMETHODDEF_DOC( BL_Shader, setUniform1i, "setUniform1i(name, ix)" )
{
if(mError) {
- Py_RETURN_NONE;
+ Py_INCREF(Py_None);
+ return Py_None;
}
- const char *uniform="";
+ char *uniform="";
int value=0;
if(PyArg_ParseTuple(args, "si", &uniform, &value ))
{
@@ -1041,9 +1046,10 @@ KX_PYMETHODDEF_DOC( BL_Shader, setUniform1i, "setUniform1i(name, ix)" )
KX_PYMETHODDEF_DOC( BL_Shader, setUniform2i , "setUniform2i(name, ix, iy)")
{
if(mError) {
- Py_RETURN_NONE;
+ Py_INCREF(Py_None);
+ return Py_None;
}
- const char *uniform="";
+ char *uniform="";
int array[2]={ 0,0 };
if(PyArg_ParseTuple(args, "sii", &uniform, &array[0],&array[1] ))
{
@@ -1065,10 +1071,11 @@ KX_PYMETHODDEF_DOC( BL_Shader, setUniform2i , "setUniform2i(name, ix, iy)")
KX_PYMETHODDEF_DOC( BL_Shader, setUniform3i, "setUniform3i(name, ix,iy,iz) ")
{
if(mError) {
- Py_RETURN_NONE;
+ Py_INCREF(Py_None);
+ return Py_None;
}
- const char *uniform="";
+ char *uniform="";
int array[3]={0,0,0};
if(PyArg_ParseTuple(args, "siii", &uniform, &array[0],&array[1],&array[2]))
{
@@ -1089,9 +1096,10 @@ KX_PYMETHODDEF_DOC( BL_Shader, setUniform3i, "setUniform3i(name, ix,iy,iz) ")
KX_PYMETHODDEF_DOC( BL_Shader, setUniform4i, "setUniform4i(name, ix,iy,iz, iw) ")
{
if(mError) {
- Py_RETURN_NONE;
+ Py_INCREF(Py_None);
+ return Py_None;
}
- const char *uniform="";
+ char *uniform="";
int array[4]={0,0,0, 0};
if(PyArg_ParseTuple(args, "siiii", &uniform, &array[0],&array[1],&array[2], &array[3] ))
{
@@ -1112,9 +1120,10 @@ KX_PYMETHODDEF_DOC( BL_Shader, setUniform4i, "setUniform4i(name, ix,iy,iz, iw) "
KX_PYMETHODDEF_DOC( BL_Shader, setUniformfv , "setUniformfv( float (list2 or list3 or list4) )")
{
if(mError) {
- Py_RETURN_NONE;
+ Py_INCREF(Py_None);
+ return Py_None;
}
- const char *uniform = "";
+ char*uniform = "";
PyObject *listPtr =0;
float array_data[4] = {0.f,0.f,0.f,0.f};
@@ -1181,9 +1190,10 @@ KX_PYMETHODDEF_DOC( BL_Shader, setUniformfv , "setUniformfv( float (list2 or lis
KX_PYMETHODDEF_DOC( BL_Shader, setUniformiv, "setUniformiv( int (list2 or list3 or list4) )")
{
if(mError) {
- Py_RETURN_NONE;
+ Py_INCREF(Py_None);
+ return Py_None;
}
- const char *uniform = "";
+ char*uniform = "";
PyObject *listPtr =0;
int array_data[4] = {0,0,0,0};
@@ -1253,7 +1263,8 @@ KX_PYMETHODDEF_DOC( BL_Shader, setUniformMatrix4,
"setUniformMatrix4(uniform-name, mat-4x4, transpose(row-major=true, col-major=false)" )
{
if(mError) {
- Py_RETURN_NONE;
+ Py_INCREF(Py_None);
+ return Py_None;
}
float matr[16] = {
@@ -1263,7 +1274,7 @@ KX_PYMETHODDEF_DOC( BL_Shader, setUniformMatrix4,
0,0,0,1
};
- const char *uniform="";
+ char *uniform="";
PyObject *matrix=0;
int transp=1; // MT_ is row major so transpose by default....
if(PyArg_ParseTuple(args, "sO|i",&uniform, &matrix,&transp))
@@ -1295,7 +1306,8 @@ KX_PYMETHODDEF_DOC( BL_Shader, setUniformMatrix3,
"setUniformMatrix3(uniform-name, list[3x3], transpose(row-major=true, col-major=false)" )
{
if(mError) {
- Py_RETURN_NONE;
+ Py_INCREF(Py_None);
+ return Py_None;
}
float matr[9] = {
@@ -1304,7 +1316,7 @@ KX_PYMETHODDEF_DOC( BL_Shader, setUniformMatrix3,
0,0,1,
};
- const char *uniform="";
+ char *uniform="";
PyObject *matrix=0;
int transp=1; // MT_ is row major so transpose by default....
if(PyArg_ParseTuple(args, "sO|i",&uniform, &matrix,&transp))
@@ -1335,7 +1347,8 @@ KX_PYMETHODDEF_DOC( BL_Shader, setUniformMatrix3,
KX_PYMETHODDEF_DOC( BL_Shader, setAttrib, "setAttrib(enum)" )
{
if(mError) {
- Py_RETURN_NONE;
+ Py_INCREF(Py_None);
+ return Py_None;
}
int attr=0;
if(PyArg_ParseTuple(args, "i", &attr )) {
@@ -1355,10 +1368,11 @@ KX_PYMETHODDEF_DOC( BL_Shader, setAttrib, "setAttrib(enum)" )
KX_PYMETHODDEF_DOC( BL_Shader, setUniformDef, "setUniformDef(name, enum)" )
{
if(mError) {
- Py_RETURN_NONE;
+ Py_INCREF(Py_None);
+ return Py_None;
}
- const char *uniform="";
+ char *uniform="";
int nloc=0;
if(PyArg_ParseTuple(args, "si",&uniform, &nloc))
{
diff --git a/source/gameengine/Ketsji/BL_Shader.h b/source/gameengine/Ketsji/BL_Shader.h
index 18ca8f8b4f8..8f303454087 100644
--- a/source/gameengine/Ketsji/BL_Shader.h
+++ b/source/gameengine/Ketsji/BL_Shader.h
@@ -102,8 +102,8 @@ private:
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
+ char* vertProg; // Vertex program string
+ char* fragProg; // Fragment program string
bool mError; // ...
bool mDirty; //
@@ -177,7 +177,7 @@ public:
void UnloadShader();
// Update predefined uniforms each render call
- void Update(const class RAS_MeshSlot & ms, class RAS_IRasterizer* rasty);
+ void Update(const class KX_MeshSlot & ms, class RAS_IRasterizer* rasty);
//// Set sampler units (copied)
//void InitializeSampler(int unit, BL_Texture* texture );
diff --git a/source/gameengine/Ketsji/BL_Texture.h b/source/gameengine/Ketsji/BL_Texture.h
index 830ffceb0f7..0d0c7a277f2 100644
--- a/source/gameengine/Ketsji/BL_Texture.h
+++ b/source/gameengine/Ketsji/BL_Texture.h
@@ -59,14 +59,6 @@ public:
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;
- }
-
};
#endif//__BL_TEXTURE_H__
diff --git a/source/gameengine/Ketsji/CMakeLists.txt b/source/gameengine/Ketsji/CMakeLists.txt
index 58411f6d25e..be009d94701 100644
--- a/source/gameengine/Ketsji/CMakeLists.txt
+++ b/source/gameengine/Ketsji/CMakeLists.txt
@@ -69,7 +69,6 @@ SET(INC
../../../intern/SoundSystem
../../../source/blender/misc
../../../source/blender/blenloader
- ../../../source/blender/gpu
../../../extern/bullet2/src
../../../extern/solid
../../../extern/glew/include
diff --git a/source/gameengine/Ketsji/KXNetwork/KX_NetworkMessageSensor.cpp b/source/gameengine/Ketsji/KXNetwork/KX_NetworkMessageSensor.cpp
index 8956df9c96b..0c66ac1fde3 100644
--- a/source/gameengine/Ketsji/KXNetwork/KX_NetworkMessageSensor.cpp
+++ b/source/gameengine/Ketsji/KXNetwork/KX_NetworkMessageSensor.cpp
@@ -196,20 +196,20 @@ PyParentObject KX_NetworkMessageSensor::Parents[] = {
PyMethodDef KX_NetworkMessageSensor::Methods[] = {
{"setSubjectFilterText", (PyCFunction)
- KX_NetworkMessageSensor::sPySetSubjectFilterText, METH_O,
- (PY_METHODCHAR)SetSubjectFilterText_doc},
+ KX_NetworkMessageSensor::sPySetSubjectFilterText, METH_VARARGS,
+ SetSubjectFilterText_doc},
{"getFrameMessageCount", (PyCFunction)
- KX_NetworkMessageSensor::sPyGetFrameMessageCount, METH_NOARGS,
- (PY_METHODCHAR)GetFrameMessageCount_doc},
+ KX_NetworkMessageSensor::sPyGetFrameMessageCount, METH_VARARGS,
+ GetFrameMessageCount_doc},
{"getBodies", (PyCFunction)
- KX_NetworkMessageSensor::sPyGetBodies, METH_NOARGS,
- (PY_METHODCHAR)GetBodies_doc},
+ KX_NetworkMessageSensor::sPyGetBodies, METH_VARARGS,
+ GetBodies_doc},
{"getSubject", (PyCFunction)
- KX_NetworkMessageSensor::sPyGetSubject, METH_NOARGS,
- (PY_METHODCHAR)GetSubject_doc},
+ KX_NetworkMessageSensor::sPyGetSubject, METH_VARARGS,
+ GetSubject_doc},
{"getSubjects", (PyCFunction)
- KX_NetworkMessageSensor::sPyGetSubjects, METH_NOARGS,
- (PY_METHODCHAR)GetSubjects_doc},
+ KX_NetworkMessageSensor::sPyGetSubjects, METH_VARARGS,
+ GetSubjects_doc},
{NULL,NULL} //Sentinel
};
@@ -218,66 +218,88 @@ PyObject* KX_NetworkMessageSensor::_getattr(const STR_String& attr) {
}
// 1. Set the message subject that this sensor listens for
-const char KX_NetworkMessageSensor::SetSubjectFilterText_doc[] =
+char KX_NetworkMessageSensor::SetSubjectFilterText_doc[] =
"\tsetSubjectFilterText(value)\n"
"\tChange the message subject text that this sensor is listening to.\n";
-PyObject* KX_NetworkMessageSensor::PySetSubjectFilterText( PyObject* self, PyObject* value)
+PyObject* KX_NetworkMessageSensor::PySetSubjectFilterText(
+ PyObject* self,
+ PyObject* args,
+ PyObject* kwds)
{
- char* Subject = PyString_AsString(value);
- if (Subject==NULL) {
- PyErr_SetString(PyExc_TypeError, "expected a string message");
+ char* Subject;
+
+ if (PyArg_ParseTuple(args, "s", &Subject))
+ {
+ m_subject = Subject;
+ }
+ else {
return NULL;
}
-
- m_subject = Subject;
- Py_RETURN_NONE;
+
+ Py_Return;
}
// 2. Get the number of messages received since the last frame
-const char KX_NetworkMessageSensor::GetFrameMessageCount_doc[] =
+char KX_NetworkMessageSensor::GetFrameMessageCount_doc[] =
"\tgetFrameMessageCount()\n"
"\tGet the number of messages received since the last frame.\n";
-PyObject* KX_NetworkMessageSensor::PyGetFrameMessageCount( PyObject* )
+PyObject* KX_NetworkMessageSensor::PyGetFrameMessageCount(
+ PyObject* self,
+ PyObject* args,
+ PyObject* kwds)
{
return PyInt_FromLong(long(m_frame_message_count));
}
// 3. Get the message bodies
-const char KX_NetworkMessageSensor::GetBodies_doc[] =
+char KX_NetworkMessageSensor::GetBodies_doc[] =
"\tgetBodies()\n"
"\tGet the list of message bodies.\n";
-PyObject* KX_NetworkMessageSensor::PyGetBodies( PyObject* )
+PyObject* KX_NetworkMessageSensor::PyGetBodies(
+ PyObject* self,
+ PyObject* args,
+ PyObject* kwds)
{
if (m_BodyList) {
return ((PyObject*) m_BodyList->AddRef());
- } else {
- return ((PyObject*) new CListValue());
}
+
+ Py_Return;
}
// 4. Get the message subject: field of the message sensor
-const char KX_NetworkMessageSensor::GetSubject_doc[] =
+char KX_NetworkMessageSensor::GetSubject_doc[] =
"\tgetSubject()\n"
"\tGet the subject: field of the message sensor.\n";
-PyObject* KX_NetworkMessageSensor::PyGetSubject( PyObject* )
+PyObject* KX_NetworkMessageSensor::PyGetSubject(
+ PyObject* self,
+ PyObject* args,
+ PyObject* kwds)
{
- return PyString_FromString(m_subject ? m_subject : "");
+ if (m_subject) {
+ return PyString_FromString(m_subject);
+ }
+
+ Py_Return;
}
// 5. Get the message subjects
-const char KX_NetworkMessageSensor::GetSubjects_doc[] =
+char KX_NetworkMessageSensor::GetSubjects_doc[] =
"\tgetSubjects()\n"
"\tGet list of message subjects.\n";
-PyObject* KX_NetworkMessageSensor::PyGetSubjects( PyObject* )
+PyObject* KX_NetworkMessageSensor::PyGetSubjects(
+ PyObject* self,
+ PyObject* args,
+ PyObject* kwds)
{
if (m_SubjectList) {
- return ((PyObject*) m_SubjectList->AddRef());
- } else {
- return ((PyObject*) new CListValue());
- }
+ return ((PyObject*) m_SubjectList->AddRef());
+ }
+
+ Py_Return;
}
diff --git a/source/gameengine/Ketsji/KXNetwork/KX_NetworkMessageSensor.h b/source/gameengine/Ketsji/KXNetwork/KX_NetworkMessageSensor.h
index 8cdfd6cdb5a..6fd92d17be3 100644
--- a/source/gameengine/Ketsji/KXNetwork/KX_NetworkMessageSensor.h
+++ b/source/gameengine/Ketsji/KXNetwork/KX_NetworkMessageSensor.h
@@ -74,11 +74,11 @@ public:
virtual PyObject* _getattr(const STR_String& attr);
- KX_PYMETHOD_DOC_O(KX_NetworkMessageSensor, SetSubjectFilterText);
- KX_PYMETHOD_DOC_NOARGS(KX_NetworkMessageSensor, GetFrameMessageCount);
- KX_PYMETHOD_DOC_NOARGS(KX_NetworkMessageSensor, GetBodies);
- KX_PYMETHOD_DOC_NOARGS(KX_NetworkMessageSensor, GetSubject);
- KX_PYMETHOD_DOC_NOARGS(KX_NetworkMessageSensor, GetSubjects);
+ KX_PYMETHOD_DOC(KX_NetworkMessageSensor, SetSubjectFilterText);
+ KX_PYMETHOD_DOC(KX_NetworkMessageSensor, GetFrameMessageCount);
+ KX_PYMETHOD_DOC(KX_NetworkMessageSensor, GetBodies);
+ KX_PYMETHOD_DOC(KX_NetworkMessageSensor, GetSubject);
+ KX_PYMETHOD_DOC(KX_NetworkMessageSensor, GetSubjects);
};
diff --git a/source/gameengine/Ketsji/KX_BlenderMaterial.cpp b/source/gameengine/Ketsji/KX_BlenderMaterial.cpp
index f92200780d5..a67e5b26667 100644
--- a/source/gameengine/Ketsji/KX_BlenderMaterial.cpp
+++ b/source/gameengine/Ketsji/KX_BlenderMaterial.cpp
@@ -19,12 +19,13 @@
#include "MT_Vector4.h"
#include "MT_Matrix4x4.h"
-#include "RAS_BucketManager.h"
#include "RAS_MeshObject.h"
#include "RAS_IRasterizer.h"
#include "RAS_OpenGLRasterizer/RAS_GLExtensionManager.h"
-#include "GPU_draw.h"
+extern "C" {
+#include "BDR_drawmesh.h"
+}
#include "STR_HashedString.h"
@@ -47,6 +48,7 @@ KX_BlenderMaterial::KX_BlenderMaterial(
BL_Material *data,
bool skin,
int lightlayer,
+ void *clientobject,
PyTypeObject *T
)
: PyObjectPlus(T),
@@ -60,7 +62,9 @@ KX_BlenderMaterial::KX_BlenderMaterial(
data->transp,
((data->ras_mode &ALPHA)!=0),
((data->ras_mode &ZSORT)!=0),
- lightlayer
+ lightlayer,
+ ((data->ras_mode &TRIANGLE)!=0),
+ clientobject
),
mMaterial(data),
mShader(0),
@@ -74,10 +78,9 @@ KX_BlenderMaterial::KX_BlenderMaterial(
{
// --------------------------------
// 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 |=RAS_BLENDERMAT;
+ m_flag |=(mMaterial->IdMode>=ONETEX)?RAS_MULTITEX:0;
+ m_flag |=(mMaterial->ras_mode & USE_LIGHT)!=0?RAS_MULTILIGHT:0;
// figure max
int enabled = mMaterial->num_enabled;
@@ -94,7 +97,7 @@ KX_BlenderMaterial::KX_BlenderMaterial(
mMaterial->blend_mode[i]
);
}
- m_multimode += mMaterial->IdMode+ (mMaterial->ras_mode & ~(COLLIDER|USE_LIGHT));
+ m_multimode += mMaterial->IdMode+mMaterial->ras_mode;
}
@@ -201,7 +204,7 @@ void KX_BlenderMaterial::OnExit()
}
if( mMaterial->tface )
- GPU_set_tpage(mMaterial->tface);
+ set_tpage(mMaterial->tface);
}
@@ -253,28 +256,25 @@ void KX_BlenderMaterial::setShaderData( bool enable, RAS_IRasterizer *ras)
void KX_BlenderMaterial::setBlenderShaderData( bool enable, RAS_IRasterizer *ras)
{
if( !enable || !mBlenderShader->Ok() ) {
- ras->SetBlendingMode(TF_SOLID);
-
// frame cleanup.
if(mLastBlenderShader) {
mLastBlenderShader->SetProg(false);
mLastBlenderShader= NULL;
}
- else
- BL_Texture::DisableAllTextures();
+ ras->SetBlendingMode(TF_SOLID);
+ BL_Texture::DisableAllTextures();
return;
}
if(!mBlenderShader->Equals(mLastBlenderShader)) {
ras->SetBlendingMode(mMaterial->transp);
+ BL_Texture::DisableAllTextures();
if(mLastBlenderShader)
mLastBlenderShader->SetProg(false);
- else
- BL_Texture::DisableAllTextures();
- mBlenderShader->SetProg(true, ras->GetTime());
+ mBlenderShader->SetProg(true);
mLastBlenderShader= mBlenderShader;
}
}
@@ -354,22 +354,21 @@ KX_BlenderMaterial::ActivatShaders(
if (GetCachingInfo() != cachingInfo) {
if (!cachingInfo)
- tmp->setShaderData(false, rasty);
+ tmp->setShaderData( false, rasty);
cachingInfo = GetCachingInfo();
if(rasty->GetDrawingMode() == RAS_IRasterizer::KX_TEXTURED)
- tmp->setShaderData(true, rasty);
+ tmp->setShaderData( true, rasty);
else
- tmp->setShaderData(false, rasty);
+ tmp->setShaderData( false, rasty);
if(mMaterial->mode & RAS_IRasterizer::KX_TWOSIDE)
rasty->SetCullFace(false);
else
rasty->SetCullFace(true);
- if (((mMaterial->ras_mode &WIRE)!=0) || (mMaterial->mode & RAS_IRasterizer::KX_LINES) ||
- (rasty->GetDrawingMode() <= RAS_IRasterizer::KX_WIREFRAME))
+ if (((mMaterial->ras_mode &WIRE)!=0) || mMaterial->mode & RAS_IRasterizer::KX_LINES)
{
if((mMaterial->ras_mode &WIRE)!=0)
rasty->SetCullFace(false);
@@ -395,24 +394,31 @@ KX_BlenderMaterial::ActivateBlenderShaders(
mLastShader= NULL;
}
+ // reset...
+ if(tmp->mMaterial->IsShared())
+ cachingInfo =0;
+
if (GetCachingInfo() != cachingInfo) {
if (!cachingInfo)
tmp->setBlenderShaderData(false, rasty);
cachingInfo = GetCachingInfo();
- if(rasty->GetDrawingMode() == RAS_IRasterizer::KX_TEXTURED)
+ if(rasty->GetDrawingMode() == RAS_IRasterizer::KX_TEXTURED) {
tmp->setBlenderShaderData(true, rasty);
- else
+ rasty->EnableTextures(true);
+ }
+ else {
tmp->setBlenderShaderData(false, rasty);
+ rasty->EnableTextures(false);
+ }
if(mMaterial->mode & RAS_IRasterizer::KX_TWOSIDE)
rasty->SetCullFace(false);
else
rasty->SetCullFace(true);
- if (((mMaterial->ras_mode & WIRE)!=0) || (mMaterial->mode & RAS_IRasterizer::KX_LINES) ||
- (rasty->GetDrawingMode() <= RAS_IRasterizer::KX_WIREFRAME))
+ if (((mMaterial->ras_mode &WIRE)!=0) || mMaterial->mode & RAS_IRasterizer::KX_LINES)
{
if((mMaterial->ras_mode &WIRE)!=0)
rasty->SetCullFace(false);
@@ -420,10 +426,10 @@ KX_BlenderMaterial::ActivateBlenderShaders(
}
else
rasty->SetLines(false);
-
- ActivatGLMaterials(rasty);
- mBlenderShader->SetAttribs(rasty, mMaterial);
}
+
+ ActivatGLMaterials(rasty);
+ mBlenderShader->SetAttribs(rasty, mMaterial);
}
void
@@ -460,8 +466,7 @@ KX_BlenderMaterial::ActivateMat(
else
rasty->SetCullFace(true);
- if (((mMaterial->ras_mode &WIRE)!=0) || (mMaterial->mode & RAS_IRasterizer::KX_LINES) ||
- (rasty->GetDrawingMode() <= RAS_IRasterizer::KX_WIREFRAME))
+ if (((mMaterial->ras_mode &WIRE)!=0) || mMaterial->mode & RAS_IRasterizer::KX_LINES)
{
if((mMaterial->ras_mode &WIRE)!=0)
rasty->SetCullFace(false);
@@ -481,10 +486,12 @@ KX_BlenderMaterial::Activate(
TCachingInfo& cachingInfo
)const
{
- if(GLEW_ARB_shader_objects && (mShader && mShader->Ok())) {
- if((mPass++) < mShader->getNumPass() ) {
+ bool dopass = false;
+ if( GLEW_ARB_shader_objects && ( mShader && mShader->Ok() ) ) {
+ if( (mPass++) < mShader->getNumPass() ) {
ActivatShaders(rasty, cachingInfo);
- return true;
+ dopass = true;
+ return dopass;
}
else {
if(mShader == mLastShader) {
@@ -492,29 +499,36 @@ KX_BlenderMaterial::Activate(
mLastShader = NULL;
}
mPass = 0;
- return false;
+ dopass = false;
+ return dopass;
}
}
- else if( GLEW_ARB_shader_objects && (mBlenderShader && mBlenderShader->Ok() ) ) {
- if(mPass++ == 0) {
+ else if( GLEW_ARB_shader_objects && ( mBlenderShader && mBlenderShader->Ok() ) ) {
+ if( (mPass++) == 0 ) {
ActivateBlenderShaders(rasty, cachingInfo);
- return true;
+ dopass = true;
+ return dopass;
}
else {
mPass = 0;
- return false;
+ dopass = false;
+ return dopass;
}
}
else {
- if(mPass++ == 0) {
- ActivateMat(rasty, cachingInfo);
- return true;
- }
- else {
- mPass = 0;
- return false;
+ switch (mPass++)
+ {
+ case 0:
+ ActivateMat(rasty, cachingInfo);
+ dopass = true;
+ break;
+ default:
+ mPass = 0;
+ dopass = false;
+ break;
}
}
+ return dopass;
}
bool KX_BlenderMaterial::UsesLighting(RAS_IRasterizer *rasty) const
@@ -522,15 +536,14 @@ bool KX_BlenderMaterial::UsesLighting(RAS_IRasterizer *rasty) const
if(!RAS_IPolyMaterial::UsesLighting(rasty))
return false;
- if(mShader && mShader->Ok())
- return true;
+ if(mShader && mShader->Ok());
else if(mBlenderShader && mBlenderShader->Ok())
return false;
- else
- return true;
+
+ return true;
}
-void KX_BlenderMaterial::ActivateMeshSlot(const RAS_MeshSlot & ms, RAS_IRasterizer* rasty) const
+void KX_BlenderMaterial::ActivateMeshSlot(const KX_MeshSlot & ms, RAS_IRasterizer* rasty) const
{
if(mShader && GLEW_ARB_shader_objects) {
mShader->Update(ms, rasty);
@@ -541,7 +554,7 @@ void KX_BlenderMaterial::ActivateMeshSlot(const RAS_MeshSlot & ms, RAS_IRasteriz
mBlenderShader->Update(ms, rasty);
/* we do blend modes here, because they can change per object
- * with the same material due to obcolor/obalpha */
+ * with the same material due to obcolor */
blendmode = mBlenderShader->GetBlendMode();
if((blendmode == TF_SOLID || blendmode == TF_ALPHA) && mMaterial->transp != TF_SOLID)
blendmode = mMaterial->transp;
@@ -620,7 +633,11 @@ void KX_BlenderMaterial::ActivateTexGen(RAS_IRasterizer *ras) const
else
ras->SetTexCoord(RAS_IRasterizer::RAS_TEXCO_DISABLE, i);
}
+
+ ras->EnableTextures(true);
}
+ else
+ ras->EnableTextures(false);
}
void KX_BlenderMaterial::setTexMatrixData(int i)
@@ -695,7 +712,8 @@ void KX_BlenderMaterial::setObjectMatrixData(int i, RAS_IRasterizer *ras)
glEnable(GL_TEXTURE_GEN_T);
glEnable(GL_TEXTURE_GEN_R);
- const MT_Matrix4x4& mvmat = ras->GetViewMatrix();
+ MT_Matrix4x4 mvmat;
+ ras->GetViewMatrix(mvmat);
glMatrixMode(GL_TEXTURE);
glLoadIdentity();
@@ -817,9 +835,7 @@ KX_PYMETHODDEF_DOC( KX_BlenderMaterial, getShader , "getShader()")
}
if(mShader && !mShader->GetError()) {
- m_flag &= ~RAS_BLENDERGLSL;
mMaterial->SetSharedMaterial(true);
- mScene->GetBucketManager()->ReleaseDisplayLists(this);
Py_INCREF(mShader);
return mShader;
}else
@@ -854,6 +870,8 @@ void KX_BlenderMaterial::SetBlenderGLSLShader(void)
delete mBlenderShader;
mBlenderShader = 0;
}
+ else
+ m_flag |= RAS_BLENDERGLSL;
}
KX_PYMETHODDEF_DOC( KX_BlenderMaterial, getMaterialIndex, "getMaterialIndex()")
diff --git a/source/gameengine/Ketsji/KX_BlenderMaterial.h b/source/gameengine/Ketsji/KX_BlenderMaterial.h
index 6e5db1b56c1..0d7657b8cdb 100644
--- a/source/gameengine/Ketsji/KX_BlenderMaterial.h
+++ b/source/gameengine/Ketsji/KX_BlenderMaterial.h
@@ -28,6 +28,7 @@ public:
BL_Material* mat,
bool skin,
int lightlayer,
+ void* clientobject,
PyTypeObject* T=&Type
);
@@ -46,7 +47,7 @@ public:
virtual
void ActivateMeshSlot(
- const RAS_MeshSlot & ms,
+ const KX_MeshSlot & ms,
RAS_IRasterizer* rasty
) const;
@@ -67,12 +68,6 @@ public:
MTFace* GetMTFace(void) const;
unsigned int* GetMCol(void) 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;
- }
// for ipos
void UpdateIPO(
diff --git a/source/gameengine/Ketsji/KX_BulletPhysicsController.cpp b/source/gameengine/Ketsji/KX_BulletPhysicsController.cpp
index 3a20bbfbb11..539eaec4a7b 100644
--- a/source/gameengine/Ketsji/KX_BulletPhysicsController.cpp
+++ b/source/gameengine/Ketsji/KX_BulletPhysicsController.cpp
@@ -14,7 +14,6 @@
#include "PHY_IPhysicsEnvironment.h"
#include "CcdPhysicsEnvironment.h"
-#include "BulletSoftBody/btSoftBody.h"
KX_BulletPhysicsController::KX_BulletPhysicsController (const CcdConstructionInfo& ci, bool dyna)
@@ -115,7 +114,7 @@ MT_Vector3 KX_BulletPhysicsController::GetAngularVelocity()
MT_Vector3 KX_BulletPhysicsController::GetVelocity(const MT_Point3& pos)
{
float linVel[3];
- CcdPhysicsController::GetVelocity(pos[0], pos[1], pos[2], linVel[0],linVel[1],linVel[2]);
+ CcdPhysicsController::GetLinearVelocity(linVel[0],linVel[1],linVel[2]);
return MT_Vector3(linVel[0],linVel[1],linVel[2]);
}
@@ -149,23 +148,13 @@ void KX_BulletPhysicsController::setScaling(const MT_Vector3& scaling)
}
MT_Scalar KX_BulletPhysicsController::GetMass()
{
- if (GetSoftBody())
- return GetSoftBody()->getTotalMass();
-
- MT_Scalar invmass = 0.f;
- if (GetRigidBody())
- invmass = GetRigidBody()->getInvMass();
+
+ MT_Scalar invmass = GetRigidBody()->getInvMass();
if (invmass)
return 1.f/invmass;
return 0.f;
}
-
-MT_Scalar KX_BulletPhysicsController::GetRadius()
-{
- return MT_Scalar(CcdPhysicsController::GetRadius());
-}
-
MT_Vector3 KX_BulletPhysicsController::getReactionForce()
{
assert(0);
@@ -178,15 +167,14 @@ void KX_BulletPhysicsController::setRigidBody(bool rigid)
void KX_BulletPhysicsController::SuspendDynamics(bool ghost)
{
btRigidBody *body = GetRigidBody();
- if (body && body->getActivationState() != DISABLE_SIMULATION)
+ if (body->getActivationState() != DISABLE_SIMULATION)
{
btBroadphaseProxy* handle = body->getBroadphaseHandle();
m_savedCollisionFlags = body->getCollisionFlags();
m_savedMass = GetMass();
m_savedCollisionFilterGroup = handle->m_collisionFilterGroup;
m_savedCollisionFilterMask = handle->m_collisionFilterMask;
- m_savedActivationState = body->getActivationState();
- body->forceActivationState(DISABLE_SIMULATION);
+ body->setActivationState(DISABLE_SIMULATION);
GetPhysicsEnvironment()->updateCcdPhysicsController(this,
0.0,
btCollisionObject::CF_STATIC_OBJECT|((ghost)?btCollisionObject::CF_NO_CONTACT_RESPONSE:(m_savedCollisionFlags&btCollisionObject::CF_NO_CONTACT_RESPONSE)),
@@ -198,14 +186,14 @@ void KX_BulletPhysicsController::SuspendDynamics(bool ghost)
void KX_BulletPhysicsController::RestoreDynamics()
{
btRigidBody *body = GetRigidBody();
- if (body && body->getActivationState() == DISABLE_SIMULATION)
+ if (body->getActivationState() == DISABLE_SIMULATION)
{
GetPhysicsEnvironment()->updateCcdPhysicsController(this,
m_savedMass,
m_savedCollisionFlags,
m_savedCollisionFilterGroup,
m_savedCollisionFilterMask);
- GetRigidBody()->forceActivationState(m_savedActivationState);
+ GetRigidBody()->forceActivationState(ACTIVE_TAG);
}
}
@@ -218,9 +206,6 @@ SG_Controller* KX_BulletPhysicsController::GetReplica(class SG_Node* destnode)
//parentcontroller is here be able to avoid collisions between parent/child
PHY_IPhysicsController* parentctrl = NULL;
- KX_BulletPhysicsController* parentKxCtrl = NULL;
- CcdPhysicsController* ccdParent = NULL;
-
if (destnode != destnode->GetRootSGParent())
{
@@ -240,15 +225,12 @@ SG_Controller* KX_BulletPhysicsController::GetReplica(class SG_Node* destnode)
KX_GameObject *clientgameobj = static_cast<KX_GameObject*>( (*childit)->GetSGClientObject());
if (clientgameobj)
{
- parentKxCtrl = (KX_BulletPhysicsController*)clientgameobj->GetPhysicsController();
- parentctrl = parentKxCtrl;
- ccdParent = parentKxCtrl;
+ parentctrl = (KX_BulletPhysicsController*)clientgameobj->GetPhysicsController();
}
}
}
}
- physicsreplica->setParentCtrl(ccdParent);
physicsreplica->PostProcessReplica(motionstate,parentctrl);
physicsreplica->m_userdata = (PHY_IPhysicsController*)physicsreplica;
return physicsreplica;
@@ -259,22 +241,18 @@ SG_Controller* KX_BulletPhysicsController::GetReplica(class SG_Node* destnode)
void KX_BulletPhysicsController::SetSumoTransform(bool nondynaonly)
{
- if (GetRigidBody())
- GetRigidBody()->activate(true);
+ GetRigidBody()->activate(true);
if (!m_bDyna)
{
- GetCollisionObject()->setCollisionFlags(GetRigidBody()->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT);
+ GetRigidBody()->setCollisionFlags(GetRigidBody()->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT);
} else
{
if (!nondynaonly)
{
btTransform worldTrans;
- if (GetRigidBody())
- {
- GetRigidBody()->getMotionState()->getWorldTransform(worldTrans);
- GetRigidBody()->setCenterOfMassTransform(worldTrans);
- }
+ GetRigidBody()->getMotionState()->getWorldTransform(worldTrans);
+ GetRigidBody()->setCenterOfMassTransform(worldTrans);
/*
scaling?
diff --git a/source/gameengine/Ketsji/KX_BulletPhysicsController.h b/source/gameengine/Ketsji/KX_BulletPhysicsController.h
index d5fca4ec6d3..2efe0474b30 100644
--- a/source/gameengine/Ketsji/KX_BulletPhysicsController.h
+++ b/source/gameengine/Ketsji/KX_BulletPhysicsController.h
@@ -9,7 +9,6 @@ class KX_BulletPhysicsController : public KX_IPhysicsController ,public CcdPhysi
{
private:
int m_savedCollisionFlags;
- int m_savedActivationState;
short int m_savedCollisionFilterGroup;
short int m_savedCollisionFilterMask;
MT_Scalar m_savedMass;
@@ -50,7 +49,9 @@ public:
virtual SG_Controller* GetReplica(class SG_Node* destnode);
- virtual MT_Scalar GetRadius();
+ void SetDyna(bool isDynamic) {
+ m_bDyna = isDynamic;
+ }
virtual void SetSumoTransform(bool nondynaonly);
diff --git a/source/gameengine/Ketsji/KX_Camera.cpp b/source/gameengine/Ketsji/KX_Camera.cpp
index fb91c793765..3830d422138 100644
--- a/source/gameengine/Ketsji/KX_Camera.cpp
+++ b/source/gameengine/Ketsji/KX_Camera.cpp
@@ -259,75 +259,10 @@ 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();
-
- // 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.,0.,0.);// center of far cliping plane in camera coordinate
- MT_Scalar F=1.0, 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., 1., 1., 1.);
- 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.25;
- // the extreme near point is the opposite point on the near clipping plane
- nfar.setValue(-nfar[0], -nfar[1], -1., 1.);
- nfar = clip_camcs_matrix*nfar;
- nearpoint.setValue(nfar[0]/nfar[3], nfar[1]/nfar[3], nfar[2]/nfar[3]);
- 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.0*(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);
-
-#if 0
// The most extreme points on the near and far plane. (normalized device coords)
MT_Vector4 hnear(1., 1., 0., 1.), hfar(1., 1., 1., 1.);
+ MT_Matrix4x4 clip_camcs_matrix = m_projection_matrix;
+ clip_camcs_matrix.invert();
// Transform to hom camera local space
hnear = clip_camcs_matrix*hnear;
@@ -338,12 +273,10 @@ void KX_Camera::ExtractFrustumSphere()
MT_Point3 farpoint(hfar[0]/hfar[3], hfar[1]/hfar[3], hfar[2]/hfar[3]);
// Compute center
- // don't use camera data in case the user specifies the matrix directly
m_frustum_center = MT_Point3(0., 0.,
- (nearpoint.dot(nearpoint) - farpoint.dot(farpoint))/(2.0*(nearpoint[2]-farpoint[2] /*m_camdata.m_clipend - m_camdata.m_clipstart*/)));
+ (nearpoint.dot(nearpoint) - farpoint.dot(farpoint))/(2.0*(m_camdata.m_clipend - m_camdata.m_clipstart)));
m_frustum_radius = m_frustum_center.distance(farpoint);
-#endif
-
+
// Transform to world space.
m_frustum_center = GetCameraToWorld()(m_frustum_center);
m_frustum_radius /= fabs(NodeGetWorldScaling()[NodeGetWorldScaling().closestAxis()]);
@@ -860,7 +793,7 @@ KX_PYMETHODDEF_DOC(KX_Camera, setOnTop,
{
class KX_Scene* scene;
- scene = KX_GetActiveScene();
+ scene = PHY_GetActiveScene();
MT_assert(scene);
scene->SetCameraOnTop(this);
Py_Return;
diff --git a/source/gameengine/Ketsji/KX_CameraActuator.cpp b/source/gameengine/Ketsji/KX_CameraActuator.cpp
index 4d24e83843e..0a97b6f0a2f 100644
--- a/source/gameengine/Ketsji/KX_CameraActuator.cpp
+++ b/source/gameengine/Ketsji/KX_CameraActuator.cpp
@@ -35,8 +35,6 @@
#include <math.h>
#include "KX_GameObject.h"
-#include "PyObjectPlus.h"
-
STR_String KX_CameraActuator::X_AXIS_STRING = "x";
STR_String KX_CameraActuator::Y_AXIS_STRING = "y";
@@ -397,16 +395,16 @@ PyParentObject KX_CameraActuator::Parents[] = {
};
PyMethodDef KX_CameraActuator::Methods[] = {
- {"setObject",(PyCFunction) KX_CameraActuator::sPySetObject, METH_O, (PY_METHODCHAR)SetObject_doc},
- {"getObject",(PyCFunction) KX_CameraActuator::sPyGetObject, METH_VARARGS, (PY_METHODCHAR)GetObject_doc},
- {"setMin" ,(PyCFunction) KX_CameraActuator::sPySetMin, METH_VARARGS, (PY_METHODCHAR)SetMin_doc},
- {"getMin" ,(PyCFunction) KX_CameraActuator::sPyGetMin, METH_NOARGS, (PY_METHODCHAR)GetMin_doc},
- {"setMax" ,(PyCFunction) KX_CameraActuator::sPySetMax, METH_VARARGS, (PY_METHODCHAR)SetMax_doc},
- {"getMax" ,(PyCFunction) KX_CameraActuator::sPyGetMax, METH_NOARGS, (PY_METHODCHAR)GetMax_doc},
- {"setHeight",(PyCFunction) KX_CameraActuator::sPySetHeight, METH_VARARGS, (PY_METHODCHAR)SetHeight_doc},
- {"getHeight",(PyCFunction) KX_CameraActuator::sPyGetHeight, METH_NOARGS, (PY_METHODCHAR)GetHeight_doc},
- {"setXY" ,(PyCFunction) KX_CameraActuator::sPySetXY, METH_VARARGS, (PY_METHODCHAR)SetXY_doc},
- {"getXY" ,(PyCFunction) KX_CameraActuator::sPyGetXY, METH_VARARGS, (PY_METHODCHAR)GetXY_doc},
+ {"setObject",(PyCFunction) KX_CameraActuator::sPySetObject, METH_VARARGS, SetObject_doc},
+ {"getObject",(PyCFunction) KX_CameraActuator::sPyGetObject, METH_NOARGS, GetObject_doc},
+ {"setMin" ,(PyCFunction) KX_CameraActuator::sPySetMin, METH_VARARGS, SetMin_doc},
+ {"getMin" ,(PyCFunction) KX_CameraActuator::sPyGetMin, METH_NOARGS, GetMin_doc},
+ {"setMax" ,(PyCFunction) KX_CameraActuator::sPySetMax, METH_VARARGS, SetMax_doc},
+ {"getMax" ,(PyCFunction) KX_CameraActuator::sPyGetMax, METH_NOARGS, GetMax_doc},
+ {"setHeight",(PyCFunction) KX_CameraActuator::sPySetHeight, METH_VARARGS, SetHeight_doc},
+ {"getHeight",(PyCFunction) KX_CameraActuator::sPyGetHeight, METH_NOARGS, GetHeight_doc},
+ {"setXY" ,(PyCFunction) KX_CameraActuator::sPySetXY, METH_VARARGS, SetXY_doc},
+ {"getXY" ,(PyCFunction) KX_CameraActuator::sPyGetXY, METH_VARARGS, GetXY_doc},
{NULL,NULL,NULL,NULL} //Sentinel
};
@@ -414,48 +412,55 @@ PyObject* KX_CameraActuator::_getattr(const STR_String& attr) {
_getattr_up(SCA_IActuator);
}
/* get obj ---------------------------------------------------------- */
-const char KX_CameraActuator::GetObject_doc[] =
-"getObject(name_only = 1)\n"
-"name_only - optional arg, when true will return the KX_GameObject rather then its name\n"
+char KX_CameraActuator::GetObject_doc[] =
+"getObject\n"
"\tReturns the object this sensor reacts to.\n";
-PyObject* KX_CameraActuator::PyGetObject(PyObject* self, PyObject* args)
+PyObject* KX_CameraActuator::PyGetObject(PyObject* self,
+ PyObject* args,
+ PyObject* kwds)
{
- int ret_name_only = 1;
- if (!PyArg_ParseTuple(args, "|i", &ret_name_only))
- return NULL;
-
- if (!m_ob)
- Py_RETURN_NONE;
-
- if (ret_name_only)
- return PyString_FromString(m_ob->GetName());
- else
- return m_ob->AddRef();
+ return PyString_FromString(m_ob->GetName());
}
/* set obj ---------------------------------------------------------- */
-const char KX_CameraActuator::SetObject_doc[] =
-"setObject(object)\n"
-"\t- object: KX_GameObject, string or None\n"
+char KX_CameraActuator::SetObject_doc[] =
+"setObject\n"
"\tSets the object this sensor reacts to.\n";
-PyObject* KX_CameraActuator::PySetObject(PyObject* self, PyObject* value)
+PyObject* KX_CameraActuator::PySetObject(PyObject* self,
+ PyObject* args,
+ PyObject* kwds)
{
- KX_GameObject *gameobj;
-
- if (!ConvertPythonToGameObject(value, &gameobj, true))
- return NULL; // ConvertPythonToGameObject sets the error
+
+ PyObject* gameobj;
+ if (PyArg_ParseTuple(args, "O!", &KX_GameObject::Type, &gameobj))
+ {
+ if (m_ob)
+ m_ob->UnregisterActuator(this);
+ m_ob = (SCA_IObject*)gameobj;
+ if (m_ob)
+ m_ob->RegisterActuator(this);
+ Py_Return;
+ }
+ PyErr_Clear();
- if (m_ob != NULL)
- m_ob->UnregisterActuator(this);
-
- m_ob = (SCA_IObject*)gameobj;
- if (m_ob)
- m_ob->RegisterActuator(this);
+ char* objectname;
+ if (PyArg_ParseTuple(args, "s", &objectname))
+ {
+ SCA_IObject *object = (SCA_IObject*)SCA_ILogicBrick::m_sCurrentLogicManager->GetGameObjectByName(STR_String(objectname));
+ if(object)
+ {
+ if (m_ob != NULL)
+ m_ob->UnregisterActuator(this);
+ m_ob = object;
+ m_ob->RegisterActuator(this);
+ Py_Return;
+ }
+ }
- Py_RETURN_NONE;
+ return NULL;
}
/* get min ---------------------------------------------------------- */
-const char KX_CameraActuator::GetMin_doc[] =
+char KX_CameraActuator::GetMin_doc[] =
"getMin\n"
"\tReturns the minimum value set in the Min: field.\n";
PyObject* KX_CameraActuator::PyGetMin(PyObject* self,
@@ -465,7 +470,7 @@ PyObject* KX_CameraActuator::PyGetMin(PyObject* self,
return PyFloat_FromDouble(m_minHeight);
}
/* set min ---------------------------------------------------------- */
-const char KX_CameraActuator::SetMin_doc[] =
+char KX_CameraActuator::SetMin_doc[] =
"setMin\n"
"\tSets the minimum value.\n";
PyObject* KX_CameraActuator::PySetMin(PyObject* self,
@@ -481,7 +486,7 @@ PyObject* KX_CameraActuator::PySetMin(PyObject* self,
return NULL;
}
/* get min ---------------------------------------------------------- */
-const char KX_CameraActuator::GetMax_doc[] =
+char KX_CameraActuator::GetMax_doc[] =
"getMax\n"
"\tReturns the maximum value set in the Max: field.\n";
PyObject* KX_CameraActuator::PyGetMax(PyObject* self,
@@ -491,7 +496,7 @@ PyObject* KX_CameraActuator::PyGetMax(PyObject* self,
return PyFloat_FromDouble(m_maxHeight);
}
/* set min ---------------------------------------------------------- */
-const char KX_CameraActuator::SetMax_doc[] =
+char KX_CameraActuator::SetMax_doc[] =
"setMax\n"
"\tSets the maximum value.\n";
PyObject* KX_CameraActuator::PySetMax(PyObject* self,
@@ -507,7 +512,7 @@ PyObject* KX_CameraActuator::PySetMax(PyObject* self,
return NULL;
}
/* get height ---------------------------------------------------------- */
-const char KX_CameraActuator::GetHeight_doc[] =
+char KX_CameraActuator::GetHeight_doc[] =
"getHeight\n"
"\tReturns the height value set in the height: field.\n";
PyObject* KX_CameraActuator::PyGetHeight(PyObject* self,
@@ -517,7 +522,7 @@ PyObject* KX_CameraActuator::PyGetHeight(PyObject* self,
return PyFloat_FromDouble(m_height);
}
/* set height ---------------------------------------------------------- */
-const char KX_CameraActuator::SetHeight_doc[] =
+char KX_CameraActuator::SetHeight_doc[] =
"setHeight\n"
"\tSets the height value.\n";
PyObject* KX_CameraActuator::PySetHeight(PyObject* self,
@@ -533,7 +538,7 @@ PyObject* KX_CameraActuator::PySetHeight(PyObject* self,
return NULL;
}
/* set XY ---------------------------------------------------------- */
-const char KX_CameraActuator::SetXY_doc[] =
+char KX_CameraActuator::SetXY_doc[] =
"setXY\n"
"\tSets axis the camera tries to get behind.\n"
"\t1=x, 0=y\n";
@@ -551,7 +556,7 @@ PyObject* KX_CameraActuator::PySetXY(PyObject* self,
}
/* get XY -------------------------------------------------------------*/
-const char KX_CameraActuator::GetXY_doc[] =
+char KX_CameraActuator::GetXY_doc[] =
"getXY\n"
"\tGets the axis the camera tries to get behind.\n"
"\tTrue = X, False = Y\n";
diff --git a/source/gameengine/Ketsji/KX_CameraActuator.h b/source/gameengine/Ketsji/KX_CameraActuator.h
index d53d12b3b82..488b36922b0 100644
--- a/source/gameengine/Ketsji/KX_CameraActuator.h
+++ b/source/gameengine/Ketsji/KX_CameraActuator.h
@@ -123,9 +123,9 @@ private :
virtual PyObject* _getattr(const STR_String& attr);
/* set object to look at */
- KX_PYMETHOD_DOC_O(KX_CameraActuator,SetObject);
+ KX_PYMETHOD_DOC(KX_CameraActuator,SetObject);
/* get current object */
- KX_PYMETHOD_DOC_VARARGS(KX_CameraActuator,GetObject);
+ KX_PYMETHOD_DOC(KX_CameraActuator,GetObject);
KX_PYMETHOD_DOC(KX_CameraActuator,SetMin);
KX_PYMETHOD_DOC(KX_CameraActuator,GetMin);
KX_PYMETHOD_DOC(KX_CameraActuator,SetMax);
diff --git a/source/gameengine/Ketsji/KX_ConstraintActuator.cpp b/source/gameengine/Ketsji/KX_ConstraintActuator.cpp
index 76357e9c58f..2401d69d3a3 100644
--- a/source/gameengine/Ketsji/KX_ConstraintActuator.cpp
+++ b/source/gameengine/Ketsji/KX_ConstraintActuator.cpp
@@ -109,11 +109,16 @@ 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 * const data)
+bool KX_ConstraintActuator::RayHit(KX_ClientObjectInfo* client, MT_Point3& hit_point, MT_Vector3& hit_normal, void * const data)
{
- m_hitObject = client->m_gameobject;
+ KX_GameObject* hitKXObj = client->m_gameobject;
+ if (client->m_type > KX_ClientObjectInfo::ACTOR)
+ {
+ // false hit
+ return false;
+ }
bool bFound = false;
if (m_property[0] == 0)
@@ -131,29 +136,11 @@ bool KX_ConstraintActuator::RayHit(KX_ClientObjectInfo* client, KX_RayCast* resu
}
else
{
- bFound = m_hitObject->GetProperty(m_property) != NULL;
+ bFound = hitKXObj->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)
-{
- 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;
+ return bFound;
}
bool KX_ConstraintActuator::Update(double curtime, bool frame)
@@ -172,15 +159,13 @@ bool KX_ConstraintActuator::Update(double curtime, bool frame)
KX_GameObject *obj = (KX_GameObject*) GetParent();
MT_Point3 position = obj->NodeGetWorldPosition();
MT_Point3 newposition;
- MT_Vector3 normal, direction, refDirection;
+ MT_Vector3 direction, refDirection;
MT_Matrix3x3 rotation = obj->NodeGetWorldOrientation();
MT_Scalar filter, newdistance, cosangle;
int axis, sign;
if (m_posDampTime) {
filter = m_posDampTime/(1.0+m_posDampTime);
- } else {
- filter = 0.0;
}
switch (m_locrot) {
case KX_ACT_CONSTRAINT_ORIX:
@@ -240,8 +225,12 @@ bool KX_ConstraintActuator::Update(double curtime, bool frame)
} else {
refDirection = m_refDirection;
}
- // apply damping on the direction
- direction = filter*direction + (1.0-filter)*refDirection;
+ if (m_posDampTime) {
+ // apply damping on the direction
+ direction = filter*direction + (1.0-filter)*refDirection;
+ } else {
+ direction = refDirection;
+ }
obj->AlignAxisToVect(direction, axis);
result = true;
goto CHECK_TIME;
@@ -253,76 +242,53 @@ bool KX_ConstraintActuator::Update(double curtime, bool frame)
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];
+ direction[0] = rotation[0][0];
+ direction[1] = rotation[1][0];
+ direction[2] = rotation[2][0];
axis = 0; // axis according to KX_GameObject::AlignAxisToVect()
- sign = 0; // X axis will be parrallel to direction of ray
+ sign = 1; // X axis will be anti parrallel to normal
break;
case KX_ACT_CONSTRAINT_DIRPY:
- normal[0] = rotation[0][1];
- normal[1] = rotation[1][1];
- normal[2] = rotation[2][1];
+ direction[0] = rotation[0][1];
+ direction[1] = rotation[1][1];
+ direction[2] = rotation[2][1];
axis = 1;
- sign = 0;
+ sign = 1;
break;
case KX_ACT_CONSTRAINT_DIRPZ:
- normal[0] = rotation[0][2];
- normal[1] = rotation[1][2];
- normal[2] = rotation[2][2];
+ direction[0] = rotation[0][2];
+ direction[1] = rotation[1][2];
+ direction[2] = rotation[2][2];
axis = 2;
- sign = 0;
+ sign = 1;
break;
case KX_ACT_CONSTRAINT_DIRNX:
- normal[0] = -rotation[0][0];
- normal[1] = -rotation[1][0];
- normal[2] = -rotation[2][0];
+ direction[0] = -rotation[0][0];
+ direction[1] = -rotation[1][0];
+ direction[2] = -rotation[2][0];
axis = 0;
- sign = 1;
+ sign = 0;
break;
case KX_ACT_CONSTRAINT_DIRNY:
- normal[0] = -rotation[0][1];
- normal[1] = -rotation[1][1];
- normal[2] = -rotation[2][1];
+ direction[0] = -rotation[0][1];
+ direction[1] = -rotation[1][1];
+ direction[2] = -rotation[2][1];
axis = 1;
- sign = 1;
+ sign = 0;
break;
case KX_ACT_CONSTRAINT_DIRNZ:
- normal[0] = -rotation[0][2];
- normal[1] = -rotation[1][2];
- normal[2] = -rotation[2][2];
+ direction[0] = -rotation[0][2];
+ direction[1] = -rotation[1][2];
+ direction[2] = -rotation[2][2];
axis = 2;
- sign = 1;
+ sign = 0;
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.0,0.0,0.0);
- break;
- case KX_ACT_CONSTRAINT_DIRPY:
- direction = MT_Vector3(0.0,1.0,0.0);
- break;
- case KX_ACT_CONSTRAINT_DIRPZ:
- direction = MT_Vector3(0.0,0.0,1.0);
- break;
- case KX_ACT_CONSTRAINT_DIRNX:
- direction = MT_Vector3(-1.0,0.0,0.0);
- break;
- case KX_ACT_CONSTRAINT_DIRNY:
- direction = MT_Vector3(0.0,-1.0,0.0);
- break;
- case KX_ACT_CONSTRAINT_DIRNZ:
- direction = MT_Vector3(0.0,0.0,-1.0);
- break;
- }
- }
+ direction.normalize();
{
MT_Point3 topoint = position + (m_maximumBound) * direction;
+ MT_Point3 resultpoint;
+ MT_Vector3 resultnormal;
PHY_IPhysicsEnvironment* pe = obj->GetPhysicsEnvironment();
KX_IPhysicsController *spc = obj->GetPhysicsController();
@@ -338,10 +304,9 @@ bool KX_ConstraintActuator::Update(double curtime, bool frame)
parent->Release();
}
}
- KX_RayCast::Callback<KX_ConstraintActuator> callback(this,spc);
- result = KX_RayCast::RayTest(pe, position, topoint, callback);
+ result = KX_RayCast::RayTest(spc, pe, position, topoint, resultpoint, resultnormal, KX_RayCast::Callback<KX_ConstraintActuator>(this));
+
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
@@ -349,40 +314,29 @@ bool KX_ConstraintActuator::Update(double curtime, bool frame)
goto CHECK_TIME;
}
if (m_option & KX_ACT_CONSTRAINT_NORMAL) {
- MT_Scalar rotFilter;
+ // the new orientation must be so that the axis is parallel to normal
+ if (sign)
+ resultnormal = -resultnormal;
// apply damping on the direction
if (m_rotDampTime) {
- rotFilter = m_rotDampTime/(1.0+m_rotDampTime);
- } else {
- rotFilter = filter;
- }
- newnormal = rotFilter*normal - (1.0-rotFilter)*newnormal;
- obj->AlignAxisToVect((sign)?-newnormal:newnormal, axis);
- if (m_option & KX_ACT_CONSTRAINT_LOCAL) {
- direction = newnormal;
- direction.normalize();
+ MT_Scalar rotFilter = 1.0/(1.0+m_rotDampTime);
+ resultnormal = (-m_rotDampTime*rotFilter)*direction + rotFilter*resultnormal;
+ } else if (m_posDampTime) {
+ resultnormal = -filter*direction + (1.0-filter)*resultnormal;
}
+ obj->AlignAxisToVect(resultnormal, axis);
+ direction = -resultnormal;
}
if (m_option & KX_ACT_CONSTRAINT_DISTANCE) {
if (m_posDampTime) {
- newdistance = filter*(position-callback.m_hitPoint).length()+(1.0-filter)*m_minimumBound;
+ newdistance = filter*(position-resultpoint).length()+(1.0-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->IsDyna()) {
- 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();
+ newdistance = (position-resultpoint).length();
}
- newposition = callback.m_hitPoint-newdistance*direction;
+ newposition = resultpoint-newdistance*direction;
} else if (m_option & KX_ACT_CONSTRAINT_PERMANENT) {
// no contact but still keep running
result = true;
@@ -390,114 +344,10 @@ bool KX_ConstraintActuator::Update(double curtime, bool frame)
}
}
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.0,0.0,0.0);
- 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.0,1.0,0.0);
- 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.0,0.0,1.0);
- 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.0,0.0,0.0);
- 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.0,-1.0,0.0);
- 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.0,0.0,-1.0);
- break;
- }
- normal.normalize();
- {
- PHY_IPhysicsEnvironment* pe = obj->GetPhysicsEnvironment();
- KX_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->IsDyna()) {
- // 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> 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.0 - 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_refDirection[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_refDirection[1]>MT_EPSILON)?m_refDirection[1]:m_refDirection[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();
+ newposition = position;
switch (m_locrot) {
case KX_ACT_CONSTRAINT_LOCX:
Clamp(newposition[0], m_minimumBound, m_maximumBound);
@@ -513,8 +363,7 @@ bool KX_ConstraintActuator::Update(double curtime, bool frame)
if (m_posDampTime) {
newposition = filter*position + (1.0-filter)*newposition;
}
- obj->NodeSetLocalPosition(newposition);
- goto CHECK_TIME;
+ break;
}
if (result) {
// set the new position but take into account parent if any
@@ -587,28 +436,28 @@ PyParentObject KX_ConstraintActuator::Parents[] = {
};
PyMethodDef KX_ConstraintActuator::Methods[] = {
- {"setDamp", (PyCFunction) KX_ConstraintActuator::sPySetDamp, METH_VARARGS, (PY_METHODCHAR)SetDamp_doc},
- {"getDamp", (PyCFunction) KX_ConstraintActuator::sPyGetDamp, METH_NOARGS, (PY_METHODCHAR)GetDamp_doc},
- {"setRotDamp", (PyCFunction) KX_ConstraintActuator::sPySetRotDamp, METH_VARARGS, (PY_METHODCHAR)SetRotDamp_doc},
- {"getRotDamp", (PyCFunction) KX_ConstraintActuator::sPyGetRotDamp, METH_NOARGS, (PY_METHODCHAR)GetRotDamp_doc},
- {"setDirection", (PyCFunction) KX_ConstraintActuator::sPySetDirection, METH_VARARGS, (PY_METHODCHAR)SetDirection_doc},
- {"getDirection", (PyCFunction) KX_ConstraintActuator::sPyGetDirection, METH_NOARGS, (PY_METHODCHAR)GetDirection_doc},
- {"setOption", (PyCFunction) KX_ConstraintActuator::sPySetOption, METH_VARARGS, (PY_METHODCHAR)SetOption_doc},
- {"getOption", (PyCFunction) KX_ConstraintActuator::sPyGetOption, METH_NOARGS, (PY_METHODCHAR)GetOption_doc},
- {"setTime", (PyCFunction) KX_ConstraintActuator::sPySetTime, METH_VARARGS, (PY_METHODCHAR)SetTime_doc},
- {"getTime", (PyCFunction) KX_ConstraintActuator::sPyGetTime, METH_NOARGS, (PY_METHODCHAR)GetTime_doc},
- {"setProperty", (PyCFunction) KX_ConstraintActuator::sPySetProperty, METH_VARARGS, (PY_METHODCHAR)SetProperty_doc},
- {"getProperty", (PyCFunction) KX_ConstraintActuator::sPyGetProperty, METH_NOARGS, (PY_METHODCHAR)GetProperty_doc},
- {"setMin", (PyCFunction) KX_ConstraintActuator::sPySetMin, METH_VARARGS, (PY_METHODCHAR)SetMin_doc},
- {"getMin", (PyCFunction) KX_ConstraintActuator::sPyGetMin, METH_NOARGS, (PY_METHODCHAR)GetMin_doc},
- {"setDistance", (PyCFunction) KX_ConstraintActuator::sPySetMin, METH_VARARGS, (PY_METHODCHAR)SetDistance_doc},
- {"getDistance", (PyCFunction) KX_ConstraintActuator::sPyGetMin, METH_NOARGS, (PY_METHODCHAR)GetDistance_doc},
- {"setMax", (PyCFunction) KX_ConstraintActuator::sPySetMax, METH_VARARGS, (PY_METHODCHAR)SetMax_doc},
- {"getMax", (PyCFunction) KX_ConstraintActuator::sPyGetMax, METH_NOARGS, (PY_METHODCHAR)GetMax_doc},
- {"setRayLength", (PyCFunction) KX_ConstraintActuator::sPySetMax, METH_VARARGS, (PY_METHODCHAR)SetRayLength_doc},
- {"getRayLength", (PyCFunction) KX_ConstraintActuator::sPyGetMax, METH_NOARGS, (PY_METHODCHAR)GetRayLength_doc},
- {"setLimit", (PyCFunction) KX_ConstraintActuator::sPySetLimit, METH_VARARGS, (PY_METHODCHAR)SetLimit_doc},
- {"getLimit", (PyCFunction) KX_ConstraintActuator::sPyGetLimit, METH_NOARGS, (PY_METHODCHAR)GetLimit_doc},
+ {"setDamp", (PyCFunction) KX_ConstraintActuator::sPySetDamp, METH_VARARGS, SetDamp_doc},
+ {"getDamp", (PyCFunction) KX_ConstraintActuator::sPyGetDamp, METH_NOARGS, GetDamp_doc},
+ {"setRotDamp", (PyCFunction) KX_ConstraintActuator::sPySetRotDamp, METH_VARARGS, SetRotDamp_doc},
+ {"getRotDamp", (PyCFunction) KX_ConstraintActuator::sPyGetRotDamp, METH_NOARGS, GetRotDamp_doc},
+ {"setDirection", (PyCFunction) KX_ConstraintActuator::sPySetDirection, METH_VARARGS, SetDirection_doc},
+ {"getDirection", (PyCFunction) KX_ConstraintActuator::sPyGetDirection, METH_NOARGS, GetDirection_doc},
+ {"setOption", (PyCFunction) KX_ConstraintActuator::sPySetOption, METH_VARARGS, SetOption_doc},
+ {"getOption", (PyCFunction) KX_ConstraintActuator::sPyGetOption, METH_NOARGS, GetOption_doc},
+ {"setTime", (PyCFunction) KX_ConstraintActuator::sPySetTime, METH_VARARGS, SetTime_doc},
+ {"getTime", (PyCFunction) KX_ConstraintActuator::sPyGetTime, METH_NOARGS, GetTime_doc},
+ {"setProperty", (PyCFunction) KX_ConstraintActuator::sPySetProperty, METH_VARARGS, SetProperty_doc},
+ {"getProperty", (PyCFunction) KX_ConstraintActuator::sPyGetProperty, METH_NOARGS, GetProperty_doc},
+ {"setMin", (PyCFunction) KX_ConstraintActuator::sPySetMin, METH_VARARGS, SetMin_doc},
+ {"getMin", (PyCFunction) KX_ConstraintActuator::sPyGetMin, METH_NOARGS, GetMin_doc},
+ {"setDistance", (PyCFunction) KX_ConstraintActuator::sPySetMin, METH_VARARGS, SetDistance_doc},
+ {"getDistance", (PyCFunction) KX_ConstraintActuator::sPyGetMin, METH_NOARGS, GetDistance_doc},
+ {"setMax", (PyCFunction) KX_ConstraintActuator::sPySetMax, METH_VARARGS, SetMax_doc},
+ {"getMax", (PyCFunction) KX_ConstraintActuator::sPyGetMax, METH_NOARGS, GetMax_doc},
+ {"setRayLength", (PyCFunction) KX_ConstraintActuator::sPySetMax, METH_VARARGS, SetRayLength_doc},
+ {"getRayLength", (PyCFunction) KX_ConstraintActuator::sPyGetMax, METH_NOARGS, GetRayLength_doc},
+ {"setLimit", (PyCFunction) KX_ConstraintActuator::sPySetLimit, METH_VARARGS, SetLimit_doc},
+ {"getLimit", (PyCFunction) KX_ConstraintActuator::sPyGetLimit, METH_NOARGS, GetLimit_doc},
{NULL,NULL} //Sentinel
};
@@ -617,7 +466,7 @@ PyObject* KX_ConstraintActuator::_getattr(const STR_String& attr) {
}
/* 2. setDamp */
-const char KX_ConstraintActuator::SetDamp_doc[] =
+char KX_ConstraintActuator::SetDamp_doc[] =
"setDamp(duration)\n"
"\t- duration: integer\n"
"\tSets the time constant of the orientation and distance constraint.\n"
@@ -627,6 +476,7 @@ PyObject* KX_ConstraintActuator::PySetDamp(PyObject* self,
PyObject* kwds) {
int dampArg;
if(!PyArg_ParseTuple(args, "i", &dampArg)) {
+ PyErr_SetString(PyExc_TypeError, "Invalid arguments");
return NULL;
}
@@ -636,7 +486,7 @@ PyObject* KX_ConstraintActuator::PySetDamp(PyObject* self,
Py_Return;
}
/* 3. getDamp */
-const char KX_ConstraintActuator::GetDamp_doc[] =
+char KX_ConstraintActuator::GetDamp_doc[] =
"getDamp()\n"
"\tReturns the damping parameter.\n";
PyObject* KX_ConstraintActuator::PyGetDamp(PyObject* self){
@@ -644,7 +494,7 @@ PyObject* KX_ConstraintActuator::PyGetDamp(PyObject* self){
}
/* 2. setRotDamp */
-const char KX_ConstraintActuator::SetRotDamp_doc[] =
+char KX_ConstraintActuator::SetRotDamp_doc[] =
"setRotDamp(duration)\n"
"\t- duration: integer\n"
"\tSets the time constant of the orientation constraint.\n"
@@ -654,6 +504,7 @@ PyObject* KX_ConstraintActuator::PySetRotDamp(PyObject* self,
PyObject* kwds) {
int dampArg;
if(!PyArg_ParseTuple(args, "i", &dampArg)) {
+ PyErr_SetString(PyExc_TypeError, "Invalid arguments");
return NULL;
}
@@ -663,7 +514,7 @@ PyObject* KX_ConstraintActuator::PySetRotDamp(PyObject* self,
Py_Return;
}
/* 3. getRotDamp */
-const char KX_ConstraintActuator::GetRotDamp_doc[] =
+char KX_ConstraintActuator::GetRotDamp_doc[] =
"getRotDamp()\n"
"\tReturns the damping time for application of the constraint.\n";
PyObject* KX_ConstraintActuator::PyGetRotDamp(PyObject* self){
@@ -671,7 +522,7 @@ PyObject* KX_ConstraintActuator::PyGetRotDamp(PyObject* self){
}
/* 2. setDirection */
-const char KX_ConstraintActuator::SetDirection_doc[] =
+char KX_ConstraintActuator::SetDirection_doc[] =
"setDirection(vector)\n"
"\t- vector: 3-tuple\n"
"\tSets the reference direction in world coordinate for the orientation constraint.\n";
@@ -683,6 +534,7 @@ PyObject* KX_ConstraintActuator::PySetDirection(PyObject* self,
MT_Vector3 dir;
if(!PyArg_ParseTuple(args, "(fff)", &x, &y, &z)) {
+ PyErr_SetString(PyExc_TypeError, "Invalid arguments");
return NULL;
}
dir[0] = x;
@@ -698,7 +550,7 @@ PyObject* KX_ConstraintActuator::PySetDirection(PyObject* self,
Py_Return;
}
/* 3. getDirection */
-const char KX_ConstraintActuator::GetDirection_doc[] =
+char KX_ConstraintActuator::GetDirection_doc[] =
"getDirection()\n"
"\tReturns the reference direction of the orientation constraint as a 3-tuple.\n";
PyObject* KX_ConstraintActuator::PyGetDirection(PyObject* self){
@@ -711,7 +563,7 @@ PyObject* KX_ConstraintActuator::PyGetDirection(PyObject* self){
}
/* 2. setOption */
-const char KX_ConstraintActuator::SetOption_doc[] =
+char KX_ConstraintActuator::SetOption_doc[] =
"setOption(option)\n"
"\t- option: integer\n"
"\tSets several options of the distance constraint.\n"
@@ -725,6 +577,7 @@ PyObject* KX_ConstraintActuator::PySetOption(PyObject* self,
PyObject* kwds) {
int option;
if(!PyArg_ParseTuple(args, "i", &option)) {
+ PyErr_SetString(PyExc_TypeError, "Invalid arguments");
return NULL;
}
@@ -733,7 +586,7 @@ PyObject* KX_ConstraintActuator::PySetOption(PyObject* self,
Py_Return;
}
/* 3. getOption */
-const char KX_ConstraintActuator::GetOption_doc[] =
+char KX_ConstraintActuator::GetOption_doc[] =
"getOption()\n"
"\tReturns the option parameter.\n";
PyObject* KX_ConstraintActuator::PyGetOption(PyObject* self){
@@ -741,7 +594,7 @@ PyObject* KX_ConstraintActuator::PyGetOption(PyObject* self){
}
/* 2. setTime */
-const char KX_ConstraintActuator::SetTime_doc[] =
+char KX_ConstraintActuator::SetTime_doc[] =
"setTime(duration)\n"
"\t- duration: integer\n"
"\tSets the activation time of the actuator.\n"
@@ -752,6 +605,7 @@ PyObject* KX_ConstraintActuator::PySetTime(PyObject* self,
PyObject* kwds) {
int t;
if(!PyArg_ParseTuple(args, "i", &t)) {
+ PyErr_SetString(PyExc_TypeError, "Invalid arguments");
return NULL;
}
@@ -762,7 +616,7 @@ PyObject* KX_ConstraintActuator::PySetTime(PyObject* self,
Py_Return;
}
/* 3. getTime */
-const char KX_ConstraintActuator::GetTime_doc[] =
+char KX_ConstraintActuator::GetTime_doc[] =
"getTime()\n"
"\tReturns the time parameter.\n";
PyObject* KX_ConstraintActuator::PyGetTime(PyObject* self){
@@ -770,7 +624,7 @@ PyObject* KX_ConstraintActuator::PyGetTime(PyObject* self){
}
/* 2. setProperty */
-const char KX_ConstraintActuator::SetProperty_doc[] =
+char KX_ConstraintActuator::SetProperty_doc[] =
"setProperty(property)\n"
"\t- property: string\n"
"\tSets the name of the property or material for the ray detection of the distance constraint.\n"
@@ -780,6 +634,7 @@ PyObject* KX_ConstraintActuator::PySetProperty(PyObject* self,
PyObject* kwds) {
char *property;
if (!PyArg_ParseTuple(args, "s", &property)) {
+ PyErr_SetString(PyExc_TypeError, "Invalid arguments");
return NULL;
}
if (property == NULL) {
@@ -792,7 +647,7 @@ PyObject* KX_ConstraintActuator::PySetProperty(PyObject* self,
Py_Return;
}
/* 3. getProperty */
-const char KX_ConstraintActuator::GetProperty_doc[] =
+char KX_ConstraintActuator::GetProperty_doc[] =
"getProperty()\n"
"\tReturns the property parameter.\n";
PyObject* KX_ConstraintActuator::PyGetProperty(PyObject* self){
@@ -800,12 +655,12 @@ PyObject* KX_ConstraintActuator::PyGetProperty(PyObject* self){
}
/* 4. setDistance */
-const char KX_ConstraintActuator::SetDistance_doc[] =
+char KX_ConstraintActuator::SetDistance_doc[] =
"setDistance(distance)\n"
"\t- distance: float\n"
"\tSets the target distance in distance constraint\n";
/* 4. setMin */
-const char KX_ConstraintActuator::SetMin_doc[] =
+char KX_ConstraintActuator::SetMin_doc[] =
"setMin(lower_bound)\n"
"\t- lower_bound: float\n"
"\tSets the lower value of the interval to which the value\n"
@@ -815,6 +670,7 @@ PyObject* KX_ConstraintActuator::PySetMin(PyObject* self,
PyObject* kwds) {
float minArg;
if(!PyArg_ParseTuple(args, "f", &minArg)) {
+ PyErr_SetString(PyExc_TypeError, "Invalid arguments");
return NULL;
}
@@ -832,11 +688,11 @@ PyObject* KX_ConstraintActuator::PySetMin(PyObject* self,
Py_Return;
}
/* 5. getDistance */
-const char KX_ConstraintActuator::GetDistance_doc[] =
+char KX_ConstraintActuator::GetDistance_doc[] =
"getDistance()\n"
"\tReturns the distance parameter \n";
/* 5. getMin */
-const char KX_ConstraintActuator::GetMin_doc[] =
+char KX_ConstraintActuator::GetMin_doc[] =
"getMin()\n"
"\tReturns the lower value of the interval to which the value\n"
"\tis clipped.\n";
@@ -845,12 +701,12 @@ PyObject* KX_ConstraintActuator::PyGetMin(PyObject* self) {
}
/* 6. setRayLength */
-const char KX_ConstraintActuator::SetRayLength_doc[] =
+char KX_ConstraintActuator::SetRayLength_doc[] =
"setRayLength(length)\n"
"\t- length: float\n"
"\tSets the maximum ray length of the distance constraint\n";
/* 6. setMax */
-const char KX_ConstraintActuator::SetMax_doc[] =
+char KX_ConstraintActuator::SetMax_doc[] =
"setMax(upper_bound)\n"
"\t- upper_bound: float\n"
"\tSets the upper value of the interval to which the value\n"
@@ -860,6 +716,7 @@ PyObject* KX_ConstraintActuator::PySetMax(PyObject* self,
PyObject* kwds){
float maxArg;
if(!PyArg_ParseTuple(args, "f", &maxArg)) {
+ PyErr_SetString(PyExc_TypeError, "Invalid arguments");
return NULL;
}
@@ -877,11 +734,11 @@ PyObject* KX_ConstraintActuator::PySetMax(PyObject* self,
Py_Return;
}
/* 7. getRayLength */
-const char KX_ConstraintActuator::GetRayLength_doc[] =
+char KX_ConstraintActuator::GetRayLength_doc[] =
"getRayLength()\n"
"\tReturns the length of the ray\n";
/* 7. getMax */
-const char KX_ConstraintActuator::GetMax_doc[] =
+char KX_ConstraintActuator::GetMax_doc[] =
"getMax()\n"
"\tReturns the upper value of the interval to which the value\n"
"\tis clipped.\n";
@@ -892,7 +749,7 @@ PyObject* KX_ConstraintActuator::PyGetMax(PyObject* self) {
/* This setter/getter probably for the constraint type */
/* 8. setLimit */
-const char KX_ConstraintActuator::SetLimit_doc[] =
+char KX_ConstraintActuator::SetLimit_doc[] =
"setLimit(type)\n"
"\t- type: integer\n"
"\t 1 : LocX\n"
@@ -913,6 +770,7 @@ PyObject* KX_ConstraintActuator::PySetLimit(PyObject* self,
PyObject* kwds) {
int locrotArg;
if(!PyArg_ParseTuple(args, "i", &locrotArg)) {
+ PyErr_SetString(PyExc_TypeError, "Invalid arguments");
return NULL;
}
@@ -921,7 +779,7 @@ PyObject* KX_ConstraintActuator::PySetLimit(PyObject* self,
Py_Return;
}
/* 9. getLimit */
-const char KX_ConstraintActuator::GetLimit_doc[] =
+char KX_ConstraintActuator::GetLimit_doc[] =
"getLimit()\n"
"\tReturns the type of constraint.\n";
PyObject* KX_ConstraintActuator::PyGetLimit(PyObject* self) {
diff --git a/source/gameengine/Ketsji/KX_ConstraintActuator.h b/source/gameengine/Ketsji/KX_ConstraintActuator.h
index 28b9b1e6a0b..d9f39124cac 100644
--- a/source/gameengine/Ketsji/KX_ConstraintActuator.h
+++ b/source/gameengine/Ketsji/KX_ConstraintActuator.h
@@ -37,9 +37,6 @@
#include "MT_Vector3.h"
#include "KX_ClientObjectInfo.h"
-class KX_RayCast;
-class KX_GameObject;
-
class KX_ConstraintActuator : public SCA_IActuator
{
Py_Header;
@@ -66,8 +63,6 @@ protected:
int m_option;
// property to check
char m_property[32];
- // hit object
- KX_GameObject* m_hitObject;
/**
* Clamp <var> to <min>, <max>. Borders are included (in as far as
@@ -95,12 +90,6 @@ protected:
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
@@ -108,13 +97,10 @@ protected:
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
+ KX_ACT_CONSTRAINT_DISTANCE = 512
};
bool IsValidMode(KX_CONSTRAINTTYPE m);
- bool RayHit(KX_ClientObjectInfo* client, KX_RayCast* result, void * const data);
- bool NeedRayCast(KX_ClientObjectInfo*);
+ bool RayHit(KX_ClientObjectInfo* client, MT_Point3& hit_point, MT_Vector3& hit_normal, void * const data);
KX_ConstraintActuator(SCA_IObject* gameobj,
int posDamptime,
@@ -158,12 +144,12 @@ protected:
KX_PYMETHOD_DOC_NOARGS(KX_ConstraintActuator,GetProperty);
KX_PYMETHOD_DOC(KX_ConstraintActuator,SetMin);
KX_PYMETHOD_DOC_NOARGS(KX_ConstraintActuator,GetMin);
- static const char SetDistance_doc[];
- static const char GetDistance_doc[];
+ static char SetDistance_doc[];
+ static char GetDistance_doc[];
KX_PYMETHOD_DOC(KX_ConstraintActuator,SetMax);
KX_PYMETHOD_DOC_NOARGS(KX_ConstraintActuator,GetMax);
- static const char SetRayLength_doc[];
- static const char GetRayLength_doc[];
+ static char SetRayLength_doc[];
+ static char GetRayLength_doc[];
KX_PYMETHOD_DOC(KX_ConstraintActuator,SetLimit);
KX_PYMETHOD_DOC_NOARGS(KX_ConstraintActuator,GetLimit);
};
diff --git a/source/gameengine/Ketsji/KX_ConstraintWrapper.cpp b/source/gameengine/Ketsji/KX_ConstraintWrapper.cpp
index c9095ff34f6..987125ca9ba 100644
--- a/source/gameengine/Ketsji/KX_ConstraintWrapper.cpp
+++ b/source/gameengine/Ketsji/KX_ConstraintWrapper.cpp
@@ -27,7 +27,6 @@
* ***** END GPL LICENSE BLOCK *****
*/
#include <Python.h>
-#include "PyObjectPlus.h"
#include "KX_ConstraintWrapper.h"
#include "PHY_IPhysicsEnvironment.h"
@@ -54,7 +53,8 @@ PyObject* KX_ConstraintWrapper::PyTestMethod(PyObject* self,
PyObject* kwds)
{
- Py_RETURN_NONE;
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyObject* KX_ConstraintWrapper::PyGetConstraintId(PyObject* self,
diff --git a/source/gameengine/Ketsji/KX_ConvertPhysicsObject.h b/source/gameengine/Ketsji/KX_ConvertPhysicsObject.h
index 53486cecf73..6653026f28a 100644
--- a/source/gameengine/Ketsji/KX_ConvertPhysicsObject.h
+++ b/source/gameengine/Ketsji/KX_ConvertPhysicsObject.h
@@ -75,7 +75,6 @@ struct KX_CBounds
struct KX_ObjectProperties
{
bool m_dyna;
- bool m_softbody;
double m_radius;
bool m_angular_rigidbody;
bool m_in_active_layer;
@@ -87,47 +86,6 @@ struct KX_ObjectProperties
bool m_disableSleeping;
bool m_hasCompoundChildren;
bool m_isCompoundChild;
-
- /////////////////////////
-
- 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*/
-
- /////////////////////////
-
- double m_margin;
KX_BoundBoxClass m_boundclass;
union {
KX_BoxBounds box;
diff --git a/source/gameengine/Ketsji/KX_ConvertPhysicsObjects.cpp b/source/gameengine/Ketsji/KX_ConvertPhysicsObjects.cpp
index 0e7a6d92ec1..e0cd5a3bc9e 100644
--- a/source/gameengine/Ketsji/KX_ConvertPhysicsObjects.cpp
+++ b/source/gameengine/Ketsji/KX_ConvertPhysicsObjects.cpp
@@ -38,8 +38,6 @@
#include "RAS_MeshObject.h"
#include "KX_Scene.h"
#include "SYS_System.h"
-#include "BL_SkinMeshObject.h"
-#include "BulletSoftBody/btSoftBody.h"
#include "PHY_Pro.h" //todo cleanup
#include "KX_ClientObjectInfo.h"
@@ -78,16 +76,16 @@
struct KX_PhysicsInstance
{
DT_VertexBaseHandle m_vertexbase;
- RAS_DisplayArray* m_darray;
+ int m_vtxarray;
RAS_IPolyMaterial* m_material;
-
- KX_PhysicsInstance(DT_VertexBaseHandle vertex_base, RAS_DisplayArray *darray, RAS_IPolyMaterial* mat)
+
+ KX_PhysicsInstance(DT_VertexBaseHandle vertex_base, int vtxarray, RAS_IPolyMaterial* mat)
: m_vertexbase(vertex_base),
- m_darray(darray),
- m_material(mat)
+ m_vtxarray(vtxarray),
+ m_material(mat)
{
}
-
+
~KX_PhysicsInstance()
{
DT_DeleteVertexBase(m_vertexbase);
@@ -102,11 +100,11 @@ static void BL_RegisterSumoObject(KX_GameObject* gameobj,class SM_Scene* sumoSce
static DT_ShapeHandle CreateShapeFromMesh(RAS_MeshObject* meshobj, bool polytope);
void KX_ConvertSumoObject( KX_GameObject* gameobj,
- RAS_MeshObject* meshobj,
- KX_Scene* kxscene,
- PHY_ShapeProps* kxshapeprops,
- PHY_MaterialProps* kxmaterial,
- struct KX_ObjectProperties* objprop)
+ RAS_MeshObject* meshobj,
+ KX_Scene* kxscene,
+ PHY_ShapeProps* kxshapeprops,
+ PHY_MaterialProps* kxmaterial,
+ struct KX_ObjectProperties* objprop)
{
@@ -152,23 +150,23 @@ void KX_ConvertSumoObject( KX_GameObject* gameobj,
objprop->m_boundobject.box.m_extends[1],
objprop->m_boundobject.box.m_extends[2]);
smprop->m_inertia.scale(objprop->m_boundobject.box.m_extends[0]*objprop->m_boundobject.box.m_extends[0],
- objprop->m_boundobject.box.m_extends[1]*objprop->m_boundobject.box.m_extends[1],
- objprop->m_boundobject.box.m_extends[2]*objprop->m_boundobject.box.m_extends[2]);
+ objprop->m_boundobject.box.m_extends[1]*objprop->m_boundobject.box.m_extends[1],
+ objprop->m_boundobject.box.m_extends[2]*objprop->m_boundobject.box.m_extends[2]);
smprop->m_inertia *= smprop->m_mass/MT_Vector3(objprop->m_boundobject.box.m_extends).length();
break;
case KX_BOUNDCYLINDER:
shape = DT_NewCylinder(smprop->m_radius, objprop->m_boundobject.c.m_height);
smprop->m_inertia.scale(smprop->m_mass*smprop->m_radius*smprop->m_radius,
- smprop->m_mass*smprop->m_radius*smprop->m_radius,
- smprop->m_mass*objprop->m_boundobject.c.m_height*objprop->m_boundobject.c.m_height);
+ smprop->m_mass*smprop->m_radius*smprop->m_radius,
+ smprop->m_mass*objprop->m_boundobject.c.m_height*objprop->m_boundobject.c.m_height);
break;
case KX_BOUNDCONE:
shape = DT_NewCone(objprop->m_radius, objprop->m_boundobject.c.m_height);
smprop->m_inertia.scale(smprop->m_mass*smprop->m_radius*smprop->m_radius,
- smprop->m_mass*smprop->m_radius*smprop->m_radius,
- smprop->m_mass*objprop->m_boundobject.c.m_height*objprop->m_boundobject.c.m_height);
+ smprop->m_mass*smprop->m_radius*smprop->m_radius,
+ smprop->m_mass*objprop->m_boundobject.c.m_height*objprop->m_boundobject.c.m_height);
break;
- /* Dynamic mesh objects. WARNING! slow. */
+ /* Dynamic mesh objects. WARNING! slow. */
case KX_BOUNDPOLYTOPE:
polytope = true;
// fall through
@@ -188,15 +186,15 @@ void KX_ConvertSumoObject( KX_GameObject* gameobj,
shape = DT_NewSphere(objprop->m_radius);
smprop->m_inertia *= smprop->m_mass*smprop->m_radius*smprop->m_radius;
break;
-
+
}
-
+
sumoObj = new SM_Object(shape, !objprop->m_ghost?smmaterial:NULL,smprop,NULL);
-
+
sumoObj->setRigidBody(objprop->m_angular_rigidbody?true:false);
-
+
BL_RegisterSumoObject(gameobj,sceneptr,sumoObj,"",true, true);
-
+
}
else {
// non physics object
@@ -322,11 +320,12 @@ static void BL_RegisterSumoObject(
physicscontroller->SetObject(gameobj->GetSGNode());
}
-static DT_ShapeHandle InstancePhysicsComplex(RAS_MeshObject* meshobj, RAS_DisplayArray *darray, RAS_IPolyMaterial *mat)
+static DT_ShapeHandle InstancePhysicsComplex(RAS_MeshObject* meshobj, int vtxarray, RAS_IPolyMaterial *mat)
{
// instance a mesh from a single vertex array & material
- const RAS_TexVert *vertex_array = &darray->m_vertex[0];
- DT_VertexBaseHandle vertex_base = DT_NewVertexBase(vertex_array[0].getXYZ(), sizeof(RAS_TexVert));
+ const RAS_TexVert *vertex_array = &((*meshobj->GetVertexCache(mat)[vtxarray])[0]);
+ //const KX_IndexArray &index_array = *meshobj->GetIndexCache(mat)[vtxarray];
+ DT_VertexBaseHandle vertex_base = DT_NewVertexBase(vertex_array[0].getLocalXYZ(), sizeof(RAS_TexVert));
DT_ShapeHandle shape = DT_NewComplexShape(vertex_base);
@@ -338,19 +337,15 @@ static DT_ShapeHandle InstancePhysicsComplex(RAS_MeshObject* meshobj, RAS_Displa
// only add polygons that have the collisionflag set
if (poly->IsCollider())
{
- DT_Begin();
- DT_VertexIndex(poly->GetVertexOffset(0));
- DT_VertexIndex(poly->GetVertexOffset(1));
- DT_VertexIndex(poly->GetVertexOffset(2));
- DT_End();
+ DT_VertexIndices(3, poly->GetVertexIndexBase().m_indexarray);
// tesselate
if (poly->VertexCount() == 4)
{
DT_Begin();
- DT_VertexIndex(poly->GetVertexOffset(0));
- DT_VertexIndex(poly->GetVertexOffset(2));
- DT_VertexIndex(poly->GetVertexOffset(3));
+ DT_VertexIndex(poly->GetVertexIndexBase().m_indexarray[0]);
+ DT_VertexIndex(poly->GetVertexIndexBase().m_indexarray[2]);
+ DT_VertexIndex(poly->GetVertexIndexBase().m_indexarray[3]);
DT_End();
}
}
@@ -359,15 +354,16 @@ static DT_ShapeHandle InstancePhysicsComplex(RAS_MeshObject* meshobj, RAS_Displa
//DT_VertexIndices(indices.size(), &indices[0]);
DT_EndComplexShape();
- map_gamemesh_to_instance.insert(GEN_HashedPtr(meshobj), new KX_PhysicsInstance(vertex_base, darray, mat));
+ map_gamemesh_to_instance.insert(GEN_HashedPtr(meshobj), new KX_PhysicsInstance(vertex_base, vtxarray, mat));
return shape;
}
-static DT_ShapeHandle InstancePhysicsPolytope(RAS_MeshObject* meshobj, RAS_DisplayArray *darray, RAS_IPolyMaterial *mat)
+static DT_ShapeHandle InstancePhysicsPolytope(RAS_MeshObject* meshobj, int vtxarray, RAS_IPolyMaterial *mat)
{
// instance a mesh from a single vertex array & material
- const RAS_TexVert *vertex_array = &darray->m_vertex[0];
- DT_VertexBaseHandle vertex_base = DT_NewVertexBase(vertex_array[0].getXYZ(), sizeof(RAS_TexVert));
+ const RAS_TexVert *vertex_array = &((*meshobj->GetVertexCache(mat)[vtxarray])[0]);
+ //const KX_IndexArray &index_array = *meshobj->GetIndexCache(mat)[vtxarray];
+ DT_VertexBaseHandle vertex_base = DT_NewVertexBase(vertex_array[0].getLocalXYZ(), sizeof(RAS_TexVert));
std::vector<DT_Index> indices;
for (int p = 0; p < meshobj->NumPolygons(); p++)
@@ -377,12 +373,12 @@ static DT_ShapeHandle InstancePhysicsPolytope(RAS_MeshObject* meshobj, RAS_Displ
// only add polygons that have the collisionflag set
if (poly->IsCollider())
{
- indices.push_back(poly->GetVertexOffset(0));
- indices.push_back(poly->GetVertexOffset(1));
- indices.push_back(poly->GetVertexOffset(2));
+ indices.push_back(poly->GetVertexIndexBase().m_indexarray[0]);
+ indices.push_back(poly->GetVertexIndexBase().m_indexarray[1]);
+ indices.push_back(poly->GetVertexIndexBase().m_indexarray[2]);
if (poly->VertexCount() == 4)
- indices.push_back(poly->GetVertexOffset(3));
+ indices.push_back(poly->GetVertexIndexBase().m_indexarray[3]);
}
}
@@ -390,7 +386,7 @@ static DT_ShapeHandle InstancePhysicsPolytope(RAS_MeshObject* meshobj, RAS_Displ
DT_VertexIndices(indices.size(), &indices[0]);
DT_EndPolytope();
- map_gamemesh_to_instance.insert(GEN_HashedPtr(meshobj), new KX_PhysicsInstance(vertex_base, darray, mat));
+ map_gamemesh_to_instance.insert(GEN_HashedPtr(meshobj), new KX_PhysicsInstance(vertex_base, vtxarray, mat));
return shape;
}
@@ -402,8 +398,8 @@ bool KX_ReInstanceShapeFromMesh(RAS_MeshObject* meshobj)
KX_PhysicsInstance *instance = *map_gamemesh_to_instance[GEN_HashedPtr(meshobj)];
if (instance)
{
- const RAS_TexVert *vertex_array = &instance->m_darray->m_vertex[0];
- DT_ChangeVertexBase(instance->m_vertexbase, vertex_array[0].getXYZ());
+ const RAS_TexVert *vertex_array = &((*meshobj->GetVertexCache(instance->m_material)[instance->m_vtxarray])[0]);
+ DT_ChangeVertexBase(instance->m_vertexbase, vertex_array[0].getLocalXYZ());
return true;
}
return false;
@@ -429,7 +425,7 @@ static DT_ShapeHandle CreateShapeFromMesh(RAS_MeshObject* meshobj, bool polytope
// Count the number of collision polygons and check they all come from the same
// vertex array
int numvalidpolys = 0;
- RAS_DisplayArray *darray = NULL;
+ int vtxarray = -1;
RAS_IPolyMaterial *poly_material = NULL;
bool reinstance = true;
@@ -441,14 +437,14 @@ static DT_ShapeHandle CreateShapeFromMesh(RAS_MeshObject* meshobj, bool polytope
if (poly->IsCollider())
{
// check polygon is from the same vertex array
- if (poly->GetDisplayArray() != darray)
+ if (poly->GetVertexIndexBase().m_vtxarray != vtxarray)
{
- if (darray == NULL)
- darray = poly->GetDisplayArray();
+ if (vtxarray < 0)
+ vtxarray = poly->GetVertexIndexBase().m_vtxarray;
else
{
reinstance = false;
- darray = NULL;
+ vtxarray = -1;
}
}
@@ -482,9 +478,9 @@ static DT_ShapeHandle CreateShapeFromMesh(RAS_MeshObject* meshobj, bool polytope
if (reinstance)
{
if (polytope)
- shape = InstancePhysicsPolytope(meshobj, darray, poly_material);
+ shape = InstancePhysicsPolytope(meshobj, vtxarray, poly_material);
else
- shape = InstancePhysicsComplex(meshobj, darray, poly_material);
+ shape = InstancePhysicsComplex(meshobj, vtxarray, poly_material);
}
else
{
@@ -493,7 +489,7 @@ static DT_ShapeHandle CreateShapeFromMesh(RAS_MeshObject* meshobj, bool polytope
std::cout << "CreateShapeFromMesh: " << meshobj->GetName() << " is not suitable for polytope." << std::endl;
if (!poly_material)
std::cout << " Check mesh materials." << std::endl;
- if (darray == NULL)
+ if (vtxarray < 0)
std::cout << " Check number of vertices." << std::endl;
}
@@ -509,10 +505,18 @@ static DT_ShapeHandle CreateShapeFromMesh(RAS_MeshObject* meshobj, bool polytope
if (poly->IsCollider())
{ /* We have to tesselate here because SOLID can only raycast triangles */
DT_Begin();
- /* V1, V2, V3 */
- DT_Vertex(poly->GetVertex(2)->getXYZ());
- DT_Vertex(poly->GetVertex(1)->getXYZ());
- DT_Vertex(poly->GetVertex(0)->getXYZ());
+ /* V1 */
+ DT_Vertex(meshobj->GetVertex(poly->GetVertexIndexBase().m_vtxarray,
+ poly->GetVertexIndexBase().m_indexarray[2],
+ poly->GetMaterial()->GetPolyMaterial())->getLocalXYZ());
+ /* V2 */
+ DT_Vertex(meshobj->GetVertex(poly->GetVertexIndexBase().m_vtxarray,
+ poly->GetVertexIndexBase().m_indexarray[1],
+ poly->GetMaterial()->GetPolyMaterial())->getLocalXYZ());
+ /* V3 */
+ DT_Vertex(meshobj->GetVertex(poly->GetVertexIndexBase().m_vtxarray,
+ poly->GetVertexIndexBase().m_indexarray[0],
+ poly->GetMaterial()->GetPolyMaterial())->getLocalXYZ());
numvalidpolys++;
DT_End();
@@ -520,10 +524,18 @@ static DT_ShapeHandle CreateShapeFromMesh(RAS_MeshObject* meshobj, bool polytope
if (poly->VertexCount() == 4)
{
DT_Begin();
- /* V1, V3, V4 */
- DT_Vertex(poly->GetVertex(3)->getXYZ());
- DT_Vertex(poly->GetVertex(2)->getXYZ());
- DT_Vertex(poly->GetVertex(0)->getXYZ());
+ /* V1 */
+ DT_Vertex(meshobj->GetVertex(poly->GetVertexIndexBase().m_vtxarray,
+ poly->GetVertexIndexBase().m_indexarray[3],
+ poly->GetMaterial()->GetPolyMaterial())->getLocalXYZ());
+ /* V3 */
+ DT_Vertex(meshobj->GetVertex(poly->GetVertexIndexBase().m_vtxarray,
+ poly->GetVertexIndexBase().m_indexarray[2],
+ poly->GetMaterial()->GetPolyMaterial())->getLocalXYZ());
+ /* V4 */
+ DT_Vertex(meshobj->GetVertex(poly->GetVertexIndexBase().m_vtxarray,
+ poly->GetVertexIndexBase().m_indexarray[0],
+ poly->GetMaterial()->GetPolyMaterial())->getLocalXYZ());
numvalidpolys++;
DT_End();
@@ -667,107 +679,189 @@ void KX_ConvertODEEngineObject(KX_GameObject* gameobj,
#endif //WIN32
-
- class KX_SoftBodyDeformer : public RAS_Deformer
+// forward declarations
+static btCollisionShape* CreateBulletShapeFromMesh(RAS_MeshObject* meshobj, bool polytope)
+{
+ if (!meshobj)
+ return 0;
+
+ btCollisionShape* collisionMeshShape = 0;
+ btConvexHullShape* convexHullShape = 0;
+ btTriangleMeshShape* concaveShape = 0;
+
+ btTriangleMesh* collisionMeshData = 0;
+
+ //see if there is any polygons, if not, bail out.
+
+ int numPoints = 0;
+ btVector3* points = 0;
+
+ // Mesh has no polygons!
+ int numpolys = meshobj->NumPolygons();
+ if (!numpolys)
{
- class RAS_MeshObject* m_pMeshObject;
- class KX_GameObject* m_gameobj;
+ return NULL;
+ }
- public:
- KX_SoftBodyDeformer(RAS_MeshObject* pMeshObject,KX_GameObject* gameobj)
- :m_pMeshObject(pMeshObject),
- m_gameobj(gameobj)
- {
- //printf("KX_SoftBodyDeformer\n");
- };
+ // Count the number of collision polygons and check they all come from the same
+ // vertex array
+ int numvalidpolys = 0;
+ int vtxarray = -1;
+ RAS_IPolyMaterial *poly_material = NULL;
+ bool reinstance = true;
- virtual ~KX_SoftBodyDeformer()
- {
- //printf("~KX_SoftBodyDeformer\n");
- };
- virtual void Relink(GEN_Map<class GEN_HashedPtr, void*>*map)
- {
- //printf("relink\n");
- }
- virtual bool Apply(class RAS_IPolyMaterial *polymat)
+ for (int p=0; p<numpolys; p++)
+ {
+ RAS_Polygon* poly = meshobj->GetPolygon(p);
+
+ // only add polygons that have the collisionflag set
+ if (poly->IsCollider())
{
- KX_BulletPhysicsController* ctrl = (KX_BulletPhysicsController*) m_gameobj->GetPhysicsController();
- if (!ctrl)
- return false;
+ // check polygon is from the same vertex array
+ if (poly->GetVertexIndexBase().m_vtxarray != vtxarray)
+ {
+ if (vtxarray < 0)
+ vtxarray = poly->GetVertexIndexBase().m_vtxarray;
+ else
+ {
+ reinstance = false;
+ vtxarray = -1;
+ }
+ }
- btSoftBody* softBody= ctrl->GetSoftBody();
- if (!softBody)
- return false;
+ // check poly is from the same material
+ if (poly->GetMaterial()->GetPolyMaterial() != poly_material)
+ {
+ if (poly_material)
+ {
+ reinstance = false;
+ poly_material = NULL;
+ }
+ else
+ poly_material = poly->GetMaterial()->GetPolyMaterial();
+ }
- //printf("apply\n");
- RAS_MeshSlot::iterator it;
- RAS_MeshMaterial *mmat;
- RAS_MeshSlot *slot;
- size_t i;
+ // count the number of collision polys
+ numvalidpolys++;
- // update the vertex in m_transverts
- Update();
+ // We have one collision poly, and we can't reinstance, so we
+ // might as well break here.
+ if (!reinstance)
+ break;
+ }
+ }
+ // No collision polygons
+ if (numvalidpolys < 1)
+ return NULL;
- // 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;
+ if (polytope)
+ {
+ convexHullShape = new btConvexHullShape(&points[0].getX(),numPoints);
+ collisionMeshShape = convexHullShape;
+ } else
+ {
+ collisionMeshData = new btTriangleMesh();
+// concaveShape = new btTriangleMeshShape(collisionMeshData);
+ //collisionMeshShape = concaveShape;
- 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);
+ numvalidpolys = 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);
+ for (int p2=0; p2<numpolys; p2++)
+ {
+ RAS_Polygon* poly = meshobj->GetPolygon(p2);
- MT_Vector3 normal (
- nodes[v.getSoftBodyIndex()].m_n.getX(),
- nodes[v.getSoftBodyIndex()].m_n.getY(),
- nodes[v.getSoftBodyIndex()].m_n.getZ());
- v.SetNormal(normal);
+ // only add polygons that have the collisionflag set
+ if (poly->IsCollider())
+ {
+ //Bullet can raycast any shape, so
+ if (polytope)
+ {
+ for (int i=0;i<poly->VertexCount();i++)
+ {
+ const float* vtx = meshobj->GetVertex(poly->GetVertexIndexBase().m_vtxarray,
+ poly->GetVertexIndexBase().m_indexarray[i],
+ poly->GetMaterial()->GetPolyMaterial())->getLocalXYZ();
+ btPoint3 point(vtx[0],vtx[1],vtx[2]);
+ convexHullShape->addPoint(point);
+ }
+ if (poly->VertexCount())
+ numvalidpolys++;
+ } else
+ {
+ {
+ const float* vtx = meshobj->GetVertex(poly->GetVertexIndexBase().m_vtxarray,
+ poly->GetVertexIndexBase().m_indexarray[2],
+ poly->GetMaterial()->GetPolyMaterial())->getLocalXYZ();
+ btPoint3 vertex0(vtx[0],vtx[1],vtx[2]);
+ vtx = meshobj->GetVertex(poly->GetVertexIndexBase().m_vtxarray,
+ poly->GetVertexIndexBase().m_indexarray[1],
+ poly->GetMaterial()->GetPolyMaterial())->getLocalXYZ();
+ btPoint3 vertex1(vtx[0],vtx[1],vtx[2]);
+ vtx = meshobj->GetVertex(poly->GetVertexIndexBase().m_vtxarray,
+ poly->GetVertexIndexBase().m_indexarray[0],
+ poly->GetMaterial()->GetPolyMaterial())->getLocalXYZ();
+ btPoint3 vertex2(vtx[0],vtx[1],vtx[2]);
+ collisionMeshData->addTriangle(vertex0,vertex1,vertex2);
+ numvalidpolys++;
}
- }
- return true;
- }
- virtual bool Update(void)
- {
- //printf("update\n");
- return true;//??
- }
- virtual RAS_Deformer *GetReplica(class KX_GameObject* replica)
- {
- KX_SoftBodyDeformer* deformer = new KX_SoftBodyDeformer(replica->GetMesh(0),replica);
- return deformer;
+ if (poly->VertexCount() == 4)
+ {
+ const float* vtx = meshobj->GetVertex(poly->GetVertexIndexBase().m_vtxarray,
+ poly->GetVertexIndexBase().m_indexarray[3],
+ poly->GetMaterial()->GetPolyMaterial())->getLocalXYZ();
+ btPoint3 vertex0(vtx[0],vtx[1],vtx[2]);
+ vtx = meshobj->GetVertex(poly->GetVertexIndexBase().m_vtxarray,
+ poly->GetVertexIndexBase().m_indexarray[2],
+ poly->GetMaterial()->GetPolyMaterial())->getLocalXYZ();
+ btPoint3 vertex1(vtx[0],vtx[1],vtx[2]);
+ vtx = meshobj->GetVertex(poly->GetVertexIndexBase().m_vtxarray,
+ poly->GetVertexIndexBase().m_indexarray[0],
+ poly->GetMaterial()->GetPolyMaterial())->getLocalXYZ();
+ btPoint3 vertex2(vtx[0],vtx[1],vtx[2]);
+ collisionMeshData->addTriangle(vertex0,vertex1,vertex2);
+ numvalidpolys++;
+ }
+
+ }
}
+ }
+
- virtual bool SkipVertexTransform()
+
+ if (numvalidpolys > 0)
+ {
+
+ if (!polytope)
{
- return true;
- }
+ bool useQuantization = true;
+ concaveShape = new btBvhTriangleMeshShape( collisionMeshData, useQuantization );
+ //concaveShape = new btTriangleMeshShape( collisionMeshData );
- protected:
- //class RAS_MeshObject *m_pMesh;
- };
+ concaveShape->recalcLocalAabb();
+ if (collisionMeshShape)
+ delete collisionMeshShape;
+ collisionMeshShape = concaveShape;
+ }
+
+
+
+ return collisionMeshShape;
+ }
+ if (collisionMeshShape)
+ delete collisionMeshShape;
+ if (collisionMeshData)
+ delete collisionMeshData;
+ return NULL;
+
+}
-// forward declarations
void KX_ConvertBulletObject( class KX_GameObject* gameobj,
class RAS_MeshObject* meshobj,
@@ -784,7 +878,6 @@ void KX_ConvertBulletObject( class KX_GameObject* gameobj,
bool isbulletdyna = false;
CcdConstructionInfo ci;
class PHY_IMotionState* motionstate = new KX_MotionState(gameobj->GetSGNode());
- class CcdShapeConstructionInfo *shapeInfo = new CcdShapeConstructionInfo();
@@ -801,99 +894,120 @@ void KX_ConvertBulletObject( class KX_GameObject* gameobj,
ci.m_gravity = btVector3(0,0,0);
ci.m_localInertiaTensor =btVector3(0,0,0);
ci.m_mass = objprop->m_dyna ? shapeprops->m_mass : 0.f;
- ci.m_margin = objprop->m_margin;
- shapeInfo->m_radius = objprop->m_radius;
isbulletdyna = objprop->m_dyna;
ci.m_localInertiaTensor = btVector3(ci.m_mass/3.f,ci.m_mass/3.f,ci.m_mass/3.f);
+ btTransform trans;
+ trans.setIdentity();
+
btCollisionShape* bm = 0;
switch (objprop->m_boundclass)
{
case KX_BOUNDSPHERE:
{
- //float radius = objprop->m_radius;
- //btVector3 inertiaHalfExtents (
- // radius,
- // radius,
- // radius);
+ 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;
- bm = shapeInfo->CreateBulletShape();
+ bm = new btSphereShape(objprop->m_radius);
+ bm->calculateLocalInertia(ci.m_mass,ci.m_localInertiaTensor);
break;
};
case KX_BOUNDBOX:
{
- shapeInfo->m_halfExtend.setValue(
+ MT_Vector3 halfExtents (
objprop->m_boundobject.box.m_extends[0],
- objprop->m_boundobject.box.m_extends[1],
- objprop->m_boundobject.box.m_extends[2]);
+ objprop->m_boundobject.box.m_extends[1],
+ objprop->m_boundobject.box.m_extends[2]);
+
+ halfExtents /= 2.f;
+
+ //btVector3 he (halfExtents[0]-CONVEX_DISTANCE_MARGIN ,halfExtents[1]-CONVEX_DISTANCE_MARGIN ,halfExtents[2]-CONVEX_DISTANCE_MARGIN );
+ //he = he.absolute();
- shapeInfo->m_halfExtend /= 2.0;
- shapeInfo->m_halfExtend = shapeInfo->m_halfExtend.absolute();
- shapeInfo->m_shapeType = PHY_SHAPE_BOX;
- bm = shapeInfo->CreateBulletShape();
+ btVector3 he (halfExtents[0],halfExtents[1],halfExtents[2]);
+ he = he.absolute();
+
+
+ bm = new btBoxShape(he);
+ bm->calculateLocalInertia(ci.m_mass,ci.m_localInertiaTensor);
break;
};
case KX_BOUNDCYLINDER:
{
- shapeInfo->m_halfExtend.setValue(
+ btVector3 halfExtents (
objprop->m_boundobject.c.m_radius,
objprop->m_boundobject.c.m_radius,
objprop->m_boundobject.c.m_height * 0.5f
);
- shapeInfo->m_shapeType = PHY_SHAPE_CYLINDER;
- bm = shapeInfo->CreateBulletShape();
- break;
- }
+ bm = new btCylinderShapeZ(halfExtents);
+ bm->calculateLocalInertia(ci.m_mass,ci.m_localInertiaTensor);
- case KX_BOUNDCONE:
- {
- shapeInfo->m_radius = objprop->m_boundobject.c.m_radius;
- shapeInfo->m_height = objprop->m_boundobject.c.m_height;
- shapeInfo->m_shapeType = PHY_SHAPE_CONE;
- bm = shapeInfo->CreateBulletShape();
break;
}
- case KX_BOUNDPOLYTOPE:
+
+ case KX_BOUNDCONE:
{
- shapeInfo->SetMesh(meshobj, true,false);
- bm = shapeInfo->CreateBulletShape();
+ btVector3 halfExtents (objprop->m_boundobject.box.m_extends[0],
+ objprop->m_boundobject.box.m_extends[1],
+ objprop->m_boundobject.box.m_extends[2]);
+
+
+ halfExtents /= 2.f;
+
+ bm = new btConeShapeZ(objprop->m_boundobject.c.m_radius,objprop->m_boundobject.c.m_height);
+ bm->calculateLocalInertia(ci.m_mass,ci.m_localInertiaTensor);
+
break;
}
- case KX_BOUNDMESH:
- {
-
- if (!ci.m_mass ||objprop->m_softbody)
- {
- // mesh shapes can be shared, check first if we already have a shape on that mesh
- class CcdShapeConstructionInfo *sharedShapeInfo = CcdShapeConstructionInfo::FindMesh(meshobj, false);
- if (sharedShapeInfo != NULL)
- {
- delete shapeInfo;
- shapeInfo = sharedShapeInfo;
- shapeInfo->AddRef();
- } else
+ case KX_BOUNDPOLYTOPE:
+ {
+ bm = CreateBulletShapeFromMesh(meshobj,true);
+ if (bm)
{
- shapeInfo->SetMesh(meshobj, false,false);
+ bm->calculateLocalInertia(ci.m_mass,ci.m_localInertiaTensor);
}
- if (objprop->m_softbody)
- shapeInfo->setVertexWeldingThreshold(0.01f); //todo: expose this to the UI
-
- bm = shapeInfo->CreateBulletShape();
- //no moving concave meshes, so don't bother calculating inertia
- //bm->calculateLocalInertia(ci.m_mass,ci.m_localInertiaTensor);
- } else
+ break;
+ }
+ case KX_BOUNDMESH:
{
- shapeInfo->SetMesh(meshobj, false,true);
- bm = shapeInfo->CreateBulletShape();
+ if (!ci.m_mass)
+ {
+ bm = CreateBulletShapeFromMesh(meshobj,false);
+ ci.m_localInertiaTensor.setValue(0.f,0.f,0.f);
+ //no moving concave meshes, so don't bother calculating inertia
+ //bm->calculateLocalInertia(ci.m_mass,ci.m_localInertiaTensor);
+ }
+
+ break;
}
- break;
+ default:
+ //interpret the shape as a concave triangle-mesh
+ {
+ if (meshobj)
+ {
+ bm = CreateBulletShapeFromMesh(meshobj,false);
+ ci.m_localInertiaTensor.setValue(0.f,0.f,0.f);
+
+ // assert(0);
+
+ /*
+ meshobj->ScheduleCollisionPolygons();
+
+ KX_DeformableMesh* gfxmesh = new KX_DeformableMesh(meshobj);
+ gfxmesh->sendFixedMapping();
+ //trianglemesh
+ bm = new TriangleMeshInterface(gfxmesh,trans);
+ */
+ }
}
}
@@ -903,11 +1017,11 @@ void KX_ConvertBulletObject( class KX_GameObject* gameobj,
if (!bm)
{
delete motionstate;
- delete shapeInfo;
return;
}
- bm->setMargin(ci.m_margin);
+ bm->setMargin(0.06);
+
if (objprop->m_isCompoundChild)
@@ -916,46 +1030,31 @@ void KX_ConvertBulletObject( class KX_GameObject* gameobj,
//take relative transform into account!
KX_BulletPhysicsController* parentCtrl = (KX_BulletPhysicsController*)objprop->m_dynamic_parent->GetPhysicsController();
assert(parentCtrl);
- CcdShapeConstructionInfo* parentShapeInfo = parentCtrl->GetShapeInfo();
btRigidBody* rigidbody = parentCtrl->GetRigidBody();
btCollisionShape* colShape = rigidbody->getCollisionShape();
assert(colShape->isCompound());
btCompoundShape* compoundShape = (btCompoundShape*)colShape;
+ btTransform childTrans;
+ childTrans.setIdentity();
+ NodeList& children = objprop->m_dynamic_parent->GetSGNode()->GetSGChildren();
- // compute the local transform from parent, this may include a parent inverse node
- SG_Node* gameNode = gameobj->GetSGNode();
- SG_Node* parentInverseNode = gameNode->GetSGParent();
- if (parentInverseNode && parentInverseNode->GetSGClientObject() != NULL)
- // this is not a parent inverse node, cancel it
- parentInverseNode = NULL;
- // now combine the parent inverse node and the game node
- MT_Point3 childPos = gameNode->GetLocalPosition();
- MT_Matrix3x3 childRot = gameNode->GetLocalOrientation();
- MT_Vector3 childScale = gameNode->GetLocalScale();
- if (parentInverseNode)
- {
- const MT_Point3& parentInversePos = parentInverseNode->GetLocalPosition();
- const MT_Matrix3x3& parentInverseRot = parentInverseNode->GetLocalOrientation();
- const MT_Vector3& parentInverseScale = parentInverseNode->GetLocalScale();
- childRot = parentInverseRot * childRot;
- childScale = parentInverseScale * childScale;
- childPos = parentInversePos+parentInverseScale*(parentInverseRot*childPos);
- }
+ MT_Point3 childPos = gameobj->GetSGNode()->GetLocalPosition();
+ MT_Matrix3x3 childRot = gameobj->GetSGNode()->GetLocalOrientation();
+ MT_Vector3 childScale = gameobj->GetSGNode()->GetLocalScale();
- shapeInfo->m_childScale.setValue(childScale.x(),childScale.y(),childScale.z());
- bm->setLocalScaling(shapeInfo->m_childScale);
-
- shapeInfo->m_childTrans.setOrigin(btVector3(childPos.x(),childPos.y(),childPos.z()));
+ bm->setLocalScaling(btVector3(childScale.x(),childScale.y(),childScale.z()));
+ childTrans.setOrigin(btVector3(childPos.x(),childPos.y(),childPos.z()));
float rotval[12];
childRot.getValue(rotval);
btMatrix3x3 newRot;
newRot.setValue(rotval[0],rotval[1],rotval[2],rotval[4],rotval[5],rotval[6],rotval[8],rotval[9],rotval[10]);
newRot = newRot.transpose();
- shapeInfo->m_childTrans.setBasis(newRot);
- parentShapeInfo->AddShape(shapeInfo);
-
- compoundShape->addChildShape(shapeInfo->m_childTrans,bm);
+ childTrans.setBasis(newRot);
+
+
+ compoundShape->addChildShape(childTrans,bm);
+ kxscene->AddShape(bm);
//do some recalc?
//recalc inertia for rigidbody
if (!rigidbody->isStaticOrKinematicObject())
@@ -970,16 +1069,15 @@ void KX_ConvertBulletObject( class KX_GameObject* gameobj,
if (objprop->m_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
+ //replace shape by compoundShape
btCompoundShape* compoundShape = new btCompoundShape();
- compoundShape->addChildShape(shapeInfo->m_childTrans,bm);
- // now replace the shape
+ btTransform identTrans;
+ identTrans.setIdentity();
+ compoundShape->addChildShape(identTrans,bm);
+ //note abount compoundShape: Bullet does not delete the child shapes when
+ //the compound shape is deleted, so insert also the child shapes
+ kxscene->AddShape(bm);
bm = compoundShape;
- shapeInfo = compoundShapeInfo;
}
@@ -1015,7 +1113,6 @@ void KX_ConvertBulletObject( class KX_GameObject* gameobj,
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 = env;
@@ -1024,70 +1121,12 @@ void KX_ConvertBulletObject( class KX_GameObject* gameobj,
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 behaviour
-
- 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_radius = objprop->m_radius;
-
-
- ///////////////////
- ci.m_gamesoftFlag = objprop->m_gamesoftFlag;
- ci.m_soft_linStiff = objprop->m_soft_linStiff;
- ci.m_soft_angStiff = objprop->m_soft_angStiff; /* angular stiffness 0..1 */
- ci.m_soft_volume= objprop->m_soft_volume; /* volume preservation 0..1 */
-
- ci.m_soft_viterations= objprop->m_soft_viterations; /* Velocities solver iterations */
- ci.m_soft_piterations= objprop->m_soft_piterations; /* Positions solver iterations */
- ci.m_soft_diterations= objprop->m_soft_diterations; /* Drift solver iterations */
- ci.m_soft_citerations= objprop->m_soft_citerations; /* Cluster solver iterations */
-
- ci.m_soft_kSRHR_CL= objprop->m_soft_kSRHR_CL; /* Soft vs rigid hardness [0,1] (cluster only) */
- ci.m_soft_kSKHR_CL= objprop->m_soft_kSKHR_CL; /* Soft vs kinetic hardness [0,1] (cluster only) */
- ci.m_soft_kSSHR_CL= objprop->m_soft_kSSHR_CL; /* Soft vs soft hardness [0,1] (cluster only) */
- ci.m_soft_kSR_SPLT_CL= objprop->m_soft_kSR_SPLT_CL; /* Soft vs rigid impulse split [0,1] (cluster only) */
-
- ci.m_soft_kSK_SPLT_CL= objprop->m_soft_kSK_SPLT_CL; /* Soft vs rigid impulse split [0,1] (cluster only) */
- ci.m_soft_kSS_SPLT_CL= objprop->m_soft_kSS_SPLT_CL; /* Soft vs rigid impulse split [0,1] (cluster only) */
- ci.m_soft_kVCF= objprop->m_soft_kVCF; /* Velocities correction factor (Baumgarte) */
- ci.m_soft_kDP= objprop->m_soft_kDP; /* Damping coefficient [0,1] */
-
- ci.m_soft_kDG= objprop->m_soft_kDG; /* Drag coefficient [0,+inf] */
- ci.m_soft_kLF= objprop->m_soft_kLF; /* Lift coefficient [0,+inf] */
- ci.m_soft_kPR= objprop->m_soft_kPR; /* Pressure coefficient [-inf,+inf] */
- ci.m_soft_kVC= objprop->m_soft_kVC; /* Volume conversation coefficient [0,+inf] */
-
- ci.m_soft_kDF= objprop->m_soft_kDF; /* Dynamic friction coefficient [0,1] */
- ci.m_soft_kMT= objprop->m_soft_kMT; /* Pose matching coefficient [0,1] */
- ci.m_soft_kCHR= objprop->m_soft_kCHR; /* Rigid contacts hardness [0,1] */
- ci.m_soft_kKHR= objprop->m_soft_kKHR; /* Kinetic contacts hardness [0,1] */
-
- ci.m_soft_kSHR= objprop->m_soft_kSHR; /* Soft contacts hardness [0,1] */
- ci.m_soft_kAHR= objprop->m_soft_kAHR; /* Anchors hardness [0,1] */
- ci.m_soft_collisionflags= objprop->m_soft_collisionflags; /* Vertex/Face or Signed Distance Field(SDF) or Clusters, Soft versus Soft or Rigid */
- ci.m_soft_numclusteriterations= objprop->m_soft_numclusteriterations; /* number of iterations to refine collision clusters*/
-
- ////////////////////
-
ci.m_collisionFilterGroup = (isbulletdyna) ? short(CcdConstructionInfo::DefaultFilter) : short(CcdConstructionInfo::StaticFilter);
ci.m_collisionFilterMask = (isbulletdyna) ? short(CcdConstructionInfo::AllFilter) : short(CcdConstructionInfo::AllFilter ^ CcdConstructionInfo::StaticFilter);
ci.m_bRigid = objprop->m_dyna && objprop->m_angular_rigidbody;
- ci.m_bSoft = objprop->m_softbody;
- MT_Vector3 scaling = gameobj->NodeGetWorldScaling();
- ci.m_scaling.setValue(scaling[0], scaling[1], scaling[2]);
KX_BulletPhysicsController* physicscontroller = new KX_BulletPhysicsController(ci,isbulletdyna);
- // shapeInfo is reference counted, decrement now as we don't use it anymore
- if (shapeInfo)
- shapeInfo->Release();
+ //remember that we created a shape so that we can delete it when the scene is removed (bullet will not delete it)
+ kxscene->AddShape(bm);
if (objprop->m_in_active_layer)
{
@@ -1098,16 +1137,10 @@ void KX_ConvertBulletObject( class KX_GameObject* gameobj,
gameobj->SetPhysicsController(physicscontroller,isbulletdyna);
physicscontroller->setNewClientInfo(gameobj->getClientInfo());
- {
- btRigidBody* rbody = physicscontroller->GetRigidBody();
-
- if (rbody && objprop->m_disableSleeping)
- rbody->setActivationState(DISABLE_DEACTIVATION);
- }
-
- CcdPhysicsController* parentCtrl = objprop->m_dynamic_parent ? (KX_BulletPhysicsController*)objprop->m_dynamic_parent->GetPhysicsController() : 0;
- physicscontroller->setParentCtrl(parentCtrl);
+ btRigidBody* rbody = physicscontroller->GetRigidBody();
+ if (objprop->m_disableSleeping)
+ rbody->setActivationState(DISABLE_DEACTIVATION);
//Now done directly in ci.m_collisionFlags so that it propagates to replica
//if (objprop->m_ghost)
@@ -1156,20 +1189,6 @@ void KX_ConvertBulletObject( class KX_GameObject* gameobj,
physicscontroller->SetObject(gameobj->GetSGNode());
-
- ///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),gameobj);
- gameobj->SetDeformer(softbodyDeformer);
-
- }
- }
-
}
diff --git a/source/gameengine/Ketsji/KX_GameActuator.cpp b/source/gameengine/Ketsji/KX_GameActuator.cpp
index 76459e46731..fcd32d5f4fe 100644
--- a/source/gameengine/Ketsji/KX_GameActuator.cpp
+++ b/source/gameengine/Ketsji/KX_GameActuator.cpp
@@ -34,7 +34,6 @@
//#include <iostream>
#include "KX_Scene.h"
#include "KX_KetsjiEngine.h"
-#include "KX_PythonInit.h" /* for config load/saving */
#ifdef HAVE_CONFIG_H
#include <config.h>
@@ -126,71 +125,6 @@ bool KX_GameActuator::Update()
}
break;
}
- case KX_GAME_SAVECFG:
- {
- if (m_ketsjiengine)
- {
- char mashal_path[512];
- char *marshal_buffer = NULL;
- 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");
- }
- }
- break;
- }
- case KX_GAME_LOADCFG:
- {
- 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);
- 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;
- }
default:
; /* do nothing? this is an internal error !!! */
}
@@ -241,13 +175,13 @@ PyParentObject KX_GameActuator::Parents[] =
PyMethodDef KX_GameActuator::Methods[] =
{
- {"getFile", (PyCFunction) KX_GameActuator::sPyGetFile, METH_VARARGS, (PY_METHODCHAR)GetFile_doc},
- {"setFile", (PyCFunction) KX_GameActuator::sPySetFile, METH_VARARGS, (PY_METHODCHAR)SetFile_doc},
+ {"getFile", (PyCFunction) KX_GameActuator::sPyGetFile, METH_VARARGS, GetFile_doc},
+ {"setFile", (PyCFunction) KX_GameActuator::sPySetFile, METH_VARARGS, SetFile_doc},
{NULL,NULL} //Sentinel
};
/* getFile */
-const char KX_GameActuator::GetFile_doc[] =
+char KX_GameActuator::GetFile_doc[] =
"getFile()\n"
"get the name of the file to start.\n";
PyObject* KX_GameActuator::PyGetFile(PyObject* self, PyObject* args, PyObject* kwds)
@@ -256,7 +190,7 @@ PyObject* KX_GameActuator::PyGetFile(PyObject* self, PyObject* args, PyObject* k
}
/* setFile */
-const char KX_GameActuator::SetFile_doc[] =
+char KX_GameActuator::SetFile_doc[] =
"setFile(name)\n"
"set the name of the file to start.\n";
PyObject* KX_GameActuator::PySetFile(PyObject* self, PyObject* args, PyObject* kwds)
diff --git a/source/gameengine/Ketsji/KX_GameActuator.h b/source/gameengine/Ketsji/KX_GameActuator.h
index bb3448995dc..8565dc46caa 100644
--- a/source/gameengine/Ketsji/KX_GameActuator.h
+++ b/source/gameengine/Ketsji/KX_GameActuator.h
@@ -54,8 +54,6 @@ protected:
KX_GAME_START,
KX_GAME_RESTART,
KX_GAME_QUIT,
- KX_GAME_SAVECFG,
- KX_GAME_LOADCFG,
KX_GAME_MAX
};
diff --git a/source/gameengine/Ketsji/KX_GameObject.cpp b/source/gameengine/Ketsji/KX_GameObject.cpp
index f2a554c6b2a..989cdabd491 100644
--- a/source/gameengine/Ketsji/KX_GameObject.cpp
+++ b/source/gameengine/Ketsji/KX_GameObject.cpp
@@ -51,7 +51,6 @@ typedef unsigned long uint_ptr;
#include "KX_GameObject.h"
#include "RAS_MeshObject.h"
#include "KX_MeshProxy.h"
-#include "KX_PolyProxy.h"
#include <stdio.h> // printf
#include "SG_Controller.h"
#include "KX_IPhysicsController.h"
@@ -65,8 +64,6 @@ typedef unsigned long uint_ptr;
#include "SCA_IActuator.h"
#include "SCA_ISensor.h"
-#include "PyObjectPlus.h" /* python stuff */
-
// This file defines relationships between parents and children
// in the game engine.
@@ -81,15 +78,12 @@ KX_GameObject::KX_GameObject(
m_bDyna(false),
m_layer(0),
m_pBlenderObject(NULL),
- m_pBlenderGroupObject(NULL),
m_bSuspendDynamics(false),
m_bUseObjectColor(false),
m_bIsNegativeScaling(false),
m_bVisible(true),
- m_bCulled(true),
m_pPhysicsController1(NULL),
m_pPhysicsEnvironment(NULL),
- m_xray(false),
m_pHitObject(NULL),
m_isDeformable(false)
{
@@ -105,11 +99,8 @@ KX_GameObject::KX_GameObject(
};
-
KX_GameObject::~KX_GameObject()
{
- RemoveMeshes();
-
// is this delete somewhere ?
//if (m_sumoObj)
// delete m_sumoObj;
@@ -171,6 +162,7 @@ STR_String KX_GameObject::GetName()
void KX_GameObject::SetName(STR_String name)
{
m_name = name;
+
}; // Set the name of the value
@@ -214,8 +206,7 @@ KX_GameObject* KX_GameObject::GetParent()
void KX_GameObject::SetParent(KX_Scene *scene, KX_GameObject* obj)
{
- // check on valid node in case a python controller holds a reference to a deleted object
- if (obj && GetSGNode() && obj->GetSGNode() && GetSGNode()->GetSGParent() != obj->GetSGNode())
+ if (obj && GetSGNode()->GetSGParent() != obj->GetSGNode())
{
// Make sure the objects have some scale
MT_Vector3 scale1 = NodeGetWorldScaling();
@@ -236,12 +227,11 @@ void KX_GameObject::SetParent(KX_Scene *scene, KX_GameObject* obj)
m_pPhysicsController1->SuspendDynamics(true);
}
// Set us to our new scale, position, and orientation
- scale2[0] = 1.0/scale2[0];
- scale2[1] = 1.0/scale2[1];
- scale2[2] = 1.0/scale2[2];
- scale1 = scale1 * scale2;
+ scale1[0] = scale1[0]/scale2[0];
+ scale1[1] = scale1[1]/scale2[1];
+ scale1[2] = scale1[2]/scale2[2];
MT_Matrix3x3 invori = obj->NodeGetWorldOrientation().inverse();
- MT_Vector3 newpos = invori*(NodeGetWorldPosition()-obj->NodeGetWorldPosition())*scale2;
+ MT_Vector3 newpos = invori*(NodeGetWorldPosition()-obj->NodeGetWorldPosition())*scale1;
NodeSetLocalScale(scale1);
NodeSetLocalPosition(MT_Point3(newpos[0],newpos[1],newpos[2]));
@@ -257,8 +247,7 @@ void KX_GameObject::SetParent(KX_Scene *scene, KX_GameObject* obj)
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())
+ if (GetSGNode()->GetSGParent())
{
// Set us to the right spot
GetSGNode()->SetLocalScale(GetSGNode()->GetWorldScaling());
@@ -294,11 +283,11 @@ void KX_GameObject::ProcessReplica(KX_GameObject* replica)
CValue* KX_GameObject::GetReplica()
{
KX_GameObject* replica = new KX_GameObject(*this);
-
+
// this will copy properties and so on...
CValue::AddDataToReplica(replica);
ProcessReplica(replica);
-
+
return replica;
}
@@ -364,47 +353,24 @@ double* KX_GameObject::GetOpenGLMatrix()
return fl;
}
-void KX_GameObject::AddMeshUser()
-{
- for (size_t i=0;i<m_meshes.size();i++)
- m_meshes[i]->AddMeshUser(this);
-
- 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 )
+void KX_GameObject::Bucketize()
{
double* fl = GetOpenGLMatrix();
for (size_t i=0;i<m_meshes.size();i++)
- m_meshes[i]->UpdateBuckets(this, fl, m_bUseObjectColor, m_objectColor, m_bVisible, m_bCulled);
-
- if (recursive) {
- UpdateBuckets_recursive(m_pSGNode);
- }
+ m_meshes[i]->Bucketize(fl, this, m_bUseObjectColor, m_objectColor);
}
+
+
void KX_GameObject::RemoveMeshes()
{
+ double* fl = GetOpenGLMatrix();
+
for (size_t i=0;i<m_meshes.size();i++)
- m_meshes[i]->RemoveFromBuckets(this);
+ m_meshes[i]->RemoveFromBuckets(fl, this);
//note: meshes can be shared, and are deleted by KX_BlenderSceneConverter
@@ -487,14 +453,13 @@ KX_GameObject::UpdateMaterialData(
)
{
int mesh = 0;
- if (((unsigned int)mesh < m_meshes.size()) && mesh >= 0) {
- list<RAS_MeshMaterial>::iterator mit = m_meshes[mesh]->GetFirstMaterial();
+ if (((unsigned int)mesh < m_meshes.size()) && mesh >= 0) {
+ RAS_MaterialBucket::Set::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 )
+ RAS_IPolyMaterial* poly = (*mit)->GetPolyMaterial();
+ if(poly->GetFlag() & RAS_BLENDERMAT)
{
KX_BlenderMaterial *m = static_cast<KX_BlenderMaterial*>(poly);
@@ -502,7 +467,8 @@ KX_GameObject::UpdateMaterialData(
{
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);
+ if(!(poly->GetFlag() & RAS_BLENDERGLSL))
+ SetObjectColor(rgba);
}
else
{
@@ -528,52 +494,14 @@ KX_GameObject::GetVisible(
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
+ bool v
)
{
m_bVisible = v;
- if (recursive)
- setVisible_recursive(m_pSGNode, v);
}
-bool
-KX_GameObject::GetCulled(
- void
- )
-{
- return m_bCulled;
-}
-
-void
-KX_GameObject::SetCulled(
- bool c
- )
-{
- m_bCulled = c;
-}
-
-
void
KX_GameObject::SetLayer(
int l
@@ -590,16 +518,51 @@ KX_GameObject::GetLayer(
return m_layer;
}
-void KX_GameObject::addLinearVelocity(const MT_Vector3& lin_vel,bool local)
+// used by Python, and the actuatorshould _not_ be misused by the
+// scene!
+void
+KX_GameObject::MarkVisible(
+ bool visible
+ )
{
- if (m_pPhysicsController1)
+ /* If explicit visibility settings are used, this is
+ * determined on this level. Maybe change this to mesh level
+ * later on? */
+
+ double* fl = GetOpenGLMatrixPtr()->getPointer();
+ for (size_t i=0;i<m_meshes.size();i++)
{
- MT_Vector3 lv = local ? NodeGetWorldOrientation() * lin_vel : lin_vel;
- m_pPhysicsController1->SetLinearVelocity(lv + m_pPhysicsController1->GetLinearVelocity(), 0);
+ m_meshes[i]->MarkVisible(fl,this,visible,m_bUseObjectColor,m_objectColor);
}
}
+// Always use the flag?
+void
+KX_GameObject::MarkVisible(
+ void
+ )
+{
+ double* fl = GetOpenGLMatrixPtr()->getPointer();
+ for (size_t i=0;i<m_meshes.size();i++)
+ {
+ m_meshes[i]->MarkVisible(fl,
+ this,
+ m_bVisible,
+ m_bUseObjectColor,
+ m_objectColor
+ );
+ }
+}
+
+
+void KX_GameObject::addLinearVelocity(const MT_Vector3& lin_vel,bool local)
+{
+ if (m_pPhysicsController1)
+ m_pPhysicsController1->SetLinearVelocity(lin_vel + m_pPhysicsController1->GetLinearVelocity(),local);
+}
+
+
void KX_GameObject::setLinearVelocity(const MT_Vector3& lin_vel,bool local)
{
@@ -615,7 +578,6 @@ void KX_GameObject::setAngularVelocity(const MT_Vector3& ang_vel,bool local)
m_pPhysicsController1->SetAngularVelocity(ang_vel,local);
}
-
void KX_GameObject::ResolveCombinedVelocities(
const MT_Vector3 & lin_vel,
const MT_Vector3 & ang_vel,
@@ -645,10 +607,6 @@ void KX_GameObject::AlignAxisToVect(const MT_Vector3& dir, int axis, float fac)
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))
@@ -779,24 +737,13 @@ MT_Vector3 KX_GameObject::GetAngularVelocity(bool local)
return velocity;
}
-MT_Vector3 KX_GameObject::GetVelocity(const MT_Point3& point)
-{
- if (m_pPhysicsController1)
- {
- return m_pPhysicsController1->GetVelocity(point);
- }
- return MT_Vector3(0.0,0.0,0.0);
-}
+
// 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_pPhysicsController1 && !GetSGNode()->GetSGParent())
+ if (m_pPhysicsController1 && (!GetSGNode() || !GetSGNode()->GetSGParent()))
{
// don't update physic controller if the object is a child:
// 1) the transformation will not be right
@@ -805,39 +752,35 @@ void KX_GameObject::NodeSetLocalPosition(const MT_Point3& trans)
m_pPhysicsController1->setPosition(trans);
}
- GetSGNode()->SetLocalPosition(trans);
+ if (GetSGNode())
+ 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_pPhysicsController1 && !GetSGNode()->GetSGParent())
+ if (m_pPhysicsController1 && (!GetSGNode() || !GetSGNode()->GetSGParent()))
{
// see note above
m_pPhysicsController1->setOrientation(rot);
}
- GetSGNode()->SetLocalOrientation(rot);
+ if (GetSGNode())
+ GetSGNode()->SetLocalOrientation(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_pPhysicsController1 && !GetSGNode()->GetSGParent())
+ if (m_pPhysicsController1 && (!GetSGNode() || !GetSGNode()->GetSGParent()))
{
// see note above
m_pPhysicsController1->setScaling(scale);
}
- GetSGNode()->SetLocalScale(scale);
+
+ if (GetSGNode())
+ GetSGNode()->SetLocalScale(scale);
}
@@ -845,17 +788,7 @@ void KX_GameObject::NodeSetLocalScale(const MT_Vector3& scale)
void KX_GameObject::NodeSetRelativeScale(const MT_Vector3& scale)
{
if (GetSGNode())
- {
GetSGNode()->RelativeScale(scale);
- if (m_pPhysicsController1 && (!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_pPhysicsController1->setScaling(newscale);
- }
- }
}
void KX_GameObject::NodeSetWorldPosition(const MT_Point3& trans)
@@ -895,13 +828,6 @@ void KX_GameObject::NodeUpdateGS(double time,bool bInitiator)
const MT_Matrix3x3& KX_GameObject::NodeGetWorldOrientation() const
{
- static MT_Matrix3x3 defaultOrientation = MT_Matrix3x3( 1.0, 0.0, 0.0,
- 0.0, 1.0, 0.0,
- 0.0, 0.0, 1.0);
-
- // check on valid node in case a python controller holds a reference to a deleted object
- if (!GetSGNode())
- return defaultOrientation;
return GetSGNode()->GetWorldOrientation();
}
@@ -909,12 +835,6 @@ const MT_Matrix3x3& KX_GameObject::NodeGetWorldOrientation() const
const MT_Vector3& KX_GameObject::NodeGetWorldScaling() const
{
- static MT_Vector3 defaultScaling = MT_Vector3(1.0, 1.0, 1.0);
-
- // check on valid node in case a python controller holds a reference to a deleted object
- if (!GetSGNode())
- return defaultScaling;
-
return GetSGNode()->GetWorldScaling();
}
@@ -922,12 +842,6 @@ const MT_Vector3& KX_GameObject::NodeGetWorldScaling() const
const MT_Point3& KX_GameObject::NodeGetWorldPosition() const
{
- static MT_Point3 defaultPosition = MT_Point3(0.0, 0.0, 0.0);
-
- // check on valid node in case a python controller holds a reference to a deleted object
- if (!GetSGNode())
- return defaultPosition;
-
return GetSGNode()->GetWorldPosition();
}
@@ -969,22 +883,15 @@ void KX_GameObject::Suspend()
PyMethodDef KX_GameObject::Methods[] = {
{"getPosition", (PyCFunction) KX_GameObject::sPyGetPosition, METH_NOARGS},
{"setPosition", (PyCFunction) KX_GameObject::sPySetPosition, METH_O},
- {"setWorldPosition", (PyCFunction) KX_GameObject::sPySetWorldPosition, METH_O},
- {"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},
{"getMass", (PyCFunction) KX_GameObject::sPyGetMass, METH_NOARGS},
{"getReactionForce", (PyCFunction) KX_GameObject::sPyGetReactionForce, METH_NOARGS},
{"getOrientation", (PyCFunction) KX_GameObject::sPyGetOrientation, METH_NOARGS},
{"setOrientation", (PyCFunction) KX_GameObject::sPySetOrientation, METH_O},
{"getVisible",(PyCFunction) KX_GameObject::sPyGetVisible, METH_NOARGS},
- {"setVisible",(PyCFunction) KX_GameObject::sPySetVisible, METH_VARARGS},
+ {"setVisible",(PyCFunction) KX_GameObject::sPySetVisible, METH_O},
{"getState",(PyCFunction) KX_GameObject::sPyGetState, METH_NOARGS},
{"setState",(PyCFunction) KX_GameObject::sPySetState, METH_O},
{"alignAxisToVect",(PyCFunction) KX_GameObject::sPyAlignAxisToVect, METH_VARARGS},
@@ -1003,7 +910,6 @@ PyMethodDef KX_GameObject::Methods[] = {
{"getMesh", (PyCFunction)KX_GameObject::sPyGetMesh,METH_VARARGS},
{"getPhysicsId", (PyCFunction)KX_GameObject::sPyGetPhysicsId,METH_NOARGS},
{"getPropertyNames", (PyCFunction)KX_GameObject::sPyGetPropertyNames,METH_NOARGS},
- {"replaceMesh",(PyCFunction) KX_GameObject::sPyReplaceMesh, METH_O},
{"endObject",(PyCFunction) KX_GameObject::sPyEndObject, METH_NOARGS},
KX_PYMETHODTABLE(KX_GameObject, rayCastTo),
KX_PYMETHODTABLE(KX_GameObject, rayCast),
@@ -1030,35 +936,13 @@ bool KX_GameObject::ConvertPythonVectorArgs(PyObject* args,
}
*/
-PyObject* KX_GameObject::PyReplaceMesh(PyObject* self, PyObject* value)
-{
- KX_Scene *scene = KX_GetActiveScene();
- char* meshname;
- void* mesh_pt;
-
- meshname = PyString_AsString(value);
- if (meshname==NULL) {
- PyErr_SetString(PyExc_ValueError, "Expected a mesh name");
- return NULL;
- }
- mesh_pt = SCA_ILogicBrick::m_sCurrentLogicManager->GetMeshByName(STR_String(meshname));
-
- if (mesh_pt==NULL) {
- PyErr_SetString(PyExc_ValueError, "The mesh name given does not exist");
- return NULL;
- }
- scene->ReplaceMesh(this, (class RAS_MeshObject*)mesh_pt);
-
- Py_RETURN_NONE;
-}
-
PyObject* KX_GameObject::PyEndObject(PyObject* self)
{
- KX_Scene *scene = KX_GetActiveScene();
+ KX_Scene *scene = PHY_GetActiveScene();
scene->DelayedRemoveObject(this);
- Py_RETURN_NONE;
+ return Py_None;
}
@@ -1148,23 +1032,18 @@ PyObject* KX_GameObject::_getattr(const STR_String& attr)
int KX_GameObject::_setattr(const STR_String& attr, PyObject *value) // _setattr method
{
- if (attr == "mass") {
- PyErr_SetString(PyExc_AttributeError, "attribute \"mass\" is read only");
+ if (attr == "mass")
return 1;
- }
- if (attr == "parent") {
- PyErr_SetString(PyExc_AttributeError, "attribute \"mass\" is read only\nUse setParent()");
+ if (attr == "parent")
return 1;
- }
if (PyInt_Check(value))
{
int val = PyInt_AsLong(value);
if (attr == "visible")
{
- SetVisible(val != 0, false);
- UpdateBuckets(false);
+ SetVisible(val != 0);
return 0;
}
}
@@ -1223,7 +1102,7 @@ int KX_GameObject::_setattr(const STR_String& attr, PyObject *value) // _setattr
}
return 1;
}
- PyErr_SetString(PyExc_AttributeError, "could not set the orientation from a 3x3 matrix, quaternion or euler sequence");
+
return 1;
}
@@ -1266,67 +1145,10 @@ int KX_GameObject::_setattr(const STR_String& attr, PyObject *value) // _setattr
return SCA_IObject::_setattr(attr, value);
}
-PyObject* KX_GameObject::PyApplyForce(PyObject* self, PyObject* args)
-{
- int local = 0;
- PyObject* pyvect;
-
- if (PyArg_ParseTuple(args, "O|i", &pyvect, &local)) {
- MT_Vector3 force;
- if (PyVecTo(pyvect, force)) {
- ApplyForce(force, (local!=0));
- Py_RETURN_NONE;
- }
- }
- return NULL;
-}
-
-PyObject* KX_GameObject::PyApplyTorque(PyObject* self, PyObject* args)
-{
- int local = 0;
- PyObject* pyvect;
- if (PyArg_ParseTuple(args, "O|i", &pyvect, &local)) {
- MT_Vector3 torque;
- if (PyVecTo(pyvect, torque)) {
- ApplyTorque(torque, (local!=0));
- Py_RETURN_NONE;
- }
- }
- return NULL;
-}
-
-PyObject* KX_GameObject::PyApplyRotation(PyObject* self, PyObject* args)
-{
- int local = 0;
- PyObject* pyvect;
-
- if (PyArg_ParseTuple(args, "O|i", &pyvect, &local)) {
- MT_Vector3 rotation;
- if (PyVecTo(pyvect, rotation)) {
- ApplyRotation(rotation, (local!=0));
- Py_RETURN_NONE;
- }
- }
- return NULL;
-}
-
-PyObject* KX_GameObject::PyApplyMovement(PyObject* self, PyObject* args)
-{
- int local = 0;
- PyObject* pyvect;
-
- if (PyArg_ParseTuple(args, "O|i", &pyvect, &local)) {
- MT_Vector3 movement;
- if (PyVecTo(pyvect, movement)) {
- ApplyMovement(movement, (local!=0));
- Py_RETURN_NONE;
- }
- }
- return NULL;
-}
-
-PyObject* KX_GameObject::PyGetLinearVelocity(PyObject* self, PyObject* args)
+PyObject* KX_GameObject::PyGetLinearVelocity(PyObject* self,
+ PyObject* args,
+ PyObject* kwds)
{
// only can get the velocity if we have a physics object connected to us...
int local = 0;
@@ -1340,7 +1162,9 @@ PyObject* KX_GameObject::PyGetLinearVelocity(PyObject* self, PyObject* args)
}
}
-PyObject* KX_GameObject::PySetLinearVelocity(PyObject* self, PyObject* args)
+PyObject* KX_GameObject::PySetLinearVelocity(PyObject* self,
+ PyObject* args,
+ PyObject* kwds)
{
int local = 0;
PyObject* pyvect;
@@ -1355,43 +1179,17 @@ PyObject* KX_GameObject::PySetLinearVelocity(PyObject* self, PyObject* args)
return NULL;
}
-PyObject* KX_GameObject::PyGetAngularVelocity(PyObject* self, PyObject* args)
-{
- // only can get the velocity if we have a physics object connected to us...
- int local = 0;
- if (PyArg_ParseTuple(args,"|i",&local))
- {
- return PyObjectFrom(GetAngularVelocity((local!=0)));
- }
- else
- {
- return NULL;
- }
-}
-
-PyObject* KX_GameObject::PySetAngularVelocity(PyObject* self, PyObject* args)
+PyObject* KX_GameObject::PySetVisible(PyObject* self, PyObject* value)
{
- int local = 0;
- PyObject* pyvect;
+ int visible = PyInt_AsLong(value);
- if (PyArg_ParseTuple(args,"O|i",&pyvect,&local)) {
- MT_Vector3 velocity;
- if (PyVecTo(pyvect, velocity)) {
- setAngularVelocity(velocity, (local!=0));
- Py_RETURN_NONE;
- }
- }
- return NULL;
-}
-
-PyObject* KX_GameObject::PySetVisible(PyObject* self, PyObject* args)
-{
- int visible, recursive = 0;
- if (!PyArg_ParseTuple(args,"i|i",&visible, &recursive))
+ if (visible==-1 && PyErr_Occurred()) {
+ PyErr_SetString(PyExc_TypeError, "expected 0 or 1");
return NULL;
+ }
- SetVisible(visible ? true:false, recursive ? true:false);
- UpdateBuckets(recursive ? true:false);
+ MarkVisible(visible!=0);
+ m_bVisible = (visible!=0);
Py_RETURN_NONE;
}
@@ -1430,7 +1228,9 @@ PyObject* KX_GameObject::PySetState(PyObject* self, PyObject* value)
-PyObject* KX_GameObject::PyGetVelocity(PyObject* self, PyObject* args)
+PyObject* KX_GameObject::PyGetVelocity(PyObject* self,
+ PyObject* args,
+ PyObject* kwds)
{
// only can get the velocity if we have a physics object connected to us...
MT_Vector3 velocity(0.0,0.0,0.0);
@@ -1511,7 +1311,7 @@ PyObject* KX_GameObject::PySetParent(PyObject* self, PyObject* value)
// The object we want to set as parent
CValue *m_ob = (CValue*)value;
KX_GameObject *obj = ((KX_GameObject*)m_ob);
- KX_Scene *scene = KX_GetActiveScene();
+ KX_Scene *scene = PHY_GetActiveScene();
this->SetParent(scene, obj);
@@ -1520,7 +1320,7 @@ PyObject* KX_GameObject::PySetParent(PyObject* self, PyObject* value)
PyObject* KX_GameObject::PyRemoveParent(PyObject* self)
{
- KX_Scene *scene = KX_GetActiveScene();
+ KX_Scene *scene = PHY_GetActiveScene();
this->RemoveParent(scene);
Py_RETURN_NONE;
}
@@ -1562,7 +1362,9 @@ PyObject* KX_GameObject::PyGetChildrenRecursive(PyObject* self)
return list;
}
-PyObject* KX_GameObject::PyGetMesh(PyObject* self, PyObject* args)
+PyObject* KX_GameObject::PyGetMesh(PyObject* self,
+ PyObject* args,
+ PyObject* kwds)
{
int mesh = 0;
@@ -1602,7 +1404,9 @@ PyObject* KX_GameObject::PySetCollisionMargin(PyObject* self, PyObject* value)
-PyObject* KX_GameObject::PyApplyImpulse(PyObject* self, PyObject* args)
+PyObject* KX_GameObject::PyApplyImpulse(PyObject* self,
+ PyObject* args,
+ PyObject* kwds)
{
PyObject* pyattach;
PyObject* pyimpulse;
@@ -1673,7 +1477,9 @@ PyObject* KX_GameObject::PySetOrientation(PyObject* self, PyObject* value)
return NULL;
}
-PyObject* KX_GameObject::PyAlignAxisToVect(PyObject* self, PyObject* args)
+PyObject* KX_GameObject::PyAlignAxisToVect(PyObject* self,
+ PyObject* args,
+ PyObject* kwds)
{
PyObject* pyvect;
int axis = 2; //z axis is the default
@@ -1718,19 +1524,6 @@ PyObject* KX_GameObject::PySetPosition(PyObject* self, PyObject* value)
return NULL;
}
-PyObject* KX_GameObject::PySetWorldPosition(PyObject* self, PyObject* value)
-{
- MT_Point3 pos;
- if (PyVecTo(value, pos))
- {
- NodeSetWorldPosition(pos);
- NodeUpdateGS(0.f,true);
- Py_RETURN_NONE;
- }
-
- return NULL;
-}
-
PyObject* KX_GameObject::PyGetPhysicsId(PyObject* self)
{
KX_IPhysicsController* ctrl = GetPhysicsController();
@@ -1758,9 +1551,9 @@ KX_PYMETHODDEF_DOC(KX_GameObject, getDistanceTo,
PyErr_Clear();
PyObject *pyother;
- KX_GameObject *other;
- if (PyArg_ParseTuple(args, "O", &pyother) && ConvertPythonToGameObject(pyother, &other, false))
+ if (PyArg_ParseTuple(args, "O!", &KX_GameObject::Type, &pyother))
{
+ KX_GameObject *other = static_cast<KX_GameObject*>(pyother);
return PyFloat_FromDouble(NodeGetWorldPosition().distance(other->NodeGetWorldPosition()));
}
@@ -1781,12 +1574,11 @@ KX_PYMETHODDEF_DOC(KX_GameObject, getVectTo,
if (!PyVecArgTo(args, toPoint))
{
PyErr_Clear();
-
- KX_GameObject *other;
- if (PyArg_ParseTuple(args, "O", &pyother) && ConvertPythonToGameObject(pyother, &other, false))
+ if (PyArg_ParseTuple(args, "O!", &KX_GameObject::Type, &pyother))
{
+ KX_GameObject *other = static_cast<KX_GameObject*>(pyother);
toPoint = other->NodeGetWorldPosition();
- } else
+ }else
{
PyErr_SetString(PyExc_TypeError, "Expected a 3D Vector or GameObject type");
return NULL;
@@ -1816,45 +1608,25 @@ KX_PYMETHODDEF_DOC(KX_GameObject, getVectTo,
return returnValue;
}
-bool KX_GameObject::RayHit(KX_ClientObjectInfo* client, KX_RayCast* result, void * const data)
+bool KX_GameObject::RayHit(KX_ClientObjectInfo* client, MT_Point3& hit_point, MT_Vector3& hit_normal, void * const data)
{
- 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 (m_xray || m_testPropName.Length() == 0 || hitKXObj->GetProperty(m_testPropName) != NULL)
- {
- m_pHitObject = 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)
-{
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);
+ // false hit
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 (!m_xray || m_testPropName.Length() == 0 || hitKXObj->GetProperty(m_testPropName) != NULL)
+
+ if (m_testPropName.Length() == 0 || hitKXObj->GetProperty(m_testPropName) != NULL)
{
+ m_pHitObject = hitKXObj;
return true;
}
- // skip the object
+
return false;
+
}
KX_PYMETHODDEF_DOC(KX_GameObject, rayCastTo,
@@ -1876,15 +1648,12 @@ KX_PYMETHODDEF_DOC(KX_GameObject, rayCastTo,
{
KX_GameObject *other;
PyErr_Clear();
-
- if (ConvertPythonToGameObject(pyarg, &other, false))
- {
- toPoint = other->NodeGetWorldPosition();
- } else
- {
+ if (!PyType_IsSubtype(pyarg->ob_type, &KX_GameObject::Type)) {
PyErr_SetString(PyExc_TypeError, "the first argument to rayCastTo must be a vector or a KX_GameObject");
return NULL;
}
+ other = static_cast<KX_GameObject*>(pyarg);
+ toPoint = other->NodeGetWorldPosition();
}
MT_Point3 fromPoint = NodeGetWorldPosition();
if (dist != 0.0f)
@@ -1894,6 +1663,8 @@ KX_PYMETHODDEF_DOC(KX_GameObject, rayCastTo,
toPoint = fromPoint + (dist) * toDir;
}
+ MT_Point3 resultPoint;
+ MT_Vector3 resultNormal;
PHY_IPhysicsEnvironment* pe = GetPhysicsEnvironment();
KX_IPhysicsController *spc = GetPhysicsController();
KX_GameObject *parent = GetParent();
@@ -1907,8 +1678,7 @@ KX_PYMETHODDEF_DOC(KX_GameObject, rayCastTo,
m_testPropName = propName;
else
m_testPropName.SetLength(0);
- KX_RayCast::Callback<KX_GameObject> callback(this,spc);
- KX_RayCast::RayTest(pe, fromPoint, toPoint, callback);
+ KX_RayCast::RayTest(spc, pe, fromPoint, toPoint, resultPoint, resultNormal, KX_RayCast::Callback<KX_GameObject>(this));
if (m_pHitObject)
{
@@ -1919,24 +1689,13 @@ KX_PYMETHODDEF_DOC(KX_GameObject, rayCastTo,
}
KX_PYMETHODDEF_DOC(KX_GameObject, rayCast,
- "rayCast(to,from,dist,prop,face,xray,poly): cast a ray and return 3-tuple (object,hit,normal) or 4-tuple (object,hit,normal,polygon) of contact point with object within dist that matches prop.\n"
- " If no hit, return (None,None,None) or (None,None,None,None).\n"
-" to = 3-tuple or object reference for destination of ray (if object, use center of object)\n"
+ "rayCast(to,from,dist,prop): cast a ray and return tuple (object,hit,normal) of contact point with object within dist that matches prop or (None,None,None) tuple if no hit\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 to\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"
-" If 0 or omitted, return value is a 3-tuple\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")
+" to = 3-tuple or object reference for destination of ray (if object, use center of object)\n"
+"Note: the object on which you call this method matters: the ray will ignore it if it goes through it\n")
{
MT_Point3 toPoint;
MT_Point3 fromPoint;
@@ -1945,24 +1704,20 @@ KX_PYMETHODDEF_DOC(KX_GameObject, rayCast,
float dist = 0.0f;
char *propName = NULL;
KX_GameObject *other;
- int face=0, xray=0, poly=0;
- if (!PyArg_ParseTuple(args,"O|Ofsiii", &pyto, &pyfrom, &dist, &propName, &face, &xray, &poly)) {
+ if (!PyArg_ParseTuple(args,"O|Ofs", &pyto, &pyfrom, &dist, &propName)) {
return NULL; // Python sets a simple error
}
if (!PyVecTo(pyto, toPoint))
{
PyErr_Clear();
-
- if (ConvertPythonToGameObject(pyto, &other, false))
- {
- toPoint = other->NodeGetWorldPosition();
- } else
- {
+ if (!PyType_IsSubtype(pyto->ob_type, &KX_GameObject::Type)) {
PyErr_SetString(PyExc_TypeError, "the first argument to rayCast must be a vector or a KX_GameObject");
return NULL;
}
+ other = static_cast<KX_GameObject*>(pyto);
+ toPoint = other->NodeGetWorldPosition();
}
if (!pyfrom || pyfrom == Py_None)
{
@@ -1971,15 +1726,12 @@ KX_PYMETHODDEF_DOC(KX_GameObject, rayCast,
else if (!PyVecTo(pyfrom, fromPoint))
{
PyErr_Clear();
-
- if (ConvertPythonToGameObject(pyfrom, &other, false))
- {
- fromPoint = other->NodeGetWorldPosition();
- } else
- {
+ if (!PyType_IsSubtype(pyfrom->ob_type, &KX_GameObject::Type)) {
PyErr_SetString(PyExc_TypeError, "the second optional argument to rayCast must be a vector or a KX_GameObject");
return NULL;
}
+ other = static_cast<KX_GameObject*>(pyfrom);
+ fromPoint = other->NodeGetWorldPosition();
}
if (dist != 0.0f) {
@@ -1993,6 +1745,8 @@ KX_PYMETHODDEF_DOC(KX_GameObject, rayCast,
return Py_BuildValue("OOO", Py_None, Py_None, Py_None);
}
+ MT_Point3 resultPoint;
+ MT_Vector3 resultNormal;
PHY_IPhysicsEnvironment* pe = GetPhysicsEnvironment();
KX_IPhysicsController *spc = GetPhysicsController();
KX_GameObject *parent = GetParent();
@@ -2006,41 +1760,20 @@ KX_PYMETHODDEF_DOC(KX_GameObject, rayCast,
m_testPropName = propName;
else
m_testPropName.SetLength(0);
- m_xray = xray;
- // to get the hit results
- KX_RayCast::Callback<KX_GameObject> callback(this,spc,NULL,face);
- KX_RayCast::RayTest(pe, fromPoint, toPoint, callback);
+ KX_RayCast::RayTest(spc, pe, fromPoint, toPoint, resultPoint, resultNormal, KX_RayCast::Callback<KX_GameObject>(this));
- if (m_pHitObject)
+ if (m_pHitObject)
{
- PyObject* returnValue = (poly) ? PyTuple_New(4) : PyTuple_New(3);
+ PyObject* returnValue = PyTuple_New(3);
if (returnValue) { // unlikely this would ever fail, if it does python sets an error
PyTuple_SET_ITEM(returnValue, 0, m_pHitObject->AddRef());
- 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* poly = callback.m_hitMesh->GetPolygon(callback.m_hitPolygon);
- KX_PolyProxy* polyproxy = new KX_PolyProxy(callback.m_hitMesh, poly);
- PyTuple_SET_ITEM(returnValue, 3, polyproxy);
- }
- else
- {
- Py_INCREF(Py_None);
- PyTuple_SET_ITEM(returnValue, 3, Py_None);
- }
- }
+ PyTuple_SET_ITEM(returnValue, 1, PyObjectFrom(resultPoint));
+ PyTuple_SET_ITEM(returnValue, 2, PyObjectFrom(resultNormal));
}
return returnValue;
}
- // no hit
- if (poly)
- return Py_BuildValue("OOOO", Py_None, Py_None, Py_None, Py_None);
- else
- return Py_BuildValue("OOO", Py_None, Py_None, Py_None);
+ return Py_BuildValue("OOO", Py_None, Py_None, Py_None);
+ //Py_RETURN_NONE;
}
/* ---------------------------------------------------------------------
@@ -2065,48 +1798,3 @@ void KX_GameObject::Relink(GEN_Map<GEN_HashedPtr, void*> *map_parameter)
}
}
-bool ConvertPythonToGameObject(PyObject * value, KX_GameObject **object, bool py_none_ok)
-{
- if (value==NULL) {
- PyErr_SetString(PyExc_TypeError, "Error in ConvertPythonToGameObject, python pointer NULL, should never happen");
- *object = NULL;
- return false;
- }
-
- if (value==Py_None) {
- *object = NULL;
-
- if (py_none_ok) {
- return true;
- } else {
- PyErr_SetString(PyExc_TypeError, "Expected KX_GameObject or a string for a name of a KX_GameObject, None is invalid");
- return false;
- }
- }
-
- if (PyString_Check(value)) {
- *object = (KX_GameObject *)SCA_ILogicBrick::m_sCurrentLogicManager->GetGameObjectByName(STR_String( PyString_AsString(value) ));
-
- if (*object) {
- return true;
- } else {
- PyErr_SetString(PyExc_ValueError, "Requested name did not match any KX_GameObject");
- return false;
- }
- }
-
- if (PyObject_TypeCheck(value, &KX_GameObject::Type)) {
- *object = static_cast<KX_GameObject*>(value);
- return true;
- }
-
- *object = NULL;
-
- if (py_none_ok) {
- PyErr_SetString(PyExc_TypeError, "Expect a KX_GameObject, a string or None");
- } else {
- PyErr_SetString(PyExc_TypeError, "Expect a KX_GameObject or a string");
- }
-
- return false;
-}
diff --git a/source/gameengine/Ketsji/KX_GameObject.h b/source/gameengine/Ketsji/KX_GameObject.h
index 4f26031356f..4e435e9ddf4 100644
--- a/source/gameengine/Ketsji/KX_GameObject.h
+++ b/source/gameengine/Ketsji/KX_GameObject.h
@@ -48,13 +48,11 @@
#include "KX_KetsjiEngine.h" /* for m_anim_framerate */
#include "KX_IPhysicsController.h" /* for suspend/resume */
#include "DNA_object_types.h"
-#include "SCA_LogicManager.h" /* for ConvertPythonToGameObject to search object names */
#define KX_OB_DYNAMIC 1
//Forward declarations.
struct KX_ClientObjectInfo;
-class KX_RayCast;
class RAS_MeshObject;
class KX_IPhysicsController;
class PHY_IPhysicsEnvironment;
@@ -75,23 +73,20 @@ protected:
int m_layer;
std::vector<RAS_MeshObject*> m_meshes;
struct Object* m_pBlenderObject;
- struct Object* m_pBlenderGroupObject;
bool m_bSuspendDynamics;
bool m_bUseObjectColor;
bool m_bIsNegativeScaling;
MT_Vector4 m_objectColor;
- // visible = user setting
- // culled = while rendering, depending on camera
- bool m_bVisible;
- bool m_bCulled;
+ // Is this object set to be visible? Only useful for the
+ // visibility subsystem right now.
+ bool m_bVisible;
KX_IPhysicsController* m_pPhysicsController1;
// used for ray casting
PHY_IPhysicsEnvironment* m_pPhysicsEnvironment;
STR_String m_testPropName;
- bool m_xray;
KX_GameObject* m_pHitObject;
SG_Node* m_pSGNode;
@@ -264,15 +259,6 @@ public:
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
*/
@@ -341,14 +327,6 @@ public:
m_pPhysicsController1 = physicscontroller;
}
- virtual class RAS_Deformer* GetDeformer()
- {
- return 0;
- }
- virtual void SetDeformer(class RAS_Deformer* deformer)
- {
-
- }
/**
* @section Coordinate system manipulation functions
@@ -414,16 +392,6 @@ public:
{
m_pBlenderObject = obj;
}
-
- struct Object* GetBlenderGroupObject( )
- {
- return m_pBlenderGroupObject;
- }
-
- void SetBlenderGroupObject( struct Object* obj)
- {
- m_pBlenderGroupObject = obj;
- }
bool IsDupliGroup()
{
@@ -459,8 +427,7 @@ public:
return (m_pSGNode && m_pSGNode->GetSGParent() && m_pSGNode->GetSGParent()->IsVertexParent());
}
- bool RayHit(KX_ClientObjectInfo* client, KX_RayCast* result, void * const data);
- bool NeedRayCast(KX_ClientObjectInfo* client);
+ bool RayHit(KX_ClientObjectInfo* client, MT_Point3& hit_point, MT_Vector3& hit_normal, void * const data);
/**
@@ -567,23 +534,18 @@ public:
/**
* @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, .. .
+ * Run through the meshes associated with this
+ * object and bucketize them. See RAS_Mesh for
+ * more details on this function. Interesting to
+ * note that polygon bucketizing seems to happen on a per
+ * object basis. Which may explain why there is such
+ * a big performance gain when all static objects
+ * are joined into 1.
*/
void
- UpdateBuckets(
- bool recursive
+ Bucketize(
);
/**
@@ -644,38 +606,38 @@ public:
ResetDebugColor(
);
- /**
- * Was this object marked visible? (only for the explicit
- * visibility system).
+ /**
+ * Set the visibility of the meshes associated with this
+ * object.
*/
- bool
- GetVisible(
- void
+ void
+ MarkVisible(
+ bool visible
);
- /**
- * Set visibility flag of this object
+ /**
+ * Set the visibility according to the visibility flag.
*/
+ void
+ MarkVisible(
void
- SetVisible(
- bool b,
- bool recursive
);
/**
- * Was this object culled?
+ * Was this object marked visible? (only for the ewxplicit
+ * visibility system).
*/
bool
- GetCulled(
+ GetVisible(
void
);
/**
- * Set culled flag of this object
+ * Set visibility flag of this object
*/
void
- SetCulled(
- bool c
+ SetVisible(
+ bool b
);
/**
@@ -704,14 +666,6 @@ public:
) { return m_bIsNegativeScaling; }
/**
- * Is this a light?
- */
- virtual bool
- IsLight(
- void
- ) { return false; }
-
- /**
* @section Logic bubbling methods.
*/
@@ -771,41 +725,33 @@ public:
KX_PYMETHOD_NOARGS(KX_GameObject,GetPosition);
KX_PYMETHOD_O(KX_GameObject,SetPosition);
- 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(KX_GameObject,GetLinearVelocity);
+ KX_PYMETHOD(KX_GameObject,SetLinearVelocity);
+ KX_PYMETHOD(KX_GameObject,GetVelocity);
KX_PYMETHOD_NOARGS(KX_GameObject,GetMass);
KX_PYMETHOD_NOARGS(KX_GameObject,GetReactionForce);
KX_PYMETHOD_NOARGS(KX_GameObject,GetOrientation);
KX_PYMETHOD_O(KX_GameObject,SetOrientation);
KX_PYMETHOD_NOARGS(KX_GameObject,GetVisible);
- KX_PYMETHOD_VARARGS(KX_GameObject,SetVisible);
+ KX_PYMETHOD_O(KX_GameObject,SetVisible);
KX_PYMETHOD_NOARGS(KX_GameObject,GetState);
KX_PYMETHOD_O(KX_GameObject,SetState);
- KX_PYMETHOD_VARARGS(KX_GameObject,AlignAxisToVect);
+ KX_PYMETHOD(KX_GameObject,AlignAxisToVect);
KX_PYMETHOD_O(KX_GameObject,GetAxisVect);
KX_PYMETHOD_NOARGS(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(KX_GameObject,ApplyImpulse);
KX_PYMETHOD_O(KX_GameObject,SetCollisionMargin);
KX_PYMETHOD_NOARGS(KX_GameObject,GetParent);
KX_PYMETHOD_O(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(KX_GameObject,GetMesh);
KX_PYMETHOD_NOARGS(KX_GameObject,GetPhysicsId);
KX_PYMETHOD_NOARGS(KX_GameObject,GetPropertyNames);
- KX_PYMETHOD_O(KX_GameObject,ReplaceMesh);
KX_PYMETHOD_NOARGS(KX_GameObject,EndObject);
KX_PYMETHOD_DOC(KX_GameObject,rayCastTo);
KX_PYMETHOD_DOC(KX_GameObject,rayCast);
@@ -829,8 +775,5 @@ private :
};
-/* utility conversion function */
-bool ConvertPythonToGameObject(PyObject * value, KX_GameObject **object, bool py_none_ok);
-
#endif //__KX_GAMEOBJECT
diff --git a/source/gameengine/Ketsji/KX_IPO_SGController.cpp b/source/gameengine/Ketsji/KX_IPO_SGController.cpp
index 67d54cf0b0b..d3aa924665e 100644
--- a/source/gameengine/Ketsji/KX_IPO_SGController.cpp
+++ b/source/gameengine/Ketsji/KX_IPO_SGController.cpp
@@ -59,9 +59,7 @@ KX_IpoSGController::KX_IpoSGController()
m_ipo_local(false),
m_modified(true),
m_ipo_start_initialized(false),
- m_ipotime(1.0),
- m_ipo_start_euler(0.0,0.0,0.0),
- m_ipo_euler_initialized(false)
+ m_ipotime(1.0)
{
m_game_object = NULL;
for (int i=0; i < KX_MAX_IPO_CHANNELS; i++)
@@ -138,11 +136,6 @@ bool KX_IpoSGController::Update(double currentTime)
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?
@@ -150,7 +143,7 @@ bool KX_IpoSGController::Update(double currentTime)
{
if (m_ipo_as_force == true)
{
- if (m_game_object && ob && m_game_object->GetPhysicsController())
+ if (m_game_object && ob)
{
m_game_object->GetPhysicsController()->ApplyForce(m_ipo_local ?
ob->GetWorldOrientation() * m_ipo_xform.GetPosition() :
@@ -206,87 +199,51 @@ bool KX_IpoSGController::Update(double currentTime)
ob->GetWorldOrientation() * m_ipo_xform.GetEulerAngles() :
m_ipo_xform.GetEulerAngles(), false);
}
- } else if (m_ipo_add) {
- if (m_ipo_start_initialized) {
- double yaw=0, pitch=0, roll=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];
+ } else {
+ double yaw=0, pitch=0, roll=0; //final Euler angles
+ double tempYaw=0, tempPitch=0, tempRoll=0; //temp holders
+ if (!m_ipo_add)
+ ob->GetLocalOrientation().getEuler(yaw, pitch, roll);
- //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];
+ //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] && m_ipo_start_initialized) {
+ if (!m_ipo_add)
+ m_ipo_start_orient.getEuler(tempYaw, tempPitch, tempRoll);
+ yaw = tempYaw + 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] && m_ipo_start_initialized) {
+ if (!m_ipo_add)
+ m_ipo_start_orient.getEuler(tempYaw, tempPitch, tempRoll);
+ pitch = tempPitch + 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] && m_ipo_start_initialized) {
+ if (!m_ipo_add)
+ m_ipo_start_orient.getEuler(tempYaw, tempPitch, tempRoll);
+ roll = tempRoll + m_ipo_xform.GetDeltaEulerAngles()[2];
+ }
+ if (m_ipo_add) {
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;
ob->SetLocalOrientation(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];
- }
+ } else {
ob->SetLocalOrientation(MT_Vector3(yaw, pitch, roll));
}
- } else if (m_ipo_start_initialized) {
- // only DROT, treat as Add
- double yaw=0, pitch=0, roll=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;
- ob->SetLocalOrientation(rotation);
}
}
//modifies scale?
diff --git a/source/gameengine/Ketsji/KX_IPO_SGController.h b/source/gameengine/Ketsji/KX_IPO_SGController.h
index 031b74294ce..0bd8980f11c 100644
--- a/source/gameengine/Ketsji/KX_IPO_SGController.h
+++ b/source/gameengine/Ketsji/KX_IPO_SGController.h
@@ -72,12 +72,6 @@ class KX_IpoSGController : public SG_Controller
/** 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 */
- class 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;
diff --git a/source/gameengine/Ketsji/KX_IPhysicsController.h b/source/gameengine/Ketsji/KX_IPhysicsController.h
index 4ea283e9f98..ecfdb8c4275 100644
--- a/source/gameengine/Ketsji/KX_IPhysicsController.h
+++ b/source/gameengine/Ketsji/KX_IPhysicsController.h
@@ -88,11 +88,7 @@ public:
m_bDyna = isDynamic;
}
- bool IsDyna(void) {
- return m_bDyna;
- }
- virtual MT_Scalar GetRadius()=0;
virtual void SetSumoTransform(bool nondynaonly)=0;
// todo: remove next line !
virtual void SetSimulatedTime(double time)=0;
diff --git a/source/gameengine/Ketsji/KX_ISceneConverter.h b/source/gameengine/Ketsji/KX_ISceneConverter.h
index 3709fa8c784..f069048cd3d 100644
--- a/source/gameengine/Ketsji/KX_ISceneConverter.h
+++ b/source/gameengine/Ketsji/KX_ISceneConverter.h
@@ -32,8 +32,6 @@
#include "STR_String.h"
#include "KX_Python.h"
-struct Scene;
-
class KX_ISceneConverter
{
@@ -79,8 +77,6 @@ public:
// use blender glsl materials
virtual void SetGLSLMaterials(bool val) =0;
virtual bool GetGLSLMaterials()=0;
-
- virtual struct Scene* GetBlenderSceneForName(const STR_String& name)=0;
};
#endif //__KX_ISCENECONVERTER_H
diff --git a/source/gameengine/Ketsji/KX_IpoActuator.cpp b/source/gameengine/Ketsji/KX_IpoActuator.cpp
index f5e17118ffb..af3add8a323 100644
--- a/source/gameengine/Ketsji/KX_IpoActuator.cpp
+++ b/source/gameengine/Ketsji/KX_IpoActuator.cpp
@@ -37,7 +37,6 @@
#include "KX_IpoActuator.h"
#include "KX_GameObject.h"
-#include "FloatValue.h"
#ifdef HAVE_CONFIG_H
#include <config.h>
@@ -63,7 +62,6 @@ STR_String KX_IpoActuator::S_KX_ACT_IPO_FROM_PROP_STRING = "FromProp";
KX_IpoActuator::KX_IpoActuator(SCA_IObject* gameobj,
const STR_String& propname,
- const STR_String& framePropname,
float starttime,
float endtime,
bool recurse,
@@ -80,7 +78,6 @@ KX_IpoActuator::KX_IpoActuator(SCA_IObject* gameobj,
m_localtime(starttime),
m_direction(1),
m_propname(propname),
- m_framepropname(framePropname),
m_ipo_as_force(ipo_as_force),
m_ipo_add(ipo_add),
m_ipo_local(ipo_local),
@@ -133,6 +130,7 @@ void KX_IpoActuator::SetStartTime(float curtime)
{
float direction = m_startframe < m_endframe ? 1.0f : -1.0f;
+ curtime = curtime - KX_KetsjiEngine::GetSuspendedDelta();
if (m_direction > 0)
m_starttime = curtime - direction*(m_localtime - m_startframe)/KX_KetsjiEngine::GetAnimFrameRate();
else
@@ -141,7 +139,7 @@ void KX_IpoActuator::SetStartTime(float curtime)
void KX_IpoActuator::SetLocalTime(float curtime)
{
- float delta_time = (curtime - m_starttime)*KX_KetsjiEngine::GetAnimFrameRate();
+ float delta_time = ((curtime - m_starttime) - KX_KetsjiEngine::GetSuspendedDelta())*KX_KetsjiEngine::GetAnimFrameRate();
// negative delta_time is caused by floating point inaccuracy
// perhaps the inaccuracy could be reduced a bit
@@ -167,8 +165,6 @@ bool KX_IpoActuator::Update(double curtime, bool frame)
int numevents = 0;
bool bIpoStart = false;
- curtime -= KX_KetsjiEngine::GetSuspendedDelta();
-
if (frame)
{
numevents = m_events.size();
@@ -184,7 +180,7 @@ bool KX_IpoActuator::Update(double curtime, bool frame)
if (m_starttime < -2.0f*start_smaller_then_end*(m_endframe - m_startframe))
{
// start for all Ipo, initial start for LOOP_STOP
- m_starttime = curtime;
+ m_starttime = curtime - KX_KetsjiEngine::GetSuspendedDelta();
m_bIpoPlaying = true;
bIpoStart = true;
}
@@ -359,20 +355,7 @@ bool KX_IpoActuator::Update(double curtime, bool frame)
default:
result = false;
}
-
- /* 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 (!result)
{
if (m_type != KX_ACT_IPO_LOOPSTOP)
@@ -440,20 +423,34 @@ PyParentObject KX_IpoActuator::Parents[] = {
};
PyMethodDef KX_IpoActuator::Methods[] = {
- {"set", (PyCFunction) KX_IpoActuator::sPySet, METH_VARARGS, (PY_METHODCHAR)Set_doc},
- {"setProperty", (PyCFunction) KX_IpoActuator::sPySetProperty, METH_VARARGS, (PY_METHODCHAR)SetProperty_doc},
- {"setStart", (PyCFunction) KX_IpoActuator::sPySetStart, METH_VARARGS, (PY_METHODCHAR)SetStart_doc},
- {"getStart", (PyCFunction) KX_IpoActuator::sPyGetStart, METH_NOARGS, (PY_METHODCHAR)GetStart_doc},
- {"setEnd", (PyCFunction) KX_IpoActuator::sPySetEnd, METH_VARARGS, (PY_METHODCHAR)SetEnd_doc},
- {"getEnd", (PyCFunction) KX_IpoActuator::sPyGetEnd, METH_NOARGS, (PY_METHODCHAR)GetEnd_doc},
- {"setIpoAsForce", (PyCFunction) KX_IpoActuator::sPySetIpoAsForce, METH_VARARGS, (PY_METHODCHAR)SetIpoAsForce_doc},
- {"getIpoAsForce", (PyCFunction) KX_IpoActuator::sPyGetIpoAsForce, METH_NOARGS, (PY_METHODCHAR)GetIpoAsForce_doc},
- {"setIpoAdd", (PyCFunction) KX_IpoActuator::sPySetIpoAdd, METH_VARARGS, (PY_METHODCHAR)SetIpoAdd_doc},
- {"getIpoAdd", (PyCFunction) KX_IpoActuator::sPyGetIpoAdd, METH_NOARGS, (PY_METHODCHAR)GetIpoAdd_doc},
- {"setType", (PyCFunction) KX_IpoActuator::sPySetType, METH_VARARGS, (PY_METHODCHAR)SetType_doc},
- {"getType", (PyCFunction) KX_IpoActuator::sPyGetType, METH_NOARGS, (PY_METHODCHAR)GetType_doc},
- {"setForceIpoActsLocal", (PyCFunction) KX_IpoActuator::sPySetForceIpoActsLocal, METH_VARARGS, (PY_METHODCHAR)SetForceIpoActsLocal_doc},
- {"getForceIpoActsLocal", (PyCFunction) KX_IpoActuator::sPyGetForceIpoActsLocal, METH_NOARGS, (PY_METHODCHAR)GetForceIpoActsLocal_doc},
+ {"set", (PyCFunction) KX_IpoActuator::sPySet,
+ METH_VARARGS, Set_doc},
+ {"setProperty", (PyCFunction) KX_IpoActuator::sPySetProperty,
+ METH_VARARGS, SetProperty_doc},
+ {"setStart", (PyCFunction) KX_IpoActuator::sPySetStart,
+ METH_VARARGS, SetStart_doc},
+ {"getStart", (PyCFunction) KX_IpoActuator::sPyGetStart,
+ METH_NOARGS, GetStart_doc},
+ {"setEnd", (PyCFunction) KX_IpoActuator::sPySetEnd,
+ METH_VARARGS, SetEnd_doc},
+ {"getEnd", (PyCFunction) KX_IpoActuator::sPyGetEnd,
+ METH_NOARGS, GetEnd_doc},
+ {"setIpoAsForce", (PyCFunction) KX_IpoActuator::sPySetIpoAsForce,
+ METH_VARARGS, SetIpoAsForce_doc},
+ {"getIpoAsForce", (PyCFunction) KX_IpoActuator::sPyGetIpoAsForce,
+ METH_NOARGS, GetIpoAsForce_doc},
+ {"setIpoAdd", (PyCFunction) KX_IpoActuator::sPySetIpoAdd,
+ METH_VARARGS, SetIpoAdd_doc},
+ {"getIpoAdd", (PyCFunction) KX_IpoActuator::sPyGetIpoAdd,
+ METH_NOARGS, GetIpoAdd_doc},
+ {"setType", (PyCFunction) KX_IpoActuator::sPySetType,
+ METH_VARARGS, SetType_doc},
+ {"getType", (PyCFunction) KX_IpoActuator::sPyGetType,
+ METH_NOARGS, GetType_doc},
+ {"setForceIpoActsLocal", (PyCFunction) KX_IpoActuator::sPySetForceIpoActsLocal,
+ METH_VARARGS, SetForceIpoActsLocal_doc},
+ {"getForceIpoActsLocal", (PyCFunction) KX_IpoActuator::sPyGetForceIpoActsLocal,
+ METH_NOARGS, GetForceIpoActsLocal_doc},
{NULL,NULL} //Sentinel
};
@@ -464,7 +461,7 @@ PyObject* KX_IpoActuator::_getattr(const STR_String& attr) {
/* set --------------------------------------------------------------------- */
-const char KX_IpoActuator::Set_doc[] =
+char KX_IpoActuator::Set_doc[] =
"set(type, startframe, endframe, mode?)\n"
"\t - type: Play, PingPong, Flipper, LoopStop, LoopEnd or FromProp (string)\n"
"\t - startframe: first frame to use (int)\n"
@@ -483,6 +480,7 @@ PyObject* KX_IpoActuator::PySet(PyObject* self,
int startFrame, stopFrame;
if(!PyArg_ParseTuple(args, "siii", &mode, &startFrame,
&stopFrame, &forceToggle)) {
+ PyErr_SetString(PyExc_TypeError, "Invalid arguments");
return NULL;
}
modenum = string2mode(mode);
@@ -507,7 +505,7 @@ PyObject* KX_IpoActuator::PySet(PyObject* self,
}
/* set property ----------------------------------------------------------- */
-const char KX_IpoActuator::SetProperty_doc[] =
+char KX_IpoActuator::SetProperty_doc[] =
"setProperty(propname)\n"
"\t - propname: name of the property (string)\n"
"\tSet the property to be used in FromProp mode.\n";
@@ -518,6 +516,7 @@ PyObject* KX_IpoActuator::PySetProperty(PyObject* self,
/* args: property */
char *propertyName;
if(!PyArg_ParseTuple(args, "s", &propertyName)) {
+ PyErr_SetString(PyExc_TypeError, "Invalid arguments");
return NULL;
}
@@ -527,7 +526,7 @@ PyObject* KX_IpoActuator::PySetProperty(PyObject* self,
}
/* 4. setStart: */
-const char KX_IpoActuator::SetStart_doc[] =
+char KX_IpoActuator::SetStart_doc[] =
"setStart(frame)\n"
"\t - frame: first frame to use (int)\n"
"\tSet the frame from which the ipo starts playing.\n";
@@ -536,6 +535,7 @@ PyObject* KX_IpoActuator::PySetStart(PyObject* self,
PyObject* kwds) {
float startArg;
if(!PyArg_ParseTuple(args, "f", &startArg)) {
+ PyErr_SetString(PyExc_TypeError, "Invalid arguments");
return NULL;
}
@@ -544,7 +544,7 @@ PyObject* KX_IpoActuator::PySetStart(PyObject* self,
Py_Return;
}
/* 5. getStart: */
-const char KX_IpoActuator::GetStart_doc[] =
+char KX_IpoActuator::GetStart_doc[] =
"getStart()\n"
"\tReturns the frame from which the ipo starts playing.\n";
PyObject* KX_IpoActuator::PyGetStart(PyObject* self) {
@@ -552,7 +552,7 @@ PyObject* KX_IpoActuator::PyGetStart(PyObject* self) {
}
/* 6. setEnd: */
-const char KX_IpoActuator::SetEnd_doc[] =
+char KX_IpoActuator::SetEnd_doc[] =
"setEnd(frame)\n"
"\t - frame: last frame to use (int)\n"
"\tSet the frame at which the ipo stops playing.\n";
@@ -561,6 +561,7 @@ PyObject* KX_IpoActuator::PySetEnd(PyObject* self,
PyObject* kwds) {
float endArg;
if(!PyArg_ParseTuple(args, "f", &endArg)) {
+ PyErr_SetString(PyExc_TypeError, "Invalid arguments");
return NULL;
}
@@ -569,7 +570,7 @@ PyObject* KX_IpoActuator::PySetEnd(PyObject* self,
Py_Return;
}
/* 7. getEnd: */
-const char KX_IpoActuator::GetEnd_doc[] =
+char KX_IpoActuator::GetEnd_doc[] =
"getEnd()\n"
"\tReturns the frame at which the ipo stops playing.\n";
PyObject* KX_IpoActuator::PyGetEnd(PyObject* self) {
@@ -577,7 +578,7 @@ PyObject* KX_IpoActuator::PyGetEnd(PyObject* self) {
}
/* 6. setIpoAsForce: */
-const char KX_IpoActuator::SetIpoAsForce_doc[] =
+char KX_IpoActuator::SetIpoAsForce_doc[] =
"setIpoAsForce(force?)\n"
"\t - force? : interpret this ipo as a force? (KX_TRUE, KX_FALSE)\n"
"\tSet whether to interpret the ipo as a force rather than a displacement.\n";
@@ -587,6 +588,7 @@ PyObject* KX_IpoActuator::PySetIpoAsForce(PyObject* self,
int boolArg;
if (!PyArg_ParseTuple(args, "i", &boolArg)) {
+ PyErr_SetString(PyExc_TypeError, "Invalid arguments");
return NULL;
}
@@ -597,7 +599,7 @@ PyObject* KX_IpoActuator::PySetIpoAsForce(PyObject* self,
Py_Return;
}
/* 7. getIpoAsForce: */
-const char KX_IpoActuator::GetIpoAsForce_doc[] =
+char KX_IpoActuator::GetIpoAsForce_doc[] =
"getIpoAsForce()\n"
"\tReturns whether to interpret the ipo as a force rather than a displacement.\n";
PyObject* KX_IpoActuator::PyGetIpoAsForce(PyObject* self) {
@@ -605,7 +607,7 @@ PyObject* KX_IpoActuator::PyGetIpoAsForce(PyObject* self) {
}
/* 6. setIpoAsForce: */
-const char KX_IpoActuator::SetIpoAdd_doc[] =
+char KX_IpoActuator::SetIpoAdd_doc[] =
"setIpoAdd(add?)\n"
"\t - add? : add flag (KX_TRUE, KX_FALSE)\n"
"\tSet whether to interpret the ipo as additive rather than absolute.\n";
@@ -615,6 +617,7 @@ PyObject* KX_IpoActuator::PySetIpoAdd(PyObject* self,
int boolArg;
if (!PyArg_ParseTuple(args, "i", &boolArg)) {
+ PyErr_SetString(PyExc_TypeError, "Invalid arguments");
return NULL;
}
@@ -625,7 +628,7 @@ PyObject* KX_IpoActuator::PySetIpoAdd(PyObject* self,
Py_Return;
}
/* 7. getIpoAsForce: */
-const char KX_IpoActuator::GetIpoAdd_doc[] =
+char KX_IpoActuator::GetIpoAdd_doc[] =
"getIpoAsAdd()\n"
"\tReturns whether to interpret the ipo as additive rather than absolute.\n";
PyObject* KX_IpoActuator::PyGetIpoAdd(PyObject* self) {
@@ -633,7 +636,7 @@ PyObject* KX_IpoActuator::PyGetIpoAdd(PyObject* self) {
}
/* 8. setType: */
-const char KX_IpoActuator::SetType_doc[] =
+char KX_IpoActuator::SetType_doc[] =
"setType(mode)\n"
"\t - mode: Play, PingPong, Flipper, LoopStop, LoopEnd or FromProp (string)\n"
"\tSet the operation mode of the actuator.\n";
@@ -643,6 +646,7 @@ PyObject* KX_IpoActuator::PySetType(PyObject* self,
int typeArg;
if (!PyArg_ParseTuple(args, "i", &typeArg)) {
+ PyErr_SetString(PyExc_TypeError, "Invalid arguments");
return NULL;
}
@@ -654,7 +658,7 @@ PyObject* KX_IpoActuator::PySetType(PyObject* self,
Py_Return;
}
/* 9. getType: */
-const char KX_IpoActuator::GetType_doc[] =
+char KX_IpoActuator::GetType_doc[] =
"getType()\n"
"\tReturns the operation mode of the actuator.\n";
PyObject* KX_IpoActuator::PyGetType(PyObject* self) {
@@ -662,7 +666,7 @@ PyObject* KX_IpoActuator::PyGetType(PyObject* self) {
}
/* 10. setForceIpoActsLocal: */
-const char KX_IpoActuator::SetForceIpoActsLocal_doc[] =
+char KX_IpoActuator::SetForceIpoActsLocal_doc[] =
"setForceIpoActsLocal(local?)\n"
"\t - local? : Apply the ipo-as-force in the object's local\n"
"\t coordinates? (KX_TRUE, KX_FALSE)\n"
@@ -674,6 +678,7 @@ PyObject* KX_IpoActuator::PySetForceIpoActsLocal(PyObject* self,
int boolArg;
if (!PyArg_ParseTuple(args, "i", &boolArg)) {
+ PyErr_SetString(PyExc_TypeError, "Invalid arguments");
return NULL;
}
@@ -682,7 +687,7 @@ PyObject* KX_IpoActuator::PySetForceIpoActsLocal(PyObject* self,
Py_Return;
}
/* 11. getForceIpoActsLocal: */
-const char KX_IpoActuator::GetForceIpoActsLocal_doc[] =
+char KX_IpoActuator::GetForceIpoActsLocal_doc[] =
"getForceIpoActsLocal()\n"
"\tReturn whether to apply the force in the object's local\n"
"\tcoordinates rather than the world global coordinates.\n";
diff --git a/source/gameengine/Ketsji/KX_IpoActuator.h b/source/gameengine/Ketsji/KX_IpoActuator.h
index 8e5baed0530..d6f52f8d59d 100644
--- a/source/gameengine/Ketsji/KX_IpoActuator.h
+++ b/source/gameengine/Ketsji/KX_IpoActuator.h
@@ -72,9 +72,6 @@ protected:
/** Name of the property (only used in from_prop mode). */
STR_String m_propname;
- /** Name of the property where we write the current frame number */
- STR_String m_framepropname;
-
/** Interpret the ipo as a force? */
bool m_ipo_as_force;
@@ -114,7 +111,6 @@ public:
KX_IpoActuator(SCA_IObject* gameobj,
const STR_String& propname,
- const STR_String& framePropname,
float starttime,
float endtime,
bool recurse,
diff --git a/source/gameengine/Ketsji/KX_KetsjiEngine.cpp b/source/gameengine/Ketsji/KX_KetsjiEngine.cpp
index 8bcda4479e1..1d6cc975ab5 100644
--- a/source/gameengine/Ketsji/KX_KetsjiEngine.cpp
+++ b/source/gameengine/Ketsji/KX_KetsjiEngine.cpp
@@ -96,7 +96,6 @@ double KX_KetsjiEngine::m_ticrate = DEFAULT_LOGIC_TIC_RATE;
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;
/**
@@ -135,8 +134,6 @@ KX_KetsjiEngine::KX_KetsjiEngine(KX_ISystem* system)
m_overrideCam(false),
m_overrideCamUseOrtho(false),
- m_overrideCamNear(0.0),
- m_overrideCamFar(0.0),
m_stereo(false),
m_curreye(0),
@@ -278,73 +275,30 @@ void KX_KetsjiEngine::StartEngine(bool clearIpo)
}
-void KX_KetsjiEngine::ClearFrame()
+bool KX_KetsjiEngine::BeginFrame()
{
- // 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);
+ bool result = false;
- 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();
- SetBackGround(firstscene->GetWorldInfo());
-
- m_canvas->SetViewPort(clearvp.GetLeft(), clearvp.GetBottom(),
- clearvp.GetRight(), clearvp.GetTop());
- m_rasterizer->ClearColorBuffer();
- }
-}
+ RAS_Rect vp;
+ KX_Scene* firstscene = *m_scenes.begin();
+ const RAS_FrameSettings &framesettings = firstscene->GetFramingType();
-bool KX_KetsjiEngine::BeginFrame()
-{
- // set the area used for rendering (stereo can assign only a subset)
+ // set the area used for rendering
m_rasterizer->SetRenderArea();
+ RAS_FramingManager::ComputeViewport(framesettings, m_canvas->GetDisplayArea(), vp);
+
if (m_canvas->BeginDraw())
{
- ClearFrame();
-
- m_rasterizer->BeginFrame(m_drawingmode , m_kxsystem->GetTimeInSeconds());
- m_rendertools->BeginFrame(m_rasterizer);
+ result = true;
- return true;
+ m_canvas->SetViewPort(vp.GetLeft(), vp.GetBottom(), vp.GetRight(), vp.GetTop());
+ SetBackGround( firstscene->GetWorldInfo() );
+ m_rasterizer->BeginFrame( m_drawingmode , m_kxsystem->GetTimeInSeconds());
+ m_rendertools->BeginFrame( m_rasterizer);
}
- return false;
+ return result;
}
@@ -356,12 +310,6 @@ void KX_KetsjiEngine::EndFrame()
{
RenderDebugProperties();
}
-
- m_average_framerate = m_logger->GetAverage();
- if (m_average_framerate < 1e-6)
- m_average_framerate = 1e-6;
- m_average_framerate = 1.0/m_average_framerate;
-
// Go to next profiling measurement, time spend after this call is shown in the next frame.
m_logger->NextMeasurement(m_kxsystem->GetTimeInSeconds());
@@ -373,6 +321,8 @@ void KX_KetsjiEngine::EndFrame()
m_canvas->EndDraw();
+
+
}
//#include "PIL_time.h"
@@ -470,7 +420,7 @@ else
m_logger->StartLog(tc_physics, m_kxsystem->GetTimeInSeconds(), true);
// set Python hooks for each scene
PHY_SetActiveEnvironment(scene->GetPhysicsEnvironment());
- KX_SetActiveScene(scene);
+ PHY_SetActiveScene(scene);
scene->GetPhysicsEnvironment()->endFrame();
@@ -568,7 +518,7 @@ else
// set Python hooks for each scene
PHY_SetActiveEnvironment(scene->GetPhysicsEnvironment());
- KX_SetActiveScene(scene);
+ PHY_SetActiveScene(scene);
m_logger->StartLog(tc_scenegraph, m_kxsystem->GetTimeInSeconds(), true);
scene->UpdateParents(m_clockTime);
@@ -651,7 +601,7 @@ void KX_KetsjiEngine::Render()
);
}
// clear the -whole- viewport
- m_canvas->ClearBuffer(RAS_ICanvas::COLOR_BUFFER|RAS_ICanvas::DEPTH_BUFFER);
+ m_canvas->ClearBuffer(RAS_ICanvas::COLOR_BUFFER);
}
m_rasterizer->SetEye(RAS_IRasterizer::RAS_STEREO_LEFTEYE);
@@ -680,6 +630,9 @@ void KX_KetsjiEngine::Render()
m_rendertools->SetAuxilaryClientInfo(scene);
+ //Initialize scene viewport.
+ SetupRenderFrame(scene, cam);
+
// do the rendering
RenderFrame(scene, cam);
}
@@ -697,6 +650,9 @@ void KX_KetsjiEngine::Render()
m_rendertools->SetAuxilaryClientInfo(scene);
+ //Initialize scene viewport.
+ SetupRenderFrame(scene, (*it));
+
// do the rendering
RenderFrame(scene, (*it));
}
@@ -729,6 +685,10 @@ void KX_KetsjiEngine::Render()
//pass the scene, for picking and raycasting (shadows)
m_rendertools->SetAuxilaryClientInfo(scene);
+ //Initialize scene viewport.
+ //SetupRenderFrame(scene);
+ SetupRenderFrame(scene, cam);
+
// do the rendering
//RenderFrame(scene);
RenderFrame(scene, cam);
@@ -888,13 +848,8 @@ void KX_KetsjiEngine::SetCameraOverrideViewMatrix(const MT_CmMatrix4x4& mat)
m_overrideCamViewMat = mat;
}
-void KX_KetsjiEngine::SetCameraOverrideClipping(float near, float far)
-{
- m_overrideCamNear = near;
- m_overrideCamFar = far;
-}
-
-void KX_KetsjiEngine::GetSceneViewport(KX_Scene *scene, KX_Camera* cam, RAS_Rect& area, RAS_Rect& viewport)
+
+void KX_KetsjiEngine::SetupRenderFrame(KX_Scene *scene, KX_Camera* cam)
{
// In this function we make sure the rasterizer settings are upto
// date. We compute the viewport so that logic
@@ -902,26 +857,17 @@ void KX_KetsjiEngine::GetSceneViewport(KX_Scene *scene, KX_Camera* cam, RAS_Rect
// 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_Rect viewport;
- RAS_FramingManager::ComputeViewport(
- scene->GetFramingType(),
- userviewport,
- viewport
- );
+ if (!cam)
+ return;
- area = userviewport;
+ if (cam->GetViewport()) {
+ viewport.SetLeft(cam->GetViewportLeft());
+ viewport.SetBottom(cam->GetViewportBottom());
+ viewport.SetRight(cam->GetViewportRight());
+ viewport.SetTop(cam->GetViewportTop());
}
else if ( m_overrideCam || (scene->GetName() != m_overrideSceneName) || m_overrideCamUseOrtho ) {
RAS_FramingManager::ComputeViewport(
@@ -929,32 +875,33 @@ void KX_KetsjiEngine::GetSceneViewport(KX_Scene *scene, KX_Camera* cam, RAS_Rect
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();
}
+ // 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()
+ );
+
}
void KX_KetsjiEngine::RenderShadowBuffers(KX_Scene *scene)
{
- CListValue *objectlist = scene->GetObjectList();
+ CListValue *lightlist = scene->GetLightList();
int i, drawmode;
- m_rendertools->SetAuxilaryClientInfo(scene);
-
- for(i=0; i<objectlist->GetCount(); i++) {
- KX_GameObject *gameobj = (KX_GameObject*)objectlist->GetValue(i);
-
- if(!gameobj->IsLight())
- continue;
-
- KX_LightObject *light = (KX_LightObject*)gameobj;
+ for(i=0; i<lightlist->GetCount(); i++) {
+ KX_LightObject *light = (KX_LightObject*)lightlist->GetValue(i);
light->Update();
@@ -992,32 +939,18 @@ void KX_KetsjiEngine::RenderShadowBuffers(KX_Scene *scene)
// update graphics
void KX_KetsjiEngine::RenderFrame(KX_Scene* scene, KX_Camera* cam)
{
- bool override_camera;
- RAS_Rect viewport, area;
float left, right, bottom, top, nearfrust, farfrust, focallength;
const float ortho = 100.0;
// KX_Camera* cam = scene->GetActiveCamera();
if (!cam)
return;
-
- 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) {
+ if (m_overrideCam && (scene->GetName() == m_overrideSceneName) && m_overrideCamUseOrtho) {
MT_CmMatrix4x4 projmat = m_overrideCamProjMat;
m_rasterizer->SetProjectionMatrix(projmat);
} else if (cam->hasValidProjectionMatrix() && !cam->GetViewport() )
@@ -1027,17 +960,12 @@ void KX_KetsjiEngine::RenderFrame(KX_Scene* scene, KX_Camera* cam)
{
RAS_FrameFrustum frustum;
float lens = cam->GetLens();
- bool orthographic = !cam->GetCameraData()->m_perspective;
nearfrust = cam->GetCameraNear();
farfrust = cam->GetCameraFar();
focallength = cam->GetFocalLength();
- if(override_camera) {
- nearfrust = m_overrideCamNear;
- farfrust = m_overrideCamFar;
- }
-
- if (orthographic) {
+ if (!cam->GetCameraData()->m_perspective)
+ {
lens *= ortho;
nearfrust = (nearfrust + 1.0)*ortho;
farfrust *= ortho;
@@ -1045,8 +973,8 @@ void KX_KetsjiEngine::RenderFrame(KX_Scene* scene, KX_Camera* cam)
RAS_FramingManager::ComputeFrustum(
scene->GetFramingType(),
- area,
- viewport,
+ m_canvas->GetDisplayArea(),
+ scene->GetSceneViewport(),
lens,
nearfrust,
farfrust,
@@ -1062,7 +990,7 @@ void KX_KetsjiEngine::RenderFrame(KX_Scene* scene, KX_Camera* cam)
MT_Matrix4x4 projmat = m_rasterizer->GetFrustumMatrix(
left, right, bottom, top, nearfrust, farfrust, focallength);
-
+
cam->SetProjectionMatrix(projmat);
// Otherwise the projection matrix for each eye will be the same...
@@ -1243,49 +1171,19 @@ void KX_KetsjiEngine::RenderDebugProperties()
CValue* propobj = (*it)->m_obj;
STR_String objname = propobj->GetName();
STR_String propname = (*it)->m_name;
- if (propname == "__state__")
+ CValue* propval = propobj->GetProperty(propname);
+ if (propval)
{
- // 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;
- }
- }
+ STR_String text = propval->GetText();
+ debugtxt = objname + "." + propname + " = " + text;
m_rendertools->RenderText2D(RAS_IRenderTools::RAS_TEXT_PADDED,
- debugtxt.Ptr(),
- xcoord,
- ycoord,
- m_canvas->GetWidth(),
- m_canvas->GetHeight());
+ debugtxt.Ptr(),
+ xcoord,
+ ycoord,
+ m_canvas->GetWidth(),
+ m_canvas->GetHeight());
ycoord += 14;
}
- else
- {
- CValue* propval = propobj->GetProperty(propname);
- if (propval)
- {
- STR_String text = propval->GetText();
- debugtxt = objname + "." + propname + " = " + text;
- m_rendertools->RenderText2D(RAS_IRenderTools::RAS_TEXT_PADDED,
- debugtxt.Ptr(),
- xcoord,
- ycoord,
- m_canvas->GetWidth(),
- m_canvas->GetHeight());
- ycoord += 14;
- }
- }
}
}
}
@@ -1383,13 +1281,12 @@ void KX_KetsjiEngine::RemoveScheduledScenes()
KX_Scene* KX_KetsjiEngine::CreateScene(const STR_String& scenename)
{
- Scene *scene = m_sceneconverter->GetBlenderSceneForName(scenename);
+
KX_Scene* tmpscene = new KX_Scene(m_keyboarddevice,
m_mousedevice,
m_networkdevice,
m_audiodevice,
- scenename,
- scene);
+ scenename);
m_sceneconverter->ConvertScene(scenename,
tmpscene,
@@ -1540,21 +1437,11 @@ double KX_KetsjiEngine::GetAnimFrameRate()
return m_anim_framerate;
}
-double KX_KetsjiEngine::GetClockTime(void) const
-{
- return m_clockTime;
-}
-
void KX_KetsjiEngine::SetAnimFrameRate(double framerate)
{
m_anim_framerate = framerate;
}
-double KX_KetsjiEngine::GetAverageFrameRate()
-{
- return m_average_framerate;
-}
-
void KX_KetsjiEngine::SetTimingDisplay(bool frameRate, bool profile, bool properties)
{
m_show_framerate = frameRate;
diff --git a/source/gameengine/Ketsji/KX_KetsjiEngine.h b/source/gameengine/Ketsji/KX_KetsjiEngine.h
index 8516049f6d8..77b69ec2d9e 100644
--- a/source/gameengine/Ketsji/KX_KetsjiEngine.h
+++ b/source/gameengine/Ketsji/KX_KetsjiEngine.h
@@ -124,8 +124,6 @@ private:
bool m_overrideCamUseOrtho;
MT_CmMatrix4x4 m_overrideCamProjMat;
MT_CmMatrix4x4 m_overrideCamViewMat;
- float m_overrideCamNear;
- float m_overrideCamFar;
bool m_stereo;
int m_curreye;
@@ -151,8 +149,6 @@ private:
/** 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? */
@@ -179,11 +175,13 @@ private:
/** Blue component of framing bar color. */
float m_overrideFrameColorB;
+ void SetupRenderFrame(KX_Scene *scene, KX_Camera* cam);
void RenderFrame(KX_Scene* scene, KX_Camera* cam);
void PostRenderFrame();
void RenderDebugProperties();
void RenderShadowBuffers(KX_Scene *scene);
void SetBackGround(KX_WorldInfo* worldinfo);
+ void SetWorldSettings(KX_WorldInfo* worldinfo);
void DoSound(KX_Scene* scene);
public:
@@ -192,7 +190,6 @@ public:
virtual ~KX_KetsjiEngine();
// set the devices and stuff. the client must take care of creating these
- void SetWorldSettings(KX_WorldInfo* worldinfo);
void SetKeyboardDevice(SCA_IInputDevice* keyboarddevice);
void SetMouseDevice(SCA_IInputDevice* mousedevice);
void SetNetworkDevice(NG_NetworkDeviceInterface* networkdevice);
@@ -205,8 +202,6 @@ public:
void SetGame2IpoMode(bool game2ipo,int startFrame);
RAS_IRasterizer* GetRasterizer(){return m_rasterizer;};
- RAS_ICanvas* GetCanvas(){return m_canvas;};
- RAS_IRenderTools* GetRenderTools(){return m_rendertools;};
///returns true if an update happened to indicate -> Render
bool NextFrame();
@@ -231,8 +226,6 @@ public:
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);
-
void SetDrawType(int drawingtype);
void SetCameraZoom(float camzoom);
@@ -241,7 +234,6 @@ public:
void SetCameraOverrideUseOrtho(bool useOrtho);
void SetCameraOverrideProjectionMatrix(const MT_CmMatrix4x4& mat);
void SetCameraOverrideViewMatrix(const MT_CmMatrix4x4& mat);
- void SetCameraOverrideClipping(float near, float far);
/**
* Sets display of all frames.
@@ -256,11 +248,6 @@ public:
bool GetUseFixedTime(void) const;
/**
- * Returns current render frame clock time
- */
- double GetClockTime(void) const;
-
- /**
* Returns the difference between the local time of the scene (when it
* was running and not suspended) and the "curtime"
*/
@@ -285,11 +272,6 @@ public:
static void SetAnimFrameRate(double framerate);
/**
- * Gets the last estimated average framerate
- */
- static double GetAverageFrameRate();
-
- /**
* Activates or deactivates timing information display.
* @param frameRate Display for frame rate on or off.
* @param profile Display for individual components on or off.
@@ -366,7 +348,6 @@ protected:
KX_Scene* CreateScene(const STR_String& scenename);
bool BeginFrame();
- void ClearFrame();
void EndFrame();
};
diff --git a/source/gameengine/Ketsji/KX_Light.cpp b/source/gameengine/Ketsji/KX_Light.cpp
index e0f171e78e0..4e3d6180d22 100644
--- a/source/gameengine/Ketsji/KX_Light.cpp
+++ b/source/gameengine/Ketsji/KX_Light.cpp
@@ -42,13 +42,14 @@
#include "KX_PyMath.h"
-#include "DNA_object_types.h"
+#ifdef BLENDER_GLSL
#include "GPU_material.h"
+#endif
KX_LightObject::KX_LightObject(void* sgReplicationInfo,SG_Callbacks callbacks,
class RAS_IRenderTools* rendertools,
const RAS_LightObject& lightobj,
- bool glsl,
+ struct GPULamp *gpulamp,
PyTypeObject* T
)
:
@@ -58,20 +59,12 @@ KX_LightObject::KX_LightObject(void* sgReplicationInfo,SG_Callbacks callbacks,
m_lightobj = lightobj;
m_lightobj.m_worldmatrix = GetOpenGLMatrixPtr();
m_rendertools->AddLight(&m_lightobj);
- m_glsl = glsl;
- m_blenderscene = ((KX_Scene*)sgReplicationInfo)->GetBlenderScene();
+ m_gpulamp = gpulamp;
};
KX_LightObject::~KX_LightObject()
{
- GPULamp *lamp;
-
- if((lamp = GetGPULamp())) {
- float obmat[4][4] = {{0}};
- GPU_lamp_update(lamp, 0, obmat);
- }
-
m_rendertools->RemoveLight(&m_lightobj);
}
@@ -80,7 +73,7 @@ CValue* KX_LightObject::GetReplica()
{
KX_LightObject* replica = new KX_LightObject(*this);
-
+
// this will copy properties and so on...
CValue::AddDataToReplica(replica);
@@ -88,23 +81,13 @@ CValue* KX_LightObject::GetReplica()
replica->m_lightobj.m_worldmatrix = replica->GetOpenGLMatrixPtr();
m_rendertools->AddLight(&replica->m_lightobj);
-
return replica;
}
-GPULamp *KX_LightObject::GetGPULamp()
-{
- if(m_glsl)
- return GPU_lamp_from_blender(m_blenderscene, GetBlenderObject(), GetBlenderGroupObject());
- else
- return false;
-}
-
void KX_LightObject::Update()
{
- GPULamp *lamp;
-
- if((lamp = GetGPULamp())) {
+#ifdef BLENDER_GLSL
+ if(m_gpulamp) {
float obmat[4][4];
double *dobmat = GetOpenGLMatrixPtr()->getPointer();
@@ -112,39 +95,38 @@ void KX_LightObject::Update()
for(int j=0; j<4; j++, dobmat++)
obmat[i][j] = (float)*dobmat;
- GPU_lamp_update(lamp, m_lightobj.m_layer, obmat);
+ GPU_lamp_update(m_gpulamp, obmat);
}
+#endif
}
bool KX_LightObject::HasShadowBuffer()
{
- GPULamp *lamp;
-
- if((lamp = GetGPULamp()))
- return GPU_lamp_has_shadow_buffer(lamp);
- else
- return false;
+#ifdef BLENDER_GLSL
+ return (m_gpulamp && GPU_lamp_has_shadow_buffer(m_gpulamp));
+#else
+ return false;
+#endif
}
int KX_LightObject::GetShadowLayer()
{
- GPULamp *lamp;
-
- if((lamp = GetGPULamp()))
- return GPU_lamp_shadow_layer(lamp);
+#ifdef BLENDER_GLSL
+ if(m_gpulamp)
+ return GPU_lamp_shadow_layer(m_gpulamp);
else
+#endif
return 0;
}
void KX_LightObject::BindShadowBuffer(RAS_IRasterizer *ras, KX_Camera *cam, MT_Transform& camtrans)
{
- GPULamp *lamp;
+#ifdef BLENDER_GLSL
float viewmat[4][4], winmat[4][4];
int winsize;
/* bind framebuffer */
- lamp = GetGPULamp();
- GPU_lamp_shadow_buffer_bind(lamp, viewmat, &winsize, winmat);
+ GPU_lamp_shadow_buffer_bind(m_gpulamp, viewmat, &winsize, winmat);
/* setup camera transformation */
MT_Matrix4x4 modelviewmat((float*)viewmat);
@@ -164,12 +146,14 @@ void KX_LightObject::BindShadowBuffer(RAS_IRasterizer *ras, KX_Camera *cam, MT_T
ras->SetProjectionMatrix(projectionmat);
ras->SetViewMatrix(modelviewmat, cam->NodeGetWorldPosition(),
cam->GetCameraLocation(), cam->GetCameraOrientation());
+#endif
}
void KX_LightObject::UnbindShadowBuffer(RAS_IRasterizer *ras)
{
- GPULamp *lamp = GetGPULamp();
- GPU_lamp_shadow_buffer_unbind(lamp);
+#ifdef BLENDER_GLSL
+ GPU_lamp_shadow_buffer_unbind(m_gpulamp);
+#endif
}
PyObject* KX_LightObject::_getattr(const STR_String& attr)
diff --git a/source/gameengine/Ketsji/KX_Light.h b/source/gameengine/Ketsji/KX_Light.h
index e5dbf0b7f4a..62eb26c61a8 100644
--- a/source/gameengine/Ketsji/KX_Light.h
+++ b/source/gameengine/Ketsji/KX_Light.h
@@ -33,7 +33,6 @@
#include "KX_GameObject.h"
struct GPULamp;
-struct Scene;
class KX_Camera;
class RAS_IRasterizer;
class RAS_IRenderTools;
@@ -45,18 +44,16 @@ class KX_LightObject : public KX_GameObject
protected:
RAS_LightObject m_lightobj;
class RAS_IRenderTools* m_rendertools; //needed for registering and replication of lightobj
- bool m_glsl;
- Scene* m_blenderscene;
- static char doc[];
+ struct GPULamp *m_gpulamp;
+ static char doc[];
public:
- KX_LightObject(void* sgReplicationInfo,SG_Callbacks callbacks,class RAS_IRenderTools* rendertools,const struct RAS_LightObject& lightobj, bool glsl, PyTypeObject *T = &Type);
+ KX_LightObject(void* sgReplicationInfo,SG_Callbacks callbacks,class RAS_IRenderTools* rendertools,const struct RAS_LightObject& lightobj, struct GPULamp *gpulamp, PyTypeObject *T = &Type);
virtual ~KX_LightObject();
virtual CValue* GetReplica();
RAS_LightObject* GetLightData() { return &m_lightobj;}
/* GLSL shadow */
- struct GPULamp *GetGPULamp();
bool HasShadowBuffer();
int GetShadowLayer();
void BindShadowBuffer(class RAS_IRasterizer *ras, class KX_Camera *cam, class MT_Transform& camtrans);
@@ -65,8 +62,6 @@ public:
virtual PyObject* _getattr(const STR_String& attr); /* lens, near, far, projection_matrix */
virtual int _setattr(const STR_String& attr, PyObject *pyvalue);
-
- virtual bool IsLight(void) { return true; }
};
#endif //__KX_LIGHT
diff --git a/source/gameengine/Ketsji/KX_MaterialIpoController.cpp b/source/gameengine/Ketsji/KX_MaterialIpoController.cpp
index 85d514bd22f..2ce5d469380 100644
--- a/source/gameengine/Ketsji/KX_MaterialIpoController.cpp
+++ b/source/gameengine/Ketsji/KX_MaterialIpoController.cpp
@@ -3,8 +3,6 @@
#include "KX_ScalarInterpolator.h"
#include "KX_GameObject.h"
-#include "BLO_sys_types.h" // for intptr_t support
-
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
@@ -78,10 +76,10 @@ SG_Controller* KX_MaterialIpoController::GetReplica(class SG_Node* destnode)
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;
+ long orgbase = (long)this;
+ long orgloc = (long)scaal;
+ long offset = orgloc-orgbase;
+ long newaddrbase = (long)iporeplica + offset;
MT_Scalar* blaptr = (MT_Scalar*) newaddrbase;
copyipo->SetNewTarget((MT_Scalar*)blaptr);
}
diff --git a/source/gameengine/Ketsji/KX_MeshProxy.cpp b/source/gameengine/Ketsji/KX_MeshProxy.cpp
index 5cc102248f2..c7a251751cd 100644
--- a/source/gameengine/Ketsji/KX_MeshProxy.cpp
+++ b/source/gameengine/Ketsji/KX_MeshProxy.cpp
@@ -35,7 +35,6 @@
#include "RAS_MeshObject.h"
#include "KX_VertexProxy.h"
-#include "KX_PolyProxy.h"
#include "KX_PolygonMaterial.h"
#include "KX_BlenderMaterial.h"
@@ -43,8 +42,6 @@
#include "KX_PyMath.h"
#include "KX_ConvertPhysicsObject.h"
-#include "PyObjectPlus.h"
-
PyTypeObject KX_MeshProxy::Type = {
PyObject_HEAD_INIT(&PyType_Type)
0,
@@ -74,12 +71,10 @@ PyParentObject KX_MeshProxy::Parents[] = {
PyMethodDef KX_MeshProxy::Methods[] = {
{"getNumMaterials", (PyCFunction)KX_MeshProxy::sPyGetNumMaterials,METH_VARARGS},
-{"getNumPolygons", (PyCFunction)KX_MeshProxy::sPyGetNumPolygons,METH_NOARGS},
{"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},
KX_PYMETHODTABLE(KX_MeshProxy, reinstancePhysicsMesh),
//{"getIndexArrayLength", (PyCFunction)KX_MeshProxy::sPyGetIndexArrayLength,METH_VARARGS},
@@ -98,11 +93,10 @@ KX_MeshProxy::_getattr(const STR_String& attr)
if (attr == "materials")
{
PyObject *materials = PyList_New(0);
- list<RAS_MeshMaterial>::iterator mit = m_meshobj->GetFirstMaterial();
+ RAS_MaterialBucket::Set::iterator mit = m_meshobj->GetFirstMaterial();
for(; mit != m_meshobj->GetLastMaterial(); ++mit)
{
- RAS_IPolyMaterial *polymat = mit->m_bucket->GetPolyMaterial();
-
+ RAS_IPolyMaterial *polymat = (*mit)->GetPolyMaterial();
if(polymat->GetFlag() & RAS_BLENDERMAT)
{
KX_BlenderMaterial *mat = static_cast<KX_BlenderMaterial*>(polymat);
@@ -152,12 +146,6 @@ PyObject* KX_MeshProxy::PyGetNumMaterials(PyObject* self,
return PyInt_FromLong(num);
}
-PyObject* KX_MeshProxy::PyGetNumPolygons(PyObject* self)
-{
- int num = m_meshobj->NumPolygons();
- return PyInt_FromLong(num);
-}
-
PyObject* KX_MeshProxy::PyGetMaterialName(PyObject* self,
PyObject* args,
PyObject* kwds)
@@ -207,11 +195,11 @@ PyObject* KX_MeshProxy::PyGetVertexArrayLength(PyObject* self,
if (PyArg_ParseTuple(args,"i",&matid))
{
- RAS_MeshMaterial *mmat = m_meshobj->GetMeshMaterial(matid);
- RAS_IPolyMaterial* mat = mmat->m_bucket->GetPolyMaterial();
-
+ RAS_IPolyMaterial* mat = m_meshobj->GetMaterialBucket(matid)->GetPolyMaterial();
if (mat)
- length = m_meshobj->NumVertices(mat);
+ {
+ length = m_meshobj->GetVertexArrayLength(mat);
+ }
}
else {
return NULL;
@@ -246,31 +234,9 @@ PyObject* KX_MeshProxy::PyGetVertex(PyObject* self,
}
-PyObject* KX_MeshProxy::PyGetPolygon(PyObject* self,
- PyObject* args,
- PyObject* kwds)
-{
- int polyindex= 1;
- PyObject* polyob = NULL;
-
- if (!PyArg_ParseTuple(args,"i",&polyindex))
- return NULL;
-
- RAS_Polygon* polygon = m_meshobj->GetPolygon(polyindex);
- if (polygon)
- {
- polyob = new KX_PolyProxy(m_meshobj, polygon);
- }
- else
- {
- PyErr_SetString(PyExc_AttributeError, "Invalid polygon index");
- }
- return polyob;
-}
-
KX_PYMETHODDEF_DOC(KX_MeshProxy, reinstancePhysicsMesh,
"Reinstance the physics mesh.")
{
//this needs to be reviewed, it is dependend on Sumo/Solid. Who is using this ?
- Py_RETURN_NONE;//(KX_ReInstanceShapeFromMesh(m_meshobj)) ? Py_RETURN_TRUE : Py_RETURN_FALSE;
+ return Py_None;//Py_Success(KX_ReInstanceShapeFromMesh(m_meshobj));
}
diff --git a/source/gameengine/Ketsji/KX_MeshProxy.h b/source/gameengine/Ketsji/KX_MeshProxy.h
index 3335c349673..7c6202c15a4 100644
--- a/source/gameengine/Ketsji/KX_MeshProxy.h
+++ b/source/gameengine/Ketsji/KX_MeshProxy.h
@@ -57,12 +57,10 @@ public:
KX_PYMETHOD(KX_MeshProxy,GetNumMaterials);
KX_PYMETHOD(KX_MeshProxy,GetMaterialName);
KX_PYMETHOD(KX_MeshProxy,GetTextureName);
- KX_PYMETHOD_NOARGS(KX_MeshProxy,GetNumPolygons);
// both take materialid (int)
KX_PYMETHOD(KX_MeshProxy,GetVertexArrayLength);
KX_PYMETHOD(KX_MeshProxy,GetVertex);
- KX_PYMETHOD(KX_MeshProxy,GetPolygon);
KX_PYMETHOD_DOC(KX_MeshProxy, reinstancePhysicsMesh);
};
diff --git a/source/gameengine/Ketsji/KX_MouseFocusSensor.cpp b/source/gameengine/Ketsji/KX_MouseFocusSensor.cpp
index 28279b9a6b8..db0bef8b7e1 100644
--- a/source/gameengine/Ketsji/KX_MouseFocusSensor.cpp
+++ b/source/gameengine/Ketsji/KX_MouseFocusSensor.cpp
@@ -62,14 +62,12 @@ KX_MouseFocusSensor::KX_MouseFocusSensor(SCA_MouseManager* eventmgr,
int focusmode,
RAS_ICanvas* canvas,
KX_Scene* kxscene,
- KX_KetsjiEngine *kxengine,
SCA_IObject* gameobj,
PyTypeObject* T)
: SCA_MouseSensor(eventmgr, startx, starty, mousemode, gameobj, T),
m_focusmode(focusmode),
m_gp_canvas(canvas),
- m_kxscene(kxscene),
- m_kxengine(kxengine)
+ m_kxscene(kxscene)
{
Init();
}
@@ -124,10 +122,16 @@ bool KX_MouseFocusSensor::Evaluate(CValue* event)
return result;
}
-bool KX_MouseFocusSensor::RayHit(KX_ClientObjectInfo* client_info, KX_RayCast* result, void * const data)
+bool KX_MouseFocusSensor::RayHit(KX_ClientObjectInfo* client_info, MT_Point3& hit_point, MT_Vector3& hit_normal, void * const data)
{
KX_GameObject* hitKXObj = client_info->m_gameobject;
+ if (client_info->m_type > KX_ClientObjectInfo::ACTOR)
+ {
+ // false hit
+ return false;
+ }
+
/* Is this me? In the ray test, there are a lot of extra checks
* for aliasing artefacts from self-hits. That doesn't happen
* here, so a simple test suffices. Or does the camera also get
@@ -138,8 +142,8 @@ bool KX_MouseFocusSensor::RayHit(KX_ClientObjectInfo* client_info, KX_RayCast* r
if ((m_focusmode == 2) || hitKXObj == thisObj)
{
m_hitObject = hitKXObj;
- m_hitPosition = result->m_hitPoint;
- m_hitNormal = result->m_hitNormal;
+ m_hitPosition = hit_point;
+ m_hitNormal = hit_normal;
return true;
}
@@ -154,6 +158,8 @@ bool KX_MouseFocusSensor::ParentObjectHasFocus(void)
m_hitObject = 0;
m_hitPosition = MT_Vector3(0,0,0);
m_hitNormal = MT_Vector3(1,0,0);
+ MT_Point3 resultpoint;
+ MT_Vector3 resultnormal;
/* All screen handling in the gameengine is done by GL,
* specifically the model/view and projection parts. The viewport
@@ -195,14 +201,11 @@ bool KX_MouseFocusSensor::ParentObjectHasFocus(void)
* calculations don't bomb. Maybe we should explicitly guard for
* division by 0.0...*/
- KX_Camera* cam = m_kxscene->GetActiveCamera();
+ /**
+ * Get the scenes current viewport.
+ */
- /* get the scenes current viewport. we recompute it because there
- * may be multiple cameras and m_kxscene->GetSceneViewport() only
- * has the one that was last drawn */
-
- RAS_Rect area, viewport;
- m_kxengine->GetSceneViewport(m_kxscene, cam, area, viewport);
+ const RAS_Rect & viewport = m_kxscene->GetSceneViewport();
float height = float(viewport.m_y2 - viewport.m_y1 + 1);
float width = float(viewport.m_x2 - viewport.m_x1 + 1);
@@ -210,9 +213,9 @@ bool KX_MouseFocusSensor::ParentObjectHasFocus(void)
float x_lb = float(viewport.m_x1);
float y_lb = float(viewport.m_y1);
+ KX_Camera* cam = m_kxscene->GetActiveCamera();
/* There's some strangeness I don't fully get here... These values
* _should_ be wrong! */
-
/* old: */
float nearclip = 0.0;
@@ -277,8 +280,7 @@ bool KX_MouseFocusSensor::ParentObjectHasFocus(void)
bool result = false;
- KX_RayCast::Callback<KX_MouseFocusSensor> callback(this,physics_controller);
- KX_RayCast::RayTest(physics_environment, frompoint3, topoint3, callback);
+ result = KX_RayCast::RayTest(physics_controller, physics_environment, frompoint3, topoint3, resultpoint, resultnormal, KX_RayCast::Callback<KX_MouseFocusSensor>(this));
result = (m_hitObject!=0);
@@ -320,12 +322,14 @@ PyParentObject KX_MouseFocusSensor::Parents[] = {
};
PyMethodDef KX_MouseFocusSensor::Methods[] = {
- {"getRayTarget", (PyCFunction) KX_MouseFocusSensor::sPyGetRayTarget, METH_VARARGS, (PY_METHODCHAR)GetRayTarget_doc},
- {"getRaySource", (PyCFunction) KX_MouseFocusSensor::sPyGetRaySource, METH_VARARGS, (PY_METHODCHAR)GetRaySource_doc},
- {"getHitObject",(PyCFunction) KX_MouseFocusSensor::sPyGetHitObject,METH_VARARGS, (PY_METHODCHAR)GetHitObject_doc},
- {"getHitPosition",(PyCFunction) KX_MouseFocusSensor::sPyGetHitPosition,METH_VARARGS, (PY_METHODCHAR)GetHitPosition_doc},
- {"getHitNormal",(PyCFunction) KX_MouseFocusSensor::sPyGetHitNormal,METH_VARARGS, (PY_METHODCHAR)GetHitNormal_doc},
- {"getRayDirection",(PyCFunction) KX_MouseFocusSensor::sPyGetRayDirection,METH_VARARGS, (PY_METHODCHAR)GetRayDirection_doc},
+ {"getRayTarget", (PyCFunction) KX_MouseFocusSensor::sPyGetRayTarget,
+ METH_VARARGS, GetRayTarget_doc},
+ {"getRaySource", (PyCFunction) KX_MouseFocusSensor::sPyGetRaySource,
+ METH_VARARGS, GetRaySource_doc},
+ {"getHitObject",(PyCFunction) KX_MouseFocusSensor::sPyGetHitObject,METH_VARARGS, GetHitObject_doc},
+ {"getHitPosition",(PyCFunction) KX_MouseFocusSensor::sPyGetHitPosition,METH_VARARGS, GetHitPosition_doc},
+ {"getHitNormal",(PyCFunction) KX_MouseFocusSensor::sPyGetHitNormal,METH_VARARGS, GetHitNormal_doc},
+ {"getRayDirection",(PyCFunction) KX_MouseFocusSensor::sPyGetRayDirection,METH_VARARGS, GetRayDirection_doc},
{NULL,NULL} //Sentinel
@@ -336,7 +340,7 @@ PyObject* KX_MouseFocusSensor::_getattr(const STR_String& attr) {
}
-const char KX_MouseFocusSensor::GetHitObject_doc[] =
+char KX_MouseFocusSensor::GetHitObject_doc[] =
"getHitObject()\n"
"\tReturns the name of the object that was hit by this ray.\n";
PyObject* KX_MouseFocusSensor::PyGetHitObject(PyObject* self,
@@ -351,7 +355,7 @@ PyObject* KX_MouseFocusSensor::PyGetHitObject(PyObject* self,
}
-const char KX_MouseFocusSensor::GetHitPosition_doc[] =
+char KX_MouseFocusSensor::GetHitPosition_doc[] =
"getHitPosition()\n"
"\tReturns the position (in worldcoordinates) where the object was hit by this ray.\n";
PyObject* KX_MouseFocusSensor::PyGetHitPosition(PyObject* self,
@@ -371,7 +375,7 @@ PyObject* KX_MouseFocusSensor::PyGetHitPosition(PyObject* self,
}
-const char KX_MouseFocusSensor::GetRayDirection_doc[] =
+char KX_MouseFocusSensor::GetRayDirection_doc[] =
"getRayDirection()\n"
"\tReturns the direction from the ray (in worldcoordinates) .\n";
PyObject* KX_MouseFocusSensor::PyGetRayDirection(PyObject* self,
@@ -392,7 +396,7 @@ PyObject* KX_MouseFocusSensor::PyGetRayDirection(PyObject* self,
}
-const char KX_MouseFocusSensor::GetHitNormal_doc[] =
+char KX_MouseFocusSensor::GetHitNormal_doc[] =
"getHitNormal()\n"
"\tReturns the normal (in worldcoordinates) of the object at the location where the object was hit by this ray.\n";
PyObject* KX_MouseFocusSensor::PyGetHitNormal(PyObject* self,
@@ -413,7 +417,7 @@ PyObject* KX_MouseFocusSensor::PyGetHitNormal(PyObject* self,
/* getRayTarget */
-const char KX_MouseFocusSensor::GetRayTarget_doc[] =
+char KX_MouseFocusSensor::GetRayTarget_doc[] =
"getRayTarget()\n"
"\tReturns the target of the ray that seeks the focus object,\n"
"\tin worldcoordinates.";
@@ -430,7 +434,7 @@ PyObject* KX_MouseFocusSensor::PyGetRayTarget(PyObject* self,
}
/* getRayTarget */
-const char KX_MouseFocusSensor::GetRaySource_doc[] =
+char KX_MouseFocusSensor::GetRaySource_doc[] =
"getRaySource()\n"
"\tReturns the source of the ray that seeks the focus object,\n"
"\tin worldcoordinates.";
diff --git a/source/gameengine/Ketsji/KX_MouseFocusSensor.h b/source/gameengine/Ketsji/KX_MouseFocusSensor.h
index 6731444699b..b011ebe1288 100644
--- a/source/gameengine/Ketsji/KX_MouseFocusSensor.h
+++ b/source/gameengine/Ketsji/KX_MouseFocusSensor.h
@@ -33,8 +33,6 @@
#include "SCA_MouseSensor.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
@@ -56,7 +54,6 @@ class KX_MouseFocusSensor : public SCA_MouseSensor
int focusmode,
RAS_ICanvas* canvas,
KX_Scene* kxscene,
- KX_KetsjiEngine* kxengine,
SCA_IObject* gameobj,
PyTypeObject* T=&Type );
@@ -79,9 +76,7 @@ class KX_MouseFocusSensor : public SCA_MouseSensor
return result;
};
- bool RayHit(KX_ClientObjectInfo* client, KX_RayCast* result, void * const data);
- bool NeedRayCast(KX_ClientObjectInfo* client) { return true; }
-
+ bool RayHit(KX_ClientObjectInfo* client, MT_Point3& hit_point, MT_Vector3& hit_normal, void * const data);
/* --------------------------------------------------------------------- */
@@ -144,6 +139,12 @@ class KX_MouseFocusSensor : public SCA_MouseSensor
/**
+ * Ref to the engine, for retrieving a reference to the current
+ * scene. */
+ class KX_KetsjiEngine* m_engine;
+
+
+ /**
* The active canvas. The size of this canvas determines a part of
* the start position of the picking ray. */
RAS_ICanvas* m_gp_canvas;
@@ -153,9 +154,6 @@ class KX_MouseFocusSensor : public SCA_MouseSensor
* 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_NearSensor.cpp b/source/gameengine/Ketsji/KX_NearSensor.cpp
index bae87c28123..140dd37f5c6 100644
--- a/source/gameengine/Ketsji/KX_NearSensor.cpp
+++ b/source/gameengine/Ketsji/KX_NearSensor.cpp
@@ -190,13 +190,13 @@ bool KX_NearSensor::Evaluate(CValue* event)
{
if (m_physCtrl)
{
- m_physCtrl->SetRadius(m_ResetMargin);
+ m_physCtrl->SetMargin(m_ResetMargin);
}
} else
{
if (m_physCtrl)
{
- m_physCtrl->SetRadius(m_Margin);
+ m_physCtrl->SetMargin(m_Margin);
}
}
@@ -252,10 +252,8 @@ bool KX_NearSensor::NewHandleCollision(void* obj1,void* obj2,const PHY_CollData
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)*/)
+ // these checks are done already in BroadPhaseFilterCollision()
+ if (gameobj /*&& (gameobj != parent)*/)
{
if (!m_colliders->SearchValue(gameobj))
m_colliders->Add(gameobj->AddRef());
@@ -311,10 +309,14 @@ PyParentObject KX_NearSensor::Parents[] = {
PyMethodDef KX_NearSensor::Methods[] = {
- {"setProperty", (PyCFunction) KX_NearSensor::sPySetProperty, METH_VARARGS, (PY_METHODCHAR)SetProperty_doc},
- {"getProperty", (PyCFunction) KX_NearSensor::sPyGetProperty, METH_VARARGS, (PY_METHODCHAR)GetProperty_doc},
- {"getHitObject",(PyCFunction) KX_NearSensor::sPyGetHitObject, METH_VARARGS, (PY_METHODCHAR)GetHitObject_doc},
- {"getHitObjectList", (PyCFunction) KX_NearSensor::sPyGetHitObjectList, METH_VARARGS, (PY_METHODCHAR)GetHitObjectList_doc},
+ {"setProperty",
+ (PyCFunction) KX_NearSensor::sPySetProperty, METH_VARARGS, SetProperty_doc},
+ {"getProperty",
+ (PyCFunction) KX_NearSensor::sPyGetProperty, METH_VARARGS, GetProperty_doc},
+ {"getHitObject",
+ (PyCFunction) KX_NearSensor::sPyGetHitObject, METH_VARARGS, GetHitObject_doc},
+ {"getHitObjectList",
+ (PyCFunction) KX_NearSensor::sPyGetHitObjectList, METH_VARARGS, GetHitObjectList_doc},
{NULL,NULL} //Sentinel
};
diff --git a/source/gameengine/Ketsji/KX_ObjectActuator.cpp b/source/gameengine/Ketsji/KX_ObjectActuator.cpp
index 98e73d4f0d7..5cd4d089c14 100644
--- a/source/gameengine/Ketsji/KX_ObjectActuator.cpp
+++ b/source/gameengine/Ketsji/KX_ObjectActuator.cpp
@@ -360,6 +360,7 @@ PyObject* KX_ObjectActuator::PySetForce(PyObject* self,
int bToggle = 0;
if (!PyArg_ParseTuple(args, "fffi", &vecArg[0], &vecArg[1],
&vecArg[2], &bToggle)) {
+ PyErr_SetString(PyExc_TypeError, "Invalid arguments");
return NULL;
}
m_force.setValue(vecArg);
@@ -389,6 +390,7 @@ PyObject* KX_ObjectActuator::PySetTorque(PyObject* self,
int bToggle = 0;
if (!PyArg_ParseTuple(args, "fffi", &vecArg[0], &vecArg[1],
&vecArg[2], &bToggle)) {
+ PyErr_SetString(PyExc_TypeError, "Invalid arguments");
return NULL;
}
m_torque.setValue(vecArg);
@@ -418,6 +420,7 @@ PyObject* KX_ObjectActuator::PySetDLoc(PyObject* self,
int bToggle = 0;
if(!PyArg_ParseTuple(args, "fffi", &vecArg[0], &vecArg[1],
&vecArg[2], &bToggle)) {
+ PyErr_SetString(PyExc_TypeError, "Invalid arguments");
return NULL;
}
m_dloc.setValue(vecArg);
@@ -447,6 +450,7 @@ PyObject* KX_ObjectActuator::PySetDRot(PyObject* self,
int bToggle = 0;
if (!PyArg_ParseTuple(args, "fffi", &vecArg[0], &vecArg[1],
&vecArg[2], &bToggle)) {
+ PyErr_SetString(PyExc_TypeError, "Invalid arguments");
return NULL;
}
m_drot.setValue(vecArg);
@@ -475,6 +479,7 @@ PyObject* KX_ObjectActuator::PySetLinearVelocity(PyObject* self,
int bToggle = 0;
if (!PyArg_ParseTuple(args, "fffi", &vecArg[0], &vecArg[1],
&vecArg[2], &bToggle)) {
+ PyErr_SetString(PyExc_TypeError, "Invalid arguments");
return NULL;
}
m_linear_velocity.setValue(vecArg);
@@ -503,6 +508,7 @@ PyObject* KX_ObjectActuator::PySetAngularVelocity(PyObject* self,
int bToggle = 0;
if (!PyArg_ParseTuple(args, "fffi", &vecArg[0], &vecArg[1],
&vecArg[2], &bToggle)) {
+ PyErr_SetString(PyExc_TypeError, "Invalid arguments");
return NULL;
}
m_angular_velocity.setValue(vecArg);
@@ -517,6 +523,7 @@ PyObject* KX_ObjectActuator::PySetDamping(PyObject* self,
PyObject* kwds) {
int damping = 0;
if (!PyArg_ParseTuple(args, "i", &damping) || damping < 0 || damping > 1000) {
+ PyErr_SetString(PyExc_TypeError, "Invalid arguments");
return NULL;
}
m_damping = damping;
@@ -546,6 +553,7 @@ PyObject* KX_ObjectActuator::PySetForceLimitX(PyObject* self,
float vecArg[2];
int bToggle = 0;
if(!PyArg_ParseTuple(args, "ffi", &vecArg[0], &vecArg[1], &bToggle)) {
+ PyErr_SetString(PyExc_TypeError, "Invalid arguments");
return NULL;
}
m_drot[0] = vecArg[0];
@@ -573,6 +581,7 @@ PyObject* KX_ObjectActuator::PySetForceLimitY(PyObject* self,
float vecArg[2];
int bToggle = 0;
if(!PyArg_ParseTuple(args, "ffi", &vecArg[0], &vecArg[1], &bToggle)) {
+ PyErr_SetString(PyExc_TypeError, "Invalid arguments");
return NULL;
}
m_drot[1] = vecArg[0];
@@ -600,6 +609,7 @@ PyObject* KX_ObjectActuator::PySetForceLimitZ(PyObject* self,
float vecArg[2];
int bToggle = 0;
if(!PyArg_ParseTuple(args, "ffi", &vecArg[0], &vecArg[1], &bToggle)) {
+ PyErr_SetString(PyExc_TypeError, "Invalid arguments");
return NULL;
}
m_drot[2] = vecArg[0];
@@ -626,6 +636,7 @@ PyObject* KX_ObjectActuator::PySetPID(PyObject* self,
{
float vecArg[3];
if (!PyArg_ParseTuple(args, "fff", &vecArg[0], &vecArg[1], &vecArg[2])) {
+ PyErr_SetString(PyExc_TypeError, "Invalid arguments");
return NULL;
}
m_torque.setValue(vecArg);
diff --git a/source/gameengine/Ketsji/KX_OdePhysicsController.cpp b/source/gameengine/Ketsji/KX_OdePhysicsController.cpp
index 6a701a5f25b..05feb11a2bc 100644
--- a/source/gameengine/Ketsji/KX_OdePhysicsController.cpp
+++ b/source/gameengine/Ketsji/KX_OdePhysicsController.cpp
@@ -169,11 +169,6 @@ MT_Scalar KX_OdePhysicsController::GetMass()
return ODEPhysicsController::getMass();
}
-MT_Scalar KX_OdePhysicsController::GetRadius()
-{
- return MT_Scalar(0.f);
-}
-
MT_Vector3 KX_OdePhysicsController::getReactionForce()
{
return MT_Vector3(0,0,0);
diff --git a/source/gameengine/Ketsji/KX_OdePhysicsController.h b/source/gameengine/Ketsji/KX_OdePhysicsController.h
index 53050f6ce3e..18f9edc6835 100644
--- a/source/gameengine/Ketsji/KX_OdePhysicsController.h
+++ b/source/gameengine/Ketsji/KX_OdePhysicsController.h
@@ -76,7 +76,7 @@ public:
virtual void SuspendDynamics(bool);
virtual void RestoreDynamics();
- virtual MT_Scalar GetRadius();
+
virtual SG_Controller* GetReplica(class SG_Node* destnode);
diff --git a/source/gameengine/Ketsji/KX_ParentActuator.cpp b/source/gameengine/Ketsji/KX_ParentActuator.cpp
index 89549ca6b57..fd1b56838e2 100644
--- a/source/gameengine/Ketsji/KX_ParentActuator.cpp
+++ b/source/gameengine/Ketsji/KX_ParentActuator.cpp
@@ -36,8 +36,6 @@
#include "KX_GameObject.h"
#include "KX_PythonInit.h"
-#include "PyObjectPlus.h"
-
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
@@ -119,7 +117,7 @@ bool KX_ParentActuator::Update()
return false; // do nothing on negative events
KX_GameObject *obj = (KX_GameObject*) GetParent();
- KX_Scene *scene = KX_GetActiveScene();
+ KX_Scene *scene = PHY_GetActiveScene();
switch (m_mode) {
case KX_PARENT_SET:
if (m_ob)
@@ -166,8 +164,8 @@ PyParentObject KX_ParentActuator::Parents[] = {
};
PyMethodDef KX_ParentActuator::Methods[] = {
- {"setObject", (PyCFunction) KX_ParentActuator::sPySetObject, METH_O, (PY_METHODCHAR)SetObject_doc},
- {"getObject", (PyCFunction) KX_ParentActuator::sPyGetObject, METH_VARARGS, (PY_METHODCHAR)GetObject_doc},
+ {"setObject", (PyCFunction) KX_ParentActuator::sPySetObject, METH_VARARGS, SetObject_doc},
+ {"getObject", (PyCFunction) KX_ParentActuator::sPyGetObject, METH_VARARGS, GetObject_doc},
{NULL,NULL} //Sentinel
};
@@ -176,46 +174,46 @@ PyObject* KX_ParentActuator::_getattr(const STR_String& attr) {
}
/* 1. setObject */
-const char KX_ParentActuator::SetObject_doc[] =
+char KX_ParentActuator::SetObject_doc[] =
"setObject(object)\n"
-"\t- object: KX_GameObject, string or None\n"
-"\tSet the object to set as parent.\n";
-PyObject* KX_ParentActuator::PySetObject(PyObject* self, PyObject* value) {
- KX_GameObject *gameobj;
-
- if (!ConvertPythonToGameObject(value, &gameobj, true))
- return NULL; // ConvertPythonToGameObject sets the error
+"\tSet the object to set as parent.\n"
+"\tCan be an object name or an object\n";
+PyObject* KX_ParentActuator::PySetObject(PyObject* self, PyObject* args, PyObject* kwds) {
+ PyObject* gameobj;
+ if (PyArg_ParseTuple(args, "O!", &KX_GameObject::Type, &gameobj))
+ {
+ if (m_ob != NULL)
+ m_ob->UnregisterActuator(this);
+ m_ob = (SCA_IObject*)gameobj;
+ if (m_ob)
+ m_ob->RegisterActuator(this);
+ Py_Return;
+ }
+ PyErr_Clear();
- if (m_ob != NULL)
- m_ob->UnregisterActuator(this);
-
- m_ob = (SCA_IObject*)gameobj;
- if (m_ob)
- m_ob->RegisterActuator(this);
+ char* objectname;
+ if (PyArg_ParseTuple(args, "s", &objectname))
+ {
+ SCA_IObject *object = (SCA_IObject*)SCA_ILogicBrick::m_sCurrentLogicManager->GetGameObjectByName(STR_String(objectname));
+ if(object)
+ {
+ if (m_ob != NULL)
+ m_ob->UnregisterActuator(this);
+ m_ob = object;
+ m_ob->RegisterActuator(this);
+ Py_Return;
+ }
+ }
- Py_RETURN_NONE;
+ return NULL;
}
/* 2. getObject */
-
-/* get obj ---------------------------------------------------------- */
-const char KX_ParentActuator::GetObject_doc[] =
-"getObject(name_only = 1)\n"
-"name_only - optional arg, when true will return the KX_GameObject rather then its name\n"
+char KX_ParentActuator::GetObject_doc[] =
+"getObject()\n"
"\tReturns the object that is set to.\n";
-PyObject* KX_ParentActuator::PyGetObject(PyObject* self, PyObject* args)
-{
- int ret_name_only = 1;
- if (!PyArg_ParseTuple(args, "|i", &ret_name_only))
- return NULL;
-
- if (!m_ob)
- Py_RETURN_NONE;
-
- if (ret_name_only)
- return PyString_FromString(m_ob->GetName());
- else
- return m_ob->AddRef();
+PyObject* KX_ParentActuator::PyGetObject(PyObject* self, PyObject* args, PyObject* kwds) {
+ return PyString_FromString(m_ob->GetName());
}
-
+
/* eof */
diff --git a/source/gameengine/Ketsji/KX_ParentActuator.h b/source/gameengine/Ketsji/KX_ParentActuator.h
index e2b30ba2d0f..93b07cd424b 100644
--- a/source/gameengine/Ketsji/KX_ParentActuator.h
+++ b/source/gameengine/Ketsji/KX_ParentActuator.h
@@ -79,9 +79,9 @@ class KX_ParentActuator : public SCA_IActuator
virtual PyObject* _getattr(const STR_String& attr);
/* 1. setObject */
- KX_PYMETHOD_DOC_O(KX_ParentActuator,SetObject);
+ KX_PYMETHOD_DOC(KX_ParentActuator,SetObject);
/* 2. getObject */
- KX_PYMETHOD_DOC_VARARGS(KX_ParentActuator,GetObject);
+ KX_PYMETHOD_DOC(KX_ParentActuator,GetObject);
}; /* end of class KX_ParentActuator : public SCA_PropertyActuator */
diff --git a/source/gameengine/Ketsji/KX_PhysicsObjectWrapper.cpp b/source/gameengine/Ketsji/KX_PhysicsObjectWrapper.cpp
index da4f05ced7c..2df4c6a9980 100644
--- a/source/gameengine/Ketsji/KX_PhysicsObjectWrapper.cpp
+++ b/source/gameengine/Ketsji/KX_PhysicsObjectWrapper.cpp
@@ -27,8 +27,6 @@
* ***** END GPL LICENSE BLOCK *****
*/
#include <Python.h>
-#include "PyObjectPlus.h"
-
#include "KX_PhysicsObjectWrapper.h"
#include "PHY_IPhysicsEnvironment.h"
#include "PHY_IPhysicsController.h"
@@ -63,7 +61,7 @@ PyObject* KX_PhysicsObjectWrapper::PySetPosition(PyObject* self,
else {
return NULL;
}
- Py_RETURN_NONE;
+ Py_INCREF(Py_None); return Py_None;
}
@@ -80,7 +78,7 @@ PyObject* KX_PhysicsObjectWrapper::PySetLinearVelocity(PyObject* self,
else {
return NULL;
}
- Py_RETURN_NONE;
+ Py_INCREF(Py_None); return Py_None;
}
PyObject* KX_PhysicsObjectWrapper::PySetAngularVelocity(PyObject* self,
@@ -96,7 +94,7 @@ PyObject* KX_PhysicsObjectWrapper::PySetAngularVelocity(PyObject* self,
else {
return NULL;
}
- Py_RETURN_NONE;
+ Py_INCREF(Py_None); return Py_None;
}
PyObject* KX_PhysicsObjectWrapper::PySetActive(PyObject* self,
@@ -111,7 +109,7 @@ PyObject* KX_PhysicsObjectWrapper::PySetActive(PyObject* self,
else {
return NULL;
}
- Py_RETURN_NONE;
+ Py_INCREF(Py_None); return Py_None;
}
diff --git a/source/gameengine/Ketsji/KX_PolyProxy.cpp b/source/gameengine/Ketsji/KX_PolyProxy.cpp
deleted file mode 100644
index bb9072b34dc..00000000000
--- a/source/gameengine/Ketsji/KX_PolyProxy.cpp
+++ /dev/null
@@ -1,265 +0,0 @@
-/**
- * $Id$
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
- *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-#ifdef HAVE_CONFIG_H
-#include <config.h>
-#endif
-
-#include "KX_PolyProxy.h"
-#include "KX_MeshProxy.h"
-#include "RAS_MeshObject.h"
-#include "KX_BlenderMaterial.h"
-#include "KX_PolygonMaterial.h"
-
-#include "KX_PyMath.h"
-
-PyTypeObject KX_PolyProxy::Type = {
- PyObject_HEAD_INIT(&PyType_Type)
- 0,
- "KX_PolyProxy",
- sizeof(KX_PolyProxy),
- 0,
- PyDestructor,
- 0,
- __getattr,
- __setattr,
- 0, //&MyPyCompare,
- __repr,
- 0, //&cvalue_as_number,
- 0,
- 0,
- 0,
- 0
-};
-
-PyParentObject KX_PolyProxy::Parents[] = {
- &KX_PolyProxy::Type,
- &SCA_IObject::Type,
- &CValue::Type,
- NULL
-};
-
-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
-};
-
-PyObject*
-KX_PolyProxy::_getattr(const STR_String& attr)
-{
- if (attr == "matname")
- {
- return PyString_FromString(m_polygon->GetMaterial()->GetPolyMaterial()->GetMaterialName());
- }
- if (attr == "texture")
- {
- return PyString_FromString(m_polygon->GetMaterial()->GetPolyMaterial()->GetTextureName());
- }
- if (attr == "material")
- {
- RAS_IPolyMaterial *polymat = m_polygon->GetMaterial()->GetPolyMaterial();
- if(polymat->GetFlag() & RAS_BLENDERMAT)
- {
- KX_BlenderMaterial* mat = static_cast<KX_BlenderMaterial*>(polymat);
- Py_INCREF(mat);
- return mat;
- }
- else
- {
- KX_PolygonMaterial* mat = static_cast<KX_PolygonMaterial*>(polymat);
- Py_INCREF(mat);
- return mat;
- }
- }
- if (attr == "matid")
- {
- // we'll have to scan through the material bucket of the mes and compare with
- // the one of the polygon
- RAS_MaterialBucket* polyBucket = m_polygon->GetMaterial();
- unsigned int matid;
- for (matid=0; matid<m_mesh->NumMaterials(); matid++)
- {
- RAS_MeshMaterial* meshMat = m_mesh->GetMeshMaterial(matid);
- if (meshMat->m_bucket == polyBucket)
- // found it
- break;
- }
- return PyInt_FromLong(matid);
- }
- if (attr == "v1")
- {
- return PyInt_FromLong(m_polygon->GetVertexOffset(0));
- }
- if (attr == "v2")
- {
- return PyInt_FromLong(m_polygon->GetVertexOffset(1));
- }
- if (attr == "v3")
- {
- return PyInt_FromLong(m_polygon->GetVertexOffset(2));
- }
- if (attr == "v4")
- {
- return PyInt_FromLong(((m_polygon->VertexCount()>3)?m_polygon->GetVertexOffset(3):0));
- }
- if (attr == "visible")
- {
- return PyInt_FromLong(m_polygon->IsVisible());
- }
- if (attr == "collide")
- {
- return PyInt_FromLong(m_polygon->IsCollider());
- }
- _getattr_up(SCA_IObject);
-}
-
-KX_PolyProxy::KX_PolyProxy(const RAS_MeshObject*mesh, RAS_Polygon* polygon)
-: m_mesh((RAS_MeshObject*)mesh),
- m_polygon(polygon)
-{
-}
-
-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;}
-STR_String sPolyName="polygone";
-const STR_String & KX_PolyProxy::GetText() {return sPolyName;};
-float KX_PolyProxy::GetNumber() { return -1;}
-STR_String KX_PolyProxy::GetName() { return sPolyName;}
-void KX_PolyProxy::SetName(STR_String) { };
-CValue* KX_PolyProxy::GetReplica() { return NULL;}
-void KX_PolyProxy::ReplicaSetName(STR_String) {};
-
-
-// stuff for python integration
-
-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<m_mesh->NumMaterials(); matid++)
- {
- RAS_MeshMaterial* meshMat = m_mesh->GetMeshMaterial(matid);
- if (meshMat->m_bucket == polyBucket)
- // found it
- break;
- }
- return PyInt_FromLong(matid);
-}
-
-KX_PYMETHODDEF_DOC_NOARGS(KX_PolyProxy, getNumVertex,
-"getNumVertex() : returns the number of vertex of the polygon, 3 or 4\n")
-{
- return PyInt_FromLong(m_polygon->VertexCount());
-}
-
-KX_PYMETHODDEF_DOC_NOARGS(KX_PolyProxy, isVisible,
-"isVisible() : returns whether the polygon is visible or not\n")
-{
- return PyInt_FromLong(m_polygon->IsVisible());
-}
-
-KX_PYMETHODDEF_DOC_NOARGS(KX_PolyProxy, isCollider,
-"isCollider() : returns whether the polygon is receives collision or not\n")
-{
- return PyInt_FromLong(m_polygon->IsCollider());
-}
-
-KX_PYMETHODDEF_DOC_NOARGS(KX_PolyProxy, getMaterialName,
-"getMaterialName() : returns the polygon material name, \"NoMaterial\" if no material\n")
-{
- return PyString_FromString(m_polygon->GetMaterial()->GetPolyMaterial()->GetMaterialName());
-}
-
-KX_PYMETHODDEF_DOC_NOARGS(KX_PolyProxy, getTextureName,
-"getTexturelName() : returns the polygon texture name, \"NULL\" if no texture\n")
-{
- return PyString_FromString(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",&index))
- {
- return NULL;
- }
- if (index < 0 || index > 3)
- {
- PyErr_SetString(PyExc_AttributeError, "Valid range for index is 0-3");
- return NULL;
- }
- if (index < m_polygon->VertexCount())
- {
- return PyInt_FromLong(m_polygon->GetVertexOffset(index));
- }
- return PyInt_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;
-}
-
-KX_PYMETHODDEF_DOC_NOARGS(KX_PolyProxy, getMaterial,
-"getMaterial() : returns a material\n")
-{
- RAS_IPolyMaterial *polymat = m_polygon->GetMaterial()->GetPolyMaterial();
- if(polymat->GetFlag() & RAS_BLENDERMAT)
- {
- KX_BlenderMaterial* mat = static_cast<KX_BlenderMaterial*>(polymat);
- Py_INCREF(mat);
- return mat;
- }
- else
- {
- KX_PolygonMaterial* mat = static_cast<KX_PolygonMaterial*>(polymat);
- Py_INCREF(mat);
- return mat;
- }
-}
diff --git a/source/gameengine/Ketsji/KX_PolyProxy.h b/source/gameengine/Ketsji/KX_PolyProxy.h
deleted file mode 100644
index 506e2c2a656..00000000000
--- a/source/gameengine/Ketsji/KX_PolyProxy.h
+++ /dev/null
@@ -1,71 +0,0 @@
-/**
- * $Id$
- *
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
- *
- * The Original Code is Copyright (C) 2001-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_POLYROXY
-#define __KX_POLYPROXY
-
-#include "SCA_IObject.h"
-
-class KX_PolyProxy : public SCA_IObject
-{
- 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();
- float GetNumber();
- STR_String GetName();
- void SetName(STR_String name); // Set the name of the value
- void ReplicaSetName(STR_String name);
- CValue* GetReplica();
-
-
-// stuff for python integration
- virtual PyObject* _getattr(const STR_String& attr);
-
- 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 //__KX_POLYPROXY
-
diff --git a/source/gameengine/Ketsji/KX_PolygonMaterial.cpp b/source/gameengine/Ketsji/KX_PolygonMaterial.cpp
index c9180bf3a80..144f74a1a4c 100644
--- a/source/gameengine/Ketsji/KX_PolygonMaterial.cpp
+++ b/source/gameengine/Ketsji/KX_PolygonMaterial.cpp
@@ -35,6 +35,10 @@
#include "BKE_global.h"
#include "BKE_image.h"
+extern "C" {
+#include "BDR_drawmesh.h"
+}
+
#include "DNA_material_types.h"
#include "DNA_texture_types.h"
#include "DNA_image_types.h"
@@ -42,8 +46,6 @@
#include "IMB_imbuf_types.h"
-#include "GPU_draw.h"
-
#include "MEM_guardedalloc.h"
#include "RAS_LightObject.h"
@@ -61,6 +63,8 @@ KX_PolygonMaterial::KX_PolygonMaterial(const STR_String &texname,
bool alpha,
bool zsort,
int lightlayer,
+ bool bIsTriangle,
+ void* clientobject,
struct MTFace* tface,
unsigned int* mcol,
PyTypeObject *T)
@@ -74,7 +78,9 @@ KX_PolygonMaterial::KX_PolygonMaterial(const STR_String &texname,
transp,
alpha,
zsort,
- lightlayer),
+ lightlayer,
+ bIsTriangle,
+ clientobject),
m_tface(tface),
m_mcol(mcol),
m_material(material),
@@ -134,29 +140,38 @@ void KX_PolygonMaterial::DefaultActivate(RAS_IRasterizer* rasty, TCachingInfo& c
if (GetCachingInfo() != cachingInfo)
{
if (!cachingInfo)
- GPU_set_tpage(NULL);
-
+ {
+ set_tpage(NULL);
+ }
cachingInfo = GetCachingInfo();
if ((m_drawingmode & 4)&& (rasty->GetDrawingMode() == RAS_IRasterizer::KX_TEXTURED))
{
- Image *ima = (Image*)m_tface->tpage;
- GPU_update_image_time(ima, rasty->GetTime());
- GPU_set_tpage(m_tface);
+ update_realtime_texture((struct MTFace*) m_tface, rasty->GetTime());
+ set_tpage(m_tface);
+ rasty->EnableTextures(true);
}
else
- GPU_set_tpage(NULL);
+ {
+ set_tpage(NULL);
+ rasty->EnableTextures(false);
+ }
if(m_drawingmode & RAS_IRasterizer::KX_TWOSIDE)
+ {
rasty->SetCullFace(false);
+ }
else
+ {
rasty->SetCullFace(true);
+ }
- if ((m_drawingmode & RAS_IRasterizer::KX_LINES) ||
- (rasty->GetDrawingMode() <= RAS_IRasterizer::KX_WIREFRAME))
+ if (m_drawingmode & RAS_IRasterizer::KX_LINES) {
rasty->SetLines(true);
- else
+ }
+ else {
rasty->SetLines(false);
+ }
}
rasty->SetSpecularity(m_specular[0],m_specular[1],m_specular[2],m_specularity);
@@ -238,8 +253,7 @@ PyObject* KX_PolygonMaterial::_getattr(const STR_String& attr)
if (attr == "lightlayer")
return PyInt_FromLong(m_lightlayer);
if (attr == "triangle")
- // deprecated, triangle/quads shouldn't have been a material property
- return 0;
+ return PyInt_FromLong(m_bIsTriangle);
if (attr == "diffuse")
return PyObjectFrom(m_diffuse);
@@ -319,7 +333,7 @@ int KX_PolygonMaterial::_setattr(const STR_String &attr, PyObject *pyvalue)
// This probably won't work...
if (attr == "triangle")
{
- // deprecated, triangle/quads shouldn't have been a material property
+ m_bIsTriangle = value;
return 0;
}
}
@@ -372,9 +386,7 @@ KX_PYMETHODDEF_DOC(KX_PolygonMaterial, updateTexture, "updateTexture(tface, rast
{
MTFace *tface = (MTFace*) PyCObject_AsVoidPtr(pytface);
RAS_IRasterizer *rasty = (RAS_IRasterizer*) PyCObject_AsVoidPtr(pyrasty);
- Image *ima = (Image*)tface->tpage;
- GPU_update_image_time(ima, rasty->GetTime());
-
+ update_realtime_texture(tface, rasty->GetTime());
Py_Return;
}
@@ -387,7 +399,7 @@ KX_PYMETHODDEF_DOC(KX_PolygonMaterial, setTexture, "setTexture(tface)")
if (PyArg_ParseTuple(args, "O!", &PyCObject_Type, &pytface))
{
MTFace *tface = (MTFace*) PyCObject_AsVoidPtr(pytface);
- GPU_set_tpage(tface);
+ set_tpage(tface);
Py_Return;
}
diff --git a/source/gameengine/Ketsji/KX_PolygonMaterial.h b/source/gameengine/Ketsji/KX_PolygonMaterial.h
index fe116f757db..11c8baa8b1f 100644
--- a/source/gameengine/Ketsji/KX_PolygonMaterial.h
+++ b/source/gameengine/Ketsji/KX_PolygonMaterial.h
@@ -68,6 +68,8 @@ public:
bool alpha,
bool zsort,
int lightlayer,
+ bool bIsTriangle,
+ void* clientobject,
struct MTFace* tface,
unsigned int* mcol,
PyTypeObject *T = &Type);
diff --git a/source/gameengine/Ketsji/KX_PyConstraintBinding.cpp b/source/gameengine/Ketsji/KX_PyConstraintBinding.cpp
index fb37eded450..c01d6a632a3 100644
--- a/source/gameengine/Ketsji/KX_PyConstraintBinding.cpp
+++ b/source/gameengine/Ketsji/KX_PyConstraintBinding.cpp
@@ -34,8 +34,6 @@
#include "PHY_IPhysicsController.h"
#include "PHY_IVehicle.h"
-#include "PyObjectPlus.h"
-
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
@@ -93,7 +91,7 @@ static PyObject* gPySetGravity(PyObject* self,
return NULL;
}
- Py_RETURN_NONE;
+ Py_INCREF(Py_None); return Py_None;
}
static PyObject* gPySetDebugMode(PyObject* self,
@@ -114,7 +112,7 @@ static PyObject* gPySetDebugMode(PyObject* self,
return NULL;
}
- Py_RETURN_NONE;
+ Py_INCREF(Py_None); return Py_None;
}
@@ -134,7 +132,7 @@ static PyObject* gPySetNumTimeSubSteps(PyObject* self,
else {
return NULL;
}
- Py_RETURN_NONE;
+ Py_INCREF(Py_None); return Py_None;
}
@@ -153,7 +151,7 @@ static PyObject* gPySetNumIterations(PyObject* self,
else {
return NULL;
}
- Py_RETURN_NONE;
+ Py_INCREF(Py_None); return Py_None;
}
@@ -173,7 +171,7 @@ static PyObject* gPySetDeactivationTime(PyObject* self,
else {
return NULL;
}
- Py_RETURN_NONE;
+ Py_INCREF(Py_None); return Py_None;
}
@@ -192,7 +190,7 @@ static PyObject* gPySetDeactivationLinearTreshold(PyObject* self,
else {
return NULL;
}
- Py_RETURN_NONE;
+ Py_INCREF(Py_None); return Py_None;
}
@@ -211,7 +209,7 @@ static PyObject* gPySetDeactivationAngularTreshold(PyObject* self,
else {
return NULL;
}
- Py_RETURN_NONE;
+ Py_INCREF(Py_None); return Py_None;
}
static PyObject* gPySetContactBreakingTreshold(PyObject* self,
@@ -229,7 +227,7 @@ static PyObject* gPySetContactBreakingTreshold(PyObject* self,
else {
return NULL;
}
- Py_RETURN_NONE;
+ Py_INCREF(Py_None); return Py_None;
}
@@ -248,7 +246,7 @@ static PyObject* gPySetCcdMode(PyObject* self,
else {
return NULL;
}
- Py_RETURN_NONE;
+ Py_INCREF(Py_None); return Py_None;
}
static PyObject* gPySetSorConstant(PyObject* self,
@@ -266,7 +264,7 @@ static PyObject* gPySetSorConstant(PyObject* self,
else {
return NULL;
}
- Py_RETURN_NONE;
+ Py_INCREF(Py_None); return Py_None;
}
static PyObject* gPySetSolverTau(PyObject* self,
@@ -284,7 +282,7 @@ static PyObject* gPySetSolverTau(PyObject* self,
else {
return NULL;
}
- Py_RETURN_NONE;
+ Py_INCREF(Py_None); return Py_None;
}
@@ -303,7 +301,7 @@ static PyObject* gPySetSolverDamping(PyObject* self,
else {
return NULL;
}
- Py_RETURN_NONE;
+ Py_INCREF(Py_None); return Py_None;
}
static PyObject* gPySetLinearAirDamping(PyObject* self,
@@ -321,7 +319,7 @@ static PyObject* gPySetLinearAirDamping(PyObject* self,
else {
return NULL;
}
- Py_RETURN_NONE;
+ Py_INCREF(Py_None); return Py_None;
}
@@ -340,7 +338,7 @@ static PyObject* gPySetUseEpa(PyObject* self,
else {
return NULL;
}
- Py_RETURN_NONE;
+ Py_INCREF(Py_None); return Py_None;
}
static PyObject* gPySetSolverType(PyObject* self,
PyObject* args,
@@ -357,7 +355,7 @@ static PyObject* gPySetSolverType(PyObject* self,
else {
return NULL;
}
- Py_RETURN_NONE;
+ Py_INCREF(Py_None); return Py_None;
}
@@ -390,7 +388,7 @@ static PyObject* gPyGetVehicleConstraint(PyObject* self,
return NULL;
}
- Py_RETURN_NONE;
+ Py_INCREF(Py_None); return Py_None;
}
@@ -435,7 +433,7 @@ static PyObject* gPyCreateConstraint(PyObject* self,
PHY_IPhysicsController* physctrl2 = (PHY_IPhysicsController*) physicsid2;
if (physctrl) //TODO:check for existance of this pointer!
{
- int constraintid = PHY_GetActiveEnvironment()->createConstraint(physctrl,physctrl2,(enum PHY_ConstraintType)constrainttype,pivotX,pivotY,pivotZ,axisX,axisY,axisZ,0);
+ int constraintid = PHY_GetActiveEnvironment()->createConstraint(physctrl,physctrl2,(enum PHY_ConstraintType)constrainttype,pivotX,pivotY,pivotZ,axisX,axisY,axisZ);
KX_ConstraintWrapper* wrap = new KX_ConstraintWrapper((enum PHY_ConstraintType)constrainttype,constraintid,PHY_GetActiveEnvironment());
@@ -450,7 +448,7 @@ static PyObject* gPyCreateConstraint(PyObject* self,
return NULL;
}
- Py_RETURN_NONE;
+ Py_INCREF(Py_None); return Py_None;
}
@@ -504,60 +502,60 @@ static PyObject* gPyRemoveConstraint(PyObject* self,
return NULL;
}
- Py_RETURN_NONE;
+ Py_INCREF(Py_None); return Py_None;
}
static struct PyMethodDef physicsconstraints_methods[] = {
{"setGravity",(PyCFunction) gPySetGravity,
- METH_VARARGS, (PY_METHODCHAR)gPySetGravity__doc__},
+ METH_VARARGS, gPySetGravity__doc__},
{"setDebugMode",(PyCFunction) gPySetDebugMode,
- METH_VARARGS, (PY_METHODCHAR)gPySetDebugMode__doc__},
+ METH_VARARGS, gPySetDebugMode__doc__},
/// settings that influence quality of the rigidbody dynamics
{"setNumIterations",(PyCFunction) gPySetNumIterations,
- METH_VARARGS, (PY_METHODCHAR)gPySetNumIterations__doc__},
+ METH_VARARGS, gPySetNumIterations__doc__},
{"setNumTimeSubSteps",(PyCFunction) gPySetNumTimeSubSteps,
- METH_VARARGS, (PY_METHODCHAR)gPySetNumTimeSubSteps__doc__},
+ METH_VARARGS, gPySetNumTimeSubSteps__doc__},
{"setDeactivationTime",(PyCFunction) gPySetDeactivationTime,
- METH_VARARGS, (PY_METHODCHAR)gPySetDeactivationTime__doc__},
+ METH_VARARGS, gPySetDeactivationTime__doc__},
{"setDeactivationLinearTreshold",(PyCFunction) gPySetDeactivationLinearTreshold,
- METH_VARARGS, (PY_METHODCHAR)gPySetDeactivationLinearTreshold__doc__},
+ METH_VARARGS, gPySetDeactivationLinearTreshold__doc__},
{"setDeactivationAngularTreshold",(PyCFunction) gPySetDeactivationAngularTreshold,
- METH_VARARGS, (PY_METHODCHAR)gPySetDeactivationAngularTreshold__doc__},
+ METH_VARARGS, gPySetDeactivationAngularTreshold__doc__},
{"setContactBreakingTreshold",(PyCFunction) gPySetContactBreakingTreshold,
- METH_VARARGS, (PY_METHODCHAR)gPySetContactBreakingTreshold__doc__},
+ METH_VARARGS, gPySetContactBreakingTreshold__doc__},
{"setCcdMode",(PyCFunction) gPySetCcdMode,
- METH_VARARGS, (PY_METHODCHAR)gPySetCcdMode__doc__},
+ METH_VARARGS, gPySetCcdMode__doc__},
{"setSorConstant",(PyCFunction) gPySetSorConstant,
- METH_VARARGS, (PY_METHODCHAR)gPySetSorConstant__doc__},
+ METH_VARARGS, gPySetSorConstant__doc__},
{"setSolverTau",(PyCFunction) gPySetSolverTau,
- METH_VARARGS, (PY_METHODCHAR)gPySetSolverTau__doc__},
+ METH_VARARGS, gPySetSolverTau__doc__},
{"setSolverDamping",(PyCFunction) gPySetSolverDamping,
- METH_VARARGS, (PY_METHODCHAR)gPySetSolverDamping__doc__},
+ METH_VARARGS, gPySetSolverDamping__doc__},
{"setLinearAirDamping",(PyCFunction) gPySetLinearAirDamping,
- METH_VARARGS, (PY_METHODCHAR)gPySetLinearAirDamping__doc__},
+ METH_VARARGS, gPySetLinearAirDamping__doc__},
{"setUseEpa",(PyCFunction) gPySetUseEpa,
- METH_VARARGS, (PY_METHODCHAR)gPySetUseEpa__doc__},
+ METH_VARARGS, gPySetUseEpa__doc__},
{"setSolverType",(PyCFunction) gPySetSolverType,
- METH_VARARGS, (PY_METHODCHAR)gPySetSolverType__doc__},
+ METH_VARARGS, gPySetSolverType__doc__},
{"createConstraint",(PyCFunction) gPyCreateConstraint,
- METH_VARARGS, (PY_METHODCHAR)gPyCreateConstraint__doc__},
+ METH_VARARGS, gPyCreateConstraint__doc__},
{"getVehicleConstraint",(PyCFunction) gPyGetVehicleConstraint,
- METH_VARARGS, (PY_METHODCHAR)gPyGetVehicleConstraint__doc__},
+ METH_VARARGS, gPyGetVehicleConstraint__doc__},
{"removeConstraint",(PyCFunction) gPyRemoveConstraint,
- METH_VARARGS, (PY_METHODCHAR)gPyRemoveConstraint__doc__},
+ METH_VARARGS, gPyRemoveConstraint__doc__},
{"getAppliedImpulse",(PyCFunction) gPyGetAppliedImpulse,
- METH_VARARGS, (PY_METHODCHAR)gPyGetAppliedImpulse__doc__},
+ METH_VARARGS, gPyGetAppliedImpulse__doc__},
//sentinel
diff --git a/source/gameengine/Ketsji/KX_PythonInit.cpp b/source/gameengine/Ketsji/KX_PythonInit.cpp
index 0032d83c2ff..db4793de23d 100644
--- a/source/gameengine/Ketsji/KX_PythonInit.cpp
+++ b/source/gameengine/Ketsji/KX_PythonInit.cpp
@@ -30,13 +30,7 @@
#include "GL/glew.h"
-// directory header for py function getBlendFileList
#include <stdlib.h>
-#ifndef WIN32
- #include <dirent.h>
-#else
- #include "BLI_winstuff.h"
-#endif
#ifdef WIN32
#pragma warning (disable : 4786)
@@ -57,25 +51,21 @@
#include "BL_ActionActuator.h"
#include "RAS_IRasterizer.h"
#include "RAS_ICanvas.h"
-#include "RAS_BucketManager.h"
#include "MT_Vector3.h"
#include "MT_Point3.h"
#include "ListValue.h"
#include "KX_Scene.h"
#include "SND_DeviceManager.h"
+#include "RAS_OpenGLRasterizer/RAS_GLExtensionManager.h"
#include "BL_Shader.h"
#include "KX_PyMath.h"
-#include "PyObjectPlus.h"
-
extern "C" {
#include "Mathutils.h" // Blender.Mathutils module copied here so the blenderlayer can use.
}
-#include "marshal.h" /* python header for loading/saving dicts */
-
#include "PHY_IPhysicsEnvironment.h"
// FIXME: Enable for access to blender python modules. This is disabled because
// python has dependencies on a lot of other modules and is a pain to link.
@@ -87,7 +77,6 @@ extern "C" {
#include "BKE_utildefines.h"
#include "BKE_global.h"
#include "BLI_blenlib.h"
-#include "GPU_material.h"
static void setSandbox(TPythonSecurityLevel level);
@@ -95,9 +84,7 @@ static void setSandbox(TPythonSecurityLevel level);
// 'local' copy of canvas ptr, for window height/width python scripts
static RAS_ICanvas* gp_Canvas = NULL;
static KX_Scene* gp_KetsjiScene = NULL;
-static KX_KetsjiEngine* gp_KetsjiEngine = NULL;
static RAS_IRasterizer* gp_Rasterizer = NULL;
-static char gp_GamePythonPath[FILE_MAXDIR + FILE_MAXFILE] = "";
void KX_RasterizerDrawDebugLine(const MT_Vector3& from,const MT_Vector3& to,const MT_Vector3& color)
{
@@ -125,16 +112,20 @@ static PyObject* gPyGetRandomFloat(PyObject*)
return PyFloat_FromDouble(MT_random());
}
-static PyObject* gPySetGravity(PyObject*, PyObject* args)
+static PyObject* gPySetGravity(PyObject*,
+ PyObject* args,
+ PyObject*)
{
MT_Vector3 vec = MT_Vector3(0., 0., 0.);
- if (!PyVecArgTo(args, vec))
- return NULL;
-
- if (gp_KetsjiScene)
- gp_KetsjiScene->SetGravity(vec);
+ if (PyVecArgTo(args, vec))
+ {
+ if (gp_KetsjiScene)
+ gp_KetsjiScene->SetGravity(vec);
+
+ Py_Return;
+ }
- Py_RETURN_NONE;
+ return NULL;
}
static char gPyExpandPath_doc[] =
@@ -147,17 +138,20 @@ file to make a full path name (doesn't change during the game, even if you load\
other .blend).\n\
The function also converts the directory separator to the local file system format.";
-static PyObject* gPyExpandPath(PyObject*, PyObject* args)
+static PyObject* gPyExpandPath(PyObject*,
+ PyObject* args,
+ PyObject*)
{
char expanded[FILE_MAXDIR + FILE_MAXFILE];
char* filename;
- if (!PyArg_ParseTuple(args,"s",&filename))
- return NULL;
-
- BLI_strncpy(expanded, filename, FILE_MAXDIR + FILE_MAXFILE);
- BLI_convertstringcode(expanded, gp_GamePythonPath);
- return PyString_FromString(expanded);
+ if (PyArg_ParseTuple(args,"s",&filename))
+ {
+ BLI_strncpy(expanded, filename, FILE_MAXDIR + FILE_MAXFILE);
+ BLI_convertstringcode(expanded, G.sce);
+ return PyString_FromString(expanded);
+ }
+ return NULL;
}
@@ -185,62 +179,62 @@ static PyObject* gPyGetSpectrum(PyObject*)
PyList_SetItem(resultlist, index, PyFloat_FromDouble(spectrum[index]));
}
}
- else {
- for (int index = 0; index < 512; index++)
- {
- PyList_SetItem(resultlist, index, PyFloat_FromDouble(0.0));
- }
- }
return resultlist;
}
-static PyObject* gPyStartDSP(PyObject*, PyObject* args)
+static PyObject* gPyStartDSP(PyObject*,
+ PyObject* args,
+ PyObject*)
{
SND_IAudioDevice* audiodevice = SND_DeviceManager::Instance();
- if (!audiodevice) {
- PyErr_SetString(PyExc_RuntimeError, "no audio device available");
- return NULL;
- }
-
- if (!usedsp) {
- audiodevice->StartUsingDSP();
- usedsp = true;
+ if (audiodevice)
+ {
+ if (!usedsp)
+ {
+ audiodevice->StartUsingDSP();
+ usedsp = true;
+ Py_Return;
+ }
}
-
- Py_RETURN_NONE;
+ return NULL;
}
-static PyObject* gPyStopDSP(PyObject*, PyObject* args)
+static PyObject* gPyStopDSP(PyObject*,
+ PyObject* args,
+ PyObject*)
{
SND_IAudioDevice* audiodevice = SND_DeviceManager::Instance();
- if (!audiodevice) {
- PyErr_SetString(PyExc_RuntimeError, "no audio device available");
- return NULL;
- }
-
- if (usedsp) {
- audiodevice->StopUsingDSP();
- usedsp = true;
+ if (audiodevice)
+ {
+ if (usedsp)
+ {
+ audiodevice->StopUsingDSP();
+ usedsp = false;
+ Py_Return;
+ }
}
-
- Py_RETURN_NONE;
+ return NULL;
}
-static PyObject* gPySetLogicTicRate(PyObject*, PyObject* args)
+static PyObject* gPySetLogicTicRate(PyObject*,
+ PyObject* args,
+ PyObject*)
{
float ticrate;
- if (!PyArg_ParseTuple(args, "f", &ticrate))
- return NULL;
+ if (PyArg_ParseTuple(args, "f", &ticrate))
+ {
+ KX_KetsjiEngine::SetTicRate(ticrate);
+ Py_Return;
+ }
- KX_KetsjiEngine::SetTicRate(ticrate);
- Py_RETURN_NONE;
+ return NULL;
}
static PyObject* gPyGetLogicTicRate(PyObject*)
@@ -248,24 +242,33 @@ static PyObject* gPyGetLogicTicRate(PyObject*)
return PyFloat_FromDouble(KX_KetsjiEngine::GetTicRate());
}
-static PyObject* gPySetPhysicsTicRate(PyObject*, PyObject* args)
+static PyObject* gPySetPhysicsTicRate(PyObject*,
+ PyObject* args,
+ PyObject*)
{
float ticrate;
- if (!PyArg_ParseTuple(args, "f", &ticrate))
- return NULL;
+ if (PyArg_ParseTuple(args, "f", &ticrate))
+ {
+
+ PHY_GetActiveEnvironment()->setFixedTimeStep(true,ticrate);
+ Py_Return;
+ }
- PHY_GetActiveEnvironment()->setFixedTimeStep(true,ticrate);
- Py_RETURN_NONE;
+ return NULL;
}
-static PyObject* gPySetPhysicsDebug(PyObject*, PyObject* args)
+static PyObject* gPySetPhysicsDebug(PyObject*,
+ PyObject* args,
+ PyObject*)
{
int debugMode;
- if (!PyArg_ParseTuple(args, "i", &debugMode))
- return NULL;
+ if (PyArg_ParseTuple(args, "i", &debugMode))
+ {
+ PHY_GetActiveEnvironment()->setDebugMode(debugMode);
+ Py_Return;
+ }
- PHY_GetActiveEnvironment()->setDebugMode(debugMode);
- Py_RETURN_NONE;
+ return NULL;
}
@@ -275,51 +278,6 @@ static PyObject* gPyGetPhysicsTicRate(PyObject*)
return PyFloat_FromDouble(PHY_GetActiveEnvironment()->getFixedTimeStep());
}
-static PyObject* gPyGetAverageFrameRate(PyObject*)
-{
- return PyFloat_FromDouble(KX_KetsjiEngine::GetAverageFrameRate());
-}
-
-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", &searchpath))
- return NULL;
-
- list = PyList_New(0);
-
- if (searchpath) {
- BLI_strncpy(cpath, searchpath, FILE_MAXDIR + FILE_MAXFILE);
- BLI_convertstringcode(cpath, gp_GamePythonPath);
- } else {
- /* Get the dir only */
- BLI_split_dirfile_basic(gp_GamePythonPath, cpath, NULL);
- }
-
- if((dp = opendir(cpath)) == NULL) {
- /* todo, show the errno, this shouldnt happen anyway if the blendfile is readable */
- fprintf(stderr, "Could not read directoty (%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 = PyString_FromString(dirp->d_name);
- PyList_Append(list, value);
- Py_DECREF(value);
- }
- }
-
- closedir(dp);
- return list;
-}
-
static STR_String gPyGetCurrentScene_doc =
"getCurrentScene()\n"
"Gets a reference to the current scene.\n";
@@ -397,45 +355,56 @@ static PyObject *pyPrintExt(PyObject *,PyObject *,PyObject *)
if(!count)
pprint("No extenstions are used in this build");
- Py_RETURN_NONE;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static struct PyMethodDef game_methods[] = {
- {"expandPath", (PyCFunction)gPyExpandPath, METH_VARARGS, (PY_METHODCHAR)gPyExpandPath_doc},
+ {"expandPath", (PyCFunction)gPyExpandPath, METH_VARARGS, gPyExpandPath_doc},
{"getCurrentController",
(PyCFunction) SCA_PythonController::sPyGetCurrentController,
- METH_NOARGS, (PY_METHODCHAR)SCA_PythonController::sPyGetCurrentController__doc__},
+ METH_NOARGS, SCA_PythonController::sPyGetCurrentController__doc__},
{"getCurrentScene", (PyCFunction) gPyGetCurrentScene,
- METH_NOARGS, (PY_METHODCHAR)gPyGetCurrentScene_doc.Ptr()},
+ METH_NOARGS, gPyGetCurrentScene_doc.Ptr()},
{"addActiveActuator",(PyCFunction) SCA_PythonController::sPyAddActiveActuator,
- METH_VARARGS, (PY_METHODCHAR)SCA_PythonController::sPyAddActiveActuator__doc__},
+ METH_VARARGS, SCA_PythonController::sPyAddActiveActuator__doc__},
{"getRandomFloat",(PyCFunction) gPyGetRandomFloat,
- METH_NOARGS, (PY_METHODCHAR)gPyGetRandomFloat_doc.Ptr()},
- {"setGravity",(PyCFunction) gPySetGravity, METH_VARARGS, (PY_METHODCHAR)"set Gravitation"},
- {"getSpectrum",(PyCFunction) gPyGetSpectrum, METH_NOARGS, (PY_METHODCHAR)"get audio spectrum"},
- {"stopDSP",(PyCFunction) gPyStopDSP, METH_VARARGS, (PY_METHODCHAR)"stop using the audio dsp (for performance reasons)"},
- {"getLogicTicRate", (PyCFunction) gPyGetLogicTicRate, METH_NOARGS, (PY_METHODCHAR)"Gets the logic tic rate"},
- {"setLogicTicRate", (PyCFunction) gPySetLogicTicRate, METH_VARARGS, (PY_METHODCHAR)"Sets the logic tic rate"},
- {"getPhysicsTicRate", (PyCFunction) gPyGetPhysicsTicRate, METH_NOARGS, (PY_METHODCHAR)"Gets the physics tic rate"},
- {"setPhysicsTicRate", (PyCFunction) gPySetPhysicsTicRate, METH_VARARGS, (PY_METHODCHAR)"Sets the physics tic rate"},
- {"getAverageFrameRate", (PyCFunction) gPyGetAverageFrameRate, METH_NOARGS, (PY_METHODCHAR)"Gets the estimated average frame rate"},
- {"getBlendFileList", (PyCFunction)gPyGetBlendFileList, METH_VARARGS, (PY_METHODCHAR)"Gets a list of blend files in the same directory as the current blend file"},
- {"PrintGLInfo", (PyCFunction)pyPrintExt, METH_NOARGS, (PY_METHODCHAR)"Prints GL Extension Info"},
+ METH_NOARGS,gPyGetRandomFloat_doc.Ptr()},
+ {"setGravity",(PyCFunction) gPySetGravity, METH_VARARGS,"set Gravitation"},
+ {"getSpectrum",(PyCFunction) gPyGetSpectrum, METH_NOARGS,"get audio spectrum"},
+ {"stopDSP",(PyCFunction) gPyStopDSP, METH_VARARGS,"stop using the audio dsp (for performance reasons)"},
+ {"getLogicTicRate", (PyCFunction) gPyGetLogicTicRate, METH_NOARGS, "Gets the logic tic rate"},
+ {"setLogicTicRate", (PyCFunction) gPySetLogicTicRate, METH_VARARGS, "Sets the logic tic rate"},
+ {"getPhysicsTicRate", (PyCFunction) gPyGetPhysicsTicRate, METH_NOARGS, "Gets the physics tic rate"},
+ {"setPhysicsTicRate", (PyCFunction) gPySetPhysicsTicRate, METH_VARARGS, "Sets the physics tic rate"},
+ {"PrintGLInfo", (PyCFunction)pyPrintExt, METH_NOARGS, "Prints GL Extension Info"},
{NULL, (PyCFunction) NULL, 0, NULL }
};
-static PyObject* gPyGetWindowHeight(PyObject*, PyObject* args)
+static PyObject* gPyGetWindowHeight(PyObject*,
+ PyObject* args,
+ PyObject*)
{
- return PyInt_FromLong((gp_Canvas ? gp_Canvas->GetHeight() : 0));
+ int height = (gp_Canvas ? gp_Canvas->GetHeight() : 0);
+
+ PyObject* heightval = PyInt_FromLong(height);
+ return heightval;
}
-static PyObject* gPyGetWindowWidth(PyObject*, PyObject* args)
+static PyObject* gPyGetWindowWidth(PyObject*,
+ PyObject* args,
+ PyObject*)
{
- return PyInt_FromLong((gp_Canvas ? gp_Canvas->GetWidth() : 0));
+
+
+ int width = (gp_Canvas ? gp_Canvas->GetWidth() : 0);
+
+ PyObject* widthval = PyInt_FromLong(width);
+ return widthval;
}
@@ -443,403 +412,282 @@ static PyObject* gPyGetWindowWidth(PyObject*, PyObject* args)
// temporarility visibility thing, will be moved to rasterizer/renderer later
bool gUseVisibilityTemp = false;
-static PyObject* gPyEnableVisibility(PyObject*, PyObject* args)
+static PyObject* gPyEnableVisibility(PyObject*,
+ PyObject* args,
+ PyObject*)
{
int visible;
- if (!PyArg_ParseTuple(args,"i",&visible))
+ if (PyArg_ParseTuple(args,"i",&visible))
+ {
+ gUseVisibilityTemp = (visible != 0);
+ }
+ else
+ {
return NULL;
-
- gUseVisibilityTemp = (visible != 0);
- Py_RETURN_NONE;
+ }
+ Py_Return;
}
-static PyObject* gPyShowMouse(PyObject*, PyObject* args)
+static PyObject* gPyShowMouse(PyObject*,
+ PyObject* args,
+ PyObject*)
{
int visible;
- if (!PyArg_ParseTuple(args,"i",&visible))
- return NULL;
-
- if (visible)
+ if (PyArg_ParseTuple(args,"i",&visible))
{
- if (gp_Canvas)
- gp_Canvas->SetMouseState(RAS_ICanvas::MOUSE_NORMAL);
- } else
- {
- if (gp_Canvas)
- gp_Canvas->SetMouseState(RAS_ICanvas::MOUSE_INVISIBLE);
+ if (visible)
+ {
+ if (gp_Canvas)
+ gp_Canvas->SetMouseState(RAS_ICanvas::MOUSE_NORMAL);
+ } else
+ {
+ if (gp_Canvas)
+ gp_Canvas->SetMouseState(RAS_ICanvas::MOUSE_INVISIBLE);
+ }
+ }
+ else {
+ return NULL;
}
- Py_RETURN_NONE;
+ Py_Return;
}
-static PyObject* gPySetMousePosition(PyObject*, PyObject* args)
+static PyObject* gPySetMousePosition(PyObject*,
+ PyObject* args,
+ PyObject*)
{
int x,y;
- if (!PyArg_ParseTuple(args,"ii",&x,&y))
+ if (PyArg_ParseTuple(args,"ii",&x,&y))
+ {
+ if (gp_Canvas)
+ gp_Canvas->SetMousePosition(x,y);
+ }
+ else {
return NULL;
+ }
- if (gp_Canvas)
- gp_Canvas->SetMousePosition(x,y);
-
- Py_RETURN_NONE;
+ Py_Return;
}
-static PyObject* gPySetEyeSeparation(PyObject*, PyObject* args)
+static PyObject* gPySetEyeSeparation(PyObject*,
+ PyObject* args,
+ PyObject*)
{
float sep;
- if (!PyArg_ParseTuple(args, "f", &sep))
- return NULL;
-
- if (!gp_Rasterizer) {
- PyErr_SetString(PyExc_RuntimeError, "Rasterizer not available");
- return NULL;
+ if (PyArg_ParseTuple(args, "f", &sep))
+ {
+ if (gp_Rasterizer)
+ gp_Rasterizer->SetEyeSeparation(sep);
+
+ Py_Return;
}
- gp_Rasterizer->SetEyeSeparation(sep);
-
- Py_RETURN_NONE;
+ return NULL;
}
static PyObject* gPyGetEyeSeparation(PyObject*, PyObject*, PyObject*)
{
- if (!gp_Rasterizer) {
- PyErr_SetString(PyExc_RuntimeError, "Rasterizer not available");
- return NULL;
- }
+ if (gp_Rasterizer)
+ return PyFloat_FromDouble(gp_Rasterizer->GetEyeSeparation());
- return PyFloat_FromDouble(gp_Rasterizer->GetEyeSeparation());
+ return NULL;
}
-static PyObject* gPySetFocalLength(PyObject*, PyObject* args)
+static PyObject* gPySetFocalLength(PyObject*,
+ PyObject* args,
+ PyObject*)
{
float focus;
- if (!PyArg_ParseTuple(args, "f", &focus))
- return NULL;
-
- if (!gp_Rasterizer) {
- PyErr_SetString(PyExc_RuntimeError, "Rasterizer not available");
- return NULL;
+ if (PyArg_ParseTuple(args, "f", &focus))
+ {
+ if (gp_Rasterizer)
+ gp_Rasterizer->SetFocalLength(focus);
+ Py_Return;
}
-
- gp_Rasterizer->SetFocalLength(focus);
- Py_RETURN_NONE;
+ return NULL;
}
static PyObject* gPyGetFocalLength(PyObject*, PyObject*, PyObject*)
{
- if (!gp_Rasterizer) {
- PyErr_SetString(PyExc_RuntimeError, "Rasterizer not available");
- return NULL;
- }
-
- return PyFloat_FromDouble(gp_Rasterizer->GetFocalLength());
-
- Py_RETURN_NONE;
+ if (gp_Rasterizer)
+ return PyFloat_FromDouble(gp_Rasterizer->GetFocalLength());
+ return NULL;
}
-static PyObject* gPySetBackgroundColor(PyObject*, PyObject* args)
+static PyObject* gPySetBackgroundColor(PyObject*,
+ PyObject* args,
+ PyObject*)
{
MT_Vector4 vec = MT_Vector4(0., 0., 0.3, 0.);
- if (!PyVecArgTo(args, vec))
- return NULL;
-
- if (gp_Canvas)
+ if (PyVecArgTo(args, vec))
{
- gp_Rasterizer->SetBackColor(vec[0], vec[1], vec[2], vec[3]);
+ if (gp_Canvas)
+ {
+ gp_Rasterizer->SetBackColor(vec[0], vec[1], vec[2], vec[3]);
+ }
+ Py_Return;
}
- Py_RETURN_NONE;
+
+ return NULL;
}
-static PyObject* gPySetMistColor(PyObject*, PyObject* args)
+static PyObject* gPySetMistColor(PyObject*,
+ PyObject* args,
+ PyObject*)
{
MT_Vector3 vec = MT_Vector3(0., 0., 0.);
- if (!PyVecArgTo(args, vec))
- return NULL;
-
- if (!gp_Rasterizer) {
- PyErr_SetString(PyExc_RuntimeError, "Rasterizer not available");
- return NULL;
- }
- gp_Rasterizer->SetFogColor(vec[0], vec[1], vec[2]);
+ if (PyVecArgTo(args, vec))
+ {
+ if (gp_Rasterizer)
+ {
+ gp_Rasterizer->SetFogColor(vec[0], vec[1], vec[2]);
+ }
+ Py_Return;
+ }
- Py_RETURN_NONE;
+ return NULL;
}
-static PyObject* gPySetMistStart(PyObject*, PyObject* args)
+static PyObject* gPySetMistStart(PyObject*,
+ PyObject* args,
+ PyObject*)
{
float miststart;
- if (!PyArg_ParseTuple(args,"f",&miststart))
- return NULL;
-
- if (!gp_Rasterizer) {
- PyErr_SetString(PyExc_RuntimeError, "Rasterizer not available");
+ if (PyArg_ParseTuple(args,"f",&miststart))
+ {
+ if (gp_Rasterizer)
+ {
+ gp_Rasterizer->SetFogStart(miststart);
+ }
+ }
+ else {
return NULL;
}
-
- gp_Rasterizer->SetFogStart(miststart);
-
- Py_RETURN_NONE;
+ Py_Return;
}
-static PyObject* gPySetMistEnd(PyObject*, PyObject* args)
+static PyObject* gPySetMistEnd(PyObject*,
+ PyObject* args,
+ PyObject*)
{
float mistend;
- if (!PyArg_ParseTuple(args,"f",&mistend))
- return NULL;
-
- if (!gp_Rasterizer) {
- PyErr_SetString(PyExc_RuntimeError, "Rasterizer not available");
+ if (PyArg_ParseTuple(args,"f",&mistend))
+ {
+ if (gp_Rasterizer)
+ {
+ gp_Rasterizer->SetFogEnd(mistend);
+ }
+ }
+ else {
return NULL;
}
-
- gp_Rasterizer->SetFogEnd(mistend);
-
- Py_RETURN_NONE;
+ Py_Return;
}
-static PyObject* gPySetAmbientColor(PyObject*, PyObject* args)
+static PyObject* gPySetAmbientColor(PyObject*,
+ PyObject* args,
+ PyObject*)
{
MT_Vector3 vec = MT_Vector3(0., 0., 0.);
- if (!PyVecArgTo(args, vec))
- return NULL;
-
- if (!gp_Rasterizer) {
- PyErr_SetString(PyExc_RuntimeError, "Rasterizer not available");
- return NULL;
- }
- gp_Rasterizer->SetAmbientColor(vec[0], vec[1], vec[2]);
+ if (PyVecArgTo(args, vec))
+ {
+ if (gp_Rasterizer)
+ {
+ gp_Rasterizer->SetAmbientColor(vec[0], vec[1], vec[2]);
+ }
+ Py_Return;
+ }
- Py_RETURN_NONE;
+ return NULL;
}
-static PyObject* gPyMakeScreenshot(PyObject*, PyObject* args)
+static PyObject* gPyMakeScreenshot(PyObject*,
+ PyObject* args,
+ PyObject*)
{
char* filename;
- if (!PyArg_ParseTuple(args,"s",&filename))
- return NULL;
-
- if (gp_Canvas)
+ if (PyArg_ParseTuple(args,"s",&filename))
{
- gp_Canvas->MakeScreenShot(filename);
- }
-
- Py_RETURN_NONE;
-}
-
-static PyObject* gPyEnableMotionBlur(PyObject*, PyObject* args)
-{
- float motionblurvalue;
- if (!PyArg_ParseTuple(args,"f",&motionblurvalue))
- return NULL;
-
- if (!gp_Rasterizer) {
- PyErr_SetString(PyExc_RuntimeError, "Rasterizer not available");
- return NULL;
+ if (gp_Canvas)
+ {
+ gp_Canvas->MakeScreenShot(filename);
+ }
}
-
- gp_Rasterizer->EnableMotionBlur(motionblurvalue);
-
- Py_RETURN_NONE;
-}
-
-static PyObject* gPyDisableMotionBlur(PyObject*, PyObject* args)
-{
- if (!gp_Rasterizer) {
- PyErr_SetString(PyExc_RuntimeError, "Rasterizer not available");
+ else {
return NULL;
}
-
- gp_Rasterizer->DisableMotionBlur();
-
- Py_RETURN_NONE;
+ Py_Return;
}
-int getGLSLSettingFlag(char *setting)
-{
- if(strcmp(setting, "lights") == 0)
- return G_FILE_GLSL_NO_LIGHTS;
- else if(strcmp(setting, "shaders") == 0)
- return G_FILE_GLSL_NO_SHADERS;
- else if(strcmp(setting, "shadows") == 0)
- return G_FILE_GLSL_NO_SHADOWS;
- else if(strcmp(setting, "ramps") == 0)
- return G_FILE_GLSL_NO_RAMPS;
- else if(strcmp(setting, "nodes") == 0)
- return G_FILE_GLSL_NO_NODES;
- else if(strcmp(setting, "extra_textures") == 0)
- return G_FILE_GLSL_NO_EXTRA_TEX;
- else
- return -1;
-}
-
-static PyObject* gPySetGLSLMaterialSetting(PyObject*,
- PyObject* args,
- PyObject*)
+static PyObject* gPyEnableMotionBlur(PyObject*,
+ PyObject* args,
+ PyObject*)
{
- char *setting;
- int enable, flag, fileflags;
-
- if (!PyArg_ParseTuple(args,"si",&setting,&enable))
- return NULL;
-
- flag = getGLSLSettingFlag(setting);
-
- if (flag==-1) {
- PyErr_SetString(PyExc_ValueError, "glsl setting is not known");
- return NULL;
- }
-
- fileflags = G.fileflags;
-
- if (enable)
- G.fileflags &= ~flag;
- else
- G.fileflags |= flag;
-
- /* display lists and GLSL materials need to be remade */
- if(G.fileflags != fileflags) {
- if(gp_KetsjiEngine) {
- KX_SceneList *scenes = gp_KetsjiEngine->CurrentScenes();
- KX_SceneList::iterator it;
-
- for(it=scenes->begin(); it!=scenes->end(); it++)
- if((*it)->GetBucketManager())
- (*it)->GetBucketManager()->ReleaseDisplayLists();
+ float motionblurvalue;
+ if (PyArg_ParseTuple(args,"f",&motionblurvalue))
+ {
+ if(gp_Rasterizer)
+ {
+ gp_Rasterizer->EnableMotionBlur(motionblurvalue);
}
-
- GPU_materials_free();
}
-
- Py_RETURN_NONE;
-}
-
-static PyObject* gPyGetGLSLMaterialSetting(PyObject*,
- PyObject* args,
- PyObject*)
-{
- char *setting;
- int enabled = 0, flag;
-
- if (!PyArg_ParseTuple(args,"s",&setting))
- return NULL;
-
- flag = getGLSLSettingFlag(setting);
-
- if (flag==-1) {
- PyErr_SetString(PyExc_ValueError, "glsl setting is not known");
+ else {
return NULL;
}
-
- enabled = ((G.fileflags & flag) != 0);
- return PyInt_FromLong(enabled);
+ Py_Return;
}
-#define KX_TEXFACE_MATERIAL 0
-#define KX_BLENDER_MULTITEX_MATERIAL 1
-#define KX_BLENDER_GLSL_MATERIAL 2
-
-static PyObject* gPySetMaterialType(PyObject*,
+static PyObject* gPyDisableMotionBlur(PyObject*,
PyObject* args,
PyObject*)
{
- int flag, type;
-
- if (!PyArg_ParseTuple(args,"i",&type))
- return NULL;
-
- if(type == KX_BLENDER_GLSL_MATERIAL)
- flag = G_FILE_GAME_MAT|G_FILE_GAME_MAT_GLSL;
- else if(type == KX_BLENDER_MULTITEX_MATERIAL)
- flag = G_FILE_GAME_MAT;
- else if(type == KX_TEXFACE_MATERIAL)
- flag = 0;
- else {
- PyErr_SetString(PyExc_ValueError, "material type is not known");
- return NULL;
+ if(gp_Rasterizer)
+ {
+ gp_Rasterizer->DisableMotionBlur();
}
-
- G.fileflags &= ~(G_FILE_GAME_MAT|G_FILE_GAME_MAT_GLSL);
- G.fileflags |= flag;
-
- Py_RETURN_NONE;
+ Py_Return;
}
-static PyObject* gPyGetMaterialType(PyObject*)
-{
- int flag;
-
- if(G.fileflags & (G_FILE_GAME_MAT|G_FILE_GAME_MAT_GLSL))
- flag = KX_BLENDER_GLSL_MATERIAL;
- else if(G.fileflags & G_FILE_GAME_MAT)
- flag = KX_BLENDER_MULTITEX_MATERIAL;
- else
- flag = KX_TEXFACE_MATERIAL;
-
- return PyInt_FromLong(flag);
-}
-
-static PyObject* gPyDrawLine(PyObject*, PyObject* args)
-{
- PyObject* ob_from;
- PyObject* ob_to;
- PyObject* ob_color;
-
- if (!gp_Rasterizer) {
- PyErr_SetString(PyExc_RuntimeError, "Rasterizer not available");
- return NULL;
- }
-
- if (!PyArg_ParseTuple(args,"OOO",&ob_from,&ob_to,&ob_color))
- return NULL;
-
- MT_Vector3 from(0., 0., 0.);
- MT_Vector3 to(0., 0., 0.);
- MT_Vector3 color(0., 0., 0.);
- if (!PyVecTo(ob_from, from))
- return NULL;
- if (!PyVecTo(ob_to, to))
- return NULL;
- if (!PyVecTo(ob_color, color))
- return NULL;
-
- gp_Rasterizer->DrawDebugLine(from,to,color);
-
- Py_RETURN_NONE;
-}
+STR_String gPyGetWindowHeight__doc__="getWindowHeight doc";
+STR_String gPyGetWindowWidth__doc__="getWindowWidth doc";
+STR_String gPyEnableVisibility__doc__="enableVisibility doc";
+STR_String gPyMakeScreenshot__doc__="make Screenshot doc";
+STR_String gPyShowMouse__doc__="showMouse(bool visible)";
+STR_String gPySetMousePosition__doc__="setMousePosition(int x,int y)";
static struct PyMethodDef rasterizer_methods[] = {
{"getWindowWidth",(PyCFunction) gPyGetWindowWidth,
- METH_VARARGS, "getWindowWidth doc"},
+ METH_VARARGS, gPyGetWindowWidth__doc__.Ptr()},
{"getWindowHeight",(PyCFunction) gPyGetWindowHeight,
- METH_VARARGS, "getWindowHeight doc"},
+ METH_VARARGS, gPyGetWindowHeight__doc__.Ptr()},
{"makeScreenshot",(PyCFunction)gPyMakeScreenshot,
- METH_VARARGS, "make Screenshot doc"},
+ METH_VARARGS, gPyMakeScreenshot__doc__.Ptr()},
{"enableVisibility",(PyCFunction) gPyEnableVisibility,
- METH_VARARGS, "enableVisibility doc"},
+ METH_VARARGS, gPyEnableVisibility__doc__.Ptr()},
{"showMouse",(PyCFunction) gPyShowMouse,
- METH_VARARGS, "showMouse(bool visible)"},
+ METH_VARARGS, gPyShowMouse__doc__.Ptr()},
{"setMousePosition",(PyCFunction) gPySetMousePosition,
- METH_VARARGS, "setMousePosition(int x,int y)"},
+ METH_VARARGS, gPySetMousePosition__doc__.Ptr()},
{"setBackgroundColor",(PyCFunction)gPySetBackgroundColor,METH_VARARGS,"set Background Color (rgb)"},
{"setAmbientColor",(PyCFunction)gPySetAmbientColor,METH_VARARGS,"set Ambient Color (rgb)"},
{"setMistColor",(PyCFunction)gPySetMistColor,METH_VARARGS,"set Mist Color (rgb)"},
@@ -853,19 +701,11 @@ static struct PyMethodDef rasterizer_methods[] = {
{"getEyeSeparation", (PyCFunction) gPyGetEyeSeparation, METH_VARARGS, "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"},
- {"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"},
- {"drawLine", (PyCFunction) gPyDrawLine,
- METH_VARARGS, "draw a line on the screen"},
{ NULL, (PyCFunction) NULL, 0, NULL }
};
+
+
// Initialization function for the module (*must* be called initGameLogic)
static char GameLogic_module_documentation[] =
@@ -878,12 +718,11 @@ static char Rasterizer_module_documentation[] =
-PyObject* initGameLogic(KX_KetsjiEngine *engine, KX_Scene* scene) // quick hack to get gravity hook
+PyObject* initGameLogic(KX_Scene* scene) // quick hack to get gravity hook
{
PyObject* m;
PyObject* d;
- gp_KetsjiEngine = engine;
gp_KetsjiScene = scene;
gUseVisibilityTemp=false;
@@ -895,10 +734,6 @@ PyObject* initGameLogic(KX_KetsjiEngine *engine, KX_Scene* scene) // quick hack
// 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", PyDict_New());
ErrorObject = PyString_FromString("GameLogic.error");
PyDict_SetItemString(d, "error", ErrorObject);
@@ -1000,38 +835,6 @@ PyObject* initGameLogic(KX_KetsjiEngine *engine, KX_Scene* scene) // quick hack
KX_MACRO_addTypesToDict(d, CAM_POS, BL_Shader::CAM_POS);
KX_MACRO_addTypesToDict(d, CONSTANT_TIMER, BL_Shader::CONSTANT_TIMER);
- /* 10 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));
-
// Check for errors
if (PyErr_Occurred())
{
@@ -1045,30 +848,13 @@ PyObject* initGameLogic(KX_KetsjiEngine *engine, KX_Scene* scene) // quick hack
// override builtin functions import() and open()
-PyObject *KXpy_open(PyObject *self, PyObject *args) {
+PyObject *KXpy_open(PyObject *self, PyObject *args)
+{
PyErr_SetString(PyExc_RuntimeError, "Sandbox: open() function disabled!\nGame Scripts should not use this function.");
return NULL;
}
-PyObject *KXpy_reload(PyObject *self, PyObject *args) {
- PyErr_SetString(PyExc_RuntimeError, "Sandbox: reload() function disabled!\nGame Scripts should not use this function.");
- return NULL;
-}
-PyObject *KXpy_file(PyObject *self, PyObject *args) {
- PyErr_SetString(PyExc_RuntimeError, "Sandbox: file() function disabled!\nGame Scripts should not use this function.");
- return NULL;
-}
-
-PyObject *KXpy_execfile(PyObject *self, PyObject *args) {
- PyErr_SetString(PyExc_RuntimeError, "Sandbox: execfile() function disabled!\nGame Scripts should not use this function.");
- return NULL;
-}
-
-PyObject *KXpy_compile(PyObject *self, PyObject *args) {
- PyErr_SetString(PyExc_RuntimeError, "Sandbox: compile() function disabled!\nGame Scripts should not use this function.");
- return NULL;
-}
PyObject *KXpy_import(PyObject *self, PyObject *args)
{
@@ -1078,17 +864,9 @@ PyObject *KXpy_import(PyObject *self, PyObject *args)
PyObject *fromlist = NULL;
PyObject *l, *m, *n;
-#if (PY_VERSION_HEX >= 0x02060000)
- int dummy_val; /* what does this do?*/
-
- if (!PyArg_ParseTuple(args, "s|OOOi:m_import",
- &name, &globals, &locals, &fromlist, &dummy_val))
- return NULL;
-#else
if (!PyArg_ParseTuple(args, "s|OOO:m_import",
&name, &globals, &locals, &fromlist))
return NULL;
-#endif
/* check for builtin modules */
m = PyImport_AddModule("sys");
@@ -1112,67 +890,40 @@ PyObject *KXpy_import(PyObject *self, PyObject *args)
}
-/* override python file type functions */
-#if 0
-static int
-file_init(PyObject *self, PyObject *args, PyObject *kwds)
-{
- KXpy_file(NULL, NULL);
- return -1;
-}
-static PyObject *
-file_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
-{
- return KXpy_file(NULL, NULL);
-}
-#endif
-static PyMethodDef meth_open[] = {{ "open", KXpy_open, METH_VARARGS, "(disabled)"}};
-static PyMethodDef meth_reload[] = {{ "reload", KXpy_reload, METH_VARARGS, "(disabled)"}};
-static PyMethodDef meth_file[] = {{ "file", KXpy_file, METH_VARARGS, "(disabled)"}};
-static PyMethodDef meth_execfile[] = {{ "execfile", KXpy_execfile, METH_VARARGS, "(disabled)"}};
-static PyMethodDef meth_compile[] = {{ "compile", KXpy_compile, METH_VARARGS, "(disabled)"}};
+static PyMethodDef meth_open[] = {
+ { "open", KXpy_open, METH_VARARGS,
+ "(disabled)"}
+};
+
+
+static PyMethodDef meth_import[] = {
+ { "import", KXpy_import, METH_VARARGS,
+ "our own import"}
+};
+
-static PyMethodDef meth_import[] = {{ "import", KXpy_import, METH_VARARGS, "our own import"}};
//static PyObject *g_oldopen = 0;
//static PyObject *g_oldimport = 0;
//static int g_security = 0;
+
void setSandbox(TPythonSecurityLevel level)
{
PyObject *m = PyImport_AddModule("__builtin__");
PyObject *d = PyModule_GetDict(m);
+ PyObject *meth = PyCFunction_New(meth_open, NULL);
switch (level) {
case psl_Highest:
//if (!g_security) {
//g_oldopen = PyDict_GetItemString(d, "open");
-
- // functions we cant trust
- PyDict_SetItemString(d, "open", PyCFunction_New(meth_open, NULL));
- PyDict_SetItemString(d, "reload", PyCFunction_New(meth_reload, NULL));
- PyDict_SetItemString(d, "file", PyCFunction_New(meth_file, NULL));
- PyDict_SetItemString(d, "execfile", PyCFunction_New(meth_execfile, NULL));
- PyDict_SetItemString(d, "compile", PyCFunction_New(meth_compile, NULL));
-
- // our own import
- PyDict_SetItemString(d, "__import__", PyCFunction_New(meth_import, NULL));
+ PyDict_SetItemString(d, "open", meth);
+ meth = PyCFunction_New(meth_import, NULL);
+ PyDict_SetItemString(d, "__import__", meth);
//g_security = level;
-
- // Overiding file dosnt stop it being accessed if your sneaky
- // f = [ t for t in (1).__class__.__mro__[-1].__subclasses__() if t.__name__ == 'file'][0]('/some_file.txt', 'w')
- // f.write('...')
- // so overwrite the file types functions. be very careful here still, since python uses python.
- // ps - python devs frown deeply upon this.
-
- /* this could mess up pythons internals, if we are serious about sandboxing
- * issues like the one above need to be solved, possibly modify __subclasses__ is safer? */
-#if 0
- PyFile_Type.tp_init = file_init;
- PyFile_Type.tp_new = file_new;
-#endif
//}
break;
/*
@@ -1255,11 +1006,6 @@ PyObject* initRasterizer(RAS_IRasterizer* rasty,RAS_ICanvas* canvas)
ErrorObject = PyString_FromString("Rasterizer.error");
PyDict_SetItemString(d, "error", ErrorObject);
- /* needed for get/setMaterialType */
- KX_MACRO_addTypesToDict(d, KX_TEXFACE_MATERIAL, KX_TEXFACE_MATERIAL);
- KX_MACRO_addTypesToDict(d, KX_BLENDER_MULTITEX_MATERIAL, KX_BLENDER_MULTITEX_MATERIAL);
- KX_MACRO_addTypesToDict(d, KX_BLENDER_GLSL_MATERIAL, KX_BLENDER_GLSL_MATERIAL);
-
// XXXX Add constants here
// Check for errors
@@ -1281,38 +1027,9 @@ static char GameKeys_module_documentation[] =
"This modules provides defines for key-codes"
;
-static char gPyEventToString_doc[] =
-"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_Compare(value, val)==0) {
- ret = key;
- break;
- }
- }
-
- PyErr_Clear(); // incase there was an error clearing
- Py_DECREF(mod);
- if (!ret) PyErr_SetString(PyExc_ValueError, "expected a valid int keyboard event");
- else Py_INCREF(ret);
-
- return ret;
-}
static struct PyMethodDef gamekeys_methods[] = {
- {"EventToString", (PyCFunction)gPyEventToString, METH_O, (PY_METHODCHAR)gPyEventToString_doc},
{ NULL, (PyCFunction) NULL, 0, NULL }
};
@@ -1461,106 +1178,12 @@ PyObject* initMathutils()
return Mathutils_Init("Mathutils"); // Use as a top level module in BGE
}
-void KX_SetActiveScene(class KX_Scene* scene)
+void PHY_SetActiveScene(class KX_Scene* scene)
{
gp_KetsjiScene = scene;
}
-class KX_Scene* KX_GetActiveScene()
+class KX_Scene* PHY_GetActiveScene()
{
return gp_KetsjiScene;
}
-
-class KX_KetsjiEngine* KX_GetActiveEngine()
-{
- return gp_KetsjiEngine;
-}
-
-// 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);
-
- marshal_length= PyString_Size(pyGlobalDictMarshal);
- *marshal_buffer = new char[marshal_length + 1];
- memcpy(*marshal_buffer, PyString_AsString(pyGlobalDictMarshal), marshal_length);
-
- Py_DECREF(pyGlobalDictMarshal);
- } else {
- printf("Error, GameLogic.globalDict could not be marshal'd\n");
- }
- } else {
- printf("Error, GameLogic.globalDict was removed\n");
- }
- Py_DECREF(gameLogic);
- } else {
- PyErr_Clear();
- printf("Error, GameLogic failed to import GameLogic.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, GameLogic failed to import GameLogic.globalDict will be lost\n");
- }
- }
- return 0;
-}
-
-void pathGamePythonConfig( char *path )
-{
- int len = strlen(gp_GamePythonPath);
-
- BLI_strncpy(path, gp_GamePythonPath, sizeof(gp_GamePythonPath));
-
- /* replace extension */
- if (BLI_testextensie(path, ".blend")) {
- strcpy(path+(len-6), ".bgeconf");
- } else {
- strcpy(path+len, ".bgeconf");
- }
-}
-
-void setGamePythonPath(char *path)
-{
- BLI_strncpy(gp_GamePythonPath, path, sizeof(gp_GamePythonPath));
-}
-
diff --git a/source/gameengine/Ketsji/KX_PythonInit.h b/source/gameengine/Ketsji/KX_PythonInit.h
index 57ee0be9400..f094a1ca575 100644
--- a/source/gameengine/Ketsji/KX_PythonInit.h
+++ b/source/gameengine/Ketsji/KX_PythonInit.h
@@ -40,27 +40,17 @@ typedef enum {
extern bool gUseVisibilityTemp;
-PyObject* initGameLogic(class KX_KetsjiEngine *engine, class KX_Scene* ketsjiscene);
+PyObject* initGameLogic(class KX_Scene* ketsjiscene);
PyObject* initGameKeys();
PyObject* initRasterizer(class RAS_IRasterizer* rasty,class RAS_ICanvas* canvas);
PyObject* initGamePlayerPythonScripting(const STR_String& progname, TPythonSecurityLevel level);
PyObject* initMathutils();
-PyObject* initVideoTexture(void);
void exitGamePlayerPythonScripting();
PyObject* initGamePythonScripting(const STR_String& progname, TPythonSecurityLevel level);
void exitGamePythonScripting();
-void setGamePythonPath(char *path);
-void pathGamePythonConfig( char *path );
-int saveGamePythonConfig( char **marshal_buffer);
-int loadGamePythonConfig(char *marshal_buffer, int marshal_length);
-
-class KX_KetsjiEngine;
-class KX_Scene;
-
-void KX_SetActiveScene(class KX_Scene* scene);
-class KX_Scene* KX_GetActiveScene();
-class KX_KetsjiEngine* KX_GetActiveEngine();
+void PHY_SetActiveScene(class KX_Scene* scene);
+class KX_Scene* PHY_GetActiveScene();
#include "MT_Vector3.h"
void KX_RasterizerDrawDebugLine(const MT_Vector3& from,const MT_Vector3& to,const MT_Vector3& color);
diff --git a/source/gameengine/Ketsji/KX_RadarSensor.cpp b/source/gameengine/Ketsji/KX_RadarSensor.cpp
index 244e9b75d8e..d371626b597 100644
--- a/source/gameengine/Ketsji/KX_RadarSensor.cpp
+++ b/source/gameengine/Ketsji/KX_RadarSensor.cpp
@@ -221,11 +221,11 @@ PyParentObject KX_RadarSensor::Parents[] = {
PyMethodDef KX_RadarSensor::Methods[] = {
{"getConeOrigin", (PyCFunction) KX_RadarSensor::sPyGetConeOrigin,
- METH_VARARGS, (PY_METHODCHAR)GetConeOrigin_doc},
+ METH_VARARGS, GetConeOrigin_doc},
{"getConeTarget", (PyCFunction) KX_RadarSensor::sPyGetConeTarget,
- METH_VARARGS, (PY_METHODCHAR)GetConeTarget_doc},
+ METH_VARARGS, GetConeTarget_doc},
{"getConeHeight", (PyCFunction) KX_RadarSensor::sPyGetConeHeight,
- METH_VARARGS, (PY_METHODCHAR)GetConeHeight_doc},
+ METH_VARARGS, GetConeHeight_doc},
{NULL,NULL,NULL,NULL} //Sentinel
};
@@ -234,7 +234,7 @@ PyObject* KX_RadarSensor::_getattr(const STR_String& attr) {
}
/* getConeOrigin */
-const char KX_RadarSensor::GetConeOrigin_doc[] =
+char KX_RadarSensor::GetConeOrigin_doc[] =
"getConeOrigin()\n"
"\tReturns the origin of the cone with which to test. The origin\n"
"\tis in the middle of the cone.";
@@ -251,7 +251,7 @@ PyObject* KX_RadarSensor::PyGetConeOrigin(PyObject* self,
}
/* getConeOrigin */
-const char KX_RadarSensor::GetConeTarget_doc[] =
+char KX_RadarSensor::GetConeTarget_doc[] =
"getConeTarget()\n"
"\tReturns the center of the bottom face of the cone with which to test.\n";
PyObject* KX_RadarSensor::PyGetConeTarget(PyObject* self,
@@ -267,7 +267,7 @@ PyObject* KX_RadarSensor::PyGetConeTarget(PyObject* self,
}
/* getConeOrigin */
-const char KX_RadarSensor::GetConeHeight_doc[] =
+char KX_RadarSensor::GetConeHeight_doc[] =
"getConeHeight()\n"
"\tReturns the height of the cone with which to test.\n";
PyObject* KX_RadarSensor::PyGetConeHeight(PyObject* self,
diff --git a/source/gameengine/Ketsji/KX_RayCast.cpp b/source/gameengine/Ketsji/KX_RayCast.cpp
index 974d4b992a6..89e2d645d54 100644
--- a/source/gameengine/Ketsji/KX_RayCast.cpp
+++ b/source/gameengine/Ketsji/KX_RayCast.cpp
@@ -40,21 +40,7 @@
#include "PHY_IPhysicsEnvironment.h"
#include "PHY_IPhysicsController.h"
-KX_RayCast::KX_RayCast(KX_IPhysicsController* ignoreController, bool faceNormal)
- :PHY_IRayCastFilterCallback(dynamic_cast<PHY_IPhysicsController*>(ignoreController), faceNormal)
-{
-}
-
-void KX_RayCast::reportHit(PHY_RayCastResult* result)
-{
- m_hitFound = true;
- m_hitPoint.setValue((const float*)result->m_hitPoint);
- m_hitNormal.setValue((const float*)result->m_hitNormal);
- 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)
+bool KX_RayCast::RayTest(KX_IPhysicsController* ignore_controller, PHY_IPhysicsEnvironment* physics_environment, const MT_Point3& _frompoint, const MT_Point3& topoint, MT_Point3& result_point, MT_Vector3& result_normal, const KX_RayCast& callback)
{
// Loops over all physics objects between frompoint and topoint,
// calling callback.RayHit for each one.
@@ -64,51 +50,58 @@ bool KX_RayCast::RayTest(PHY_IPhysicsEnvironment* physics_environment, const MT_
// 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;
+ PHY__Vector3 phy_pos;
+ PHY__Vector3 phy_normal;
- while((hit_controller = physics_environment->rayTest(callback,
+ while((hit_controller = physics_environment->rayTest(dynamic_cast<PHY_IPhysicsController*>(ignore_controller),
frompoint.x(),frompoint.y(),frompoint.z(),
- topoint.x(),topoint.y(),topoint.z())) != NULL)
+ topoint.x(),topoint.y(),topoint.z(),
+ phy_pos[0],phy_pos[1],phy_pos[2],
+ phy_normal[0],phy_normal[1],phy_normal[2])))
{
+ result_point = MT_Point3(phy_pos);
+ result_normal = MT_Vector3(phy_normal);
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;
+ return false;
}
- // The biggest danger to 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., we don't endless loop. */
- MT_Scalar marg = 0.001 + hit_controller->GetMargin();
- marg *= 2.f;
+ if (callback.RayHit(info, result_point, result_normal))
+ return true;
+
+ // There is a bug in the code below: the delta is computed with the wrong
+ // sign on the face opposite to the center, resulting in infinite looping.
+ // In Blender 2.45 this code was never executed because callback.RayHit() always
+ // returned true, causing the ray sensor to stop on the first object.
+ // To avoid changing the behaviour will simply return false here.
+ // It should be discussed if we want the ray sensor to "see" through objects
+ // that don't have the required property/material (condition to get here)
+ return false;
+
+ // skip past the object and keep tracing
+ /* We add 0.01 of fudge, so that if the margin && radius == 0., we don't endless loop. */
+ MT_Scalar marg = 0.01 + hit_controller->GetMargin();
+ marg += 2.f * hit_controller->GetMargin();
/* Calculate the other side of this object */
- MT_Scalar h = MT_abs(todir.dot(callback.m_hitNormal));
- if (h <= 0.01)
- // 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;
+ PHY__Vector3 hitpos;
+ hit_controller->getPosition(hitpos);
+ MT_Point3 hitObjPos(hitpos);
+
+ MT_Vector3 hitvector = hitObjPos - result_point;
+ if (hitvector.dot(hitvector) > MT_EPSILON)
+ {
+ hitvector.normalize();
+ marg *= 2.*todir.dot(hitvector);
+ }
+ frompoint = result_point + marg * todir;
}
- return false;
+
+ return hit_controller;
}
diff --git a/source/gameengine/Ketsji/KX_RayCast.h b/source/gameengine/Ketsji/KX_RayCast.h
index c3084c997a1..607dabd8afc 100644
--- a/source/gameengine/Ketsji/KX_RayCast.h
+++ b/source/gameengine/Ketsji/KX_RayCast.h
@@ -30,14 +30,12 @@
#ifndef __KX_RAYCAST_H__
#define __KX_RAYCAST_H__
-#include "PHY_IPhysicsEnvironment.h"
-#include "PHY_IPhysicsController.h"
-#include "MT_Point3.h"
-#include "MT_Vector3.h"
+class MT_Point3;
+class MT_Vector3;
+class KX_IPhysicsController;
+class PHY_IPhysicsEnvironment;
-class RAS_MeshObject;
struct KX_ClientObjectInfo;
-class KX_IPhysicsController;
/**
* Defines a function for doing a ray cast.
@@ -51,27 +49,17 @@ class KX_IPhysicsController;
*
* Returns true if a client was accepted, false if nothing found.
*/
-class KX_RayCast : public PHY_IRayCastFilterCallback
+class KX_RayCast
{
+protected:
+ KX_RayCast() {};
public:
- bool m_hitFound;
- MT_Point3 m_hitPoint;
- MT_Vector3 m_hitNormal;
- const RAS_MeshObject* m_hitMesh;
- int m_hitPolygon;
-
- KX_RayCast(KX_IPhysicsController* ignoreController, bool faceNormal);
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;
+ virtual bool RayHit(KX_ClientObjectInfo* client, MT_Point3& hit_point, MT_Vector3& hit_normal) const = 0;
/**
* Callback wrapper.
@@ -83,11 +71,13 @@ public:
/// Public interface.
/// Implement bool RayHit in your class to receive ray callbacks.
- static bool RayTest(
+ static bool RayTest(KX_IPhysicsController* physics_controller,
PHY_IPhysicsEnvironment* physics_environment,
- const MT_Point3& frompoint,
+ const MT_Point3& _frompoint,
const MT_Point3& topoint,
- KX_RayCast& callback);
+ MT_Point3& result_point,
+ MT_Vector3& result_normal,
+ const KX_RayCast& callback);
};
@@ -96,32 +86,18 @@ template<class T> class KX_RayCast::Callback : public KX_RayCast
T *self;
void *data;
public:
- Callback(T *_self, KX_IPhysicsController* controller=NULL, void *_data = NULL, bool faceNormal=false)
- : KX_RayCast(controller, faceNormal),
- self(_self),
+ Callback(T *_self, void *_data = NULL)
+ : self(_self),
data(_data)
{
}
~Callback() {}
-
- virtual bool RayHit(KX_ClientObjectInfo* client)
- {
- return self->RayHit(client, this, data);
- }
-
- virtual bool needBroadphaseRayCast(PHY_IPhysicsController* controller)
+
+ virtual bool RayHit(KX_ClientObjectInfo* client, MT_Point3& hit_point, MT_Vector3& hit_normal) const
{
- 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);
+ return self->RayHit(client, hit_point, hit_normal, data);
}
-
};
diff --git a/source/gameengine/Ketsji/KX_RaySensor.cpp b/source/gameengine/Ketsji/KX_RaySensor.cpp
index e24fb773eac..a416c8c9f89 100644
--- a/source/gameengine/Ketsji/KX_RaySensor.cpp
+++ b/source/gameengine/Ketsji/KX_RaySensor.cpp
@@ -51,7 +51,6 @@ 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,
@@ -59,7 +58,6 @@ KX_RaySensor::KX_RaySensor(class SCA_EventManager* eventmgr,
: SCA_ISensor(gameobj,eventmgr, T),
m_propertyname(propname),
m_bFindMaterial(bFindMaterial),
- m_bXRay(bXRay),
m_distance(distance),
m_scene(ketsjiScene),
m_axis(axis)
@@ -106,10 +104,16 @@ bool KX_RaySensor::IsPositiveTrigger()
return result;
}
-bool KX_RaySensor::RayHit(KX_ClientObjectInfo* client, KX_RayCast* result, void * const data)
+bool KX_RaySensor::RayHit(KX_ClientObjectInfo* client, MT_Point3& hit_point, MT_Vector3& hit_normal, void * const data)
{
KX_GameObject* hitKXObj = client->m_gameobject;
+
+ if (client->m_type > KX_ClientObjectInfo::ACTOR)
+ {
+ // false hit
+ return false;
+ }
bool bFound = false;
if (m_propertyname.Length() == 0)
@@ -135,44 +139,17 @@ bool KX_RaySensor::RayHit(KX_ClientObjectInfo* client, KX_RayCast* result, void
{
m_rayHit = true;
m_hitObject = hitKXObj;
- m_hitPosition = result->m_hitPoint;
- m_hitNormal = result->m_hitNormal;
+ m_hitPosition = hit_point;
+ m_hitNormal = hit_normal;
}
- // 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)
-{
- 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)
- {
- // not quite correct: an object may have multiple material
- // should check all the material and not only the first one
- if (!client->m_auxilary_info || (m_propertyname != ((char*)client->m_auxilary_info)))
- return false;
- }
- else
- {
- if (client->m_gameobject->GetProperty(m_propertyname) == NULL)
- return false;
- }
- }
- return true;
+ return bFound;
+
}
+
+
bool KX_RaySensor::Evaluate(CValue* event)
{
bool result = false;
@@ -238,6 +215,8 @@ bool KX_RaySensor::Evaluate(CValue* event)
m_rayDirection = todir;
MT_Point3 topoint = frompoint + (m_distance) * todir;
+ MT_Point3 resultpoint;
+ MT_Vector3 resultnormal;
PHY_IPhysicsEnvironment* pe = m_scene->GetPhysicsEnvironment();
if (!pe)
@@ -259,8 +238,7 @@ bool KX_RaySensor::Evaluate(CValue* event)
PHY_IPhysicsEnvironment* physics_environment = this->m_scene->GetPhysicsEnvironment();
- KX_RayCast::Callback<KX_RaySensor> callback(this, spc);
- KX_RayCast::RayTest(physics_environment, frompoint, topoint, callback);
+ result = KX_RayCast::RayTest(spc, physics_environment, frompoint, topoint, resultpoint, resultnormal, KX_RayCast::Callback<KX_RaySensor>(this));
/* now pass this result to some controller */
@@ -287,10 +265,6 @@ bool KX_RaySensor::Evaluate(CValue* event)
// notify logicsystem that ray JUST left the Object
result = true;
}
- else
- {
- result = false;
- }
}
if (reset)
@@ -335,14 +309,14 @@ PyParentObject KX_RaySensor::Parents[] = {
};
PyMethodDef KX_RaySensor::Methods[] = {
- {"getHitObject",(PyCFunction) KX_RaySensor::sPyGetHitObject,METH_VARARGS, (PY_METHODCHAR)GetHitObject_doc},
- {"getHitPosition",(PyCFunction) KX_RaySensor::sPyGetHitPosition,METH_VARARGS, (PY_METHODCHAR)GetHitPosition_doc},
- {"getHitNormal",(PyCFunction) KX_RaySensor::sPyGetHitNormal,METH_VARARGS, (PY_METHODCHAR)GetHitNormal_doc},
- {"getRayDirection",(PyCFunction) KX_RaySensor::sPyGetRayDirection,METH_VARARGS, (PY_METHODCHAR)GetRayDirection_doc},
+ {"getHitObject",(PyCFunction) KX_RaySensor::sPyGetHitObject,METH_VARARGS, GetHitObject_doc},
+ {"getHitPosition",(PyCFunction) KX_RaySensor::sPyGetHitPosition,METH_VARARGS, GetHitPosition_doc},
+ {"getHitNormal",(PyCFunction) KX_RaySensor::sPyGetHitNormal,METH_VARARGS, GetHitNormal_doc},
+ {"getRayDirection",(PyCFunction) KX_RaySensor::sPyGetRayDirection,METH_VARARGS, GetRayDirection_doc},
{NULL,NULL} //Sentinel
};
-const char KX_RaySensor::GetHitObject_doc[] =
+char KX_RaySensor::GetHitObject_doc[] =
"getHitObject()\n"
"\tReturns the name of the object that was hit by this ray.\n";
PyObject* KX_RaySensor::PyGetHitObject(PyObject* self,
@@ -357,7 +331,7 @@ PyObject* KX_RaySensor::PyGetHitObject(PyObject* self,
}
-const char KX_RaySensor::GetHitPosition_doc[] =
+char KX_RaySensor::GetHitPosition_doc[] =
"getHitPosition()\n"
"\tReturns the position (in worldcoordinates) where the object was hit by this ray.\n";
PyObject* KX_RaySensor::PyGetHitPosition(PyObject* self,
@@ -377,7 +351,7 @@ PyObject* KX_RaySensor::PyGetHitPosition(PyObject* self,
}
-const char KX_RaySensor::GetRayDirection_doc[] =
+char KX_RaySensor::GetRayDirection_doc[] =
"getRayDirection()\n"
"\tReturns the direction from the ray (in worldcoordinates) .\n";
PyObject* KX_RaySensor::PyGetRayDirection(PyObject* self,
@@ -397,7 +371,7 @@ PyObject* KX_RaySensor::PyGetRayDirection(PyObject* self,
}
-const char KX_RaySensor::GetHitNormal_doc[] =
+char KX_RaySensor::GetHitNormal_doc[] =
"getHitNormal()\n"
"\tReturns the normal (in worldcoordinates) of the object at the location where the object was hit by this ray.\n";
PyObject* KX_RaySensor::PyGetHitNormal(PyObject* self,
diff --git a/source/gameengine/Ketsji/KX_RaySensor.h b/source/gameengine/Ketsji/KX_RaySensor.h
index 02a755fedc1..f4305b053d1 100644
--- a/source/gameengine/Ketsji/KX_RaySensor.h
+++ b/source/gameengine/Ketsji/KX_RaySensor.h
@@ -36,14 +36,12 @@
#include "MT_Point3.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;
double m_distance;
class KX_Scene* m_scene;
bool m_bTriggered;
@@ -58,8 +56,7 @@ public:
KX_RaySensor(class SCA_EventManager* eventmgr,
SCA_IObject* gameobj,
const STR_String& propname,
- bool bFindMaterial,
- bool bXRay,
+ bool fFindMaterial,
double distance,
int axis,
class KX_Scene* ketsjiScene,
@@ -71,8 +68,7 @@ public:
virtual bool IsPositiveTrigger();
virtual void Init();
- bool RayHit(KX_ClientObjectInfo* client, KX_RayCast* result, void * const data);
- bool NeedRayCast(KX_ClientObjectInfo* client);
+ bool RayHit(KX_ClientObjectInfo* client, MT_Point3& hit_point, MT_Vector3& hit_normal, void * const data);
KX_PYMETHOD_DOC(KX_RaySensor,GetHitObject);
KX_PYMETHOD_DOC(KX_RaySensor,GetHitPosition);
diff --git a/source/gameengine/Ketsji/KX_SCA_AddObjectActuator.cpp b/source/gameengine/Ketsji/KX_SCA_AddObjectActuator.cpp
index 5777f54b799..e36891b56f4 100644
--- a/source/gameengine/Ketsji/KX_SCA_AddObjectActuator.cpp
+++ b/source/gameengine/Ketsji/KX_SCA_AddObjectActuator.cpp
@@ -39,8 +39,6 @@
#include "KX_GameObject.h"
#include "KX_IPhysicsController.h"
-#include "PyObjectPlus.h"
-
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
@@ -54,20 +52,14 @@ KX_SCA_AddObjectActuator::KX_SCA_AddObjectActuator(SCA_IObject *gameobj,
int time,
SCA_IScene* scene,
const MT_Vector3& linvel,
- bool linv_local,
- const MT_Vector3& angvel,
- bool angv_local,
+ bool local,
PyTypeObject* T)
:
SCA_IActuator(gameobj, T),
m_OriginalObject(original),
m_scene(scene),
-
m_linear_velocity(linvel),
- m_localLinvFlag(linv_local),
-
- m_angular_velocity(angvel),
- m_localAngvFlag(angv_local)
+ m_localFlag(local)
{
if (m_OriginalObject)
m_OriginalObject->RegisterActuator(this);
@@ -188,16 +180,14 @@ PyParentObject KX_SCA_AddObjectActuator::Parents[] = {
NULL
};
PyMethodDef KX_SCA_AddObjectActuator::Methods[] = {
- {"setObject", (PyCFunction) KX_SCA_AddObjectActuator::sPySetObject, METH_O, (PY_METHODCHAR)SetObject_doc},
- {"setTime", (PyCFunction) KX_SCA_AddObjectActuator::sPySetTime, METH_O, (PY_METHODCHAR)SetTime_doc},
- {"getObject", (PyCFunction) KX_SCA_AddObjectActuator::sPyGetObject, METH_VARARGS, (PY_METHODCHAR)GetObject_doc},
- {"getTime", (PyCFunction) KX_SCA_AddObjectActuator::sPyGetTime, METH_NOARGS, (PY_METHODCHAR)GetTime_doc},
- {"getLinearVelocity", (PyCFunction) KX_SCA_AddObjectActuator::sPyGetLinearVelocity, METH_NOARGS, (PY_METHODCHAR)GetLinearVelocity_doc},
- {"setLinearVelocity", (PyCFunction) KX_SCA_AddObjectActuator::sPySetLinearVelocity, METH_VARARGS, (PY_METHODCHAR)SetLinearVelocity_doc},
- {"getAngularVelocity", (PyCFunction) KX_SCA_AddObjectActuator::sPyGetAngularVelocity, METH_NOARGS, (PY_METHODCHAR)GetAngularVelocity_doc},
- {"setAngularVelocity", (PyCFunction) KX_SCA_AddObjectActuator::sPySetAngularVelocity, METH_VARARGS, (PY_METHODCHAR)SetAngularVelocity_doc},
- {"getLastCreatedObject", (PyCFunction) KX_SCA_AddObjectActuator::sPyGetLastCreatedObject, METH_NOARGS,"getLastCreatedObject() : get the object handle to the last created object\n"},
- {"instantAddObject", (PyCFunction) KX_SCA_AddObjectActuator::sPyInstantAddObject, METH_NOARGS,"instantAddObject() : immediately add object without delay\n"},
+ {"setObject", (PyCFunction) KX_SCA_AddObjectActuator::sPySetObject, METH_VARARGS, SetObject_doc},
+ {"setTime", (PyCFunction) KX_SCA_AddObjectActuator::sPySetTime, METH_VARARGS, SetTime_doc},
+ {"getObject", (PyCFunction) KX_SCA_AddObjectActuator::sPyGetObject, METH_VARARGS, GetObject_doc},
+ {"getTime", (PyCFunction) KX_SCA_AddObjectActuator::sPyGetTime, METH_VARARGS, GetTime_doc},
+ {"getLinearVelocity", (PyCFunction) KX_SCA_AddObjectActuator::sPyGetLinearVelocity, METH_VARARGS, GetLinearVelocity_doc},
+ {"setLinearVelocity", (PyCFunction) KX_SCA_AddObjectActuator::sPySetLinearVelocity, METH_VARARGS, SetLinearVelocity_doc},
+ {"getLastCreatedObject", (PyCFunction) KX_SCA_AddObjectActuator::sPyGetLastCreatedObject, METH_VARARGS,"getLastCreatedObject() : get the object handle to the last created object\n"},
+ {"instantAddObject", (PyCFunction) KX_SCA_AddObjectActuator::sPyInstantAddObject, METH_VARARGS,"instantAddObject() : immediately add object without delay\n"},
{NULL,NULL} //Sentinel
};
@@ -209,101 +199,121 @@ PyObject* KX_SCA_AddObjectActuator::_getattr(const STR_String& attr)
}
/* 1. setObject */
-const char KX_SCA_AddObjectActuator::SetObject_doc[] =
-"setObject(object)\n"
-"\t- object: KX_GameObject, string or None\n"
+char KX_SCA_AddObjectActuator::SetObject_doc[] =
+"setObject(name)\n"
+"\t- name: string\n"
"\tSets the object that will be added. There has to be an object\n"
"\tof this name. If not, this function does nothing.\n";
-PyObject* KX_SCA_AddObjectActuator::PySetObject(PyObject* self, PyObject* value)
-{
- KX_GameObject *gameobj;
-
- if (!ConvertPythonToGameObject(value, &gameobj, true))
- return NULL; // ConvertPythonToGameObject sets the error
-
- if (m_OriginalObject != NULL)
- m_OriginalObject->UnregisterActuator(this);
- m_OriginalObject = (SCA_IObject*)gameobj;
- if (m_OriginalObject)
- m_OriginalObject->RegisterActuator(this);
+
+
+PyObject* KX_SCA_AddObjectActuator::PySetObject(PyObject* self,
+ PyObject* args,
+ PyObject* kwds)
+{
+ PyObject* gameobj;
+ if (PyArg_ParseTuple(args, "O!", &KX_GameObject::Type, &gameobj))
+ {
+ if (m_OriginalObject != NULL)
+ m_OriginalObject->UnregisterActuator(this);
+ m_OriginalObject = (SCA_IObject*)gameobj;
+ if (m_OriginalObject)
+ m_OriginalObject->RegisterActuator(this);
+ Py_Return;
+ }
+ PyErr_Clear();
- Py_RETURN_NONE;
+ char* objectname;
+ if (PyArg_ParseTuple(args, "s", &objectname))
+ {
+ if (m_OriginalObject != NULL)
+ m_OriginalObject->UnregisterActuator(this);
+ m_OriginalObject = (SCA_IObject*)SCA_ILogicBrick::m_sCurrentLogicManager->GetGameObjectByName(STR_String(objectname));;
+ if (m_OriginalObject)
+ m_OriginalObject->RegisterActuator(this);
+ Py_Return;
+ }
+
+ return NULL;
}
/* 2. setTime */
-const char KX_SCA_AddObjectActuator::SetTime_doc[] =
+char KX_SCA_AddObjectActuator::SetTime_doc[] =
"setTime(duration)\n"
"\t- duration: integer\n"
"\tSets the lifetime of the object that will be added, in frames. \n"
"\tIf the duration is negative, it is set to 0.\n";
-PyObject* KX_SCA_AddObjectActuator::PySetTime(PyObject* self, PyObject* value)
+PyObject* KX_SCA_AddObjectActuator::PySetTime(PyObject* self,
+ PyObject* args,
+ PyObject* kwds)
{
- int deltatime = PyInt_AsLong(value);
- if (deltatime==-1 && PyErr_Occurred()) {
- PyErr_SetString(PyExc_TypeError, "expected an int");
+ int deltatime;
+
+ if (!PyArg_ParseTuple(args, "i", &deltatime))
return NULL;
- }
m_timeProp = deltatime;
if (m_timeProp < 0) m_timeProp = 0;
- Py_RETURN_NONE;
+ Py_Return;
}
/* 3. getTime */
-const char KX_SCA_AddObjectActuator::GetTime_doc[] =
+char KX_SCA_AddObjectActuator::GetTime_doc[] =
"GetTime()\n"
"\tReturns the lifetime of the object that will be added.\n";
-PyObject* KX_SCA_AddObjectActuator::PyGetTime(PyObject* self)
+PyObject* KX_SCA_AddObjectActuator::PyGetTime(PyObject* self,
+ PyObject* args,
+ PyObject* kwds)
{
return PyInt_FromLong(m_timeProp);
}
/* 4. getObject */
-const char KX_SCA_AddObjectActuator::GetObject_doc[] =
-"getObject(name_only = 1)\n"
-"name_only - optional arg, when true will return the KX_GameObject rather then its name\n"
+char KX_SCA_AddObjectActuator::GetObject_doc[] =
+"getObject()\n"
"\tReturns the name of the object that will be added.\n";
-PyObject* KX_SCA_AddObjectActuator::PyGetObject(PyObject* self, PyObject* args)
-{
- int ret_name_only = 1;
- if (!PyArg_ParseTuple(args, "|i", &ret_name_only))
- return NULL;
+
+
+PyObject* KX_SCA_AddObjectActuator::PyGetObject(PyObject* self,
+ PyObject* args,
+ PyObject* kwds)
+{
if (!m_OriginalObject)
- Py_RETURN_NONE;
-
- if (ret_name_only)
- return PyString_FromString(m_OriginalObject->GetName());
- else
- return m_OriginalObject->AddRef();
+ Py_Return;
+
+ return PyString_FromString(m_OriginalObject->GetName());
}
/* 5. getLinearVelocity */
-const char KX_SCA_AddObjectActuator::GetLinearVelocity_doc[] =
+char KX_SCA_AddObjectActuator::GetLinearVelocity_doc[] =
"GetLinearVelocity()\n"
"\tReturns the linear velocity that will be assigned to \n"
"\tthe created object.\n";
-PyObject* KX_SCA_AddObjectActuator::PyGetLinearVelocity(PyObject* self)
+
+
+PyObject* KX_SCA_AddObjectActuator::PyGetLinearVelocity(PyObject* self,
+ PyObject* args,
+ PyObject* kwds)
{
PyObject *retVal = PyList_New(3);
- PyList_SET_ITEM(retVal, 0, PyFloat_FromDouble(m_linear_velocity[0]));
- PyList_SET_ITEM(retVal, 1, PyFloat_FromDouble(m_linear_velocity[1]));
- PyList_SET_ITEM(retVal, 2, PyFloat_FromDouble(m_linear_velocity[2]));
+ PyList_SetItem(retVal, 0, PyFloat_FromDouble(m_linear_velocity[0]));
+ PyList_SetItem(retVal, 1, PyFloat_FromDouble(m_linear_velocity[1]));
+ PyList_SetItem(retVal, 2, PyFloat_FromDouble(m_linear_velocity[2]));
return retVal;
}
@@ -311,62 +321,25 @@ PyObject* KX_SCA_AddObjectActuator::PyGetLinearVelocity(PyObject* self)
/* 6. setLinearVelocity */
-const char KX_SCA_AddObjectActuator::SetLinearVelocity_doc[] =
+char KX_SCA_AddObjectActuator::SetLinearVelocity_doc[] =
"setLinearVelocity(vx, vy, vz)\n"
"\t- vx: float\n"
"\t- vy: float\n"
"\t- vz: float\n"
-"\t- local: bool\n"
"\tAssign this velocity to the created object. \n";
-PyObject* KX_SCA_AddObjectActuator::PySetLinearVelocity(PyObject* self, PyObject* args)
-{
-
- float vecArg[3];
- if (!PyArg_ParseTuple(args, "fff", &vecArg[0], &vecArg[1], &vecArg[2]))
- return NULL;
-
- m_linear_velocity.setValue(vecArg);
- Py_RETURN_NONE;
-}
-/* 7. getAngularVelocity */
-const char KX_SCA_AddObjectActuator::GetAngularVelocity_doc[] =
-"GetAngularVelocity()\n"
-"\tReturns the angular velocity that will be assigned to \n"
-"\tthe created object.\n";
-
-PyObject* KX_SCA_AddObjectActuator::PyGetAngularVelocity(PyObject* self)
-{
- PyObject *retVal = PyList_New(3);
-
- PyList_SET_ITEM(retVal, 0, PyFloat_FromDouble(m_angular_velocity[0]));
- PyList_SET_ITEM(retVal, 1, PyFloat_FromDouble(m_angular_velocity[1]));
- PyList_SET_ITEM(retVal, 2, PyFloat_FromDouble(m_angular_velocity[2]));
-
- return retVal;
-}
-
-
-
-/* 8. setAngularVelocity */
-const char KX_SCA_AddObjectActuator::SetAngularVelocity_doc[] =
-"setAngularVelocity(vx, vy, vz)\n"
-"\t- vx: float\n"
-"\t- vy: float\n"
-"\t- vz: float\n"
-"\t- local: bool\n"
-"\tAssign this angular velocity to the created object. \n";
-
-PyObject* KX_SCA_AddObjectActuator::PySetAngularVelocity(PyObject* self, PyObject* args)
+PyObject* KX_SCA_AddObjectActuator::PySetLinearVelocity(PyObject* self,
+ PyObject* args,
+ PyObject* kwds)
{
float vecArg[3];
if (!PyArg_ParseTuple(args, "fff", &vecArg[0], &vecArg[1], &vecArg[2]))
return NULL;
- m_angular_velocity.setValue(vecArg);
- Py_RETURN_NONE;
+ m_linear_velocity.setValue(vecArg);
+ Py_Return;
}
void KX_SCA_AddObjectActuator::InstantAddObject()
@@ -377,9 +350,8 @@ void KX_SCA_AddObjectActuator::InstantAddObject()
// 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);
+ game_obj->setLinearVelocity(m_linear_velocity,m_localFlag);
+ game_obj->ResolveCombinedVelocities(m_linear_velocity, MT_Vector3(0., 0., 0.), m_localFlag, false);
// keep a copy of the last object, to allow python scripters to change it
if (m_lastCreatedObject)
@@ -396,32 +368,33 @@ void KX_SCA_AddObjectActuator::InstantAddObject()
}
}
-PyObject* KX_SCA_AddObjectActuator::PyInstantAddObject(PyObject* self)
+PyObject* KX_SCA_AddObjectActuator::PyInstantAddObject(PyObject* self,
+ PyObject* args,
+ PyObject* kwds)
{
InstantAddObject();
- Py_RETURN_NONE;
+ Py_Return;
}
/* 7. GetLastCreatedObject */
-const char KX_SCA_AddObjectActuator::GetLastCreatedObject_doc[] =
+char KX_SCA_AddObjectActuator::GetLastCreatedObject_doc[] =
"getLastCreatedObject()\n"
"\tReturn the last created object. \n";
-PyObject* KX_SCA_AddObjectActuator::PyGetLastCreatedObject(PyObject* self)
+PyObject* KX_SCA_AddObjectActuator::PyGetLastCreatedObject(PyObject* self,
+ PyObject* args,
+ PyObject* kwds)
{
SCA_IObject* result = this->GetLastCreatedObject();
-
- // if result->GetSGNode() is NULL
- // it means the object has ended, The BGE python api crashes in many places if the object is returned.
- if (result && (static_cast<KX_GameObject *>(result))->GetSGNode())
+ if (result)
{
result->AddRef();
return result;
}
// don't return NULL to python anymore, it gives trouble in the scripts
- Py_RETURN_NONE;
+ Py_Return;
}
diff --git a/source/gameengine/Ketsji/KX_SCA_AddObjectActuator.h b/source/gameengine/Ketsji/KX_SCA_AddObjectActuator.h
index 278d4180284..1359f39278d 100644
--- a/source/gameengine/Ketsji/KX_SCA_AddObjectActuator.h
+++ b/source/gameengine/Ketsji/KX_SCA_AddObjectActuator.h
@@ -60,13 +60,9 @@ class KX_SCA_AddObjectActuator : public SCA_IActuator
/// Linear velocity upon creation of the object.
MT_Vector3 m_linear_velocity;
-
- /// Angular velocity upon creation of the object.
- MT_Vector3 m_angular_velocity;
/// Apply the velocity locally
- bool m_localLinvFlag;
- bool m_localAngvFlag;
+ bool m_localFlag;
SCA_IObject* m_lastCreatedObject;
@@ -83,9 +79,7 @@ public:
int time,
SCA_IScene* scene,
const MT_Vector3& linvel,
- bool linv_local,
- const MT_Vector3& angvel,
- bool angv_local,
+ bool local,
PyTypeObject* T=&Type
);
@@ -119,25 +113,21 @@ public:
void InstantAddObject();
/* 1. setObject */
- KX_PYMETHOD_DOC_O(KX_SCA_AddObjectActuator,SetObject);
+ KX_PYMETHOD_DOC(KX_SCA_AddObjectActuator,SetObject);
/* 2. setTime */
- KX_PYMETHOD_DOC_O(KX_SCA_AddObjectActuator,SetTime);
+ KX_PYMETHOD_DOC(KX_SCA_AddObjectActuator,SetTime);
/* 3. getTime */
- KX_PYMETHOD_DOC_NOARGS(KX_SCA_AddObjectActuator,GetTime);
+ KX_PYMETHOD_DOC(KX_SCA_AddObjectActuator,GetTime);
/* 4. getObject */
- KX_PYMETHOD_DOC_VARARGS(KX_SCA_AddObjectActuator,GetObject);
+ KX_PYMETHOD_DOC(KX_SCA_AddObjectActuator,GetObject);
/* 5. getLinearVelocity */
- KX_PYMETHOD_DOC_NOARGS(KX_SCA_AddObjectActuator,GetLinearVelocity);
+ KX_PYMETHOD_DOC(KX_SCA_AddObjectActuator,GetLinearVelocity);
/* 6. setLinearVelocity */
- KX_PYMETHOD_DOC_VARARGS(KX_SCA_AddObjectActuator,SetLinearVelocity);
- /* 7. getAngularVelocity */
- KX_PYMETHOD_DOC_NOARGS(KX_SCA_AddObjectActuator,GetAngularVelocity);
- /* 8. setAngularVelocity */
- KX_PYMETHOD_DOC_VARARGS(KX_SCA_AddObjectActuator,SetAngularVelocity);
- /* 9. getLastCreatedObject */
- KX_PYMETHOD_DOC_NOARGS(KX_SCA_AddObjectActuator,GetLastCreatedObject);
- /* 10. instantAddObject*/
- KX_PYMETHOD_DOC_NOARGS(KX_SCA_AddObjectActuator,InstantAddObject);
+ KX_PYMETHOD_DOC(KX_SCA_AddObjectActuator,SetLinearVelocity);
+ /* 7. getLastCreatedObject */
+ KX_PYMETHOD_DOC(KX_SCA_AddObjectActuator,GetLastCreatedObject);
+ /* 8. instantAddObject*/
+ KX_PYMETHOD_DOC(KX_SCA_AddObjectActuator,InstantAddObject);
}; /* end of class KX_SCA_AddObjectActuator : public KX_EditObjectActuator */
diff --git a/source/gameengine/Ketsji/KX_SCA_ReplaceMeshActuator.cpp b/source/gameengine/Ketsji/KX_SCA_ReplaceMeshActuator.cpp
index 261d9ec8f0c..630df2d21d9 100644
--- a/source/gameengine/Ketsji/KX_SCA_ReplaceMeshActuator.cpp
+++ b/source/gameengine/Ketsji/KX_SCA_ReplaceMeshActuator.cpp
@@ -37,8 +37,6 @@
#include "KX_SCA_ReplaceMeshActuator.h"
-#include "PyObjectPlus.h"
-
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
@@ -82,7 +80,7 @@ PyParentObject KX_SCA_ReplaceMeshActuator::Parents[] = {
PyMethodDef KX_SCA_ReplaceMeshActuator::Methods[] = {
- {"setMesh", (PyCFunction) KX_SCA_ReplaceMeshActuator::sPySetMesh, METH_O, (PY_METHODCHAR)SetMesh_doc},
+ {"setMesh", (PyCFunction) KX_SCA_ReplaceMeshActuator::sPySetMesh, METH_VARARGS, SetMesh_doc},
KX_PYMETHODTABLE(KX_SCA_ReplaceMeshActuator, instantReplaceMesh),
KX_PYMETHODTABLE(KX_SCA_ReplaceMeshActuator, getMesh),
@@ -99,31 +97,30 @@ PyObject* KX_SCA_ReplaceMeshActuator::_getattr(const STR_String& attr)
/* 1. setMesh */
-const char KX_SCA_ReplaceMeshActuator::SetMesh_doc[] =
+char KX_SCA_ReplaceMeshActuator::SetMesh_doc[] =
"setMesh(name)\n"
- "\t- name: string or None\n"
+ "\t- name: string\n"
"\tSet the mesh that will be substituted for the current one.\n";
-PyObject* KX_SCA_ReplaceMeshActuator::PySetMesh(PyObject* self, PyObject* value)
+PyObject* KX_SCA_ReplaceMeshActuator::PySetMesh(PyObject* self,
+ PyObject* args,
+ PyObject* kwds)
{
- if (value == Py_None) {
- m_mesh = NULL;
- } else {
- char* meshname = PyString_AsString(value);
- if (!meshname) {
- PyErr_SetString(PyExc_ValueError, "Expected the name of a mesh or None");
- return NULL;
- }
- void* mesh = SCA_ILogicBrick::m_sCurrentLogicManager->GetMeshByName(STR_String(meshname));
-
- if (mesh==NULL) {
- PyErr_SetString(PyExc_ValueError, "The mesh name given does not exist");
- return NULL;
- }
+ char* meshname;
+
+ if (!PyArg_ParseTuple(args, "s", &meshname))
+ {
+ return NULL;
+ }
+
+ void* mesh = SCA_ILogicBrick::m_sCurrentLogicManager->GetMeshByName(STR_String(meshname));
+
+ if (mesh) {
m_mesh= (class RAS_MeshObject*)mesh;
+ Py_Return;
}
- Py_RETURN_NONE;
+ return NULL;
}
KX_PYMETHODDEF_DOC(KX_SCA_ReplaceMeshActuator, getMesh,
@@ -132,7 +129,7 @@ KX_PYMETHODDEF_DOC(KX_SCA_ReplaceMeshActuator, getMesh,
)
{
if (!m_mesh)
- Py_RETURN_NONE;
+ Py_Return;
return PyString_FromString(const_cast<char *>(m_mesh->GetName().ReadPtr()));
}
@@ -142,7 +139,7 @@ KX_PYMETHODDEF_DOC(KX_SCA_ReplaceMeshActuator, instantReplaceMesh,
"instantReplaceMesh() : immediately replace mesh without delay\n")
{
InstantReplaceMesh();
- Py_RETURN_NONE;
+ Py_Return;
}
/* ------------------------------------------------------------------------- */
diff --git a/source/gameengine/Ketsji/KX_SCA_ReplaceMeshActuator.h b/source/gameengine/Ketsji/KX_SCA_ReplaceMeshActuator.h
index 1da154cc222..5ba0a099b14 100644
--- a/source/gameengine/Ketsji/KX_SCA_ReplaceMeshActuator.h
+++ b/source/gameengine/Ketsji/KX_SCA_ReplaceMeshActuator.h
@@ -76,7 +76,7 @@ class KX_SCA_ReplaceMeshActuator : public SCA_IActuator
void InstantReplaceMesh();
/* 1. setMesh */
- KX_PYMETHOD_DOC_O(KX_SCA_ReplaceMeshActuator,SetMesh);
+ KX_PYMETHOD_DOC(KX_SCA_ReplaceMeshActuator,SetMesh);
KX_PYMETHOD_DOC(KX_SCA_ReplaceMeshActuator,getMesh);
KX_PYMETHOD_DOC(KX_SCA_ReplaceMeshActuator,instantReplaceMesh);
diff --git a/source/gameengine/Ketsji/KX_SG_BoneParentNodeRelationship.cpp b/source/gameengine/Ketsji/KX_SG_BoneParentNodeRelationship.cpp
index d651373869a..f085ff435dc 100644
--- a/source/gameengine/Ketsji/KX_SG_BoneParentNodeRelationship.cpp
+++ b/source/gameengine/Ketsji/KX_SG_BoneParentNodeRelationship.cpp
@@ -78,7 +78,7 @@ UpdateChildCoordinates(
if (parent)
{
- BL_ArmatureObject *armature = (BL_ArmatureObject*)(parent->GetSGClientObject());
+ const BL_ArmatureObject *armature = (const BL_ArmatureObject*)(parent->GetSGClientObject());
if (armature)
{
MT_Matrix4x4 parent_matrix;
diff --git a/source/gameengine/Ketsji/KX_Scene.cpp b/source/gameengine/Ketsji/KX_Scene.cpp
index 476a931355f..2828663c63d 100644
--- a/source/gameengine/Ketsji/KX_Scene.cpp
+++ b/source/gameengine/Ketsji/KX_Scene.cpp
@@ -68,7 +68,6 @@
#include "SG_IObject.h"
#include "SG_Tree.h"
#include "DNA_group_types.h"
-#include "DNA_scene_types.h"
#include "BKE_anim.h"
#include "KX_SG_NodeRelationships.h"
@@ -117,8 +116,7 @@ KX_Scene::KX_Scene(class SCA_IInputDevice* keyboarddevice,
class SCA_IInputDevice* mousedevice,
class NG_NetworkDeviceInterface *ndi,
class SND_IAudioDevice* adi,
- const STR_String& sceneName,
- Scene *scene):
+ const STR_String& sceneName):
PyObjectPlus(&KX_Scene::Type),
m_keyboardmgr(NULL),
m_mousemgr(NULL),
@@ -128,8 +126,7 @@ KX_Scene::KX_Scene(class SCA_IInputDevice* keyboarddevice,
m_adi(adi),
m_networkDeviceInterface(ndi),
m_active_camera(NULL),
- m_ueberExecutionPriority(0),
- m_blenderScene(scene)
+ m_ueberExecutionPriority(0)
{
m_suspendedtime = 0.0;
m_suspendeddelta = 0.0;
@@ -159,7 +156,7 @@ KX_Scene::KX_Scene(class SCA_IInputDevice* keyboarddevice,
KX_NetworkEventManager* netmgr = new KX_NetworkEventManager(m_logicmgr, ndi);
-
+ SCA_JoystickManager *joymgr = new SCA_JoystickManager(m_logicmgr);
m_logicmgr->RegisterEventManager(alwaysmgr);
m_logicmgr->RegisterEventManager(propmgr);
@@ -170,15 +167,7 @@ KX_Scene::KX_Scene(class SCA_IInputDevice* keyboarddevice,
m_logicmgr->RegisterEventManager(rndmgr);
m_logicmgr->RegisterEventManager(raymgr);
m_logicmgr->RegisterEventManager(netmgr);
-
-
- 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);
- }
+ m_logicmgr->RegisterEventManager(joymgr);
m_soundScene = new SND_Scene(adi);
MT_assert (m_networkDeviceInterface != NULL);
@@ -245,9 +234,40 @@ KX_Scene::~KX_Scene()
{
delete m_bucketmanager;
}
+#ifdef USE_BULLET
+ // This is a fix for memory leaks in bullet: the collision shapes is not destroyed
+ // when the physical controllers are destroyed. The reason is that shapes are shared
+ // between replicas of an object. There is no reference count in Bullet so the
+ // only workaround that does not involve changes in Bullet is to save in this array
+ // the list of shapes that are created when the scene is created (see KX_ConvertPhysicsObjects.cpp)
+ class btCollisionShape* shape;
+ class btTriangleMeshShape* meshShape;
+ vector<class btCollisionShape*>::iterator it = m_shapes.begin();
+ while (it != m_shapes.end()) {
+ shape = *it;
+ if (shape->getShapeType() == TRIANGLE_MESH_SHAPE_PROXYTYPE)
+ {
+ meshShape = static_cast<btTriangleMeshShape*>(shape);
+ // shapes based on meshes use an interface that contains the vertices.
+ // Again the idea is to be able to share the interface between shapes but
+ // this is not used in Blender: each base object will have its own interface
+ btStridingMeshInterface* meshInterface = meshShape->getMeshInterface();
+ if (meshInterface)
+ delete meshInterface;
+ }
+ delete shape;
+ it++;
+ }
+#endif
//Py_DECREF(m_attrlist);
}
+void KX_Scene::AddShape(class btCollisionShape*shape)
+{
+ m_shapes.push_back(shape);
+}
+
+
void KX_Scene::SetProjectionMatrix(MT_CmMatrix4x4& pmat)
{
m_projectionmat = pmat;
@@ -464,7 +484,7 @@ KX_GameObject* KX_Scene::AddNodeReplicaObject(class SG_IObject* node, class CVal
// this is the list of object that are send to the graphics pipeline
m_objectlist->Add(newobj->AddRef());
- newobj->AddMeshUser();
+ newobj->Bucketize();
// logic cannot be replicated, until the whole hierarchy is replicated.
m_logicHierarchicalGameObjects.push_back(newobj);
@@ -614,8 +634,7 @@ void KX_Scene::DupliGroupRecurse(CValue* obj, int level)
GroupObject *go;
vector<KX_GameObject*> duplilist;
- if (!groupobj->GetSGNode() ||
- !groupobj->IsDupliGroup() ||
+ if (!groupobj->IsDupliGroup() ||
level>MAX_DUPLI_RECUR)
return;
@@ -635,7 +654,6 @@ void KX_Scene::DupliGroupRecurse(CValue* obj, int level)
if (blgroupobj == blenderobj)
// this check is also in group_duplilist()
continue;
-
gameobj = (KX_GameObject*)m_logicmgr->FindGameObjByBlendObj(blenderobj);
if (gameobj == NULL)
{
@@ -643,9 +661,6 @@ void KX_Scene::DupliGroupRecurse(CValue* obj, int level)
// Should not happen as dupli group are created automatically
continue;
}
-
- gameobj->SetBlenderGroupObject(blgroupobj);
-
if ((blenderobj->lay & group->layer)==0)
{
// object is not visible in the 3D view, will not be instantiated
@@ -703,6 +718,17 @@ void KX_Scene::DupliGroupRecurse(CValue* obj, int level)
newscale*(groupobj->NodeGetWorldOrientation() * gameobj->NodeGetWorldPosition());
replica->NodeSetLocalPosition(newpos);
+ if (replica->GetPhysicsController())
+ {
+ // not required, already done in NodeSetLocalOrientation..
+ //replica->GetPhysicsController()->setPosition(newpos);
+ //replica->GetPhysicsController()->setOrientation(newori.getRotation());
+ // Scaling has been set relatively hereabove, this does not
+ // set the scaling of the controller. I don't know why it's just the
+ // relative scale and not the full scale that has to be put here...
+ replica->GetPhysicsController()->setScaling(newscale);
+ }
+
replica->GetSGNode()->UpdateWorldData(0);
replica->GetSGNode()->SetBBox(gameobj->GetSGNode()->BBox());
replica->GetSGNode()->SetRadius(gameobj->GetSGNode()->Radius());
@@ -827,6 +853,18 @@ SCA_IObject* KX_Scene::AddReplicaObject(class CValue* originalobject,
// set the replica's relative scale with the rootnode's scale
replica->NodeSetRelativeScale(newscale);
+ if (replica->GetPhysicsController())
+ {
+ // not needed, already done in NodeSetLocalPosition()
+ //replica->GetPhysicsController()->setPosition(newpos);
+ //replica->GetPhysicsController()->setOrientation(newori.getRotation());
+ replica->GetPhysicsController()->setScaling(newscale);
+ }
+
+ // here we want to set the relative scale: the rootnode's scale will override all other
+ // scalings, so lets better prepare for it
+
+
replica->GetSGNode()->UpdateWorldData(0);
replica->GetSGNode()->SetBBox(originalobj->GetSGNode()->BBox());
replica->GetSGNode()->SetRadius(originalobj->GetSGNode()->Radius());
@@ -937,8 +975,6 @@ int KX_Scene::NewRemoveObject(class CValue* gameobj)
newobj->RemoveMeshes();
ret = 1;
- if (m_lightlist->RemoveValue(newobj)) // TODO - use newobj->IsLight() test when its merged in from apricot. - Campbell
- ret = newobj->Release();
if (m_objectlist->RemoveValue(newobj))
ret = newobj->Release();
if (m_tempObjectList->RemoveValue(newobj))
@@ -986,13 +1022,13 @@ void KX_Scene::ReplaceMesh(class CValue* obj,void* meshobj)
{
BL_DeformableGameObject* newobj = static_cast<BL_DeformableGameObject*>( gameobj );
- if (newobj->GetDeformer())
+ if (newobj->m_pDeformer)
{
- delete newobj->GetDeformer();
- newobj->SetDeformer(NULL);
+ delete newobj->m_pDeformer;
+ newobj->m_pDeformer = NULL;
}
- if (mesh->IsDeformed())
+ if (mesh->m_class == 1)
{
// we must create a new deformer but which one?
KX_GameObject* parentobj = newobj->GetParent();
@@ -1039,7 +1075,7 @@ void KX_Scene::ReplaceMesh(class CValue* obj,void* meshobj)
NULL
);
}
- newobj->SetDeformer( shapeDeformer);
+ newobj->m_pDeformer = shapeDeformer;
}
else if (bHasArmature)
{
@@ -1051,14 +1087,14 @@ void KX_Scene::ReplaceMesh(class CValue* obj,void* meshobj)
static_cast<BL_ArmatureObject*>( parentobj )
);
releaseParent= false;
- newobj->SetDeformer(skinDeformer);
+ newobj->m_pDeformer = skinDeformer;
}
else if (bHasDvert)
{
BL_MeshDeformer* meshdeformer = new BL_MeshDeformer(
newobj, oldblendobj, static_cast<BL_SkinMeshObject*>(mesh)
);
- newobj->SetDeformer(meshdeformer);
+ newobj->m_pDeformer = meshdeformer;
}
// release parent reference if its not being used
@@ -1066,8 +1102,7 @@ void KX_Scene::ReplaceMesh(class CValue* obj,void* meshobj)
parentobj->Release();
}
}
-
- gameobj->AddMeshUser();
+ gameobj->Bucketize();
}
@@ -1219,9 +1254,7 @@ void KX_Scene::MarkSubTreeVisible(SG_Tree *node, RAS_IRasterizer* rasty, bool vi
for (int m=0;m<nummeshes;m++)
(gameobj->GetMesh(m))->SchedulePolygons(rasty->GetDrawingMode());
}
-
- gameobj->SetCulled(!visible);
- gameobj->UpdateBuckets(false);
+ gameobj->MarkVisible(visible);
}
}
if (node->Left())
@@ -1233,13 +1266,12 @@ void KX_Scene::MarkSubTreeVisible(SG_Tree *node, RAS_IRasterizer* rasty, bool vi
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())
+ if (!gameobj->GetVisible())
return;
// Shadow lamp layers
if(layer && !(gameobj->GetLayer() & layer)) {
- gameobj->SetCulled(true);
- gameobj->UpdateBuckets(false);
+ gameobj->MarkVisible(false);
return;
}
@@ -1249,7 +1281,7 @@ void KX_Scene::MarkVisible(RAS_IRasterizer* rasty, KX_GameObject* gameobj,KX_Cam
// If the camera is inside this node, then the object is visible.
if (!vis)
{
- vis = gameobj->GetSGNode()->inside( cam->GetCameraLocation() );
+ vis = gameobj->GetSGNode()->inside( GetActiveCamera()->GetCameraLocation() );
}
// Test the object's bound sphere against the view frustum.
@@ -1285,11 +1317,9 @@ void KX_Scene::MarkVisible(RAS_IRasterizer* rasty, KX_GameObject* gameobj,KX_Cam
}
// Visibility/ non-visibility are marked
// elsewhere now.
- gameobj->SetCulled(false);
- gameobj->UpdateBuckets(false);
+ gameobj->MarkVisible();
} else {
- gameobj->SetCulled(true);
- gameobj->UpdateBuckets(false);
+ gameobj->MarkVisible(false);
}
}
diff --git a/source/gameengine/Ketsji/KX_Scene.h b/source/gameengine/Ketsji/KX_Scene.h
index 5f7e1167e27..80a2abe287a 100644
--- a/source/gameengine/Ketsji/KX_Scene.h
+++ b/source/gameengine/Ketsji/KX_Scene.h
@@ -54,7 +54,6 @@
*/
struct SM_MaterialProps;
struct SM_ShapeProps;
-struct Scene;
class GEN_HashedPtr;
class CListValue;
@@ -123,6 +122,11 @@ protected:
*/
list<class KX_Camera*> m_cameras;
/**
+ * The set of bullet shapes that must be deleted at the end of the scene
+ * to avoid memory leak (not deleted by bullet because shape are shared between replicas)
+ */
+ vector<class btCollisionShape*> m_shapes;
+ /**
* Various SCA managers used by the scene
*/
SCA_LogicManager* m_logicmgr;
@@ -278,15 +282,12 @@ protected:
*/
PyObject* m_attrlist;
- struct Scene* m_blenderScene;
-
public:
KX_Scene(class SCA_IInputDevice* keyboarddevice,
class SCA_IInputDevice* mousedevice,
class NG_NetworkDeviceInterface* ndi,
class SND_IAudioDevice* adi,
- const STR_String& scenename,
- struct Scene* scene);
+ const STR_String& scenename );
virtual
~KX_Scene();
@@ -321,6 +322,7 @@ public:
int NewRemoveObject(CValue* gameobj);
void ReplaceMesh(CValue* gameobj,
void* meshobj);
+ void AddShape(class btCollisionShape* shape);
/**
* @section Logic stuff
* Initiate an update of the logic system.
@@ -586,10 +588,6 @@ public:
* was running and not suspended) and the "curtime"
*/
double getSuspendedDelta();
- /**
- * Returns the Blender scene this was made from
- */
- struct Scene *GetBlenderScene() { return m_blenderScene; }
};
typedef std::vector<KX_Scene*> KX_SceneList;
diff --git a/source/gameengine/Ketsji/KX_SceneActuator.cpp b/source/gameengine/Ketsji/KX_SceneActuator.cpp
index 35484699b17..d6164dc812a 100644
--- a/source/gameengine/Ketsji/KX_SceneActuator.cpp
+++ b/source/gameengine/Ketsji/KX_SceneActuator.cpp
@@ -259,12 +259,12 @@ PyParentObject KX_SceneActuator::Parents[] =
PyMethodDef KX_SceneActuator::Methods[] =
{
- {"setUseRestart", (PyCFunction) KX_SceneActuator::sPySetUseRestart, METH_VARARGS, (PY_METHODCHAR)SetUseRestart_doc},
- {"setScene", (PyCFunction) KX_SceneActuator::sPySetScene, METH_VARARGS, (PY_METHODCHAR)SetScene_doc},
- {"setCamera", (PyCFunction) KX_SceneActuator::sPySetCamera, METH_VARARGS, (PY_METHODCHAR)SetCamera_doc},
- {"getUseRestart", (PyCFunction) KX_SceneActuator::sPyGetUseRestart, METH_VARARGS, (PY_METHODCHAR)GetUseRestart_doc},
- {"getScene", (PyCFunction) KX_SceneActuator::sPyGetScene, METH_VARARGS, (PY_METHODCHAR)GetScene_doc},
- {"getCamera", (PyCFunction) KX_SceneActuator::sPyGetCamera, METH_VARARGS, (PY_METHODCHAR)GetCamera_doc},
+ {"setUseRestart", (PyCFunction) KX_SceneActuator::sPySetUseRestart, METH_VARARGS, SetUseRestart_doc},
+ {"setScene", (PyCFunction) KX_SceneActuator::sPySetScene, METH_VARARGS, SetScene_doc},
+ {"setCamera", (PyCFunction) KX_SceneActuator::sPySetCamera, METH_VARARGS, SetCamera_doc},
+ {"getUseRestart", (PyCFunction) KX_SceneActuator::sPyGetUseRestart, METH_VARARGS, GetUseRestart_doc},
+ {"getScene", (PyCFunction) KX_SceneActuator::sPyGetScene, METH_VARARGS, GetScene_doc},
+ {"getCamera", (PyCFunction) KX_SceneActuator::sPyGetCamera, METH_VARARGS, GetCamera_doc},
{NULL,NULL} //Sentinel
};
@@ -278,7 +278,7 @@ PyObject* KX_SceneActuator::_getattr(const STR_String& attr)
/* 2. setUseRestart--------------------------------------------------------- */
-const char KX_SceneActuator::SetUseRestart_doc[] =
+char KX_SceneActuator::SetUseRestart_doc[] =
"setUseRestart(flag)\n"
"\t- flag: 0 or 1.\n"
"\tSet flag to 1 to restart the scene.\n" ;
@@ -301,7 +301,7 @@ PyObject* KX_SceneActuator::PySetUseRestart(PyObject* self,
/* 3. getUseRestart: */
-const char KX_SceneActuator::GetUseRestart_doc[] =
+char KX_SceneActuator::GetUseRestart_doc[] =
"getUseRestart()\n"
"\tReturn whether the scene will be restarted.\n" ;
PyObject* KX_SceneActuator::PyGetUseRestart(PyObject* self,
@@ -314,7 +314,7 @@ PyObject* KX_SceneActuator::PyGetUseRestart(PyObject* self,
/* 4. set scene------------------------------------------------------------- */
-const char KX_SceneActuator::SetScene_doc[] =
+char KX_SceneActuator::SetScene_doc[] =
"setScene(scene)\n"
"\t- scene: string\n"
"\tSet the name of scene the actuator will switch to.\n" ;
@@ -339,7 +339,7 @@ PyObject* KX_SceneActuator::PySetScene(PyObject* self,
/* 5. getScene: */
-const char KX_SceneActuator::GetScene_doc[] =
+char KX_SceneActuator::GetScene_doc[] =
"getScene()\n"
"\tReturn the name of the scene the actuator wants to switch to.\n" ;
PyObject* KX_SceneActuator::PyGetScene(PyObject* self,
@@ -352,7 +352,7 @@ PyObject* KX_SceneActuator::PyGetScene(PyObject* self,
/* 6. set camera------------------------------------------------------------ */
-const char KX_SceneActuator::SetCamera_doc[] =
+char KX_SceneActuator::SetCamera_doc[] =
"setCamera(camera)\n"
"\t- camera: string\n"
"\tSet the camera to switch to.\n" ;
@@ -394,7 +394,7 @@ PyObject* KX_SceneActuator::PySetCamera(PyObject* self,
/* 7. getCamera: */
-const char KX_SceneActuator::GetCamera_doc[] =
+char KX_SceneActuator::GetCamera_doc[] =
"getCamera()\n"
"\tReturn the name of the camera to switch to.\n" ;
PyObject* KX_SceneActuator::PyGetCamera(PyObject* self,
diff --git a/source/gameengine/Ketsji/KX_SoundActuator.cpp b/source/gameengine/Ketsji/KX_SoundActuator.cpp
index afa5af3bc04..34a3baec093 100644
--- a/source/gameengine/Ketsji/KX_SoundActuator.cpp
+++ b/source/gameengine/Ketsji/KX_SoundActuator.cpp
@@ -69,11 +69,11 @@ KX_SoundActuator::KX_SoundActuator(SCA_IObject* gameobj,
KX_SoundActuator::~KX_SoundActuator()
{
- if (m_soundObject)
- {
- m_soundScene->RemoveActiveObject(m_soundObject);
- m_soundScene->DeleteObject(m_soundObject);
- }
+ //m_soundScene->RemoveObject(this->m_soundObject);
+ //(this->m_soundObject)->DeleteWhenFinished();
+ m_soundScene->RemoveActiveObject(m_soundObject);
+// m_soundScene->DeleteObjectWhenFinished(m_soundObject);
+ m_soundScene->DeleteObject(m_soundObject);
}
@@ -82,12 +82,9 @@ CValue* KX_SoundActuator::GetReplica()
{
KX_SoundActuator* replica = new KX_SoundActuator(*this);
replica->ProcessReplica();
- if (m_soundObject)
- {
- SND_SoundObject* soundobj = new SND_SoundObject(*m_soundObject);
- replica->setSoundObject(soundobj);
- m_soundScene->AddObject(soundobj);
- }
+ SND_SoundObject* soundobj = new SND_SoundObject(*m_soundObject);
+ replica->setSoundObject(soundobj);
+ m_soundScene->AddObject(soundobj);
// this will copy properties and so on...
CValue::AddDataToReplica(replica);
@@ -107,12 +104,6 @@ bool KX_SoundActuator::Update(double curtime, bool frame)
RemoveAllEvents();
- if (!m_soundObject)
- return false;
-
- // actual audio device playing state
- bool isplaying = (m_soundObject->GetPlaystate() != SND_STOPPED) ? true : false;
-
if (m_pino)
{
bNegativeEvent = true;
@@ -122,40 +113,30 @@ bool KX_SoundActuator::Update(double curtime, bool frame)
if (bNegativeEvent)
{
// here must be a check if it is still playing
- if (m_isplaying && isplaying)
+ m_isplaying = false;
+
+ switch (m_type)
{
- switch (m_type)
+ case KX_SOUNDACT_PLAYSTOP:
+ case KX_SOUNDACT_LOOPSTOP:
+ case KX_SOUNDACT_LOOPBIDIRECTIONAL_STOP:
{
- case KX_SOUNDACT_PLAYSTOP:
- case KX_SOUNDACT_LOOPSTOP:
- case KX_SOUNDACT_LOOPBIDIRECTIONAL_STOP:
- {
- m_soundScene->RemoveActiveObject(m_soundObject);
- break;
- }
- case KX_SOUNDACT_PLAYEND:
- {
- m_soundObject->SetPlaystate(SND_MUST_STOP_WHEN_FINISHED);
- break;
- }
- case KX_SOUNDACT_LOOPEND:
- case KX_SOUNDACT_LOOPBIDIRECTIONAL:
- {
- m_soundObject->SetLoopMode(SND_LOOP_OFF);
- m_soundObject->SetPlaystate(SND_MUST_STOP_WHEN_FINISHED);
- break;
- }
- default:
- // implement me !!
+ m_soundScene->RemoveActiveObject(m_soundObject);
break;
}
+ case KX_SOUNDACT_PLAYEND:
+ {
+ m_soundObject->SetPlaystate(SND_MUST_STOP_WHEN_FINISHED);
+ break;
+ }
+ default:
+ // implement me !!
+ break;
}
- // remember that we tried to stop the actuator
- m_isplaying = false;
}
else
{
- if (!m_isplaying)
+ if (m_soundObject && !m_isplaying)
{
switch (m_type)
{
@@ -192,10 +173,8 @@ bool KX_SoundActuator::Update(double curtime, bool frame)
}
}
}
- // verify that the sound is still playing
- isplaying = (m_soundObject->GetPlaystate() != SND_STOPPED) ? true : false;
- if (isplaying)
+ if (m_isplaying)
{
m_soundObject->SetPosition(((KX_GameObject*)this->GetParent())->NodeGetWorldPosition());
m_soundObject->SetVelocity(((KX_GameObject*)this->GetParent())->GetLinearVelocity());
@@ -204,15 +183,14 @@ bool KX_SoundActuator::Update(double curtime, bool frame)
}
else
{
- m_isplaying = false;
result = false;
}
- /*
+
if (result && (m_soundObject->IsLifeSpanOver(curtime)) && ((m_type == KX_SOUNDACT_PLAYEND) || (m_type == KX_SOUNDACT_PLAYSTOP)))
{
m_pino = true;
}
- */
+
return result;
}
@@ -309,10 +287,6 @@ PyObject* KX_SoundActuator::PySetFilename(PyObject* self, PyObject* args, PyObje
PyObject* KX_SoundActuator::PyGetFilename(PyObject* self, PyObject* args, PyObject* kwds)
{
- if (!m_soundObject)
- {
- return PyString_FromString("");
- }
STR_String objectname = m_soundObject->GetObjectName();
char* name = objectname.Ptr();
@@ -327,11 +301,7 @@ PyObject* KX_SoundActuator::PyGetFilename(PyObject* self, PyObject* args, PyObje
PyObject* KX_SoundActuator::PyStartSound(PyObject* self, PyObject* args, PyObject* kwds)
{
- if (m_soundObject)
- // This has no effect if the actuator is not active.
- // To start the sound you must activate the actuator.
- // This function is to restart the sound.
- m_soundObject->StartSound();
+ m_soundObject->StartSound();
Py_Return;
}
@@ -339,9 +309,7 @@ PyObject* KX_SoundActuator::PyStartSound(PyObject* self, PyObject* args, PyObjec
PyObject* KX_SoundActuator::PyPauseSound(PyObject* self, PyObject* args, PyObject* kwds)
{
- if (m_soundObject)
- // unfortunately, openal does not implement pause correctly, it is equivalent to a stop
- m_soundObject->PauseSound();
+ m_soundObject->PauseSound();
Py_Return;
}
@@ -349,8 +317,7 @@ PyObject* KX_SoundActuator::PyPauseSound(PyObject* self, PyObject* args, PyObjec
PyObject* KX_SoundActuator::PyStopSound(PyObject* self, PyObject* args, PyObject* kwds)
{
- if (m_soundObject)
- m_soundObject->StopSound();
+ m_soundObject->StopSound();
Py_Return;
}
@@ -362,8 +329,7 @@ PyObject* KX_SoundActuator::PySetGain(PyObject* self, PyObject* args, PyObject*
if (!PyArg_ParseTuple(args, "f", &gain))
return NULL;
- if (m_soundObject)
- m_soundObject->SetGain(gain);
+ m_soundObject->SetGain(gain);
Py_Return;
}
@@ -372,7 +338,7 @@ PyObject* KX_SoundActuator::PySetGain(PyObject* self, PyObject* args, PyObject*
PyObject* KX_SoundActuator::PyGetGain(PyObject* self, PyObject* args, PyObject* kwds)
{
- float gain = (m_soundObject) ? m_soundObject->GetGain() : 1.0f;
+ float gain = m_soundObject->GetGain();
PyObject* result = PyFloat_FromDouble(gain);
return result;
@@ -386,8 +352,7 @@ PyObject* KX_SoundActuator::PySetPitch(PyObject* self, PyObject* args, PyObject*
if (!PyArg_ParseTuple(args, "f", &pitch))
return NULL;
- if (m_soundObject)
- m_soundObject->SetPitch(pitch);
+ m_soundObject->SetPitch(pitch);
Py_Return;
}
@@ -396,7 +361,7 @@ PyObject* KX_SoundActuator::PySetPitch(PyObject* self, PyObject* args, PyObject*
PyObject* KX_SoundActuator::PyGetPitch(PyObject* self, PyObject* args, PyObject* kwds)
{
- float pitch = (m_soundObject) ? m_soundObject->GetPitch() : 1.0;
+ float pitch = m_soundObject->GetPitch();
PyObject* result = PyFloat_FromDouble(pitch);
return result;
@@ -410,8 +375,7 @@ PyObject* KX_SoundActuator::PySetRollOffFactor(PyObject* self, PyObject* args, P
if (!PyArg_ParseTuple(args, "f", &rollofffactor))
return NULL;
- if (m_soundObject)
- m_soundObject->SetRollOffFactor(rollofffactor);
+ m_soundObject->SetRollOffFactor(rollofffactor);
Py_Return;
}
@@ -420,7 +384,7 @@ PyObject* KX_SoundActuator::PySetRollOffFactor(PyObject* self, PyObject* args, P
PyObject* KX_SoundActuator::PyGetRollOffFactor(PyObject* self, PyObject* args, PyObject* kwds)
{
- float rollofffactor = (m_soundObject) ? m_soundObject->GetRollOffFactor() : 1.0;
+ float rollofffactor = m_soundObject->GetRollOffFactor();
PyObject* result = PyFloat_FromDouble(rollofffactor);
return result;
@@ -434,8 +398,7 @@ PyObject* KX_SoundActuator::PySetLooping(PyObject* self, PyObject* args, PyObjec
if (!PyArg_ParseTuple(args, "i", &looping))
return NULL;
- if (m_soundObject)
- m_soundObject->SetLoopMode(looping);
+ m_soundObject->SetLoopMode(looping);
Py_Return;
}
@@ -444,7 +407,7 @@ PyObject* KX_SoundActuator::PySetLooping(PyObject* self, PyObject* args, PyObjec
PyObject* KX_SoundActuator::PyGetLooping(PyObject* self, PyObject* args, PyObject* kwds)
{
- int looping = (m_soundObject) ? m_soundObject->GetLoopMode() : SND_LOOP_OFF;
+ int looping = m_soundObject->GetLoopMode();
PyObject* result = PyInt_FromLong(looping);
return result;
@@ -462,8 +425,7 @@ PyObject* KX_SoundActuator::PySetPosition(PyObject* self, PyObject* args, PyObje
if (!PyArg_ParseTuple(args, "fff", &pos[0], &pos[1], &pos[2]))
return NULL;
- if (m_soundObject)
- m_soundObject->SetPosition(pos);
+ m_soundObject->SetPosition(pos);
Py_Return;
}
@@ -480,8 +442,7 @@ PyObject* KX_SoundActuator::PySetVelocity(PyObject* self, PyObject* args, PyObje
if (!PyArg_ParseTuple(args, "fff", &vel[0], &vel[1], &vel[2]))
return NULL;
- if (m_soundObject)
- m_soundObject->SetVelocity(vel);
+ m_soundObject->SetVelocity(vel);
Py_Return;
}
@@ -504,8 +465,7 @@ PyObject* KX_SoundActuator::PySetOrientation(PyObject* self, PyObject* args, PyO
if (!PyArg_ParseTuple(args, "fffffffff", &ori[0][0], &ori[0][1], &ori[0][2], &ori[1][0], &ori[1][1], &ori[1][2], &ori[2][0], &ori[2][1], &ori[2][2]))
return NULL;
- if (m_soundObject)
- m_soundObject->SetOrientation(ori);
+ m_soundObject->SetOrientation(ori);
Py_Return;
}
diff --git a/source/gameengine/Ketsji/KX_StateActuator.cpp b/source/gameengine/Ketsji/KX_StateActuator.cpp
index e360c4bac1f..95a79f0c480 100644
--- a/source/gameengine/Ketsji/KX_StateActuator.cpp
+++ b/source/gameengine/Ketsji/KX_StateActuator.cpp
@@ -140,9 +140,9 @@ KX_StateActuator::Parents[] = {
PyMethodDef
KX_StateActuator::Methods[] = {
{"setOperation", (PyCFunction) KX_StateActuator::sPySetOperation,
- METH_VARARGS, (PY_METHODCHAR)SetOperation_doc},
+ METH_VARARGS, SetOperation_doc},
{"setMask", (PyCFunction) KX_StateActuator::sPySetMask,
- METH_VARARGS, (PY_METHODCHAR)SetMask_doc},
+ METH_VARARGS, SetMask_doc},
{NULL,NULL} //Sentinel
};
@@ -157,7 +157,7 @@ KX_StateActuator::_getattr(
/* set operation ---------------------------------------------------------- */
-const char
+char
KX_StateActuator::SetOperation_doc[] =
"setOperation(op)\n"
"\t - op : bit operation (0=Copy, 1=Set, 2=Clear, 3=Negate)"
@@ -180,7 +180,7 @@ KX_StateActuator::PySetOperation(PyObject* self,
}
/* set mask ---------------------------------------------------------- */
-const char
+char
KX_StateActuator::SetMask_doc[] =
"setMask(mask)\n"
"\t - mask : bits that will be modified"
diff --git a/source/gameengine/Ketsji/KX_SumoPhysicsController.cpp b/source/gameengine/Ketsji/KX_SumoPhysicsController.cpp
index c842ca1ee14..4032a795ce3 100644
--- a/source/gameengine/Ketsji/KX_SumoPhysicsController.cpp
+++ b/source/gameengine/Ketsji/KX_SumoPhysicsController.cpp
@@ -205,11 +205,6 @@ MT_Scalar KX_SumoPhysicsController::GetMass()
return SumoPhysicsController::getMass();
}
-MT_Scalar KX_SumoPhysicsController::GetRadius()
-{
- return SumoPhysicsController::GetRadius();
-}
-
MT_Vector3 KX_SumoPhysicsController::getReactionForce()
{
float force[3];
diff --git a/source/gameengine/Ketsji/KX_SumoPhysicsController.h b/source/gameengine/Ketsji/KX_SumoPhysicsController.h
index abe48d99043..1dd930bf3d9 100644
--- a/source/gameengine/Ketsji/KX_SumoPhysicsController.h
+++ b/source/gameengine/Ketsji/KX_SumoPhysicsController.h
@@ -84,7 +84,6 @@ public:
virtual void setPosition(const MT_Point3& pos);
virtual void setScaling(const MT_Vector3& scaling);
virtual MT_Scalar GetMass();
- virtual MT_Scalar GetRadius();
virtual MT_Vector3 getReactionForce();
virtual void setRigidBody(bool rigid);
diff --git a/source/gameengine/Ketsji/KX_TouchSensor.cpp b/source/gameengine/Ketsji/KX_TouchSensor.cpp
index 1935a0bde39..60e1d87d318 100644
--- a/source/gameengine/Ketsji/KX_TouchSensor.cpp
+++ b/source/gameengine/Ketsji/KX_TouchSensor.cpp
@@ -55,17 +55,9 @@ void KX_TouchSensor::SynchronizeTransform()
void KX_TouchSensor::EndFrame() {
m_colliders->ReleaseAndRemoveAll();
- m_hitObject = NULL;
m_bTriggered = false;
}
-void KX_TouchSensor::UnregisterToManager()
-{
- // before unregistering the sensor, make sure we release all references
- EndFrame();
- m_eventmgr->RemoveSensor(this);
-}
-
bool KX_TouchSensor::Evaluate(CValue* event)
{
bool result = false;
@@ -184,10 +176,7 @@ bool KX_TouchSensor::NewHandleCollision(void*object1,void*object2,const PHY_Coll
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())
+ if (gameobj && (gameobj != parent) && client_info->isActor())
{
if (!m_colliders->SearchValue(gameobj))
m_colliders->Add(gameobj->AddRef());
@@ -251,13 +240,13 @@ PyParentObject KX_TouchSensor::Parents[] = {
PyMethodDef KX_TouchSensor::Methods[] = {
{"setProperty",
- (PyCFunction) KX_TouchSensor::sPySetProperty, METH_VARARGS, (PY_METHODCHAR)SetProperty_doc},
+ (PyCFunction) KX_TouchSensor::sPySetProperty, METH_VARARGS, SetProperty_doc},
{"getProperty",
- (PyCFunction) KX_TouchSensor::sPyGetProperty, METH_VARARGS, (PY_METHODCHAR)GetProperty_doc},
+ (PyCFunction) KX_TouchSensor::sPyGetProperty, METH_VARARGS, GetProperty_doc},
{"getHitObject",
- (PyCFunction) KX_TouchSensor::sPyGetHitObject, METH_VARARGS, (PY_METHODCHAR)GetHitObject_doc},
+ (PyCFunction) KX_TouchSensor::sPyGetHitObject, METH_VARARGS, GetHitObject_doc},
{"getHitObjectList",
- (PyCFunction) KX_TouchSensor::sPyGetHitObjectList, METH_VARARGS, (PY_METHODCHAR)GetHitObjectList_doc},
+ (PyCFunction) KX_TouchSensor::sPyGetHitObjectList, METH_VARARGS, GetHitObjectList_doc},
{NULL,NULL} //Sentinel
};
@@ -268,7 +257,7 @@ PyObject* KX_TouchSensor::_getattr(const STR_String& attr) {
/* Python API */
/* 1. setProperty */
-const char KX_TouchSensor::SetProperty_doc[] =
+char KX_TouchSensor::SetProperty_doc[] =
"setProperty(name)\n"
"\t- name: string\n"
"\tSet the property or material to collide with. Use\n"
@@ -294,7 +283,7 @@ PyObject* KX_TouchSensor::PySetProperty(PyObject* self,
Py_Return;
}
/* 2. getProperty */
-const char KX_TouchSensor::GetProperty_doc[] =
+char KX_TouchSensor::GetProperty_doc[] =
"getProperty(name)\n"
"\tReturns the property or material to collide with. Use\n"
"\tgetTouchMaterial() to find out whether this sensor\n"
@@ -305,7 +294,7 @@ PyObject* KX_TouchSensor::PyGetProperty(PyObject* self,
return PyString_FromString(m_touchedpropname);
}
-const char KX_TouchSensor::GetHitObject_doc[] =
+char KX_TouchSensor::GetHitObject_doc[] =
"getHitObject()\n"
;
PyObject* KX_TouchSensor::PyGetHitObject(PyObject* self,
@@ -321,7 +310,7 @@ PyObject* KX_TouchSensor::PyGetHitObject(PyObject* self,
Py_Return;
}
-const char KX_TouchSensor::GetHitObjectList_doc[] =
+char KX_TouchSensor::GetHitObjectList_doc[] =
"getHitObjectList()\n"
"\tReturn a list of the objects this object collided with,\n"
"\tbut only those matching the property/material condition.\n";
@@ -375,7 +364,7 @@ PyObject* KX_TouchSensor::PyGetHitObjectList(PyObject* self,
}
/* 5. getTouchMaterial */
-const char KX_TouchSensor::GetTouchMaterial_doc[] =
+char KX_TouchSensor::GetTouchMaterial_doc[] =
"getTouchMaterial()\n"
"\tReturns KX_TRUE if this sensor looks for a specific material,\n"
"\tKX_FALSE if it looks for a specific property.\n" ;
@@ -387,7 +376,7 @@ PyObject* KX_TouchSensor::PyGetTouchMaterial(PyObject* self,
}
/* 6. setTouchMaterial */
-const char KX_TouchSensor::SetTouchMaterial_doc[] =
+char KX_TouchSensor::SetTouchMaterial_doc[] =
"setTouchMaterial(flag)\n"
"\t- flag: KX_TRUE or KX_FALSE.\n"
"\tSet flag to KX_TRUE to switch on positive pulse mode,\n"
diff --git a/source/gameengine/Ketsji/KX_TouchSensor.h b/source/gameengine/Ketsji/KX_TouchSensor.h
index 8fbb1c676ba..b611d296939 100644
--- a/source/gameengine/Ketsji/KX_TouchSensor.h
+++ b/source/gameengine/Ketsji/KX_TouchSensor.h
@@ -77,7 +77,6 @@ public:
virtual void RegisterSumo(KX_TouchEventManager* touchman);
virtual void UnregisterSumo(KX_TouchEventManager* touchman);
- virtual void UnregisterToManager();
// virtual DT_Bool HandleCollision(void* obj1,void* obj2,
// const DT_CollData * coll_data);
diff --git a/source/gameengine/Ketsji/KX_TrackToActuator.cpp b/source/gameengine/Ketsji/KX_TrackToActuator.cpp
index acc4a6ab5d7..f5b463abf02 100644
--- a/source/gameengine/Ketsji/KX_TrackToActuator.cpp
+++ b/source/gameengine/Ketsji/KX_TrackToActuator.cpp
@@ -42,8 +42,6 @@
#include <iostream>
#include "KX_GameObject.h"
-#include "PyObjectPlus.h"
-
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
@@ -456,12 +454,12 @@ PyParentObject KX_TrackToActuator::Parents[] = {
PyMethodDef KX_TrackToActuator::Methods[] = {
- {"setObject", (PyCFunction) KX_TrackToActuator::sPySetObject, METH_O, (PY_METHODCHAR)SetObject_doc},
- {"getObject", (PyCFunction) KX_TrackToActuator::sPyGetObject, METH_VARARGS, (PY_METHODCHAR)GetObject_doc},
- {"setTime", (PyCFunction) KX_TrackToActuator::sPySetTime, METH_VARARGS, (PY_METHODCHAR)SetTime_doc},
- {"getTime", (PyCFunction) KX_TrackToActuator::sPyGetTime, METH_VARARGS, (PY_METHODCHAR)GetTime_doc},
- {"setUse3D", (PyCFunction) KX_TrackToActuator::sPySetUse3D, METH_VARARGS, (PY_METHODCHAR)SetUse3D_doc},
- {"getUse3D", (PyCFunction) KX_TrackToActuator::sPyGetUse3D, METH_VARARGS, (PY_METHODCHAR)GetUse3D_doc},
+ {"setObject", (PyCFunction) KX_TrackToActuator::sPySetObject, METH_VARARGS, SetObject_doc},
+ {"getObject", (PyCFunction) KX_TrackToActuator::sPyGetObject, METH_VARARGS, GetObject_doc},
+ {"setTime", (PyCFunction) KX_TrackToActuator::sPySetTime, METH_VARARGS, SetTime_doc},
+ {"getTime", (PyCFunction) KX_TrackToActuator::sPyGetTime, METH_VARARGS, GetTime_doc},
+ {"setUse3D", (PyCFunction) KX_TrackToActuator::sPySetUse3D, METH_VARARGS, SetUse3D_doc},
+ {"getUse3D", (PyCFunction) KX_TrackToActuator::sPyGetUse3D, METH_VARARGS, GetUse3D_doc},
{NULL,NULL} //Sentinel
};
@@ -475,53 +473,55 @@ PyObject* KX_TrackToActuator::_getattr(const STR_String& attr)
/* 1. setObject */
-const char KX_TrackToActuator::SetObject_doc[] =
+char KX_TrackToActuator::SetObject_doc[] =
"setObject(object)\n"
-"\t- object: KX_GameObject, string or None\n"
+"\t- object: string\n"
"\tSet the object to track with the parent of this actuator.\n";
-PyObject* KX_TrackToActuator::PySetObject(PyObject* self, PyObject* value)
-{
- KX_GameObject *gameobj;
-
- if (!ConvertPythonToGameObject(value, &gameobj, true))
- return NULL; // ConvertPythonToGameObject sets the error
+PyObject* KX_TrackToActuator::PySetObject(PyObject* self, PyObject* args, PyObject* kwds) {
+ PyObject* gameobj;
+ if (PyArg_ParseTuple(args, "O!", &KX_GameObject::Type, &gameobj))
+ {
+ if (m_object != NULL)
+ m_object->UnregisterActuator(this);
+ m_object = (SCA_IObject*)gameobj;
+ if (m_object)
+ m_object->RegisterActuator(this);
+ Py_Return;
+ }
+ PyErr_Clear();
- if (m_object != NULL)
- m_object->UnregisterActuator(this);
-
- m_object = (SCA_IObject*)gameobj;
- if (m_object)
- m_object->RegisterActuator(this);
+ char* objectname;
+ if (PyArg_ParseTuple(args, "s", &objectname))
+ {
+ if (m_object != NULL)
+ m_object->UnregisterActuator(this);
+ m_object= static_cast<SCA_IObject*>(SCA_ILogicBrick::m_sCurrentLogicManager->GetGameObjectByName(STR_String(objectname)));
+ if (m_object)
+ m_object->RegisterActuator(this);
+ Py_Return;
+ }
- Py_RETURN_NONE;
+ return NULL;
}
/* 2. getObject */
-const char KX_TrackToActuator::GetObject_doc[] =
-"getObject(name_only = 1)\n"
-"name_only - optional arg, when true will return the KX_GameObject rather then its name\n"
-"\tReturns the object to track with the parent of this actuator\n";
-PyObject* KX_TrackToActuator::PyGetObject(PyObject* self, PyObject* args)
+char KX_TrackToActuator::GetObject_doc[] =
+"getObject()\n"
+"\tReturns the object to track with the parent of this actuator.\n";
+PyObject* KX_TrackToActuator::PyGetObject(PyObject* self, PyObject* args, PyObject* kwds)
{
- int ret_name_only = 1;
- if (!PyArg_ParseTuple(args, "|i", &ret_name_only))
- return NULL;
-
if (!m_object)
- Py_RETURN_NONE;
-
- if (ret_name_only)
- return PyString_FromString(m_object->GetName());
- else
- return m_object->AddRef();
+ Py_Return;
+
+ return PyString_FromString(m_object->GetName());
}
/* 3. setTime */
-const char KX_TrackToActuator::SetTime_doc[] =
+char KX_TrackToActuator::SetTime_doc[] =
"setTime(time)\n"
"\t- time: integer\n"
"\tSet the time in frames with which to delay the tracking motion.\n";
@@ -542,7 +542,7 @@ PyObject* KX_TrackToActuator::PySetTime(PyObject* self, PyObject* args, PyObject
/* 4.getTime */
-const char KX_TrackToActuator::GetTime_doc[] =
+char KX_TrackToActuator::GetTime_doc[] =
"getTime()\n"
"\t- time: integer\n"
"\tReturn the time in frames with which the tracking motion is delayed.\n";
@@ -554,7 +554,7 @@ PyObject* KX_TrackToActuator::PyGetTime(PyObject* self, PyObject* args, PyObject
/* 5. getUse3D */
-const char KX_TrackToActuator::GetUse3D_doc[] =
+char KX_TrackToActuator::GetUse3D_doc[] =
"getUse3D()\n"
"\tReturns 1 if the motion is allowed to extend in the z-direction.\n";
PyObject* KX_TrackToActuator::PyGetUse3D(PyObject* self, PyObject* args, PyObject* kwds)
@@ -565,7 +565,7 @@ PyObject* KX_TrackToActuator::PyGetUse3D(PyObject* self, PyObject* args, PyObjec
/* 6. setUse3D */
-const char KX_TrackToActuator::SetUse3D_doc[] =
+char KX_TrackToActuator::SetUse3D_doc[] =
"setUse3D(value)\n"
"\t- value: 0 or 1\n"
"\tSet to 1 to allow the tracking motion to extend in the z-direction,\n"
diff --git a/source/gameengine/Ketsji/KX_TrackToActuator.h b/source/gameengine/Ketsji/KX_TrackToActuator.h
index 445132a6094..1d1cf46d21b 100644
--- a/source/gameengine/Ketsji/KX_TrackToActuator.h
+++ b/source/gameengine/Ketsji/KX_TrackToActuator.h
@@ -75,9 +75,9 @@ class KX_TrackToActuator : public SCA_IActuator
virtual PyObject* _getattr(const STR_String& attr);
/* 1. setObject */
- KX_PYMETHOD_DOC_O(KX_TrackToActuator,SetObject);
+ KX_PYMETHOD_DOC(KX_TrackToActuator,SetObject);
/* 2. getObject */
- KX_PYMETHOD_DOC_VARARGS(KX_TrackToActuator,GetObject);
+ KX_PYMETHOD_DOC(KX_TrackToActuator,GetObject);
/* 3. setTime */
KX_PYMETHOD_DOC(KX_TrackToActuator,SetTime);
/* 4. getTime */
diff --git a/source/gameengine/Ketsji/KX_VehicleWrapper.cpp b/source/gameengine/Ketsji/KX_VehicleWrapper.cpp
index 028f96f6c5b..7e8160a4d67 100644
--- a/source/gameengine/Ketsji/KX_VehicleWrapper.cpp
+++ b/source/gameengine/Ketsji/KX_VehicleWrapper.cpp
@@ -1,8 +1,6 @@
#include <Python.h>
-#include "PyObjectPlus.h"
-
#include "KX_VehicleWrapper.h"
#include "PHY_IPhysicsEnvironment.h"
#include "PHY_IVehicle.h"
@@ -49,34 +47,32 @@ PyObject* KX_VehicleWrapper::PyAddWheel(PyObject* self,
if (PyArg_ParseTuple(args,"OOOOffi",&wheelGameObject,&pylistPos,&pylistDir,&pylistAxleDir,&suspensionRestLength,&wheelRadius,&hasSteering))
{
KX_GameObject* gameOb = (KX_GameObject*) wheelGameObject;
-
- if (gameOb->GetSGNode())
- {
- PHY_IMotionState* motionState = new KX_MotionState(gameOb->GetSGNode());
-
- MT_Vector3 attachPos,attachDir,attachAxle;
- PyVecTo(pylistPos,attachPos);
- PyVecTo(pylistDir,attachDir);
- PyVecTo(pylistAxleDir,attachAxle);
- PHY__Vector3 aPos,aDir,aAxle;
- aPos[0] = attachPos[0];
- aPos[1] = attachPos[1];
- aPos[2] = attachPos[2];
- aDir[0] = attachDir[0];
- aDir[1] = attachDir[1];
- aDir[2] = attachDir[2];
- aAxle[0] = -attachAxle[0];//someone reverse some conventions inside Bullet (axle winding)
- aAxle[1] = -attachAxle[1];
- aAxle[2] = -attachAxle[2];
-
- printf("attempt for addWheel: suspensionRestLength%f wheelRadius %f, hasSteering:%d\n",suspensionRestLength,wheelRadius,hasSteering);
- m_vehicle->AddWheel(motionState,aPos,aDir,aAxle,suspensionRestLength,wheelRadius,hasSteering);
- }
+
+ PHY_IMotionState* motionState = new KX_MotionState(gameOb->GetSGNode());
+
+ MT_Vector3 attachPos,attachDir,attachAxle;
+ PyVecTo(pylistPos,attachPos);
+ PyVecTo(pylistDir,attachDir);
+ PyVecTo(pylistAxleDir,attachAxle);
+ PHY__Vector3 aPos,aDir,aAxle;
+ aPos[0] = attachPos[0];
+ aPos[1] = attachPos[1];
+ aPos[2] = attachPos[2];
+ aDir[0] = attachDir[0];
+ aDir[1] = attachDir[1];
+ aDir[2] = attachDir[2];
+ aAxle[0] = -attachAxle[0];//someone reverse some conventions inside Bullet (axle winding)
+ aAxle[1] = -attachAxle[1];
+ aAxle[2] = -attachAxle[2];
+
+ printf("attempt for addWheel: suspensionRestLength%f wheelRadius %f, hasSteering:%d\n",suspensionRestLength,wheelRadius,hasSteering);
+ m_vehicle->AddWheel(motionState,aPos,aDir,aAxle,suspensionRestLength,wheelRadius,hasSteering);
} else {
return NULL;
}
- Py_RETURN_NONE;
+ Py_INCREF(Py_None);
+ return Py_None;
}
@@ -161,7 +157,8 @@ PyObject* KX_VehicleWrapper::PyApplyEngineForce(PyObject* self,
else {
return NULL;
}
- Py_RETURN_NONE;
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyObject* KX_VehicleWrapper::PySetTyreFriction(PyObject* self,
@@ -178,7 +175,8 @@ PyObject* KX_VehicleWrapper::PySetTyreFriction(PyObject* self,
else {
return NULL;
}
- Py_RETURN_NONE;
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyObject* KX_VehicleWrapper::PySetSuspensionStiffness(PyObject* self,
@@ -195,7 +193,8 @@ PyObject* KX_VehicleWrapper::PySetSuspensionStiffness(PyObject* self,
else {
return NULL;
}
- Py_RETURN_NONE;
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyObject* KX_VehicleWrapper::PySetSuspensionDamping(PyObject* self,
@@ -211,7 +210,8 @@ PyObject* KX_VehicleWrapper::PySetSuspensionDamping(PyObject* self,
} else {
return NULL;
}
- Py_RETURN_NONE;
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyObject* KX_VehicleWrapper::PySetSuspensionCompression(PyObject* self,
@@ -227,7 +227,8 @@ PyObject* KX_VehicleWrapper::PySetSuspensionCompression(PyObject* self,
} else {
return NULL;
}
- Py_RETURN_NONE;
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyObject* KX_VehicleWrapper::PySetRollInfluence(PyObject* self,
@@ -244,7 +245,8 @@ PyObject* KX_VehicleWrapper::PySetRollInfluence(PyObject* self,
else {
return NULL;
}
- Py_RETURN_NONE;
+ Py_INCREF(Py_None);
+ return Py_None;
}
@@ -262,7 +264,8 @@ PyObject* KX_VehicleWrapper::PyApplyBraking(PyObject* self,
else {
return NULL;
}
- Py_RETURN_NONE;
+ Py_INCREF(Py_None);
+ return Py_None;
}
@@ -282,7 +285,8 @@ PyObject* KX_VehicleWrapper::PySetSteeringValue(PyObject* self,
else {
return NULL;
}
- Py_RETURN_NONE;
+ Py_INCREF(Py_None);
+ return Py_None;
}
diff --git a/source/gameengine/Ketsji/KX_VertexProxy.cpp b/source/gameengine/Ketsji/KX_VertexProxy.cpp
index 25205714308..5cec65dff1c 100644
--- a/source/gameengine/Ketsji/KX_VertexProxy.cpp
+++ b/source/gameengine/Ketsji/KX_VertexProxy.cpp
@@ -82,7 +82,7 @@ PyObject*
KX_VertexProxy::_getattr(const STR_String& attr)
{
if (attr == "XYZ")
- return PyObjectFrom(MT_Vector3(m_vertex->getXYZ()));
+ return PyObjectFrom(MT_Vector3(m_vertex->getLocalXYZ()));
if (attr == "UV")
return PyObjectFrom(MT_Point2(m_vertex->getUV1()));
@@ -102,11 +102,11 @@ KX_VertexProxy::_getattr(const STR_String& attr)
// pos
if (attr == "x")
- return PyFloat_FromDouble(m_vertex->getXYZ()[0]);
+ return PyFloat_FromDouble(m_vertex->getLocalXYZ()[0]);
if (attr == "y")
- return PyFloat_FromDouble(m_vertex->getXYZ()[1]);
+ return PyFloat_FromDouble(m_vertex->getLocalXYZ()[1]);
if (attr == "z")
- return PyFloat_FromDouble(m_vertex->getXYZ()[2]);
+ return PyFloat_FromDouble(m_vertex->getLocalXYZ()[2]);
// Col
if (attr == "r")
@@ -184,7 +184,7 @@ int KX_VertexProxy::_setattr(const STR_String& attr, PyObject *pyvalue)
{
float val = PyFloat_AsDouble(pyvalue);
// pos
- MT_Point3 pos(m_vertex->getXYZ());
+ MT_Point3 pos(m_vertex->getLocalXYZ());
if (attr == "x")
{
pos.x() = val;
@@ -312,7 +312,7 @@ PyObject* KX_VertexProxy::PyGetXYZ(PyObject*,
PyObject*,
PyObject*)
{
- return PyObjectFrom(MT_Point3(m_vertex->getXYZ()));
+ return PyObjectFrom(MT_Point3(m_vertex->getLocalXYZ()));
}
PyObject* KX_VertexProxy::PySetXYZ(PyObject*,
@@ -426,7 +426,7 @@ PyObject* KX_VertexProxy::PySetUV2(PyObject*,
{
if (PyVecTo(list, vec))
{
- m_vertex->SetFlag((m_vertex->getFlag()|RAS_TexVert::SECOND_UV));
+ m_vertex->SetFlag((m_vertex->getFlag()|TV_2NDUV));
m_vertex->SetUnit(unit);
m_vertex->SetUV2(vec);
m_mesh->SetMeshModified(true);
diff --git a/source/gameengine/Ketsji/KX_VisibilityActuator.cpp b/source/gameengine/Ketsji/KX_VisibilityActuator.cpp
index 4b0db5a7953..b4693a7a7db 100644
--- a/source/gameengine/Ketsji/KX_VisibilityActuator.cpp
+++ b/source/gameengine/Ketsji/KX_VisibilityActuator.cpp
@@ -38,12 +38,10 @@
KX_VisibilityActuator::KX_VisibilityActuator(
SCA_IObject* gameobj,
bool visible,
- bool recursive,
PyTypeObject* T
)
: SCA_IActuator(gameobj,T),
- m_visible(visible),
- m_recursive(recursive)
+ m_visible(visible)
{
// intentionally empty
}
@@ -77,10 +75,10 @@ KX_VisibilityActuator::Update()
KX_GameObject *obj = (KX_GameObject*) GetParent();
- obj->SetVisible(m_visible, m_recursive);
- obj->UpdateBuckets(m_recursive);
+ obj->SetVisible(m_visible);
+ obj->MarkVisible();
- return false;
+ return true;
}
/* ------------------------------------------------------------------------- */
@@ -122,7 +120,7 @@ KX_VisibilityActuator::Parents[] = {
PyMethodDef
KX_VisibilityActuator::Methods[] = {
{"set", (PyCFunction) KX_VisibilityActuator::sPySetVisible,
- METH_VARARGS, (PY_METHODCHAR)SetVisible_doc},
+ METH_VARARGS, SetVisible_doc},
{NULL,NULL} //Sentinel
};
@@ -137,7 +135,7 @@ KX_VisibilityActuator::_getattr(
/* set visibility ---------------------------------------------------------- */
-const char
+char
KX_VisibilityActuator::SetVisible_doc[] =
"setVisible(visible?)\n"
"\t - visible? : Make the object visible? (KX_TRUE, KX_FALSE)"
diff --git a/source/gameengine/Ketsji/KX_VisibilityActuator.h b/source/gameengine/Ketsji/KX_VisibilityActuator.h
index d1b85ab998c..9b4753033fb 100644
--- a/source/gameengine/Ketsji/KX_VisibilityActuator.h
+++ b/source/gameengine/Ketsji/KX_VisibilityActuator.h
@@ -39,14 +39,12 @@ class KX_VisibilityActuator : public SCA_IActuator
/** Make visible? */
bool m_visible;
- bool m_recursive;
public:
KX_VisibilityActuator(
SCA_IObject* gameobj,
bool visible,
- bool recursive,
PyTypeObject* T=&Type
);
diff --git a/source/gameengine/Ketsji/Makefile b/source/gameengine/Ketsji/Makefile
index 0b48ad8b8c3..47a4855b00c 100644
--- a/source/gameengine/Ketsji/Makefile
+++ b/source/gameengine/Ketsji/Makefile
@@ -35,13 +35,10 @@ include nan_compile.mk
CCFLAGS += $(LEVEL_1_CPP_WARNINGS)
-CPPFLAGS += $(NAN_SDLCFLAGS)
CPPFLAGS += $(OGL_CPPFLAGS)
CPPFLAGS += -I$(NAN_GLEW)/include
CPPFLAGS += -I$(OPENGL_HEADERS)
-CPPFLAGS += -I$(NAN_PYTHON)/include/python$(NAN_PYTHON_VERSION)
-CPPFLAGS += -I../../blender/python
-CPPFLAGS += -I../../blender/python/api2_2x
+CPPFLAGS += -I$(NAN_PYTHON)/include/python$(NAN_PYTHON_VERSION) -I../../blender/python
CPPFLAGS += -I$(NAN_STRING)/include
CPPFLAGS += -I$(NAN_SOUNDSYSTEM)/include
CPPFLAGS += -I$(NAN_FUZZICS)/include -I$(NAN_SUMO) -I$(NAN_MOTO)/include
@@ -64,9 +61,13 @@ CPPFLAGS += -I../../blender/blenlib
CPPFLAGS += -I../../blender/include
CPPFLAGS += -I../../blender/makesdna
CPPFLAGS += -I../../blender/imbuf
-CPPFLAGS += -I../../blender/gpu
CPPFLAGS += -I$(NAN_GUARDEDALLOC)/include
+ifeq ($(WITH_BF_GLEXT),true)
+ CPPFLAGS += -DWITH_GLEXT
+endif
+
+
###########################
SOURCEDIR = source/gameengine/Ketsji
diff --git a/source/gameengine/Ketsji/SConscript b/source/gameengine/Ketsji/SConscript
index f5c620b583f..f6f744b199a 100644
--- a/source/gameengine/Ketsji/SConscript
+++ b/source/gameengine/Ketsji/SConscript
@@ -32,19 +32,20 @@ incs += ' #source/gameengine/SceneGraph #source/gameengine/Physics/common #sourc
incs += ' #source/gameengine/Physics/BlOde #source/gameengine/Physics/Dummy'
incs += ' #source/gameengine/Physics/Sumo #source/gameengine/Physics/Sumo/include'
incs += ' #source/gameengine/Physics/Sumo/Fuzzics/include #source/gameengine/Network/LoopBackNetwork'
-incs += ' #source/blender/misc #source/blender/blenloader #extern/glew/include #source/blender/gpu'
+incs += ' #source/blender/misc #source/blender/blenloader #extern/glew/include'
cflags = []
if env['OURPLATFORM'] == 'win32-vc':
cflags.append('/GR')
cflags.append('/Ox')
+if env['WITH_BF_GLEXT'] == 1:
+ env['CPPFLAGS'].append('-DWITH_GLEXT')
+
incs += ' ' + env['BF_SOLID_INC']
incs += ' ' + env['BF_PYTHON_INC']
+incs += ' ' + env['BF_SDL_INC']
incs += ' ' + env['BF_BULLET_INC']
incs += ' ' + env['BF_OPENGL_INC']
-if env['WITH_BF_SDL']:
- incs += ' ' + env['BF_SDL_INC']
-
env.BlenderLib ( 'bf_ketsji', sources, Split(incs), [], libtype=['game','player'], priority=[25, 72], compileflags = cflags )
diff --git a/source/gameengine/Makefile b/source/gameengine/Makefile
index 51bc0f7d39f..1d3bc8c2058 100644
--- a/source/gameengine/Makefile
+++ b/source/gameengine/Makefile
@@ -35,7 +35,7 @@ DIR = $(OCGDIR)/gameengine
DIRS = BlenderRoutines
DIRS += Converter
DIRS += Expressions GameLogic Ketsji Rasterizer SceneGraph
-DIRS += Network Physics VideoTexture
+DIRS += Network Physics
ifeq ($(WITH_BF_BLENDERGAMEENGINE),true)
DIRS += GamePlayer
diff --git a/source/gameengine/Physics/BlOde/OdePhysicsController.h b/source/gameengine/Physics/BlOde/OdePhysicsController.h
index 925f5b6686a..d3eb443ed3a 100644
--- a/source/gameengine/Physics/BlOde/OdePhysicsController.h
+++ b/source/gameengine/Physics/BlOde/OdePhysicsController.h
@@ -111,8 +111,6 @@ public:
virtual void calcXform(){}
virtual void SetMargin(float margin) {}
virtual float GetMargin() const {return 0.f;}
- virtual float GetRadius() const {return 0.f;}
- virtual void SetRadius(float margin) {}
// clientinfo for raycasts for example
virtual void* getNewClientInfo() { return m_clientInfo;}
diff --git a/source/gameengine/Physics/BlOde/OdePhysicsEnvironment.cpp b/source/gameengine/Physics/BlOde/OdePhysicsEnvironment.cpp
index 2e8ee31058f..a04560aaf09 100644
--- a/source/gameengine/Physics/BlOde/OdePhysicsEnvironment.cpp
+++ b/source/gameengine/Physics/BlOde/OdePhysicsEnvironment.cpp
@@ -198,7 +198,7 @@ int ODEPhysicsEnvironment::createConstraint(class PHY_IPhysicsController* ctrl
}
-void ODEPhysicsEnvironment::removeConstraint(void *constraintid)
+void ODEPhysicsEnvironment::removeConstraint(int constraintid)
{
if (constraintid)
{
@@ -206,7 +206,8 @@ void ODEPhysicsEnvironment::removeConstraint(void *constraintid)
}
}
-PHY_IPhysicsController* ODEPhysicsEnvironment::rayTest(PHY_IRayCastFilterCallback &filterCallback,float fromX,float fromY,float fromZ, float toX,float toY,float toZ)
+PHY_IPhysicsController* ODEPhysicsEnvironment::rayTest(PHY_IPhysicsController* ignoreClient,float fromX,float fromY,float fromZ, float toX,float toY,float toZ,
+ float& hitX,float& hitY,float& hitZ,float& normalX,float& normalY,float& normalZ)
{
//m_OdeWorld
diff --git a/source/gameengine/Physics/BlOde/OdePhysicsEnvironment.h b/source/gameengine/Physics/BlOde/OdePhysicsEnvironment.h
index dcc87d614c0..7c61902f8e2 100644
--- a/source/gameengine/Physics/BlOde/OdePhysicsEnvironment.h
+++ b/source/gameengine/Physics/BlOde/OdePhysicsEnvironment.h
@@ -54,7 +54,8 @@ public:
float axisX,float axisY,float axisZ);
virtual void removeConstraint(void * constraintid);
- virtual PHY_IPhysicsController* rayTest(PHY_IRayCastFilterCallback &filterCallback,float fromX,float fromY,float fromZ, float toX,float toY,float toZ);
+ virtual PHY_IPhysicsController* rayTest(PHY_IPhysicsController* ignoreClient,float fromX,float fromY,float fromZ, float toX,float toY,float toZ,
+ float& hitX,float& hitY,float& hitZ,float& normalX,float& normalY,float& normalZ);
//gamelogic callbacks
diff --git a/source/gameengine/Physics/Bullet/CMakeLists.txt b/source/gameengine/Physics/Bullet/CMakeLists.txt
index 6c733786caf..b610fd1bbb0 100644
--- a/source/gameengine/Physics/Bullet/CMakeLists.txt
+++ b/source/gameengine/Physics/Bullet/CMakeLists.txt
@@ -30,10 +30,6 @@ SET(INC
.
../common
../../../../extern/bullet2/src
- ../../../../intern/moto/include
- ../../../kernel/gen_system
- ../../../../intern/string
- ../../Rasterizer
)
BLENDERLIB(bf_bullet "${SRC}" "${INC}")
diff --git a/source/gameengine/Physics/Bullet/CcdPhysicsController.cpp b/source/gameengine/Physics/Bullet/CcdPhysicsController.cpp
index c9c30c1b450..b872fae6138 100644
--- a/source/gameengine/Physics/Bullet/CcdPhysicsController.cpp
+++ b/source/gameengine/Physics/Bullet/CcdPhysicsController.cpp
@@ -15,18 +15,10 @@ subject to the following restrictions:
#include "CcdPhysicsController.h"
#include "btBulletDynamicsCommon.h"
-#include "BulletCollision/CollisionShapes/btScaledBvhTriangleMeshShape.h"
+
#include "PHY_IMotionState.h"
#include "CcdPhysicsEnvironment.h"
-#include "RAS_MeshObject.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"
class BP_Proxy;
@@ -48,36 +40,22 @@ btVector3 startVel(0,0,0);//-10000);
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_bulletMotionState = 0;
CreateRigidbody();
-///???
-#ifdef WIN32
- if (GetRigidBody() && !GetRigidBody()->isStaticObject())
- GetRigidBody()->setLinearVelocity(startVel);
-#endif
+
+ #ifdef WIN32
+ if (m_body->getInvMass())
+ m_body->setLinearVelocity(startVel);
+ #endif
}
@@ -129,351 +107,20 @@ public:
};
-btRigidBody* CcdPhysicsController::GetRigidBody()
-{
- return btRigidBody::upcast(m_object);
-}
-btCollisionObject* CcdPhysicsController::GetCollisionObject()
-{
- return m_object;
-}
-btSoftBody* CcdPhysicsController::GetSoftBody()
-{
- return btSoftBody::upcast(m_object);
-}
-
-#include "BulletSoftBody/btSoftBodyHelpers.h"
-
-
-
void CcdPhysicsController::CreateRigidbody()
{
- //btTransform trans = GetTransformFromMotionState(m_MotionState);
- m_bulletMotionState = new BlenderBulletMotionState(m_MotionState);
-
- ///either create a btCollisionObject, btRigidBody or btSoftBody
-
- //create a collision object
-
- 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))
- {
- 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;
-
-
- int nodecount = 0;
-
- int numtriangles = 1;
-
- btVector3 p(0,0,0);// = getOrigin();
- btScalar h = 1.f;
-
- btSoftRigidDynamicsWorld* softDynaWorld = (btSoftRigidDynamicsWorld*)m_cci.m_physicsEnv->getDynamicsWorld();
-
- PHY__Vector3 grav;
- grav[0] = softDynaWorld->getGravity().getX();
- grav[1] = softDynaWorld->getGravity().getY();
- grav[2] = softDynaWorld->getGravity().getZ();
- softDynaWorld->getWorldInfo().m_gravity.setValue(grav[0],grav[1],grav[2]); //??
-
-
- //btSoftBody* psb=btSoftBodyHelpers::CreateRope(sbi, btVector3(-10,0,i*0.25),btVector3(10,0,i*0.25), 16,1+2);
-
- btSoftBody* psb = 0;
-
- if (m_cci.m_collisionShape->getShapeType() == CONVEX_HULL_SHAPE_PROXYTYPE)
- {
- btConvexHullShape* convexHull = (btConvexHullShape* )m_cci.m_collisionShape;
-
- //psb = btSoftBodyHelpers::CreateFromConvexHull(sbi,&transformedVertices[0],convexHull->getNumPoints());
-
- {
- int nvertices = convexHull->getNumPoints();
- const btVector3* vertices = convexHull->getPoints();
- btSoftBodyWorldInfo& worldInfo = softDynaWorld->getWorldInfo();
-
- 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 int idx[]={ 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
- {
-
- btSoftBodyWorldInfo& sbi= softDynaWorld->getWorldInfo();
-
- 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;
- PHY_ScalarType vertexType;
- int numverts;
- int vertexstride;
- unsigned char* indexbase;
- int indexstride;
- int numtris;
- PHY_ScalarType indexType;
- trimeshshape->getMeshInterface()->getLockedVertexIndexBase(&vertexBase,numverts,vertexType,vertexstride,&indexbase,indexstride,numtris,indexType);
-
- psb = btSoftBodyHelpers::CreateFromTriMesh(sbi,(const btScalar*)vertexBase,(const int*)indexbase,numtris);
- }
- } else
- {
- btBvhTriangleMeshShape* trimeshshape = (btBvhTriangleMeshShape*) 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;
- int numtris;
- PHY_ScalarType indexType;
- trimeshshape->getMeshInterface()->getLockedVertexIndexBase(&vertexBase,numverts,vertexType,vertexstride,&indexbase,indexstride,numtris,indexType);
-
- psb = btSoftBodyHelpers::CreateFromTriMesh(sbi,(const btScalar*)vertexBase,(const int*)indexbase,numtris);
- }
-
-
- //psb = btSoftBodyHelpers::CreateFromTriMesh(sbi,&pts[0].getX(),triangles,numtriangles);
- }
-
- }
-
-
-
- m_object = psb;
-
- //psb->m_cfg.collisions = btSoftBody::fCollision::SDF_RS;//btSoftBody::fCollision::CL_SS+ btSoftBody::fCollision::CL_RS;
-
- //psb->m_cfg.collisions = btSoftBody::fCollision::SDF_RS + btSoftBody::fCollision::VF_SS;//CL_SS;
-
-
- //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] */
+ btTransform trans = GetTransformFromMotionState(m_MotionState);
- 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->activate();
-// psb->setActivationState(1);
-// psb->setDeactivationTime(1.f);
-
- //psb->m_materials[0]->m_kLST = 0.1+(i/(btScalar)(n-1))*0.9;
- 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++)
- {
- // 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 = 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;
-
-
-
-
-
-
-// m_object->setCollisionShape(rbci.m_collisionShape);
- btTransform startTrans;
-
- if (rbci.m_motionState)
- {
- rbci.m_motionState->getWorldTransform(startTrans);
- } else
- {
- startTrans = rbci.m_startWorldTransform;
- }
- //startTrans.setIdentity();
-
- //m_object->setWorldTransform(startTrans);
- //m_object->setInterpolationWorldTransform(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;
- GetSoftBody()->transform(startTrans);
- }
-
-// btVector3 wp = m_softBody->getWorldTransform().getOrigin();
-// MT_Point3 center(wp.getX(),wp.getY(),wp.getZ());
-// m_gameobj->NodeSetWorldPosition(center);
+ m_bulletMotionState = new BlenderBulletMotionState(m_MotionState);
+ m_body = new btRigidBody(m_cci.m_mass,
+ m_bulletMotionState,
+ m_cci.m_collisionShape,
+ m_cci.m_localInertiaTensor * m_cci.m_inertiaFactor,
+ m_cci.m_linearDamping,m_cci.m_angularDamping,
+ m_cci.m_friction,m_cci.m_restitution);
- } else
- {
- 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
//
@@ -485,39 +132,16 @@ void CcdPhysicsController::CreateRigidbody()
if ((m_cci.m_collisionFilterGroup & CcdConstructionInfo::SensorFilter) != 0)
{
// reset the flags that have been set so far
- GetCollisionObject()->setCollisionFlags(0);
+ m_body->setCollisionFlags(0);
}
- 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);
- }
- }
- if (m_object && m_cci.m_do_anisotropic)
- {
- m_object->setAnisotropicFriction(m_cci.m_anisotropicFriction);
- }
-
-}
+ m_body->setCollisionFlags(m_body->getCollisionFlags() | m_cci.m_collisionFlags);
+ m_body->setGravity( m_cci.m_gravity);
+ m_body->setDamping(m_cci.m_linearDamping, m_cci.m_angularDamping);
-static void DeleteBulletShape(btCollisionShape* shape)
-{
- if (shape->getShapeType() == TRIANGLE_MESH_SHAPE_PROXYTYPE)
+ if (!m_cci.m_bRigid)
{
- // shapes based on meshes use an interface that contains the vertices.
- btTriangleMeshShape* meshShape = static_cast<btTriangleMeshShape*>(shape);
- btStridingMeshInterface* meshInterface = meshShape->getMeshInterface();
- if (meshInterface)
- delete meshInterface;
+ m_body->setAngularFactor(0.f);
}
- delete shape;
}
CcdPhysicsController::~CcdPhysicsController()
@@ -530,28 +154,7 @@ CcdPhysicsController::~CcdPhysicsController()
delete m_MotionState;
if (m_bulletMotionState)
delete m_bulletMotionState;
- delete m_object;
-
- 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);
- }
- }
- DeleteBulletShape(m_collisionShape);
- }
- if (m_shapeInfo)
- {
- m_shapeInfo->Release();
- }
+ delete m_body;
}
@@ -562,26 +165,12 @@ bool CcdPhysicsController::SynchronizeMotionStates(float time)
{
//sync non-static to motionstate, and static from motionstate (todo: add kinematic etc.)
- btSoftBody* sb = GetSoftBody();
- if (sb)
+ if (!m_body->isStaticObject())
{
- 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 btVector3& worldPos = body->getCenterOfMassPosition();
+ const btVector3& worldPos = m_body->getCenterOfMassPosition();
m_MotionState->setWorldPosition(worldPos[0],worldPos[1],worldPos[2]);
- const btQuaternion& worldquat = body->getOrientation();
+ const btQuaternion& worldquat = m_body->getOrientation();
m_MotionState->setWorldOrientation(worldquat[0],worldquat[1],worldquat[2],worldquat[3]);
m_MotionState->calculateWorldTransformations();
@@ -600,7 +189,7 @@ bool CcdPhysicsController::SynchronizeMotionStates(float time)
btTransform oldTrans = m_body->getCenterOfMassTransform();
btTransform newTrans(worldquat,worldPos);
- SetCenterOfMassTransform(newTrans);
+ m_body->setCenterOfMassTransform(newTrans);
//need to keep track of previous position for friction effects...
m_MotionState->calculateWorldTransformations();
@@ -628,41 +217,13 @@ void CcdPhysicsController::WriteDynamicsToMotionState()
// controller replication
void CcdPhysicsController::PostProcessReplica(class PHY_IMotionState* motionstate,class PHY_IPhysicsController* parentctrl)
{
-
- m_softBodyTransformInitialized=false;
m_MotionState = motionstate;
m_registerCount = 0;
- m_collisionShape = NULL;
-
- // always create a new shape to avoid scaling bug
- if (m_shapeInfo)
- {
- m_shapeInfo->AddRef();
- m_collisionShape = m_shapeInfo->CreateBulletShape();
-
- 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);
- }
- }
+
- m_object = 0;
+ m_body = 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);
- }
- }
+
m_cci.m_physicsEnv->addCcdPhysicsController(this);
@@ -698,75 +259,40 @@ void CcdPhysicsController::PostProcessReplica(class PHY_IMotionState* motionsta
}
-
-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);
- }
- if (body)
- {
- body->setInterpolationLinearVelocity(body->getLinearVelocity());
- body->setInterpolationAngularVelocity(body->getAngularVelocity());
- body->updateInertiaTensor();
- }
- m_object->setWorldTransform(xform);
- }
- }
-}
-
// kinematic methods
void CcdPhysicsController::RelativeTranslate(float dlocX,float dlocY,float dlocZ,bool local)
{
- if (m_object)
+ if (m_body)
{
- m_object->activate(true);
- if (m_object->isStaticObject())
+ m_body->activate(true);
+ if (m_body->isStaticObject())
{
- m_object->setCollisionFlags(m_object->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT);
+ m_body->setCollisionFlags(m_body->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT);
}
- btRigidBody* body = GetRigidBody();
btVector3 dloc(dlocX,dlocY,dlocZ);
- btTransform xform = m_object->getWorldTransform();
-
+ btTransform xform = m_body->getCenterOfMassTransform();
+
if (local)
{
dloc = xform.getBasis()*dloc;
}
xform.setOrigin(xform.getOrigin() + dloc);
- SetCenterOfMassTransform(xform);
+ m_body->setCenterOfMassTransform(xform);
}
}
void CcdPhysicsController::RelativeRotate(const float rotval[9],bool local)
{
- if (m_object)
+ if (m_body)
{
- m_object->activate(true);
- if (m_object->isStaticObject())
+ m_body->activate(true);
+ if (m_body->isStaticObject())
{
- m_object->setCollisionFlags(m_object->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT);
+ m_body->setCollisionFlags(m_body->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT);
}
btMatrix3x3 drotmat( rotval[0],rotval[4],rotval[8],
@@ -777,15 +303,15 @@ void CcdPhysicsController::RelativeRotate(const float rotval[9],bool local)
btMatrix3x3 currentOrn;
GetWorldOrientation(currentOrn);
- btTransform xform = m_object->getWorldTransform();
-
+ btTransform xform = m_body->getCenterOfMassTransform();
+
xform.setBasis(xform.getBasis()*(local ?
drotmat : (currentOrn.inverse() * drotmat * currentOrn)));
- SetCenterOfMassTransform(xform);
+ m_body->setCenterOfMassTransform(xform);
}
-}
+}
void CcdPhysicsController::GetWorldOrientation(btMatrix3x3& mat)
{
@@ -797,7 +323,7 @@ void CcdPhysicsController::GetWorldOrientation(btMatrix3x3& mat)
void CcdPhysicsController::getOrientation(float &quatImag0,float &quatImag1,float &quatImag2,float &quatReal)
{
- btQuaternion q = m_object->getWorldTransform().getRotation();
+ btQuaternion q = m_body->getCenterOfMassTransform().getRotation();
quatImag0 = q[0];
quatImag1 = q[1];
quatImag2 = q[2];
@@ -805,72 +331,58 @@ void CcdPhysicsController::getOrientation(float &quatImag0,float &quatImag1,flo
}
void CcdPhysicsController::setOrientation(float quatImag0,float quatImag1,float quatImag2,float quatReal)
{
- if (m_object)
+ if (m_body)
{
- m_object->activate(true);
- if (m_object->isStaticObject())
+ m_body->activate(true);
+ if (m_body->isStaticObject())
{
- m_object->setCollisionFlags(m_object->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT);
+ m_body->setCollisionFlags(m_body->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT);
}
// not required
//m_MotionState->setWorldOrientation(quatImag0,quatImag1,quatImag2,quatReal);
- btTransform xform = m_object->getWorldTransform();
+ btTransform xform = m_body->getCenterOfMassTransform();
xform.setRotation(btQuaternion(quatImag0,quatImag1,quatImag2,quatReal));
- SetCenterOfMassTransform(xform);
+ m_body->setCenterOfMassTransform(xform);
// not required
//m_bulletMotionState->setWorldTransform(xform);
-
-
-
}
}
void CcdPhysicsController::setWorldOrientation(const btMatrix3x3& orn)
{
- if (m_object)
+ if (m_body)
{
- m_object->activate(true);
- if (m_object->isStaticObject())
+ m_body->activate(true);
+ if (m_body->isStaticObject())
{
- m_object->setCollisionFlags(m_object->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT);
+ m_body->setCollisionFlags(m_body->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT);
}
// not required
//m_MotionState->setWorldOrientation(quatImag0,quatImag1,quatImag2,quatReal);
- btTransform xform = m_object->getWorldTransform();
+ btTransform xform = m_body->getCenterOfMassTransform();
xform.setBasis(orn);
- SetCenterOfMassTransform(xform);
+ m_body->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(float posX,float posY,float posZ)
{
- if (m_object)
+ if (m_body)
{
- m_object->activate(true);
- if (m_object->isStaticObject())
+ m_body->activate(true);
+ if (m_body->isStaticObject())
{
- m_object->setCollisionFlags(m_object->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT);
+ m_body->setCollisionFlags(m_body->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT);
}
// not required, this function is only used to update the physic controller
//m_MotionState->setWorldPosition(posX,posY,posZ);
- btTransform xform = m_object->getWorldTransform();
+ btTransform xform = m_body->getCenterOfMassTransform();
xform.setOrigin(btVector3(posX,posY,posZ));
- SetCenterOfMassTransform(xform);
- if (!m_softBodyTransformInitialized)
- m_softbodyStartTrans.setOrigin(xform.getOrigin());
+ m_body->setCenterOfMassTransform(xform);
// not required
//m_bulletMotionState->setWorldTransform(xform);
}
@@ -883,7 +395,7 @@ void CcdPhysicsController::resolveCombinedVelocities(float linvelX,float linvel
void CcdPhysicsController::getPosition(PHY__Vector3& pos) const
{
- const btTransform& xform = m_object->getWorldTransform();
+ const btTransform& xform = m_body->getCenterOfMassTransform();
pos[0] = xform.getOrigin().x();
pos[1] = xform.getOrigin().y();
pos[2] = xform.getOrigin().z();
@@ -897,16 +409,15 @@ void CcdPhysicsController::setScaling(float scaleX,float scaleY,float scaleZ)
{
m_cci.m_scaling = btVector3(scaleX,scaleY,scaleZ);
- if (m_object && m_object->getCollisionShape())
+ if (m_body && m_body->getCollisionShape())
{
- m_object->getCollisionShape()->setLocalScaling(m_cci.m_scaling);
+ m_body->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)
+ if (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);
+ m_body->getCollisionShape()->calculateLocalInertia(m_cci.m_mass, m_cci.m_localInertiaTensor);
+ m_body->setMassProps(m_cci.m_mass, m_cci.m_localInertiaTensor * m_cci.m_inertiaFactor);
}
}
@@ -917,23 +428,19 @@ void CcdPhysicsController::setScaling(float scaleX,float scaleY,float scaleZ)
void CcdPhysicsController::ApplyTorque(float torqueX,float torqueY,float torqueZ,bool local)
{
btVector3 torque(torqueX,torqueY,torqueZ);
- btTransform xform = m_object->getWorldTransform();
-
-
- if (m_object && torque.length2() > (SIMD_EPSILON*SIMD_EPSILON))
+ btTransform xform = m_body->getCenterOfMassTransform();
+ if (m_body && torque.length2() > (SIMD_EPSILON*SIMD_EPSILON))
{
- btRigidBody* body = GetRigidBody();
- m_object->activate();
- if (m_object->isStaticObject())
+ m_body->activate();
+ if (m_body->isStaticObject())
{
- m_object->setCollisionFlags(m_object->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT);
+ m_body->setCollisionFlags(m_body->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT);
}
if (local)
{
torque = xform.getBasis()*torque;
}
- if (body)
- body->applyTorque(torque);
+ m_body->applyTorque(torque);
}
}
@@ -941,57 +448,41 @@ void CcdPhysicsController::ApplyForce(float forceX,float forceY,float forceZ,bo
{
btVector3 force(forceX,forceY,forceZ);
-
- if (m_object && force.length2() > (SIMD_EPSILON*SIMD_EPSILON))
+ if (m_body && force.length2() > (SIMD_EPSILON*SIMD_EPSILON))
{
- m_object->activate();
- if (m_object->isStaticObject())
+ m_body->activate();
+ if (m_body->isStaticObject())
{
- m_object->setCollisionFlags(m_object->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT);
+ m_body->setCollisionFlags(m_body->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT);
}
-
{
- btTransform xform = m_object->getWorldTransform();
-
+ btTransform xform = m_body->getCenterOfMassTransform();
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);
- }
}
+ m_body->applyCentralForce(force);
}
}
void CcdPhysicsController::SetAngularVelocity(float ang_velX,float ang_velY,float ang_velZ,bool local)
{
btVector3 angvel(ang_velX,ang_velY,ang_velZ);
- if (m_object && angvel.length2() > (SIMD_EPSILON*SIMD_EPSILON))
+ if (m_body && angvel.length2() > (SIMD_EPSILON*SIMD_EPSILON))
{
- m_object->activate(true);
- if (m_object->isStaticObject())
+ m_body->activate(true);
+ if (m_body->isStaticObject())
{
- m_object->setCollisionFlags(m_object->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT);
- } else
+ m_body->setCollisionFlags(m_body->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT);
+ }
{
- btTransform xform = m_object->getWorldTransform();
+ btTransform xform = m_body->getCenterOfMassTransform();
if (local)
{
angvel = xform.getBasis()*angvel;
}
- btRigidBody* body = GetRigidBody();
- if (body)
- body->setAngularVelocity(angvel);
-
}
+ m_body->setAngularVelocity(angvel);
}
}
@@ -999,53 +490,39 @@ void CcdPhysicsController::SetLinearVelocity(float lin_velX,float lin_velY,floa
{
btVector3 linVel(lin_velX,lin_velY,lin_velZ);
- if (m_object/* && linVel.length2() > (SIMD_EPSILON*SIMD_EPSILON)*/)
+ if (m_body && linVel.length2() > (SIMD_EPSILON*SIMD_EPSILON))
{
- m_object->activate(true);
- if (m_object->isStaticObject())
+ m_body->activate(true);
+ if (m_body->isStaticObject())
{
- m_object->setCollisionFlags(m_object->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT);
- return;
+ m_body->setCollisionFlags(m_body->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT);
}
-
- btSoftBody* soft = GetSoftBody();
- if (soft)
- {
- if (local)
- {
- linVel = m_softbodyStartTrans.getBasis()*linVel;
- }
- soft->setVelocity(linVel);
- } else
+
{
- btTransform xform = m_object->getWorldTransform();
+ btTransform xform = m_body->getCenterOfMassTransform();
if (local)
{
linVel = xform.getBasis()*linVel;
}
- btRigidBody* body = GetRigidBody();
- if (body)
- body->setLinearVelocity(linVel);
}
+ m_body->setLinearVelocity(linVel);
}
}
void CcdPhysicsController::applyImpulse(float attachX,float attachY,float attachZ, float impulseX,float impulseY,float impulseZ)
{
btVector3 impulse(impulseX,impulseY,impulseZ);
- if (m_object && impulse.length2() > (SIMD_EPSILON*SIMD_EPSILON))
+ if (m_body && impulse.length2() > (SIMD_EPSILON*SIMD_EPSILON))
{
- m_object->activate();
- if (m_object->isStaticObject())
+ m_body->activate();
+ if (m_body->isStaticObject())
{
- m_object->setCollisionFlags(m_object->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT);
+ m_body->setCollisionFlags(m_body->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT);
}
btVector3 pos(attachX,attachY,attachZ);
- btRigidBody* body = GetRigidBody();
- if (body)
- body->applyImpulse(impulse,pos);
-
+
+ m_body->applyImpulse(impulse,pos);
}
}
@@ -1055,55 +532,29 @@ void CcdPhysicsController::SetActive(bool active)
// reading out information from physics
void CcdPhysicsController::GetLinearVelocity(float& linvX,float& linvY,float& linvZ)
{
- btRigidBody* body = GetRigidBody();
- if (body)
- {
- const btVector3& linvel = body->getLinearVelocity();
- linvX = linvel.x();
- linvY = linvel.y();
- linvZ = linvel.z();
- } else
- {
- linvX = 0.f;
- linvY = 0.f;
- linvZ = 0.f;
- }
+ const btVector3& linvel = this->m_body->getLinearVelocity();
+ linvX = linvel.x();
+ linvY = linvel.y();
+ linvZ = linvel.z();
}
void CcdPhysicsController::GetAngularVelocity(float& angVelX,float& angVelY,float& angVelZ)
{
- btRigidBody* body = GetRigidBody();
- if (body)
- {
- const btVector3& angvel= body->getAngularVelocity();
- angVelX = angvel.x();
- angVelY = angvel.y();
- angVelZ = angvel.z();
- } else
- {
- angVelX = 0.f;
- angVelY = 0.f;
- angVelZ = 0.f;
- }
+ const btVector3& angvel= m_body->getAngularVelocity();
+ angVelX = angvel.x();
+ angVelY = angvel.y();
+ angVelZ = angvel.z();
}
void CcdPhysicsController::GetVelocity(const float posX,const float posY,const float posZ,float& linvX,float& linvY,float& linvZ)
{
btVector3 pos(posX,posY,posZ);
- btRigidBody* body = GetRigidBody();
- if (body)
- {
- btVector3 linvel = body->getVelocityInLocalPoint(pos);
- linvX = linvel.x();
- linvY = linvel.y();
- linvZ = linvel.z();
- } else
- {
- linvX = 0.f;
- linvY = 0.f;
- linvZ = 0.f;
- }
+ btVector3 rel_pos = pos-m_body->getCenterOfMassPosition();
+ btVector3 linvel = m_body->getVelocityInLocalPoint(rel_pos);
+ linvX = linvel.x();
+ linvY = linvel.y();
+ linvZ = linvel.z();
}
void CcdPhysicsController::getReactionForce(float& forceX,float& forceY,float& forceZ)
{
@@ -1114,15 +565,11 @@ void CcdPhysicsController::setRigidBody(bool rigid)
{
if (!rigid)
{
- btRigidBody* body = GetRigidBody();
- if (body)
- {
- //fake it for now
- btVector3 inertia = body->getInvInertiaDiagLocal();
- inertia[1] = 0.f;
- body->setInvInertiaDiagLocal(inertia);
- body->updateInertiaTensor();
- }
+ //fake it for now
+ btVector3 inertia = m_body->getInvInertiaDiagLocal();
+ inertia[1] = 0.f;
+ m_body->setInvInertiaDiagLocal(inertia);
+ m_body->updateInertiaTensor();
}
}
@@ -1139,52 +586,40 @@ void CcdPhysicsController::setNewClientInfo(void* clientinfo)
void CcdPhysicsController::UpdateDeactivation(float timeStep)
{
- btRigidBody* body = GetRigidBody();
- if (body)
- {
- body->updateDeactivation( timeStep);
- }
+ m_body->updateDeactivation( timeStep);
}
bool CcdPhysicsController::wantsSleeping()
{
- btRigidBody* body = GetRigidBody();
- if (body)
- {
- return body->wantsSleeping();
- }
- //check it out
- return true;
+
+ return m_body->wantsSleeping();
}
PHY_IPhysicsController* CcdPhysicsController::GetReplica()
{
- // This is used only to replicate Near and Radar sensor controllers
- // The replication of object physics controller is done in KX_BulletPhysicsController::GetReplica()
+ //very experimental, shape sharing is not implemented yet.
+ //just support btSphereShape/ConeShape for now
+
CcdConstructionInfo cinfo = m_cci;
- if (m_shapeInfo)
- {
- // This situation does not normally happen
- cinfo.m_collisionShape = m_shapeInfo->CreateBulletShape();
- }
- else if (m_collisionShape)
+ if (cinfo.m_collisionShape)
{
- switch (m_collisionShape->getShapeType())
+ switch (cinfo.m_collisionShape->getShapeType())
{
case SPHERE_SHAPE_PROXYTYPE:
{
- btSphereShape* orgShape = (btSphereShape*)m_collisionShape;
+ btSphereShape* orgShape = (btSphereShape*)cinfo.m_collisionShape;
cinfo.m_collisionShape = new btSphereShape(*orgShape);
break;
}
- case CONE_SHAPE_PROXYTYPE:
+ case CONE_SHAPE_PROXYTYPE:
{
- btConeShape* orgShape = (btConeShape*)m_collisionShape;
+ btConeShape* orgShape = (btConeShape*)cinfo.m_collisionShape;
cinfo.m_collisionShape = new btConeShape(*orgShape);
break;
}
+
default:
{
return 0;
@@ -1193,7 +628,6 @@ PHY_IPhysicsController* CcdPhysicsController::GetReplica()
}
cinfo.m_MotionState = new DefaultMotionState();
- cinfo.m_shapeInfo = m_shapeInfo;
CcdPhysicsController* replica = new CcdPhysicsController(cinfo);
return replica;
@@ -1255,273 +689,3 @@ void DefaultMotionState::calculateWorldTransformations()
}
-// Shape constructor
-std::map<RAS_MeshObject*, CcdShapeConstructionInfo*> CcdShapeConstructionInfo::m_meshShapeMap;
-
-CcdShapeConstructionInfo* CcdShapeConstructionInfo::FindMesh(RAS_MeshObject* mesh, bool polytope)
-{
- if (polytope)
- // 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, bool polytope,bool useGimpact)
-{
- m_useGimpact = useGimpact;
-
- // assume no shape information
- // no support for dynamic change of shape yet
- assert(m_meshObject == NULL);
- m_shapeType = PHY_SHAPE_NONE;
- m_vertexArray.clear();
- m_polygonIndexArray.clear();
- m_meshObject = NULL;
-
- if (!meshobj)
- return false;
-
- // Mesh has no polygons!
- int numpolys = meshobj->NumPolygons();
- if (!numpolys)
- {
- return false;
- }
-
- // check that we have at least one colliding polygon
- int numvalidpolys = 0;
-
- for (int p=0; p<numpolys; p++)
- {
- RAS_Polygon* poly = meshobj->GetPolygon(p);
-
- // only add polygons that have the collisionflag set
- if (poly->IsCollider())
- {
- numvalidpolys++;
- break;
- }
- }
-
- // No collision polygons
- if (numvalidpolys < 1)
- return false;
-
- m_shapeType = (polytope) ? PHY_SHAPE_POLYTOPE : PHY_SHAPE_MESH;
-
- numvalidpolys = 0;
-
- for (int p2=0; p2<numpolys; p2++)
- {
- RAS_Polygon* poly = meshobj->GetPolygon(p2);
-
- // only add polygons that have the collisionflag set
- if (poly->IsCollider())
- {
- //Bullet can raycast any shape, so
- if (polytope)
- {
- for (int i=0;i<poly->VertexCount();i++)
- {
- const float* vtx = poly->GetVertex(i)->getXYZ();
- btPoint3 point(vtx[0],vtx[1],vtx[2]);
- //avoid duplicates (could better directly use vertex offsets, rather than a vertex compare)
- bool found = false;
- for (int j=0;j<m_vertexArray.size();j++)
- {
- if (m_vertexArray[j]==point)
- {
- found = true;
- break;
- }
- }
- if (!found)
- m_vertexArray.push_back(point);
-
- numvalidpolys++;
- }
- } else
- {
- {
- const float* vtx = poly->GetVertex(2)->getXYZ();
- btPoint3 vertex0(vtx[0],vtx[1],vtx[2]);
-
- vtx = poly->GetVertex(1)->getXYZ();
- btPoint3 vertex1(vtx[0],vtx[1],vtx[2]);
-
- vtx = poly->GetVertex(0)->getXYZ();
- btPoint3 vertex2(vtx[0],vtx[1],vtx[2]);
-
- m_vertexArray.push_back(vertex0);
- m_vertexArray.push_back(vertex1);
- m_vertexArray.push_back(vertex2);
- m_polygonIndexArray.push_back(p2);
- numvalidpolys++;
- }
- if (poly->VertexCount() == 4)
- {
- const float* vtx = poly->GetVertex(3)->getXYZ();
- btPoint3 vertex0(vtx[0],vtx[1],vtx[2]);
-
- vtx = poly->GetVertex(2)->getXYZ();
- btPoint3 vertex1(vtx[0],vtx[1],vtx[2]);
-
- vtx = poly->GetVertex(0)->getXYZ();
- btPoint3 vertex2(vtx[0],vtx[1],vtx[2]);
-
- m_vertexArray.push_back(vertex0);
- m_vertexArray.push_back(vertex1);
- m_vertexArray.push_back(vertex2);
- m_polygonIndexArray.push_back(p2);
- numvalidpolys++;
- }
- }
- }
- }
-
- if (!numvalidpolys)
- {
- // should not happen
- m_shapeType = PHY_SHAPE_NONE;
- return false;
- }
- m_meshObject = meshobj;
- if (!polytope)
- {
- // triangle shape can be shared, store the mesh object in the map
- m_meshShapeMap.insert(std::pair<RAS_MeshObject*,CcdShapeConstructionInfo*>(meshobj,this));
- }
- return true;
-}
-
-btCollisionShape* CcdShapeConstructionInfo::CreateBulletShape()
-{
- btCollisionShape* collisionShape = 0;
- btTriangleMeshShape* concaveShape = 0;
- btTriangleMesh* collisionMeshData = 0;
- btCompoundShape* compoundShape = 0;
- CcdShapeConstructionInfo* nextShapeInfo;
-
- switch (m_shapeType)
- {
- case PHY_SHAPE_NONE:
- break;
-
- case PHY_SHAPE_BOX:
- collisionShape = new btBoxShape(m_halfExtend);
- break;
-
- case PHY_SHAPE_SPHERE:
- collisionShape = new btSphereShape(m_radius);
- break;
-
- case PHY_SHAPE_CYLINDER:
- collisionShape = new btCylinderShapeZ(m_halfExtend);
- break;
-
- case PHY_SHAPE_CONE:
- collisionShape = new btConeShapeZ(m_radius, m_height);
- break;
-
- case PHY_SHAPE_POLYTOPE:
- collisionShape = new btConvexHullShape(&m_vertexArray.begin()->getX(), m_vertexArray.size());
- 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 (m_useGimpact)
- {
- collisionMeshData = new btTriangleMesh();
-
-
- // m_vertexArray is necessarily a multiple of 3
- for (std::vector<btPoint3>::iterator it=m_vertexArray.begin(); it != m_vertexArray.end(); )
- {
- collisionMeshData->addTriangle(*it++,*it++,*it++);
- }
- btGImpactMeshShape* gimpactShape = new btGImpactMeshShape(collisionMeshData);
-
- collisionShape = gimpactShape;
- gimpactShape->updateBound();
-
- } else
- {
- if (!m_unscaledShape)
- {
- collisionMeshData = new btTriangleMesh(true,false);
- collisionMeshData->m_weldingThreshold = m_weldingThreshold;
-
- // m_vertexArray is necessarily a multiple of 3
- for (std::vector<btPoint3>::iterator it=m_vertexArray.begin(); it != m_vertexArray.end(); )
- {
- collisionMeshData->addTriangle(*it++,*it++,*it++);
- }
- // this shape will be shared and not deleted until shapeInfo is deleted
- m_unscaledShape = new btBvhTriangleMeshShape( collisionMeshData, true );
- m_unscaledShape->recalcLocalAabb();
- }
- collisionShape = new btScaledBvhTriangleMeshShape(m_unscaledShape, btVector3(1.0f,1.0f,1.0f));
- }
- 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();
- if (collisionShape)
- {
- collisionShape->setLocalScaling((*sit)->m_childScale);
- compoundShape->addChildShape((*sit)->m_childTrans, collisionShape);
- }
- }
- collisionShape = compoundShape;
- }
- }
- return collisionShape;
-}
-
-void CcdShapeConstructionInfo::AddShape(CcdShapeConstructionInfo* shapeInfo)
-{
- m_shapeArray.push_back(shapeInfo);
-}
-
-CcdShapeConstructionInfo::~CcdShapeConstructionInfo()
-{
- for (std::vector<CcdShapeConstructionInfo*>::iterator sit = m_shapeArray.begin();
- sit != m_shapeArray.end();
- sit++)
- {
- (*sit)->Release();
- }
- m_shapeArray.clear();
- if (m_unscaledShape)
- {
- DeleteBulletShape(m_unscaledShape);
- }
- 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);
- }
- }
-}
-
-
diff --git a/source/gameengine/Physics/Bullet/CcdPhysicsController.h b/source/gameengine/Physics/Bullet/CcdPhysicsController.h
index 054ec91122a..448e5622eff 100644
--- a/source/gameengine/Physics/Bullet/CcdPhysicsController.h
+++ b/source/gameengine/Physics/Bullet/CcdPhysicsController.h
@@ -17,15 +17,11 @@ subject to the following restrictions:
#ifndef BULLET2_PHYSICSCONTROLLER_H
#define BULLET2_PHYSICSCONTROLLER_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 "LinearMath/btTransform.h"
#include "PHY_IMotionState.h"
@@ -35,119 +31,8 @@ extern float gAngularSleepingTreshold;
extern bool gDisableDeactivation;
class CcdPhysicsEnvironment;
class btMotionState;
-class RAS_MeshObject;
-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:
-
-
- static CcdShapeConstructionInfo* FindMesh(RAS_MeshObject* mesh, bool polytope);
-
- CcdShapeConstructionInfo() :
- m_shapeType(PHY_SHAPE_NONE),
- m_radius(1.0),
- m_height(1.0),
- m_halfExtend(0.f,0.f,0.f),
- m_childScale(1.0f,1.0f,1.0f),
- m_refCount(1),
- m_meshObject(NULL),
- m_unscaledShape(NULL),
- m_useGimpact(false),
- m_weldingThreshold(0.f)
- {
- m_childTrans.setIdentity();
- }
-
- ~CcdShapeConstructionInfo();
-
- CcdShapeConstructionInfo* AddRef()
- {
- m_refCount++;
- return this;
- }
-
- int Release()
- {
- if (--m_refCount > 0)
- return m_refCount;
- delete this;
- return 0;
- }
-
- void AddShape(CcdShapeConstructionInfo* shapeInfo);
-
- btTriangleMeshShape* GetMeshShape(void)
- {
- return m_unscaledShape;
- }
- CcdShapeConstructionInfo* GetChildShape(int i)
- {
- if (i < 0 || i >= m_shapeArray.size())
- return NULL;
-
- return m_shapeArray.at(i);
- }
- bool SetMesh(RAS_MeshObject* mesh, bool polytope,bool useGimpact);
- RAS_MeshObject* GetMesh(void)
- {
- return m_meshObject;
- }
-
- btCollisionShape* CreateBulletShape();
-
- // member variables
- PHY_ShapeType m_shapeType;
- btScalar m_radius;
- btScalar m_height;
- btVector3 m_halfExtend;
- btTransform m_childTrans;
- btVector3 m_childScale;
- std::vector<btPoint3> m_vertexArray; // Contains both vertex array for polytope shape and
- // triangle array for concave mesh shape.
- // 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.
-
- void setVertexWeldingThreshold(float threshold)
- {
- m_weldingThreshold = threshold;
- }
- float getVertexWeldingThreshold() const
- {
- return m_weldingThreshold;
- }
-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
- btBvhTriangleMeshShape* m_unscaledShape;// holds the shared unscale BVH mesh shape,
- // the actual shape is of type btScaledBvhTriangleMeshShape
- std::vector<CcdShapeConstructionInfo*> m_shapeArray; // for compound shapes
- bool m_useGimpact; //use gimpact for concave dynamic/moving collision detection
- float m_weldingThreshold; //welding closeby vertices together can improve softbody stability etc.
-};
struct CcdConstructionInfo
{
@@ -167,28 +52,21 @@ struct CcdConstructionInfo
CcdConstructionInfo()
- : m_localInertiaTensor(1.f, 1.f, 1.f),
- m_gravity(0,0,0),
+ : m_gravity(0,0,0),
m_scaling(1.f,1.f,1.f),
m_mass(0.f),
m_restitution(0.1f),
m_friction(0.5f),
m_linearDamping(0.1f),
m_angularDamping(0.1f),
- m_margin(0.06f),
- m_gamesoftFlag(0),
m_collisionFlags(0),
m_bRigid(false),
- m_bSoft(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_inertiaFactor(1.f)
{
}
@@ -200,50 +78,8 @@ struct CcdConstructionInfo
btScalar m_friction;
btScalar m_linearDamping;
btScalar m_angularDamping;
- btScalar m_margin;
-
- ////////////////////
- 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_bRigid;
- bool m_bSoft;
///optional use of collision group/mask:
///only collision with object goups that match the collision mask.
@@ -253,59 +89,29 @@ struct CcdConstructionInfo
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
-
};
class btRigidBody;
-class btCollisionObject;
-class btSoftBody;
+
///CcdPhysicsController is a physics object that supports continuous collision detection and time of impact based physics resolution.
class CcdPhysicsController : public PHY_IPhysicsController
{
-
- btCollisionObject* m_object;
-
-
+ btRigidBody* m_body;
class PHY_IMotionState* m_MotionState;
btMotionState* m_bulletMotionState;
- class btCollisionShape* m_collisionShape;
- class CcdShapeConstructionInfo* m_shapeInfo;
-
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;
-
void GetWorldOrientation(btMatrix3x3& mat);
void CreateRigidbody();
@@ -329,24 +135,11 @@ class CcdPhysicsController : public PHY_IPhysicsController
virtual ~CcdPhysicsController();
- CcdConstructionInfo& getConstructionInfo()
- {
- return m_cci;
- }
- const CcdConstructionInfo& getConstructionInfo() const
- {
- return m_cci;
- }
-
-
- btRigidBody* GetRigidBody();
- btCollisionObject* GetCollisionObject();
- btSoftBody* GetSoftBody();
- CcdShapeConstructionInfo* GetShapeInfo() { return m_shapeInfo; }
+ btRigidBody* GetRigidBody() { return m_body;}
btCollisionShape* GetCollisionShape() {
- return m_object->getCollisionShape();
+ return m_body->getCollisionShape();
}
////////////////////////////////////
// PHY_IPhysicsController interface
@@ -413,37 +206,14 @@ class CcdPhysicsController : public PHY_IPhysicsController
}
virtual void calcXform() {} ;
- virtual void SetMargin(float margin)
- {
- if (m_collisionShape)
- m_collisionShape->setMargin(btScalar(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;
- }
+ virtual void SetMargin(float margin) {};
+ virtual float GetMargin() const {return 0.f;};
bool wantsSleeping();
void UpdateDeactivation(float timeStep);
- void SetCenterOfMassTransform(btTransform& xform);
-
static btTransform GetTransformFromMotionState(PHY_IMotionState* motionState);
void setAabb(const btVector3& aabbMin,const btVector3& aabbMax);
@@ -463,23 +233,6 @@ class CcdPhysicsController : public PHY_IPhysicsController
{
return m_cci.m_physicsEnv;
}
-
- void setParentCtrl(CcdPhysicsController* parentCtrl)
- {
- m_parentCtrl = parentCtrl;
- }
-
- CcdPhysicsController* getParentCtrl()
- {
- return m_parentCtrl;
- }
-
- const CcdPhysicsController* getParentCtrl() const
- {
- return m_parentCtrl;
- }
-
-
};
diff --git a/source/gameengine/Physics/Bullet/CcdPhysicsEnvironment.cpp b/source/gameengine/Physics/Bullet/CcdPhysicsEnvironment.cpp
index 4fe35630784..dfbcf115fd7 100644
--- a/source/gameengine/Physics/Bullet/CcdPhysicsEnvironment.cpp
+++ b/source/gameengine/Physics/Bullet/CcdPhysicsEnvironment.cpp
@@ -23,9 +23,6 @@ subject to the following restrictions:
#include "btBulletDynamicsCommon.h"
#include "LinearMath/btIDebugDraw.h"
#include "BulletCollision/CollisionDispatch/btSimulationIslandManager.h"
-#include "BulletSoftBody/btSoftRigidDynamicsWorld.h"
-#include "BulletSoftBody/btSoftBodyRigidBodyCollisionConfiguration.h"
-#include "BulletCollision/Gimpact/btGImpactCollisionAlgorithm.h"
//profiling/timings
#include "LinearMath/btQuickprof.h"
@@ -33,7 +30,6 @@ subject to the following restrictions:
#include "PHY_IMotionState.h"
-#define CCD_CONSTRAINT_DISABLE_LINKED_COLLISION 0x80
bool useIslands = true;
@@ -57,7 +53,6 @@ void DrawRasterizerLine(const float* from,const float* to,int color);
#include <stdio.h>
-#include <string.h> // for memset
#ifdef NEW_BULLET_VEHICLE_SUPPORT
class WrapperVehicle : public PHY_IVehicle
@@ -334,29 +329,30 @@ m_filterCallback(NULL)
{
m_triggerCallbacks[i] = 0;
}
-
-// m_collisionConfiguration = new btDefaultCollisionConfiguration();
- m_collisionConfiguration = new btSoftBodyRigidBodyCollisionConfiguration();
-
if (!dispatcher)
{
- btCollisionDispatcher* disp = new btCollisionDispatcher(m_collisionConfiguration);
- dispatcher = disp;
- btGImpactCollisionAlgorithm::registerAlgorithm(disp);
+ dispatcher = new btCollisionDispatcher();
m_ownDispatcher = dispatcher;
}
- //m_broadphase = new btAxisSweep3(btVector3(-1000,-1000,-1000),btVector3(1000,1000,1000));
- //m_broadphase = new btSimpleBroadphase();
- m_broadphase = new btDbvtBroadphase();
+ if(!pairCache)
+ {
+
+ //todo: calculate/let user specify this world sizes
+ btVector3 worldMin(-10000,-10000,-10000);
+ btVector3 worldMax(10000,10000,10000);
+
+ pairCache = new btAxisSweep3(worldMin,worldMax);
+ // remember that this was allocated by us so that we can release it
+ m_ownPairCache = pairCache;
+ //broadphase = new btSimpleBroadphase();
+ }
m_filterCallback = new CcdOverlapFilterCallBack(this);
- m_broadphase->getOverlappingPairCache()->setOverlapFilterCallback(m_filterCallback);
+ pairCache->setOverlapFilterCallback(m_filterCallback);
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 = new btDiscreteDynamicsWorld(dispatcher,pairCache,m_solver);
m_debugDrawer = 0;
m_gravity = btVector3(0.f,-10.f,0.f);
m_dynamicsWorld->setGravity(m_gravity);
@@ -367,42 +363,24 @@ m_filterCallback(NULL)
void CcdPhysicsEnvironment::addCcdPhysicsController(CcdPhysicsController* ctrl)
{
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->setUserPointer(ctrl);
+ body->setGravity( m_gravity );
m_controllers.insert(ctrl);
- 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
+ //use explicit group/filter for finer control over collision in bullet => near/radar sensor
+ m_dynamicsWorld->addRigidBody(body, ctrl->GetCollisionFilterGroup(), ctrl->GetCollisionFilterMask());
+ if (body->isStaticOrKinematicObject())
{
- if (ctrl->GetSoftBody())
- {
- btSoftBody* softBody = ctrl->GetSoftBody();
- m_dynamicsWorld->addSoftBody(softBody);
- } else
- {
- if (obj->getCollisionShape())
- {
- m_dynamicsWorld->addCollisionObject(obj,ctrl->GetCollisionFilterGroup(), ctrl->GetCollisionFilterMask());
- }
- }
- }
- if (obj->isStaticOrKinematicObject())
- {
- obj->setActivationState(ISLAND_SLEEPING);
+ body->setActivationState(ISLAND_SLEEPING);
}
//CollisionObject(body,ctrl->GetCollisionFilterGroup(),ctrl->GetCollisionFilterMask());
- assert(obj->getBroadphaseHandle());
+ assert(body->getBroadphaseHandle());
btBroadphaseInterface* scene = getBroadphase();
@@ -411,7 +389,7 @@ void CcdPhysicsEnvironment::addCcdPhysicsController(CcdPhysicsController* ctrl)
assert(shapeinterface);
- const btTransform& t = ctrl->GetCollisionObject()->getWorldTransform();
+ const btTransform& t = ctrl->GetRigidBody()->getCenterOfMassTransform();
btPoint3 minAabb,maxAabb;
@@ -423,59 +401,42 @@ void CcdPhysicsEnvironment::addCcdPhysicsController(CcdPhysicsController* ctrl)
//extent it with the motion
- if (body)
- {
- btVector3 linMotion = body->getLinearVelocity()*timeStep;
-
- float maxAabbx = maxAabb.getX();
- float maxAabby = maxAabb.getY();
- float maxAabbz = maxAabb.getZ();
- float minAabbx = minAabb.getX();
- float minAabby = minAabb.getY();
- float minAabbz = minAabb.getZ();
-
- if (linMotion.x() > 0.f)
- maxAabbx += linMotion.x();
- else
- minAabbx += linMotion.x();
- if (linMotion.y() > 0.f)
- maxAabby += linMotion.y();
- else
- minAabby += linMotion.y();
- if (linMotion.z() > 0.f)
- maxAabbz += linMotion.z();
- else
- minAabbz += linMotion.z();
-
-
- minAabb = btVector3(minAabbx,minAabby,minAabbz);
- maxAabb = btVector3(maxAabbx,maxAabby,maxAabbz);
- }
+ btVector3 linMotion = body->getLinearVelocity()*timeStep;
+ float maxAabbx = maxAabb.getX();
+ float maxAabby = maxAabb.getY();
+ float maxAabbz = maxAabb.getZ();
+ float minAabbx = minAabb.getX();
+ float minAabby = minAabb.getY();
+ float minAabbz = minAabb.getZ();
+ if (linMotion.x() > 0.f)
+ maxAabbx += linMotion.x();
+ else
+ minAabbx += linMotion.x();
+ if (linMotion.y() > 0.f)
+ maxAabby += linMotion.y();
+ else
+ minAabby += linMotion.y();
+ if (linMotion.z() > 0.f)
+ maxAabbz += linMotion.z();
+ else
+ minAabbz += linMotion.z();
-}
-
+ minAabb = btVector3(minAabbx,minAabby,minAabbz);
+ maxAabb = btVector3(maxAabbx,maxAabby,maxAabbz);
+
+
+
+
+}
void CcdPhysicsEnvironment::removeCcdPhysicsController(CcdPhysicsController* ctrl)
{
//also remove constraint
- btRigidBody* body = ctrl->GetRigidBody();
- if (body)
- {
- m_dynamicsWorld->removeRigidBody(ctrl->GetRigidBody());
- } else
- {
- //if a softbody
- if (ctrl->GetSoftBody())
- {
- m_dynamicsWorld->removeSoftBody(ctrl->GetSoftBody());
- } else
- {
- m_dynamicsWorld->removeCollisionObject(ctrl->GetCollisionObject());
- }
- }
+
+ m_dynamicsWorld->removeRigidBody(ctrl->GetRigidBody());
m_controllers.erase(ctrl);
if (ctrl->m_registerCount != 0)
@@ -490,20 +451,13 @@ void CcdPhysicsEnvironment::updateCcdPhysicsController(CcdPhysicsController* ctr
// this function is used when the collisionning group of a controller is changed
// remove and add the collistioning object
btRigidBody* body = ctrl->GetRigidBody();
- btCollisionObject* obj = ctrl->GetCollisionObject();
- if (obj)
- {
- btVector3 inertia(0.0,0.0,0.0);
- m_dynamicsWorld->removeCollisionObject(obj);
- obj->setCollisionFlags(newCollisionFlags);
- if (body)
- {
- if (newMass)
- body->getCollisionShape()->calculateLocalInertia(newMass, inertia);
- body->setMassProps(newMass, inertia);
- }
- m_dynamicsWorld->addCollisionObject(obj, newCollisionGroup, newCollisionMask);
- }
+ btVector3 inertia;
+
+ m_dynamicsWorld->removeCollisionObject(body);
+ body->setCollisionFlags(newCollisionFlags);
+ body->getCollisionShape()->calculateLocalInertia(newMass, inertia);
+ body->setMassProps(newMass, inertia);
+ m_dynamicsWorld->addCollisionObject(body, 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;
@@ -515,9 +469,9 @@ void CcdPhysicsEnvironment::enableCcdPhysicsController(CcdPhysicsController* ctr
{
if (m_controllers.insert(ctrl).second)
{
- btCollisionObject* obj = ctrl->GetCollisionObject();
- obj->setUserPointer(ctrl);
- m_dynamicsWorld->addCollisionObject(obj,
+ btRigidBody* body = ctrl->GetRigidBody();
+ body->setUserPointer(ctrl);
+ m_dynamicsWorld->addCollisionObject(body,
ctrl->GetCollisionFilterGroup(), ctrl->GetCollisionFilterMask());
}
}
@@ -526,19 +480,7 @@ void CcdPhysicsEnvironment::disableCcdPhysicsController(CcdPhysicsController* ct
{
if (m_controllers.erase(ctrl))
{
- btRigidBody* body = ctrl->GetRigidBody();
- if (body)
- {
- m_dynamicsWorld->removeRigidBody(body);
- } else
- {
- if (ctrl->GetSoftBody())
- {
- } else
- {
- m_dynamicsWorld->removeCollisionObject(body);
- }
- }
+ m_dynamicsWorld->removeRigidBody(ctrl->GetRigidBody());
}
}
@@ -559,18 +501,10 @@ bool CcdPhysicsEnvironment::proceedDeltaTime(double curTime,float timeStep)
(*it)->SynchronizeMotionStates(timeStep);
}
- processFhSprings(curTime,timeStep);
-
float subStep = timeStep / float(m_numTimeSubSteps);
for (i=0;i<m_numTimeSubSteps;i++)
{
-// m_dynamicsWorld->stepSimulation(subStep,20,1./240.);//perform always a full simulation step
- m_dynamicsWorld->stepSimulation(subStep,0);//perform always a full simulation step
- }
-
- for (it=m_controllers.begin(); it!=m_controllers.end(); it++)
- {
- (*it)->SynchronizeMotionStates(timeStep);
+ m_dynamicsWorld->stepSimulation(subStep,0);//perform always a full simulation step
}
for (it=m_controllers.begin(); it!=m_controllers.end(); it++)
@@ -584,181 +518,11 @@ bool CcdPhysicsEnvironment::proceedDeltaTime(double curTime,float timeStep)
veh->SyncWheels();
}
- if (m_dynamicsWorld->getDebugDrawer() && m_dynamicsWorld->getDebugDrawer()->getDebugMode() >0)
- m_dynamicsWorld->debugDrawWorld();
-
-
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)
- {
-
- }
-
- 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 timeStep)
-{
- std::set<CcdPhysicsController*>::iterator it;
-
- 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();
-
-
- 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.0 - 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.0), 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));
- }
-
- }
-
-
- }
-
-
- }
- }
-
-}
void CcdPhysicsEnvironment::setDebugMode(int debugMode)
{
@@ -814,7 +578,7 @@ void CcdPhysicsEnvironment::setSolverDamping(float damping)
void CcdPhysicsEnvironment::setLinearAirDamping(float damping)
{
- //gLinearAirDamping = damping;
+ gLinearAirDamping = damping;
}
void CcdPhysicsEnvironment::setUseEpa(bool epa)
@@ -833,7 +597,7 @@ void CcdPhysicsEnvironment::setSolverType(int solverType)
{
m_solver = new btSequentialImpulseConstraintSolver();
-// ((btSequentialImpulseConstraintSolver*)m_solver)->setSolverMode(btSequentialImpulseConstraintSolver::SOLVER_USE_WARMSTARTING | btSequentialImpulseConstraintSolver::SOLVER_RANDMIZE_ORDER);
+ ((btSequentialImpulseConstraintSolver*)m_solver)->setSolverMode(btSequentialImpulseConstraintSolver::SOLVER_USE_WARMSTARTING | btSequentialImpulseConstraintSolver::SOLVER_RANDMIZE_ORDER);
break;
}
}
@@ -854,13 +618,7 @@ void CcdPhysicsEnvironment::setSolverType(int solverType)
-void CcdPhysicsEnvironment::getGravity(PHY__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)
@@ -883,16 +641,13 @@ int CcdPhysicsEnvironment::createUniversalD6Constraint(
const btVector3& linearMinLimits,
const btVector3& linearMaxLimits,
const btVector3& angularMinLimits,
- const btVector3& angularMaxLimits,int flags
+ const btVector3& angularMaxLimits
)
{
- 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;
@@ -904,10 +659,9 @@ int CcdPhysicsEnvironment::createUniversalD6Constraint(
{
- bool useReferenceFrameA = true;
genericConstraint = new btGeneric6DofConstraint(
*rb0,*rb1,
- frameInA,frameInB,useReferenceFrameA);
+ frameInA,frameInB);
genericConstraint->setLinearLowerLimit(linearMinLimits);
genericConstraint->setLinearUpperLimit(linearMaxLimits);
genericConstraint->setAngularLowerLimit(angularMinLimits);
@@ -922,7 +676,7 @@ int CcdPhysicsEnvironment::createUniversalD6Constraint(
if (genericConstraint)
{
// m_constraints.push_back(genericConstraint);
- m_dynamicsWorld->addConstraint(genericConstraint,disableCollisionBetweenLinkedBodies);
+ m_dynamicsWorld->addConstraint(genericConstraint);
genericConstraint->setUserConstraintId(gConstraintUid++);
genericConstraint->setUserConstraintType(PHY_GENERIC_6DOF_CONSTRAINT);
@@ -955,54 +709,35 @@ void CcdPhysicsEnvironment::removeConstraint(int constraintId)
struct FilterClosestRayResultCallback : public btCollisionWorld::ClosestRayResultCallback
{
- PHY_IRayCastFilterCallback& m_phyRayFilter;
- const btCollisionShape* m_hitTriangleShape;
- int m_hitTriangleIndex;
+ PHY_IPhysicsController* m_ignoreClient;
- FilterClosestRayResultCallback (PHY_IRayCastFilterCallback& phyRayFilter,const btVector3& rayFrom,const btVector3& rayTo)
+ FilterClosestRayResultCallback (PHY_IPhysicsController* ignoreClient,const btVector3& rayFrom,const btVector3& rayTo)
: btCollisionWorld::ClosestRayResultCallback(rayFrom,rayTo),
- m_phyRayFilter(phyRayFilter),
- m_hitTriangleShape(NULL),
- m_hitTriangleIndex(0)
+ m_ignoreClient(ignoreClient)
{
- }
- virtual ~FilterClosestRayResultCallback()
- {
}
- virtual bool needsCollision(btBroadphaseProxy* proxy0) const
+ virtual ~FilterClosestRayResultCallback()
{
- 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)
+ virtual float AddSingleResult( btCollisionWorld::LocalRayResult& rayResult)
{
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;
+ //ignore client...
+ if (curHit != m_ignoreClient)
+ {
+ //if valid
+ return ClosestRayResultCallback::AddSingleResult(rayResult);
}
- return ClosestRayResultCallback::addSingleResult(rayResult,normalInWorldSpace);
+ return m_closestHitFraction;
}
};
-PHY_IPhysicsController* CcdPhysicsEnvironment::rayTest(PHY_IRayCastFilterCallback &filterCallback, float fromX,float fromY,float fromZ, float toX,float toY,float toZ)
+PHY_IPhysicsController* CcdPhysicsEnvironment::rayTest(PHY_IPhysicsController* ignoreClient, float fromX,float fromY,float fromZ, float toX,float toY,float toZ,
+ float& hitX,float& hitY,float& hitZ,float& normalX,float& normalY,float& normalZ)
{
@@ -1016,101 +751,19 @@ PHY_IPhysicsController* CcdPhysicsEnvironment::rayTest(PHY_IRayCastFilterCallbac
//Either Ray Cast with or without filtering
//btCollisionWorld::ClosestRayResultCallback rayCallback(rayFrom,rayTo);
- FilterClosestRayResultCallback rayCallback(filterCallback,rayFrom,rayTo);
-
+ FilterClosestRayResultCallback rayCallback(ignoreClient,rayFrom,rayTo);
- PHY_RayCastResult result;
- memset(&result, 0, sizeof(result));
+ PHY_IPhysicsController* nearestHit = 0;
// don't collision with sensor object
- rayCallback.m_collisionFilterMask = CcdConstructionInfo::AllFilter ^ CcdConstructionInfo::SensorFilter;
- //, ,filterCallback.m_faceNormal);
-
- m_dynamicsWorld->rayTest(rayFrom,rayTo,rayCallback);
- if (rayCallback.hasHit())
+ m_dynamicsWorld->rayTest(rayFrom,rayTo,rayCallback, CcdConstructionInfo::AllFilter ^ CcdConstructionInfo::SensorFilter);
+ 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())
- {
- result.m_meshObject = shapeInfo->GetMesh();
- result.m_polygon = shapeInfo->m_polygonIndexArray.at(rayCallback.m_hitTriangleIndex);
+ nearestHit = static_cast<CcdPhysicsController*>(rayCallback.m_collisionObject->getUserPointer());
+ hitX = rayCallback.m_hitPointWorld.getX();
+ hitY = rayCallback.m_hitPointWorld.getY();
+ hitZ = rayCallback.m_hitPointWorld.getZ();
- // Bullet returns the normal from "outside".
- // If the user requests the real normal, compute it now
- if (filterCallback.m_faceNormal)
- {
- // mesh shapes are shared and stored in the shapeInfo
- btTriangleMeshShape* triangleShape = shapeInfo->GetMeshShape();
- if (triangleShape)
- {
- // this code is copied from Bullet
- btVector3 triangle[3];
- const unsigned char *vertexbase;
- int numverts;
- PHY_ScalarType type;
- int stride;
- const unsigned char *indexbase;
- int indexstride;
- int numfaces;
- PHY_ScalarType indicestype;
- btStridingMeshInterface* meshInterface = triangleShape->getMeshInterface();
-
- meshInterface->getLockedReadOnlyVertexIndexBase(
- &vertexbase,
- numverts,
- type,
- stride,
- &indexbase,
- indexstride,
- numfaces,
- indicestype,
- 0);
-
- unsigned int* gfxbase = (unsigned int*)(indexbase+rayCallback.m_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);
- btVector3 triangleNormal;
- triangleNormal = (triangle[1]-triangle[0]).cross(triangle[2]-triangle[0]);
- rayCallback.m_hitNormalWorld = rayCallback.m_collisionObject->getWorldTransform().getBasis()*triangleNormal;
- }
- }
- }
- }
- }
if (rayCallback.m_hitNormalWorld.length2() > (SIMD_EPSILON*SIMD_EPSILON))
{
rayCallback.m_hitNormalWorld.normalize();
@@ -1118,14 +771,14 @@ PHY_IPhysicsController* CcdPhysicsEnvironment::rayTest(PHY_IRayCastFilterCallbac
{
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);
+ normalX = rayCallback.m_hitNormalWorld.getX();
+ normalY = rayCallback.m_hitNormalWorld.getY();
+ normalZ = rayCallback.m_hitNormalWorld.getZ();
+
}
- return result.m_controller;
+ return nearestHit;
}
@@ -1148,13 +801,6 @@ btBroadphaseInterface* CcdPhysicsEnvironment::getBroadphase()
return m_dynamicsWorld->getBroadphase();
}
-btDispatcher* CcdPhysicsEnvironment::getDispatcher()
-{
- return m_dynamicsWorld->getDispatcher();
-}
-
-
-
@@ -1187,12 +833,6 @@ CcdPhysicsEnvironment::~CcdPhysicsEnvironment()
if (NULL != m_filterCallback)
delete m_filterCallback;
-
- if (NULL != m_collisionConfiguration)
- delete m_collisionConfiguration;
-
- if (NULL != m_broadphase)
- delete m_broadphase;
}
@@ -1205,7 +845,7 @@ void CcdPhysicsEnvironment::setConstraintParam(int constraintId,int param,float
{
//param = 1..12, min0,max0,min1,max1...min6,max6
btGeneric6DofConstraint* genCons = (btGeneric6DofConstraint*)typedConstraint;
- genCons->setLimit(param,value0,value1);
+ genCons->SetLimit(param,value0,value1);
break;
};
default:
@@ -1468,37 +1108,14 @@ PHY_IPhysicsController* CcdPhysicsEnvironment::CreateSphereController(float radi
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
+ float axis2X,float axis2Y,float axis2Z
)
{
- bool disableCollisionBetweenLinkedBodies = (0!=(flags & CCD_CONSTRAINT_DISABLE_LINKED_COLLISION));
-
-
CcdPhysicsController* c0 = (CcdPhysicsController*)ctrl0;
CcdPhysicsController* c1 = (CcdPhysicsController*)ctrl1;
@@ -1506,166 +1123,14 @@ int CcdPhysicsEnvironment::createConstraint(class PHY_IPhysicsController* ctrl
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 pivotInA(pivotX,pivotY,pivotZ);
btVector3 pivotInB = rb1 ? rb1->getCenterOfMassTransform().inverse()(rb0->getCenterOfMassTransform()(pivotInA)) :
rb0->getCenterOfMassTransform() * pivotInA;
btVector3 axisInA(axisX,axisY,axisZ);
@@ -1690,7 +1155,7 @@ int CcdPhysicsEnvironment::createConstraint(class PHY_IPhysicsController* ctrl
pivotInA);
}
- m_dynamicsWorld->addConstraint(p2p,disableCollisionBetweenLinkedBodies);
+ m_dynamicsWorld->addConstraint(p2p);
// m_constraints.push_back(p2p);
p2p->setUserConstraintId(gConstraintUid++);
@@ -1726,11 +1191,10 @@ int CcdPhysicsEnvironment::createConstraint(class PHY_IPhysicsController* ctrl
btTransform globalFrameA = rb0->getCenterOfMassTransform() * frameInA;
frameInB = inv * globalFrameA;
- bool useReferenceFrameA = true;
-
+
genericConstraint = new btGeneric6DofConstraint(
*rb0,*rb1,
- frameInA,frameInB,useReferenceFrameA);
+ frameInA,frameInB);
} else
@@ -1751,16 +1215,15 @@ int CcdPhysicsEnvironment::createConstraint(class PHY_IPhysicsController* ctrl
///frameInB in worldspace
frameInB = rb0->getCenterOfMassTransform() * frameInA;
- bool useReferenceFrameA = true;
genericConstraint = new btGeneric6DofConstraint(
*rb0,s_fixedObject2,
- frameInA,frameInB,useReferenceFrameA);
+ frameInA,frameInB);
}
if (genericConstraint)
{
//m_constraints.push_back(genericConstraint);
- m_dynamicsWorld->addConstraint(genericConstraint,disableCollisionBetweenLinkedBodies);
+ m_dynamicsWorld->addConstraint(genericConstraint);
genericConstraint->setUserConstraintId(gConstraintUid++);
genericConstraint->setUserConstraintType(type);
//64 bit systems can't cast pointer to int. could use size_t instead.
@@ -1826,7 +1289,7 @@ int CcdPhysicsEnvironment::createConstraint(class PHY_IPhysicsController* ctrl
if (coneTwistContraint)
{
//m_constraints.push_back(genericConstraint);
- m_dynamicsWorld->addConstraint(coneTwistContraint,disableCollisionBetweenLinkedBodies);
+ m_dynamicsWorld->addConstraint(coneTwistContraint);
coneTwistContraint->setUserConstraintId(gConstraintUid++);
coneTwistContraint->setUserConstraintType(type);
//64 bit systems can't cast pointer to int. could use size_t instead.
@@ -1865,7 +1328,7 @@ int CcdPhysicsEnvironment::createConstraint(class PHY_IPhysicsController* ctrl
hinge->setAngularOnly(angularOnly);
//m_constraints.push_back(hinge);
- m_dynamicsWorld->addConstraint(hinge,disableCollisionBetweenLinkedBodies);
+ m_dynamicsWorld->addConstraint(hinge);
hinge->setUserConstraintId(gConstraintUid++);
hinge->setUserConstraintType(type);
//64 bit systems can't cast pointer to int. could use size_t instead.
@@ -1907,9 +1370,8 @@ int CcdPhysicsEnvironment::createConstraint(class PHY_IPhysicsController* ctrl
PHY_IPhysicsController* CcdPhysicsEnvironment::CreateConeController(float coneradius,float coneheight)
{
CcdConstructionInfo cinfo;
-
- // we don't need a CcdShapeConstructionInfo for this shape:
- // it is simple enough for the standard copy constructor (see CcdPhysicsController::GetReplica)
+ //This is a memory leak: Bullet does not delete the shape and it cannot be added to
+ //the KX_Scene.m_shapes list -- too bad but that's not a lot of data
cinfo.m_collisionShape = new btConeShape(coneradius,coneheight);
cinfo.m_MotionState = 0;
cinfo.m_physicsEnv = this;
diff --git a/source/gameengine/Physics/Bullet/CcdPhysicsEnvironment.h b/source/gameengine/Physics/Bullet/CcdPhysicsEnvironment.h
index 74384dd8cf2..825a5e525f2 100644
--- a/source/gameengine/Physics/Bullet/CcdPhysicsEnvironment.h
+++ b/source/gameengine/Physics/Bullet/CcdPhysicsEnvironment.h
@@ -56,10 +56,6 @@ class CcdPhysicsEnvironment : public PHY_IPhysicsEnvironment
protected:
btIDebugDraw* m_debugDrawer;
-
- class btDefaultCollisionConfiguration* m_collisionConfiguration;
- class btBroadphaseInterface* m_broadphase;
-
//solver iterations
int m_numIterations;
@@ -74,7 +70,6 @@ protected:
btContactSolverInfo m_solverInfo;
- void processFhSprings(double curTime,float timeStep);
public:
CcdPhysicsEnvironment(btDispatcher* dispatcher=0, btOverlappingPairCache* pairCache=0);
@@ -120,14 +115,12 @@ protected:
virtual void setDebugMode(int debugMode);
virtual void setGravity(float x,float y,float z);
- virtual void getGravity(PHY__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
+ float axis2X=0,float axis2Y=0,float axis2Z=0
);
@@ -139,7 +132,7 @@ protected:
const btVector3& linearMinLimits,
const btVector3& linearMaxLimits,
const btVector3& angularMinLimits,
- const btVector3& angularMaxLimits,int flags
+ const btVector3& angularMaxLimits
);
virtual void setConstraintParam(int constraintId,int param,float value,float value1);
@@ -164,7 +157,8 @@ protected:
btTypedConstraint* getConstraintById(int constraintId);
- virtual PHY_IPhysicsController* rayTest(PHY_IRayCastFilterCallback &filterCallback, float fromX,float fromY,float fromZ, float toX,float toY,float toZ);
+ virtual PHY_IPhysicsController* rayTest(PHY_IPhysicsController* ignoreClient, float fromX,float fromY,float fromZ, float toX,float toY,float toZ,
+ float& hitX,float& hitY,float& hitZ,float& normalX,float& normalY,float& normalZ);
//Methods for gamelogic collision/physics callbacks
@@ -198,7 +192,8 @@ protected:
btBroadphaseInterface* getBroadphase();
- btDispatcher* getDispatcher();
+
+
bool IsSatCollisionDetectionEnabled() const
@@ -217,10 +212,7 @@ protected:
void SyncMotionStates(float timeStep);
- class btSoftRigidDynamicsWorld* getDynamicsWorld()
- {
- return m_dynamicsWorld;
- }
+
class btConstraintSolver* GetConstraintSolver();
@@ -238,13 +230,13 @@ protected:
std::vector<WrapperVehicle*> m_wrapperVehicles;
- //use explicit btSoftRigidDynamicsWorld/btDiscreteDynamicsWorld* so that we have access to
+ //use explicit 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 btDiscreteDynamicsWorld* m_dynamicsWorld;
class btConstraintSolver* m_solver;
diff --git a/source/gameengine/Physics/Bullet/Makefile b/source/gameengine/Physics/Bullet/Makefile
index d5570e75833..49259d0a67c 100644
--- a/source/gameengine/Physics/Bullet/Makefile
+++ b/source/gameengine/Physics/Bullet/Makefile
@@ -37,10 +37,5 @@ CCFLAGS += $(LEVEL_1_CPP_WARNINGS)
CPPFLAGS += -I$(NAN_BULLET2)/include
CPPFLAGS += -I$(NAN_GUARDEDALLOC)/include
-CPPFLAGS += -I$(NAN_STRING)/include
-CPPFLAGS += -I$(NAN_MOTO)/include
-CPPFLAGS += -I../../../kernel/gen_system
CPPFLAGS += -I../../Physics/common
CPPFLAGS += -I../../Physics/Dummy
-CPPFLAGS += -I../../Rasterizer
-
diff --git a/source/gameengine/Physics/Bullet/SConscript b/source/gameengine/Physics/Bullet/SConscript
index 0936d45197a..dd6eab0f018 100644
--- a/source/gameengine/Physics/Bullet/SConscript
+++ b/source/gameengine/Physics/Bullet/SConscript
@@ -3,7 +3,7 @@ Import ('env')
sources = 'CcdPhysicsEnvironment.cpp CcdPhysicsController.cpp'
-incs = '. ../common #source/kernel/gen_system #intern/string #intern/moto/include #source/gameengine/Rasterizer'
+incs = '. ../common'
incs += ' ' + env['BF_BULLET_INC']
diff --git a/source/gameengine/Physics/Dummy/DummyPhysicsEnvironment.cpp b/source/gameengine/Physics/Dummy/DummyPhysicsEnvironment.cpp
index ba196b5cf55..f512d44c9f2 100644
--- a/source/gameengine/Physics/Dummy/DummyPhysicsEnvironment.cpp
+++ b/source/gameengine/Physics/Dummy/DummyPhysicsEnvironment.cpp
@@ -92,7 +92,8 @@ void DummyPhysicsEnvironment::setGravity(float x,float y,float z)
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
+ float axis2X,float axis2Y,float axis2Z
+
)
{
@@ -108,7 +109,8 @@ void DummyPhysicsEnvironment::removeConstraint(int constraintid)
}
}
-PHY_IPhysicsController* DummyPhysicsEnvironment::rayTest(PHY_IRayCastFilterCallback &filterCallback,float fromX,float fromY,float fromZ, float toX,float toY,float toZ)
+PHY_IPhysicsController* DummyPhysicsEnvironment::rayTest(PHY_IPhysicsController* ignoreClient,float fromX,float fromY,float fromZ, float toX,float toY,float toZ,
+ float& hitX,float& hitY,float& hitZ,float& normalX,float& normalY,float& normalZ)
{
//collision detection / raytesting
return NULL;
diff --git a/source/gameengine/Physics/Dummy/DummyPhysicsEnvironment.h b/source/gameengine/Physics/Dummy/DummyPhysicsEnvironment.h
index a92b1e7f4a6..b5a61f72e4a 100644
--- a/source/gameengine/Physics/Dummy/DummyPhysicsEnvironment.h
+++ b/source/gameengine/Physics/Dummy/DummyPhysicsEnvironment.h
@@ -58,7 +58,7 @@ public:
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
+ float axis2X=0,float axis2Y=0,float axis2Z=0
);
virtual void removeConstraint(int constraintid);
@@ -69,7 +69,8 @@ public:
return 0;
}
- virtual PHY_IPhysicsController* rayTest(PHY_IRayCastFilterCallback &filterCallback, float fromX,float fromY,float fromZ, float toX,float toY,float toZ);
+ virtual PHY_IPhysicsController* rayTest(PHY_IPhysicsController* ignoreClient, float fromX,float fromY,float fromZ, float toX,float toY,float toZ,
+ float& hitX,float& hitY,float& hitZ,float& normalX,float& normalY,float& normalZ);
//gamelogic callbacks
diff --git a/source/gameengine/Physics/Sumo/SConscript b/source/gameengine/Physics/Sumo/SConscript
index 86e8db5919f..be7922efd44 100644
--- a/source/gameengine/Physics/Sumo/SConscript
+++ b/source/gameengine/Physics/Sumo/SConscript
@@ -1,6 +1,7 @@
#!/usr/bin/python
Import ('env')
+sumoenv = env.Copy()
sources = ['SumoPHYCallbackBridge.cpp',
'SumoPhysicsController.cpp',
'SumoPhysicsEnvironment.cpp',
@@ -15,7 +16,7 @@ incs =['.',
'Fuzzics/include',
'#/intern/moto/include'
]
-incs += [env['BF_SOLID_INC']]
+incs += [sumoenv['BF_SOLID_INC']]
cflags = []
if env['OURPLATFORM']=='win32-vc':
diff --git a/source/gameengine/Physics/Sumo/SumoPhysicsController.h b/source/gameengine/Physics/Sumo/SumoPhysicsController.h
index d8ee54935d7..95f01b45f2b 100644
--- a/source/gameengine/Physics/Sumo/SumoPhysicsController.h
+++ b/source/gameengine/Physics/Sumo/SumoPhysicsController.h
@@ -120,7 +120,6 @@ public:
virtual void SetMargin(float margin) ;
virtual float GetMargin() const;
virtual float GetRadius() const ;
- virtual void SetRadius(float margin) { SetMargin(margin); }
// clientinfo for raycasts for example
diff --git a/source/gameengine/Physics/Sumo/SumoPhysicsEnvironment.cpp b/source/gameengine/Physics/Sumo/SumoPhysicsEnvironment.cpp
index 3be5e027345..65018d2523e 100644
--- a/source/gameengine/Physics/Sumo/SumoPhysicsEnvironment.cpp
+++ b/source/gameengine/Physics/Sumo/SumoPhysicsEnvironment.cpp
@@ -26,7 +26,6 @@
*
* ***** END GPL LICENSE BLOCK *****
*/
-#include <string.h> // memset
#include "SumoPhysicsEnvironment.h"
#include "PHY_IMotionState.h"
#include "SumoPhysicsController.h"
@@ -111,8 +110,8 @@ int SumoPhysicsEnvironment::createConstraint(
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
+ float axis2X,float axis2Y,float axis2Z
+
)
{
int constraintid = 0;
@@ -126,35 +125,37 @@ void SumoPhysicsEnvironment::removeConstraint(int constraintid)
}
}
-PHY_IPhysicsController* SumoPhysicsEnvironment::rayTest(PHY_IRayCastFilterCallback &filterCallback,
+PHY_IPhysicsController* SumoPhysicsEnvironment::rayTest(PHY_IPhysicsController* ignoreClientCtrl,
float fromX,float fromY,float fromZ,
- float toX,float toY,float toZ)
+ float toX,float toY,float toZ,
+ float& hitX,float& hitY,float& hitZ,
+ float& normalX,float& normalY,float& normalZ)
{
- SumoPhysicsController* ignoreCtr = static_cast<SumoPhysicsController*> (filterCallback.m_ignoreController);
+ SumoPhysicsController* ignoreCtr = static_cast<SumoPhysicsController*> (ignoreClientCtrl);
//collision detection / raytesting
MT_Point3 hit, normal;
- PHY_RayCastResult result;
+ PHY_IPhysicsController *ret = 0;
SM_Object* sm_ignore = 0;
if (ignoreCtr)
sm_ignore = ignoreCtr->GetSumoObject();
- memset(&result, 0, sizeof(result));
SM_Object* smOb = m_sumoScene->rayTest(sm_ignore,MT_Point3(fromX, fromY, fromZ),MT_Point3(toX, toY, toZ), hit, normal);
if (smOb)
{
- result.m_controller = (PHY_IPhysicsController *) smOb->getPhysicsClientObject();
- result.m_hitPoint[0] = hit[0];
- result.m_hitPoint[1] = hit[1];
- result.m_hitPoint[2] = hit[2];
- result.m_hitNormal[0] = normal[0];
- result.m_hitNormal[1] = normal[1];
- result.m_hitNormal[2] = normal[2];
- filterCallback.reportHit(&result);
+ ret = (PHY_IPhysicsController *) smOb->getPhysicsClientObject();
}
- return result.m_controller;
+ hitX = hit[0];
+ hitY = hit[1];
+ hitZ = hit[2];
+
+ normalX = normal[0];
+ normalY = normal[1];
+ normalZ = normal[2];
+
+ return ret;
}
//gamelogic callbacks
void SumoPhysicsEnvironment::addSensor(PHY_IPhysicsController* ctrl)
diff --git a/source/gameengine/Physics/Sumo/SumoPhysicsEnvironment.h b/source/gameengine/Physics/Sumo/SumoPhysicsEnvironment.h
index 65b07a7a0be..8b9fb463034 100644
--- a/source/gameengine/Physics/Sumo/SumoPhysicsEnvironment.h
+++ b/source/gameengine/Physics/Sumo/SumoPhysicsEnvironment.h
@@ -63,7 +63,7 @@ public:
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
+ float axis2X=0,float axis2Y=0,float axis2Z=0
);
@@ -75,7 +75,8 @@ public:
return 0;
}
- virtual PHY_IPhysicsController* rayTest(PHY_IRayCastFilterCallback &filterCallback,float fromX,float fromY,float fromZ, float toX,float toY,float toZ);
+ virtual PHY_IPhysicsController* rayTest(PHY_IPhysicsController* ignoreClient,float fromX,float fromY,float fromZ, float toX,float toY,float toZ,
+ float& hitX,float& hitY,float& hitZ,float& normalX,float& normalY,float& normalZ);
//gamelogic callbacks
diff --git a/source/gameengine/Physics/common/PHY_DynamicTypes.h b/source/gameengine/Physics/common/PHY_DynamicTypes.h
index 3b3e42c38d2..c289b9d8bcb 100644
--- a/source/gameengine/Physics/common/PHY_DynamicTypes.h
+++ b/source/gameengine/Physics/common/PHY_DynamicTypes.h
@@ -87,18 +87,6 @@ typedef enum PHY_ConstraintType {
} PHY_ConstraintType;
-typedef enum PHY_ShapeType {
- PHY_SHAPE_NONE,
- PHY_SHAPE_BOX,
- PHY_SHAPE_SPHERE,
- PHY_SHAPE_CYLINDER,
- PHY_SHAPE_CONE,
- PHY_SHAPE_MESH,
- PHY_SHAPE_POLYTOPE,
- PHY_SHAPE_COMPOUND
-} PHY_ShapeType;
-
-
typedef float PHY_Vector3[3];
#endif //__PHY_DYNAMIC_TYPES
diff --git a/source/gameengine/Physics/common/PHY_IPhysicsController.h b/source/gameengine/Physics/common/PHY_IPhysicsController.h
index 884e14cfb5a..ca8edea114a 100644
--- a/source/gameengine/Physics/common/PHY_IPhysicsController.h
+++ b/source/gameengine/Physics/common/PHY_IPhysicsController.h
@@ -90,8 +90,7 @@ class PHY_IPhysicsController
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 GetRadius() const { return 0.f;}
PHY__Vector3 GetWorldPosition(PHY__Vector3& localpos);
};
diff --git a/source/gameengine/Physics/common/PHY_IPhysicsEnvironment.h b/source/gameengine/Physics/common/PHY_IPhysicsEnvironment.h
index 0e9c571924c..5b275066665 100644
--- a/source/gameengine/Physics/common/PHY_IPhysicsEnvironment.h
+++ b/source/gameengine/Physics/common/PHY_IPhysicsEnvironment.h
@@ -33,50 +33,6 @@
#include <vector>
#include "PHY_DynamicTypes.h"
class PHY_IVehicle;
-class RAS_MeshObject;
-class PHY_IPhysicsController;
-
-/**
- * pass back information from rayTest
- */
-struct PHY_RayCastResult
-{
- PHY_IPhysicsController* m_controller;
- PHY__Vector3 m_hitPoint;
- PHY__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
-};
-
-/**
- * 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 environement (Bullet).
- */
-class PHY_IRayCastFilterCallback
-{
-public:
- PHY_IPhysicsController* m_ignoreController;
- bool m_faceNormal;
-
- 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)
- :m_ignoreController(ignoreController),
- m_faceNormal(faceNormal)
- {
- }
-};
/**
* Physics Environment takes care of stepping the simulation and is a container for physics entities (rigidbodies,constraints, materials etc.)
@@ -129,7 +85,7 @@ class PHY_IPhysicsEnvironment
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
+ float axis2X=0,float axis2Y=0,float axis2Z=0
)=0;
virtual void removeConstraint(int constraintid)=0;
virtual float getAppliedImpulse(int constraintid){ return 0.f;}
@@ -138,7 +94,8 @@ class PHY_IPhysicsEnvironment
//complex constraint for vehicles
virtual PHY_IVehicle* getVehicleConstraint(int constraintId) =0;
- virtual PHY_IPhysicsController* rayTest(PHY_IRayCastFilterCallback &filterCallback, float fromX,float fromY,float fromZ, float toX,float toY,float toZ)=0;
+ virtual PHY_IPhysicsController* rayTest(PHY_IPhysicsController* ignoreClient, float fromX,float fromY,float fromZ, float toX,float toY,float toZ,
+ float& hitX,float& hitY,float& hitZ,float& normalX,float& normalY,float& normalZ)=0;
//Methods for gamelogic collision/physics callbacks
diff --git a/source/gameengine/PyDoc/BL_ActionActuator.py b/source/gameengine/PyDoc/BL_ActionActuator.py
index b68d3014115..d56888cde80 100644
--- a/source/gameengine/PyDoc/BL_ActionActuator.py
+++ b/source/gameengine/PyDoc/BL_ActionActuator.py
@@ -164,14 +164,5 @@ class BL_ActionActuator(SCA_IActuator):
@param mode: True for armature/world space, False for bone space
@type mode: boolean
"""
- def setFrameProperty(prop):
- """
- @param prop: A string specifying the property of the object that will be updated with the action frame number.
- @type prop: string
- """
- def getFrameProperty():
- """
- Returns the name of the property that is set to the current frame number.
-
- @rtype: string
- """
+
+
diff --git a/source/gameengine/PyDoc/BL_ShapeActionActuator.py b/source/gameengine/PyDoc/BL_ShapeActionActuator.py
index a26b276a2da..63cce253fa4 100644
--- a/source/gameengine/PyDoc/BL_ShapeActionActuator.py
+++ b/source/gameengine/PyDoc/BL_ShapeActionActuator.py
@@ -154,14 +154,5 @@ class BL_ShapeActionActuator(SCA_IActuator):
@rtype: string
"""
- def setFrameProperty(prop):
- """
- @param prop: A string specifying the property of the object that will be updated with the action frame number.
- @type prop: string
- """
- def getFrameProperty():
- """
- Returns the name of the property that is set to the current frame number.
-
- @rtype: string
- """
+
+
diff --git a/source/gameengine/PyDoc/GameKeys.py b/source/gameengine/PyDoc/GameKeys.py
index 1a0a737718e..268fb9cc172 100644
--- a/source/gameengine/PyDoc/GameKeys.py
+++ b/source/gameengine/PyDoc/GameKeys.py
@@ -164,12 +164,3 @@ Example::
# Activate Right!
"""
-
-def EventToString(event):
- """
- Return the string name of a key event. Will raise a ValueError error if its invalid.
-
- @type event: int
- @param event: key event from GameKeys or the keyboard sensor.
- @rtype: string
- """
diff --git a/source/gameengine/PyDoc/GameLogic.py b/source/gameengine/PyDoc/GameLogic.py
index 9dab7db6081..965c0522bd7 100644
--- a/source/gameengine/PyDoc/GameLogic.py
+++ b/source/gameengine/PyDoc/GameLogic.py
@@ -13,10 +13,11 @@ Documentation for the GameLogic Module.
See L{WhatsNew} for updates, changes and new functionality in the Game Engine Python API.
Examples::
- # To get the controller thats running this python script:
- co = GameLogic.getCurrentController() # GameLogic is automatically imported
+ # To get a controller:
+ import GameLogic
+ co = GameLogic.getCurrentController()
- # To get the game object this controller is on:
+ # To get the game object associated with this controller:
obj = co.getOwner()
L{KX_GameObject} and L{KX_Camera} or L{KX_Light} methods are
available depending on the type of object::
@@ -31,18 +32,16 @@ Documentation for the GameLogic Module.
sensors = co.getSensors()
See the sensor's reference for available methods:
- - L{DelaySensor<SCA_DelaySensor.SCA_DelaySensor>}
- - L{JoystickSensor<SCA_JoystickSensor.SCA_JoystickSensor>}
- - L{KeyboardSensor<SCA_KeyboardSensor.SCA_KeyboardSensor>}
- - L{MouseFocusSensor<KX_MouseFocusSensor.KX_MouseFocusSensor>}
- - L{MouseSensor<SCA_MouseSensor.SCA_MouseSensor>}
- - L{NearSensor<KX_NearSensor.KX_NearSensor>}
- - L{NetworkMessageSensor<KX_NetworkMessageSensor.KX_NetworkMessageSensor>}
- - L{PropertySensor<SCA_PropertySensor.SCA_PropertySensor>}
- - L{RadarSensor<KX_RadarSensor.KX_RadarSensor>}
- - L{RandomSensor<SCA_RandomSensor.SCA_RandomSensor>}
- - L{RaySensor<KX_RaySensor.KX_RaySensor>}
- - L{TouchSensor<KX_TouchSensor.KX_TouchSensor>}
+ - L{KX_NetworkMessageSensor}
+ - L{KX_RaySensor}
+ - L{KX_MouseFocusSensor}
+ - L{KX_NearSensor}
+ - L{KX_RadarSensor}
+ - L{KX_TouchSensor}
+ - L{SCA_KeyboardSensor}
+ - L{SCA_MouseSensor}
+ - L{SCA_PropertySensor}
+ - L{SCA_RandomSensor}
You can also access actuators linked to the controller::
# To get an actuator attached to the controller:
@@ -55,23 +54,23 @@ Documentation for the GameLogic Module.
GameLogic.addActiveActuator(actuator, True)
See the actuator's reference for available methods:
- - L{ActionActuator<BL_ActionActuator.BL_ActionActuator>}
- - L{AddObjectActuator<KX_SCA_AddObjectActuator.KX_SCA_AddObjectActuator>}
- - L{CameraActuator<KX_CameraActuator.KX_CameraActuator>}
- - L{CDActuator<KX_CDActuator.KX_CDActuator>}
- - L{ConstraintActuator<KX_ConstraintActuator.KX_ConstraintActuator>}
- - L{EndObjectActuator<KX_SCA_EndObjectActuator.KX_SCA_EndObjectActuator>}
- - L{GameActuator<KX_GameActuator.KX_GameActuator>}
- - L{IpoActuator<KX_IpoActuator.KX_IpoActuator>}
- - L{NetworkMessageActuator<KX_NetworkMessageActuator.KX_NetworkMessageActuator>}
- - L{ObjectActuator<KX_ObjectActuator.KX_ObjectActuator>}
- - L{PropertyActuator<SCA_PropertyActuator.SCA_PropertyActuator>}
- - L{RandomActuator<SCA_RandomActuator.SCA_RandomActuator>}
- - L{ReplaceMeshActuator<KX_SCA_ReplaceMeshActuator.KX_SCA_ReplaceMeshActuator>}
- - L{SceneActuator<KX_SceneActuator.KX_SceneActuator>}
- - L{SoundActuator<KX_SoundActuator.KX_SoundActuator>}
- - L{TrackToActuator<KX_TrackToActuator.KX_TrackToActuator>}
- - L{VisibilityActuator<KX_VisibilityActuator.KX_VisibilityActuator>}
+ - L{BL_ActionActuator}
+ - L{KX_CameraActuator}
+ - L{KX_CDActuator}
+ - L{KX_ConstraintActuator}
+ - L{KX_GameActuator}
+ - L{KX_IpoActuator}
+ - L{KX_NetworkMessageActuator}
+ - L{KX_ObjectActuator}
+ - L{KX_SCA_AddObjectActuator}
+ - L{KX_SCA_EndObjectActuator}
+ - L{KX_SCA_ReplaceMeshActuator}
+ - L{KX_SceneActuator}
+ - L{KX_SoundActuator}
+ - L{KX_TrackToActuator}
+ - L{KX_VisibilityActuator}
+ - L{SCA_PropertyActuator}
+ - L{SCA_RandomActuator}
Most logic brick's methods are accessors for the properties available in the logic buttons.
Consult the logic bricks documentation for more information on how each logic brick works.
@@ -221,13 +220,6 @@ def setPhysicsTicRate(ticrate):
@param ticrate: The new update frequency (in Hz).
@type ticrate: float
"""
-def getAverageFrameRate():
- """
- Gets the estimated average framerate
-
- @return: The estimed average framerate in frames per second
- @rtype: float
- """
def expandPath(path):
"""
@@ -244,13 +236,3 @@ def expandPath(path):
@return: The converted string
@rtype: string
"""
-
-def getBlendFileList(path = "//"):
- """
- Returns a list of blend files in the same directory as the open blend file, or from using the option argument.
-
- @param path: Optional directory argument, will be expanded (like expandPath) into the full path.
- @type path: string
- @return: A list of filenames, with no directory prefix
- @rtype: list
- """
diff --git a/source/gameengine/PyDoc/KX_ActuatorSensor.py b/source/gameengine/PyDoc/KX_ActuatorSensor.py
index b0e138a8009..f9aef86f7f0 100644
--- a/source/gameengine/PyDoc/KX_ActuatorSensor.py
+++ b/source/gameengine/PyDoc/KX_ActuatorSensor.py
@@ -1,29 +1,21 @@
# $Id$
# Documentation for KX_ActuatorSensor
from SCA_IActuator import *
-from SCA_ISensor import *
class KX_ActuatorSensor(SCA_ISensor):
"""
Actuator sensor detect change in actuator state of the parent object.
It generates a positive pulse if the corresponding actuator is activated
and a negative pulse if the actuator is deactivated.
-
- Properties:
-
- @ivar actuator: the name of the actuator that the sensor is monitoring.
- @type actuator: string
"""
def getActuator():
"""
- DEPRECATED: use the actuator property
Return the Actuator with which the sensor operates.
@rtype: string
"""
def setActuator(name):
"""
- DEPRECATED: use the actuator property
Sets the Actuator with which to operate. If there is no Actuator
of this name, the function has no effect.
diff --git a/source/gameengine/PyDoc/KX_CameraActuator.py b/source/gameengine/PyDoc/KX_CameraActuator.py
index 9a9abaf3d57..032fc7338ac 100644
--- a/source/gameengine/PyDoc/KX_CameraActuator.py
+++ b/source/gameengine/PyDoc/KX_CameraActuator.py
@@ -8,13 +8,11 @@ class KX_CameraActuator(SCA_IActuator):
@author: snail
"""
- def getObject(name_only = 1):
+ def getObject():
"""
Returns the name of the object this actuator tracks.
- @type name_only: bool
- @param name_only: optional argument, when 0 return a KX_GameObject
- @rtype: string, KX_GameObject or None if no object is set
+ rtype: string
"""
def setObject(target):
@@ -22,7 +20,7 @@ class KX_CameraActuator(SCA_IActuator):
Sets the object this actuator tracks.
@param target: the object to track.
- @type target: L{KX_GameObject}, string or None
+ @type target: string or L{KX_GameObject}
"""
def getMin():
diff --git a/source/gameengine/PyDoc/KX_ConstraintActuator.py b/source/gameengine/PyDoc/KX_ConstraintActuator.py
index 7c7ad5aa0fa..b1c6f3c0f4e 100644
--- a/source/gameengine/PyDoc/KX_ConstraintActuator.py
+++ b/source/gameengine/PyDoc/KX_ConstraintActuator.py
@@ -58,11 +58,11 @@ class KX_ConstraintActuator(SCA_IActuator):
See module L{GameLogic} for valid constraint types.
- @param limit:
- Position constraints: KX_CONSTRAINTACT_LOCX, KX_CONSTRAINTACT_LOCY, KX_CONSTRAINTACT_LOCZ
- Rotation constraints: KX_CONSTRAINTACT_ROTX, KX_CONSTRAINTACT_ROTY or KX_CONSTRAINTACT_ROTZ
- Distance contraints: KX_ACT_CONSTRAINT_DIRPX, KX_ACT_CONSTRAINT_DIRPY, KX_ACT_CONSTRAINT_DIRPZ, KX_ACT_CONSTRAINT_DIRNX, KX_ACT_CONSTRAINT_DIRNY, KX_ACT_CONSTRAINT_DIRNZ
- Orientation constraints: KX_ACT_CONSTRAINT_ORIX, KX_ACT_CONSTRAINT_ORIY, KX_ACT_CONSTRAINT_ORIZ
+ @param limit: Position constraints: KX_CONSTRAINTACT_LOCX, KX_CONSTRAINTACT_LOCY, KX_CONSTRAINTACT_LOCZ,
+ Rotation constraints: KX_CONSTRAINTACT_ROTX, KX_CONSTRAINTACT_ROTY or KX_CONSTRAINTACT_ROTZ
+ Distance contraints: KX_ACT_CONSTRAINT_DIRPX, KX_ACT_CONSTRAINT_DIRPY, KX_ACT_CONSTRAINT_DIRPZ,
+ KX_ACT_CONSTRAINT_DIRNX, KX_ACT_CONSTRAINT_DIRNY, KX_ACT_CONSTRAINT_DIRNZ,
+ Orientation constraints: KX_ACT_CONSTRAINT_ORIX, KX_ACT_CONSTRAINT_ORIY, KX_ACT_CONSTRAINT_ORIZ
"""
def getLimit():
"""
@@ -70,11 +70,11 @@ class KX_ConstraintActuator(SCA_IActuator):
See module L{GameLogic} for valid constraints.
- @return:
- Position constraints: KX_CONSTRAINTACT_LOCX, KX_CONSTRAINTACT_LOCY, KX_CONSTRAINTACT_LOCZ,
- Rotation constraints: KX_CONSTRAINTACT_ROTX, KX_CONSTRAINTACT_ROTY, KX_CONSTRAINTACT_ROTZ,
- Distance contraints: KX_ACT_CONSTRAINT_DIRPX, KX_ACT_CONSTRAINT_DIRPY, KX_ACT_CONSTRAINT_DIRPZ, KX_ACT_CONSTRAINT_DIRNX, KX_ACT_CONSTRAINT_DIRNY, KX_ACT_CONSTRAINT_DIRNZ,
- Orientation constraints: KX_ACT_CONSTRAINT_ORIX, KX_ACT_CONSTRAINT_ORIY, KX_ACT_CONSTRAINT_ORIZ
+ @return: Position constraints: KX_CONSTRAINTACT_LOCX, KX_CONSTRAINTACT_LOCY, KX_CONSTRAINTACT_LOCZ,
+ Rotation constraints: KX_CONSTRAINTACT_ROTX, KX_CONSTRAINTACT_ROTY, KX_CONSTRAINTACT_ROTZ,
+ Distance contraints: KX_ACT_CONSTRAINT_DIRPX, KX_ACT_CONSTRAINT_DIRPY, KX_ACT_CONSTRAINT_DIRPZ,
+ KX_ACT_CONSTRAINT_DIRNX, KX_ACT_CONSTRAINT_DIRNY, KX_ACT_CONSTRAINT_DIRNZ,
+ Orientation constraints: KX_ACT_CONSTRAINT_ORIX, KX_ACT_CONSTRAINT_ORIY, KX_ACT_CONSTRAINT_ORIZ
"""
def setRotDamp(duration):
"""
@@ -107,7 +107,7 @@ class KX_ConstraintActuator(SCA_IActuator):
@type option: integer
@param option: Binary combination of the following values:
- 64 : Activate alignment to surface
+ 64 : Activate alignment to surface
128 : Detect material rather than property
256 : No deactivation if ray does not hit target
512 : Activate distance control
diff --git a/source/gameengine/PyDoc/KX_GameObject.py b/source/gameengine/PyDoc/KX_GameObject.py
index efeffab2eed..a5ba5b1d634 100644
--- a/source/gameengine/PyDoc/KX_GameObject.py
+++ b/source/gameengine/PyDoc/KX_GameObject.py
@@ -30,16 +30,11 @@ class KX_GameObject:
Delete this object, can be used inpace of the EndObject Actuator.
The actual removal of the object from the scene is delayed.
"""
- def replaceMesh(mesh_name):
- """
- Replace the mesh of this object with a new mesh. This works the same was as the actuator.
- @type mesh_name: string
- """
- def getVisible():
+ def getVisible(visible):
"""
Gets the game object's visible flag.
- @rtype: boolean
+ @type visible: boolean
"""
def setVisible(visible):
"""
@@ -54,25 +49,16 @@ class KX_GameObject:
@rtype: int
@return: the objects state.
"""
- def setState(state):
+ def setState():
"""
- Sets the game object's state flag.
+ Sets the game object's visible flag.
The bitmasks for states from 1 to 30 can be set with (1<<0, 1<<1, 1<<2 ... 1<<29)
- @type state: integer
+ @type visible: boolean
"""
def setPosition(pos):
"""
- Sets the game object's position.
- Global coordinates for root object, local for child objects.
-
-
- @type pos: [x, y, z]
- @param pos: the new position, in local coordinates.
- """
- def setWorldPosition(pos):
- """
- Sets the game object's position in world coordinates regardless if the object is root or child.
+ Sets the game object's position.
@type pos: [x, y, z]
@param pos: the new position, in world coordinates.
@@ -123,50 +109,6 @@ class KX_GameObject:
@return: The game object's rotation matrix
@note: When using this matrix with Blender.Mathutils.Matrix() types, it will need to be transposed.
"""
- def applyMovement(movement, local = 0):
- """
- Sets the game object's movement.
-
- @type movement: 3d vector.
- @param movement: movement vector.
- @type local: boolean
- @param local: - False: you get the "global" movement ie: relative to world orientation (default).
- - True: you get the "local" movement ie: relative to object orientation.
- """
- def applyRotation(movement, local = 0):
- """
- Sets the game object's rotation.
-
- @type rotation: 3d vector.
- @param rotation: rotation vector.
- @type local: boolean
- @param local: - False: you get the "global" rotation ie: relative to world orientation (default).
- - True: you get the "local" rotation ie: relative to object orientation.
- """
- def applyForce(force, local = 0):
- """
- Sets the game object's force.
-
- This requires a dynamic object.
-
- @type force: 3d vector.
- @param force: force vector.
- @type local: boolean
- @param local: - False: you get the "global" force ie: relative to world orientation (default).
- - True: you get the "local" force ie: relative to object orientation.
- """
- def applyTorque(torque, local = 0):
- """
- Sets the game object's torque.
-
- This requires a dynamic object.
-
- @type torque: 3d vector.
- @param torque: torque vector.
- @type local: boolean
- @param local: - False: you get the "global" torque ie: relative to world orientation (default).
- - True: you get the "local" torque ie: relative to object orientation.
- """
def getLinearVelocity(local = 0):
"""
Gets the game object's linear velocity.
@@ -187,36 +129,12 @@ class KX_GameObject:
This method sets game object's velocity through it's centre of mass,
ie no angular velocity component.
- This requires a dynamic object.
-
@type velocity: 3d vector.
@param velocity: linear velocity vector.
@type local: boolean
@param local: - False: you get the "global" velocity ie: relative to world orientation (default).
- True: you get the "local" velocity ie: relative to object orientation.
"""
- def getAngularVelocity(local = 0):
- """
- Gets the game object's angular velocity.
-
- @type local: boolean
- @param local: - False: you get the "global" velocity ie: relative to world orientation (default).
- - True: you get the "local" velocity ie: relative to object orientation.
- @rtype: list [vx, vy, vz]
- @return: the object's angular velocity.
- """
- def setAngularVelocity(velocity, local = 0):
- """
- Sets the game object's angular velocity.
-
- This requires a dynamic object.
-
- @type velocity: 3d vector.
- @param velocity: angular velocity vector.
- @type local: boolean
- @param local: - False: you get the "global" velocity ie: relative to world orientation (default).
- - True: you get the "local" velocity ie: relative to object orientation.
- """
def getVelocity(point):
"""
Gets the game object's velocity at the specified point.
@@ -362,13 +280,11 @@ class KX_GameObject:
@rtype: L{KX_GameObject}
@return: the first object hit or None if no object or object does not match prop
"""
- def rayCast(objto,objfrom,dist,prop,face,xray,poly):
+ def rayCast(to,from,dist,prop):
"""
Look from a point/object to another point/object and find first object hit within dist that matches prop.
- if poly is 0, returns a 3-tuple with object reference, hit point and hit normal or (None,None,None) if no hit.
- if poly is 1, returns a 4-tuple with in addition a L{KX_PolyProxy} as 4th element.
-
- Ex::
+ Returns a 3-tuple with object reference, hit point and hit normal or (None,None,None) if no hit.
+ Ex:
# shoot along the axis gun-gunAim (gunAim should be collision-free)
ob,point,normal = gun.rayCast(gunAim,None,50)
if ob:
@@ -376,42 +292,21 @@ class KX_GameObject:
Notes:
The ray ignores the object on which the method is called.
- It is casted from/to object center or explicit [x,y,z] points.
-
- The face paremeter determines the orientation of the normal::
- 0 => hit normal is always oriented towards the ray origin (as if you casted the ray from outside)
- 1 => hit normal is the real face normal (only for mesh object, otherwise face has no effect)
-
- The ray has X-Ray capability if xray parameter is 1, otherwise the first object hit (other than self object) stops the ray.
- The prop and xray parameters interact as follow::
- prop off, xray off: return closest hit or no hit if there is no object on the full extend of the ray.
- prop off, xray on : idem.
- prop on, xray off: return closest hit if it matches prop, no hit otherwise.
- 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.
- The L{KX_PolyProxy} 4th element of the return tuple when poly=1 allows to retrieve information on the polygon hit by the ray.
- If there is no hit or the hit object is not a static mesh, None is returned as 4th element.
-
- The ray ignores collision-free objects and faces that dont have the collision flag enabled, you can however use ghost objects.
+ If is casted from/to object center or explicit [x,y,z] points.
+ The ray does not have X-Ray capability: the first object hit (other than self object) stops the ray
+ If a property was specified and the first object hit does not have that property, there is no hit
+ The ray ignores collision-free objects and faces that dont have the collision flag enabled, you can however use ghost objects.
- @param objto: [x,y,z] or object to which the ray is casted
- @type objto: L{KX_GameObject} or 3-tuple
- @param objfrom: [x,y,z] or object from which the ray is casted; None or omitted => use self object center
- @type objfrom: L{KX_GameObject} or 3-tuple or None
+ @param to: [x,y,z] or object to which the ray is casted
+ @type to: L{KX_GameObject} or 3-tuple
+ @param from: [x,y,z] or object from which the ray is casted; None or omitted => use self object center
+ @type from: L{KX_GameObject} or 3-tuple or None
@param dist: max distance to look (can be negative => look behind); 0 or omitted => detect up to to
@type dist: float
@param prop: property name that object must have; can be omitted => detect any object
@type prop: string
- @param face: normal option: 1=>return face normal; 0 or omitted => normal is oriented towards origin
- @type face: int
- @param xray: X-ray option: 1=>skip objects that don't match prop; 0 or omitted => stop on first object
- @type xray: int
- @param poly: polygon option: 1=>return value is a 4-tuple and the 4th element is a L{KX_PolyProxy}
- @type poly: int
- @rtype: 3-tuple (L{KX_GameObject}, 3-tuple (x,y,z), 3-tuple (nx,ny,nz))
- or 4-tuple (L{KX_GameObject}, 3-tuple (x,y,z), 3-tuple (nx,ny,nz), L{KX_PolyProxy})
- @return: (object,hitpoint,hitnormal) or (object,hitpoint,hitnormal,polygon)
- If no hit, returns (None,None,None) or (None,None,None,None)
- If the object hit is not a static mesh, polygon is None
+ @rtype: 3-tuple (L{KX_GameObject}, 3-tuple (x,y,z), 3-tuple (nx,ny,nz))
+ @return: (object,hitpoint,hitnormal) or (None,None,None)
"""
diff --git a/source/gameengine/PyDoc/KX_IpoActuator.py b/source/gameengine/PyDoc/KX_IpoActuator.py
index e2fe3b289e3..1cdab829385 100644
--- a/source/gameengine/PyDoc/KX_IpoActuator.py
+++ b/source/gameengine/PyDoc/KX_IpoActuator.py
@@ -6,7 +6,7 @@ class KX_IpoActuator(SCA_IActuator):
"""
IPO actuator activates an animation.
"""
- def set(mode, startframe, endframe, force):
+ def set(mode, startframe, endframe, mode):
"""
Sets the properties of the actuator.
@@ -16,8 +16,8 @@ class KX_IpoActuator(SCA_IActuator):
@type startframe: integer
@param endframe: last frame to use
@type endframe: integer
- @param force: special mode
- @type force: integer (0=normal, 1=interpret location as force, 2=additive)
+ @param mode: special mode
+ @type mode: integer (0=normal, 1=interpret location as force, 2=additive)
"""
def setProperty(property):
"""
diff --git a/source/gameengine/PyDoc/KX_MeshProxy.py b/source/gameengine/PyDoc/KX_MeshProxy.py
index 03bc36b6ac1..e43fa3598f0 100644
--- a/source/gameengine/PyDoc/KX_MeshProxy.py
+++ b/source/gameengine/PyDoc/KX_MeshProxy.py
@@ -95,21 +95,6 @@ class KX_MeshProxy:
@rtype: L{KX_VertexProxy}
@return: a vertex object.
"""
- def getNumPolygons():
- """
- Returns the number of polygon in the mesh.
-
- @rtype: integer
- """
- def getPolygon(index):
- """
- Gets the specified polygon from the mesh.
-
- @type index: integer
- @param index: polygon number
- @rtype: L{KX_PolyProxy}
- @return: a polygon object.
- """
def reinstancePhysicsMesh():
"""
Updates the physics system with the changed mesh.
diff --git a/source/gameengine/PyDoc/KX_ObjectActuator.py b/source/gameengine/PyDoc/KX_ObjectActuator.py
index b7b76473292..db577d21e6f 100644
--- a/source/gameengine/PyDoc/KX_ObjectActuator.py
+++ b/source/gameengine/PyDoc/KX_ObjectActuator.py
@@ -111,7 +111,9 @@ class KX_ObjectActuator(SCA_IActuator):
For the servo control actuator, this is the target speed.
@rtype: list [vx, vy, vz, local]
- @return: A four item list, containing the vector velocity, and whether the velocity is applied in local coordinates (True) or world coordinates (False)
+ @return: A four item list, containing the vector velocity, and whether
+ the velocity is applied in local coordinates (True) or world
+ coordinates (False)
"""
def setLinearVelocity(vx, vy, vz, local):
"""
diff --git a/source/gameengine/PyDoc/KX_ParentActuator.py b/source/gameengine/PyDoc/KX_ParentActuator.py
index 6d6e0937257..f45bb5d20b1 100644
--- a/source/gameengine/PyDoc/KX_ParentActuator.py
+++ b/source/gameengine/PyDoc/KX_ParentActuator.py
@@ -12,12 +12,11 @@ class KX_ParentActuator(SCA_IActuator):
Object can be either a L{KX_GameObject} or the name of the object.
- @type object: L{KX_GameObject}, string or None
+ @type object: L{KX_GameObject} or string
"""
- def getObject(name_only = 1):
+ def getObject():
"""
Returns the name of the object to change to.
- @type name_only: bool
- @param name_only: optional argument, when 0 return a KX_GameObject
- @rtype: string, KX_GameObject or None if no object is set
+
+ @rtype: string
"""
diff --git a/source/gameengine/PyDoc/KX_PolyProxy.py b/source/gameengine/PyDoc/KX_PolyProxy.py
deleted file mode 100644
index bcd42c2ac2e..00000000000
--- a/source/gameengine/PyDoc/KX_PolyProxy.py
+++ /dev/null
@@ -1,100 +0,0 @@
-# $Id$
-# Documentation for the polygon proxy class
-
-class KX_PolyProxy:
- """
- A polygon holds the index of the vertex forming the poylgon.
-
- Note:
- The polygon attributes are read-only, you need to retrieve the vertex proxy if you want
- to change the vertex settings.
-
- @ivar matname: The name of polygon material, empty if no material.
- @type matname: string
- @ivar material: The material of the polygon
- @type material: L{KX_PolygonMaterial} or KX_BlenderMaterial
- @ivar texture: The texture name of the polygon.
- @type texture: string
- @ivar matid: The material index of the polygon, use this to retrieve vertex proxy from mesh proxy
- @type matid: integer
- @ivar v1: vertex index of the first vertex of the polygon, use this to retrieve vertex proxy from mesh proxy
- @type v1: integer
- @ivar v2: vertex index of the second vertex of the polygon, use this to retrieve vertex proxy from mesh proxy
- @type v2: integer
- @ivar v3: vertex index of the third vertex of the polygon, use this to retrieve vertex proxy from mesh proxy
- @type v3: integer
- @ivar v4: vertex index of the fourth vertex of the polygon, 0 if polygon has only 3 vertex
- use this to retrieve vertex proxy from mesh proxy
- @type v4: integer
- @ivar visible: visible state of the polygon: 1=visible, 0=invisible
- @type visible: integer
- @ivar collide: collide state of the polygon: 1=receives collision, 0=collision free.
- @type collide: integer
- """
-
- def getMaterialName():
- """
- Returns the polygon material name with MA prefix
-
- @rtype: string
- @return: material name
- """
- def getMaterial():
- """
- Returns the polygon material
-
- @rtype: L{KX_PolygonMaterial} or KX_BlenderMaterial
- """
- def getTextureName():
- """
- Returns the polygon texture name
-
- @rtype: string
- @return: texture name
- """
- def getMaterialIndex():
- """
- Returns the material bucket index of the polygon.
- This index and the ones returned by getVertexIndex() are needed to retrieve the vertex proxy from L{KX_MeshProxy}.
-
- @rtype: integer
- @return: the material index in the mesh
- """
- def getNumVertex():
- """
- Returns the number of vertex of the polygon.
-
- @rtype: integer
- @return: number of vertex, 3 or 4.
- """
- def isVisible():
- """
- Returns whether the polygon is visible or not
-
- @rtype: integer
- @return: 0=invisible, 1=visible
- """
- def isCollider():
- """
- Returns whether the polygon is receives collision or not
-
- @rtype: integer
- @return: 0=collision free, 1=receives collision
- """
- def getVertexIndex(vertex):
- """
- Returns the mesh vertex index of a polygon vertex
- This index and the one returned by getMaterialIndex() are needed to retrieve the vertex proxy from L{KX_MeshProxy}.
-
- @type vertex: integer
- @param vertex: index of the vertex in the polygon: 0->3
- @rtype: integer
- @return: mesh vertex index
- """
- def getMesh():
- """
- Returns a mesh proxy
-
- @rtype: L{KX_MeshProxy}
- @return: mesh proxy
- """
diff --git a/source/gameengine/PyDoc/KX_SCA_AddObjectActuator.py b/source/gameengine/PyDoc/KX_SCA_AddObjectActuator.py
index c3b2e947ddb..44f9e051c8c 100644
--- a/source/gameengine/PyDoc/KX_SCA_AddObjectActuator.py
+++ b/source/gameengine/PyDoc/KX_SCA_AddObjectActuator.py
@@ -13,7 +13,7 @@ class KX_SCA_AddObjectActuator(SCA_IActuator):
C{ERROR: GameObject I{OBName} has a AddObjectActuator I{ActuatorName} without object (in 'nonactive' layer)}
"""
- def setObject(object):
+ def setObject(obj):
"""
Sets the game object to add.
@@ -21,18 +21,17 @@ class KX_SCA_AddObjectActuator(SCA_IActuator):
If the object does not exist, this function is ignored.
- object can either be a L{KX_GameObject} or the name of an object or None.
+ obj can either be a L{KX_GameObject} or the name of an object.
- @type object: L{KX_GameObject}, string or None
+ @type obj: L{KX_GameObject} or string
"""
- def getObject(name_only = 0):
+ def getObject():
"""
Returns the name of the game object to be added.
Returns None if no game object has been assigned to be added.
- @type name_only: bool
- @param name_only: optional argument, when 0 return a KX_GameObject
- @rtype: string, KX_GameObject or None if no object is set
+
+ @rtype: string
"""
def setTime(time):
"""
@@ -66,23 +65,6 @@ class KX_SCA_AddObjectActuator(SCA_IActuator):
@rtype: list [vx, vy, vz]
"""
- def setAngularVelocity(vx, vy, vz):
- """
- Sets the initial angular velocity of added objects.
-
- @type vx: float
- @param vx: the x component of the initial angular velocity.
- @type vy: float
- @param vy: the y component of the initial angular velocity.
- @type vz: float
- @param vz: the z component of the initial angular velocity.
- """
- def getAngularVelocity():
- """
- Returns the initial angular velocity of added objects.
-
- @rtype: list [vx, vy, vz]
- """
def getLastCreatedObject():
"""
Returns the last object created by this actuator.
diff --git a/source/gameengine/PyDoc/KX_SCA_ReplaceMeshActuator.py b/source/gameengine/PyDoc/KX_SCA_ReplaceMeshActuator.py
index 498f6072e23..eb00a91a4ce 100644
--- a/source/gameengine/PyDoc/KX_SCA_ReplaceMeshActuator.py
+++ b/source/gameengine/PyDoc/KX_SCA_ReplaceMeshActuator.py
@@ -59,9 +59,8 @@ class KX_SCA_ReplaceMeshActuator(SCA_IActuator):
def setMesh(name):
"""
Sets the name of the mesh that will replace the current one.
- When the name is None it will unset the mesh value so no action is taken.
- @type name: string or None
+ @type name: string
"""
def getMesh():
"""
@@ -69,6 +68,6 @@ class KX_SCA_ReplaceMeshActuator(SCA_IActuator):
Returns None if no mesh has been scheduled to be added.
- @rtype: string or None
+ @rtype: string
"""
diff --git a/source/gameengine/PyDoc/KX_TrackToActuator.py b/source/gameengine/PyDoc/KX_TrackToActuator.py
index 948302991b7..39fb99ec2e2 100644
--- a/source/gameengine/PyDoc/KX_TrackToActuator.py
+++ b/source/gameengine/PyDoc/KX_TrackToActuator.py
@@ -18,16 +18,16 @@ class KX_TrackToActuator(SCA_IActuator):
"""
Sets the object to track.
- @type object: L{KX_GameObject}, string or None
+ @type object: L{KX_GameObject} or string
@param object: Either a reference to a game object or the name of the object to track.
"""
- def getObject(name_only):
+ def getObject():
"""
Returns the name of the object to track.
- @type name_only: bool
- @param name_only: optional argument, when 0 return a KX_GameObject
- @rtype: string, KX_GameObject or None if no object is set
+ Returns None if no object has been set to track.
+
+ @rtype: string
"""
def setTime(time):
"""
diff --git a/source/gameengine/PyDoc/Rasterizer.py b/source/gameengine/PyDoc/Rasterizer.py
index 6a67cdcc71b..f0e48b6ed43 100644
--- a/source/gameengine/PyDoc/Rasterizer.py
+++ b/source/gameengine/PyDoc/Rasterizer.py
@@ -37,11 +37,7 @@ Example Uses an L{SCA_MouseSensor}, and two L{KX_ObjectActuator}s to implement M
# Centre the mouse
Rasterizer.setMousePosition(Rasterizer.getWindowWidth()/2, Rasterizer.getWindowHeight()/2)
-@group Material Types: KX_TEXFACE_MATERIAL, KX_BLENDER_MULTITEX_MATERIAL, KX_BLENDER_GLSL_MATERIAL
-@var KX_TEXFACE_MATERIAL: Materials as defined by the texture face settings.
-@var KX_BLENDER_MULTITEX_MATERIAL: Materials approximating blender materials with multitexturing.
-@var KX_BLENDER_GLSL_MATERIAL: Materials approximating blender materials with GLSL.
-
+
"""
def getWindowWidth():
@@ -88,8 +84,7 @@ def setMousePosition(x, y):
"""
Sets the mouse cursor position.
- @type x: integer
- @type y: integer
+ @type x, y: integer
"""
def setBackgroundColor(rgba):
@@ -150,47 +145,3 @@ def getFocalLength():
@rtype: float
"""
-
-def setMaterialMode(mode):
- """
- Set the material mode to use for OpenGL rendering.
-
- @type mode: KX_TEXFACE_MATERIAL, KX_BLENDER_MULTITEX_MATERIAL, KX_BLENDER_GLSL_MATERIAL
- @note: Changes will only affect newly created scenes.
- """
-
-def getMaterialMode(mode):
- """
- Get the material mode to use for OpenGL rendering.
-
- @rtype: KX_TEXFACE_MATERIAL, KX_BLENDER_MULTITEX_MATERIAL, KX_BLENDER_GLSL_MATERIAL
- """
-
-def setGLSLMaterialSetting(setting, enable):
- """
- Enables or disables a GLSL material setting.
-
- @type setting: string (lights, shaders, shadows, ramps, nodes, extra_textures)
- @type enable: boolean
- """
-
-def getGLSLMaterialSetting(setting, enable):
- """
- Get the state of a GLSL material setting.
-
- @type setting: string (lights, shaders, shadows, ramps, nodes, extra_textures)
- @rtype: boolean
- """
-
-def drawLine(fromVec,toVec,color):
- """
- Draw a line in the 3D scene.
-
- @param fromVec: the origin of the line
- @type fromVec: list [x, y, z]
- @param toVec: the end of the line
- @type toVec: list [x, y, z]
- @param color: the color of the line
- @type color: list [r, g, b]
- """
-
diff --git a/source/gameengine/PyDoc/SCA_DelaySensor.py b/source/gameengine/PyDoc/SCA_DelaySensor.py
deleted file mode 100644
index b99ed08bed5..00000000000
--- a/source/gameengine/PyDoc/SCA_DelaySensor.py
+++ /dev/null
@@ -1,73 +0,0 @@
-# $Id$
-# Documentation for SCA_DelaySensor
-from SCA_ISensor import *
-
-class SCA_DelaySensor(SCA_ISensor):
- """
- The Delay sensor generates positive and negative triggers at precise time,
- expressed in number of frames. The delay parameter defines the length
- of the initial OFF period. A positive trigger is generated at the end of this period.
- The duration parameter defines the length of the ON period following the OFF period.
- There is a negative trigger at the end of the ON period. If duration is 0, the sensor
- stays ON and there is no negative trigger.
- The sensor runs the OFF-ON cycle once unless the repeat option is set: the
- OFF-ON cycle repeats indefinately (or the OFF cycle if duration is 0).
- Use SCA_ISensor::reset() at any time to restart sensor.
-
- Properties:
-
- @ivar delay: length of the initial OFF period as number of frame, 0 for immediate trigger.
- @type delay: integer.
- @ivar duration: length of the ON period in number of frame after the initial OFF period.
- If duration is greater than 0, a negative trigger is sent at the end of the ON pulse.
- @type duration: integer
- @ivar repeat: 1 if the OFF-ON cycle should be repeated indefinately, 0 if it should run once.
- @type repeat: integer
-
- """
- def setDelay(delay):
- """
- DEPRECATED: use the delay property
- Set the initial delay before the positive trigger.
-
- @param delay: length of the initial OFF period as number of frame, 0 for immediate trigger
- @type delay: integer
- """
- def setDuration(duration):
- """
- DEPRECATED: use the duration property
- Set the duration of the ON pulse after initial delay and the generation of the positive trigger.
- If duration is greater than 0, a negative trigger is sent at the end of the ON pulse.
-
- @param duration: length of the ON period in number of frame after the initial OFF period
- @type duration: integer
- """
- def setRepeat(repeat):
- """
- DEPRECATED: use the repeat property
- Set if the sensor repeat mode.
-
- @param repeat: 1 if the OFF-ON cycle should be repeated indefinately, 0 if it should run once.
- @type repeat: integer
- """
- def getDelay():
- """
- DEPRECATED: use the delay property
- Return the delay parameter value.
-
- @rtype: integer
- """
- def getDuration():
- """
- DEPRECATED: use the duration property
- Return the duration parameter value
-
- @rtype: integer
- """
- def getRepeat():
- """
- DEPRECATED: use the repeat property
- Return the repeat parameter value
-
- @rtype: KX_TRUE or KX_FALSE
- """
diff --git a/source/gameengine/PyDoc/SCA_ILogicBrick.py b/source/gameengine/PyDoc/SCA_ILogicBrick.py
index 18cb900f28d..ea09fcaea37 100644
--- a/source/gameengine/PyDoc/SCA_ILogicBrick.py
+++ b/source/gameengine/PyDoc/SCA_ILogicBrick.py
@@ -5,9 +5,6 @@ from KX_GameObject import *
class SCA_ILogicBrick:
"""
Base class for all logic bricks.
-
- @ivar executePriority: This determines the order controllers are evaluated, and actuators are activated (lower priority is executed first).
- @type executePriority: int
"""
def getOwner():
@@ -16,8 +13,6 @@ class SCA_ILogicBrick:
@rtype: L{KX_GameObject}
"""
-
- #--The following methods are deprecated--
def setExecutePriority(priority):
"""
Sets the priority of this logic brick.
@@ -25,8 +20,6 @@ class SCA_ILogicBrick:
This determines the order controllers are evaluated, and actuators are activated.
Bricks with lower priority will be executed first.
- Deprecated: Use the "executePriority" property instead.
-
@type priority: integer
@param priority: the priority of this logic brick.
"""
@@ -34,8 +27,6 @@ class SCA_ILogicBrick:
"""
Gets the execution priority of this logic brick.
- Deprecated: Use the "executePriority" property instead.
-
@rtype: integer
@return: this logic bricks current priority.
"""
diff --git a/source/gameengine/PyDoc/SCA_ISensor.py b/source/gameengine/PyDoc/SCA_ISensor.py
index ab35996aa50..0ebc2debb31 100644
--- a/source/gameengine/PyDoc/SCA_ISensor.py
+++ b/source/gameengine/PyDoc/SCA_ISensor.py
@@ -5,43 +5,11 @@ from SCA_ILogicBrick import *
class SCA_ISensor(SCA_ILogicBrick):
"""
Base class for all sensor logic bricks.
-
- @ivar usePosPulseMode: Flag to turn positive pulse mode on and off.
- @type usePosPulseMode: boolean
- @ivar useNegPulseMode: Flag to turn negative pulse mode on and off.
- @type useNegPulseMode: boolean
- @ivar frequency: The frequency for pulse mode sensors.
- @type frequency: int
- @ivar level: Flag to set whether to detect level or edge transition when entering a state.
- It makes a difference only in case of logic state transition (state actuator).
- A level detector will immediately generate a pulse, negative or positive
- depending on the sensor condition, as soon as the state is activated.
- A edge detector will wait for a state change before generating a pulse.
- @type level: boolean
- @ivar invert: Flag to set if this sensor activates on positive or negative events.
- @type invert: boolean
- @ivar triggered: True if this sensor brick is in a positive state. (Read only)
- @type triggered: boolean
- @ivar positive: True if this sensor brick is in a positive state. (Read only)
- @type positive: boolean
"""
- def reset():
- """
- Reset sensor internal state, effect depends on the type of sensor and settings.
-
- The sensor is put in its initial state as if it was just activated.
- """
-
- #--The following methods are deprecated--
def isPositive():
"""
- True if this sensor brick is in a positive state.
- """
-
- def isTriggered():
- """
- True if this sensor brick has triggered the current controller.
+ True if this sensor brick has been activated.
"""
def getUsePosPulseMode():
@@ -109,3 +77,4 @@ class SCA_ISensor(SCA_ILogicBrick):
@param level: Detect level instead of edge? (KX_TRUE, KX_FALSE)
@type level: boolean
"""
+
diff --git a/source/gameengine/PyDoc/SCA_JoystickSensor.py b/source/gameengine/PyDoc/SCA_JoystickSensor.py
deleted file mode 100644
index 111ee7f4cfa..00000000000
--- a/source/gameengine/PyDoc/SCA_JoystickSensor.py
+++ /dev/null
@@ -1,163 +0,0 @@
-# $Id: SCA_RandomSensor.py 15444 2008-07-05 17:05:05Z lukep $
-# Documentation for SCA_RandomSensor
-from SCA_ISensor import *
-
-class SCA_JoystickSensor(SCA_ISensor):
- """
- This sensor detects player joystick events.
-
- Properties:
-
- @ivar axisPosition: (read-only) The state of the joysticks axis as a list of 4 values, each spesifying the value of an axis between -32767 and 32767 depending on how far the axis is pushed, 0 for nothing.
- The first 2 values are used by most joysticks and gamepads for directional control. 3rd and 4th values are only on some joysticks and can be used for arbitary controls.
- left:[-32767, 0, ...], right:[32767, 0, ...], up:[0, -32767, ...], down:[0, 32767, ...]
- @type axisPosition: [integer, integer, integer, integer]
- @ivar numAxis: (read-only) The number of axes for the joystick at this index.
- @type numAxis: integer
- @ivar numButtons: (read-only) The number of buttons for the joystick at this index.
- @type numButtons: integer
- @ivar numHats: (read-only) The number of hats for the joystick at this index.
- @type numHats: integer
- @ivar connected: (read-only) True if a joystick is connected at this joysticks index.
- @type connected: boolean
- @ivar index: The joystick index to use (from 0 to 7). The first joystick is always 0.
- @type index: integer
- @ivar threshold: Axis threshold. Joystick axis motion below this threshold wont trigger an event. Use values between (0 and 32767), lower values are more sensitive.
- @type threshold: integer
- @ivar button: The button index the sensor reacts to (first button = 0). When the "All Events" toggle is set, this option has no effect.
- @type button: integer
- @ivar axis: The axis this sensor reacts to, as a list of two values [axisIndex, axisDirection]
- axisIndex: the axis index to use when detecting axis movement, 1=primary directional control, 2=secondary directional control.
- axisDirection: 0=right, 1=up, 2=left, 3=down
- @type axis: [integer, integer]
- @ivar hat: The hat the sensor reacts to, as a list of two values: [hatIndex, hatDirection]
- hatIndex: the hat index to use when detecting hat movement, 1=primary hat, 2=secondary hat.
- hatDirection: 0-11
- @type hat: [integer, integer]
- """
-
- def getButtonActiveList():
- """
- Returns a list containing the indicies of the currently pressed buttons.
- @rtype: list
- """
- def getButtonStatus(buttonIndex):
- """
- Returns a bool of the current pressed state of the specified button.
- @param buttonIndex: the button index, 0=first button
- @type buttonIndex: integer
- @rtype: bool
- """
- def getIndex():
- """
- DEPRECATED: use the 'index' property.
- Returns the joystick index to use (from 1 to 8).
- @rtype: integer
- """
- def setIndex(index):
- """
- DEPRECATED: use the 'index' property.
- Sets the joystick index to use.
- @param index: The index of this joystick sensor, Clamped between 1 and 8.
- @type index: integer
- @note: This is only useful when you have more then 1 joystick connected to your computer - multiplayer games.
- """
- def getAxis():
- """
- DEPRECATED: use the 'axis' property.
- Returns the current axis this sensor reacts to. See L{getAxisValue()<SCA_JoystickSensor.getAxisValue>} for the current axis state.
- @rtype: list
- @return: 2 values returned are [axisIndex, axisDirection] - see L{setAxis()<SCA_JoystickSensor.setAxis>} for their purpose.
- @note: When the "All Events" toggle is set, this option has no effect.
- """
- def setAxis(axisIndex, axisDirection):
- """
- DEPRECATED: use the 'axis' property.
- @param axisIndex: Set the axis index to use when detecting axis movement.
- @type axisIndex: integer from 1 to 2
- @param axisDirection: Set the axis direction used for detecting motion. 0:right, 1:up, 2:left, 3:down.
- @type axisDirection: integer from 0 to 3
- @note: When the "All Events" toggle is set, this option has no effect.
- """
- def getAxisValue():
- """
- DEPRECATED: use the 'axisPosition' property.
- Returns the state of the joysticks axis. See differs to L{getAxis()<SCA_JoystickSensor.getAxis>} returning the current state of the joystick.
- @rtype: list
- @return: 4 values, each spesifying the value of an axis between -32767 and 32767 depending on how far the axis is pushed, 0 for nothing.
-
- The first 2 values are used by most joysticks and gamepads for directional control. 3rd and 4th values are only on some joysticks and can be used for arbitary controls.
-
- left:[-32767, 0, ...], right:[32767, 0, ...], up:[0, -32767, ...], down:[0, 32767, ...]
- @note: Some gamepads only set the axis on and off like a button.
- """
- def getThreshold():
- """
- DEPRECATED: use the 'threshold' property.
- Get the axis threshold. See L{setThreshold()<SCA_JoystickSensor.setThreshold>} for details.
- @rtype: integer
- """
- def setThreshold(threshold):
- """
- DEPRECATED: use the 'threshold' property.
- Set the axis threshold.
- @param threshold: Joystick axis motion below this threshold wont trigger an event. Use values between (0 and 32767), lower values are more sensitive.
- @type threshold: integer
- """
- def getButton():
- """
- DEPRECATED: use the 'button' property.
- Returns the button index the sensor reacts to. See L{getButtonValue()<SCA_JoystickSensor.getButtonValue>} for a list of pressed buttons.
- @rtype: integer
- @note: When the "All Events" toggle is set, this option has no effect.
- """
- def setButton(index):
- """
- DEPRECATED: use the 'button' property.
- Sets the button index the sensor reacts to when the "All Events" option is not set.
- @note: When the "All Events" toggle is set, this option has no effect.
- """
- def getButtonValue():
- """
- DEPRECATED: use the 'getButtonActiveList' method.
- Returns a list containing the indicies of the currently pressed buttons.
- @rtype: list
- """
- def getHat():
- """
- DEPRECATED: use the 'hat' property.
- Returns the current hat direction this sensor is set to.
- [hatNumber, hatDirection].
- @rtype: list
- @note: When the "All Events" toggle is set, this option has no effect.
- """
- def setHat(index,direction):
- """
- DEPRECATED: use the 'hat' property.
- Sets the hat index the sensor reacts to when the "All Events" option is not set.
- @type index: integer
- """
- def getNumAxes():
- """
- DEPRECATED: use the 'numAxis' property.
- Returns the number of axes for the joystick at this index.
- @rtype: integer
- """
- def getNumButtons():
- """
- DEPRECATED: use the 'numButtons' property.
- Returns the number of buttons for the joystick at this index.
- @rtype: integer
- """
- def getNumHats():
- """
- DEPRECATED: use the 'numHats' property.
- Returns the number of hats for the joystick at this index.
- @rtype: integer
- """
- def isConnected():
- """
- DEPRECATED: use the 'connected' property.
- Returns True if a joystick is detected at this joysticks index.
- @rtype: bool
- """
diff --git a/source/gameengine/PyDoc/SCA_KeyboardSensor.py b/source/gameengine/PyDoc/SCA_KeyboardSensor.py
index f6a7a7d8a97..2f741f7d6a2 100644
--- a/source/gameengine/PyDoc/SCA_KeyboardSensor.py
+++ b/source/gameengine/PyDoc/SCA_KeyboardSensor.py
@@ -7,99 +7,44 @@ class SCA_KeyboardSensor(SCA_ISensor):
A keyboard sensor detects player key presses.
See module L{GameKeys} for keycode values.
-
- @ivar key: The key code this sensor is looking for.
- @type key: keycode from L{GameKeys} module
- @ivar hold1: The key code for the first modifier this sensor is looking for.
- @type hold1: keycode from L{GameKeys} module
- @ivar hold2: The key code for the second modifier this sensor is looking for.
- @type hold2: keycode from L{GameKeys} module
- @ivar toggleProperty: The name of the property that indicates whether or not to log keystrokes as a string.
- @type toggleProperty: string
- @ivar targetProperty: The name of the property that receives keystrokes in case in case a string is logged.
- @type targetProperty: string
- @ivar useAllKeys: Flag to determine whether or not to accept all keys.
- @type useAllKeys: boolean
"""
- def getEventList():
- """
- Get a list of pressed keys that have either been pressed, or just released, or are active this frame.
-
- @rtype: list of key status. [[keycode, status]]
- @return: A list of keyboard events
- """
-
- def getKeyStatus(keycode):
- """
- Get the status of a key.
-
- @rtype: key state (KX_NO_INPUTSTATUS, KX_JUSTACTIVATED, KX_ACTIVE or KX_JUSTRELEASED)
- @return: The state of the given key
- @type keycode: integer
- @param keycode: The code that represents the key you want to get the state of
- """
- #--The following methods are deprecated--
def getKey():
"""
Returns the key code this sensor is looking for.
-
- Deprecated: Use the "key" property instead.
-
- @rtype: keycode from L{GameKeys} module
"""
def setKey(keycode):
"""
Set the key this sensor should listen for.
- Deprecated: Use the "key" property instead.
-
@type keycode: keycode from L{GameKeys} module
"""
def getHold1():
"""
Returns the key code for the first modifier this sensor is looking for.
-
- Deprecated: Use the "hold1" property instead.
-
- @rtype: keycode from L{GameKeys} module
"""
- def setHold1(keycode):
+ def setHold1():
"""
Sets the key code for the first modifier this sensor should look for.
-
- Deprecated: Use the "hold1" property instead.
-
- @type keycode: keycode from L{GameKeys} module
"""
def getHold2():
"""
Returns the key code for the second modifier this sensor is looking for.
-
- Deprecated: Use the "hold2" property instead.
-
- @rtype: keycode from L{GameKeys} module
"""
- def setHold2(keycode):
+ def setHold2():
"""
Sets the key code for the second modifier this sensor should look for.
-
- Deprecated: Use the "hold2" property instead.
-
- @type keycode: keycode from L{GameKeys} module
"""
def getPressedKeys():
"""
Get a list of keys that have either been pressed, or just released this frame.
- Deprecated: Use getEventList() instead.
-
@rtype: list of key status. [[keycode, status]]
"""
@@ -107,7 +52,7 @@ class SCA_KeyboardSensor(SCA_ISensor):
"""
Get a list of currently pressed keys that have either been pressed, or just released
- Deprecated: Use getEventList() instead.
-
@rtype: list of key status. [[keycode, status]]
- """ \ No newline at end of file
+ """
+
+
diff --git a/source/gameengine/PyDoc/SCA_MouseSensor.py b/source/gameengine/PyDoc/SCA_MouseSensor.py
index 9550cbb4105..06b261f67fa 100644
--- a/source/gameengine/PyDoc/SCA_MouseSensor.py
+++ b/source/gameengine/PyDoc/SCA_MouseSensor.py
@@ -5,20 +5,10 @@ from SCA_ISensor import *
class SCA_MouseSensor(SCA_ISensor):
"""
Mouse Sensor logic brick.
-
- Properties:
-
- @ivar position: current [x,y] coordinates of the mouse, in frame coordinates (pixels)
- @type position: [integer,interger]
- @ivar mode: sensor mode: 1=KX_MOUSESENSORMODE_LEFTBUTTON 2=KX_MOUSESENSORMODE_MIDDLEBUTTON
- 3=KX_MOUSESENSORMODE_RIGHTBUTTON 4=KX_MOUSESENSORMODE_WHEELUP
- 5=KX_MOUSESENSORMODE_WHEELDOWN 9=KX_MOUSESENSORMODE_MOVEMENT
- @type mode: integer
"""
def getXPosition():
"""
- DEPRECATED: use the position property
Gets the x coordinate of the mouse.
@rtype: integer
@@ -26,7 +16,6 @@ class SCA_MouseSensor(SCA_ISensor):
"""
def getYPosition():
"""
- DEPRECATED: use the position property
Gets the y coordinate of the mouse.
@rtype: integer
diff --git a/source/gameengine/PyDoc/SCA_PropertyActuator.py b/source/gameengine/PyDoc/SCA_PropertyActuator.py
index 52aefcae651..dc1233ddfb7 100644
--- a/source/gameengine/PyDoc/SCA_PropertyActuator.py
+++ b/source/gameengine/PyDoc/SCA_PropertyActuator.py
@@ -5,17 +5,9 @@ from SCA_IActuator import *
class SCA_PropertyActuator(SCA_IActuator):
"""
Property Actuator
-
- Properties:
-
- @ivar property: the property on which to operate.
- @type property: string
- @ivar value: the value with which the actuator operates.
- @type value: string
"""
def setProperty(prop):
"""
- DEPRECATED: use the 'property' property
Set the property on which to operate.
If there is no property of this name, the call is ignored.
@@ -25,14 +17,12 @@ class SCA_PropertyActuator(SCA_IActuator):
"""
def getProperty():
"""
- DEPRECATED: use the 'property' property
Returns the name of the property on which to operate.
@rtype: string
"""
def setValue(value):
"""
- DEPRECATED: use the 'value' property
Set the value with which the actuator operates.
If the value is not compatible with the type of the
@@ -42,7 +32,6 @@ class SCA_PropertyActuator(SCA_IActuator):
"""
def getValue():
"""
- DEPRECATED: use the 'value' property
Gets the value with which this actuator operates.
@rtype: string
diff --git a/source/gameengine/PyDoc/SCA_PropertySensor.py b/source/gameengine/PyDoc/SCA_PropertySensor.py
index 949ffd3b703..22de8d8b986 100644
--- a/source/gameengine/PyDoc/SCA_PropertySensor.py
+++ b/source/gameengine/PyDoc/SCA_PropertySensor.py
@@ -5,22 +5,10 @@ from SCA_ISensor import *
class SCA_PropertySensor(SCA_ISensor):
"""
Activates when the game object property matches.
-
- Properties:
-
- @ivar type: type of check on the property:
- KX_PROPSENSOR_EQUAL(1), KX_PROPSENSOR_NOTEQUAL(2), KX_PROPSENSOR_INTERVAL(3),
- KX_PROPSENSOR_CHANGED(4), KX_PROPSENSOR_EXPRESSION(5)
- @type type: integer
- @ivar property: the property with which the sensor operates.
- @type property: string
- @ivar value: the value with which the sensor compares to the value of the property.
- @type value: string
"""
def getType():
"""
- DEPRECATED: use the type property
Gets when to activate this sensor.
@return: KX_PROPSENSOR_EQUAL, KX_PROPSENSOR_NOTEQUAL,
@@ -30,7 +18,6 @@ class SCA_PropertySensor(SCA_ISensor):
def setType(checktype):
"""
- DEPRECATED: use the type property
Set the type of check to perform.
@type checktype: KX_PROPSENSOR_EQUAL, KX_PROPSENSOR_NOTEQUAL,
@@ -40,7 +27,6 @@ class SCA_PropertySensor(SCA_ISensor):
def getProperty():
"""
- DEPRECATED: use the property property
Return the property with which the sensor operates.
@rtype: string
@@ -48,7 +34,6 @@ class SCA_PropertySensor(SCA_ISensor):
"""
def setProperty(name):
"""
- DEPRECATED: use the property property
Sets the property with which to operate. If there is no property
of that name, this call is ignored.
@@ -56,7 +41,6 @@ class SCA_PropertySensor(SCA_ISensor):
"""
def getValue():
"""
- DEPRECATED: use the value property
Return the value with which the sensor compares to the value of the property.
@rtype: string
@@ -64,7 +48,6 @@ class SCA_PropertySensor(SCA_ISensor):
"""
def setValue(value):
"""
- DEPRECATED: use the value property
Set the value with which the sensor operates. If the value
is not compatible with the type of the property, the subsequent
action is ignored.
diff --git a/source/gameengine/PyDoc/SCA_PythonController.py b/source/gameengine/PyDoc/SCA_PythonController.py
index 06f2b7e9d1d..6d91736d636 100644
--- a/source/gameengine/PyDoc/SCA_PythonController.py
+++ b/source/gameengine/PyDoc/SCA_PythonController.py
@@ -6,14 +6,6 @@ class SCA_PythonController(SCA_IController):
"""
A Python controller uses a Python script to activate it's actuators,
based on it's sensors.
-
- Properties:
-
- @ivar script: the Python script this controller executes
- @type script: string, read-only
- @ivar state: the controllers state bitmask.
- This can be used with the GameObject's state to test if the controller is active.
- @type state: integer
"""
def getSensors():
@@ -44,7 +36,6 @@ class SCA_PythonController(SCA_IController):
"""
def getScript():
"""
- DEPRECATED: use the script property
Gets the Python script this controller executes.
@rtype: string
@@ -57,7 +48,6 @@ class SCA_PythonController(SCA_IController):
"""
def getState():
"""
- DEPRECATED: use the state property
Get the controllers state bitmask, this can be used with the GameObject's state to test if the the controller is active.
This for instance will always be true however you could compare with a previous state to see when the state was activated.
GameLogic.getCurrentController().getState() & GameLogic.getCurrentController().getOwner().getState()
diff --git a/source/gameengine/PyDoc/SCA_RandomActuator.py b/source/gameengine/PyDoc/SCA_RandomActuator.py
index 000a1af7846..353b398b1ff 100644
--- a/source/gameengine/PyDoc/SCA_RandomActuator.py
+++ b/source/gameengine/PyDoc/SCA_RandomActuator.py
@@ -5,35 +5,9 @@ from SCA_IActuator import *
class SCA_RandomActuator(SCA_IActuator):
"""
Random Actuator
-
- Properties:
-
- @ivar seed: Seed of the random number generator.
- Equal seeds produce equal series. If the seed is 0,
- the generator will produce the same value on every call.
- @type seed: integer
- @ivar para1: the first parameter of the active distribution.
- Refer to the documentation of the generator types for the meaning
- of this value.
- @type para1: float, read-only
- @ivar para2: the second parameter of the active distribution.
- Refer to the documentation of the generator types for the meaning
- of this value.
- @type para2: float, read-only
- @ivar distribution: distribution type:
- 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
- @type distribution: integer, read-only
- @ivar property: the name of the property to set with the random value.
- If the generator and property types do not match, the assignment is ignored.
- @type property: string
-
"""
def setSeed(seed):
"""
- DEPRECATED: use the seed property
Sets the seed of the random number generator.
Equal seeds produce equal series. If the seed is 0,
@@ -43,14 +17,12 @@ class SCA_RandomActuator(SCA_IActuator):
"""
def getSeed():
"""
- DEPRECATED: use the seed property
Returns the initial seed of the generator.
@rtype: integer
"""
def getPara1():
"""
- DEPRECATED: use the para1 property
Returns the first parameter of the active distribution.
Refer to the documentation of the generator types for the meaning
@@ -60,7 +32,6 @@ class SCA_RandomActuator(SCA_IActuator):
"""
def getPara2():
"""
- DEPRECATED: use the para2 property
Returns the second parameter of the active distribution.
Refer to the documentation of the generator types for the meaning
@@ -70,7 +41,6 @@ class SCA_RandomActuator(SCA_IActuator):
"""
def getDistribution():
"""
- DEPRECATED: use the distribution property
Returns the type of random distribution.
@rtype: distribution type
@@ -81,7 +51,6 @@ class SCA_RandomActuator(SCA_IActuator):
"""
def setProperty(property):
"""
- DEPRECATED: use the property property
Set the property to which the random value is assigned.
If the generator and property types do not match, the assignment is ignored.
@@ -91,7 +60,6 @@ class SCA_RandomActuator(SCA_IActuator):
"""
def getProperty():
"""
- DEPRECATED: use the property property
Returns the name of the property to set.
@rtype: string
diff --git a/source/gameengine/PyDoc/SConscript b/source/gameengine/PyDoc/SConscript
deleted file mode 100644
index ac0b163d7bd..00000000000
--- a/source/gameengine/PyDoc/SConscript
+++ /dev/null
@@ -1,28 +0,0 @@
-#!/usr/bin/python
-Import ('env')
-
-
-from optparse import OptionParser
-try:
- import epydoc
-except ImportError:
- print "No epydoc install detected, Python API Docs will not be generated "
-if epydoc:
- from epydoc.docbuilder import build_doc_index
- from epydoc import cli
- names = env.Glob("source/gameengine/PyDoc/*.py")
- docindex = build_doc_index(names)
- optvalues = cli.OPTION_DEFAULTS
- optvalues["verbose"] = 1
- optvalues["target"] = env["BF_DOCDIR"]+"/BGE_API/"
- optvalues["url"] = "http://www.blender.org"
- optvalues["top"] = "Game Engine API"
- optvalues["name"] = "Blender"
- optvalues["noprivate"] = 1
- optvalues["noframes"] = 1
- optvalues["names"] = names
- optparser = OptionParser()
- optparser.set_defaults(**optvalues)
- (options, args) = optparser.parse_args([])
- cli.write_html(docindex, options)
-
diff --git a/source/gameengine/PyDoc/epy_docgen.sh b/source/gameengine/PyDoc/epy_docgen.sh
index b243101ddcb..7fb5e49c996 100644
--- a/source/gameengine/PyDoc/epy_docgen.sh
+++ b/source/gameengine/PyDoc/epy_docgen.sh
@@ -7,5 +7,5 @@
# set posix locale so regex works properly for [A-Z]*.py
LC_ALL=POSIX
-epydoc --debug -v -o BPY_GE --url "http://www.blender.org" --top GameLogic \
+epydoc -v -o BPY_GE --url "http://www.blender.org" --top GameLogic \
--name "Blender GameEngine" --no-private --no-frames *.py
diff --git a/source/gameengine/Rasterizer/Makefile b/source/gameengine/Rasterizer/Makefile
index 917f70c7108..e3b1f274ee5 100644
--- a/source/gameengine/Rasterizer/Makefile
+++ b/source/gameengine/Rasterizer/Makefile
@@ -49,6 +49,10 @@ ifeq ($(OS),darwin)
CPPFLAGS += -fpascal-strings
endif
+ifeq ($(WITH_BF_GLEXT),true)
+ CPPFLAGS += -DWITH_GLEXT
+endif
+
###############
SOURCEDIR = source/gameengine/Rasterizer
diff --git a/source/gameengine/Rasterizer/RAS_2DFilterManager.cpp b/source/gameengine/Rasterizer/RAS_2DFilterManager.cpp
index 282c7306285..ef206332057 100644
--- a/source/gameengine/Rasterizer/RAS_2DFilterManager.cpp
+++ b/source/gameengine/Rasterizer/RAS_2DFilterManager.cpp
@@ -58,7 +58,7 @@
RAS_2DFilterManager::RAS_2DFilterManager():
texturewidth(-1), textureheight(-1),
canvaswidth(-1), canvasheight(-1),
-numberoffilters(0), need_tex_update(true)
+numberoffilters(0)
{
isshadersupported = GLEW_ARB_shader_objects &&
GLEW_ARB_fragment_shader && GLEW_ARB_multitexture;
@@ -78,7 +78,6 @@ numberoffilters(0), need_tex_update(true)
m_gameObjects[passindex] = NULL;
}
texname[0] = texname[1] = texname[2] = -1;
- errorprinted= false;
}
RAS_2DFilterManager::~RAS_2DFilterManager()
@@ -86,107 +85,76 @@ RAS_2DFilterManager::~RAS_2DFilterManager()
FreeTextures();
}
-void RAS_2DFilterManager::PrintShaderErrors(unsigned int shader, const char *task, const char *code)
+unsigned int RAS_2DFilterManager::CreateShaderProgram(char* shadersource)
{
- GLcharARB log[5000];
- GLsizei length = 0;
- const char *c, *pos, *end;
- int line = 1;
+ GLuint program = 0;
+ GLuint fShader = glCreateShaderObjectARB(GL_FRAGMENT_SHADER);
+ GLint success;
- if(errorprinted)
- return;
-
- errorprinted= true;
-
- glGetInfoLogARB(shader, sizeof(log), &length, log);
- end = code + strlen(code);
+ glShaderSourceARB(fShader, 1, (const char**)&shadersource, NULL);
- 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++;
- }
- printf("%s", c);
-
- printf("%s\n", log);
-}
-
-unsigned int RAS_2DFilterManager::CreateShaderProgram(const char* shadersource)
-{
- GLuint program = 0;
- GLuint fShader = glCreateShaderObjectARB(GL_FRAGMENT_SHADER);
- GLint success;
+ glCompileShaderARB(fShader);
- glShaderSourceARB(fShader, 1, (const char**)&shadersource, NULL);
-
- glCompileShaderARB(fShader);
-
-
- glGetObjectParameterivARB(fShader, GL_COMPILE_STATUS, &success);
- if(!success)
- {
- /*Shader Comile Error*/
- PrintShaderErrors(fShader, "compile", shadersource);
- return 0;
- }
-
- program = glCreateProgramObjectARB();
- glAttachObjectARB(program, fShader);
+ glGetObjectParameterivARB(fShader, GL_COMPILE_STATUS, &success);
+ if(!success)
+ {
+ /*Shader Comile Error*/
+ std::cout << "2dFilters - Shader compile error" << std::endl;
+ return 0;
+ }
+
+ program = glCreateProgramObjectARB();
+ glAttachObjectARB(program, fShader);
- glLinkProgramARB(program);
- glGetObjectParameterivARB(program, GL_LINK_STATUS, &success);
- if (!success)
- {
- /*Program Link Error*/
- PrintShaderErrors(fShader, "link", shadersource);
- return 0;
- }
-
- glValidateProgramARB(program);
- glGetObjectParameterivARB(program, GL_VALIDATE_STATUS, &success);
- if (!success)
- {
- /*Program Validation Error*/
- PrintShaderErrors(fShader, "validate", shadersource);
- return 0;
- }
+ glLinkProgramARB(program);
+ glGetObjectParameterivARB(program, GL_LINK_STATUS, &success);
+ if (!success)
+ {
+ /*Program Link Error*/
+ std::cout << "2dFilters - Shader program link error" << std::endl;
+ return 0;
+ }
+
+ glValidateProgramARB(program);
+ glGetObjectParameterivARB(program, GL_VALIDATE_STATUS, &success);
+ if (!success)
+ {
+ /*Program Validation Error*/
+ std::cout << "2dFilters - Shader program validation error" << std::endl;
+ return 0;
+ }
- return program;
+ return program;
}
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;
+ 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)
+void RAS_2DFilterManager::AnalyseShader(int passindex, vector<STR_String>& propNames)
{
texflag[passindex] = 0;
if(glGetUniformLocationARB(m_filters[passindex], "bgl_DepthTexture") != -1)
@@ -217,50 +185,50 @@ void RAS_2DFilterManager::StartShaderProgram(int passindex)
glActiveTextureARB(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texname[0]);
- if (uniformLoc != -1)
- {
+ if (uniformLoc != -1)
+ {
glUniform1iARB(uniformLoc, 0);
- }
+ }
- /* send depth texture to glsl program if it needs */
+ /* 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]);
+ uniformLoc = glGetUniformLocationARB(m_filters[passindex], "bgl_DepthTexture");
+ glActiveTextureARB(GL_TEXTURE1);
+ glBindTexture(GL_TEXTURE_2D, texname[1]);
- if (uniformLoc != -1)
- {
- glUniform1iARB(uniformLoc, 1);
- }
- }
+ if (uniformLoc != -1)
+ {
+ glUniform1iARB(uniformLoc, 1);
+ }
+ }
- /* send luminance texture to glsl program if it needs */
+ /* 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_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);
- }
+ if (uniformLoc != -1)
+ {
+ glUniform2fvARB(uniformLoc, 9, textureoffsets);
+ }
uniformLoc = glGetUniformLocationARB(m_filters[passindex], "bgl_RenderedTextureWidth");
- if (uniformLoc != -1)
- {
+ if (uniformLoc != -1)
+ {
glUniform1fARB(uniformLoc,texturewidth);
- }
+ }
uniformLoc = glGetUniformLocationARB(m_filters[passindex], "bgl_RenderedTextureHeight");
- if (uniformLoc != -1)
- {
+ if (uniformLoc != -1)
+ {
glUniform1fARB(uniformLoc,textureheight);
- }
+ }
int i, objProperties = m_properties[passindex].size();
for(i=0; i<objProperties; i++)
@@ -281,11 +249,11 @@ void RAS_2DFilterManager::EndShaderProgram()
void RAS_2DFilterManager::FreeTextures()
{
- if(texname[0]!=(unsigned int)-1)
+ if(texname[0]!=-1)
glDeleteTextures(1, (GLuint*)&texname[0]);
- if(texname[1]!=(unsigned int)-1)
+ if(texname[1]!=-1)
glDeleteTextures(1, (GLuint*)&texname[1]);
- if(texname[2]!=(unsigned int)-1)
+ if(texname[2]!=-1)
glDeleteTextures(1, (GLuint*)&texname[2]);
}
@@ -332,20 +300,20 @@ void RAS_2DFilterManager::UpdateOffsetMatrix(RAS_ICanvas* canvas)
RAS_Rect canvas_rect = canvas->GetWindowArea();
canvaswidth = canvas->GetWidth();
canvasheight = canvas->GetHeight();
-
texturewidth = canvaswidth + canvas_rect.GetLeft();
textureheight = canvasheight + canvas_rect.GetBottom();
+
GLint i,j;
i = 0;
- while ((1 << i) <= texturewidth)
- i++;
- texturewidth = (1 << (i));
+ while ((1 << i) <= texturewidth)
+ i++;
+ texturewidth = (1 << (i));
- // Now for height
- i = 0;
- while ((1 << i) <= textureheight)
- i++;
- textureheight = (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;
@@ -360,23 +328,6 @@ void RAS_2DFilterManager::UpdateOffsetMatrix(RAS_ICanvas* canvas)
}
}
-void RAS_2DFilterManager::UpdateCanvasTextureCoord(unsigned int * viewport)
-{
- /*
- 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[0] *= -1;
- canvascoord[1] = (GLfloat) (texturewidth - viewport[0]) / viewport[2];
-
- canvascoord[2] = (GLfloat) viewport[1] / viewport[3];
- canvascoord[2] *= -1;
- canvascoord[3] = (GLfloat)(textureheight - viewport[1]) / viewport[3];
-}
-
void RAS_2DFilterManager::RenderFilters(RAS_ICanvas* canvas)
{
bool need_depth=false;
@@ -404,21 +355,12 @@ void RAS_2DFilterManager::RenderFilters(RAS_ICanvas* canvas)
if(num_filters <= 0)
return;
- GLuint viewport[4]={0};
- glGetIntegerv(GL_VIEWPORT,(GLint *)viewport);
-
if(canvaswidth != canvas->GetWidth() || canvasheight != canvas->GetHeight())
{
UpdateOffsetMatrix(canvas);
- UpdateCanvasTextureCoord((unsigned int*)viewport);
- need_tex_update = true;
- }
-
- if(need_tex_update)
- {
SetupTextures(need_depth, need_luminance);
- need_tex_update = false;
}
+ GLuint viewport[4]={0};
if(need_depth){
glActiveTextureARB(GL_TEXTURE1);
@@ -429,9 +371,10 @@ void RAS_2DFilterManager::RenderFilters(RAS_ICanvas* canvas)
if(need_luminance){
glActiveTextureARB(GL_TEXTURE2);
glBindTexture(GL_TEXTURE_2D, texname[2]);
- glCopyTexImage2D(GL_TEXTURE_2D,0,GL_LUMINANCE16, 0, 0, texturewidth,textureheight, 0);
+ glCopyTexImage2D(GL_TEXTURE_2D,0,GL_LUMINANCE16, 0, 0 , texturewidth,textureheight, 0);
}
+ glGetIntegerv(GL_VIEWPORT,(GLint *)viewport);
glViewport(0,0, texturewidth, textureheight);
glDisable(GL_DEPTH_TEST);
@@ -455,10 +398,10 @@ void RAS_2DFilterManager::RenderFilters(RAS_ICanvas* canvas)
glBegin(GL_QUADS);
glColor4f(1.f, 1.f, 1.f, 1.f);
- glTexCoord2f(1.0, 1.0); glMultiTexCoord2fARB(GL_TEXTURE3_ARB, canvascoord[1], canvascoord[3]); glVertex2f(1,1);
- glTexCoord2f(0.0, 1.0); glMultiTexCoord2fARB(GL_TEXTURE3_ARB, canvascoord[0], canvascoord[3]); glVertex2f(-1,1);
- glTexCoord2f(0.0, 0.0); glMultiTexCoord2fARB(GL_TEXTURE3_ARB, canvascoord[0], canvascoord[2]); glVertex2f(-1,-1);
- glTexCoord2f(1.0, 0.0); glMultiTexCoord2fARB(GL_TEXTURE3_ARB, canvascoord[1], canvascoord[2]); glVertex2f(1,-1);
+ glTexCoord2f(1.0, 1.0); glVertex2f(1,1);
+ glTexCoord2f(0.0, 1.0); glVertex2f(-1,1);
+ glTexCoord2f(0.0, 0.0); glVertex2f(-1,-1);
+ glTexCoord2f(1.0, 0.0); glVertex2f(1,-1);
glEnd();
}
}
@@ -474,7 +417,7 @@ void RAS_2DFilterManager::EnableFilter(vector<STR_String>& propNames, void* game
return;
if(pass<0 || pass>=MAX_RENDER_PASS)
return;
- need_tex_update = true;
+
if(mode == RAS_2DFILTER_DISABLED)
{
m_enabled[pass] = 0;
diff --git a/source/gameengine/Rasterizer/RAS_2DFilterManager.h b/source/gameengine/Rasterizer/RAS_2DFilterManager.h
index 6a420a974d4..f5998e1f093 100644
--- a/source/gameengine/Rasterizer/RAS_2DFilterManager.h
+++ b/source/gameengine/Rasterizer/RAS_2DFilterManager.h
@@ -33,20 +33,17 @@
class RAS_2DFilterManager
{
private:
- unsigned int CreateShaderProgram(const char* shadersource);
+ unsigned int CreateShaderProgram(char* shadersource);
unsigned int CreateShaderProgram(int filtermode);
void AnalyseShader(int passindex, 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(unsigned int * viewport);
-
- float canvascoord[4];
+
float textureoffsets[18];
float view[4];
/* texname[0] contains render to texture, texname[1] contains depth texture, texname[2] contains luminance texture*/
@@ -61,8 +58,6 @@ private:
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];
diff --git a/source/gameengine/Rasterizer/RAS_BucketManager.cpp b/source/gameengine/Rasterizer/RAS_BucketManager.cpp
index f7938bb62e6..82bdce44519 100644
--- a/source/gameengine/Rasterizer/RAS_BucketManager.cpp
+++ b/source/gameengine/Rasterizer/RAS_BucketManager.cpp
@@ -26,6 +26,10 @@
* ***** END GPL LICENSE BLOCK *****
*/
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
#ifdef WIN32
// don't show these anoying STL warnings
#pragma warning (disable:4786)
@@ -35,54 +39,14 @@
#include "RAS_MaterialBucket.h"
#include "STR_HashedString.h"
#include "RAS_MeshObject.h"
+#define KX_NUM_MATERIALBUCKETS 100
#include "RAS_IRasterizer.h"
#include "RAS_IRenderTools.h"
#include "RAS_BucketManager.h"
-#include <algorithm>
#include <set>
-/* 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()
{
@@ -90,179 +54,153 @@ 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();
+ RAS_BucketManagerClearAll();
}
-void RAS_BucketManager::OrderBuckets(const MT_Transform& cameratrans, BucketList& buckets, vector<sortedmeshslot>& slots, bool alpha)
+/**
+ * struct alphamesh holds a mesh, (m_ms) it's depth, (m_z) and the bucket it came from (m_bucket.)
+ */
+struct RAS_BucketManager::alphamesh
{
- 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)
- for (mit = (*bit)->msBegin(); mit != (*bit)->msEnd(); ++mit)
- if (!mit->IsCulled())
- size++;
-
- slots.resize(size);
-
- for (bit = buckets.begin(); bit != buckets.end(); ++bit)
- for (mit = (*bit)->msBegin(); mit != (*bit)->msEnd(); ++mit)
- if (!mit->IsCulled())
- slots[i++].set(&*mit, *bit, pnorm);
-
- if(alpha)
- sort(slots.begin(), slots.end(), backtofront());
- else
- sort(slots.begin(), slots.end(), fronttoback());
-}
+public:
+ MT_Scalar m_z;
+ RAS_MaterialBucket::T_MeshSlotList::iterator m_ms;
+ RAS_MaterialBucket *m_bucket;
+ alphamesh(MT_Scalar z, RAS_MaterialBucket::T_MeshSlotList::iterator &ms, RAS_MaterialBucket *bucket) :
+ m_z(z),
+ m_ms(ms),
+ m_bucket(bucket)
+ {}
+};
-void RAS_BucketManager::RenderAlphaBuckets(
- const MT_Transform& cameratrans, RAS_IRasterizer* rasty, RAS_IRenderTools* rendertools)
+struct RAS_BucketManager::backtofront
{
- 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.
- rasty->SetDepthMask(RAS_IRasterizer::KX_DEPTHMASK_DISABLED);
-
- OrderBuckets(cameratrans, m_AlphaBuckets, slots, true);
-
- for(sit=slots.begin(); sit!=slots.end(); ++sit) {
- rendertools->SetClientObject(rasty, sit->m_ms->m_clientObj);
-
- while(sit->m_bucket->ActivateMaterial(cameratrans, rasty, rendertools))
- sit->m_bucket->RenderMeshSlot(cameratrans, rasty, rendertools, *(sit->m_ms));
+ bool operator()(const alphamesh &a, const alphamesh &b)
+ {
+ return a.m_z < b.m_z;
}
+};
+
- rasty->SetDepthMask(RAS_IRasterizer::KX_DEPTHMASK_ENABLED);
-}
-
-void RAS_BucketManager::RenderSolidBuckets(
+void RAS_BucketManager::RenderAlphaBuckets(
const MT_Transform& cameratrans, RAS_IRasterizer* rasty, RAS_IRenderTools* rendertools)
{
BucketList::iterator bit;
- list<RAS_MeshSlot>::iterator mit;
-
- rasty->SetDepthMask(RAS_IRasterizer::KX_DEPTHMASK_ENABLED);
-
- for (bit = m_SolidBuckets.begin(); bit != m_SolidBuckets.end(); ++bit) {
- for (mit = (*bit)->msBegin(); mit != (*bit)->msEnd(); ++mit) {
- if (mit->IsCulled())
- continue;
-
- rendertools->SetClientObject(rasty, mit->m_clientObj);
-
- while ((*bit)->ActivateMaterial(cameratrans, rasty, rendertools))
- (*bit)->RenderMeshSlot(cameratrans, rasty, rendertools, *mit);
+ std::multiset<alphamesh, backtofront> alphameshset;
+ RAS_MaterialBucket::T_MeshSlotList::iterator mit;
+
+ /* Camera's near plane equation: cam_norm.dot(point) + cam_origin */
+ const MT_Vector3 cam_norm(cameratrans.getBasis()[2]);
+ const MT_Scalar cam_origin = cameratrans.getOrigin()[2];
+ for (bit = m_AlphaBuckets.begin(); bit != m_AlphaBuckets.end(); ++bit)
+ {
+ for (mit = (*bit)->msBegin(); mit != (*bit)->msEnd(); ++mit)
+ {
+ if ((*mit).m_bVisible)
+ {
+ MT_Point3 pos((*mit).m_OpenGLMatrix[12], (*mit).m_OpenGLMatrix[13], (*mit).m_OpenGLMatrix[14]);
+ alphameshset.insert(alphamesh(MT_dot(cam_norm, pos) + cam_origin, mit, *bit));
+ }
}
}
- /* 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);
+ // It shouldn't be strictly necessary to disable depth writes; but
+ // it is needed for compatibility.
+ rasty->SetDepthMask(RAS_IRasterizer::KX_DEPTHMASK_DISABLED);
- while(sit->m_bucket->ActivateMaterial(cameratrans, rasty, rendertools))
- sit->m_bucket->RenderMeshSlot(cameratrans, rasty, rendertools, *(sit->m_ms));
+ RAS_IRasterizer::DrawMode drawingmode;
+ std::multiset< alphamesh, backtofront>::iterator msit = alphameshset.begin();
+ for (; msit != alphameshset.end(); ++msit)
+ {
+ rendertools->SetClientObject((*(*msit).m_ms).m_clientObj);
+ while ((*msit).m_bucket->ActivateMaterial(cameratrans, rasty, rendertools, drawingmode))
+ (*msit).m_bucket->RenderMeshSlot(cameratrans, rasty, rendertools, *(*msit).m_ms, drawingmode);
}
-#endif
+
+ rasty->SetDepthMask(RAS_IRasterizer::KX_DEPTHMASK_ENABLED);
}
void RAS_BucketManager::Renderbuckets(
const MT_Transform& cameratrans, RAS_IRasterizer* rasty, RAS_IRenderTools* rendertools)
{
- /* beginning each frame, clear (texture/material) caching information */
+ BucketList::iterator bucket;
+
+ rasty->EnableTextures(false);
+ rasty->SetDepthMask(RAS_IRasterizer::KX_DEPTHMASK_ENABLED);
+
+ // beginning each frame, clear (texture/material) caching information
rasty->ClearCachingInfo();
- RenderSolidBuckets(cameratrans, rasty, rendertools);
- RenderAlphaBuckets(cameratrans, rasty, rendertools);
+ RAS_MaterialBucket::StartFrame();
+
+ for (bucket = m_MaterialBuckets.begin(); bucket != m_MaterialBuckets.end(); ++bucket)
+ (*bucket)->Render(cameratrans,rasty,rendertools);
- rendertools->SetClientObject(rasty, NULL);
+ RenderAlphaBuckets(cameratrans, rasty, rendertools);
+ RAS_MaterialBucket::EndFrame();
}
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++)
+ BucketList::iterator it;
+ for (it = m_MaterialBuckets.begin(); it != m_MaterialBuckets.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);
+ m_MaterialBuckets.push_back(bucket);
return bucket;
}
-void RAS_BucketManager::OptimizeBuckets(MT_Scalar distance)
+void RAS_BucketManager::RAS_BucketManagerClearAll()
{
- BucketList::iterator bit;
+ BucketList::iterator it;
+ for (it = m_MaterialBuckets.begin(); it != m_MaterialBuckets.end(); it++)
+ {
+ delete (*it);
+ }
+ for (it = m_AlphaBuckets.begin(); it != m_AlphaBuckets.end(); it++)
+ {
+ delete(*it);
+ }
- distance = 10.0;
-
- 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);
+ m_MaterialBuckets.clear();
+ m_AlphaBuckets.clear();
}
-void RAS_BucketManager::ReleaseDisplayLists(RAS_IPolyMaterial *mat)
+void RAS_BucketManager::ReleaseDisplayLists()
{
BucketList::iterator bit;
- list<RAS_MeshSlot>::iterator mit;
+ RAS_MaterialBucket::T_MeshSlotList::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_MaterialBuckets.begin(); bit != m_MaterialBuckets.end(); ++bit) {
+ 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;
- }
+ for (mit = (*bit)->msBegin(); mit != (*bit)->msEnd(); ++mit) {
+ if(mit->m_DisplayList) {
+ mit->m_DisplayList->Release();
+ mit->m_DisplayList = NULL;
}
}
}
diff --git a/source/gameengine/Rasterizer/RAS_BucketManager.h b/source/gameengine/Rasterizer/RAS_BucketManager.h
index 74526f365a0..08b67ed022f 100644
--- a/source/gameengine/Rasterizer/RAS_BucketManager.h
+++ b/source/gameengine/Rasterizer/RAS_BucketManager.h
@@ -39,33 +39,32 @@
class RAS_BucketManager
{
+ //GEN_Map<class RAS_IPolyMaterial,class RAS_MaterialBucket*> m_MaterialBuckets;
+
typedef std::vector<class RAS_MaterialBucket*> BucketList;
- BucketList m_SolidBuckets;
+ BucketList m_MaterialBuckets;
BucketList m_AlphaBuckets;
- struct sortedmeshslot;
+ struct alphamesh;
struct backtofront;
- struct fronttoback;
public:
RAS_BucketManager();
virtual ~RAS_BucketManager();
- void Renderbuckets(const MT_Transform & cameratrans,
+ void RenderAlphaBuckets(const MT_Transform& cameratrans,
RAS_IRasterizer* rasty, RAS_IRenderTools* rendertools);
+ void Renderbuckets(const MT_Transform & cameratrans,
+ RAS_IRasterizer* rasty,
+ class RAS_IRenderTools* rendertools);
RAS_MaterialBucket* FindBucket(RAS_IPolyMaterial * material, bool &bucketCreated);
- void OptimizeBuckets(MT_Scalar distance);
- void ReleaseDisplayLists(RAS_IPolyMaterial * material = NULL);
+ void ReleaseDisplayLists();
private:
- void OrderBuckets(const MT_Transform& cameratrans, BucketList& buckets, vector<sortedmeshslot>& slots, bool alpha);
+ void RAS_BucketManagerClearAll();
- void RenderSolidBuckets(const MT_Transform& cameratrans,
- RAS_IRasterizer* rasty, RAS_IRenderTools* rendertools);
- void RenderAlphaBuckets(const MT_Transform& cameratrans,
- RAS_IRasterizer* rasty, RAS_IRenderTools* rendertools);
};
#endif //__RAS_BUCKETMANAGER
diff --git a/source/gameengine/Rasterizer/RAS_Deformer.h b/source/gameengine/Rasterizer/RAS_Deformer.h
index 3332ac4c0a7..4e8484ab880 100644
--- a/source/gameengine/Rasterizer/RAS_Deformer.h
+++ b/source/gameengine/Rasterizer/RAS_Deformer.h
@@ -44,11 +44,7 @@ public:
virtual void Relink(GEN_Map<class GEN_HashedPtr, void*>*map)=0;
virtual bool Apply(class RAS_IPolyMaterial *polymat)=0;
virtual bool Update(void)=0;
- virtual RAS_Deformer *GetReplica(class KX_GameObject* replica)=0;
- virtual bool SkipVertexTransform()
- {
- return false;
- }
+ virtual RAS_Deformer *GetReplica()=0;
protected:
class RAS_MeshObject *m_pMesh;
};
diff --git a/source/gameengine/Rasterizer/RAS_FramingManager.h b/source/gameengine/Rasterizer/RAS_FramingManager.h
index 610bd13ff12..dcb48c1c2a0 100644
--- a/source/gameengine/Rasterizer/RAS_FramingManager.h
+++ b/source/gameengine/Rasterizer/RAS_FramingManager.h
@@ -108,13 +108,6 @@ public :
) const {
return m_frame_type;
};
-
- void
- SetFrameType(
- RAS_FrameType type
- ) {
- m_frame_type = type;
- };
float
BarRed(
@@ -147,6 +140,14 @@ public :
};
private :
+
+ /**
+ * private to force use of public constructor
+ */
+
+ RAS_FrameSettings(
+ const RAS_FrameSettings &
+ );
RAS_FrameType m_frame_type;
float m_bar_r;
@@ -212,6 +213,9 @@ public :
RAS_FrameFrustum &frustum
);
+
+private :
+
static
void
ComputeDefaultFrustum(
@@ -222,8 +226,6 @@ public :
RAS_FrameFrustum & frustum
);
-private :
-
static
void
ComputeBestFitViewRect(
diff --git a/source/gameengine/Rasterizer/RAS_IPolygonMaterial.cpp b/source/gameengine/Rasterizer/RAS_IPolygonMaterial.cpp
index fb3607f89f4..4ee06d96603 100644
--- a/source/gameengine/Rasterizer/RAS_IPolygonMaterial.cpp
+++ b/source/gameengine/Rasterizer/RAS_IPolygonMaterial.cpp
@@ -42,8 +42,11 @@ RAS_IPolyMaterial::RAS_IPolyMaterial(const STR_String& texname,
int transp,
bool alpha,
bool zsort,
- int lightlayer)
- : m_texturename(texname),
+ int lightlayer,
+ bool bIsTriangle,
+ void* clientobject=NULL) :
+
+ m_texturename(texname),
m_materialname(matname),
m_tile(tile),
m_tilexrep(tilexrep),
@@ -53,6 +56,7 @@ RAS_IPolyMaterial::RAS_IPolyMaterial(const STR_String& texname,
m_alpha(alpha),
m_zsort(zsort),
m_lightlayer(lightlayer),
+ m_bIsTriangle(bIsTriangle),
m_polymatid(m_newpolymatid++),
m_flag(0),
m_multimode(0)
@@ -68,16 +72,15 @@ bool RAS_IPolyMaterial::Equals(const RAS_IPolyMaterial& lhs) const
{
if(m_flag &RAS_BLENDERMAT)
{
- bool test = (
+ return (
this->m_multimode == lhs.m_multimode &&
this->m_flag == lhs.m_flag &&
this->m_drawingmode == lhs.m_drawingmode &&
this->m_transp == lhs.m_transp &&
+ this->m_lightlayer == lhs.m_lightlayer &&
this->m_texturename.hash() == lhs.m_texturename.hash() &&
this->m_materialname.hash() == lhs.m_materialname.hash()
);
-
- return test;
}
else
{
@@ -89,6 +92,8 @@ bool RAS_IPolyMaterial::Equals(const RAS_IPolyMaterial& lhs) const
this->m_alpha == lhs.m_alpha &&
this->m_zsort == lhs.m_zsort &&
this->m_drawingmode == lhs.m_drawingmode &&
+ this->m_bIsTriangle == lhs.m_bIsTriangle &&
+ this->m_lightlayer == lhs.m_lightlayer &&
this->m_texturename.hash() == lhs.m_texturename.hash() &&
this->m_materialname.hash() == lhs.m_materialname.hash()
);
@@ -118,6 +123,11 @@ bool RAS_IPolyMaterial::IsZSort() const
return m_zsort;
}
+bool RAS_IPolyMaterial::UsesTriangles() const
+{
+ return m_bIsTriangle;
+}
+
unsigned int RAS_IPolyMaterial::hash() const
{
return m_texturename.hash();
@@ -162,10 +172,5 @@ bool RAS_IPolyMaterial::UsesLighting(RAS_IRasterizer *rasty) const
return dolights;
}
-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
index 218dd91cb30..8fc53e6b038 100644
--- a/source/gameengine/Rasterizer/RAS_IPolygonMaterial.h
+++ b/source/gameengine/Rasterizer/RAS_IPolygonMaterial.h
@@ -71,6 +71,7 @@ protected:
bool m_alpha;
bool m_zsort;
int m_lightlayer;
+ bool m_bIsTriangle;
unsigned int m_polymatid;
static unsigned int m_newpolymatid;
@@ -105,7 +106,9 @@ public:
int transp,
bool alpha,
bool zsort,
- int lightlayer);
+ int lightlayer,
+ bool bIsTriangle,
+ void* clientobject);
virtual ~RAS_IPolyMaterial() {};
/**
@@ -126,13 +129,14 @@ public:
{
return false;
}
- virtual void ActivateMeshSlot(const class RAS_MeshSlot & ms, RAS_IRasterizer* rasty) const {}
+ virtual void ActivateMeshSlot(const class KX_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;
+ bool UsesTriangles() const;
unsigned int hash() const;
int GetDrawingMode() const;
const STR_String& GetMaterialName() const;
@@ -141,7 +145,6 @@ public:
const unsigned int GetFlag() const;
virtual bool UsesLighting(RAS_IRasterizer *rasty) const;
- virtual bool UsesObjectColor() const;
/*
* PreCalculate texture gen
diff --git a/source/gameengine/Rasterizer/RAS_IRasterizer.h b/source/gameengine/Rasterizer/RAS_IRasterizer.h
index b4b90c3608b..9e03212283e 100644
--- a/source/gameengine/Rasterizer/RAS_IRasterizer.h
+++ b/source/gameengine/Rasterizer/RAS_IRasterizer.h
@@ -169,10 +169,6 @@ public:
*/
virtual bool BeginFrame(int drawingmode, double time)=0;
/**
- * ClearColorBuffer clears the color buffer.
- */
- virtual void ClearColorBuffer()=0;
- /**
* ClearDepthBuffer clears the depth buffer.
*/
virtual void ClearDepthBuffer()=0;
@@ -185,8 +181,7 @@ public:
*/
virtual void EndFrame()=0;
/**
- * SetRenderArea sets the render area from the 2d canvas.
- * Returns true if only of subset of the canvas is used.
+ * SetRenderArea sets the render area from the 2d canvas
*/
virtual void SetRenderArea()=0;
@@ -200,8 +195,6 @@ public:
* @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.
*/
@@ -224,18 +217,39 @@ public:
// Drawing Functions
/**
- * IndexPrimitives: Renders primitives from mesh slot.
- */
- virtual void IndexPrimitives(class RAS_MeshSlot& ms)=0;
- virtual void IndexPrimitivesMulti(class RAS_MeshSlot& ms)=0;
+ * IndexPrimitives: Renders primitives.
+ * @param vertexarrays is an array of vertex arrays
+ * @param indexarrays is an array of index arrays
+ * @param mode determines the type of primitive stored in the vertex/index arrays
+ * @param useObjectColor will render the object using @param rgbacolor instead of
+ * vertex colors.
+ */
+ virtual void IndexPrimitives( const vecVertexArray& vertexarrays,
+ const vecIndexArrays & indexarrays,
+ DrawMode mode,
+ bool useObjectColor,
+ const MT_Vector4& rgbacolor,
+ class KX_ListSlot** slot)=0;
+
+ virtual void IndexPrimitivesMulti(
+ const vecVertexArray& vertexarrays,
+ const vecIndexArrays & indexarrays,
+ DrawMode mode,
+ bool useObjectColor,
+ const MT_Vector4& rgbacolor,
+ class KX_ListSlot** slot)=0;
/**
* IndexPrimitives_3DText will render text into the polygons.
* The text to be rendered is from @param rendertools client object's text property.
*/
- virtual void IndexPrimitives_3DText(class RAS_MeshSlot& ms,
+ virtual void IndexPrimitives_3DText( const vecVertexArray& vertexarrays,
+ const vecIndexArrays & indexarrays,
+ DrawMode mode,
class RAS_IPolyMaterial* polymat,
- class RAS_IRenderTools* rendertools)=0;
+ class RAS_IRenderTools* rendertools,
+ bool useObjectColor,
+ const MT_Vector4& rgbacolor)=0;
virtual void SetProjectionMatrix(MT_CmMatrix4x4 & mat)=0;
/* This one should become our final version, methinks. */
@@ -257,6 +271,9 @@ public:
virtual const MT_Point3& GetCameraPosition()=0;
/**
*/
+ virtual void LoadViewMatrix()=0;
+ /**
+ */
virtual void SetFog(float start,
float dist,
float r,
@@ -292,6 +309,9 @@ public:
*/
virtual int GetDrawingMode()=0;
/**
+ */
+ virtual void EnableTextures(bool enable)=0;
+ /**
* Sets face culling
*/
virtual void SetCullFace(bool enable)=0;
@@ -365,9 +385,7 @@ public:
virtual void SetAttribNum(int num) = 0;
virtual void SetTexCoord(TexCoGen coords, int unit) = 0;
virtual void SetAttrib(TexCoGen coords, int unit) = 0;
-
- virtual const MT_Matrix4x4& GetViewMatrix() const = 0;
- virtual const MT_Matrix4x4& GetViewInvMatrix() const = 0;
+ virtual void GetViewMatrix(MT_Matrix4x4 &mat) const = 0;
virtual bool QueryLists(){return false;}
virtual bool QueryArrays(){return false;}
@@ -380,7 +398,6 @@ public:
virtual void SetMotionBlurState(int newstate)=0;
virtual void SetBlendingMode(int blendmode)=0;
- virtual void SetFrontFace(bool ccw)=0;
};
#endif //__RAS_IRASTERIZER
diff --git a/source/gameengine/Rasterizer/RAS_IRenderTools.cpp b/source/gameengine/Rasterizer/RAS_IRenderTools.cpp
index 555a3520bb4..2be9bb75ebf 100644
--- a/source/gameengine/Rasterizer/RAS_IRenderTools.cpp
+++ b/source/gameengine/Rasterizer/RAS_IRenderTools.cpp
@@ -28,22 +28,42 @@
#include "RAS_IRenderTools.h"
-void RAS_IRenderTools::SetClientObject(RAS_IRasterizer* rasty, void *obj)
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+void RAS_IRenderTools::SetViewMat(const MT_Transform& trans)
+{
+ trans.getValue(m_viewmat);
+}
+
+
+
+void RAS_IRenderTools::SetClientObject(void* obj)
{
if (m_clientobject != obj)
+ {
m_clientobject = obj;
+ m_modified = true;
+ }
}
+
+
void RAS_IRenderTools::SetAuxilaryClientInfo(void* inf)
{
m_auxilaryClientInfo = inf;
}
+
+
void RAS_IRenderTools::AddLight(struct RAS_LightObject* lightobject)
{
m_lights.push_back(lightobject);
}
+
+
void RAS_IRenderTools::RemoveLight(struct RAS_LightObject* lightobject)
{
std::vector<struct RAS_LightObject*>::iterator lit =
@@ -51,5 +71,5 @@ void RAS_IRenderTools::RemoveLight(struct RAS_LightObject* lightobject)
if (!(lit==m_lights.end()))
m_lights.erase(lit);
-}
+}
diff --git a/source/gameengine/Rasterizer/RAS_IRenderTools.h b/source/gameengine/Rasterizer/RAS_IRenderTools.h
index 57f331e64cb..54a663ba111 100644
--- a/source/gameengine/Rasterizer/RAS_IRenderTools.h
+++ b/source/gameengine/Rasterizer/RAS_IRenderTools.h
@@ -44,9 +44,12 @@ class RAS_IRenderTools
{
protected:
+ float m_viewmat[16];
void* m_clientobject;
void* m_auxilaryClientInfo;
+ bool m_modified;
+
std::vector<struct RAS_LightObject*> m_lights;
RAS_2DFilterManager m_filtermanager;
@@ -65,7 +68,8 @@ public:
RAS_IRenderTools(
) :
- m_clientobject(NULL)
+ m_clientobject(NULL),
+ m_modified(true)
{
};
@@ -127,21 +131,24 @@ public:
float v1[3],
float v2[3],
float v3[3],
- float v4[3],
- int glattrib
+ float v4[3]
)=0;
virtual
- void
- ProcessLighting(
- int layer,
+ void
+ SetViewMat(
const MT_Transform& trans
+ );
+
+ virtual
+ int
+ ProcessLighting(
+ int layer
)=0;
virtual
void
SetClientObject(
- RAS_IRasterizer* rasty,
void* obj
);
@@ -183,6 +190,24 @@ public:
virtual
void
Render2DFilters(RAS_ICanvas* canvas)=0;
+
+ virtual
+ class RAS_IPolyMaterial*
+ CreateBlenderPolyMaterial(
+ const STR_String &texname,
+ bool ba,
+ const STR_String& matname,
+ int tile,
+ int tilexrep,
+ int tileyrep,
+ int mode,
+ bool transparant,
+ bool zsort,
+ int lightlayer,
+ bool bIsTriangle,
+ void* clientobject,
+ void* tface
+ )=0;
};
#endif //__RAS_IRENDERTOOLS
diff --git a/source/gameengine/Rasterizer/RAS_MaterialBucket.cpp b/source/gameengine/Rasterizer/RAS_MaterialBucket.cpp
index ad8d7ebd5b0..0015b6a251f 100644
--- a/source/gameengine/Rasterizer/RAS_MaterialBucket.cpp
+++ b/source/gameengine/Rasterizer/RAS_MaterialBucket.cpp
@@ -28,6 +28,10 @@
#include "RAS_MaterialBucket.h"
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
#ifdef WIN32
#pragma warning (disable:4786)
#include <windows.h>
@@ -40,423 +44,79 @@
#include "RAS_MeshObject.h"
#include "RAS_Deformer.h" // __NLA
-/* mesh slot */
-
-RAS_MeshSlot::RAS_MeshSlot()
-{
- 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.0, 0.0, 0.0, 0.0);
- m_DisplayList = NULL;
- m_bDisplayList = true;
- m_joinSlot = NULL;
-}
-
-RAS_MeshSlot::~RAS_MeshSlot()
-{
- vector<RAS_DisplayArray*>::iterator it;
-
- Split(true);
-
- while(m_joinedSlots.size())
- m_joinedSlots.front()->Split(true);
- 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)
+KX_VertexIndex::KX_VertexIndex(int size)
{
- vector<RAS_DisplayArray*>::iterator it;
-
- m_clientObj = NULL;
- m_pDeformer = 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++;
- }
+ m_size = size;
}
-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.size() > 0)? m_displayArrays[m_startarray]: NULL;
-
- 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)
+void KX_VertexIndex::SetIndex(short loc,unsigned int index)
{
- 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;
- }
+ m_indexarray[loc]=index;
}
-bool RAS_MeshSlot::end(RAS_MeshSlot::iterator& it)
+bool KX_MeshSlot::Less(const KX_MeshSlot& lhs) const
{
- return (it.array == NULL);
+ bool result = ((m_mesh < lhs.m_mesh ) ||
+ ((m_mesh == lhs.m_mesh)&&(m_OpenGLMatrix < lhs.m_OpenGLMatrix)));
+
+ return result;
}
-RAS_DisplayArray *RAS_MeshSlot::CurrentDisplayArray()
+KX_MeshSlot::~KX_MeshSlot()
{
- return m_currentArray;
+ if (m_DisplayList)
+ m_DisplayList->Release();
}
-void RAS_MeshSlot::SetDisplayArray(int numverts)
-{
- vector<RAS_DisplayArray*>::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)
+RAS_MaterialBucket::RAS_MaterialBucket(RAS_IPolyMaterial* mat)
+ :m_bModified(true)
{
- SetDisplayArray(numverts);
+ m_material = mat;
}
-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;
+RAS_IPolyMaterial* RAS_MaterialBucket::GetPolyMaterial() const
+{
+ return m_material;
}
-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++;
-}
-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)
+void RAS_MaterialBucket::SetMeshSlot(KX_MeshSlot& ms)
{
- vector<RAS_DisplayArray*>::iterator it;
- iterator mit;
- size_t i;
-
- // verify if we can join
- if(m_joinSlot || m_joinedSlots.size() || 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);
-
- 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
+ m_meshSlots.insert(ms);
}
-bool RAS_MeshSlot::Split(bool force)
-{
- list<RAS_MeshSlot*>::iterator jit;
- RAS_MeshSlot *target = m_joinSlot;
- vector<RAS_DisplayArray*>::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.size()) {
- 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;
-}
-bool RAS_MeshSlot::IsCulled()
+void RAS_MaterialBucket::RemoveMeshSlot(KX_MeshSlot& ms)
{
- list<RAS_MeshSlot*>::iterator it;
+ T_MeshSlotList::iterator it = m_meshSlots.find(ms);
- if(m_joinSlot)
- return true;
- if(!m_bCulled)
- return false;
-
- for(it=m_joinedSlots.begin(); it!=m_joinedSlots.end(); it++)
- if(!(*it)->m_bCulled)
- return false;
-
- return true;
+ if (!(it == m_meshSlots.end()))
+ m_meshSlots.erase(it);
+
}
-/* 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()
+void RAS_MaterialBucket::MarkVisibleMeshSlot(KX_MeshSlot& ms,
+ bool visible,
+ bool color,
+ const MT_Vector4& rgbavec)
{
-}
-
-RAS_IPolyMaterial* RAS_MaterialBucket::GetPolyMaterial() const
-{
- return m_material;
+ T_MeshSlotList::iterator it = m_meshSlots.find(ms);
+
+ assert (!(it == m_meshSlots.end()));
+ (*it).m_bVisible = visible;
+ (*it).m_bObjectColor = color;
+ (*it).m_RGBAcolor= rgbavec;
}
bool RAS_MaterialBucket::IsAlpha() const
@@ -469,132 +129,162 @@ 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;
+void RAS_MaterialBucket::StartFrame()
+{
}
-RAS_MeshSlot* RAS_MaterialBucket::CopyMesh(RAS_MeshSlot *ms)
+
+
+void RAS_MaterialBucket::EndFrame()
{
- m_meshSlots.push_back(RAS_MeshSlot(*ms));
-
- return &m_meshSlots.back();
}
-void RAS_MaterialBucket::RemoveMesh(RAS_MeshSlot* ms)
+unsigned int RAS_MaterialBucket::NumMeshSlots()
{
- list<RAS_MeshSlot>::iterator it;
-
- for(it=m_meshSlots.begin(); it!=m_meshSlots.end(); it++) {
- if(&*it == ms) {
- m_meshSlots.erase(it);
- return;
- }
- }
+ return m_meshSlots.size();
}
-list<RAS_MeshSlot>::iterator RAS_MaterialBucket::msBegin()
+RAS_MaterialBucket::T_MeshSlotList::iterator RAS_MaterialBucket::msBegin()
{
return m_meshSlots.begin();
}
-list<RAS_MeshSlot>::iterator RAS_MaterialBucket::msEnd()
+RAS_MaterialBucket::T_MeshSlotList::iterator RAS_MaterialBucket::msEnd()
{
return m_meshSlots.end();
}
bool RAS_MaterialBucket::ActivateMaterial(const MT_Transform& cameratrans, RAS_IRasterizer* rasty,
- RAS_IRenderTools *rendertools)
+ RAS_IRenderTools *rendertools, RAS_IRasterizer::DrawMode &drawmode)
{
+ rendertools->SetViewMat(cameratrans);
+
if (!rasty->SetMaterial(*m_material))
return false;
if (m_material->UsesLighting(rasty))
- rendertools->ProcessLighting(RAS_IRenderTools::RAS_LIGHT_OBJECT_LAYER, cameratrans);
+ rendertools->ProcessLighting(RAS_IRenderTools::RAS_LIGHT_OBJECT_LAYER/*m_material->GetLightLayer()*/);
else
- rendertools->ProcessLighting(-1, cameratrans);
+ rendertools->ProcessLighting(-1);
+
+ if(rasty->GetDrawingMode() < RAS_IRasterizer::KX_SOLID)
+ drawmode = RAS_IRasterizer::KX_MODE_LINES;
+ else if(m_material->UsesTriangles())
+ drawmode = RAS_IRasterizer::KX_MODE_TRIANGLES;
+ else
+ drawmode = RAS_IRasterizer::KX_MODE_QUADS;
return true;
}
void RAS_MaterialBucket::RenderMeshSlot(const MT_Transform& cameratrans, RAS_IRasterizer* rasty,
- RAS_IRenderTools* rendertools, RAS_MeshSlot &ms)
+ RAS_IRenderTools* rendertools, const KX_MeshSlot &ms, RAS_IRasterizer::DrawMode drawmode)
{
+ if (!ms.m_bVisible)
+ return;
+
m_material->ActivateMeshSlot(ms, rasty);
+ /* __NLA Do the deformation */
if (ms.m_pDeformer)
{
ms.m_pDeformer->Apply(m_material);
// KX_ReInstanceShapeFromMesh(ms.m_mesh); // Recompute the physics mesh. (Can't call KX_* from RAS_)
}
+ /* End __NLA */
- if(IsZSort() && rasty->GetDrawingMode() >= RAS_IRasterizer::KX_SOLID)
- ms.m_mesh->SortPolygons(ms, cameratrans*MT_Transform(ms.m_OpenGLMatrix));
+ if (rasty->GetDrawingMode() >= RAS_IRasterizer::KX_SOLID)
+ ms.m_mesh->SortPolygons(cameratrans*MT_Transform(ms.m_OpenGLMatrix));
rendertools->PushMatrix();
- if (!ms.m_pDeformer || !ms.m_pDeformer->SkipVertexTransform())
- {
- rendertools->applyTransform(rasty,ms.m_OpenGLMatrix,m_material->GetDrawingMode());
- }
+ rendertools->applyTransform(rasty,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.
+ // then it won't have texture coordinates for actual drawing
+ KX_ListSlot **displaylist;
if(ms.m_pDeformer)
- ms.m_bDisplayList = false;
+ displaylist = 0;
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;
+ displaylist = 0;
else
- ms.m_bDisplayList = true;
+ displaylist = &ms.m_DisplayList;
- // for text drawing using faces
+ // Use the text-specific IndexPrimitives for text faces
if (m_material->GetDrawingMode() & RAS_IRasterizer::RAS_RENDER_3DPOLYGON_TEXT)
- rasty->IndexPrimitives_3DText(ms, m_material, rendertools);
- // for multitexturing
- else if((m_material->GetFlag() & (RAS_MULTITEX|RAS_BLENDERGLSL)))
- rasty->IndexPrimitivesMulti(ms);
- // use normal IndexPrimitives
+ {
+ rasty->IndexPrimitives_3DText(
+ ms.m_mesh->GetVertexCache(m_material),
+ ms.m_mesh->GetIndexCache(m_material),
+ drawmode,
+ m_material,
+ rendertools, // needed for textprinting on polys
+ ms.m_bObjectColor,
+ ms.m_RGBAcolor);
+ }
+
+ // for using glMultiTexCoord
+ else if((m_material->GetFlag() & RAS_MULTITEX))
+ {
+ rasty->IndexPrimitivesMulti(
+ ms.m_mesh->GetVertexCache(m_material),
+ ms.m_mesh->GetIndexCache(m_material),
+ drawmode,
+ ms.m_bObjectColor,
+ ms.m_RGBAcolor,
+ displaylist);
+ }
+
+ // Use the normal IndexPrimitives
else
- rasty->IndexPrimitives(ms);
+ {
+ rasty->IndexPrimitives(
+ ms.m_mesh->GetVertexCache(m_material),
+ ms.m_mesh->GetIndexCache(m_material),
+ drawmode,
+ ms.m_bObjectColor,
+ ms.m_RGBAcolor,
+ displaylist);
+ }
- if(rasty->QueryLists())
+ if(rasty->QueryLists()) {
if(ms.m_DisplayList)
ms.m_mesh->SetMeshModified(false);
+ }
rendertools->PopMatrix();
}
-void RAS_MaterialBucket::Optimize(MT_Scalar distance)
+void RAS_MaterialBucket::Render(const MT_Transform& cameratrans,
+ RAS_IRasterizer* rasty,
+ RAS_IRenderTools* rendertools)
{
- /* TODO: still have to check before this works correct:
- * - lightlayer, frontface, text, billboard
- * - make it work with physics */
+ if (m_meshSlots.begin()== m_meshSlots.end())
+ return;
+
+ //rendertools->SetViewMat(cameratrans);
+
+ //rasty->SetMaterial(*m_material);
-#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
+ RAS_IRasterizer::DrawMode drawmode;
+ for (T_MeshSlotList::const_iterator it = m_meshSlots.begin();
+ ! (it == m_meshSlots.end()); ++it)
+ {
+ rendertools->SetClientObject((*it).m_clientObj);
+ while (ActivateMaterial(cameratrans, rasty, rendertools, drawmode)) {
+ RenderMeshSlot(cameratrans, rasty, rendertools, *it, drawmode);
+ }
+ }
+ // to reset the eventual GL_CW mode
+ rendertools->SetClientObject(NULL);
}
+
diff --git a/source/gameengine/Rasterizer/RAS_MaterialBucket.h b/source/gameengine/Rasterizer/RAS_MaterialBucket.h
index 475f01d549a..4eef889c533 100644
--- a/source/gameengine/Rasterizer/RAS_MaterialBucket.h
+++ b/source/gameengine/Rasterizer/RAS_MaterialBucket.h
@@ -36,15 +36,30 @@
#include "MT_Transform.h"
#include "RAS_IPolygonMaterial.h"
#include "RAS_IRasterizer.h"
-#include "RAS_Deformer.h"
-
+#include "RAS_Deformer.h" // __NLA
#include <vector>
+#include <map>
#include <set>
-#include <list>
using namespace std;
-/* Display List Slot */
+/**
+ * KX_VertexIndex
+ */
+struct KX_VertexIndex {
+public:
+ KX_VertexIndex(int size);
+ void SetIndex(short loc,unsigned int index);
+
+ // The vertex array
+ short m_vtxarray;
+ // An index into the vertex array for up to 4 verticies
+ unsigned short m_indexarray[4];
+ short m_size;
+};
+/**
+ * KX_ListSlot.
+ */
class KX_ListSlot
{
protected:
@@ -65,149 +80,91 @@ public:
virtual void SetModified(bool mod)=0;
};
-class RAS_DisplayArray;
-class RAS_MeshSlot;
-class RAS_MeshMaterial;
-class RAS_MaterialBucket;
-
-/* An array with data used for OpenGL drawing */
-
-class RAS_DisplayArray
-{
-public:
- vector<RAS_TexVert> m_vertex;
- vector<unsigned short> m_index;
- enum { LINE = 2, TRIANGLE = 3, QUAD = 4 } m_type;
- //RAS_MeshSlot *m_origSlot;
- int m_users;
-
- enum { BUCKET_MAX_INDEX = 65535 };
- enum { BUCKET_MAX_VERTEX = 65535 };
-};
-
-/* Entry of a RAS_MeshObject into RAS_MaterialBucket */
-
-class RAS_MeshSlot
+/**
+ * KX_MeshSlot.
+ */
+class KX_MeshSlot
{
-private:
- // indices into display arrays
- int m_startarray;
- int m_endarray;
- int m_startindex;
- int m_endindex;
- int m_startvertex;
- int m_endvertex;
- vector<RAS_DisplayArray*> 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;
- double* 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 AddPolygon(int numverts);
- int AddVertex(const RAS_TexVert& tv);
- void AddPolygonVertex(int offset);
-
- /* optimization */
- bool Split(bool force=false);
- bool Join(RAS_MeshSlot *target, MT_Scalar distance);
- bool Equals(RAS_MeshSlot *target);
- bool IsCulled();
+ void* m_clientObj;
+ RAS_Deformer* m_pDeformer; // __NLA
+ double* m_OpenGLMatrix;
+ class RAS_MeshObject* m_mesh;
+ mutable bool m_bVisible; // for visibility
+ mutable bool m_bObjectColor;
+ mutable MT_Vector4 m_RGBAcolor;
+ mutable KX_ListSlot* m_DisplayList; // for lists
+ KX_MeshSlot() :
+ m_pDeformer(NULL),
+ m_bVisible(true),
+ m_DisplayList(0)
+ {
+ }
+ ~KX_MeshSlot();
+ bool Less(const KX_MeshSlot& lhs) const;
};
-/* Used by RAS_MeshObject, to point to it's slots in a bucket */
-class RAS_MeshMaterial
+inline bool operator <( const KX_MeshSlot& rhs,const KX_MeshSlot& lhs)
{
-public:
- RAS_MeshSlot *m_baseslot;
- class RAS_MaterialBucket *m_bucket;
-
- GEN_Map<GEN_HashedPtr,RAS_MeshSlot*> m_slots;
-};
-
-/* Contains a list of display arrays with the same material,
- * and a mesh slot for each mesh that uses display arrays in
- * this bucket */
+ return ( rhs.Less(lhs));
+}
+/**
+ * Contains a list of meshs with the same material properties.
+ */
class RAS_MaterialBucket
{
public:
+ typedef std::set<KX_MeshSlot> T_MeshSlotList;
+
RAS_MaterialBucket(RAS_IPolyMaterial* mat);
- virtual ~RAS_MaterialBucket();
+ virtual ~RAS_MaterialBucket() {}
+
+ void Render(const MT_Transform& cameratrans,
+ class RAS_IRasterizer* rasty,
+ class RAS_IRenderTools* rendertools);
- /* Bucket Sorting */
- struct less;
- typedef set<RAS_MaterialBucket*, less> Set;
-
- /* Material Properties */
RAS_IPolyMaterial* GetPolyMaterial() const;
- bool IsAlpha() const;
- bool IsZSort() const;
+ bool IsAlpha() const;
+ bool IsZSort() const;
- /* Rendering */
- bool ActivateMaterial(const MT_Transform& cameratrans, RAS_IRasterizer* rasty,
- RAS_IRenderTools *rendertools);
- void RenderMeshSlot(const MT_Transform& cameratrans, RAS_IRasterizer* rasty,
- RAS_IRenderTools* rendertools, RAS_MeshSlot &ms);
-
- /* Mesh Slot Access */
- list<RAS_MeshSlot>::iterator msBegin();
- list<RAS_MeshSlot>::iterator msEnd();
+ static void StartFrame();
+ static void EndFrame();
- 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 SetMeshSlot(KX_MeshSlot& ms);
+ void RemoveMeshSlot(KX_MeshSlot& ms);
+ void MarkVisibleMeshSlot(KX_MeshSlot& ms,
+ bool visible,
+ bool color,
+ const MT_Vector4& rgbavec);
+ void RenderMeshSlot(const MT_Transform& cameratrans, RAS_IRasterizer* rasty,
+ RAS_IRenderTools* rendertools, const KX_MeshSlot &ms, RAS_IRasterizer::DrawMode drawmode);
+ bool ActivateMaterial(const MT_Transform& cameratrans, RAS_IRasterizer* rasty,
+ RAS_IRenderTools *rendertools, RAS_IRasterizer::DrawMode& drawmode);
+
+ unsigned int NumMeshSlots();
+ T_MeshSlotList::iterator msBegin();
+ T_MeshSlotList::iterator msEnd();
+
+ struct less
+ {
+ bool operator()(const RAS_MaterialBucket* x, const RAS_MaterialBucket* y) const
+ {
+ return *x->GetPolyMaterial() < *y->GetPolyMaterial();
+ }
+ };
+
+ typedef set<RAS_MaterialBucket*, less> Set;
private:
- list<RAS_MeshSlot> m_meshSlots;
+
+ T_MeshSlotList m_meshSlots;
+ bool m_bModified;
RAS_IPolyMaterial* m_material;
+ double* m_pOGLMatrix;
};
-#endif //__RAS_MATERIAL_BUCKET
+#endif //__KX_BUCKET
diff --git a/source/gameengine/Rasterizer/RAS_MeshObject.cpp b/source/gameengine/Rasterizer/RAS_MeshObject.cpp
index a907994bf57..af5228e4c35 100644
--- a/source/gameengine/Rasterizer/RAS_MeshObject.cpp
+++ b/source/gameengine/Rasterizer/RAS_MeshObject.cpp
@@ -26,6 +26,10 @@
* ***** END GPL LICENSE BLOCK *****
*/
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
#include "RAS_MeshObject.h"
#include "RAS_IRasterizer.h"
#include "MT_MinMax.h"
@@ -33,85 +37,63 @@
#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();
- }
+STR_String RAS_MeshObject::s_emptyname = "";
- /* 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
+KX_ArrayOptimizer::~KX_ArrayOptimizer()
{
- bool operator()(const polygonSlot &a, const polygonSlot &b) const
+ for (vector<KX_VertexArray*>::iterator itv = m_VertexArrayCache1.begin();
+ !(itv == m_VertexArrayCache1.end());++itv)
{
- return a.m_z < b.m_z;
+ delete (*itv);
}
-};
-struct RAS_MeshObject::fronttoback
-{
- bool operator()(const polygonSlot &a, const polygonSlot &b) const
+ for (vector<KX_IndexArray*>::iterator iti = m_IndexArrayCache1.begin();
+ !(iti == m_IndexArrayCache1.end());++iti)
{
- return a.m_z > b.m_z;
+ delete (*iti);
}
-};
+
+ m_TriangleArrayCount.clear();
+ m_VertexArrayCache1.clear();
+ m_IndexArrayCache1.clear();
+
+
+}
-/* mesh object */
-STR_String RAS_MeshObject::s_emptyname = "";
RAS_MeshObject::RAS_MeshObject(Mesh* mesh, int lightlayer)
- : m_lightlayer(lightlayer),
- m_bModified(true),
- m_bMeshModified(true),
+ : m_bModified(true),
+ m_lightlayer(lightlayer),
+ m_zsort(false),
+ m_MeshMod(true),
m_mesh(mesh),
- m_bDeformed(false)
+ m_class(0)
{
}
-RAS_MeshObject::~RAS_MeshObject()
-{
- vector<RAS_Polygon*>::iterator it;
- for(it=m_Polygons.begin(); it!=m_Polygons.end(); it++)
- delete (*it);
+bool RAS_MeshObject::MeshModified()
+{
+ return m_MeshMod;
}
-bool RAS_MeshObject::MeshModified()
+
+RAS_MeshObject::~RAS_MeshObject()
{
- return m_bMeshModified;
+ for (vector<RAS_Polygon*>::iterator it=m_Polygons.begin();!(it==m_Polygons.end());it++)
+ {
+ delete (*it);
+ }
+
+ ClearArrayData();
}
+
+
unsigned int RAS_MeshObject::GetLightLayer()
{
return m_lightlayer;
@@ -126,21 +108,18 @@ int RAS_MeshObject::NumMaterials()
const STR_String& RAS_MeshObject::GetMaterialName(unsigned int matid)
{
- RAS_MeshMaterial* mmat = GetMeshMaterial(matid);
-
- if(mmat)
- return mmat->m_bucket->GetPolyMaterial()->GetMaterialName();
+ RAS_MaterialBucket* bucket = GetMaterialBucket(matid);
- return s_emptyname;
+ return bucket?bucket->GetPolyMaterial()->GetMaterialName():s_emptyname;
}
-RAS_MeshMaterial* RAS_MeshObject::GetMeshMaterial(unsigned int matid)
+RAS_MaterialBucket* RAS_MeshObject::GetMaterialBucket(unsigned int matid)
{
if (m_materials.size() > 0 && (matid < m_materials.size()))
{
- list<RAS_MeshMaterial>::iterator it = m_materials.begin();
+ RAS_MaterialBucket::Set::const_iterator it = m_materials.begin();
while (matid--) ++it;
- return &*it;
+ return *it;
}
return NULL;
@@ -155,24 +134,21 @@ int RAS_MeshObject::NumPolygons()
-RAS_Polygon* RAS_MeshObject::GetPolygon(int num) const
+RAS_Polygon* RAS_MeshObject::GetPolygon(int num)
{
return m_Polygons[num];
}
-
- list<RAS_MeshMaterial>::iterator GetFirstMaterial();
- list<RAS_MeshMaterial>::iterator GetLastMaterial();
-list<RAS_MeshMaterial>::iterator RAS_MeshObject::GetFirstMaterial()
+RAS_MaterialBucket::Set::iterator RAS_MeshObject::GetFirstMaterial()
{
return m_materials.begin();
}
-list<RAS_MeshMaterial>::iterator RAS_MeshObject::GetLastMaterial()
+RAS_MaterialBucket::Set::iterator RAS_MeshObject::GetLastMaterial()
{
return m_materials.end();
}
@@ -195,238 +171,377 @@ const STR_String& RAS_MeshObject::GetName()
const STR_String& RAS_MeshObject::GetTextureName(unsigned int matid)
{
- RAS_MeshMaterial* mmat = GetMeshMaterial(matid);
+ RAS_MaterialBucket* bucket = GetMaterialBucket(matid);
- if(mmat)
- return mmat->m_bucket->GetPolyMaterial()->GetTextureName();
-
- return s_emptyname;
+ return bucket?bucket->GetPolyMaterial()->GetTextureName():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;
-}
-RAS_Polygon* RAS_MeshObject::AddPolygon(RAS_MaterialBucket *bucket, int numverts)
+void RAS_MeshObject::AddPolygon(RAS_Polygon* poly)
{
- 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);
- 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++) {
+/*
+ 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);
+ {
+ RAS_TexVert* vtx = poly->GetVertex(v);
+ vtx->setDebugRGBA(abgr);
+ }
}
*/
- /* m_debugcolor = 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& uv,
- const MT_Point2& uv2,
- const MT_Vector4& tangent,
- const unsigned int rgba,
- const MT_Vector3& normal,
- bool flat,
- int origindex)
-{
- RAS_TexVert texvert(xyz, uv, uv2, 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();
+ const vecVertexArray & vertexvec = GetVertexCache(mat);
+
+ for (vector<KX_VertexArray*>::const_iterator it = vertexvec.begin(); it != vertexvec.end(); ++it)
+ {
+ KX_VertexArray::iterator vit;
+ for (vit=(*it)->begin(); vit != (*it)->end(); vit++)
+ {
+ vit->SetRGBA(rgba);
+ }
+ }
+}
+
+void RAS_MeshObject::SchedulePoly(const KX_VertexIndex& idx,
+ int numverts,
+ RAS_IPolyMaterial* mat)
+{
+ KX_ArrayOptimizer* ao = GetArrayOptimizer(mat);
+
+ ao->m_IndexArrayCache1[idx.m_vtxarray]->push_back(idx.m_indexarray[0]);
+ ao->m_IndexArrayCache1[idx.m_vtxarray]->push_back(idx.m_indexarray[1]);
+ ao->m_IndexArrayCache1[idx.m_vtxarray]->push_back(idx.m_indexarray[2]);
+
+ if (!mat->UsesTriangles())
+ ao->m_IndexArrayCache1[idx.m_vtxarray]->push_back(idx.m_indexarray[3]);
+}
- if(!flat) {
- /* 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++)
+void RAS_MeshObject::ScheduleWireframePoly(const KX_VertexIndex& idx,
+ int numverts,
+ int edgecode,
+ RAS_IPolyMaterial* mat)
+{
+ //int indexpos = m_IndexArrayCount[idx.m_vtxarray];
+ int edgetrace = 1<<(numverts-1);
+ bool drawedge = (edgecode & edgetrace)!=0;
+ edgetrace = 1;
+ int prevvert = idx.m_indexarray[numverts-1];
+ KX_ArrayOptimizer* ao = GetArrayOptimizer(mat);
+
+ for (int v = 0; v < numverts; v++)
+ {
+ unsigned int curvert = idx.m_indexarray[v];
+ if (drawedge)
{
- 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;
+ ao->m_IndexArrayCache1[idx.m_vtxarray]->push_back(prevvert);
+ ao->m_IndexArrayCache1[idx.m_vtxarray]->push_back(curvert);
}
+ prevvert = curvert;
+ drawedge = (edgecode & edgetrace)!=0;
+ edgetrace*=2;
}
+ //m_IndexArrayCount[idx.m_vtxarray] = indexpos;
+}
- /* no shared vertex found, add a new one */
- offset = slot->AddVertex(texvert);
- if(poly->IsVisible())
- slot->AddPolygonVertex(offset);
- poly->SetVertexOffset(i, offset);
+int RAS_MeshObject::FindOrAddVertex(int vtxarray,
+ const MT_Point3& xyz,
+ const MT_Point2& uv,
+ const MT_Point2& uv2,
+ const MT_Vector4& tangent,
+ const unsigned int rgbacolor,
+ const MT_Vector3& normal,
+ bool flat,
+ RAS_IPolyMaterial* mat,
+ int origindex)
+{
+ KX_ArrayOptimizer* ao = GetArrayOptimizer(mat);
+
+ int numverts = ao->m_VertexArrayCache1[vtxarray]->size();//m_VertexArrayCount[vtxarray];
+ RAS_TexVert newvert(xyz,uv,uv2,tangent,rgbacolor,normal, flat? TV_CALCFACENORMAL: 0,origindex);
+#define KX_FIND_SHARED_VERTICES
+#ifdef KX_FIND_SHARED_VERTICES
if(!flat) {
- SharedVertex shared;
- shared.m_darray = darray;
- shared.m_offset = offset;
- m_sharedvertex_map[origindex].push_back(shared);
+ for (std::vector<RAS_MatArrayIndex>::iterator it = m_xyz_index_to_vertex_index_mapping[origindex].begin();
+ it != m_xyz_index_to_vertex_index_mapping[origindex].end();
+ it++)
+ {
+ if ((*it).m_arrayindex1 == ao->m_index1 &&
+ (*it).m_array == vtxarray &&
+ *(*it).m_matid == *mat &&
+ (*ao->m_VertexArrayCache1[vtxarray])[(*it).m_index].closeTo(&newvert)
+ )
+ {
+ return (*it).m_index;
+ }
+ }
}
+#endif // KX_FIND_SHARED_VERTICES
+
+ // no vertex found, add one
+ ao->m_VertexArrayCache1[vtxarray]->push_back(newvert);
+ // printf("(%f,%f,%f) ",xyz[0],xyz[1],xyz[2]);
+ RAS_MatArrayIndex idx;
+ idx.m_arrayindex1 = ao->m_index1;
+ idx.m_array = vtxarray;
+ idx.m_index = numverts;
+ idx.m_matid = mat;
+ m_xyz_index_to_vertex_index_mapping[origindex].push_back(idx);
+
+ return numverts;
}
-int RAS_MeshObject::NumVertices(RAS_IPolyMaterial* mat)
+vecVertexArray& RAS_MeshObject::GetVertexCache (RAS_IPolyMaterial* mat)
{
- RAS_MeshMaterial *mmat;
- RAS_MeshSlot *slot;
- RAS_MeshSlot::iterator it;
- size_t len = 0;
+ KX_ArrayOptimizer* ao = GetArrayOptimizer(mat);
+
+ return ao->m_VertexArrayCache1;
+}
- mmat = GetMeshMaterial(mat);
- slot = mmat->m_baseslot;
- for(slot->begin(it); !slot->end(it); slot->next(it))
- len += it.endvertex - it.startvertex;
+int RAS_MeshObject::GetVertexArrayLength(RAS_IPolyMaterial* mat)
+{
+ int len = 0;
+
+ const vecVertexArray & vertexvec = GetVertexCache(mat);
+ vector<KX_VertexArray*>::const_iterator it = vertexvec.begin();
+ for (; it != vertexvec.end(); ++it)
+ {
+ len += (*it)->size();
+ }
+
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;
+ RAS_TexVert* vertex = NULL;
+
+ RAS_MaterialBucket* bucket = GetMaterialBucket(matid);
+ if (bucket)
+ {
+ RAS_IPolyMaterial* mat = bucket->GetPolyMaterial();
+ if (mat)
+ {
+ const vecVertexArray & vertexvec = GetVertexCache(mat);
+ vector<KX_VertexArray*>::const_iterator it = vertexvec.begin();
+
+ for (unsigned int len = 0; it != vertexvec.end(); ++it)
+ {
+ if (index < len + (*it)->size())
+ {
+ vertex = &(*(*it))[index-len];
+ break;
+ }
+ else
+ {
+ len += (*it)->size();
+ }
+ }
+ }
+ }
+
+ return vertex;
+}
+
+
- mmat = GetMeshMaterial(matid);
+const vecIndexArrays& RAS_MeshObject::GetIndexCache (RAS_IPolyMaterial* mat)
+{
+ KX_ArrayOptimizer* ao = GetArrayOptimizer(mat);
+
+ return ao->m_IndexArrayCache1;
+}
- if(!mmat)
- return NULL;
+
+
+KX_ArrayOptimizer* RAS_MeshObject::GetArrayOptimizer(RAS_IPolyMaterial* polymat)
+{
+ KX_ArrayOptimizer** aop = m_matVertexArrayS[polymat];
+
+ if(aop)
+ return *aop;
- 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];
+ // didn't find array, but an array might already exist
+ // for a material equal to this one
+ for(int i=0;i<m_matVertexArrayS.size();i++) {
+ RAS_IPolyMaterial *mat = (RAS_IPolyMaterial*)(m_matVertexArrayS.getKey(i)->getValue());
+ if(*mat == *polymat) {
+ m_matVertexArrayS.insert(polymat, *m_matVertexArrayS.at(i));
+ return *m_matVertexArrayS.at(i);
+ }
}
+
+ // create new array
+ int numelements = m_matVertexArrayS.size();
+ m_sortedMaterials.push_back(polymat);
+
+ KX_ArrayOptimizer* ao = new KX_ArrayOptimizer(numelements);
+ m_matVertexArrayS.insert(polymat, ao);
- return NULL;
+ return ao;
}
-void RAS_MeshObject::AddMeshUser(void *clientobj)
+
+
+void RAS_MeshObject::Bucketize(double* oglmatrix,
+ void* clientobj,
+ bool useObjectColor,
+ const MT_Vector4& rgbavec)
{
- list<RAS_MeshMaterial>::iterator it;
+ KX_MeshSlot ms;
+ ms.m_clientObj = clientobj;
+ ms.m_mesh = this;
+ ms.m_OpenGLMatrix = oglmatrix;
+ ms.m_bObjectColor = useObjectColor;
+ ms.m_RGBAcolor = rgbavec;
+
+ for (RAS_MaterialBucket::Set::iterator it = m_materials.begin();it!=m_materials.end();++it)
+ {
+ RAS_MaterialBucket* bucket = *it;
+// KX_ArrayOptimizer* oa = GetArrayOptimizer(bucket->GetPolyMaterial());
+ bucket->SetMeshSlot(ms);
+ }
- 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 */
- RAS_MeshSlot *ms = it->m_bucket->CopyMesh(it->m_baseslot);
- ms->m_clientObj = clientobj;
- it->m_slots.insert(clientobj, ms);
+}
+
+
+
+void RAS_MeshObject::MarkVisible(double* oglmatrix,
+ void* clientobj,
+ bool visible,
+ bool useObjectColor,
+ const MT_Vector4& rgbavec)
+{
+ KX_MeshSlot ms;
+ ms.m_clientObj = clientobj;
+ ms.m_mesh = this;
+ ms.m_OpenGLMatrix = oglmatrix;
+ ms.m_RGBAcolor = rgbavec;
+ ms.m_bObjectColor= useObjectColor;
+
+ for (RAS_MaterialBucket::Set::iterator it = m_materials.begin();it!=m_materials.end();++it)
+ {
+ RAS_MaterialBucket* bucket = *it;
+// KX_ArrayOptimizer* oa = GetArrayOptimizer(bucket->GetPolyMaterial());
+ bucket->MarkVisibleMeshSlot(ms,visible,useObjectColor,rgbavec);
}
}
-void RAS_MeshObject::UpdateBuckets(void* clientobj,
- double* oglmatrix,
- bool useObjectColor,
- const MT_Vector4& rgbavec,
- bool visible,
- bool culled)
+
+void RAS_MeshObject::RemoveFromBuckets(double* oglmatrix,
+ void* clientobj)
{
- list<RAS_MeshMaterial>::iterator it;
+ KX_MeshSlot ms;
+ ms.m_clientObj = clientobj;
+ ms.m_mesh = this;
+ ms.m_OpenGLMatrix = oglmatrix;
- for(it = m_materials.begin();it!=m_materials.end();++it) {
- RAS_MeshSlot **msp = it->m_slots[clientobj];
+ for (RAS_MaterialBucket::Set::iterator it = m_materials.begin();it!=m_materials.end();++it)
+ {
+ RAS_MaterialBucket* bucket = *it;
+// RAS_IPolyMaterial* polymat = bucket->GetPolyMaterial();
+ //KX_ArrayOptimizer* oa = GetArrayOptimizer(polymat);
+ bucket->RemoveMeshSlot(ms);
+ }
- if(!msp)
- continue;
+}
+
+
+
+/*
+ * RAS_MeshObject::GetVertex returns the vertex located somewhere in the vertexpool
+ * it is the clients responsibility to make sure the array and index are valid
+ */
+RAS_TexVert* RAS_MeshObject::GetVertex(short array,
+ unsigned int index,
+ RAS_IPolyMaterial* polymat)
+{
+ KX_ArrayOptimizer* ao = GetArrayOptimizer(polymat);
+ return &((*(ao->m_VertexArrayCache1)[array])[index]);
+}
- RAS_MeshSlot *ms = *msp;
- ms->m_mesh = this;
- ms->m_OpenGLMatrix = oglmatrix;
- ms->m_bObjectColor = useObjectColor;
- ms->m_RGBAcolor = rgbavec;
- ms->m_bVisible = visible;
- ms->m_bCulled = culled || !visible;
- /* split if necessary */
- ms->Split();
+void RAS_MeshObject::ClearArrayData()
+{
+ for (int i=0;i<m_matVertexArrayS.size();i++) {
+ KX_ArrayOptimizer** ao = m_matVertexArrayS.at(i);
+
+ // we have duplicate entries, only free once
+ for(int j=i+1;j<m_matVertexArrayS.size();j++) {
+ if(ao == m_matVertexArrayS.at(j)) {
+ ao = NULL;
+ break;
+ }
+ }
+
+ if (ao)
+ delete *ao;
}
}
-void RAS_MeshObject::RemoveFromBuckets(void *clientobj)
+
+
+/**
+ * RAS_MeshObject::CreateNewVertices creates vertices within sorted pools of vertices that share same material
+*/
+int RAS_MeshObject::FindVertexArray(int numverts,
+ RAS_IPolyMaterial* polymat)
{
- list<RAS_MeshMaterial>::iterator it;
+// bool found=false;
+ int array=-1;
- for(it = m_materials.begin();it!=m_materials.end();++it) {
- RAS_MeshSlot **msp = it->m_slots[clientobj];
+ KX_ArrayOptimizer* ao = GetArrayOptimizer(polymat);
- if(!msp)
- continue;
-
- RAS_MeshSlot *ms = *msp;
+ for (unsigned int i=0;i<ao->m_VertexArrayCache1.size();i++)
+ {
+ if ( (ao->m_TriangleArrayCount[i] + (numverts-2)) < BUCKET_MAX_TRIANGLES)
+ {
+ if((ao->m_VertexArrayCache1[i]->size()+numverts < BUCKET_MAX_INDICES))
+ {
+ array = i;
+ ao->m_TriangleArrayCount[array]+=numverts-2;
+ break;
+ }
+ }
+ }
- it->m_bucket->RemoveMesh(ms);
- it->m_slots.remove(clientobj);
+ if (array == -1)
+ {
+ array = ao->m_VertexArrayCache1.size();
+ vector<RAS_TexVert>* va = new vector<RAS_TexVert>;
+ ao->m_VertexArrayCache1.push_back(va);
+ KX_IndexArray *ia = new KX_IndexArray();
+ ao->m_IndexArrayCache1.push_back(ia);
+ ao->m_TriangleArrayCount.push_back(numverts-2);
}
+
+ return array;
}
+
+
+
//void RAS_MeshObject::Transform(const MT_Transform& trans)
//{
//m_trans.translate(MT_Vector3(0,0,1));//.operator *=(trans);
@@ -448,7 +563,71 @@ void RAS_MeshObject::RelativeTransform(const MT_Vector3& vec)
}
*/
-void RAS_MeshObject::SortPolygons(RAS_MeshSlot& ms, const MT_Transform &transform)
+
+
+void RAS_MeshObject::UpdateMaterialList()
+{
+ m_materials.clear();
+ unsigned int numpolys = m_Polygons.size();
+ // for all polygons, find out which material they use, and add it to the set of materials
+ for (unsigned int i=0;i<numpolys;i++)
+ {
+ m_materials.insert(m_Polygons[i]->GetMaterial());
+ }
+}
+
+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 KX_VertexArray& vertexarray, const KX_IndexArray& 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]].getLocalXYZ();
+ }
+
+ /* 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(KX_IndexArray& 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;
+ }
+};
+
+void RAS_MeshObject::SortPolygons(const MT_Transform &transform)
{
// Limitations: sorting is quite simple, and handles many
// cases wrong, partially due to polygons being sorted per
@@ -466,34 +645,43 @@ void RAS_MeshObject::SortPolygons(RAS_MeshSlot& ms, const MT_Transform &transfor
// to avoid excessive state changes while drawing. e) would
// require splitting polygons.
- RAS_MeshSlot::iterator it;
- size_t j;
+ if (!m_zsort)
+ return;
- for(ms.begin(it); !ms.end(it); ms.next(it)) {
- unsigned int nvert = (int)it.array->m_type;
- unsigned int totpoly = it.totindex/nvert;
+ // Extract camera Z plane...
+ const MT_Vector3 pnorm(transform.getBasis()[2]);
+ // unneeded: const MT_Scalar pval = transform.getOrigin()[2];
- if(totpoly <= 1)
- continue;
- if(it.array->m_type == RAS_DisplayArray::LINE)
+ for (RAS_MaterialBucket::Set::iterator it = m_materials.begin();it!=m_materials.end();++it)
+ {
+ if(!(*it)->IsZSort())
continue;
- // Extract camera Z plane...
- const MT_Vector3 pnorm(transform.getBasis()[2]);
- // unneeded: const MT_Scalar pval = transform.getOrigin()[2];
+ RAS_IPolyMaterial *mat = (*it)->GetPolyMaterial();
+ KX_ArrayOptimizer* ao = GetArrayOptimizer(mat);
- vector<polygonSlot> slots(totpoly);
+ vecIndexArrays& indexarrays = ao->m_IndexArrayCache1;
+ vecVertexArray& vertexarrays = ao->m_VertexArrayCache1;
+ unsigned int i, j, nvert = (mat->UsesTriangles())? 3: 4;
- /* get indices and z into temporary array */
- for(j=0; j<totpoly; j++)
- slots[j].get(it.vertex, it.index, j*nvert, nvert, pnorm);
+ for(i=0; i<indexarrays.size(); i++) {
+ KX_IndexArray& indexarray = *indexarrays[i];
+ KX_VertexArray& vertexarray = *vertexarrays[i];
- /* sort (stable_sort might be better, if flickering happens?) */
- std::sort(slots.begin(), slots.end(), backtofront());
+ unsigned int totpoly = indexarray.size()/nvert;
+ vector<polygonSlot> slots(totpoly);
- /* get indices from temporary array again */
- for(j=0; j<totpoly; j++)
- slots[j].set(it.index, j*nvert, nvert);
+ /* get indices and z into temporary array */
+ for(j=0; j<totpoly; j++)
+ slots[j].get(vertexarray, indexarray, j*nvert, nvert, pnorm);
+
+ /* sort (stable_sort might be better, if flickering happens?) */
+ std::sort(slots.begin(), slots.end(), backtofront());
+
+ /* get indices from temporary array again */
+ for(j=0; j<totpoly; j++)
+ slots[j].set(indexarray, j*nvert, nvert);
+ }
}
}
@@ -502,8 +690,37 @@ void RAS_MeshObject::SchedulePolygons(int drawingmode)
{
if (m_bModified)
{
+ int i, numpolys = m_Polygons.size();
+
+ for (RAS_MaterialBucket::Set::iterator it = m_materials.begin();it!=m_materials.end();++it)
+ if ((*it)->IsZSort())
+ m_zsort = true;
+
+ if (drawingmode == RAS_IRasterizer::KX_WIREFRAME)
+ {
+ for (i=0;i<numpolys;i++)
+ {
+ RAS_Polygon* poly = m_Polygons[i];
+ if (poly->IsVisible())
+ ScheduleWireframePoly(poly->GetVertexIndexBase(),poly->VertexCount(),poly->GetEdgeCode(),
+ poly->GetMaterial()->GetPolyMaterial());
+
+ }
+ m_zsort = false;
+ }
+ else
+ {
+ for (i=0;i<numpolys;i++)
+ {
+ RAS_Polygon* poly = m_Polygons[i];
+ if (poly->IsVisible())
+ SchedulePoly(poly->GetVertexIndexBase(),poly->VertexCount(),
+ poly->GetMaterial()->GetPolyMaterial());
+ }
+ }
+
m_bModified = false;
- m_bMeshModified = true;
+ m_MeshMod = true;
}
}
diff --git a/source/gameengine/Rasterizer/RAS_MeshObject.h b/source/gameengine/Rasterizer/RAS_MeshObject.h
index 0d35a2f402b..99806666fa6 100644
--- a/source/gameengine/Rasterizer/RAS_MeshObject.h
+++ b/source/gameengine/Rasterizer/RAS_MeshObject.h
@@ -36,7 +36,6 @@
#include <vector>
#include <set>
-#include <list>
#include "RAS_Polygon.h"
#include "RAS_MaterialBucket.h"
@@ -45,71 +44,194 @@
#include "GEN_HashedPtr.h"
struct Mesh;
+/**
+ * This class holds an array of vertices and indicies.
+ */
+class KX_ArrayOptimizer
+{
+public:
+ KX_ArrayOptimizer(int index)
+ : m_index1(index)
+ {};
+ virtual ~KX_ArrayOptimizer();
+
+ vector<KX_VertexArray*> m_VertexArrayCache1;
+ vector<int> m_TriangleArrayCount;
+ vector<KX_IndexArray*> m_IndexArrayCache1;
+
+ /**
+ order in which they are stored into the mesh
+ */
+ int m_index1;
+};
+
+/**
+ * This struct holds a triangle.
+ */
+struct RAS_TriangleIndex
+{
+public:
+ int m_index[3];
+ int m_array;
+ RAS_IPolyMaterial* m_matid;
+ bool m_collider;
+};
+
+/**
+ * This class looks horribly broken. Only m_matid is used, and
+ * m_matid is a (int) RAS_IPolyMaterial*.
+ * --> m_matid == lhs.m_matid should be *m_matid == *lhs.m_matid
+ */
+class RAS_MatArrayIndex
+{
+public:
-/* 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. */
+ int m_arrayindex1;
+ RAS_IPolyMaterial* m_matid;
+ int m_array;
+ int m_index;
+
+/*
+ inline bool Less(const RAS_MatArrayIndex& lhs) const {
+ bool result =
+ ( (m_matid < lhs.m_matid) ||
+ ((m_matid == lhs.m_matid)&&(m_array < lhs.m_array)) ||
+ ((m_matid == lhs.m_matid) && (m_array == lhs.m_array) &&
+ (m_index < lhs.m_index))
+
+ );
+ return result;
+
+ }
+*/
+
+};
+/*
+inline bool operator <( const RAS_MatArrayIndex& rhs,const RAS_MatArrayIndex& lhs)
+{
+ return ( rhs.Less(lhs));
+}*/
+/**
+ * RAS_MeshObject stores mesh data for the renderer.
+ */
class RAS_MeshObject
{
-private:
+
+ // GEN_Map<class RAS_IPolyMaterial,KX_ArrayOptimizer*> m_matVertexArrayS;
+ //vector<class RAS_IPolyMaterial*,KX_ArrayOptimizer> m_vertexArrays;
+ virtual KX_ArrayOptimizer* GetArrayOptimizer(RAS_IPolyMaterial* polymat);
+ //vector<RAS_Polygon*> m_polygons;
+
unsigned int m_debugcolor;
- int m_lightlayer;
-
bool m_bModified;
- bool m_bMeshModified;
-
+ int m_lightlayer;
+
+ vector<class RAS_Polygon*> m_Polygons;
STR_String m_name;
static STR_String s_emptyname;
+ bool m_zsort;
+ bool m_MeshMod;
- vector<class RAS_Polygon*> m_Polygons;
-
- /* polygon sorting */
struct polygonSlot;
struct backtofront;
struct fronttoback;
+ void SchedulePoly(
+ const KX_VertexIndex& idx,
+ int numverts,
+ RAS_IPolyMaterial* mat
+ );
+
+ void ScheduleWireframePoly(
+ const KX_VertexIndex& idx,
+ int numverts,
+ int edgecode,
+ RAS_IPolyMaterial* mat
+ );
+
protected:
- list<RAS_MeshMaterial> m_materials;
+ enum { BUCKET_MAX_INDICES = 65535 };//2048};//8192};
+ enum { BUCKET_MAX_TRIANGLES = 65535 };
+
+ GEN_Map<GEN_HashedPtr,KX_ArrayOptimizer*> m_matVertexArrayS;
+
+ RAS_MaterialBucket::Set m_materials;
Mesh* m_mesh;
- bool m_bDeformed;
-
public:
// for now, meshes need to be in a certain layer (to avoid sorting on lights in realtime)
RAS_MeshObject(Mesh* mesh, int lightlayer);
virtual ~RAS_MeshObject();
-
- bool IsDeformed() { return m_bDeformed; }
+ vector<RAS_IPolyMaterial*> m_sortedMaterials;
+ vector<vector<RAS_MatArrayIndex> > m_xyz_index_to_vertex_index_mapping;
+ vector<RAS_TriangleIndex > m_triangle_indices;
- /* materials */
+ int m_class;
+
+ unsigned int GetLightLayer();
int NumMaterials();
const STR_String& GetMaterialName(unsigned int matid);
+ RAS_MaterialBucket* GetMaterialBucket(unsigned int matid);
const STR_String& GetTextureName(unsigned int matid);
+ virtual void AddPolygon(RAS_Polygon* poly);
+ void UpdateMaterialList();
+
+ int NumPolygons();
+ RAS_Polygon* GetPolygon(int num);
+
+ virtual void Bucketize(
+ double* oglmatrix,
+ void* clientobj,
+ bool useObjectColor,
+ const MT_Vector4& rgbavec
+ );
- RAS_MeshMaterial* GetMeshMaterial(unsigned int matid);
- RAS_MeshMaterial* GetMeshMaterial(RAS_IPolyMaterial *mat);
-
- list<RAS_MeshMaterial>::iterator GetFirstMaterial();
- list<RAS_MeshMaterial>::iterator GetLastMaterial();
+ void RemoveFromBuckets(
+ double* oglmatrix,
+ void* clientobj
+ );
- unsigned int GetLightLayer();
+ void MarkVisible(
+ double* oglmatrix,
+ void* clientobj,
+ bool visible,
+ bool useObjectColor,
+ const MT_Vector4& rgbavec
+ );
- /* name */
- void SetName(STR_String name);
- const STR_String& GetName();
+ void DebugColor(unsigned int abgr);
+ void SetVertexColor(RAS_IPolyMaterial* mat,MT_Vector4 rgba);
+
+ /**
+ * Sorts the polygons by their transformed z values.
+ */
+ void SortPolygons(const MT_Transform &transform);
- /* modification state */
- bool MeshModified();
- void SetMeshModified(bool v){m_bMeshModified = v;}
+ void SchedulePolygons(int drawingmode);
- /* original blender mesh */
- Mesh* GetMesh() { return m_mesh; }
+ void ClearArrayData();
+
+ RAS_MaterialBucket::Set::iterator GetFirstMaterial();
+ RAS_MaterialBucket::Set::iterator GetLastMaterial();
+
+ virtual RAS_TexVert* GetVertex(
+ short array,
+ unsigned int index,
+ RAS_IPolyMaterial* polymat
+ );
+
+ virtual int FindVertexArray(
+ int numverts,
+ RAS_IPolyMaterial* polymat
+ );
- /* mesh construction */
- virtual RAS_Polygon* AddPolygon(RAS_MaterialBucket *bucket, int numverts);
- virtual void AddVertex(RAS_Polygon *poly, int i,
+ // find (and share) or add vertices
+ // for some speedup, only the last 20 added vertices are searched for equality
+
+ virtual int FindOrAddVertex(
+ int vtxarray,
const MT_Point3& xyz,
const MT_Point2& uv,
const MT_Point2& uv2,
@@ -117,43 +239,27 @@ public:
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);
-
- int NumPolygons();
- RAS_Polygon* GetPolygon(int num) const;
+ RAS_IPolyMaterial* mat,
+ int origindex
+ );
- /* buckets */
- virtual void AddMeshUser(void *clientobj);
- virtual void UpdateBuckets(
- void* clientobj,
- double* oglmatrix,
- bool useObjectColor,
- const MT_Vector4& rgbavec,
- bool visible,
- bool culled);
+ vecVertexArray& GetVertexCache (RAS_IPolyMaterial* mat);
+
+ int GetVertexArrayLength(RAS_IPolyMaterial* mat);
- void RemoveFromBuckets(void *clientobj);
+ RAS_TexVert* GetVertex(
+ unsigned int matid,
+ unsigned int index
+ );
- /* 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);
+ const vecIndexArrays& GetIndexCache (RAS_IPolyMaterial* mat);
+ void SetName(STR_String name);
+ const STR_String& GetName();
- /* for construction to find shared vertices */
- struct SharedVertex {
- RAS_DisplayArray *m_darray;
- int m_offset;
- };
+ bool MeshModified();
+ void SetMeshModified(bool v){m_MeshMod = v;}
+ Mesh* GetMesh() { return m_mesh; }
- vector<vector<SharedVertex> > m_sharedvertex_map;
};
#endif //__RAS_MESHOBJECT
diff --git a/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Blur2DFilter.h b/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Blur2DFilter.h
index 81821639489..33c4b3faab0 100644
--- a/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Blur2DFilter.h
+++ b/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Blur2DFilter.h
@@ -28,7 +28,7 @@
#ifndef __RAS_BLUR2DFILTER
#define __RAS_BLUR2DFILTER
-const char * BlurFragmentShader=STRINGIFY(
+char * BlurFragmentShader=STRINGIFY(
uniform sampler2D bgl_RenderedTexture;
uniform vec2 bgl_TextureCoordinateOffset[9];
diff --git a/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Dilation2DFilter.h b/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Dilation2DFilter.h
index 2ee75396f42..c41e5ac06af 100644
--- a/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Dilation2DFilter.h
+++ b/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Dilation2DFilter.h
@@ -28,7 +28,7 @@
#ifndef __RAS_DILATION2DFILTER
#define __RAS_DILATION2DFILTER
-const char * DilationFragmentShader=STRINGIFY(
+char * DilationFragmentShader=STRINGIFY(
uniform sampler2D bgl_RenderedTexture;
uniform vec2 bgl_TextureCoordinateOffset[9];
diff --git a/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Erosion2DFilter.h b/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Erosion2DFilter.h
index d3ce829bab0..2bb357c958a 100644
--- a/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Erosion2DFilter.h
+++ b/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Erosion2DFilter.h
@@ -28,7 +28,7 @@
#ifndef __RAS_EROSION2DFILTER
#define __RAS_EROSION2DFILTER
-const char * ErosionFragmentShader=STRINGIFY(
+char * ErosionFragmentShader=STRINGIFY(
uniform sampler2D bgl_RenderedTexture;
uniform vec2 bgl_TextureCoordinateOffset[9];
diff --git a/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_GrayScale2DFilter.h b/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_GrayScale2DFilter.h
index ae51308e9a4..7324edd4e92 100644
--- a/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_GrayScale2DFilter.h
+++ b/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_GrayScale2DFilter.h
@@ -28,7 +28,7 @@
#ifndef __RAS_GRAYSCALE2DFILTER
#define __RAS_GRAYSCALE2DFILTER
-const char * GrayScaleFragmentShader=STRINGIFY(
+char * GrayScaleFragmentShader=STRINGIFY(
uniform sampler2D bgl_RenderedTexture;
void main(void)
diff --git a/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Invert2DFilter.h b/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Invert2DFilter.h
index f723f619f68..5d90fe3475b 100644
--- a/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Invert2DFilter.h
+++ b/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Invert2DFilter.h
@@ -28,7 +28,7 @@
#ifndef __RAS_INVERT2DFILTER
#define __RAS_INVERT2DFILTER
-const char * InvertFragmentShader=STRINGIFY(
+char * InvertFragmentShader=STRINGIFY(
uniform sampler2D bgl_RenderedTexture;
void main(void)
diff --git a/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Laplacian2DFilter.h b/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Laplacian2DFilter.h
index bfbb40b2fc9..cbe926976df 100644
--- a/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Laplacian2DFilter.h
+++ b/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Laplacian2DFilter.h
@@ -28,7 +28,7 @@
#ifndef __RAS_LAPLACION2DFILTER
#define __RAS_LAPLACION2DFILTER
-const char * LaplacionFragmentShader=STRINGIFY(
+char * LaplacionFragmentShader=STRINGIFY(
uniform sampler2D bgl_RenderedTexture;
uniform vec2 bgl_TextureCoordinateOffset[9];
diff --git a/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Prewitt2DFilter.h b/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Prewitt2DFilter.h
index 0cbf8a7a802..7cd1082e5e3 100644
--- a/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Prewitt2DFilter.h
+++ b/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Prewitt2DFilter.h
@@ -28,7 +28,7 @@
#ifndef __RAS_PREWITT2DFILTER
#define __RAS_PREWITT2DFILTER
-const char * PrewittFragmentShader=STRINGIFY(
+char * PrewittFragmentShader=STRINGIFY(
uniform sampler2D bgl_RenderedTexture;
uniform vec2 bgl_TextureCoordinateOffset[9];
diff --git a/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Sepia2DFilter.h b/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Sepia2DFilter.h
index ca431af4cd7..d1c16f39823 100644
--- a/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Sepia2DFilter.h
+++ b/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Sepia2DFilter.h
@@ -28,7 +28,7 @@
#ifndef __RAS_SEPIA2DFILTER
#define __RAS_SEPIA2DFILTER
-const char * SepiaFragmentShader=STRINGIFY(
+char * SepiaFragmentShader=STRINGIFY(
uniform sampler2D bgl_RenderedTexture;
void main(void)
diff --git a/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Sharpen2DFilter.h b/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Sharpen2DFilter.h
index 5a9661e2617..14e0be6df9d 100644
--- a/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Sharpen2DFilter.h
+++ b/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Sharpen2DFilter.h
@@ -28,7 +28,7 @@
#ifndef __RAS_SHARPEN2DFILTER
#define __RAS_SHARPEN2DFILTER
-const char * SharpenFragmentShader=STRINGIFY(
+char * SharpenFragmentShader=STRINGIFY(
uniform sampler2D bgl_RenderedTexture;
uniform vec2 bgl_TextureCoordinateOffset[9];
diff --git a/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Sobel2DFilter.h b/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Sobel2DFilter.h
index 142e4f0e3d4..40c17c285ce 100644
--- a/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Sobel2DFilter.h
+++ b/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Sobel2DFilter.h
@@ -28,7 +28,7 @@
#ifndef __RAS_SOBEL2DFILTER
#define __RAS_SOBEL2DFILTER
-const char * SobelFragmentShader=STRINGIFY(
+char * SobelFragmentShader=STRINGIFY(
uniform sampler2D bgl_RenderedTexture;
uniform vec2 bgl_TextureCoordinateOffset[9];
diff --git a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/CMakeLists.txt b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/CMakeLists.txt
index e4403ace69f..2a6d64ecc73 100644
--- a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/CMakeLists.txt
+++ b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/CMakeLists.txt
@@ -32,7 +32,6 @@ SET(INC
../../../../intern/moto/include
../../../../source/gameengine/Rasterizer
../../../../extern/glew/include
- ../../../../source/blender/gpu
)
BLENDERLIB(bf_oglrasterizer "${SRC}" "${INC}")
diff --git a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/Makefile b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/Makefile
index aee485a22be..f01978b8eb1 100644
--- a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/Makefile
+++ b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/Makefile
@@ -41,11 +41,12 @@ CPPFLAGS += -I$(OPENGL_HEADERS)
CPPFLAGS += -I$(NAN_STRING)/include
CPPFLAGS += -I$(NAN_MOTO)/include
CPPFLAGS += -I../../../kernel/gen_system
-CPPFLAGS += -I../../../blender/gpu
CPPFLAGS += -I../../BlenderRoutines
CPPFLAGS += -I..
-
ifeq ($(OS),darwin)
CPPFLAGS += -fpascal-strings
endif
+ifeq ($(WITH_BF_GLEXT),true)
+ CPPFLAGS += -DWITH_GLEXT
+endif
diff --git a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_ListRasterizer.cpp b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_ListRasterizer.cpp
index 2c4b55ff964..c2687319717 100644
--- a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_ListRasterizer.cpp
+++ b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_ListRasterizer.cpp
@@ -9,7 +9,6 @@
#include "GL/glew.h"
-#include "RAS_MaterialBucket.h"
#include "RAS_TexVert.h"
#include "MT_assert.h"
@@ -126,20 +125,20 @@ void RAS_ListRasterizer::RemoveListSlot(RAS_ListSlot* list)
}
}
-RAS_ListSlot* RAS_ListRasterizer::FindOrAdd(RAS_MeshSlot& ms)
+RAS_ListSlot* RAS_ListRasterizer::FindOrAdd(const vecVertexArray& vertexarrays, KX_ListSlot** slot)
{
/*
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
+ :: sorted by vertex array
*/
- RAS_ListSlot* localSlot = (RAS_ListSlot*)ms.m_DisplayList;
+ RAS_ListSlot* localSlot = (RAS_ListSlot*)*slot;
if(!localSlot) {
- RAS_Lists::iterator it = mLists.find(&ms);
+ RAS_Lists::iterator it = mLists.find(vertexarrays);
if(it == mLists.end()) {
localSlot = new RAS_ListSlot(this);
- mLists.insert(std::pair<RAS_MeshSlot*, RAS_ListSlot*>(&ms, localSlot));
+ mLists.insert(std::pair<vecVertexArray, RAS_ListSlot*>(vertexarrays, localSlot));
} else {
localSlot = static_cast<RAS_ListSlot*>(it->second->AddRef());
}
@@ -158,45 +157,69 @@ void RAS_ListRasterizer::ReleaseAlloc()
mLists.clear();
}
-void RAS_ListRasterizer::IndexPrimitives(RAS_MeshSlot& ms)
+
+void RAS_ListRasterizer::IndexPrimitives(
+ const vecVertexArray & vertexarrays,
+ const vecIndexArrays & indexarrays,
+ DrawMode mode,
+ bool useObjectColor,
+ const MT_Vector4& rgbacolor,
+ class KX_ListSlot** slot)
{
RAS_ListSlot* localSlot =0;
- if(ms.m_bDisplayList) {
- localSlot = FindOrAdd(ms);
+ // useObjectColor(are we updating every frame?)
+ if(!useObjectColor && slot) {
+ localSlot = FindOrAdd(vertexarrays, slot);
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;
+ *slot = localSlot;
return;
}
}
- if (mUseVertexArrays)
- RAS_VAOpenGLRasterizer::IndexPrimitives(ms);
- else
- RAS_OpenGLRasterizer::IndexPrimitives(ms);
+ if (mUseVertexArrays) {
+ RAS_VAOpenGLRasterizer::IndexPrimitives(
+ vertexarrays, indexarrays,
+ mode, useObjectColor,
+ rgbacolor,slot
+ );
+ } else {
+ RAS_OpenGLRasterizer::IndexPrimitives(
+ vertexarrays, indexarrays,
+ mode, useObjectColor,
+ rgbacolor,slot
+ );
+ }
- if(ms.m_bDisplayList) {
+ if(!useObjectColor && slot) {
localSlot->EndList();
- ms.m_DisplayList = localSlot;
+ *slot = localSlot;
}
}
-void RAS_ListRasterizer::IndexPrimitivesMulti(RAS_MeshSlot& ms)
+void RAS_ListRasterizer::IndexPrimitivesMulti(
+ const vecVertexArray& vertexarrays,
+ const vecIndexArrays & indexarrays,
+ DrawMode mode,
+ bool useObjectColor,
+ const MT_Vector4& rgbacolor,
+ class KX_ListSlot** slot)
{
RAS_ListSlot* localSlot =0;
- if(ms.m_bDisplayList) {
- localSlot = FindOrAdd(ms);
+ // useObjectColor(are we updating every frame?)
+ if(!useObjectColor && slot) {
+ localSlot = FindOrAdd(vertexarrays, slot);
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;
+ *slot = localSlot;
return;
}
}
@@ -204,14 +227,23 @@ void RAS_ListRasterizer::IndexPrimitivesMulti(RAS_MeshSlot& ms)
// workaround: note how we do not use vertex arrays for making display
// lists, since glVertexAttribPointerARB doesn't seem to work correct
// in display lists on ATI? either a bug in the driver or in Blender ..
- if (mUseVertexArrays && !localSlot)
- RAS_VAOpenGLRasterizer::IndexPrimitivesMulti(ms);
- else
- RAS_OpenGLRasterizer::IndexPrimitivesMulti(ms);
+ if (mUseVertexArrays && !localSlot) {
+ RAS_VAOpenGLRasterizer::IndexPrimitivesMulti(
+ vertexarrays, indexarrays,
+ mode, useObjectColor,
+ rgbacolor,slot
+ );
+ } else {
+ RAS_OpenGLRasterizer::IndexPrimitivesMulti(
+ vertexarrays, indexarrays,
+ mode, useObjectColor,
+ rgbacolor,slot
+ );
+ }
- if(ms.m_bDisplayList) {
+ if(!useObjectColor && slot) {
localSlot->EndList();
- ms.m_DisplayList = localSlot;
+ *slot = localSlot;
}
}
diff --git a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_ListRasterizer.h b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_ListRasterizer.h
index 96d6d2a995d..b1b19144c12 100644
--- a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_ListRasterizer.h
+++ b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_ListRasterizer.h
@@ -4,7 +4,6 @@
#include "RAS_MaterialBucket.h"
#include "RAS_VAOpenGLRasterizer.h"
#include <vector>
-#include <map>
class RAS_ListRasterizer;
class RAS_ListSlot : public KX_ListSlot
@@ -35,14 +34,14 @@ enum RAS_ListSlotFlags {
LIST_REGEN =64
};
-typedef std::map<class RAS_MeshSlot*, RAS_ListSlot*> RAS_Lists;
+typedef std::map<const vecVertexArray, RAS_ListSlot*> RAS_Lists;
class RAS_ListRasterizer : public RAS_VAOpenGLRasterizer
{
bool mUseVertexArrays;
RAS_Lists mLists;
- RAS_ListSlot* FindOrAdd(class RAS_MeshSlot& ms);
+ RAS_ListSlot* FindOrAdd(const vecVertexArray& vertexarrays, KX_ListSlot** slot);
void ReleaseAlloc();
public:
@@ -50,8 +49,23 @@ public:
RAS_ListRasterizer(RAS_ICanvas* canvas, bool useVertexArrays=false, bool lock=false);
virtual ~RAS_ListRasterizer();
- virtual void IndexPrimitives(class RAS_MeshSlot& ms);
- virtual void IndexPrimitivesMulti(class RAS_MeshSlot& ms);
+ virtual void IndexPrimitives(
+ const vecVertexArray& vertexarrays,
+ const vecIndexArrays & indexarrays,
+ DrawMode mode,
+ bool useObjectColor,
+ const MT_Vector4& rgbacolor,
+ class KX_ListSlot** slot
+ );
+
+ virtual void IndexPrimitivesMulti(
+ const vecVertexArray& vertexarrays,
+ const vecIndexArrays & indexarrays,
+ DrawMode mode,
+ bool useObjectColor,
+ const MT_Vector4& rgbacolor,
+ class KX_ListSlot** slot
+ );
virtual bool Init();
virtual void Exit();
diff --git a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLRasterizer.cpp b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLRasterizer.cpp
index 3cad5fe74f2..1dcc6e70934 100644
--- a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLRasterizer.cpp
+++ b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLRasterizer.cpp
@@ -38,9 +38,6 @@
#include "MT_CmMatrix4x4.h"
#include "RAS_IRenderTools.h" // rendering text
-#include "GPU_draw.h"
-#include "GPU_material.h"
-
/**
* 32x32 bit masks for vinterlace stereo mode
*/
@@ -70,12 +67,10 @@ RAS_OpenGLRasterizer::RAS_OpenGLRasterizer(RAS_ICanvas* canvas)
m_motionblurvalue(-1.0),
m_texco_num(0),
m_attrib_num(0),
- m_last_blendmode(GPU_BLEND_SOLID),
- m_last_frontface(true),
+ m_last_blendmode(0),
m_materialCachingInfo(0)
{
- m_viewmatrix.setIdentity();
- m_viewinvmatrix.setIdentity();
+ m_viewmatrix.Identity();
for (int i = 0; i < 32; i++)
{
@@ -92,9 +87,81 @@ RAS_OpenGLRasterizer::~RAS_OpenGLRasterizer()
{
}
+
+
+static void Myinit_gl_stuff(void)
+{
+ float mat_specular[] = { 0.5, 0.5, 0.5, 1.0 };
+ float mat_shininess[] = { 35.0 };
+/* float one= 1.0; */
+ int a, x, y;
+ GLubyte pat[32*32];
+ const GLubyte *patc= pat;
+
+ glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, mat_specular);
+ glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, mat_specular);
+ glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, mat_shininess);
+
+
+#if defined(__FreeBSD) || defined(__linux__)
+ glDisable(GL_DITHER); /* op sgi/sun hardware && 12 bits */
+#endif
+
+ /* no local viewer, looks ugly in ortho mode */
+ /* glLightModelfv(GL_LIGHT_MODEL_LOCAL_VIEWER, &one); */
+
+ glDepthFunc(GL_LEQUAL);
+ /* scaling matrices */
+ glEnable(GL_NORMALIZE);
+
+ glShadeModel(GL_FLAT);
+
+ glDisable(GL_ALPHA_TEST);
+ glDisable(GL_BLEND);
+ glDisable(GL_DEPTH_TEST);
+ glDisable(GL_FOG);
+ glDisable(GL_LIGHTING);
+ glDisable(GL_LOGIC_OP);
+ glDisable(GL_STENCIL_TEST);
+ glDisable(GL_TEXTURE_1D);
+ glDisable(GL_TEXTURE_2D);
+
+ glEnableClientState(GL_VERTEX_ARRAY);
+ glEnableClientState(GL_NORMAL_ARRAY);
+
+ glPixelTransferi(GL_MAP_COLOR, GL_FALSE);
+ glPixelTransferi(GL_RED_SCALE, 1);
+ glPixelTransferi(GL_RED_BIAS, 0);
+ glPixelTransferi(GL_GREEN_SCALE, 1);
+ glPixelTransferi(GL_GREEN_BIAS, 0);
+ glPixelTransferi(GL_BLUE_SCALE, 1);
+ glPixelTransferi(GL_BLUE_BIAS, 0);
+ glPixelTransferi(GL_ALPHA_SCALE, 1);
+ glPixelTransferi(GL_ALPHA_BIAS, 0);
+
+ a = 0;
+ for(x=0; x<32; x++)
+ {
+ for(y=0; y<4; y++)
+ {
+ if( (x) & 1) pat[a++]= 0x88;
+ else pat[a++]= 0x22;
+ }
+ }
+
+ glPolygonStipple(patc);
+
+ glFrontFace(GL_CCW);
+ glCullFace(GL_BACK);
+ glEnable(GL_CULL_FACE);
+}
+
+
+
bool RAS_OpenGLRasterizer::Init()
{
- GPU_state_init();
+
+ Myinit_gl_stuff();
m_redback = 0.4375;
m_greenback = 0.4375;
@@ -105,12 +172,7 @@ bool RAS_OpenGLRasterizer::Init()
m_ambg = 0.0f;
m_ambb = 0.0f;
- glDisable(GL_BLEND);
- glDisable(GL_ALPHA_TEST);
- m_last_blendmode = GPU_BLEND_SOLID;
-
- glFrontFace(GL_CCW);
- m_last_frontface = true;
+ SetBlendingMode(0);
glClearColor(m_redback,m_greenback,m_blueback,m_alphaback);
glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
@@ -254,10 +316,21 @@ void RAS_OpenGLRasterizer::Exit()
EndFrame();
}
+bool RAS_OpenGLRasterizer::InterlacedStereo() const
+{
+ return m_stereomode == RAS_STEREO_VINTERLACE || m_stereomode == RAS_STEREO_INTERLACED;
+}
+
bool RAS_OpenGLRasterizer::BeginFrame(int drawingmode, double time)
{
m_time = time;
m_drawingmode = drawingmode;
+
+ if (!InterlacedStereo() || m_curreye == RAS_STEREO_LEFTEYE)
+ {
+ m_2DCanvas->ClearColor(m_redback,m_greenback,m_blueback,m_alphaback);
+ m_2DCanvas->ClearBuffer(RAS_ICanvas::COLOR_BUFFER);
+ }
// Blender camera routine destroys the settings
if (m_drawingmode < KX_SOLID)
@@ -271,12 +344,7 @@ bool RAS_OpenGLRasterizer::BeginFrame(int drawingmode, double time)
glEnable (GL_CULL_FACE);
}
- glDisable(GL_BLEND);
- glDisable(GL_ALPHA_TEST);
- m_last_blendmode = GPU_BLEND_SOLID;
-
- glFrontFace(GL_CCW);
- m_last_frontface = true;
+ SetBlendingMode(0);
glShadeModel(GL_SMOOTH);
@@ -291,28 +359,34 @@ void RAS_OpenGLRasterizer::SetDrawingMode(int drawingmode)
{
m_drawingmode = drawingmode;
- if(m_drawingmode == KX_WIREFRAME)
- glDisable(GL_CULL_FACE);
+ switch (m_drawingmode)
+ {
+ case KX_WIREFRAME:
+ {
+ glDisable (GL_CULL_FACE);
+ break;
+ }
+ default:
+ {
+ }
+ }
}
+
+
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()
{
@@ -406,16 +480,14 @@ void RAS_OpenGLRasterizer::SetRenderArea()
break;
}
}
+
void RAS_OpenGLRasterizer::SetStereoMode(const StereoMode stereomode)
{
m_stereomode = stereomode;
}
-RAS_IRasterizer::StereoMode RAS_OpenGLRasterizer::GetStereoMode()
-{
- return m_stereomode;
-}
+
bool RAS_OpenGLRasterizer::Stereo()
{
@@ -425,10 +497,6 @@ bool RAS_OpenGLRasterizer::Stereo()
return true;
}
-bool RAS_OpenGLRasterizer::InterlacedStereo()
-{
- return m_stereomode == RAS_STEREO_VINTERLACE || m_stereomode == RAS_STEREO_INTERLACED;
-}
void RAS_OpenGLRasterizer::SetEye(const StereoEye eye)
{
@@ -505,84 +573,294 @@ void RAS_OpenGLRasterizer::SwapBuffers()
-const MT_Matrix4x4& RAS_OpenGLRasterizer::GetViewMatrix() const
+void RAS_OpenGLRasterizer::GetViewMatrix(MT_Matrix4x4 &mat) const
{
- return m_viewmatrix;
+ float viewmat[16];
+ glGetFloatv(GL_MODELVIEW_MATRIX, viewmat);
+ mat.setValue(viewmat);
}
-const MT_Matrix4x4& RAS_OpenGLRasterizer::GetViewInvMatrix() const
-{
- return m_viewinvmatrix;
+
+
+void RAS_OpenGLRasterizer::IndexPrimitives(const vecVertexArray & vertexarrays,
+ const vecIndexArrays & indexarrays,
+ DrawMode mode,
+ bool useObjectColor,
+ const MT_Vector4& rgbacolor,
+ class KX_ListSlot** slot
+ )
+{
+ const RAS_TexVert* vertexarray;
+ unsigned int numindices, vt;
+
+ for (vt=0;vt<vertexarrays.size();vt++)
+ {
+ vertexarray = &((*vertexarrays[vt]) [0]);
+ const KX_IndexArray & indexarray = (*indexarrays[vt]);
+ numindices = indexarray.size();
+
+ if (!numindices)
+ break;
+
+ int vindex=0;
+ switch (mode)
+ {
+ case KX_MODE_LINES:
+ {
+ glBegin(GL_LINES);
+ vindex=0;
+ for (unsigned int i=0;i<numindices;i+=2)
+ {
+ glVertex3fv(vertexarray[(indexarray[vindex++])].getLocalXYZ());
+ glVertex3fv(vertexarray[(indexarray[vindex++])].getLocalXYZ());
+ }
+ glEnd();
+ }
+ break;
+ case KX_MODE_QUADS:
+ {
+ glBegin(GL_QUADS);
+ vindex=0;
+ if (useObjectColor)
+ {
+ for (unsigned int i=0;i<numindices;i+=4)
+ {
+
+ glColor4d(rgbacolor[0], rgbacolor[1], rgbacolor[2], rgbacolor[3]);
+
+ glNormal3fv(vertexarray[(indexarray[vindex])].getNormal());
+ glTexCoord2fv(vertexarray[(indexarray[vindex])].getUV1());
+ glVertex3fv(vertexarray[(indexarray[vindex])].getLocalXYZ());
+ vindex++;
+
+ glNormal3fv(vertexarray[(indexarray[vindex])].getNormal());
+ glTexCoord2fv(vertexarray[(indexarray[vindex])].getUV1());
+ glVertex3fv(vertexarray[(indexarray[vindex])].getLocalXYZ());
+ vindex++;
+
+ glNormal3fv(vertexarray[(indexarray[vindex])].getNormal());
+ glTexCoord2fv(vertexarray[(indexarray[vindex])].getUV1());
+ glVertex3fv(vertexarray[(indexarray[vindex])].getLocalXYZ());
+ vindex++;
+
+ glNormal3fv(vertexarray[(indexarray[vindex])].getNormal());
+ glTexCoord2fv(vertexarray[(indexarray[vindex])].getUV1());
+ glVertex3fv(vertexarray[(indexarray[vindex])].getLocalXYZ());
+ vindex++;
+ }
+ }
+ else
+ {
+ for (unsigned int i=0;i<numindices;i+=4)
+ {
+ // This looks curiously endian unsafe to me.
+ // However it depends on the way the colors are packed into
+ // the m_rgba field of RAS_TexVert
+
+ glColor4ubv((const GLubyte *)(vertexarray[(indexarray[vindex])].getRGBA()));
+ glNormal3fv(vertexarray[(indexarray[vindex])].getNormal());
+ glTexCoord2fv(vertexarray[(indexarray[vindex])].getUV1());
+ glVertex3fv(vertexarray[(indexarray[vindex])].getLocalXYZ());
+ vindex++;
+
+ glColor4ubv((const GLubyte *)(vertexarray[(indexarray[vindex])].getRGBA()));
+ glNormal3fv(vertexarray[(indexarray[vindex])].getNormal());
+ glTexCoord2fv(vertexarray[(indexarray[vindex])].getUV1());
+ glVertex3fv(vertexarray[(indexarray[vindex])].getLocalXYZ());
+ vindex++;
+
+ glColor4ubv((const GLubyte *)(vertexarray[(indexarray[vindex])].getRGBA()));
+ glNormal3fv(vertexarray[(indexarray[vindex])].getNormal());
+ glTexCoord2fv(vertexarray[(indexarray[vindex])].getUV1());
+ glVertex3fv(vertexarray[(indexarray[vindex])].getLocalXYZ());
+ vindex++;
+
+ glColor4ubv((const GLubyte *)(vertexarray[(indexarray[vindex])].getRGBA()));
+ glNormal3fv(vertexarray[(indexarray[vindex])].getNormal());
+ glTexCoord2fv(vertexarray[(indexarray[vindex])].getUV1());
+ glVertex3fv(vertexarray[(indexarray[vindex])].getLocalXYZ());
+ vindex++;
+ }
+ }
+ glEnd();
+ break;
+ }
+ case KX_MODE_TRIANGLES:
+ {
+ glBegin(GL_TRIANGLES);
+ vindex=0;
+ if (useObjectColor)
+ {
+ for (unsigned int i=0;i<numindices;i+=3)
+ {
+
+ glColor4d(rgbacolor[0], rgbacolor[1], rgbacolor[2], rgbacolor[3]);
+
+ glNormal3fv(vertexarray[(indexarray[vindex])].getNormal());
+ glTexCoord2fv(vertexarray[(indexarray[vindex])].getUV1());
+ glVertex3fv(vertexarray[(indexarray[vindex])].getLocalXYZ());
+ vindex++;
+
+ glNormal3fv(vertexarray[(indexarray[vindex])].getNormal());
+ glTexCoord2fv(vertexarray[(indexarray[vindex])].getUV1());
+ glVertex3fv(vertexarray[(indexarray[vindex])].getLocalXYZ());
+ vindex++;
+
+ glNormal3fv(vertexarray[(indexarray[vindex])].getNormal());
+ glTexCoord2fv(vertexarray[(indexarray[vindex])].getUV1());
+ glVertex3fv(vertexarray[(indexarray[vindex])].getLocalXYZ());
+ vindex++;
+ }
+ }
+ else
+ {
+ for (unsigned int i=0;i<numindices;i+=3)
+ {
+
+ glColor4ubv((const GLubyte *)(vertexarray[(indexarray[vindex])].getRGBA()));
+ glNormal3fv(vertexarray[(indexarray[vindex])].getNormal());
+ glTexCoord2fv(vertexarray[(indexarray[vindex])].getUV1());
+ glVertex3fv(vertexarray[(indexarray[vindex])].getLocalXYZ());
+ vindex++;
+
+ glColor4ubv((const GLubyte *)(vertexarray[(indexarray[vindex])].getRGBA()));
+ glNormal3fv(vertexarray[(indexarray[vindex])].getNormal());
+ glTexCoord2fv(vertexarray[(indexarray[vindex])].getUV1());
+ glVertex3fv(vertexarray[(indexarray[vindex])].getLocalXYZ());
+ vindex++;
+
+ glColor4ubv((const GLubyte *)(vertexarray[(indexarray[vindex])].getRGBA()));
+ glNormal3fv(vertexarray[(indexarray[vindex])].getNormal());
+ glTexCoord2fv(vertexarray[(indexarray[vindex])].getUV1());
+ glVertex3fv(vertexarray[(indexarray[vindex])].getLocalXYZ());
+ vindex++;
+ }
+ }
+ glEnd();
+ break;
+ }
+ default:
+ {
+ }
+
+ } // switch
+ } // for each vertexarray
+
}
-void RAS_OpenGLRasterizer::IndexPrimitives_3DText(RAS_MeshSlot& ms,
+void RAS_OpenGLRasterizer::IndexPrimitives_3DText(const vecVertexArray & vertexarrays,
+ const vecIndexArrays & indexarrays,
+ DrawMode mode,
class RAS_IPolyMaterial* polymat,
- class RAS_IRenderTools* rendertools)
+ class RAS_IRenderTools* rendertools,
+ bool useObjectColor,
+ const MT_Vector4& rgbacolor
+ )
{
- bool obcolor = ms.m_bObjectColor;
- MT_Vector4& rgba = ms.m_RGBAcolor;
- RAS_MeshSlot::iterator it;
-
- // handle object color
- if (obcolor) {
+ const RAS_TexVert* vertexarray;
+ unsigned int numindices, vt;
+
+ if (useObjectColor)
+ {
glDisableClientState(GL_COLOR_ARRAY);
- glColor4d(rgba[0], rgba[1], rgba[2], rgba[3]);
+ glColor4d(rgbacolor[0], rgbacolor[1], rgbacolor[2], rgbacolor[3]);
}
else
+ {
glEnableClientState(GL_COLOR_ARRAY);
-
- for(ms.begin(it); !ms.end(it); ms.next(it)) {
- RAS_TexVert *vertex;
- size_t i, j, numvert;
+ }
+
+ for (vt=0;vt<vertexarrays.size();vt++)
+ {
+ vertexarray = &((*vertexarrays[vt]) [0]);
+ const KX_IndexArray & indexarray = (*indexarrays[vt]);
+ numindices = indexarray.size();
- 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)
+ if (!numindices)
+ break;
+
+ int vindex=0;
+ switch (mode)
+ {
+ case KX_MODE_LINES:
{
- vertex = &it.vertex[it.index[i]];
- glVertex3fv(vertex->getXYZ());
-
- vertex = &it.vertex[it.index[i+1]];
- glVertex3fv(vertex->getXYZ());
+ glBegin(GL_LINES);
+ vindex=0;
+ for (unsigned int i=0;i<numindices;i+=2)
+ {
+ glVertex3fv(vertexarray[(indexarray[vindex++])].getLocalXYZ());
+ glVertex3fv(vertexarray[(indexarray[vindex++])].getLocalXYZ());
+ }
+ glEnd();
}
-
- glEnd();
- }
- else {
- // triangle and quad text drawing
- for(i=0; i<it.totindex; i+=numvert)
+ break;
+ case KX_MODE_QUADS:
{
- float v[4][3];
- 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];
+ vindex=0;
+ for (unsigned int i=0;i<numindices;i+=4)
+ {
+ float v1[3],v2[3],v3[3],v4[3];
+
+ v1[0] = vertexarray[(indexarray[vindex])].getLocalXYZ()[0];
+ v1[1] = vertexarray[(indexarray[vindex])].getLocalXYZ()[1];
+ v1[2] = vertexarray[(indexarray[vindex])].getLocalXYZ()[2];
+ vindex++;
+
+ v2[0] = vertexarray[(indexarray[vindex])].getLocalXYZ()[0];
+ v2[1] = vertexarray[(indexarray[vindex])].getLocalXYZ()[1];
+ v2[2] = vertexarray[(indexarray[vindex])].getLocalXYZ()[2];
+ vindex++;
+
+ v3[0] = vertexarray[(indexarray[vindex])].getLocalXYZ()[0];
+ v3[1] = vertexarray[(indexarray[vindex])].getLocalXYZ()[1];
+ v3[2] = vertexarray[(indexarray[vindex])].getLocalXYZ()[2];
+ vindex++;
+
+ v4[0] = vertexarray[(indexarray[vindex])].getLocalXYZ()[0];
+ v4[1] = vertexarray[(indexarray[vindex])].getLocalXYZ()[1];
+ v4[2] = vertexarray[(indexarray[vindex])].getLocalXYZ()[2];
+
+ vindex++;
+
+ rendertools->RenderText(polymat->GetDrawingMode(),polymat,v1,v2,v3,v4);
+ ClearCachingInfo();
}
-
- // 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_UV1)
- glattrib = unit;
-
- rendertools->RenderText(polymat->GetDrawingMode(), polymat,
- v[0], v[1], v[2], (numvert == 4)? v[3]: NULL, glattrib);
-
- ClearCachingInfo();
+ break;
}
- }
- }
-
- glDisableClientState(GL_COLOR_ARRAY);
+ case KX_MODE_TRIANGLES:
+ {
+ glBegin(GL_TRIANGLES);
+ vindex=0;
+ for (unsigned int i=0;i<numindices;i+=3)
+ {
+ float v1[3],v2[3],v3[3];
+
+ v1[0] = vertexarray[(indexarray[vindex])].getLocalXYZ()[0];
+ v1[1] = vertexarray[(indexarray[vindex])].getLocalXYZ()[1];
+ v1[2] = vertexarray[(indexarray[vindex])].getLocalXYZ()[2];
+ vindex++;
+
+ v2[0] = vertexarray[(indexarray[vindex])].getLocalXYZ()[0];
+ v2[1] = vertexarray[(indexarray[vindex])].getLocalXYZ()[1];
+ v2[2] = vertexarray[(indexarray[vindex])].getLocalXYZ()[2];
+ vindex++;
+
+ v3[0] = vertexarray[(indexarray[vindex])].getLocalXYZ()[0];
+ v3[1] = vertexarray[(indexarray[vindex])].getLocalXYZ()[1];
+ v3[2] = vertexarray[(indexarray[vindex])].getLocalXYZ()[2];
+ vindex++;
+
+ rendertools->RenderText(polymat->GetDrawingMode(),polymat,v1,v2,v3,NULL);
+ ClearCachingInfo();
+ }
+ glEnd();
+ break;
+ }
+ default:
+ {
+ }
+ } //switch
+ } //for each vertexarray
}
void RAS_OpenGLRasterizer::SetTexCoordNum(int num)
@@ -619,14 +897,14 @@ void RAS_OpenGLRasterizer::TexCoord(const RAS_TexVert &tv)
if(GLEW_ARB_multitexture) {
for(unit=0; unit<m_texco_num; unit++) {
- if(tv.getFlag() & RAS_TexVert::SECOND_UV && (int)tv.getUnit() == unit) {
+ if(tv.getFlag() & TV_2NDUV && (int)tv.getUnit() == unit) {
glMultiTexCoord2fvARB(GL_TEXTURE0_ARB+unit, tv.getUV2());
continue;
}
switch(m_texco[unit]) {
case RAS_TEXCO_ORCO:
case RAS_TEXCO_GLOB:
- glMultiTexCoord3fvARB(GL_TEXTURE0_ARB+unit, tv.getXYZ());
+ glMultiTexCoord3fvARB(GL_TEXTURE0_ARB+unit, tv.getLocalXYZ());
break;
case RAS_TEXCO_UV1:
glMultiTexCoord2fvARB(GL_TEXTURE0_ARB+unit, tv.getUV1());
@@ -651,7 +929,7 @@ void RAS_OpenGLRasterizer::TexCoord(const RAS_TexVert &tv)
switch(m_attrib[unit]) {
case RAS_TEXCO_ORCO:
case RAS_TEXCO_GLOB:
- glVertexAttrib3fvARB(unit, tv.getXYZ());
+ glVertexAttrib3fvARB(unit, tv.getLocalXYZ());
break;
case RAS_TEXCO_UV1:
glVertexAttrib2fvARB(unit, tv.getUV1());
@@ -675,80 +953,211 @@ void RAS_OpenGLRasterizer::TexCoord(const RAS_TexVert &tv)
}
}
-
-void RAS_OpenGLRasterizer::IndexPrimitives(RAS_MeshSlot& ms)
+void RAS_OpenGLRasterizer::Tangent( const RAS_TexVert& v1,
+ const RAS_TexVert& v2,
+ const RAS_TexVert& v3,
+ const MT_Vector3 &no)
{
- IndexPrimitivesInternal(ms, false);
+ // TODO: set for deformer...
+ MT_Vector3 x1(v1.getLocalXYZ()), x2(v2.getLocalXYZ()), x3(v3.getLocalXYZ());
+ MT_Vector2 uv1(v1.getUV1()), uv2(v2.getUV1()), uv3(v3.getUV1());
+ MT_Vector3 dx1(x2 - x1), dx2(x3 - x1);
+ MT_Vector2 duv1(uv2 - uv1), duv2(uv3 - uv1);
+
+ MT_Scalar r = 1.0 / (duv1.x() * duv2.y() - duv2.x() * duv1.y());
+ duv1 *= r;
+ duv2 *= r;
+ MT_Vector3 sdir(duv2.y() * dx1 - duv1.y() * dx2);
+ MT_Vector3 tdir(duv1.x() * dx2 - duv2.x() * dx1);
+
+ // Gram-Schmidt orthogonalize
+ MT_Vector3 t(sdir - no.cross(no.cross(sdir)));
+ if (!MT_fuzzyZero(t)) t /= t.length();
+
+ float tangent[4];
+ t.getValue(tangent);
+ // Calculate handedness
+ tangent[3] = no.dot(sdir.cross(tdir)) < 0.0 ? -1.0 : 1.0;
}
-void RAS_OpenGLRasterizer::IndexPrimitivesMulti(RAS_MeshSlot& ms)
-{
- IndexPrimitivesInternal(ms, true);
-}
-void RAS_OpenGLRasterizer::IndexPrimitivesInternal(RAS_MeshSlot& ms, bool multi)
+void RAS_OpenGLRasterizer::IndexPrimitivesMulti(
+ const vecVertexArray& vertexarrays,
+ const vecIndexArrays & indexarrays,
+ DrawMode mode,
+ bool useObjectColor,
+ const MT_Vector4& rgbacolor,
+ class KX_ListSlot** slot
+ )
{
- bool obcolor = ms.m_bObjectColor;
- bool wireframe = m_drawingmode <= KX_WIREFRAME;
- MT_Vector4& rgba = ms.m_RGBAcolor;
- RAS_MeshSlot::iterator it;
-
- // iterate over display arrays, each containing an index + vertex 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
- glBegin(GL_LINES);
+ const RAS_TexVert* vertexarray;
+ unsigned int numindices,vt;
- for(i=0; i<it.totindex; i+=2)
- {
- vertex = &it.vertex[it.index[i]];
- glVertex3fv(vertex->getXYZ());
+ for (vt=0;vt<vertexarrays.size();vt++)
+ {
+ vertexarray = &((*vertexarrays[vt]) [0]);
+ const KX_IndexArray & indexarray = (*indexarrays[vt]);
+ numindices = indexarray.size();
- vertex = &it.vertex[it.index[i+1]];
- glVertex3fv(vertex->getXYZ());
- }
+ if (!numindices)
+ break;
- glEnd();
- }
- else {
- // triangle and quad drawing
- if(it.array->m_type == RAS_DisplayArray::TRIANGLE)
- glBegin(GL_TRIANGLES);
- else
+ int vindex=0;
+ switch (mode)
+ {
+ case KX_MODE_LINES:
+ {
+ glBegin(GL_LINES);
+ vindex=0;
+ for (unsigned int i=0;i<numindices;i+=2)
+ {
+ glVertex3fv(vertexarray[(indexarray[vindex++])].getLocalXYZ());
+ glVertex3fv(vertexarray[(indexarray[vindex++])].getLocalXYZ());
+ }
+ glEnd();
+ }
+ break;
+ case KX_MODE_QUADS:
+ {
glBegin(GL_QUADS);
-
- for(i=0; i<it.totindex; i+=numvert)
+ vindex=0;
+ if (useObjectColor)
+ {
+ for (unsigned int i=0;i<numindices;i+=4)
+ {
+
+ glColor4d(rgbacolor[0], rgbacolor[1], rgbacolor[2], rgbacolor[3]);
+
+ //
+ glNormal3fv(vertexarray[(indexarray[vindex])].getNormal());
+ TexCoord(vertexarray[(indexarray[vindex])]);
+ glVertex3fv(vertexarray[(indexarray[vindex])].getLocalXYZ());
+ vindex++;
+
+ //
+ glNormal3fv(vertexarray[(indexarray[vindex])].getNormal());
+ TexCoord(vertexarray[(indexarray[vindex])]);
+ glVertex3fv(vertexarray[(indexarray[vindex])].getLocalXYZ());
+ vindex++;
+
+ //
+ glNormal3fv(vertexarray[(indexarray[vindex])].getNormal());
+ TexCoord(vertexarray[(indexarray[vindex])]);
+ glVertex3fv(vertexarray[(indexarray[vindex])].getLocalXYZ());
+ vindex++;
+
+ //
+ glNormal3fv(vertexarray[(indexarray[vindex])].getNormal());
+ TexCoord(vertexarray[(indexarray[vindex])]);
+ glVertex3fv(vertexarray[(indexarray[vindex])].getLocalXYZ());
+ vindex++;
+ }
+ }
+ else
+ {
+ for (unsigned int i=0;i<numindices;i+=4)
+ {
+ // This looks curiously endian unsafe to me.
+ // However it depends on the way the colors are packed into
+ // the m_rgba field of RAS_TexVert
+
+ //
+ glColor4ubv((const GLubyte *)(vertexarray[(indexarray[vindex])].getRGBA()));
+
+ glNormal3fv(vertexarray[(indexarray[vindex])].getNormal());
+ TexCoord(vertexarray[(indexarray[vindex])]);
+ glVertex3fv(vertexarray[(indexarray[vindex])].getLocalXYZ());
+ vindex++;
+
+ //
+ glColor4ubv((const GLubyte *)(vertexarray[(indexarray[vindex])].getRGBA()));
+ glNormal3fv(vertexarray[(indexarray[vindex])].getNormal());
+ TexCoord(vertexarray[(indexarray[vindex])]);
+ glVertex3fv(vertexarray[(indexarray[vindex])].getLocalXYZ());
+ vindex++;
+
+ //
+ glColor4ubv((const GLubyte *)(vertexarray[(indexarray[vindex])].getRGBA()));
+ glNormal3fv(vertexarray[(indexarray[vindex])].getNormal());
+ TexCoord(vertexarray[(indexarray[vindex])]);
+ glVertex3fv(vertexarray[(indexarray[vindex])].getLocalXYZ());
+ vindex++;
+
+ //
+ glColor4ubv((const GLubyte *)(vertexarray[(indexarray[vindex])].getRGBA()));
+ glNormal3fv(vertexarray[(indexarray[vindex])].getNormal());
+ TexCoord(vertexarray[(indexarray[vindex])]);
+ glVertex3fv(vertexarray[(indexarray[vindex])].getLocalXYZ());
+ vindex++;
+ }
+ }
+ glEnd();
+ break;
+ }
+ case KX_MODE_TRIANGLES:
{
- if(obcolor)
- glColor4d(rgba[0], rgba[1], rgba[2], rgba[3]);
-
- for(j=0; j<numvert; j++) {
- vertex = &it.vertex[it.index[i+j]];
-
- if(!wireframe) {
- if(!obcolor)
- glColor4ubv((const GLubyte *)(vertex->getRGBA()));
-
- glNormal3fv(vertex->getNormal());
-
- if(multi)
- TexCoord(*vertex);
- else
- glTexCoord2fv(vertex->getUV1());
+ glBegin(GL_TRIANGLES);
+ vindex=0;
+ if (useObjectColor)
+ {
+ for (unsigned int i=0;i<numindices;i+=3)
+ {
+
+ glColor4d(rgbacolor[0], rgbacolor[1], rgbacolor[2], rgbacolor[3]);
+ //
+ glNormal3fv(vertexarray[(indexarray[vindex])].getNormal());
+ TexCoord(vertexarray[(indexarray[vindex])]);
+ glVertex3fv(vertexarray[(indexarray[vindex])].getLocalXYZ());
+ vindex++;
+
+ //
+ glNormal3fv(vertexarray[(indexarray[vindex])].getNormal());
+ TexCoord(vertexarray[(indexarray[vindex])]);
+ glVertex3fv(vertexarray[(indexarray[vindex])].getLocalXYZ());
+ vindex++;
+
+ //
+ glNormal3fv(vertexarray[(indexarray[vindex])].getNormal());
+ TexCoord(vertexarray[(indexarray[vindex])]);
+ glVertex3fv(vertexarray[(indexarray[vindex])].getLocalXYZ());
+ vindex++;
+ }
+ }
+ else
+ {
+ for (unsigned int i=0;i<numindices;i+=3)
+ {
+ //
+ glColor4ubv((const GLubyte *)(vertexarray[(indexarray[vindex])].getRGBA()));
+ glNormal3fv(vertexarray[(indexarray[vindex])].getNormal());
+ TexCoord(vertexarray[(indexarray[vindex])]);
+ glVertex3fv(vertexarray[(indexarray[vindex])].getLocalXYZ());
+ vindex++;
+
+ //
+ glColor4ubv((const GLubyte *)(vertexarray[(indexarray[vindex])].getRGBA()));
+ glNormal3fv(vertexarray[(indexarray[vindex])].getNormal());
+ TexCoord(vertexarray[(indexarray[vindex])]);
+ glVertex3fv(vertexarray[(indexarray[vindex])].getLocalXYZ());
+ vindex++;
+
+ //
+ glColor4ubv((const GLubyte *)(vertexarray[(indexarray[vindex])].getRGBA()));
+ glNormal3fv(vertexarray[(indexarray[vindex])].getNormal());
+ TexCoord(vertexarray[(indexarray[vindex])]);
+ glVertex3fv(vertexarray[(indexarray[vindex])].getLocalXYZ());
+ vindex++;
}
-
- glVertex3fv(vertex->getXYZ());
}
+ glEnd();
+ break;
}
-
- glEnd();
- }
- }
+ default:
+ {
+ }
+ } // switch
+ } // for each vertexarray
}
void RAS_OpenGLRasterizer::SetProjectionMatrix(MT_CmMatrix4x4 &mat)
@@ -777,7 +1186,7 @@ MT_Matrix4x4 RAS_OpenGLRasterizer::GetFrustumMatrix(
float frustnear,
float frustfar,
float focallength,
- bool
+ bool
){
MT_Matrix4x4 result;
double mat[16];
@@ -823,7 +1232,7 @@ MT_Matrix4x4 RAS_OpenGLRasterizer::GetFrustumMatrix(
void RAS_OpenGLRasterizer::SetViewMatrix(const MT_Matrix4x4 &mat, const MT_Vector3& campos,
const MT_Point3 &, const MT_Quaternion &camOrientQuat)
{
- m_viewmatrix = mat;
+ MT_Matrix4x4 viewMat = mat;
// correction for stereo
if(m_stereomode != RAS_STEREO_NOSTEREO)
@@ -850,7 +1259,7 @@ void RAS_OpenGLRasterizer::SetViewMatrix(const MT_Matrix4x4 &mat, const MT_Vecto
MT_Transform transform;
transform.setIdentity();
transform.translate(-(eyeline * m_eyeseparation / 2.0));
- m_viewmatrix *= transform;
+ viewMat *= transform;
}
break;
case RAS_STEREO_RIGHTEYE:
@@ -859,21 +1268,20 @@ void RAS_OpenGLRasterizer::SetViewMatrix(const MT_Matrix4x4 &mat, const MT_Vecto
MT_Transform transform;
transform.setIdentity();
transform.translate(eyeline * m_eyeseparation / 2.0);
- m_viewmatrix *= transform;
+ viewMat *= transform;
}
break;
}
}
- 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);
+ // convert row major matrix 'viewMat' to column major for OpenGL
+ MT_Scalar cammat[16];
+ viewMat.getValue(cammat);
+ MT_CmMatrix4x4 viewCmmat = cammat;
glMatrixMode(GL_MODELVIEW);
- glLoadMatrixd(glviewmat);
+ m_viewmatrix = viewCmmat;
+ glLoadMatrixd(&m_viewmatrix(0,0));
m_campos = campos;
}
@@ -884,6 +1292,20 @@ const MT_Point3& RAS_OpenGLRasterizer::GetCameraPosition()
}
+
+void RAS_OpenGLRasterizer::LoadViewMatrix()
+{
+ glLoadMatrixd(&m_viewmatrix(0,0));
+}
+
+
+
+void RAS_OpenGLRasterizer::EnableTextures(bool enable)
+{
+}
+
+
+
void RAS_OpenGLRasterizer::SetCullFace(bool enable)
{
if (enable)
@@ -951,10 +1373,7 @@ void RAS_OpenGLRasterizer::SetPolygonOffset(float mult, float add)
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_motionblur = 1;
m_motionblurvalue = motionblurvalue;
}
@@ -969,23 +1388,23 @@ void RAS_OpenGLRasterizer::SetBlendingMode(int blendmode)
if(blendmode == m_last_blendmode)
return;
- if(blendmode == GPU_BLEND_SOLID) {
+ if(blendmode == 0) {
glDisable(GL_BLEND);
glDisable(GL_ALPHA_TEST);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
}
- else if(blendmode == GPU_BLEND_ADD) {
+ else if(blendmode == 1) {
glBlendFunc(GL_ONE, GL_ONE);
glEnable(GL_BLEND);
glDisable(GL_ALPHA_TEST);
}
- else if(blendmode == GPU_BLEND_ALPHA) {
+ else if(blendmode == 2) {
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_BLEND);
glEnable(GL_ALPHA_TEST);
glAlphaFunc(GL_GREATER, 0.0f);
}
- else if(blendmode == GPU_BLEND_CLIP) {
+ else if(blendmode == 4) {
glDisable(GL_BLEND);
glEnable(GL_ALPHA_TEST);
glAlphaFunc(GL_GREATER, 0.5f);
@@ -994,16 +1413,3 @@ void RAS_OpenGLRasterizer::SetBlendingMode(int blendmode)
m_last_blendmode = blendmode;
}
-void RAS_OpenGLRasterizer::SetFrontFace(bool ccw)
-{
- if(m_last_frontface == ccw)
- return;
-
- if(ccw)
- glFrontFace(GL_CCW);
- else
- glFrontFace(GL_CW);
-
- m_last_frontface = ccw;
-}
-
diff --git a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLRasterizer.h b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLRasterizer.h
index d39fd642f86..02056cce446 100644
--- a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLRasterizer.h
+++ b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLRasterizer.h
@@ -41,7 +41,7 @@ using namespace std;
#include "RAS_MaterialBucket.h"
#include "RAS_ICanvas.h"
-#define RAS_MAX_TEXCO 8 // match in BL_Material
+#define RAS_MAX_TEXCO 3 // match in BL_Material
#define RAS_MAX_ATTRIB 16 // match in BL_BlenderShader
struct OglDebugLine
@@ -77,8 +77,7 @@ class RAS_OpenGLRasterizer : public RAS_IRasterizer
float m_ambb;
double m_time;
- MT_Matrix4x4 m_viewmatrix;
- MT_Matrix4x4 m_viewinvmatrix;
+ MT_CmMatrix4x4 m_viewmatrix;
MT_Point3 m_campos;
StereoMode m_stereomode;
@@ -88,6 +87,7 @@ class RAS_OpenGLRasterizer : public RAS_IRasterizer
float m_focallength;
bool m_setfocallength;
int m_noOfScanlines;
+ bool InterlacedStereo() const;
//motion blur
int m_motionblur;
@@ -100,7 +100,6 @@ protected:
int m_texco_num;
int m_attrib_num;
int m_last_blendmode;
- bool m_last_frontface;
/** Stores the caching information for the last material activated. */
RAS_IPolyMaterial::TCachingInfo m_materialCachingInfo;
@@ -130,16 +129,13 @@ public:
virtual bool Init();
virtual void Exit();
virtual bool BeginFrame(int drawingmode, 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);
@@ -148,15 +144,33 @@ public:
virtual float GetFocalLength();
virtual void SwapBuffers();
+ virtual void IndexPrimitives(
+ const vecVertexArray& vertexarrays,
+ const vecIndexArrays & indexarrays,
+ DrawMode mode,
+ bool useObjectColor,
+ const MT_Vector4& rgbacolor,
+ class KX_ListSlot** slot
+ );
- virtual void IndexPrimitives(class RAS_MeshSlot& ms);
- virtual void IndexPrimitivesMulti(class RAS_MeshSlot& ms);
virtual void IndexPrimitives_3DText(
- class RAS_MeshSlot& ms,
+ const vecVertexArray& vertexarrays,
+ const vecIndexArrays & indexarrays,
+ DrawMode mode,
class RAS_IPolyMaterial* polymat,
- class RAS_IRenderTools* rendertools);
+ class RAS_IRenderTools* rendertools,
+ bool useObjectColor,
+ const MT_Vector4& rgbacolor
+ );
+
+ virtual void IndexPrimitivesMulti(
+ const vecVertexArray& vertexarrays,
+ const vecIndexArrays & indexarrays,
+ DrawMode mode,
+ bool useObjectColor,
+ const MT_Vector4& rgbacolor,
+ class KX_ListSlot** slot);
- void IndexPrimitivesInternal(RAS_MeshSlot& ms, bool multi);
virtual void SetProjectionMatrix(MT_CmMatrix4x4 & mat);
virtual void SetProjectionMatrix(const MT_Matrix4x4 & mat);
@@ -168,6 +182,7 @@ public:
);
virtual const MT_Point3& GetCameraPosition();
+ virtual void LoadViewMatrix();
virtual void SetFog(
float start,
@@ -199,6 +214,7 @@ public:
virtual void SetDrawingMode(int drawingmode);
virtual int GetDrawingMode();
+ virtual void EnableTextures(bool enable);
virtual void SetCullFace(bool enable);
virtual void SetLines(bool enable);
@@ -254,10 +270,13 @@ public:
virtual void SetTexCoord(TexCoGen coords, int unit);
virtual void SetAttrib(TexCoGen coords, int unit);
- void TexCoord(const RAS_TexVert &tv);
+ void TexCoord(const RAS_TexVert &tv);
+ virtual void GetViewMatrix(MT_Matrix4x4 &mat) const;
- const MT_Matrix4x4& GetViewMatrix() const;
- const MT_Matrix4x4& GetViewInvMatrix() const;
+ void Tangent(const RAS_TexVert& v1,
+ const RAS_TexVert& v2,
+ const RAS_TexVert& v3,
+ const MT_Vector3 &no);
virtual void EnableMotionBlur(float motionblurvalue);
virtual void DisableMotionBlur();
@@ -274,7 +293,6 @@ public:
};
virtual void SetBlendingMode(int blendmode);
- virtual void SetFrontFace(bool ccw);
};
#endif //__RAS_OPENGLRASTERIZER
diff --git a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_VAOpenGLRasterizer.cpp b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_VAOpenGLRasterizer.cpp
index 2cb3b52adfb..c78a97ad7be 100644
--- a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_VAOpenGLRasterizer.cpp
+++ b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_VAOpenGLRasterizer.cpp
@@ -33,7 +33,6 @@
#include <stdlib.h>
#include "GL/glew.h"
-#include "GPU_extensions.h"
#include "STR_String.h"
#include "RAS_TexVert.h"
@@ -78,16 +77,16 @@ void RAS_VAOpenGLRasterizer::SetDrawingMode(int drawingmode)
{
case KX_BOUNDINGBOX:
case KX_WIREFRAME:
- //glDisableClientState(GL_COLOR_ARRAY);
- //glDisable(GL_CULL_FACE);
+ glDisableClientState(GL_COLOR_ARRAY);
+ glDisable(GL_CULL_FACE);
break;
case KX_SOLID:
- //glDisableClientState(GL_COLOR_ARRAY);
+ glDisableClientState(GL_COLOR_ARRAY);
break;
case KX_TEXTURED:
case KX_SHADED:
case KX_SHADOW:
- //glEnableClientState(GL_COLOR_ARRAY);
+ glEnableClientState(GL_COLOR_ARRAY);
default:
break;
}
@@ -99,121 +98,141 @@ void RAS_VAOpenGLRasterizer::Exit()
glEnableClientState(GL_NORMAL_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glDisableClientState(GL_COLOR_ARRAY);
+ EnableTextures(false);
RAS_OpenGLRasterizer::Exit();
}
-void RAS_VAOpenGLRasterizer::IndexPrimitives(RAS_MeshSlot& ms)
+void RAS_VAOpenGLRasterizer::IndexPrimitives( const vecVertexArray& vertexarrays,
+ const vecIndexArrays & indexarrays,
+ DrawMode mode,
+ bool useObjectColor,
+ const MT_Vector4& rgbacolor,
+ class KX_ListSlot** slot)
{
- static const GLsizei stride = sizeof(RAS_TexVert);
- bool wireframe = m_drawingmode <= KX_WIREFRAME;
- RAS_MeshSlot::iterator it;
+ static const GLsizei vtxstride = sizeof(RAS_TexVert);
GLenum drawmode;
+ if(mode == KX_MODE_TRIANGLES)
+ drawmode = GL_TRIANGLES;
+ else if(mode == KX_MODE_QUADS)
+ drawmode = GL_QUADS;
+ else
+ drawmode = GL_LINES;
- if(!wireframe)
- glEnableClientState(GL_TEXTURE_COORD_ARRAY);
+ const RAS_TexVert* vertexarray;
+ unsigned int numindices, vt;
- // use glDrawElements to draw each vertexarray
- for(ms.begin(it); !ms.end(it); ms.next(it)) {
- if(it.totindex == 0)
- continue;
+ if (drawmode != GL_LINES)
+ {
+ if (useObjectColor)
+ {
+ glDisableClientState(GL_COLOR_ARRAY);
+ glColor4d(rgbacolor[0], rgbacolor[1], rgbacolor[2], rgbacolor[3]);
+ } else
+ {
+ glColor4d(0,0,0,1.0);
+ glEnableClientState(GL_COLOR_ARRAY);
+ }
+ }
+ else
+ {
+ glColor3d(0,0,0);
+ }
- // 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;
+ EnableTextures(false);
+ glEnableClientState(GL_TEXTURE_COORD_ARRAY);
- // colors
- if (drawmode != GL_LINES && !wireframe) {
- if (ms.m_bObjectColor) {
- const MT_Vector4& rgba = ms.m_RGBAcolor;
+ // use glDrawElements to draw each vertexarray
+ for (vt=0;vt<vertexarrays.size();vt++)
+ {
+ vertexarray = &((*vertexarrays[vt]) [0]);
+ const KX_IndexArray & indexarray = (*indexarrays[vt]);
+ numindices = indexarray.size();
- glDisableClientState(GL_COLOR_ARRAY);
- glColor4d(rgba[0], rgba[1], rgba[2], rgba[3]);
- }
- else {
- glColor4f(0.0f, 0.0f, 0.0f, 1.0f);
- glEnableClientState(GL_COLOR_ARRAY);
- }
- }
- 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) {
- glTexCoordPointer(2, GL_FLOAT, stride, it.vertex->getUV1());
- if(glIsEnabled(GL_COLOR_ARRAY))
- glColorPointer(4, GL_UNSIGNED_BYTE, stride, it.vertex->getRGBA());
- }
+ if (!numindices)
+ continue;
+
+ glVertexPointer(3,GL_FLOAT,vtxstride,vertexarray->getLocalXYZ());
+ glNormalPointer(GL_FLOAT,vtxstride,vertexarray->getNormal());
+ glTexCoordPointer(2,GL_FLOAT,vtxstride,vertexarray->getUV1());
+ if(glIsEnabled(GL_COLOR_ARRAY))
+ glColorPointer(4,GL_UNSIGNED_BYTE,vtxstride,vertexarray->getRGBA());
+
+ //if(m_Lock)
+ // local->Begin(vertexarrays[vt]->size());
// here the actual drawing takes places
- glDrawElements(drawmode, it.totindex, GL_UNSIGNED_SHORT, it.index);
- }
+ glDrawElements(drawmode,numindices,GL_UNSIGNED_SHORT,&(indexarray[0]));
- if(!wireframe) {
- glDisableClientState(GL_TEXTURE_COORD_ARRAY);
- glDisableClientState(GL_COLOR_ARRAY);
+ //if(m_Lock)
+ // local->End();
}
+
+ glDisableClientState(GL_TEXTURE_COORD_ARRAY);
}
-void RAS_VAOpenGLRasterizer::IndexPrimitivesMulti(RAS_MeshSlot& ms)
+void RAS_VAOpenGLRasterizer::IndexPrimitivesMulti( const vecVertexArray& vertexarrays,
+ const vecIndexArrays & indexarrays,
+ DrawMode mode,
+ bool useObjectColor,
+ const MT_Vector4& rgbacolor,
+ class KX_ListSlot** slot)
{
- static const GLsizei stride = sizeof(RAS_TexVert);
- bool wireframe = m_drawingmode <= KX_WIREFRAME;
- RAS_MeshSlot::iterator it;
+ static const GLsizei vtxstride = sizeof(RAS_TexVert);
+
GLenum drawmode;
+ if(mode == KX_MODE_TRIANGLES)
+ drawmode = GL_TRIANGLES;
+ else if(mode == KX_MODE_QUADS)
+ drawmode = GL_QUADS;
+ else
+ drawmode = GL_LINES;
- if(!wireframe)
- EnableTextures(true);
+ const RAS_TexVert* vertexarray;
+ unsigned int numindices, vt;
+
+ if (drawmode != GL_LINES)
+ {
+ if (useObjectColor)
+ {
+ glDisableClientState(GL_COLOR_ARRAY);
+ glColor4d(rgbacolor[0], rgbacolor[1], rgbacolor[2], rgbacolor[3]);
+ }
+ else
+ {
+ glColor4d(0,0,0,1.0);
+ glEnableClientState(GL_COLOR_ARRAY);
+ }
+ }
+ else
+ {
+ glColor3d(0,0,0);
+ }
// use glDrawElements to draw each vertexarray
- for(ms.begin(it); !ms.end(it); ms.next(it)) {
- if(it.totindex == 0)
- continue;
+ for (vt=0;vt<vertexarrays.size();vt++)
+ {
+ vertexarray = &((*vertexarrays[vt]) [0]);
+ const KX_IndexArray & indexarray = (*indexarrays[vt]);
+ numindices = indexarray.size();
- // 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;
+ if (!numindices)
+ continue;
- // colors
- if (drawmode != GL_LINES && !wireframe) {
- if (ms.m_bObjectColor) {
- const MT_Vector4& rgba = ms.m_RGBAcolor;
+ glVertexPointer(3,GL_FLOAT,vtxstride,vertexarray->getLocalXYZ());
+ glNormalPointer(GL_FLOAT,vtxstride,vertexarray->getNormal());
+ TexCoordPtr(vertexarray);
+ if(glIsEnabled(GL_COLOR_ARRAY))
+ glColorPointer(4,GL_UNSIGNED_BYTE,vtxstride,vertexarray->getRGBA());
- glDisableClientState(GL_COLOR_ARRAY);
- glColor4d(rgba[0], rgba[1], rgba[2], rgba[3]);
- }
- else {
- glColor4f(0.0f, 0.0f, 0.0f, 1.0f);
- glEnableClientState(GL_COLOR_ARRAY);
- }
- }
- 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(glIsEnabled(GL_COLOR_ARRAY))
- glColorPointer(4, GL_UNSIGNED_BYTE, stride, it.vertex->getRGBA());
- }
+ //if(m_Lock)
+ // local->Begin(vertexarrays[vt]->size());
// here the actual drawing takes places
- glDrawElements(drawmode, it.totindex, GL_UNSIGNED_SHORT, it.index);
- }
-
- if(!wireframe) {
- glDisableClientState(GL_COLOR_ARRAY);
- EnableTextures(false);
+ glDrawElements(drawmode,numindices,GL_UNSIGNED_SHORT,&(indexarray[0]));
+
+ //if(m_Lock)
+ // local->End();
}
}
@@ -229,7 +248,7 @@ void RAS_VAOpenGLRasterizer::TexCoordPtr(const RAS_TexVert *tv)
for(unit=0; unit<m_texco_num; unit++)
{
glClientActiveTextureARB(GL_TEXTURE0_ARB+unit);
- if(tv->getFlag() & RAS_TexVert::SECOND_UV && (int)tv->getUnit() == unit) {
+ if(tv->getFlag() & TV_2NDUV && (int)tv->getUnit() == unit) {
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glTexCoordPointer(2, GL_FLOAT, sizeof(RAS_TexVert), tv->getUV2());
continue;
@@ -238,7 +257,7 @@ void RAS_VAOpenGLRasterizer::TexCoordPtr(const RAS_TexVert *tv)
{
case RAS_TEXCO_ORCO:
case RAS_TEXCO_GLOB:
- glTexCoordPointer(3, GL_FLOAT, sizeof(RAS_TexVert),tv->getXYZ());
+ glTexCoordPointer(3, GL_FLOAT, sizeof(RAS_TexVert),tv->getLocalXYZ());
break;
case RAS_TEXCO_UV1:
glTexCoordPointer(2, GL_FLOAT, sizeof(RAS_TexVert),tv->getUV1());
@@ -265,7 +284,7 @@ void RAS_VAOpenGLRasterizer::TexCoordPtr(const RAS_TexVert *tv)
switch(m_attrib[unit]) {
case RAS_TEXCO_ORCO:
case RAS_TEXCO_GLOB:
- glVertexAttribPointerARB(unit, 3, GL_FLOAT, GL_FALSE, sizeof(RAS_TexVert), tv->getXYZ());
+ glVertexAttribPointerARB(unit, 3, GL_FLOAT, GL_FALSE, sizeof(RAS_TexVert), tv->getLocalXYZ());
break;
case RAS_TEXCO_UV1:
glVertexAttribPointerARB(unit, 2, GL_FLOAT, GL_FALSE, sizeof(RAS_TexVert), tv->getUV1());
@@ -294,6 +313,11 @@ void RAS_VAOpenGLRasterizer::EnableTextures(bool enable)
TexCoGen *texco, *attrib;
int unit, texco_num, attrib_num;
+ /* disable previously enabled texture coordinates and attributes. ideally
+ * this shouldn't be necessary .. */
+ if(enable)
+ EnableTextures(false);
+
/* we cache last texcoords and attribs to ensure we disable the ones that
* were actually last set */
if(enable) {
diff --git a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_VAOpenGLRasterizer.h b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_VAOpenGLRasterizer.h
index 766bbfbed0e..e4cc4ace0e8 100644
--- a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_VAOpenGLRasterizer.h
+++ b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_VAOpenGLRasterizer.h
@@ -50,10 +50,22 @@ public:
virtual void SetDrawingMode(int drawingmode);
- virtual void IndexPrimitives(class RAS_MeshSlot& ms);
- virtual void IndexPrimitivesMulti(class RAS_MeshSlot& ms);
+ virtual void IndexPrimitives( const vecVertexArray& vertexarrays,
+ const vecIndexArrays & indexarrays,
+ DrawMode mode,
+ bool useObjectColor,
+ const MT_Vector4& rgbacolor,
+ class KX_ListSlot** slot);
+
+ virtual void IndexPrimitivesMulti(
+ const vecVertexArray& vertexarrays,
+ const vecIndexArrays & indexarrays,
+ DrawMode mode,
+ bool useObjectColor,
+ const MT_Vector4& rgbacolor,
+ class KX_ListSlot** slot);
+
-private:
virtual void EnableTextures(bool enable);
//virtual bool QueryArrays(){return true;}
//virtual bool QueryLists(){return m_Lock;}
diff --git a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/SConscript b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/SConscript
index 8d46528f7f0..0cf9c326370 100644
--- a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/SConscript
+++ b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/SConscript
@@ -1,9 +1,12 @@
#!/usr/bin/python
Import ('env')
+if env['WITH_BF_GLEXT'] == 1:
+ env['CPPFLAGS'].append('-DWITH_GLEXT')
+
sources = env.Glob('*.cpp')
incs = '. #source/kernel/gen_system #intern/string #intern/moto/include #source/gameengine/Rasterizer #source/gameengine/BlenderRoutines '
-incs += ' #source/blender/gpu #extern/glew/include ' + env['BF_OPENGL_INC']
+incs += ' #extern/glew/include ' + env['BF_OPENGL_INC']
env.BlenderLib ( 'bf_oglrasterizer', Split(sources), Split(incs), [], libtype=['game','player'], priority=[40, 120] )
diff --git a/source/gameengine/Rasterizer/RAS_Polygon.cpp b/source/gameengine/Rasterizer/RAS_Polygon.cpp
index 50331d7a664..b74cb9cfcac 100644
--- a/source/gameengine/Rasterizer/RAS_Polygon.cpp
+++ b/source/gameengine/Rasterizer/RAS_Polygon.cpp
@@ -26,82 +26,99 @@
* ***** END GPL LICENSE BLOCK *****
*/
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
#ifdef WIN32
+
#pragma warning (disable:4786)
#endif
#include "RAS_Polygon.h"
-RAS_Polygon::RAS_Polygon(RAS_MaterialBucket* bucket, RAS_DisplayArray *darray, int numvert)
+RAS_Polygon::RAS_Polygon(RAS_MaterialBucket* bucket,
+ bool visible,
+ int numverts,
+ int vtxarrayindex)
+ :m_bucket(bucket),
+ m_vertexindexbase(numverts),
+ m_numverts(numverts),
+ m_edgecode(65535)
{
- 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;
+ m_vertexindexbase.m_vtxarray = vtxarrayindex ;//m_bucket->FindVertexArray(numverts);
+ m_polyFlags.Visible = visible;
}
+
+
int RAS_Polygon::VertexCount()
{
- return m_numvert;
+ return m_numverts;
}
-void RAS_Polygon::SetVertexOffset(int i, unsigned short offset)
+
+
+void RAS_Polygon::SetVertex(int i,
+ unsigned int vertexindex ) //const MT_Point3& xyz,const MT_Point2& uv,const unsigned int rgbacolor,const MT_Vector3& normal)
{
- m_offset[i] = offset;
+ m_vertexindexbase.SetIndex(i,vertexindex); //m_bucket->FindOrAddVertex(m_vertexindexbase.m_vtxarray,
+ //xyz,uv,rgbacolor,normal));
}
-RAS_TexVert *RAS_Polygon::GetVertex(int i)
+
+
+const KX_VertexIndex& RAS_Polygon::GetIndexBase()
{
- return &m_darray->m_vertex[m_offset[i]];
+ return m_vertexindexbase;
}
-int RAS_Polygon::GetVertexOffset(int i)
+
+
+void RAS_Polygon::SetVisibleWireframeEdges(int edgecode)
{
- return m_offset[i];
+ m_edgecode = edgecode;
}
+
+
+// each bit is for a visible edge, starting with bit 1 for the first edge, bit 2 for second etc.
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;
+ return m_polyFlags.Visible;
}
-void RAS_Polygon::SetVisible(bool visible)
-{
- if(visible) m_polyflags |= VISIBLE;
- else m_polyflags &= ~VISIBLE;
-}
+
bool RAS_Polygon::IsCollider()
{
- return (m_polyflags & COLLIDER) != 0;
+ return m_polyFlags.Collider;
}
-void RAS_Polygon::SetCollider(bool visible)
+
+
+void RAS_Polygon::SetCollider(bool col)
{
- if(visible) m_polyflags |= COLLIDER;
- else m_polyflags &= ~COLLIDER;
+ m_polyFlags.Collider = col;
}
-RAS_MaterialBucket* RAS_Polygon::GetMaterial()
+
+
+KX_VertexIndex& RAS_Polygon::GetVertexIndexBase()
{
- return m_bucket;
+ return m_vertexindexbase;
}
-RAS_DisplayArray* RAS_Polygon::GetDisplayArray()
+
+
+RAS_MaterialBucket* RAS_Polygon::GetMaterial()
{
- return m_darray;
+ return m_bucket;
}
diff --git a/source/gameengine/Rasterizer/RAS_Polygon.h b/source/gameengine/Rasterizer/RAS_Polygon.h
index 18526ba45f7..7ce7926a816 100644
--- a/source/gameengine/Rasterizer/RAS_Polygon.h
+++ b/source/gameengine/Rasterizer/RAS_Polygon.h
@@ -35,47 +35,55 @@
#include <vector>
using namespace std;
-/* polygon flags */
+
+//
+// Bitfield that stores the flags for each CValue derived class
+//
+struct PolygonFlags {
+ PolygonFlags() :
+ Visible(true),
+ Collider(true)
+ {
+ }
+ unsigned char Visible : 1;
+ unsigned char Collider : 1;
+ //int Visible : 1;
+ //int Collider : 1;
+};
class RAS_Polygon
{
- /* location */
RAS_MaterialBucket* m_bucket;
- RAS_DisplayArray* m_darray;
- unsigned short m_offset[4];
- unsigned short m_numvert;
-
- /* flags */
- unsigned char m_edgecode;
- unsigned char m_polyflags;
+ KX_VertexIndex m_vertexindexbase;
+ int m_numverts;
+ int m_edgecode;
+ PolygonFlags m_polyFlags;
+
public:
- enum {
- VISIBLE = 1,
- COLLIDER = 2
- };
-
- RAS_Polygon(RAS_MaterialBucket* bucket, RAS_DisplayArray* darray, int numvert);
+ RAS_Polygon(RAS_MaterialBucket* bucket,
+ bool visible,
+ int numverts,
+ int vtxarrayindex) ;
virtual ~RAS_Polygon() {};
+// RAS_TexVert* GetVertex(int index);
int VertexCount();
- RAS_TexVert* GetVertex(int i);
-
- void SetVertexOffset(int i, unsigned short offset);
- int GetVertexOffset(int i);
+ void SetVertex(int i, unsigned int vertexindex); //const MT_Point3& xyz,const MT_Point2& uv,const unsigned int rgbacolor,const MT_Vector3& normal)
+ const KX_VertexIndex& GetIndexBase();
+
+ void SetVisibleWireframeEdges(int edgecode);
// each bit is for a visible edge, starting with bit 1 for the first edge, bit 2 for second etc.
int GetEdgeCode();
- void SetEdgeCode(int edgecode);
bool IsVisible();
- void SetVisible(bool visible);
-
bool IsCollider();
- void SetCollider(bool collider);
+ void SetCollider(bool col);
+ KX_VertexIndex& GetVertexIndexBase();
RAS_MaterialBucket* GetMaterial();
- RAS_DisplayArray* GetDisplayArray();
+
};
#endif
diff --git a/source/gameengine/Rasterizer/RAS_TexVert.cpp b/source/gameengine/Rasterizer/RAS_TexVert.cpp
index b92965ed1cc..935633dc636 100644
--- a/source/gameengine/Rasterizer/RAS_TexVert.cpp
+++ b/source/gameengine/Rasterizer/RAS_TexVert.cpp
@@ -27,7 +27,12 @@
*/
#include "RAS_TexVert.h"
-#include "MT_Matrix4x4.h"
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#define SHORT(x) short(x*32767.0)
RAS_TexVert::RAS_TexVert(const MT_Point3& xyz,
const MT_Point2& uv,
@@ -35,7 +40,7 @@ RAS_TexVert::RAS_TexVert(const MT_Point3& xyz,
const MT_Vector4& tangent,
const unsigned int rgba,
const MT_Vector3& normal,
- const bool flat,
+ const short flag,
const unsigned int origindex)
{
xyz.getValue(m_localxyz);
@@ -44,10 +49,9 @@ RAS_TexVert::RAS_TexVert(const MT_Point3& xyz,
SetRGBA(rgba);
SetNormal(normal);
tangent.getValue(m_tangent);
- m_flag = (flat)? FLAT: 0;
+ m_flag = flag;
m_origindex = origindex;
m_unit = 2;
- m_softBodyIndex = -1;
}
const MT_Point3& RAS_TexVert::xyz()
@@ -97,7 +101,7 @@ void RAS_TexVert::SetFlag(const short flag)
void RAS_TexVert::SetUnit(const unsigned int u)
{
- m_unit = u<=MAX_UNIT?u:MAX_UNIT;
+ m_unit = u<=TV_MAX?u:TV_MAX;
}
void RAS_TexVert::SetNormal(const MT_Vector3& normal)
@@ -105,18 +109,12 @@ 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)
{
return (m_flag == other->m_flag &&
m_rgba == other->m_rgba &&
MT_fuzzyEqual(MT_Vector3(m_normal), MT_Vector3(other->m_normal)) &&
- MT_fuzzyEqual(MT_Vector3(m_tangent), MT_Vector3(other->m_tangent)) &&
MT_fuzzyEqual(MT_Vector2(m_uv1), MT_Vector2(other->m_uv1)) &&
MT_fuzzyEqual(MT_Vector2(m_uv2), MT_Vector2(other->m_uv2)) && // p --
MT_fuzzyEqual(MT_Vector3(m_localxyz), MT_Vector3(other->m_localxyz))) ;
@@ -133,10 +131,11 @@ unsigned int RAS_TexVert::getUnit() const
return m_unit;
}
-void RAS_TexVert::Transform(const MT_Matrix4x4& mat, const MT_Matrix4x4& nmat)
+
+void RAS_TexVert::getOffsets(void* &xyz, void* &uv1, void* &rgba, void* &normal) const
{
- SetXYZ((mat*MT_Vector4(m_localxyz[0], m_localxyz[1], m_localxyz[2], 1.0)).getValue());
- SetNormal((nmat*MT_Vector4(m_normal[0], m_normal[1], m_normal[2], 1.0)).getValue());
- SetTangent((nmat*MT_Vector4(m_tangent[0], m_tangent[1], m_tangent[2], 1.0)).getValue());
+ xyz = (void *) m_localxyz;
+ uv1 = (void *) m_uv1;
+ rgba = (void *) &m_rgba;
+ normal = (void *) m_normal;
}
-
diff --git a/source/gameengine/Rasterizer/RAS_TexVert.h b/source/gameengine/Rasterizer/RAS_TexVert.h
index 54da109cbf1..bf092b4b230 100644
--- a/source/gameengine/Rasterizer/RAS_TexVert.h
+++ b/source/gameengine/Rasterizer/RAS_TexVert.h
@@ -37,6 +37,11 @@
static MT_Point3 g_pt3;
static MT_Point2 g_pt2;
+#define TV_CALCFACENORMAL 0x0001
+#define TV_2NDUV 0x0002
+
+#define TV_MAX 3//match Def in BL_Material.h
+
class RAS_TexVert
{
@@ -44,23 +49,16 @@ class RAS_TexVert
float m_uv1[2]; // 2*4 = 8
float m_uv2[2]; // 2*4 = 8
unsigned int m_rgba; // 4
- float m_tangent[4]; // 4*4 = 16
- float m_normal[3]; // 3*4 = 12
+ float m_tangent[4]; // 4*2 = 8
+ float m_normal[3]; // 3*2 = 6
short m_flag; // 2
- short m_softBodyIndex; //2
unsigned int m_unit; // 4
- unsigned int m_origindex; // 4
+ unsigned int m_origindex; // 4
//---------
- // 56+6+8+2=72
+ // 56
// 32 bytes total size, fits nice = 56 = not fit nice.
-
+ // We'll go for 64 bytes total size - 24 bytes left.
public:
- enum {
- FLAT = 1,
- SECOND_UV = 2,
- MAX_UNIT = 8
- };
-
short getFlag() const;
unsigned int getUnit() const;
@@ -72,7 +70,7 @@ public:
const MT_Vector4& tangent,
const unsigned int rgba,
const MT_Vector3& normal,
- const bool flat,
+ const short flag,
const unsigned int origindex);
~RAS_TexVert() {};
@@ -84,7 +82,7 @@ public:
return m_uv2;
};
- const float* getXYZ() const {
+ const float* getLocalXYZ() const {
return m_localxyz;
};
@@ -92,16 +90,6 @@ public:
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;
}
@@ -120,19 +108,20 @@ public:
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);
-
- // compare two vertices, to test if they can be shared, used for
- // splitting up based on uv's, colors, etc
+ // compare two vertices, and return TRUE if both are almost identical (they can be shared)
bool closeTo(const RAS_TexVert* other);
+
+ bool closeTo(const MT_Point3& otherxyz,
+ const MT_Point2& otheruv,
+ const unsigned int otherrgba,
+ short othernormal[3]) const;
+ void getOffsets(void*&xyz, void *&uv1, void *&rgba, void *&normal) const;
};
#endif //__RAS_TEXVERT
diff --git a/source/gameengine/Rasterizer/SConscript b/source/gameengine/Rasterizer/SConscript
index a024f7e0ee6..e6bc657ed6d 100644
--- a/source/gameengine/Rasterizer/SConscript
+++ b/source/gameengine/Rasterizer/SConscript
@@ -3,8 +3,11 @@ Import ('env')
sources = env.Glob('*.cpp')
+if env['WITH_BF_GLEXT'] == 1:
+ env['CPPFLAGS'].append('-DWITH_GLEXT')
-incs = '. #source/kernel/gen_system #intern/string #intern/moto/include #source/gameengine/BlenderRoutines #extern/glew/include #source/gameengine/Expressions #source/blender/blenkernel #source/blender/makesdna'
+
+incs = '. #source/kernel/gen_system #intern/string #intern/moto/include #source/gameengine/BlenderRoutines #extern/glew/include #source/gameengine/Expressions'
incs += ' ' + env['BF_PYTHON_INC']
if env['OURPLATFORM']=='win32-vc':
diff --git a/source/gameengine/SConscript b/source/gameengine/SConscript
index e841f206eee..c2750d19706 100644
--- a/source/gameengine/SConscript
+++ b/source/gameengine/SConscript
@@ -15,8 +15,7 @@ SConscript(['BlenderRoutines/SConscript',
'Rasterizer/RAS_OpenGLRasterizer/SConscript',
'SceneGraph/SConscript',
'Physics/Bullet/SConscript',
- 'Physics/Sumo/SConscript',
- 'VideoTexture/SConscript'
+ 'Physics/Sumo/SConscript'
])
if env['WITH_BF_PLAYER']:
diff --git a/source/gameengine/VideoTexture/BlendType.h b/source/gameengine/VideoTexture/BlendType.h
deleted file mode 100644
index ac3ed8812a6..00000000000
--- a/source/gameengine/VideoTexture/BlendType.h
+++ /dev/null
@@ -1,75 +0,0 @@
-/* $Id$
------------------------------------------------------------------------------
-This source file is part of VideoTexture library
-
-Copyright (c) 2006 The Zdeno Ash Miklas
-
-This program is free software; you can redistribute it and/or modify it under
-the terms of the GNU Lesser General Public License as published by the Free Software
-Foundation; either version 2 of the License, or (at your option) any later
-version.
-
-This program is distributed in the hope that it will be useful, but WITHOUT
-ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
-
-You should have received a copy of the GNU Lesser General Public License along with
-this program; if not, write to the Free Software Foundation, Inc., 59 Temple
-Place - Suite 330, Boston, MA 02111-1307, USA, or go to
-http://www.gnu.org/copyleft/lesser.txt.
------------------------------------------------------------------------------
-*/
-
-#if !defined BLENDTYPE_H
-#define BLENDTYPE_H
-
-
-/// class allows check type of blender python object and access its contained object
-template <class PyObj> class BlendType
-{
-public:
- /// constructor
- BlendType (char * name) : m_name(name) {}
-
- /// 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(obj->ob_type->tp_name, m_name) == 0)
- // if name of type match, save pointer to type
- m_objType = obj->ob_type;
- 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 (obj->ob_type != m_objType)
- return NULL;
- // return pointer to object
- return (PyObj*)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
- 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 1674602edd7..00000000000
--- a/source/gameengine/VideoTexture/CMakeLists.txt
+++ /dev/null
@@ -1,61 +0,0 @@
-# $Id$
-# ***** BEGIN GPL LICENSE BLOCK *****
-#
-# This program is free software; you can redistribute it and/or
-# modify it under the terms of the GNU General Public License
-# as published by the Free Software Foundation; either version 2
-# of the License, or (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software Foundation,
-# Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, 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 *****
-
-FILE(GLOB SRC *.cpp)
-
-SET(INC
- .
- ../../../source/gameengine/Ketsji
- ../../../source/gameengine/Expressions
- ../../../source/gameengine/GameLogic
- ../../../source/gameengine/SceneGraph
- ../../../source/gameengine/Rasterizer
- ../../../source/gameengine/Rasterizer/RAS_OpenGLRasterizer
- ../../../source/gameengine/BlenderRoutines
- ../../../source/blender/include
- ../../../source/blender/blenlib
- ../../../source/blender/blenkernel
- ../../../source/blender/makesdna
- ../../../source/blender/imbuf
- ../../../source/blender/python
- ../../../source/blender/gpu
- ../../../source/kernel/gen_system
- ../../../intern/string
- ../../../intern/moto/include
- ../../../intern/guardedalloc
- ../../../intern/SoundSystem
- ../../../extern/glew/include
- ${PYTHON_INC}
-)
-
-IF(WITH_FFMPEG)
- SET(INC ${INC} ${FFMPEG_INC})
- ADD_DEFINITIONS(-DWITH_FFMPEG)
- ADD_DEFINITIONS(-D__STDC_CONSTANT_MACROS)
-ENDIF(WITH_FFMPEG)
-
-BLENDERLIB(bf_videotex "${SRC}" "${INC}")
-#env.BlenderLib ( 'bf_videotex', sources, Split(incs), [], libtype=['game','player'], priority=[25, 72], compileflags = cflags )
diff --git a/source/gameengine/VideoTexture/Common.h b/source/gameengine/VideoTexture/Common.h
deleted file mode 100644
index f771077bbba..00000000000
--- a/source/gameengine/VideoTexture/Common.h
+++ /dev/null
@@ -1,55 +0,0 @@
-/* $Id$
------------------------------------------------------------------------------
-This source file is part of VideoTexture library
-
-Copyright (c) 2006 The Zdeno Ash Miklas
-
-This program is free software; you can redistribute it and/or modify it under
-the terms of the GNU Lesser General Public License as published by the Free Software
-Foundation; either version 2 of the License, or (at your option) any later
-version.
-
-This program is distributed in the hope that it will be useful, but WITHOUT
-ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
-
-You should have received a copy of the GNU Lesser General Public License along with
-this program; if not, write to the Free Software Foundation, Inc., 59 Temple
-Place - Suite 330, Boston, MA 02111-1307, USA, or go to
-http://www.gnu.org/copyleft/lesser.txt.
------------------------------------------------------------------------------
-*/
-
-#if defined WIN32
-#define WINDOWS_LEAN_AND_MEAN
-#endif
-
-#if !defined NULL
-#define NULL 0
-#endif
-
-#if !defined HRESULT
-#define HRESULT long
-#endif
-
-#if !defined DWORD
-#define DWORD unsigned long
-#endif
-
-#if !defined S_OK
-#define S_OK ((HRESULT)0L)
-#endif
-
-#if !defined BYTE
-#define BYTE unsigned char
-#endif
-
-#if !defined WIN32
-#define Sleep(time) sleep(time)
-#endif
-
-#if !defined FAILED
-#define FAILED(Status) ((HRESULT)(Status)<0)
-#endif
-
-#include <iostream>
diff --git a/source/gameengine/VideoTexture/Exception.cpp b/source/gameengine/VideoTexture/Exception.cpp
deleted file mode 100644
index 8704d49f2a7..00000000000
--- a/source/gameengine/VideoTexture/Exception.cpp
+++ /dev/null
@@ -1,215 +0,0 @@
-/* $Id$
------------------------------------------------------------------------------
-This source file is part of VideoTexture library
-
-Copyright (c) 2006 The Zdeno Ash Miklas
-
-This program is free software; you can redistribute it and/or modify it under
-the terms of the GNU Lesser General Public License as published by the Free Software
-Foundation; either version 2 of the License, or (at your option) any later
-version.
-
-This program is distributed in the hope that it will be useful, but WITHOUT
-ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
-
-You should have received a copy of the GNU Lesser General Public License along with
-this program; if not, write to the Free Software Foundation, Inc., 59 Temple
-Place - Suite 330, Boston, MA 02111-1307, USA, or go to
-http://www.gnu.org/copyleft/lesser.txt.
------------------------------------------------------------------------------
-*/
-
-
-#include <strstream>
-#include <fstream>
-
-#include <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, 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
-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, char * fil, int lin)
-: m_expID (&expID), m_hRslt (rslt)
-{
- // set file and line
- if (strlen(fil) > 0 || lin > 0)
- setFileLine (fil, lin);
-}
-
-
-// set file and line
-void Exception::setFileLine (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::ostrstream os(rsltTxt, rsltSize);
- os << std::hex << m_hRslt << delimRslt << '\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();
- SceneInvalidDesc.registerDesc();
- CameraInvalidDesc.registerDesc();
- ObserverInvalidDesc.registerDesc();
- MirrorInvalidDesc.registerDesc();
- MirrorSizeInvalidDesc.registerDesc();
- MirrorNormalInvalidDesc.registerDesc();
- MirrorHorizontalDesc.registerDesc();
- MirrorTooSmallDesc.registerDesc();
- SourceVideoEmptyDesc.registerDesc();
- SourceVideoCreationDesc.registerDesc();
-}
diff --git a/source/gameengine/VideoTexture/Exception.h b/source/gameengine/VideoTexture/Exception.h
deleted file mode 100644
index 1a3c25071b1..00000000000
--- a/source/gameengine/VideoTexture/Exception.h
+++ /dev/null
@@ -1,216 +0,0 @@
-/* $Id$
------------------------------------------------------------------------------
-This source file is part of VideoTexture library
-
-Copyright (c) 2006 The Zdeno Ash Miklas
-
-This program is free software; you can redistribute it and/or modify it under
-the terms of the GNU Lesser General Public License as published by the Free Software
-Foundation; either version 2 of the License, or (at your option) any later
-version.
-
-This program is distributed in the hope that it will be useful, but WITHOUT
-ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
-
-You should have received a copy of the GNU Lesser General Public License along with
-this program; if not, write to the Free Software Foundation, Inc., 59 Temple
-Place - Suite 330, Boston, MA 02111-1307, USA, or go to
-http://www.gnu.org/copyleft/lesser.txt.
------------------------------------------------------------------------------
-*/
-
-
-#if !defined 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, 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
- 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, char * fil, int lin);
- // set source file and line of exception
- void setFileLine (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 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 SceneInvalidDesc;
-extern ExpDesc CameraInvalidDesc;
-extern ExpDesc ObserverInvalidDesc;
-extern ExpDesc MirrorInvalidDesc;
-extern ExpDesc MirrorSizeInvalidDesc;
-extern ExpDesc MirrorNormalInvalidDesc;
-extern ExpDesc MirrorHorizontalDesc;
-extern ExpDesc MirrorTooSmallDesc;
-extern ExpDesc SourceVideoEmptyDesc;
-extern ExpDesc SourceVideoCreationDesc;
-
-
-void registerAllExceptions(void);
-#endif
diff --git a/source/gameengine/VideoTexture/FilterBase.cpp b/source/gameengine/VideoTexture/FilterBase.cpp
deleted file mode 100644
index b0112cd355b..00000000000
--- a/source/gameengine/VideoTexture/FilterBase.cpp
+++ /dev/null
@@ -1,150 +0,0 @@
-/* $Id$
------------------------------------------------------------------------------
-This source file is part of VideoTexture library
-
-Copyright (c) 2007 The Zdeno Ash Miklas
-
-This program is free software; you can redistribute it and/or modify it under
-the terms of the GNU Lesser General Public License as published by the Free Software
-Foundation; either version 2 of the License, or (at your option) any later
-version.
-
-This program is distributed in the hope that it will be useful, but WITHOUT
-ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
-
-You should have received a copy of the GNU Lesser General Public License along with
-this program; if not, write to the Free Software Foundation, Inc., 59 Temple
-Place - Suite 330, Boston, MA 02111-1307, USA, or go to
-http://www.gnu.org/copyleft/lesser.txt.
------------------------------------------------------------------------------
-*/
-
-#include "FilterBase.h"
-
-#include <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;
- }
-}
-
-
-// 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(value->ob_type))
- {
- // 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 b6080f018d5..00000000000
--- a/source/gameengine/VideoTexture/FilterBase.h
+++ /dev/null
@@ -1,138 +0,0 @@
-/* $Id$
------------------------------------------------------------------------------
-This source file is part of VideoTexture library
-
-Copyright (c) 2007 The Zdeno Ash Miklas
-
-This program is free software; you can redistribute it and/or modify it under
-the terms of the GNU Lesser General Public License as published by the Free Software
-Foundation; either version 2 of the License, or (at your option) any later
-version.
-
-This program is distributed in the hope that it will be useful, but WITHOUT
-ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
-
-You should have received a copy of the GNU Lesser General Public License along with
-this program; if not, write to the Free Software Foundation, Inc., 59 Temple
-Place - Suite 330, Boston, MA 02111-1307, USA, or go to
-http://www.gnu.org/copyleft/lesser.txt.
------------------------------------------------------------------------------
-*/
-
-#if !defined FILTERBASE_H
-#define FILTERBASE_H
-
-#include "Common.h"
-
-#include <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
-
-// 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; }
-
- /// 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);
- }
-};
-
-
-// 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 43d7566102a..00000000000
--- a/source/gameengine/VideoTexture/FilterBlueScreen.cpp
+++ /dev/null
@@ -1,178 +0,0 @@
-/* $Id$
------------------------------------------------------------------------------
-This source file is part of VideoTexture library
-
-Copyright (c) 2007 The Zdeno Ash Miklas
-
-This program is free software; you can redistribute it and/or modify it under
-the terms of the GNU Lesser General Public License as published by the Free Software
-Foundation; either version 2 of the License, or (at your option) any later
-version.
-
-This program is distributed in the hope that it will be useful, but WITHOUT
-ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
-
-You should have received a copy of the GNU Lesser General Public License along with
-this program; if not, write to the Free Software Foundation, Inc., 59 Temple
-Place - Suite 330, Boston, MA 02111-1307, USA, or go to
-http://www.gnu.org/copyleft/lesser.txt.
------------------------------------------------------------------------------
-*/
-
-
-#include <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 || !PySequence_Check(value) || PySequence_Length(value) != 3
- || !PyInt_Check(PySequence_Fast_GET_ITEM(value, 0))
- || !PyInt_Check(PySequence_Fast_GET_ITEM(value, 1))
- || !PyInt_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)(PyInt_AsLong(PySequence_Fast_GET_ITEM(value, 0))),
- (unsigned char)(PyInt_AsLong(PySequence_Fast_GET_ITEM(value, 1))),
- (unsigned char)(PyInt_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 || !PySequence_Check(value) || PySequence_Length(value) != 2
- || !PyInt_Check(PySequence_Fast_GET_ITEM(value, 0))
- || !PyInt_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)(PyInt_AsLong(PySequence_Fast_GET_ITEM(value, 0))),
- (unsigned short)(PyInt_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 =
-{
- PyObject_HEAD_INIT(NULL)
- 0, /*ob_size*/
- "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 820e4a44501..00000000000
--- a/source/gameengine/VideoTexture/FilterBlueScreen.h
+++ /dev/null
@@ -1,97 +0,0 @@
-/* $Id$
------------------------------------------------------------------------------
-This source file is part of blendTex library
-
-Copyright (c) 2007 The Zdeno Ash Miklas
-
-This program is free software; you can redistribute it and/or modify it under
-the terms of the GNU Lesser General Public License as published by the Free Software
-Foundation; either version 2 of the License, or (at your option) any later
-version.
-
-This program is distributed in the hope that it will be useful, but WITHOUT
-ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
-
-You should have received a copy of the GNU Lesser General Public License along with
-this program; if not, write to the Free Software Foundation, Inc., 59 Temple
-Place - Suite 330, Boston, MA 02111-1307, USA, or go to
-http://www.gnu.org/copyleft/lesser.txt.
------------------------------------------------------------------------------
-*/
-
-#if !defined 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 colour
- 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 22ee729b200..00000000000
--- a/source/gameengine/VideoTexture/FilterColor.cpp
+++ /dev/null
@@ -1,350 +0,0 @@
-/* $Id$
------------------------------------------------------------------------------
-This source file is part of VideoTexture library
-
-Copyright (c) 2007 The Zdeno Ash Miklas
-
-This program is free software; you can redistribute it and/or modify it under
-the terms of the GNU Lesser General Public License as published by the Free Software
-Foundation; either version 2 of the License, or (at your option) any later
-version.
-
-This program is distributed in the hope that it will be useful, but WITHOUT
-ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
-
-You should have received a copy of the GNU Lesser General Public License along with
-this program; if not, write to the Free Software Foundation, Inc., 59 Temple
-Place - Suite 330, Boston, MA 02111-1307, USA, or go to
-http://www.gnu.org/copyleft/lesser.txt.
------------------------------------------------------------------------------
-*/
-
-
-#include <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 =
-{
- PyObject_HEAD_INIT(NULL)
- 0, /*ob_size*/
- "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 gray scale 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_Length(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_Length(row) == 5;
- // check items
- for (int c = 0; valid && c < 5; ++c)
- {
- // item must be int
- valid = PyInt_Check(PySequence_Fast_GET_ITEM(row, c));
- // if it is valid, save it in matrix
- if (valid)
- mat[r][c] = short(PyInt_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 =
-{
- PyObject_HEAD_INIT(NULL)
- 0, /*ob_size*/
- "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_Length(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_Length(row) == 2;
- // check items
- for (int c = 0; valid && c < 2; ++c)
- {
- // item must be int
- valid = PyInt_Check(PySequence_Fast_GET_ITEM(row, c));
- // if it is valid, save it in matrix
- if (valid)
- lev[r][c] = (unsigned short)(PyInt_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 =
-{
- PyObject_HEAD_INIT(NULL)
- 0, /*ob_size*/
- "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 b7e52c4521c..00000000000
--- a/source/gameengine/VideoTexture/FilterColor.h
+++ /dev/null
@@ -1,168 +0,0 @@
-/* $Id$
------------------------------------------------------------------------------
-This source file is part of blendTex library
-
-Copyright (c) 2007 The Zdeno Ash Miklas
-
-This program is free software; you can redistribute it and/or modify it under
-the terms of the GNU Lesser General Public License as published by the Free Software
-Foundation; either version 2 of the License, or (at your option) any later
-version.
-
-This program is distributed in the hope that it will be useful, but WITHOUT
-ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
-
-You should have received a copy of the GNU Lesser General Public License along with
-this program; if not, write to the Free Software Foundation, Inc., 59 Temple
-Place - Suite 330, Boston, MA 02111-1307, USA, or go to
-http://www.gnu.org/copyleft/lesser.txt.
------------------------------------------------------------------------------
-*/
-
-#if !defined FILTERCOLOR_H
-#define FILTERCOLOR_H
-
-#include "Common.h"
-
-#include "FilterBase.h"
-
-
-/// pixel filter for gray scale
-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 gray scale 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 03a79c1c8ce..00000000000
--- a/source/gameengine/VideoTexture/FilterNormal.cpp
+++ /dev/null
@@ -1,162 +0,0 @@
-/* $Id$
------------------------------------------------------------------------------
-This source file is part of VideoTexture library
-
-Copyright (c) 2007 The Zdeno Ash Miklas
-
-This program is free software; you can redistribute it and/or modify it under
-the terms of the GNU Lesser General Public License as published by the Free Software
-Foundation; either version 2 of the License, or (at your option) any later
-version.
-
-This program is distributed in the hope that it will be useful, but WITHOUT
-ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
-
-You should have received a copy of the GNU Lesser General Public License along with
-this program; if not, write to the Free Software Foundation, Inc., 59 Temple
-Place - Suite 330, Boston, MA 02111-1307, USA, or go to
-http://www.gnu.org/copyleft/lesser.txt.
------------------------------------------------------------------------------
-*/
-
-
-#include <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 || !PyInt_Check(value))
- {
- PyErr_SetString(PyExc_TypeError, "The value must be a int");
- return -1;
- }
- // set color index
- getFilter(self)->setColor((unsigned short)(PyInt_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 == NULL || !PyFloat_Check(value))
- {
- PyErr_SetString(PyExc_TypeError, "The value must be a float");
- return -1;
- }
- // set depth
- getFilter(self)->setDepth(float(PyFloat_AsDouble(value)));
- // success
- return 0;
-}
-
-
-// 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 =
-{
- PyObject_HEAD_INIT(NULL)
- 0, /*ob_size*/
- "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 840043be9a1..00000000000
--- a/source/gameengine/VideoTexture/FilterNormal.h
+++ /dev/null
@@ -1,107 +0,0 @@
-/* $Id$
------------------------------------------------------------------------------
-This source file is part of blendTex library
-
-Copyright (c) 2007 The Zdeno Ash Miklas
-
-This program is free software; you can redistribute it and/or modify it under
-the terms of the GNU Lesser General Public License as published by the Free Software
-Foundation; either version 2 of the License, or (at your option) any later
-version.
-
-This program is distributed in the hope that it will be useful, but WITHOUT
-ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
-
-You should have received a copy of the GNU Lesser General Public License along with
-this program; if not, write to the Free Software Foundation, Inc., 59 Temple
-Place - Suite 330, Boston, MA 02111-1307, USA, or go to
-http://www.gnu.org/copyleft/lesser.txt.
------------------------------------------------------------------------------
-*/
-
-#if !defined 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 f3676e93a6d..00000000000
--- a/source/gameengine/VideoTexture/FilterSource.cpp
+++ /dev/null
@@ -1,171 +0,0 @@
-/* $Id$
------------------------------------------------------------------------------
-This source file is part of VideoTexture library
-
-Copyright (c) 2007 The Zdeno Ash Miklas
-
-This program is free software; you can redistribute it and/or modify it under
-the terms of the GNU Lesser General Public License as published by the Free Software
-Foundation; either version 2 of the License, or (at your option) any later
-version.
-
-This program is distributed in the hope that it will be useful, but WITHOUT
-ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
-
-You should have received a copy of the GNU Lesser General Public License along with
-this program; if not, write to the Free Software Foundation, Inc., 59 Temple
-Place - Suite 330, Boston, MA 02111-1307, USA, or go to
-http://www.gnu.org/copyleft/lesser.txt.
------------------------------------------------------------------------------
-*/
-
-// implementation
-
-#include <PyObjectPlus.h>
-#include <structmember.h>
-
-#include "FilterSource.h"
-
-#include "FilterBase.h"
-#include "PyTypeList.h"
-
-
-// FilterRGB24
-
-// define python type
-PyTypeObject FilterRGB24Type =
-{
- PyObject_HEAD_INIT(NULL)
- 0, /*ob_size*/
- "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 =
-{
- PyObject_HEAD_INIT(NULL)
- 0, /*ob_size*/
- "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 =
-{
- PyObject_HEAD_INIT(NULL)
- 0, /*ob_size*/
- "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 7e90747d252..00000000000
--- a/source/gameengine/VideoTexture/FilterSource.h
+++ /dev/null
@@ -1,258 +0,0 @@
-/* $Id$
------------------------------------------------------------------------------
-This source file is part of blendTex library
-
-Copyright (c) 2007 The Zdeno Ash Miklas
-
-This program is free software; you can redistribute it and/or modify it under
-the terms of the GNU Lesser General Public License as published by the Free Software
-Foundation; either version 2 of the License, or (at your option) any later
-version.
-
-This program is distributed in the hope that it will be useful, but WITHOUT
-ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
-
-You should have received a copy of the GNU Lesser General Public License along with
-this program; if not, write to the Free Software Foundation, Inc., 59 Temple
-Place - Suite 330, Boston, MA 02111-1307, USA, or go to
-http://www.gnu.org/copyleft/lesser.txt.
------------------------------------------------------------------------------
-*/
-
-#if !defined 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 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 YV12 conversion
-class FilterYV12 : public FilterBase
-{
-public:
- /// constructor
- FilterYV12 (void) {}
- /// 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, short * size)
- { 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
diff --git a/source/gameengine/VideoTexture/ImageBase.cpp b/source/gameengine/VideoTexture/ImageBase.cpp
deleted file mode 100644
index dcca20de24a..00000000000
--- a/source/gameengine/VideoTexture/ImageBase.cpp
+++ /dev/null
@@ -1,529 +0,0 @@
-/* $Id$
------------------------------------------------------------------------------
-This source file is part of VideoTexture library
-
-Copyright (c) 2007 The Zdeno Ash Miklas
-
-This program is free software; you can redistribute it and/or modify it under
-the terms of the GNU Lesser General Public License as published by the Free Software
-Foundation; either version 2 of the License, or (at your option) any later
-version.
-
-This program is distributed in the hope that it will be useful, but WITHOUT
-ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
-
-You should have received a copy of the GNU Lesser General Public License along with
-this program; if not, write to the Free Software Foundation, Inc., 59 Temple
-Place - Suite 330, Boston, MA 02111-1307, USA, or go to
-http://www.gnu.org/copyleft/lesser.txt.
------------------------------------------------------------------------------
-*/
-
-#include "ImageBase.h"
-
-#include <vector>
-#include <string.h>
-
-#include <PyObjectPlus.h>
-#include <structmember.h>
-
-#include "FilterBase.h"
-
-#include "Exception.h"
-
-
-
-// ImageBase class implementation
-
-// constructor
-ImageBase::ImageBase (bool staticSrc) : m_image(NULL), m_imgSize(0),
-m_avail(false), m_scale(false), m_scaleChange(false), m_flip(false),
-m_staticSources(staticSrc), m_pyfilter(NULL)
-{
- m_size[0] = m_size[1] = 0;
-}
-
-
-// destructor
-ImageBase::~ImageBase (void)
-{
- // release 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)
-{
- // 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();
- // init image
- init(m_sources[0]->getSize()[0], m_sources[0]->getSize()[1]);
- }
- // calculate new image
- calcImage(texId);
- }
- // if image is available, return it, otherwise NULL
- return m_avail ? m_image : NULL;
-}
-
-
-// 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;
-}
-
-
-// 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])
- {
- // 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
- 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 (void)
-{
- // if source is available
- if (m_source != NULL)
- // get image from source
- m_image = m_source->m_image->getImage();
- // 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 release requires deleting of object, do it
- if (self->m_image->release())
- delete self->m_image;
- self->m_image = NULL;
- }
-}
-
-// get image data
-PyObject * Image_getImage (PyImage * self, void * closure)
-{
- try
- {
- // get image
- unsigned int * image = self->m_image->getImage();
- return Py_BuildValue("s#", image, self->m_image->getBuffSize());
- }
- catch (Exception & exp)
- {
- exp.report();
- }
- 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)
-{
- self->m_image->refresh();
- Py_RETURN_NONE;
-}
-
-// 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 filter source object
-PyObject * Image_getSource (PyImage * self, PyObject * args)
-{
- // get arguments
- char * id;
- if (self->m_image != NULL && PyArg_ParseTuple(args, "s", &id))
- {
- // 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 (self->m_image != NULL && PyArg_ParseTuple(args, "sO", &id, &obj))
- {
- // check type of object
- if (pyImageTypes.in(obj->ob_type))
- {
- // 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(value->ob_type))
- {
- // 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;
-}
diff --git a/source/gameengine/VideoTexture/ImageBase.h b/source/gameengine/VideoTexture/ImageBase.h
deleted file mode 100644
index 138580ce701..00000000000
--- a/source/gameengine/VideoTexture/ImageBase.h
+++ /dev/null
@@ -1,349 +0,0 @@
-/* $Id$
------------------------------------------------------------------------------
-This source file is part of blendTex library
-
-Copyright (c) 2007 The Zdeno Ash Miklas
-
-This program is free software; you can redistribute it and/or modify it under
-the terms of the GNU Lesser General Public License as published by the Free Software
-Foundation; either version 2 of the License, or (at your option) any later
-version.
-
-This program is distributed in the hope that it will be useful, but WITHOUT
-ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
-
-You should have received a copy of the GNU Lesser General Public License along with
-this program; if not, write to the Free Software Foundation, Inc., 59 Temple
-Place - Suite 330, Boston, MA 02111-1307, USA, or go to
-http://www.gnu.org/copyleft/lesser.txt.
------------------------------------------------------------------------------
-*/
-
-#if !defined IMAGEBASE_H
-#define IMAGEBASE_H
-
-#include "Common.h"
-
-#include <vector>
-#include <PyObjectPlus.h>
-
-#include "PyTypeList.h"
-
-#include "FilterBase.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);
-
- /// get image
- unsigned int * getImage (unsigned int texId = 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 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);
-
-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;
-
- /// 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) {}
-
- /// 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 neighbour)
- 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 (void);
- /// 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, void * closure);
-// get image size
-PyObject * Image_getSize (PyImage * self, void * closure);
-// refresh image - invalidate current content
-PyObject * Image_refresh (PyImage * self);
-
-// 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 pixel filter object
-PyObject * Image_getFilter (PyImage * self, void * closure);
-// set pixel filter object
-int Image_setFilter (PyImage * self, PyObject * value, void * closure);
-
-
-#endif
diff --git a/source/gameengine/VideoTexture/ImageBuff.cpp b/source/gameengine/VideoTexture/ImageBuff.cpp
deleted file mode 100644
index 19ad17ac643..00000000000
--- a/source/gameengine/VideoTexture/ImageBuff.cpp
+++ /dev/null
@@ -1,166 +0,0 @@
-/* $Id$
------------------------------------------------------------------------------
-This source file is part of VideoTexture library
-
-Copyright (c) 2007 The Zdeno Ash Miklas
-
-This program is free software; you can redistribute it and/or modify it under
-the terms of the GNU Lesser General Public License as published by the Free Software
-Foundation; either version 2 of the License, or (at your option) any later
-version.
-
-This program is distributed in the hope that it will be useful, but WITHOUT
-ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
-
-You should have received a copy of the GNU Lesser General Public License along with
-this program; if not, write to the Free Software Foundation, Inc., 59 Temple
-Place - Suite 330, Boston, MA 02111-1307, USA, or go to
-http://www.gnu.org/copyleft/lesser.txt.
------------------------------------------------------------------------------
-*/
-
-// implementation
-
-#include <PyObjectPlus.h>
-#include <structmember.h>
-
-#include "ImageBuff.h"
-
-#include "ImageBase.h"
-#include "FilterSource.h"
-
-
-// default filter
-FilterRGB24 defFilter;
-
-
-// load image from buffer
-void ImageBuff::load (unsigned char * img, short width, short height)
-{
- // 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;
-}
-
-
-
-// cast Image pointer to ImageBuff
-inline ImageBuff * getImageBuff (PyImage * self)
-{ return static_cast<ImageBuff*>(self->m_image); }
-
-
-// python methods
-
-// load image
-static PyObject * load (PyImage * self, PyObject * args)
-{
- // parameters: string image buffer, its size, width, height
- unsigned char * buff;
- unsigned int buffSize;
- short width;
- short height;
- // parse parameters
- if (!PyArg_ParseTuple(args, "s#hh", &buff, &buffSize, &width, &height))
- {
- // report error
- PyErr_SetString(PyExc_TypeError, "Parameters are not correct");
- return NULL;
- }
- // else check buffer size
- else
- {
- // calc proper buffer size
- unsigned int propSize = width * height;
- // use pixel size from filter
- if (self->m_image->getFilter() != NULL)
- propSize *= self->m_image->getFilter()->m_filter->firstPixelSize();
- else
- propSize *= defFilter.firstPixelSize();
- // check if buffer size is correct
- if (propSize != buffSize)
- {
- // if not, report error
- PyErr_SetString(PyExc_TypeError, "Buffer hasn't correct size");
- return NULL;
- }
- else
- // if correct, load image
- getImageBuff(self)->load(buff, width, height);
- }
- Py_RETURN_NONE;
-}
-
-
-// methods structure
-static PyMethodDef imageBuffMethods[] =
-{
- {"load", (PyCFunction)load, METH_VARARGS, "Load image from buffer"},
- {NULL}
-};
-// attributes structure
-static PyGetSetDef imageBuffGetSets[] =
-{ // attributes from ImageBase class
- {(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 neighbour)", 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 =
-{
- PyObject_HEAD_INIT(NULL)
- 0, /*ob_size*/
- "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*/
- 0, /*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)Image_init<ImageBuff>, /* 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 fa2025fa8c4..00000000000
--- a/source/gameengine/VideoTexture/ImageBuff.h
+++ /dev/null
@@ -1,51 +0,0 @@
-/* $Id$
------------------------------------------------------------------------------
-This source file is part of VideoTexture library
-
-Copyright (c) 2007 The Zdeno Ash Miklas
-
-This program is free software; you can redistribute it and/or modify it under
-the terms of the GNU Lesser General Public License as published by the Free Software
-Foundation; either version 2 of the License, or (at your option) any later
-version.
-
-This program is distributed in the hope that it will be useful, but WITHOUT
-ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
-
-You should have received a copy of the GNU Lesser General Public License along with
-this program; if not, write to the Free Software Foundation, Inc., 59 Temple
-Place - Suite 330, Boston, MA 02111-1307, USA, or go to
-http://www.gnu.org/copyleft/lesser.txt.
------------------------------------------------------------------------------
-*/
-
-#if !defined IMAGEBUFF_H
-#define IMAGEBUFF_H
-
-
-#include "Common.h"
-
-#include "ImageBase.h"
-
-
-/// class for image buffer
-class ImageBuff : public ImageBase
-{
-public:
- /// constructor
- ImageBuff (void) : ImageBase(true) {}
-
- /// destructor
- virtual ~ImageBuff (void) {}
-
- /// load image from buffer
- void load (unsigned char * img, short width, short height);
-
- /// 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 b07b362818c..00000000000
--- a/source/gameengine/VideoTexture/ImageMix.cpp
+++ /dev/null
@@ -1,205 +0,0 @@
-/* $Id$
------------------------------------------------------------------------------
-This source file is part of VideoTexture library
-
-Copyright (c) 2007 The Zdeno Ash Miklas
-
-This program is free software; you can redistribute it and/or modify it under
-the terms of the GNU Lesser General Public License as published by the Free Software
-Foundation; either version 2 of the License, or (at your option) any later
-version.
-
-This program is distributed in the hope that it will be useful, but WITHOUT
-ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
-
-You should have received a copy of the GNU Lesser General Public License along with
-this program; if not, write to the Free Software Foundation, Inc., 59 Temple
-Place - Suite 330, Boston, MA 02111-1307, USA, or go to
-http://www.gnu.org/copyleft/lesser.txt.
------------------------------------------------------------------------------
-*/
-
-// implementation
-
-#include <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)
-{
- // 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
-PyObject * getWeight (PyImage * self, PyObject * args)
-{
- // weight
- short weight = 0;
- // get arguments
- char * id;
- if (self->m_image != NULL && PyArg_ParseTuple(args, "s", &id))
- // get weight
- weight = getImageMix(self)->getWeight(id);
- // return weight
- return Py_BuildValue("h", weight);
-}
-
-
-// set source weight
-PyObject * setWeight (PyImage * self, PyObject * args)
-{
- // get arguments
- char * id;
- short weight = 0;
- if (self->m_image != NULL && PyArg_ParseTuple(args, "sh", &id, &weight))
- // 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_NOARGS, "Refresh image - invalidate its current content"},
- {NULL}
-};
-// attributes structure
-static PyGetSetDef imageMixGetSets[] =
-{ // attributes from ImageBase class
- {(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 neighbour)", 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 =
-{
- PyObject_HEAD_INIT(NULL)
- 0, /*ob_size*/
- "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*/
- 0, /*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 b4842bd6b40..00000000000
--- a/source/gameengine/VideoTexture/ImageMix.h
+++ /dev/null
@@ -1,123 +0,0 @@
-/* $Id$
------------------------------------------------------------------------------
-This source file is part of VideoTexture library
-
-Copyright (c) 2007 The Zdeno Ash Miklas
-
-This program is free software; you can redistribute it and/or modify it under
-the terms of the GNU Lesser General Public License as published by the Free Software
-Foundation; either version 2 of the License, or (at your option) any later
-version.
-
-This program is distributed in the hope that it will be useful, but WITHOUT
-ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
-
-You should have received a copy of the GNU Lesser General Public License along with
-this program; if not, write to the Free Software Foundation, Inc., 59 Temple
-Place - Suite 330, Boston, MA 02111-1307, USA, or go to
-http://www.gnu.org/copyleft/lesser.txt.
------------------------------------------------------------------------------
-*/
-
-#if !defined 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_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);
-};
-
-
-/// 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 58697ed3cc7..00000000000
--- a/source/gameengine/VideoTexture/ImageRender.cpp
+++ /dev/null
@@ -1,742 +0,0 @@
-/* $Id$
------------------------------------------------------------------------------
-This source file is part of VideoTexture library
-
-Copyright (c) 2007 The Zdeno Ash Miklas
-
-This program is free software; you can redistribute it and/or modify it under
-the terms of the GNU Lesser General Public License as published by the Free Software
-Foundation; either version 2 of the License, or (at your option) any later
-version.
-
-This program is distributed in the hope that it will be useful, but WITHOUT
-ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
-
-You should have received a copy of the GNU Lesser General Public License along with
-this program; if not, write to the Free Software Foundation, Inc., 59 Temple
-Place - Suite 330, Boston, MA 02111-1307, USA, or go to
-http://www.gnu.org/copyleft/lesser.txt.
------------------------------------------------------------------------------
-*/
-
-// implementation
-
-#include <PyObjectPlus.h>
-#include <structmember.h>
-#include <float.h>
-#include <math.h>
-
-
-#include <BIF_gl.h>
-
-#include "KX_PythonInit.h"
-#include "DNA_scene_types.h"
-#include "RAS_CameraData.h"
-#include "RAS_MeshObject.h"
-#include "BLI_arithb.h"
-
-#include "ImageRender.h"
-#include "ImageBase.h"
-#include "BlendType.h"
-#include "Exception.h"
-#include "Texture.h"
-
-ExceptionID SceneInvalid, CameraInvalid, ObserverInvalid;
-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 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) :
- ImageViewport(),
- m_render(true),
- m_scene(scene),
- m_camera(camera),
- m_owncamera(false),
- m_observer(NULL),
- m_mirror(NULL),
- m_clip(100.f)
-{
- // initialize background colour
- setBackground(0, 0, 255, 255);
- // retrieve rendering objects
- m_engine = KX_GetActiveEngine();
- m_rasterizer = m_engine->GetRasterizer();
- m_canvas = m_engine->GetCanvas();
- m_rendertools = m_engine->GetRenderTools();
-}
-
-// destructor
-ImageRender::~ImageRender (void)
-{
- if (m_owncamera)
- m_camera->Release();
-}
-
-
-// set background color
-void ImageRender::setBackground (int red, int green, int blue, int alpha)
-{
- m_background[0] = (red < 0) ? 0.f : (red > 255) ? 1.f : float(red)/255.f;
- m_background[1] = (green < 0) ? 0.f : (green > 255) ? 1.f : float(green)/255.f;
- m_background[2] = (blue < 0) ? 0.f : (blue > 255) ? 1.f : float(blue)/255.f;
- m_background[3] = (alpha < 0) ? 0.f : (alpha > 255) ? 1.f : float(alpha)/255.f;
-}
-
-
-// capture image from viewport
-void ImageRender::calcImage (unsigned int texId)
-{
- if (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
- m_avail = false;
- return;
- }
- // render the scene from the camera
- Render();
- // get image from viewport
- ImageViewport::calcImage(texId);
- // restore OpenGL state
- m_canvas->EndFrame();
-}
-
-void ImageRender::Render()
-{
- RAS_FrameFrustum frustrum;
-
- if (!m_render)
- return;
-
- if (m_mirror)
- {
- // mirror mode, compute camera frustrum, 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.01f)
- return;
- // 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 frustrum:
- // 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
- frustrum.x1 = mirrorOffset[0]-width;
- frustrum.x2 = mirrorOffset[0]+width;
- frustrum.y1 = mirrorOffset[1]-height;
- frustrum.y2 = mirrorOffset[1]+height;
- frustrum.camnear = -mirrorOffset[2];
- frustrum.camfar = -mirrorOffset[2]+m_clip;
- }
- const float ortho = 100.0;
- const RAS_IRasterizer::StereoMode stereomode = m_rasterizer->GetStereoMode();
-
- // The screen area that ImageViewport will copy is also the rendering zone
- 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(RAS_IRasterizer::KX_TEXTURED,m_engine->GetClockTime());
- m_rendertools->BeginFrame(m_rasterizer);
- m_engine->SetWorldSettings(m_scene->GetWorldInfo());
- m_rendertools->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)
- {
- // frustrum was computed above
- // get frustrum matrix and set projection matrix
- MT_Matrix4x4 projmat = m_rasterizer->GetFrustumMatrix(
- frustrum.x1, frustrum.x2, frustrum.y1, frustrum.y2, frustrum.camnear, frustrum.camfar);
-
- m_camera->SetProjectionMatrix(projmat);
- } else if (m_camera->hasValidProjectionMatrix())
- {
- m_rasterizer->SetProjectionMatrix(m_camera->GetProjectionMatrix());
- } else
- {
- float lens = m_camera->GetLens();
- 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();
-
- if (orthographic) {
- lens *= ortho;
- nearfrust = (nearfrust + 1.0)*ortho;
- farfrust *= ortho;
- }
- // 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) / float(blenderScene->r.ysch);
-
- RAS_FramingManager::ComputeDefaultFrustum(
- nearfrust,
- farfrust,
- lens,
- aspect_ratio,
- frustrum);
-
- MT_Matrix4x4 projmat = m_rasterizer->GetFrustumMatrix(
- frustrum.x1, frustrum.x2, frustrum.y1, frustrum.y2, frustrum.camnear, frustrum.camfar);
-
- m_camera->SetProjectionMatrix(projmat);
- }
-
- MT_Transform camtrans(m_camera->GetWorldToCamera());
- if (!m_camera->GetCameraData()->m_perspective)
- camtrans.getOrigin()[2] *= ortho;
- MT_Matrix4x4 viewmat(camtrans);
-
- m_rasterizer->SetViewMatrix(viewmat, m_camera->NodeGetWorldPosition(),
- m_camera->GetCameraLocation(), m_camera->GetCameraOrientation());
- m_camera->SetModelviewMatrix(viewmat);
- // restore the stereo mode now that the matrix is computed
- m_rasterizer->SetStereoMode(stereomode);
-
- // do not update the mesh, we don't want to do it more than once per frame
- //m_scene->UpdateMeshTransformations();
-
- m_scene->CalculateVisibleMeshes(m_rasterizer,m_camera);
-
- m_scene->RenderBuckets(camtrans, m_rasterizer, m_rendertools);
-}
-
-
-// cast Image pointer to ImageRender
-inline ImageRender * getImageRender (PyImage * self)
-{ return static_cast<ImageRender*>(self->m_image); }
-
-
-// python methods
-
-// Blender Scene type
-BlendType<KX_Scene> sceneType ("KX_Scene");
-// Blender Camera type
-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;
- // parameter keywords
- static char *kwlist[] = {"sceneObj", "cameraObj", NULL};
- // get parameters
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO", kwlist, &scene, &camera))
- 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);
-
- // 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);
- }
- catch (Exception & exp)
- {
- exp.report();
- return -1;
- }
- // initialization succeded
- return 0;
-}
-
-
-// get background color
-PyObject * getBackground (PyImage * self, void * closure)
-{
- return Py_BuildValue("[BBBB]",
- 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_Length(value) != 4
- || !PyInt_Check(PySequence_Fast_GET_ITEM(value, 0))
- || !PyInt_Check(PySequence_Fast_GET_ITEM(value, 1))
- || !PyInt_Check(PySequence_Fast_GET_ITEM(value, 2))
- || !PyInt_Check(PySequence_Fast_GET_ITEM(value, 3)))
- {
- PyErr_SetString(PyExc_TypeError, "The value must be a sequence of 4 integer between 0 and 255");
- return -1;
- }
- // set background color
- getImageRender(self)->setBackground((unsigned char)(PyInt_AsLong(PySequence_Fast_GET_ITEM(value, 0))),
- (unsigned char)(PyInt_AsLong(PySequence_Fast_GET_ITEM(value, 1))),
- (unsigned char)(PyInt_AsLong(PySequence_Fast_GET_ITEM(value, 2))),
- (unsigned char)(PyInt_AsLong(PySequence_Fast_GET_ITEM(value, 3))));
- // success
- return 0;
-}
-
-
-// methods structure
-static PyMethodDef imageRenderMethods[] =
-{ // methods from ImageBase class
- {"refresh", (PyCFunction)Image_refresh, METH_NOARGS, "Refresh image - invalidate its current content"},
- {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*)"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 neighbour)", 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 ImageRenderType =
-{
- PyObject_HEAD_INIT(NULL)
- 0, /*ob_size*/
- "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*/
- 0, /*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 char *kwlist[] = {"scene", "observer", "mirror", "material", NULL};
- // get parameters
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "OOO|h", 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*>(scene);
- else
- 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*>(observer);
- else if (observer != NULL && PyObject_TypeCheck(observer, &KX_Camera::Type))
- observerPtr = static_cast<KX_Camera*>(observer);
- else
- 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*>(mirror);
- else
- 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 succeded
- return 0;
-}
-
-// get background color
-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*)"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 neighbour)", 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}
-};
-
-
-// constructor
-ImageRender::ImageRender (KX_Scene * scene, KX_GameObject * observer, KX_GameObject * mirror, RAS_IPolyMaterial * mat) :
- ImageViewport(),
- m_render(false),
- m_scene(scene),
- 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 frustrum 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;
-
- m_camera= new KX_Camera(scene, KX_Scene::m_callbacks, camdata);
- 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();
- m_rendertools = m_engine->GetRenderTools();
- // 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 = CalcNormFloat4((float*)v1->getXYZ(), (float*)v2->getXYZ(), (float*)v3->getXYZ(), (float*)v4->getXYZ(), normal);
- } else
- {
- area = CalcNormFloat((float*)v1->getXYZ(), (float*)v2->getXYZ(), (float*)v3->getXYZ(), normal);
- }
- area = fabs(area);
- mirrorArea += area;
- VecMulf(normal, area);
- VecAddf(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
- VecMulf(mirrorNormal, 1.0f/mirrorArea);
- if (Normalize(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 (fabs(mirrorNormal[2]) > fabs(mirrorNormal[1]) &&
- fabs(mirrorNormal[2]) > fabs(mirrorNormal[0]))
- {
- // the mirror is more horizontal than vertical
- VecCopyf(axis, yaxis);
- }
- else
- {
- // the mirror is more vertical than horizontal
- VecCopyf(axis, zaxis);
- }
- dist = Inpf(mirrorNormal, axis);
- if (fabs(dist) < FLT_EPSILON)
- {
- // the mirror is already fully aligned with up axis
- VecCopyf(mirrorUp, axis);
- }
- else
- {
- // projection of axis to mirror plane through normal
- VecCopyf(vec, mirrorNormal);
- VecMulf(vec, dist);
- VecSubf(mirrorUp, axis, vec);
- if (Normalize(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
- VecCopyf(mirrorMat[2], mirrorNormal);
- VecMulf(mirrorMat[2], -1.0f);
- VecCopyf(mirrorMat[1], mirrorUp);
- Crossf(mirrorMat[0], mirrorMat[1], mirrorMat[2]);
- // transpose to make it a orientation matrix from local space to mirror space
- Mat3Transp(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++)
- {
- VecCopyf(vec, (float*)(*it)->getXYZ());
- Mat3MulVecfl(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
- Mat3Transp(mirrorMat);
- Mat3MulVecfl(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;
-
- setBackground(0, 0, 255, 255);
-}
-
-
-
-
-// define python type
-PyTypeObject ImageMirrorType =
-{
- PyObject_HEAD_INIT(NULL)
- 0, /*ob_size*/
- "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*/
- 0, /*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 c94e2f1e718..00000000000
--- a/source/gameengine/VideoTexture/ImageRender.h
+++ /dev/null
@@ -1,104 +0,0 @@
-/* $Id$
------------------------------------------------------------------------------
-This source file is part of VideoTexture library
-
-Copyright (c) 2007 The Zdeno Ash Miklas
-
-This program is free software; you can redistribute it and/or modify it under
-the terms of the GNU Lesser General Public License as published by the Free Software
-Foundation; either version 2 of the License, or (at your option) any later
-version.
-
-This program is distributed in the hope that it will be useful, but WITHOUT
-ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
-
-You should have received a copy of the GNU Lesser General Public License along with
-this program; if not, write to the Free Software Foundation, Inc., 59 Temple
-Place - Suite 330, Boston, MA 02111-1307, USA, or go to
-http://www.gnu.org/copyleft/lesser.txt.
------------------------------------------------------------------------------
-*/
-
-#if !defined 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_IRenderTools.h>
-
-#include "ImageViewport.h"
-
-
-/// class for render 3d scene
-class ImageRender : public ImageViewport
-{
-public:
- /// constructor
- ImageRender (KX_Scene * scene, KX_Camera * camera);
- ImageRender (KX_Scene * scene, KX_GameObject * observer, KX_GameObject * mirror, RAS_IPolyMaterial * mat);
-
- /// destructor
- virtual ~ImageRender (void);
-
- /// get background color
- int getBackground (int idx) { return (idx < 0 || idx > 3) ? 0 : int(m_background[idx]*255.f); }
- /// set background color
- void setBackground (int red, int green, int blue, int alpha);
-
- /// clipping distance
- float getClip (void) { return m_clip; }
- /// set whole buffer use
- void setClip (float clip) { m_clip = clip; }
-
-protected:
- /// true if ready to render
- bool m_render;
- /// rendered scene
- KX_Scene * m_scene;
- /// camera for render
- KX_Camera * m_camera;
- /// do we own the camera?
- bool m_owncamera;
- /// 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;
- /// render tools
- RAS_IRenderTools* m_rendertools;
- /// engine
- KX_KetsjiEngine* m_engine;
-
- /// background colour
- float m_background[4];
-
-
- /// render 3d scene to image
- virtual void calcImage (unsigned int texId);
-
- void Render();
- void SetupRenderFrame(KX_Scene *scene, KX_Camera* cam);
- void RenderFrame(KX_Scene* scene, KX_Camera* cam);
- void SetBackGround(KX_WorldInfo* wi);
- 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 4c2c81e2208..00000000000
--- a/source/gameengine/VideoTexture/ImageViewport.cpp
+++ /dev/null
@@ -1,331 +0,0 @@
-/* $Id$
------------------------------------------------------------------------------
-This source file is part of VideoTexture library
-
-Copyright (c) 2007 The Zdeno Ash Miklas
-
-This program is free software; you can redistribute it and/or modify it under
-the terms of the GNU Lesser General Public License as published by the Free Software
-Foundation; either version 2 of the License, or (at your option) any later
-version.
-
-This program is distributed in the hope that it will be useful, but WITHOUT
-ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
-
-You should have received a copy of the GNU Lesser General Public License along with
-this program; if not, write to the Free Software Foundation, Inc., 59 Temple
-Place - Suite 330, Boston, MA 02111-1307, USA, or go to
-http://www.gnu.org/copyleft/lesser.txt.
------------------------------------------------------------------------------
-*/
-
-// implementation
-
-#include <PyObjectPlus.h>
-#include <structmember.h>
-
-#include <BIF_gl.h>
-
-#include "Texture.h"
-#include "ImageBase.h"
-#include "FilterSource.h"
-#include "ImageViewport.h"
-
-
-// constructor
-ImageViewport::ImageViewport (void) : m_alpha(false), m_texInit(false)
-{
- // get viewport rectangle
- glGetIntegerv(GL_VIEWPORT, m_viewport);
- // create buffer for viewport image
- m_viewportImage = new BYTE [4 * getViewportSize()[0] * getViewportSize()[1]];
- // set attributes
- setWhole(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)
-{
- 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)
-{
- // 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::calcImage (unsigned int texId)
-{
- // if scale was changed
- if (m_scaleChange)
- // reset image
- init(m_capSize[0], m_capSize[1]);
- // if texture wasn't initialized
- if (!m_texInit)
- {
- // initialize it
- loadTexture(texId, m_image, m_size);
- m_texInit = true;
- }
- // if texture can be directly created
- if (texId != 0 && m_pyfilter == NULL && m_capSize[0] == calcSize(m_capSize[0])
- && m_capSize[1] == calcSize(m_capSize[1]) && !m_flip)
- {
- // 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]);
- // image is not available
- m_avail = false;
- }
- // otherwise copy viewport to buffer, if image is not available
- else if (!m_avail)
- {
- // get frame buffer data
- if (m_alpha)
- {
- glReadPixels(m_upLeft[0], m_upLeft[1], (GLsizei)m_capSize[0], (GLsizei)m_capSize[1], GL_RGBA,
- GL_UNSIGNED_BYTE, m_viewportImage);
- // filter loaded data
- 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_RGB,
- GL_UNSIGNED_BYTE, m_viewportImage);
- // filter loaded data
- FilterRGB24 filt;
- filterImage(filt, m_viewportImage, m_capSize);
- }
- }
-}
-
-
-
-// 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;
- }
- // set whole
- if (self->m_image != NULL) getImageViewport(self)->setWhole(value == Py_True);
- // 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)
-{
- return Py_BuildValue("(ii)", getImageViewport(self)->getPosition()[0],
- getImageViewport(self)->getPosition()[1]);
-}
-
-// set position
-static int ImageViewport_setPosition (PyImage * self, PyObject * value, void * closure)
-{
- // check validity of parameter
- if (value == NULL || !PySequence_Check(value) || PySequence_Length(value) != 2
- || !PyInt_Check(PySequence_Fast_GET_ITEM(value, 0))
- || !PyInt_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 [] = {
- GLint(PyInt_AsLong(PySequence_Fast_GET_ITEM(value, 0))),
- GLint(PyInt_AsLong(PySequence_Fast_GET_ITEM(value, 1)))
- };
- getImageViewport(self)->setPosition(pos);
- // success
- return 0;
-}
-
-// get capture size
-PyObject * ImageViewport_getCaptureSize (PyImage * self, void * closure)
-{
- return Py_BuildValue("(ii)", getImageViewport(self)->getCaptureSize()[0],
- getImageViewport(self)->getCaptureSize()[1]);
-}
-
-// set capture size
-int ImageViewport_setCaptureSize (PyImage * self, PyObject * value, void * closure)
-{
- // check validity of parameter
- if (value == NULL || !PySequence_Check(value) || PySequence_Length(value) != 2
- || !PyInt_Check(PySequence_Fast_GET_ITEM(value, 0))
- || !PyInt_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 [] = {
- short(PyInt_AsLong(PySequence_Fast_GET_ITEM(value, 0))),
- short(PyInt_AsLong(PySequence_Fast_GET_ITEM(value, 1)))
- };
- getImageViewport(self)->setCaptureSize(size);
- // success
- return 0;
-}
-
-
-// methods structure
-static PyMethodDef imageViewportMethods[] =
-{ // methods from ImageBase class
- {"refresh", (PyCFunction)Image_refresh, METH_NOARGS, "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*)"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 neighbour)", 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 ImageViewportType =
-{
- PyObject_HEAD_INIT(NULL)
- 0, /*ob_size*/
- "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*/
- 0, /*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 0449249cf95..00000000000
--- a/source/gameengine/VideoTexture/ImageViewport.h
+++ /dev/null
@@ -1,98 +0,0 @@
-/* $Id$
------------------------------------------------------------------------------
-This source file is part of VideoTexture library
-
-Copyright (c) 2007 The Zdeno Ash Miklas
-
-This program is free software; you can redistribute it and/or modify it under
-the terms of the GNU Lesser General Public License as published by the Free Software
-Foundation; either version 2 of the License, or (at your option) any later
-version.
-
-This program is distributed in the hope that it will be useful, but WITHOUT
-ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
-
-You should have received a copy of the GNU Lesser General Public License along with
-this program; if not, write to the Free Software Foundation, Inc., 59 Temple
-Place - Suite 330, Boston, MA 02111-1307, USA, or go to
-http://www.gnu.org/copyleft/lesser.txt.
------------------------------------------------------------------------------
-*/
-
-#if !defined IMAGEVIEWPORT_H
-#define IMAGEVIEWPORT_H
-
-
-#include "Common.h"
-
-#include "ImageBase.h"
-
-
-/// class for viewport access
-class ImageViewport : public ImageBase
-{
-public:
- /// constructor
- ImageViewport (void);
-
- /// 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 = NULL);
-
- /// get position in viewport
- GLint * getPosition (void) { return m_position; }
- /// set position in viewport
- void setPosition (GLint * pos = NULL);
-
-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);
-
- /// 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/Makefile b/source/gameengine/VideoTexture/Makefile
deleted file mode 100644
index bead176808b..00000000000
--- a/source/gameengine/VideoTexture/Makefile
+++ /dev/null
@@ -1,65 +0,0 @@
-#
-# $Id$
-#
-# ***** BEGIN GPL LICENSE BLOCK *****
-#
-# This program is free software; you can redistribute it and/or
-# modify it under the terms of the GNU General Public License
-# as published by the Free Software Foundation; either version 2
-# of the License, or (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software Foundation,
-# Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
-#
-# The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
-# All rights reserved.
-#
-# The Original Code is: all of this file.
-#
-# Contributor(s): none yet.
-#
-# ***** END GPL LICENSE BLOCK *****
-#
-#
-
-LIBNAME = videotex
-DIR = $(OCGDIR)/gameengine/$(LIBNAME)
-SOURCEDIR = source/gameengine/VideoTexture
-
-include nan_compile.mk
-
-CCFLAGS += $(LEVEL_1_CPP_WARNINGS)
-
-CPPFLAGS += $(OGL_CPPFLAGS)
-CPPFLAGS += -I$(NAN_GLEW)/include
-CPPFLAGS += -I$(OPENGL_HEADERS)
-CPPFLAGS += -I$(NAN_PYTHON)/include/python$(NAN_PYTHON_VERSION)
-CPPFLAGS += -I../../blender/python
-CPPFLAGS += -I$(NAN_STRING)/include
-CPPFLAGS += -I$(NAN_SOUNDSYSTEM)/include
-CPPFLAGS += -I$(NAN_MOTO)/include
-CPPFLAGS += -I../Rasterizer/RAS_OpenGLRasterizer
-CPPFLAGS += -I../Rasterizer -I../GameLogic -I../SceneGraph
-CPPFLAGS += -I../BlenderRoutines -I../Expressions -I../Ketsji
-CPPFLAGS += -I../../kernel/gen_system
-CPPFLAGS += -I.
-CPPFLAGS += -I../../blender/blenkernel
-CPPFLAGS += -I../../blender/blenlib
-CPPFLAGS += -I../../blender/include
-CPPFLAGS += -I../../blender/makesdna
-CPPFLAGS += -I../../blender/imbuf
-CPPFLAGS += -I../../blender/gpu
-CPPFLAGS += -I$(NAN_GUARDEDALLOC)/include
-
-ifeq ($(WITH_FFMPEG),true)
- CPPFLAGS += -DWITH_FFMPEG
- CPPFLAGS += $(NAN_FFMPEGCFLAGS)
-endif
-
-
diff --git a/source/gameengine/VideoTexture/PyTypeList.cpp b/source/gameengine/VideoTexture/PyTypeList.cpp
deleted file mode 100644
index 6d2676dce09..00000000000
--- a/source/gameengine/VideoTexture/PyTypeList.cpp
+++ /dev/null
@@ -1,83 +0,0 @@
-/* $Id$
------------------------------------------------------------------------------
-This source file is part of blendTex library
-
-Copyright (c) 2007 The Zdeno Ash Miklas
-
-This program is free software; you can redistribute it and/or modify it under
-the terms of the GNU Lesser General Public License as published by the Free Software
-Foundation; either version 2 of the License, or (at your option) any later
-version.
-
-This program is distributed in the hope that it will be useful, but WITHOUT
-ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
-
-You should have received a copy of the GNU Lesser General Public License along with
-this program; if not, write to the Free Software Foundation, Inc., 59 Temple
-Place - Suite 330, Boston, MA 02111-1307, USA, or go to
-http://www.gnu.org/copyleft/lesser.txt.
------------------------------------------------------------------------------
-*/
-
-
-#include "PyTypeList.h"
-
-#include <memory>
-#include <vector>
-
-#include <PyObjectPlus.h>
-
-
-/// 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)
-{
- PyTypeListItem * typeItem;
- // 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, (char*)(*it)->getName(), (PyObject*)(*it)->getType());
- }
-}
diff --git a/source/gameengine/VideoTexture/PyTypeList.h b/source/gameengine/VideoTexture/PyTypeList.h
deleted file mode 100644
index 4daf88bfa19..00000000000
--- a/source/gameengine/VideoTexture/PyTypeList.h
+++ /dev/null
@@ -1,85 +0,0 @@
-/* $Id$
------------------------------------------------------------------------------
-This source file is part of blendTex library
-
-Copyright (c) 2007 The Zdeno Ash Miklas
-
-This program is free software; you can redistribute it and/or modify it under
-the terms of the GNU Lesser General Public License as published by the Free Software
-Foundation; either version 2 of the License, or (at your option) any later
-version.
-
-This program is distributed in the hope that it will be useful, but WITHOUT
-ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
-
-You should have received a copy of the GNU Lesser General Public License along with
-this program; if not, write to the Free Software Foundation, Inc., 59 Temple
-Place - Suite 330, Boston, MA 02111-1307, USA, or go to
-http://www.gnu.org/copyleft/lesser.txt.
------------------------------------------------------------------------------
-*/
-
-#if !defined PYTYPELIST_H
-#define PYTYPELIST_H
-
-#include "Common.h"
-
-#include <memory>
-#include <vector>
-
-#include <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:
- /// 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
- std::auto_ptr<PyTypeListType> m_list;
-};
-
-
-/// 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/SConscript b/source/gameengine/VideoTexture/SConscript
deleted file mode 100644
index f3fe0dab6ad..00000000000
--- a/source/gameengine/VideoTexture/SConscript
+++ /dev/null
@@ -1,32 +0,0 @@
-#!/usr/bin/python
-import sys
-
-Import ('env')
-
-sources = env.Glob('*.cpp')
-
-incs = '. #source/gameengine/Ketsji #source/gameengine/Expressions'
-incs += ' #source/gameengine/GameLogic #source/gameengine/SceneGraph #source/gameengine/Rasterizer'
-incs += ' #source/gameengine/Rasterizer/RAS_OpenGLRasterizer'
-incs += ' #source/gameengine/BlenderRoutines'
-incs += ' #source/blender/include #source/blender/blenlib #source/blender/blenkernel'
-incs += ' #source/blender/makesdna #source/blender/imbuf #source/blender/python'
-incs += ' #source/blender/gpu #source/kernel/gen_system #intern/string #intern/moto/include'
-incs += ' #intern/guardedalloc #intern/SoundSystem'
-incs += ' #extern/glew/include'
-
-cflags = []
-defs = ''
-if env['OURPLATFORM'] == 'win32-vc':
- cflags.append('/GR')
- cflags.append('/Ox')
-
-incs += ' ' + env['BF_PYTHON_INC']
-#incs += ' ' + env['BF_OPENGL_INC']
-
-if env['WITH_BF_FFMPEG']:
- defs += ' WITH_FFMPEG'
- incs += ' ' + env['BF_FFMPEG_INC']
- defs += ' __STDC_CONSTANT_MACROS'
-
-env.BlenderLib ( 'bf_videotex', sources, Split(incs), Split(defs), libtype=['game','player'], priority=[25, 72], compileflags = cflags )
diff --git a/source/gameengine/VideoTexture/Texture.cpp b/source/gameengine/VideoTexture/Texture.cpp
deleted file mode 100644
index 66c67023e38..00000000000
--- a/source/gameengine/VideoTexture/Texture.cpp
+++ /dev/null
@@ -1,476 +0,0 @@
-/* $Id$
------------------------------------------------------------------------------
-This source file is part of VideoTexture library
-
-Copyright (c) 2007 The Zdeno Ash Miklas
-
-This program is free software; you can redistribute it and/or modify it under
-the terms of the GNU Lesser General Public License as published by the Free Software
-Foundation; either version 2 of the License, or (at your option) any later
-version.
-
-This program is distributed in the hope that it will be useful, but WITHOUT
-ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
-
-You should have received a copy of the GNU Lesser General Public License along with
-this program; if not, write to the Free Software Foundation, Inc., 59 Temple
-Place - Suite 330, Boston, MA 02111-1307, USA, or go to
-http://www.gnu.org/copyleft/lesser.txt.
------------------------------------------------------------------------------
-*/
-
-// implementation
-
-#include <PyObjectPlus.h>
-#include <structmember.h>
-
-#include <KX_GameObject.h>
-#include <RAS_MeshObject.h>
-#include <DNA_mesh_types.h>
-#include <DNA_meshdata_types.h>
-#include <DNA_image_types.h>
-#include <IMB_imbuf_types.h>
-#include <BDR_drawmesh.h>
-#include <KX_PolygonMaterial.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 <BIF_gl.h>
-
-
-// macro for exception handling and logging
-#define CATCH_EXCP catch (Exception & exp) \
-{ exp.report(); }
-
-
-// Blender GameObject type
-BlendType<KX_GameObject> gameObjectType ("KX_GameObject");
-
-
-// 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)
- {
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
- gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA, size[0], size[1], GL_RGBA, GL_UNSIGNED_BYTE, texture);
- }
- 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 material ID
-short getMaterialID (PyObject * obj, 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
-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_imgTexture = NULL;
- self->m_matTexture = NULL;
- self->m_mipmap = false;
- self->m_scaledImg = NULL;
- self->m_scaledImgSize = 0;
- 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
-void Texture_dealloc (Texture * self)
-{
- // release renderer
- Py_XDECREF(self->m_source);
- // close texture
- Texture_close(self);
- // release scaled image buffer
- delete [] self->m_scaledImg;
- // release object
- self->ob_type->tp_free((PyObject*)self);
-}
-
-
-ExceptionID MaterialNotAvail;
-ExpDesc MaterialNotAvailDesc (MaterialNotAvail, "Texture material is not available");
-
-// Texture object initialization
-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 char *kwlist[] = {"gameObj", "materialID", "textureID", "textureObj", NULL};
-
- // get parameters
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|hhO!", 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);
- 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 if (mat->GetFlag() & RAS_BLENDERMAT)
- {
- // get blender material texture
- self->m_matTexture = static_cast<KX_BlenderMaterial*>(mat)->getTex(texID);
- self->m_useMatTexture = true;
- }
- else
- {
- // get texture pointer from polygon material
- MTFace * tface = static_cast<KX_PolygonMaterial*>(mat)->GetMTFace();
- self->m_imgTexture = (Image*)tface->tpage;
- 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 = self->m_orgTex;
- // drop actual texture
- if (self->m_actTex != 0)
- {
- glDeleteTextures(1, (GLuint *)&self->m_actTex);
- self->m_actTex = 0;
- }
- }
- Py_RETURN_NONE;
-}
-
-
-// refresh texture
-PyObject * Texture_refresh (Texture * self, PyObject * args)
-{
- // get parameter - refresh source
- PyObject * param;
- if (!PyArg_ParseTuple(args, "O", &param) || !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
- {
- self->m_orgTex = self->m_imgTexture->bindcode;
- self->m_imgTexture->bindcode = self->m_actTex;
- }
- }
-
- // get texture
- unsigned int * texture = self->m_source->m_image->getImage(self->m_actTex);
- // if texture is available
- if (texture != NULL)
- {
- // get texture size
- short * orgSize = self->m_source->m_image->getSize();
- // calc scaled sizes
- short size[] = {ImageBase::calcSize(orgSize[0]), ImageBase::calcSize(orgSize[1])};
- // scale texture if needed
- if (size[0] != orgSize[0] || size[1] != orgSize[1])
- {
- // if scaled image buffer is smaller than needed
- if (self->m_scaledImgSize < (unsigned int)(size[0] * size[1]))
- {
- // new size
- self->m_scaledImgSize = size[0] * size[1];
- // allocate scaling image
- delete [] self->m_scaledImg;
- self->m_scaledImg = new unsigned int[self->m_scaledImgSize];
- }
- // scale texture
- gluScaleImage(GL_RGBA, orgSize[0], orgSize[1], GL_UNSIGNED_BYTE, texture,
- size[0], size[1], GL_UNSIGNED_BYTE, self->m_scaledImg);
- // use scaled image instead original
- texture = self->m_scaledImg;
- }
- // 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 mipmap value
-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
-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
-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(value->ob_type))
- {
- // 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},
- {NULL}
-};
-
-
-// class Texture declaration
-PyTypeObject TextureType =
-{
- PyObject_HEAD_INIT(NULL)
- 0, /*ob_size*/
- "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*/
- 0, /*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 1bbef8f0f9e..00000000000
--- a/source/gameengine/VideoTexture/Texture.h
+++ /dev/null
@@ -1,92 +0,0 @@
-/* $Id$
------------------------------------------------------------------------------
-This source file is part of VideoTexture library
-
-Copyright (c) 2006 The Zdeno Ash Miklas
-
-This program is free software; you can redistribute it and/or modify it under
-the terms of the GNU Lesser General Public License as published by the Free Software
-Foundation; either version 2 of the License, or (at your option) any later
-version.
-
-This program is distributed in the hope that it will be useful, but WITHOUT
-ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
-
-You should have received a copy of the GNU Lesser General Public License along with
-this program; if not, write to the Free Software Foundation, Inc., 59 Temple
-Place - Suite 330, Boston, MA 02111-1307, USA, or go to
-http://www.gnu.org/copyleft/lesser.txt.
------------------------------------------------------------------------------
-*/
-
-#if !defined TEXTURE_H
-#define TEXTURE_H
-
-#include <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"
-
-
-// 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;
-
- // texture image for game materials
- Image * m_imgTexture;
- // texture for blender materials
- BL_Texture * m_matTexture;
-
- // use mipmapping
- bool m_mipmap;
-
- // scaled image buffer
- unsigned int * m_scaledImg;
- // scaled image buffer size
- unsigned int m_scaledImgSize;
- // 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, char * name);
-
-// Exceptions
-extern ExceptionID MaterialNotAvail;
-
-// object type
-extern BlendType<KX_GameObject> gameObjectType;
-
-#endif
diff --git a/source/gameengine/VideoTexture/VideoBase.cpp b/source/gameengine/VideoTexture/VideoBase.cpp
deleted file mode 100644
index 10117c3af9e..00000000000
--- a/source/gameengine/VideoTexture/VideoBase.cpp
+++ /dev/null
@@ -1,195 +0,0 @@
-/* $Id$
------------------------------------------------------------------------------
-This source file is part of VideoTexture library
-
-Copyright (c) 2007 The Zdeno Ash Miklas
-
-This program is free software; you can redistribute it and/or modify it under
-the terms of the GNU Lesser General Public License as published by the Free Software
-Foundation; either version 2 of the License, or (at your option) any later
-version.
-
-This program is distributed in the hope that it will be useful, but WITHOUT
-ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
-
-You should have received a copy of the GNU Lesser General Public License along with
-this program; if not, write to the Free Software Foundation, Inc., 59 Temple
-Place - Suite 330, Boston, MA 02111-1307, USA, or go to
-http://www.gnu.org/copyleft/lesser.txt.
------------------------------------------------------------------------------
-*/
-
-#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;
- }
- }
- }
-}
-
-
-// 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; }
-
-// stop video
-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)
-{
- 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_Length(value) != 2
- || !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 longs");
- 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 || !PyInt_Check(value))
- {
- PyErr_SetString(PyExc_TypeError, "The value must be an int");
- return -1;
- }
- // set repeat
- getVideo(self)->setRepeat(int(PyInt_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 15ecb7a78f4..00000000000
--- a/source/gameengine/VideoTexture/VideoBase.h
+++ /dev/null
@@ -1,185 +0,0 @@
-/* $Id$
------------------------------------------------------------------------------
-This source file is part of VideoTexture library
-
-Copyright (c) 2007 The Zdeno Ash Miklas
-
-This program is free software; you can redistribute it and/or modify it under
-the terms of the GNU Lesser General Public License as published by the Free Software
-Foundation; either version 2 of the License, or (at your option) any later
-version.
-
-This program is distributed in the hope that it will be useful, but WITHOUT
-ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
-
-You should have received a copy of the GNU Lesser General Public License along with
-this program; if not, write to the Free Software Foundation, Inc., 59 Temple
-Place - Suite 330, Boston, MA 02111-1307, USA, or go to
-http://www.gnu.org/copyleft/lesser.txt.
------------------------------------------------------------------------------
-*/
-
-#if !defined VIDEOBASE_H
-#define VIDEOBASE_H
-
-
-#include <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;
- }
- /// stop/pause 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.0 ? 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_stop (PyImage * self);
-PyObject * Video_refresh (PyImage * self);
-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);
-
-
-#endif
-
diff --git a/source/gameengine/VideoTexture/VideoFFmpeg.cpp b/source/gameengine/VideoTexture/VideoFFmpeg.cpp
deleted file mode 100644
index 02798c7e596..00000000000
--- a/source/gameengine/VideoTexture/VideoFFmpeg.cpp
+++ /dev/null
@@ -1,927 +0,0 @@
-/* $Id$
------------------------------------------------------------------------------
-This source file is part of VideoTexture library
-
-Copyright (c) 2007 The Zdeno Ash Miklas
-
-This program is free software; you can redistribute it and/or modify it under
-the terms of the GNU Lesser General Public License as published by the Free Software
-Foundation; either version 2 of the License, or (at your option) any later
-version.
-
-This program is distributed in the hope that it will be useful, but WITHOUT
-ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
-
-You should have received a copy of the GNU Lesser General Public License along with
-this program; if not, write to the Free Software Foundation, Inc., 59 Temple
-Place - Suite 330, Boston, MA 02111-1307, USA, or go to
-http://www.gnu.org/copyleft/lesser.txt.
------------------------------------------------------------------------------
-*/
-
-#ifdef WITH_FFMPEG
-
-// INT64_C fix for some linux machines (C99ism)
-#define __STDC_CONSTANT_MACROS
-#include <stdint.h>
-
-
-#include "MEM_guardedalloc.h"
-#include "PIL_time.h"
-
-#include <string>
-
-#include "Exception.h"
-#include "VideoFFmpeg.h"
-
-
-// default framerate
-const double defFrameRate = 25.0;
-// time scale constant
-const long timeScale = 1000;
-
-// macro for exception handling and logging
-#define CATCH_EXCP catch (Exception & exp) \
-{ exp.report(); m_status = SourceError; }
-
-extern "C" void do_init_ffmpeg();
-
-// 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_curPosition(-1), m_startTime(0),
-m_captWidth(0), m_captHeight(0), m_captRate(0.f), m_isImage(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;
-}
-
-// destructor
-VideoFFmpeg::~VideoFFmpeg ()
-{
-}
-
-
-// release components
-bool VideoFFmpeg::release()
-{
- // release
- if (m_codecCtx)
- {
- avcodec_close(m_codecCtx);
- m_codecCtx = NULL;
- }
- if (m_formatCtx)
- {
- av_close_input_file(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;
- return true;
-}
-
-
-// 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, AVFormatParameters *formatParams)
-{
- AVFormatContext *formatCtx;
- int i, videoStream;
- AVCodec *codec;
- AVCodecContext *codecCtx;
-
- if(av_open_input_file(&formatCtx, filename, inputFormat, 0, formatParams)!=0)
- return -1;
-
- if(av_find_stream_info(formatCtx)<0)
- {
- av_close_input_file(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==CODEC_TYPE_VIDEO))
- {
- videoStream=i;
- break;
- }
- }
-
- if(videoStream==-1)
- {
- av_close_input_file(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)
- {
- av_close_input_file(formatCtx);
- return -1;
- }
- codecCtx->workaround_bugs = 1;
- if(avcodec_open(codecCtx, codec)<0)
- {
- av_close_input_file(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(formatCtx->streams[videoStream]->r_frame_rate);
-#endif
- if (m_baseFrameRate <= 0.0)
- m_baseFrameRate = defFrameRate;
-
- m_codec = codec;
- m_codecCtx = codecCtx;
- m_formatCtx = formatCtx;
- m_videoStream = videoStream;
- m_frame = avcodec_alloc_frame();
- m_frameDeinterlaced = avcodec_alloc_frame();
- m_frameRGB = avcodec_alloc_frame();
-
- // 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 == PIX_FMT_RGB32 ||
- m_codecCtx->pix_fmt == PIX_FMT_BGR32 ||
- m_codecCtx->pix_fmt == PIX_FMT_RGB32_1 ||
- m_codecCtx->pix_fmt == PIX_FMT_BGR32_1)
- {
- // allocate buffer to store final decoded frame
- m_format = RGBA32;
- avpicture_fill((AVPicture*)m_frameRGB,
- (uint8_t*)MEM_callocN(avpicture_get_size(
- PIX_FMT_RGBA,
- m_codecCtx->width, m_codecCtx->height),
- "ffmpeg rgba"),
- PIX_FMT_RGBA, m_codecCtx->width, m_codecCtx->height);
- // allocate sws context
- m_imgConvertCtx = sws_getContext(
- m_codecCtx->width,
- m_codecCtx->height,
- m_codecCtx->pix_fmt,
- m_codecCtx->width,
- m_codecCtx->height,
- PIX_FMT_RGBA,
- SWS_FAST_BILINEAR,
- NULL, NULL, NULL);
- } else
- {
- // allocate buffer to store final decoded frame
- m_format = RGB24;
- avpicture_fill((AVPicture*)m_frameRGB,
- (uint8_t*)MEM_callocN(avpicture_get_size(
- PIX_FMT_RGB24,
- m_codecCtx->width, m_codecCtx->height),
- "ffmpeg rgb"),
- PIX_FMT_RGB24, m_codecCtx->width, m_codecCtx->height);
- // allocate sws context
- m_imgConvertCtx = sws_getContext(
- m_codecCtx->width,
- m_codecCtx->height,
- m_codecCtx->pix_fmt,
- m_codecCtx->width,
- m_codecCtx->height,
- PIX_FMT_RGB24,
- SWS_FAST_BILINEAR,
- NULL, NULL, NULL);
- }
- if (!m_imgConvertCtx) {
- avcodec_close(m_codecCtx);
- av_close_input_file(m_formatCtx);
- av_free(m_frame);
- MEM_freeN(m_frameDeinterlaced->data[0]);
- av_free(m_frameDeinterlaced);
- MEM_freeN(m_frameRGB->data[0]);
- av_free(m_frameRGB);
- return -1;
- }
- return 0;
-}
-
-// open video file
-void VideoFFmpeg::openFile (char * filename)
-{
- do_init_ffmpeg();
-
- 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 (
-#ifdef FFMPEG_PB_IS_POINTER
- m_formatCtx->pb && m_formatCtx->pb->is_streamed
-#else
- m_formatCtx->pb.is_streamed
-#endif
- )
- {
- // the file is in fact a streaming source, prevent seeking
- m_isFile = false;
- // 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();
- }
-
-}
-
-
-// open video capture device
-void VideoFFmpeg::openCam (char * file, short camIdx)
-{
- // open camera source
- AVInputFormat *inputFormat;
- AVFormatParameters formatParams;
- AVRational frameRate;
- char *p, filename[28], rateStr[20];
-
- do_init_ffmpeg();
-
- memset(&formatParams, 0, sizeof(formatParams));
-#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 explicitely
- // instead of device type. Examples of valid filename:
- // /dev/v4l/video0:pal
- // /dev/ieee1394/1:ntsc
- // dv1394:secam
- // v4l:pal
- 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
- {
- inputFormat = av_find_input_format("video4linux");
- 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)
- formatParams.standard = p+1;
-#endif
- //frame rate
- if (m_captRate <= 0.f)
- m_captRate = defFrameRate;
- sprintf(rateStr, "%f", m_captRate);
- av_parse_video_frame_rate(&frameRate, rateStr);
- // populate format parameters
- // need to specify the time base = inverse of rate
- formatParams.time_base.num = frameRate.den;
- formatParams.time_base.den = frameRate.num;
- formatParams.width = m_captWidth;
- formatParams.height = m_captHeight;
-
- 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);
-}
-
-// play video
-bool VideoFFmpeg::play (void)
-{
- try
- {
- // if object is able to play
- if (VideoBase::play())
- {
- // set video position
- setPositions();
- // return success
- return true;
- }
- }
- CATCH_EXCP;
- return false;
-}
-
-
-// stop video
-bool VideoFFmpeg::stop (void)
-{
- try
- {
- if (VideoBase::stop())
- {
- return true;
- }
- }
- CATCH_EXCP;
- return false;
-}
-
-
-// set video range
-void VideoFFmpeg::setRange (double start, double stop)
-{
- try
- {
- // set range
- VideoBase::setRange(start, stop);
- // set range for video
- setPositions();
- }
- CATCH_EXCP;
-}
-
-// set framerate
-void VideoFFmpeg::setFrameRate (float rate)
-{
- VideoBase::setFrameRate(rate);
-}
-
-
-// image calculation
-void VideoFFmpeg::calcImage (unsigned int texId)
-{
- loadFrame();
-}
-
-
-// load frame from video
-void VideoFFmpeg::loadFrame (void)
-{
- // get actual time
- double actTime = PIL_check_seconds_timer() - m_startTime;
- // if video has ended
- if (m_isFile && actTime * m_frameRate >= m_range[1])
- {
- // 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;
- }
- // if video is playing
- if (m_status == SourcePlaying)
- {
- // actual frame
- long actFrame = m_isFile ? long(actTime * actFrameRate()) : m_lastFrame + 1;
- // if actual frame differs from last frame
- if (actFrame != m_lastFrame)
- {
- // get image
- if(grabFrame(actFrame))
- {
- AVFrame* frame = getFrame();
- // 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]));
- // 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();
- }
- }
- }
- }
-}
-
-
-// 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_isFile && !m_eof && m_lastFrame >= 0 && m_lastFrame < m_range[1] * actFrameRate())
- // continue from actual position
- m_startTime -= double(m_lastFrame) / actFrameRate();
- else
- m_startTime -= m_range[0];
-}
-
-// position pointer in file, position in second
-bool VideoFFmpeg::grabFrame(long position)
-{
- AVPacket packet;
- int frameFinished;
- int posFound = 1;
- bool frameLoaded = false;
- long long targetTs = 0;
-
- // 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_video(
- m_codecCtx,
- m_frame, &frameFinished,
- packet.data, packet.size);
- if (frameFinished)
- m_curPosition++;
- }
- 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)
- {
- double timeBase = av_q2d(m_formatCtx->streams[m_videoStream]->time_base);
- long long pos = (long long)
- ((long long) (position - m_preseek) * AV_TIME_BASE / m_baseFrameRate);
- long long startTs = m_formatCtx->streams[m_videoStream]->start_time;
-
- if (pos < 0)
- pos = 0;
-
- if (startTs != AV_NOPTS_VALUE)
- pos += (long long)(startTs * AV_TIME_BASE * timeBase);
-
- if (position <= m_curPosition || !m_eof)
- {
- // no need to seek past the end of the file
- if (av_seek_frame(m_formatCtx, -1, 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 = (long long)(((double) position) / m_baseFrameRate / timeBase);
- if (startTs != AV_NOPTS_VALUE)
- targetTs += startTs;
-
- posFound = 0;
- avcodec_flush_buffers(m_codecCtx);
- }
-
- while(av_read_frame(m_formatCtx, &packet)>=0)
- {
- if(packet.stream_index == m_videoStream)
- {
- avcodec_decode_video(m_codecCtx,
- m_frame, &frameFinished,
- packet.data, packet.size);
-
- if (frameFinished && !posFound)
- {
- if (packet.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 = !frameLoaded;
- if (frameLoaded)
- m_curPosition = position;
- return frameLoaded;
-}
-
-
-// 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 char *kwlist[] = {"file", "capture", "rate", "width", "height", NULL};
-
- // get parameters
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|hfhh", 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;
-}
-
-PyObject * VideoFFmpeg_getPreseek (PyImage *self, void * closure)
-{
- return Py_BuildValue("h", getFFmpeg(self)->getPreseek());
-}
-
-// set range
-int VideoFFmpeg_setPreseek (PyImage * self, PyObject * value, void * closure)
-{
- // check validity of parameter
- if (value == NULL || !PyInt_Check(value))
- {
- PyErr_SetString(PyExc_TypeError, "The value must be an integer");
- return -1;
- }
- // set preseek
- getFFmpeg(self)->setPreseek(PyInt_AsLong(value));
- // success
- return 0;
-}
-
-// get deinterlace
-PyObject * VideoFFmpeg_getDeinterlace (PyImage * self, void * closure)
-{
- if (getFFmpeg(self)->getDeinterlace())
- Py_RETURN_TRUE;
- else
- Py_RETURN_FALSE;
-}
-
-// set flip
-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 video"},
- {"stop", (PyCFunction)Video_stop, METH_NOARGS, "Stop (pause) video"},
- {"refresh", (PyCFunction)Video_refresh, METH_NOARGS, "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*)"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 neighbour)", 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 =
-{
- PyObject_HEAD_INIT(NULL)
- 0, /*ob_size*/
- "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*/
- 0, /*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", &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;
-}
-
-PyObject * Image_reload (PyImage * self, PyObject *args)
-{
- char * newname = NULL;
-
- if (self->m_image != NULL && PyArg_ParseTuple(args, "|s", &newname))
- {
- 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_NOARGS, "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*)"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 neighbour)", 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 =
-{
- PyObject_HEAD_INIT(NULL)
- 0, /*ob_size*/
- "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*/
- 0, /*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 e60f1727aab..00000000000
--- a/source/gameengine/VideoTexture/VideoFFmpeg.h
+++ /dev/null
@@ -1,173 +0,0 @@
-/* $Id$
------------------------------------------------------------------------------
-This source file is part of VideoTexture library
-
-Copyright (c) 2007 The Zdeno Ash Miklas
-
-This program is free software; you can redistribute it and/or modify it under
-the terms of the GNU Lesser General Public License as published by the Free Software
-Foundation; either version 2 of the License, or (at your option) any later
-version.
-
-This program is distributed in the hope that it will be useful, but WITHOUT
-ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
-
-You should have received a copy of the GNU Lesser General Public License along with
-this program; if not, write to the Free Software Foundation, Inc., 59 Temple
-Place - Suite 330, Boston, MA 02111-1307, USA, or go to
-http://www.gnu.org/copyleft/lesser.txt.
------------------------------------------------------------------------------
-*/
-#if !defined VIDEOFFMPEG_H
-#define VIDEOFFMPEG_H
-
-#ifdef WITH_FFMPEG
-extern "C" {
-#include <ffmpeg/avformat.h>
-#include <ffmpeg/avcodec.h>
-#include <ffmpeg/rational.h>
-#include <ffmpeg/swscale.h>
-}
-
-#if LIBAVFORMAT_VERSION_INT < (49 << 16)
-#define FFMPEG_OLD_FRAME_RATE 1
-#else
-#define FFMPEG_CODEC_IS_POINTER 1
-#endif
-
-#if LIBAVFORMAT_VERSION_INT >= (52 << 16)
-#define FFMPEG_PB_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"
-
-
-// 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);
-
- /// play video
- virtual bool play (void);
- /// stop/pause 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;
-
- /// 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;
-
- /// keep last image name
- STR_String m_imageName;
-
- /// image calculation
- virtual void calcImage (unsigned int texId);
-
- /// load frame from video
- void loadFrame (void);
-
- /// 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, AVFormatParameters *formatParams);
-
- /// check if a frame is available and load it in pFrame, return true if a frame could be retrieved
- bool grabFrame(long frame);
-
- /// return the frame in RGB24 format, the image data is found in AVFrame.data[0]
- AVFrame* getFrame(void) { return m_frameRGB; }
-};
-
-inline VideoFFmpeg * getFFmpeg (PyImage * self)
-{
- return static_cast<VideoFFmpeg*>(self->m_image);
-}
-
-#endif //WITH_FFMPEG
-
-#endif
diff --git a/source/gameengine/VideoTexture/blendVideoTex.cpp b/source/gameengine/VideoTexture/blendVideoTex.cpp
deleted file mode 100644
index ec066811a52..00000000000
--- a/source/gameengine/VideoTexture/blendVideoTex.cpp
+++ /dev/null
@@ -1,196 +0,0 @@
-/* $Id$
------------------------------------------------------------------------------
-This source file is part of VideoTexure library
-
-Copyright (c) 2006 The Zdeno Ash Miklas
-
-This program is free software; you can redistribute it and/or modify it under
-the terms of the GNU Lesser General Public License as published by the Free Software
-Foundation; either version 2 of the License, or (at your option) any later
-version.
-
-This program is distributed in the hope that it will be useful, but WITHOUT
-ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
-
-You should have received a copy of the GNU Lesser General Public License along with
-this program; if not, write to the Free Software Foundation, Inc., 59 Temple
-Place - Suite 330, Boston, MA 02111-1307, USA, or go to
-http://www.gnu.org/copyleft/lesser.txt.
------------------------------------------------------------------------------
-*/
-
-#include <PyObjectPlus.h>
-
-#include <RAS_GLExtensionManager.h>
-
-#include <RAS_IPolygonMaterial.h>
-
-//Old API
-//#include "TexPlayer.h"
-//#include "TexImage.h"
-//#include "TexFrameBuff.h"
-
-//#include "TexPlayerGL.h"
-
-#include "ImageBase.h"
-#include "FilterBase.h"
-#include "Texture.h"
-
-#include "Exception.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", &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, "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 Py_BuildValue("s", Exception::m_lastError.c_str());
-}
-
-// set log file
-static PyObject * setLogFile (PyObject *self, PyObject *args)
-{
- // get parameters
- if (!PyArg_ParseTuple(args, "s", &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;
- if (!PyArg_ParseTuple(args, "O", &pyImg) || !pyImageTypes.in(pyImg->ob_type))
- {
- // if object is incorect, report error
- PyErr_SetString(PyExc_TypeError, "The value must be a image source object");
- return NULL;
- }
- // get image structure
- PyImage * img = reinterpret_cast<PyImage*>(pyImg);
- // create array object
- unsigned int * imgBuff = img->m_image->getImage();
- // if image is available, convert it to array
- if (imgBuff != NULL)
- // Nasty problem here: the image buffer is an array of integers
- // in the processor endian format. The user must take care of that in the script.
- // Need to find an elegant solution to this problem
- return Py_BuildValue("s#", imgBuff, img->m_image->getBuffSize());
- // otherwise return None
- Py_RETURN_NONE;
-}
-
-
-// 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 array from image source"},
- {NULL} /* Sentinel */
-};
-
-#if WITH_FFMPEG
-extern PyTypeObject VideoFFmpegType;
-extern PyTypeObject ImageFFmpegType;
-#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;
-extern PyTypeObject ImageRenderType;
-extern PyTypeObject ImageMirrorType;
-extern PyTypeObject ImageViewportType;
-extern PyTypeObject ImageViewportType;
-
-
-static void registerAllTypes(void)
-{
-#if WITH_FFMPEG
- pyImageTypes.add(&VideoFFmpegType, "VideoFFmpeg");
- pyImageTypes.add(&ImageFFmpegType, "ImageFFmpeg");
-#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");
-}
-
-PyObject* initVideoTexture(void)
-{
- // 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;
-
- PyObject * m = Py_InitModule4("VideoTexture", moduleMethods,
- "Module that allows to play video files on textures in GameBlender.",
- (PyObject*)NULL,PYTHON_API_VERSION);
- if (m == NULL)
- return NULL;
-
- // initialize classes
- pyImageTypes.reg(m);
- pyFilterTypes.reg(m);
-
- Py_INCREF(&TextureType);
- PyModule_AddObject(m, (char*)"Texture", (PyObject*)&TextureType);
-
- // init last error description
- Exception::m_lastError[0] = '\0';
- return m;
-}
-
-// registration to Image types, put here because of silly linker bug