def makePoints(n=1000): """ make a cloud of points that are a single node VS branching and making subnodes to control display """ #points = np.random.uniform(-10,10,(n,4)) points = np.random.randn(n, 3) colors = np.random.rand(n, 4) fmt = GeomVertexFormat.getV3c4() #3 component vertex, w/ 4 comp color vertexData = GeomVertexData('points', fmt, Geom.UHStatic) verts = GeomVertexWriter(vertexData, 'vertex') color = GeomVertexWriter(vertexData, 'color') for point, clr4 in zip(points, colors): #for point in points: verts.addData3f(*point) #color.addData4f(*point) color.addData4f(*clr4) #color.addData4f(.1,.1,.1,1) #pointCloud = GeomLinestrips(Geom.UHStatic) #this is f*****g cool! pointCloud = GeomTristrips(Geom.UHStatic) #this is f*****g cool! #pointCloud = GeomPoints(Geom.UHStatic) #pointCloud.addVerticies(*range(n)) pointCloud.addConsecutiveVertices(0, n) #warning may error since n-1? pointCloud.closePrimitive() cloud = Geom(vertexData) cloud.addPrimitive(pointCloud) return cloud
def __build_ocean_mesh(self): vdata = GeomVertexData('data', GeomVertexFormat.getV3n3c4t2(), Geom.UHStatic) vertex = GeomVertexWriter(vdata, 'vertex') normal = GeomVertexWriter(vdata, 'normal') texcoord = GeomVertexWriter(vdata, 'texcoord') color = GeomVertexWriter(vdata, 'color') axes = [Vec3.unitX(), Vec3.unitY(), Vec3.unitZ()] face = 0 for x in range(3): for s in [-1, 1]: for i in range(self.__n + 1): for j in range(self.__n + 1): a = (i * 1.0 / self.__n) * (pi / 2) - (pi / 4) b = (j * 1.0 / self.__n) * (pi / 2) - (pi / 4) xAxis = axes[(x + 3) % 3] yAxis = axes[(x + 4) % 3] zAxis = axes[(x + 5) % 3] v = (xAxis * (-cos(a) * sin(b)) + yAxis * (sin(a) * cos(b)) + zAxis * (cos(a) * cos(b))) * s v.normalize() normal.addData3f(v) vertex.addData3f(v * self.__radius) texcoord.addData2f(i * 1.0, j * 1.0) color.addData4f(self.__ocean_color) face = face + 1 prim = self.__heightmap_primitive() geom = Geom(vdata) geom.addPrimitive(prim) return geom
def pg_draw_tris(pg, render): format = GeomVertexFormat.getV3c4() vdata = GeomVertexData('pgtris', format, Geom.UHStatic) vdata.setNumRows(len(pg.nodes)) vertex = GeomVertexWriter(vdata, 'vertex') color = GeomVertexWriter(vdata, 'color') prim = GeomTriangles(Geom.UHStatic) for pt in pg.nodes: vertex.addData3f(pt.x, pt.y, pt.z) color.addData4f(random.random(), random.random(), random.random(), 1.0) for pt in pg.nodes: if len(pt.conn) > 0: for i, cpt in enumerate(pt.conn): next_cpt = pt.conn[(i + 1) % len(pt.conn)] prim.addVertices(pt.idx, cpt.idx, next_cpt.idx) print("%d - %d - %d" % (pt.idx, cpt.idx, next_cpt.idx)) geom = Geom(vdata) geom.addPrimitive(prim) node = GeomNode('TheTris') node.addGeom(geom) nodePath = render.attachNewNode(node) nodePath.setPos(0, 10, 0)
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 _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 addPoint(self, x, y, wheel_dir, force): """ Adds a point to the skid mark trail. The coordinates are in the world frame. The force is a number between zero and one, where one is the max force and makes the biggest and darkest skid mark. The argument 'wheel_dir' is given in degrees, where zero points toward the positive X axis. """ h = self.wheel_width * 0.5 rads = (wheel_dir - 90) * math.pi / 180.0 x0b, y0b = x + h * math.cos(rads), y + h * math.sin(rads) rads = (wheel_dir + 90) * math.pi / 180.0 x1b, y1b = x + h * math.cos(rads), y + h * math.sin(rads) x0a, y0a, x1a, y1a = self.lastpoints self.lastpoints = (x0b, y0b, x1b, y1b) if not self.havelast: self.havelast = True return indx = self.nextrect * 4 self.nextrect += 1 if self.nextrect >= self.nrects: self.nextrect = 0 vtx = GeomVertexWriter(self.vdata, "vertex") cx = GeomVertexWriter(self.vdata, "color") vtx.setRow(indx) cx.setRow(indx) c = self.forceToColor(force) vtx.addData3f(x0a, y0a, self.zpos) vtx.addData3f(x1a, y1a, self.zpos) vtx.addData3f(x0b, y0b, self.zpos) vtx.addData3f(x1b, y1b, self.zpos) cx.addData4f(*c) cx.addData4f(*c) cx.addData4f(*c) cx.addData4f(*c)
def makeSelectRect(): ctup = (1, 1, 1, 1) fmt = GeomVertexFormat.getV3c4() vertexData = GeomVertexData('points', fmt, Geom.UHDynamic) points = ( #makes nice for Tristrips (0, 0, 0), (0, 0, 1), (1, 0, 0), (1, 0, 1), ) verts = GeomVertexWriter(vertexData, 'vertex') color = GeomVertexWriter(vertexData, 'color') for point in points: verts.addData3f(*point) color.addData4f(*ctup) boxLines = GeomLinestrips(Geom.UHDynamic) boxLines.addVertices(0, 1, 3, 2) boxLines.addVertex(0) boxLines.closePrimitive() boxTris = GeomTristrips(Geom.UHDynamic) boxTris.addConsecutiveVertices(0, 3) boxTris.closePrimitive() box = Geom(vertexData) box.addPrimitive(boxLines) #box.addPrimitive(boxTris) return box
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 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 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 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 __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_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 create_GeomNode_Single_Point(color_vec4=Vec4(1., 1., 1., 1.)): # ---- step 1: create point at (0,0,0) and close the primitive format = GeomVertexFormat.getV3c4() vdata = GeomVertexData("colored_point", format, Geom.UHStatic) vdata.setNumRows(4) # add color to each vertex colorWriter = GeomVertexWriter(vdata, "color") # add a vertex position to each vertex vertexPosWriter = GeomVertexWriter(vdata, "vertex") # just one origin point vertex, it gets transformed later # to it's intended position vertexPosWriter.addData3f(0., 0., 0.) colorWriter.addData4f(color_vec4) # build the primitive pointsprimitive = GeomPoints(Geom.UHStatic) pointsprimitive.addVertex(0) pointsprimitive.closePrimitive() # this resets all the data contained in the vertexPosWriter and colorWriter # ----- step 3: make a GeomNode out of the Geom (to which the Primitives have been added) # make a Geom object to hold the primitives geom = Geom(vdata) geom.addPrimitive(pointsprimitive) geom_node = GeomNode("colored_point_node") geom_node.addGeom(geom) return geom_node
def makeSelectRect(): ctup = (1,1,1,1) fmt = GeomVertexFormat.getV3c4() vertexData = GeomVertexData('points', fmt, Geom.UHDynamic) points = ( #makes nice for Tristrips (0,0,0), (0,0,1), (1,0,0), (1,0,1), ) verts = GeomVertexWriter(vertexData, 'vertex') color = GeomVertexWriter(vertexData, 'color') for point in points: verts.addData3f(*point) color.addData4f(*ctup) boxLines = GeomLinestrips(Geom.UHDynamic) boxLines.addVertices(0,1,3,2) boxLines.addVertex(0) boxLines.closePrimitive() boxTris = GeomTristrips(Geom.UHDynamic) boxTris.addConsecutiveVertices(0,3) boxTris.closePrimitive() box = Geom(vertexData) box.addPrimitive(boxLines) #box.addPrimitive(boxTris) return box
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 make_geom(vertices, normals, colors, texcoords): if panda3d is None: raise ImportError("Cannot locate Panda3D") format = "V3" if normals is not None: assert len(normals) == len(vertices) format += "n3" if colors is not None: assert len(colors) == len(vertices) format += "cp" if texcoords is not None: assert len(texcoords) == len(vertices) format += "t2" format = getattr(GeomVertexFormat, "get" + format)() vdata = GeomVertexData("", format, Geom.UHStatic) v_vertex = GeomVertexWriter(vdata, 'vertex') if normals is not None: v_normals = GeomVertexWriter(vdata, 'normal') if colors is not None: v_colors = GeomVertexWriter(vdata, 'color') if texcoords is not None: v_texcoords = GeomVertexWriter(vdata, 'texcoord') for n in range(len(vertices)): v_vertex.addData3f(*vertices[n]) if normals is not None: v_normals.addData3f(*normals[n]) if colors is not None: v_colors.addData4f(*colors[n]) if texcoords is not None: v_texcoords.addData2f(*texcoords[n]) return Geom(vdata)
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 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 __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 primitives(self, vdata): vertex = GeomVertexWriter(vdata, 'vertex') color = GeomVertexWriter(vdata, 'color') n = len(self.border) # Points for p in self.border: vertex.addData3f(p.x, p.y, p.z) color.addData4f(0.5, 0.5, 0.5, 0.0) for p in self.border: vertex.addData3f(p.x, p.y, p.z + self.top) color.addData4f(1.0, 1.0, 1.0, 0.0) # Wall wall = GeomTristrips(Geom.UHStatic) for i in range(n): wall.addVertices(i, i + n) wall.addVertices(0, n) wall.closePrimitive() yield wall # Ceiling if self.cover: ceil = GeomTristrips(Geom.UHStatic) ceil.addConsecutiveVertices(n, n) ceil.addVertex(n) ceil.closePrimitive() yield ceil
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 createColoredUnitDisk(color_vec4=Vec4(0., 0., 1., 1.), num_of_verts=10, origin_point=Vec3(0., 0., 0.), radius=1.): # Own Geometry # format = GeomVertexFormat.getV3c4t2() format = GeomVertexFormat.getV3c4() vdata = GeomVertexData("colored_circle", format, Geom.UHStatic) vdata.setNumRows(4) vertexPosWriter = GeomVertexWriter(vdata, "vertex") # num_of_verts = 10 # phi = 0. r = radius # origin_point_x = 0. # origin_point_z = 0. vertexPosWriter.addData3f(origin_point[0], origin_point[1], origin_point[2]) circle_points = math_utils.get_circle_vertices(num_of_verts=num_of_verts, radius=r) circle_points[:,0] += origin_point[0] circle_points[:,1] += origin_point[1] circle_points[:,2] += origin_point[2] _normal_vector_info = Vec3(0., 1., 0.) # this is returned just as info about the normal vector of the generated geometry for p in circle_points: vertexPosWriter.addData3f(p[0], 0, p[1]) # for i in range(num_of_verts): # phi += 2. * np.pi / num_of_verts # x = r * np.cos(phi) # z = r * np.sin(phi) # vertexPosWriter.addData3f(x, 0, z) # let's also add color to each vertex colorWriter = GeomVertexWriter(vdata, "color") colorWriter.addData4f(color_vec4) # origin point for i in range(num_of_verts): colorWriter.addData4f(color_vec4) # make primitives and assign vertices to them (primitives and primitive # groups can be made independently from vdata, and are later assigned # to vdata) tris = GeomTrifans(Geom.UHStatic) # the first vertex is a vertex that all triangles share tris.add_consecutive_vertices(0, num_of_verts+1) tris.addVertex(1) tris.closePrimitive() # the 1st primitive is finished # make a Geom object to hold the primitives geom = Geom(vdata) geom.addPrimitive(tris) geom_node = GeomNode("colored_circle_node") geom_node.addGeom(geom) return geom_node, _normal_vector_info
def makePoints(n=1000): """ make a cloud of points that are a single node VS branching and making subnodes to control display """ #points = np.random.uniform(-10,10,(n,4)) points = np.random.randn(n,3) colors = np.random.rand(n,4) fmt = GeomVertexFormat.getV3c4() #3 component vertex, w/ 4 comp color vertexData = GeomVertexData('points', fmt, Geom.UHStatic) verts = GeomVertexWriter(vertexData, 'vertex') color = GeomVertexWriter(vertexData, 'color') for point,clr4 in zip(points,colors): #for point in points: verts.addData3f(*point) #color.addData4f(*point) color.addData4f(*clr4) #color.addData4f(.1,.1,.1,1) #pointCloud = GeomLinestrips(Geom.UHStatic) #this is f*****g cool! pointCloud = GeomTristrips(Geom.UHStatic) #this is f*****g cool! #pointCloud = GeomPoints(Geom.UHStatic) #pointCloud.addVerticies(*range(n)) pointCloud.addConsecutiveVertices(0,n) #warning may error since n-1? pointCloud.closePrimitive() cloud = Geom(vertexData) cloud.addPrimitive(pointCloud) return cloud
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, base, obj, **kwargs): super(GalaxyView, self).__init__(base, obj, **kwargs) array = GeomVertexArrayFormat() array.addColumn(InternalName.make('vertex'), 3, Geom.NTFloat32, Geom.CPoint) array.addColumn(InternalName.make('color'), 4, Geom.NTFloat32, Geom.CColor) array.addColumn(InternalName.make('size'), 1, Geom.NTFloat32, Geom.COther) gmformat = GeomVertexFormat() gmformat.addArray(array) gmformat = GeomVertexFormat.registerFormat(gmformat) vdata = GeomVertexData('points', gmformat, Geom.UHDynamic) vertex = GeomVertexWriter(vdata, 'vertex') color = GeomVertexWriter(vdata, 'color') size = GeomVertexWriter(vdata, 'size') self.node = NodePath('galaxy') self.node.reparentTo(self.base.render) self.node.setTransparency(TransparencyAttrib.MAlpha) lumsort = sorted([star.luminosity for star in self.obj.stars]) #highest_luminosity = lumsort[-1] median_luminosity = lumsort[len(lumsort) / 2] for star in self.obj.stars: vertex.addData3f(star.galpos.x, star.galpos.y, star.galpos.z) color.addData4f(star.red, star.green, star.blue, 1.0) #size.addData1f(min(100, max(5, 10-star.magnitude/2))) sizeval = 10 + log(star.luminosity) size.addData1f(min(30, max(10, sizeval))) prim = GeomPoints(Geom.UHStatic) prim.addConsecutiveVertices(0, len(self.obj.stars)) prim.closePrimitive() geom = Geom(vdata) geom.addPrimitive(prim) node = GeomNode('gnode') node.addGeom(geom) galaxy_node = self.node.attachNewNode(node) galaxy_node.setRenderModeThickness(1) ts = TextureStage.getDefault() #TextureStage('ts') #ts.setMode(TextureStage.MGlow) galaxy_node.setTexGen(ts, TexGenAttrib.MPointSprite) galaxy_node.setTexture( ts, self.base.loader.loadTexture('texture/flare.png')) #galaxy_node.setRenderModePerspective(True) galaxy_node.setBin("unsorted", 1) galaxy_node.setDepthWrite(0) galaxy_node.setTransparency(1) self.setup_glow_shader() """
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 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 # Vertex data for the poles needs to be different for key, value in self.map.items(): v_x, v_y, v_z, asteroid_color = value n_x, n_y, n_z = 1, 1, 1 #c_r, c_g, c_b, c_a = asteroid_color, asteroid_color, asteroid_color, 1 c_r, c_g, c_b, c_a = asteroid_color, asteroid_color, asteroid_color, 1 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) #Create triangles #top of sphere verts_per_row = int(360 / self.step) + 1 for vert in range(1, verts_per_row + 1): tris = GeomTriangles(Geom.UHStatic) tris.addVertices(vert + 1, 0, vert) tris.closePrimitive() geom.addPrimitive(tris) #middle of shpere for row in range(1, int(180 / self.step) - 1): for vert_iir in range( 0, verts_per_row - 1): # vert_iir = vertex index in row, not vertex number vert_number = verts_per_row * row + vert_iir + 1 vert_up_row = vert_number - verts_per_row #Bottom Triangle in the sphere tris = GeomTriangles(Geom.UHStatic) tris.add_vertices(vert_up_row, vert_number, vert_up_row + 1) tris.close_primitive() geom.addPrimitive(tris) #Top triangle of square tris = GeomTriangles(Geom.UHStatic) tris.add_vertices(vert_number + 1, vert_up_row + 1, vert_number) tris.close_primitive() geom.addPrimitive(tris) #bottom of sphere last_vert = len(self.map) - 1 for vert in range(last_vert - verts_per_row, last_vert): tris = GeomTriangles(Geom.UHStatic) tris.add_vertices(vert - 1, last_vert, vert) tris.close_primitive() geom.addPrimitive(tris) # Create the actual node node = GeomNode('geom_node') node.addGeom(geom) return node
class Skidmark: def __init__(self, wheel_pos, radius, heading): self.radius = radius v_f = GeomVertexFormat.getV3() self.vdata = GeomVertexData('skid', v_f, Geom.UHDynamic) self.vdata.setNumRows(1) self.vertex = GeomVertexWriter(self.vdata, 'vertex') self.prim = GeomTriangles(Geom.UHStatic) self.cnt = 1 self.last_pos = wheel_pos geom = Geom(self.vdata) geom.addPrimitive(self.prim) node = GeomNode('gnode') node.addGeom(geom) nodePath = render.attachNewNode(node) nodePath.setTransparency(True) nodePath.setDepthOffset(1) self.__set_material(nodePath) nodePath.node().setBounds(OmniBoundingVolume()) self.add_vertices(radius, heading) self.add_vertices(radius, heading) self.remove_seq = Sequence( Wait(8), LerpFunc(nodePath.setAlphaScale, 8, 1, 0, 'easeInOut'), Func(nodePath.remove_node)) self.remove_seq.start() def __set_material(self, nodePath): mat = Material() mat.setAmbient((.35, .35, .35, .5)) mat.setDiffuse((.35, .35, .35, .5)) mat.setSpecular((.35, .35, .35, .5)) mat.setShininess(12.5) nodePath.set_material(mat, 1) def add_vertices(self, radius, heading): base_pos = self.last_pos + (0, 0, -radius + .05) rot_mat = Mat4() rot_mat.setRotateMat(heading, (0, 0, 1)) self.vertex.addData3f(base_pos + rot_mat.xformVec((-.12, 0, 0))) self.vertex.addData3f(base_pos + rot_mat.xformVec((.12, 0, 0))) if self.cnt >= 3: self.prim.addVertices(self.cnt - 3, self.cnt - 2, self.cnt - 1) self.prim.addVertices(self.cnt - 2, self.cnt, self.cnt - 1) self.cnt += 2 def update(self, pos, heading): if (pos - self.last_pos).length() > .2: self.last_pos = pos self.add_vertices(self.radius, heading) def destroy(self): self.remove_seq = self.remove_seq.finish()
def makeGeom(index_counter, array, ctup, i, pipe, geomType=GeomPoints): """ multiprocessing capable geometery maker """ #man = indexMan(('127.0.0.1',5000), authkey='none') #man.connect() #index = man.index() index = {} fmt = GeomVertexFormat.getV3c4() vertexData = GeomVertexData( 'points', fmt, Geom.UHDynamic ) #FIXME use the index for these too? with setPythonTag, will have to 'reserve' some #vertexData.setPythonTag('uid',index.reserve()) #maybe we don't need this? the geom should have it all? cloudGeom = Geom(vertexData) #cloudGeom.setPythonTag('uid',index.reserve()) cloudNode = GeomNode('bin %s selectable' % (i)) uid = next(index_counter) index[uid] = None cloudNode.setPythonTag( 'uid', uid ) #FIXME we return cloudnode elsewhere... maybe on the other end we can set the uid in the index properly? points = array verts = GeomVertexWriter(vertexData, 'vertex') color = GeomVertexWriter(vertexData, 'color') for point in points: index[next(index_counter)] = [ point, cloudNode.getPythonTag('uid'), None ] #FIXME we're gonna need a decode on the other end? 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... #output[i] = cloudNode #print('ping',{i:cloudNode}) #pipe.send((i,)) #out = q.get() #print('pong',out) #q.put(out) if pipe == None: return cloudNode, index pipe.send( cloudNode.encodeToBamStream()) #FIXME make this return a pointer NOPE pipe.send(index) #FIXME make this return a pointer NOPE
def set_points(self, position, color): assert len(position) == len(color) self.vertexData.setNumRows(len(position)) self.primitive.clearVertices() for i in range(len(position)): self.primitive.addVertex(i) self.primitive.closePrimitive() positionWriter = GeomVertexWriter(self.vertexData, "vertex") colorWriter = GeomVertexWriter(self.vertexData, "color") for p, c in zip(position, color): positionWriter.addData3f(p[0], p[1], p[2]) colorWriter.addData4f(c[0], c[1], c[2], c[3])
def makeAxis(): #FIXME make this scale based on zoom??? """ x y z r g b """ colors = ( (1,0,0,1), (0,1,0,1), (0,0,1,1), (1,0,0,1), (0,1,0,1), (0,0,1,1), ) points = ( (0,0,0), (0,0,0), (0,0,0), (1,0,0), (0,1,0), (0,0,1), ) fmt = GeomVertexFormat.getV3c4() #3 component vertex, w/ 4 comp color #fmt = GeomVertexFormat.getV3() #3 component vertex, w/ 4 comp color vertexData = GeomVertexData('points', fmt, Geom.UHStatic) verts = GeomVertexWriter(vertexData, 'vertex') color = GeomVertexWriter(vertexData, 'color') for p,c in zip(points,colors): verts.addData3f(*p) color.addData4f(*c) axisX = GeomLinestrips(Geom.UHStatic) axisX.addVertices(0,3) axisX.closePrimitive() axisY = GeomLinestrips(Geom.UHStatic) axisY.addVertices(1,4) axisY.closePrimitive() axisZ = GeomLinestrips(Geom.UHStatic) axisZ.addVertices(2,5) axisZ.closePrimitive() axis = Geom(vertexData) axis.addPrimitive(axisX) axis.addPrimitive(axisY) axis.addPrimitive(axisZ) return axis
def update_geometry(self): # The geosphere itself vertex = GeomVertexWriter(self.sphere_vdata, 'vertex') normal = GeomVertexWriter(self.sphere_vdata, 'normal') # u_map and v_map are in [-pi, pi] u_map_list = [(float(u) / float(self.res[0]) - 0.5) * 2.0 * pi for u in range(0, self.res[0] + 1)] v_map_list = [(float(v) / float(self.res[1]) - 0.5) * 2.0 * pi for v in range(0, self.res[1] + 1)] if self.unwrap_state == 0.0: # Flat map for v_map in v_map_list: for u_map in u_map_list: vertex.addData3f(u_map, 0.0, v_map / 2.0) normal.addData3f(0.0, -1.0, 0.0) else: # Non-flat map sphere_radius = 1.0 / self.unwrap_state sphere_offset = sphere_radius - self.unwrap_state for v_map in v_map_list: for u_map in u_map_list: u_sphere = u_map / sphere_radius v_sphere = v_map / sphere_radius # And this, kids, is why you should pay attention in trigonometry. v_x, v_y, v_z = sin(u_sphere) * cos(v_sphere/2.0) * sphere_radius, \ -cos(u_sphere) * cos(v_sphere/2.0) * sphere_radius + sphere_offset, \ sin(v_sphere / 2.0) * sphere_radius n_x_un, n_y_un, n_z_un = v_x, sphere_offset - v_y, v_z # FIXME: This is a lie. length = sqrt(n_x_un**2 + n_y_un**2 + n_z_un**2) n_x, n_y, n_z = n_x_un / length, n_y_un / length, n_z_un / length vertex.addData3f(v_x, v_y, v_z) normal.addData3f(n_x, n_y, n_z) # The connections between bases segs_per_connection = 30 vertex = GeomVertexWriter(self.connections_vdata, 'vertex') color = GeomVertexWriter(self.connections_vdata, 'color') for c_1_uv, c_2_uv in self.connections: # s will be [0.0, 1.0] for s in [float(c)/float(segs_per_connection+1) for c in range(0, segs_per_connection+2)]: u = (c_1_uv[0] * s) + (c_2_uv[0] * (1.0 - s)) v = (c_1_uv[1] * s) + (c_2_uv[1] * (1.0 - s)) (v_x, v_y, v_z), (n_x, n_y, n_z) = self.uv_to_xyz(u, v) min_height = 0.0001 * (1.0 - self.unwrap_state) max_height = (0.2 - min_height) * self.unwrap_state seg_height = (1.0 - (abs(s-0.5) * 2.0)**2.0) * max_height + min_height vertex.addData3f(v_x + n_x*seg_height, v_y + n_y*seg_height, v_z + n_z*seg_height) color.addData4f(1, 1, 1, 1) for c in range(0, len(self.connections)): for s in range(0, segs_per_connection+1): seg = GeomLines(Geom.UHDynamic) seg.addVertices(c*(segs_per_connection+2) + s, c*(segs_per_connection+2) + s + 1) seg.closePrimitive() self.connections_geom.addPrimitive(seg)
def draw_landscape_mesh(self): _format = GeomVertexFormat.get_v3n3cp() self.landscape_vdata = GeomVertexData('terrain', _format, Geom.UHStatic) self.landscape_vdata.setNumRows(self.n_points**2) vertex = GeomVertexWriter(self.landscape_vdata, 'vertex') normal = GeomVertexWriter(self.landscape_vdata, 'normal') color = GeomVertexWriter(self.landscape_vdata, 'color') for j in range(self.n_points): for i in range(self.n_points): # Terrain Vertices vertex.addData3f(self.x[j][i], self.y[j][i], self.lz[j][i]) # Terrain Colors if self.lz[j][i] < 2: color.addData4f(0.3, 0.2, 0.1, 1) elif self.lz[j][i] < 5: color.addData4f(0.8, 0.8, 0.4, 1) elif self.lz[j][i] < 50: color.addData4f(0, 0.5, 0, 1) elif self.lz[j][i] < 70: color.addData4f(0, 0.3, 0, 1) elif self.lz[j][i] < 80: color.addData4f(0.7, 0.7, 0.7, 1) else: color.addData4f(0.8, 1, 1, 1) # Terrain Normals if self.lz[j][i] != 0: n = np.array([self.x[j][i], self.y[j][i], self.lz[j][i]]) else: n = np.array([self.x[j][i], self.y[j][i], 1e-12]) norm = n / np.linalg.norm(n) normal.addData3f(norm[0], norm[1], norm[2]) # Terrain Primitive prim = GeomTriangles(Geom.UHStatic) for j in range(self.n_points): for i in range(self.n_points): if j != self.n_points - 1 and i != self.n_points - 1: prim.add_vertices(j * (self.n_points) + i, j * (self.n_points) + (i + 1), (j + 1) * (self.n_points) + i) prim.add_vertices(j * (self.n_points) + (i + 1), (j + 1) * (self.n_points) + (i + 1), (j + 1) * (self.n_points) + i) geom = Geom(self.landscape_vdata) prim.closePrimitive() geom.addPrimitive(prim) node = GeomNode('gnode') node.addGeom(geom) landscape_nodePath = render.attachNewNode(node) landscape_nodePath.setPos(-50, -50, 0) landscape_nodePath.setAntialias(AntialiasAttrib.MAuto) return landscape_nodePath
def __init__(self, nrects: int = 100, wheel_width=0.2, zpos=-0.38): """ Initalizes one track for a skid mark. The mark will be placed parallel to X-Y in world coordinates. They will be placed at the given height given by 'zpos'. The 'nrects' argument specifies how long the skid can be in input point locations. You can make the skid mark longer by increasing nrects, or spreading out the distance between input points. Once nrect points have been input, the earlier points will disappear. The 'wheel-width' parameter is the thickness of the wheel that is producing the marks. """ self.wheel_width = wheel_width # One unit = about 10 inches in current world. self.wheel_state = [ ] # Tupels of: X, Y position of wheel, While Direction in degrees, and force self.nrects = nrects self.zpos = zpos self.vdata = GeomVertexData("skid", GeomVertexFormat.getV3c4(), Geom.UHStatic) self.vdata.setNumRows(4 * nrects) vtx = GeomVertexWriter(self.vdata, "vertex") cx = GeomVertexWriter(self.vdata, "color") prim = GeomTriangles(Geom.UHStatic) c = self.forceToColor(0.0) # Here we set up all the vertexts and the primatives that use them. For each set of four vertices, a # flat rectangle is defined. Then 4 primatives are defined by splitting up the rectangle into pair of 2 # triangles -- 4 triangles per rectangle. Each pair of triangles are identical, except that their normals # are opposite, so that we don't have to worry about back culling later. Although it would be possible # to share vertics between the rectangles we don't do that here so that the chain can be cut at any point # by only operating on the vertics and not visiting the primatives. Finally, to "disable" a rectangle, # we set all the vertics to the same point in 3D space (and therefore create a zero-area rectangle). for i in range(nrects): vtx.addData3f(0.0, 0.0, 0.0) vtx.addData3f(0.0, 0.0, 0.0) vtx.addData3f(0.0, 0.0, 0.0) vtx.addData3f(0.0, 0.0, 0.0) cx.addData4f(*c) cx.addData4f(*c) cx.addData4f(*c) cx.addData4f(*c) j = i * 4 j0, j1, j2, j3 = j + 0, j + 1, j + 2, j + 3 prim.addVertices(j0, j1, j3) prim.addVertices(j3, j1, j0) prim.addVertices(j0, j3, j2) prim.addVertices(j2, j3, j0) prim.closePrimitive() geom = Geom(self.vdata) geom.addPrimitive(prim) node = GeomNode('Skid') node.addGeom(geom) self.nodepath = render.attachNewNode(node) self.nextrect = 0 self.havelast = False self.lastpoints = (0, 0, 0, 0)
def drawBody(self, pos, quat, radius=1,UVcoord=(1,1), numVertices=_polySize): # if isRoot: # self.bodydata = GeomVertexData("body vertices", GeomVertexFormat.getV3n3t2(), Geom.UHStatic) vdata = self.bodydata circleGeom = Geom(vdata) # this was originally a copy of all previous geom in vdata... vertWriter = GeomVertexWriter(vdata, "vertex") #colorWriter = GeomVertexWriter(vdata, "color") normalWriter = GeomVertexWriter(vdata, "normal") # drawReWriter = GeomVertexRewriter(vdata, "drawFlag") texReWriter = GeomVertexRewriter(vdata, "texcoord") startRow = vdata.getNumRows() vertWriter.setRow(startRow) #colorWriter.setRow(startRow) normalWriter.setRow(startRow) texReWriter.setRow(startRow) #axisAdj=Mat4.rotateMat(45, axis)*Mat4.scaleMat(radius)*Mat4.translateMat(pos) perp1 = quat.getRight() perp2 = quat.getForward() #TODO: PROPERLY IMPLEMENT RADIAL NOISE #vertex information is written here angleSlice = 2 * pi / numVertices currAngle = 0 for i in xrange(numVertices+1): adjCircle = pos + (perp1 * cos(currAngle) + perp2 * sin(currAngle)) * radius * (.5+bNodeRadNoise*random.random()) normal = perp1 * cos(currAngle) + perp2 * sin(currAngle) normalWriter.addData3f(normal) vertWriter.addData3f(adjCircle) texReWriter.addData2f(float(UVcoord[0]*i) / numVertices,UVcoord[1]) # UV SCALE HERE! #colorWriter.addData4f(0.5, 0.5, 0.5, 1) currAngle += angleSlice #we cant draw quads directly so we use Tristrips if (startRow != 0): 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) return circleGeomNode
def createTexturedUnitQuadGeomNode(): # Own Geometry # format = GeomVertexFormat.getV3c4t2() format = GeomVertexFormat.getV3t2() vdata = GeomVertexData("textured_quad", format, Geom.UHStatic) vdata.setNumRows(4) vertexPosWriter = GeomVertexWriter(vdata, "vertex") vertexPosWriter.addData3f(0, 0, 0) vertexPosWriter.addData3f(1, 0, 0) vertexPosWriter.addData3f(1, 0, 1) vertexPosWriter.addData3f(0, 0, 1) # let's also add color to each vertex # colorWriter = GeomVertexWriter(vdata, "color") # colorWriter.addData4f(0,0,1,1) # colorWriter.addData4f(0,0,1,1) # colorWriter.addData4f(0,0,1,1) # colorWriter.addData4f(0,0,1,1) # let's add texture coordinates (u,v) texcoordWriter = GeomVertexWriter(vdata, "texcoord") texcoordWriter.addData2f(0, 0) texcoordWriter.addData2f(1, 0) texcoordWriter.addData2f(1, 1) texcoordWriter.addData2f(0, 1) # make primitives and assign vertices to them (primitives and primitive # groups can be made independently from vdata, and are later assigned # to vdata) tris = GeomTriangles(Geom.UHStatic) # 1st triangle tris.addVertices(0, 1, 3) tris.closePrimitive() # the 1st primitive is finished # 2nd triangle tris.addVertices(1, 2, 3) tris.closePrimitive() # make a Geom object to hold the primitives quadGeom = Geom(vdata) quadGeom.addPrimitive(tris) # now put quadGeom in a GeomNode. You can now position your geometry # in the scene graph. quadGeomNode = GeomNode("quad") quadGeomNode.addGeom(quadGeom) return quadGeomNode
def create_colored_polygon2d_GeomNode_from_point_cloud(point_cloud, color_vec4=Vec4(0., 0., 1., 1.)): # for triangulation (with tripy) the elements of point_cloud # must be 3-tuples instead of np.arrays triangles = tripy_modified.earclip( [tuple(elem) for elem in point_cloud]) triangles = np.array(triangles) # convert tuples to np.arrays # naive rendering: abusing the concept of an index buffer # format = GeomVertexFormat.getV3c4t2() format = GeomVertexFormat.getV3c4() vdata = GeomVertexData("colored_polygon", format, Geom.UHStatic) vdata.setNumRows(4) # make a Geom object to hold the primitives geom = Geom(vdata) # give it a reference to the # add position and color to each vertex vertex_pos_writer = GeomVertexWriter(vdata, "vertex") vertex_color_writer = GeomVertexWriter(vdata, "color") # fill vertex buffer for triangle in triangles: vertex_pos_writer.addData3f(triangle[0][0], 0, triangle[0][1]) # z is up vertex_pos_writer.addData3f(triangle[1][0], 0, triangle[1][1]) vertex_pos_writer.addData3f(triangle[2][0], 0, triangle[2][1]) vertex_color_writer.addData4f(color_vec4) vertex_color_writer.addData4f(color_vec4) vertex_color_writer.addData4f(color_vec4) # create the GeomPrimitive (just one) by filling the index buffer # in stages. The documentation says 'Each GeomPrimitive object actually # stores several different individual primitives, each of which is # represwended simply as a list of vertex numbers, indexing into the # vertices stored in the associated GeomVertexData' tris = GeomTriangles(Geom.UHStatic) # derived from GeomPrimitive # for idx, triangle in enumerate(triangles): # tris.addVertex(idx*3 + 0) # tris.addVertex(idx*3 + 1) # tris.addVertex(idx*3 + 2) # # close the current primitive (not the GeomPrimitive!) tris.add_consecutive_vertices(0, 3*len(triangles)) tris.closePrimitive() geom.addPrimitive(tris) geom_node = GeomNode("colored_polygon_node") geom_node.addGeom(geom) return geom_node
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 makePoint(point=(0,0,0)): clr4 = [1,1,1,1] fmt = GeomVertexFormat.getV3c4() #3 component vertex, w/ 4 comp color vertexData = GeomVertexData('points', fmt, Geom.UHStatic) verts = GeomVertexWriter(vertexData, 'vertex') verts.addData3f(*point) color = GeomVertexWriter(vertexData, 'color') color.addData4f(*clr4) pointCloud = GeomPoints(Geom.UHStatic) pointCloud.addVertex(0) pointCloud.closePrimitive() cloud = Geom(vertexData) cloud.addPrimitive(pointCloud) cloudNode = GeomNode('point') cloudNode.addGeom(cloud) return cloudNode
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 makeGeom(index_counter, array,ctup,i,pipe, geomType=GeomPoints): """ multiprocessing capable geometery maker """ #man = indexMan(('127.0.0.1',5000), authkey='none') #man.connect() #index = man.index() index = {} fmt = GeomVertexFormat.getV3c4() vertexData = GeomVertexData('points', fmt, Geom.UHDynamic) #FIXME use the index for these too? with setPythonTag, will have to 'reserve' some #vertexData.setPythonTag('uid',index.reserve()) #maybe we don't need this? the geom should have it all? cloudGeom = Geom(vertexData) #cloudGeom.setPythonTag('uid',index.reserve()) cloudNode = GeomNode('bin %s selectable'%(i)) uid = next(index_counter) index[uid] = None cloudNode.setPythonTag('uid',uid) #FIXME we return cloudnode elsewhere... maybe on the other end we can set the uid in the index properly? points = array verts = GeomVertexWriter(vertexData, 'vertex') color = GeomVertexWriter(vertexData, 'color') for point in points: index[next(index_counter)]=[point,cloudNode.getPythonTag('uid'),None] #FIXME we're gonna need a decode on the other end? 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... #output[i] = cloudNode #print('ping',{i:cloudNode}) #pipe.send((i,)) #out = q.get() #print('pong',out) #q.put(out) if pipe == None: return cloudNode, index pipe.send(cloudNode.encodeToBamStream()) #FIXME make this return a pointer NOPE pipe.send(index) #FIXME make this return a pointer NOPE
def makeCameraTarget(): colors = ( (0,0,1,1), (1,0,0,1), (0,1,0,1), (0,0,1,1), (1,0,0,1), (0,1,0,1), ) points = ( (0,0,1), (-1,0,0), (0,-1,0), (0,0,-1), (1,0,0), (0,1,0), (0,0,1), ) fmt = GeomVertexFormat.getV3c4() #3 component vertex, w/ 4 comp color #fmt = GeomVertexFormat.getV3() #3 component vertex, w/ 4 comp color vertexData = GeomVertexData('points', fmt, Geom.UHStatic) verts = GeomVertexWriter(vertexData, 'vertex') color = GeomVertexWriter(vertexData, 'color') for p,c in zip(points,colors): verts.addData3f(*p) color.addData4f(*c) targetTris = GeomTristrips(Geom.UHStatic) targetTris.addConsecutiveVertices(0,6) targetTris.addVertex(0) targetTris.addVertex(1) targetTris.addVertex(3) targetTris.addVertex(5) targetTris.addVertex(2) targetTris.addVertex(4) targetTris.addVertex(0) targetTris.closePrimitive() target = Geom(vertexData) target.addPrimitive(targetTris) return target
def makeNode(self, pointmap=(lambda x, y: (x, y, 0))): vt = tuple(self.vertices) t = Triangulator() fmt = GeomVertexFormat.getV3() vdata = GeomVertexData('name', fmt, Geom.UHStatic) vertex = GeomVertexWriter(vdata, 'vertex') for x, y in vt: t.addPolygonVertex(t.addVertex(x, y)) vertex.addData3f(pointmap(x, y)) t.triangulate() prim = GeomTriangles(Geom.UHStatic) for n in xrange(t.getNumTriangles()): prim.addVertices(t.getTriangleV0(n),t.getTriangleV1(n),t.getTriangleV2(n)) prim.closePrimitive() geom = Geom(vdata) geom.addPrimitive(prim) node = GeomNode('gnode') node.addGeom(geom) return node
def draw_vert(self,v, v_color): format = GeomVertexFormat.getV3cp() vdata=GeomVertexData('vert', format, Geom.UHDynamic) vertex=GeomVertexWriter(vdata, 'vertex') color=GeomVertexWriter(vdata, 'color') vertex.addData3f(0.0,0.0,0.0) color.addData4f(v_color) mesh = Geom(vdata) point = GeomPoints(Geom.UHDynamic) point.addVertex(0) point.closePrimitive() mesh.addPrimitive(point) vert_node = GeomNode(self.mesh.name+'_vert_'+str(v.ID)) vert_node.addGeom(mesh) vert_node.setTag('ID',str(v.ID)) rendered_vert = self.render_root.attachNewNode(vert_node) rendered_vert.setPos(v.pos.x,v.pos.y,v.pos.z) rendered_vert.setRenderModeThickness(5.0) self.render_nodes['vert_'+str(v.ID)] = rendered_vert
def makeCircle(vdata, numVertices=40,offset=Vec3(0,0,0), direction=1): circleGeom=Geom(vdata) vertWriter=GeomVertexWriter(vdata, "vertex") normalWriter=GeomVertexWriter(vdata, "normal") colorWriter=GeomVertexWriter(vdata, "color") uvWriter=GeomVertexWriter(vdata, "texcoord") drawWriter=GeomVertexWriter(vdata, "drawFlag") #make sure we start at the end of the GeomVertexData so we dont overwrite anything #that might be there already startRow=vdata.getNumRows() vertWriter.setRow(startRow) colorWriter.setRow(startRow) uvWriter.setRow(startRow) normalWriter.setRow(startRow) drawWriter.setRow(startRow) angle=2*math.pi/numVertices currAngle=angle for i in range(numVertices): position=Vec3(math.cos(currAngle)+offset.getX(), math.sin(currAngle)+offset.getY(),offset.getZ()) vertWriter.addData3f(position) uvWriter.addData2f(position.getX()/2.0+0.5,position.getY()/2.0+0.5) colorWriter.addData4f(1.0, 1.0, 1.0, 1.0) position.setZ(position.getZ()*direction) position.normalize() normalWriter.addData3f(position) #at default Opengl only draws "front faces" (all shapes whose vertices are arranged CCW). We #need direction so we can specify which side we want to be the front face currAngle+=angle*direction circle=GeomTrifans(Geom.UHStatic) circle.addConsecutiveVertices(startRow, numVertices) circle.closePrimitive() circleGeom.addPrimitive(circle) return circleGeom
def msgVec(self, ctup, x, y, z): vertexData = GeomVertexData('points', self.fmt, Geom.UHDynamic) cloudGeom = Geom(vertexData) cloudNode = GeomNode('just some points') verts = GeomVertexWriter(vertexData, 'vertex') color = GeomVertexWriter(vertexData, 'color') for x_, y_, z_, c in zip(x, y, z, ctup): verts.addData3f(x_, y_, z_) color.addData4f(*c) points = self.geomType(Geom.UHDynamic) # FIXME static? points.addConsecutiveVertices(0,len(x)) points.closePrimitive() cloudGeom.addPrimitive(points) cloudNode.addGeom(cloudGeom) #TODO figure out if it is faster to add and subtract Geoms from geom nodes... print(cloudNode) return cloudNode
def make_square4v(coord1, coord2, coord3, coord4, tex_coord): format = GeomVertexFormat.getV3n3t2() vdata = GeomVertexData("square", format, Geom.UHStatic) vertex = GeomVertexWriter(vdata, "vertex") normal = GeomVertexWriter(vdata, "normal") texcoord = GeomVertexWriter(vdata, "texcoord") # make sure we draw the sqaure in the right plane vertex.addData3f(coord1) vertex.addData3f(coord2) vertex.addData3f(coord3) vertex.addData3f(coord4) side1 = coord1 - coord2 side2 = coord1 - coord4 norm1 = side1.cross(side2) side1 = coord2 - coord3 side2 = coord2 - coord4 norm2 = side1.cross(side2) normal.addData3f(norm1) normal.addData3f(norm1) normal.addData3f(norm1) normal.addData3f(norm2) # adding different colors to the vertex for visibility u1, v1, u2, v2 = tex_coord texcoord.addData2f(u1, v2) texcoord.addData2f(u1, v1) texcoord.addData2f(u2, v1) texcoord.addData2f(u2, v2) # quads arent directly supported by the Geom interface # you might be interested in the CardMaker class if you are # interested in rectangle though tri1.addVertex(0) tri1.addVertex(1) tri1.addVertex(3) tri1.addConsecutiveVertices(1, 3) tri1.closePrimitive() square = Geom(vdata) square.addPrimitive(tri1) return square
def make_cube(x, y, z): # FIXME make prism """ make x, y, z sized cube (ints pls) """ colors = [[1,1,1,0] for i in range(8)] #colors[0] = np.array((1,1,1,1)) #colors[1] = np.array((1,0,0,0)) #colors[2] = np.array((0,1,0,0)) #colors[5] = np.array((0,0,1,0)) points = ( (0,0,0), (0,0,z), (0,y,0), (0,y,z), (x,0,0), (x,0,z), (x,y,0), (x,y,z), ) order = [0, 5, 1, 7, 3, 2, 1, 0, 5, 4, 7, 6, 2, 4, 0] # perfect for clockwise #order = [2, 6, 3, 7, 5, 6, 4, 2, 0, 3, 1, 4, 0, 4] #order.reverse() #order = [4, 3, 7, 8, 5, 3, 1, 4, 2, 7, 6, 5, 2, 1] fmt = GeomVertexFormat.getV3c4() vertexData = GeomVertexData('points', fmt, Geom.UHStatic) verts = GeomVertexWriter(vertexData, 'vertex') color = GeomVertexWriter(vertexData, 'color') for p,c in zip(points,colors): verts.addData3f(*p) color.addData4f(*c) targetTris = GeomTristrips(Geom.UHStatic) targetTris.addConsecutiveVertices(0,8) for i in order: targetTris.addVertex(i)#-1) targetTris.closePrimitive() target = Geom(vertexData) target.addPrimitive(targetTris) return target
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 makeClickableGeom(): vdata = GeomVertexData('handleData', GeomVertexFormat.getV3(), Geom.UHStatic) v = GeomVertexWriter(vdata, 'vertex') length = 1.0 cylRad = 0.10 circRes = 8 # Add vertices cylinder. for z in [length/2.0, -length/2.0]: for i in xrange(circRes): theta = i*(2*pi/circRes) v.addData3f(cylRad*sin(theta), cylRad*cos(theta), z) geom = Geom(vdata) # Make polys for the circles CCW = 1 CW = 0 for i, wind in ((0, CCW), (circRes, CW)): circle = GeomTristrips(Geom.UHStatic) l = range(i, i+circRes) for i in xrange(1-wind, (len(l)-wind)/2): l.insert(2*i+wind, l.pop()) for v in l: circle.addVertex(v) circle.closePrimitive() geom.addPrimitive(circle) # Make polys for the cylinder. cyl = GeomTristrips(Geom.UHStatic) for i in xrange(circRes): cyl.addVertex(i + circRes) cyl.addVertex(i) cyl.addVertex(circRes) cyl.addVertex(0) cyl.closePrimitive() geom.addPrimitive(cyl) node = GeomNode('geomnode') node.addGeom(geom) return node
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 reconstruct(self): trianglator = Triangulator() #Add vertices to the trianglator for vertex in self.vertices: trianglator.addPolygonVertex(trianglator.addVertex(vertex)) trianglator.triangulate() #Prepare to create the primative self.vdata = GeomVertexData('floor', GeomVertexFormat.getV3n3cpt2(), Geom.UHStatic) vertexW = GeomVertexWriter(self.vdata, 'vertex') normalW = GeomVertexWriter(self.vdata, 'normal') colorW = GeomVertexWriter(self.vdata, 'color') texcoordW = GeomVertexWriter(self.vdata, 'texcoord') #Add vertices to the primative i = 0 while i < trianglator.getNumVertices(): vertex = trianglator.getVertex(i) vertexW.addData3f(vertex.x,vertex.y,0.0) normalW.addData3f(0,0,1) colorW.addData4f(0.1,0.1,0.1,0.5) texcoordW.addData2f(0.0, 1.0) i+=1 self.geom = Geom(self.vdata) #Add triangles to the primative i = 0 print(trianglator.getNumTriangles()) while i < trianglator.getNumTriangles(): tri = GeomTriangles(Geom.UHStatic) tri.addVertices(trianglator.getTriangleV0(i),trianglator.getTriangleV1(i),trianglator.getTriangleV2(i)) tri.closePrimitive() self.geom.addPrimitive(tri) i+=1 self.addGeom(self.geom)
def makeSquare(face, rhs=True): format=GeomVertexFormat.getV3n3cpt2() format=GeomVertexFormat.getV3n3t2() vdata=GeomVertexData('square', format, Geom.UHStatic) vertex=GeomVertexWriter(vdata, 'vertex') normal=GeomVertexWriter(vdata, 'normal') #color=GeomVertexWriter(vdata, 'color') texcoord=GeomVertexWriter(vdata, 'texcoord') if not rhs: face = list(reversed(face)) normalvec = (face[1]-face[0]).cross(face[2]-face[0]) normalvec.normalize() f = 0.9 if rhs else 0.8 f = 1.0 for ver in face: vertex.addData3f(ver*f) normal.addData3f(normalvec) #color.addData3f((ver+1.0+2.0)*0.25) #color.addData3f(ver*0.0+1.0) if not normalvec.z: texcoord.addData2f(0.0, 0.0) texcoord.addData2f(1.0, 0.0) texcoord.addData2f(1.0, 1.0) texcoord.addData2f(0.0, 1.0) tri=GeomTriangles(Geom.UHStatic) tri.addVertices(0, 1, 2) tri.addVertices(2, 3, 0) tri.closePrimitive() square=Geom(vdata) square.addPrimitive(tri) return square