Beispiel #1
0
    def __init__(self, name, format = GeomVertexFormat.getV3()):
        self.views = []
        self.vertexBuffer = GeomVertexData(name + "-vdata", format, GeomEnums.UHDynamic)

        self.np = NodePath(name)
        self.np.node().setBounds(OmniBoundingVolume())
        self.np.node().setFinal(1)
Beispiel #2
0
    def _CreateOneSynapse(self, presynCell, synapsesType):

        presynCell.setPresynapticFocus()  # highlight presynaptic cells

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

        vertex.addData3f(presynCell.getNode().getPos(self._node))
        vertex.addData3f(0, 0, 0)

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

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

        node = GeomNode("Synapse_" + str(synapsesType))
        node.addGeom(geom)

        nodePath = self._node.attachNewNode(node)

        nodePath.setRenderModeThickness(2)

        # color of the line
        if presynCell.active:
            nodePath.setColor(COL_DISTAL_SYNAPSES_ACTIVE)
        else:
            nodePath.setColor(COL_DISTAL_SYNAPSES_INACTIVE)
Beispiel #3
0
def makeRotationGeomNode():
    vdata = GeomVertexData('rotHandleData', GeomVertexFormat.getV3(),
            Geom.UHStatic)
    v = GeomVertexWriter(vdata, 'vertex')
    radius = 0.7
    width = 0.08
    res = 30
    innerRad = radius - width

    for i in xrange(res):
        theta = i*(2*pi/res)
        v.addData3f(innerRad*sin(theta), innerRad*cos(theta), width/2.0)
        v.addData3f(innerRad*sin(theta), innerRad*cos(theta), -width/2.0)
        v.addData3f(radius*sin(theta), radius*cos(theta), width/2.0)
        v.addData3f(radius*sin(theta), radius*cos(theta), -width/2.0)

    circle = Geom(vdata)
    # Make prims for the faces of the torus
    faces = [GeomTristrips(Geom.UHStatic) for i in xrange(4)]
    for i in xrange(res):
        i = i*4
        faces[0].addVertices(i + 1, i)
        faces[1].addVertices(i + 2, i + 1)
        faces[2].addVertices(i + 3, i + 2)
        faces[3].addVertices(i, i + 3)
    for i in xrange(4):
        faces[i].addVertices((i + 1) % 4, i)
        faces[i].closePrimitive()
        circle.addPrimitive(faces[i])
    node = GeomNode('geomnode')
    node.addGeom(circle)
    return node
Beispiel #4
0
    def _CreateOneSynapse(self, presynCell, synapsesType):

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

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

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

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

        node = GeomNode("Synapse_" + str(synapsesType))
        node.addGeom(geom)

        nodePath = self.__cellsNodePath.attachNewNode(node)

        nodePath.setRenderModeThickness(2)
        # color of the line
        if presynCell.active:
            nodePath.setColor(COL_PROXIMAL_SYNAPSES_ACTIVE)
        else:
            nodePath.setColor(COL_PROXIMAL_SYNAPSES_INACTIVE)
Beispiel #5
0
    def addMeshConvexRB(self,vertices, faces,ghost=False,**kw):
        #step 1) create GeomVertexData and add vertex information
        format=GeomVertexFormat.getV3()
        vdata=GeomVertexData("vertices", format, Geom.UHStatic)
        
        vertexWriter=GeomVertexWriter(vdata, "vertex")
        [vertexWriter.addData3f(v[0],v[1],v[2]) for v in vertices]
        
        #step 2) make primitives and assign vertices to them
        tris=GeomTriangles(Geom.UHStatic)
        [self.setGeomFaces(tris,face) for face in faces]
        
        #step 3) make a Geom object to hold the primitives
        geom=Geom(vdata)
        geom.addPrimitive(tris)
        
        #step 4) create the bullet mesh and node
        mesh = BulletTriangleMesh()
        mesh.addGeom(geom)

        shape = BulletConvexHullShape(mesh, dynamic=not ghost)#
        if ghost :
            inodenp = self.worldNP.attachNewNode(BulletGhostNode('Mesh'))
        else :
            inodenp = self.worldNP.attachNewNode(BulletRigidBodyNode('Mesh'))
        inodenp.node().addShape(shape)
#        inodenp.setPos(0, 0, 0.1)
        self.setRB(inodenp,**kw)
        inodenp.setCollideMask(BitMask32.allOn())
   
        self.world.attachRigidBody(inodenp.node())
        return inodenp
Beispiel #6
0
    def __init__(self, whl_pos, whl_radius, car_h):
        GameObject.__init__(self)
        self.radius = whl_radius
        v_f = GeomVertexFormat.getV3()
        vdata = GeomVertexData('skid', v_f, Geom.UHDynamic)
        prim = GeomTriangles(Geom.UHStatic)
        self.vtx_cnt = 1
        self.last_pos = whl_pos
        geom = Geom(vdata)
        geom.add_primitive(prim)
        self.node = GeomNode('gnode')
        self.node.add_geom(geom)
        nodepath = self.eng.gfx.root.attach_node(self.node)
        nodepath.set_transparency(True)
        nodepath.set_depth_offset(1)
        nodepath.node.set_two_sided(True)  # for self-shadowing issues
        self.__set_material(nodepath)
        nodepath.p3dnode.set_bounds(OmniBoundingVolume())
        self.add_vertices(whl_radius, car_h)
        self.add_vertices(whl_radius, car_h)

        def alpha(time, n_p):
            if not n_p.is_empty:
                n_p.node.set_shader_input('alpha', time)
            # this if seems necessary since, if there are skidmarks and you
            # exit from the race (e.g. back to the menu), then alpha is being
            # called from the interval manager even if the interval manager
            # correctly says that there are 0 intervals.

        self.remove_seq = Sequence(
            Wait(8), LerpFunc(alpha, 8, .5, 0, 'easeInOut', [nodepath]),
            Func(nodepath.remove_node))
        self.remove_seq.start()
Beispiel #7
0
def makeRotationGeomNode():
    vdata = GeomVertexData('rotHandleData', GeomVertexFormat.getV3(),
                           Geom.UHStatic)
    v = GeomVertexWriter(vdata, 'vertex')
    radius = 0.7
    width = 0.08
    res = 30
    innerRad = radius - width

    for i in xrange(res):
        theta = i * (2 * pi / res)
        v.addData3f(innerRad * sin(theta), innerRad * cos(theta), width / 2.0)
        v.addData3f(innerRad * sin(theta), innerRad * cos(theta), -width / 2.0)
        v.addData3f(radius * sin(theta), radius * cos(theta), width / 2.0)
        v.addData3f(radius * sin(theta), radius * cos(theta), -width / 2.0)

    circle = Geom(vdata)
    # Make prims for the faces of the torus
    faces = [GeomTristrips(Geom.UHStatic) for i in xrange(4)]
    for i in xrange(res):
        i = i * 4
        faces[0].addVertices(i + 1, i)
        faces[1].addVertices(i + 2, i + 1)
        faces[2].addVertices(i + 3, i + 2)
        faces[3].addVertices(i, i + 3)
    for i in xrange(4):
        faces[i].addVertices((i + 1) % 4, i)
        faces[i].closePrimitive()
        circle.addPrimitive(faces[i])
    node = GeomNode('geomnode')
    node.addGeom(circle)
    return node
