Esempio n. 1
0
 def __call__(self, inputs):
     """ inputs is the list of input values """
     scene = inputs[0]
     if scene:
         return (sg.Scene(scene), )
     else:
         return sg.Scene()
Esempio n. 2
0
def generic_vtk_read(reader, fname, split=True, **kwds):

    r = reader
    r.initialize(fname)
    mesh = r.outputs[0]

    points = mesh.points.to_array()
    polys = mesh.polys
    faces = polys.to_array()

    faces = faces.reshape((polys.number_of_cells, polys.max_cell_size + 1))
    indexList = faces[:, 1:]

    pts = points.tolist()

    scene = sg.Scene()

    scalars = mesh.point_data.scalars
    if scalars and split:
        scalars = scalars.to_array()
        dim = 1 if len(scalars.shape) == 1 else scalars.shape[-1]
        set_scalars = []
        if dim == 1:
            set_scalars = np.unique(scalars)
        elif dim in (3, 4):
            set_scalars = set(tuple(x) for x in scalars.tolist())

        leaf_index = 100
        for s in set_scalars:
            idx = None
            if dim == 1:
                idx = (scalars[indexList] == s).any(axis=1).nonzero()[0]
            elif dim in (3, 4):
                vertex_has_color = (scalars == s).all(axis=1)
                idx = vertex_has_color[indexList].any(axis=1).nonzero()[0]

            if len(idx) == 0:  #or s <= 99:
                continue
            my_faces = indexList[idx].tolist()
            tset = sg.FaceSet(pointList=pts, indexList=my_faces)
            color = np.random.randint(0, 255, 3).tolist() if dim == 1 else s
            shape = sg.Shape(tset, sg.Material(color))
            if dim == 1:
                shape.id = int(s)
            else:
                if s == (153, 102, 51):
                    shape.id = 1
                elif s == (0, 255, 255):
                    shape.id = 2
                else:
                    shape.id = leaf_index
                    leaf_index += 1
                if dim == 3 and s == (150, 150, 150):
                    continue
            scene.add(shape)
    else:
        tset = sg.FaceSet(pointList=pts, indexList=indexList.tolist())
        scene += tset

    return scene
Esempio n. 3
0
    def read(self, fname):
        """ read an ascii point file """
        import warnings
        pts = sg.Point3Array([])
        col = sg.Color4Array([])
        isptsfile = ('.pts' in fname)
        istxtfile = ('.txt' in fname)
        ispwnfile = ('.pwn' in fname)
        isxyzfile = ('.xyz' in fname)
        f = file(fname, "r")
        if isptsfile or ispwnfile:
            f.readline()  # skip line number
        i = 0
        lines = f.readlines()
        sep = None
        if not isxyzfile:
            if ';' in lines[0]: sep = ';'
            elif ',' in lines[0]: sep = ','
            elif '\t' in lines[0]: sep = '\t'

        for line in lines:
            if line[0] == '#': continue
            if sep != ',':
                line = line.replace(',', '.')
            values = line.split(sep)
            try:
                pts.append(
                    mt.Vector3(float(values[0]), float(values[1]),
                               float(values[2])))
                if len(values) > 3:
                    if not isptsfile and not istxtfile:
                        col.append(
                            sg.Color4(int(values[3]), int(values[4]),
                                      int(values[5]), 0))
                    else:
                        col.append(
                            sg.Color4(int(values[4]), int(values[5]),
                                      int(values[6]), 0))
            except Exception as e:
                if isptsfile and len(values) == 4:
                    #warnings.warn("Skip line "+str(i+isptsfile)+" in file '"+fname+"'.")
                    pass
                else:
                    if len(values) != 0:
                        warnings.warn("Error in file '" + fname +
                                      "' at line " + str(i + isptsfile))
                        raise e
            i += 1
        f.close()
        center = pts.getCenter()
        if len(col) == len(pts):
            pointset = sg.PointSet(pts, col)
        else:
            pointset = sg.PointSet(pts)
        pointset = sg.Translated(-center, pointset)
        sc = sg.Scene()
        sc += pointset
        return sc
