Пример #1
0
    def update(self):
        # print 'SPRITE ANIMATION UPDATE'
        # update frame
        self.current_texture += 1
        if self.current_texture == self.numtex:
            self.current_texture = 0

        t = self.textures[self.current_texture]

        # gnr is a tuple (see addAnimGeomRenderState() below)
        for gnr in self.anim_render_states:
            geom_node = gnr[0]
            geom_number = gnr[1]
            render_state = gnr[2]

            # geom_render_state = geom_node.getGeomState(geom_number)
            # print geom_render_state
            # attr = geom_render_state.getAttrib(26)  # attrib 26 is the texture attribute (hope this is static)
            # print attr
            # tex = attr.getTexture()

            # do the texture switch on the geom level by setting the TextureAttrib on its RenderState
            ta = TextureAttrib.make(t)
            new_state = render_state.setAttrib(
                ta, 1
            )  # potentialy needs passing "int override" (=1?) as second param
            geom_node.setGeomState(geom_number, new_state)
Пример #2
0
    def update(self):
        # print 'SPRITE ANIMATION UPDATE'
        # update frame
        self.current_texture += 1
        if self.current_texture == self.numtex:
            self.current_texture = 0
            
        t = self.textures[self.current_texture]

        # gnr is a tuple (see addAnimGeomRenderState() below)
        for gnr in self.anim_render_states:
            geom_node = gnr[0]
            geom_number = gnr[1]
            render_state = gnr[2]

            # geom_render_state = geom_node.getGeomState(geom_number)              
            # print geom_render_state
            # attr = geom_render_state.getAttrib(26)  # attrib 26 is the texture attribute (hope this is static)
            # print attr
            # tex = attr.getTexture()

            # do the texture switch on the geom level by setting the TextureAttrib on its RenderState
            ta = TextureAttrib.make(t)
            new_state = render_state.setAttrib(ta, 1) # potentialy needs passing "int override" (=1?) as second param          
            geom_node.setGeomState(geom_number, new_state)
Пример #3
0
 def setMaterial(self, mat):
     self.material.material = mat
     if mat:
         #self.state3D = self.state3D.setAttrib(BSPMaterialAttrib.make(mat.material))
         self.state3D = self.state3D.setAttrib(TextureAttrib.make(mat.material))
         #if mat.material.hasKeyvalue("$translucent") and bool(int(mat.material.getKeyvalue("$translucent"))):
         #    self.state3D = self.state3D.setAttrib(TransparencyAttrib.make(TransparencyAttrib.MDual))
         if self.geom3D:
             self.solid.setFaceGeomState(self.geom3D, self.state3D)
Пример #4
0
 def gen_arc_left(self, left_side, radius, end_radius, orig_radius, arc, x3,
                  y3, z3, new_z1, new_z2, segment_shape):
     left_surface = self.surfaces[left_side["surface"]]
     start_width = left_side["start_width"]
     end_width = left_side["end_width"]
     left_section = geom.make_circle(
         self.cur_x1, self.cur_y1, self.cur_z1,
         self.cur_x1 + (x3 * start_width), self.cur_y1 + (y3 * start_width),
         self.cur_z1 + (z3 * start_width), radius + orig_radius,
         end_radius + orig_radius, arc, new_z1, new_z2, left_surface["len"],
         left_surface["width"], end_width, False)[0]
     tex_attr = TextureAttrib.make(left_surface["tex"])
     state = RenderState.make(tex_attr)
     self.snode.addGeom(left_section, state)
     self.mesh.addGeom(left_section)
     segment_shape.addGeom(left_section)
