Instead use __contains__, eg.
if key in gameOb: ...
Mathutils returns from PyMath.cpp were incorrectly using wrapped Mathutils types. Wrapped types should only be used with a callback now.
When the mesh field is left blank and Physics option is enabled, it reinstances the physics mesh from the existing mesh.
like calling gameOb.reinstancePhysicsMesh() from python.
Add support back for reinstancePhysics mesh, a frequently requested feature in the BGE forums.
from what I can tell Sumo supported this but bullet never did.
Currently only accessible via python at the moment.
- rigid body, dynamic, static types work.
- instanced physics meshes are modified too.
- compound shapes are not supported.
Physics mesh can be re-instanced from...
* shape keys & armature deformations
* subsurf (any other modifiers too)
* RAS_TexVert's (can be modified from python)
Moved the reinstancePhysicsMesh functions from RAS_MeshObject into KX_GameObject since the physics data is stored here.
video and blend file demo.
http://www.graphicall.org/ftp/ideasman42/reinstance.ogvhttp://www.graphicall.org/ftp/ideasman42/reinstance_demo.blend
Remove the last of the odd C++/python wrapper code from http://www.python.org/doc/PyCPP.html (~1998)
* Use python subclasses rather then having fake subclassing through get/set attributes calling parent types.
* PyObject getset arrays are created while initializing the types, converted from our own attribute arrays. This way python deals with subclasses and we dont have to define getattro or setattro functions for each type.
* GameObjects and Scenes no longer have attribute access to properties. only dictionary style access - ob['prop']
* remove each class's get/set/dir functions.
* remove isA() methods, can use PyObject_TypeCheck() in C and issubclass() in python.
* remove Parents[] array for each C++ class, was only used for isA() and wasnt correct in quite a few cases.
* remove PyTypeObject that was being passed as the last argument to each class (the parent classes too).
TODO -
* Light and VertexProxy need to be converted to using attributes.
* memory for getset arrays is never freed, not that bad since its will only allocates once.
Any 3x3 or 4x4 rna matrix will automatically be returned as a Mathutils matrix.
This makes useful stuff like multiplying a vector location by an object matrix possible.
ob = bpy.data.scenes[0].objects[0]
print (ob.data.verts[0].co * ob.matrix)
Also added mathutils matrix types to the BGE GameObject.localOrientation, worldOrientation
* MT_Matrix3x3 added getValue3x3 and setValue3x3, assumed a 4x3 float array.
* KX_GameObject.cpp convenience functions NodeSetGlobalOrientation, NodeGetLocalOrientation, NodeGetLocalScaling, NodeGetLocalPosition.
* 2.5 python api now initializes modules BGL, Mathutils and Geometry
* modules py3 PyModuleDef's use PyModuleDef_HEAD_INIT, rather then {}, was making msvc fail to build.
* added macros for Vector_ReadCallback, Vector_WriteCallback etc. to check if the callback pointer is set before calling the function.
in short, vectors can work as if they are thin wrapped but not crash blender if the original data is removed.
* RNA vector's return Mathutils vector types.
* BGE vectors for GameObject's localPosition, worldPosition, localPosition, localScale, worldScale, localInertia.
* Comment USE_MATHUTILS define to disable returning vectors.
Example...
* 2.49... *
loc = gameOb.worldPosition
loc[1] = 0
gameOb.worldPosition = loc
* With vectors... *
gameOb.worldPosition[1] = 0
* But this wont crash... *
loc = gameOb.worldPosition
gameOb.endObject()
loc[1] = 0 # will raise an error that the objects removed.
This breaks games which assume return values are lists.
Will add this to eulers, matrix and quaternion types later.
- Deprecation warnings for using attribute access
- Added dictionary functions to KX_GameObject and ListValue
ob.get(key, default=None)
ob.has_key(key)
ob.has_key is important since there was no way to do something like hasattr(ob, "attr") which can be replaced by ob.has_key("attr") - (both still work of course).
ob.get is just useful in many cases where you want a property if it exists but can fallback to a default.
- CListValue::FindValue was adding a reference but the ~3 places it was used were releasing the reference. added a FindValue that accepts a const char* type to avoid converting python strings to STR_String.
Compound shape control
======================
1) GUI control
It is now possible to control which child shape is added to
a parent compound shape in the Physics buttons. The "Compound"
shape button becomes "Add to parent" on child objects and
determines whether the child shape is to be added to the top
parent compound shape when the game is stated.
Notes: * "Compound" is only available to top parent objects
(objects without parent).
* Nesting of compound shape is not possible: a child
object with "Add to parent" button set will be added
to the top parent compound shape, regardless of its
position in the parent-child hierarchy and even if its
immediate parent doesn't have the "Add to parent" button set.
2) runtime control
It is now possible to control the compound shape at runtime:
The SetParent actuator has a new "Compound" button that indicates
whether the object shape should be added to the compound shape
of the parent object, provided the parent has a compound shape
of course. If not, the object retain it's individual state
while parented.
Similarly, the KX_GameObject.setParent() python function has
a new compound parameter.
Notes: * When an object is dynamically added to a compound
shape, it looses temporarily all its physics capability
to the benefit of the parent: it cannot register collisions
and the characteristics of its shape are lost (ghost, sensor,
dynamic, etc.).
* Nested compound shape is not supported: if the object
being parented is already a compound shape, it is not
added to the compound parent (as if the Compound option
was not set in the actuator or the setParent function).
* To ensure compatibility with old blend files, the Blender
subversion is changed to 2.48.5 and the old blend files
are automatically converted to match the old behavior:
all children of a Compound object will have the "Add to
parent" button set automatically.
Child ghost control
===================
It is now possible to control if an object should becomes ghost
or solid when parented. This is only applicable if the object
is not added to the parent compound shape (see above).
A new "Ghost" button is available on the SetParent actuator to
that effect. Similarly the KX_GameObject.setParent() python function
has a new compound parameter.
Notes: * This option is not applicable to sensor objects: they stay
ghost all the time.
* Make sure the child object does not enter in collision with
the parent shape when the Ghost option if off and the parent is
dynamic: the collision creates a reaction force but the parent
cannot escape the child, so the force builds up and produces
eratic movements.
* The collision capability of an ordinary object (dynamic or static)
is limited when it is parented: it becomes automatically static
and can only detect dynamic and sensor objects.
* A sensor object retain its full collision capability when parented:
it can detect static and dynamic object.
Python control
==============
KX_GameObject.setParent(parent,compound,ghost):
Sets this object's parent.
Control the shape status with the optional compound and ghost parameters:
compound=1: the object shape should be added to the parent compound shape (default)
compound=0: the object should keep its individual shape.
In that case you can control if it should be ghost or not:
ghost=1 if the object should be made ghost while parented (default)
ghost=0 if the object should be solid while parented
Note: if the object type is sensor, it stays ghost regardless of ghost parameter
parent: KX_GameObject reference or string (object name w/o OB prefix)
- corrections to docs
- disallow calling controller.activate(actuator) when the controller is not active. (Raise a SystemError)
- Added 2 new attributes, CValue.name - deprecates CValue.getName(), KX_GameObject.children deprecated KX_GameObject.getChildren(), (same for getChildrenRecursive()).
A new type of "Sensor" physics object is available in the GE for advanced
collision management. It's called Sensor for its similarities with the
physics objects that underlie the Near and Radar sensors.
Like the Near and Radar object it is:
- static and ghost
- invisible by default
- always active to ensure correct collision detection
- capable of detecting both static and dynamic objects
- ignoring collision with their parent
- capable of broadphase filtering based on:
* Actor option: the collisioning object must have the Actor flag set to be detected
* property/material: as specified in the collision sensors attached to it
Broadphase filtering is important for performance reason: the collision points
will be computed only for the objects that pass the broahphase filter.
- automatically removed from the simulation when no collision sensor is active on it
Unlike the Near and Radar object it can:
- take any shape, including triangle mesh
- be made visible for debugging (just use the Visible actuator)
- have multiple collision sensors using it
Other than that, the sensor objects are ordinary objects. You can move them
freely or parent them. When parented to a dynamic object, they can provide
advanced collision control to this object.
The type of collision capability depends on the shape:
- box, sphere, cylinder, cone, convex hull provide volume detection.
- triangle mesh provides surface detection but you can give some volume
to the suface by increasing the margin in the Advanced Settings panel.
The margin applies on both sides of the surface.
Performance tip:
- Sensor objects perform better than Near and Radar: they do less synchronizations
because of the Scenegraph optimizations and they can have multiple collision sensors
on them (with different property filtering for example).
- Always prefer simple shape (box, sphere) to complex shape whenever possible.
- Always use broadphase filtering (avoid collision sensor with empty propery/material)
- Use collision sensor only when you need them. When no collision sensor is active
on the sensor object, it is removed from the simulation and consume no CPU.
Known limitations:
- When running Blender in debug mode, you will see one warning line of the console:
"warning btCollisionDispatcher::needsCollision: static-static collision!"
In release mode this message is not printed.
- Collision margin has no effect on sphere, cone and cylinder shape.
Other performance improvements:
- Remove unnecessary interpolation for Near and Radar objects and by extension
sensor objects.
- Use direct matrix copy instead of quaternion to synchronize orientation.
Other bug fix:
- Fix Near/Radar position error on newly activated objects. This was causing
several detection problems in YoFrankie
- Fix margin not passed correctly to gImpact shape.
- Disable force/velocity actions on static objects
This commit extends the technique of dynamic linked list to the logic
system to eliminate as much as possible temporaries, map lookup or
full scan. The logic engine is now free of memory allocation, which is
an important stability factor.
The overhead of the logic system is reduced by a factor between 3 and 6
depending on the logic setup. This is the speed-up you can expect on
a logic setup using simple bricks. Heavy bricks like python controllers
and ray sensors will still take about the same time to execute so the
speed up will be less important.
The core of the logic engine has been much reworked but the functionality
is still the same except for one thing: the priority system on the
execution of controllers. The exact same remark applies to actuators but
I'll explain for controllers only:
Previously, it was possible, with the "executePriority" attribute to set
a controller to run before any other controllers in the game. Other than
that, the sequential execution of controllers, as defined in Blender was
guaranteed by default.
With the new system, the sequential execution of controllers is still
guaranteed but only within the controllers of one object. the user can
no longer set a controller to run before any other controllers in the
game. The "executePriority" attribute controls the execution of controllers
within one object. The priority is a small number starting from 0 for the
first controller and incrementing for each controller.
If this missing feature is a must, a special method can be implemented
to set a controller to run before all other controllers.
Other improvements:
- Systematic use of reference in parameter passing to avoid unnecessary data copy
- Use pre increment in iterator instead of post increment to avoid temporary allocation
- Use const char* instead of STR_String whenever possible to avoid temporary allocation
- Fix reference counting bugs (memory leak)
- Fix a crash in certain cases of state switching and object deletion
- Minor speed up in property sensor
- Removal of objects during the game is a lot faster
not fixed but the problem is now less bad when projection painting, bilinear interpolation was rounding down.
- added gameOb.attrDict to get the internal gameObject dict.
- mesh.getVertex wasnt setting an exception.
This commit extend the technique of dynamic linked list to the mesh
slots so as to eliminate dumb scan or map lookup. It provides massive
performance improvement in the culling and in the rasterizer when
the majority of objects are static.
Other improvements:
- Compute the opengl matrix only for objects that are visible.
- Simplify hash function for GEN_HasedPtr
- Scan light list instead of general object list to render shadows
- Remove redundant opengl calls to set specularity, shinyness and diffuse
between each mesh slots.
- Cache GPU material to avoid frequent call to GPU_material_from_blender
- Only set once the fixed elements of mesh slot
- Use more inline function
The following table shows the performance increase between 2.48, 1st round
and this round of improvement. The test was done with a scene containing
40000 objects, of which 1000 are in the view frustrum approximately. The
object are simple textured cube to make sure the GPU is not the bottleneck.
As some of the rasterizer processing time has moved under culling, I present
the sum of scenegraph(includes culling)+rasterizer time
Scenegraph+rasterizer(ms) 2.48 1st round 3rd round
All objects static, 323.0 86.0 7.2
all visible, 1000 in
the view frustrum
All objects static, 219.0 49.7 N/A(*)
all invisible.
All objects moving, 323.0 105.6 34.7
all visible, 1000 in
the view frustrum
Scene destruction 40min 40min 4s
(*) : this time is not representative because the frame rate was at 60fps.
In that case, the GPU holds down the GE by frame sync. By design, the
overhead of the rasterizer is 0 when the the objects are invisible.
This table shows a global speed up between 9x and 45x compared to 2.48a
for scenegraph, culling and rasterizer overhead. The speed up goes much
higher when objects are invisible.
An additional 2-4x speed up is possible in the scenegraph by upgrading
the Moto library to use Eigen2 BLAS library instead of C++ classes but
the scenegraph is already so fast that it is not a priority right now.
Next speed up in logic: many things to do there...
Own bug, conversion function to get an orientation from python - PyOrientationTo() ignored user input completely :| (breaking the orientation attribute)
Also made KX_GameObject worldOrientation writable and minor doc fixes.
Some functions used
ProcessReplica(replica);
others
replica->ProcessReplica()
Use the second method everywhere so the PyObjectPlus's ProcessReplica() can be called from its subclasses.
Note that PyObjectPlus's ProcessReplica isnt used yet.
Separate getting a normal attribute and getting __dict__, was having to do too a check for __dict__ on each class (multiple times per getattro call from python) when its not used that often.
- initialize pythons sys.argv in the blenderplayer
- ignore all arguments after a single " - " in the blenderplayer (like in blender), so args can be passed to the game.
- add a utility function PyOrientationTo() - to take a Py euler, quat or 3x3 matrix and convert into a C++ MT_Matrix3x3.
- add utility function ConvertPythonToMesh to get a RAS_MeshObject from a KX_MeshProxy or a name.
- Added error prefix arguments to ConvertPythonToGameObject, ConvertPythonToMesh and PyOrientationTo so the error messages can include what function they came from.
- deprecated brick.getOwner() for the "owner" attribute.
This changes how the BGE classes and Python work together, which hasnt changed since blender went opensource.
The main difference is PyObjectPlus - the base class for most game engine classes, no longer inherit from PyObject, and cannot be cast to a PyObject.
This has the advantage that the BGE does not have to keep 2 reference counts valid for C++ and Python.
Previously C++ classes would never be freed while python held a reference, however this reference could be problematic eg: a GameObject that isnt in a scene anymore should not be used by python, doing so could even crash blender in some cases.
Instead PyObjectPlus has a member "PyObject *m_proxy" which is lazily initialized when python needs it. m_proxy reference counts are managed by python, though it should never be freed while the C++ class exists since it holds a reference to avoid making and freeing it all the time.
When the C++ class is free'd it sets the m_proxy reference to NULL, If python accesses this variable it will raise a RuntimeError, (check the isValid attribute to see if its valid without raising an error).
- This replaces the m_zombie bool and IsZombie() tests added recently.
In python return values that used to be..
return value->AddRef();
Are now
return value->GetProxy();
or...
return value->NewProxy(true); // true means python owns this C++ value which will be deleted when the PyObject is freed
Other small changes...
- KX_Camera and KX_Light didnt have get/setitem access in their PyType definition.
- CList.from_id() error checking for a long was checking for -1 against an unsigned value (own fault)
- CValue::SpecialRelease was incrementing an int for no reason.
- renamed m_attrlist to m_attr_dict since its a PyDict type.
- removed custom getattro/setattro functions for KX_Scene and KX_GameObject, use py_base_getattro, py_base_setattro for all subclasses of PyObjectPlus.
- lowercase windows.h in VideoBase.cpp for cross compiling.
Common cases of this are when python references an object from the AddObject actuator that has ended, or a scene has been loaded and the old objects freed.
This means some scripts will raise errors now in certain cases but better give the error early rather then failing silently with strange hard to track down behavior & crashes.
Added "isValid" attribute for checking objects are in a scene.
At the moment it uses the SceneGraph Node to check of the objects valid but it might be better to do this in a more generic way so scenes, meshes etc also have this check.
Clamp objects min/max velocity.
Accessed with bullet physics from the advanced button with dynamic and rigid body objects.
- useful for preventing unstable physics in cases where objects move too fast.
- can add linear velocity with the motion actuator to give smooth motion transitions, without moving too fast.
- minimum velocity means objects don't stop moving.
- python scripts can adjust these values speedup or throttle velocity in the existing direction.
Also made copy properties from an object with no properties work (in case you want to clear all props)
Added occlusion culling capability in the BGE.
More info: http://wiki.blender.org/index.php/Dev:Ref/Release_Notes/2.49/Game_Engine#BGE_Scenegraph_improvement
MSVC, scons, cmake, Makefile updated.
Other minor performance improvements:
- The rasterizer was computing the openGL model matrix of the objects too many times
- DBVT view frustrum culling was not properly culling behind the near plane:
Large objects behind the camera were sent to the GPU
- Remove all references to mesh split/join feature as it is not yet functional
Support for assigning any Type to a KX_GameObject
so you can do...
gameOb.follow = otherGameOb
gameOb[otherGameOb] = distanceTo
gameOb["path"] = [(x,y,x), (x,y,x)]
del gameOb[mesh]
* types that cannot be converted into CValue types are written into the KX_GameObject dict
* the KX_GameObject dict is only initialized when needed
* Python properties in this dict cannot be accessed by logic bricks
* dir(ob) and ob.getPropertyNames() return items from both CValue and Py dictionary properties.
Also found that CType was converting python lists to CType Lists but very buggy, would crash after printing the list most times.
Use python lists instead since logic bricks dont deal with lists.
There were also some problems with int to python conversion
- assigning a PyLong to a KX_GameObject from python would raise an error
- PyLong were coerced into floats when used with internal CValue arithmetic
Changes...
- PyLong is converted into CIntValue for coercing and assigning from python
- CValue's generic GetNumber() function returns a double rather then a float.
- Print an error when a PyType cant be coerced into a CValue
Tested with python, expressions and property sensor.
This commit contains a number of performance improvements for the
BGE in the Scenegraph (parent relation between objects in the
scene) and view frustrum culling.
The scenegraph improvement consists in avoiding position update
if the object has not moved since last update and the removal
of redundant updates and synchronization with the physics engine.
The view frustrum culling improvement consists in using the DBVT
broadphase facility of Bullet to build a tree of graphical objects
in the scene. The elements of the tree are Aabb boxes (Aligned
Axis Bounding Boxes) enclosing the objects. This provides good
precision in closed and opened scenes. This new culling system
is enabled by default but just in case, it can be disabled with
a button in the World settings. There is no do_version in this
commit but it will be added before the 2.49 release. For now you
must manually enable the DBVT culling option in World settings
when you open an old file.
The above improvements speed up scenegraph and culling up to 5x.
However, this performance improvement is only visible when
you have hundreds or thousands of objects.
The main interest of the DBVT tree is to allow easy occlusion
culling and automatic LOD system. This will be the object of further
improvements.
- Initialize python types with PyType_Ready, which adds methods to the type dictionary.
- use Pythons get/setattro (uses a python string for the attribute rather then char*). Using basic C strings seems nice but internally python converts them to python strings and discards them for most functions that accept char arrays.
- Method lookups use the PyTypes dictionary (should be faster then Py_FindMethod)
- Renamed __getattr -> py_base_getattro, _getattr -> py_getattro, __repr -> py_base_repr, py_delattro, py_getattro_self etc.
From here is possible to put all the parent classes methods into each python types dictionary to avoid nested lookups (api has 4 levels of lookups in some places), tested this but its not ready yet.
Simple tests for getting a method within a loop show this to be between 0.5 and 3.2x faster then using Py_FindMethod()
- Bugfix for running dir() on all BGE python objects. was not getting the immediate methods and attributes for each class.
- Use attributes for KX_Scene (so they are included with dir())
- Override __dict__ attributes for KX_Scene and KX_GameObject so custom properties are included with a dir()
ob.someProp = 10
can now be...
ob["someProp"] = 10
For simple get/set test with an objects 10 properties, this is ~30% faster.
Though I like the attribute access, its slower because it needs to lookup BGE attributes and methods (for parent classes as well as KX_GameObject class).
This could also be an advantage if there are collisions between new attributes added for 2.49 and existing properties a game uses.
Made some other small optimizations,
- Getting and setting property can use const char* as well as STR_String (avoids making new STR_Strings just to do the lookup).
- CValue::SetPropertiesModified() and CValue::SetPropertiesModified(), were looping through all items in the std::map, advancing from the beginning each time.
Deprecated..
getPosition, setPosition, getOrientation, setOrientation, getState, setState, getParent, getVisible, getMass
* swapped set/get to get/set in KX_PYATTRIBUTE_RW_FUNCTION macro to match pythons getsetattrs.
* deprecation warnings in the api and notes in epydocs.
* added 'state' attribute
* gameob.mass = 10 # now works because its not checking only for float values.
* dir(gameob) # includes attributes now
* fixed segfaults in CListValue.index(val) and CListValue.count(val) when the pyTypes could not be converted into a CValue.
* added scene.objects to replace scene.getObjectList()
* added function names to PyArg_ParseTuple() so errors will include the function names
* removed cases of PyArg_ParseTuple(args,"O",&pyobj) where METH_O ensures a single argument.
* Made PyObjectFrom use ugly python api rather then Py_BuildValue(), approx %40 speedup for functions that return Python vector and matrix types like ob.orientation.