示例#1
0
def mapMaskSoft(dimensions = (1024, 1024), mesh = None):
    """
    Create a texture mask for the selected human (software renderer).
    """
    progress = Progress() (0)
    if mesh is None:
        mesh = G.app.selectedHuman.mesh

    W = dimensions[0]
    H = dimensions[1]

    components = 4
    dstImg = mh.Image(width=W, height=H, components=components)
    dstImg.data[...] = np.tile([0,0,0,255], (H,W)).reshape((H,W,components))

    faces = getFaces(mesh)

    coords = np.asarray([0,H])[None,None,:] + mesh.texco[mesh.fuvs[faces]] * np.asarray([W,-H])[None,None,:]
    shape = mesh.fvert[faces].shape
    shape = tuple(list(shape) + [components])
    colors = np.repeat(1, np.prod(shape)).reshape(shape)

    log.debug("mapMask: begin render")

    progress(0.1, 0.55)
    RasterizeTriangles(dstImg, coords[:,[0,1,2],:], MaskShader())
    progress(0.55, 0.99)
    RasterizeTriangles(dstImg, coords[:,[2,3,0],:], MaskShader())

    log.debug("mapMask: end render")

    progress.finish()
    return dstImg
示例#2
0
def mapMaskSoft(dimensions = (1024, 1024), mesh = None):
    """
    Create a texture mask for the selected human (software renderer).
    """
    progress = Progress() (0)
    if mesh is None:
        mesh = G.app.selectedHuman.mesh

    W = dimensions[0]
    H = dimensions[1]

    components = 4
    dstImg = mh.Image(width=W, height=H, components=components)
    dstImg.data[...] = np.tile([0,0,0,255], (H,W)).reshape((H,W,components))

    faces = getFaces(mesh)

    coords = np.asarray([0,H])[None,None,:] + mesh.texco[mesh.fuvs[faces]] * np.asarray([W,-H])[None,None,:]
    shape = mesh.fvert[faces].shape
    shape = tuple(list(shape) + [components])
    colors = np.repeat(1, np.prod(shape)).reshape(shape)

    log.debug("mapMask: begin render")

    progress(0.1, 0.55)
    RasterizeTriangles(dstImg, coords[:,[0,1,2],:], MaskShader())
    progress(0.55, 0.99)
    RasterizeTriangles(dstImg, coords[:,[2,3,0],:], MaskShader())

    log.debug("mapMask: end render")

    progress.finish()
    return dstImg
示例#3
0
 def generate(self, progress: Progress):
     with open(self._file, "w") as file:
         file.write("cpf\n")
         for e in self._elements:
             file.write("{0:011d}\n".format(e))
             progress.next()
     progress.finish()
示例#4
0
def mapImageSoft(srcImg, mesh, leftTop, rightBottom):
    progress = Progress() (0)
    dstImg = mh.Image(G.app.selectedHuman.getTexture())

    dstW = dstImg.width
    dstH = dstImg.height

    srcImg = srcImg.convert(dstImg.components)

    camera = getCamera(mesh)
    faces = getFaces(mesh)

    # log.debug('matrix: %s', G.app.modelCamera.getConvertToScreenMatrix())

    progress(0.05)
    texco = np.asarray([0,dstH])[None,None,:] + mesh.texco[mesh.fuvs[faces]] * np.asarray([dstW,-dstH])[None,None,:]
    matrix_ = np.asarray(G.app.modelCamera.getConvertToScreenMatrix(mesh))
    coord = np.concatenate((mesh.coord[mesh.fvert[faces]], np.ones((len(faces),4,1))), axis=-1)
    # log.debug('texco: %s, coord: %s', texco.shape, coord.shape)
    coord = np.sum(matrix_[None,None,:,:] * coord[:,:,None,:], axis = -1)
    # log.debug('coord: %s', coord.shape)
    coord = coord[:,:,:2] / coord[:,:,3:]
    progress(0.1)
    # log.debug('coord: %s', coord.shape)
    # log.debug('coords: %f-%f, %f-%f',
    #           np.amin(coord[...,0]), np.amax(coord[...,0]),
    #           np.amin(coord[...,1]), np.amax(coord[...,1]))
    # log.debug('rect: %s %s', leftTop, rightBottom)
    coord -= np.asarray([leftTop[0], leftTop[1]])[None,None,:]
    coord /= np.asarray([rightBottom[0] - leftTop[0], rightBottom[1] - leftTop[1]])[None,None,:]
    alpha = np.sum(mesh.vnorm[mesh.fvert[faces]] * camera[None,None,:], axis=-1)
    alpha = np.maximum(0, alpha)
    # alpha[...] = 1 # debug
    # log.debug('alpha: %s', alpha.shape)
    # log.debug('coords: %f-%f, %f-%f',
    #           np.amin(coord[...,0]), np.amax(coord[...,0]),
    #           np.amin(coord[...,1]), np.amax(coord[...,1]))
    progress(0.15)
    uva = np.concatenate((coord, alpha[...,None]), axis=-1)
    # log.debug('uva: %s', uva.shape)
    valid = np.any(alpha >= 0, axis=1)
    # log.debug('valid: %s', valid.shape)
    texco = texco[valid,:,:]
    uva = uva[valid,:,:]

    # log.debug('%s %s', texco.shape, uva.shape)
    # log.debug('src: %s, dst: %s', srcImg.data.shape, dstImg.data.shape)

    log.debug("mapImage: begin render")

    progress(0.2, 0.6)
    RasterizeTriangles(dstImg, texco[:,[0,1,2],:], UvAlphaShader(dstImg, srcImg, uva[:,[0,1,2],:]))
    progress(0.6, 0.99)
    RasterizeTriangles(dstImg, texco[:,[2,3,0],:], UvAlphaShader(dstImg, srcImg, uva[:,[2,3,0],:]))
    progress.finish()

    log.debug("mapImage: end render")

    return dstImg