Пример #5
0
 def gen_arc_right(self, right_side, radius, end_radius, orig_radius, arc,
                   x3, y3, z3, new_z1, new_z2, segment_shape):
     right_surface = self.surfaces[right_side["surface"]]
     start_width = right_side["start_width"]
     end_width = right_side["end_width"]
     right_section = \
         geom.make_circle(self.cur_x2 - (x3 * start_width), self.cur_y2 - (y3 * start_width),
                          self.cur_z1 - (z3 * start_width),
                          self.cur_x2, self.cur_y2, self.cur_z2,
                          radius - orig_radius,
                          end_radius - orig_radius,
                          arc, new_z1, new_z2,
                          right_surface["len"], right_surface["width"], end_width, True)[0]
     tex_attr = TextureAttrib.make(right_surface["tex"])
     state = RenderState.make(tex_attr)
     self.snode.addGeom(right_section, state)
     self.mesh.addGeom(right_section)
     segment_shape.addGeom(right_section)
Пример #6
0
 def gen_str_right(self, segment, right_side, x3, y3, x4, y4, new_z2,
                   segment_shape):
     right_surface = self.surfaces[right_side["surface"]]
     start_width = right_side["start_width"]
     end_width = right_side["end_width"]
     right_section = geom.make_square(
         self.cur_x2, self.cur_y2, self.cur_z2,
         self.cur_x2 - (x4 * start_width), self.cur_y2 - (y4 * start_width),
         self.cur_z2,
         self.cur_x2 + (x3 * segment["length"]) - (x4 * end_width),
         self.cur_y2 + (y3 * segment["length"]) - (y4 * end_width), new_z2,
         self.cur_x2 + (x3 * segment["length"]),
         self.cur_y2 + (y3 * segment["length"]), new_z2,
         right_surface["len"], right_surface["width"])
     tex_attr = TextureAttrib.make(right_surface["tex"])
     state = RenderState.make(tex_attr)
     self.snode.addGeom(right_section, state)
     self.mesh.addGeom(right_section)
     segment_shape.addGeom(right_section)
Пример #7
0
 def gen_str_left(self, segment, left_side, x3, y3, x4, y4, z4, new_z1,
                  segment_shape):
     left_surface = self.surfaces[left_side["surface"]]
     start_width = left_side["start_width"]
     end_width = left_side["end_width"]
     left_section = geom.make_square(
         self.cur_x1 + (x4 * start_width), self.cur_y1 + (y4 * start_width),
         self.cur_z1 + (z4 * start_width), self.cur_x1, self.cur_y1,
         self.cur_z1, self.cur_x1 + (x3 * segment["length"]),
         self.cur_y1 + (y3 * segment["length"]), new_z1,
         self.cur_x1 + (x3 * segment["length"]) + (x4 * end_width),
         self.cur_y1 + (y3 * segment["length"]) + (y4 * end_width),
         new_z1 + (z4 * end_width), left_surface["len"],
         left_surface["width"])
     tex_attr = TextureAttrib.make(left_surface["tex"])
     state = RenderState.make(tex_attr)
     self.snode.addGeom(left_section, state)
     self.mesh.addGeom(left_section)
     segment_shape.addGeom(left_section)
Пример #8
0
    def __init__(self, base):
        # Load texture
        tex = Loader(base).loadTexture((Path(path.realpath(__file__)).parent.parent.parent / "res/images/checkerboard.png").absolute())
        tex.setMagfilter(SamplerState.FT_nearest)
        tex.setMinfilter(SamplerState.FT_nearest)

        # Set up vertex data
        vdata = GeomVertexData("floor_data", GeomVertexFormat.get_v3t2(), Geom.UHStatic)
        vdata.setNumRows(6)
        vertex = GeomVertexWriter(vdata, "vertex")
        texcoord = GeomVertexWriter(vdata, "texcoord")

        vertex.addData3(-5, -5, 0)
        texcoord.addData3(0, 0, 0)
        vertex.addData3(-5, 5, 0)
        texcoord.addData3(0, 10, 0)
        vertex.addData3(5, 5, 0)
        texcoord.addData3(10, 10, 0)

        vertex.addData3(5, 5, 0)
        texcoord.addData3(10, 10, 0)
        vertex.addData3(5, -5, 0)
        texcoord.addData3(10, 0, 0)
        vertex.addData3(-5, -5, 0)
        texcoord.addData3(0, 0, 0)

        # Create primitive
        prim = GeomTriangles(Geom.UHStatic)
        prim.addVertices(0, 1, 2)
        prim.addVertices(3, 4, 5)
        geom = Geom(vdata)
        geom.add_primitive(prim)

        # Initialize geometry node
        GeomNode.__init__(self, "floor")
        attrib = TextureAttrib.make(tex)
        state = RenderState.make(attrib)
        self.addGeom(geom, state)