Esempio n. 4
0
    def read(self, fname, split=True, *args):
        """ read a ply file """

        tag = 'header'  # element

        types = {}
        types['char'] = types['uchar'] = int
        types['short'] = types['ushort'] = types['int'] = types['uint'] = int
        types['float'] = types['double'] = float

        # define data
        vertices = []
        faces = []
        textures = []
        texture_files = []
        vertex_colours = []
        line = 0
        nb_vertices = 0
        nb_faces = 0
        elements = []
        properties = {}
        format = 'ascii'

        counter = 0
        # read the obj file
        with open(fname, "r") as f:
            l = f.readline().strip()
            if l != 'ply':
                return sg.Scene()
            for l in f:
                l = l.strip()
                fields = l.split()
                if not fields:
                    continue

                if tag == 'header':
                    key = fields[0]
                    if key == 'end_header':
                        tag_index = 0
                        tag = elements[tag_index]
                        continue
                    # format
                    elif key == 'format':
                        format = fields[1]
                    # comment
                    elif key == 'comment':
                        if fields[1] != 'TextureFile':
                            continue
                        else:
                            texture_files.append(fields[2])
                    elif key == 'element':
                        if fields[1] == 'vertex':
                            nb_vertices = int(fields[2])
                            elements.append('vertex')
                        elif fields[1] == 'face':
                            nb_faces = int(fields[2])
                            elements.append('face')
                    elif key == 'property':
                        name = elements[-1]
                        key = fields[-1]
                        _types = [fields[1]]
                        if fields[1] == 'list':
                            _types = fields[2:-1]
                        _types = [types[t] for t in _types]
                        properties.setdefault(name, []).append((key, _types))

                else:
                    counter += 1
                    p = properties[tag]

                    if tag == 'vertex':
                        v = []
                        i = 0
                        for t in p:
                            assert len(t[1]) <= 1
                            v.append(t[1][0](fields[i]))
                            i += 1
                        vertices.append(v[:3])
                        if len(v) >= 6.:  #if vertext colours exsist
                            vertex_colours.append(v[3:])
                        if counter == nb_vertices:
                            tag_index += 1
                            tag = elements[tag_index]
                            counter = 0

                    elif tag == 'face':
                        f = []
                        tex = []
                        vv = f
                        i = 0
                        for t in p:
                            if len(t[1]) == 1:
                                pass  #TODO
                            else:
                                # list
                                assert len(t[1]) == 2
                                name = t[0]
                                if name.startswith('vertex'):
                                    vv = f
                                elif name.startswith('tex'):
                                    vv = tex
                                else:
                                    print 'UNKNOWN property: ', name

                                n = t[1][0](fields[i])
                                i += 1
                                for j in range(n):
                                    vv.append(t[1][1](fields[i]))
                                    i += 1

                        if f:
                            faces.append(f)
                        if tex:
                            textures.append(tex)

                        if counter == nb_faces:
                            tag_index += 1
                            counter = 0

    # Build the scene
        scene = sg.Scene()
        tset = sg.FaceSet(pointList=vertices,
                          indexList=faces,
                          colorList=vertex_colours,
                          colorPerVertex=True)
        scene += tset

        return scene
Esempio n. 5
0
def load(fn):
    return list(scenegraph.Scene(fn))
Esempio n. 6
0
    def read(self,fname):
        """ read an ascii point file """
        
        import warnings
        import struct

        stream = file(fname,"r")
        header = stream.readline()
        assert header.strip() == 'ply'
        def nextline():
            line = stream.readline()
            while line.startswith('comment'):
                line = stream.readline()
            return line.strip()

        format = nextline()
        fkeyword, fcoding, fversion = format.split()
        fversion = float(fversion)
        assert fcoding in ['binary_little_endian','binary_big_endian','ascii']
        if fcoding != 'ascii':
            reversebytes = (fcoding.split('_')[1] != sys.byteorder)


        nline = nextline()
        spec = []
        asciitypes = { 'float' : float ,'int' : int , 'uchar' :int, 'char' : int, 'short' : int, 'ushort' : int, 'double' : float }
        unpacktypes = { 'float' : 'f' ,'int' : 'i', 'uchar' : 'B', 'char' : 'b', 'short' : 'h', 'ushort' : 'H', 'double' : 'd' }
        while nline != 'end_header':
            if nline.startswith('element'):
                elementkwd, elementname, elementnb = nline.split()
                spec.append((elementname, int(elementnb), []))
            elif nline.startswith('property'):
                propval = nline.split()
                if len(propval) == 3:
                    propkwd, proptype, propname = propval
                    spec[-1][2].append((propname,proptype))
                    assert proptype in unpacktypes
                elif len(propval) == 5:
                    propkwd, proplist, propsizetype, proptype, propname = propval
                    spec[-1][2].append((propname,(propsizetype,proptype)))
            nline = nextline()
        colorprops = []
        knowncolortypes = ['red','green','blue','diffuse_red','diffuse_green','diffuse_blue','alpha']
        if spec[0][0] == 'vertex':
            for propname, proptype in spec[0][2]:
                if propname in knowncolortypes:
                    colorprops .append(propname)
        if len(colorprops) == 0 : colorprops = None
        else : 
            colorprops.sort(cmp=lambda c1,c2:cmp(knowncolortypes.index(c1),knowncolortypes.index(c2)))
            assert len(colorprops) in [3,4]

        points = []
        colors = []
        faces = []
        for element in spec:
            elemname, elementnb, elemspec = element
            for ielem in range(elementnb):
                ielement = {}
                if fcoding == 'ascii':
                    linevalues = nextline().split()
                    itv = 0
                    for elemprop in elemspec:
                        propname,proptype = elemprop
                        if type(proptype) == tuple:
                            propsizetype, proptype = proptype
                            tr = asciitypes[propsizetype]
                            nbpropv = tr(linevalues[itv]) ; itv += 1
                            value = []
                            tr = asciitypes[proptype]
                            for ival in range(nbpropv):
                                value.append(tr(linevalues[itv])); itv += 1
                        else:
                            tr = asciitypes[proptype]
                            value = tr(linevalues[itv]); itv += 1
                        ielement[propname] = value
                else:
                    def readnextval(stream, ptype):
                        flag = unpacktypes[ptype]
                        psize = struct.calcsize(flag)
                        val = stream.read(psize)
                        if reversebytes:
                            val = ''.join(list(reversed(val)))
                        return struct.unpack(flag, val)[0]

                    for elemprop in elemspec:
                        propname,proptype = elemprop
                        if type(proptype) == tuple:
                            propsizetype, proptype = proptype
                            nbpropv = readnextval(stream, propsizetype)
                            value = []
                            for ival in range(nbpropv):
                                value.append(readnextval(stream, proptype))
                        else:
                            value = readnextval(stream, proptype)
                        ielement[propname] = value
                if elemname == 'vertex':
                    points.append((ielement['x'],ielement['y'],ielement['z']))
                    if colorprops:
                        val = [ielement[cni] for cni in colorprops]
                        if colorprops[3] == 'alpha':
                            val[3] = 255 - val[3]
                        else:
                            val.append(0)
                        colors.append(tuple(val))
                elif elemname == 'face':
                    faces.append(ielement['vertex_indices'])
        if colors == []: colors = None
        if len(faces) == 0:
            return sg.Scene([sg.Shape(sg.PointSet(points, colors))])
        else:
            return sg.Scene([sg.Shape(sg.FaceSet(points, faces, colorList=colors))])