Beispiel #8
0
 def create_instance(self):
     self.vertexData = GeomVertexData('vertexData',
                                      GeomVertexFormat.getV3(),
                                      Geom.UHStatic)
     self.vertexWriter = GeomVertexWriter(self.vertexData, 'vertex')
     radius = 1.0
     top = LPoint3d(0, 0, radius * 1.25)
     north_pole = LPoint3d(0, 0, radius)
     south_pole = LPoint3d(0, 0, -radius)
     bottom = LPoint3d(0, 0, -radius * 1.25)
     self.vertexWriter.addData3f(*top)
     self.vertexWriter.addData3f(*north_pole)
     self.vertexWriter.addData3f(*south_pole)
     self.vertexWriter.addData3f(*bottom)
     self.lines = GeomLines(Geom.UHStatic)
     self.lines.addVertex(0)
     self.lines.addVertex(1)
     self.lines.addVertex(2)
     self.lines.addVertex(3)
     self.lines.closePrimitive()
     self.geom = Geom(self.vertexData)
     self.geom.addPrimitive(self.lines)
     self.node = GeomNode(self.body.get_ascii_name() + '-axis')
     self.node.addGeom(self.geom)
     self.instance = NodePath(self.node)
     self.instance.setRenderModeThickness(settings.axis_thickness)
     self.instance.setColor(self.parent.get_orbit_color())
     self.instance.setAntialias(AntialiasAttrib.MMultisample)
     self.instance.reparentTo(self.context.annotation)
Beispiel #9
0
def makeSprite(name, texture, scale, add = False):
    from panda3d.core import (GeomVertexFormat, GeomVertexData, GeomEnums,
                              InternalName, GeomVertexWriter, GeomPoints,
                              Geom, GeomNode, NodePath, TextureStage,
                              TexGenAttrib, BoundingSphere)
    format = GeomVertexFormat.getV3()
    data = GeomVertexData(name + "_data", format, GeomEnums.UHStatic)
    writer = GeomVertexWriter(data, InternalName.getVertex())
    writer.addData3f((0, 0, 0))
    primitive = GeomPoints(GeomEnums.UHStatic)
    primitive.addVertex(0)
    primitive.closePrimitive()
    geom = Geom(data)
    geom.addPrimitive(primitive)
    geomNode = GeomNode(name)
    geomNode.addGeom(geom)
    np = NodePath(geomNode)
    np.setLightOff(1)
    np.setMaterialOff(1)
    np.setRenderModePerspective(True)
    ts = TextureStage('sprite')
    if add:
        ts.setMode(TextureStage.MAdd)
    np.setTexture(ts, texture)
    np.setTexGen(ts, TexGenAttrib.MPointSprite)

    np.setDepthWrite(False)
    np.setDepthOffset(1)
    np.setTransparency(True)
    np.node().setBounds(BoundingSphere((0, 0, 0), 1))
    np.node().setFinal(True)
    np.flattenStrong()
    np.setScale(scale)

    return np
Beispiel #10
0
 def __init__(self, wheel_pos, radius, heading):
     self.radius = radius
     v_f = GeomVertexFormat.getV3()
     self.vdata = GeomVertexData('skid', v_f, Geom.UHDynamic)
     self.vdata.setNumRows(1)
     self.vertex = GeomVertexWriter(self.vdata, 'vertex')
     self.prim = GeomTriangles(Geom.UHStatic)
     self.cnt = 1
     self.last_pos = wheel_pos
     geom = Geom(self.vdata)
     geom.addPrimitive(self.prim)
     node = GeomNode('gnode')
     node.addGeom(geom)
     nodePath = render.attachNewNode(node)
     nodePath.setTransparency(True)
     nodePath.setDepthOffset(1)
     self.__set_material(nodePath)
     nodePath.node().setBounds(OmniBoundingVolume())
     self.add_vertices(radius, heading)
     self.add_vertices(radius, heading)
     self.remove_seq = Sequence(
         Wait(8),
         LerpFunc(nodePath.setAlphaScale, 8, 1, 0, 'easeInOut'),
         Func(nodePath.remove_node))
     self.remove_seq.start()
Beispiel #11
0
    def Cube(size=1.0,
             geom_name="CubeMaker",
             gvd_name="Data",
             gvw_name="vertex"):
        from panda3d.core import (
            Vec3,
            GeomVertexFormat,
            GeomVertexData,
            GeomVertexWriter,
            GeomTriangles,
            Geom,
            GeomNode,
            NodePath,
            GeomPoints,
            loadPrcFileData,
        )

        format = GeomVertexFormat.getV3()
        data = GeomVertexData(gvd_name, format, Geom.UHStatic)
        vertices = GeomVertexWriter(data, gvw_name)

        size = float(size) / 2.0
        vertices.addData3f(-size, -size, -size)
        vertices.addData3f(+size, -size, -size)
        vertices.addData3f(-size, +size, -size)
        vertices.addData3f(+size, +size, -size)
        vertices.addData3f(-size, -size, +size)
        vertices.addData3f(+size, -size, +size)
        vertices.addData3f(-size, +size, +size)
        vertices.addData3f(+size, +size, +size)

        triangles = GeomTriangles(Geom.UHStatic)

        def addQuad(v0, v1, v2, v3):
            triangles.addVertices(v0, v1, v2)
            triangles.addVertices(v0, v2, v3)
            triangles.closePrimitive()

        addQuad(4, 5, 7, 6)  # Z+
        addQuad(0, 2, 3, 1)  # Z-
        addQuad(3, 7, 5, 1)  # X+
        addQuad(4, 6, 2, 0)  # X-
        addQuad(2, 6, 7, 3)  # Y+
        addQuad(0, 1, 5, 4)  # Y+

        geom = Geom(data)
        geom.addPrimitive(triangles)

        node = GeomNode(geom_name)
        node.addGeom(geom)

        return NodePath(node)
Beispiel #12
0
    def __init__(self, name='ConstrainedDelaunayTriangles', geomVertexDataObj=None,
                 format=GeomVertexFormat.getV3(), usage=Geom.UHDynamic,
                 onVertexCreationCallback=None, universalZ=0):

        if geomVertexDataObj is None:
            geomVertexDataObj = GeomVertexData(name, format, usage)
        self.vertexData = geomVertexDataObj
        # self.vertexRewriter = GeomVertexRewriter(self.vertexData, 'vertex')

        if onVertexCreationCallback is None:
            onVertexCreationCallback = lambda vdata: None
        self._onVertexCreationCallback = onVertexCreationCallback

        self.universalZ = universalZ
Beispiel #13
0
def makeGeomNode():
    vdata = GeomVertexData('handleData', GeomVertexFormat.getV3(),
            Geom.UHStatic)
    v = GeomVertexWriter(vdata, 'vertex')
    length = 1.0
    gapLen = 0.2
    coneLen = 0.18
    coneRad = 0.06
    circRes = 10

    v.addData3f(0, 0, -length/2.0) # back cone butt
    v.addData3f(0, 0, -length/2.0 + coneLen) # back cone point
    v.addData3f(0, 0, -gapLen/2.0)
    v.addData3f(0, 0, gapLen/2.0)
    v.addData3f(0, 0, length/2.0 - coneLen) # front cone butt
    v.addData3f(0, 0, length/2.0) # font cone point
    # Add vertices for the cone's circles.
    for z in [-length/2.0, length/2.0 - coneLen]:
        for i in xrange(circRes):
            theta = i*(2*pi/circRes)
            v.addData3f(coneRad*sin(theta), coneRad*cos(theta), z)

    lines = Geom(vdata)
    # Make prims for the two lines.
    for vertices in [(0, 2), (3, 5)]:
        line = GeomLines(Geom.UHStatic)
        line.addVertices(*vertices)
        line.closePrimitive()
        lines.addPrimitive(line)

    cones = Geom(vdata)
    # Make prims for the cones.
    for back, circ in [(0, 6), (4, 6 + circRes)]:
        point = back + 1
        cone = GeomTriangles(Geom.UHStatic)
        for i in xrange(circRes):
            if i + 1 == circRes:
                cone.addVertices(back, circ, circ + i)
                cone.addVertices(point, circ + i, circ)
            else:
                cone.addVertices(back, circ + i + 1, circ + i)
                cone.addVertices(point, circ + i, circ + i + 1)
        cone.closePrimitive()
        cones.addPrimitive(cone)
    
    node = GeomNode('geomnode')
    node.addGeom(lines)
    node.addGeom(cones)
    return node