示例#5
0
def mapImageSoft(srcImg, mesh, leftTop, rightBottom):
    progress = Progress() (0)
    dstImg = mh.Image(G.app.selectedHuman.getTexture())

    dstW = dstImg.width
    dstH = dstImg.height

    srcImg = srcImg.convert(dstImg.components)

    camera = getCamera(mesh)
    faces = getFaces(mesh)

    # log.debug('matrix: %s', G.app.modelCamera.getConvertToScreenMatrix())

    progress(0.05)
    texco = np.asarray([0,dstH])[None,None,:] + mesh.texco[mesh.fuvs[faces]] * np.asarray([dstW,-dstH])[None,None,:]
    matrix_ = np.asarray(G.app.modelCamera.getConvertToScreenMatrix(mesh))
    coord = np.concatenate((mesh.coord[mesh.fvert[faces]], np.ones((len(faces),4,1))), axis=-1)
    # log.debug('texco: %s, coord: %s', texco.shape, coord.shape)
    coord = np.sum(matrix_[None,None,:,:] * coord[:,:,None,:], axis = -1)
    # log.debug('coord: %s', coord.shape)
    coord = coord[:,:,:2] / coord[:,:,3:]
    progress(0.1)
    # log.debug('coord: %s', coord.shape)
    # log.debug('coords: %f-%f, %f-%f',
    #           np.amin(coord[...,0]), np.amax(coord[...,0]),
    #           np.amin(coord[...,1]), np.amax(coord[...,1]))
    # log.debug('rect: %s %s', leftTop, rightBottom)
    coord -= np.asarray([leftTop[0], leftTop[1]])[None,None,:]
    coord /= np.asarray([rightBottom[0] - leftTop[0], rightBottom[1] - leftTop[1]])[None,None,:]
    alpha = np.sum(mesh.vnorm[mesh.fvert[faces]] * camera[None,None,:], axis=-1)
    alpha = np.maximum(0, alpha)
    # alpha[...] = 1 # debug
    # log.debug('alpha: %s', alpha.shape)
    # log.debug('coords: %f-%f, %f-%f',
    #           np.amin(coord[...,0]), np.amax(coord[...,0]),
    #           np.amin(coord[...,1]), np.amax(coord[...,1]))
    progress(0.15)
    uva = np.concatenate((coord, alpha[...,None]), axis=-1)
    # log.debug('uva: %s', uva.shape)
    valid = np.any(alpha >= 0, axis=1)
    # log.debug('valid: %s', valid.shape)
    texco = texco[valid,:,:]
    uva = uva[valid,:,:]

    # log.debug('%s %s', texco.shape, uva.shape)
    # log.debug('src: %s, dst: %s', srcImg.data.shape, dstImg.data.shape)

    log.debug("mapImage: begin render")

    progress(0.2, 0.6)
    RasterizeTriangles(dstImg, texco[:,[0,1,2],:], UvAlphaShader(dstImg, srcImg, uva[:,[0,1,2],:]))
    progress(0.6, 0.99)
    RasterizeTriangles(dstImg, texco[:,[2,3,0],:], UvAlphaShader(dstImg, srcImg, uva[:,[2,3,0],:]))
    progress.finish()

    log.debug("mapImage: end render")

    return dstImg
示例#6
0
 def write(self, progress: Progress):
     with open(self._file, "w") as file:
         file.write("cpf,id,data\n")
         while self._record < self._records:
             buffer = self._fill_buffer()
             file.write("".join(buffer))
             progress.next(n=len(buffer))
         progress.finish()
示例#7
0
文件: builder.py 项目: ebak/xbuild
 def _buildInitialDepGraph(self, targets):
     '''Invoked by build().'''
     for target in targets:
         if not self._putToBuildQueue(target):
             errorf("BUILD FAILED! exitCode: {}", 1)
             if self.progressFn:
                 from progress import Progress
                 prg = Progress(1)
                 prg.finish(1)
                 self.progressFn(prg)
             return 1
     return 0