Пример #9
0
    def gen_segments(self):
        i = 0
        for segment in self.track_data["segments"]:
            seg_type = segment["type"]
            surface = self.surfaces[segment["surface"]]
            gradient = segment.get("grade")
            gradient = gradient if gradient is not None else 0

            segment_mesh = BulletTriangleMesh()

            if seg_type == "str":
                section = self.gen_str_segment(segment, surface, gradient,
                                               segment_mesh)
            elif seg_type == "arc":
                section = self.gen_arc_segment(segment, surface, gradient,
                                               segment_mesh)
            else:
                continue

            tex_attr = TextureAttrib.make(surface["tex"])
            state = RenderState.make(tex_attr)
            self.snode.addGeom(section, state)
            self.mesh.addGeom(section)
            segment_mesh.addGeom(section)

            segment_shape = BulletTriangleMeshShape(segment_mesh,
                                                    dynamic=False)
            segment_ghost = render.attachNewNode(
                BulletGhostNode(f'track_segment_{i}'))
            segment_ghost.node().addShape(segment_shape)
            self.world.attachGhost(segment_ghost.node())
            segment_ghost.setTwoSided(True)

            self.segments.append(segment_ghost)

            i += 1
Пример #10
0
def getColorAttributesFromModel(model):
    
    # Calculate the net transformation
    transform = model.getNetTransform()
    transformMat = transform.getMat()
    
    areas = []
    rgbColors = []
    textures = []
    transparencies = []
    for nodePath in model.findAllMatches('**/+GeomNode'):
        geomNode = nodePath.node()
        
        for n in range(geomNode.getNumGeoms()):
            state = geomNode.getGeomState(n)
        
            geom = geomNode.getGeom(n)
            area = getSurfaceAreaFromGeom(geom, transformMat)
        
            if state.hasAttrib(TextureAttrib.getClassType()):
                # Get color from texture
                texAttr = state.getAttrib(TextureAttrib.getClassType())
                tex = texAttr.getTexture()
                
                # Load texture image from file and compute average color
                texFilename = str(tex.getFullpath())
                img = scipy.ndimage.imread(texFilename)

                texture = os.path.splitext(os.path.basename(texFilename))[0]
                
                #TODO: handle black-and-white and RGBA texture
                assert img.dtype == np.uint8
                assert img.ndim == 3 and img.shape[-1] == 3
                
                rgbColor = (np.mean(img, axis=(0,1)) / 255.0).tolist()

                rgbColors.append(rgbColor)
                transparencies.append(False)
                areas.append(area)
                textures.append(texture)

            elif state.hasAttrib(ColorAttrib.getClassType()):
                colorAttr = state.getAttrib(ColorAttrib.getClassType())
                
                if (colorAttr.getColorType() == ColorAttrib.TFlat or colorAttr.getColorType() == ColorAttrib.TOff):
                    # Get flat color
                    color = colorAttr.getColor()
                    
                    isTransparent = False
                    if isinstance(color, LVecBase4f):
                        rgbColor= [color[0], color[1], color[2]]
                        alpha = color[3]
                        
                        if state.hasAttrib(TransparencyAttrib.getClassType()):
                            transAttr = state.getAttrib(TransparencyAttrib.getClassType())
                            if transAttr.getMode() != TransparencyAttrib.MNone and alpha < 1.0:
                                isTransparent = True
                        elif alpha < 1.0:
                            isTransparent = True
                            
                    elif isinstance(color, LVecBase3f):
                        rgbColor= [color[0], color[1], color[2]]
                    else:
                        raise Exception('Unsupported color class type: %s' % (color.__class__.__name__))
                
                    rgbColors.append(rgbColor)
                    transparencies.append(isTransparent)
                    areas.append(area)
                    textures.append(None)
                
                else:
                    # Get colors from vertex data
                    verAreas, verRgbColors, vertransparencies = getColorAttributesFromVertexData(geom, transformMat)
                    areas.extend(verAreas)
                    rgbColors.extend(verRgbColors)
                    transparencies.extend(vertransparencies)
                    textures.extend([None,]*len(vertransparencies))
            
    areas = np.array(areas)
    areas /= np.sum(areas)
            
    return areas, rgbColors, transparencies, textures
