Example #1
0
 def save(self):
     """Saves the light's properties back to :attr:`xmlnode`"""
     self.xmlnode.set('id', self.id)
     self.xmlnode.set('name', self.id)
     colornode = self.xmlnode.find('%s/%s/%s' % (tag('technique_common'),
         tag('directional'), tag('color')))
     colornode.text = ' '.join(map(str, self.color))
Example #2
0
    def load( collada, localscope, node ):
        indexnode = node.find(tag('p'))
        if indexnode is None: raise DaeIncompleteError('Missing index in polylist')
        vcountnode = node.find(tag('vcount'))
        if vcountnode is None: raise DaeIncompleteError('Missing vcount in polylist')

        try:
            if vcountnode.text is None:
                vcounts = numpy.array([], dtype=numpy.int32)
            else:
                vcounts = numpy.fromstring(vcountnode.text, dtype=numpy.int32, sep=' ')
            vcounts[numpy.isnan(vcounts)] = 0
        except ValueError as ex:
            raise DaeMalformedError('Corrupted vcounts in polylist')

        all_inputs = primitive.Primitive._getInputs(collada, localscope, node.findall(tag('input')))

        try:
            if indexnode.text is None:
                index = numpy.array([], dtype=numpy.int32)
            else:
                index = numpy.fromstring(indexnode.text, dtype=numpy.int32, sep=' ')
            index[numpy.isnan(index)] = 0
        except: raise DaeMalformedError('Corrupted index in polylist')

        polylist = Polylist(all_inputs, node.get('material'), index, vcounts, node)
        return polylist
Example #3
0
 def _loadShadingParam( collada, localscope, node ):
     """Load from the node a definition for a material property."""
     children = node.getchildren()
     if not children: raise DaeIncompleteError('Incorrect effect shading parameter '+node.tag)
     vnode = children[0]
     if vnode.tag == tag('color'):
         try:
             value = tuple([ float(v) for v in vnode.text.split() ])
         except ValueError as ex:
             raise DaeMalformedError('Corrupted color definition in effect '+id)
         except IndexError as ex:
             raise DaeMalformedError('Corrupted color definition in effect '+id)
     elif vnode.tag == tag('float'):
         try: value = float(vnode.text)
         except ValueError as ex:
             raise DaeMalformedError('Corrupted float definition in effect '+id)
     elif vnode.tag == tag('texture'):
         value = Map.load(collada, localscope, vnode)
     elif vnode.tag == tag('param'):
         refid = vnode.get('ref')
         if refid is not None and refid in localscope:
             value = localscope[refid]
         else:
             return None
     else:
         raise DaeUnsupportedError('Unknown shading param definition ' + \
                 vnode.tag)
     return value
Example #4
0
 def _loadShadingParam( collada, localscope, node ):
     """Load from the node a definition for a material property."""
     children = node.getchildren()
     if not children: raise DaeIncompleteError('Incorrect effect shading parameter '+node.tag)
     vnode = children[0]
     if vnode.tag == tag('color'):
         try:
             value = tuple([ float(v) for v in vnode.text.split() ])
         except ValueError as ex:
             raise DaeMalformedError('Corrupted color definition in effect '+id)
         except IndexError as ex:
             raise DaeMalformedError('Corrupted color definition in effect '+id)
     elif vnode.tag == tag('float'):
         try: value = float(vnode.text)
         except ValueError as ex:
             raise DaeMalformedError('Corrupted float definition in effect '+id)
     elif vnode.tag == tag('texture'):
         value = Map.load(collada, localscope, vnode)
     elif vnode.tag == tag('param'):
         refid = vnode.get('ref')
         if refid is not None and refid in localscope:
             value = localscope[refid]
         else:
             return None
     else:
         raise DaeUnsupportedError('Unknown shading param definition ' + \
                 vnode.tag)
     return value
Example #5
0
    def save(self):
        """Saves the geometry node back to :attr:`xmlnode`"""
        self.xmlnode.set('url', "#%s" % self.geometry.id)

        for m in self.materials:
            m.save()

        matparent = self.xmlnode.find(
            '%s/%s' % (tag('bind_material'), tag('technique_common')))
        if matparent is None and len(self.materials) == 0:
            return
        elif matparent is None:
            matparent = E.technique_common()
            self.xmlnode.append(E.bind_material(matparent))
        elif len(self.materials) == 0 and matparent is not None:
            bindnode = self.xmlnode.find('%s' % tag('bind_material'))
            self.xmlnode.remove(bindnode)
            return

        for m in self.materials:
            if m.xmlnode not in matparent:
                matparent.append(m.xmlnode)
        xmlnodes = [m.xmlnode for m in self.materials]
        for n in matparent:
            if n not in xmlnodes:
                matparent.remove(n)
Example #6
0
    def __init__(self, controller, materials, xmlnode=None):
        """Creates a controller node

        :param collada.controller.Controller controller:
          A controller to instantiate in the scene
        :param list materials:
          A list containing items of type :class:`collada.scene.MaterialNode`.
          Each of these represents a material that the controller should be
          bound to.
        :param xmlnode:
          When loaded, the xmlnode it comes from

        """
        self.controller = controller
        """ An object of type :class:`collada.controller.Controller` representing
        the controller being instantiated in the scene"""
        self.materials = materials
        """A list containing items of type :class:`collada.scene.MaterialNode`.
          Each of these represents a material that the controller is bound to."""
        if xmlnode != None:
            self.xmlnode = xmlnode
            """ElementTree representation of the controller node."""
        else:
            self.xmlnode = ElementTree.Element(tag('instance_controller'))
            bindnode = ElementTree.Element(tag('bind_material'))
            technode = ElementTree.Element(tag('technique_common'))
            bindnode.append(technode)
            self.xmlnode.append(bindnode)
            for mat in materials:
                technode.append(mat.xmlnode)