示例#8
0
def writeSkeletonFile(human, filepath, config):
    Pprogress = Progress(3)  # Parent.
    filename = os.path.basename(filepath)
    name = formatName(os.path.splitext(filename)[0])
    filename = name + ".skeleton.xml"
    filepath = os.path.join(os.path.dirname(filepath), filename)

    skel = human.getSkeleton()

    f = codecs.open(filepath, 'w', encoding="utf-8")
    lines = []

    lines.append('<?xml version="1.0" encoding="UTF-8"?>')
    lines.append('<!-- Exported from MakeHuman (www.makehuman.org) -->')
    lines.append('<skeleton>')
    lines.append('    <bones>')
    progress = Progress(len(skel.getBones()))
    for bIdx, bone in enumerate(skel.getBones()):
        pos = config.scale * bone.getRestOffset()
        if config.feetOnGround and not bone.parent:
            pos[1] += getFeetOnGroundOffset(config)
        lines.append('        <bone id="%s" name="%s">' % (bIdx, bone.name))
        lines.append('            <position x="%s" y="%s" z="%s" />' %
                     (pos[0], pos[1], pos[2]))
        lines.append('            <rotation angle="0">')
        lines.append('                <axis x="1" y="0" z="0" />')
        lines.append('            </rotation>')
        lines.append('        </bone>')
        progress.step()
    lines.append('    </bones>')
    Pprogress.step()

    lines.append('    <bonehierarchy>')
    progress = Progress(len(skel.getBones()))
    for bone in skel.getBones():
        if bone.parent:
            lines.append('        <boneparent bone="%s" parent="%s" />' %
                         (bone.name, bone.parent.name))
        progress.step()
    lines.append('    </bonehierarchy>')
    Pprogress.step()

    if hasattr(human, 'animations'):
        lines.append('    <animations>')
        for anim in human.animations:
            writeAnimation(human, lines, anim.getAnimationTrack())
        lines.append('    </animations>')

    lines.append('</skeleton>')

    f.write("\n".join(lines))
    f.close()
    Pprogress.finish()
示例#9
0
def mapLightingSoft(
        lightpos=(-10.99, 20.0, 20.0), mesh=None, res=(1024, 1024), border=1):
    """
    Create a lightmap for the selected human (software renderer).
    """
    progress = Progress()(0)

    if mesh is None:
        mesh = G.app.selectedHuman.mesh

    W = res[0]
    H = res[1]

    dstImg = mh.Image(width=W, height=H, components=4)
    dstImg.data[...] = 0

    delta = lightpos - mesh.coord
    ld = vnormalize(delta)
    del delta
    s = np.sum(ld * mesh.vnorm, axis=-1)
    del ld
    s = np.maximum(0, np.minimum(255, (s * 256))).astype(np.uint8)
    mesh.color[..., :3] = s[..., None]
    mesh.color[..., 3] = 255
    del s

    faces = getFaces(mesh)

    coords = np.asarray(
        [0, H])[None, None, :] + mesh.texco[mesh.fuvs[faces]] * np.asarray(
            [W, -H])[None, None, :]
    colors = mesh.color[mesh.fvert[faces]]
    # log.debug("mapLighting: %s %s %s", faces.shape, coords.shape, colors.shape)

    log.debug("mapLighting: begin render")

    progress(0.1, 0.5)
    RasterizeTriangles(dstImg, coords[:, [0, 1, 2], :],
                       ColorShader(colors[:, [0, 1, 2], :]))
    progress(0.5, 0.9)
    RasterizeTriangles(dstImg, coords[:, [2, 3, 0], :],
                       ColorShader(colors[:, [2, 3, 0], :]))

    progress(0.9, 0.99)
    dstImg = fixSeams(dstImg, mesh, border)

    log.debug("mapLighting: end render")

    mesh.setColor([255, 255, 255, 255])

    progress.finish()
    return dstImg
示例#10
0
def writeSkeletonFile(human, filepath, config):
    Pprogress = Progress(3)  # Parent.
    filename = os.path.basename(filepath)
    name = formatName(os.path.splitext(filename)[0])
    filename = name + ".skeleton.xml"
    filepath = os.path.join(os.path.dirname(filepath), filename)

    skel = human.getSkeleton()

    f = codecs.open(filepath, 'w', encoding="utf-8")
    lines = []

    lines.append('<?xml version="1.0" encoding="UTF-8"?>')
    lines.append('<!-- Exported from MakeHuman (www.makehuman.org) -->')
    lines.append('<skeleton>')
    lines.append('    <bones>')
    progress = Progress(len(skel.getBones()))
    for bIdx, bone in enumerate(skel.getBones()):
        pos = config.scale * bone.getRestOffset()
        if config.feetOnGround and not bone.parent:
            pos[1] += getFeetOnGroundOffset(config)
        lines.append('        <bone id="%s" name="%s">' % (bIdx, bone.name))
        lines.append('            <position x="%s" y="%s" z="%s" />' % (pos[0], pos[1], pos[2]))
        lines.append('            <rotation angle="0">')
        lines.append('                <axis x="1" y="0" z="0" />')
        lines.append('            </rotation>')
        lines.append('        </bone>')
        progress.step()
    lines.append('    </bones>')
    Pprogress.step()

    lines.append('    <bonehierarchy>')
    progress = Progress(len(skel.getBones()))
    for bone in skel.getBones():
        if bone.parent:
            lines.append('        <boneparent bone="%s" parent="%s" />' % (bone.name, bone.parent.name))
        progress.step()
    lines.append('    </bonehierarchy>')
    Pprogress.step()

    if hasattr(human, 'animations'):
        lines.append('    <animations>')
        for anim in human.animations:
            writeAnimation(human, lines, anim.getAnimationTrack())
        lines.append('    </animations>')

    lines.append('</skeleton>')

    f.write("\n".join(lines))
    f.close()
    Pprogress.finish()