Пример #11
0
def getStateFromMaterial(prim_material, texture_cache, col_inst=None):
    state = RenderState.makeEmpty()

    mat = Material()
    texattr = TextureAttrib.makeAllOff()

    hasDiffuse = False
    if prim_material and prim_material.effect:

        diffuse = getattr(prim_material.effect, 'diffuse', None)
        transparent = getattr(prim_material.effect, 'transparent', None)
        if isinstance(diffuse, collada.material.Map) and isinstance(
                transparent, collada.material.Map):
            if diffuse.sampler.surface.image == transparent.sampler.surface.image:
                #some exporters put the same map in the diffuse channel
                # and the transparent channel when they don't really mean to
                transparent = None

        if isinstance(diffuse, collada.material.Map) or isinstance(
                transparent, collada.material.Map):
            diffuseMap = None
            transparentMap = None
            diffuseInitColor = None
            if isinstance(diffuse, collada.material.Map):
                diffuseMap = diffuse
            else:
                diffuseInitColor = v4fromtuple(diffuse)
            if isinstance(transparent, collada.material.Map):
                transparentMap = transparent
            if diffuseMap == transparentMap:
                transparentMap = None

            diffuseTexture = getTexture(color=diffuseMap,
                                        alpha=transparentMap,
                                        texture_cache=texture_cache,
                                        diffuseinit=diffuseInitColor)
            texattr = addTextureStage('tsDiff', TextureStage.MModulate,
                                      texattr, diffuseTexture)
            hasDiffuse = True

        if type(diffuse) is tuple:
            mat.setDiffuse(v4fromtuple(diffuse))

        # hack to look for sketchup version < 8 where transparency was exported flipped
        # also ColladaMaya v2.03b had this same issue
        flip_alpha = False
        if col_inst and col_inst.assetInfo:
            for contributor in col_inst.assetInfo.contributors:
                tool_name = contributor.authoring_tool
                if tool_name is None:
                    continue
                split = tool_name.split()
                if len(split) == 3 and \
                      split[0].strip().lower() == 'google' and \
                      split[1].strip().lower() == 'sketchup':
                    version = split[2].strip().split('.')
                    try:
                        major_version = int(version[0])
                        if major_version < 8:
                            flip_alpha = True
                    except (ValueError, TypeError):
                        continue

                try:
                    collada_maya_idx = split.index('ColladaMaya')
                    if split[collada_maya_idx + 1] == 'v2.03b':
                        flip_alpha = True
                except (ValueError, IndexError):
                    continue

        if type(transparent) is tuple:
            trR, trG, trB = transparent[0], transparent[1], transparent[2]
            trA = transparent[3] if len(transparent) > 3 else 1.0
        else:
            trR, trG, trB = 1.0, 1.0, 1.0
            trA = 1.0

        transparency = getattr(prim_material.effect, 'transparency', 1.0)
        if transparency is None:
            transparency = 1.0
        a_one = prim_material.effect.opaque_mode == collada.material.OPAQUE_MODE.A_ONE
        if a_one:
            alphaR = alphaG = alphaB = alphaA = transparency * trA
        else:
            alphaR = transparency * trR
            alphaG = transparency * trG
            alphaB = transparency * trB
            alphaA = luminance([trR, trG, trB])
            flip_alpha = not flip_alpha

        if flip_alpha:
            alphaR = 1.0 - alphaR
            alphaG = 1.0 - alphaG
            alphaB = 1.0 - alphaB
            alphaA = 1.0 - alphaA

        if alphaA < 1.0:
            state = state.addAttrib(
                ColorScaleAttrib.make(VBase4(alphaR, alphaG, alphaB, alphaA)))

        emission = getattr(prim_material.effect, 'emission', None)
        if isinstance(emission, collada.material.Map):
            emissionTexture = getTexture(alpha=emission,
                                         texture_cache=texture_cache)
            texattr = addTextureStage('tsEmiss', TextureStage.MGlow, texattr,
                                      emissionTexture)
        elif type(emission) is tuple:
            mat.setEmission(v4fromtuple(emission))

        ambient = getattr(prim_material.effect, 'ambient', None)
        if type(ambient) is tuple:
            mat.setAmbient(v4fromtuple(ambient))

        specular = getattr(prim_material.effect, 'specular', None)
        if isinstance(specular, collada.material.Map):
            specularTexture = getTexture(color=specular,
                                         texture_cache=texture_cache)
            texattr = addTextureStage('tsSpec', TextureStage.MGloss, texattr,
                                      specularTexture)
            mat.setSpecular(VBase4(0.1, 0.1, 0.1, 1.0))
        elif type(specular) is tuple:
            mat.setSpecular(v4fromtuple(specular))

        shininess = getattr(prim_material.effect, 'shininess', None)
        #this sets a sane value for blinn shading
        if shininess <= 1.0:
            if shininess < 0.01:
                shininess = 1.0
            shininess = shininess * 128.0
        mat.setShininess(shininess)

        bumpmap = getattr(prim_material.effect, 'bumpmap', None)
        if isinstance(bumpmap, collada.material.Map):
            bumpTexture = getTexture(color=bumpmap,
                                     texture_cache=texture_cache)
            texattr = addTextureStage('tsBump', TextureStage.MNormal, texattr,
                                      bumpTexture)

        if prim_material.effect.double_sided:
            state = state.addAttrib(
                CullFaceAttrib.make(CullFaceAttrib.MCullNone))

    if hasDiffuse:
        state = state.addAttrib(DepthOffsetAttrib.make(1))

    state = state.addAttrib(MaterialAttrib.make(mat))
    state = state.addAttrib(texattr)

    return state
