def _CreateOneSynapse(self, presynCell, synapsesType): form = GeomVertexFormat.getV3() vdata = GeomVertexData("SynapseLine", form, Geom.UHStatic) vdata.setNumRows(1) vertex = GeomVertexWriter(vdata, "vertex") vertex.addData3f(presynCell.getNode().getPos(self.__node)) vertex.addData3f(0, 0, 0) # vertex.addData3f(self.__node.getPos()) # printLog("inputObj:"+str(i)+"bits:"+str(y)) # printLog(inputObj[i].inputBits[y].getNode().getPos(self.__node)) prim = GeomLines(Geom.UHStatic) prim.addVertices(0, 1) geom = Geom(vdata) geom.addPrimitive(prim) node = GeomNode("Synapse_" + str(synapsesType)) node.addGeom(geom) nodePath = self.__cellsNodePath.attachNewNode(node) nodePath.setRenderModeThickness(2) # color of the line if presynCell.active: nodePath.setColor(COL_PROXIMAL_SYNAPSES_ACTIVE) else: nodePath.setColor(COL_PROXIMAL_SYNAPSES_INACTIVE)
def drawBody(self, pos, quat, radius=1, keepDrawing=True, numVertices=16): """ this draws the body of the tree. This draws a ring of vertices and connects the rings with triangles to from the body. the keepDrawing parameter tells the function whether or not we're at an end if the vertices before were an end, don't draw branches to it """ vdata = self.bodydata circleGeom = Geom(vdata) vertWriter = GeomVertexWriter(vdata, "vertex") normalWriter = GeomVertexWriter(vdata, "normal") texReWriter = GeomVertexRewriter(vdata, "texcoord") startRow = vdata.getNumRows() vertWriter.setRow(startRow) normalWriter.setRow(startRow) sCoord = 0 if (startRow != 0): texReWriter.setRow(startRow - numVertices) sCoord = texReWriter.getData2f().getX() + 1 draw = (startRow - numVertices) in self.drawFlags if not draw: sCoord -= 1 drawIndex = startRow texReWriter.setRow(startRow) angleSlice = 2 * math.pi / numVertices currAngle = 0 perp1 = quat.getRight() perp2 = quat.getForward() #vertex information is written here for i in xrange(numVertices + 1): #doubles the last vertex to fix UV seam adjCircle = pos + (perp1 * math.cos(currAngle) + perp2 * math.sin(currAngle)) * radius normal = perp1 * math.cos(currAngle) + perp2 * math.sin(currAngle) normalWriter.addData3f(normal) vertWriter.addData3f(adjCircle) texReWriter.addData2f(1.0 * i / numVertices, sCoord) if keepDrawing: self.drawFlags.add(drawIndex) drawIndex += 1 currAngle += angleSlice draw = (startRow - numVertices) in self.drawFlags #we cant draw quads directly so we use Tristrips if (startRow != 0) and draw: lines = GeomTristrips(Geom.UHStatic) for i in xrange(numVertices + 1): lines.addVertex(i + startRow) lines.addVertex(i + startRow - numVertices - 1) lines.addVertex(startRow) lines.addVertex(startRow - numVertices) lines.closePrimitive() #lines.decompose() circleGeom.addPrimitive(lines) circleGeomNode = GeomNode("Debug") circleGeomNode.addGeom(circleGeom) self.numPrimitives += numVertices * 2 self.bodies.attachNewNode(circleGeomNode)
def draw_face(self, f, f_color): #add normal format = GeomVertexFormat.getV3n3cp() vdata = GeomVertexData('vert', format, Geom.UHDynamic) vertex = GeomVertexWriter(vdata, 'vertex') color = GeomVertexWriter(vdata, 'color') normal = GeomVertexWriter(vdata, 'normal') vertex.addData3f(f.v1.pos) normal.addData3f(f.v1.norm.x, f.v1.norm.y, f.v1.norm.z) color.addData4f(f_color) vertex.addData3f(f.v2.pos) normal.addData3f(f.v2.norm.x, f.v2.norm.y, f.v2.norm.z) color.addData4f(f_color) vertex.addData3f(f.v3.pos) normal.addData3f(f.v3.norm.x, f.v3.norm.y, f.v3.norm.z) color.addData4f(f_color) mesh = Geom(vdata) tri = GeomTriangles(Geom.UHDynamic) tri.addVertex(0) tri.addVertex(1) tri.addVertex(2) tri.closePrimitive() mesh.addPrimitive(tri) face_node = GeomNode(self.mesh.name + '_face_' + str(f.ID)) face_node.addGeom(mesh) face_node.setTag('ID', str(f.ID)) rendered_face = self.render_root.attachNewNode(face_node) rendered_face.setTwoSided(True) self.render_nodes['face_' + str(f.ID)] = rendered_face
def makeRotationGeomNode(): vdata = GeomVertexData('rotHandleData', GeomVertexFormat.getV3(), Geom.UHStatic) v = GeomVertexWriter(vdata, 'vertex') radius = 0.7 width = 0.08 res = 30 innerRad = radius - width for i in xrange(res): theta = i * (2 * pi / res) v.addData3f(innerRad * sin(theta), innerRad * cos(theta), width / 2.0) v.addData3f(innerRad * sin(theta), innerRad * cos(theta), -width / 2.0) v.addData3f(radius * sin(theta), radius * cos(theta), width / 2.0) v.addData3f(radius * sin(theta), radius * cos(theta), -width / 2.0) circle = Geom(vdata) # Make prims for the faces of the torus faces = [GeomTristrips(Geom.UHStatic) for i in xrange(4)] for i in xrange(res): i = i * 4 faces[0].addVertices(i + 1, i) faces[1].addVertices(i + 2, i + 1) faces[2].addVertices(i + 3, i + 2) faces[3].addVertices(i, i + 3) for i in xrange(4): faces[i].addVertices((i + 1) % 4, i) faces[i].closePrimitive() circle.addPrimitive(faces[i]) node = GeomNode('geomnode') node.addGeom(circle) return node
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 buildGeom(self, meshData): prims = meshData["prims"] vertices = meshData["vertices"] normals = meshData["normals"] texcoords = meshData["texcoords"] vdata = GeomVertexData('mesh', GeomVertexFormat.getV3n3t2(), Geom.UHStatic) vwriter = GeomVertexWriter(vdata, 'vertex') nvwriter = GeomVertexWriter(vdata, 'normal') tvwriter = GeomVertexWriter(vdata, 'texcoord') for i in range(len(vertices)): v = vertices[i] n = normals[i] t = texcoords[i] vwriter.addData3f(v) nvwriter.addData3f(n) tvwriter.addData2f(t) prim = GeomTriangles(Geom.UHStatic) for i in range(len(prims)): A, B, C = prims[i] prim.addVertices(A, B, C) prim.closePrimitive() geom = Geom(vdata) geom.addPrimitive(prim) geomNode = GeomNode('trig') geomNode.addGeom(geom) geomNode.unify(1, True) return geomNode
def _makeGeom(array,ctup,i,pipe, geomType=GeomPoints): #XXX testing multiple Geom version ... for perf seems like it will be super slow #SUUUPER slow TONS of draw calls #wwwayyy better to make a bunch of geoms ahead of time... """ multiprocessing capable geometery maker """ fmt = GeomVertexFormat.getV3c4() cloudNode = GeomNode('bin %s selectable'%(i)) for point in array: vertexData = GeomVertexData('poitn', fmt, Geom.UHStatic) GeomVertexWriter(vertexData, 'vertex').addData3f(*point) GeomVertexWriter(vertexData, 'color').addData4f(*ctup) #verts.addData3f(*point) #color.addData4f(*ctup) points = geomType(Geom.UHStatic) points.addVertex(0) points.closePrimitive() cloudGeom = Geom(vertexData) cloudGeom.addPrimitive(points) cloudNode.addGeom(cloudGeom) #TODO figure out if it is faster to add and subtract Geoms from geom nodes... #output[i] = cloudNode #print('ping',{i:cloudNode}) #pipe.send((i,)) #out = q.get() #print('pong',out) #q.put(out) if pipe == None: return (cloudNode) pipe.send(cloudNode.encodeToBamStream()) #FIXME make this return a pointer NOPE
def make_node_from_mesh(points: np.ndarray, faces: np.ndarray, normals: np.ndarray, rgba: np.ndarray = np.asarray([1, 1, 1, 1])): vertex_normal_format = GeomVertexFormat.get_v3n3c4() v_data = GeomVertexData('sphere', vertex_normal_format, Geom.UHStatic) num_rows = np.max([points.shape[0], faces.shape[0]]) v_data.setNumRows(int(num_rows)) vertex_data = GeomVertexWriter(v_data, 'vertex') normal_data = GeomVertexWriter(v_data, 'normal') color_data = GeomVertexWriter(v_data, 'color') for point, normal in zip(points, normals): vertex_data.addData3(point[0], point[1], point[2]) normal_data.addData3(normal[0], normal[1], normal[2]) color_data.addData4(rgba[0], rgba[1], rgba[2], rgba[3]) geom = Geom(v_data) for face in faces: tri = GeomTriangles(Geom.UHStatic) p_1 = points[face[0], :] p_2 = points[face[1], :] p_3 = points[face[2], :] norm = normals[face[0], :] if np.dot(np.cross(p_2 - p_1, p_3 - p_2), norm) < 0: tri.add_vertices(face[2], face[1], face[0]) else: tri.add_vertices(face[0], face[1], face[2]) geom.addPrimitive(tri) node = GeomNode('gnode') node.addGeom(geom) return node
def makeSimpleGeomBuffer(array, color, geomType=GeomPoints): """ massively faster than the nonbuffer version """ full = [tuple(d) for d in np.hstack((array,color))] fmt = GeomVertexFormat.getV3c4() vertexData = GeomVertexData('points', fmt, Geom.UHDynamic) #FIXME use the index for these too? with setPythonTag, will have to 'reserve' some cloudGeom = Geom(vertexData) cloudNode = GeomNode('just some points') vertexData.setNumRows(len(array)) mem_array = vertexData.modifyArray(0) view = memoryview(mem_array) arr = np.asarray(view) arr[:] = full points = geomType(Geom.UHDynamic) points.addConsecutiveVertices(0,len(array)) points.closePrimitive() cloudGeom.addPrimitive(points) cloudNode.addGeom(cloudGeom) return cloudNode
def makeSimpleGeom(array, ctup, geomType = GeomPoints, fix = False): fmt = GeomVertexFormat.getV3c4() vertexData = GeomVertexData('points', fmt, Geom.UHDynamic) #FIXME use the index for these too? with setPythonTag, will have to 'reserve' some cloudGeom = Geom(vertexData) cloudNode = GeomNode('just some points') verts = GeomVertexWriter(vertexData, 'vertex') color = GeomVertexWriter(vertexData, 'color') if fix: if len(ctup) == len(array): for point,c in zip(array, ctup): verts.addData3f(*point) color.addData4f(*c) else: for point in array: verts.addData3f(*point) color.addData4f(*ctup) else: for point in array: verts.addData3f(*point) color.addData4f(*ctup) points = geomType(Geom.UHDynamic) points.addConsecutiveVertices(0,len(array)) points.closePrimitive() cloudGeom.addPrimitive(points) cloudNode.addGeom(cloudGeom) #TODO figure out if it is faster to add and subtract Geoms from geom nodes... if fix: return cloudNode.__reduce__() else: return cloudNode # decoding fails becuase ForkingPickler is called for reasons beyond comprehension
def create_mesh(parentnp, debug=False, invert=False): '''This creates a simple 17x17 grid mesh for the sides of our cube. The ultimate goal is to use a LOD system, probably based on quadtrees. If debug is true then we get a color gradiant on our vertexes.''' x = -1.0 y = -1.0 vertex_count = 0 u = 0.0 v = 0.0 WIDTH_STEP = 2 / 16.0 while y <= 1.0: while x <= 1.0: vertex.addData3f(x, y, 0) if invert: normal.addData3f( myNormalize((Vec3(2 * x + 1, 2 * y + 1, 2 * 0 - 1)))) else: normal.addData3f( myNormalize((Vec3(2 * x - 1, 2 * y - 1, 2 * 0 - 1)))) if debug: color.addData4f(1.0, u, v, 1.0) texcoord.addData2f(u, v) vertex_count += 1 x += WIDTH_STEP u += WIDTH_STEP / 2.0 x = -1.0 u = 0 y += WIDTH_STEP v += WIDTH_STEP / 2.0 print vertex_count triangles = [] for y in range(0, 16): for x in range(0, 16): v = 17 * y + x tri = GeomTriangles(Geom.UHDynamic) tri.addVertex(v) tri.addVertex(v + 1) tri.addVertex(v + 17) tri.closePrimitive() triangles.append(tri) tri = GeomTriangles(Geom.UHDynamic) tri.addVertex(v + 1) tri.addVertex(v + 18) tri.addVertex(v + 17) tri.closePrimitive() triangles.append(tri) mesh = Geom(vdata) for t in triangles: mesh.addPrimitive(t) mnode = GeomNode('quadface') mnode.addGeom(mesh) nodePath = parentnp.attachNewNode(mnode) return nodePath
def makeRotationGeomNode(): vdata = GeomVertexData('rotHandleData', GeomVertexFormat.getV3(), Geom.UHStatic) v = GeomVertexWriter(vdata, 'vertex') radius = 0.7 width = 0.08 res = 30 innerRad = radius - width for i in xrange(res): theta = i*(2*pi/res) v.addData3f(innerRad*sin(theta), innerRad*cos(theta), width/2.0) v.addData3f(innerRad*sin(theta), innerRad*cos(theta), -width/2.0) v.addData3f(radius*sin(theta), radius*cos(theta), width/2.0) v.addData3f(radius*sin(theta), radius*cos(theta), -width/2.0) circle = Geom(vdata) # Make prims for the faces of the torus faces = [GeomTristrips(Geom.UHStatic) for i in xrange(4)] for i in xrange(res): i = i*4 faces[0].addVertices(i + 1, i) faces[1].addVertices(i + 2, i + 1) faces[2].addVertices(i + 3, i + 2) faces[3].addVertices(i, i + 3) for i in xrange(4): faces[i].addVertices((i + 1) % 4, i) faces[i].closePrimitive() circle.addPrimitive(faces[i]) node = GeomNode('geomnode') node.addGeom(circle) return node
def draw_face(self,f,f_color): #add normal format = GeomVertexFormat.getV3n3cp() vdata=GeomVertexData('vert', format, Geom.UHDynamic) vertex=GeomVertexWriter(vdata, 'vertex') color=GeomVertexWriter(vdata, 'color') normal=GeomVertexWriter(vdata, 'normal') vertex.addData3f(f.v1.pos) normal.addData3f(f.v1.norm.x, f.v1.norm.y, f.v1.norm.z) color.addData4f(f_color) vertex.addData3f(f.v2.pos) normal.addData3f(f.v2.norm.x, f.v2.norm.y, f.v2.norm.z) color.addData4f(f_color) vertex.addData3f(f.v3.pos) normal.addData3f(f.v3.norm.x, f.v3.norm.y, f.v3.norm.z) color.addData4f(f_color) mesh = Geom(vdata) tri = GeomTriangles(Geom.UHDynamic) tri.addVertex(0) tri.addVertex(1) tri.addVertex(2) tri.closePrimitive() mesh.addPrimitive(tri) face_node = GeomNode(self.mesh.name+'_face_'+str(f.ID)) face_node.addGeom(mesh) face_node.setTag('ID',str(f.ID)) rendered_face = self.render_root.attachNewNode(face_node) rendered_face.setTwoSided(True) self.render_nodes['face_'+str(f.ID)] = rendered_face
def gen_submesh(verts, faces, rgba=[1, 0, 0, 1]): """ TODO 20201202: replace pandanode with trimesh :param verts: np.array([[v00, v01, v02], [v10, v11, v12], ...] :param faces: np.array([[ti00, ti01, ti02], [ti10, ti11, ti12], ...] :param color: rgba :return: author: weiwei date: 20171219 """ # gen vert normals vertnormals = np.zeros((len(verts), 3)) for fc in faces: vert0 = verts[fc[0], :] vert1 = verts[fc[1], :] vert2 = verts[fc[2], :] facenormal = np.cross(vert2 - vert1, vert0 - vert1) vertnormals[fc[0], :] = vertnormals[fc[0]] + facenormal vertnormals[fc[1], :] = vertnormals[fc[1]] + facenormal vertnormals[fc[2], :] = vertnormals[fc[2]] + facenormal for i in range(0, len(vertnormals)): vertnormals[i, :] = vertnormals[i, :] / np.linalg.norm( vertnormals[i, :]) geom = da.pandageom_from_vvnf(verts, vertnormals, faces) node = GeomNode('surface') node.addGeom(geom) surface_nodepath = NodePath('surface') surface_nodepath.attachNewNode(node) surface_nodepath.setColor(rgba[0], rgba[1], rgba[2], rgba[3]) surface_nodepath.setTransparency(TransparencyAttrib.MDual) surface_nodepath.setTwoSided(True) surface_sgm = StaticGeometricModel(surface_nodepath) return surface_sgm
def create_model(self): # Set up the vertex arrays vformat = GeomVertexFormat.get_v3c4() vdata = GeomVertexData("Data", vformat, Geom.UHStatic) vertex = GeomVertexWriter(vdata, 'vertex') color = GeomVertexWriter(vdata, 'color') geom = Geom(vdata) # Vertex data vertex.addData3f(1.5, 0, -1) color.addData4f(1, 0, 0, 1) vertex.addData3f(-1.5, 0, -1) color.addData4f(0, 1, 0, 1) vertex.addData3f(0, 0, 1) color.addData4f(0, 0, 1, 1) # Primitive tri = GeomTriangles(Geom.UHStatic) tri.add_vertex(2) tri.add_vertex(1) tri.add_vertex(0) tri.close_primitive() geom.addPrimitive(tri) # Create the actual node node = GeomNode('geom_node') node.addGeom(geom) np = NodePath(node) # Shader and initial shader vars np.set_shader(Shader.load(Shader.SL_GLSL, "shader/shader.vert", "shader/shader.frag")) np.set_shader_input("time", 0.0) # No instancing necessary #np.set_instance_count(27) # return np np.reparent_to(base.render) self.model = np
class Sky(object): def __init__(self, mp): vdata = GeomVertexData("name_me", GeomVertexFormat.getV3c4(), Geom.UHStatic) vertex = GeomVertexWriter(vdata, "vertex") color = GeomVertexWriter(vdata, "color") primitive = GeomTristrips(Geom.UHStatic) film_size = base.cam.node().getLens().getFilmSize() x = film_size.getX() / 2.0 z = x * 256.0 / 240.0 vertex.addData3f(x, 90, z) vertex.addData3f(-x, 90, z) vertex.addData3f(x, 90, -z) vertex.addData3f(-x, 90, -z) color.addData4f(VBase4(*mp["backgroundcolor1"])) color.addData4f(VBase4(*mp["backgroundcolor1"])) color.addData4f(VBase4(*mp["backgroundcolor2"])) color.addData4f(VBase4(*mp["backgroundcolor2"])) primitive.addNextVertices(4) primitive.closePrimitive() geom = Geom(vdata) geom.addPrimitive(primitive) self.node = GeomNode("sky") self.node.addGeom(geom) base.camera.attachNewNode(self.node) def remove(self): NodePath(self.node).removeNode()
def make_cube(x, y, z, size): squares = [] squares.append( make_square(x - (size / 2), y - (size / 2), z - (size / 2), x + (size / 2), y - (size / 2), z + (size / 2)) ) squares.append( make_square(x - (size / 2), y + (size / 2), z - (size / 2), x + (size / 2), y + (size / 2), z + (size / 2)) ) squares.append( make_square(x - (size / 2), y + (size / 2), z + (size / 2), x + (size / 2), y - (size / 2), z + (size / 2)) ) squares.append( make_square(x - (size / 2), y + (size / 2), z - (size / 2), x + (size / 2), y - (size / 2), z - (size / 2)) ) squares.append( make_square(x - (size / 2), y - (size / 2), z - (size / 2), x - (size / 2), y + (size / 2), z + (size / 2)) ) squares.append( make_square(x + (size / 2), y - (size / 2), z - (size / 2), x + (size / 2), y + (size / 2), z + (size / 2)) ) snode = GeomNode("square") for s in squares: snode.addGeom(s) cube = render.attachNewNode(snode) cube.setTwoSided(True)
def __build_Patches(self, sphere): vdata = GeomVertexData("Data", self.__vformat['high'], Geom.UHStatic) vertices = GeomVertexWriter(vdata, "vertex") mapcoords = GeomVertexWriter(vdata, "mapcoord") texcoords = GeomVertexWriter(vdata, "texcoord") _num_rows = len(sphere.pts) vertices.reserveNumRows(_num_rows) mapcoords.reserveNumRows(_num_rows) texcoords.reserveNumRows(_num_rows) # Pts. for pt, uv, coords, in zip(sphere.pts, sphere.uvs, sphere.coords): vertices.addData3f(*pt) mapcoords.addData2f(*coords) texcoords.addData2f(*uv) ## *.99+.01) # Patches. prim = GeomPatches(3, Geom.UHStatic) prim.reserveNumVertices(len(sphere.tris)) for tri in sphere.tris: prim.addVertices(*tri) prim.closePrimitive() # Geom. geom = Geom(vdata) geom.addPrimitive(prim) geom_node = GeomNode("geom") geom_node.addGeom(geom) geom_np = NodePath(geom_node) return geom_np
def _CreateOneSynapse(self, presynCell, synapsesType): presynCell.setPresynapticFocus() # highlight presynaptic cells form = GeomVertexFormat.getV3() vdata = GeomVertexData("SynapseLine", form, Geom.UHStatic) vdata.setNumRows(1) vertex = GeomVertexWriter(vdata, "vertex") vertex.addData3f(presynCell.getNode().getPos(self._node)) vertex.addData3f(0, 0, 0) prim = GeomLines(Geom.UHStatic) prim.addVertices(0, 1) geom = Geom(vdata) geom.addPrimitive(prim) node = GeomNode("Synapse_" + str(synapsesType)) node.addGeom(geom) nodePath = self._node.attachNewNode(node) nodePath.setRenderModeThickness(2) # color of the line if presynCell.active: nodePath.setColor(COL_DISTAL_SYNAPSES_ACTIVE) else: nodePath.setColor(COL_DISTAL_SYNAPSES_INACTIVE)
def __build_Tris(self, sphere, mode): vdata = GeomVertexData("Data", self.__vformat[mode], Geom.UHStatic) _num_rows = len(sphere.pts) # Vertices. vertices = GeomVertexWriter(vdata, "vertex") vertices.reserveNumRows(_num_rows) for pt in sphere.pts: vertices.addData3f(*pt) # Map coords. if mode == "mid": mapcoords = GeomVertexWriter(vdata, "mapcoord") mapcoords.reserveNumRows(_num_rows) for mc in sphere.coords: u, v = mc[:2] mapcoords.addData2f(u, v) # Tris. prim = GeomTriangles(Geom.UHStatic) prim.reserveNumVertices(len(sphere.tris)) for tri in sphere.tris: prim.addVertices(*tri) prim.closePrimitive() # Geom. geom = Geom(vdata) geom.addPrimitive(prim) geom_node = GeomNode("geom") geom_node.addGeom(geom) geom_np = NodePath(geom_node) return geom_np
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, scale=10): axisNode = GeomNode('axis') axisGeom = makeAxis() axisNode.addGeom(axisGeom) axis = render.attachNewNode(axisNode) axis.setScale(scale, scale, scale) axis.setRenderModeThickness(2)
def create_model(self): # Set up the vertex arrays vformat = GeomVertexFormat.get_v3c4() vdata = GeomVertexData("Data", vformat, Geom.UHStatic) vertex = GeomVertexWriter(vdata, 'vertex') color = GeomVertexWriter(vdata, 'color') geom = Geom(vdata) # Vertex data vertex.addData3f(1.5, 0, -1) color.addData4f(1, 0, 0, 1) vertex.addData3f(-1.5, 0, -1) color.addData4f(0, 1, 0, 1) vertex.addData3f(0, 0, 1) color.addData4f(0, 0, 1, 1) # Primitive tri = GeomTriangles(Geom.UHStatic) tri.add_vertex(2) tri.add_vertex(1) tri.add_vertex(0) tri.close_primitive() geom.addPrimitive(tri) # Create the actual node node = GeomNode('geom_node') node.addGeom(geom) np = NodePath(node) # Shader and initial shader vars np.set_shader( Shader.load(Shader.SL_GLSL, "shader/shader.vert", "shader/shader.frag")) np.set_shader_input("time", 0.0) # No instancing necessary #np.set_instance_count(27) # return np np.reparent_to(base.render) self.model = np
def make_cube(x, y, z, size): squares = [] squares.append( make_square(x - (size / 2), y - (size / 2), z - (size / 2), x + (size / 2), y - (size / 2), z + (size / 2))) squares.append( make_square(x - (size / 2), y + (size / 2), z - (size / 2), x + (size / 2), y + (size / 2), z + (size / 2))) squares.append( make_square(x - (size / 2), y + (size / 2), z + (size / 2), x + (size / 2), y - (size / 2), z + (size / 2))) squares.append( make_square(x - (size / 2), y + (size / 2), z - (size / 2), x + (size / 2), y - (size / 2), z - (size / 2))) squares.append( make_square(x - (size / 2), y - (size / 2), z - (size / 2), x - (size / 2), y + (size / 2), z + (size / 2))) squares.append( make_square(x + (size / 2), y - (size / 2), z - (size / 2), x + (size / 2), y + (size / 2), z + (size / 2))) snode = GeomNode('square') for s in squares: snode.addGeom(s) cube = render.attachNewNode(snode) cube.setTwoSided(True)
def __build_Star_Sphere(self, bg_stars): from panda3d.core import GeomVertexWriter, GeomVertexFormat, GeomVertexData from panda3d.core import Geom, GeomNode, GeomPoints, AmbientLight self.star_sphere_np.removeNode() # Fill GeomVertexData. vformat = GeomVertexFormat.getV3c4() vdata = GeomVertexData("Data", vformat, Geom.UHStatic) vertices = GeomVertexWriter(vdata, "vertex") colours = GeomVertexWriter(vdata, "color") for coords in bg_stars: x, y, z = coords vertices.addData3f(x, y, z) colours.addData4f(1, 1, 1, 1) # Render bg stars. bg_stars = GeomPoints(Geom.UHStatic) bg_stars.addNextVertices(_env.STAR_COUNT) bg_stars_geom = Geom(vdata) bg_stars_geom.addPrimitive(bg_stars) star_sphere = GeomNode("star_sphere") star_sphere.addGeom(bg_stars_geom) star_sphere_np = NodePath(star_sphere) star_sphere_np.reparentTo(self.NP) return star_sphere_np
def __build_Geom(self, data_dict, tris, prim_type=GeomTriangles): data_list = list(data_dict.items()) _num_rows = 0 for field, data in data_list: if not _num_rows: _num_rows = len(data) writer = self.__writers[field] writer.reserveNumRows(_num_rows) set_data = self._data_types[self.field_types[field]][-1] for datum in data: set_data(writer, *datum) # Tris prim = prim_type(Geom.UHStatic) prim.reserveNumVertices(len(tris)) for tri in tris: prim.addVertices(*tri) prim.closePrimitive() # Geom. geom = Geom(self.__vdata) geom.addPrimitive(prim) geom_node = GeomNode("geom") geom_node.addGeom(geom) geom_np = NodePath(geom_node) return geom_np
def add_plane(map_width, map_height): # Prepare the vertex format writers v_fmt = GeomVertexFormat.getV3n3c4() v_data = GeomVertexData('TerrainData', v_fmt, Geom.UHStatic) vertex = GeomVertexWriter(v_data, 'vertex') normal = GeomVertexWriter(v_data, 'normal') color = GeomVertexWriter(v_data, 'color') #texcoord = GeomVertexWriter(v_data, 'texcoord') # Create a primitive prim = GeomTrifans(Geom.UHStatic) poly_color = (uniform(0, 0.05), uniform(0, 0.5), uniform(0.5, 1), 0.5, ) for i, point in enumerate([ (-map_width/2, -map_height/2), (map_width/2, -map_height/2), (map_width/2, map_height/2), (-map_width/2, map_height/2), ]): x, y = point vertex.addData3f(x, y, 0) normal.addData3f(0, 0, 1) color.addData4f(*poly_color) #texcoord.addData2f(1, 0) prim.addVertex(i) prim.addVertex(0) prim.closePrimitive() # Add to the scene graph geom = Geom(v_data) geom.addPrimitive(prim) node = GeomNode('gnode') node.addGeom(geom) nodePath = render.attachNewNode(node) nodePath.setTwoSided(True) nodePath.setAlphaScale(0.5)
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 __init__(self): ShowBase.__init__(self) mesh = Mesh.create_plate(position=(0, 0), width=6, height=2, num_elements_width=6, num_elements_height=3) geom = mesh.get_render_mesh() node = GeomNode('g-node') node.addGeom(geom) node_path = self.render.attachNewNode(node) # noinspection PyArgumentList shader = Shader.load(lang=Shader.SL_GLSL, vertex="../shaders/grid_shader.vert", fragment="../shaders/grid_shader.frag") node_path.setShader(shader) node_path.set_shader_input('color', (0.2, 0.5, 0)) self.camera.setPos(0, 0, 10) self.camera.lookAt(node_path) self.disableMouse() controller = MouseController(self.camera, self) controller.zoom()
def load(self): if panda3d is None: raise ImportError("Cannot locate Panda3D") #KLUDGE if self.material is not None and self.colors is None: col = self.material.getAmbient() col = (col[0] / col[3], col[1] / col[3], col[2] / col[3], 1.0) self.colors = (col,) * len(self.vertices) #/KLUDGE geom = make_geom(self.vertices, self.normals, self.colors, self.texcoords) prim = GeomTriangles(Geom.UHStatic) for face in self.faces: #TODO: proper tesselation! the current one only works for convex faces first = face[0] curr = face[1] for v in face[2:]: prim.addVertex(curr) prim.addVertex(v) prim.addVertex(first) curr = v prim.closePrimitive() geom.addPrimitive(prim) node = GeomNode(self.name) node.addGeom(geom) self.node = NodePath(node) self.node.setTwoSided(True) if self.material is not None: self.node.setMaterial(self.material, priority=1) self.loaded = True
def draw_rain_mesh(self): _format = GeomVertexFormat.get_v3cp() self.rain_vdata = GeomVertexData('rain', _format, Geom.UHDynamic) self.rain_vdata.setNumRows(self.n_points**2) vertex = GeomVertexWriter(self.rain_vdata, 'vertex') color = GeomVertexWriter(self.rain_vdata, 'color') for j in range(self.n_points): for i in range(self.n_points): # Rain Vertices vertex.addData3f(self.x[j][i], self.y[j][i], self.n_points) # Rain Colors color.addData4f(0.3, 0.3, 1, 0) # Rain Primitive prim = GeomPoints(Geom.UHDynamic) for j in range(self.n_points): for i in range(self.n_points): prim.add_vertices(j * (self.n_points) + i, j * (self.n_points) + i, j * (self.n_points) + i) geom = Geom(self.rain_vdata) prim.closePrimitive() geom.addPrimitive(prim) node = GeomNode('gnode') node.addGeom(geom) rain_nodePath = render.attachNewNode(node) rain_nodePath.setTransparency(TransparencyAttrib.MAlpha) rain_nodePath.setAntialias(AntialiasAttrib.MAuto) rain_nodePath.setRenderModeThickness(2) rain_nodePath.setPos(-50, -50, 0)
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)
def draw(self): if self.rendered_mesh != None: self.reset_draw() format=GeomVertexFormat.getV3n3cp() vdata=GeomVertexData('tri', format, Geom.UHDynamic) vertex=GeomVertexWriter(vdata, 'vertex') normal=GeomVertexWriter(vdata, 'normal') color=GeomVertexWriter(vdata, 'color') v_mapping = {} i=0 for v in self.verts.values(): vertex.addData3f(v.pos.x,v.pos.y,v.pos.z) normal.addData3f(v.norm.x, v.norm.y, v.norm.z) color.addData4f(v.color[0],v.color[1],v.color[2],v.color[3]) v_mapping[v.ID] = i i += 1 mesh = Geom(vdata) for f in self.faces.values(): tri = GeomTriangles(Geom.UHDynamic) tri.addVertex(v_mapping[f.v1.ID]) tri.addVertex(v_mapping[f.v2.ID]) tri.addVertex(v_mapping[f.v3.ID]) tri.closePrimitive() mesh.addPrimitive(tri) snode = GeomNode(self.name) snode.addGeom(mesh) self.rendered_mesh = render.attachNewNode(snode) self.rendered_mesh.setTwoSided(True)
class Sky(object): def __init__(self, mp): vdata = GeomVertexData('name_me', GeomVertexFormat.getV3c4(), Geom.UHStatic) vertex = GeomVertexWriter(vdata, 'vertex') color = GeomVertexWriter(vdata, 'color') primitive = GeomTristrips(Geom.UHStatic) film_size = base.cam.node().getLens().getFilmSize() x = film_size.getX() / 2.0 z = x * 256.0 / 240.0 vertex.addData3f(x, 90, z) vertex.addData3f(-x, 90, z) vertex.addData3f(x, 90, -z) vertex.addData3f(-x, 90, -z) color.addData4f(VBase4(*mp['backgroundcolor1'])) color.addData4f(VBase4(*mp['backgroundcolor1'])) color.addData4f(VBase4(*mp['backgroundcolor2'])) color.addData4f(VBase4(*mp['backgroundcolor2'])) primitive.addNextVertices(4) primitive.closePrimitive() geom = Geom(vdata) geom.addPrimitive(primitive) self.node = GeomNode('sky') self.node.addGeom(geom) base.camera.attachNewNode(self.node) def remove(self): NodePath(self.node).removeNode()
def __build_Tris(self, sphere, mode): vdata = GeomVertexData("Data", self.__vformat[mode], Geom.UHStatic) _num_rows = len(sphere.pts) # Vertices. vertices = GeomVertexWriter(vdata, "vertex") vertices.reserveNumRows(_num_rows) for pt in sphere.pts: vertices.addData3f(*pt) # Map coords. if mode == "mid": mapcoords = GeomVertexWriter(vdata, "mapcoord") mapcoords.reserveNumRows(_num_rows) for mc in sphere.coords: u, v = mc[:2] mapcoords.addData2f(u,v) # Tris. prim = GeomTriangles(Geom.UHStatic) prim.reserveNumVertices(len(sphere.tris)) for tri in sphere.tris: prim.addVertices(*tri) prim.closePrimitive() # Geom. geom = Geom(vdata) geom.addPrimitive(prim) geom_node = GeomNode("geom") geom_node.addGeom(geom) geom_np = NodePath(geom_node) return geom_np
def draw(self): if self.rendered_mesh != None: self.reset_draw() format = GeomVertexFormat.getV3n3cp() vdata = GeomVertexData('tri', format, Geom.UHDynamic) vertex = GeomVertexWriter(vdata, 'vertex') normal = GeomVertexWriter(vdata, 'normal') color = GeomVertexWriter(vdata, 'color') v_mapping = {} i = 0 for v in self.verts.values(): vertex.addData3f(v.pos.x, v.pos.y, v.pos.z) normal.addData3f(v.norm.x, v.norm.y, v.norm.z) color.addData4f(v.color[0], v.color[1], v.color[2], v.color[3]) v_mapping[v.ID] = i i += 1 mesh = Geom(vdata) for f in self.faces.values(): tri = GeomTriangles(Geom.UHDynamic) tri.addVertex(v_mapping[f.v1.ID]) tri.addVertex(v_mapping[f.v2.ID]) tri.addVertex(v_mapping[f.v3.ID]) tri.closePrimitive() mesh.addPrimitive(tri) snode = GeomNode(self.name) snode.addGeom(mesh) self.rendered_mesh = render.attachNewNode(snode) self.rendered_mesh.setTwoSided(True)
def __init__(self, scale=10): axisNode = GeomNode('axis') axisGeom = makeAxis() axisNode.addGeom(axisGeom) axis = render.attachNewNode(axisNode) axis.setScale(scale,scale,scale) axis.setRenderModeThickness(2)
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)
def makeSimpleGeomBuffer(array, color, geomType=GeomPoints): """ massively faster than the nonbuffer version """ full = [tuple(d) for d in np.hstack((array, color))] fmt = GeomVertexFormat.getV3c4() vertexData = GeomVertexData( 'points', fmt, Geom.UHDynamic ) #FIXME use the index for these too? with setPythonTag, will have to 'reserve' some cloudGeom = Geom(vertexData) cloudNode = GeomNode('just some points') vertexData.setNumRows(len(array)) mem_array = vertexData.modifyArray(0) view = memoryview(mem_array) arr = np.asarray(view) arr[:] = full points = geomType(Geom.UHDynamic) points.addConsecutiveVertices(0, len(array)) points.closePrimitive() cloudGeom.addPrimitive(points) cloudNode.addGeom(cloudGeom) return cloudNode
def create_geom(self, sidelength): # Set up the vertex arrays vformat = GeomVertexFormat.getV3n3c4() vdata = GeomVertexData("Data", vformat, Geom.UHDynamic) vertex = GeomVertexWriter(vdata, 'vertex') normal = GeomVertexWriter(vdata, 'normal') color = GeomVertexWriter(vdata, 'color') geom = Geom(vdata) # Write vertex data for x in range(0, sidelength): for y in range(0, sidelength): # vertex_number = x * sidelength + y v_x, v_y, v_z = self.map_b[(x, y)] n_x, n_y, n_z = 0.0, 0.0, 1.0 c_r, c_g, c_b, c_a = 0.5, 0.5, 0.5, 0.5 vertex.addData3f(v_x, v_y, v_z) normal.addData3f(n_x, n_y, n_z) color.addData4f(c_r, c_g, c_b, c_a) # Add triangles for x in range(0, sidelength - 1): for y in range(0, sidelength - 1): # The vertex arrangement (y up, x right) # 2 3 # 0 1 v_0 = x * sidelength + y v_1 = x * sidelength + (y + 1) v_2 = (x + 1) * sidelength + y v_3 = (x + 1) * sidelength + (y + 1) if (x+y)%1 == 0: # An even square tris = GeomTriangles(Geom.UHStatic) tris.addVertices(v_0, v_2, v_3) tris.closePrimitive() geom.addPrimitive(tris) tris = GeomTriangles(Geom.UHStatic) tris.addVertices(v_3, v_1, v_0) tris.closePrimitive() geom.addPrimitive(tris) else: # An odd square tris = GeomTriangles(Geom.UHStatic) tris.addVertices(v_1, v_0, v_2) tris.closePrimitive() geom.addPrimitive(tris) tris = GeomTriangles(Geom.UHStatic) tris.addVertices(v_2, v_3, v_1) tris.closePrimitive() geom.addPrimitive(tris) # Create the actual node node = GeomNode('geom_node') node.addGeom(geom) # Remember GeomVertexWriters to adjust vertex data later #self.vertex_writer = vertex #self.color_writer = color self.vdata = vdata return node
def getGeomNode(self): if self.finished == False: self.triangles.closePrimitive() self.mesh.addPrimitive(self.triangles) self.finished = True geomNode = GeomNode(self.name) geomNode.addGeom(self.mesh) return geomNode
def __init__(self, mesh, pm_filebuf): scene_members = getSceneMembers(mesh) base = ShowBase() if len(scene_members) > 1: print('There is more than one geometry in the scene, so I think this is not a progressive base mesh.') sys.exit(1) rotateNode = GeomNode("rotater") rotatePath = render.attachNewNode(rotateNode) matrix = numpy.identity(4) if mesh.assetInfo.upaxis == collada.asset.UP_AXIS.X_UP: r = collada.scene.RotateTransform(0,1,0,90) matrix = r.matrix elif mesh.assetInfo.upaxis == collada.asset.UP_AXIS.Y_UP: r = collada.scene.RotateTransform(1,0,0,90) matrix = r.matrix rotatePath.setMat(Mat4(*matrix.T.flatten().tolist())) geom, renderstate, mat4 = scene_members[0] node = GeomNode("primitive") node.addGeom(geom) if renderstate is not None: node.setGeomState(0, renderstate) self.geomPath = rotatePath.attachNewNode(node) self.geomPath.setMat(mat4) wrappedNode = ensureCameraAt(self.geomPath, base.camera) base.disableMouse() attachLights(render) render.setShaderAuto() render.setTransparency(TransparencyAttrib.MDual, 1) base.render.analyze() KeyboardMovement() MouseDrag(wrappedNode) MouseScaleZoom(wrappedNode) ButtonUtils(wrappedNode) MouseCamera() print('Loading pm into memory... ', end=' ') sys.stdout.flush() self.pm_refinements = readPDAE(pm_filebuf) self.pm_index = 0 print('Done') self.slider = DirectSlider(range=(0,len(self.pm_refinements)), value=0, pageSize=len(self.pm_refinements)/20, command=self.sliderMoved, pos=(0, 0, -.9), scale=1) for key, val in uiArgs.items(): self.slider.thumb[key] = val self.triText = OnscreenText(text="", pos=(-1,0.85), scale = 0.15, fg=(1, 0.5, 0.5, 1), align=TextNode.ALeft, mayChange=1) base.run()
def __init__(self): ShowBase.__init__(self) PanditorDisableMouseFunc() camera.setPos(0.0, 0.0, 50.0) camera.lookAt(0.0) PanditorEnableMouseFunc() # 1) create GeomVertexData frmt = GeomVertexFormat.getV3n3cp() vdata = GeomVertexData('triangle', frmt, Geom.UHDynamic) # 2) create Writers/Rewriters (must all be created before any readers and readers are one-pass-temporary) vertex = GeomVertexRewriter(vdata, 'vertex') normal = GeomVertexRewriter(vdata, 'normal') color = GeomVertexRewriter(vdata, 'color') zUp = Vec3(0, 0, 1) wt = Vec4(1.0, 1.0, 1.0, 1.0) gr = Vec4(0.5, 0.5, 0.5, 1.0) # 3) write each column on the vertex data object (for speed, have a different writer for each column) def addPoint(x, y, z): vertex.addData3f(x, y, z) normal.addData3f(zUp) color.addData4f(wt) addPoint(0.0, 0.0, 0.0) addPoint(5.0, 0.0, 0.0) addPoint(0.0, 5.0, 0.0) addPoint(5.0, 5.0, 0.0) # 4) create a primitive and add the vertices via index (not truely associated with the actual vertex table, yet) tris = GeomTriangles(Geom.UHDynamic) tris.addVertices(0, 1, 2) tris.closePrimitive() # exception thrown if verts added != 3, other types inform Panda how many verts/primitive tris.addVertices(2, 1, 3) print "vdataPoints", vdata.getArrays()[0] # 5.1) (adding to scene) create a Geom and add primitives of like base-type i.e. triangles and triangle strips geom = Geom(vdata) geom.addPrimitive(tris) # 5.2) create a GeomNode to hold the Geom(s) and add the Geom(s) gn = GeomNode('gnode') gn.addGeom(geom) # 5.3) attache the node to the scene gnNodePath = render.attachNewNode(gn) geomPts = Geom(vdata) pts = GeomPoints(Geom.UHStatic) pts.addVertices(0, 1, 2) pts.closePrimitive() geomPts.addPrimitive(pts) pointsNode = GeomNode('points_node') pointsNode.addGeom(geomPts) pointsNP = render.attachNewNode(pointsNode) pointsNP.setZ(0.5) render.ls()
def create_mesh(parentnp, debug=False, invert=False): """This creates a simple 17x17 grid mesh for the sides of our cube. The ultimate goal is to use a LOD system, probably based on quadtrees. If debug is true then we get a color gradiant on our vertexes.""" x = -1.0 y = -1.0 vertex_count = 0 u = 0.0 v = 0.0 WIDTH_STEP = 2 / 16.0 while y <= 1.0: while x <= 1.0: vertex.addData3f(x, y, 0) if invert: normal.addData3f(myNormalize((Vec3(2 * x + 1, 2 * y + 1, 2 * 0 - 1)))) else: normal.addData3f(myNormalize((Vec3(2 * x - 1, 2 * y - 1, 2 * 0 - 1)))) if debug: color.addData4f(1.0, u, v, 1.0) texcoord.addData2f(u, v) vertex_count += 1 x += WIDTH_STEP u += WIDTH_STEP / 2.0 x = -1.0 u = 0 y += WIDTH_STEP v += WIDTH_STEP / 2.0 print vertex_count triangles = [] for y in range(0, 16): for x in range(0, 16): v = 17 * y + x tri = GeomTriangles(Geom.UHDynamic) tri.addVertex(v) tri.addVertex(v + 1) tri.addVertex(v + 17) tri.closePrimitive() triangles.append(tri) tri = GeomTriangles(Geom.UHDynamic) tri.addVertex(v + 1) tri.addVertex(v + 18) tri.addVertex(v + 17) tri.closePrimitive() triangles.append(tri) mesh = Geom(vdata) for t in triangles: mesh.addPrimitive(t) mnode = GeomNode("quadface") mnode.addGeom(mesh) nodePath = parentnp.attachNewNode(mnode) return nodePath
def main(): import pickle from .util.util import ui_text, console, exit_cleanup, frame_rate, startup_data from .keys import AcceptKeys from .render_manager import renderManager from .ui import CameraControl, Axis3d, Grid3d base = ShowBase() base.setBackgroundColor(0,0,0) base.disableMouse() startup_data() console() exit_cleanup() frame_rate() CameraControl() Axis3d() Grid3d() r = renderManager() from .test_objects import makeSimpleGeom import numpy as np from .trees import treeMe from uuid import uuid4 from panda3d.core import GeomLinestrips n = 1000 #positions = np.array([i for i in zip(np.linspace(-1000,1000,n),np.linspace(-1000,1000,n),np.linspace(-1000,1000,n))]) # wat 1 #positions = np.array([i for i in zip(np.linspace(-1000,1000,n),np.linspace(-1000,1000,n),np.zeros(n))]) # wat 2 positions = np.array([i for i in zip(np.linspace(-1000,1000,n),np.zeros(n),np.zeros(n))]) #positions = np.random.randint(-1000,1000,(n,3)) # so it turns out that the collision nodes don't render properly on this, the tree constructed with math is correct, the rendering is not r.geomRoot.attachNewNode(makeSimpleGeom(positions,(1,1,1,1))) uuids = np.array(['%s'%uuid4() for _ in range(n)]) bounds = np.ones(n) * .5 treeMe(r.collRoot, positions, uuids, bounds) base.camLens.setFov(90) n = 1E4 # apparently 1e8 is a bit too big and 1e7 is slowwww... definitely need downsampling positions = np.array([i for i in zip(10*np.sin(np.arange(0,n)),np.arange(0,n),10*np.cos(np.arange(0,n)))]) # fukken saved r.geomRoot.attachNewNode(makeSimpleGeom(positions,(1,1,1,1), geomType=GeomLinestrips)) #with open('edge_case_data_tuple.pickle','rb') as f: #data_tuple = pickle.load(f) #r.cache['edgecase'] = False #r.set_nodes('edgecase',data_tuple) sgn = GeomNode('srct') sgn.addGeom(makeSelectRect()) sn = render.attachNewNode(sgn) sn.setSx(10) sn.setSy(10) sn.setColor(.5,.5,.5,.5) ut = ui_text() dt = BoxSel(visualize = BoxSel.VIS_ALL) ac = AcceptKeys() base.run()
def __init__(self,n): self.accept('escape',sys.exit) poses = np.random.randint(-100,100,(n,3)) geomParent = render.attachNewNode('geomParent') geoms = GeomNode('container') for _ in range(n): ax = makeAxis() #ax.setPos(np.random.randint(-100,100)) #FIXME geoms.addGeom(ax) geomParent.attachNewNode(geoms)
def create_model(self): # Set up the vertex arrays vformatArray = GeomVertexArrayFormat() # Panda3D implicitly generates a bounding volume from a # column named "vertex", so you either # * have a column of that name, or # * add a bounding volume yourself. vformatArray.addColumn(InternalName.make("vertex"), 3, Geom.NTFloat32, Geom.CPoint) vformatArray.addColumn(InternalName.make("color"), 4, Geom.NTFloat32, Geom.CColor) vformat = GeomVertexFormat() vformat.addArray(vformatArray) vformat = GeomVertexFormat.registerFormat(vformat) vdata = GeomVertexData("Data", vformat, Geom.UHStatic) vertex = GeomVertexWriter(vdata, 'vertex') color = GeomVertexWriter(vdata, 'color') geom = Geom(vdata) # Vertex data vertex.addData3f(1.5, 0, -1) color.addData4f(1, 0, 0, 1) vertex.addData3f(-1.5, 0, -1) color.addData4f(0, 1, 0, 1) vertex.addData3f(0, 0, 1) color.addData4f(0, 0, 1, 1) # Primitive tri = GeomPatches(3, Geom.UHStatic) tri.add_vertex(2) tri.add_vertex(1) tri.add_vertex(0) tri.close_primitive() geom.addPrimitive(tri) # Create the actual node node = GeomNode('geom_node') node.addGeom(geom) np = NodePath(node) # Shader, initial shader vars, number of instances np.set_shader(Shader.load(Shader.SL_GLSL, vertex = "shader.vert", tess_control = "shader.tesc", tess_evaluation = "shader.tese", geometry = "shader.geom", fragment = "shader.frag")) np.set_shader_input("time", 0.0) np.set_shader_input("tess_level", 32.0) np.set_instance_count(num_instances) np.set_shader_input("numInstances", num_instances) return np
def Chunk2Geom(self,sChunk,origin): """ Decodes chunk into Panda3D geometry format @param sChunk: encoded chunk origin: chunk location in world as 3-tuple @return A panda3D Node object translated appropriately to place the decoded chunk correctly within the world. """ # determine where chunk should be placed in world space orgX=origin[0] orgY=origin[1] orgZ=origin[2] # determine chunk's coordinate chunkX=orgX/16 chunkY=orgY/16 # generate name tags for the various parts chunkId="%s_%s" % (chunkX,chunkY) vtxName="vtx_%s" % chunkId nodeName="chunk_%s" % chunkId # create empty node for entire chunk chunkNode=render.attachNewNode(nodeName) # convert string chunk to numeric chunk=[ord(c) for c in sChunk] # TODO: read chunk data and generate cube nodes flags=chunk[0]+(chunk[1]<<8)+(chunk[2]<<16)+(chunk[3]<<24) chunk=chunk[4:] # remove biome/flagbits for cY in range(16): for cX in range(16): for cZ in range(256): cell=cZ+(cX<<8)+(cY<<12) # lookup neighbours me=chunk[cell] if me>0: n_up=chunk[cell-1] if cZ>0 else 0 n_dn=chunk[cell+1] if cZ<255 else 0 n_lt=chunk[cell-256] if cX>0 else 0 n_rt=chunk[cell+256] if cX<15 else 0 n_bk=chunk[cell-4096] if cY>0 else 0 n_fd=chunk[cell+4096] if cY<15 else 0 if n_up==0 or n_dn==0 or \ n_lt==0 or n_rt==0 or \ n_bk==0 or n_fd==0: # for any non-obscured block # generate a cube block=GeomNode("%s_block_%s_%s_%s"%(nodeName,cX,cY,cZ)) block.addGeom(self.cubeGeom) blockNode=chunkNode.attachNewNode(block) blockNode.setTexture(self.textures[me]) blockNode.setPos(cX,cY,cZ) chunkNode.setPos(chunkX*16,chunkY*16,-64) return chunkNode
def __init__(self): self.base = ShowBase() self.base.disableMouse() self.base.camera.setPos(0, -10, 0) color_vertices = [(0.2, 0.2, 0.1, 1), (0.2, 0.7, 0.1, 1), (0.7, 0.7, 0.1, 1), (0.7, 0.2, 0.1, 1)] square = make_square(color_vertices) sq_node = GeomNode('square') sq_node.addGeom(square) self.base.render.attachNewNode(sq_node)
def __init__(self): self.escapeText = genLabelText("ESC: Quit", 0) self.accept("escape", sys.exit) cloudNode = GeomNode('points') #self.cloudGeom=makePoints(999999) self.cloudGeom=makePoints(9999) cloudNode.addGeom(self.cloudGeom) #ooops dont forget this! cloud = render.attachNewNode(cloudNode) cloud.hprInterval(20,Point3(360,0,0)).loop() #scale this with zoom taskMgr.add(self.spawnTask,'newInput')