Beispiel #14
0
def makeGeomNode():
    vdata = GeomVertexData('handleData', GeomVertexFormat.getV3(),
                           Geom.UHStatic)
    v = GeomVertexWriter(vdata, 'vertex')
    length = 1.0
    gapLen = 0.2
    coneLen = 0.18
    coneRad = 0.06
    circRes = 10

    v.addData3f(0, 0, -length / 2.0)  # back cone butt
    v.addData3f(0, 0, -length / 2.0 + coneLen)  # back cone point
    v.addData3f(0, 0, -gapLen / 2.0)
    v.addData3f(0, 0, gapLen / 2.0)
    v.addData3f(0, 0, length / 2.0 - coneLen)  # front cone butt
    v.addData3f(0, 0, length / 2.0)  # font cone point
    # Add vertices for the cone's circles.
    for z in [-length / 2.0, length / 2.0 - coneLen]:
        for i in xrange(circRes):
            theta = i * (2 * pi / circRes)
            v.addData3f(coneRad * sin(theta), coneRad * cos(theta), z)

    lines = Geom(vdata)
    # Make prims for the two lines.
    for vertices in [(0, 2), (3, 5)]:
        line = GeomLines(Geom.UHStatic)
        line.addVertices(*vertices)
        line.closePrimitive()
        lines.addPrimitive(line)

    cones = Geom(vdata)
    # Make prims for the cones.
    for back, circ in [(0, 6), (4, 6 + circRes)]:
        point = back + 1
        cone = GeomTriangles(Geom.UHStatic)
        for i in xrange(circRes):
            if i + 1 == circRes:
                cone.addVertices(back, circ, circ + i)
                cone.addVertices(point, circ + i, circ)
            else:
                cone.addVertices(back, circ + i + 1, circ + i)
                cone.addVertices(point, circ + i, circ + i + 1)
        cone.closePrimitive()
        cones.addPrimitive(cone)

    node = GeomNode('geomnode')
    node.addGeom(lines)
    node.addGeom(cones)
    return node
Beispiel #15
0
 def create_instance(self):
     if not self.orbit:
         return
     self.vertexData = GeomVertexData('vertexData',
                                      GeomVertexFormat.getV3(),
                                      Geom.UHStatic)
     self.vertexWriter = GeomVertexWriter(self.vertexData, 'vertex')
     delta = self.body.parent.get_local_position()
     for i in range(self.nbOfPoints):
         time = self.orbit.period / self.nbOfPoints * i
         pos = self.orbit.get_position_at(time)
         rot = self.orbit.get_rotation_at(time)
         pos = self.orbit.frame.get_local_position(rot.xform(pos)) - delta
         self.vertexWriter.addData3f(*pos)
     self.lines = GeomLines(Geom.UHStatic)
     for i in range(self.nbOfPoints - 1):
         self.lines.addVertex(i)
         self.lines.addVertex(i + 1)
         self.lines.closePrimitive()
     self.lines.addVertex(self.nbOfPoints - 1)
     self.lines.addVertex(0)
     self.lines.closePrimitive()
     self.geom = Geom(self.vertexData)
     self.geom.addPrimitive(self.lines)
     self.node = GeomNode(self.body.get_ascii_name() + '-orbit')
     self.node.addGeom(self.geom)
     self.instance = NodePath(self.node)
     self.instance.setRenderModeThickness(settings.orbit_thickness)
     self.instance.setCollideMask(GeomNode.getDefaultCollideMask())
     self.instance.node().setPythonTag('owner', self)
     self.instance.reparentTo(self.context.annotation_shader)
     if self.color is None:
         self.color = self.parent.get_orbit_color()
     self.instance.setColor(self.color * self.fade)
     self.instance.setAntialias(AntialiasAttrib.MMultisample)
     self.appearance = ModelAppearance(attribute_color=True)
     if settings.use_inv_scaling:
         vertex_control = LargeObjectVertexControl()
     else:
         vertex_control = None
     self.instance_ready = True
     self.shader = BasicShader(lighting_model=FlatLightingModel(),
                               vertex_control=vertex_control)
     self.shader.apply(self, self.appearance)
     self.shader.update(self, self.appearance)
Beispiel #16
0
 def makeNode(self, pointmap=(lambda x, y: (x, y, 0))):
     vt = tuple(self.vertices)
     t = Triangulator()
     fmt = GeomVertexFormat.getV3()
     vdata = GeomVertexData('name', fmt, Geom.UHStatic)
     vertex = GeomVertexWriter(vdata, 'vertex')
     for x, y in vt:
         t.addPolygonVertex(t.addVertex(x, y))
         vertex.addData3f(pointmap(x, y))
     t.triangulate()
     prim = GeomTriangles(Geom.UHStatic)
     for n in xrange(t.getNumTriangles()):
         prim.addVertices(t.getTriangleV0(n),t.getTriangleV1(n),t.getTriangleV2(n))
     prim.closePrimitive()
     geom = Geom(vdata)
     geom.addPrimitive(prim)
     node = GeomNode('gnode')
     node.addGeom(geom)
     return node
Beispiel #17
0
    def __init__(self):
        ShowBase.__init__(self)  # 初期化

        vs = open('vs_water.glsl', "r", encoding="UTF-8").read()
        fs = open('fs_water.glsl', "r", encoding="UTF-8").read()

        props = WindowProperties()
        props.setTitle('Fragment')
        Win_size = (1920, 1080)  # ウィンドウサイズ
        props.setSize(Win_size)  # ウィンドウのサイズを設定
        props.setCursorHidden(True)  # マウスカーソルを隠す
        base.win.requestProperties(props)

        self.AspectRaito = float(Win_size[0] / Win_size[1])  # アスペクト比を計算

        self.accept("escape", sys.exit)  # 終了
        self.disableMouse()  # マウスカーソルを非表示
        self.setFrameRateMeter(True)  # FPSを表示

        camera.setPos(0, -2, 0)  # カメラを配置
        format = GeomVertexFormat.getV3()

        mesh = GeomVertexData('', format, Geom.UHDynamic)  # メッシュを用意
        vertex = GeomVertexWriter(mesh, 'vertex')  # 頂点オブジェクト
        vertex.addData3(-1, 0, -1)  # 頂点を追加
        vertex.addData3(-1, 0, 1)
        vertex.addData3(1, 0, 1)
        vertex.addData3(1, 0, -1)
        tri = GeomTriangles(Geom.UHDynamic)  # 面オブジェクト
        tri.addVertices(0, 2, 1)  # 面のインデックスを追加
        tri.addVertices(0, 3, 2)
        node = GeomNode('')
        geo = Geom(mesh)  # ジオメトリオブジェクト
        geo.addPrimitive(tri)  # プリミティブにする
        node.addGeom(geo)
        self.panel = render.attachNewNode(node)  # レンダーオブジェクトとして追加

        shader = Shader.make(Shader.SL_GLSL, vs, fs)
        self.panel.setShader(shader)
        resolution = self.win.getXSize(), self.win.getYSize()
        self.panel.setShaderInput('resolution', resolution)

        taskMgr.add(self.Loop, 'update')  # メインループ
