I’ve been using a small library as part of an AI project for some time. I just came across Fenrir’s work on visualising objects for ODE. The code is based on the demo in the Panda3D manual and is a prelude to making something more complicated. I thought someone else might find this useful.
Example using wire frame objects as managed objects:
from direct.showbase.ShowBase import ShowBase
from panda3d.ode import OdeWorld, OdeHashSpace, OdeJointGroup
from panda3d.ode import OdeBody, OdeMass, OdeBoxGeom, OdePlaneGeom
from panda3d.ode import OdeUtil
from panda3d.core import BitMask32, CardMaker, Point3, Vec4, Quat
from random import randint, random
from ode_managed import OdeManagedBox, OdeManagedCapsule
from ode_managed import OdeManagedSphere, odeUpdate, OdeManagedCylinder
from direct.showbase.DirectObject import DirectObject
import sys
from wire_obj import wireGeom
PLATFORM_GRAV = True
base = ShowBase()
base.disableMouse()
base.camera.setPos(40, 40, 20)
do = DirectObject()
do.accept('q', sys.exit)
env = type('', (object,), {})()
env.world = OdeWorld()
env.world.setGravity(0, 0, -0.0981)
env.world.initSurfaceTable(1)
env.world.setSurfaceEntry(0, 0, 150, 0.0, 9.1, 0.9, 0.00001, 0.0, 0.002)
env.space = OdeHashSpace()
env.space.setAutoCollideWorld(env.world)
env.contactgroup = OdeJointGroup()
env.space.setAutoCollideJointGroup(env.contactgroup)
env.ode_stepsize = 1.0 / 45
env.odeManaged = []
OdeUtil.randSetSeed(0)
amount = (4, 8)
for i in range(randint(*amount)):
geom = wireGeom().generate('box', extents=(1, 1, 1))
geom.reparentTo(render)
box = OdeManagedBox(
env=env,
pobject=geom,
cat=BitMask32(0x00000002),
col=BitMask32(0x00000001),
mass=OdeManagedBox.mkBoxMass(10, geom),
)
box.setPosition((randint(-10, 10), randint(-10, 10), 15 + random()))
box.visible.setColor(random(), random(), random(), 1)
box.setHpr((randint(-45, 45), randint(-45, 45), randint(-45, 45)))
env.odeManaged.append((box, 0.01, 0.01))
for i in range(randint(*amount)):
geom = wireGeom().generate ('capsule', radius=0.4, length=1.1)
geom.reparentTo(render)
capsule = OdeManagedCapsule(
env=env,
pobject=geom,
cat=BitMask32(0x00000002),
col=BitMask32(0x00000001),
mass=OdeManagedBox.mkCapsuleMass(10, geom),
)
capsule.setPosition((randint(-10, 10), randint(-10, 10), 15 + random()))
capsule.visible.setColor(random(), random(), random(), 1)
capsule.setHpr((randint(-45, 45), randint(-45, 45), randint(-45, 45)))
env.odeManaged.append((capsule, 0.01, 0.01))
for i in range(randint(*amount)):
geom = wireGeom().generate('cylinder', radius=0.5, length=1.5)
geom.reparentTo(render)
cylinder = OdeManagedCylinder(
env=env,
pobject=geom,
cat=BitMask32(0x00000002),
col=BitMask32(0x00000001),
mass=OdeManagedBox.mkCylinderMass(10, geom),
)
cylinder.setPosition((randint(-10, 10), randint(-10, 10), 15 + random()))
cylinder.visible.setColor(random(), random(), random(), 1)
cylinder.setHpr((randint(-45, 45), randint(-45, 45), randint(-45, 45)))
env.odeManaged.append((cylinder, 0.01, 0.01))
for i in range(randint(*amount)):
geom = wireGeom().generate('sphere', radius=0.5)
geom.reparentTo(render)
sphere = OdeManagedSphere(
env=env,
pobject=geom,
cat=BitMask32(0x00000002),
col=BitMask32(0x00000001),
mass=OdeManagedBox.mkSphereMass(10, geom),
)
sphere.setPosition((randint(-10, 10), randint(-10, 10), 15 + random()))
sphere.visible.setColor(random(), random(), random(), 1)
sphere.setHpr((randint(-45, 45), randint(-45, 45), randint(-45, 45)))
env.odeManaged.append((sphere, 0.01, 0.01))
geom = wireGeom().generate('box', extents=(15, 15, 0.5))
geom.reparentTo(render)
if PLATFORM_GRAV:
big_box = OdeManagedBox(
env=env,
pobject=geom,
cat=BitMask32(0x00000001),
col=BitMask32(0x00000002),
mass=OdeManagedBox.mkBoxMass(100, geom),
)
big_box.body.setGravityMode(0)
env.odeManaged.append((big_box, 0.01, 0.01))
else:
big_box = OdeManagedBox(
env=env,
pobject=geom,
cat=BitMask32(0x00000001),
col=BitMask32(0x00000002),
)
while True:
odeUpdate(env)
base.camera.lookAt(big_box.visible)
base.taskMgr.step()
Managed ODE/Panda3D objects, ode_managed.py
:
from panda3d.ode import OdeBody, OdeMass, OdeTriMeshGeom
from panda3d.ode import OdeTriMeshData, OdeUtil
from panda3d.ode import OdeSphereGeom, OdeBoxGeom
from panda3d.ode import OdeCappedCylinderGeom, OdeCylinderGeom
from panda3d.core import Point3, VBase3, Quat
import logging
logger = logging.getLogger("logger")
class OdeManaged(object):
def __init__(self, env, pobject, geom, cat, col, mass=None, cobject=None):
self.env = env
self.visible = pobject
if cobject is None:
self.cobject = pobject
self.visible_offset = VBase3(0.0, 0.0, 0.0)
else:
self.cobject = cobject
self.visible_offset = pobject.getPos() - cobject.getPos()
self.geom = geom
self.geom.setCategoryBits(cat)
self.geom.setCollideBits(col)
self.mass = mass
if mass is None:
self.geom.setPosition(self.visible_offset + self.visible.getPos(render))
self.geom.setQuaternion(self.visible.getQuat(render))
else:
self.body = OdeBody(self.env.world)
self.body.setMass(mass)
self.geom.setBody(self.body)
self.body.setPosition(self.visible_offset + self.visible.getPos(render))
self.body.setQuaternion(self.visible.getQuat(render))
self.start_linear = self.body.getLinearVel()
self.start_angular = self.body.getAngularVel()
self.start_quat = self.visible.getQuat(render)
self.start_pos = (self.visible_offset + self.visible.getPos(render))
self.start_hpr = self.visible.getHpr()
def removeFrmScnGrph(self):
self.visible.removeNode()
def setPosition(self, pos):
pos = VBase3(*pos)
self.visible.setPos(pos)
if self.mass is None:
self.geom.setPosition(pos)
else:
self.body.setPosition(pos)
self.visible.setPos(pos - self.visible_offset)
def reset(self):
self.geom.setPosition(self.start_pos)
self.geom.setQuaternion(self.start_quat)
if self.mass is not None:
self.body.setForce(0, 0, 0)
self.body.setLinearVel(self.start_linear)
self.body.setAngularVel(self.start_angular)
self.visible.setPos(self.start_pos - self.visible_offset)
def resetStartPosition(self):
if self.mass is not None:
self.start_linear = self.body.getLinearVel()
self.start_angular = self.body.getAngularVel()
self.start_pos = self.body.getPosition()
else:
self.start_pos = self.geom.getPosition()
self.start_quat = self.visible.getQuat(render)
self.start_hpr = self.visible.getHpr()
def setHpr(self, hpr):
self.visible.setHpr(*hpr)
quat = Quat()
quat.setHpr(hpr)
if self.mass is None:
self.geom.setQuaternion(quat)
else:
self.body.setQuaternion(quat)
@staticmethod
def mkBoxMass(massp, pobject):
mass = OdeMass()
minDim, maxDim = pobject.getTightBounds()
dimms = Point3(maxDim - minDim)
mass.setBox(massp, dimms.getX(), dimms.getY(), dimms.getZ())
return mass
@staticmethod
def mkSphereMass(massp, pobject):
mass = OdeMass()
minp, maxp = pobject.getTightBounds()
dims = Point3(maxp - minp)
diameter = max([dims.getX(), dims.getY(), dims.getZ()])
mass.setSphere(massp, diameter)
return mass
@staticmethod
def mkCylinderMass(massp, pobject):
mass = OdeMass()
minDim, maxDim = pobject.getTightBounds()
dimms = Point3(maxDim - minDim)
radius = dimms.getX() / 2
mass.setCylinder(massp, 3, radius, dimms.getZ())
return mass
@staticmethod
def mkCapsuleMass(massp, pobject):
mass = OdeMass()
minDim, maxDim = pobject.getTightBounds()
dimms = Point3(maxDim - minDim)
radius = dimms.getX() / 2
mass.setCapsule(massp, 3, radius, dimms.getZ())
return mass
class OdeManagedTrimesh(OdeManaged):
def __init__(self, env, pobject, col, cat, cobject=None, mass=None):
if cobject is None:
objdata = OdeTriMeshData(pobject, True)
else:
objdata = OdeTriMeshData(cobject, True)
geom = OdeTriMeshGeom(env.space, objdata)
OdeManaged.__init__(self, env=env, pobject=pobject,
cobject=cobject, geom=geom, col=col,
cat=cat, mass=mass)
class OdeManagedSphere(OdeManaged):
def __init__(self, env, pobject, cat, col, mass):
minp, maxp = pobject.getTightBounds()
dims = Point3(maxp - minp)
diameter = max([dims.getX(), dims.getY(), dims.getZ()])
geom = OdeSphereGeom(env.space, diameter / 2.0)
OdeManaged.__init__(self, env=env, pobject=pobject, geom=geom,
col=col, cat=cat, mass=mass)
class OdeManagedBox(OdeManaged):
def __init__(self, env, pobject, cat, col, cobject=None, mass=None):
if cobject is None:
minp, maxp = pobject.getTightBounds()
else:
minp, maxp = cobject.getTightBounds()
dims = Point3(maxp - minp)
geom = OdeBoxGeom(env.space, dims.getX(), dims.getY(), dims.getZ())
OdeManaged.__init__(self, env=env, pobject=pobject,
cobject=cobject, geom=geom, col=col,
cat=cat, mass=mass)
class OdeManagedCapsule(OdeManaged):
def __init__(self, env, pobject, cat, col, cobject=None, mass=None):
if cobject is None:
minp, maxp = pobject.getTightBounds()
else:
minp, maxp = cobject.getTightBounds()
dims = Point3(maxp - minp)
radius = dims.getX() / 2
geom = OdeCappedCylinderGeom(env.space, radius, dims.getZ())
OdeManaged.__init__(self, env=env, pobject=pobject,
cobject=cobject, geom=geom, col=col,
cat=cat, mass=mass)
class OdeManagedCylinder(OdeManaged):
def __init__(self, env, pobject, cat, col, cobject=None, mass=None):
if cobject is None:
minp, maxp = pobject.getTightBounds()
else:
minp, maxp = cobject.getTightBounds()
dims = Point3(maxp - minp)
radius = dims.getX() / 2
geom = OdeCylinderGeom(env.space, radius, dims.getZ())
OdeManaged.__init__(self, env=env, pobject=pobject,
cobject=cobject, geom=geom, col=col,
cat=cat, mass=mass)
def odeUpdate(env):
env.space.autoCollide() # Setup the contact joints
env.world.quickStep(env.ode_stepsize)
# Dampen velocity & rotation
for m, lf, af in env.odeManaged:
coef_velocity = m.body.getLinearVel() * -lf
m.body.addForce(coef_velocity)
coef_rotation = m.body.getAngularVel() * -af
m.body.addTorque(coef_rotation)
m.visible.setPosQuat(render, m.visible_offset + m.body.getPosition(),
Quat(m.body.getQuaternion()))
env.contactgroup.empty()
Wire frame objects by FenrirWolf; wire_obj.py
:
# import direct.directbase.DirectStart
from panda3d.core import Point3, Vec3, Vec4, BitMask32
from panda3d.ode import OdeHashSpace, OdeSimpleSpace, OdeWorld, OdeJointGroup
from panda3d.core import GeomVertexFormat, GeomVertexData, GeomVertexWriter
from panda3d.core import Geom, GeomNode, GeomPoints, NodePath, GeomLinestrips
from panda3d.core import CardMaker
from panda3d.ode import OdePlaneGeom
from direct.showbase.DirectObject import DirectObject
from direct.showbase.ShowBase import ShowBase
import math
import random
import sys
"""
Note that wireprims are wire-like representations of geom, in the same manner as Ogre's debug mode. I find this the most useful way to represent
ODE geom structures visually, as you can clearly see the orientation versus a more generic wireframe mesh.
These wireprims are rendered as linestrips. Therefore, only vertices are required and texturing is not supported. You can use standard render attribute changes such
as setColor in order to change the line's color. By default it is green.
This class merely returns a NodePath to a GeomNode that is a representation of what is requested. You can use this outside of ODE geom visualizations, obviously.
Supported are sphere, box, cylinder, capsule (aka capped cylinder), ray, and plane
to use:
sphereNodepath = wireGeom().generate ('sphere', radius=1.0)
boxNodepath = wireGeom().generate ('box', extents=(1, 1, 1))
cylinderNodepath = wireGeom().generate ('cylinder', radius=1.0, length=3.0)
rayNodepath = wireGeom().generate ('ray', length=3.0)
planeNodepath = wireGeom().generate ('plane')
"""
class wireGeom:
def __init__ (self):
# GeomNode to hold our individual geoms
self.gnode = GeomNode ('wirePrim')
# How many times to subdivide our spheres/cylinders resulting vertices. Keep low
# because this is supposed to be an approximate representation
self.subdiv = 12
def line (self, start, end):
# since we're doing line segments, just vertices in our geom
format = GeomVertexFormat.getV3()
# build our data structure and get a handle to the vertex column
vdata = GeomVertexData ('', format, Geom.UHStatic)
vertices = GeomVertexWriter (vdata, 'vertex')
# build a linestrip vertex buffer
lines = GeomLinestrips (Geom.UHStatic)
vertices.addData3f (start[0], start[1], start[2])
vertices.addData3f (end[0], end[1], end[2])
lines.addVertices (0, 1)
lines.closePrimitive()
geom = Geom (vdata)
geom.addPrimitive (lines)
# Add our primitive to the geomnode
self.gnode.addGeom (geom)
def circle (self, radius, axis, offset):
# since we're doing line segments, just vertices in our geom
format = GeomVertexFormat.getV3()
# build our data structure and get a handle to the vertex column
vdata = GeomVertexData ('', format, Geom.UHStatic)
vertices = GeomVertexWriter (vdata, 'vertex')
# build a linestrip vertex buffer
lines = GeomLinestrips (Geom.UHStatic)
for i in range (0, self.subdiv):
angle = i / float(self.subdiv) * 2.0 * math.pi
ca = math.cos (angle)
sa = math.sin (angle)
if axis == "x":
vertices.addData3f (0, radius * ca, radius * sa + offset)
if axis == "y":
vertices.addData3f (radius * ca, 0, radius * sa + offset)
if axis == "z":
vertices.addData3f (radius * ca, radius * sa, offset)
for i in range (1, self.subdiv):
lines.addVertices(i - 1, i)
lines.addVertices (self.subdiv - 1, 0)
lines.closePrimitive()
geom = Geom (vdata)
geom.addPrimitive (lines)
# Add our primitive to the geomnode
self.gnode.addGeom (geom)
def capsule (self, radius, length, axis):
# since we're doing line segments, just vertices in our geom
format = GeomVertexFormat.getV3()
# build our data structure and get a handle to the vertex column
vdata = GeomVertexData ('', format, Geom.UHStatic)
vertices = GeomVertexWriter (vdata, 'vertex')
# build a linestrip vertex buffer
lines = GeomLinestrips (Geom.UHStatic)
# draw upper dome
for i in range (0, self.subdiv // 2 + 1):
angle = i / float(self.subdiv) * 2.0 * math.pi
ca = math.cos (angle)
sa = math.sin (angle)
if axis == "x":
vertices.addData3f (0, radius * ca, radius * sa + (length / 2))
if axis == "y":
vertices.addData3f (radius * ca, 0, radius * sa + (length / 2))
# draw lower dome
for i in range (0, self.subdiv // 2 + 1):
angle = -math.pi + i / float(self.subdiv) * 2.0 * math.pi
ca = math.cos (angle)
sa = math.sin (angle)
if axis == "x":
vertices.addData3f (0, radius * ca, radius * sa - (length / 2))
if axis == "y":
vertices.addData3f (radius * ca, 0, radius * sa - (length / 2))
for i in range (1, self.subdiv + 1):
lines.addVertices(i - 1, i)
lines.addVertices (self.subdiv + 1, 0)
lines.closePrimitive()
geom = Geom (vdata)
geom.addPrimitive (lines)
# Add our primitive to the geomnode
self.gnode.addGeom (geom)
def rect (self, width, height, axis):
# since we're doing line segments, just vertices in our geom
format = GeomVertexFormat.getV3()
# build our data structure and get a handle to the vertex column
vdata = GeomVertexData ('', format, Geom.UHStatic)
vertices = GeomVertexWriter (vdata, 'vertex')
# build a linestrip vertex buffer
lines = GeomLinestrips (Geom.UHStatic)
# draw a box
if axis == "x":
vertices.addData3f (0, -width, -height)
vertices.addData3f (0, width, -height)
vertices.addData3f (0, width, height)
vertices.addData3f (0, -width, height)
if axis == "y":
vertices.addData3f (-width, 0, -height)
vertices.addData3f (width, 0, -height)
vertices.addData3f (width, 0, height)
vertices.addData3f (-width, 0, height)
if axis == "z":
vertices.addData3f (-width, -height, 0)
vertices.addData3f (width, -height, 0)
vertices.addData3f (width, height, 0)
vertices.addData3f (-width, height, 0)
for i in range (1, 3):
lines.addVertices(i - 1, i)
lines.addVertices (3, 0)
lines.closePrimitive()
geom = Geom (vdata)
geom.addPrimitive (lines)
# Add our primitive to the geomnode
self.gnode.addGeom (geom)
def generate (self, type, radius=1.0, length=1.0, extents=Point3(1, 1, 1), R=-1, G=-1, B=-1):
if R==-1:
R=random.uniform(0,1)
if G==-1:
G=random.uniform(0,1)
if B==-1:
B=random.uniform(0,1)
if type == 'sphere':
# generate a simple sphere
self.circle (radius, "x", 0)
self.circle (radius, "y", 0)
self.circle (radius, "z", 0)
if type == 'capsule':
# generate a simple capsule
self.capsule (radius, length, "x")
self.capsule (radius, length, "y")
self.circle (radius, "z", -length / 2)
self.circle (radius, "z", length / 2)
if type == 'box':
# generate a simple box
self.rect (extents[1]/2, extents[2]/2, "x")
self.rect (extents[0]/2, extents[2]/2, "y")
self.rect (extents[0]/2, extents[1]/2, "z")
if type == 'cylinder':
# generate a simple cylinder
self.line ((0, -radius, -length / 2), (0, -radius, length/2))
self.line ((0, radius, -length / 2), (0, radius, length/2))
self.line ((-radius, 0, -length / 2), (-radius, 0, length/2))
self.line ((radius, 0, -length / 2), (radius, 0, length/2))
self.circle (radius, "z", -length / 2)
self.circle (radius, "z", length / 2)
if type == 'ray':
# generate a ray
self.circle (length / 10, "x", 0)
self.circle (length / 10, "z", 0)
self.line ((0, 0, 0), (0, 0, length))
self.line ((0, 0, length), (0, -length/10, length*0.9))
self.line ((0, 0, length), (0, length/10, length*0.9))
if type == 'plane':
# generate a plane
length = 3.0
self.rect (1.0, 1.0, "z")
self.line ((0, 0, 0), (0, 0, length))
self.line ((0, 0, length), (0, -length/10, length*0.9))
self.line ((0, 0, length), (0, length/10, length*0.9))
# rename ourselves to wirePrimBox, etc.
name = self.gnode.getName()
self.gnode.setName(name + type.capitalize())
NP = NodePath (self.gnode) # Finally, make a nodepath to our geom
NP.setColor(R, G, B) # Set default color
return NP