Example #7
0
    def load(collada, localscope, node):
        sourceid = node.get('id')
        arraynode = node.find(tag('float_array'))
        if arraynode is None:
            raise DaeIncompleteError('No float_array in source node')
        if arraynode.text is None:
            data = numpy.array([], dtype=numpy.float32)
        else:
            try:
                data = numpy.fromstring(arraynode.text,
                                        dtype=numpy.float32,
                                        sep=' ')
            except ValueError:
                raise DaeMalformedError('Corrupted float array')
        data[numpy.isnan(data)] = 0

        paramnodes = node.findall(
            '%s/%s/%s' %
            (tag('technique_common'), tag('accessor'), tag('param')))
        if not paramnodes:
            raise DaeIncompleteError('No accessor info in source node')
        components = [param.get('name') for param in paramnodes]
        if len(components
               ) == 2 and components[0] == 'U' and components[1] == 'V':
            #U,V is used for "generic" arguments - convert to S,T
            components = ['S', 'T']
        if len(components) == 3 and components[0] == 'S' and components[
                1] == 'T' and components[2] == 'P':
            components = ['S', 'T']
            data.shape = (-1, 3)
            #remove 3d texcoord dimension because we don't support it
            #TODO
            data = numpy.array(zip(data[:, 0], data[:, 1]))
            data.shape = (-1)
        return FloatSource(sourceid, data, tuple(components), xmlnode=node)
Example #8
0
    def save(self):
        """Saves the source back to :attr:`xmlnode`"""
        shape_in = self.data.shape
        self.data.shape = (-1,)

        txtdata = ' '.join(map(lambda x: '%.7g'%x , self.data.tolist()))

        rawlen = len( self.data )
        if len(self.components) == 1 and self.components[0]==None:	#no components provided 
            self.data.shape = shape_in
        else:
            self.data.shape = (-1, len(self.components) )
        acclen = len( self.data )
        node = self.xmlnode.find(tag('float_array'))
        node.text = txtdata
        node.set('count', str(rawlen))
        node.set('id', self.id+'-array' )
        node = self.xmlnode.find('%s/%s'%(tag('technique_common'), tag('accessor')))
        node.clear()
        node.set('count', str(acclen))
        node.set('source', '#'+self.id+'-array')
        if len(self.components) == 1 and self.components[0]==None:
            node.set('stride', str(rawlen/acclen))
            if shape_in[1::] == (4,4):
                node.append(E.param(type='float4x4'))
            else:
                node.append(E.param(type='float'))
        else:
            node.set('stride', str(len(self.components)))
            for c in self.components:
                node.append(E.param(type='float', name=c))
        self.xmlnode.set('id', self.id )
Example #9
0
    def load( collada, localscope, node ):
        sourceid = node.get('id')
        arraynode = node.find(tag('float_array'))
        if arraynode is None: raise DaeIncompleteError('No float_array in source node')
        if arraynode.text is None:
            data = numpy.array([], dtype=numpy.float32)
        else:
            try: data = numpy.fromstring(arraynode.text, dtype=numpy.float32, sep=' ')
            except ValueError: raise DaeMalformedError('Corrupted float array')
        data[numpy.isnan(data)] = 0

        paramnodes = node.findall('%s/%s/%s'%(tag('technique_common'), tag('accessor'), tag('param')))
        if not paramnodes: raise DaeIncompleteError('No accessor info in source node')
        components = [ param.get('name') for param in paramnodes ]
        if len(components) == 2 and components[0] == 'U' and components[1] == 'V':
            #U,V is used for "generic" arguments - convert to S,T
            components = ['S', 'T']
        if len(components) == 3 and components[0] == 'S' and components[1] == 'T' and components[2] == 'P':
            components = ['S', 'T']
            data.shape = (-1, 3)
            #remove 3d texcoord dimension because we don't support it
            #TODO
            data = numpy.array(zip(data[:,0], data[:,1]))
            data.shape = (-1)
        return FloatSource( sourceid, data, tuple(components), xmlnode=node )
Example #10
0
    def save(self):
        """Saves the geometry node back to :attr:`xmlnode`"""
        self.xmlnode.set('url', "#%s" % self.geometry.id)

        for m in self.materials:
            m.save()

        matparent = self.xmlnode.find('%s/%s'%( tag('bind_material'), tag('technique_common') ) )
        if matparent is None and len(self.materials)==0:
            return
        elif matparent is None:
            matparent = E.technique_common()
            self.xmlnode.append(E.bind_material(matparent))
        elif len(self.materials) == 0 and matparent is not None:
            bindnode = self.xmlnode.find('%s' % tag('bind_material'))
            self.xmlnode.remove(bindnode)
            return

        for m in self.materials:
            if m.xmlnode not in matparent:
                matparent.append(m.xmlnode)
        xmlnodes = [m.xmlnode for m in self.materials]
        for n in matparent:
            if n not in xmlnodes:
                matparent.remove(n)
Example #11
0
    def _create_anim_src_elem(anim_name, src_data, src_suffix, src_type, param_name, param_type):
        """"""
        idName = anim_name + "-" + src_suffix
        src_elem = E.source(id=idName)

        idName += "-array"
        count = len(src_data) / 16 if param_type == "float4x4" else len(src_data)

        if src_type == "float":
            str_src_data = " ".join([str(round(val, precision)) for val in src_data]) + " "
            str_src_data = str_src_data.replace(".0 ", " ")
        else:
            str_src_data = " ".join(map(str, src_data))
        src_elem.append(E(src_type + "_array", str_src_data, id=idName, count=str(count)))

        src_elem.append(
            E.technique_common(
                E.accessor(
                    E.param(name=param_name, type=param_type),  # accessor child
                    source="#" + idName,
                    count=str(count),  # accessor attribs
                )
            )
        )

        if param_type == "float4x4":
            src_elem.find(tag("technique_common")).find(tag("accessor")).set("stride", str(16))

        return src_elem