Beispiel #18
0
def Patch(size=1.0):
    (path, node) = empty_node('patch')
    form = GeomVertexFormat.getV3()
    vdata = GeomVertexData("vertices", form, Geom.UHStatic)

    vertexWriter = GeomVertexWriter(vdata, b"vertex")
    vertexWriter.addData3f(-size, -size, 0)
    vertexWriter.addData3f(size, -size, 0)
    vertexWriter.addData3f(size, size, 0)
    vertexWriter.addData3f(-size, size, 0)
    patches = GeomPatches(4, Geom.UHStatic)

    patches.addConsecutiveVertices(0, 4)  #South, west, north, east
    patches.closePrimitive()

    gm = Geom(vdata)
    gm.addPrimitive(patches)

    node.addGeom(gm)
    return path
 def CreateTestScene(self):
 
     form = GeomVertexFormat.getV3()
     vdata = GeomVertexData("myLine", form, Geom.UHStatic)
     vdata.setNumRows(1)
     vertex = GeomVertexWriter(vdata, "vertex")
 
     vertex.addData3f(0, 0, 0)
     vertex.addData3f(60, 0, 50)
 
     prim = GeomLines(Geom.UHStatic)
     prim.addVertices(0, 1)
 
     geom = Geom(vdata)
     geom.addPrimitive(prim)
 
     node = GeomNode("gnode")
     node.addGeom(geom)
 
     nodePath = self.render.attachNewNode(node)
Beispiel #20
0
 def addLine(self, points):
     """
 Adds a line to class GeomNode from a pair of points
 """
     #Creates objects needed to draw a geometry on the HUD
     #The vertex data which will define the rendered geometry
     vertex_data = GeomVertexData("graph", GeomVertexFormat.getV3(),
                                  Geom.UHStatic)
     #The object that writes vertexes the vertex data
     writer = GeomVertexWriter(vertex_data, "vertex")
     for point in points:
         writer.add_data3f(point[0], 0, point[1])
     #Defines that this geometry represents a polyline
     primitive = GeomLinestrips(Geom.UHStatic)
     #Tells geometry how many verticies will be added(?)
     primitive.add_consecutive_vertices(0, 2)
     primitive.close_primitive()
     geometry = Geom(vertex_data)
     geometry.add_primitive(primitive)
     #Draws a graph on the HUD
     self.geom_node.add_geom(geometry)
Beispiel #21
0
def makeClickableGeom():
    vdata = GeomVertexData('handleData', GeomVertexFormat.getV3(),
                           Geom.UHStatic)
    v = GeomVertexWriter(vdata, 'vertex')
    length = 1.0
    cylRad = 0.10
    circRes = 8

    # Add vertices cylinder.
    for z in [length / 2.0, -length / 2.0]:
        for i in xrange(circRes):
            theta = i * (2 * pi / circRes)
            v.addData3f(cylRad * sin(theta), cylRad * cos(theta), z)

    geom = Geom(vdata)
    # Make polys for the circles
    CCW = 1
    CW = 0
    for i, wind in ((0, CCW), (circRes, CW)):
        circle = GeomTristrips(Geom.UHStatic)
        l = range(i, i + circRes)
        for i in xrange(1 - wind, (len(l) - wind) / 2):
            l.insert(2 * i + wind, l.pop())
        for v in l:
            circle.addVertex(v)
        circle.closePrimitive()
        geom.addPrimitive(circle)

    # Make polys for the cylinder.
    cyl = GeomTristrips(Geom.UHStatic)
    for i in xrange(circRes):
        cyl.addVertex(i + circRes)
        cyl.addVertex(i)
    cyl.addVertex(circRes)
    cyl.addVertex(0)
    cyl.closePrimitive()
    geom.addPrimitive(cyl)
    node = GeomNode('geomnode')
    node.addGeom(geom)
    return node
Beispiel #22
0
def createPlane(width,height):

    format=GeomVertexFormat.getV3()
    vdata=GeomVertexData("vertices", format, Geom.UHStatic)

    vertexWriter=GeomVertexWriter(vdata, "vertex")
    vertexWriter.addData3f(0,0,0)
    vertexWriter.addData3f(width,0,0)
    vertexWriter.addData3f(width,height,0)
    vertexWriter.addData3f(0,height,0)

    #step 2) make primitives and assign vertices to them
    tris=GeomTriangles(Geom.UHStatic)

    #have to add vertices one by one since they are not in order
    tris.addVertex(0)
    tris.addVertex(1)
    tris.addVertex(3)

    #indicates that we have finished adding vertices for the first triangle.
    tris.closePrimitive()

    #since the coordinates are in order we can use this convenience function.
    tris.addConsecutiveVertices(1,3) #add vertex 1, 2 and 3
    tris.closePrimitive()

    #step 3) make a Geom object to hold the primitives
    squareGeom=Geom(vdata)
    squareGeom.addPrimitive(tris)

    #now put squareGeom in a GeomNode. You can now position your geometry in the scene graph.
    squareGN=GeomNode("square")
    squareGN.addGeom(squareGeom)

    terrainNode = NodePath("terrNode")
    terrainNode.reparentTo(render)
    terrainNode.attachNewNode(squareGN)
    terrainNode.setX(-width/2)
    texGrass = loader.loadTexture("textures/envir-ground.jpg")
    terrainNode.setTexture(texGrass)
Beispiel #23
0
def makeClickableGeom():
    vdata = GeomVertexData('handleData', GeomVertexFormat.getV3(),
            Geom.UHStatic)
    v = GeomVertexWriter(vdata, 'vertex')
    length = 1.0
    cylRad = 0.10
    circRes = 8

    # Add vertices cylinder.
    for z in [length/2.0, -length/2.0]:
        for i in xrange(circRes):
            theta = i*(2*pi/circRes)
            v.addData3f(cylRad*sin(theta), cylRad*cos(theta), z)

    geom = Geom(vdata)
    # Make polys for the circles
    CCW = 1
    CW = 0
    for i, wind in ((0, CCW), (circRes, CW)):
        circle = GeomTristrips(Geom.UHStatic)
        l = range(i, i+circRes)
        for i in xrange(1-wind, (len(l)-wind)/2):
            l.insert(2*i+wind, l.pop())
        for v in l:
            circle.addVertex(v)
        circle.closePrimitive()
        geom.addPrimitive(circle)

    # Make polys for the cylinder.
    cyl = GeomTristrips(Geom.UHStatic)
    for i in xrange(circRes):
        cyl.addVertex(i + circRes)
        cyl.addVertex(i)
    cyl.addVertex(circRes)
    cyl.addVertex(0)
    cyl.closePrimitive()
    geom.addPrimitive(cyl)
    node = GeomNode('geomnode')
    node.addGeom(geom)
    return node
Beispiel #24
0
 def create_instance(self):
     self.vertexData = GeomVertexData('vertexData', GeomVertexFormat.getV3(), Geom.UHStatic)
     self.vertexWriter = GeomVertexWriter(self.vertexData, 'vertex')
     delta = self.body.parent.get_local_position()
     if self.orbit.is_periodic():
         epoch = self.context.time.time_full - self.orbit.period / 2
         step = self.orbit.period / (self.nbOfPoints - 1)
     else:
         #TODO: Properly calculate orbit start and end time
         epoch = self.orbit.get_time_of_perihelion() - self.orbit.period * 5.0
         step = self.orbit.period * 10.0 / (self.nbOfPoints - 1)
     for i in range(self.nbOfPoints):
         time = epoch + step * i
         pos = self.orbit.get_position_at(time) - delta
         self.vertexWriter.addData3f(*pos)
     self.lines = GeomLines(Geom.UHStatic)
     for i in range(self.nbOfPoints-1):
         self.lines.addVertex(i)
         self.lines.addVertex(i+1)
     if self.orbit.is_periodic() and self.orbit.is_closed():
         self.lines.addVertex(self.nbOfPoints-1)
         self.lines.addVertex(0)
     self.geom = Geom(self.vertexData)
     self.geom.addPrimitive(self.lines)
     self.node = GeomNode(self.body.get_ascii_name() + '-orbit')
     self.node.addGeom(self.geom)
     self.instance = NodePath(self.node)
     self.instance.setRenderModeThickness(settings.orbit_thickness)
     self.instance.setCollideMask(GeomNode.getDefaultCollideMask())
     self.instance.node().setPythonTag('owner', self)
     self.instance.reparentTo(self.context.annotation)
     if self.color is None:
         self.color = self.parent.get_orbit_color()
     self.instance.setColor(srgb_to_linear(self.color * self.fade))
     self.instance_ready = True
     if self.shader is None:
         self.create_shader()
     self.shader.apply(self, self.appearance)
     self.shader.update(self, self.appearance)
