Example #1
0
File: Grid.py Project: crempp/psg
	def drawSquare(self, x1,y1,z1, x2,y2,z2):
		format=GeomVertexFormat.getV3n3cpt2()
		vdata=GeomVertexData('square', format, Geom.UHStatic)
		
		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(self.myNormalize(Vec3(2*x1-1, 2*y1-1, 2*z1-1)))
		normal.addData3f(self.myNormalize(Vec3(2*x2-1, 2*y1-1, 2*z1-1)))
		normal.addData3f(self.myNormalize(Vec3(2*x2-1, 2*y2-1, 2*z2-1)))
		normal.addData3f(self.myNormalize(Vec3(2*x1-1, 2*y2-1, 2*z2-1)))
		
		#adding different colors to the vertex for visibility
		color.addData4f(0.0,0.5,0.0,0.5)
		color.addData4f(0.0,0.5,0.0,0.5)
		color.addData4f(0.0,0.5,0.0,0.5)
		color.addData4f(0.0,0.5,0.0,0.5)
		
		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.UHStatic)
		tri2=GeomTriangles(Geom.UHStatic)
		
		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)
		#square.setIntoCollideMask(BitMask32.bit(1))
		
		squareNP = NodePath(GeomNode('square gnode')) 
		squareNP.node().addGeom(square)
		squareNP.setTransparency(1) 
		squareNP.setAlphaScale(.5) 
		squareNP.setTwoSided(True)
		squareNP.setCollideMask(BitMask32.bit(1))
		return squareNP
def makeCircle(vdata, numVertices=40,offset=Vec3(0,0,0), direction=1):
	circleGeom=Geom(vdata)

	vertWriter=GeomVertexWriter(vdata, "vertex")
	normalWriter=GeomVertexWriter(vdata, "normal")
	colorWriter=GeomVertexWriter(vdata, "color")
	uvWriter=GeomVertexWriter(vdata, "texcoord")
	drawWriter=GeomVertexWriter(vdata, "drawFlag")

	#make sure we start at the end of the GeomVertexData so we dont overwrite anything
	#that might be there already
	startRow=vdata.getNumRows()

	vertWriter.setRow(startRow)
	colorWriter.setRow(startRow)
	uvWriter.setRow(startRow)
	normalWriter.setRow(startRow)
	drawWriter.setRow(startRow)

	angle=2*math.pi/numVertices
	currAngle=angle

	for i in range(numVertices):
		position=Vec3(math.cos(currAngle)+offset.getX(), math.sin(currAngle)+offset.getY(),offset.getZ())
		vertWriter.addData3f(position)
		uvWriter.addData2f(position.getX()/2.0+0.5,position.getY()/2.0+0.5)
		colorWriter.addData4f(1.0, 1.0, 1.0, 1.0)
		position.setZ(position.getZ()*direction)
		position.normalize()
		normalWriter.addData3f(position)
		
		#at default Opengl only draws "front faces" (all shapes whose vertices are arranged CCW). We
		#need direction so we can specify which side we want to be the front face
		currAngle+=angle*direction

	circle=GeomTrifans(Geom.UHStatic)
	circle.addConsecutiveVertices(startRow, numVertices)
	circle.closePrimitive()

	circleGeom.addPrimitive(circle)
	
	return circleGeom
Example #3
0
def create_table_geom():
    format = GeomVertexFormat.getV3n3c4t2()
    # GeomVertexData. 
    vdata = GeomVertexData('table_vertex', format, Geom.UHStatic)
    
    vertex = GeomVertexWriter(vdata, 'vertex')
    normal = GeomVertexWriter(vdata, 'normal')
    color = GeomVertexWriter(vdata, 'color')
    texcoord = GeomVertexWriter(vdata, 'texcoord')

    vertex.addData3f(xmax, ymin, 0)
    normal.addData3f(0, 0, 1)
    color.addData4f(0, 0, 1, 1)
    texcoord.addData2f(1, 0)
    
    vertex.addData3f(xmax, ymax, 0)
    normal.addData3f(0, 0, 1)
    color.addData4f(0, 0, 1, 1)
    texcoord.addData2f(1, 1)
    
    vertex.addData3f(xmin, ymax, 0)
    normal.addData3f(0, 0, 1)
    color.addData4f(0, 0, 1, 1)
    texcoord.addData2f(0, 1)
    
    vertex.addData3f(xmin, ymin, 0)
    normal.addData3f(0, 0, 1)
    color.addData4f(0, 0, 1, 1)
    texcoord.addData2f(0, 0)
    
    prim = GeomTriangles(Geom.UHStatic)
    prim.addVertex(0)
    prim.addVertex(1)
    prim.addVertex(2)
    prim.closePrimitive()
    
    prim.addVertex(0)
    prim.addVertex(2)
    prim.addVertex(3)
    prim.closePrimitive()

    geom = Geom(vdata)
    geom.addPrimitive(prim)
    return geom
Example #4
0
	def init_node_path(self):
		if self.node_path:
			self.node_path.remove()
		polygon = self.source
		vdata = GeomVertexData('name_me', self.format, Geom.UHStatic)
		vertex = GeomVertexWriter(vdata, 'vertex')
		normal = GeomVertexWriter(vdata, 'normal')
		color = GeomVertexWriter(vdata, 'color')
		texcoord = GeomVertexWriter(vdata, 'texcoord')
		primitive = GeomTristrips(Geom.UHStatic)
		vertex.addData3f(*coords_to_panda(*polygon.A.point.coords))
		vertex.addData3f(*coords_to_panda(*polygon.B.point.coords))
		vertex.addData3f(*coords_to_panda(*polygon.C.point.coords))
		if hasattr(polygon, 'D'):
			vertex.addData3f(*coords_to_panda(*polygon.D.point.coords))
		else:
			vertex.addData3f(*coords_to_panda(*polygon.C.point.coords))
		if polygon.A.normal:
			normal.addData3f(*coords_to_panda(*polygon.A.normal.coords))
			normal.addData3f(*coords_to_panda(*polygon.B.normal.coords))
			normal.addData3f(*coords_to_panda(*polygon.C.normal.coords))
			if hasattr(polygon, 'D'):
				normal.addData3f(*coords_to_panda(*polygon.D.normal.coords))
		if polygon.A.normal:
			gray = 1.0
		else:
			gray = 0.0
		self.old_color = (gray, gray, gray, 1.0)
		color.addData4f(gray, gray, gray, 1.0)
		color.addData4f(gray, gray, gray, 1.0)
		color.addData4f(gray, gray, gray, 1.0)
		if hasattr(polygon, 'D'):
			color.addData4f(gray, gray, gray, 1.0)
		if polygon.A.texcoord:
			pal = ((polygon.texture_palette + 1) * 256)
			
			texcoord_A = uv_to_panda2(polygon, pal, *polygon.A.texcoord.coords)
			texcoord_B = uv_to_panda2(polygon, pal, *polygon.B.texcoord.coords)
			texcoord_C = uv_to_panda2(polygon, pal, *polygon.C.texcoord.coords)
			texcoord.addData2f(*texcoord_A)
			texcoord.addData2f(*texcoord_B)
			texcoord.addData2f(*texcoord_C)
			if hasattr(polygon, 'D'):
				texcoord_D = uv_to_panda2(polygon, pal, *polygon.D.texcoord.coords)
				texcoord.addData2f(*texcoord_D)
		primitive.addNextVertices(4)
		primitive.closePrimitive()
		geom = Geom(vdata)
		geom.addPrimitive(primitive)
		node = GeomNode('gnode')
		node.addGeom(geom)
		self.node_path = self.parent.node_path_mesh.attachNewNode(node)