Example #12
0
    def _create_anim_src_elem(anim_name, src_data, src_suffix, src_type,
                              param_name, param_type):
        """"""
        idName = anim_name + "-" + src_suffix
        src_elem = E.source(id=idName)

        idName += "-array"
        count = len(src_data) / 16 if param_type == "float4x4" else len(
            src_data)

        if src_type == "float":
            str_src_data = " ".join(
                [str(round(val, precision)) for val in src_data]) + " "
            str_src_data = str_src_data.replace(".0 ", " ")
        else:
            str_src_data = " ".join(map(str, src_data))
        src_elem.append(
            E(src_type + "_array", str_src_data, id=idName, count=str(count)))

        src_elem.append(
            E.technique_common(
                E.accessor(
                    E.param(name=param_name, type=param_type),  #accessor child
                    source="#" + idName,
                    count=str(count)  #accessor attribs
                )))

        if param_type == "float4x4":
            src_elem.find(tag("technique_common")).find(tag("accessor")).set(
                "stride", str(16))

        return src_elem
Example #13
0
    def __init__(self, controller, materials, xmlnode=None):
        """Creates a controller node

        :param collada.controller.Controller controller:
          A controller to instantiate in the scene
        :param list materials:
          A list containing items of type :class:`collada.scene.MaterialNode`.
          Each of these represents a material that the controller should be
          bound to.
        :param xmlnode:
          When loaded, the xmlnode it comes from

        """
        self.controller = controller
        """ An object of type :class:`collada.controller.Controller` representing
        the controller being instantiated in the scene"""
        self.materials = materials
        """A list containing items of type :class:`collada.scene.MaterialNode`.
          Each of these represents a material that the controller is bound to."""
        if xmlnode != None:
            self.xmlnode = xmlnode
            """ElementTree representation of the controller node."""
        else:
            self.xmlnode = ElementTree.Element( tag('instance_controller') )
            bindnode = ElementTree.Element( tag('bind_material') )
            technode = ElementTree.Element( tag('technique_common') )
            bindnode.append( technode )
            self.xmlnode.append( bindnode )
            for mat in materials: technode.append( mat.xmlnode )
Example #14
0
    def load( collada, localscope, node ):
        indexnode = node.find(tag('p'))
        if indexnode is None: raise DaeIncompleteError('Missing index in polylist')
        vcountnode = node.find(tag('vcount'))
        if vcountnode is None: raise DaeIncompleteError('Missing vcount in polylist')

        try:
            if vcountnode.text is None:
                vcounts = numpy.array([], dtype=numpy.int32)
            else:
                vcounts = numpy.fromstring(vcountnode.text, dtype=numpy.int32, sep=' ')
            vcounts[numpy.isnan(vcounts)] = 0
        except ValueError as ex:
            raise DaeMalformedError('Corrupted vcounts in polylist')

        all_inputs = primitive.Primitive._getInputs(collada, localscope, node.findall(tag('input')))

        try:
            if indexnode.text is None:
                index = numpy.array([], dtype=numpy.int32)
            else:
                index = numpy.fromstring(indexnode.text, dtype=numpy.int32, sep=' ')
            index[numpy.isnan(index)] = 0
        except: raise DaeMalformedError('Corrupted index in polylist')

        polylist = Polylist(all_inputs, node.get('material'), index, vcounts, node)
        return polylist
Example #15
0
 def save(self):
     """Saves the light's properties back to :attr:`xmlnode`"""
     self.xmlnode.set('id', self.id)
     self.xmlnode.set('name', self.id)
     colornode = self.xmlnode.find(
         '%s/%s/%s' %
         (tag('technique_common'), tag('directional'), tag('color')))
     colornode.text = ' '.join(map(str, self.color))
Example #16
0
    def save(self):
        """Saves the collada document back to :attr:`xmlnode`"""
        libraries = [(self.geometries, 'library_geometries'),
                     (self.controllers, 'library_controllers'),
                     (self.lights, 'library_lights'),
                     (self.cameras, 'library_cameras'),
                     (self.images, 'library_images'),
                     (self.effects, 'library_effects'),
                     (self.materials, 'library_materials'),
                     (self.nodes, 'library_nodes'),
                     (self.scenes, 'library_visual_scenes')]

        self.assetInfo.save()
        assetnode = self.xmlnode.getroot().find(tag('asset'))
        if assetnode is not None:
            self.xmlnode.getroot().remove(assetnode)
        self.xmlnode.getroot().insert(0, self.assetInfo.xmlnode)

        library_loc = 0
        for i, node in enumerate(self.xmlnode.getroot()):
            if node.tag == tag('asset'):
                library_loc = i + 1

        for arr, name in libraries:
            node = self.xmlnode.find(tag(name))
            if node is None:
                if len(arr) == 0:
                    continue
                self.xmlnode.getroot().insert(library_loc, E(name))
                node = self.xmlnode.find(tag(name))
            elif node is not None and len(arr) == 0:
                self.xmlnode.getroot().remove(node)
                continue

            for o in arr:
                o.save()
                if o.xmlnode not in node:
                    node.append(o.xmlnode)
            xmlnodes = [o.xmlnode for o in arr]
            for n in node:
                if n not in xmlnodes:
                    node.remove(n)

        scenenode = self.xmlnode.find(tag('scene'))
        scenenode.clear()
        if self.scene is not None:
            sceneid = self.scene.id
            if sceneid not in self.scenes:
                raise DaeBrokenRefError('Default scene %s not found' % sceneid)
            scenenode.append(E.instance_visual_scene(url="#%s" % sceneid))

        if self.validator is not None:
            if not self.validator.validate(self.xmlnode):
                raise DaeSaveValidationError(
                    "Validation error when saving: " + self.validator.
                    COLLADA_SCHEMA_1_4_1_INSTANCE.error_log.last_error.message)