Пример #12
0
    def gen_geom(self, mesh_json):
        # Create vertex format
        geom_array = GeomVertexArrayFormat()
        geom_array.add_column("vertex", 3, Geom.NTFloat32, Geom.CPoint)
        has_normals = False
        has_texcoords = False
        has_weights = False
        if "normals" in mesh_json:
            geom_array.add_column("normal", 3, Geom.NTFloat32, Geom.CNormal)
            has_normals = True
        if "texcoords" in mesh_json:
            geom_array.add_column("texcoord", 3, Geom.NTFloat32,
                                  Geom.CTexcoord)
            has_texcoords = True
        if "weights" in mesh_json:
            geom_array.add_column("joint", 4, Geom.NTUint8, Geom.CIndex)
            geom_array.add_column("weight", 4, Geom.NTFloat32, Geom.COther)
            has_weights = True
        geom_format = GeomVertexFormat()
        geom_format.add_array(geom_array)
        geom_format = GeomVertexFormat.register_format(geom_format)

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

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

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

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

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

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

            # Disable culling
            self.geom_path.node().setBounds(OmniBoundingVolume())
            self.geom_path.node().setFinal(True)
Пример #13
0
def getStateFromMaterial(prim_material, texture_cache, col_inst=None):
    state = RenderState.makeEmpty()
    
    mat = Material()
    texattr = TextureAttrib.makeAllOff()
    
    hasDiffuse = False
    if prim_material and prim_material.effect:
        
        diffuse = getattr(prim_material.effect, 'diffuse', None)
        transparent = getattr(prim_material.effect, 'transparent', None)
        if isinstance(diffuse, collada.material.Map) and isinstance(transparent, collada.material.Map):
            if diffuse.sampler.surface.image == transparent.sampler.surface.image:
                #some exporters put the same map in the diffuse channel
                # and the transparent channel when they don't really mean to
                transparent = None
        
        if isinstance(diffuse, collada.material.Map) or isinstance(transparent, collada.material.Map):
            diffuseMap = None
            transparentMap = None
            diffuseInitColor = None
            if isinstance(diffuse, collada.material.Map):
                diffuseMap = diffuse
            else:
                diffuseInitColor = v4fromtuple(diffuse)
            if isinstance(transparent, collada.material.Map):
                transparentMap = transparent
            if diffuseMap == transparentMap:
                transparentMap = None
                
            diffuseTexture = getTexture(color=diffuseMap, alpha=transparentMap, texture_cache=texture_cache, diffuseinit=diffuseInitColor)
            texattr = addTextureStage('tsDiff', TextureStage.MModulate, texattr, diffuseTexture)
            hasDiffuse = True

        if type(diffuse) is tuple:
            mat.setDiffuse(v4fromtuple(diffuse))
        
        # hack to look for sketchup version < 8 where transparency was exported flipped
        # also ColladaMaya v2.03b had this same issue
        flip_alpha = False
        if col_inst and col_inst.assetInfo:
            for contributor in col_inst.assetInfo.contributors:
                tool_name = contributor.authoring_tool
                if tool_name is None:
                    continue
                split = tool_name.split()
                if len(split) == 3 and \
                      split[0].strip().lower() == 'google' and \
                      split[1].strip().lower() == 'sketchup':
                    version = split[2].strip().split('.')
                    try:
                        major_version = int(version[0])
                        if major_version < 8:
                            flip_alpha = True
                    except (ValueError, TypeError):
                        continue
                    
                try:
                    collada_maya_idx = split.index('ColladaMaya')
                    if split[collada_maya_idx + 1] == 'v2.03b':
                        flip_alpha = True
                except (ValueError, IndexError):
                    continue
        
        if type(transparent) is tuple:
            trR, trG, trB = transparent[0], transparent[1], transparent[2]
            trA = transparent[3] if len(transparent) > 3 else 1.0
        else:
            trR, trG, trB = 1.0, 1.0, 1.0
            trA = 1.0
        
        transparency = getattr(prim_material.effect, 'transparency', 1.0)
        if transparency is None:
            transparency = 1.0
        a_one = prim_material.effect.opaque_mode == collada.material.OPAQUE_MODE.A_ONE
        if a_one:
            alphaR = alphaG = alphaB = alphaA = transparency * trA
        else:
            alphaR = transparency * trR
            alphaG = transparency * trG
            alphaB = transparency * trB
            alphaA = luminance([trR, trG, trB])
            flip_alpha = not flip_alpha
        
        if flip_alpha:
            alphaR = 1.0 - alphaR
            alphaG = 1.0 - alphaG
            alphaB = 1.0 - alphaB
            alphaA = 1.0 - alphaA
        
        if alphaA < 1.0:
            state = state.addAttrib(ColorScaleAttrib.make(VBase4(alphaR, alphaG, alphaB, alphaA)))
        
        emission = getattr(prim_material.effect, 'emission', None)
        if isinstance(emission, collada.material.Map):
            emissionTexture = getTexture(alpha=emission, texture_cache=texture_cache)
            texattr = addTextureStage('tsEmiss', TextureStage.MGlow, texattr, emissionTexture)
        elif type(emission) is tuple:
            mat.setEmission(v4fromtuple(emission))
        
        ambient = getattr(prim_material.effect, 'ambient', None)
        if type(ambient) is tuple:
            mat.setAmbient(v4fromtuple(ambient))
        
        specular = getattr(prim_material.effect, 'specular', None)
        if isinstance(specular, collada.material.Map):
            specularTexture = getTexture(color=specular, texture_cache=texture_cache)
            texattr = addTextureStage('tsSpec', TextureStage.MGloss, texattr, specularTexture)
            mat.setSpecular(VBase4(0.1, 0.1, 0.1, 1.0))
        elif type(specular) is tuple:
            mat.setSpecular(v4fromtuple(specular))

        shininess = getattr(prim_material.effect, 'shininess', None)
        #this sets a sane value for blinn shading
        if shininess <= 1.0:
            if shininess < 0.01:
                shininess = 1.0
            shininess = shininess * 128.0
        mat.setShininess(shininess)

        bumpmap = getattr(prim_material.effect, 'bumpmap', None)
        if isinstance(bumpmap, collada.material.Map):
            bumpTexture = getTexture(color=bumpmap, texture_cache=texture_cache)
            texattr = addTextureStage('tsBump', TextureStage.MNormal, texattr, bumpTexture)

        if prim_material.effect.double_sided:
            state = state.addAttrib(CullFaceAttrib.make(CullFaceAttrib.MCullNone))

    if hasDiffuse:
        state = state.addAttrib(DepthOffsetAttrib.make(1))
    
    state = state.addAttrib(MaterialAttrib.make(mat))
    state = state.addAttrib(texattr)
    
    return state