Example #5
0
 def addGeometry(self, geomData):
   debugGui = dict()
   
   format = GeomVertexFormat.getV3n3t2()
   vdata = GeomVertexData('name', format, Geom.UHStatic)
   vertex = GeomVertexWriter(vdata, 'vertex')
   normal = GeomVertexWriter(vdata, 'normal')
   texcoord = GeomVertexWriter(vdata, 'texcoord')
   prim = GeomTriangles(Geom.UHStatic)
   
   postphonedTriangles = list()
   vtxTargetId0 = vtxTargetId1 = vtxTargetId2 = None
   vtxDataCounter = 0
   for vtxSourceId0, vtxSourceId1, vtxSourceId2 in geomData.triangles:
     vx0,vy0,vz0 = v0 = geomData.getVertex(vtxSourceId0)
     vx1,vy1,vz1 = v1 = geomData.getVertex(vtxSourceId1)
     vx2,vy2,vz2 = v2 = geomData.getVertex(vtxSourceId2)
     # prepare the vertices
     uvx0, uvy0 = uv0 = geomData.getUv(vtxSourceId0)
     uvx1, uvy1 = uv1 = geomData.getUv(vtxSourceId1)
     uvx2, uvy2 = uv2 = geomData.getUv(vtxSourceId2)
     #
     n0 = geomData.getNormal(vtxSourceId0)
     n1 = geomData.getNormal(vtxSourceId1)
     n2 = geomData.getNormal(vtxSourceId2)
     
     # make it wrap nicely
     if min(uvx0,uvx1,uvx2) < .25 and max(uvx0,uvx1,uvx2) > 0.75:
       if uvx0 < 0.25: uvx0 += 1.0
       if uvx1 < 0.25: uvx1 += 1.0
       if uvx2 < 0.25: uvx2 += 1.0
     
     vertex.addData3f(*v0)
     normal.addData3f(*n0)
     texcoord.addData2f(*uv0)
     vtxTargetId0 = vtxDataCounter
     vtxDataCounter += 1
   
     vertex.addData3f(*v1)
     normal.addData3f(*n1)
     texcoord.addData2f(*uv1)
     vtxTargetId1 = vtxDataCounter
     vtxDataCounter += 1
   
     vertex.addData3f(*v2)
     normal.addData3f(*n2)
     texcoord.addData2f(*uv2)
     vtxTargetId2 = vtxDataCounter
     vtxDataCounter += 1
     
     prim.addVertex(vtxTargetId0)
     prim.addVertex(vtxTargetId1)
     prim.addVertex(vtxTargetId2)
     prim.closePrimitive()
     
     if False:
       if vtxSourceId0 not in debugGui:
         i = InfoTextBillaboarded(render)
         i.setScale(0.05)
         i.billboardNodePath.setPos(Vec3(x0,y0,z0)*1.1)
         i.setText('%i: %.1f %.1f %.1f\n%.1f %.1f' % (vtxSourceId0, x0,y0,z0, nx0, ny0))
         debugGui[vtxSourceId0] = i
       if vtxSourceId1 not in debugGui:
         i = InfoTextBillaboarded(render)
         i.setScale(0.05)
         i.billboardNodePath.setPos(Vec3(x1,y1,z1)*1.1)
         i.setText('%i: %.1f %.1f %.1f\n%.1f %.1f' % (vtxSourceId1, x1,y1,z1, nx1, ny1))
         debugGui[vtxSourceId1] = i
       if vtxSourceId2 not in debugGui:
         i = InfoTextBillaboarded(render)
         i.setScale(0.05)
         i.billboardNodePath.setPos(Vec3(x2,y2,z2)*1.1)
         i.setText('%i: %.1f %.1f %.1f\n%.1f %.1f' % (vtxSourceId2, x2,y2,z2, nx2, ny2))
         debugGui[vtxSourceId2] = i
   
   geom = Geom(vdata)
   geom.addPrimitive(prim)
   
   node = GeomNode('gnode')
   node.addGeom(geom)
   
   nodePath = self.attachNewNode(node)
   return nodePath
Example #6
0
  def make_layer(self, i, a, b):
    # get data
    data = self.subdata[a][b]

    # set color + alpha of vertex texture
    def ap(n):
      alpha = 0
      if i == n:
        alpha = 1.0
      return alpha
    def tp(n):
      list = [0, 0, 0, 0]
      if i == n:
        list = [1, 1, 1, 0.75]
      return list

    # set vertex data
    vdata = GeomVertexData('plane', GeomVertexFormat.getV3n3c4t2(), Geom.UHStatic)
    vertex = GeomVertexWriter(vdata, 'vertex')
    normal = GeomVertexWriter(vdata, 'normal')
    color = GeomVertexWriter(vdata, 'color')
    uv = GeomVertexWriter(vdata, 'texcoord')

    # set vertices
    number = 0
    for x in range(0, len(data) - 1):
      for y in range(0, len(data[x]) - 1):
        # get vertex data
        v1 = Vec3(x, y, data[x][y]['h'])
        c1 = data[x][y]['c']
        t1 = data[x][y]['texnum']
        v2 = Vec3(x+1, y, data[x+1][y]['h'])
        c2 = data[x+1][y]['c']
        t2 = data[x+1][y]['texnum']
        v3 = Vec3(x+1, y+1, data[x+1][y+1]['h'])
        c3 = data[x+1][y+1]['c']
        t3 = data[x+1][y+1]['texnum']
        v4 = Vec3(x, y+1, data[x][y+1]['h'])
        c4 = data[x][y+1]['c']
        t4 = data[x][y+1]['texnum']
        n=(0, 0, 1) # normal

        # assign vertex colors + alpha
        a1, a2, a3, a4 = ap(t1), ap(t2), ap(t3), ap(t4)
        t1, t2, t3, t4 = tp(t1), tp(t2), tp(t3), tp(t4)

        if v1[2]==0:
          t1 = [data[x][y]['c'][0], data[x][y]['c'][1], data[x][y]['c'][2],
                a1]
        if v2[2]==0:
          t2 = [data[x+1][y]['c'][0], data[x+1][y]['c'][1],
                data[x+1][y]['c'][2], a2]
        if v3[2]==0:
          t3 = [data[x+1][y+1]['c'][0], data[x+1][y+1]['c'][1],
                data[x+1][y+1]['c'][2], a3]
        if v4[2]==0:
          t4 = [data[x][y+1]['c'][0], data[x][y+1]['c'][1],
                data[x][y+1]['c'][2], a4]

        if a1 == 0 and a2 == 0 and a3 == 0 and a4 == 0:
          continue

        # add vertices
        vertex.addData3f(v1)
        normal.addData3f(*n)
        color.addData4f(*t1)
        uv.addData2f(0,0)

        vertex.addData3f(v2)
        normal.addData3f(*n)
        color.addData4f(*t2)
        uv.addData2f(1,0)

        vertex.addData3f(v3)
        normal.addData3f(*n)
        color.addData4f(*t3)
        uv.addData2f(1,1)

        vertex.addData3f(v1)
        normal.addData3f(*n)
        color.addData4f(*t1)
        uv.addData2f(0,0)

        vertex.addData3f(v3)
        normal.addData3f(*n)
        color.addData4f(*t3)
        uv.addData2f(1,1)

        vertex.addData3f(v4)
        normal.addData3f(*n)
        color.addData4f(*t4)
        uv.addData2f(0,1)

        number = number + 2

    # add triangles
    prim = GeomTriangles(Geom.UHStatic)
    for n in range(number):
      prim.addVertices((n * 3) + 2, (n * 3) + 0, (n * 3) + 1)
    prim.closePrimitive()

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

    # make geom node
    node = GeomNode("layer" + str(i) + "_" + str(a) + "_" + str(b))
    node.addGeom(geom)

    # make mesh nodePath
    mesh = NodePath(node)

    # load and assign texture
    txfile = self.tiles[i]['tex']
    tx = base.loader.loadTexture(txfile)
    tx.setMinfilter(Texture.FTLinearMipmapLinear)
    mesh.setDepthTest(DepthTestAttrib.MLessEqual)
    mesh.setDepthWrite(False)
    mesh.setTransparency(True)
    mesh.setTexture(tx)

    # set render order
    mesh.setBin("", 1)

    # locate mesh
    mesh.setPos(self.divsep * (a * int(len(self.data[a]) / self.div)),
                self.divsep * (b * int(len(self.data[b]) / self.div)), 0.001)

    # reparent mesh
    mesh.reparentTo(self.root)

    # return mesh
    return mesh
