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 _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 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 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 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 _get_geom_vertex_data(cls, layer: Layer, nozzle_diam: float, height: float, name: str) -> GeomVertexData: """Generate GeomVertexData for the provided Layer. Parameters ---------- layer : Layer Layer for which the data should be generated and written. nozzle_diam : float Nozzle diameter. height : float Layer height, thickness. name : str Name for generated GeomVertexData Returns ------- GeomVertexData Generated GeomVertexData. """ geom_vertex_count = sum([len(path) * 4 for path in layer.paths]) geom_data = GeomVertexData(name, cls._GEOM_VERTEX_FORMAT, Geom.UHStatic) geom_data.setNumRows(geom_vertex_count) cls._write_geom_data(geom_data=geom_data, layer=layer, width=nozzle_diam, height=height) return geom_data
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 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 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 _get_geom_data_plate(build_plate_size: LVector2d, name: str = "") -> GeomVertexData: """Generate build plate GeomVertexData. Parameters ---------- build_plate_size : LVector2d Build plate size. name : str Name for the generated GeomVertexData. """ # noinspection PyArgumentList geom_data = GeomVertexData(name, GeomVertexFormat.get_v3t2(), Geom.UHStatic) geom_data.setNumRows(4) writer_vertex = GeomVertexWriter(geom_data, "vertex") writer_texture = GeomVertexWriter(geom_data, "texcoord") # Add build plate vertices writer_vertex.addData3d(0, 0, 0) writer_vertex.addData3d(build_plate_size.x, 0, 0) writer_vertex.addData3d(build_plate_size.x, build_plate_size.y, 0) writer_vertex.addData3d(0, build_plate_size.y, 0) for uv in [(0, 0), (1, 0), (1, 1), (0, 1)]: writer_texture.addData2(*uv) return geom_data
def __init__(self, size, translation, rotation, color, text): self._visible = False wy, wx, wz = size[0], size[1], size[2] format = GeomVertexFormat.getV3c4() vdata = GeomVertexData('cu_points', format, Geom.UHStatic) vdata.setNumRows(8) self._pos_writer = GeomVertexWriter(vdata, 'vertex') self._color_writer = GeomVertexWriter(vdata, 'color') self._pos_writer.set_row(0) self._color_writer.set_row(0) self._pos_writer.addData3f(-0.5 * wx, -0.5 * wy, 0.) self._pos_writer.addData3f(-0.5 * wx, -0.5 * wy, wz) self._pos_writer.addData3f(0.5 * wx, -0.5 * wy, wz) self._pos_writer.addData3f(0.5 * wx, -0.5 * wy, 0.) self._pos_writer.addData3f(-0.5 * wx, 0.5 * wy, 0.) self._pos_writer.addData3f(-0.5 * wx, 0.5 * wy, wz) self._pos_writer.addData3f(0.5 * wx, 0.5 * wy, wz) self._pos_writer.addData3f(0.5 * wx, 0.5 * wy, 0.) for i in range(8): self._color_writer.addData4f(color[0], color[1], color[2], color[3]) lines = GeomLines(Geom.UHStatic) lines.addVertices(0, 1) lines.addVertices(1, 2) lines.addVertices(2, 3) lines.addVertices(3, 0) lines.addVertices(4, 5) lines.addVertices(5, 6) lines.addVertices(6, 7) lines.addVertices(7, 4) lines.addVertices(0, 4) lines.addVertices(1, 5) lines.addVertices(2, 6) lines.addVertices(3, 7) cuboid = Geom(vdata) cuboid.addPrimitive(lines) node = GeomNode('cuboid') node.addGeom(cuboid) self._node_path = NodePath(node) # self.title = OnscreenText(text=text, style=1, fg=(1, 1, 1, 1), pos=(-0.1, 0.1), scale=.05, # parent=self._node_path, align=TextNode.ARight) self._txt_node = TextNode('id') self._txt_node.setText(text) self._txt_node.setTextScale(0.2) self._txt_node.setCardColor(0, 0, 1, 1) self._txt_node.setCardAsMargin(0, 0, 0, 0) self._txt_node.setCardDecal(True) self._txt_node.set_align(2) text_geom = GeomNode('text') text_geom.addChild(self._txt_node) self._txt_np = NodePath(text_geom) self._txt_np.reparentTo(self._node_path) self.show() self.update_values(size, translation, rotation, color, text)
def create_model(self): vdata = GeomVertexData('name', Diagram.gformat, Geom.UHStatic) vdata.setNumRows(len(self.values)*2) vertex = GeomVertexWriter(vdata, 'vertex') color = GeomVertexWriter(vdata, 'color') prim = GeomTristrips(Geom.UHStatic) i = 0 for x, z in self.values: vertex.addData3(0, x, 0) color.addData4(0, 0, 1, 1) prim.addVertex(i) vertex.addData3(0, x, z/100) color.addData4(0, 0, 1, 1) prim.addVertex(i+1) i += 2 prim.closePrimitive() diagram_geom = Geom(vdata) diagram_geom.addPrimitive(prim) node = GeomNode('gnode') node.addGeom(diagram_geom) node.setTag('entity_type', self.__class__.__name__) node.setTag('entity_id', self.entity_id) model_parent = self.parent.geom[0] parent_scale = model_parent.getScale() nodePath = render.attachNewNode(node) nodePath.reparentTo(model_parent) nodePath.set_two_sided(True) nodePath.setLightOff() node_parent = self.parent.start.geom[0] L = self.parent.longitude() h = 1 nodePath.setScale(h / parent_scale[2], 1 / parent_scale[1], 1 / parent_scale[0]) nodePath.wrtReparentTo(node_parent) """ model = app.base.loader.loadModel("data/geom/plate") model.set_two_sided(True) model.setTag('entity_type', self.__class__.__name__) model.setTag('entity_id', self.entity_id) self.geom = [model]""" self.update_model()
def __init__(self, max_r): self.max_r = max_r format = GeomVertexFormat.getV3c4() vdata = GeomVertexData('point', format, Geom.UHDynamic) self._pos_writer = GeomVertexWriter(vdata, 'vertex') self._color_writer = GeomVertexWriter(vdata, 'color') line_num = 60 vdata.setNumRows(line_num) angles = np.linspace(0, np.pi * 2 - np.pi * 2 / line_num, line_num) other_rgba = (0., 0., 0.3, 0.1) other2_rgba = (0.1, 0.1, 0.4, 0.4) axis_rgba = (0.2, 0.2, 0.5, 1.0) max_r = 250 for indx, angle in enumerate(angles): if indx % 5 == 0: rgba = axis_rgba else: rgba = other_rgba self._pos_writer.addData3d(0, 0, 0.) self._color_writer.addData4f(rgba[0], rgba[1], rgba[2], rgba[3]) self._pos_writer.addData3d(max_r * np.sin(angle), max_r * np.cos(angle), 0.) self._color_writer.addData4f(rgba[0], rgba[1], rgba[2], rgba[3]) grnd_prmtv = GeomLines(Geom.UHStatic) grnd_prmtv.addConsecutiveVertices(0, 2 * line_num) grnd_prmtv.closePrimitive() ground_geom = Geom(vdata) ground_geom.addPrimitive(grnd_prmtv) snode = GeomNode('ground_lines') snode.addGeom(ground_geom) self.points_node = base.render.attachNewNode(snode) self.points_node.setTwoSided(True) for rad in range(int(max_r)): color = axis_rgba pp = makeArc(angleDegrees=360, numSteps=160, scale=rad, color=color) tn = TextNode('dd') tn.setText(str(rad)) tn.setTextScale(0.2) tn.setTextColor(color) text_geom = GeomNode('text') text_geom.addChild(tn) tp = NodePath(text_geom) tp.setPos((0, rad - 0.2, 0)) tp.setHpr((0, -90, 0)) tp.reparentTo(self.points_node) pp.reparentTo(self.points_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 __init__(self): # Basics ShowBase.__init__(self) #base.disableMouse() base.setFrameRateMeter(True) self.accept("escape", sys.exit) self.camera.set_pos(-10, -10, 10) self.camera.look_at(0, 0, 0) # A light plight = PointLight("plight") plight.setColor(VBase4(1, 1, 1, 1)) plnp = render.attachNewNode(plight) plnp.setPos(100, 100, 100) render.setLight(plnp) # Create the geometry vformat = GeomVertexFormat.getV3n3c4() vdata = GeomVertexData("Data", vformat, Geom.UHStatic) vdata.setNumRows(3) vertex = GeomVertexWriter(vdata, 'vertex') normal = GeomVertexWriter(vdata, 'normal') color = GeomVertexWriter(vdata, 'color') vertex.addData3f(100, 0, 0) normal.addData3f(0, 0, 1) color.addData4f(0, 1, 0, 1) vertex.addData3f(100, 100, 0) normal.addData3f(0, 0, 1) color.addData4f(0, 0, 1, 1) vertex.addData3f(0, 100, 0) normal.addData3f(0, 0, 1) color.addData4f(1, 0, 0, 1) prim = GeomTriangles(Geom.UHStatic) prim.addVertices(0, 1, 2) prim.closePrimitive() geom = Geom(vdata) geom.addPrimitive(prim) node = GeomNode("GNode") node.addGeom(geom) nodePath = self.render.attachNewNode(node)
def _build_sticker_geom(sticker, sticker_color, scalar=1): """Builds and returns a Geom composed of the specified points in sticker, colored the specified color. Parameters ---------- sticker: tuple A size-4 tuple consisting of the middle, edge, corner, and edge points, respectively. sticker_color: tuple The RGB values for the sticker color. scalar: float, optional The scale of the sticker from 0 to 1, where 1 has the sticker cover the entier cubie. Defaults to 1. Returns ------- Geom The just-built Geom of the sticker. """ sticker = CubeModel._scale_sticker(sticker, scalar) vertex_format = GeomVertexFormat.getV3c4() vertex_data = GeomVertexData("vertices", vertex_format, Geom.UHStatic) vertex_data.setNumRows(4) vertex_writer = GeomVertexWriter(vertex_data, 'vertex') color_writer = GeomVertexWriter(vertex_data, 'color') vertex_writer.addData3f(sticker[0]) color_writer.addData3f(sticker_color) vertex_writer.addData3f(sticker[1]) color_writer.addData3f(sticker_color) vertex_writer.addData3f(sticker[2]) color_writer.addData3f(sticker_color) vertex_writer.addData3f(sticker[3]) color_writer.addData3f(sticker_color) color_writer.addData3f(sticker_color) triangles = GeomTriangles(Geom.UH_static) triangles.addVertices(0, 1, 2) triangles.addVertices(0, 3, 2) triangles.closePrimitive() geom = Geom(vertex_data) geom.addPrimitive(triangles) return geom
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 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 createColoredUnitQuadGeomNode(color_vec4=Vec4(0., 0., 1., 1.), center_it=False): # Own Geometry # format = GeomVertexFormat.getV3c4t2() format = GeomVertexFormat.getV3c4() vdata = GeomVertexData("colored_quad", format, Geom.UHStatic) vdata.setNumRows(4) vertexPosWriter = GeomVertexWriter(vdata, "vertex") if center_it == False: vertexPosWriter.addData3f(0, 0, 0) vertexPosWriter.addData3f(1, 0, 0) vertexPosWriter.addData3f(1, 0, 1) vertexPosWriter.addData3f(0, 0, 1) else: vertexPosWriter.addData3f(0 - 0.5, 0, 0 - 0.5) vertexPosWriter.addData3f(1 - 0.5, 0, 0 - 0.5) vertexPosWriter.addData3f(1 - 0.5, 0, 1 - 0.5) vertexPosWriter.addData3f(0 - 0.5, 0, 1 - 0.5) # let's also add color to each vertex colorWriter = GeomVertexWriter(vdata, "color") colorWriter.addData4f(color_vec4) colorWriter.addData4f(color_vec4) colorWriter.addData4f(color_vec4) 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 = 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("colored_quad_node") quadGeomNode.addGeom(quadGeom) return quadGeomNode
class ModelBuilder: def __init__(self): self.vformat = GeomVertexFormat.getV3n3c4() self.vdata = GeomVertexData("Data", self.vformat, Geom.UHStatic) self.vdata.setNumRows(3) self.vertex = GeomVertexWriter(self.vdata, 'vertex') self.normal = GeomVertexWriter(self.vdata, 'normal') self.color = GeomVertexWriter(self.vdata, 'color') self.prim = GeomTriangles(Geom.UHStatic) self.idx = 0 def _add_point(self, v, n, c): self.vertex.addData3f(v[0], v[1], v[2]) self.normal.addData3f(n[0], n[1], n[2]) self.color.addData4f(c[0], c[1], c[2], c[3]) self.idx += 1 return self.idx - 1 def add_triangle(self, v1, v2, v3, n, c): i0 = self._add_point(v1, n, c) i1 = self._add_point(v2, n, c) i2 = self._add_point(v3, n, c) self.prim.addVertices(i0, i1, i2) def add_rect(self, org, w, h, n, c): i0 = self._add_point(org, n, c) i1 = self._add_point(org + w, n, c) i2 = self._add_point(org + w + h, n, c) i3 = self._add_point(org + h, n, c) self.prim.addVertices(i0, i1, i2) self.prim.addVertices(i2, i3, i0) def add_box(self, org, w, h, l, c): self.add_rect(org, w, h, -norm(l), c) self.add_rect(org, w, l, -norm(h), c) self.add_rect(org, h, l, -norm(w), c) self.add_rect(org + w, l, h, norm(w), c) self.add_rect(org + h, l, w, norm(h), c) self.add_rect(org + l, h, w, norm(l), c) def build(self, name): self.prim.closePrimitive() geom = Geom(self.vdata) geom.addPrimitive(self.prim) node = GeomNode(name) node.addGeom(geom) return node
class Mesh4: """ Base class for meshes in R4. Args: vertices :: array_like (N,4) A list of vertex positions in the mesh. normals :: array_like (N,4) Vectors perpendicular to the mesh at each vertex. colours :: array_like (N,4) The colour of each vertex. tetrahedra :: array_like (M,4) A list of indices that group vertices into 4-simplices. """ def __init__(self, vertices, normals, colours, tetrahedra): super().__init__() self.n_vertices = len(vertices) self.n_tetrahedra = len(tetrahedra) self.data = GeomVertexData(repr(self), format4, Geom.UHDynamic) self.data.setNumRows(self.n_vertices) self.prim = GeomLinesAdjacency(Geom.UHDynamic) vertex_writer = GeomVertexWriter(self.data, "vertex") normal_writer = GeomVertexWriter(self.data, "normal") colour_writer = GeomVertexWriter(self.data, "colour") for vertex in vertices: vertex_writer.addData4(*vertex) for normal in normals: normal_writer.addData4(*normal) for colour in colours: colour_writer.addData4(*colour) for tetra in tetrahedra: self.prim.addVertices(*tetra) self.prim.closePrimitive() self.geom = Geom(self.data) self.geom.addPrimitive(self.prim) self.node = GeomNode(repr(self)) self.node.addGeom(self.geom) def __len__(self): return len(self.n_vertices)
def create_Triangle_Mesh_From_Vertices_and_Indices(vertices, indices, color_vec4=Vec4(1., 1., 1., 1.)): """ create a mesh out of flat arrays of vertices and indices, which were prepared to create a mesh made of triangles. """ # Own Geometry # format = GeomVertexFormat.getV3c4t2() format = GeomVertexFormat.getV3c4() vdata = GeomVertexData("colored_mesh_out_of_triangles", format, Geom.UHStatic) vdata.setNumRows(4) # let's also add color to each vertex colorWriter = GeomVertexWriter(vdata, "color") vertexPosWriter = GeomVertexWriter(vdata, "vertex") vertices = np.reshape(vertices, (-1, 3)) for v in vertices: vertexPosWriter.addData3f(v[0], v[1], v[2]) 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 = GeomTriangles(Geom.UHStatic) indices = np.reshape(indices, (-1, 3)) for index_triple in indices: tris.addVertices(index_triple[0], index_triple[1], index_triple[2]) tris.closePrimitive() # make a Geom object to hold the primitives geom = Geom(vdata) # vdata contains the vertex position/color/... buffers geom.addPrimitive(tris) # tris contains the index buffer # now put geom in a GeomNode geom_node = GeomNode("colored_polygon_node") geom_node.addGeom(geom) return geom_node
def createColoredArrowGeomNode(color_vec4=Vec4(0., 0., 1., 1.), center_it=False): # Own Geometry # format = GeomVertexFormat.getV3c4t2() format = GeomVertexFormat.getV3c4() vdata = GeomVertexData("colored_quad", format, Geom.UHStatic) vdata.setNumRows(4) vertexPosWriter = GeomVertexWriter(vdata, "vertex") if center_it is False: vertexPosWriter.addData3f( 0, 0, 0) vertexPosWriter.addData3f( 0, 0, 1) vertexPosWriter.addData3f(cos(pi / 6.), 0., .5) else: vertexPosWriter.addData3f( 0, 0, 0 - 0.5) vertexPosWriter.addData3f( 0, 0, 1 - 0.5) vertexPosWriter.addData3f(cos(pi / 6.), 0., .5 - 0.5) # let's also add color to each vertex colorWriter = GeomVertexWriter(vdata, "color") colorWriter.addData4f(color_vec4) colorWriter.addData4f(color_vec4) 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 = GeomTriangles(Geom.UHStatic) # 1st triangle tris.addVertices(0, 2, 1) tris.closePrimitive() # the 1st primitive is finished # make a Geom object to hold the primitives quadGeom = Geom(vdata) quadGeom.addPrimitive(tris) # add the Geom object to a GeomNode geomNode = GeomNode("colored_arrowhead_node") geomNode.addGeom(quadGeom) return geomNode
def CreateTestScene(self): form = GeomVertexFormat.getV3() vdata = GeomVertexData("myLine", form, Geom.UHStatic) vdata.setNumRows(1) vertex = GeomVertexWriter(vdata, "vertex") vertex.addData3f(0, 0, 0) vertex.addData3f(60, 0, 50) prim = GeomLines(Geom.UHStatic) prim.addVertices(0, 1) geom = Geom(vdata) geom.addPrimitive(prim) node = GeomNode("gnode") node.addGeom(geom) nodePath = self.render.attachNewNode(node)
def _get_geom_vertex_data(cls, size: LVector3d, name: str) -> GeomVertexData: """Generate GeomVertexData for the bounding box. Parameters ---------- size : LVector3d Bounding box size. name : str Name for generated GeomVertexData. Returns ------- GeomVertexData Bounding box GeomVertexData. """ geom_data = GeomVertexData(name, cls._GEOM_VERTEX_FORMAT, Geom.UHStatic) geom_data.setNumRows(8) # 8 cube vertices writer_color = GeomVertexWriter(geom_data, "color") writer_vertex = GeomVertexWriter(geom_data, "vertex") # VERTEX COLORS for i in range(8): writer_color.addData4(cls._COLOR_BOUNDING_BOX_DEFAULT) # VERTEX COORDS # Bounding box writer_vertex.addData3d(0, 0, 0) writer_vertex.addData3d(size.x, 0, 0) writer_vertex.addData3d(size.x, 0, size.z) writer_vertex.addData3d(0, 0, size.z) writer_vertex.addData3d(0, size.y, 0) writer_vertex.addData3d(size.x, size.y, 0) writer_vertex.addData3d(size.x, size.y, size.z) writer_vertex.addData3d(0, size.y, size.z) return geom_data
def createCircle(color_vec4=Vec4(1., 1., 1., 1.), with_hole=False, num_of_verts=10, radius=1.): # Own Geometry format = GeomVertexFormat.getV3c4() vdata = GeomVertexData("colored_circle", format, Geom.UHStatic) vdata.setNumRows(4) vertexPosWriter = GeomVertexWriter(vdata, "vertex") # generates circles in x-y plane circle_points = math_utils.get_circle_vertices(num_of_verts=num_of_verts, radius=radius) for p in circle_points: vertexPosWriter.addData3f(p[0], p[1], p[2]) # let's also add color to each vertex colorWriter = GeomVertexWriter(vdata, "color") 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) line = GeomLinestrips(Geom.UHStatic) line.add_consecutive_vertices(0, num_of_verts) if with_hole != True: line.add_vertex(0) # connect it up at the end line.closePrimitive() # the 1st primitive is finished # make a Geom object to hold the primitives geom = Geom(vdata) geom.addPrimitive(line) geom_node = GeomNode("colored_circle_node") geom_node.addGeom(geom) return geom_node
def addPoint(self, x, y, wheel_dir, force): self.wheel_state.append((x, y, wheel_dir, force)) if len(self.wheel_state) < 1: return h = self.wheel_width * 0.5 vdata = GeomVertexData("skid", GeomVertexFormat.getV3c4(), Geom.UHStatic) vdata.setNumRows(len(self.wheel_state) + 2) vtx = GeomVertexWriter(vdata, "vertex") cx = GeomVertexWriter(vdata, "color") prim = GeomTriangles(Geom.UHStatic) i = 0 lastx, lasty = self.wheel_state[0][0], self.wheel_state[0][1] for ws in self.wheel_state: x, y, a, f = ws weight = h * (self.calWeight(lastx, lasty, x, y, a) + 0.1) rads = (a - 90) * math.pi / 180.0 x0, y0 = x + weight * math.cos(rads), y + weight * math.sin(rads) rads = (a + 90) * math.pi / 180.0 x1, y1 = x + weight * math.cos(rads), y + weight * math.sin(rads) c = self.forceToColor(f) vtx.addData3f(x0, y0, -0.4) vtx.addData3f(x1, y1, -0.4) cx.addData4f(*c) cx.addData4f(*c) i += 2 if i > 2: prim.addVertices(i - 4, i - 2, i - 3) prim.addVertices(i - 1, i - 3, i - 2) prim.addVertices(i - 3, i - 2, i - 4) prim.addVertices(i - 2, i - 3, i - 1) prim.closePrimitive() geom = Geom(vdata) geom.addPrimitive(prim) node = GeomNode('Skid') node.addGeom(geom) if self.nodepath: self.nodepath.removeNode() self.nodepath = render.attachNewNode(node)
def get_render_mesh(self): array = GeomVertexArrayFormat() array.addColumn("vertex", 3, Geom.NTFloat32, Geom.CPoint) array.addColumn("barycenter", 3, Geom.NTFloat32, Geom.CPoint) vertex_format = GeomVertexFormat() vertex_format.addArray(array) vertex_format = GeomVertexFormat.registerFormat(vertex_format) v_data = GeomVertexData('mesh', vertex_format, Geom.UHStatic) v_data.setNumRows(len(self.nodes)) vertex = GeomVertexWriter(v_data, 'vertex') barycenter = GeomVertexWriter(v_data, 'barycenter') prim = GeomTriangles(Geom.UHStatic) vertex_id = 0 for elem in self.elements: def node_coords(e, i): return self.nodes[e.nodes[i]].coordinate vertex.addData3(node_coords(elem, 0).x, node_coords(elem, 0).y, 0) vertex.addData3(node_coords(elem, 1).x, node_coords(elem, 1).y, 0) vertex.addData3(node_coords(elem, 2).x, node_coords(elem, 2).y, 0) barycenter.addData3(1, 0, 0) barycenter.addData3(0, 1, 0) barycenter.addData3(0, 0, 1) prim.addVertices(vertex_id, vertex_id + 1, vertex_id + 2) vertex_id += 3 vertex.addData3(node_coords(elem, 2).x, node_coords(elem, 2).y, 0) vertex.addData3(node_coords(elem, 3).x, node_coords(elem, 3).y, 0) vertex.addData3(node_coords(elem, 0).x, node_coords(elem, 0).y, 0) barycenter.addData3(1, 0, 0) barycenter.addData3(0, 1, 0) barycenter.addData3(0, 0, 1) prim.addVertices(vertex_id, vertex_id + 1, vertex_id + 2) vertex_id += 3 geom = Geom(v_data) geom.addPrimitive(prim) return geom
def __init__(self, base): # Load texture tex = Loader(base).loadTexture((Path(path.realpath(__file__)).parent.parent.parent / "res/images/checkerboard.png").absolute()) tex.setMagfilter(SamplerState.FT_nearest) tex.setMinfilter(SamplerState.FT_nearest) # Set up vertex data vdata = GeomVertexData("floor_data", GeomVertexFormat.get_v3t2(), Geom.UHStatic) vdata.setNumRows(6) vertex = GeomVertexWriter(vdata, "vertex") texcoord = GeomVertexWriter(vdata, "texcoord") vertex.addData3(-5, -5, 0) texcoord.addData3(0, 0, 0) vertex.addData3(-5, 5, 0) texcoord.addData3(0, 10, 0) vertex.addData3(5, 5, 0) texcoord.addData3(10, 10, 0) vertex.addData3(5, 5, 0) texcoord.addData3(10, 10, 0) vertex.addData3(5, -5, 0) texcoord.addData3(10, 0, 0) vertex.addData3(-5, -5, 0) texcoord.addData3(0, 0, 0) # Create primitive prim = GeomTriangles(Geom.UHStatic) prim.addVertices(0, 1, 2) prim.addVertices(3, 4, 5) geom = Geom(vdata) geom.add_primitive(prim) # Initialize geometry node GeomNode.__init__(self, "floor") attrib = TextureAttrib.make(tex) state = RenderState.make(attrib) self.addGeom(geom, state)
def __init__(self, data, timescale, scale, record, dark_matter, no_ordinary_matter): self.data = data self.scale = scale self.timescale = timescale self.dark_matter = dark_matter self.no_ordinary_matter = no_ordinary_matter self.n_particles = self.data.shape[1] ShowBase.__init__(self) vdata = GeomVertexData('galaxies', GeomVertexFormat.get_v3c4(), Geom.UHStatic) vdata.setNumRows(self.n_particles) self.vertex = GeomVertexWriter(vdata, 'vertex') color = GeomVertexWriter(vdata, 'color') for i in range(self.n_particles): if (self.data[0][i].dark_matter and not self.dark_matter) or (not self.data[0][i].dark_matter and self.no_ordinary_matter): continue pos = self.data[0][i].pos / self.scale self.vertex.addData3(*pos) color.addData4(1, 1, 1, 1) prim = GeomPoints(Geom.UHStatic) prim.add_consecutive_vertices(0, self.n_particles - 1) geom = Geom(vdata) geom.addPrimitive(prim) node = GeomNode('gnode') node.addGeom(geom) nodePath = self.render.attach_new_node(node) nodePath.setRenderModeThickness(2) self.disableMouse() self.useTrackball() self.trackball.node().set_pos(0, 100, 0) self.trackball.node().set_hpr(90, 0, 90) self.setBackgroundColor(0, 0, 0) self.taskMgr.add(self.update_task, "VertexUpdateTask") self.record(record)
def __init__(self, point_cloud_size): format = GeomVertexFormat.getV3c4t2() vdata = GeomVertexData('point', format, Geom.UHDynamic) self._pos_writer = GeomVertexWriter(vdata, 'vertex') self._color_writer = GeomVertexWriter(vdata, 'color') self._tex_writer = GeomVertexWriter(vdata, 'texcoord') self._point_cloud_size = point_cloud_size self._prev_point_cloud_size = 0 assert point_cloud_size > 0 vdata.setNumRows(point_cloud_size * 6) self._tex_writer.set_row(0) set_texture(self._tex_writer, point_cloud_size) pnts = GeomTriangles(Geom.UHStatic) pnts.addConsecutiveVertices(0, 3 * 2 * point_cloud_size) pnts.closePrimitive() points_geom = Geom(vdata) points_geom.addPrimitive(pnts) snode = GeomNode('points') snode.addGeom(points_geom) dir_name = osp.dirname(__file__) # print(osp.join(dir_name, 'pnts_vs.glsl')) vs_shader = osp.join(dir_name, 'pnts_vs.glsl') fs_shader = osp.join(dir_name, 'pnts_fs.glsl') myShader = Shader.load( Shader.SL_GLSL, vertex=Filename.fromOsSpecific(vs_shader).getFullpath(), fragment=Filename.fromOsSpecific(fs_shader).getFullpath()) assert myShader is not None self.points_node = base.render.attachNewNode(snode) self.points_node.setPos(0., 0., 0.) self.points_node.set_shader(myShader) self.points_node.set_shader_input( "view_size", (base.win.getXSize(), base.win.getYSize())) self.points_node.node().setBounds( BoundingBox((-1000., -1000., -1000.), (1000., 1000., 1000.))) self.points_node.setTransparency(TransparencyAttrib.MAlpha)
class MeshGenerator(): def __init__(self, name = 'Mesh'): self.name = name self.finished = False self.format = GeomVertexFormat.getV3c4t2() #print self.format self.vertexData = GeomVertexData(name, self.format, Geom.UHStatic) self.vertexData.setNumRows(26136) self.mesh = Geom(self.vertexData) self.triangles = GeomTriangles(Geom.UHStatic) self.triangleData = self.triangles.modifyVertices() self.triangleData.setNumRows(26136) self.vertex = GeomVertexWriter(self.vertexData, 'vertex') self.normal = GeomVertexWriter(self.vertexData, 'normal') self.color = GeomVertexWriter(self.vertexData, 'color') self.texcoord = GeomVertexWriter(self.vertexData, 'texcoord') self.faceCount = 0 def makeFace(self, x1, y1, z1, x2, y2, z2, id, color): if x1 != x2: self.vertex.addData3f(x1, y1, z1) self.vertex.addData3f(x2, y1, z1) self.vertex.addData3f(x2, y2, z2) self.vertex.addData3f(x1, y2, z2) else: self.vertex.addData3f(x1, y1, z1) self.vertex.addData3f(x2, y2, z1) self.vertex.addData3f(x2, y2, z2) self.vertex.addData3f(x1, y1, z2) self.color.addData4f(color, color, color, 1.0) self.color.addData4f(color, color, color, 1.0) self.color.addData4f(color, color, color, 1.0) self.color.addData4f(color, color, color, 1.0) if id == 1: self.texcoord.addData2f(0.0, 0.5) self.texcoord.addData2f(0.0, 0.0) self.texcoord.addData2f(0.25, 0.0) self.texcoord.addData2f(0.25, 0.5) elif id == 2: self.texcoord.addData2f(0.25, 0.5) self.texcoord.addData2f(0.25, 0.0) self.texcoord.addData2f(0.5, 0.0) self.texcoord.addData2f(0.5, 0.5) elif id == 3: self.texcoord.addData2f(0.5, 0.5) self.texcoord.addData2f(0.5, 0.0) self.texcoord.addData2f(0.75, 0.0) self.texcoord.addData2f(0.75, 0.5) elif id == 4: self.texcoord.addData2f(0.75, 0.5) self.texcoord.addData2f(0.75, 0.0) self.texcoord.addData2f(1.0, 0.0) self.texcoord.addData2f(1.0, 0.5) elif id == 5: self.texcoord.addData2f(0.0, 1.0) self.texcoord.addData2f(0.0, 0.5) self.texcoord.addData2f(0.25, 0.5) self.texcoord.addData2f(0.25, 1.0) elif id == 6: self.texcoord.addData2f(0.25, 1.0) self.texcoord.addData2f(0.25, 0.5) self.texcoord.addData2f(0.5, 0.5) self.texcoord.addData2f(0.5, 1.0) vertexId = self.faceCount * 4 self.triangles.addVertices(vertexId, vertexId + 1, vertexId + 3) self.triangles.addVertices(vertexId + 1, vertexId + 2, vertexId + 3) self.faceCount += 1 def makeFrontFace(self, x, y, z, id): self.makeFace(x + 1, y + 1, z - 1, x, y + 1, z, id, 0.6) def makeBackFace(self, x, y, z, id): self.makeFace(x, y, z - 1, x + 1, y, z, id, 0.85) def makeRightFace(self, x, y, z, id): self.makeFace(x + 1, y, z - 1, x + 1, y + 1, z, id, 1.0) def makeLeftFace(self, x, y, z, id): self.makeFace(x, y + 1, z - 1, x, y, z, id, 0.9) def makeTopFace(self, x, y, z, id): self.makeFace(x + 1, y + 1, z, x, y, z, id, 1.0) def makeBottomFace(self, x, y, z, id): self.makeFace(x, y + 1, z - 1, x + 1, y, z - 1, id, 0.70) def getMesh(self): return self.mesh 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 createBox(self): """ Create the skybox GeomNode :return: """ obj = '' obj += "# Skybox\n" obj += 'mtllib skybox.mtl\n' mtl = '# material for skybox\n' fmt = GeomVertexFormat.getV3n3t2() vdata = GeomVertexData('skybox', fmt, Geom.UHStatic) vdata.setNumRows(24) vertex = GeomVertexWriter(vdata, 'vertex') normals = GeomVertexWriter(vdata, 'normal') texcoord = GeomVertexWriter(vdata, 'texcoord') node = GeomNode('skybox') for normal in self.normals: geom = Geom(vdata) prim = GeomTriangles(Geom.UHStatic) idx = vertex.getWriteRow() verts = self.vertMappings[normal] tcs = self.getFaceMapping(normal) for v, t in zip(verts, tcs): vertex.addData3f(v[0]*2, v[1]*2, v[2]*2) normals.addData3f(normal) texcoord.addData2f(t) obj += 'v {0} {1} {2}\n'.format(v[0]*2, v[1]*2, v[2]*2) obj += 'vn {0} {1} {2}\n'.format(*normal) obj += 'vt {0} {1}\n'.format(*t) tex = self.getFaceTexture(normal) prim.addVertices(idx, idx + 1, idx + 3) prim.closePrimitive() obj += "usemtl {0}\n".format(tex.getName()) obj += 'f {0}/{0} {1}/{1} {2}/{2}\n'.format(1+idx, 1+idx+1, 1+idx+3) prim.addVertices(idx + 1, idx + 2, idx + 3) prim.closePrimitive() obj += "usemtl {0}\n".format(tex.getName()) obj += 'f {0}/{0} {1}/{1} {2}/{2}\n'.format(1+idx+1, 1+idx+2, 1+idx+3) geom.addPrimitive(prim) tex.setWrapU(Texture.WMMirror) tex.setWrapV(Texture.WMMirror) node.addGeom(geom, RenderState.make(TextureAttrib.make(tex))) mtl += "newmtl {0}\n".format(tex.getName()) mtl += "Ka 1 1 1\n" mtl += "Kd 1 1 1\n" mtl += "map_Kd {0}\n".format(tex.getFilename().toOsSpecific()) return node
import numpy as np from panda3d.core import Geom, GeomVertexFormat, GeomVertexData from .util.ipython import embed size = 1000 data = np.random.randint(0,1000,(size,3)) #color = np.random.randint(0,255,(size,4)) color = np.repeat(np.random.randint(0,255,(1,4)), size, 0) #full = np.hstack((data,color)) full = [tuple(d) for d in np.hstack((data,color))] #full = [tuple(*d,*color) for d in data] geom = GeomVertexData('points', GeomVertexFormat.getV3c4(), Geom.UHDynamic) geom.setNumRows(len(full)) array = geom.modifyArray(0) # need a writeable version handle = array.modifyHandle() #options are then the following: view = memoryview(array) arr = np.asarray(view) arr[:] = full embed() #OR #handle.copyDataFrom('some other handle to a GVDA') #handle.copySubataFrom(to_start, to_size, buffer, from_start, from_size)
def add_button(self, text, label_id, pos_x, pos_y, width=0.0, hight=0.1): if width == 0.0: for c in range(len(text)/2): width += 0.08 ls = LineSegs("lines") ls.setColor(0,1,0,1) ls.drawTo(-width/2, 0, hight/2) ls.drawTo(width/2, 0, hight/2) ls.drawTo(width/2, 0,-hight/2) ls.drawTo(-width/2, 0,-hight/2) ls.drawTo(-width/2, 0, hight/2) border = ls.create(False) border.setTag('back_ground', '1') array = GeomVertexArrayFormat() array.addColumn("vertex", 4, Geom.NTFloat32, Geom.CPoint) arr_format = GeomVertexFormat() arr_format.addArray(array) arr_format = GeomVertexFormat.registerFormat(arr_format) vdata = GeomVertexData('fill', arr_format, Geom.UHStatic) vdata.setNumRows(4) vertex = GeomVertexWriter(vdata, 'vertex') vertex.addData3f(-width/2, 0, hight/2) vertex.addData3f(width/2, 0, hight/2) vertex.addData3f(-width/2, 0,-hight/2) vertex.addData3f(width/2, 0,-hight/2) prim = GeomTristrips(Geom.UHStatic) prim.addVertex(0) prim.addVertex(1) prim.addVertex(2) prim.addVertex(3) geom = Geom(vdata) geom.addPrimitive(prim) node = GeomNode('gnode') node.addGeom(geom) nodePath = NodePath("button") nodePath.attachNewNode(node) nodePath.setPos(0,0,0) nodePath.setTag('button', '1') nodePath.setBin("unsorted", 0) nodePath.setDepthTest(False) nodePath.setColor(0,0,0,1) nodePath.attachNewNode(border) nodePath1 = NodePath("button") nodePath1.attachNewNode(node) nodePath1.setPos(0,0,0) nodePath1.setTag('button1', '1') nodePath1.setBin("unsorted", 0) nodePath1.setDepthTest(False) nodePath1.setColor(0,1,0,1) nodePath1.attachNewNode(border) button=DirectFrame( enableEdit=1, text=text, geom=nodePath, text_scale=0.05, text_fg=(0,1,0,1), borderWidth=(1,1), relief = None, text_pos=(0,-0.01,0), textMayChange=1, state=DGG.NORMAL, parent=aspect2d ) button.setPos(pos_x,0,pos_y) button.bind(DGG.B1PRESS, button_click, [button]) button.bind(DGG.WITHIN, button_hover, [button]) button.bind(DGG.WITHOUT, button_no_hover, [button]) # button.resetFrameSize() # self.button.bind(DGG.WITHIN, self.onMouseHoverInFunction, [button, some_value1]) defines.ENTITIES[defines.ENTITY_ID] = {'CATEGORY':'button', 'BUTTON':button, 'NODE':nodePath, 'LABEL':label_id,'STATUS': 0} defines.ENTITY_ID += 1
class Chunk2GeomDecoder: """ Chunk decoder that decodes chunks to Panda3D Geoms/Nodes """ def __init__(self): self.textures={} for k in texMap: v=texMap[k] tex=loader.loadTexture("gfx/%s"%v) tex.setWrapU(Texture.WM_clamp) tex.setWrapV(Texture.WM_clamp) self.textures[k]=tex self.viewPoint=(0,0,0) self.cubeVtxSrc=[ # 14 vertices per cube mapped # so that UV coords utilize # the typical cube unwrap: # # #### <-- square texture # ##U# # BLFR # ##D# #=unused # # This form uses 14 vertices per cube since # the extra (worldspace overlapped) vertices # map different U,V coordinates at the same # worldspace coordinates, depending on face # # x y z u v (1.00,1.00,1.00,0.00,0.50), # A (1.00,1.00,0.00,0.00,0.25), # B (0.00,1.00,1.00,0.25,0.50), # C (0.00,1.00,0.00,0.25,0.25), # D (0.00,0.00,1.00,0.50,0.50), # E (0.00,0.00,0.00,0.50,0.25), # F (1.00,0.00,1.00,0.75,0.50), # G (1.00,0.00,0.00,0.75,0.25), # H (1.00,1.00,1.00,1.00,0.50), # I (1.00,1.00,0.00,1.00,0.25), # J (0.00,1.00,1.00,0.50,0.75), # K (1.00,1.00,1.00,0.75,0.75), # L (0.00,1.00,0.00,0.50,0.00), # M (1.00,1.00,0.00,0.75,0.00) # N ] self.triSrc=[ # # Faces (QUAD/TRIPAIR) # using RHR vertex ordering for # correct face surface normals # # front: EFHG/EFH+HGE # rear: CABD/CAB+BDC # left: CDFE/CDF+FEC # right: GHJI/GHJ+JIG # upper: KEGL/KEG+GLK # lower: FMNH/FMN+NHF # "EFH","HGE", "CAB","BDC", "CDF","FEC", "GHJ","JIG", "KEG","GLK", "FMN","NHF" ] # # setup cube # # one cube node will be generated per non-air block # since different block id's potentially refer to # different textures and thus must be separate nodes # of the scene graph. # # 1. vertices self.cubeVtx=GeomVertexData('blockCube',GeomVertexFormat.getV3t2(),Geom.UHStatic) self.cubeVtx.setNumRows(len(self.cubeVtxSrc)) vtxW=GeomVertexWriter(self.cubeVtx,'vertex') txcW=GeomVertexWriter(self.cubeVtx,'texcoord') for vertex in self.cubeVtxSrc: vtxW.addData3f(*vertex[0:3]) txcW.addData2f(*vertex[3:5]) # 2. mesh self.cubeMesh=GeomTriangles(Geom.UHStatic) for tri in self.triSrc: for triV in tri: triVtxId=ord(triV)-65 # changea 'A'-'N' to 0-13 self.cubeMesh.addVertex(triVtxId) self.cubeMesh.close_primitive() # 3. geometry (primitive+vertex pair) self.cubeGeom=Geom(self.cubeVtx) self.cubeGeom.addPrimitive(self.cubeMesh) def setViewpoint(x,y,z): self.viewPoint=(x,y,z) @decompress 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