def build_node_path(self, parent_node_path, bullet_world): land_geom = self.__build_land_mesh() ocean_geom = self.__build_ocean_mesh() land_mesh = BulletTriangleMesh() land_mesh.addGeom(land_geom) land_shape = BulletTriangleMeshShape(land_mesh, dynamic=False) ocean_shape = BulletSphereShape(self.__radius) land_bullet_node = BulletRigidBodyNode('land collider') land_bullet_node.addShape(land_shape) bullet_world.attachRigidBody(land_bullet_node) land_bullet_node_path = parent_node_path.attachNewNode( land_bullet_node) ocean_bullet_node = BulletGhostNode('ocean collider') ocean_bullet_node.addShape(ocean_shape) bullet_world.attachGhost(ocean_bullet_node) ocean_bullet_node_path = land_bullet_node_path.attachNewNode( ocean_bullet_node) land_node = GeomNode('land') land_node.addGeom(land_geom) land_node_path = land_bullet_node_path.attachNewNode(land_node) ocean_node = GeomNode('ocean') ocean_node.addGeom(ocean_geom) ocean_node_path = ocean_bullet_node_path.attachNewNode(ocean_node) ocean_node_path.setTransparency(TransparencyAttrib.MAlpha) self.__node_path = land_bullet_node_path land_bullet_node.setPythonTag('planet', self) return land_bullet_node_path
def isRayHitMeshAll(self, pfrom, pto, objcm): """ :param pfrom: :param pto: :param objcm: :return: author: weiwei date: 20190805 """ geom = base.pg.packpandageom_fn(objcm.trimesh.vertices, objcm.trimesh.face_normals, objcm.trimesh.faces) targetobjmesh = BulletTriangleMesh() targetobjmesh.addGeom(geom) bullettmshape = BulletTriangleMeshShape(targetobjmesh, dynamic=True) bullettmshape.setMargin(1e-6) targetobjmeshnode = BulletRigidBodyNode('facet') targetobjmeshnode.addShape(bullettmshape) self.world.attach(targetobjmeshnode) result = self.world.rayTestAll(base.pg.npToV3(pfrom), base.pg.npToV3(pto)) self.world.removeRigidBody(targetobjmeshnode) if result.hasHits(): allhits = [] for hit in result.getHits(): allhits.append([hit.getHitPos(), -hit.getHitNormal()]) return allhits else: return []
def addMeshConvexRB(self,vertices, faces,ghost=False,**kw): #step 1) create GeomVertexData and add vertex information format=GeomVertexFormat.getV3() vdata=GeomVertexData("vertices", format, Geom.UHStatic) vertexWriter=GeomVertexWriter(vdata, "vertex") [vertexWriter.addData3f(v[0],v[1],v[2]) for v in vertices] #step 2) make primitives and assign vertices to them tris=GeomTriangles(Geom.UHStatic) [self.setGeomFaces(tris,face) for face in faces] #step 3) make a Geom object to hold the primitives geom=Geom(vdata) geom.addPrimitive(tris) #step 4) create the bullet mesh and node mesh = BulletTriangleMesh() mesh.addGeom(geom) shape = BulletConvexHullShape(mesh, dynamic=not ghost)# if ghost : inodenp = self.worldNP.attachNewNode(BulletGhostNode('Mesh')) else : inodenp = self.worldNP.attachNewNode(BulletRigidBodyNode('Mesh')) inodenp.node().addShape(shape) # inodenp.setPos(0, 0, 0.1) self.setRB(inodenp,**kw) inodenp.setCollideMask(BitMask32.allOn()) self.world.attachRigidBody(inodenp.node()) return inodenp
def setup(self): self.worldNP = render.attachNewNode('World') # World self.debugNP = self.worldNP.attachNewNode(BulletDebugNode('Debug')) self.debugNP.show() self.world = BulletWorld() self.world.setGravity(Vec3(0, 0, -9.81)) self.world.setDebugNode(self.debugNP.node()) # Ground p0 = Point3(-20, -20, 0) p1 = Point3(-20, 20, 0) p2 = Point3(20, -20, 0) p3 = Point3(20, 20, 0) mesh = BulletTriangleMesh() mesh.addTriangle(p0, p1, p2) mesh.addTriangle(p1, p2, p3) shape = BulletTriangleMeshShape(mesh, dynamic=False) np = self.worldNP.attachNewNode(BulletRigidBodyNode('Mesh')) np.node().addShape(shape) np.setPos(0, 0, -2) np.setCollideMask(BitMask32.allOn()) self.world.attachRigidBody(np.node()) # Soft body world information info = self.world.getWorldInfo() info.setAirDensity(1.2) info.setWaterDensity(0) info.setWaterOffset(0) info.setWaterNormal(Vec3(0, 0, 0)) # Softbody for i in range(50): p00 = Point3(-2, -2, 0) p10 = Point3( 2, -2, 0) p01 = Point3(-2, 2, 0) p11 = Point3( 2, 2, 0) node = BulletSoftBodyNode.makePatch(info, p00, p10, p01, p11, 6, 6, 0, True) node.generateBendingConstraints(2) node.getCfg().setLiftCoefficient(0.004) node.getCfg().setDynamicFrictionCoefficient(0.0003) node.getCfg().setAeroModel(BulletSoftBodyConfig.AMVertexTwoSided) node.setTotalMass(0.1) node.addForce(Vec3(0, 2, 0), 0) np = self.worldNP.attachNewNode(node) np.setPos(self.Vec3Rand() * 10 + Vec3(0, 0, 20)) np.setHpr(self.Vec3Rand() * 16) self.world.attachSoftBody(node) fmt = GeomVertexFormat.getV3n3t2() geom = BulletHelper.makeGeomFromFaces(node, fmt, True) node.linkGeom(geom) nodeV = GeomNode('') nodeV.addGeom(geom) npV = np.attachNewNode(nodeV)
def __init__(self, bulletWorld): #model used as collision mesh VOLCANO collisionModel = loader.loadModel('models/VolcanoCollision2') tex = loader.loadTexture("models/mars_1k_tex.jpg") collisionModel.setTexture(tex) mesh = BulletTriangleMesh() for geomNP in collisionModel.findAllMatches('**/+GeomNode'): geomNode = geomNP.node() ts = geomNP.getTransform(collisionModel) for geom in geomNode.getGeoms(): mesh.addGeom(geom, ts) shape = BulletTriangleMeshShape(mesh, dynamic=False) self.rigidNode = BulletRigidBodyNode('Heightfield') self.rigidNode.notifyCollisions(False) np = render.attachNewNode(self.rigidNode) np.node().addShape(shape) collisionModel.reparentTo(np) np.setScale(7) ###Ucomment next line for RAZOR map: #np.setHpr(0,90,0) np.setPos(0, 0, -2) np.setCollideMask(BitMask32.allOn()) np.node().notifyCollisions(False) bulletWorld.attachRigidBody(np.node()) self.hf = np.node() # To enable/disable debug visualization
def __init__(self, model, world, worldNP, pos, scale, hpr): self.worldNP = worldNP bulletWorld = world # Initialize the model. self.AIModel = loader.loadModel(model) self.AINode = BulletRigidBodyNode('AIChar') self.AIModel.setScale(scale) self.AIModel.flattenLight() # Combines all geom nodes into one geom node. # Build the triangle mesh shape and attach it with the transform. geom = self.AIModel.findAllMatches('**/+GeomNode').getPath(0).node().getGeom(0) mesh = BulletTriangleMesh() mesh.addGeom(geom) shape = BulletTriangleMeshShape(mesh, dynamic=False) self.AINode.addShape(shape, TransformState.makePosHprScale(Point3(0,0,0), hpr, scale)) self.AINode.setMass(0) bulletWorld.attachRigidBody(self.AINode) # Apply the same transforms on the model being rendered. self.AIModel.reparentTo(render) self.AIModel.setH(hpr.getX()) self.AIModel.setP(hpr.getY()) self.AIModel.setR(hpr.getZ()) self.AINode.setAngularFactor(Vec3(0,0,0)) # Attach it to the world. self.AIChar = self.worldNP.attachNewNode(self.AINode) self.AIModel.reparentTo(self.AIChar) self.AIChar.setPos(pos)
def genCollisionMeshNp(nodepath, basenodepath=None, name='autogen'): """ generate the collision mesh of a nodepath using nodepath this function suppose the nodepath is a single model with one geomnode :param nodepath: the panda3d nodepath of the object :param basenodepath: the nodepath to compute relative transform, identity if none :param name: the name of the rigidbody :return: bulletrigidbody author: weiwei date: 20161212, tsukuba """ geomnodepath = nodepath.find("**/+GeomNode") geombullnode = BulletRigidBodyNode(name) geom = geomnodepath.node().getGeom(0) geomtf = nodepath.getTransform(base.render) if basenodepath is not None: geomtf = nodepath.getTransform(basenodepath) geombullmesh = BulletTriangleMesh() geombullmesh.addGeom(geom) bullettmshape = BulletTriangleMeshShape(geombullmesh, dynamic=True) bullettmshape.setMargin(0) geombullnode.addShape(bullettmshape, geomtf) return geombullnode
def genCollisionMeshMultiNp(nodepath, basenodepath=None, name='autogen'): """ generate the collision mesh of a nodepath using nodepath this function suppose the nodepath has multiple models with many geomnodes use genCollisionMeshMultiNp instead of genCollisionMeshNp for generality :param nodepath: the panda3d nodepath of the object :param basenodepath: the nodepath to compute relative transform, identity if none :param name: the name of the rigidbody :return: bulletrigidbody author: weiwei date: 20161212, tsukuba """ gndcollection = nodepath.findAllMatches("**/+GeomNode") geombullnode = BulletRigidBodyNode(name) for gnd in gndcollection: geom = gnd.node().getGeom(0) geomtf = gnd.getTransform(base.render) if basenodepath is not None: geomtf = gnd.getTransform(basenodepath) geombullmesh = BulletTriangleMesh() geombullmesh.addGeom(geom) bullettmshape = BulletTriangleMeshShape(geombullmesh, dynamic=True) bullettmshape.setMargin(0) geombullnode.addShape(bullettmshape, geomtf) return geombullnode
def __init__(self, name, modelPath, displayModelPath, game, pos): self.name = name self.modelPath = modelPath self.game = game self.model = self.game.loader.loadModel(self.modelPath) geomNodes = self.model.findAllMatches('**/+GeomNode') self.geomNode = geomNodes.getPath(0).node() self.geom = self.geomNode.getGeom(0) #self.shape = BulletConvexHullShape() #self.shape.addGeom(self.geom) mesh = BulletTriangleMesh() mesh.addGeom(self.geom) self.shape = BulletTriangleMeshShape(mesh, dynamic=False) self.node = BulletRigidBodyNode(self.name) self.node.addShape(self.shape) self.np = self.game.render.attachNewNode(self.node) self.np.setPos(pos) self.game.world.attachRigidBody(self.node) #self.model.reparentTo(self.np) self.displayModel = self.game.loader.loadModel(displayModelPath) self.displayModel.reparentTo(self.np) self.displayModel.setTwoSided(True) self.slice_able = False
def __init__(self, model, world, worldNP, pos, scale, hpr): self.worldNP = worldNP bulletWorld = world # Initialize the model. self.AIModel = loader.loadModel(model) self.AINode = BulletRigidBodyNode("AIChar") self.AIModel.setScale(scale) self.AIModel.flattenLight() # Combines all geom nodes into one geom node. # Build the triangle mesh shape and attach it with the transform. geom = self.AIModel.findAllMatches("**/+GeomNode").getPath(0).node().getGeom(0) mesh = BulletTriangleMesh() mesh.addGeom(geom) shape = BulletTriangleMeshShape(mesh, dynamic=False) self.AINode.addShape(shape, TransformState.makePosHprScale(Point3(0, 0, 0), hpr, scale)) self.AINode.setMass(0) bulletWorld.attachRigidBody(self.AINode) # Apply the same transforms on the model being rendered. self.AIModel.reparentTo(render) self.AIModel.setH(hpr.getX()) self.AIModel.setP(hpr.getY()) self.AIModel.setR(hpr.getZ()) self.AINode.setAngularFactor(Vec3(0, 0, 0)) # Attach it to the world. self.AIChar = self.worldNP.attachNewNode(self.AINode) self.AIModel.reparentTo(self.AIChar) self.AIChar.setPos(pos)
def genBulletCDMeshMultiNp(nodepath, basenodepath=None, name='autogen'): """ generate the BulletCD mesh of a nodepath using nodepath this function suppose the nodepath has multiple models with many geomnodes use genBulletCDMeshMultiNp instead of genBulletCDMeshNp for generality :param nodepath: the panda3d nodepath of the object :param basenodepath: the nodepath to compute relative transform, identity if none :param name: the name of the rigidbody :return: bulletrigidbody author: weiwei date: 20161212, tsukuba """ gndcollection = nodepath.findAllMatches("**/+GeomNode") geombullnode = BulletRigidBodyNode(name) for gnd in gndcollection: geom = gnd.node().getGeom(0) geomtf = gnd.getTransform(base.render) if basenodepath is not None: geomtf = gnd.getTransform(basenodepath) geombullmesh = BulletTriangleMesh() geombullmesh.addGeom(geom) bullettmshape = BulletTriangleMeshShape(geombullmesh, dynamic=True) bullettmshape.setMargin(0) geombullnode.addShape(bullettmshape, geomtf) return geombullnode
def bulletRayHit(pfrom, pto, geom): """ NOTE: this function is quite slow find the nearest collision point between vec(pto-pfrom) and the mesh of nodepath :param pfrom: starting point of the ray, Point3 :param pto: ending point of the ray, Point3 :param geom: meshmodel, a panda3d datatype :return: None or Point3 author: weiwei date: 20161201 """ bulletworld = BulletWorld() facetmesh = BulletTriangleMesh() facetmesh.addGeom(geom) facetmeshnode = BulletRigidBodyNode('facet') bullettmshape = BulletTriangleMeshShape(facetmesh, dynamic=True) bullettmshape.setMargin(1e-6) facetmeshnode.addShape(bullettmshape) bulletworld.attach(facetmeshnode) result = bulletworld.rayTestClosest(pfrom, pto) if result.hasHit(): return result.getHitPos() else: return None
def genBulletCDMeshList(objcmlist, basenodepath=None, name='autogen'): """ generate the collision mesh of a nodepath using nodepathlist this function suppose the nodepathlist is a list of models with many geomnodes "Multi" means each nodepath in the nodepath list may have multiple nps (parent-child relations) use genCollisionMeshMultiNp instead if the meshes have parent-child relations :param nodepathlist: panda3d nodepathlist :param basenodepath: the nodepath to compute relative transform, identity if none :param name: the name of the rigidbody :return: bulletrigidbody author: weiwei date: 20190514 """ geombullnode = BulletRigidBodyNode(name) for objcm in objcmlist: gndcollection = objcm.objnp.findAllMatches("+GeomNode") for gnd in gndcollection: geom = copy.deepcopy(gnd.node().getGeom(0)) geomtf = gnd.getTransform(base.render) if basenodepath is not None: geomtf = gnd.getTransform(basenodepath) geombullmesh = BulletTriangleMesh() geombullmesh.addGeom(geom) bullettmshape = BulletTriangleMeshShape(geombullmesh, dynamic=True) bullettmshape.setMargin(0) geombullnode.addShape(bullettmshape, geomtf) return geombullnode
def createLetter(self, loadFile, name, x, y, z): self.name = name self.letter = loader.loadModel(loadFile) geomnodes = self.letter.findAllMatches('**/+GeomNode') gn = geomnodes.getPath(0).node() geom = gn.getGeom(0) mesh = BulletTriangleMesh() mesh.addGeom(geom) shape = BulletTriangleMeshShape(mesh, dynamic=False) self.letterNode = BulletRigidBodyNode('Letter') self.letterNode.setMass(0) self.letterNode.addShape(shape) self.letters.append(self.letterNode) letternn = render.attachNewNode(self.letterNode) letternn.setPos(x, y, z) letternn.setScale(1) letternn.setP(90) # orients the mesh for the letters to be upright self.world.attachRigidBody(self.letterNode) self.letter.reparentTo(letternn) self.letter.setP( -90) # orients the actual letter objects to be upright
def rayHit(pfrom, pto, geom): """ NOTE: this function is quite slow find the nearest collision point between vec(pto-pfrom) and the mesh of nodepath :param pfrom: starting point of the ray, Point3 :param pto: ending point of the ray, Point3 :param geom: meshmodel, a panda3d datatype :return: None or Point3 author: weiwei date: 20161201 """ bulletworld = BulletWorld() facetmesh = BulletTriangleMesh() facetmesh.addGeom(geom) facetmeshnode = BulletRigidBodyNode('facet') bullettmshape = BulletTriangleMeshShape(facetmesh, dynamic=True) bullettmshape.setMargin(0) facetmeshnode.addShape(bullettmshape) bulletworld.attachRigidBody(facetmeshnode) result = bulletworld.rayTestClosest(pfrom, pto) if result.hasHit(): return result.getHitPos() else: return None
def loadModel(self): if (self.viewing_object): self.world.removeRigidBody(self.viewing_object.node()) Tk().withdraw( ) # we don't want a full GUI, so keep the root window from appearing filename = askopenfilename( ) # show an "Open" dialog box and return the path to the selected file # filename = "models/new2.obj" pandafile = Filename.fromOsSpecific(filename) viewing_object_NP = loader.loadModel(pandafile) geom = viewing_object_NP.findAllMatches("**/+GeomNode").getPath( 0).node().getGeom(0) mesh = BulletTriangleMesh() mesh.addGeom(geom) shape = BulletTriangleMeshShape(mesh, dynamic=True) body = BulletRigidBodyNode("viewing_object") self.viewing_object = self.worldNP.attachNewNode(body) self.viewing_object.node().addShape(shape) self.viewing_object.setPos(0, 0, 0) self.viewing_object.setHpr(0, 90, 0) self.viewing_object.setCollideMask(BitMask32.allOn()) self.world.attachRigidBody(self.viewing_object.node()) self.viewing_object.setScale(50)
def generate_chunk(self): """ this function will generate the actual geometry that is the chunk """ self.update_block_faces() self.material_nodes = { material_id: GeomNode(self.name) for material_id in block_id_mapping.keys() } self.bullet_mesh = BulletTriangleMesh() # self.texture_np = NodePath('textures') for i in range(self.arr_x): for j in range(self.arr_y): for k in range(self.arr_z): if self.block_arr[i, j, k][0] == 1: # convert from chunk coordinates to world coordinates so the goemetry is in the right place rel_x = i + self.x_range[0] rel_y = j + self.y_range[0] # only x and y need to be shifted, z is fine as is geom = self.make_cube_geom( pos=(rel_x, rel_y, k), faces_no_draw=self.block_arr[i, j, k][2:]) material_id = self.block_arr[i, j, k][1] self.material_nodes[material_id].addGeom(geom) self.bullet_mesh.addGeom(geom)
def make_collision_from_model(input_model, node_number, mass, world, target_pos, h_adj): # tristrip generation from static models # generic tri-strip collision generator begins geom_nodes = input_model.find_all_matches('**/+GeomNode') geom_nodes = geom_nodes.get_path(node_number).node() # print(geom_nodes) geom_target = geom_nodes.get_geom(0) # print(geom_target) output_bullet_mesh = BulletTriangleMesh() output_bullet_mesh.add_geom(geom_target) tri_shape = BulletTriangleMeshShape(output_bullet_mesh, dynamic=False) print(output_bullet_mesh) body = BulletRigidBodyNode('input_model_tri_mesh') np = self.render.attach_new_node(body) np.node().add_shape(tri_shape) np.node().set_mass(mass) np.node().set_friction(0.01) np.set_pos(target_pos) np.set_scale(1) np.set_h(h_adj) # np.set_p(180) # np.set_r(180) np.set_collide_mask(BitMask32.allOn()) world.attach_rigid_body(np.node())
def __init__(self, track_data, world): super().__init__() self.track_data = track_data self.world = world self.snode = GeomNode('track') self.width = track_data["width"] self.cur_x1 = 0 self.cur_y1 = 0 self.cur_z1 = 0 self.cur_x2 = self.width self.cur_y2 = 0 self.cur_z2 = 0 self.mesh = BulletTriangleMesh() self.surfaces = {} self.load_surfaces() self.segments = [] self.gen_segments() shape = BulletTriangleMeshShape(self.mesh, dynamic=False) self.track = render.attachNewNode(BulletRigidBodyNode('Track')) self.track.node().addShape(shape) self.world.attachRigidBody(self.track.node()) self.track.attachNewNode(self.snode) self.track.setTwoSided(True) self.track.setCollideMask(BitMask32.allOn())
def getCollisionShapeFromModel(model, mode='box', defaultCentered=False): #NOTE: make sure the position is relative to the center of the object minBounds, maxBounds = model.getTightBounds() offset = minBounds + (maxBounds - minBounds) / 2.0 transform = TransformState.makeIdentity() if mode == 'mesh': # Use exact triangle mesh approximation mesh = BulletTriangleMesh() geomNodes = model.findAllMatches('**/+GeomNode') for nodePath in geomNodes: geomNode = nodePath.node() for n in range(geomNode.getNumGeoms()): geom = geomNode.getGeom(n) mesh.addGeom(geom) shape = BulletTriangleMeshShape(mesh, dynamic=False) transform = model.getTransform() elif mode == "sphere": minBounds, maxBounds = model.getTightBounds() dims = maxBounds - minBounds radius = np.sqrt(np.square(dims[0]) + np.square(dims[1])) / 2.0 height = dims[2] shape = BulletCapsuleShape(radius, 2 * radius) if not defaultCentered: transform = TransformState.makePos(offset) elif mode == "hull": shape = BulletConvexHullShape() geomNodes = model.findAllMatches('**/+GeomNode') for nodePath in geomNodes: geomNode = nodePath.node() for n in range(geomNode.getNumGeoms()): geom = geomNode.getGeom(n) shape.addGeom(geom) elif mode == 'box': # Bounding box approximation minBounds, maxBounds = model.getTightBounds() dims = maxBounds - minBounds shape = BulletBoxShape(Vec3(dims.x / 2, dims.y / 2, dims.z / 2)) if not defaultCentered: transform = TransformState.makePos(offset) elif mode == 'capsule': minBounds, maxBounds = model.getTightBounds() dims = maxBounds - minBounds radius = np.sqrt(np.square(dims[0]) + np.square(dims[1])) / 2.0 height = dims[2] shape = BulletCapsuleShape(radius, height - 2 * radius) if not defaultCentered: transform = TransformState.makePos(offset) else: raise Exception( 'Unknown mode type for physic object collision shape: %s' % (mode)) return shape, transform
def __init__(self): base.accept('f1', self.toggleDebug) self.debugNode = BulletDebugNode('Debug') self.debugNode.showWireframe(True) self.debugNode.showConstraints(True) self.debugNode.showBoundingBoxes(False) self.debugNode.showNormals(False) self.debugNP = base.render.attachNewNode(self.debugNode) # self.debugNP.show() # World self.world = BulletWorld() self.world.setGravity(Vec3(0, 0, -9.81)) self.world.setDebugNode(self.debugNP.node()) # Terrain visNP = base.loader.loadModel('models/terrain.egg') mesh = BulletTriangleMesh() for x in visNP.findAllMatches('**/+GeomNode'): geom = x.node().getGeom(0) mesh.addGeom(geom) shape = BulletTriangleMeshShape(mesh, dynamic=True) body = BulletRigidBodyNode('Bowl') bodyNP = base.render.attachNewNode(body) bodyNP.node().addShape(shape) bodyNP.setPos(0, 0, 1) bodyNP.setCollideMask(BitMask32.allOn()) self.world.attachRigidBody(bodyNP.node()) visNP.reparentTo(bodyNP) shapex = BulletBoxShape(5) bodyx = BulletRigidBodyNode('Egg') bodyNPx = base.render.attachNewNode(bodyx) bodyNPx.setPos(0, 0, 3) bodyNPx.node().setMass(100.0) bodyNPx.node().addShape(shapex) self.world.attachRigidBody(bodyNPx.node()) # visNP.reparentTo(bodyNPx) # Player self.players = [] self.myId = -1 self.speed = Vec3(0, 0, 0) self.walk_speed = 2.5 # Camera base.disableMouse() props = WindowProperties() props.setCursorHidden(True) base.win.requestProperties(props) # SkySphere Sky() self.initCam()
def get_bullet_shape(geom_node): shape = BulletTriangleMesh() for i in range(geom_node.getNumGeoms()): geom = geom_node.getGeom(i) # state = geom_node.getGeomState(i) shape.addGeom(geom) shape = BulletTriangleMeshShape(shape, True) return shape
def ModelToBTS(model): geomnodes = model.findAllMatches('**/+GeomNode') gn = geomnodes.getPath(0).node() geom = gn.getGeom(0) mesh = BulletTriangleMesh() mesh.addGeom(geom) shape = BulletTriangleMeshShape(mesh, dynamic=False) return shape
def egg_to_BulletTriangleMeshShape(self, modelnp): mesh = BulletTriangleMesh() for collisionNP in modelnp.findAllMatches('**/+CollisionNode'): collisionNode = collisionNP.node() for collisionPolygon in collisionNode.getSolids(): tri_points = collisionPolygon.getPoints() mesh.addTriangle(tri_points[0], tri_points[1], tri_points[2]) shape = BulletTriangleMeshShape(mesh, dynamic=False) return shape
def gen_cdmesh_vvnf(vertices, vertex_normals, faces, name='auto'): geom = da.pandageom_from_vvnf(vertices * SCALE_FOR_PRECISION, vertex_normals, faces) bullet_triangles_mesh = BulletTriangleMesh() bullet_triangles_mesh.addGeom(geom) bullet_triangles_shape = BulletTriangleMeshShape(bullet_triangles_mesh, dynamic=True) bullet_triangles_shape.setMargin(0) geombullnode = BulletRigidBodyNode(name=name) geombullnode.addShape(bullet_triangles_shape) return geombullnode
def bullet_shape_from(source, dynamic=False): mesh = BulletTriangleMesh() for geom_node in source.findAllMatches('**/+GeomNode'): gn = geom_node.node() ts = gn.getTransform() for geom in gn.getGeoms(): mesh.addGeom(geom, True, ts) return BulletTriangleMeshShape(mesh, dynamic=dynamic)
def __init__(self, bulletWorld): self.env = loader.loadModel("models/env") self.env.reparentTo(render) self.env.setPos(0,0,-6) self.env.setScale(400) self.environ_tex = loader.loadTexture("models/tex/env_sky.jpg") self.env.setTexture(self.environ_tex, 1) self.period_cloud = self.env.hprInterval(400, (360, 0, 0)) self.period_cloud.loop() self.ground = loader.loadModel("models/Ground2") self.ground.reparentTo(render) self.ground.setPos(0,0,-5) self.ground.setScale(0.5,0.5,0) self.ground_tex = loader.loadTexture("models/tex/ground.tif") self.ground.setTexture(self.ground_tex, 1) # model used as collision mesh collisionModel = loader.loadModel('models/Track2') # model used as display model model = loader.loadModel('models/Track2') tex = loader.loadTexture("models/tex/Main.png") model.setTexture(tex) # renders track from two camera views model.setTwoSided(True) collisionModel.setScale(1, 1, 100) mesh = BulletTriangleMesh() for geomNP in collisionModel.findAllMatches('**/+GeomNode'): geomNode = geomNP.node() ts = geomNP.getTransform(collisionModel) for geom in geomNode.getGeoms(): mesh.addGeom(geom, ts) shape = BulletTriangleMeshShape(mesh, dynamic=False) self.rigidNode = BulletRigidBodyNode('Heightfield') self.rigidNode.notifyCollisions(False) np = render.attachNewNode(self.rigidNode) np.node().addShape(shape) model.setScale(1, 1, .1) model.reparentTo(np) np.setScale(.7) np.setPos(0, 0, -5) np.setCollideMask(BitMask32(0xf0)) np.node().notifyCollisions(False) bulletWorld.attachRigidBody(np.node()) self.hf = np.node() # To enable/disable debug visualisation
def build_bullet_from_model(modelNP): body = BulletRigidBodyNode('...') for geomNP in modelNP.findAllMatches('**/+GeomNode'): geomNode = geomNP.node() ts = geomNode.getTransform() for geom in geomNode.getGeoms(): mesh = BulletTriangleMesh() mesh.addGeom(geom) shape = BulletTriangleMeshShape(mesh, dynamic=False) body.addShape(shape, ts) return body
def setup_world(self): self.world_node = self.render.attachNewNode('World') self.world.setGravity(Vec3(0, 0, -9.81)) # Landscape model = self.loader.loadModel("mesh/models/landscape/landscape") model.reparentTo(self.render) model.setScale(100) model.flatten_light() geom_nodes = model.findAllMatches('**/+GeomNode') geom_node = geom_nodes.getPath(0).node() geom_mesh = geom_node.getGeom(0) mesh = BulletTriangleMesh() mesh.add_geom(geom_mesh) ground_shape = BulletTriangleMeshShape(mesh, dynamic=False) ground_node = self.world_node.attachNewNode( BulletRigidBodyNode('Ground')) ground_node.node().addShape(ground_shape) ''' if self.debug_mode: debug_node_path = self.world_node.attachNewNode(BulletDebugNode('Debug')) debug_node_path.show() debug_node_path.node().showNormals(True) self.world.setDebugNode(debug_node_path.node()) ''' self.debug_node_path = self.world_node.attachNewNode( BulletDebugNode('Debug')) self.debug_node_path.hide() self.world.setDebugNode(self.debug_node_path.node()) ground_node.setPos(0, 0, 0) ground_node.setCollideMask(BitMask32.allOn()) self.world.attachRigidBody(ground_node.node()) # Character player = Player() # Other models path = 'mesh/models/bullet/pyramid' self.add_model(path, pos_x=50, pos_y=15, pos_z=370, scale=5) self.add_model(path, pos_x=30, pos_y=15, pos_z=370, scale=5) self.add_model(path, pos_x=70, pos_y=15, pos_z=390, scale=5) self.add_model(path, pos_x=50, pos_y=40, pos_z=360, scale=5) path = 'mesh/models/bullet/ball' self.add_model(path, pos_x=0, pos_y=15, pos_z=400, scale=8) self.add_model(path, pos_x=30, pos_y=40, pos_z=450, scale=8) taskMgr.add(self.update, 'updateWorld')
def __init__( self, world:BulletWorld, entity:Entity, dynamic=False, rotation=[None, None, None] ): geomNodes = entity.model.findAllMatches('**/+GeomNode') geomNode = geomNodes.getPath(0).node() geom = geomNode.getGeom(0) mesh = BulletTriangleMesh() mesh.addGeom(geom) shape = BulletTriangleMeshShape(mesh, dynamic=dynamic) super().__init__(world, entity, shape, 'mesh', rotation)
def renderObject(self,scale,hpr,collisionOn=False): (x_scale,y_scale,z_scale) = scale (h,p,r) = hpr if collisionOn is True: if self.name is 'wide_ramp': (x_c,y_c,z_c) = (x_scale + .2,y_scale+2.5,z_scale+1.75) if self.name is 'tree1': (x_c,y_c,z_c) = (x_scale,y_scale,z_scale) if self.name is 'tree2': (x_c,y_c,z_c) = (x_scale,y_scale,z_scale) if self.name is 'rock1': (x_c,y_c,z_c) = (x_scale * 2,y_scale * 2,z_scale*2) if self.name is 'rock2': (x_c,y_c,z_c) = (x_scale*100,y_scale*100,z_scale*100) if self.name is 'gate': (x_c,y_c,z_c) = (x_scale * 10,y_scale,z_scale*3.5) if self.name is 'statue': (x_c,y_c,z_c) = (x_scale,y_scale,z_scale) mesh = BulletTriangleMesh() for geomNP in self.model.findAllMatches('**/+GeomNode'): geomNode = geomNP.node() ts = geomNP.getTransform(self.model) for geom in geomNode.getGeoms(): mesh.addGeom(geom, ts) shape = BulletTriangleMeshShape(mesh, dynamic=False) node = BulletRigidBodyNode(self.name) node.setMass(0) node.addShape(shape) np = self.__game.render.attachNewNode(node) np.setPos(self.x,self.y,self.z) np.setHpr(h,p,r) np.setScale(x_c,y_c,z_c) self.__game.world.attachRigidBody(node) self.model.setPos(self.x,self.y,self.z) self.model.setHpr(h,p,r) self.model.setScale(x_scale,y_scale,z_scale) self.model.reparentTo(self.__game.render) if self.name is 'statue': plat_texture = loader.loadTexture('models/textures/rocky.jpg') self.model.setTexture(plat_texture,1) ts = TextureStage.getDefault() texture = self.model.getTexture() self.model.setTexScale(ts, 1, 1)
def modelToShape2(model): """ :type model: str :return: panda3d.bullet.BulletTriangleMeshShape """ np = loader.loadModel(model) #####componer luego mesh = BulletTriangleMesh() for geomNP in np.findAllMatches('**/+GeomNode'): geomNode = geomNP.node() ts = geomNP.getTransform(np) for geom in geomNode.getGeoms(): mesh.addGeom(geom, ts) shape = BulletTriangleMeshShape(mesh, False) return shape
def modelToShape(model, dynamic=False): """ :type model: panda3d.core.NodePath :type dynamic: bool :return: tuple(panda3d.bullet.BulletTriangleMeshShape, transform) """ geomnodes = model.findAllMatches('**/+GeomNode') transform = model.getTransform() gn = geomnodes.getPath(0).node() geom = gn.getGeom(0) mesh = BulletTriangleMesh() mesh.addGeom(geom) shape = BulletTriangleMeshShape(mesh, dynamic) return shape, transform
def createElement(self, name, type, start, end=None): if type == "cell": model_file = "sphere.dae" elif type == "bit": model_file = "box.dae" elif type == "segment" or type == "synapse": model_file = "cylinder.dae" # Create the rigid body body_node = BulletRigidBodyNode(name) body_node.setDeactivationEnabled(False) body_np = self.render.attachNewNode(body_node) body_np.setName(name) if type == "segment" or type == "synapse": # Calculate the linear distance between the start and the end position of the segment. length = (Point3(start) - Point3(end)).length() body_np.setPos(start) body_np.lookAt(end) body_np.setScale(1, length / 2, 1) else: body_np.setPos(start) # Load the 3d model file using the asset folder relative path and attach the geom node to rigid body object_np = self.loader.loadModel( Filename.from_os_specific( os.path.join(REPO_DIR, "models", model_file))) object_np.reparentTo(body_np) object_np.setPosHpr((0, 0, 0), (0, 0, 0)) object_np.setName(name + "_geom") object_np.setTexGen(TextureStage.getDefault(), TexGenAttrib.MWorldPosition) # Apply any transforms from modelling sotware to gain performance object_np.flattenStrong() # Create the shape used for collisions geom_nodes = object_np.findAllMatches("**/+GeomNode") mesh = BulletTriangleMesh() for geom in geom_nodes[0].node().getGeoms(): mesh.addGeom(geom) shape = BulletTriangleMeshShape(mesh, dynamic=True) body_node.addShape(shape) self.physics_manager.attachRigidBody(body_node) return body_np
def setupWalls(self, _obj, _eggFile): tmpMesh = BulletTriangleMesh() node = _obj.node() if node.isGeomNode(): tmpMesh.addGeom(node.getGeom(0)) else: return body = BulletRigidBodyNode("wall") body.addShape(BulletTriangleMeshShape(tmpMesh, dynamic=False)) body.setMass(0) np = self.rootNode.attachNewNode(body) np.setCollideMask(BitMask32.bit(1)) self.parent.physics_world.attachRigidBody(body)
def setupCollisionMeshAndRigidNodeFromModel(self): mesh = BulletTriangleMesh() for geomNP in self.floorModel.findAllMatches('**/+GeomNode'): geomNode = geomNP.node() ts = geomNP.getTransform(self.floorModel) for geom in geomNode.getGeoms(): mesh.addGeom(geom, ts) shape = BulletTriangleMeshShape(mesh, dynamic=False) self.rigidNode = BulletRigidBodyNode('Floor') self.rigidNode.notifyCollisions(False) self.rigidNodePath = self.parentNodePath.attachNewNode(self.rigidNode) self.rigidNodePath.node().addShape(shape) self.rigidNodePath.setScale(12, 12, 1.5) self.rigidNodePath.setCollideMask(BitMask32.allOn()) self.rigidNodePath.node().notifyCollisions(False)
def setup_collision(self, modelName): mesh = BulletTriangleMesh() geoms = GeomNode('{}'.format(modelName)) a = 0 for x in self.model.findAllMatches('**/+GeomNode').getPath( 0).node().modifyGeoms(): if a <= len(self.model.findAllMatches('**/+GeomNode')): geoms.addGeom(x) for geom in geoms.getGeoms(): mesh.addGeom(geom) shape = BulletTriangleMeshShape(mesh, dynamic=self.dynamic) self.nodePath = self.worldnp.attachNewNode( BulletRigidBodyNode('{}'.format(self.model))) self.nodePath.node().addShape(shape) self.model.reparentTo(self.nodePath) self.model.setPos(self.nodePath.getPos())
def __init__(self, app, map_name): map_file = 'assets/maps/{}/{}.bam'.format(map_name, map_name) self.app = app self.physics_world = BulletWorld() node = BulletRigidBodyNode('Ground') self.np = self.app.render.attach_new_node(node) self.np.setPos(0, 0, 0) self.physics_world.attachRigidBody(node) self.model = loader.load_model(map_file) self.model.reparent_to(self.np) self.env_data = EnvironmentData(self.model, map_name, 'maps') self.physics_world.setGravity(self.env_data.gravity) sky = self.model.find(SKYSPHERE) sky.reparent_to(base.cam) sky.set_bin('background', 0) sky.set_depth_write(False) sky.set_compass() sky.set_light_off() # Bullet collision mesh collision_solids = self.model.find_all_matches( '{}*'.format(TERRAIN_COLLIDER) ) #collision_solids.hide() for collision_solid in collision_solids: collision_solid.flatten_strong() for geom_node in collision_solid.find_all_matches('**/+GeomNode'): mesh = BulletTriangleMesh() for geom in geom_node.node().get_geoms(): mesh.addGeom(geom) shape = BulletTriangleMeshShape(mesh, dynamic=False) terrain_node = BulletRigidBodyNode('terrain') terrain_node.add_shape(shape) terrain_node.set_friction(self.env_data.friction) terrain_np = geom_node.attach_new_node(terrain_node) terrain_np.set_collide_mask(CM_TERRAIN | CM_COLLIDE) self.physics_world.attach_rigid_body(terrain_node)
def createPlatform(self, x, y, z): self.platform = loader.loadModel('../models/disk/disk.egg') geomnodes = self.platform.findAllMatches('**/+GeomNode') gn = geomnodes.getPath(0).node() geom = gn.getGeom(0) mesh = BulletTriangleMesh() mesh.addGeom(geom) shape = BulletTriangleMeshShape(mesh, dynamic=False) node = BulletRigidBodyNode('Platform') node.setMass(0) node.addShape(shape) platformnn = render.attachNewNode(node) platformnn.setPos(x, y, z) platformnn.setScale(3) self.world.attachRigidBody(node) self.platform.reparentTo(platformnn)
def createWall(self, x, y, z, h): self.wall = loader.loadModel('../models/wall/wall.egg') geomnodes = self.wall.findAllMatches('**/+GeomNode') gn = geomnodes.getPath(0).node() geom = gn.getGeom(0) mesh = BulletTriangleMesh() mesh.addGeom(geom) shape = BulletTriangleMeshShape(mesh, dynamic=False) wallNode = BulletRigidBodyNode('Wall') wallNode.setMass(0) wallNode.addShape(shape) wallnn = render.attachNewNode(wallNode) wallnn.setPos(x, y, z) wallnn.setH(h) wallnn.setScale(0.5, 50.5, 4.5) self.world.attachRigidBody(wallNode) self.wall.reparentTo(wallnn)
def __addTriangleMesh(self, body, model, pos=(0,0,0), hpr=(0,0,0), scale=(1,1,1), dynamic=True): mesh = BulletTriangleMesh() def one(): geom = model.node().getGeom(0) mesh.addGeom(geom) return [] children = model.findAllMatches('**/+GeomNode') or one() model.flattenLight() for piece in children: geom = piece.node().getGeom(0) mesh.addGeom(geom) shape = BulletTriangleMeshShape(mesh, dynamic=dynamic ) body.addShape( shape, TransformState.makePosHprScale(pos,hpr,scale) )
def _createBulletShape_(self,np, apply_scale = True, apply_transform = True): """ @brief Creates a BulletTriangleMeshShape from the geometries in the model node. The passed node path must point to a GeomNode type. The Geom objects are then added to a BulletTriangleMesh object which is then used to initialize the Shape. Optionally, the node's transform and scaled can be baked into the Geometries (recommended according to the Panda3D guide https://www.panda3d.org/manual/index.php/Bullet_FAQ). If you apply the scale and transform make sure not to apply them again to the shape or the bullet node that contains the shape as it'll compound the effect. @warning: If the underlying GeomNode contains multiple geometries each with a different transform and scale then it's best to set apply_scale and apply_transform to True. @param np: The nodepath containing the GeomNode @param apply_scale: Boolean that allows choosing whether or not to apply the nodepath's scale to the geometries @param apply_transform: Boolean that indicates whether or not to apply the nodepath's trasform to the geometries. @return: A BulletTriangleMeshShape object containing the node's geometries """ geom_node = np.node() if type(geom_node) is not GeomNode: logging.error("Node %s is not a GeomNode node type"%(np.getName())) return None bullet_mesh = BulletTriangleMesh() # Assembling transform tr = TransformState.makeIdentity() geom_scale = np.getScale() if apply_transform: tr = tr.setPos(np.getPos()) tr = tr.setQuat(np.getQuat()) sc = LPoint3(1) tr = tr.setScale(sc) if apply_scale: # baking scale into geometry data tr = tr.setScale(geom_scale) for geom in geom_node.getGeoms(): bullet_mesh.addGeom(geom,True,tr) bullet_shape = BulletTriangleMeshShape(bullet_mesh,False,True,True) bullet_shape.setMargin(GameObject.DEFAULT_COLLISION_MARGIN) return bullet_shape
def _create_bullet_nodepath(geom, geom_node, entity): bullet_node = BulletRigidBodyNode("NavmeshCollision") transform = geom_node.getTransform() mesh = BulletTriangleMesh() mesh.addGeom(geom, True, transform) shape = BulletTriangleMeshShape(mesh, dynamic=False) bullet_node.addShape(shape) mask = BitMask32() mask.set_word(CollisionGroups.navmesh) bullet_node.set_into_collide_mask(mask) # Associate with entity bullet_nodepath = base.render.attachNewNode(bullet_node) bullet_nodepath.set_python_tag("entity", entity) return bullet_nodepath
def addPhysicsObject(self, model, objectType): """Adds a physical object to the level The object isn't linked with a graphical object """ if objectType == "barrier": # Use a triangle mesh to represent the barrier as # it could be concave mesh = BulletTriangleMesh() mesh.addGeom(model.node().getGeom(0)) shape = BulletTriangleMeshShape(mesh, dynamic=False) rigidNode = BulletRigidBodyNode("barrier") rigidNode.addShape(shape) self.physicsWorld.attachRigidBody(rigidNode) # Set the position from the model pNode = self.outsideWorldRender.attachNewNode(rigidNode) pNode.setPos(model.getPos()) else: raise ValueError("Invalid physics object type: %s" % objectType)
def genCollisionMeshGeom(geom, name='autogen'): """ generate the collision mesh of a nodepath using geom :param geom: the panda3d geom of the object :param basenodepath: the nodepath to compute relative transform :return: bulletrigidbody author: weiwei date: 20161212, tsukuba """ geomtf = TransformState.makeIdentity() geombullmesh = BulletTriangleMesh() geombullmesh.addGeom(geom) geombullnode = BulletRigidBodyNode(name) bullettmshape = BulletTriangleMeshShape(geombullmesh, dynamic=True) bullettmshape.setMargin(0) geombullnode.addShape(bullettmshape, geomtf) return geombullnode
def __init__(self, bulletWorld): self.sky = SkyDome() # model used as collision mesh collisionModel = loader.loadModel('models/walledTrack') # model used as display model model = loader.loadModel('models/FullTrack') tex = loader.loadTexture("models/tex/Main.png") ts = TextureStage('ts') ts.setMode(TextureStage.MBlend) model.setTexture(ts, tex, 2) #model.setTexScale(ts, 70) # renders track from two camera views model.setTwoSided(True) mesh = BulletTriangleMesh() for geomNP in collisionModel.findAllMatches('**/+GeomNode'): geomNode = geomNP.node() ts = geomNP.getTransform(collisionModel) for geom in geomNode.getGeoms(): mesh.addGeom(geom, ts) shape = BulletTriangleMeshShape(mesh, dynamic=False) self.rigidNode = BulletRigidBodyNode('Track') self.rigidNode.notifyCollisions(False) np = render.attachNewNode(self.rigidNode) np.node().addShape(shape) model.reparentTo(np) np.setScale(70) np.setPos(0, 0, -5) np.setCollideMask(BitMask32(0xf0)) np.node().notifyCollisions(False) bulletWorld.attachRigidBody(np.node()) self.hf = np.node() # To enable/disable debug visualisation
def createEnvironment(self): self.environ = loader.loadModel("models/square") self.environ.reparentTo(render) self.environ.setPos(0, 0, 0) self.environ.setScale(500, 500, 1) self.moon_tex = loader.loadTexture("models/moon_1k_tex.jpg") self.environ.setTexture(self.moon_tex, 1) shape = BulletPlaneShape(Vec3(0, 0, 1), 0) node = BulletRigidBodyNode('Ground') node.addShape(shape) np = render.attachNewNode(node) np.setPos(0, 0, 0) self.bulletWorld.attachRigidBody(node) self.visNP = loader.loadModel('models/track.egg') self.tex = loader.loadTexture("models/tex/Main.png") self.visNP.setTexture(self.tex) geom = self.visNP.findAllMatches('**/+GeomNode').getPath(0).node().getGeom(0) mesh = BulletTriangleMesh() mesh.addGeom(geom) trackShape = BulletTriangleMeshShape(mesh, dynamic=False) body = BulletRigidBodyNode('Bowl') self.visNP.node().getChild(0).addChild(body) bodyNP = render.anyPath(body) bodyNP.node().addShape(trackShape) bodyNP.node().setMass(0.0) bodyNP.setTexture(self.tex) self.bulletWorld.attachRigidBody(bodyNP.node()) self.visNP.reparentTo(render) self.bowlNP = bodyNP self.visNP.setScale(70)
def create_object(self): from panda3d.core import Filename, NodePath, BitMask32 from panda3d.bullet import BulletRigidBodyNode, BulletTriangleMesh, BulletTriangleMeshShape from game_system.resources import ResourceManager f = Filename.fromOsSpecific(ResourceManager.get_absolute_path(ResourceManager["Map"]["map.egg"])) model = loader.loadModel(f) bullet_node = BulletRigidBodyNode("MapCollision") bullet_nodepath = NodePath(bullet_node) mesh = BulletTriangleMesh() for geomNP in model.findAllMatches('**/+GeomNode'): geomNode = geomNP.node() ts = geomNode.getTransform() for geom in geomNode.getGeoms(): mesh.addGeom(geom, True, ts) shape = BulletTriangleMeshShape(mesh, dynamic=False) bullet_node.addShape(shape) bullet_nodepath.set_collide_mask(BitMask32.bit(0)) model.reparentTo(bullet_nodepath) return bullet_nodepath
def __init__(self, render, world, x, y, z): self.movingPlatform = loader.loadModel('../models/square-flat/square.egg') geomnodes = self.movingPlatform.findAllMatches('**/+GeomNode') gn = geomnodes.getPath(0).node() geom = gn.getGeom(0) mesh = BulletTriangleMesh() mesh.addGeom(geom) shape = BulletTriangleMeshShape(mesh, dynamic=False) self.node = BulletRigidBodyNode('MovingPlatform') self.node.setMass(0) self.node.addShape(shape) self.movingPlatformnn = render.attachNewNode(self.node) self.movingPlatformnn.setPos(x, y, z) self.movingPlatformnn.setScale(9, 7, 0.5) world.attachRigidBody(self.node) self.movingPlatform.reparentTo(self.movingPlatformnn) # Associates movingPlatformnn with movingPlatform self.movingPlatformnn.setPythonTag("movingPlatformNP", self.movingPlatform) # Create a sequence of intervals and play them together using parallel downInterval = self.movingPlatformnn.posInterval(3, Point3(x, y, z), startPos=Point3(x, y, z + 15)) upInterval = self.movingPlatformnn.posInterval(3, Point3(x, y, z + 15), startPos=Point3(x, y, z)) # To randomize a little, take x position of platform. If it's even move downward. If it's odd, upward if x % 2 == 0: elevate = Sequence(downInterval, upInterval, name="elevate") else: elevate = Sequence(upInterval, downInterval, name="elevateOpposite") elevateParallel = Parallel() elevateParallel.append(elevate) elevateParallel.loop()
def buildTriangleMesh(cls, _engine, _obj, _levelEgg, _mass=0, _isDynamic=False): """Build a bullet TriangleMesh for objects""" mesh = BulletTriangleMesh() node = _obj.node() if node.isGeomNode(): mesh.addGeom(node.getGeom(0)) else: return body = BulletRigidBodyNode(_obj.getTag("level"))#+str(_obj.getTag("id"))) body.addShape(BulletTriangleMeshShape(mesh, dynamic=_isDynamic)) body.setMass(_mass) np = _engine.BulletObjects["level"].attachNewNode(body) #np.setCollideMask(BitMask32.allOn()) np.setScale(_obj.getScale(_levelEgg)) np.setPos(_obj.getPos(_levelEgg)) np.setHpr(_obj.getHpr(_levelEgg)) _engine.bulletWorld.attachRigidBody(body) return np
def makeSB(): body = BulletRigidBodyNode('...') geomNodeCollection = loader.loadModel('out2.egg').findAllMatches('**/+GeomNode') for geomNP in geomNodeCollection: geomNode = geomNP.node() ts = geomNode.getTransform() mesh = BulletTriangleMesh() for geom in geomNode.getGeoms(): mesh.addGeom(geom) shape = BulletTriangleMeshShape(mesh, dynamic=True) body.addShape(shape, ts) body.addChild(geomNode) #world.attachRigidBody(node) #body.copyTo(np) body.setMass(100.0) world.attachRigidBody(body) np1 = render.attachNewNode(body) np1.setPos(0, 0, 10) np1.setHpr(0,0,90) np1.setScale(0.5,0.5,0.5) print(body.getNumChildren()) return body #body = makeSB() # Update #taskMgr.add(update, 'update') #run()
def createLetter(self, loadFile, name, x, y, z): self.name = name self.letter = loader.loadModel(loadFile) geomnodes = self.letter.findAllMatches('**/+GeomNode') gn = geomnodes.getPath(0).node() geom = gn.getGeom(0) mesh = BulletTriangleMesh() mesh.addGeom(geom) shape = BulletTriangleMeshShape(mesh, dynamic=False) self.letterNode = BulletRigidBodyNode('Letter') self.letterNode.setMass(0) self.letterNode.addShape(shape) self.letters.append(self.letterNode) letternn = render.attachNewNode(self.letterNode) letternn.setPos(x, y, z) letternn.setScale(1) letternn.setP(90) # orients the mesh for the letters to be upright self.world.attachRigidBody(self.letterNode) self.letter.reparentTo(letternn) self.letter.setP(-90) # orients the actual letter objects to be upright
def setup(self): self.worldNP = render.attachNewNode('World') # World self.debugNP = self.worldNP.attachNewNode(BulletDebugNode('Debug')) self.debugNP.show() self.debugNP.node().showWireframe(True) self.debugNP.node().showConstraints(True) self.debugNP.node().showBoundingBoxes(False) self.debugNP.node().showNormals(False) self.world = BulletWorld() self.world.setGravity(Vec3(0, 0, -9.81)) self.world.setDebugNode(self.debugNP.node()) # Ground shape = BulletPlaneShape(Vec3(0, 0, 1), 0) body = BulletRigidBodyNode('Ground') bodyNP = self.worldNP.attachNewNode(body) bodyNP.node().addShape(shape) bodyNP.setPos(0, 0, 0) bodyNP.setCollideMask(BitMask32.allOn()) self.world.attachRigidBody(bodyNP.node()) # Bowl visNP = loader.loadModel('models/bowl.egg') geom = visNP.findAllMatches('**/+GeomNode').getPath(0).node().getGeom(0) mesh = BulletTriangleMesh() mesh.addGeom(geom) shape = BulletTriangleMeshShape(mesh, dynamic=True) body = BulletRigidBodyNode('Bowl') bodyNP = self.worldNP.attachNewNode(body) bodyNP.node().addShape(shape) bodyNP.node().setMass(10.0) bodyNP.setPos(0, 0, 0) bodyNP.setCollideMask(BitMask32.allOn()) self.world.attachRigidBody(bodyNP.node()) visNP.reparentTo(bodyNP) self.bowlNP = bodyNP self.bowlNP.setScale(2) # Eggs self.eggNPs = [] for i in range(5): x = random.gauss(0, 0.1) y = random.gauss(0, 0.1) z = random.gauss(0, 0.1) + 1 h = random.random() * 360 p = random.random() * 360 r = random.random() * 360 visNP = loader.loadModel('models/egg.egg') geom = visNP.findAllMatches('**/+GeomNode').getPath(0).node().getGeom(0) shape = BulletConvexHullShape() shape.addGeom(geom) body = BulletRigidBodyNode('Egg-%i' % i) bodyNP = self.worldNP.attachNewNode(body) bodyNP.node().setMass(1.0) bodyNP.node().addShape(shape) bodyNP.node().setDeactivationEnabled(False) bodyNP.setCollideMask(BitMask32.allOn()) bodyNP.setPosHpr(x, y, z, h, p, r) #bodyNP.setScale(1.5) self.world.attachRigidBody(bodyNP.node()) visNP.reparentTo(bodyNP) self.eggNPs.append(bodyNP)
def setup(self): self.worldNP = render.attachNewNode('World') # World self.debugNP = self.worldNP.attachNewNode(BulletDebugNode('Debug')) self.debugNP.show() self.world = BulletWorld() self.world.setGravity(Vec3(0, 0, -9.81)) self.world.setDebugNode(self.debugNP.node()) # Ground p0 = Point3(-20, -20, 0) p1 = Point3(-20, 20, 0) p2 = Point3(20, -20, 0) p3 = Point3(20, 20, 0) mesh = BulletTriangleMesh() mesh.addTriangle(p0, p1, p2) mesh.addTriangle(p1, p2, p3) shape = BulletTriangleMeshShape(mesh, dynamic=False) np = self.worldNP.attachNewNode(BulletRigidBodyNode('Mesh')) np.node().addShape(shape) np.setPos(0, 0, -4) np.setCollideMask(BitMask32.allOn()) self.world.attachRigidBody(np.node()) # Soft body world information info = self.world.getWorldInfo() info.setAirDensity(1.2) info.setWaterDensity(0) info.setWaterOffset(0) info.setWaterNormal(Vec3(0, 0, 0)) # Softbody - From points/indices #import cube #points = [Point3(x,y,z) * 3 for x,y,z in cube.nodes] #indices = sum([list(x) for x in cube.elements], []) #node = BulletSoftBodyNode.makeTetMesh(info, points, indices, True) #node.setVolumeMass(300); #node.getShape(0).setMargin(0.01) #node.getMaterial(0).setLinearStiffness(0.8) #node.getCfg().setPositionsSolverIterations(1) #node.getCfg().clearAllCollisionFlags() #node.getCfg().setCollisionFlag(BulletSoftBodyConfig.CFClusterSoftSoft, True) #node.getCfg().setCollisionFlag(BulletSoftBodyConfig.CFClusterRigidSoft, True) #node.generateClusters(16) #softNP = self.worldNP.attachNewNode(node) #softNP.setPos(0, 0, 8) #softNP.setHpr(0, 0, 45) #self.world.attachSoftBody(node) # Softbody - From tetgen data ele = file('models/cube/cube.1.ele', 'r').read() face = file('models/cube/cube.1.face', 'r').read() node = file('models/cube/cube.1.node', 'r').read() node = BulletSoftBodyNode.makeTetMesh(info, ele, face, node) node.setName('Tetra') node.setVolumeMass(300) node.getShape(0).setMargin(0.01) node.getMaterial(0).setLinearStiffness(0.1) node.getCfg().setPositionsSolverIterations(1) node.getCfg().clearAllCollisionFlags() node.getCfg().setCollisionFlag(BulletSoftBodyConfig.CFClusterSoftSoft, True) node.getCfg().setCollisionFlag(BulletSoftBodyConfig.CFClusterRigidSoft, True) node.generateClusters(6) softNP = self.worldNP.attachNewNode(node) softNP.setPos(0, 0, 8) softNP.setHpr(45, 0, 0) self.world.attachSoftBody(node) # Option 1: visNP = loader.loadModel('models/cube/cube.egg') visNP.reparentTo(softNP) geom = visNP \ .findAllMatches('**/+GeomNode').getPath(0).node() \ .modifyGeom(0) node.linkGeom(geom)
def setup(self): self.worldNP = render.attachNewNode('World') # World self.debugNP = self.worldNP.attachNewNode(BulletDebugNode('Debug')) self.debugNP.show() self.world = BulletWorld() self.world.setGravity(Vec3(0, 0, -9.81)) self.world.setDebugNode(self.debugNP.node()) # Ground p0 = Point3(-20, -20, 0) p1 = Point3(-20, 20, 0) p2 = Point3(20, -20, 0) p3 = Point3(20, 20, 0) mesh = BulletTriangleMesh() mesh.addTriangle(p0, p1, p2) mesh.addTriangle(p1, p2, p3) shape = BulletTriangleMeshShape(mesh, dynamic=False) np = self.worldNP.attachNewNode(BulletRigidBodyNode('Mesh')) np.node().addShape(shape) np.setPos(0, 0, -2) np.setCollideMask(BitMask32.allOn()) self.world.attachRigidBody(np.node()) # Soft body world information info = self.world.getWorldInfo() info.setAirDensity(1.2) info.setWaterDensity(0) info.setWaterOffset(0) info.setWaterNormal(Vec3(0, 0, 0)) # Softbody def makeSB(pos, hpr): import torus geom = torus.makeGeom() #geom = loader.loadModel('models/torus.egg') \ # .findAllMatches('**/+GeomNode').getPath(0).node() \ # .modifyGeom(0) geomNode = GeomNode('') geomNode.addGeom(geom) node = BulletSoftBodyNode.makeTriMesh(info, geom) node.linkGeom(geomNode.modifyGeom(0)) node.generateBendingConstraints(2) node.getCfg().setPositionsSolverIterations(2) node.getCfg().setCollisionFlag(BulletSoftBodyConfig.CFVertexFaceSoftSoft, True) node.randomizeConstraints() node.setTotalMass(50, True) softNP = self.worldNP.attachNewNode(node) softNP.setPos(pos) softNP.setHpr(hpr) self.world.attachSoftBody(node) geomNP = softNP.attachNewNode(geomNode) makeSB(Point3(-3, 0, 4), (0, 0, 0)) makeSB(Point3(0, 0, 4), (0, 90, 90)) makeSB(Point3(3, 0, 4), (0, 0, 0))
def setup(self): # Debug (useful to turn on for physics) self.debugNP = self.render.attachNewNode(BulletDebugNode('Debug')) self.debugNP.hide() # Physics World self.world = BulletWorld() self.world.setGravity(Vec3(0, 0, -9.81)) self.world.setDebugNode(self.debugNP.node()) # Main Character self.player = Player() self.player.createPlayer(render, self.world) # Enemies self.createEnemies() # Music self.backgroundMusic = loader.loadSfx('../sounds/elfman-piano-solo.ogg') self.backgroundMusic.setLoop(True) self.backgroundMusic.stop() self.backgroundMusic.setVolume(0.9) # lower this when I add sound effects # Sound Effects self.collect = base.loader.loadSfx("../sounds/collect-sound.wav") self.collect.setVolume(1) self.damage = base.loader.loadSfx("../sounds/damage.wav") self.damage.setVolume(0.5) self.winner = base.loader.loadSfx("../sounds/win-yay.wav") self.winner.setVolume(1) self.dead = base.loader.loadSfx("../sounds/severe-damage.wav") self.dead.setVolume(1) # Level 1 Skybox self.skybox = loader.loadModel('../models/skybox_galaxy.egg') self.skybox.setScale(1000) # make big enough to cover whole terrain self.skybox.setBin('background', 1) self.skybox.setDepthWrite(0) self.skybox.setLightOff() self.skybox.reparentTo(render) # Lighting dLight = DirectionalLight("dLight") dLight.setColor(Vec4(0.8, 0.8, 0.5, 1)) dLight.setDirection(Vec3(-5, -5, -5)) dlnp = render.attachNewNode(dLight) dlnp.setHpr(0, 60, 0) render.setLight(dlnp) aLight = AmbientLight("aLight") aLight.setColor(Vec4(0.5, 0.5, 0.5, 1)) alnp = render.attachNewNode(aLight) render.setLight(alnp) # Fog colour = (0.2, 0.2, 0.3) genfog = Fog("general fog") genfog.setColor(*colour) genfog.setExpDensity(0.003) render.setFog(genfog) base.setBackgroundColor(*colour) # Create wall (x, y, z, h) self.createWall(-30.2215, -6.2, -2, 45) self.createWall(-203, 555.8, -2, 70) #-----Level 1 Platforms----- # Platform to collect B self.createPlatform(72, 70.2927, -1) # Platforms to collect R self.createPlatform(211, 210, -1) self.createPlatform(225, 223, 2.7) # Platforms to collect E and A self.createPlatform(330, 462, -0.4) self.createPlatform(340, 471, 2.1) self.createPlatform(350, 480, 4) self.createPlatform(335, 483, 5) # Platforms to collect K self.createPlatform(184, 712, -1) self.createPlatform(208, 730, -1) self.createPlatform(207, 711, -1) self.createPlatform(186, 731, -1) #-----Level 2 Platforms----- # Moving platforms if self.movingPlatforms > 0: del self.movingPlatforms[:] self.createMovingPlatforms() # Create complex mesh for Track using BulletTriangleMeshShape mesh = BulletTriangleMesh() self.track = loader.loadModel("../models/mountain_valley_track.egg") self.track.flattenStrong() for geomNP in self.track.findAllMatches('**/+GeomNode'): geomNode = geomNP.node() ts = geomNP.getTransform(self.track) for geom in geomNode.getGeoms(): mesh.addGeom(geom, ts) shape = BulletTriangleMeshShape(mesh, dynamic=False) node = BulletRigidBodyNode('Track') node.setMass(0) node.addShape(shape) tracknn = render.attachNewNode(node) self.world.attachRigidBody(tracknn.node()) tracknn.setPos(27, -5, -2) self.track.reparentTo(tracknn)
def planContactpairs(self, torqueresist = 50, fgrtipdist = 82): """ find the grasps using parallel pairs :param: torqueresist the maximum allowable distance to com :param: fgrtipdist the maximum dist between finger tips :return: author: weiwei date: 20161130, harada office @ osaka university """ # note that pairnormals and pairfacets are duplicated for each contactpair # the duplication is performed on purpose for convenient access # also, each contactpair"s" corresponds to a facetpair # it is empty when no contactpair is available self.gripcontactpairs = [] # gripcontactpairnormals and gripcontactpairfacets are not helpful # they are kept for convenience (they could be accessed using facetnormals and facetpairs) self.gripcontactpairnormals = [] self.gripcontactpairfacets = [] # for precollision detection # bulletworldprecc = BulletWorld() # # build the collision shape of objtrimesh # geomobj = pandageom.packpandageom(self.objtrimesh.vertices, self.objtrimesh.face_normals, # self.objtrimesh.faces) # objmesh = BulletTriangleMesh() # objmesh.addGeom(geomobj) # objmeshnode = BulletRigidBodyNode('objmesh') # objmeshnode.addShape(BulletTriangleMeshShape(objmesh, dynamic=True)) # bulletworldprecc.attachRigidBody(objmeshnode) # for raytracing bulletworldray = BulletWorld() nfacets = self.facets.shape[0] self.facetpairs = list(itertools.combinations(range(nfacets), 2)) for facetpair in self.facetpairs: # print "facetpair" # print facetpair, len(self.facetpairs) self.gripcontactpairs.append([]) self.gripcontactpairnormals.append([]) self.gripcontactpairfacets.append([]) # if one of the facet doesnt have samples, jump to next if self.objsamplepnts_refcls[facetpair[0]].shape[0] is 0 or \ self.objsamplepnts_refcls[facetpair[1]].shape[0] is 0: # print "no sampled points" continue # check if the faces are opposite and parallel dotnorm = np.dot(self.facetnormals[facetpair[0]], self.facetnormals[facetpair[1]]) if dotnorm < -0.95: # check if any samplepnts's projection from facetpairs[i][0] falls in the polygon of facetpairs[i][1] facet0pnts = self.objsamplepnts_refcls[facetpair[0]] facet0normal = self.facetnormals[facetpair[0]] facet1normal = self.facetnormals[facetpair[1]] # generate collision mesh facetmesh = BulletTriangleMesh() faceidsonfacet = self.facets[facetpair[1]] geom = pandageom.packpandageom(self.objtrimesh.vertices, self.objtrimesh.face_normals[faceidsonfacet], self.objtrimesh.faces[faceidsonfacet]) facetmesh.addGeom(geom) facetmeshbullnode = BulletRigidBodyNode('facet') facetmeshbullnode.addShape(BulletTriangleMeshShape(facetmesh, dynamic=True)) bulletworldray.attachRigidBody(facetmeshbullnode) # check the projection of a ray for facet0pnt in facet0pnts: pFrom = Point3(facet0pnt[0], facet0pnt[1], facet0pnt[2]) pTo = pFrom + Vec3(facet1normal[0], facet1normal[1], facet1normal[2])*9999 result = bulletworldray.rayTestClosest(pFrom, pTo) if result.hasHit(): hitpos = result.getHitPos() if np.linalg.norm(np.array(facet0pnt.tolist())-np.array([hitpos[0], hitpos[1], hitpos[2]])) < fgrtipdist: fgrcenter = (np.array(facet0pnt.tolist())+np.array([hitpos[0], hitpos[1], hitpos[2]]))/2.0 # avoid large torque if np.linalg.norm(self.objtrimesh.center_mass - fgrcenter) < torqueresist: self.gripcontactpairs[-1].append([facet0pnt.tolist(), [hitpos[0], hitpos[1], hitpos[2]]]) self.gripcontactpairnormals[-1].append([[facet0normal[0], facet0normal[1], facet0normal[2]], [facet1normal[0], facet1normal[1], facet1normal[2]]]) self.gripcontactpairfacets[-1].append(facetpair) # pre collision checking: it takes one finger as a cylinder and # computes its collision with the object ## first finger # cylindernode0 = BulletRigidBodyNode('cylindernode0') # cylinder0height = 50 # cylinder0normal = Vec3(facet0normal[0], facet0normal[1], facet0normal[2]) # cylindernode0.addShape(BulletCylinderShape(radius=self.preccradius, # height=cylinder0height, # up=cylinder0normal), # TransformState.makePos(pFrom+cylinder0normal*cylinder0height*.6)) # bulletworldprecc.attachRigidBody(cylindernode0) # ## second finger # cylindernode1 = BulletRigidBodyNode('cylindernode1') # cylinder1height = cylinder1height # # use the inverse of facet0normal instead of facet1normal to follow hand orientation # cylinder1normal = Vec3(-facet0normal[0], -facet0normal[1], -facet0normal[2]) # cylindernode1.addShape(BulletCylinderShape(radius=self.preccradius, # height=cylinder1height, # up=cylinder1normal), # TransformState.makePos(pFrom+cylinder1normal*cylinder1height*.6)) # bulletworldprecc.attachRigidBody(cylindernode1) # if bulletworldprecc.contactTestPair(cylindernode0, objmeshnode) and \ # bulletworldprecc.contactTestPair(cylindernode1, objmeshnode): bulletworldray.removeRigidBody(facetmeshbullnode) # update the pairs availablepairids = np.where(self.gripcontactpairs)[0] self.facetpairs = np.array(self.facetpairs)[availablepairids] self.gripcontactpairs = np.array(self.gripcontactpairs)[availablepairids] self.gripcontactpairnormals = np.array(self.gripcontactpairnormals)[availablepairids] self.gripcontactpairfacets = np.array(self.gripcontactpairfacets)[availablepairids]
def setup(self): self.worldNP = render.attachNewNode('World') # World self.debugNP = self.worldNP.attachNewNode(BulletDebugNode('Debug')) self.debugNP.show() #self.debugNP.showTightBounds() #self.debugNP.showBounds() self.world = BulletWorld() self.world.setGravity(Vec3(0, 0, -9.81)) self.world.setDebugNode(self.debugNP.node()) # Ground p0 = Point3(-20, -20, 0) p1 = Point3(-20, 20, 0) p2 = Point3(20, -20, 0) p3 = Point3(20, 20, 0) mesh = BulletTriangleMesh() mesh.addTriangle(p0, p1, p2) mesh.addTriangle(p1, p2, p3) shape = BulletTriangleMeshShape(mesh, dynamic=False) np = self.worldNP.attachNewNode(BulletRigidBodyNode('Mesh')) np.node().addShape(shape) np.setPos(0, 0, -2) np.setCollideMask(BitMask32.allOn()) self.world.attachRigidBody(np.node()) # Stair origin = Point3(0, 0, 0) size = Vec3(2, 10, 1) shape = BulletBoxShape(size * 0.5) for i in range(10): pos = origin + size * i pos.setY(0) np = self.worldNP.attachNewNode(BulletRigidBodyNode('Stair%i' % i)) np.node().addShape(shape) np.setPos(pos) np.setCollideMask(BitMask32.allOn()) npV = loader.loadModel('models/box.egg') npV.reparentTo(np) npV.setScale(size) self.world.attachRigidBody(np.node()) # Soft body world information info = self.world.getWorldInfo() info.setAirDensity(1.2) info.setWaterDensity(0) info.setWaterOffset(0) info.setWaterNormal(Vec3(0, 0, 0)) # Softbody center = Point3(0, 0, 0) radius = Vec3(1, 1, 1) * 1.5 node = BulletSoftBodyNode.makeEllipsoid(info, center, radius, 128) node.setName('Ellipsoid') node.getMaterial(0).setLinearStiffness(0.1) node.getCfg().setDynamicFrictionCoefficient(1) node.getCfg().setDampingCoefficient(0.001) node.getCfg().setPressureCoefficient(1500) node.setTotalMass(30, True) node.setPose(True, False) np = self.worldNP.attachNewNode(node) np.setPos(15, 0, 12) #np.setH(90.0) #np.showBounds() #np.showTightBounds() self.world.attachSoftBody(np.node()) geom = BulletHelper.makeGeomFromFaces(node) node.linkGeom(geom) nodeV = GeomNode('EllipsoidVisual') nodeV.addGeom(geom) npV = np.attachNewNode(nodeV)