Beispiel #25
0
def QuadPatch(x0,
              y0,
              x1,
              y1,
              x_inverted=False,
              y_inverted=False,
              xy_swap=False,
              offset=None):

    (x0, y0, x1, y1, dx, dy) = convert_xy(x0, y0, x1, y1, x_inverted,
                                          y_inverted, xy_swap)

    if offset is None:
        offset = 1.0

    (path, node) = empty_node('patch')
    form = GeomVertexFormat.getV3()
    vdata = GeomVertexData("vertices", form, Geom.UHStatic)

    vertexWriter = GeomVertexWriter(vdata, b"vertex")
    x0 = 2.0 * x0 - 1.0
    x1 = 2.0 * x1 - 1.0
    y0 = 2.0 * y0 - 1.0
    y1 = 2.0 * y1 - 1.0
    vertexWriter.addData3f(x0, y0, offset)
    vertexWriter.addData3f(x1, y0, offset)
    vertexWriter.addData3f(x1, y1, offset)
    vertexWriter.addData3f(x0, y1, offset)
    patches = GeomPatches(4, Geom.UHStatic)

    patches.addConsecutiveVertices(0, 4)  #South, west, north, east
    patches.closePrimitive()

    gm = Geom(vdata)
    gm.addPrimitive(patches)

    node.addGeom(gm)
    return path
    def __init__(self, vertexName='ConstrainedDelaunayTriangles', vertexFormat=GeomVertexFormat.getV3(),
                  usage = Geom.UHDynamic, onVertexCreationCallback = None, universalZ = 0.0):
        self._vertexData = GeomVertexData(vertexName, vertexFormat, Geom.UHDynamic)
        self._geomTriangles = GeomTriangles(usage)
        self._geomTrianglesHoles = GeomTriangles(usage)
        self._vertexRewriter = GeomVertexRewriter(self._vertexData, 'vertex')  # user cannot have control of a writer

        if onVertexCreationCallback is None:
            onVertexCreationCallback = lambda x, y, z: None  # something to call without checking existence later
        self._vertexCallback = onVertexCreationCallback

        self._universalZ = universalZ
        self.__holes = [[]]
        self.__polygon = []
        inf = float('inf')
        negInf = float('-inf')
        self.bounds = {
            'minX': inf,
            'maxX': negInf,
            'minY': inf,
            'maxY': negInf,
        }
        self.lastStaticVertexIndex = -1
Beispiel #27
0
	def line (self, start, end):
		# since we're doing line segments, just vertices in our geom
		format = GeomVertexFormat.getV3()
	   
		# build our data structure and get a handle to the vertex column
		vdata = GeomVertexData ('', format, Geom.UHStatic)
		vertices = GeomVertexWriter (vdata, 'vertex')
		   
		# build a linestrip vertex buffer
		lines = GeomLinestrips (Geom.UHStatic)
	   
		vertices.addData3f (start[0], start[1], start[2])
		vertices.addData3f (end[0], end[1], end[2])
	   
		lines.addVertices (0, 1)
		
		lines.closePrimitive()
	   
		geom = Geom (vdata)
		geom.addPrimitive (lines)
		# Add our primitive to the geomnode
		#self.gnode.addGeom (geom)
		return geom
Beispiel #28
0
    def generate(self):
        format = GeomVertexFormat.getV3()
        data = GeomVertexData("Data", format, Geom.UHStatic)
        vertices = GeomVertexWriter(data, "vertex")

        size = self.size
        vertices.addData3f(-size, -size, -size)
        vertices.addData3f(+size, -size, -size)
        vertices.addData3f(-size, +size, -size)
        vertices.addData3f(+size, +size, -size)
        vertices.addData3f(-size, -size, +size)
        vertices.addData3f(+size, -size, +size)
        vertices.addData3f(-size, +size, +size)
        vertices.addData3f(+size, +size, +size)

        triangles = GeomTriangles(Geom.UHStatic)

        def addQuad(v0, v1, v2, v3):
            triangles.addVertices(v0, v1, v2)
            triangles.addVertices(v0, v2, v3)
            triangles.closePrimitive()

        addQuad(4, 5, 7, 6)  # Z+
        addQuad(0, 2, 3, 1)  # Z-
        addQuad(3, 7, 5, 1)  # X+
        addQuad(4, 6, 2, 0)  # X-
        addQuad(2, 6, 7, 3)  # Y+
        addQuad(0, 1, 5, 4)  # Y+

        geom = Geom(data)
        geom.addPrimitive(triangles)

        node = GeomNode("CubeMaker")
        node.addGeom(geom)
        cube = NodePath(node)
        cube.setColor(0.0, 1.0, 1.0)
        return cube
 def line(self):
     # Create and populate the Moon orbit model using Vertices and Lines
     self.planetOrbitVertexData = GeomVertexData(self.description+'OrbitVertexData', GeomVertexFormat.getV3(), Geom.UHDynamic)
     self.planetOrbitVertexWriter = GeomVertexWriter(self.planetOrbitVertexData, 'vertex')
     self.planetOrbitNumberPoints = 360
     for i in range(self.planetOrbitNumberPoints):
         angleDegrees = i * 360 / self.planetOrbitNumberPoints
         angleRadians = angleDegrees * (pi / 180.0)
         x = -self.distance * sin(angleRadians)
         y =  self.distance * cos(angleRadians)
         self.planetOrbitVertexWriter.addData3f(x, y, 0.0)
     self.planetOrbitLines = GeomLines(Geom.UHStatic)
     for i in range(self.planetOrbitNumberPoints-1):
         self.planetOrbitLines.addVertex(i)
         self.planetOrbitLines.addVertex(i+1)
         self.planetOrbitLines.closePrimitive()
         self.planetOrbitLines.addVertex(self.planetOrbitNumberPoints-1)
         self.planetOrbitLines.addVertex(0)
     self.planetOrbitLines.closePrimitive()
     self.planetOrbitGeom = Geom(self.planetOrbitVertexData)
     self.planetOrbitGeom.addPrimitive(self.planetOrbitLines)
     self.planetOrbitNode = GeomNode(self.description+'OrbitNode')
     self.planetOrbitNode.addGeom(self.planetOrbitGeom)
     self.planetOrbitNnodePath = render.attachNewNode(self.planetOrbitNode)
     self.planetOrbitNnodePath.reparentTo(self.worldOrigin)
     return self.planetOrbitVertexWriter
Beispiel #30
0
    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)
