コード例 #1
0
        def apply(self, mesh, filename):
            if os.path.exists(filename):
                raise FilterException("Specified mesh filename already exists")

            dotloc = filename.rfind('.')
            if dotloc == -1:
                mtlfilename = filename
            else:
                mtlfilename = filename[:dotloc]
            mtlfilename += '.mtl'
            if os.path.exists(mtlfilename):
                raise FilterException("Material filename already exists")

            # Handle materials first, iterating through all materials
            fmtl = open(mtlfilename, 'w')
            save_obj_util.write_mtl(mesh, fmtl, mtlfilename)
            fmtl.close()

            f = open(filename, 'w')
            rel_mtlfilename = os.path.relpath(mtlfilename,
                                              os.path.dirname(filename))
            save_obj_util.write_obj(mesh, rel_mtlfilename, f)
            f.close()

            return mesh
コード例 #2
0
 def apply(self, filename):
     if not os.path.isfile(filename):
         raise FilterException("argument is not a valid file")
     try:
         col = collada.Collada(filename)
     except collada.DaeError, e:
         print e
         raise FilterException("errors while loading file")
コード例 #3
0
        def apply(self, mesh, pm_file, percent):
            try:
                pmin = open(pm_file, 'r')
            except IOError:
                raise FilterException("Invalid pm file")

            try:
                percent = float(percent)
            except ValueError:
                percent = None

            if percent is None or percent < 0.0:
                raise FilterException("Invalid percentage")

            mesh = add_back_pm(mesh, pmin, percent)
            return mesh
コード例 #4
0
        def apply(self, mesh, filename):
            if os.path.exists(filename):
                raise FilterException("specified filename already exists")

            all_vertices, all_faces = self.aggregate_dae(mesh)

            outputfile = open(filename, "w")
            outputfile.write("ply\n")
            outputfile.write("format ascii 1.0\n")
            outputfile.write("element vertex %d\n" % len(all_vertices))
            outputfile.write("property float x\n")
            outputfile.write("property float y\n")
            outputfile.write("property float z\n")
            outputfile.write("element face %d\n" % len(all_faces))
            outputfile.write("property list uchar int vertex_indices\n")
            outputfile.write("end_header\n")

            for vertex in all_vertices:
                outputfile.write("%(v0)f %(v1)f %(v2)f\n" % {
                    'v0': vertex[0],
                    'v1': vertex[1],
                    'v2': vertex[2]
                })

            for face in all_faces:
                outputfile.write("3 %(v0)d %(v1)d %(v2)d\n" % {
                    'v0': face[0],
                    'v1': face[1],
                    'v2': face[2]
                })

            outputfile.close()
            return mesh
コード例 #5
0
    def apply(self, filename):
        if not os.path.isfile(filename):
            raise FilterException("argument is not a valid file")

        col = loadOBJ(open(filename, 'rb').read(),
                      aux_file_loader=filepath_loader(filename))

        return col
コード例 #6
0
 def apply(self, mesh, filename):
     if os.path.exists(filename):
         raise FilterException("specified filename already exists")
     bam_data = getBam(mesh, os.path.basename(filename))
     f = open(filename, 'wb')
     f.write(bam_data)
     f.close()
     return mesh
コード例 #7
0
 def apply(self, mesh, filename):
     if os.path.exists(filename):
         raise FilterException("specified filename already exists")
     
     generator = ThreeJSDictGenerator(mesh)
     generator.saveTo(filename)
     
     return mesh
コード例 #8
0
        def apply(self, mesh, filename, N, W, H):

            try:
                N = int(N)
            except ValueError:
                raise FilterException("Given value for N not a valid integer")
            if N < 1:
                raise FilterException("Given value for N not a valid integer")

            try:
                W = int(W)
            except ValueError:
                raise FilterException("Given value for W not a valid integer")
            if W < 1:
                raise FilterException("Given value for W not a valid integer")

            try:
                H = int(H)
            except ValueError:
                raise FilterException("Given value for H not a valid integer")
            if H < 1:
                raise FilterException("Given value for H not a valid integer")

            if os.path.exists(filename):
                raise FilterException("specified filename already exists")

            p3dApp = setupPandaApp(mesh)
            saveRotateScreenshots(p3dApp, filename, N, W, H)

            return mesh