Example #7
0
  def make_base(self, a, b):
    # get data
    data = self.subdata[a][b]
    # set vertex data
    vdata = GeomVertexData('plane', GeomVertexFormat.getV3n3c4t2(), Geom.UHStatic)
    vertex = GeomVertexWriter(vdata, 'vertex')
    normal = GeomVertexWriter(vdata, 'normal')
    color = GeomVertexWriter(vdata, 'color')
    uv = GeomVertexWriter(vdata, 'texcoord')

    # set vertices
    number = 0
    for x in range(0, len(data) - 1):
      for y in range(0, len(data[x]) - 1):
        # get vertex data
        v1 = Vec3(x, y, data[x][y]['h'])
        v2 = Vec3(x + 1, y, data[x+1][y]['h'])
        v3 = Vec3(x + 1, y + 1, data[x+1][y+1]['h'])
        v4 = Vec3(x, y + 1, data[x][y+1]['h'])
        n = (0, 0, 1) # normal

        # assign vertex colors + alpha
        option = 1 # black
        if option == 1:
          c = 0
          c1 = [c, c, c, 1]
          c2 = [c, c, c, 1]
          c3 = [c, c, c, 1]
          c4 = [c, c, c, 1]
        # option2: color vertices
        if option == 2:
          alpha = 1.0
          c1 = [data[x][y]['c'][0], data[x][y]['c'][1],
                data[x][y]['c'][2], alpha]
          c2 = [data[x+1][y]['c'][0], data[x+1][y]['c'][1],
                data[x+1][y]['c'][2], alpha]
          c3 = [data[x+1][y+1]['c'][0], data[x+1][y+1]['c'][1],
                data[x+1][y+1]['c'][2], alpha]
          c4 = [data[x][y+1]['c'][0], data[x][y+1]['c'][1],
                data[x][y+1]['c'][2], alpha]

        if option == 3:
          c1 = self.color_vertex(v1)
          c2 = self.color_vertex(v2)
          c3 = self.color_vertex(v3)
          c4 = self.color_vertex(v4)

        vertex.addData3f(v1)
        normal.addData3f(*n)
        color.addData4f(*c1)
        uv.addData2f(0,0)

        vertex.addData3f(v2)
        normal.addData3f(*n)
        color.addData4f(*c2)
        uv.addData2f(1,0)

        vertex.addData3f(v3)
        normal.addData3f(*n)
        color.addData4f(*c3)
        uv.addData2f(1,1)

        vertex.addData3f(v1)
        normal.addData3f(*n)
        color.addData4f(*c1)
        uv.addData2f(0,0)

        vertex.addData3f(v3)
        normal.addData3f(*n)
        color.addData4f(*c3)
        uv.addData2f(1,1)

        vertex.addData3f(v4)
        normal.addData3f(*n)
        color.addData4f(*c4)
        uv.addData2f(0,1)

#         # add vertex h
#         vertex.addData3f(v1)
#         # normal.addData3f(*n)
#         vertex.addData3f(v2)
#         # normal.addData3f(*n)
#         vertex.addData3f(v3)
#         # normal.addData3f(*n)
#         vertex.addData3f(v1)
#         # normal.addData3f(*n)
#         vertex.addData3f(v3)
#         # normal.addData3f(*n)
#         vertex.addData3f(v4)
#         # normal.addData3f(*n)
#         # add vertex color
#         color.addData4f(*c1)
#         color.addData4f(*c2)
#         color.addData4f(*c3)
#         color.addData4f(*c1)
#         color.addData4f(*c3)
#         color.addData4f(*c4)

        # iterate
        number = number + 2

    # add triangles
    prim = GeomTriangles(Geom.UHStatic)
    for n in range(number):
      prim.addVertices((n * 3) + 2, (n * 3) + 0, (n * 3) + 1)
    prim.closePrimitive()

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

    # make geom node
    node = GeomNode("base" + "_" + str(a) + "_" + str(b))
    node.addGeom(geom)

    # make mesh nodePath
    mesh = NodePath(node)
    # set render order
    mesh.setBin("", 1)

    # locate mesh
    mesh.setPos(self.divsep * (a * int(len(self.data[a]) / self.div)),
                self.divsep * (b * int(len(self.data[b]) / self.div)), 0)

    # reparent mesh
    mesh.reparentTo(self.root)

    # return mesh
    return mesh
Example #8
0
def generate_sphere(name, radius, resolution):
    """
    Generates a sphere with the provided resolution.

    @type name: string
    @param name: Name of this sphere.

    @type radius: number
    @param radius: Radius of sphere in kilometers.

    @type resolution: number
    @param resolution: Resolution of sphere (minimum 2)

    @rtype: GeomNode
    @return: A GeomNode with the given sphere.
    """

    if resolution < 2:
        raise ValueError, "resolution must be >= 2"

    horizBands = resolution*2
    vertBands = horizBands*2

    vertexFormat = GeomVertexFormat.getV3n3c4t2()
    vdata = GeomVertexData('%s_vdata' % name, vertexFormat, Geom.UHDynamic)

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

    vertDelta = omath.TWOPI / vertBands
    horizDelta = omath.TWOPI / horizBands

    numVertices = 0

    for i in range(vertBands+1):
        lowTheta = i * vertDelta
        highTheta = (i+1) * vertDelta

        cosLowTheta = math.cos(lowTheta)
        sinLowTheta = math.sin(lowTheta)
        cosHighTheta = math.cos(highTheta)
        sinHighTheta = math.sin(highTheta)

        for j in range(horizBands):
            horizTheta = j * horizDelta

            cosHorizTheta = math.cos(horizTheta)
            sinHorizTheta = math.sin(horizTheta)

            ex = cosLowTheta*cosHorizTheta
            ey = sinLowTheta
            ez = cosLowTheta*sinHorizTheta

            vertex.addData3f(ex*radius, ey*radius, ez*radius)
            normal.addData3f(ex, ey, ez)
            color.addData4f(.75, .75, .75, 1)
            texcoord.addData2f(i / vertBands, j / horizBands)

            ex = cosHighTheta*cosHorizTheta
            ey = sinHighTheta
            ez = cosHighTheta*sinHorizTheta

            vertex.addData3f(ex*radius, ey*radius, ez*radius)
            normal.addData3f(ex, ey, ez)
            color.addData4f(.75, .75, .75, 1)
            texcoord.addData2f(i / vertBands, j / horizBands)

            numVertices += 2

    prim = GeomTristrips(Geom.UHStatic)
    prim.addConsecutiveVertices(0, numVertices)
    prim.closePrimitive()

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

    geomNode = GeomNode(name)
    geomNode.addGeom(geom)

    return GeomScaler(geomNode)
