def makeGeom(): # Vertex data fmt = GeomVertexFormat.getV3n3t2() vdata = GeomVertexData('', fmt, Geom.UHStatic) vertex = GeomVertexWriter(vdata, InternalName.getVertex()) normal = GeomVertexWriter(vdata, InternalName.getNormal()) texcoord = GeomVertexWriter(vdata, InternalName.getTexcoord()) for (x, y, z) in vertices: vertex.addData3f(x, y, z) normal.addData3f(0, 0, 0) # Privitive prim = GeomTriangles(Geom.UHStatic) for (i1, i2, i3) in indices: prim.addVertices(i1, i2, i3) prim.closePrimitive() # Geom geom = Geom(vdata) geom.addPrimitive(prim) return geom
def makeGeom(): # Vertex data fmt = GeomVertexFormat.getV3n3t2() vdata = GeomVertexData('', fmt, Geom.UHStatic) vertex = GeomVertexWriter(vdata, InternalName.getVertex()) normal = GeomVertexWriter(vdata, InternalName.getNormal()) texcoord = GeomVertexWriter(vdata, InternalName.getTexcoord()) for (x, y, z) in vertices: vertex.addData3f(x, y, z) normal.addData3f(0, 0, 0) # Privitive prim = GeomTriangles(Geom.UHStatic) for (i1, i2, i3) in indices: prim.addVertices(i1, i2, i3) prim.closePrimitive() # Geom geom = Geom(vdata) geom.addPrimitive(prim) return geom
def makeSprite(name, texture, scale, add = False): from panda3d.core import (GeomVertexFormat, GeomVertexData, GeomEnums, InternalName, GeomVertexWriter, GeomPoints, Geom, GeomNode, NodePath, TextureStage, TexGenAttrib, BoundingSphere) format = GeomVertexFormat.getV3() data = GeomVertexData(name + "_data", format, GeomEnums.UHStatic) writer = GeomVertexWriter(data, InternalName.getVertex()) writer.addData3f((0, 0, 0)) primitive = GeomPoints(GeomEnums.UHStatic) primitive.addVertex(0) primitive.closePrimitive() geom = Geom(data) geom.addPrimitive(primitive) geomNode = GeomNode(name) geomNode.addGeom(geom) np = NodePath(geomNode) np.setLightOff(1) np.setMaterialOff(1) np.setRenderModePerspective(True) ts = TextureStage('sprite') if add: ts.setMode(TextureStage.MAdd) np.setTexture(ts, texture) np.setTexGen(ts, TexGenAttrib.MPointSprite) np.setDepthWrite(False) np.setDepthOffset(1) np.setTransparency(True) np.node().setBounds(BoundingSphere((0, 0, 0), 1)) np.node().setFinal(True) np.flattenStrong() np.setScale(scale) return np
def begin(self, numVerts): self.vertexBuffer.uncleanSetNumRows(numVerts) for view in self.views: view.clear() self.vwriter = GeomVertexWriter(self.vertexBuffer, InternalName.getVertex()) self.twriter = GeomVertexWriter(self.vertexBuffer, InternalName.getTexcoord()) self.nwriter = GeomVertexWriter(self.vertexBuffer, InternalName.getNormal())
def getFaceFormat(): global FaceFormat if not FaceFormat: arr = GeomVertexArrayFormat() arr.addColumn(InternalName.getVertex(), 3, GeomEnums.NTStdfloat, GeomEnums.CPoint) arr.addColumn(InternalName.getNormal(), 3, GeomEnums.NTStdfloat, GeomEnums.CNormal) arr.addColumn(InternalName.getTangent(), 3, GeomEnums.NTStdfloat, GeomEnums.CVector) arr.addColumn(InternalName.getBinormal(), 3, GeomEnums.NTStdfloat, GeomEnums.CVector) arr.addColumn(InternalName.getTexcoord(), 2, GeomEnums.NTStdfloat, GeomEnums.CTexcoord) FaceFormat = GeomVertexFormat.registerFormat(arr) return FaceFormat
def pandageom_from_points(vertices, rgba_list=None, name=''): """ pack the vertices into a panda3d point cloud geom :param vertices: :param rgba_list: a list with a single 1x4 nparray or with len(vertices) 1x4 nparray :param name: :return: author: weiwei date: 20170328, 20210116 """ if rgba_list is None: # default vertex_rgbas = np.array([[0, 0, 0, 255]] * len(vertices), dtype=np.uint8) elif type(rgba_list) is not list: raise Exception('rgba\_list must be a list!') elif len(rgba_list) == 1: vertex_rgbas = np.tile((np.array(rgba_list[0]) * 255).astype(np.uint8), (len(vertices), 1)) elif len(rgba_list) == len(vertices): vertex_rgbas = (np.array(rgba_list) * 255).astype(np.uint8) else: raise ValueError( 'rgba_list must be a list of one or len(vertices) 1x4 nparray!') vertformat = GeomVertexFormat() arrayformat = GeomVertexArrayFormat() arrayformat.addColumn(InternalName.getVertex(), 3, GeomEnums.NTFloat32, GeomEnums.CPoint) vertformat.addArray(arrayformat) arrayformat = GeomVertexArrayFormat() arrayformat.addColumn(InternalName.getColor(), 4, GeomEnums.NTUint8, GeomEnums.CColor) vertformat.addArray(arrayformat) vertformat = GeomVertexFormat.registerFormat(vertformat) vertexdata = GeomVertexData(name, vertformat, Geom.UHStatic) vertexdata.modifyArrayHandle(0).copyDataFrom( np.ascontiguousarray(vertices, dtype=np.float32)) vertexdata.modifyArrayHandle(1).copyDataFrom(vertex_rgbas) primitive = GeomPoints(Geom.UHStatic) primitive.setIndexType(GeomEnums.NTUint32) primitive.modifyVertices(-1).modifyHandle().copyDataFrom( np.arange(len(vertices), dtype=np.uint32)) geom = Geom(vertexdata) geom.addPrimitive(primitive) return geom
def pandageom_from_points(vertices, rgba=None, name=''): """ pack the vertices into a panda3d point cloud geom :param vertices: :param rgba: rgba color for each vertex, can be list or nparray (rgb is also acceptable) :param name: :return: author: weiwei date: 20170328, 20210116, 20220721 """ if rgba is None: # default vertex_rgbas = np.asarray([[0, 0, 0, 255]] * len(vertices), dtype=np.uint8) if isinstance(rgba, list): rgba = np.array(rgba) if not isinstance(rgba, np.array): raise ValueError('rgba must be a list or an nparray!') if len(rgba) == 1: vertex_rgbas = np.tile((rgba * 255).astype(np.uint8), (len(vertices), 1)) elif len(rgba) == len(vertices): vertex_rgbas = (rgba * 255).astype(np.uint8) n_color_bit = rgba.shape[1] vertformat = GeomVertexFormat() arrayformat = GeomVertexArrayFormat() arrayformat.addColumn(InternalName.getVertex(), 3, GeomEnums.NTFloat32, GeomEnums.CPoint) vertformat.addArray(arrayformat) arrayformat = GeomVertexArrayFormat() arrayformat.addColumn(InternalName.getColor(), n_color_bit, GeomEnums.NTUint8, GeomEnums.CColor) vertformat.addArray(arrayformat) vertformat = GeomVertexFormat.registerFormat(vertformat) vertexdata = GeomVertexData(name, vertformat, Geom.UHStatic) vertexdata.modifyArrayHandle(0).copyDataFrom( np.ascontiguousarray(vertices, dtype=np.float32)) vertexdata.modifyArrayHandle(1).copyDataFrom(vertex_rgbas) primitive = GeomPoints(Geom.UHStatic) primitive.setIndexType(GeomEnums.NTUint32) primitive.modifyVertices(-1).modifyHandle().copyDataFrom( np.arange(len(vertices), dtype=np.uint32)) geom = Geom(vertexdata) geom.addPrimitive(primitive) return geom
def regenerateGeometry(self): # # Generate vertex data # numVerts = len(self.vertices) vdata = GeomVertexData("SolidFace", getFaceFormat(), GeomEnums.UHStatic) vdata.uncleanSetNumRows(len(self.vertices)) vwriter = GeomVertexWriter(vdata, InternalName.getVertex()) twriter = GeomVertexWriter(vdata, InternalName.getTexcoord()) nwriter = GeomVertexWriter(vdata, InternalName.getNormal()) tanwriter = GeomVertexWriter(vdata, InternalName.getTangent()) bwriter = GeomVertexWriter(vdata, InternalName.getBinormal()) for i in range(len(self.vertices)): vert = self.vertices[i] vwriter.setData3f(vert.pos) twriter.setData2f(vert.uv) nwriter.setData3f(self.plane.getNormal()) tanwriter.setData3f(self.material.tangent) bwriter.setData3f(self.material.binormal) # # Generate indices # # Triangles in 3D view prim3D = GeomTriangles(GeomEnums.UHStatic) prim3D.reserveNumVertices((numVerts - 2) * 3) for i in range(1, numVerts - 1): prim3D.addVertices(i + 1, i, 0) prim3D.closePrimitive() # Line loop in 2D view.. using line strips prim2D = GeomLinestrips(GeomEnums.UHStatic) prim2D.reserveNumVertices(numVerts + 1) for i in range(numVerts): prim2D.addVertex(i) # Close off the line strip with the first vertex.. creating a line loop prim2D.addVertex(0) prim2D.closePrimitive() # # Generate mesh objects # geom3D = SolidFaceGeom(vdata) geom3D.setDrawMask(VIEWPORT_3D_MASK) geom3D.setPlaneCulled(True) geom3D.setPlane(self.plane) geom3D.addPrimitive(prim3D) self.index3D = self.solid.addFaceGeom(geom3D, self.state3D) geom3DLines = SolidFaceGeom(vdata) geom3DLines.addPrimitive(prim2D) geom3DLines.setDrawMask(VIEWPORT_3D_MASK) geom3DLines.setDraw(False) self.index3DLines = self.solid.addFaceGeom(geom3DLines, self.state3DLines) geom2D = SolidFaceGeom(vdata) geom2D.addPrimitive(prim2D) geom2D.setDrawMask(VIEWPORT_2D_MASK) self.index2D = self.solid.addFaceGeom(geom2D, self.state2D) self.geom3D = geom3D self.geom3DLines = geom3DLines self.geom2D = geom2D self.vdata = vdata self.hasGeometry = True
def __init__(self, mainReference): self.mainRef = mainReference # fog experiment myFog = Fog("Mist") myFog.setColor(0.6, 0.6, 0.6) myFog.setExpDensity(0.0007) render.setFog(myFog) # loading H_Block self.H_Block = loader.loadModel("../../models/H_Block/H_Block") self.H_Block.reparentTo(self.mainRef.render) # loading H_Block's colision mesh self.H_Block_col = loader.loadModel("../../models/H_Block/H_Block_collision") self.H_Block_col.ls() # creating triangle meshes for all static nodes self.hBlockRoomGeom = self.H_Block_col.getChild(0).getNode(0).getGeom(0) self.hBlockBulletMesh = BulletTriangleMesh() self.hBlockBulletMesh.addGeom(self.hBlockRoomGeom) self.hBlockBulletShape = BulletTriangleMeshShape(self.hBlockBulletMesh, dynamic=False) self.bulletHBlockNode = BulletRigidBodyNode('hBlockNode') self.bulletHBlockNode.addShape(self.hBlockBulletShape) self.mainRef.world.attachRigidBody(self.bulletHBlockNode) self.mainRef.render.attachNewNode(self.bulletHBlockNode).setCollideMask(BitMask32.allOn()) # arrays containing all regions and portals dividing those regions self.convexRegions = [] self.portals = [] self.convexRegionsGeometry = loader.loadModel("../../models/H_Block/ConvexRegions2") self.portalsGeometry = loader.loadModel("../../models/H_Block/Portals2") # self.portalsGeometry.reparentTo(self.mainRef.render) # Regions self.convexRegions.append( Region(0) ) # Just making the access to convexRegions easier for convexRegion in self.convexRegionsGeometry.getChild(0).getChildren(): regionNode = convexRegion.getNode(0) regionID = int( regionNode.getTag("prop") ) self.convexRegions.append( Region(regionID) ) # Get vertices that define the convex region vertexReader = GeomVertexReader(regionNode.getGeom(0).getVertexData(), InternalName.getVertex()) while( not(vertexReader.isAtEnd() ) ): data = vertexReader.getData3() X = data.getX() Y = data.getY() Z = data.getZ() self.convexRegions[-1].vertices.append(Vec3(X,Y,Z)) self.convexRegions = sorted(self.convexRegions, key=lambda convexRegion: convexRegion.regionID) # Debug # for cr in self.convexRegions: # print cr.regionID # Portals for portal in self.portalsGeometry.getChild(0).getChildren(): portalNode = portal.getNode(0) # Get vertices that define the portal frontiers = [] vertexReader = GeomVertexReader(portalNode.getGeom(0).getVertexData(), InternalName.getVertex()) for i in range(2): # We got 2 vertices per portal data = vertexReader.getData3() X = data.getX() Y = data.getY() frontiers.append(Vec2(X,Y)) connectedRegionsIDs = map(int, portalNode.getTag("prop").split(',')) self.portals.append( Portal(connectedRegionsIDs, frontiers) ) self.convexRegions[ connectedRegionsIDs[0] ].portalEntrancesList.append( PortalEntrance( self.portals[-1], connectedRegionsIDs[1] ) ) self.convexRegions[ connectedRegionsIDs[1] ].portalEntrancesList.append( PortalEntrance( self.portals[-1], connectedRegionsIDs[0] ) )
def processModel(path): scene = loadModel(path) if scene.isEmpty(): print("Error converting `{0}`!".format(path)) return fPath = Filename.fromOsSpecific(path) outputPath = Filename.toOsSpecific( Filename("bam2smd/" + fPath.getDirname() + "/" + fPath.getBasenameWoExtension() + "/")) if not os.path.exists(outputPath): os.makedirs(outputPath) isCharacter = not scene.find("**/+Character").isEmpty() isAnimation = not scene.find("**/+AnimBundleNode").isEmpty() if not isAnimation: if isCharacter: nodes = Skeleton(scene.findAllMatches("**/+Character")) else: nodes = Skeleton(None) names = {} for geomNp in scene.findAllMatches("**/+GeomNode"): smd = "version 1\n" smd += str(nodes) smd += "skeleton\n" smd += "time 0\n" if isCharacter: boneIds = sorted(nodes.bones.keys()) for iBone in range(len(boneIds)): boneId = boneIds[iBone] bone = nodes.bones[boneId] if isinstance(bone, CharacterJoint): boneTform = bone.getTransformState() pos = boneTform.getPos() boneMat = boneTform.getMat().getUpper3() #boneMat.transposeInPlace() rot = mat3NormalizedToEulO(boneMat) else: pos = Vec3() rot = Vec3() smd += boneFrameString(boneId, pos, rot) else: smd += "0 0 0 0 0 0 0\n" smd += "end\n" smd += "triangles\n" for geom in geomNp.node().getGeoms(): geom = geom.decompose() vdata = geom.getVertexData() blendTable = vdata.getTransformBlendTable() for prim in geom.getPrimitives(): numTris = prim.getNumPrimitives() for nTri in range(numTris): start = prim.getPrimitiveStart(nTri) end = prim.getPrimitiveEnd(nTri) smd += "no_material\n" for primVert in range(start, end): vertIdx = prim.getVertex(primVert) reader = GeomVertexReader(vdata) reader.setColumn(InternalName.getVertex()) reader.setRow(vertIdx) pos = reader.getData3f() uv = Vec2(0, 0) if vdata.hasColumn(InternalName.getTexcoord()): reader.setColumn(InternalName.getTexcoord()) reader.setRow(vertIdx) uv = reader.getData2f() norm = Vec3.forward() if vdata.hasColumn(InternalName.getNormal()): reader.setColumn(InternalName.getNormal()) reader.setRow(vertIdx) norm = reader.getData3f() smd += "0 {0:.6f} {1:.6f} {2:.6f} {3:.6f} {4:.6f} {5:.6f} {6:.6f} {7:.6f} ".format( pos[0], pos[1], pos[2], norm[0], norm[1], norm[2], uv[0], uv[1]) if (isCharacter and blendTable and vdata.getNumArrays() > 1 and vdata.getArray(1).hasColumn( InternalName.getTransformBlend())): reader.setColumn( 1, vdata.getArray( 1).getArrayFormat().getColumn( InternalName.getTransformBlend())) reader.setRow(vertIdx) nBlend = reader.getData1i() blend = blendTable.getBlend(nBlend) numTransforms = blend.getNumTransforms() smd += "{0} ".format(numTransforms) for nTransform in range(numTransforms): transform = blend.getTransform(nTransform) if isinstance(transform, JointVertexTransform): boneId = nodes.getBoneId( transform.getJoint()) smd += "{0} {1:.6f} ".format( boneId, blend.getWeight(nTransform)) else: smd += "1 0 1.0" smd += "\n" smd += "end\n" smdFile = geomNp.getName() if len(smdFile) == 0: smdFile = getUnknownName() elif names.get(smdFile, 0) > 0: smdFile = smdFile + "_{0}".format(names[smdFile]) names[smdFile] += 1 else: names[smdFile] = 1 smdFile += ".smd" outFile = open(outputPath + "\\" + smdFile, "w") outFile.write(smd) outFile.flush() outFile.close() else: bundles = scene.findAllMatches("**/+AnimBundleNode") bundle = bundles[0].node().getBundle() nodes = Skeleton(bundles) smd = "version 1\n" smd += str(nodes) smd += "skeleton\n" numFrames = bundle.getNumFrames() boneIds = sorted(nodes.bones.keys()) for iFrame in range(numFrames): smd += "time {0}\n".format(iFrame) for iBone in range(len(boneIds)): bone = nodes.getBone(boneIds[iBone]) if isinstance(bone, AnimChannelACMatrixSwitchType): boneFrameMat = Mat4() bone.getValueNoScaleShear(iFrame, boneFrameMat) boneFrameTransform = TransformState.makeMat(boneFrameMat) pos = boneFrameTransform.getPos() rotMat = boneFrameMat.getUpper3() #rotMat.transposeInPlace() rot = mat3NormalizedToEulO(rotMat) smd += boneFrameString(boneIds[iBone], pos, rot) smd += "end\n" smdFile = fPath.getBasenameWoExtension() + ".smd" outFile = open(outputPath + "\\" + smdFile, "w") outFile.write(smd) outFile.flush() outFile.close()