コード例 #1
0
ファイル: geom.py プロジェクト: TheEnbyperor/racing_sim
def make_circle(x1,
                y1,
                z1,
                x2,
                y2,
                z2,
                inner_radius,
                end_inner_radius,
                arc,
                new_z1,
                new_z2,
                tex_len=None,
                tex_width=None,
                end_radius=None,
                rev=False):
    format = GeomVertexFormat.getV3n3cpt2()
    vdata = GeomVertexData('circle', format, Geom.UHDynamic)

    vertex = GeomVertexWriter(vdata, 'vertex')
    normal = GeomVertexWriter(vdata, 'normal')
    texcoord = GeomVertexWriter(vdata, 'texcoord')

    ccw = arc < 0
    arc = -arc if ccw else arc

    num_parts = 50 * (arc / 360)**-1
    num_draw = round(num_parts * (arc / 360))

    x3 = x1 - x2
    y3 = y1 - y2
    z3 = z1 - z2
    x3, y3, z3 = normalized(x3, y3, z3)

    theta_offset = math.atan2(y1 - y2, x1 - x2)
    orig_radius = math.sqrt((x2 - x1)**2 + (y2 - y1)**2 + (z2 - z1)**2)

    cur_x1 = x1
    cur_y1 = y1
    cur_z1 = z1
    cur_x2 = x2
    cur_y2 = y2
    cur_z2 = z2

    z1_diff = new_z1 - z1
    z2_diff = new_z2 - z2

    if end_radius is None:
        end_radius = orig_radius

    inner_radius_diff = end_inner_radius - inner_radius
    radius_diff = end_radius - orig_radius

    for i in range(num_draw + 1):
        theta = (math.pi - 2 * math.pi * (i / num_parts)) % (2 * math.pi)
        interp = (i / num_draw)

        inner_radius_interp = inner_radius + (inner_radius_diff *
                                              (i / num_parts))

        radius = (orig_radius + (radius_diff * interp)) + inner_radius_interp

        radius_offset = 0
        if rev:
            radius_offset = radius_diff * interp

        x1_interp = x1 + ((inner_radius + radius_offset) * x3)
        y1_interp = y1 + ((inner_radius + radius_offset) * y3)
        z1_interp = z1 + ((inner_radius + radius_offset) * z3)

        x_outer = (math.cos((-theta if ccw else theta) + theta_offset) *
                   radius) + x1_interp
        y_outer = (math.sin((-theta if ccw else theta) + theta_offset) *
                   radius) + y1_interp
        x_inner = (math.cos((-theta if ccw else theta) + theta_offset) *
                   inner_radius_interp) + x1_interp
        y_inner = (math.sin((-theta if ccw else theta) + theta_offset) *
                   inner_radius_interp) + y1_interp

        D = Vec3(cur_x1, cur_y1, cur_z1)
        C = Vec3(cur_x2, cur_y2, cur_z2)
        B = Vec3(x_inner, y_inner, z1_interp + (z1_diff * interp))
        A = Vec3(x_outer, y_outer, z1_interp + (z2_diff * interp))
        normal_vec = (C - A).cross(D - B).normalize()

        vertex.addData3(x_inner, y_inner, z1_interp + (z1_diff * interp))
        cur_x1, cur_y1, cur_z1 = x_inner, y_inner, z1_interp + (z1_diff *
                                                                interp)
        normal.addData3(normal_vec)

        texcoord.addData2f(
            (((i / num_parts) * 2 * math.pi * inner_radius_interp) /
             tex_len) if tex_len is not None else 1.0,
            (orig_radius / tex_width) if tex_width is not None else 1.0)

        vertex.addData3(x_outer, y_outer, z1_interp + (z2_diff * interp))
        cur_x2, cur_y2, cur_z2 = x_outer, y_outer, z1_interp + (z2_diff *
                                                                interp)
        normal.addData3(normal_vec)
        texcoord.addData2f((((i / num_parts) * 2 * math.pi * radius) /
                            tex_len) if tex_len is not None else 1.0, 0)

    tris = GeomTriangles(Geom.UHDynamic)
    for i in range(num_draw * 2):
        tris.addVertices(0 + i, 1 + i, 2 + i)

    circle = Geom(vdata)
    circle.addPrimitive(tris)

    return circle, cur_x1, cur_y1, cur_z1, cur_x2, cur_y2, cur_z2
コード例 #2
0
def getNodeFromController(controller, controlled_prim):
    if type(controlled_prim) is collada.controller.BoundSkinPrimitive:
        ch = Character('simplechar')
        bundle = ch.getBundle(0)
        skeleton = PartGroup(bundle, '<skeleton>')

        character_joints = {}
        for (name, joint_matrix) in controller.joint_matrices.iteritems():
            joint_matrix.shape = (-1)
            character_joints[name] = CharacterJoint(ch, bundle, skeleton, name,
                                                    Mat4(*joint_matrix))

        tbtable = TransformBlendTable()

        for influence in controller.index:
            blend = TransformBlend()
            for (joint_index, weight_index) in influence:
                char_joint = character_joints[controller.getJoint(joint_index)]
                weight = controller.getWeight(weight_index)[0]
                blend.addTransform(JointVertexTransform(char_joint), weight)
            tbtable.addBlend(blend)

        array = GeomVertexArrayFormat()
        array.addColumn(InternalName.make('vertex'), 3, Geom.NTFloat32,
                        Geom.CPoint)
        array.addColumn(InternalName.make('normal'), 3, Geom.NTFloat32,
                        Geom.CPoint)
        array.addColumn(InternalName.make('texcoord'), 2, Geom.NTFloat32,
                        Geom.CTexcoord)
        blendarr = GeomVertexArrayFormat()
        blendarr.addColumn(InternalName.make('transform_blend'), 1,
                           Geom.NTUint16, Geom.CIndex)

        format = GeomVertexFormat()
        format.addArray(array)
        format.addArray(blendarr)
        aspec = GeomVertexAnimationSpec()
        aspec.setPanda()
        format.setAnimation(aspec)
        format = GeomVertexFormat.registerFormat(format)

        dataname = controller.id + '-' + controlled_prim.primitive.material.id
        vdata = GeomVertexData(dataname, format, Geom.UHStatic)
        vertex = GeomVertexWriter(vdata, 'vertex')
        normal = GeomVertexWriter(vdata, 'normal')
        texcoord = GeomVertexWriter(vdata, 'texcoord')
        transform = GeomVertexWriter(vdata, 'transform_blend')

        numtris = 0
        if type(controlled_prim.primitive) is collada.polylist.BoundPolylist:
            for poly in controlled_prim.primitive.polygons():
                for tri in poly.triangles():
                    for tri_pt in range(3):
                        vertex.addData3f(tri.vertices[tri_pt][0],
                                         tri.vertices[tri_pt][1],
                                         tri.vertices[tri_pt][2])
                        normal.addData3f(tri.normals[tri_pt][0],
                                         tri.normals[tri_pt][1],
                                         tri.normals[tri_pt][2])
                        if len(controlled_prim.primitive._texcoordset) > 0:
                            texcoord.addData2f(tri.texcoords[0][tri_pt][0],
                                               tri.texcoords[0][tri_pt][1])
                        transform.addData1i(tri.indices[tri_pt])
                    numtris += 1
        elif type(controlled_prim.primitive
                  ) is collada.triangleset.BoundTriangleSet:
            for tri in controlled_prim.primitive.triangles():
                for tri_pt in range(3):
                    vertex.addData3f(tri.vertices[tri_pt][0],
                                     tri.vertices[tri_pt][1],
                                     tri.vertices[tri_pt][2])
                    normal.addData3f(tri.normals[tri_pt][0],
                                     tri.normals[tri_pt][1],
                                     tri.normals[tri_pt][2])
                    if len(controlled_prim.primitive._texcoordset) > 0:
                        texcoord.addData2f(tri.texcoords[0][tri_pt][0],
                                           tri.texcoords[0][tri_pt][1])
                    transform.addData1i(tri.indices[tri_pt])
                numtris += 1

        tbtable.setRows(SparseArray.lowerOn(vdata.getNumRows()))

        gprim = GeomTriangles(Geom.UHStatic)
        for i in range(numtris):
            gprim.addVertices(i * 3, i * 3 + 1, i * 3 + 2)
            gprim.closePrimitive()

        pgeom = Geom(vdata)
        pgeom.addPrimitive(gprim)

        render_state = getStateFromMaterial(controlled_prim.primitive.material)
        control_node = GeomNode("ctrlnode")
        control_node.addGeom(pgeom, render_state)
        ch.addChild(control_node)

        bundle = AnimBundle('simplechar', 5.0, 2)
        skeleton = AnimGroup(bundle, '<skeleton>')
        root = AnimChannelMatrixXfmTable(skeleton, 'root')

        #hjoint = AnimChannelMatrixXfmTable(root, 'joint1')
        #table = [10, 11, 12, 13, 14, 15, 14, 13, 12, 11]
        #data = PTAFloat.emptyArray(len(table))
        #for i in range(len(table)):
        #    data.setElement(i, table[i])
        #hjoint.setTable(ord('i'), CPTAFloat(data))

        #vjoint = AnimChannelMatrixXfmTable(hjoint, 'joint2')
        #table = [10, 9, 8, 7, 6, 5, 6, 7, 8, 9]
        #data = PTAFloat.emptyArray(len(table))
        #for i in range(len(table)):
        #    data.setElement(i, table[i])
        #vjoint.setTable(ord('j'), CPTAFloat(data))

        wiggle = AnimBundleNode('wiggle', bundle)

        np = NodePath(ch)
        anim = NodePath(wiggle)
        a = Actor(np, {'simplechar': anim})
        a.loop('simplechar')
        return a
        #a.setPos(0, 0, 0)

    else:
        raise Exception("Error: unsupported controller type")
コード例 #3
0
    def regenerateGeometry(self):
        #
        # Generate vertex data
        #

        numVerts = len(self.vertices)

        vdata = GeomVertexData("SolidFace", getFaceFormat(), GeomEnums.UHStatic)
        vdata.uncleanSetNumRows(len(self.vertices))

        vwriter = GeomVertexWriter(vdata, InternalName.getVertex())
        twriter = GeomVertexWriter(vdata, InternalName.getTexcoord())
        nwriter = GeomVertexWriter(vdata, InternalName.getNormal())
        tanwriter = GeomVertexWriter(vdata, InternalName.getTangent())
        bwriter = GeomVertexWriter(vdata, InternalName.getBinormal())

        for i in range(len(self.vertices)):
            vert = self.vertices[i]
            vwriter.setData3f(vert.pos)
            twriter.setData2f(vert.uv)
            nwriter.setData3f(self.plane.getNormal())
            tanwriter.setData3f(self.material.tangent)
            bwriter.setData3f(self.material.binormal)

        #
        # Generate indices
        #

        # Triangles in 3D view
        prim3D = GeomTriangles(GeomEnums.UHStatic)
        prim3D.reserveNumVertices((numVerts - 2) * 3)
        for i in range(1, numVerts - 1):
            prim3D.addVertices(i + 1, i, 0)
            prim3D.closePrimitive()

        # Line loop in 2D view.. using line strips
        prim2D = GeomLinestrips(GeomEnums.UHStatic)
        prim2D.reserveNumVertices(numVerts + 1)
        for i in range(numVerts):
            prim2D.addVertex(i)
        # Close off the line strip with the first vertex.. creating a line loop
        prim2D.addVertex(0)
        prim2D.closePrimitive()

        #
        # Generate mesh objects
        #

        geom3D = SolidFaceGeom(vdata)
        geom3D.setDrawMask(VIEWPORT_3D_MASK)
        geom3D.setPlaneCulled(True)
        geom3D.setPlane(self.plane)
        geom3D.addPrimitive(prim3D)
        self.index3D = self.solid.addFaceGeom(geom3D, self.state3D)

        geom3DLines = SolidFaceGeom(vdata)
        geom3DLines.addPrimitive(prim2D)
        geom3DLines.setDrawMask(VIEWPORT_3D_MASK)
        geom3DLines.setDraw(False)
        self.index3DLines = self.solid.addFaceGeom(geom3DLines, self.state3DLines)

        geom2D = SolidFaceGeom(vdata)
        geom2D.addPrimitive(prim2D)
        geom2D.setDrawMask(VIEWPORT_2D_MASK)
        self.index2D = self.solid.addFaceGeom(geom2D, self.state2D)

        self.geom3D = geom3D
        self.geom3DLines = geom3DLines
        self.geom2D = geom2D

        self.vdata = vdata

        self.hasGeometry = True