コード例 #9
0
        def apply(self, mesh, pm_filename, mipmap_tarfilename):
            try:
                pm_filebuf = open(pm_filename,
                                  'r') if pm_filename != 'NONE' else None
            except IOError as ex:
                raise FilterException("Error opening pm file: %s" % str(ex))

            try:
                mipmap_tarfilebuf = open(mipmap_tarfilename, 'rb')
            except IOError as ex:
                raise FilterException("Error opening mipmap tar: %s" % str(ex))

            perceptualdiff = which('perceptualdiff')
            if perceptualdiff is None:
                raise FilterException(
                    "perceptualdiff exectuable not found on path")

            printPmPerceptualError(mesh, pm_filebuf, mipmap_tarfilebuf)
            return mesh
コード例 #10
0
        def apply(self, mesh, filename):
            if os.path.exists(filename):
                raise FilterException("specified filename already exists")

            json_data = badgerfish.to_json(mesh.xmlnode.getroot(), indent=4)
            f = open(filename, 'w')
            f.write(json_data)
            f.close()

            return mesh
コード例 #11
0
        def apply(self, mesh, filename):
            if os.path.exists(filename):
                raise FilterException("specified filename already exists")

            z = zipfile.ZipFile(filename, 'w', zipfile.ZIP_DEFLATED)

            basename = os.path.basename(filename)
            dotloc = basename.find('.')
            if dotloc == -1:
                dirname = basename
            else:
                dirname = basename[:dotloc]

            names_used = [dirname + '.obj']

            prev_written = []
            for cimg in mesh.images:
                img_data = cimg.data
                img_name = posixpath.basename(cimg.path)

                dotloc = img_name.find('.')
                if dotloc == -1:
                    base_img_name = img_name
                    img_ext = ''
                else:
                    base_img_name = img_name[:dotloc]
                    img_ext = img_name[dotloc:]

                while base_img_name + img_ext in names_used:
                    base_img_name = base_img_name + 'x'

                img_path = "%s/%s%s" % (dirname, base_img_name, img_ext)
                if img_path not in prev_written:
                    z.writestr(img_path, img_data)
                    prev_written.append(img_path)

                cimg.path = "./%s%s" % (base_img_name, img_ext)

            mtl_data = StringIO()
            save_obj_util.write_mtl(mesh, mtl_data)
            z.writestr("%s/%s.mtl" % (dirname, dirname), mtl_data.getvalue())
            mtl_data.close()

            obj_data = StringIO()
            save_obj_util.write_obj(mesh, "%s.mtl" % (dirname), obj_data)
            z.writestr("%s/%s.obj" % (dirname, dirname), obj_data.getvalue())
            obj_data.close()

            z.close()

            return mesh
コード例 #12
0
def write_obj(mesh, mtlfilename, f):
    """Write Wavefront OBJ contents of mesh to a file-like object."""

    f.write("mtllib %s\n" % mtlfilename)

    # Iterate through all primitives in each geometry instance
    vert_offset = 1
    norm_offset = 1
    tc_offset = 1
    for boundgeom in mesh.scene.objects('geometry'):
        f.write("# %s - %s\n" %
                (boundgeom.original.name, boundgeom.original.id))
        for boundprim in boundgeom.primitives():
            # Determine the properties of these primitives we're going
            # to use
            emit_normals = boundprim.normal is not None
            emit_texcoords = boundprim.texcoordset is not None and len(
                boundprim.texcoordset) > 0
            if emit_texcoords and len(boundprim.texcoordset) > 1:
                raise FilterException(
                    "OBJ only supports one texture coordinate set.")

            # Write transformed vertices, normals, texcoords
            f.write("\n".join([
                'v %.7g %.7g %.7g' % tuple(vert)
                for vert in boundprim.vertex.tolist()
            ]))
            f.write("\n")

            if emit_normals:
                f.write("\n".join([
                    'vn %.7g %.7g %.7g' % tuple(norm)
                    for norm in boundprim.normal.tolist()
                ]))
                f.write("\n")

            if emit_texcoords:
                f.write("\n".join([
                    'vt %.7g %.7g' % tuple(uv)
                    for uv in boundprim.texcoordset[0].tolist()
                ]))
                f.write("\n")

            # Start using the right material
            if boundprim.material:
                f.write("usemtl %s\n" % boundprim.material.id)

            if emit_normals and emit_texcoords:
                format_string = "f %d/%d/%d %d/%d/%d %d/%d/%d"
                index_iter = zip(boundprim.vertex_index + vert_offset,
                                 boundprim.texcoord_indexset[0] + tc_offset,
                                 boundprim.normal_index + norm_offset)
            elif emit_normals:
                format_string = "f %d//%d %d//%d %d//%d"
                index_iter = zip(boundprim.vertex_index + vert_offset,
                                 boundprim.normal_index + norm_offset)
            elif emit_texcoords:
                format_string = "f %d/%d %d/%d %d/%d"
                index_iter = zip(boundprim.vertex_index + vert_offset,
                                 boundprim.texcoord_indexset[0] + tc_offset)
            else:
                format_string = "f %d %d %d"
                index_iter = zip(boundprim.vertex_index + vert_offset)

            # Write transformed primitives
            f.write("\n".join([
                format_string % tuple(chain.from_iterable(list(zip(*idx))))
                for idx in index_iter
            ]))
            f.write("\n")

            # Finally, update offsets
            vert_offset += boundprim.vertex.shape[0]
            if emit_normals:
                norm_offset += boundprim.normal.shape[0]
            if emit_texcoords:
                tc_offset += boundprim.texcoordset[0].shape[0]

    f.write("\n")