Beispiel #31
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(
Beispiel #32
0
def draw_shape(angles, width, radius):
    res = 10
    if radius == 0:
        point = GeomNode('gnode')
        vdata = GeomVertexData('occ', GeomVertexFormat.getV3(), Geom.UHStatic)
        vdata.setNumRows(1)
        vertex = GeomVertexWriter(vdata, 'vertex')
        vertex.addData3f(0, 0, 0)

        geom = Geom(vdata)
        g = GeomPoints(Geom.UHStatic)
        g.addVertex(0)
        geom.addPrimitive(g)
        point.addGeom(geom)
        return point, point
    #first, sort angles in ascending order
    #if negative is given, translate to range of 2pi
    for i in range(len(angles)):
        if angles[i] < 0: angles[i] = 360 + angles[i]
    angles.sort()
    angles = [math.radians(a) for a in angles]
    angles.append(angles[0])  #read first angle to account for wrapping around

    #function = 'w/sin(theta)'

    vdata = GeomVertexData('occ', GeomVertexFormat.getV3(), Geom.UHStatic)
    vdata.setNumRows(1)
    vertex = GeomVertexWriter(vdata, 'vertex')

    numverts = [3] * (len(angles) - 1
                      )  #center, and two points on function lines

    for i in range(len(angles) - 1):
        #find center point
        #L = [None,None]
        #sign = [-1,1]
        #for p in range(2):
        #    theta1 = angles[i+p] - sign[p]*math.pi/2
        #    theta2 = angles[i+p] + sign[p]*math.pi/4
        #    x1 = width*math.cos(theta1)
        #    y1 = width*math.sin(theta1)
        #    r = math.sqrt(2*width**2)
        #    x2 = r*math.cos(theta2)
        #    y2 = r*math.sin(theta2)
        #    L[p] = line([x1,y1], [x2,y2])
        #R = intersection(L[0],L[1])

        #if R is False:
        #    R = [x1,y1] #if parallel, shift both lines down by y_width
        #vertex.addData3f(R[0],R[1],1)
        difang = (angles[i + 1] - angles[i]) / 2
        l = width / math.sin(difang)
        avgang = (angles[i] + angles[i + 1]) / 2
        x0 = l * math.cos(avgang)
        y0 = l * math.sin(avgang)
        vertex.addData3f(x0, y0, 1)

        newang1 = angles[i] + (math.pi / 2 - math.acos(width / radius))
        x = radius * math.cos(newang1)
        y = radius * math.sin(newang1)
        vertex.addData3f(x, y, 1)
        newang2 = angles[i + 1] - (math.pi / 2 - math.acos(width / radius))
        for angle in arc(newang1, newang2, res):
            vertex.addData3f(radius * math.cos(math.radians(angle)),
                             radius * math.sin(math.radians(angle)), 1)
            numverts[i] = numverts[i] + 1
        x = radius * math.cos(newang2)
        y = radius * math.sin(newang2)
        vertex.addData3f(x, y, 1)

    #copy all data to the bottom, moving it down to z = -1
    vertread = GeomVertexReader(vdata, 'vertex')
    while not vertread.isAtEnd():
        v = vertread.getData3f()
        vertex.addData3f(v[0], v[1], -1)

    #draw
    geom = Geom(vdata)
    #draw top
    for i in range(len(angles) - 1):
        for j in range(numverts[i] - 2):
            ind = sum(numverts[0:i]) + j
            g = GeomTriangles(Geom.UHStatic)
            g.add_vertices(ind - j, ind + 1, ind + 2)
            geom.addPrimitive(g)

    #draw bottom
    for i in range(len(angles) - 1):
        for j in range(numverts[i] - 2):
            ind = sum(numverts) + sum(numverts[0:i]) + j
            g = GeomTriangles(Geom.UHStatic)
            g.add_vertices(ind - j, ind + 2, ind + 1)
            geom.addPrimitive(g)

    #draw edges
    for i in range(len(angles) - 1):
        for j in range(numverts[i] - 1):
            ind = sum(numverts[0:i]) + j
            g = GeomTriangles(Geom.UHStatic)
            g.add_vertices(ind, ind + sum(numverts), ind + 1)
            g.add_vertices(ind + sum(numverts), ind + 1 + sum(numverts),
                           ind + 1)
            geom.addPrimitive(g)
        g = GeomTriangles(Geom.UHStatic)
        ind = sum(numverts[0:i])
        indx = sum(numverts[0:i + 1])
        g.add_vertices(indx - 1, indx + sum(numverts) - 1, ind)
        g.add_vertices(indx + sum(numverts) - 1, sum(numverts) + ind, ind)
        geom.addPrimitive(g)

    #outline object
    lines = Geom(vdata)
    l = GeomLines(Geom.UHStatic)
    for i in range(len(angles) - 1):
        for j in range(numverts[i] - 1):
            ind = sum(numverts[0:i]) + j
            l.add_vertices(ind, ind + 1)
            l.add_vertices(sum(numverts) + ind, sum(numverts) + ind + 1)
        ind = sum(numverts[0:i])
        indx = sum(numverts[0:i + 1])
        l.add_vertices(ind, indx - 1)
        l.add_vertices(sum(numverts) + ind, sum(numverts) + indx - 1)
        l.add_vertices(ind + 1, sum(numverts) + ind + 1)
        l.add_vertices(indx - 1, sum(numverts) + indx - 1)
        lines.addPrimitive(l)

    node = GeomNode('gnode')
    node.addGeom(geom)
    nodeL = GeomNode('gnode')
    nodeL.addGeom(lines)
    return node, nodeL
Beispiel #33
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)
Beispiel #34
0
class Mesh(NodePath):

    _formats = {
        (0, 0, 0): GeomVertexFormat.getV3(),
        (1, 0, 0): GeomVertexFormat.getV3c4(),
        (0, 1, 0): GeomVertexFormat.getV3t2(),
        (0, 0, 1): GeomVertexFormat.getV3n3(),
        (1, 0, 1): GeomVertexFormat.getV3n3c4(),
        (1, 1, 0): GeomVertexFormat.getV3c4t2(),
        (0, 1, 1): GeomVertexFormat.getV3n3t2(),
        (1, 1, 1): GeomVertexFormat.getV3n3c4t2(),
    }

    _modes = {
        'triangle': GeomTriangles,
        'tristrip': GeomTristrips,
        'ngon': GeomTrifans,
        'line': GeomLinestrips,
        'point': GeomPoints,
    }

    def __init__(self,
                 vertices=None,
                 triangles=None,
                 colors=None,
                 uvs=None,
                 normals=None,
                 static=True,
                 mode='triangle',
                 thickness=1):
        super().__init__('mesh')

        self.vertices = vertices
        self.triangles = triangles
        self.colors = colors
        self.uvs = uvs
        self.normals = normals
        self.static = static
        self.mode = mode
        self.thickness = thickness

        for var in (('vertices', vertices), ('triangles', triangles),
                    ('colors', colors), ('uvs', uvs), ('normals', normals)):
            name, value = var
            if value is None:
                setattr(self, name, list())

        if self.vertices:
            self.generate()

    def generate(
            self
    ):  # call this after setting some of the variables to update it
        if hasattr(self, 'geomNode'):
            self.geomNode.removeAllGeoms()

        static_mode = Geom.UHStatic if self.static else Geom.UHDynamic
        vertex_format = Mesh._formats[(bool(self.colors), bool(self.uvs),
                                       bool(self.normals))]
        vdata = GeomVertexData('name', vertex_format, static_mode)
        vdata.setNumRows(len(self.vertices))  # for speed
        if not hasattr(self, 'geomNode'):
            self.geomNode = GeomNode('mesh')
            self.attachNewNode(self.geomNode)

        vertexwriter = GeomVertexWriter(vdata, 'vertex')
        for v in self.vertices:
            vertexwriter.addData3f(*v)

        if self.colors:
            colorwriter = GeomVertexWriter(vdata, 'color')
            for c in self.colors:
                colorwriter.addData4f(c)

        if self.uvs:
            uvwriter = GeomVertexWriter(vdata, 'texcoord')
            for uv in self.uvs:
                uvwriter.addData2f(uv[0], uv[1])

        if self.normals != None:
            normalwriter = GeomVertexWriter(vdata, 'normal')
            for norm in self.normals:
                normalwriter.addData3f(*norm)

        if self.mode != 'line' or not self._triangles:
            self.indices = list()

            if self._triangles:
                if isinstance(self._triangles[0], int):
                    for t in self._triangles:
                        self.indices.append(t)

                elif len(
                        self._triangles[0]
                ) >= 3:  # if tris are tuples like this: ((0,1,2), (1,2,3))
                    for t in self._triangles:
                        if len(t) == 3:
                            self.indices.extend(t)

                        elif len(t) == 4:  # turn quad into tris
                            self.indices.extend(
                                [t[i] for i in (0, 1, 2, 2, 3, 0)])

            else:
                self.indices = [i for i in range(len(self.vertices))]

            prim = Mesh._modes[self.mode](static_mode)

            self.generated_vertices = [self.vertices[i] for i in self.indices]
            for v in self.indices:
                prim.addVertex(v)

            prim.close_primitive()
            geom = Geom(vdata)
            geom.addPrimitive(prim)
            self.geomNode.addGeom(geom)

        else:  # line with segments defined in triangles
            for line in self._triangles:
                prim = Mesh._modes[self.mode](static_mode)
                for e in line:
                    prim.addVertex(e)
                prim.close_primitive()
                geom = Geom(vdata)
                geom.addPrimitive(prim)
                self.geomNode.addGeom(geom)

        if self.mode == 'point':
            self.setTexGen(TextureStage.getDefault(),
                           TexGenAttrib.MPointSprite)
            # self.set_render_mode_perspective(True)

        # print('finished')

    @property
    def recipe(self):
        if hasattr(self, '_recipe'):
            return self._recipe

        return dedent(f'''
            Mesh(
                vertices={[tuple(e) for e in self.vertices]},
                triangles={self._triangles},
                colors={[tuple(e) for e in self.colors]},
                uvs={self.uvs},
                normals={[tuple(e) for e in self.normals]},
                static={self.static},
                mode="{self.mode}",
                thickness={self.thickness}
            )
        ''')

    @recipe.setter
    def recipe(self, value):
        self._recipe = value

    def __add__(self, other):
        self.vertices += other.vertices
        self.triangles += other.triangles
        if other.colors:
            self.colors += other.colors
        else:
            self.colors += (color.white, ) * len(other.vertices)

        self.normals += other.normals
        self.uvs += other.uvs

    def __deepcopy__(self, memo):
        m = Mesh(self.vertices, self.triangles, self.colors, self.uvs,
                 self.normals, self.static, self.mode, self.thickness)
        m.name = self.name
        return m

    @property
    def thickness(self):
        return self.getRenderModeThickness()

    @thickness.setter
    def thickness(self, value):
        self.setRenderModeThickness(value)

    @property
    def triangles(self):
        if self._triangles == None:
            self._triangles = [(i, i + 1, i + 2)
                               for i in range(0, len(self.vertices), 3)]

        return self._triangles

    @triangles.setter
    def triangles(self, value):
        self._triangles = value

    def generate_normals(self, smooth=True):
        self.normals = list(
            generate_normals(self.vertices, self.triangles, smooth))
        self.generate()
        return self.normals

    def colorize(self,
                 left=color.white,
                 right=color.blue,
                 down=color.red,
                 up=color.green,
                 back=color.white,
                 forward=color.white,
                 smooth=True,
                 world_space=True):
        colorize(self, left, right, down, up, back, forward, smooth,
                 world_space)

    def project_uvs(self, aspect_ratio=1, direction='forward'):
        project_uvs(self, aspect_ratio)

    def clear(self, regenerate=True):
        self.vertices, self.triangles, self.colors, self.uvs, self.normals = list(
        ), list(), list(), list(), list()
        if regenerate:
            self.generate()

    def save(self, name='', path=application.compressed_models_folder):
        if not application.compressed_models_folder.exists():
            application.compressed_models_folder.mkdir()

        if not name and hasattr(self, 'path'):
            name = self.path.stem
            if not '.' in name:
                name += '.ursinamesh'

        if name.endswith('ursinamesh'):
            with open(path / name, 'w') as f:
                # recipe = self.recipe.replace('LVector3f', '')
                f.write(self.recipe)
            print('saved .ursinamesh to:', path / name)

        elif name.endswith('.obj'):
            from ursina.mesh_importer import ursina_mesh_to_obj
            ursina_mesh_to_obj(self, name, path)

        elif name.endswith('.bam'):
            success = self.writeBamFile(path / name)
            print('saved .bam to:', path / name)