コード例 #4
0
def visualize(centers, corners, edges):
    from meshtool.filters.panda_filters.pandacore import getVertexData, attachLights, ensureCameraAt
    from meshtool.filters.panda_filters.pandacontrols import KeyboardMovement, MouseDrag, MouseScaleZoom, MouseCamera
    from panda3d.core import GeomPoints, GeomTriangles, Geom, GeomNode, GeomVertexFormat, GeomVertexData, GeomVertexWriter, LineSegs, VBase3
    from direct.showbase.ShowBase import ShowBase

    format = GeomVertexFormat.getV3c4()
    vdata = GeomVertexData('pts', format, Geom.UHDynamic)
    vertex = GeomVertexWriter(vdata, 'vertex')
    color = GeomVertexWriter(vdata, 'color')

    vertex_index = 0
    center_vertex_indices = {}
    corner_vertex_indices = {}
    for key, center in centers.iteritems():
        vertex.addData3f(center.x * X_SCALE, center.y * Y_SCALE,
                         center.elevation * Z_SCALE)
        curcolor = hex2rgb(COLORS[center.biome])
        color.addData4f(curcolor[0], curcolor[1], curcolor[2], 1)
        center_vertex_indices[key] = vertex_index
        vertex_index += 1

        for corner in center.corners:
            vertex.addData3f(corner.x * X_SCALE, corner.y * Y_SCALE,
                             corner.elevation * Z_SCALE)
            color.addData4f(curcolor[0], curcolor[1], curcolor[2], 1)
            corner_vertex_indices[corner.id] = vertex_index
            vertex_index += 1

    tris = GeomTriangles(Geom.UHDynamic)

    for edge in edges.itervalues():
        corner0 = edge.corner0
        corner1 = edge.corner1
        center0 = edge.center0
        center1 = edge.center1
        if corner0 is None or corner1 is None:
            continue

        tris.addVertices(corner_vertex_indices[corner1.id],
                         corner_vertex_indices[corner0.id],
                         center_vertex_indices[center0.id])

        tris.addVertices(center_vertex_indices[center1.id],
                         corner_vertex_indices[corner0.id],
                         corner_vertex_indices[corner1.id])

    tris.closePrimitive()

    pgeom = Geom(vdata)
    pgeom.addPrimitive(tris)

    node = GeomNode("primitive")
    node.addGeom(pgeom)

    p3dApp = ShowBase()
    attachLights(render)
    geomPath = render.attachNewNode(node)
    #geomPath.setRenderModeThickness(6.0)

    #geomPath.setRenderModeWireframe()

    ensureCameraAt(geomPath, base.cam)

    boundingSphere = geomPath.getBounds()
    base.cam.setPos(boundingSphere.getCenter() + boundingSphere.getRadius())

    base.cam.lookAt(boundingSphere.getCenter())

    geomPath.setScale(VBase3(50, 50, 50))

    KeyboardMovement()
    #MouseDrag(geomPath)
    MouseCamera()
    MouseScaleZoom(geomPath)
    #render.setShaderAuto()
    p3dApp.run()