示例#11
0
def mapLightingSoft(lightpos = (-10.99, 20.0, 20.0), mesh = None, res = (1024, 1024), border = 1):
    """
    Create a lightmap for the selected human (software renderer).
    """
    progress = Progress() (0)

    if mesh is None:
        mesh = G.app.selectedHuman.mesh

    W = res[0]
    H = res[1]

    dstImg = mh.Image(width=W, height=H, components=4)
    dstImg.data[...] = 0

    delta = lightpos - mesh.coord
    ld = vnormalize(delta)
    del delta
    s = np.sum(ld * mesh.vnorm, axis=-1)
    del ld
    s = np.maximum(0, np.minimum(255, (s * 256))).astype(np.uint8)
    mesh.color[...,:3] = s[...,None]
    mesh.color[...,3] = 255
    del s

    faces = getFaces(mesh)

    coords = np.asarray([0,H])[None,None,:] + mesh.texco[mesh.fuvs[faces]] * np.asarray([W,-H])[None,None,:]
    colors = mesh.color[mesh.fvert[faces]]
    # log.debug("mapLighting: %s %s %s", faces.shape, coords.shape, colors.shape)

    log.debug("mapLighting: begin render")

    progress(0.1, 0.5)
    RasterizeTriangles(dstImg, coords[:,[0,1,2],:], ColorShader(colors[:,[0,1,2],:]))
    progress(0.5, 0.9)
    RasterizeTriangles(dstImg, coords[:,[2,3,0],:], ColorShader(colors[:,[2,3,0],:]))

    progress(0.9, 0.99)
    dstImg = fixSeams(dstImg, mesh, border)

    log.debug("mapLighting: end render")

    mesh.setColor([255, 255, 255, 255])

    progress.finish()
    return dstImg
def stochastic_page_rank(graph, node, n_iter=1000000, n_steps=100):
    """Stochastic PageRank estimation

    Parameters:
    graph -- a graph object as returned by load_graph()
    n_iter (int) -- number of random walks performed
    n_steps (int) -- number of followed links before random walk is stopped

    Returns:
    A dict that assigns each page its hit frequency

    This function estimates the Page Rank by counting how frequently
    a random walk that starts on a random node will after n_steps end
    on each node of the given graph.
    """
    #create an empty dictionary
    Nodecount = {}
    prog = Progress(n_iter,
                    "Permforming stochastic page rank. This may take while"
                    )  #setting up progress bar
    for nodes in range(0, len(list(graph.nodes))):  #loop through all the nodes
        Nodecount[list(
            graph.nodes
        )[nodes]] = 0  #set each node in the dictionary with a value of 0
    for i in range(0, n_iter):
        prog += 1  #progress bar
        prog.show()
        node = randomnodechooser(graph)
        for x in range(
                0, n_steps
        ):  #loop for n amount of random links to follow per random node we start from
            RandomNodenumber = random.randint(0,
                                              int(len(graph.edges(node))) -
                                              1)  #seelect a random number
            # use random number to select a random index in the list of edges from the randomnode
            node = (list(graph.edges(node))[RandomNodenumber])[1]
        Nodecount[node] += (1 / n_iter
                            )  #Increase the finnally landed node by 1/n iter.
        ## The most common will be largest
    prog.finish()
    return Nodecount
def distribution_page_rank(graph, n_iter=100):
    """Probabilistic PageRank estimation

    Parameters:
    graph -- a graph object as returned by load_graph()
    n_iter (int) -- number of probability distribution updates

    Returns:
    A dict that assigns each page its probability to be reached

    This function estimates the Page Rank by iteratively calculating
    the probability that a random walker is currently on any node.
    """
    node_prob = {}  #create an empty dictionary
    prog = Progress(n_iter,
                    "Permforming distribution page rank. This may take while"
                    )  #set up progress bar
    for z in range(0, len(list(graph.nodes))):  #loop through each node
        # set each node in the dictionary with an equal value with 1/n amount of nodes
        node_prob[list(graph.nodes)[z]] = 1 / len(list(graph.nodes))
    for i in range(0, n_iter):  #loop n times
        prog += 1  #progress bar
        prog.show()
        next_prob = {}  #second dictionary
        for count in range(
                0, len(graph.nodes)
        ):  #set the second dictionary to all have default values of 0
            next_prob[list(graph.nodes)[count]] = 0
        for node in range(0, len((graph.nodes))):  #for each node in the graph
            Currentnode = list(graph.nodes)[node]
            # sets the probability to choose a node to 1/n the current nodes amount of edges
            p = node_prob[Currentnode] / len(graph.edges(Currentnode))
            for edges in range(0, len(graph.edges(Currentnode))
                               ):  #All edges probabilities are increaseed by p
                CurrentEdges = list(graph.edges(Currentnode))
                next_prob[CurrentEdges[edges][1]] += p
        node_prob = next_prob  #this optimises the algorithim and refutes it being thrown off by random chance
    prog.finish()
    return node_prob
示例#14
0
文件: buildqueue.py 项目: ebak/xbuild
 def start(self):
     if self.finished:
         raise NotImplementedError(
             "Builder instance can be used only once.")
     self.rc = 0
     if not len(self.sortedList):
         # if self.printUpToDate:
         cinfo(self.printInfo, "All targets are up-to-date. Nothing to do.")
         self.finished = True
         return
     self.workers = [Worker(self, i) for i in range(self.numWorkers)]
     try:
         for worker in self.workers:
             worker.start()
         for worker in self.workers:
             logger.debugf("Joining worker {}", worker.id)
             worker.join()
     # exception handling: progressFn have to be called with end marker
     finally:
         if self.progressFn:
             prg = Progress(self.numWorkers)
             prg.finish(self.rc)
             self.progressFn(prg)