Example #17
0
    def save(self):
        """Saves the collada document back to :attr:`xmlnode`"""
        libraries = [(self.geometries, 'library_geometries'),
                     (self.controllers, 'library_controllers'),
                     (self.lights, 'library_lights'),
                     (self.cameras, 'library_cameras'),
                     (self.images, 'library_images'),
                     (self.effects, 'library_effects'),
                     (self.materials, 'library_materials'),
                     (self.nodes, 'library_nodes'),
                     (self.scenes, 'library_visual_scenes')]

        self.assetInfo.save()
        assetnode = self.xmlnode.getroot().find(tag('asset'))
        if assetnode is not None:
            self.xmlnode.getroot().replace(assetnode, self.assetInfo.xmlnode)
        else:
            self.xmlnode.getroot().insert(0, self.assetInfo.xmlnode)

        library_loc = 0
        for i, node in enumerate(self.xmlnode.getroot()):
            if node.tag == tag('asset'):
                library_loc = i+1

        for arr, name in libraries:
            node = self.xmlnode.find( tag(name) )
            if node is None:
                if len(arr) == 0:
                    continue
                self.xmlnode.getroot().insert(library_loc, E(name))
                node = self.xmlnode.find( tag(name) )
            elif node is not None and len(arr) == 0:
                self.xmlnode.getroot().remove(node)
                continue

            for o in arr:
                o.save()
                if o.xmlnode not in node:
                    node.append(o.xmlnode)
            xmlnodes = [o.xmlnode for o in arr]
            for n in node:
                if n not in xmlnodes:
                    node.remove(n)

        scenenode = self.xmlnode.find(tag('scene'))
        scenenode.clear()
        if self.scene is not None:
            sceneid = self.scene.id
            if sceneid not in self.scenes:
                raise DaeBrokenRefError('Default scene %s not found' % sceneid)
            scenenode.append(E.instance_visual_scene(url="#%s" % sceneid))

        if self.validator is not None:
            if not self.validator.validate(self.xmlnode):
                raise DaeSaveValidationError("Validation error when saving: " +
                        schema.COLLADA_SCHEMA_1_4_1_INSTANCE.error_log.last_error.message)
Example #18
0
 def load(collada, localscope, node):
     colornode = node.find( '%s/%s/%s'%(tag('technique_common'),tag('directional'),
                                        tag('color') ) )
     if colornode is None:
         raise DaeIncompleteError('Missing color for directional light')
     try:
         color = tuple([float(v) for v in colornode.text.split()])
     except ValueError as ex:
         raise DaeMalformedError('Corrupted color values in light definition')
     return DirectionalLight(node.get('id'), color, xmlnode = node)
Example #19
0
 def load( collada, node ):
     url = node.get('url')
     if not url.startswith('#'): raise DaeMalformedError('Invalid url in geometry instance %s' % url)
     geometry = collada.geometries.get(url[1:])
     if not geometry: raise DaeBrokenRefError('Geometry %s not found in library'%url)
     matnodes = node.findall('%s/%s/%s'%( tag('bind_material'), tag('technique_common'), tag('instance_material') ) )
     materials = []
     for matnode in matnodes:
         materials.append( MaterialNode.load(collada, matnode) )
     return GeometryNode( geometry, materials, xmlnode=node)
Example #20
0
 def load( collada, node ):
     url = node.get('url')
     if not url.startswith('#'): raise DaeMalformedError('Invalid url in controller instance %s' % url)
     controller = collada.controllers.get(url[1:])
     if not controller: raise DaeBrokenRefError('Controller %s not found in library'%url)
     matnodes = node.findall('%s/%s/%s'%( tag('bind_material'), tag('technique_common'), tag('instance_material') ) )
     materials = []
     for matnode in matnodes:
         materials.append( MaterialNode.load(collada, matnode) )
     return ControllerNode( controller, materials, xmlnode=node)
Example #21
0
 def load( collada, node ):
     url = node.get('url')
     if not url.startswith('#'): raise DaeMalformedError('Invalid url in controller instance %s' % url)
     controller = collada.controllers.get(url[1:])
     if not controller: raise DaeBrokenRefError('Controller %s not found in library'%url)
     matnodes = node.findall('%s/%s/%s'%( tag('bind_material'), tag('technique_common'), tag('instance_material') ) )
     materials = []
     for matnode in matnodes:
         materials.append( MaterialNode.load(collada, matnode) )
     return ControllerNode( controller, materials, xmlnode=node)
Example #22
0
 def load( collada, node ):
     url = node.get('url')
     if not url.startswith('#'): raise DaeMalformedError('Invalid url in geometry instance %s' % url)
     geometry = collada.geometries.get(url[1:])
     if not geometry: raise DaeBrokenRefError('Geometry %s not found in library'%url)
     matnodes = node.findall('%s/%s/%s'%( tag('bind_material'), tag('technique_common'), tag('instance_material') ) )
     materials = []
     for matnode in matnodes:
         materials.append( MaterialNode.load(collada, matnode) )
     return GeometryNode( geometry, materials, xmlnode=node)
Example #23
0
 def save(self):
     """Saves the light's properties back to :attr:`xmlnode`"""
     self.xmlnode.set('id', self.id)
     self.xmlnode.set('name', self.id)
     pnode = self.xmlnode.find( '%s/%s'%(tag('technique_common'), tag('point')) )
     colornode = pnode.find( tag('color') )
     colornode.text = ' '.join(map(str, self.color ) )
     _correctValInNode(pnode, 'constant_attenuation', self.constant_att)
     _correctValInNode(pnode, 'linear_attenuation', self.linear_att)
     _correctValInNode(pnode, 'quadratic_attenuation', self.quad_att)
     _correctValInNode(pnode, 'zfar', self.zfar)