Пример #14
0
    def load(self):
        Entity.load(self)

        self.setPos(self.cEntity.getOrigin())
        self.setHpr(self.cEntity.getAngles())
        
        self.setColorScale(self.getEntityValueColor("_light") * 2, 1)
        
        self.hide(CIGlobals.ShadowCameraBitmask)
        
        beamAndHalo = loader.loadModel("phase_14/models/misc/light_beam_and_halo.bam")
        
        # Blend between halo and beam
        spotlightroot = self.attachNewNode('spotlightRoot')
        spotlightroot.setP(90)
        self.spotlight = beamAndHalo.find("**/beam")
        self.spotlight.setBillboardAxis()
        self.spotlight.reparentTo(spotlightroot)
        self.spotlight.setDepthWrite(False)
        
        ts = TextureStage('spotlight')
        ts.setMode(TextureStage.MAdd)
        state = self.spotlight.node().getGeomState(0)
        attr = TextureAttrib.make()
        attr = attr.addOnStage(ts, loader.loadTexture("phase_14/maps/glow_test02.png"), 1)
        state = state.setAttrib(attr)
        self.spotlight.node().setGeomState(0, state)
        
        self.halo = CIGlobals.makeSprite(
            "halo", loader.loadTexture("phase_14/maps/light_glow03.png"), 5, True)
        self.halo.reparentTo(self)
        
        beamAndHalo.removeNode()
        
        self.spotlightLength = self.getEntityValueFloat("SpotlightLength") / 16.0
        self.spotlightWidth = self.getEntityValueFloat("SpotlightWidth") / 16.0
        
        entPos = self.getPos()
        
        spotDir = self.getQuat().getForward()
        # User specified a max length, but clip that length so the spot effect doesn't appear to go through a floor or wall
        traceEnd = entPos + (spotDir * self.spotlightLength)
        endPos = self.bspLoader.clipLine(entPos, traceEnd)
        realLength = (endPos - entPos).length()
        self.spotlight.setSz(realLength)
        self.spotlight.setSx(self.spotlightWidth)
        
        self.spotlightDir = spotDir
        self.negSpotlightDir = -self.spotlightDir
        
        # Full beam, no halo
        self.setBeamHaloFactor(1.0)
        
        self.reparentTo(render)
        
        # Only update the spotlight if the object passes the Cull test.
        self.node().setFinal(True)
        clbk = CallbackNode('point_spotlight_callback')
        clbk.setCullCallback(CallbackObject.make(self.__spotlightThink))
        clbk.setBounds(BoundingSphere((0, 0, 0), 0))
        self.callback = self.attachNewNode(clbk)
        self.callback.hide(CIGlobals.ReflectionCameraBitmask)
        self.callback.hide(CIGlobals.ShadowCameraBitmask)