Example #9
0
    def pandaRender(self):
        frameList = []
        for node in self.compositeFrames.getiterator("composite-frame"):
            if node.tag == "composite-frame" and node.attrib.get("id") == str(self.internalFrameIndex):
                for frameCallNode in node:
                    for frameNode in self.frames.getiterator("frame"):
                        if frameNode.tag == "frame" and frameNode.attrib.get("id") == frameCallNode.attrib.get("id"):
                            offsetX = (
                                0
                                if frameCallNode.attrib.get("offset-x") == None
                                else float(frameCallNode.attrib.get("offset-x"))
                            )
                            offsetY = (
                                0
                                if frameCallNode.attrib.get("offset-y") == None
                                else float(frameCallNode.attrib.get("offset-y"))
                            )
                            tweenId = frameCallNode.attrib.get("tween")
                            frameInTween = (
                                0
                                if frameCallNode.attrib.get("frame-in-tween") == None
                                else int(frameCallNode.attrib.get("frame-in-tween"))
                            )
                            addWidth = 0 if frameNode.attrib.get("w") == None else float(frameNode.attrib.get("w"))
                            addHeight = 0 if frameNode.attrib.get("h") == None else float(frameNode.attrib.get("h"))
                            sInPixels = 0 if frameNode.attrib.get("s") == None else float(frameNode.attrib.get("s"))
                            tInPixels = 0 if frameNode.attrib.get("t") == None else float(frameNode.attrib.get("t"))
                            swInPixels = sInPixels + addWidth
                            thInPixels = tInPixels + addHeight
                            s = sInPixels / self.baseWidth
                            t = 1 - (
                                tInPixels / self.baseHeight
                            )  # Complemented to deal with loading image upside down.
                            S = swInPixels / self.baseWidth
                            T = 1 - (
                                thInPixels / self.baseHeight
                            )  # Complemented to deal with loading image upside down.
                            blend = (
                                "overwrite"
                                if frameCallNode.attrib.get("blend") == None
                                else frameCallNode.attrib.get("blend")
                            )
                            scaleX = (
                                1
                                if frameCallNode.attrib.get("scale-x") == None
                                else float(frameCallNode.attrib.get("scale-x"))
                            )
                            scaleY = (
                                1
                                if frameCallNode.attrib.get("scale-y") == None
                                else float(frameCallNode.attrib.get("scale-y"))
                            )
                            color = Color(1, 1, 1, 1)
                            tweenHasColor = False
                            frameCallHasColor = False
                            frameCallColorName = frameCallNode.attrib.get("color-name")
                            if frameCallColorName != None:
                                # Get color at frame call as first resort.
                                frameCallHasColor = True
                                for colorNode in self.colors.getiterator("color"):
                                    if colorNode.tag == "color" and colorNode.attrib.get("name") == frameCallColorName:
                                        R = 1 if colorNode.attrib.get("r") == None else float(colorNode.attrib.get("r"))
                                        G = 1 if colorNode.attrib.get("g") == None else float(colorNode.attrib.get("g"))
                                        B = 1 if colorNode.attrib.get("b") == None else float(colorNode.attrib.get("b"))
                                        A = 1 if colorNode.attrib.get("a") == None else float(colorNode.attrib.get("a"))
                                        color = Color(R, G, B, A)
                                        break  # leave for loop when we find the correct color
                                pass

                            if tweenId != None and tweenId != "0":
                                # Get color at tween frame as second resort.
                                thisTween = None
                                frameLength = 1
                                advancementFunction = "linear"
                                foundTween = False
                                pointList = []
                                colorList = []
                                for tweenNode in self.tweens.getiterator("motion-tween"):
                                    if tweenNode.tag == "motion-tween" and tweenNode.attrib.get("id") == tweenId:
                                        foundTween = True
                                        frameLength = (
                                            1
                                            if tweenNode.attrib.get("length-in-frames") == None
                                            else tweenNode.attrib.get("length-in-frames")
                                        )
                                        advancementFunction = (
                                            "linear"
                                            if tweenNode.attrib.get("advancement-function") == None
                                            else tweenNode.attrib.get("advancement-function")
                                        )
                                        for pointOrColorNode in tweenNode.getiterator():
                                            if pointOrColorNode.tag == "point":
                                                pX = (
                                                    0
                                                    if pointOrColorNode.attrib.get("x") == None
                                                    else float(pointOrColorNode.attrib.get("x"))
                                                )
                                                pY = (
                                                    0
                                                    if pointOrColorNode.attrib.get("y") == None
                                                    else float(pointOrColorNode.attrib.get("y"))
                                                )
                                                pointList.append(Point(pX, pY, 0))
                                            elif pointOrColorNode.tag == "color-state":
                                                colorName = (
                                                    "white"
                                                    if pointOrColorNode.attrib.get("name") == None
                                                    else pointOrColorNode.attrib.get("name")
                                                )
                                                for colorNode in self.colors.getiterator("color"):
                                                    if (
                                                        colorNode.tag == "color"
                                                        and colorNode.attrib.get("name") == colorName
                                                    ):
                                                        R = (
                                                            1
                                                            if colorNode.attrib.get("r") == None
                                                            else float(colorNode.attrib.get("r"))
                                                        )
                                                        G = (
                                                            1
                                                            if colorNode.attrib.get("g") == None
                                                            else float(colorNode.attrib.get("g"))
                                                        )
                                                        B = (
                                                            1
                                                            if colorNode.attrib.get("b") == None
                                                            else float(colorNode.attrib.get("b"))
                                                        )
                                                        A = (
                                                            1
                                                            if colorNode.attrib.get("a") == None
                                                            else float(colorNode.attrib.get("a"))
                                                        )
                                                        colorList.append(Color(R, G, B, A))
                                                        break  # leave for loop when we find the correct color reference
                                            pass  # Run through all child nodes of selected tween
                                        break  # Exit after finding correct tween
                                pass
                                if foundTween:
                                    thisTween = Tween(frameLength, advancementFunction, pointList, colorList)
                                    offset = thisTween.XYFromFrame(frameInTween)
                                    offsetFromTweenX = int(offset.X)
                                    offsetFromTweenY = int(offset.Y)
                                    offsetX += int(offset.X)
                                    offsetY += int(offset.Y)
                                    if thisTween.hasColorComponent():
                                        tweenHasColor = True
                                        if frameCallHasColor == False:
                                            color = thisTween.colorFromFrame(frameInTween)
                                    pass
                            if (
                                frameNode.attrib.get("color-name") != None
                                and frameCallHasColor == False
                                and tweenHasColor == False
                            ):
                                # Get color at frame definition as last resort.
                                for colorNode in colors.getiterator("color"):
                                    if colorNode.tag == "color" and colorNode.attrib.get(
                                        "name"
                                    ) == frameNode.attrib.get("color-name"):
                                        R = 1 if colorNode.attrib.get("r") == None else float(colorNode.attrib.get("r"))
                                        G = 1 if colorNode.attrib.get("g") == None else float(colorNode.attrib.get("g"))
                                        B = 1 if colorNode.attrib.get("b") == None else float(colorNode.attrib.get("b"))
                                        A = 1 if colorNode.attrib.get("a") == None else float(colorNode.attrib.get("a"))
                                        color = Color(R, G, B, A)
                                        break  # leave for loop when we find the correct color
                                pass
                            rotationZ = (
                                0
                                if frameCallNode.attrib.get("rotation-z") == None
                                else float(frameCallNode.attrib.get("rotation-z"))
                            )
                            frameList.append(
                                Frame(
                                    Bound(offsetX, offsetY, addWidth, addHeight),
                                    s,
                                    t,
                                    S,
                                    T,
                                    blend,
                                    scaleX,
                                    scaleY,
                                    color,
                                    rotationZ,
                                )
                            )
                    pass
                break  # Leave once we've found the appropriate frame

        # Prepare tracking list of consumed nodes.
        self.clearNodesForDrawing()
        # Make an identifier to tack onto primitive names in Panda3d's scene graph.
        frameIndexForName = 1

        # Loop through loaded frames that make up composite frame.
        for loadedFrame in frameList:
            # For debugging purposes, print the object.
            if False:
                loadedFrame.printAsString()

            # Set up place to store primitive 3d object; note: requires vertex data made by GeomVertexData
            squareMadeByTriangleStrips = GeomTristrips(Geom.UHDynamic)

            # Set up place to hold 3d data and for the following coordinates:
            #   square's points (V3: x, y, z),
            #   the colors at each point of the square (c4: r, g, b, a), and
            #   for the UV texture coordinates at each point of the square     (t2: S, T).
            vertexData = GeomVertexData(
                "square-" + str(frameIndexForName), GeomVertexFormat.getV3c4t2(), Geom.UHDynamic
            )
            vertex = GeomVertexWriter(vertexData, "vertex")
            color = GeomVertexWriter(vertexData, "color")
            texcoord = GeomVertexWriter(vertexData, "texcoord")

            # Add the square's data
            # Upper-Left corner of square
            vertex.addData3f(-loadedFrame.bound.Width / 2.0, 0, -loadedFrame.bound.Height / 2.0)
            color.addData4f(loadedFrame.color.R, loadedFrame.color.G, loadedFrame.color.B, loadedFrame.color.A)
            texcoord.addData2f(loadedFrame.s, loadedFrame.T)

            # Upper-Right corner of square
            vertex.addData3f(loadedFrame.bound.Width / 2.0, 0, -loadedFrame.bound.Height / 2.0)
            color.addData4f(loadedFrame.color.R, loadedFrame.color.G, loadedFrame.color.B, loadedFrame.color.A)
            texcoord.addData2f(loadedFrame.S, loadedFrame.T)

            # Lower-Left corner of square
            vertex.addData3f(-loadedFrame.bound.Width / 2.0, 0, loadedFrame.bound.Height / 2.0)
            color.addData4f(loadedFrame.color.R, loadedFrame.color.G, loadedFrame.color.B, loadedFrame.color.A)
            texcoord.addData2f(loadedFrame.s, loadedFrame.t)

            # Lower-Right corner of square
            vertex.addData3f(loadedFrame.bound.Width / 2.0, 0, loadedFrame.bound.Height / 2.0)
            color.addData4f(loadedFrame.color.R, loadedFrame.color.G, loadedFrame.color.B, loadedFrame.color.A)
            texcoord.addData2f(loadedFrame.S, loadedFrame.t)

            # Pass data to primitive
            squareMadeByTriangleStrips.addNextVertices(4)
            squareMadeByTriangleStrips.closePrimitive()
            square = Geom(vertexData)
            square.addPrimitive(squareMadeByTriangleStrips)
            # Pass primtive to drawing node
            drawPrimitiveNode = GeomNode("square-" + str(frameIndexForName))
            drawPrimitiveNode.addGeom(square)
            # Pass node to scene (effect camera)
            nodePath = self.effectCameraNodePath.attachNewNode(drawPrimitiveNode)
            # Linear dodge:
            if loadedFrame.blendMode == "darken":
                nodePath.setAttrib(
                    ColorBlendAttrib.make(
                        ColorBlendAttrib.MAdd,
                        ColorBlendAttrib.OOneMinusFbufferColor,
                        ColorBlendAttrib.OOneMinusIncomingColor,
                    )
                )
                pass
            elif loadedFrame.blendMode == "multiply":
                nodePath.setAttrib(
                    ColorBlendAttrib.make(ColorBlendAttrib.MAdd, ColorBlendAttrib.OFbufferColor, ColorBlendAttrib.OZero)
                )
                pass
            elif loadedFrame.blendMode == "color-burn":
                nodePath.setAttrib(
                    ColorBlendAttrib.make(
                        ColorBlendAttrib.MAdd, ColorBlendAttrib.OZero, ColorBlendAttrib.OOneMinusIncomingColor
                    )
                )
                pass
            elif loadedFrame.blendMode == "linear-burn":
                nodePath.setAttrib(
                    ColorBlendAttrib.make(
                        ColorBlendAttrib.MAdd, ColorBlendAttrib.OZero, ColorBlendAttrib.OIncomingColor
                    )
                )
                pass
            elif loadedFrame.blendMode == "lighten":
                nodePath.setAttrib(
                    ColorBlendAttrib.make(
                        ColorBlendAttrib.MMax, ColorBlendAttrib.OIncomingColor, ColorBlendAttrib.OFbufferColor
                    )
                )
                pass
            elif loadedFrame.blendMode == "color-dodge":
                nodePath.setAttrib(
                    ColorBlendAttrib.make(ColorBlendAttrib.MAdd, ColorBlendAttrib.OOne, ColorBlendAttrib.OOne)
                )
                pass
            elif loadedFrame.blendMode == "linear-dodge":
                nodePath.setAttrib(
                    ColorBlendAttrib.make(
                        ColorBlendAttrib.MAdd, ColorBlendAttrib.OOne, ColorBlendAttrib.OOneMinusIncomingColor
                    )
                )
                pass
            else:  # Overwrite:
                nodePath.setAttrib(
                    ColorBlendAttrib.make(
                        ColorBlendAttrib.MAdd, ColorBlendAttrib.OIncomingAlpha, ColorBlendAttrib.OOneMinusIncomingAlpha
                    )
                )
                pass
            nodePath.setDepthTest(False)
            # Apply texture
            nodePath.setTexture(self.tex)
            # Apply translation, then rotation, then scaling to node.
            nodePath.setPos(
                (
                    loadedFrame.bound.X + loadedFrame.bound.Width / 2.0,
                    1,
                    -loadedFrame.bound.Y - loadedFrame.bound.Height / 2.0,
                )
            )
            nodePath.setR(loadedFrame.rotationZ)
            nodePath.setScale(loadedFrame.scaleX, 1, loadedFrame.scaleY)
            nodePath.setTwoSided(True)
            self.consumedNodesList.append(nodePath)
            frameIndexForName = frameIndexForName + 1
        # Loop continues on through each frame called in the composite frame.
        pass