Example #24
0
 def load(collada, localscope, node):
     tecnode = node.find('%s/%s' % (tag('optics'),tag('technique_common')))
     if tecnode is None or len(tecnode) == 0:
         raise DaeIncompleteError('Missing common technique in camera')
     camnode = tecnode[0]
     if camnode.tag == tag('perspective'):
         return PerspectiveCamera.load(collada, localscope, node)
     elif camnode.tag == tag('orthographic'):
         return OrthographicCamera.load(collada, localscope, node)
     else:
         raise DaeUnsupportedError('Unrecognized camera type: %s' % camnode.tag)
Example #25
0
 def save(self):
     """Saves the sampler data back to :attr:`xmlnode`"""
     samplernode = self.xmlnode.find(tag("sampler2D"))
     sourcenode = samplernode.find(tag("source"))
     if self.minfilter:
         minnode = samplernode.find(tag("minfilter"))
         minnode.text = self.minfilter
     if self.magfilter:
         maxnode = samplernode.find(tag("magfilter"))
         maxnode.text = self.magfilter
     sourcenode.text = self.surface.id
     self.xmlnode.set("sid", self.id)
Example #26
0
 def load(collada, localscope, node):
     tecnode = node.find('%s/%s' % (tag('optics'), tag('technique_common')))
     if tecnode is None or len(tecnode) == 0:
         raise DaeIncompleteError('Missing common technique in camera')
     camnode = tecnode[0]
     if camnode.tag == tag('perspective'):
         return PerspectiveCamera.load(collada, localscope, node)
     elif camnode.tag == tag('orthographic'):
         return OrthographicCamera.load(collada, localscope, node)
     else:
         raise DaeUnsupportedError('Unrecognized camera type: %s' %
                                   camnode.tag)
Example #27
0
 def save(self):
     """Saves the surface data back to :attr:`xmlnode`"""
     surfacenode = self.xmlnode.find( tag('surface') )
     initnode = surfacenode.find( tag('init_from') )
     if self.format:
         formatnode = surfacenode.find( tag('format') )
         if formatnode is None:
             surfacenode.append(E.format(self.format))
         else:
             formatnode.text = self.format
     initnode.text = self.image.id
     self.xmlnode.set('sid', self.id)
Example #28
0
 def save(self):
     """Saves the light's properties back to :attr:`xmlnode`"""
     self.xmlnode.set('id', self.id)
     self.xmlnode.set('name', self.id)
     pnode = self.xmlnode.find('%s/%s' %
                               (tag('technique_common'), tag('point')))
     colornode = pnode.find(tag('color'))
     colornode.text = ' '.join(map(str, self.color))
     _correctValInNode(pnode, 'constant_attenuation', self.constant_att)
     _correctValInNode(pnode, 'linear_attenuation', self.linear_att)
     _correctValInNode(pnode, 'quadratic_attenuation', self.quad_att)
     _correctValInNode(pnode, 'zfar', self.zfar)
Example #29
0
 def save(self):
     """Saves the sampler data back to :attr:`xmlnode`"""
     samplernode = self.xmlnode.find( tag('sampler2D') )
     sourcenode = samplernode.find( tag('source') )
     if self.minfilter:
         minnode = samplernode.find( tag('minfilter') )
         minnode.text = self.minfilter
     if self.magfilter:
         maxnode = samplernode.find( tag('magfilter') )
         maxnode.text = self.magfilter
     sourcenode.text = self.surface.id
     self.xmlnode.set('sid', self.id)
Example #30
0
 def save(self):
     """Saves the surface data back to :attr:`xmlnode`"""
     surfacenode = self.xmlnode.find( tag('surface') )
     initnode = surfacenode.find( tag('init_from') )
     if self.format:
         formatnode = surfacenode.find( tag('format') )
         if formatnode is None:
             surfacenode.append(E.format(self.format))
         else:
             formatnode.text = self.format
     initnode.text = self.image.id
     self.xmlnode.set('sid', self.id)
Example #31
0
 def load(collada, localscope, node):
     colornode = node.find(
         '%s/%s/%s' %
         (tag('technique_common'), tag('directional'), tag('color')))
     if colornode is None:
         raise DaeIncompleteError('Missing color for directional light')
     try:
         color = tuple([float(v) for v in colornode.text.split()])
     except ValueError as ex:
         raise DaeMalformedError(
             'Corrupted color values in light definition')
     return DirectionalLight(node.get('id'), color, xmlnode=node)
Example #32
0
 def save(self):
     """Saves the sampler data back to :attr:`xmlnode`"""
     samplernode = self.xmlnode.find( tag('sampler2D') )
     sourcenode = samplernode.find( tag('source') )
     if self.minfilter:
         minnode = samplernode.find( tag('minfilter') )
         minnode.text = self.minfilter
     if self.magfilter:
         maxnode = samplernode.find( tag('magfilter') )
         maxnode.text = self.magfilter
     sourcenode.text = self.surface.id
     self.xmlnode.set('sid', self.id)