Пример #15
0
    def createBox(self):
        """
        Create the skybox GeomNode
        :return:
        """

        obj = ''
        obj += "# Skybox\n"
        obj += 'mtllib skybox.mtl\n'


        mtl = '# material for skybox\n'

        fmt = GeomVertexFormat.getV3n3t2()
        vdata = GeomVertexData('skybox', fmt, Geom.UHStatic)
        vdata.setNumRows(24)

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

        node = GeomNode('skybox')

        for normal in self.normals:
            geom = Geom(vdata)
            prim = GeomTriangles(Geom.UHStatic)

            idx = vertex.getWriteRow()

            verts = self.vertMappings[normal]
            tcs = self.getFaceMapping(normal)

            for v, t in zip(verts, tcs):
                vertex.addData3f(v[0]*2, v[1]*2, v[2]*2)
                normals.addData3f(normal)
                texcoord.addData2f(t)

                obj += 'v {0} {1} {2}\n'.format(v[0]*2, v[1]*2, v[2]*2)
                obj += 'vn {0} {1} {2}\n'.format(*normal)
                obj += 'vt {0} {1}\n'.format(*t)


            tex = self.getFaceTexture(normal)

            prim.addVertices(idx, idx + 1, idx + 3)
            prim.closePrimitive()

            obj += "usemtl {0}\n".format(tex.getName())
            obj += 'f {0}/{0} {1}/{1} {2}/{2}\n'.format(1+idx, 1+idx+1, 1+idx+3)

            prim.addVertices(idx + 1, idx + 2, idx + 3)
            prim.closePrimitive()

            obj += "usemtl {0}\n".format(tex.getName())
            obj += 'f {0}/{0} {1}/{1} {2}/{2}\n'.format(1+idx+1, 1+idx+2, 1+idx+3)

            geom.addPrimitive(prim)

            tex.setWrapU(Texture.WMMirror)
            tex.setWrapV(Texture.WMMirror)

            node.addGeom(geom, RenderState.make(TextureAttrib.make(tex)))


            mtl += "newmtl {0}\n".format(tex.getName())
            mtl += "Ka 1 1 1\n"
            mtl += "Kd 1 1 1\n"
            mtl += "map_Kd {0}\n".format(tex.getFilename().toOsSpecific())

        return node