Example #10
0
    def draw(self):
        format = GeomVertexFormat.getV3n3cpt2()
        vdata = GeomVertexData('square', format, Geom.UHStatic)

        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(self.x1, self.y1, self.z1)
        vertex.addData3f(self.x2, self.y1, self.z1)
        vertex.addData3f(self.x2, self.y2, self.z2)
        vertex.addData3f(self.x1, self.y2, self.z2)

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

        #adding different colors to the vertex for visibility
        color.addData4f(self.r, self.g, self.b, self.a)
        color.addData4f(self.r, self.g, self.b, self.a)
        color.addData4f(self.r, self.g, self.b, self.a)
        color.addData4f(self.r, self.g, self.b, self.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 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.UHStatic)
        tri2 = GeomTriangles(Geom.UHStatic)

        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)
        #square.setIntoCollideMask(BitMask32.bit(1))

        self.squareNP = NodePath(GeomNode('square gnode'))
        self.squareNP.node().addGeom(square)
        self.squareNP.setTransparency(1)
        self.squareNP.setAlphaScale(.5)
        self.squareNP.setTwoSided(True)
        #squareNP.setCollideMask(BitMask32.bit(1))
        self.squareNP.reparentTo(self.parent)

        return self.squareNP
Example #11
0
class Track3d(object):
    '''
    Generate the 3d Mesh out of the StreetData and the 2dTrack
    '''

    def __init__(self, res, x, y, z=200, player_count=1, street_data=""):
        '''
        '''
        self._notify = DirectNotify().newCategory("TrackGen3D")
        self._notify.info("New Track3D-Object created: %s" % (self))
        # street_data = (Vec2(4.0,4.0), Vec2(10.0,10.0), Vec2(10.0,0.0), Vec2(4.0,0.0), Vec2(0.0,-1.0))
        # street_data = StreetData(Vec2(15.0,1.0), Vec2(15.0,-5.0), Vec2(0.0,-5.0), mirrored=True) #, Vec2(15.0,0.0)
        self.street_data = StreetData()

        # self.street_data.readFile("data/road/road01.xml")
        # self.street_data.readFile("data/road/tube.xml")
        if street_data == "":
            datas = ["road01", "tube"]
            street_data = datas[random.randint(0, len(datas) - 1)]
        self.street_data.readFile("data/road/" + street_data + ".xml")

        self.streetTextrange = 0.0
        self.track = Track(x, y, z)
        self.track.generateTestTrack(player_count)
        # self.track.generateTrack(player_count)

        self.track_points = self.track.getInterpolatedPoints(res)
        self.varthickness = []  # Generate the Vector for thickness of the road

        self.generateNormals()
        # for i in range(len(self.track_points)-1):
        # if i == 0:
        # self.varthickness.append(self.calcTheVector(self.track_points[i],self.track_points[i],self.track_points[i+1])) #First
        # continue
        # self.varthickness.append(self.calcTheVector(self.track_points[i-1],self.track_points[i],self.track_points[i+1]))
        # self.varthickness.append(self.calcTheVector(self.track_points[len(self.track_points)-2],self.track_points[len(self.track_points)-1],self.track_points[len(self.track_points)-1])) #Last
        ##
        # Normalizing the Vector
        # for i in self.varthickness:
        # i.normalize()
        ##
        # print self.varthickness[-1]
        # print self.varthickness[0]
        # print self.varthickness[1]
        # print self.varthickness[2]

        # Spin the last 100 Points a litte bit to Vec3(-1,0,0)
        for i in range(-100, 1):
            # print self.varthickness[i] * (-i / 100), self.varthickness[i] , ((i* -1) / 100.0), i
            # print ((i* -1) / 100.0), self.varthickness[i], self.varthickness[i] * ((i* -1) / 100.0)
            self.varthickness[i] = self.varthickness[i] * (((i + 1) * -1) / 100.0) + Vec3(-1, 0, 0)
            self.normals[i] = self.normals[i] * (((i + 1) * -1) / 100.0) + Vec3(0, 0, 1)

            self.varthickness[i].normalize()
            self.normals[i].normalize()
            # print self.varthickness[i]

        # print self.varthickness[-1]
        # print self.varthickness[0]
        # print self.varthickness[1]
        # print self.varthickness[2]
        # print self.varthickness
        # for i in range(len(self.varthickness)):
        # if self.varthickness[i-1].almostEqual(self.varthickness[i], 0.3):
        # pass
        # else:
        # print "varthickness", self.varthickness[i-1], self.varthickness[i]

