def regesterGeomRequirements(self, LOD, collection): n = NodePath('tmp') if self.barkTexture is not None: n.setTexture(self.barkTexture) n.setShaderInput('diffTex', self.barkTexture) format = GeomVertexFormat.getV3n3t2() else: format = GeomVertexFormat.getV3n3() n.setColor(.4, .3, .3, 1) #n.setShader(customLoader.makeShader(n)) trunkRequirements = meshManager.GeomRequirements( geomVertexFormat=format, renderState=n.getState()) n = NodePath('tmp') if self.leafTexture is not None: #n.setTag("alpha","") n.setShaderInput("alpha", 0, 0, 0) # marker we need cutout alpha n.setTexture(self.leafTexture) n.setShaderInput('diffTex', self.leafTexture) format = GeomVertexFormat.getV3n3t2() else: format = GeomVertexFormat.getV3n3c4() #n.setShader(customLoader.makeShader(n,debugCodePrefix="tree",debugGraphPrefix="tree")) leafRequirements = meshManager.GeomRequirements( geomVertexFormat=format, renderState=n.getState()) self.trunkDataIndex[LOD] = collection.add(trunkRequirements) self.leafDataIndex[LOD] = collection.add(leafRequirements)
def regesterGeomRequirements(self, LOD, collection): n = NodePath("tmp") if self.barkTexture is not None: n.setTexture(self.barkTexture) n.setShaderInput("diffTex", self.barkTexture) format = GeomVertexFormat.getV3n3t2() else: format = GeomVertexFormat.getV3n3() n.setColor(0.4, 0.3, 0.3, 1) # n.setShader(customLoader.makeShader(n)) trunkRequirements = meshManager.GeomRequirements(geomVertexFormat=format, renderState=n.getState()) n = NodePath("tmp") if self.leafTexture is not None: # n.setTag("alpha","") n.setShaderInput("alpha", 0, 0, 0) # marker we need cutout alpha n.setTexture(self.leafTexture) n.setShaderInput("diffTex", self.leafTexture) format = GeomVertexFormat.getV3n3t2() else: format = GeomVertexFormat.getV3n3c4() # n.setShader(customLoader.makeShader(n,debugCodePrefix="tree",debugGraphPrefix="tree")) leafRequirements = meshManager.GeomRequirements(geomVertexFormat=format, renderState=n.getState()) self.trunkDataIndex[LOD] = collection.add(trunkRequirements) self.leafDataIndex[LOD] = collection.add(leafRequirements)
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 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
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 __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 __init__(self, voxel_unit_size): self.voxel_unit_size = voxel_unit_size self.triangles = GeomTriangles(Geom.UHStatic) self.format = GeomVertexFormat.getV3n3c4() self.v_data = GeomVertexData('square', self.format, Geom.UHStatic) self.vertex = GeomVertexWriter(self.v_data, 'vertex') self.normal = GeomVertexWriter(self.v_data, 'normal') self.color = GeomVertexWriter(self.v_data, 'color')
def __init__(self, name = 'Mesh'): ''' Constructor ''' self.name = name self.finished = False self.format = GeomVertexFormat.getV3n3c4() self.vertexData = GeomVertexData(name, self.format, Geom.UHStream) self.mesh = Geom(self.vertexData) self.triangles = GeomTriangles(Geom.UHStream) self.triangleData = self.triangles.modifyVertices() 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 __init__(self, point, vertices, map_width=1024, map_height=1024, base=0.0): self.point = point # TODO: Sort these clockwise (they still are 2D points) # http://stackoverflow.com/questions/6989100/sort-points-in-clockwise-order # Might just need to reverse if the wrong way. I think they're already # ordered. Should be able to tell by checking the normal calculation. self.vertices = vertices # Ensure that stuff is working correctly if [-10.101, -10.101] in vertices: raise ValueError("Can't create this region.") # TODO: Constrain the bounds like this... though it's somewhat busted. # for i, v in enumerate(vertices): # x, y = v # x = max(min(x, map_width/2), -map_width/2) # y = max(min(y, map_height/2), -map_height/2) # vertices[i] = (x, y) for v in vertices: if not (-map_width/2 <= v[0] <= map_width/2 and -map_height/2 <= v[1] <= map_height/2): raise ValueError("Can't create this region.") # 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 # TODO: Migrate to Tristrips. # TODO: Make walls, floors (and ceilings?) prim = GeomTrifans(Geom.UHStatic) DETAIL = 128 HEIGHT_SCALE = 20 vertices = [ (v[0], v[1], snoise2( v[0]/DETAIL, v[1]/DETAIL, base=base, persistence=0.5, lacunarity=2.0, repeatx=map_width/4, repeaty=map_height/4, octaves=5) * HEIGHT_SCALE) for v in vertices] num_high = len(list(filter(lambda x: x[2] > HEIGHT_SCALE * 0.4, vertices))) num_above = len(list(filter(lambda x: HEIGHT_SCALE * 0.4 > x[2] > 0, vertices))) num_below = len(list(filter(lambda x: x[2] <= 0, vertices))) num_deep = len(list(filter(lambda x: x[2] < -HEIGHT_SCALE * 0.2, vertices))) # Calculate the color: # * White if high altitude # * Green if land # * Tan if coast # * Blue if water # * Dark Blue if deep water # poly_color = (uniform(0, 1), uniform(0, 1), uniform(0, 1), 1, ) if num_high: white = uniform(0.7, 1.0) poly_color = (white, white, white, 1.0) elif num_below and num_above: yellow = uniform(0.5, 1.0) poly_color = (yellow, yellow, 0.0, 1.0) elif num_deep: poly_color = (0.0, 0.0, uniform(0.5, 1.0), 1.0) elif num_below: poly_color = (0.3, 0.3, uniform(0.5, 1.0), 1.0) else: poly_color = (0.0, uniform(0.5, 1.0), 0.0, 1.0) for i, point in enumerate(vertices): vertex.addData3f(point[0], point[1], max(point[2], 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)
def generate( self ): # call this after setting some of the variables to update it if not self.vertices: return if hasattr(self, 'geomNode'): self.geomNode.removeAllGeoms() static_mode = Geom.UHStatic if self.static else Geom.UHDynamic formats = { (0, 0, 0): GeomVertexFormat.getV3(), (1, 0, 0): GeomVertexFormat.getV3c4(), (0, 1, 0): GeomVertexFormat.getV3t2(), (0, 0, 1): GeomVertexFormat.getV3n3(), (1, 0, 1): GeomVertexFormat.getV3n3c4(), (1, 1, 0): GeomVertexFormat.getV3c4t2(), (0, 1, 1): GeomVertexFormat.getV3n3t2(), (1, 1, 1): GeomVertexFormat.getV3n3c4t2(), } vertex_format = formats[(bool(self.colors), bool(self.uvs), bool(self.normals))] vdata = GeomVertexData('name', vertex_format, static_mode) vdata.setNumRows(len(self.vertices)) # for speed vertexwriter = GeomVertexWriter(vdata, 'vertex') for v in self.vertices: vertexwriter.addData3f((v[0], v[2], v[1])) # swap y and z if self.colors: colorwriter = GeomVertexWriter(vdata, 'color') for c in self.colors: colorwriter.addData4f(c) if self.uvs: uvwriter = GeomVertexWriter(vdata, 'texcoord') for uv in self.uvs: uvwriter.addData2f(uv[0], uv[1]) if self.normals != None: normalwriter = GeomVertexWriter(vdata, 'normal') for norm in self.normals: normalwriter.addData3f((norm[0], norm[2], norm[1])) modes = { 'triangle': GeomTriangles(static_mode), 'tristrip': GeomTristrips(static_mode), 'ngon': GeomTrifans(static_mode), 'line': GeomLines(static_mode), 'lines': GeomLinestrips(static_mode), 'point': GeomPoints(static_mode), } if self.mode == 'line' and len(self.vertices) % 2 > 0: if len(self.vertices) == 1: self.mode = point print( 'warning: number of vertices must be even for line mode, ignoring last vert' ) self.vertices = self.vertices[:len(self.vertices) - 1] prim = modes[self.mode] if self._triangles: if isinstance(self._triangles[0], int): for t in self._triangles: prim.addVertex(t) elif len( self._triangles[0] ) >= 3: # if tris are tuples like this: ((0,1,2), (1,2,3)) for t in self._triangles: if len(t) == 3: for e in t: prim.addVertex(e) elif len(t) == 4: # turn quad into tris prim.addVertex(t[0]) prim.addVertex(t[1]) prim.addVertex(t[2]) prim.addVertex(t[2]) prim.addVertex(t[3]) prim.addVertex(t[0]) else: prim.addConsecutiveVertices(0, len(self.vertices)) prim.close_primitive() geom = Geom(vdata) geom.addPrimitive(prim) self.geomNode = GeomNode('mesh') self.geomNode.addGeom(geom) self.attachNewNode(self.geomNode) # print('finished') self.recipe = f'''Mesh(
def create_profile(self): """ Creates the necessary rendering geometry to render the 3d rendition of an IBeam profile. """ beam = self.beam s = self.s prof = beam.profile c_1 = (0.25882353, 0.80784314, 0.95686275, 1) c_2 = (0.19607843, 0.63529412, 0.75686275, 1) fmt = GeomVertexFormat.getV3n3c4() vertexData = GeomVertexData('I prof', fmt, Geom.UHStatic) vertexData.setNumRows(108) vertices = GeomVertexWriter(vertexData, 'vertex') normals = GeomVertexWriter(vertexData, 'normal') colors = GeomVertexWriter(vertexData, 'color') T = beam.elements[0].trans_matrix[:3, :3] b_0 = np.array([beam.x[0], beam.y[0], beam.z[0]]) / s b_l = np.array([beam.x[-1], beam.y[-1], beam.z[-1]]) / s points = np.array([[0, prof.b / 2, -prof.h / 2], [0, -prof.b / 2, -prof.h / 2], [0, -prof.b / 2, -prof.h / 2 + prof.t_f], [0, -prof.t_w / 2, -prof.h / 2 + prof.t_f], [0, prof.t_w / 2, -prof.h / 2 + prof.t_f], [0, prof.b / 2, -prof.h / 2 + prof.t_f] ]) / s R = np.array([[1, 0, 0], [0, -1, 0], [0, 0, -1]]) ps = None for p in points: if ps is None: ps = np.reshape(np.dot(R, p), (1, 3)) else: ps = np.append(ps, np.reshape(np.dot(R, p), (1, 3)), axis=0) points = np.append(points, ps, axis=0) ps = None for p in points: if ps is None: ps = np.reshape(b_0 + np.dot(T.T, p), (1, 3)) else: ps = np.append(ps, np.reshape(b_0 + np.dot(T.T, p), (1, 3)), axis=0) pe = None for p in points: if pe is None: pe = np.reshape(b_l + np.dot(T.T, p), (1, 3)) else: pe = np.append(pe, np.reshape(b_l + np.dot(T.T, p), (1, 3)), axis=0) points = np.append(ps, pe, axis=0) surfs = np.array([[0, 1, 2, c_1], [0, 2, 5, c_1], # front [4, 3, 10, c_1], [4, 10, 9, c_1], [8, 11, 6, c_1], [8, 6, 7, c_1], [12, 0, 5, c_1], [12, 5, 17, c_1], # t./b. sides [1, 13, 14, c_1], [1, 14, 2, c_1], [11, 23, 18, c_1], [11, 18, 6, c_1], [20, 8, 7, c_1], [20, 7, 19, c_1], [16, 4, 9, c_2], [16, 9, 21, c_2], # Mid sides [3, 15, 22, c_2], [3, 22, 10, c_2], [13, 12, 17, c_1], [13, 17, 14, c_1], # Back [15, 16, 21, c_1], [15, 21, 22, c_1], [23, 20, 19, c_1], [23, 19, 18, c_1], [7, 6, 18, c_1], [7, 18, 19, c_1], # T. t. fl. [9, 8, 20, c_1], [9, 20, 21, c_1], # In. t. fl. l [11, 10, 22, c_1], [11, 22, 23, c_1], # In. t. fl. r [5, 4, 16, c_1], [5, 16, 17, c_1], # In. b. fl. l. [3, 2, 14, c_1], [3, 14, 15, c_1], # In. b. fl. l. [1, 0, 12, c_1], [1, 12, 13, c_1], # Bot. bot. fl. ]) prim = GeomTriangles(Geom.UHStatic) vtx_count = -1 for surf in surfs: p, n = self.mk_surface(points[surf[0]], points[surf[1]], points[surf[2]]) for i in range(p.shape[0]): vertices.addData3f(*p[i, :]) normals.addData3f(*(-n)) colors.addData4f(*surf[3]) vtx_count += 1 prim.add_vertices(vtx_count - 2, vtx_count - 1, vtx_count) geom = Geom(vertexData) geom.addPrimitive(prim) node = GeomNode('I_frame') node.addGeom(geom) return node
def create_profile(self): """ Creates the necessary rendering geometry to render the 3d rendition of a CHS. """ beam = self.beam s = self.s prof = beam.profile color = (0.25882353, 0.80784314, 0.95686275, 1) fmt = GeomVertexFormat.getV3n3c4() vertexData = GeomVertexData('something', fmt, Geom.UHStatic) vertexData.setNumRows(2304) vertices = GeomVertexWriter(vertexData, 'vertex') normals = GeomVertexWriter(vertexData, 'normal') colors = GeomVertexWriter(vertexData, 'color') T = beam.elements[0].trans_matrix[:3, :3] b_0 = np.array([beam.x[0], beam.y[0], beam.z[0]]) / s b_l = np.array([beam.x[-1], beam.y[-1], beam.z[-1]]) / s s_ang = 49 wall = [] for in_out in ((prof.D / 2) / s, (prof.D / 2 - prof.t) / s): for b in [b_0, b_l]: layer = [] for j in range(s_ang): ang = j * (2 * np.pi / (s_ang-1)) p = b + np.dot(T.T, np.array([0, in_out * np.sin(ang), in_out * np.cos(ang)])) layer.append(p) if layer: wall.append(layer) prim = GeomTriangles(Geom.UHStatic) vtx_count = -1 for io in (0, 1): for l in range(2): for a in range(s_ang-1): if io == 0: p, n = self.mk_surface(wall[l][a], wall[l+1][a+1], wall[l][a+1]) else: p, n = self.mk_surface(wall[l+io][a], wall[l+io][a+1], wall[l+1+io][a+1]) for i in range(p.shape[0]): vertices.addData3f(*p[i, :]) normals.addData3f(*(-n)) colors.addData4f(*color) vtx_count += 1 prim.add_vertices(vtx_count - 2, vtx_count - 1, vtx_count) if io == 0: p, n = self.mk_surface(wall[l+io][a], wall[l+1+io][a], wall[l+1+io][a+1]) else: p, n = self.mk_surface(wall[l+io][a], wall[l+1+io][a+1], wall[l+1+io][a]) for i in range(p.shape[0]): vertices.addData3f(*p[i, :]) normals.addData3f(*(-n)) colors.addData4f(*color) vtx_count += 1 prim.add_vertices(vtx_count - 2, vtx_count - 1, vtx_count) for io in (0, 2): for a in range(s_ang-1): if io == 0: p, n = self.mk_surface(wall[0][a], wall[-2][a+1], wall[-2][a]) else: p, n = self.mk_surface(wall[1][a], wall[-1][a], wall[-1][a+1]) for i in range(p.shape[0]): vertices.addData3f(*p[i, :]) normals.addData3f(*(-n)) colors.addData4f(*color) vtx_count += 1 prim.add_vertices(vtx_count - 2, vtx_count - 1, vtx_count) if io == 0: p, n = self.mk_surface(wall[0][a], wall[0][a+1], wall[-2][a+1]) else: p, n = self.mk_surface(wall[1][a], wall[-1][a+1], wall[1][a+1]) for i in range(p.shape[0]): vertices.addData3f(*p[i, :]) normals.addData3f(*(-n)) colors.addData4f(*color) vtx_count += 1 prim.add_vertices(vtx_count - 2, vtx_count - 1, vtx_count) geom = Geom(vertexData) geom.addPrimitive(prim) node = GeomNode('CHS') node.addGeom(geom) return node
class Mesh(NodePath): _formats = { (0, 0, 0): GeomVertexFormat.getV3(), (1, 0, 0): GeomVertexFormat.getV3c4(), (0, 1, 0): GeomVertexFormat.getV3t2(), (0, 0, 1): GeomVertexFormat.getV3n3(), (1, 0, 1): GeomVertexFormat.getV3n3c4(), (1, 1, 0): GeomVertexFormat.getV3c4t2(), (0, 1, 1): GeomVertexFormat.getV3n3t2(), (1, 1, 1): GeomVertexFormat.getV3n3c4t2(), } _modes = { 'triangle': GeomTriangles, 'tristrip': GeomTristrips, 'ngon': GeomTrifans, 'line': GeomLinestrips, 'point': GeomPoints, } def __init__(self, vertices=None, triangles=None, colors=None, uvs=None, normals=None, static=True, mode='triangle', thickness=1): super().__init__('mesh') self.vertices = vertices self.triangles = triangles self.colors = colors self.uvs = uvs self.normals = normals self.static = static self.mode = mode self.thickness = thickness for var in (('vertices', vertices), ('triangles', triangles), ('colors', colors), ('uvs', uvs), ('normals', normals)): name, value = var if value is None: setattr(self, name, list()) if self.vertices: self.generate() def generate( self ): # call this after setting some of the variables to update it if hasattr(self, 'geomNode'): self.geomNode.removeAllGeoms() static_mode = Geom.UHStatic if self.static else Geom.UHDynamic vertex_format = Mesh._formats[(bool(self.colors), bool(self.uvs), bool(self.normals))] vdata = GeomVertexData('name', vertex_format, static_mode) vdata.setNumRows(len(self.vertices)) # for speed if not hasattr(self, 'geomNode'): self.geomNode = GeomNode('mesh') self.attachNewNode(self.geomNode) vertexwriter = GeomVertexWriter(vdata, 'vertex') for v in self.vertices: vertexwriter.addData3f(*v) if self.colors: colorwriter = GeomVertexWriter(vdata, 'color') for c in self.colors: colorwriter.addData4f(c) if self.uvs: uvwriter = GeomVertexWriter(vdata, 'texcoord') for uv in self.uvs: uvwriter.addData2f(uv[0], uv[1]) if self.normals != None: normalwriter = GeomVertexWriter(vdata, 'normal') for norm in self.normals: normalwriter.addData3f(*norm) if self.mode != 'line' or not self._triangles: self.indices = list() if self._triangles: if isinstance(self._triangles[0], int): for t in self._triangles: self.indices.append(t) elif len( self._triangles[0] ) >= 3: # if tris are tuples like this: ((0,1,2), (1,2,3)) for t in self._triangles: if len(t) == 3: self.indices.extend(t) elif len(t) == 4: # turn quad into tris self.indices.extend( [t[i] for i in (0, 1, 2, 2, 3, 0)]) else: self.indices = [i for i in range(len(self.vertices))] prim = Mesh._modes[self.mode](static_mode) self.generated_vertices = [self.vertices[i] for i in self.indices] for v in self.indices: prim.addVertex(v) prim.close_primitive() geom = Geom(vdata) geom.addPrimitive(prim) self.geomNode.addGeom(geom) else: # line with segments defined in triangles for line in self._triangles: prim = Mesh._modes[self.mode](static_mode) for e in line: prim.addVertex(e) prim.close_primitive() geom = Geom(vdata) geom.addPrimitive(prim) self.geomNode.addGeom(geom) if self.mode == 'point': self.setTexGen(TextureStage.getDefault(), TexGenAttrib.MPointSprite) # self.set_render_mode_perspective(True) # print('finished') @property def recipe(self): if hasattr(self, '_recipe'): return self._recipe return dedent(f''' Mesh( vertices={[tuple(e) for e in self.vertices]}, triangles={self._triangles}, colors={[tuple(e) for e in self.colors]}, uvs={self.uvs}, normals={[tuple(e) for e in self.normals]}, static={self.static}, mode="{self.mode}", thickness={self.thickness} ) ''') @recipe.setter def recipe(self, value): self._recipe = value def __add__(self, other): self.vertices += other.vertices self.triangles += other.triangles if other.colors: self.colors += other.colors else: self.colors += (color.white, ) * len(other.vertices) self.normals += other.normals self.uvs += other.uvs def __deepcopy__(self, memo): m = Mesh(self.vertices, self.triangles, self.colors, self.uvs, self.normals, self.static, self.mode, self.thickness) m.name = self.name return m @property def thickness(self): return self.getRenderModeThickness() @thickness.setter def thickness(self, value): self.setRenderModeThickness(value) @property def triangles(self): if self._triangles == None: self._triangles = [(i, i + 1, i + 2) for i in range(0, len(self.vertices), 3)] return self._triangles @triangles.setter def triangles(self, value): self._triangles = value def generate_normals(self, smooth=True): self.normals = list( generate_normals(self.vertices, self.triangles, smooth)) self.generate() return self.normals def colorize(self, left=color.white, right=color.blue, down=color.red, up=color.green, back=color.white, forward=color.white, smooth=True, world_space=True): colorize(self, left, right, down, up, back, forward, smooth, world_space) def project_uvs(self, aspect_ratio=1, direction='forward'): project_uvs(self, aspect_ratio) def clear(self, regenerate=True): self.vertices, self.triangles, self.colors, self.uvs, self.normals = list( ), list(), list(), list(), list() if regenerate: self.generate() def save(self, name='', path=application.compressed_models_folder): if not application.compressed_models_folder.exists(): application.compressed_models_folder.mkdir() if not name and hasattr(self, 'path'): name = self.path.stem if not '.' in name: name += '.ursinamesh' if name.endswith('ursinamesh'): with open(path / name, 'w') as f: # recipe = self.recipe.replace('LVector3f', '') f.write(self.recipe) print('saved .ursinamesh to:', path / name) elif name.endswith('.obj'): from ursina.mesh_importer import ursina_mesh_to_obj ursina_mesh_to_obj(self, name, path) elif name.endswith('.bam'): success = self.writeBamFile(path / name) print('saved .bam to:', path / name)
def generate( self ): # call this after setting some of the variables to update it if hasattr(self, 'geomNode'): self.geomNode.removeAllGeoms() static_mode = Geom.UHStatic if self.static else Geom.UHDynamic formats = { (0, 0, 0): GeomVertexFormat.getV3(), (1, 0, 0): GeomVertexFormat.getV3c4(), (0, 1, 0): GeomVertexFormat.getV3t2(), (0, 0, 1): GeomVertexFormat.getV3n3(), (1, 0, 1): GeomVertexFormat.getV3n3c4(), (1, 1, 0): GeomVertexFormat.getV3c4t2(), (0, 1, 1): GeomVertexFormat.getV3n3t2(), (1, 1, 1): GeomVertexFormat.getV3n3c4t2(), } vertex_format = formats[(bool(self.colors), bool(self.uvs), bool(self.normals))] vdata = GeomVertexData('name', vertex_format, static_mode) vdata.setNumRows(len(self.vertices)) # for speed vertexwriter = GeomVertexWriter(vdata, 'vertex') for v in self.vertices: vertexwriter.addData3f((v[0], v[2], v[1])) # swap y and z if self.colors: colorwriter = GeomVertexWriter(vdata, 'color') for c in self.colors: colorwriter.addData4f(c) if self.uvs: uvwriter = GeomVertexWriter(vdata, 'texcoord') for uv in self.uvs: uvwriter.addData2f(uv[0], uv[1]) if self.normals != None: normalwriter = GeomVertexWriter(vdata, 'normal') for norm in self.normals: normalwriter.addData3f((norm[0], norm[2], norm[1])) modes = { 'triangle': GeomTriangles(static_mode), 'tristrip': GeomTristrips(static_mode), 'ngon': GeomTrifans(static_mode), 'line': GeomLinestrips(static_mode), 'point': GeomPoints(static_mode), } if self.mode != 'line' or not self._triangles: prim = modes[self.mode] if self._triangles: if isinstance(self._triangles[0], int): for t in self._triangles: prim.addVertex(t) elif len( self._triangles[0] ) >= 3: # if tris are tuples like this: ((0,1,2), (1,2,3)) for t in self._triangles: if len(t) == 3: for e in t: prim.addVertex(e) elif len(t) == 4: # turn quad into tris prim.addVertex(t[0]) prim.addVertex(t[1]) prim.addVertex(t[2]) prim.addVertex(t[2]) prim.addVertex(t[3]) prim.addVertex(t[0]) else: prim.addConsecutiveVertices(0, len(self.vertices)) prim.close_primitive() geom = Geom(vdata) geom.addPrimitive(prim) else: # line with segments defnined in triangles for line in self._triangles: prim = modes[self.mode] for e in line: prim.addVertex(e) prim.close_primitive() geom = Geom(vdata) geom.addPrimitive(prim) self.geomNode = GeomNode('mesh') self.geomNode.addGeom(geom) self.attachNewNode(self.geomNode) # if self.normals: # self.normals = [tuple(e) for e in self.normals] self.recipe = dedent(f''' Mesh( vertices={[tuple(e) for e in self.vertices]}, triangles={self._triangles}, colors={[tuple(e) for e in self.colors]}, uvs={self.uvs}, normals={[tuple(e) for e in self.normals]}, static={self.static}, mode="{self.mode}", thickness={self.thickness} ) ''')
def generate(self, terrain, size, lod=1.0): if self.meshgentype == "marching": mesher = MarchingCubes() elif self.meshgentype == "dual": mesher = DualContour(noise=manager.get('noise')) else: mesher = Voxel() triangles = mesher.generateMesh(terrain, size, lod) #format = GeomVertexFormat.registerFormat(GeomVertexFormat.getV3n3c4t2()) format = GeomVertexFormat.registerFormat(GeomVertexFormat.getV3n3c4()) vdata = GeomVertexData('chunk_mesh', format, Geom.UHStatic) vertex = GeomVertexWriter(vdata, 'vertex') normal = GeomVertexWriter(vdata, 'normal') color = GeomVertexWriter(vdata, 'color') texcoord = GeomVertexWriter(vdata, 'texcoord') prim = GeomTriangles(Geom.UHStatic) vertexcount = 0 for triangle in triangles: for avertex in triangle: #print triangle #make vertices here shade = 0.5 vertex.addData3f(avertex[0], avertex[1], avertex[2]) #fix normals x1, y1, z1 = triangle[0][0], triangle[0][1], triangle[0][2] x2, y2, z2 = triangle[1][0], triangle[1][1], triangle[1][2] x3, y3, z3 = triangle[2][0], triangle[2][1], triangle[2][2] normx = (z1 - z2) * (y3 - y2) - (y1 - y2) * (z3 - z2) normy = (x1 - x2) * (z3 - z2) - (z1 - z2) * (x3 - x2) normz = (y1 - y2) * (x3 - x2) - (x1 - x2) * (y3 - y2) normlength = math.sqrt(normx**2 + normy**2 + normz**2) if normlength != 0: normx /= normlength normy /= normlength normz /= normlength normal.addData3f(normx, normy, normz) color.addData4f(shade, shade, shade, 1) #color.addData4f(random.randrange(0,255), random.randrange(0,255), random.randrange(0,255), 1) #texcoord.addData2f(triangle[0][0] / 16, triangle[0][1] / 16) #texcoord.addData2f(0, 1) #make triangles prim.addVertices(vertexcount, vertexcount + 1, vertexcount + 2) prim.closePrimitive() vertexcount += 3 #print prim #attach primitives and render geom = Geom(vdata) geom.addPrimitive(prim) """try: self.node.removeNode() self.bulletnode.removeShape(self.bulletshape) self.root.bulletworld.removeRigidBody(self.bulletnode) self.bulletnp.removeNode() except AttributeError: pass""" node = GeomNode("terrainmesh") node.addGeom(geom) return node #self.meshed = True """#do bullet meshing
class Mesh(NodePath): _formats = { (0, 0, 0): GeomVertexFormat.getV3(), (1, 0, 0): GeomVertexFormat.getV3c4(), (0, 1, 0): GeomVertexFormat.getV3t2(), (0, 0, 1): GeomVertexFormat.getV3n3(), (1, 0, 1): GeomVertexFormat.getV3n3c4(), (1, 1, 0): GeomVertexFormat.getV3c4t2(), (0, 1, 1): GeomVertexFormat.getV3n3t2(), (1, 1, 1): GeomVertexFormat.getV3n3c4t2(), } _modes = { 'triangle': GeomTriangles, 'tristrip': GeomTristrips, 'ngon': GeomTrifans, 'line': GeomLinestrips, 'point': GeomPoints, } def __init__(self, vertices=None, triangles=None, colors=None, uvs=None, normals=None, static=True, mode='triangle', thickness=1): super().__init__('mesh') self.vertices = vertices self.triangles = triangles self.colors = colors self.uvs = uvs self.normals = normals self.static = static self.mode = mode self.thickness = thickness for var in (('vertices', vertices), ('triangles', triangles), ('colors', colors), ('uvs', uvs), ('normals', normals)): name, value = var if value is None: setattr(self, name, list()) if self.vertices: self.vertices = [tuple(v) for v in self.vertices] self.generate() def generate( self ): # call this after setting some of the variables to update it if hasattr(self, 'geomNode'): self.geomNode.removeAllGeoms() static_mode = Geom.UHStatic if self.static else Geom.UHDynamic vertex_format = Mesh._formats[(bool(self.colors), bool(self.uvs), bool(self.normals))] vdata = GeomVertexData('name', vertex_format, static_mode) vdata.setNumRows(len(self.vertices)) # for speed vertexwriter = GeomVertexWriter(vdata, 'vertex') for v in self.vertices: vertexwriter.addData3f((v[0], v[2], v[1])) # swap y and z if self.colors: colorwriter = GeomVertexWriter(vdata, 'color') for c in self.colors: colorwriter.addData4f(c) if self.uvs: uvwriter = GeomVertexWriter(vdata, 'texcoord') for uv in self.uvs: uvwriter.addData2f(uv[0], uv[1]) if self.normals != None: normalwriter = GeomVertexWriter(vdata, 'normal') for norm in self.normals: normalwriter.addData3f((norm[0], norm[2], norm[1])) if self.mode != 'line' or not self._triangles: prim = Mesh._modes[self.mode](static_mode) if self._triangles: if isinstance(self._triangles[0], int): for t in self._triangles: prim.addVertex(t) elif len( self._triangles[0] ) >= 3: # if tris are tuples like this: ((0,1,2), (1,2,3)) for t in self._triangles: if len(t) == 3: for e in t: prim.addVertex(e) elif len(t) == 4: # turn quad into tris prim.addVertex(t[0]) prim.addVertex(t[1]) prim.addVertex(t[2]) prim.addVertex(t[2]) prim.addVertex(t[3]) prim.addVertex(t[0]) else: prim.addConsecutiveVertices(0, len(self.vertices)) prim.close_primitive() geom = Geom(vdata) geom.addPrimitive(prim) else: # line with segments defined in triangles for line in self._triangles: prim = Mesh._modes[self.mode](static_mode) for e in line: prim.addVertex(e) prim.close_primitive() geom = Geom(vdata) geom.addPrimitive(prim) self.geomNode = GeomNode('mesh') self.geomNode.addGeom(geom) self.attachNewNode(self.geomNode) # if self.normals: # self.normals = [tuple(e) for e in self.normals] self.recipe = dedent(f''' Mesh( vertices={[tuple(e) for e in self.vertices]}, triangles={self._triangles}, colors={[tuple(e) for e in self.colors]}, uvs={self.uvs}, normals={[tuple(e) for e in self.normals]}, static={self.static}, mode="{self.mode}", thickness={self.thickness} ) ''') # print('finished') def __add__(self, other): self.vertices += other.vertices self.triangles += other.triangles if other.colors: self.colors += other.colors else: self.colors += (color.white, ) * len(other.vertices) self.normals += other.normals self.uvs += other.uvs @property def thickness(self): return self.getRenderModeThickness() @thickness.setter def thickness(self, value): self.setRenderModeThickness(value) @property def triangles(self): if self._triangles == None: self._triangles = [(i, i + 1, i + 2) for i in range(0, len(self.vertices), 3)] return self._triangles @triangles.setter def triangles(self, value): self._triangles = value def generate_normals(self, smooth=True): self.normals = list( generate_normals(self.vertices, self.triangles, smooth)) self.generate() return self.normals def colorize(self, left=color.white, right=color.blue, down=color.red, up=color.green, back=color.white, forward=color.white, smooth=True, world_space=True): colorize(self, left, right, down, up, back, forward, smooth, world_space) def project_uvs(self, aspect_ratio=1, direction='forward'): project_uvs(self, aspect_ratio) def clear(self, regenerate=True): self.vertices, self.triangles, self.colors, self.uvs, self.normals = list( ), list(), list(), list(), list() if regenerate: self.generate() def save(self, name, path=application.asset_folder, filetype='ursinamesh'): if filetype == 'ursinamesh': if not '.' in name: name += '.ursinamesh' with open(path / name, 'w') as f: recipe = self.recipe.replace('LVector3f', '') f.write(recipe) elif filetype == 'obj': from ursina.mesh_importer import ursina_mesh_to_obj ursina_mesh_to_obj(self, name, path)
def __init__(self): # Basics ShowBase.__init__(self) # self.disableMouse() self.setFrameRateMeter(True) self.backfaceCullingOff() self.accept("escape", sys.exit) self.camera.set_pos(-10, -10, 10) self.camera.look_at(-10, 0, 0) # A light plight = PointLight("plight") plight.setColor(VBase4(1, 1, 1, 1)) plnp = self.render.attachNewNode(plight) plnp.setPos(10, 10, 50) self.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(0, 0, 0) normal.addData3f(0, 0, 1) color.addData4f(0, 0, 1, 1) vertex.addData3f(0, 150, 0) normal.addData3f(0, 0, 1) color.addData4f(0, 1, 0, 1) vertex.addData3f(10, 150, 0) normal.addData3f(0, 0, 1) color.addData4f(1, 0, 0, 1) vertex.addData3f(10, 0, 0) normal.addData3f(0, 0, 1) color.addData4f(0, 0, 0, 1) ''' prim = GeomTriangles(Geom.UHStatic) ''' prim.addVertices(0, 1, 2) prim.addVertices(2, 1, 0) prim.addVertices(2, 3, 0) prim.addVertices(0, 3, 2) ''' org = np.array([0, 0, 0]) add_rect(0, org, np.array([1, 0, 0]), np.array([0, 1, 0]), (1, 1, 1, 1), vertex, normal, color, prim) add_rect(1, org, np.array([-0.05, 0, 0]), np.array([0, 2, 0]), (0, 0, 1, 1), vertex, normal, color, prim) add_rect(2, org, np.array([2, 0, 0]), np.array([0, -0.05, 0]), (0, 1, 0, 1), vertex, normal, color, prim) prim.closePrimitive() geom = Geom(vdata) geom.addPrimitive(prim) node = GeomNode("GNode") node.addGeom(geom) nodePath = self.render.attachNewNode(node)
def generate(self, terrain, size, lod=1.0): if self.meshgentype == "marching": mesher = MarchingCubes() elif self.meshgentype == "dual": mesher = DualContour(noise=manager.get('noise')) else: mesher = Voxel() triangles = mesher.generateMesh(terrain, size, lod) #format = GeomVertexFormat.registerFormat(GeomVertexFormat.getV3n3c4t2()) format = GeomVertexFormat.registerFormat(GeomVertexFormat.getV3n3c4()) vdata = GeomVertexData('chunk_mesh', format, Geom.UHStatic) vertex = GeomVertexWriter(vdata, 'vertex') normal = GeomVertexWriter(vdata, 'normal') color = GeomVertexWriter(vdata, 'color') texcoord = GeomVertexWriter(vdata, 'texcoord') prim = GeomTriangles(Geom.UHStatic) vertexcount = 0 for triangle in triangles: for avertex in triangle: #print triangle #make vertices here shade = 0.5 vertex.addData3f(avertex[0], avertex[1], avertex[2]) #fix normals x1, y1, z1 = triangle[0][0], triangle[0][1], triangle[0][2] x2, y2, z2 = triangle[1][0], triangle[1][1], triangle[1][2] x3, y3, z3 = triangle[2][0], triangle[2][1], triangle[2][2] normx = (z1 - z2) * (y3 - y2) - (y1 - y2) * (z3 - z2) normy = (x1 - x2) * (z3 - z2) - (z1 - z2) * (x3 - x2) normz = (y1 - y2) * (x3 - x2) - (x1 - x2) * (y3 - y2) normlength = math.sqrt(normx ** 2 + normy ** 2 + normz ** 2) if normlength != 0: normx /= normlength normy /= normlength normz /= normlength normal.addData3f(normx, normy, normz) color.addData4f(shade, shade, shade, 1) #color.addData4f(random.randrange(0,255), random.randrange(0,255), random.randrange(0,255), 1) #texcoord.addData2f(triangle[0][0] / 16, triangle[0][1] / 16) #texcoord.addData2f(0, 1) #make triangles prim.addVertices(vertexcount, vertexcount + 1, vertexcount + 2) prim.closePrimitive() vertexcount += 3 #print prim #attach primitives and render geom = Geom(vdata) geom.addPrimitive(prim) """try: self.node.removeNode() self.bulletnode.removeShape(self.bulletshape) self.root.bulletworld.removeRigidBody(self.bulletnode) self.bulletnp.removeNode() except AttributeError: pass""" node = GeomNode("terrainmesh") node.addGeom(geom) return node #self.meshed = True """#do bullet meshing
from direct.showbase.ShowBase import ShowBase from direct.task import Task from direct.actor.Actor import Actor from direct.interval.IntervalGlobal import Sequence from panda3d.core import Point3 from panda3d.core import Geom, GeomVertexFormat, GeomVertexData, GeomVertexWriter, GeomNode, GeomTriangles from math import pi, sin, cos um = pymetasurf.UnitMetaball() um.set_resolution(40,40,40) um.set_bounds(-3, -3, -3, 3, 3, 3) um.polygonize() format=GeomVertexFormat.getV3n3c4() vdata=GeomVertexData("vertices", format, Geom.UHStatic) vertexWriter=GeomVertexWriter(vdata, "vertex") for p in um.tri_list: vertexWriter.addData3f(p[0],p[1],p[2]) normalWriter=GeomVertexWriter(vdata, "normal") for p in um.normal_list: normalWriter.addData3f(p[0],p[1],p[2]) colorWriter=GeomVertexWriter(vdata, "color") for p in um.tri_list: colorWriter.addData4f(1.0 - (p[0] * 0.1),1.0 - (p[1] * 0.1), 1.0 - (p[2] * 0.1),1.0) tris = GeomTriangles(Geom.UHStatic) tris.addConsecutiveVertices(0, len(um.tri_list)) tris.closePrimitive()