Beispiel #35
0
    def createModelClone(self, modelFilename):

        newVisualCar = loader.loadModel(modelFilename)
        geomNodeCollection = newVisualCar.findAllMatches('**/+GeomNode')

        simpleTris = []

        self.unmodifiedVertexData = []

        for nodePath in geomNodeCollection:
            geomNode = nodePath.node()
            for i in range(geomNode.getNumGeoms()):

                geom = geomNode.getGeom(i)

                vdata = geom.getVertexData()
                vertex = GeomVertexReader(vdata, 'vertex')
                while not vertex.isAtEnd():
                    v = vertex.getData3f()
                    vertexModelX, vertexModelY, vertexModelZ = v
                    self.unmodifiedVertexData.append(
                        [vertexModelX, vertexModelY, vertexModelZ])

                for primitiveIndex in range(geom.getNumPrimitives()):
                    prim = geom.getPrimitive(primitiveIndex)
                    prim = prim.decompose()
                    for p in range(prim.getNumPrimitives()):
                        s = prim.getPrimitiveStart(p)
                        e = prim.getPrimitiveEnd(p)
                        singleTriData = []
                        for i in range(s, e):
                            vertex.setRow(prim.getVertex(s))
                            vi = prim.getVertex(i)
                            singleTriData.append(vi)
                        simpleTris.append(singleTriData)

        simpleVertices = self.unmodifiedVertexData

        format = GeomVertexFormat.getV3()

        vdata = GeomVertexData('shadow', format, Geom.UHDynamic)
        self.pandaVertexData = vdata
        vertex = GeomVertexWriter(vdata, 'vertex')
        for vertexIndex in range(len(simpleVertices)):
            simpleVertex = simpleVertices[vertexIndex]
            vertex.addData3f(0, 0, 0)

        tris = GeomTriangles(Geom.UHStatic)
        for index in range(len(simpleTris)):
            simpleTri = simpleTris[index]
            tris.addVertex(simpleTri[0])
            tris.addVertex(simpleTri[1])
            tris.addVertex(simpleTri[2])
            tris.closePrimitive()

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

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

        self.snode = snode