# -------------------------------------------------------------------------------------

    def resetWriters(self):
        '''
        '''
        self.vdata = GeomVertexData('street', GeomVertexFormat.getV3n3c4t2(), Geom.UHStatic)

        self.vertex = GeomVertexWriter(self.vdata, 'vertex')
        self.normal = GeomVertexWriter(self.vdata, 'normal')
        self.color = GeomVertexWriter(self.vdata, 'color')
        self.texcoord = GeomVertexWriter(self.vdata, 'texcoord')
        self.prim = GeomTriangles(Geom.UHStatic)

# -------------------------------------------------------------------------------------

    def calcTheVector(self, pre, now, past):
        vector1 = (pre[0] - now[0], pre[1] - now[1])
        vector2 = (now[0] - past[0], now[1] - past[1])
        high = pre[2] - past[2]
        return Vec3(((vector1[1] + vector2[1]) / 2.0), ((vector1[0] + vector2[0]) / 2.0), high)

# -------------------------------------------------------------------------------------

    def getVarthickness(self):
        return self.varthickness

# -------------------------------------------------------------------------------------

    def setTrackPoints(self, track_points):
        '''
        '''
        self.track_points = track_points

    def getTrackPoints(self):
        '''
        '''
        return self.track_points

    trackpoints = property(fget=getTrackPoints, fset=setTrackPoints)

# -------------------------------------------------------------------------------------

    def generateNormals(self):
        '''
        '''
        self.varthickness = []
        self.normals = []
        last_normal = Vec3(0, 0, 1)
        # last_vec = Vec3(0, 1, 0)
        for i in range(len(self.track_points)):
            if i == 0:
                vec = self.track_points[0] - self.track_points[1]
            elif i + 1 == len(self.track_points):
                vec = self.track_points[i - 1] - self.track_points[0]
            else:
                vec = self.track_points[i - 1] - self.track_points[i + 1]

            # calculate here the direction out of the street vector and the last normal
            last_normal.normalize()
            vec.normalize()
            mat = Mat3()

            mat.setRotateMat(-90, last_normal)  # turn the direction around the last_normal
            turned_vec = mat.xform(vec)

            turned_vec.normalize()
            last_normal = turned_vec.cross(vec)  # calculate the new normal

            turned_vec.normalize()
            self.varthickness.append(turned_vec)
            self.normals.append(last_normal)

# -------------------------------------------------------------------------------------

    def createVertices(self, track_points=None, street_data=None):
        '''
        '''
        if track_points is None:
            track_points = self.track_points
        if street_data is None:
            street_data = self.street_data

        self.resetWriters()
        texcoordinates = []
        # street_data_length = len(street_data)

        texcoordinates = street_data.getTexCoordinates()
        tracklength = self.track.getLength()
        tex_step = 0.006 * (0.0002 * tracklength)
        for i in range(len(track_points)):
            turned_vec = self.varthickness[i]
            last_normal = self.normals[i]
            j = 0
            for shapedot in street_data:
                # this is like a layer in 3d [Ebenengleichung]
                # vec = vec + vec*scalar + vec*scalar
                # this is used to transform the 2d-Streetshape to 3d
                point = track_points[i] + (turned_vec * shapedot[0]) + (last_normal * shapedot[1])

                self.vertex.addData3f(point[0], point[1], point[2])
                self.normal.addData3f(0, 0, 1)  # KA how to calc
                self.streetTextrange += tex_step

                self.texcoord.addData2f(texcoordinates[j], self.streetTextrange)
                j += 1

# -------------------------------------------------------------------------------------

    def connectVertices(self, street_data):
        # param j = len(street_Data)
        j = len(street_data)
        for i in range(self.vdata.getNumRows() - (j)):  # -j??????  oder +-1
            if (i + 1) % j != 0:
                self.prim.addVertex(i)
                self.prim.addVertex(i + 1)
                self.prim.addVertex(i + j + 1)
                self.prim.closePrimitive()

                self.prim.addVertex(i)
                self.prim.addVertex(i + j + 1)
                self.prim.addVertex(i + j)
                self.prim.closePrimitive()
            else:  # close mesh's bottom side

                self.prim.addVertex(i + 1 - j)
                self.prim.addVertex(i + 1)
                self.prim.addVertex(i)
                self.prim.closePrimitive()

                self.prim.addVertex(i)
                self.prim.addVertex(i + 1)
                self.prim.addVertex(i + j)
                self.prim.closePrimitive()

        # close start and end
        k = self.vdata.getNumRows() - j
        for i in range(j):
            if (i + 1) % j != 0:
                self.prim.addVertex(i)
                self.prim.addVertex(i + k + 1)
                self.prim.addVertex(i + 1)
                self.prim.closePrimitive()

                self.prim.addVertex(i)
                self.prim.addVertex(i + k)
                self.prim.addVertex(i + k + 1)
                self.prim.closePrimitive()

            else:  # close mesh's bottom side
                self.prim.addVertex(i)
                self.prim.addVertex(i + k - j + 1)
                self.prim.addVertex(i - j + 1)
                self.prim.closePrimitive()

                self.prim.addVertex(i)
                self.prim.addVertex(i + k)
                self.prim.addVertex(i + k - j + 1)
                self.prim.closePrimitive()