示例#15
0
def Render(settings):
    progress = Progress.begin()

    if not mh.hasRenderToRenderbuffer():
        settings['dimensions'] = (G.windowWidth, G.windowHeight)

    if settings['lightmapSSS']:
        progress(0, 0.05, "Storing data")
        import material
        human = G.app.selectedHuman
        materialBackup = material.Material(human.material)

        progress(0.05, 0.1, "Projecting lightmaps")
        diffuse = imgop.Image(data=human.material.diffuseTexture)
        lmap = projection.mapSceneLighting(settings['scene'],
                                           border=human.material.sssRScale)
        progress(0.1, 0.4, "Applying medium scattering")
        lmapG = imgop.blurred(lmap, human.material.sssGScale, 13)
        progress(0.4, 0.7, "Applying high scattering")
        lmapR = imgop.blurred(lmap, human.material.sssRScale, 13)
        lmap = imgop.compose([lmapR, lmapG, lmap])
        if not diffuse.isEmpty:
            progress(0.7, 0.8, "Combining textures")
            lmap = imgop.resized(lmap,
                                 diffuse.width,
                                 diffuse.height,
                                 filter=image.FILTER_BILINEAR)
            progress(0.8, 0.9)
            lmap = imgop.multiply(lmap, diffuse)
        lmap.sourcePath = "Internal_Renderer_Lightmap_SSS_Texture"

        progress(0.9, 0.95, "Setting up renderer")
        human.material.diffuseTexture = lmap
        human.configureShading(diffuse=True)
        human.shadeless = True
        progress(0.95, 0.98, None)
    else:
        progress(0, 0.99, None)

    if not mh.hasRenderToRenderbuffer():
        # Limited fallback mode, read from screen buffer
        log.message("Fallback render: grab screen")
        img = mh.grabScreen(0, 0, G.windowWidth, G.windowHeight)
        alphaImg = None
    else:
        # Render to framebuffer object
        renderprog = Progress()
        renderprog(0, 0.99 - 0.59 * settings['AA'], "Rendering")
        width, height = settings['dimensions']
        log.message("Rendering at %sx%s", width, height)
        if settings['AA']:
            width = width * 2
            height = height * 2
        img = mh.renderToBuffer(width, height)
        alphaImg = mh.renderAlphaMask(width, height)
        img = imgop.addAlpha(img, imgop.getChannel(alphaImg, 0))

        if settings['AA']:
            renderprog(0.4, 0.99, "AntiAliasing")
            # Resize to 50% using bi-linear filtering
            img = img.resized(width / 2,
                              height / 2,
                              filter=image.FILTER_BILINEAR)
            # TODO still haven't figured out where components get swapped, but this hack appears to be necessary
            img.data[:, :, :] = img.data[:, :, (2, 1, 0, 3)]
        renderprog.finish()

    if settings['lightmapSSS']:
        progress(0.98, 0.99, "Restoring data")
        human.material = materialBackup

    progress(1, None, 'Rendering complete')

    gui3d.app.getCategory('Rendering').getTaskByName('Viewer').setImage(img)
    mh.changeTask('Rendering', 'Viewer')
    gui3d.app.statusPersist('Rendering complete')
示例#16
0
def exportStlAscii(filepath, config, exportJoints=False):
    """
    This function exports MakeHuman mesh to stereolithography ascii format.

    Parameters
    ----------

    human:
      *Human*.  The object whose information is to be used for the export.
    filepath:
      *string*.  The filepath of the file to export the object to.
    config:
      *Config*.  Export configuration.
    """

    progress = Progress(0, None)

    human = config.human
    config.setupTexFolder(filepath)
    filename = os.path.basename(filepath)
    name = config.goodName(os.path.splitext(filename)[0])

    objects = human.getObjects(True)
    meshes = [o.mesh.clone(1, True) for o in objects]

    from codecs import open

    fp = open(filepath, "w", encoding="utf-8")
    solid = name.replace(" ", "_")
    fp.write("solid %s\n" % solid)

    progress(0.3, 0.99, "Writing Objects")
    objprog = Progress(len(meshes))

    def chunked_enumerate(chunk_size, offs, list_):
        return zip(range(offs, offs + chunk_size), list_[offs : offs + chunk_size])

    for mesh in meshes:
        coord = config.scale * mesh.coord + config.offset
        offs = 0
        chunk_size = (
            2000
        )  # The higher the chunk size, the faster, but setting this too high can run into memory errors on some machines
        meshprog = Progress(math.ceil(float(len(mesh.fvert)) / chunk_size))
        while offs < len(mesh.fvert):
            fp.write(
                "".join(
                    [
                        (
                            "facet normal %f %f %f\n" % tuple(mesh.fnorm[fn])
                            + "\touter loop\n"
                            + "\t\tvertex %f %f %f\n" % tuple(coord[fv[0]])
                            + "\t\tvertex %f %f %f\n" % tuple(coord[fv[1]])
                            + "\t\tvertex %f %f %f\n" % tuple(coord[fv[2]])
                            + "\tendloop\n"
                            + "\tendfacet\n"
                            + "facet normal %f %f %f\n" % tuple(mesh.fnorm[fn])
                            + "\touter loop\n"
                            + "\t\tvertex %f %f %f\n" % tuple(coord[fv[2]])
                            + "\t\tvertex %f %f %f\n" % tuple(coord[fv[3]])
                            + "\t\tvertex %f %f %f\n" % tuple(coord[fv[0]])
                            + "\tendloop\n"
                            + "\tendfacet\n"
                        )
                        for fn, fv in chunked_enumerate(offs, chunk_size, mesh.fvert)
                    ]
                )
            )
            fp.flush()
            os.fsync(fp.fileno())
            offs += chunk_size
            meshprog.step()
        meshprog.finish()
        objprog.step()

    fp.write("endsolid %s\n" % solid)
    fp.close()
    progress(1, None, "STL export finished. Exported file: %s", filepath)