#codec = PlyCodec()
#sg.SceneFactory.get().registerCodec(codec)
Esempio n. 7
0
 def scene(self, jsonrep):
     return sg.Scene(list(map(self.convert,jsonrep['data'])))
Esempio n. 8
0
 def read(self, fname):
     t = gtsread(fname)
     return sg.Scene([sg.Shape(t)])
Esempio n. 9
0
class AscCodec (sg.SceneCodec):
    """ Ascii Point File Format 

    """

    def __init__(self):
        """
        Initialisation of the codec info
        """
        sg.SceneCodec.__init__(self,"ASC",sg.SceneCodec.Mode.ReadWrite)

    def formats(self):
        """ return formats """
        return [ sg.SceneFormat("Asc Codec",["asc","pts","xyz","pwn",'txt'],"The Ascii point file format") ]
        # pts format :
        #         first line : nb of points 
        #          then x y z w r g b
        # pwn format :
        #         first line : nb of points 
        #          then x y z
        # asc format :
        #          lines : x y z [r g b]
        # xyz format :
        #          lines : x y z
    def read(self,fname):
        """ read an ascii point file """
        import warnings
        pts = sg.Point3Array([])
        col = sg.Color4Array([])
        isptsfile = ('.pts' in fname)
        ispwnfile = ('.pwn' in fname)
        f = file(fname,"r")
        if isptsfile or ispwnfile:
            f.readline() # skip line number
        i = 0
        lines = f.readlines()
        sep = None
        if ';' in lines[0]: sep = ';'
        elif ',' in lines[0]: sep = ','
        elif '\t' in lines[0]: sep = '\t'

        for line in lines:
            if line[0] == '#': continue
            values = line.split(sep)
            try:
                pts.append(mt.Vector3(float(values[0]),float(values[1]),float(values[2])))
                if len(values) > 3:
                    if not isptsfile : col.append(sg.Color4(int(values[3]),int(values[4]),int(values[5]),0))
                    else : col.append(sg.Color4(int(values[4]),int(values[5]),int(values[6]),0))
            except Exception,e:
                if isptsfile and len(values) == 4:
                    #warnings.warn("Skip line "+str(i+isptsfile)+" in file '"+fname+"'.")
                    pass
                else:
                    if len(values) != 0:
                        warnings.warn("Error in file '"+fname+"' at line "+str(i+isptsfile))
                        raise e
            i+=1
        f.close()
        center = pts.getCenter()
        if len(col) == len(pts) :
            pointset = sg.PointSet(pts,col)
        else:
            pointset = sg.PointSet(pts)
        pointset = sg.Translated(-center,pointset)
        sc = sg.Scene()
        sc += pointset
        return sc