Beispiel #36
0
class Mesh(NodePath):

    _formats = {
        (0, 0, 0): GeomVertexFormat.getV3(),
        (1, 0, 0): GeomVertexFormat.getV3c4(),
        (0, 1, 0): GeomVertexFormat.getV3t2(),
        (0, 0, 1): GeomVertexFormat.getV3n3(),
        (1, 0, 1): GeomVertexFormat.getV3n3c4(),
        (1, 1, 0): GeomVertexFormat.getV3c4t2(),
        (0, 1, 1): GeomVertexFormat.getV3n3t2(),
        (1, 1, 1): GeomVertexFormat.getV3n3c4t2(),
    }

    _modes = {
        'triangle': GeomTriangles,
        'tristrip': GeomTristrips,
        'ngon': GeomTrifans,
        'line': GeomLinestrips,
        'point': GeomPoints,
    }

    def __init__(self,
                 vertices=None,
                 triangles=None,
                 colors=None,
                 uvs=None,
                 normals=None,
                 static=True,
                 mode='triangle',
                 thickness=1):
        super().__init__('mesh')

        self.vertices = vertices
        self.triangles = triangles
        self.colors = colors
        self.uvs = uvs
        self.normals = normals
        self.static = static
        self.mode = mode
        self.thickness = thickness

        for var in (('vertices', vertices), ('triangles', triangles),
                    ('colors', colors), ('uvs', uvs), ('normals', normals)):
            name, value = var
            if value is None:
                setattr(self, name, list())

        if self.vertices:
            self.vertices = [tuple(v) for v in self.vertices]
            self.generate()

    def generate(
            self
    ):  # call this after setting some of the variables to update it
        if hasattr(self, 'geomNode'):
            self.geomNode.removeAllGeoms()

        static_mode = Geom.UHStatic if self.static else Geom.UHDynamic
        vertex_format = Mesh._formats[(bool(self.colors), bool(self.uvs),
                                       bool(self.normals))]
        vdata = GeomVertexData('name', vertex_format, static_mode)
        vdata.setNumRows(len(self.vertices))  # for speed

        vertexwriter = GeomVertexWriter(vdata, 'vertex')
        for v in self.vertices:
            vertexwriter.addData3f((v[0], v[2], v[1]))  # swap y and z

        if self.colors:
            colorwriter = GeomVertexWriter(vdata, 'color')
            for c in self.colors:
                colorwriter.addData4f(c)

        if self.uvs:
            uvwriter = GeomVertexWriter(vdata, 'texcoord')
            for uv in self.uvs:
                uvwriter.addData2f(uv[0], uv[1])

        if self.normals != None:
            normalwriter = GeomVertexWriter(vdata, 'normal')
            for norm in self.normals:
                normalwriter.addData3f((norm[0], norm[2], norm[1]))

        if self.mode != 'line' or not self._triangles:
            prim = Mesh._modes[self.mode](static_mode)

            if self._triangles:
                if isinstance(self._triangles[0], int):
                    for t in self._triangles:
                        prim.addVertex(t)

                elif len(
                        self._triangles[0]
                ) >= 3:  # if tris are tuples like this: ((0,1,2), (1,2,3))
                    for t in self._triangles:
                        if len(t) == 3:
                            for e in t:
                                prim.addVertex(e)
                        elif len(t) == 4:  # turn quad into tris
                            prim.addVertex(t[0])
                            prim.addVertex(t[1])
                            prim.addVertex(t[2])
                            prim.addVertex(t[2])
                            prim.addVertex(t[3])
                            prim.addVertex(t[0])

            else:
                prim.addConsecutiveVertices(0, len(self.vertices))

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

        else:  # line with segments defined in triangles
            for line in self._triangles:
                prim = Mesh._modes[self.mode](static_mode)
                for e in line:
                    prim.addVertex(e)
                prim.close_primitive()
                geom = Geom(vdata)
                geom.addPrimitive(prim)

        self.geomNode = GeomNode('mesh')
        self.geomNode.addGeom(geom)
        self.attachNewNode(self.geomNode)

        # if self.normals:
        #     self.normals = [tuple(e) for e in self.normals]
        self.recipe = dedent(f'''
            Mesh(
                vertices={[tuple(e) for e in self.vertices]},
                triangles={self._triangles},
                colors={[tuple(e) for e in self.colors]},
                uvs={self.uvs},
                normals={[tuple(e) for e in self.normals]},
                static={self.static},
                mode="{self.mode}",
                thickness={self.thickness}
            )
        ''')
        # print('finished')

    def __add__(self, other):
        self.vertices += other.vertices
        self.triangles += other.triangles
        if other.colors:
            self.colors += other.colors
        else:
            self.colors += (color.white, ) * len(other.vertices)

        self.normals += other.normals
        self.uvs += other.uvs

    @property
    def thickness(self):
        return self.getRenderModeThickness()

    @thickness.setter
    def thickness(self, value):
        self.setRenderModeThickness(value)

    @property
    def triangles(self):
        if self._triangles == None:
            self._triangles = [(i, i + 1, i + 2)
                               for i in range(0, len(self.vertices), 3)]

        return self._triangles

    @triangles.setter
    def triangles(self, value):
        self._triangles = value

    def generate_normals(self, smooth=True):
        self.normals = list(
            generate_normals(self.vertices, self.triangles, smooth))
        self.generate()
        return self.normals

    def colorize(self,
                 left=color.white,
                 right=color.blue,
                 down=color.red,
                 up=color.green,
                 back=color.white,
                 forward=color.white,
                 smooth=True,
                 world_space=True):
        colorize(self, left, right, down, up, back, forward, smooth,
                 world_space)

    def project_uvs(self, aspect_ratio=1, direction='forward'):
        project_uvs(self, aspect_ratio)

    def clear(self, regenerate=True):
        self.vertices, self.triangles, self.colors, self.uvs, self.normals = list(
        ), list(), list(), list(), list()
        if regenerate:
            self.generate()

    def save(self, name, path=application.asset_folder, filetype='ursinamesh'):
        if filetype == 'ursinamesh':
            if not '.' in name:
                name += '.ursinamesh'

            with open(path / name, 'w') as f:
                recipe = self.recipe.replace('LVector3f', '')
                f.write(recipe)

        elif filetype == 'obj':
            from ursina.mesh_importer import ursina_mesh_to_obj
            ursina_mesh_to_obj(self, name, path)
	def createModelClone(self,modelFilename):

		newVisualCar = loader.loadModel(modelFilename)
		geomNodeCollection = newVisualCar.findAllMatches('**/+GeomNode')

		simpleTris=[]

		self.unmodifiedVertexData=[]

		for nodePath in geomNodeCollection:
			geomNode = nodePath.node()
			for i in range(geomNode.getNumGeoms()):

				geom = geomNode.getGeom(i)

				vdata = geom.getVertexData()
				vertex = GeomVertexReader(vdata, 'vertex')
				while not vertex.isAtEnd():
					v=vertex.getData3f()
					vertexModelX,vertexModelY,vertexModelZ=v
					self.unmodifiedVertexData.append([vertexModelX,vertexModelY,vertexModelZ])

				for primitiveIndex in range(geom.getNumPrimitives()):
					prim=geom.getPrimitive(primitiveIndex)
					prim=prim.decompose()
					for p in range(prim.getNumPrimitives()):
						s = prim.getPrimitiveStart(p)
						e = prim.getPrimitiveEnd(p)
						singleTriData=[]
						for i in range(s, e):
							vertex.setRow(prim.getVertex(s)) 
							vi = prim.getVertex(i)
							singleTriData.append(vi)
						simpleTris.append(singleTriData)

		simpleVertices=self.unmodifiedVertexData

		format=GeomVertexFormat.getV3()

		vdata=GeomVertexData('shadow', format, Geom.UHDynamic)
		self.pandaVertexData=vdata
		vertex=GeomVertexWriter(vdata, 'vertex')
		for vertexIndex in range(len(simpleVertices)):
			simpleVertex=simpleVertices[vertexIndex]
			vertex.addData3f(0,0,0)

		tris=GeomTriangles(Geom.UHStatic)
		for index in range(len(simpleTris)):
			simpleTri=simpleTris[index]
			tris.addVertex(simpleTri[0])
			tris.addVertex(simpleTri[1])
			tris.addVertex(simpleTri[2])
			tris.closePrimitive()

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

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

		self.snode=snode