Example #33
0
    def load(collada, localscope, morphnode, controllernode):
        baseid = morphnode.get('source')
        if len(baseid) < 2 or baseid[0] != '#' or \
                not baseid[1:] in collada.geometries:
            raise DaeBrokenRefError('Base source of morph %s not found' %
                                    baseid)
        basegeom = collada.geometries[baseid[1:]]

        method = morphnode.get('method')
        if method is None:
            method = 'NORMALIZED'
        if not (method == 'NORMALIZED' or method == 'RELATIVE'):
            raise DaeMalformedError(
                "Morph method must be either NORMALIZED or RELATIVE. Found '%s'"
                % method)

        inputnodes = morphnode.findall('%s/%s' %
                                       (tag('targets'), tag('input')))
        if inputnodes is None or len(inputnodes) < 2:
            raise DaeIncompleteError("Not enough inputs in a morph")

        try:
            inputs = [(i.get('semantic'), i.get('source')) for i in inputnodes]
        except ValueError as ex:
            raise DaeMalformedError('Corrupted inputs in morph')

        target_source = None
        weight_source = None
        for i in inputs:
            if len(i[1]) < 2 or i[1][0] != '#' or not i[1][1:] in localscope:
                raise DaeBrokenRefError('Input in morph node %s not found' %
                                        i[1])
            if i[0] == 'MORPH_TARGET':
                target_source = localscope[i[1][1:]]
            elif i[0] == 'MORPH_WEIGHT':
                weight_source = localscope[i[1][1:]]

        if not type(target_source) is source.IDRefSource or \
                not type(weight_source) is source.FloatSource:
            raise DaeIncompleteError("Not enough inputs in targets of morph")

        if len(target_source) != len(weight_source):
            raise DaeMalformedError("Morph inputs must be of same length")

        target_list = []
        for target, weight in zip(target_source, weight_source):
            if len(target) < 1 or not (target in collada.geometries):
                raise DaeBrokenRefError(
                    "Targeted geometry %s in morph not found" % target)
            target_list.append((collada.geometries[target], weight[0]))

        return Morph(basegeom, target_list, controllernode)
Example #34
0
 def _loadLights(self):
     """Load light library."""
     libnodes = self.xmlnode.findall(tag('library_lights'))
     if libnodes is not None:
         for libnode in libnodes:
             if libnode is not None:
                 for lightnode in libnode.findall(tag('light')):
                     try:
                         lig = light.Light.load(self, {}, lightnode)
                     except DaeError as ex:
                         self.handleError(ex)
                     else:
                         self.lights.append(lig)
Example #35
0
 def _loadCameras(self):
     """Load camera library."""
     libnodes = self.xmlnode.findall(tag('library_cameras'))
     if libnodes is not None:
         for libnode in libnodes:
             if libnode is not None:
                 for cameranode in libnode.findall(tag('camera')):
                     try:
                         cam = camera.Camera.load(self, {}, cameranode)
                     except DaeError as ex:
                         self.handleError(ex)
                     else:
                         self.cameras.append(cam)
Example #36
0
 def _loadImages(self):
     """Load image library."""
     libnodes = self.xmlnode.findall(tag('library_images'))
     if libnodes is not None:
         for libnode in libnodes:
             if libnode is not None:
                 for imgnode in libnode.findall(tag('image')):
                     try:
                         img = material.CImage.load(self, {}, imgnode)
                     except DaeError as ex:
                         self.handleError(ex)
                     else:
                         self.images.append(img)
Example #37
0
 def _loadMaterials(self):
     """Load material library."""
     libnodes = self.xmlnode.findall(tag('library_materials'))
     if libnodes is not None:
         for libnode in libnodes:
             if libnode is not None:
                 for materialnode in libnode.findall(tag('material')):
                     try:
                         mat = material.Material.load(self, {}, materialnode)
                     except DaeError as ex:
                         self.handleError(ex)
                     else:
                         self.materials.append(mat)
Example #38
0
 def _loadEffects(self):
     """Load effect library."""
     libnodes = self.xmlnode.findall(tag('library_effects'))
     if libnodes is not None:
         for libnode in libnodes:
             if libnode is not None:
                 for effectnode in libnode.findall(tag('effect')):
                     try:
                         effect = material.Effect.load(self, {}, effectnode)
                     except DaeError as ex:
                         self.handleError(ex)
                     else:
                         self.effects.append(effect)
Example #39
0
 def _loadImages(self):
     """Load image library."""
     libnodes = self.xmlnode.findall(tag('library_images'))
     if libnodes is not None:
         for libnode in libnodes:
             if libnode is not None:
                 for imgnode in libnode.findall(tag('image')):
                     try:
                         img = material.CImage.load(self, {}, imgnode)
                     except DaeError as ex:
                         self.handleError(ex)
                     else:
                         self.images.append(img)
Example #40
0
 def _loadCameras(self):
     """Load camera library."""
     libnodes = self.xmlnode.findall(tag('library_cameras'))
     if libnodes is not None:
         for libnode in libnodes:
             if libnode is not None:
                 for cameranode in libnode.findall(tag('camera')):
                     try:
                         cam = camera.Camera.load(self, {}, cameranode)
                     except DaeError as ex:
                         self.handleError(ex)
                     else:
                         self.cameras.append(cam)
Example #41
0
 def _loadEffects(self):
     """Load effect library."""
     libnodes = self.xmlnode.findall(tag('library_effects'))
     if libnodes is not None:
         for libnode in libnodes:
             if libnode is not None:
                 for effectnode in libnode.findall(tag('effect')):
                     try:
                         effect = material.Effect.load(self, {}, effectnode)
                     except DaeError as ex:
                         self.handleError(ex)
                     else:
                         self.effects.append(effect)
Example #42
0
 def _loadAnimations(self):
     """Load animation library."""
     libnodes = self.xmlnode.findall(tag('library_animations'))
     if libnodes is not None:
         for libnode in libnodes:
             if libnode is not None:
                 for animnode in libnode.findall(tag('animation')):
                     try:
                         A = animation.Animation.load(self, {}, animnode)
                     except DaeError as ex:
                         self.handleError(ex)
                     else:
                         self.animations.append(A)
Example #43
0
 def _loadDefaultScene(self):
     """Loads the default scene from <scene> tag in the root node."""
     node = self.xmlnode.find('%s/%s' % (tag('scene'), tag('instance_visual_scene')))
     try:
         if node != None:
             sceneid = node.get('url')
             if not sceneid.startswith('#'):
                 raise DaeMalformedError('Malformed default scene reference to %s: '%sceneid)
             self.scene = self.scenes.get(sceneid[1:])
             if not self.scene:
                 raise DaeBrokenRefError('Default scene %s not found' % sceneid)
     except DaeError as ex:
         self.handleError(ex)