コード例 #5
0
    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
        self.geomNode = GeomNode('mesh')
        self.attachNewNode(self.geomNode)

        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)
            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)

        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}
            )
        ''')
コード例 #6
0
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
コード例 #7
0
def createCube(parent, index, cubeMembership, walls):

    vertexFormat = GeomVertexFormat.getV3n3cp()
    vertexData = GeomVertexData("cube_data", vertexFormat, Geom.UHStatic)
    tris = GeomTriangles(Geom.UHStatic)

    posWriter = GeomVertexWriter(vertexData, "vertex")
    colWriter = GeomVertexWriter(vertexData, "color")
    normalWriter = GeomVertexWriter(vertexData, "normal")

    vertexCount = 0

    for direction in (-1, 1):

        for i in range(3):

            normal = VBase3()
            normal[i] = direction
            rgb = [0., 0., 0.]
            rgb[i] = 1.

            if direction == 1:
                rgb[i - 1] = 1.

            r, g, b = rgb
            color = (r, g, b, 0.)

            for a, b in ((-1., -1.), (-1., 1.), (1., 1.), (1., -1.)):

                pos = VBase3()
                pos[i] = direction
                pos[(i + direction) % 3] = a
                pos[(i + direction * 2) % 3] = b

                posWriter.addData3f(pos)
                colWriter.addData4f(color)
                normalWriter.addData3f(normal)

            vertexCount += 4

            tris.addVertices(vertexCount - 2, vertexCount - 3, vertexCount - 4)
            tris.addVertices(vertexCount - 4, vertexCount - 1, vertexCount - 2)

    geom = Geom(vertexData)
    geom.addPrimitive(tris)
    node = GeomNode("cube_node")
    node.addGeom(geom)
    cube = parent.attachNewNode(node)
    x = index % 9 // 3 - 1
    y = index // 9 - 1
    z = index % 9 % 3 - 1
    cube.setScale(.4)
    cube.setPos(x * 0.85, y * 0.85, z * 0.85)
    membership = set()  # the walls this cube belongs to
    cubeMembership[cube] = membership

    if x == -1:
        walls["left"].append(cube)
        membership.add("left")
    elif x == 1:
        walls["right"].append(cube)
        membership.add("right")
    if y == -1:
        walls["front"].append(cube)
        membership.add("front")
    elif y == 1:
        walls["back"].append(cube)
        membership.add("back")
    if z == -1:
        walls["bottom"].append(cube)
        membership.add("bottom")
    elif z == 1:
        walls["top"].append(cube)
        membership.add("top")

    return cube
コード例 #8
0
def renderCharts(facegraph, verts, vert_indices, lineset=None):

    from meshtool.filters.panda_filters.pandacore import getVertexData, attachLights, ensureCameraAt
    from meshtool.filters.panda_filters.pandacontrols import KeyboardMovement, MouseDrag, MouseScaleZoom, ButtonUtils
    from panda3d.core import GeomTriangles, Geom, GeomNode, GeomVertexFormat, GeomVertexData, GeomVertexWriter, LineSegs
    from direct.showbase.ShowBase import ShowBase

    vformat = GeomVertexFormat.getV3c4()
    vdata = GeomVertexData('tris', vformat, Geom.UHDynamic)

    vertex = GeomVertexWriter(vdata, 'vertex')
    color = GeomVertexWriter(vdata, 'color')

    colors = gen_color3(len(facegraph))
    numtris = 0
    for chart, data in facegraph.nodes_iter(data=True):
        curcolor = next(colors)
        for tri in data['tris']:
            triv = verts[vert_indices[tri]]
            vertex.addData3f(triv[0][0], triv[0][1], triv[0][2])
            vertex.addData3f(triv[1][0], triv[1][1], triv[1][2])
            vertex.addData3f(triv[2][0], triv[2][1], triv[2][2])
            color.addData4f(curcolor[0], curcolor[1], curcolor[2], 1)
            color.addData4f(curcolor[0], curcolor[1], curcolor[2], 1)
            color.addData4f(curcolor[0], curcolor[1], curcolor[2], 1)
            numtris += 1

    tris = GeomTriangles(Geom.UHDynamic)
    tris.addConsecutiveVertices(0, 3 * numtris)
    tris.closePrimitive()

    linenodes = []
    if lineset:
        for lines in lineset:
            ls = LineSegs()
            ls.setThickness(4)
            curcolor = next(colors)
            ls.setColor(curcolor[0] / 256.0, curcolor[1] / 256.0,
                        curcolor[2] / 256.0, 1)

            tuples = False
            for blah in lines:
                if isinstance(blah, tuple):
                    tuples = True
                break
            if tuples:
                for i, j in lines:
                    frompt = verts[i]
                    topt = verts[j]
                    ls.moveTo(frompt[0], frompt[1], frompt[2])
                    ls.drawTo(topt[0], topt[1], topt[2])
            else:
                for i in range(len(lines) - 1):
                    frompt = verts[lines[i]]
                    topt = verts[lines[i + 1]]
                    ls.moveTo(frompt[0], frompt[1], frompt[2])
                    ls.drawTo(topt[0], topt[1], topt[2])

            linenodes.append(ls.create())

    pgeom = Geom(vdata)
    pgeom.addPrimitive(tris)

    node = GeomNode("primitive")
    node.addGeom(pgeom)

    p3dApp = ShowBase()
    #attachLights(render)
    geomPath = render.attachNewNode(node)

    for linenode in linenodes:
        geomPath.attachNewNode(linenode)

    #geomPath.setRenderModeWireframe()

    ensureCameraAt(geomPath, base.cam)

    boundingSphere = geomPath.getBounds()
    base.cam.setPos(boundingSphere.getCenter() + boundingSphere.getRadius())

    base.cam.lookAt(boundingSphere.getCenter())

    KeyboardMovement()
    ButtonUtils(geomPath)
    MouseDrag(geomPath)
    MouseScaleZoom(geomPath)
    #render.setShaderAuto()
    p3dApp.run()
コード例 #9
0
    def generate(self):
        '''(Re)generate the entire terrain erasing any current changes'''
        factor = self.blockSize * self.chunkSize
        #print "Factor:", factor
        for terrain in self.terrains:
            terrain.getRoot().removeNode()
        self.terrains = []
        # Breaking master heightmap into subimages
        heightmaps = []
        self.xchunks = (self.heightfield.getXSize() - 1) / factor
        self.ychunks = (self.heightfield.getYSize() - 1) / factor
        #print "X,Y chunks:", self.xchunks, self.ychunks
        n = 0
        for y in range(0, self.ychunks):
            for x in range(0, self.xchunks):
                heightmap = PNMImage(factor + 1, factor + 1)
                heightmap.copySubImage(self.heightfield,
                                       0,
                                       0,
                                       xfrom=x * factor,
                                       yfrom=y * factor)
                heightmaps.append(heightmap)
                n += 1

        # Generate GeoMipTerrains
        n = 0
        y = self.ychunks - 1
        x = 0
        for heightmap in heightmaps:
            terrain = GeoMipTerrain(str(n))
            terrain.setHeightfield(heightmap)
            terrain.setBruteforce(self.bruteForce)
            terrain.setBlockSize(self.blockSize)
            terrain.generate()
            self.terrains.append(terrain)
            root = terrain.getRoot()
            root.reparentTo(self.root)
            root.setPos(n % self.xchunks * factor, (y) * factor, 0)

            # In order to texture span properly we need to reiterate through every vertex
            # and redefine the uv coordinates based on our size, not the subGeoMipTerrain's
            root = terrain.getRoot()
            children = root.getChildren()
            for child in children:
                geomNode = child.node()
                for i in range(geomNode.getNumGeoms()):
                    geom = geomNode.modifyGeom(i)
                    vdata = geom.modifyVertexData()
                    texcoord = GeomVertexWriter(vdata, 'texcoord')
                    vertex = GeomVertexReader(vdata, 'vertex')
                    while not vertex.isAtEnd():
                        v = vertex.getData3f()
                        t = texcoord.setData2f(
                            (v[0] + self.blockSize / 2 + self.blockSize * x) /
                            (self.xsize - 1),
                            (v[1] + self.blockSize / 2 + self.blockSize * y) /
                            (self.ysize - 1))
            x += 1
            if x >= self.xchunks:
                x = 0
                y -= 1
            n += 1
コード例 #10
0
ファイル: geometry.py プロジェクト: tarsbase/cosmonium
def RingFaceGeometry(up, inner_radius, outer_radius, nbOfPoints):
    format = GeomVertexFormat.getV3n3cpt2()
    vdata = GeomVertexData('ring', format, Geom.UHStatic)
    vdata.unclean_set_num_rows(nbOfPoints)
    vertex = GeomVertexWriter(vdata, 'vertex')
    normal = GeomVertexWriter(vdata, 'normal')
    color = GeomVertexWriter(vdata, 'color')
    texcoord = GeomVertexWriter(vdata, 'texcoord')
    for i in range(nbOfPoints):
        angle = 2 * pi / nbOfPoints * i
        x = cos(angle)
        y = sin(angle)
        vertex.addData3f(outer_radius * x, outer_radius * y, 0)
        normal.addData3f(0, 0, up)
        color.addData4f(1, 1, 1, 1)
        texcoord.addData2f(1, 0)
        vertex.addData3f(inner_radius * x, inner_radius * y, 0)
        normal.addData3f(0, 0, up)
        color.addData4f(1, 1, 1, 1)
        texcoord.addData2f(0, 0)
    triangles = GeomTriangles(Geom.UHStatic)
    triangles.reserve_num_vertices(nbOfPoints - 1)
    for i in range(nbOfPoints - 1):
        if up < 0:
            triangles.addVertex(i * 2 + 0)
            triangles.addVertex(i * 2 + 1)
            triangles.addVertex(i * 2 + 2)
            triangles.closePrimitive()
            triangles.addVertex(i * 2 + 2)
            triangles.addVertex(i * 2 + 1)
            triangles.addVertex(i * 2 + 3)
            triangles.closePrimitive()
        else:
            triangles.addVertex(i * 2 + 2)
            triangles.addVertex(i * 2 + 1)
            triangles.addVertex(i * 2 + 0)
            triangles.closePrimitive()
            triangles.addVertex(i * 2 + 3)
            triangles.addVertex(i * 2 + 1)
            triangles.addVertex(i * 2 + 2)
            triangles.closePrimitive()
    if up < 0:
        triangles.addVertex((nbOfPoints - 1) * 2 + 0)
        triangles.addVertex((nbOfPoints - 1) * 2 + 1)
        triangles.addVertex(0)
        triangles.closePrimitive()
        triangles.addVertex(0)
        triangles.addVertex((nbOfPoints - 1) * 2 + 1)
        triangles.addVertex(1)
        triangles.closePrimitive()
    else:
        triangles.addVertex(0)
        triangles.addVertex((nbOfPoints - 1) * 2 + 1)
        triangles.addVertex((nbOfPoints - 1) * 2 + 0)
        triangles.closePrimitive()
        triangles.addVertex(1)
        triangles.addVertex((nbOfPoints - 1) * 2 + 1)
        triangles.addVertex(0)
        triangles.closePrimitive()
    geom = Geom(vdata)
    geom.addPrimitive(triangles)
    return geom
コード例 #11
0
    def addTriMeshSB(self,vertices, faces,normals = None,ghost=False,**kw):
        #step 1) create GeomVertexData and add vertex information
        # Soft body world information
        info = self.world.getWorldInfo()
        info.setAirDensity(0.0)
        info.setWaterDensity(0)
        info.setWaterOffset(0)
        info.setWaterNormal(Vec3(0, 0, 0))
        
        format=GeomVertexFormat.getV3n3() #getV3()#http://www.panda3d.org/manual/index.php/Pre-defined_vertex_formats
#        vdata = GeomVertexData('name', format, Geom.UHStatic)
        vdata=GeomVertexData("Mesh", format, Geom.UHStatic)
        
        vertexWriter=GeomVertexWriter(vdata, "vertex")
        [vertexWriter.addData3f(v[0],v[1],v[2]) for v in vertices]

        if normals is not None :
            normalWriter = GeomVertexWriter(vdata, 'normal')
            [normalWriter.addData3f(n[0],n[1],n[2]) for n in normals] 
        else :
            print "we need normals to bind geom to SoftBody"
            return None
        
        #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)
        
        vdata = geom.getVertexData()
#        print (vdata,vdata.hasColumn(InternalName.getVertex()))
        geomNode = GeomNode('')
        geomNode.addGeom(geom)

        #step 4) create the bullet softbody and node
        bodyNode = BulletSoftBodyNode.makeTriMesh(info, geom)
#        bodyNode.linkGeom(geomNode.modifyGeom(0))
        bodyNode.setName('Tri')
        bodyNode.linkGeom(geom)  
        bodyNode.generateBendingConstraints(1)#???
        #bodyNode.getMaterial(0).setLinearStiffness(0.8)
        bodyNode.getCfg().setPositionsSolverIterations(4)
#        bodyNode.getCfg().setCollisionFlag(BulletSoftBodyConfig.CFVertexFaceSoftSoft, True)
        bodyNode.getCfg().setDynamicFrictionCoefficient(1)
        bodyNode.getCfg().setDampingCoefficient(0.001)
        bodyNode.getCfg().setPressureCoefficient(15000*10.0)  
        bodyNode.getCfg().setPoseMatchingCoefficient(0.2)
        bodyNode.setPose(True, True)
#        bodyNode.randomizeConstraints()
        bodyNode.setTotalMass(50000*10, True)
        
        bodyNP = self.worldNP.attachNewNode(bodyNode)
#        fmt = GeomVertexFormat.getV3n3t2()
#        geom = BulletHelper.makeGeomFromFaces(bodyNode, fmt,True)

#        bodyNode.linkGeom(geomNode.modifyGeom(0))
#        geomNode = GeomNode('')
#        geomNode.addGeom(geom)
        
#        world.attachSoftBody(bodyNode)
#        inodenp.setPos(0, 0, 0.1)
#        self.setRB(bodyNP,**kw)#set po
#        inodenp.setCollideMask(BitMask32.allOn())
        self.world.attachSoftBody(bodyNode)
        geomNP = bodyNP.attachNewNode(geomNode)
        return bodyNP,geomNP
コード例 #12
0
ファイル: minicolumn.py プロジェクト: sergius-htm/HTMpandaVis
    def CreateProximalSynapses(self, inputNames, inputObj, permanences, thresholdConnected, createOnlyActive=False):

        self.DestroyProximalSynapses()

        printLog("Creating proximal permanences", verbosityMedium)
        printLog("To inputObj called:" + str(inputNames), verbosityMedium)
        printLog("permanences count:" + str(len(permanences)), verbosityMedium)
        printLog("active:" + str(sum([i for i in permanences])), verbosityHigh)

        # inputObj are divided into separate items in list - [input1,input2,input3]
        # permanences are one united array [1,0,0,1,0,1,0...]
        # length is the same

        # synapses can be connected to one input or to several inputObj
        # if to more than one - split synapses array
        synapsesDiv = []
        offset = 0
        for inputName in inputNames:
            synapsesDiv.append(permanences[offset : offset + inputObj[inputName].count])
            offset += inputObj[inputName].count

        for i in range(len(synapsesDiv)):  # for each input object

            inputObj[inputNames[i]].resetProximalFocus()  # clear color highlight

            for y in range(
                len(synapsesDiv[i])
            ):  # go through every synapse and check if its connected (we are comparing permanences)
                if synapsesDiv[i][y] >= thresholdConnected:

                    if createOnlyActive and not inputObj[inputNames[i]].inputBits[y].active:# we want to show only active synapses
                        continue

                    form = GeomVertexFormat.getV3()
                    vdata = GeomVertexData("ProximalSynapseLine", form, Geom.UHStatic)
                    vdata.setNumRows(1)
                    vertex = GeomVertexWriter(vdata, "vertex")

                    vertex.addData3f(
                        inputObj[inputNames[i]]
                        .inputBits[y]
                        .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))

                    # highlight
                    inputObj[inputNames[i]].inputBits[
                        y
                    ].setProximalFocus()  # highlight connected bits

                    prim = GeomLines(Geom.UHStatic)
                    prim.addVertices(0, 1)
                    

                    geom = Geom(vdata)
                    geom.addPrimitive(prim)

                    node = GeomNode("ProximalSynapse")
                    node.addGeom(geom)
                                       

                    nodePath = self.__cellsNodePath.attachNewNode(node)
                    
                    nodePath.setRenderModeThickness(2)
                    # color of the line
                    if inputObj[inputNames[i]].inputBits[y].active:
                        nodePath.setColor(COL_PROXIMAL_SYNAPSES_ACTIVE)
                    else:
                        nodePath.setColor(COL_PROXIMAL_SYNAPSES_INACTIVE)
コード例 #13
0
 def __init__(self, parent):
     DirectObject.DirectObject.__init__(self)
     self.debugMode = config.GetInt('loading-screen') == 2
     self.parent = parent
     self.state = False
     self.currScreenshot = None
     self.snapshot = None
     self.snapshotFrame = None
     self.snapshotFrameBasic = None
     self.currentTime = 0
     self.analyzeMode = False
     self.loadScale = 1.0
     self.unmappedTicks = []
     self.stepInfo = { }
     self.accept(base.win.getWindowEvent(), self.adjustSize)
     self.accept('tick', self.tick)
     self.currStage = 'unmapped'
     self.stagePercent = 0
     self.numObjects = 0
     self.currPercent = 0.0
     self.line = LineSegs()
     self.line.setColor((0, 0, 0, 1))
     self.line.setThickness(1)
     self.stageLabel = None
     self.currNum = 0
     self.overallPercent = 0
     self.lastPercent = 0
     self.topLock = aspect2dp.attachNewNode('topShift')
     self.root = self.topLock.attachNewNode('loadingScreenRoot')
     self.root.setZ(-1)
     self.root.stash()
     self.model = loader.loadModel('models/gui/pir_m_gui_gen_loadScreen.bam')
     self.model.setP(90)
     self.model.reparentTo(self.root)
     cm = CardMaker('backdrop')
     cm.setFrame(-10, 10, -10, 10)
     if self.debugMode:
         self.backdrop = self.root.attachNewNode(cm.generate())
         self.backdrop.setX(-1.5)
         self.backdrop.setZ(-1)
         self.backdrop.setScale(4)
         self.backdrop.setColor(0.5, 0.5, 0.5, 1)
         cm = CardMaker('loadingBarBase')
         cm.setFrame(-0.90000000000000002, 0.90000000000000002, 0.10000000000000001, 0.5)
         self.loadingBarBacking = self.root.attachNewNode(cm.generate())
         self.loadingBarRoot = self.root.attachNewNode('loadingBarRoot')
         cm.setName('analysisBarBase')
         cm.setFrame(-0.90000000000000002, 0.90000000000000002, -0.5, -0.10000000000000001)
         self.analysisBar = self.root.attachNewNode(cm.generate())
         self.analysisBarRoot = self.root.attachNewNode('analysisBarRoot')
         self.analysisBar.hide()
         self.analysisButtons = []
         self.enterToContinue = DirectLabel(parent = self.root, text = 'Press Shift To Continue', relief = None, text_scale = 0.10000000000000001, pos = (0, 0, -0.90000000000000002), text_align = TextNode.ACenter)
         self.enterToContinue.hide()
         self.stageLabel = DirectLabel(parent = self.root, text = '', relief = None, text_scale = 0.10000000000000001, pos = (-1.25, 0, 0.75), text_align = TextNode.ALeft, textMayChange = 1)
         self.tickLabel = DirectLabel(parent = self.root, text = '', relief = None, text_scale = 0.10000000000000001, pos = (0.75, 0, 0.75), textMayChange = 1)
         self.overallLabel = DirectLabel(parent = self.root, text = '', relief = None, text_scale = 0.10000000000000001, pos = (0, 0, -0.75), textMayChange = 1)
     else:
         self.backdrop = loader.loadModel('models/gui/pir_m_gui_gen_loadScreen')
         self.backdrop.reparentTo(self.root)
         bg = self.backdrop.find('**/expandable_bg')
         bg.setScale(1000, 1, 1000)
         bg.flattenStrong()
         self.backdrop.find('**/loadbar_grey').setColorScale(0.14999999999999999, 0.14999999999999999, 0.14999999999999999, 0.10000000000000001)
         self.loadingBar = self.backdrop.find('**/loadbar')
         self.loadingBar.setColorScale(0.20000000000000001, 0.59999999999999998, 0.5, 1)
         self.loadingPlank = NodePathCollection()
         self.loadingPlank.addPath(self.backdrop.find('**/plank_loading_bar'))
         self.loadingPlank.addPath(self.backdrop.find('**/loadbar'))
         self.loadingPlank.addPath(self.backdrop.find('**/loadbar_frame'))
         self.loadingPlank.addPath(self.backdrop.find('**/loadbar_grey'))
         self.titlePlank = self.backdrop.find('**/plank_title')
         self.percentLabel = DirectLabel(text = '0%', parent = self.root, relief = None, text_font = PiratesGlobals.getPirateFont(), text_fg = PiratesGuiGlobals.TextFG2, text_shadow = PiratesGuiGlobals.TextShadow, text_scale = 0.031, pos = (0, 0, -0.44450000000000001), textMayChange = 1)
         self.loadingPlank.addPath(self.percentLabel)
         self.screenshot = self.backdrop.find('**/screenshot')
         copyGeom = self.loadingBar.find('**/+GeomNode').node().getGeom(0)
         format = copyGeom.getVertexData().getFormat()
         primitive = copyGeom.getPrimitive(0)
         data = GeomVertexData(self.screenshot.node().getGeom(0).getVertexData())
         data.setFormat(format)
         writer = GeomVertexWriter(data, 'texcoord')
         writer.setData2f(0, 0)
         writer.setData2f(1, 0)
         writer.setData2f(1, 1)
         writer.setData2f(0, 1)
         geom = Geom(data)
         geom.addPrimitive(primitive)
         self.screenshot.node().removeGeom(0)
         self.screenshot.node().addGeom(geom)
         self.titlePlankMiddle = self.backdrop.find('**/plank_title_middle_box')
         self.titlePlankLeft = self.backdrop.find('**/plank_title_left')
         self.titlePlankRight = self.backdrop.find('**/plank_title_right')
     self.loadingBarColors = [ (((i % 10) / 10.0 + 0.5) / 2.0, ((i % 100) / 10 / 10.0 + 0.5) / 2.0, (i / 100 / 10.0 + 0.5) / 2.0, 1) for i in range(1000) ]
     random.shuffle(self.loadingBarColors)
     self.lastUpdateTime = globalClock.getRealTime()
     self.locationLabel = DirectLabel(parent = self.root, relief = None, text = '', text_font = PiratesGlobals.getPirateOutlineFont(), text_fg = PiratesGuiGlobals.TextFG1, text_shadow = PiratesGuiGlobals.TextShadow, text_scale = PiratesGuiGlobals.TextScaleTitleJumbo * 0.69999999999999996, text_align = TextNode.ACenter, pos = (0.0, 0.0, 0.51500000000000001), textMayChange = 1)
     self.locationText = None
     self.hintLabel = DirectLabel(parent = self.root, relief = None, text = '', text_font = PiratesGlobals.getPirateOutlineFont(), text_fg = PiratesGuiGlobals.TextFG1, text_shadow = PiratesGuiGlobals.TextShadow, text_scale = PiratesGuiGlobals.TextScaleTitleJumbo * 0.5, text_align = TextNode.ACenter, pos = (0.0, 0.0, -0.62), text_wordwrap = 30, textMayChange = 1)
     self.hintText = None
     self.adImage = None
     self.allowLiveFlatten = ConfigVariableBool('allow-live-flatten')
     self.title_art = []
     self.tempVolume = []
     self.adjustSize(base.win)
     gsg = base.win.getGsg()
     if gsg:
         self.root.prepareScene(gsg)
コード例 #14
0
    def __init__(self, size, pos, depth, mask, spec = WaterSpec()):
        NodePath.__init__(self, 'waterNode')
        self.setPos(pos)

        self.spec = spec
        self.pos = pos
        self.depth = depth
        self.size = size
        self.mask = mask
        self.height = pos[2]
        
        normal = (0, 0, 1)
        tangent = (normal[0], normal[2], -normal[1])
        binormal = (normal[2], normal[1], -normal[0])
        
        # Build array for new format.
        array = GeomVertexArrayFormat()
        array.addColumn(InternalName.make('vertex'), 3, Geom.NTFloat32, Geom.CPoint)
        array.addColumn(InternalName.make('texcoord'), 2, Geom.NTFloat32, Geom.CTexcoord)
        array.addColumn(InternalName.make('normal'), 3, Geom.NTFloat32, Geom.CVector)
        array.addColumn(InternalName.make('binormal'), 3, Geom.NTFloat32, Geom.CVector)
        array.addColumn(InternalName.make('tangent'), 3, Geom.NTFloat32, Geom.CVector)

        # Create and register format.
        format = GeomVertexFormat()
        format.addArray(array)
        format = GeomVertexFormat.registerFormat(format)

        vdata = GeomVertexData('waterPlanes', format, Geom.UHStatic)
        vdata.setNumRows(4)
        vtxWriter = GeomVertexWriter(vdata, 'vertex')
        tcWriter = GeomVertexWriter(vdata, 'texcoord')
        tnWriter = GeomVertexWriter(vdata, 'tangent')
        bnWriter = GeomVertexWriter(vdata, 'binormal')
        normWriter = GeomVertexWriter(vdata, 'normal')
        # top left corner
        vtxWriter.addData3f(size[0], size[3], 0)
        tcWriter.addData2f(0, 1)
        normWriter.addData3f(*normal)
        tnWriter.addData3f(*tangent)
        bnWriter.addData3f(*binormal)
        # bottom left corner
        vtxWriter.addData3f(size[0], size[2], 0)
        tcWriter.addData2f(0, 0)
        normWriter.addData3f(*normal)
        tnWriter.addData3f(*tangent)
        bnWriter.addData3f(*binormal)
        # top right corner
        vtxWriter.addData3f(size[1], size[3], 0)
        tcWriter.addData2f(1, 1)
        normWriter.addData3f(*normal)
        tnWriter.addData3f(*tangent)
        bnWriter.addData3f(*binormal)
        # bottom right corner
        vtxWriter.addData3f(size[1], size[2], 0)
        tcWriter.addData2f(1, 0)
        normWriter.addData3f(*normal)
        tnWriter.addData3f(*tangent)
        bnWriter.addData3f(*binormal)
        
        topTris = GeomTriangles(Geom.UHStatic)
        topTris.addVertices(0, 1, 2)
        topTris.addVertices(3, 2, 1)
        topGeom = Geom(vdata)
        topGeom.addPrimitive(topTris)
        self.topNP = self.attachNewNode(GeomNode('waterTop'))
        self.topNP.node().addGeom(topGeom)
        
        # Reverse the winding for the bottom water plane
        botTris = GeomTriangles(Geom.UHStatic)
        botTris.addVertices(2, 1, 0)
        botTris.addVertices(1, 2, 3)        
        botGeom = Geom(vdata)
        botGeom.addPrimitive(botTris)
        self.botNP = self.attachNewNode(GeomNode('waterBot'))
        self.botNP.node().addGeom(botGeom)

        # Create an AABB which defines the volume of this water.
        self.aabb = BoundingBox(Point3(size[0], size[2], -depth), Point3(size[1], size[3], 0))
        self.aabb.xform(self.getMat(render))
        
        self.cubemap = base.bspLoader.getClosestCubemapTexture(self.getPos(render))

        self.dudvFrame = 0
コード例 #15
0
ファイル: panda3d_visu.py プロジェクト: EParisot/mod1
    def draw_water_mesh(self):
        _format = GeomVertexFormat.get_v3n3cp()
        self.water_vdata = GeomVertexData('water', _format, Geom.UHDynamic)
        self.water_vdata.setNumRows((self.n_points // self.details)**2)
        vertex = GeomVertexWriter(self.water_vdata, 'vertex')
        normal = GeomVertexWriter(self.water_vdata, 'normal')
        color = GeomVertexWriter(self.water_vdata, 'color')

        for j in range(0, self.n_points, self.details):
            for i in range(0, self.n_points, self.details):
                if j == self.n_points - self.details:
                    j = self.n_points - 1
                if i == self.n_points - self.details:
                    i = self.n_points - 1
                # Water Vertices
                vertex.addData3f(self.x[j][i], self.y[j][i], self.wz[j][i])
                # Water Color
                color.addData4f(0.3, 0.3, 1, 0.8)
                # water Normals
                n = np.array([self.x[j][i], self.y[j][i], self.wz[j][i]])
                norm = n / np.linalg.norm(n)
                normal.addData3f(norm[0], norm[1], norm[2])
        # Water Primitive
        prim = GeomTriangles(Geom.UHDynamic)
        for j in range(self.n_points // self.details):
            for i in range(self.n_points // self.details):
                if j != (self.n_points // self.details) - 1 and i != (
                        self.n_points // self.details) - 1:
                    prim.add_vertices(
                        j * (self.n_points // self.details) + i,
                        j * (self.n_points // self.details) + (i + 1),
                        (j + 1) * (self.n_points // self.details) + i)
                    prim.add_vertices(
                        j * (self.n_points // self.details) + (i + 1),
                        (j + 1) * (self.n_points // self.details) + (i + 1),
                        (j + 1) * (self.n_points // self.details) + i)
        geom = Geom(self.water_vdata)
        prim.closePrimitive()
        geom.addPrimitive(prim)
        node = GeomNode('gnode')
        node.addGeom(geom)
        water_nodePath = render.attachNewNode(node)
        water_nodePath.setTransparency(TransparencyAttrib.MAlpha)
        water_nodePath.setAntialias(AntialiasAttrib.MAuto)
        water_nodePath.setPos(-50, -50, 0)

        # Border
        self.water_border_vdata = GeomVertexData('water_border', _format,
                                                 Geom.UHDynamic)
        self.water_border_vdata.setNumRows(8)
        vertex = GeomVertexWriter(self.water_border_vdata, 'vertex')
        normal = GeomVertexRewriter(self.water_border_vdata, 'normal')
        color = GeomVertexWriter(self.water_border_vdata, 'color')
        for i in [0, 99]:
            for j in range(1, -1, -1):
                # Borders Vertices
                vertex.addData3f(i, 0, j)
                # Borders Colors
                color.addData4f(0.3, 0.3, 1, 0.8)
                # Borders Normals
                n = np.array([i, 0, 1e-12 if j == 0 else 1])
                norm = n / np.linalg.norm(n)
                normal.addData3f(norm[0], norm[1], norm[2])
        for i in [99, 0]:
            for j in range(1, -1, -1):
                vertex.addData3f(i, 99, j)
                color.addData4f(0.3, 0.3, 1, 0.8)
                n = np.array([i, 99, 1e-12 if j == 0 else 1])
                norm = n / np.linalg.norm(n)
                normal.addData3f(norm[0], norm[1], norm[2])
        # Borders Primitive
        prim = GeomTriangles(Geom.UHDynamic)
        for i in range(0, 8, 2):
            prim.add_vertices(i, i+1 if i+1 < 8 else i+1-8, \
                i+2 if i+2 < 8 else i+2-8)
            prim.add_vertices(i+2 if i+2 < 8 else i+2-8, \
                i+1 if i+1 < 8 else i+1-8, i+3 if i+3 < 8 else i+3-8)
        geom = Geom(self.water_border_vdata)
        geom.addPrimitive(prim)
        node = GeomNode('gnode')
        node.addGeom(geom)
        water_border_nodePath = render.attachNewNode(node)
        water_border_nodePath.setTransparency(TransparencyAttrib.MAlpha)
        water_border_nodePath.setAntialias(AntialiasAttrib.MAuto)
        water_border_nodePath.setPos(-50, -50, 0)
コード例 #16
0
    def gen_geom(self, mesh_json):
        # Create vertex format
        geom_array = GeomVertexArrayFormat()
        geom_array.add_column("vertex", 3, Geom.NTFloat32, Geom.CPoint)
        has_normals = False
        has_texcoords = False
        has_weights = False
        if "normals" in mesh_json:
            geom_array.add_column("normal", 3, Geom.NTFloat32, Geom.CNormal)
            has_normals = True
        if "texcoords" in mesh_json:
            geom_array.add_column("texcoord", 3, Geom.NTFloat32,
                                  Geom.CTexcoord)
            has_texcoords = True
        if "weights" in mesh_json:
            geom_array.add_column("joint", 4, Geom.NTUint8, Geom.CIndex)
            geom_array.add_column("weight", 4, Geom.NTFloat32, Geom.COther)
            has_weights = True
        geom_format = GeomVertexFormat()
        geom_format.add_array(geom_array)
        geom_format = GeomVertexFormat.register_format(geom_format)

        # Set up vertex data
        vdata = GeomVertexData(
            str(random.randint(0, 255)) + "_vdata", geom_format, Geom.UHStatic)
        vcount = len(mesh_json["vertices"]) // 3
        vdata.setNumRows(vcount)
        vertex = GeomVertexWriter(vdata, "vertex")

        for i in range(vcount):
            vertex.addData3(mesh_json["vertices"][3 * i],
                            mesh_json["vertices"][3 * i + 1],
                            mesh_json["vertices"][3 * i + 2])
        if has_normals:
            normal = GeomVertexWriter(vdata, "normal")
            for i in range(vcount):
                normal.addData3(mesh_json["normals"][3 * i],
                                mesh_json["normals"][3 * i + 1],
                                mesh_json["normals"][3 * i + 2])
        if has_texcoords:
            texcoord = GeomVertexWriter(vdata, "texcoord")
            for i in range(vcount):
                texcoord.addData2(mesh_json["texcoords"][2 * i],
                                  mesh_json["texcoords"][2 * i + 1])
        if has_weights:
            joint = GeomVertexWriter(vdata, "joint")
            weight = GeomVertexWriter(vdata, "weight")
            for i in range(vcount):
                joint_count = len(mesh_json["joints"][i])
                joint.addData4(
                    0 if joint_count < 1 else mesh_json["joints"][i][0],
                    0 if joint_count < 2 else mesh_json["joints"][i][1],
                    0 if joint_count < 3 else mesh_json["joints"][i][2],
                    0 if joint_count < 4 else mesh_json["joints"][i][3])
                weight.addData4(
                    0 if joint_count < 1 else mesh_json["weights"][i][0],
                    0 if joint_count < 2 else mesh_json["weights"][i][1],
                    0 if joint_count < 3 else mesh_json["weights"][i][2],
                    0 if joint_count < 4 else mesh_json["weights"][i][3])

        # Create primitive
        prim = GeomTriangles(Geom.UHStatic)
        for i in range(vcount // 3):
            prim.addVertices(3 * i, 3 * i + 1, 3 * i + 2)
        geom = Geom(vdata)
        geom.add_primitive(prim)

        # Load texture
        tex = None
        if "texture" in mesh_json:
            tex = Loader(EComponent.base).loadTexture(
                (Path("resources") / mesh_json["texture"]).absolute())
            tex.setMagfilter(SamplerState.FT_nearest)
            tex.setMinfilter(SamplerState.FT_nearest)

        # Create new geometry node
        geom_node = GeomNode(str(random.randint(0, 255)) + "_node")
        if tex is None:
            geom_node.addGeom(geom)
        else:
            attrib = TextureAttrib.make(tex)
            state = RenderState.make(attrib)
            geom_node.addGeom(geom, state)
        if EComponent.panda_root_node is not None:
            self.geom_path = EComponent.panda_root_node.attach_new_node(
                geom_node)
            self.geom_path.set_shader_input("object_id", self.object_id)

        # Set shader
        if has_weights and self.geom_path is not None:
            self.geom_path.setTag("shader type", "skinned")
            bone_mats = PTA_LMatrix4f()
            for _ in range(100):
                bone_mats.push_back(helper.np_mat4_to_panda(np.identity(4)))
            self.geom_path.set_shader_input(f"boneMats", bone_mats)

            # Disable culling
            self.geom_path.node().setBounds(OmniBoundingVolume())
            self.geom_path.node().setFinal(True)
コード例 #17
0
    def generateNode(self):
        self.destroy()

        self.node = NodePath('gameobjectnode')
        self.node.setTwoSided(True)
        self.node.reparentTo(self.parent.node)

        if self.properties['avoidable'] == True:
            self.node.setTag("avoidable", 'true')
        else:
            self.node.setTag("avoidable", 'false')

        #setting scripting part
        self.node.setTag("onWalked", self.onWalked)
        self.node.setTag("onPicked", self.onPicked)
        #set unique id
        self.node.setTag("id", self.properties['id'])

        tex = loader.loadTexture(
            resourceManager.getResource(self.properties['url']) + '.png')
        tex.setWrapV(Texture.WM_clamp)
        tex.setWrapU(Texture.WM_clamp)

        #this is true pixel art
        #change to FTLinear for linear interpolation between pixel colors
        tex.setMagfilter(Texture.FTNearest)
        tex.setMinfilter(Texture.FTNearest)

        xorig = tex.getOrigFileXSize() / self.baseDimension
        yorig = tex.getOrigFileYSize() / self.baseDimension
        xscaled = (tex.getOrigFileXSize() /
                   self.baseDimension) * self.properties['scale']
        yscaled = (tex.getOrigFileYSize() /
                   self.baseDimension) * self.properties['scale']

        self.node.setTag("xscaled", str(xscaled))
        self.node.setTag("yscaled", str(yscaled))

        cm = CardMaker("tileobject")
        cm.setFrame(0, xorig, 0, yorig)

        ts = TextureStage('ts')
        ts.setMode(TextureStage.MDecal)

        # distinguish between 3d collisions (for objects with an height and sensible self.properties['inclination'])
        # and 2d collisions for plain sprites
        if self.properties['walkable'] == 'false':
            if self.properties['collisionmode'] == "3d":
                #must handle differently objects which are small and big
                if xscaled < 1:
                    self.collisionTube = CollisionBox(
                        LPoint3f(
                            0.5 - xscaled / 2 - self.properties['offsetwidth'],
                            0, 0),
                        LPoint3f(
                            0.5 + xscaled / 2 + self.properties['offsetwidth'],
                            0.1, 0.3 + self.properties['offsetheight']))

                if xscaled >= 1:
                    self.collisionTube = CollisionBox(
                        LPoint3f(0 - self.properties['offsetwidth'], 0, 0),
                        LPoint3f(xscaled + self.properties['offsetwidth'], 0.1,
                                 0.3 + self.properties['offsetheight']))

                self.collisionNode = CollisionNode('objectSphere')
                self.collisionNode.addSolid(self.collisionTube)
                self.collisionNodeNp = self.node.attachNewNode(
                    self.collisionNode)
                self.collisionNodeNp.setX(self.properties['offsethorizontal'])
                self.collisionNodeNp.setZ(self.properties['offsetvertical'])
                self.collisionNodeNp.setX(self.collisionNodeNp.getX() +
                                          self.properties['offsetcollisionh'])
                self.collisionNodeNp.setZ(self.collisionNodeNp.getZ() +
                                          self.properties['offsetcollisionv'] +
                                          0.1)
                if main.editormode:
                    self.collisionNodeNp.show()

            elif self.properties['collisionmode'] == "2d":
                #must handle differently objects which are small and big
                if xscaled < 1:
                    self.collisionTube = CollisionBox(
                        LPoint3f(
                            0.5 - xscaled / 2 - self.properties['offsetwidth'],
                            0, 0),
                        LPoint3f(
                            0.5 + xscaled / 2 + self.properties['offsetwidth'],
                            yscaled + self.properties['offsetheight'], 0.3))

                if xscaled >= 1:
                    self.collisionTube = CollisionBox(
                        LPoint3f(0 - self.properties['offsetwidth'], 0, 0),
                        LPoint3f(xscaled + self.properties['offsetwidth'],
                                 yscaled + self.properties['offsetheight'],
                                 0.3))

                self.collisionNode = CollisionNode('objectSphere')
                self.collisionNode.addSolid(self.collisionTube)
                self.collisionNodeNp = self.node.attachNewNode(
                    self.collisionNode)
                self.collisionNodeNp.setP(
                    -(270 - int(self.properties['inclination'])))
                self.collisionNodeNp.setX(self.properties['offsethorizontal'])
                self.collisionNodeNp.setZ(self.properties['offsetvertical'])
                self.collisionNodeNp.setX(self.collisionNodeNp.getX() +
                                          self.properties['offsetcollisionh'])
                self.collisionNodeNp.setZ(self.collisionNodeNp.getZ() +
                                          self.properties['offsetcollisionv'] +
                                          0.1)
                if main.editormode:
                    self.collisionNodeNp.show()

        geomnode = NodePath(cm.generate())
        if geomnode.node().isGeomNode():
            vdata = geomnode.node().modifyGeom(0).modifyVertexData()
            writer = GeomVertexWriter(vdata, 'vertex')
            reader = GeomVertexReader(vdata, 'vertex')
            '''
            this part apply rotation flattening to the perspective view
            by modifying directly structure vertices
            '''
            i = 0  #counter
            while not reader.isAtEnd():
                v = reader.getData3f()
                x = v[0]
                y = v[1]
                z = v[2]
                newx = x
                newy = y
                newz = z
                if self.properties['rotation'] == -90.0:
                    if i == 0:
                        newx = math.fabs(
                            math.cos(
                                math.radians(
                                    self.properties['inclination']))) * z
                        newz = 0
                        ssen = math.fabs(
                            math.sin(
                                math.radians(
                                    self.properties['inclination']))) * z
                        sparsen = math.fabs(
                            math.sin(
                                math.radians(
                                    self.properties['inclination']))) * ssen
                        spercos = math.fabs(
                            math.cos(
                                math.radians(
                                    self.properties['inclination']))) * ssen
                        newy -= spercos
                        newz += sparsen
                    if i == 2:
                        newx += math.fabs(
                            math.cos(
                                math.radians(
                                    self.properties['inclination']))) * z
                        newz = 0
                        ssen = math.fabs(
                            math.sin(
                                math.radians(
                                    self.properties['inclination']))) * z
                        sparsen = math.fabs(
                            math.sin(
                                math.radians(
                                    self.properties['inclination']))) * ssen
                        spercos = math.fabs(
                            math.cos(
                                math.radians(
                                    self.properties['inclination']))) * ssen
                        newy -= spercos
                        newz += sparsen
                    writer.setData3f(newx, newy, newz)
                i += 1  #increase vertex counter
        if xscaled >= 1:
            geomnode.setX(0)
        if xscaled < 1:
            geomnode.setX(0.5 - xscaled / 2)
        geomnode.setScale(self.properties['scale'])
        geomnode.setX(geomnode.getX() + self.properties['offsethorizontal'])
        geomnode.setZ(geomnode.getZ() + self.properties['offsetvertical'])
        geomnode.setY(-self.properties['elevation'])
        geomnode.setP(int(self.properties['inclination']) - 360)
        geomnode.setTexture(tex)
        geomnode.setTransparency(TransparencyAttrib.MAlpha)
        geomnode.reparentTo(self.node)
        self.node.setR(self.properties['rotation'])
コード例 #18
0
def makeSquare(x1, y1, z1, x2, y2, z2):
    format = GeomVertexFormat.getV3n3cpt2()
    vdata = GeomVertexData('square', format, Geom.UHDynamic)

    vertex = GeomVertexWriter(vdata, 'vertex')
    normal = GeomVertexWriter(vdata, 'normal')
    color = GeomVertexWriter(vdata, 'color')
    texcoord = GeomVertexWriter(vdata, 'texcoord')

    #make sure we draw the sqaure in the right plane
    if x1 != x2:
        vertex.addData3f(x1, y1, z1)
        vertex.addData3f(x2, y1, z1)
        vertex.addData3f(x2, y2, z2)
        vertex.addData3f(x1, y2, z2)

        normal.addData3f(myNormalize(Vec3(2 * x1 - 1, 2 * y1 - 1, 2 * z1 - 1)))
        normal.addData3f(myNormalize(Vec3(2 * x2 - 1, 2 * y1 - 1, 2 * z1 - 1)))
        normal.addData3f(myNormalize(Vec3(2 * x2 - 1, 2 * y2 - 1, 2 * z2 - 1)))
        normal.addData3f(myNormalize(Vec3(2 * x1 - 1, 2 * y2 - 1, 2 * z2 - 1)))

    else:
        vertex.addData3f(x1, y1, z1)
        vertex.addData3f(x2, y2, z1)
        vertex.addData3f(x2, y2, z2)
        vertex.addData3f(x1, y1, z2)

        normal.addData3f(myNormalize(Vec3(2 * x1 - 1, 2 * y1 - 1, 2 * z1 - 1)))
        normal.addData3f(myNormalize(Vec3(2 * x2 - 1, 2 * y2 - 1, 2 * z1 - 1)))
        normal.addData3f(myNormalize(Vec3(2 * x2 - 1, 2 * y2 - 1, 2 * z2 - 1)))
        normal.addData3f(myNormalize(Vec3(2 * x1 - 1, 2 * y1 - 1, 2 * z2 - 1)))

    #adding different colors to the vertex for visibility
    color.addData4f(1.0, 0.0, 0.0, 1.0)
    color.addData4f(0.0, 1.0, 0.0, 1.0)
    color.addData4f(0.0, 0.0, 1.0, 1.0)
    color.addData4f(1.0, 0.0, 1.0, 1.0)

    texcoord.addData2f(0.0, 1.0)
    texcoord.addData2f(0.0, 0.0)
    texcoord.addData2f(1.0, 0.0)
    texcoord.addData2f(1.0, 1.0)

    #quads arent directly supported by the Geom interface
    #you might be interested in the CardMaker class if you are
    #interested in rectangle though
    tri1 = GeomTriangles(Geom.UHDynamic)
    tri2 = GeomTriangles(Geom.UHDynamic)

    tri1.addVertex(0)
    tri1.addVertex(1)
    tri1.addVertex(3)

    tri2.addConsecutiveVertices(1, 3)

    tri1.closePrimitive()
    tri2.closePrimitive()

    square = Geom(vdata)
    square.addPrimitive(tri1)
    square.addPrimitive(tri2)

    return square
コード例 #19
0
    def makeMountains():

        format = GeomVertexFormat.getV3t2()
        vdata = GeomVertexData('mountains', format, Geom.UHStatic)
        vertex = GeomVertexWriter(vdata, 'vertex')
        texcoord = GeomVertexWriter(vdata, 'texcoord')

        format2 = GeomVertexFormat.getV3c4()
        vdata2 = GeomVertexData('sky', format2, Geom.UHStatic)
        vertex2 = GeomVertexWriter(vdata2, 'vertex')
        color2 = GeomVertexWriter(vdata2, 'color')

        numQuads = 32

        angle = 0
        textureX = 0
        angleAdd = math.pi * 2 / numQuads
        textureXAdd = 1.0 / numQuads
        currentQuad = 0
        numVertices = 0

        while currentQuad < numQuads:
            if currentQuad == 0:

                vertexX = math.sin(angle) * 3000
                vertexY = math.cos(angle) * 3000
                vertex.addData3f(vertexX, vertexY, 0.0)
                vertex.addData3f(vertexX, vertexY, 360.0)

                texcoord.addData2f(1.0, 0.0)
                texcoord.addData2f(1.0, 1.0)

                numVertices = numVertices + 2

            vertexX = math.sin(angle) * 3000
            vertexY = math.cos(angle) * 3000

            vertex.addData3f(vertexX, vertexY, 0.0)
            vertex.addData3f(vertexX, vertexY, 360.0)

            vertex2.addData3f(vertexX, vertexY, 360.0)
            color2.addData4f(45.0 / 255.0, 112.0 / 255.0, 255.0 / 255.0, 1.0)
            #color2.addData4f(1.0,1.0,1.0,1.0)

            #print('created vertex at '+str(vertexX)+','+str(vertexY)+',2')
            #print('created vertex at '+str(vertexX)+','+str(vertexY)+',0')

            texcoord.addData2f(textureX, 0.0)
            texcoord.addData2f(textureX, 1.0)
            #print('texturex is '+str(textureX))

            #print('creating vertices v'+str(numVertices)+' and v'+str(numVertices+1))

            numVertices = numVertices + 2
            currentQuad = currentQuad + 1
            textureX = textureX + textureXAdd
            angle = angle + angleAdd

        vertex2.addData3f(0.0, 0.0, 360.0)
        #color2.addData4f(1.0,1.0,1.0,1.0)
        color2.addData4f(45.0 / 255.0, 112.0 / 255.0, 255.0 / 255.0, 1.0)

        currentQuad = 0
        currentOffset = 2
        tris = GeomTriangles(Geom.UHDynamic)

        #print('creating tris - numVertices is '+str(numVertices))

        while currentQuad < numQuads:

            vertexOffsets = []
            for innerIndex in range(4):
                offset = currentOffset + innerIndex
                #print('comparing '+str(offset)+' with '+str(numVertices-1))
                if offset > numVertices - 1:
                    offset = offset - numVertices
                vertexOffsets.append(offset)

            #print('adding tri connecting v'+str(vertexOffsets[0])+', v'+str(vertexOffsets[1])+', v'+str(vertexOffsets[3]))
            #print('adding tri connecting v'+str(vertexOffsets[1])+', v'+str(vertexOffsets[3])+', v'+str(vertexOffsets[2]))

            tris.addVertex(vertexOffsets[0])
            tris.addVertex(vertexOffsets[2])
            tris.addVertex(vertexOffsets[1])
            tris.closePrimitive()

            tris.addVertex(vertexOffsets[1])
            tris.addVertex(vertexOffsets[2])
            tris.addVertex(vertexOffsets[3])
            tris.closePrimitive()

            currentOffset = currentOffset + 2
            currentQuad = currentQuad + 1

        tris2 = GeomTriangles(Geom.UHDynamic)
        currentOffset = 1

        numTris = numQuads
        currentTri = 0
        while currentTri < numTris:

            tris2.addVertex(numTris)
            tris2.addVertex(currentTri)
            if currentTri == numTris - 1:
                tris2.addVertex(0)
            else:
                tris2.addVertex(currentTri + 1)
            tris2.closePrimitive()

            currentTri = currentTri + 1

        mountains = Geom(vdata)
        mountains.addPrimitive(tris)

        sky = Geom(vdata2)
        sky.addPrimitive(tris2)

        snode = GeomNode('mountains')
        snode.addGeom(mountains)

        snode2 = GeomNode('sky')
        snode2.addGeom(sky)

        returnValues = {"mountains": snode, "sky": snode2}
        return returnValues
コード例 #20
0
ファイル: geom.py プロジェクト: Schiggebam/WarOfShapes3D
 def __init__(self, vdata):
     self.count = 0
     self.vertex = GeomVertexWriter(vdata, 'vertex')
     self.normal = GeomVertexWriter(vdata, 'normal')
     self.color = GeomVertexWriter(vdata, 'color')
     self.texcoord = GeomVertexWriter(vdata, 'texcoord')
コード例 #21
0
ファイル: Meshes.py プロジェクト: pdefromont/SpaceBusGame
    def __init__(self,
                 x_extend=None,
                 y_extend=None,
                 x_size=1,
                 y_size=1,
                 z=-0.01,
                 tickness=1.,
                 name='Grid',
                 x_color=None,
                 y_color=None):
        GeomNode.__init__(self, name)
        if x_color is None:
            x_color = LVector4f(1.0, 1.0, 1.0, 1.0)

        if y_color is None:
            y_color = LVector4f(1.0, 1.0, 1.0, 1.0)

        if x_extend is None:
            x_extend = [0, 10]
        if y_extend is None:
            y_extend = [0, 10]

        self.vertexData = GeomVertexData("Chunk", GeomVertexFormat.getV3c4(),
                                         Geom.UHStatic)
        self.vertex = GeomVertexWriter(self.vertexData, 'vertex')
        self.color = GeomVertexWriter(self.vertexData, 'color')

        self.mesh = Geom(self.vertexData)
        self.lines = GeomLines(Geom.UHStatic)

        nb_lines_x = int((x_extend[1] - x_extend[0]) / x_size)
        nb_lines_y = int((y_extend[1] - y_extend[0]) / y_size)

        vertex_nb = 0
        for ix in range(nb_lines_x):
            for iy in range(nb_lines_y):
                x = x_extend[0] + ix * x_size
                y = y_extend[0] + iy * y_size

                self.vertex.addData3f(x, y, z)
                self.color.addData4f(x_color)

                self.vertex.addData3f(x + x_size, y, z)
                self.color.addData4f(x_color)

                self.vertex.addData3f(x, y, z)
                self.color.addData4f(y_color)

                self.vertex.addData3f(x, y + y_size, z)
                self.color.addData4f(y_color)

                self.lines.add_vertices(vertex_nb, vertex_nb + 1,
                                        vertex_nb + 2, vertex_nb + 3)
                vertex_nb += 4

        self.lines.closePrimitive()
        self.mesh.addPrimitive(self.lines)
        self.addGeom(self.mesh)

        NodePath(self).setRenderModeThickness(tickness)
        NodePath(self).setLightOff()
        NodePath(self).setColorOff()
        NodePath(self).set_bin('fixed', 8)
コード例 #22
0
def drawBody(nodePath, vdata, pos, vecList, radius=1, keepDrawing=True, numVertices=8):

    circleGeom = Geom(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)

    sCoord = 0

    if (startRow != 0):
        texReWriter.setRow(startRow - numVertices)
        sCoord = texReWriter.getData2f().getX() + 1

        drawReWriter.setRow(startRow - numVertices)
        if(drawReWriter.getData1f() == False):
            sCoord -= 1

    drawReWriter.setRow(startRow)
    texReWriter.setRow(startRow)

    angleSlice = 2 * math.pi / numVertices
    currAngle = 0

    #axisAdj=LMatrix4.rotateMat(45, axis)*LMatrix4.scaleMat(radius)*LMatrix4.translateMat(pos)

    perp1 = vecList[1]
    perp2 = vecList[2]

    # vertex information is written here
    for i in range(numVertices):
        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(sCoord, (i + 0.001) / (numVertices - 1))
        colorWriter.addData4f(0.5, 0.5, 0.5, 1)
        drawReWriter.addData1f(keepDrawing)
        currAngle += angleSlice

    drawReader = GeomVertexReader(vdata, "drawFlag")
    drawReader.setRow(startRow - numVertices)

    # we cant draw quads directly so we use Tristrips
    if (startRow != 0) & (drawReader.getData1f() != False):
        lines = GeomTristrips(Geom.UHStatic)
        half = int(numVertices * 0.5)
        for i in range(numVertices):
            lines.addVertex(i + startRow)
            if i < half:
                lines.addVertex(i + startRow - half)
            else:
                lines.addVertex(i + startRow - half - numVertices)

        lines.addVertex(startRow)
        lines.addVertex(startRow - half)
        lines.closePrimitive()
        lines.decompose()
        circleGeom.addPrimitive(lines)

        circleGeomNode = GeomNode("Debug")
        circleGeomNode.addGeom(circleGeom)

        # I accidentally made the front-face face inwards. Make reverse makes the tree render properly and
        # should cause any surprises to any poor programmer that tries to use
        # this code
        circleGeomNode.setAttrib(CullFaceAttrib.makeReverse(), 1)
        global numPrimitives
        numPrimitives += numVertices * 2

        nodePath.attachNewNode(circleGeomNode)
コード例 #23
0
    def __init__(self):
        ShowBase.__init__(self)

        self.cols = 100
        self.rows = 100

        base.disableMouse()
        base.setFrameRateMeter(True)
        self.cameraHeight = 13
        self.camera.set_pos(self.cols / 2, -30, self.cameraHeight)
        self.camera.look_at(self.cols / 2, 300, 0)

        plights = []

        for i in range(0, int(self.cols / 5), 2):
            plight = PointLight("plight")
            plight.setColor(VBase4(1, 1, 1, 1))
            plights.append(plight)
            plights[i] = self.render.attachNewNode(plight)
            x, y, z = self.camera.get_pos()
            plights[i].setPos(self.cols / 2 + ((i - int(i / 2)) * 10), y + 20,
                              5)
            self.render.set_light(plights[i])

            plight = PointLight("plight")
            plight.setColor(VBase4(1, 1, 1, 1))
            plights.append(plight)
            plights[i + 1] = self.render.attachNewNode(plight)
            x, y, z = self.camera.get_pos()
            plights[i + 1].setPos(self.cols / 2 + ((i - int(i / 2)) * 10),
                                  y + 20, 10)
            self.render.set_light(plights[i + 1])

        self.plights = plights

        format = GeomVertexFormat.getV3c4()
        vdata = GeomVertexData('name', format, Geom.UHStatic)
        vdata.setNumRows(self.cols * self.rows)
        self.vertex = GeomVertexWriter(vdata, 'vertex')
        self.color = GeomVertexWriter(vdata, 'color')

        pz = [random.uniform(-1, 1)]
        for i in range(self.rows):
            pz.append(random.uniform(pz[i - 1] - 1, pz[i] + 1))
        for y in range(0, self.rows):
            for x in range(0, self.cols):
                nz1 = random.uniform(pz[x] - 1, pz[x] + 1)
                nz2 = random.uniform(pz[x - 1] - 1, pz[x - 1] + 1)
                nz3 = random.uniform(pz[x + 1] - 1, pz[x + 1] + 1)
                nz = (nz1 + nz2 + nz3) / 3
                self.vertex.add_data3f((x, y + 1, nz))
                self.vertex.add_data3f((x, y, pz[x]))
                if nz < -5:
                    self.color.add_data4f(0.2, 0.1, 0, 1)
                elif nz < -3:
                    self.color.add_data4f(0, 0.2, 0.1, 1)
                elif nz < 0:
                    self.color.add_data4f(0, 0.4, 0.2, 1)
                elif nz < 2:
                    self.color.add_data4f(0.4, 0.4, 0.4, 1)
                else:
                    self.color.add_data4f(1, 1, 1, 1)
                if nz < -5:
                    self.color.add_data4f(0.2, 0.1, 0, 1)
                elif nz < -3:
                    self.color.add_data4f(0, 0.2, 0.1, 1)
                elif pz[x] < 0:
                    self.color.add_data4f(0, 0.4, 0.2, 1)
                elif pz[x] < 2:
                    self.color.add_data4f(0.4, 0.4, 0.4, 1)
                else:
                    self.color.add_data4f(1, 1, 1, 1)
                pz[x] = nz
                #print (nz)
        self.pz = pz

        geom = Geom(vdata)
        for y in range(0, self.rows):
            prim = GeomTristrips(Geom.UH_static)
            prim.addVertex(y * self.cols * 2)
            prim.add_next_vertices((self.cols * 2) - 1)
            prim.close_primitive()
            geom.addPrimitive(prim)

        nodeTris = GeomNode("TriStrips")
        nodeTris.addGeom(geom)
        self.nodeTrisPath = self.render.attachNewNode(nodeTris)
        self.task_mgr.add(self.moveForwardTask, "moveForwardTask")

        self.vdata = vdata
        self.newNodePath = []
        self.counter = 0
        self.rows1 = self.rows

        skybox = self.loader.loadModel("models/skybox.bam")
        skybox.reparent_to(self.render)
        skybox.set_scale(20000)

        skybox_texture = self.loader.loadTexture("textures/dayfair.jpg")
        skybox_texture.set_minfilter(SamplerState.FT_linear)
        skybox_texture.set_magfilter(SamplerState.FT_linear)
        skybox_texture.set_wrap_u(SamplerState.WM_repeat)
        skybox_texture.set_wrap_v(SamplerState.WM_mirror)
        skybox_texture.set_anisotropic_degree(16)
        skybox.set_texture(skybox_texture)

        skybox_shader = Shader.load(Shader.SL_GLSL, "skybox.vert.glsl",
                                    "skybox.frag.glsl")
        skybox.set_shader(skybox_shader)
コード例 #24
0
ファイル: __init__.py プロジェクト: PlumpMath/Blockiverse
    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)
コード例 #25
0
ファイル: annotations.py プロジェクト: ondrocks/cosmonium
    def create_instance(self):
        self.vertexData = GeomVertexData('vertexData',
                                         GeomVertexFormat.getV3c4(),
                                         Geom.UHStatic)
        self.vertexWriter = GeomVertexWriter(self.vertexData, 'vertex')
        self.colorwriter = GeomVertexWriter(self.vertexData, 'color')
        for r in range(1, self.nbOfRings + 1):
            for i in range(self.nbOfPoints):
                angle = 2 * pi / self.nbOfPoints * i
                x = cos(angle) * sin(pi * r / (self.nbOfRings + 1))
                y = sin(angle) * sin(pi * r / (self.nbOfRings + 1))
                z = sin(-pi / 2 + pi * r / (self.nbOfRings + 1))

                self.vertexWriter.addData3f(
                    (self.context.observer.infinity * x,
                     self.context.observer.infinity * y,
                     self.context.observer.infinity * z))
                if r == self.nbOfRings / 2 + 1:
                    self.colorwriter.addData4f(self.color.x * 1.5, 0, 0, 1)
                else:
                    self.colorwriter.addData4f(*self.color)
        for s in range(self.nbOfSectors):
            for i in range(self.points_to_remove,
                           self.nbOfPoints // 2 - self.points_to_remove + 1):
                angle = 2 * pi / self.nbOfPoints * i
                x = cos(2 * pi * s / self.nbOfSectors) * sin(angle)
                y = sin(2 * pi * s / self.nbOfSectors) * sin(angle)
                z = cos(angle)

                self.vertexWriter.addData3f(
                    (self.context.observer.infinity * x,
                     self.context.observer.infinity * y,
                     self.context.observer.infinity * z))
                if s == 0:
                    self.colorwriter.addData4f(self.color.x * 1.5, 0, 0, 1)
                else:
                    self.colorwriter.addData4f(*self.color)
        self.lines = GeomLines(Geom.UHStatic)
        index = 0
        for r in range(self.nbOfRings):
            for i in range(self.nbOfPoints - 1):
                self.lines.addVertex(index)
                self.lines.addVertex(index + 1)
                self.lines.closePrimitive()
                index += 1
            self.lines.addVertex(index)
            self.lines.addVertex(index - self.nbOfPoints + 1)
            self.lines.closePrimitive()
            index += 1
        for r in range(self.nbOfSectors):
            for i in range(self.nbOfPoints // 2 - self.points_to_remove * 2):
                self.lines.addVertex(index)
                self.lines.addVertex(index + 1)
                self.lines.closePrimitive()
                index += 1
            index += 1
        self.geom = Geom(self.vertexData)
        self.geom.addPrimitive(self.lines)
        self.node = GeomNode("grid")
        self.node.addGeom(self.geom)
        self.instance = NodePath(self.node)
        self.instance.setRenderModeThickness(settings.grid_thickness)
        #myMaterial = Material()
        #myMaterial.setEmission((1.0, 1.0, 1.0, 1))
        #self.instance.setMaterial(myMaterial)
        self.instance.reparentTo(self.context.annotation)
        self.instance.setQuat(LQuaternion(*self.orientation))
コード例 #26
0
    def CreateProximalSynapses(self, inputObjects, inputs, synapses):

        for child in self.__cellsNodePath.getChildren():
            if child.getName() == "ProximalSynapseLine":
                child.removeNode()

        printLog("Creating proximal synapses", verbosityMedium)
        printLog("To inputs called:" + str(inputObjects), verbosityMedium)
        printLog("Synapses count:" + str(len(synapses)), verbosityMedium)
        printLog("active:" + str(sum([i for i in synapses])), verbosityHigh)

        # inputs are divided into separate items in list - [input1,input2,input3]
        # synapses are one united array [1,0,0,1,0,1,0...]
        # length is the same

        # synapses can be connected to one input or to several inputs
        # if to more than one - split synapses array
        synapsesDiv = []
        offset = 0
        for inputObj in inputObjects:
            synapsesDiv.append(synapses[offset:offset +
                                        inputs[inputObj].count])
            offset += inputs[inputObj].count

        for i in range(len(synapsesDiv)):  # for each input object

            inputs[
                inputObjects[i]].resetProximalFocus()  # clear color highlight

            for y in range(len(synapsesDiv[i])
                           ):  # go through every synapse and check activity
                if synapsesDiv[i][y] == 1:

                    form = GeomVertexFormat.getV3()
                    vdata = GeomVertexData("ProximalSynapseLine", form,
                                           Geom.UHStatic)
                    vdata.setNumRows(1)
                    vertex = GeomVertexWriter(vdata, "vertex")

                    vertex.addData3f(
                        inputs[inputObjects[i]].inputBits[y].getNode().getPos(
                            self.__node))
                    vertex.addData3f(0, 0, 0)
                    # vertex.addData3f(self.__node.getPos())
                    # printLog("Inputs:"+str(i)+"bits:"+str(y))
                    # printLog(inputs[i].inputBits[y].getNode().getPos(self.__node))

                    # highlight
                    inputs[inputObjects[i]].inputBits[y].setProximalFocus(
                    )  # highlight connected bits

                    prim = GeomLines(Geom.UHStatic)
                    prim.addVertices(0, 1)

                    geom = Geom(vdata)
                    geom.addPrimitive(prim)

                    node = GeomNode("ProximalSynapse")
                    node.addGeom(geom)

                    nodePath = self.__cellsNodePath.attachNewNode(node)

                    nodePath.setRenderModeThickness(2)
                    # color of the line
                    if inputs[inputObjects[i]].inputBits[y].active:
                        nodePath.setColor(COL_PROXIMAL_SYNAPSES_ACTIVE)
                    else:
                        nodePath.setColor(COL_PROXIMAL_SYNAPSES_INACTIVE)
コード例 #27
0
ファイル: geometry.py プロジェクト: mhcrnl/panda_examples
 def interpolate_maps(self, task):
     # First, the actual interpolation
     t_index = self.last_time
     current_map = {}
     for x in range(0, self.sidelength):
         for y in range(0, self.sidelength):
             # calculate vertices
             p_1 = self.map_a[(x, y)]
             p_2 = self.map_b[(x, y)]
             v_x = p_1[0]*(1.0-t_index) + p_2[0]*t_index
             v_y = p_1[1]*(1.0-t_index) + p_2[1]*t_index
             v_z = p_1[2]*(1.0-t_index) + p_2[2]*t_index
             current_map[(x, y)] = (v_x, v_y, v_z)
     # Set up the writers
     vertex = GeomVertexWriter(self.vdata, 'vertex')
     normal = GeomVertexWriter(self.vdata, 'normal')
     # We don't use vertex readers as we don't care about the
     # current state, but if we did, it'd look like this:
     #     vertex_reader = GeomVertexReader(self.vdata, 'vertex')
     #     v = vertex_reader.getData3f()
     # Remember that all vertex readers working on a
     # GeomVertexData have to be created *after* the writers
     # working on it (due to engine internals; see the manual).
     for x in range(0, self.sidelength):
         for y in range(0, self.sidelength):
             v_x, v_y, v_z = current_map[(x, y)]
             vertex.setData3f(v_x, v_y, v_z)
             # Calculate the normal
             if x==0 and y==0:
                 s_0 = Vec3( 0.0,  1.0, v_z - current_map[(x, y+1)][2])
                 s_1 = Vec3( 1.0,  0.0, v_z - current_map[(x+1, y)][2])
                 e_0 = s_0.cross(s_1)
                 # Flip if necessary, then normalize
                 if e_0[2] < 0.0:
                     e_0 = e_0*-1.0
                 n = e_0
                 n = n/n.length()
             elif x==0 and y==(self.sidelength-1):
                 # First, we calculate the vectors to the neighbors.
                 s_1 = Vec3( 1.0,  0.0, v_z - current_map[(x+1, y)][2])
                 s_2 = Vec3( 0.0, -1.0, v_z - current_map[(x, y-1)][2])
                 e_1 = s_1.cross(s_2)
                 # Flip if necessary, then normalize
                 if e_1[2] < 0.0:
                     e_1 = e_1*-1.0
                 n = e_1
                 n = n/n.length()
             elif x==(self.sidelength-1) and y==0:
                 # First, we calculate the vectors to the neighbors.
                 s_0 = Vec3( 0.0,  1.0, v_z - current_map[(x, y+1)][2])
                 s_3 = Vec3(-1.0,  0.0, v_z - current_map[(x-1, y)][2])
                 e_3 = s_3.cross(s_0)
                 # Flip if necessary, then normalize
                 if e_3[2] < 0.0:
                     e_3 = e_3*-1.0
                 n = e_3
                 n = n/n.length()
             elif x==(self.sidelength-1) or y==(self.sidelength-1):
                 # First, we calculate the vectors to the neighbors.
                 s_2 = Vec3( 0.0, -1.0, v_z - current_map[(x, y-1)][2])
                 s_3 = Vec3(-1.0,  0.0, v_z - current_map[(x-1, y)][2])
                 e_2 = s_2.cross(s_3)
                 # Flip if necessary, then normalize
                 if e_2[2] < 0.0:
                     e_2 = e_2*-1.0
                 n = e_2
                 n = n/n.length()
             elif x==0:
                 # First, we calculate the vectors to the neighbors.
                 s_0 = Vec3( 0.0,  1.0, v_z - current_map[(x, y+1)][2])
                 s_1 = Vec3( 1.0,  0.0, v_z - current_map[(x+1, y)][2])
                 s_2 = Vec3( 0.0, -1.0, v_z - current_map[(x, y-1)][2])
                 e_0 = s_0.cross(s_1)
                 e_1 = s_1.cross(s_2)
                 # Flip if necessary, then normalize
                 if e_0[2] < 0.0:
                     e_0 = e_0*-1.0
                 if e_1[2] < 0.0:
                     e_1 = e_1*-1.0
                 n = e_0 + e_1
                 n = n/n.length()
             elif y==0:
                 # First, we calculate the vectors to the neighbors.
                 s_0 = Vec3( 0.0,  1.0, v_z - current_map[(x, y+1)][2])
                 s_1 = Vec3( 1.0,  0.0, v_z - current_map[(x+1, y)][2])
                 s_3 = Vec3(-1.0,  0.0, v_z - current_map[(x-1, y)][2])
                 e_0 = s_0.cross(s_1)
                 e_3 = s_3.cross(s_0)
                 # Flip if necessary, then normalize
                 if e_0[2] < 0.0:
                     e_0 = e_0*-1.0
                 if e_3[2] < 0.0:
                     e_3 = e_3*-1.0
                 n = e_0 + e_3
                 n = n/n.length()
             elif x==(self.sidelength-1):
                 # First, we calculate the vectors to the neighbors.
                 s_1 = Vec3( 1.0,  0.0, v_z - current_map[(x+1, y)][2])
                 s_2 = Vec3( 0.0, -1.0, v_z - current_map[(x, y-1)][2])
                 s_3 = Vec3(-1.0,  0.0, v_z - current_map[(x-1, y)][2])
                 e_1 = s_1.cross(s_2)
                 e_2 = s_2.cross(s_3)
                 # Flip if necessary, then normalize
                 if e_1[2] < 0.0:
                     e_1 = e_1*-1.0
                 if e_2[2] < 0.0:
                     e_2 = e_2*-1.0
                 n = e_1 + e_2
                 n = n/n.length()
             elif y==(self.sidelength-1):
                 # First, we calculate the vectors to the neighbors.
                 s_1 = Vec3( 1.0,  0.0, v_z - current_map[(x+1, y)][2])
                 s_2 = Vec3( 0.0, -1.0, v_z - current_map[(x, y-1)][2])
                 s_3 = Vec3(-1.0,  0.0, v_z - current_map[(x-1, y)][2])
                 e_1 = s_1.cross(s_2)
                 e_2 = s_2.cross(s_3)
                 # Flip if necessary, then normalize
                 if e_1[2] < 0.0:
                     e_1 = e_1*-1.0
                 if e_2[2] < 0.0:
                     e_2 = e_2*-1.0
                 n = e_1 + e_2
                 n = n/n.length()
             else: # This is a normal case, not an edge or corner.
                 # First, we calculate the vectors to the neighbors.
                 s_0 = Vec3( 0.0,  1.0, v_z - current_map[(x, y+1)][2])
                 s_1 = Vec3( 1.0,  0.0, v_z - current_map[(x+1, y)][2])
                 s_2 = Vec3( 0.0, -1.0, v_z - current_map[(x, y-1)][2])
                 s_3 = Vec3(-1.0,  0.0, v_z - current_map[(x-1, y)][2])
                 e_0 = s_0.cross(s_1)
                 e_1 = s_1.cross(s_2)
                 e_2 = s_2.cross(s_3)
                 e_3 = s_3.cross(s_0)
                 # Flip if necessary, then normalize
                 if e_0[2] < 0.0:
                     e_0 = e_0*-1.0
                 if e_1[2] < 0.0:
                     e_1 = e_1*-1.0
                 if e_2[2] < 0.0:
                     e_2 = e_2*-1.0
                 if e_3[2] < 0.0:
                     e_3 = e_3*-1.0
                 n = e_0 + e_1 + e_2 + e_3
                 n = n/n.length()
             normal.setData3f(n[0], n[1], n[2])
     return Task.cont
コード例 #28
0
    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(
コード例 #29
0
ファイル: mesh.py プロジェクト: Shaked-g/Ariel_OOP_2020
    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)
コード例 #30
0
def makeSquare(
    x1, y1, z1, x2, y2, z2, color
):  # This is straight copied off the Panda3d 'procedural cube' example https://github.com/panda3d/panda3d/blob/master/samples/procedural-cube/main.py#L11

    format = GeomVertexFormat.getV3n3cpt2()
    vdata = GeomVertexData('square', format, Geom.UHDynamic)

    vertex = GeomVertexWriter(vdata, 'vertex')
    normal = GeomVertexWriter(vdata, 'normal')
    color_setter = GeomVertexWriter(vdata, 'color')
    texcoord = GeomVertexWriter(vdata, 'texcoord')

    # make sure we draw the sqaure in the right plane
    if x1 != x2:
        vertex.addData3(x1, y1, z1)
        vertex.addData3(x2, y1, z1)
        vertex.addData3(x2, y2, z2)
        vertex.addData3(x1, y2, z2)

        normal.addData3(normalized(2 * x1 - 1, 2 * y1 - 1, 2 * z1 - 1))
        normal.addData3(normalized(2 * x2 - 1, 2 * y1 - 1, 2 * z1 - 1))
        normal.addData3(normalized(2 * x2 - 1, 2 * y2 - 1, 2 * z2 - 1))
        normal.addData3(normalized(2 * x1 - 1, 2 * y2 - 1, 2 * z2 - 1))

    else:
        vertex.addData3(x1, y1, z1)
        vertex.addData3(x2, y2, z1)
        vertex.addData3(x2, y2, z2)
        vertex.addData3(x1, y1, z2)

        normal.addData3(normalized(2 * x1 - 1, 2 * y1 - 1, 2 * z1 - 1))
        normal.addData3(normalized(2 * x2 - 1, 2 * y2 - 1, 2 * z1 - 1))
        normal.addData3(normalized(2 * x2 - 1, 2 * y2 - 1, 2 * z2 - 1))
        normal.addData3(normalized(2 * x1 - 1, 2 * y1 - 1, 2 * z2 - 1))

    # adding different colors to the vertex for visibility
    if np.sum(color) > 0:
        a = 1  # Alpha transparency
    else:
        a = 0

    # Handling channel size 1 or 3
    if np.size(color) == 1:
        for i in range(
                4
        ):  # Have to run this 4 times cuz each vertex on the square has a color setting
            color_setter.addData2f(color, a)
    elif np.size(color) == 3:
        r, g, b = color[0], color[1], color[2]
        for i in range(4):
            color_setter.addData4f(r, g, b, a)

    texcoord.addData2f(0.0, 1.0)
    texcoord.addData2f(0.0, 0.0)
    texcoord.addData2f(1.0, 0.0)
    texcoord.addData2f(1.0, 1.0)

    # Quads aren't directly supported by the Geom interface
    # you might be interested in the CardMaker class if you are
    # interested in rectangle though
    tris = GeomTriangles(Geom.UHDynamic)
    tris.addVertices(0, 1, 3)
    tris.addVertices(1, 2, 3)

    square = Geom(vdata)
    square.addPrimitive(tris)
    return square