示例#17
0
# coding=utf8

from progress import Progress

progress = Progress(description="Processing some items..", size=15)

import time

for i in range(15):
    time.sleep(0.2)
    progress.next_item("%d" % (15 - i))

progress.finish()

progress.reset(description="Processing another one..", size=20)

for i in range(20):
    time.sleep(0.2)
    progress.next_item("%d" % i)

progress.finish()
示例#18
0
def Render(settings):
    progress = Progress.begin()
    
    if not mh.hasRenderToRenderbuffer():
        settings['dimensions'] = (G.windowWidth, G.windowHeight)

    if settings['lightmapSSS']:
        progress(0, 0.05, "Storing data")
        import material
        human = G.app.selectedHuman
        materialBackup = material.Material(human.material)

        progress(0.05, 0.1, "Projecting lightmaps")
        diffuse = imgop.Image(data = human.material.diffuseTexture)
        lmap = projection.mapSceneLighting(
            settings['scene'], border = human.material.sssRScale)
        progress(0.1, 0.4, "Applying medium scattering")
        lmapG = imgop.blurred(lmap, human.material.sssGScale, 13)
        progress(0.4, 0.7, "Applying high scattering")
        lmapR = imgop.blurred(lmap, human.material.sssRScale, 13)
        lmap = imgop.compose([lmapR, lmapG, lmap])
        if not diffuse.isEmpty:
            progress(0.7, 0.8, "Combining textures")
            lmap = imgop.resized(lmap, diffuse.width, diffuse.height, filter=image.FILTER_BILINEAR)
            progress(0.8, 0.9)
            lmap = imgop.multiply(lmap, diffuse)
        lmap.sourcePath = "Internal_Renderer_Lightmap_SSS_Texture"

        progress(0.9, 0.95, "Setting up renderer")
        human.material.diffuseTexture = lmap
        human.configureShading(diffuse = True)
        human.shadeless = True
        progress(0.95, 0.98, None)
    else:
        progress(0, 0.99, None)
        
    if not mh.hasRenderToRenderbuffer():
        # Limited fallback mode, read from screen buffer
        log.message("Fallback render: grab screen")
        img = mh.grabScreen(0, 0, G.windowWidth, G.windowHeight)
        alphaImg = None
    else:
        # Render to framebuffer object
        renderprog = Progress()
        renderprog(0, 0.99 - 0.59 * settings['AA'], "Rendering")
        width, height = settings['dimensions']
        log.message("Rendering at %sx%s", width, height)
        if settings['AA']:
            width = width * 2
            height = height * 2
        img = mh.renderToBuffer(width, height)
        alphaImg = mh.renderAlphaMask(width, height)
        img = imgop.addAlpha(img, imgop.getChannel(alphaImg, 0))

        if settings['AA']:
            renderprog(0.4, 0.99, "AntiAliasing")
            # Resize to 50% using bi-linear filtering
            img = img.resized(width/2, height/2, filter=image.FILTER_BILINEAR)
            # TODO still haven't figured out where components get swapped, but this hack appears to be necessary
            img.data[:,:,:] = img.data[:,:,(2,1,0,3)]
        renderprog.finish()

    if settings['lightmapSSS']:
        progress(0.98, 0.99, "Restoring data")
        human.material = materialBackup

    progress(1, None, 'Rendering complete')

    gui3d.app.getCategory('Rendering').getTaskByName('Viewer').setImage(img)
    mh.changeTask('Rendering', 'Viewer')
    gui3d.app.statusPersist('Rendering complete')
示例#19
0
def Render(settings):
    progress = Progress.begin()

    if not mh.hasRenderToRenderbuffer():
        settings['dimensions'] = (G.windowWidth, G.windowHeight)

    if settings['lightmapSSS']:
        progress(0, 0.05, "Storing data")
        import material
        human = G.app.selectedHuman
        materialBackup = material.Material(human.material)

        progress(0.05, 0.1, "Projecting lightmaps")
        diffuse = imgop.Image(data=human.material.diffuseTexture)
        lmap = projection.mapSceneLighting(settings['scene'],
                                           border=human.material.sssRScale)
        progress(0.1, 0.4, "Applying medium scattering")
        lmapG = imgop.blurred(lmap, human.material.sssGScale, 13)
        progress(0.4, 0.7, "Applying high scattering")
        lmapR = imgop.blurred(lmap, human.material.sssRScale, 13)
        lmap = imgop.compose([lmapR, lmapG, lmap])
        if not diffuse.isEmpty:
            progress(0.7, 0.8, "Combining textures")
            lmap = imgop.resized(lmap, diffuse.width, diffuse.height)
            progress(0.8, 0.9)
            lmap = imgop.multiply(lmap, diffuse)
        lmap.sourcePath = "Internal_Renderer_Lightmap_SSS_Texture"

        progress(0.9, 0.95, "Setting up renderer")
        human.material.diffuseTexture = lmap
        human.mesh.configureShading(diffuse=True)
        human.mesh.shadeless = True
        progress(0.95, 0.98, None)
    else:
        progress(0, 0.99, None)

    if not mh.hasRenderToRenderbuffer():
        # Limited fallback mode, read from screen buffer
        log.message("Fallback render: grab screen")
        img = mh.grabScreen(0, 0, G.windowWidth, G.windowHeight)
        alphaImg = None
    else:
        # Render to framebuffer object
        renderprog = Progress()
        renderprog(0, 0.99 - 0.59 * settings['AA'], "Rendering")
        width, height = settings['dimensions']
        log.message("Rendering at %sx%s", width, height)
        if settings['AA']:
            width = width * 2
            height = height * 2
        img = mh.renderToBuffer(width, height)
        alphaImg = mh.renderAlphaMask(width, height)
        img = imgop.addAlpha(img, imgop.getChannel(alphaImg, 0))

        if settings['AA']:
            renderprog(0.4, 0.99, "AntiAliasing")
            # Resize to 50% using Qt image class
            qtImg = img.toQImage()
            del img
            # Bilinear filtered resize for anti-aliasing
            scaledImg = qtImg.scaled(
                width / 2,
                height / 2,
                transformMode=gui.QtCore.Qt.SmoothTransformation)
            del qtImg
            img = scaledImg
            #img = image.Image(scaledImg)    # Convert back to MH image
            #del scaledImg
        renderprog.finish()

    if settings['lightmapSSS']:
        progress(0.98, 0.99, "Restoring data")
        human.material = materialBackup

    progress(1, None, 'Rendering complete')

    gui3d.app.getCategory('Rendering').getTaskByName('Viewer').setImage(img)
    mh.changeTask('Rendering', 'Viewer')
    gui3d.app.statusPersist('Rendering complete.')