Example #44
0
 def _loadScenes(self):
     """Load scene library."""
     libnodes = self.xmlnode.findall(tag('library_visual_scenes'))
     if libnodes is not None:
         for libnode in libnodes:
             if libnode is not None:
                 for scenenode in libnode.findall(tag('visual_scene')):
                     try:
                         S = scene.Scene.load(self, scenenode)
                     except DaeError as ex:
                         self.handleError(ex)
                     else:
                         self.scenes.append(S)
Example #45
0
 def _loadScenes(self):
     """Load scene library."""
     libnodes = self.xmlnode.findall(tag('library_visual_scenes'))
     if libnodes is not None:
         for libnode in libnodes:
             if libnode is not None:
                 for scenenode in libnode.findall(tag('visual_scene')):
                     try:
                         S = scene.Scene.load(self, scenenode)
                     except DaeError as ex:
                         self.handleError(ex)
                     else:
                         self.scenes.append(S)
Example #46
0
 def _loadDefaultScene(self):
     """Loads the default scene from <scene> tag in the root node."""
     node = self.xmlnode.find('%s/%s' % (tag('scene'), tag('instance_visual_scene')))
     try:
         if node != None:
             sceneid = node.get('url')
             if not sceneid.startswith('#'):
                 raise DaeMalformedError('Malformed default scene reference to %s: '%sceneid)
             self.scene = self.scenes.get(sceneid[1:])
             if not self.scene:
                 raise DaeBrokenRefError('Default scene %s not found' % sceneid)
     except DaeError as ex:
         self.handleError(ex)
Example #47
0
 def _loadAnimations(self):
     """Load animation library."""
     libnodes = self.xmlnode.findall(tag('library_animations'))
     if libnodes is not None:
         for libnode in libnodes:
             if libnode is not None:
                 for animnode in libnode.findall(tag('animation')):
                     try:
                         A = animation.Animation.load(self, {}, animnode)
                     except DaeError as ex:
                         self.handleError(ex)
                     else:
                         self.animations.append(A)
Example #48
0
 def _loadLights(self):
     """Load light library."""
     libnodes = self.xmlnode.findall(tag('library_lights'))
     if libnodes is not None:
         for libnode in libnodes:
             if libnode is not None:
                 for lightnode in libnode.findall(tag('light')):
                     try:
                         lig = light.Light.load(self, {}, lightnode)
                     except DaeError as ex:
                         self.handleError(ex)
                     else:
                         self.lights.append(lig)
Example #49
0
 def _loadMaterials(self):
     """Load material library."""
     libnodes = self.xmlnode.findall(tag('library_materials'))
     if libnodes is not None:
         for libnode in libnodes:
             if libnode is not None:
                 for materialnode in libnode.findall(tag('material')):
                     try:
                         mat = material.Material.load(self, {}, materialnode)
                     except DaeError as ex:
                         self.handleError(ex)
                     else:
                         self.materials.append(mat)
Example #50
0
 def load(collada, localscope, node):
     author = node.find( tag('author') )
     authoring_tool = node.find( tag('authoring_tool') )
     comments = node.find( tag('comments') )
     copyright = node.find( tag('copyright') )
     source_data = node.find( tag('source_data') )
     if author is not None: author = author.text
     if authoring_tool is not None: authoring_tool = authoring_tool.text
     if comments is not None: comments = comments.text
     if copyright is not None: copyright = copyright.text
     if source_data is not None: source_data = source_data.text
     return Contributor(author=author, authoring_tool=authoring_tool,
                        comments=comments, copyright=copyright, source_data=source_data, xmlnode=node)
Example #51
0
 def load(collada, localscope, node):
     pnode = node.find( '%s/%s'%(tag('technique_common'),tag('spot')) )
     colornode = pnode.find( tag('color') )
     if colornode is None:
         raise DaeIncompleteError('Missing color for spot light')
     try:
         color = tuple([float(v) for v in colornode.text.split()])
     except ValueError as ex:
         raise DaeMalformedError('Corrupted color values in spot light definition')
     constant_att = linear_att = quad_att = falloff_ang = falloff_exp = None
     cattnode = pnode.find( tag('constant_attenuation') )
     lattnode = pnode.find( tag('linear_attenuation') )
     qattnode = pnode.find( tag('quadratic_attenuation') )
     fangnode = pnode.find( tag('falloff_angle') )
     fexpnode = pnode.find( tag('falloff_exponent') )
     try:
         if cattnode is not None:
             constant_att = float(cattnode.text)
         if lattnode is not None:
             linear_att = float(lattnode.text)
         if qattnode is not None:
             quad_att = float(qattnode.text)
         if fangnode is not None:
             falloff_ang = float(fangnode.text)
         if fexpnode is not None:
             falloff_exp = float(fexpnode.text)
     except ValueError as ex:
         raise DaeMalformedError('Corrupted values in spot light definition')
     return SpotLight(node.get('id'), color, constant_att, linear_att,
             quad_att, falloff_ang, falloff_exp, xmlnode = node)
Example #52
0
 def load( collada, localscope, node ):
     sourceid = node.get('id')
     arraynode = node.find(tag('Name_array'))
     if arraynode is None: raise DaeIncompleteError('No Name_array in source node')
     if arraynode.text is None:
         values = []
     else:
         try: values = [v for v in arraynode.text.split()]
         except ValueError: raise DaeMalformedError('Corrupted Name array')
     data = numpy.array( values, dtype=numpy.unicode_ )
     paramnodes = node.findall('%s/%s/%s'%(tag('technique_common'), tag('accessor'), tag('param')))
     if not paramnodes: raise DaeIncompleteError('No accessor info in source node')
     components = [ param.get('name') for param in paramnodes ]
     return NameSource( sourceid, data, tuple(components), xmlnode=node )