# -------------------------------------------------------------------------------------

    def createRoadMesh(self):
        '''
        '''
        # Creating the Vertex
        self.createVertices()
        # Connect the Vertex
        self.connectVertices(self.street_data)

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

        node = GeomNode('street')
        node.addGeom(geom)

        # nodePath = self.render.attachNewNode(node)
        return node

    # -------------------------------------------------------------------------------------

    def createUninterpolatedRoadMesh(self):
        '''
        '''
        # Creating the Vertex
        self.createVertices(self.track.getPoints(), self.street_data)
        # Connect the Vertex
        self.connectVertices(self.street_data)

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

        node = GeomNode('street')
        node.addGeom(geom)

        # nodePath = self.render.attachNewNode(node)
        return node

# -------------------------------------------------------------------------------------

    def createBorderLeftMesh(self):
        '''
        '''
        # Creating the Vertex
        self.createVertices(self.track_points, self.street_data.border_l)

        # Connect the Vertex
        self.connectVertices(self.street_data.border_l)

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

        node = GeomNode('border_l')
        node.addGeom(geom)

        # nodePath = self.render.attachNewNode(node)
        return node

# -------------------------------------------------------------------------------------

    def createBorderRightMesh(self):
        '''
        '''
        # Creating the Vertex
        self.createVertices(self.track_points, self.street_data.border_r)
        # Connect the Vertex
        self.connectVertices(self.street_data.border_r)

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

        node = GeomNode('border_r')
        node.addGeom(geom)

        # nodePath = self.render.attachNewNode(node)
        return node

# -------------------------------------------------------------------------------------

    def createBorderLeftCollisionMesh(self):
        '''
        '''
        # Creating the Vertex
        self.createVertices(self.track_points, self.street_data.border_l_coll)

        # Connect the Vertex
        self.connectVertices(self.street_data.border_l_coll)

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

        node = GeomNode('border_l_coll')
        node.addGeom(geom)

        # nodePath = self.render.attachNewNode(node)
        return node

# -------------------------------------------------------------------------------------

    def createBorderRightCollisionMesh(self):
        '''
        '''
        # Creating the Vertex
        self.createVertices(self.track_points, self.street_data.border_r_coll)
        # Connect the Vertex
        self.connectVertices(self.street_data.border_r_coll)

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

        node = GeomNode('border_r_coll')
        node.addGeom(geom)

        # nodePath = self.render.attachNewNode(node)
        return node