示例#20
0
    for i in range(n_iter + 1):
        # by choosing a random node from the starting nodes in the graph
        current_node = random.choice(list(graph_rep.keys()))
        # show a progress bar to track progress of the ongoing calculation
        prog.counter += 0.000325
        prog.show()
        # for every step taken by the walker before reaching the end URL:
        for j in range(n_steps + 1):
            # the walker randomly enters one of the URLs from the starting/current node's targets
            current_node = random.choice(list(graph_rep[current_node]))
        # up the hit count for the current node
        hit_count[current_node] += 1 / n_iter
        # update the hit_count dictionary with this upped hit frequency
        hit_count.update({current_node: hit_count[current_node]})
    # hide the progress bar
    prog.finish()
    return hit_count


def distribution_page_rank(graph_rep, n_iter=100):
    """Probabilistic PageRank estimation

    Parameters:
    graph_rep -- a graph object as returned by load_graph()
    n_iter (int) -- number of probability distribution updates

    Returns:
    node_prob -- A dict that assigns each page its probability to be reached

    This function estimates the Page Rank by iteratively calculating
    the probability that a random walker is currently on any node.
示例#21
0
def writeSkeletonFile(human, filepath, config):
    import transformations as tm
    Pprogress = Progress(3)  # Parent.
    filename = os.path.basename(filepath)
    filename = getbasefilename(filename)
    filename = filename + ".skeleton.xml"
    filepath = os.path.join(os.path.dirname(filepath), filename)

    skel = human.getSkeleton()
    if config.scale != 1:
        skel = skel.scaled(config.scale)

    f = io.open(filepath, 'w', encoding="utf-8")
    lines = []

    lines.append('<?xml version="1.0" encoding="UTF-8"?>')
    lines.append(
        '<!-- Exported from MakeHuman (www.makehumancommunity.org) -->')
    lines.append('<!-- Skeleton: %s -->' % skel.name)
    lines.append('<skeleton>')
    lines.append('    <bones>')
    progress = Progress(len(skel.getBones()))
    for bIdx, bone in enumerate(skel.getBones()):
        mat = bone.getRelativeMatrix(
            offsetVect=config.offset
        )  # TODO adapt offset if mesh orientation is different

        # Bone positions are in parent bone space
        pos = mat[:3, 3]

        angle, axis, _ = tm.rotation_from_matrix(mat)

        lines.append('        <bone id="%s" name="%s">' % (bIdx, bone.name))
        lines.append('            <position x="%s" y="%s" z="%s" />' %
                     (pos[0], pos[1], pos[2]))
        lines.append('            <rotation angle="%s">' % angle)
        lines.append('                <axis x="%s" y="%s" z="%s" />' %
                     (axis[0], axis[1], axis[2]))
        lines.append('            </rotation>')
        lines.append('        </bone>')
        progress.step()
    lines.append('    </bones>')
    Pprogress.step()

    lines.append('    <bonehierarchy>')
    progress = Progress(len(skel.getBones()))
    for bone in skel.getBones():
        if bone.parent:
            lines.append('        <boneparent bone="%s" parent="%s" />' %
                         (bone.name, bone.parent.name))
        progress.step()
    lines.append('    </bonehierarchy>')
    Pprogress.step()

    animations = [human.getAnimation(name) for name in human.getAnimations()]
    # TODO compensate animations for alternate rest pose
    if len(animations) > 0:
        lines.append('    <animations>')
        for anim in animations:
            # Use pose matrices, not skinning matrices
            anim.resetBaked()
            #anim = bvhanim.getAnimationTrack()
            writeAnimation(human, lines, anim, config)
        lines.append('    </animations>')

    lines.append('</skeleton>')

    f.write("\n".join(lines))
    f.close()
    Pprogress.finish()
示例#22
0
def writeSkeletonFile(human, filepath, config):
    import transformations as tm
    Pprogress = Progress(3)  # Parent.
    filename = os.path.basename(filepath)
    filename = getbasefilename(filename)
    filename = filename + ".skeleton.xml"
    filepath = os.path.join(os.path.dirname(filepath), filename)

    skel = human.getSkeleton()
    if config.scale != 1:
        skel = skel.scaled(config.scale)
    if not skel.isInRestPose():
        # Export skeleton with the current pose as rest pose
        skel = skel.createFromPose()

    f = codecs.open(filepath, 'w', encoding="utf-8")
    lines = []

    lines.append('<?xml version="1.0" encoding="UTF-8"?>')
    lines.append('<!-- Exported from MakeHuman (www.makehuman.org) -->')
    lines.append('<!-- Skeleton: %s -->' % skel.name)
    lines.append('<skeleton>')
    lines.append('    <bones>')
    progress = Progress(len(skel.getBones()))
    for bIdx, bone in enumerate(skel.getBones()):
        mat = bone.getRelativeMatrix(offsetVect=config.offset)  # TODO adapt offset if mesh orientation is different

        # Bone positions are in parent bone space
        pos = mat[:3,3]

        angle, axis, _ = tm.rotation_from_matrix(mat)

        lines.append('        <bone id="%s" name="%s">' % (bIdx, bone.name))
        lines.append('            <position x="%s" y="%s" z="%s" />' % (pos[0], pos[1], pos[2]))
        lines.append('            <rotation angle="%s">' % angle)
        lines.append('                <axis x="%s" y="%s" z="%s" />' % (axis[0], axis[1], axis[2]))
        lines.append('            </rotation>')
        lines.append('        </bone>')
        progress.step()
    lines.append('    </bones>')
    Pprogress.step()

    lines.append('    <bonehierarchy>')
    progress = Progress(len(skel.getBones()))
    for bone in skel.getBones():
        if bone.parent:
            lines.append('        <boneparent bone="%s" parent="%s" />' % (bone.name, bone.parent.name))
        progress.step()
    lines.append('    </bonehierarchy>')
    Pprogress.step()

    if hasattr(human, 'animations'):
        lines.append('    <animations>')
        for anim in human.animations:
            writeAnimation(human, lines, anim.getAnimationTrack(), config)
        lines.append('    </animations>')

    lines.append('</skeleton>')

    f.write("\n".join(lines))
    f.close()
    Pprogress.finish()
示例#23
0
def exportStlAscii(filepath, config, exportJoints=False):
    """
    This function exports MakeHuman mesh to stereolithography ascii format.

    Parameters
    ----------

    human:
      *Human*.  The object whose information is to be used for the export.
    filepath:
      *string*.  The filepath of the file to export the object to.
    config:
      *Config*.  Export configuration.
    """

    progress = Progress(0, None)

    human = config.human
    config.setupTexFolder(filepath)
    filename = os.path.basename(filepath)
    name = config.goodName(os.path.splitext(filename)[0])

    objects = human.getObjects(True)
    meshes = [o.mesh.clone(1, True) for o in objects]

    from codecs import open
    fp = open(filepath, 'w', encoding="utf-8")
    solid = name.replace(' ', '_')
    fp.write('solid %s\n' % solid)

    progress(0.3, 0.99, "Writing Objects")
    objprog = Progress(len(meshes))

    def chunked_enumerate(chunk_size, offs, list_):
        return zip(range(offs, offs + chunk_size),
                   list_[offs:offs + chunk_size])

    for mesh in meshes:
        coord = config.scale * mesh.coord + config.offset
        offs = 0
        chunk_size = 2000  # The higher the chunk size, the faster, but setting this too high can run into memory errors on some machines
        meshprog = Progress(math.ceil(float(len(mesh.fvert)) / chunk_size))
        while (offs < len(mesh.fvert)):
            fp.write("".join([
                ('facet normal %f %f %f\n' % tuple(mesh.fnorm[fn]) +
                 '\touter loop\n' +
                 '\t\tvertex %f %f %f\n' % tuple(coord[fv[0]]) +
                 '\t\tvertex %f %f %f\n' % tuple(coord[fv[1]]) +
                 '\t\tvertex %f %f %f\n' % tuple(coord[fv[2]]) +
                 '\tendloop\n' + '\tendfacet\n' +
                 'facet normal %f %f %f\n' % tuple(mesh.fnorm[fn]) +
                 '\touter loop\n' +
                 '\t\tvertex %f %f %f\n' % tuple(coord[fv[2]]) +
                 '\t\tvertex %f %f %f\n' % tuple(coord[fv[3]]) +
                 '\t\tvertex %f %f %f\n' % tuple(coord[fv[0]]) +
                 '\tendloop\n' + '\tendfacet\n')
                for fn, fv in chunked_enumerate(offs, chunk_size, mesh.fvert)
            ]))
            fp.flush()
            os.fsync(fp.fileno())
            offs += chunk_size
            meshprog.step()
        meshprog.finish()
        objprog.step()

    fp.write('endsolid %s\n' % solid)
    fp.close()
    progress(1, None, "STL export finished. Exported file: %s", filepath)
示例#24
0
# coding=utf8

from progress import Progress

progress = Progress(description="Processing some items..", size=15)

import time

for i in range(15):
    time.sleep(0.2)
    progress.next_item("%d" % (15-i))

progress.finish()

progress.reset(description="Processing another one..", size=20)

for i in range(20):
    time.sleep(0.2)
    progress.next_item("%d" % i)

progress.finish()