Example #53
0
 def load( collada, localscope, node ):
     sourceid = node.get('id')
     arraynode = node.find(tag('Name_array'))
     if arraynode is None: raise DaeIncompleteError('No Name_array in source node')
     if arraynode.text is None:
         values = []
     else:
         try: values = [v for v in arraynode.text.split()]
         except ValueError: raise DaeMalformedError('Corrupted Name array')
     data = numpy.array( values, dtype=numpy.string_ )
     paramnodes = node.findall('%s/%s/%s'%(tag('technique_common'), tag('accessor'), tag('param')))
     if not paramnodes: raise DaeIncompleteError('No accessor info in source node')
     components = [ param.get('name') for param in paramnodes ]
     return NameSource( sourceid, data, tuple(components), xmlnode=node )
Example #54
0
    def load(collada, localscope, node):
        orthonode = node.find('%s/%s/%s' % (
            tag('optics'),
            tag('technique_common'),
            tag('orthographic')))

        if orthonode is None: raise DaeIncompleteError('Missing orthographic for camera definition')

        xmag = orthonode.find( tag('xmag') )
        ymag = orthonode.find( tag('ymag') )
        aspect_ratio = orthonode.find( tag('aspect_ratio') )
        znearnode = orthonode.find( tag('znear') )
        zfarnode = orthonode.find( tag('zfar') )
        id = node.get('id', '')

        try:
            if xmag is not None:
                xmag = float(xmag.text)
            if ymag is not None:
                ymag = float(ymag.text)
            if aspect_ratio is not None:
                aspect_ratio = float(aspect_ratio.text)
            znear = float(znearnode.text)
            zfar = float(zfarnode.text)
        except (TypeError, ValueError) as ex:
            raise DaeMalformedError('Corrupted float values in camera definition')

        #There are some exporters that incorrectly output all three of these.
        # Worse, they actually got the caculation of aspect_ratio wrong!
        # So instead of failing to load, let's just add one more hack because of terrible exporters
        if xmag is not None and ymag is not None and aspect_ratio is not None:
            aspect_ratio = None

        return OrthographicCamera(id, znear, zfar, xmag=xmag, ymag=ymag,
                aspect_ratio=aspect_ratio, xmlnode=node)
Example #55
0
 def load(collada, localscope, node):
     tecnode = node.find( tag('technique_common') )
     if tecnode is None or len(tecnode) == 0:
         raise DaeIncompleteError('Missing common technique in light')
     lightnode = tecnode[0]
     if lightnode.tag == tag('directional'):
         return DirectionalLight.load( collada, localscope, node )
     elif lightnode.tag == tag('point'):
         return PointLight.load( collada, localscope, node )
     elif lightnode.tag == tag('ambient'):
         return AmbientLight.load( collada, localscope, node )
     elif lightnode.tag == tag('spot'):
         return SpotLight.load( collada, localscope, node )
     else:
         raise DaeUnsupportedError('Unrecognized light type: %s'%lightnode.tag)
Example #56
0
 def _loadGeometry(self):
     """Load geometry library."""
     libnodes = self.xmlnode.findall(tag('library_geometries'))
     if libnodes is not None:
         for libnode in libnodes:
             if libnode is not None:
                 for geomnode in libnode.findall(tag('geometry')):
                     if geomnode.find(tag('mesh')) is None:
                         continue
                     try:
                         G = geometry.Geometry.load(self, {}, geomnode)
                     except DaeError as ex:
                         self.handleError(ex)
                     else:
                         self.geometries.append(G)
Example #57
0
    def load(collada, localscope, node):
        sourceid = node.get('id')
        arraynode = node.find(tag('float_array'))
        if not arraynode is None:
            return FloatSource.load(collada, localscope, node)

        arraynode = node.find(tag('IDREF_array'))
        if not arraynode is None:
            return IDRefSource.load(collada, localscope, node)

        arraynode = node.find(tag('Name_array'))
        if not arraynode is None:
            return NameSource.load(collada, localscope, node)

        if arraynode is None: raise DaeIncompleteError('No array found in source %s' % sourceid)
Example #58
0
    def load(collada, localscope, node):
        sourceid = node.get('id')
        arraynode = node.find(tag('float_array'))
        if not arraynode is None:
            return FloatSource.load(collada, localscope, node)

        arraynode = node.find(tag('IDREF_array'))
        if not arraynode is None:
            return IDRefSource.load(collada, localscope, node)

        arraynode = node.find(tag('Name_array'))
        if not arraynode is None:
            return NameSource.load(collada, localscope, node)

        if arraynode is None: raise DaeIncompleteError('No array found in source %s' % sourceid)
Example #59
0
 def load(collada, localscope, node):
     tecnode = node.find(tag('technique_common'))
     if tecnode is None or len(tecnode) == 0:
         raise DaeIncompleteError('Missing common technique in light')
     lightnode = tecnode[0]
     if lightnode.tag == tag('directional'):
         return DirectionalLight.load(collada, localscope, node)
     elif lightnode.tag == tag('point'):
         return PointLight.load(collada, localscope, node)
     elif lightnode.tag == tag('ambient'):
         return AmbientLight.load(collada, localscope, node)
     elif lightnode.tag == tag('spot'):
         return SpotLight.load(collada, localscope, node)
     else:
         raise DaeUnsupportedError('Unrecognized light type: %s' %
                                   lightnode.tag)
Example #60
0
 def save(self):
     """Saves the image back to :attr:`xmlnode`. Only the :attr:`id` attribute is saved.
     The image itself will have to be saved to its original source to make modifications."""
     self.xmlnode.set('id', self.id)
     self.xmlnode.set('name', self.id)
     initnode = self.xmlnode.find( tag('init_from') )
     initnode.text = self.path