Example #12
0
    def pandaRender(self):
        frameList = []
        for node in self.compositeFrames.getiterator('composite-frame'):
            if node.tag == "composite-frame" and node.attrib.get("id") == str(self.internalFrameIndex):
                for frameCallNode in node:
                    for frameNode in self.frames.getiterator('frame'):
                        if frameNode.tag == "frame" and frameNode.attrib.get("id") == frameCallNode.attrib.get("id"):
                            offsetX = 0 if frameCallNode.attrib.get("offset-x") == None else float(frameCallNode.attrib.get("offset-x"))
                            offsetY = 0 if frameCallNode.attrib.get("offset-y") == None else float(frameCallNode.attrib.get("offset-y"))
                            tweenId = frameCallNode.attrib.get("tween")
                            frameInTween = 0 if frameCallNode.attrib.get("frame-in-tween") == None else int(frameCallNode.attrib.get("frame-in-tween"))
                            addWidth = 0 if frameNode.attrib.get("w") == None else float(frameNode.attrib.get("w"))
                            addHeight = 0 if frameNode.attrib.get("h") == None else float(frameNode.attrib.get("h"))
                            sInPixels = 0 if frameNode.attrib.get("s") == None else float(frameNode.attrib.get("s"))
                            tInPixels = 0 if frameNode.attrib.get("t") == None else float(frameNode.attrib.get("t"))
                            swInPixels = sInPixels + addWidth
                            thInPixels = tInPixels + addHeight
                            s = (sInPixels / self.baseWidth)
                            t = 1 - (tInPixels / self.baseHeight) # Complemented to deal with loading image upside down.
                            S = (swInPixels / self.baseWidth)
                            T = 1 - (thInPixels / self.baseHeight) # Complemented to deal with loading image upside down.
                            blend = "overwrite" if frameCallNode.attrib.get("blend") == None else frameCallNode.attrib.get("blend")
                            scaleX = 1 if frameCallNode.attrib.get("scale-x") == None else float(frameCallNode.attrib.get("scale-x"))
                            scaleY = 1 if frameCallNode.attrib.get("scale-y") == None else float(frameCallNode.attrib.get("scale-y"))
                            color = Color(1,1,1,1)
                            tweenHasColor = False
                            frameCallHasColor = False
                            frameCallColorName = frameCallNode.attrib.get("color-name")
                            if frameCallColorName != None:
                                # Get color at frame call as first resort.
                                frameCallHasColor = True
                                for colorNode in self.colors.getiterator('color'):
                                    if colorNode.tag == 'color' and colorNode.attrib.get("name") == frameCallColorName:
                                        R = 1 if colorNode.attrib.get("r") == None else float(colorNode.attrib.get("r"))
                                        G = 1 if colorNode.attrib.get("g") == None else float(colorNode.attrib.get("g"))
                                        B = 1 if colorNode.attrib.get("b") == None else float(colorNode.attrib.get("b"))
                                        A = 1 if colorNode.attrib.get("a") == None else float(colorNode.attrib.get("a"))
                                        color = Color(R, G, B, A)
                                        break # leave for loop when we find the correct color
                                pass

                            if tweenId != None and tweenId != "0":
                                # Get color at tween frame as second resort.
                                thisTween = None
                                frameLength = 1
                                advancementFunction = "linear"
                                foundTween = False
                                pointList = []
                                colorList = []
                                for tweenNode in self.tweens.getiterator('motion-tween'):
                                    if tweenNode.tag == "motion-tween" and tweenNode.attrib.get("id") == tweenId:
                                        foundTween = True
                                        frameLength = 1 if tweenNode.attrib.get("length-in-frames") == None else tweenNode.attrib.get("length-in-frames")
                                        advancementFunction = "linear" if tweenNode.attrib.get("advancement-function") == None else tweenNode.attrib.get("advancement-function")
                                        for pointOrColorNode in tweenNode.getiterator():
                                            if pointOrColorNode.tag == "point":
                                                pX = 0 if pointOrColorNode.attrib.get("x") == None else float(pointOrColorNode.attrib.get("x"))
                                                pY = 0 if pointOrColorNode.attrib.get("y") == None else float(pointOrColorNode.attrib.get("y"))
                                                pointList.append(Point(pX, pY, 0))
                                            elif pointOrColorNode.tag == "color-state":
                                                colorName = "white" if pointOrColorNode.attrib.get("name") == None else pointOrColorNode.attrib.get("name")
                                                for colorNode in self.colors.getiterator('color'):
                                                    if colorNode.tag == 'color' and colorNode.attrib.get("name") == colorName:
                                                        R = 1 if colorNode.attrib.get("r") == None else float(colorNode.attrib.get("r"))
                                                        G = 1 if colorNode.attrib.get("g") == None else float(colorNode.attrib.get("g"))
                                                        B = 1 if colorNode.attrib.get("b") == None else float(colorNode.attrib.get("b"))
                                                        A = 1 if colorNode.attrib.get("a") == None else float(colorNode.attrib.get("a"))
                                                        colorList.append(Color(R, G, B, A))
                                                        break # leave for loop when we find the correct color reference
                                            pass # Run through all child nodes of selected tween
                                        break # Exit after finding correct tween
                                pass
                                if foundTween:
                                    thisTween = Tween(frameLength, advancementFunction, pointList, colorList)
                                    offset = thisTween.XYFromFrame(frameInTween);
                                    offsetFromTweenX = int(offset.X);
                                    offsetFromTweenY = int(offset.Y);
                                    offsetX += int(offset.X);
                                    offsetY += int(offset.Y);
                                    if thisTween.hasColorComponent():
                                        tweenHasColor = True;
                                        if frameCallHasColor == False:
                                            color = thisTween.colorFromFrame(frameInTween);
                                    pass
                            if frameNode.attrib.get("color-name") != None and frameCallHasColor == False and tweenHasColor == False:
                                # Get color at frame definition as last resort.
                                for colorNode in colors.getiterator('color'):
                                    if colorNode.tag == 'color' and colorNode.attrib.get("name") == frameNode.attrib.get("color-name"):
                                        R = 1 if colorNode.attrib.get("r") == None else float(colorNode.attrib.get("r"))
                                        G = 1 if colorNode.attrib.get("g") == None else float(colorNode.attrib.get("g"))
                                        B = 1 if colorNode.attrib.get("b") == None else float(colorNode.attrib.get("b"))
                                        A = 1 if colorNode.attrib.get("a") == None else float(colorNode.attrib.get("a"))
                                        color = Color(R, G, B, A)
                                        break # leave for loop when we find the correct color
                                pass
                            rotationZ = 0 if frameCallNode.attrib.get("rotation-z") == None else float(frameCallNode.attrib.get("rotation-z"))
                            frameList.append(Frame(Bound(offsetX, offsetY, addWidth, addHeight), s, t, S, T, blend, scaleX, scaleY, color, rotationZ))
                    pass 
                break # Leave once we've found the appropriate frame

        # Prepare tracking list of consumed nodes.
        self.clearNodesForDrawing()
        # Make an identifier to tack onto primitive names in Panda3d's scene graph.
        frameIndexForName = 1
                
        # Loop through loaded frames that make up composite frame.
        for loadedFrame in frameList:              
            # For debugging purposes, print the object.
            if False:
                loadedFrame.printAsString()
            
            # Set up place to store primitive 3d object; note: requires vertex data made by GeomVertexData
            squareMadeByTriangleStrips = GeomTristrips(Geom.UHDynamic)
              
            # Set up place to hold 3d data and for the following coordinates:
            #   square's points (V3: x, y, z), 
            #   the colors at each point of the square (c4: r, g, b, a), and
            #   for the UV texture coordinates at each point of the square     (t2: S, T).
            vertexData = GeomVertexData('square-'+str(frameIndexForName), GeomVertexFormat.getV3c4t2(), Geom.UHDynamic)
            vertex = GeomVertexWriter(vertexData, 'vertex')
            color = GeomVertexWriter(vertexData, 'color')
            texcoord = GeomVertexWriter(vertexData, 'texcoord') 
              
            # Add the square's data
            # Upper-Left corner of square
            vertex.addData3f(-loadedFrame.bound.Width / 2.0, 0, -loadedFrame.bound.Height / 2.0)
            color.addData4f(loadedFrame.color.R,loadedFrame.color.G,loadedFrame.color.B,loadedFrame.color.A)
            texcoord.addData2f(loadedFrame.s, loadedFrame.T)

            # Upper-Right corner of square
            vertex.addData3f(loadedFrame.bound.Width / 2.0, 0, -loadedFrame.bound.Height / 2.0)
            color.addData4f(loadedFrame.color.R,loadedFrame.color.G,loadedFrame.color.B,loadedFrame.color.A)
            texcoord.addData2f(loadedFrame.S, loadedFrame.T)
            
            # Lower-Left corner of square
            vertex.addData3f(-loadedFrame.bound.Width / 2.0, 0, loadedFrame.bound.Height / 2.0)
            color.addData4f(loadedFrame.color.R,loadedFrame.color.G,loadedFrame.color.B,loadedFrame.color.A)
            texcoord.addData2f(loadedFrame.s, loadedFrame.t)
            
            # Lower-Right corner of square
            vertex.addData3f(loadedFrame.bound.Width / 2.0, 0, loadedFrame.bound.Height / 2.0)
            color.addData4f(loadedFrame.color.R,loadedFrame.color.G,loadedFrame.color.B,loadedFrame.color.A)
            texcoord.addData2f(loadedFrame.S, loadedFrame.t)

            # Pass data to primitive
            squareMadeByTriangleStrips.addNextVertices(4)
            squareMadeByTriangleStrips.closePrimitive()
            square = Geom(vertexData)
            square.addPrimitive(squareMadeByTriangleStrips)
            # Pass primtive to drawing node
            drawPrimitiveNode=GeomNode('square-'+str(frameIndexForName))    
            drawPrimitiveNode.addGeom(square)
            # Pass node to scene (effect camera)
            nodePath = self.effectCameraNodePath.attachNewNode(drawPrimitiveNode)
            # Linear dodge:
            if loadedFrame.blendMode == "darken":
                nodePath.setAttrib(ColorBlendAttrib.make(ColorBlendAttrib.MAdd, ColorBlendAttrib.OOneMinusFbufferColor, ColorBlendAttrib.OOneMinusIncomingColor))
                pass
            elif loadedFrame.blendMode == "multiply":
                nodePath.setAttrib(ColorBlendAttrib.make(ColorBlendAttrib.MAdd, ColorBlendAttrib.OFbufferColor, ColorBlendAttrib.OZero))
                pass
            elif loadedFrame.blendMode == "color-burn":
                nodePath.setAttrib(ColorBlendAttrib.make(ColorBlendAttrib.MAdd, ColorBlendAttrib.OZero, ColorBlendAttrib.OOneMinusIncomingColor))
                pass
            elif loadedFrame.blendMode == "linear-burn":
                nodePath.setAttrib(ColorBlendAttrib.make(ColorBlendAttrib.MAdd, ColorBlendAttrib.OZero, ColorBlendAttrib.OIncomingColor))
                pass
            elif loadedFrame.blendMode == "lighten":
                nodePath.setAttrib(ColorBlendAttrib.make(ColorBlendAttrib.MMax, ColorBlendAttrib.OIncomingColor, ColorBlendAttrib.OFbufferColor))
                pass
            elif loadedFrame.blendMode == "color-dodge":
                nodePath.setAttrib(ColorBlendAttrib.make(ColorBlendAttrib.MAdd, ColorBlendAttrib.OOne, ColorBlendAttrib.OOne))
                pass
            elif loadedFrame.blendMode == "linear-dodge":
                nodePath.setAttrib(ColorBlendAttrib.make(ColorBlendAttrib.MAdd, ColorBlendAttrib.OOne, ColorBlendAttrib.OOneMinusIncomingColor))
                pass
            else: # Overwrite:
                nodePath.setAttrib(ColorBlendAttrib.make(ColorBlendAttrib.MAdd, ColorBlendAttrib.OIncomingAlpha, ColorBlendAttrib.OOneMinusIncomingAlpha))
                pass
            nodePath.setDepthTest(False)
            # Apply texture
            nodePath.setTexture(self.tex)
            # Apply translation, then rotation, then scaling to node.
            nodePath.setPos((loadedFrame.bound.X + loadedFrame.bound.Width / 2.0, 1, -loadedFrame.bound.Y - loadedFrame.bound.Height / 2.0))
            nodePath.setR(loadedFrame.rotationZ)
            nodePath.setScale(loadedFrame.scaleX, 1, loadedFrame.scaleY)
            nodePath.setTwoSided(True)
            self.consumedNodesList.append(nodePath)
            frameIndexForName = frameIndexForName + 1
        # Loop continues on through each frame called in the composite frame.
        pass