Пример #16
0
def getStateFromMaterial(prim_material):
    state = RenderState.makeFullDefault()
    
    emission = None
    ambient = None
    diffuse = None
    specular = None
    shininess = None
    reflection = None
    reflectivity = None
    
    if prim_material:
        for prop in prim_material.supported:
            value = getattr(prim_material, prop)
            
            if value is None:
                continue
            
            if type(value) is tuple:
                val4 = value[3] if len(value) > 3 else 1.0
                value = VBase4(value[0], value[1], value[2], val4)
            
            if isinstance(value, collada.material.Map):
                texture_file = value.sampler.surface.image.path
                if not texture_file is None:
                    (root, leaf) = os.path.split(sys.argv[1])
                    tex_absolute = os.path.join(root, texture_file)
                    myImage = PNMImage()
                    myImage.read(Filename(tex_absolute))
                    myTexture = Texture(texture_file)
                    myTexture.load(myImage)
                    state = state.addAttrib(TextureAttrib.make(myTexture))
            elif prop == 'emission':
                emission = value
            elif prop == 'ambient':
                ambient = value
            elif prop == 'diffuse':
                diffuse = value
            elif prop == 'specular':
                specular = value
            elif prop == 'shininess':
                shininess = value
            elif prop == 'reflective':
                reflective = value
            elif prop == 'reflectivity':
                reflectivity = value
            elif prop == 'transparent':
                pass
            elif prop == 'transparency':
                pass
            else:
                raise
    
    mat = Material()
    
    if not emission is None:
        mat.setEmission(emission)
    if not ambient is None:
        mat.setAmbient(ambient)
    if not diffuse is None:
        mat.setDiffuse(diffuse)
    if not specular is None:
        mat.setSpecular(specular)
    if not shininess is None:
        mat.setShininess(shininess)
        
    state = state.addAttrib(MaterialAttrib.make(mat))
    return state