コード例 #13
0
 def apply(self, mesh):
     succ = saveMipMaps(mesh)
     if not succ:
         raise FilterException('Failed to save mipmaps')
     return mesh
コード例 #14
0
def getMipMaps(mesh):

    mipmaps = {}
    for effect in mesh.effects:
        for prop in effect.supported:
            propval = getattr(effect, prop)
            if isinstance(propval, collada.material.Map):
                image_name = propval.sampler.surface.image.path
                image_data = propval.sampler.surface.image.data

                try:
                    im = Image.open(StringIO(image_data))
                    im.load()
                except IOError:
                    from panda3d.core import Texture
                    from panda3d.core import StringStream
                    from panda3d.core import PNMImage

                    #PIL failed, so lets try DDS reader with panda3d
                    t = Texture(image_name)
                    success = t.readDds(StringStream(image_data))
                    if success == 0:
                        raise FilterException("Failed to read image file %s" %
                                              image_name)

                    #convert DDS to PNG
                    outdata = t.getRamImageAs('RGBA').getData()
                    try:
                        im = Image.fromstring('RGBA',
                                              (t.getXSize(), t.getYSize()),
                                              outdata)
                        im.load()
                    except IOError:
                        raise FilterException("Failed to read image file %s" %
                                              image_name)

                #Keep JPG in same format since JPG->PNG is pretty bad
                if im.format == 'JPEG':
                    output_format = 'JPEG'
                    output_extension = 'jpg'
                    output_options = {'quality': 95, 'optimize': True}
                else:
                    output_format = 'PNG'
                    output_extension = 'png'
                    output_options = {'optimize': True}

                #store a copy to the original image so we can resize from it directly each time
                orig_im = im

                width, height = im.size

                #round down to power of 2
                width = int(math.pow(2, int(math.log(width, 2))))
                height = int(math.pow(2, int(math.log(height, 2))))

                pil_images = []

                while True:
                    im = orig_im.resize((width, height), Image.ANTIALIAS)
                    pil_images.insert(0, im)
                    if width == 1 and height == 1:
                        break
                    width = max(width / 2, 1)
                    height = max(height / 2, 1)

                tar_buf = StringIO()
                tar = tarfile.TarFile(fileobj=tar_buf, mode='w')

                cur_offset = 0
                byte_ranges = []
                for i, pil_img in enumerate(pil_images):
                    buf = StringIO()
                    pil_img.save(buf, output_format, **output_options)
                    file_len = buf.tell()
                    cur_name = '%dx%d.%s' % (pil_img.size[0], pil_img.size[1],
                                             output_extension)
                    tar_info = tarfile.TarInfo(name=cur_name)
                    tar_info.size = file_len
                    buf.seek(0)
                    tar.addfile(tarinfo=tar_info, fileobj=buf)

                    #tar files have a 512 byte header
                    cur_offset += 512
                    file_start = cur_offset

                    byte_ranges.append({
                        'offset': file_start,
                        'length': file_len,
                        'width': pil_img.size[0],
                        'height': pil_img.size[1]
                    })

                    #file lengths are rounded up to nearest 512 multiple
                    file_len = 512 * ((file_len + 512 - 1) / 512)
                    cur_offset += file_len

                tar.close()

                mipmaps[propval.sampler.surface.image.path] = (
                    tar_buf.getvalue(), byte_ranges)
    return mipmaps
コード例 #15
0
 def apply(self, mesh, filename):
     if os.path.exists(filename):
         raise FilterException("specified filename already exists")
     p3dApp = setupPandaApp(mesh)
     saveScreenshot(p3dApp, filename)
     return mesh