Example #1
0
def main():

    global base, render, taskMgr, loader, model_iter

    model_iter = iter(getModel(int(sys.argv[1])))

    base = MyBase()
    render = base.render
    taskMgr = base.taskMgr
    loader = base.loader

    base.disableMouse()
    pandacore.attachLights(render)
    render.setShaderAuto()
    render.setTransparency(TransparencyAttrib.MDual, 1)

    base.cam.setPos(0, 30000, 10000)
    base.cam.lookAt(0, 0, 0.0)

    KeyboardMovement()
    MouseCamera()

    base.win.setClearColor(VBase4(0.9, 0.9, 0.9, 1))

    render.setAntialias(AntialiasAttrib.MAuto)

    taskMgr.add(nextModelTask, 'nextModelTask')

    base.run()
Example #2
0
def renderVerts(verts, idx):

    from meshtool.filters.panda_filters.pandacore import getVertexData, attachLights, ensureCameraAt
    from meshtool.filters.panda_filters.pandacontrols import KeyboardMovement, MouseDrag, MouseScaleZoom
    from panda3d.core import GeomTriangles, Geom, GeomNode
    from direct.showbase.ShowBase import ShowBase

    vdata, indexdata = getVertexData(verts, idx)
    gprim = GeomTriangles(Geom.UHStatic)
    gprim.setIndexType(Geom.NTUint32)
    gprim.setVertices(indexdata)
    gprim.closePrimitive()
    pgeom = Geom(vdata)
    pgeom.addPrimitive(gprim)
    node = GeomNode("primitive")
    node.addGeom(pgeom)
    p3dApp = ShowBase()
    #attachLights(render)
    geomPath = render.attachNewNode(node)
    geomPath.setRenderModeWireframe()
    ensureCameraAt(geomPath, base.camera)
    KeyboardMovement()
    #render.setShaderAuto()
    p3dApp.run()
Example #3
0
    def __init__(self, mesh_path, progressive_texture_path):

        resolutions = []
        f = tarfile.open(progressive_texture_path)
        for resolution_name in f.getnames():
            toset = {
                'size': resolution_name[:-4],
                'contents': f.extractfile(resolution_name).read()
            }
            texpnm = PNMImage()
            texpnm.read(StringStream(toset['contents']), 'something.jpg')
            newtex = Texture()
            newtex.load(texpnm)
            toset['texture'] = newtex
            resolutions.append(toset)

        self.resolutions = resolutions

        def aux_loader(fname):
            return resolutions[0]['contents']

        mesh = collada.Collada(mesh_path, aux_file_loader=aux_loader)

        scene_members = getSceneMembers(mesh)

        base = ShowBase()

        rotateNode = GeomNode("rotater")
        rotatePath = render.attachNewNode(rotateNode)
        matrix = numpy.identity(4)
        if mesh.assetInfo.upaxis == collada.asset.UP_AXIS.X_UP:
            r = collada.scene.RotateTransform(0, 1, 0, 90)
            matrix = r.matrix
        elif mesh.assetInfo.upaxis == collada.asset.UP_AXIS.Y_UP:
            r = collada.scene.RotateTransform(1, 0, 0, 90)
            matrix = r.matrix
        rotatePath.setMat(Mat4(*matrix.T.flatten().tolist()))

        geom, renderstate, mat4 = scene_members[0]
        node = GeomNode("primitive")
        node.addGeom(geom)
        if renderstate is not None:
            node.setGeomState(0, renderstate)
        self.geomPath = rotatePath.attachNewNode(node)
        self.geomPath.setMat(mat4)

        wrappedNode = ensureCameraAt(self.geomPath, base.camera)
        base.disableMouse()
        attachLights(render)
        render.setShaderAuto()
        render.setTransparency(TransparencyAttrib.MDual, 1)

        base.render.analyze()
        KeyboardMovement()
        MouseDrag(wrappedNode)
        MouseScaleZoom(wrappedNode)
        MouseCamera()

        num_resolutions = len(resolutions) - 1
        self.slider = DirectSlider(range=(0, num_resolutions),
                                   value=0,
                                   pageSize=1,
                                   command=self.sliderMoved,
                                   pos=(0, 0, -.9),
                                   scale=1)
        for key, val in uiArgs.iteritems():
            self.slider.thumb[key] = val

        self.triText = OnscreenText(text="",
                                    pos=(-1, 0.85),
                                    scale=0.15,
                                    fg=(1, 0.5, 0.5, 1),
                                    align=TextNode.ALeft,
                                    mayChange=1)

        base.run()
Example #4
0
def visualize(centers, corners, edges):
    from meshtool.filters.panda_filters.pandacore import getVertexData, attachLights, ensureCameraAt
    from meshtool.filters.panda_filters.pandacontrols import KeyboardMovement, MouseDrag, MouseScaleZoom, MouseCamera
    from panda3d.core import GeomPoints, GeomTriangles, Geom, GeomNode, GeomVertexFormat, GeomVertexData, GeomVertexWriter, LineSegs, VBase3
    from direct.showbase.ShowBase import ShowBase

    format = GeomVertexFormat.getV3c4()
    vdata = GeomVertexData('pts', format, Geom.UHDynamic)
    vertex = GeomVertexWriter(vdata, 'vertex')
    color = GeomVertexWriter(vdata, 'color')

    vertex_index = 0
    center_vertex_indices = {}
    corner_vertex_indices = {}
    for key, center in centers.iteritems():
        vertex.addData3f(center.x * X_SCALE, center.y * Y_SCALE,
                         center.elevation * Z_SCALE)
        curcolor = hex2rgb(COLORS[center.biome])
        color.addData4f(curcolor[0], curcolor[1], curcolor[2], 1)
        center_vertex_indices[key] = vertex_index
        vertex_index += 1

        for corner in center.corners:
            vertex.addData3f(corner.x * X_SCALE, corner.y * Y_SCALE,
                             corner.elevation * Z_SCALE)
            color.addData4f(curcolor[0], curcolor[1], curcolor[2], 1)
            corner_vertex_indices[corner.id] = vertex_index
            vertex_index += 1

    tris = GeomTriangles(Geom.UHDynamic)

    for edge in edges.itervalues():
        corner0 = edge.corner0
        corner1 = edge.corner1
        center0 = edge.center0
        center1 = edge.center1
        if corner0 is None or corner1 is None:
            continue

        tris.addVertices(corner_vertex_indices[corner1.id],
                         corner_vertex_indices[corner0.id],
                         center_vertex_indices[center0.id])

        tris.addVertices(center_vertex_indices[center1.id],
                         corner_vertex_indices[corner0.id],
                         corner_vertex_indices[corner1.id])

    tris.closePrimitive()

    pgeom = Geom(vdata)
    pgeom.addPrimitive(tris)

    node = GeomNode("primitive")
    node.addGeom(pgeom)

    p3dApp = ShowBase()
    attachLights(render)
    geomPath = render.attachNewNode(node)
    #geomPath.setRenderModeThickness(6.0)

    #geomPath.setRenderModeWireframe()

    ensureCameraAt(geomPath, base.cam)

    boundingSphere = geomPath.getBounds()
    base.cam.setPos(boundingSphere.getCenter() + boundingSphere.getRadius())

    base.cam.lookAt(boundingSphere.getCenter())

    geomPath.setScale(VBase3(50, 50, 50))

    KeyboardMovement()
    #MouseDrag(geomPath)
    MouseCamera()
    MouseScaleZoom(geomPath)
    #render.setShaderAuto()
    p3dApp.run()
Example #5
0
def renderCharts(facegraph, verts, vert_indices, lineset=None):

    from meshtool.filters.panda_filters.pandacore import getVertexData, attachLights, ensureCameraAt
    from meshtool.filters.panda_filters.pandacontrols import KeyboardMovement, MouseDrag, MouseScaleZoom, ButtonUtils
    from panda3d.core import GeomTriangles, Geom, GeomNode, GeomVertexFormat, GeomVertexData, GeomVertexWriter, LineSegs
    from direct.showbase.ShowBase import ShowBase

    vformat = GeomVertexFormat.getV3c4()
    vdata = GeomVertexData('tris', vformat, Geom.UHDynamic)

    vertex = GeomVertexWriter(vdata, 'vertex')
    color = GeomVertexWriter(vdata, 'color')

    colors = gen_color3(len(facegraph))
    numtris = 0
    for chart, data in facegraph.nodes_iter(data=True):
        curcolor = next(colors)
        for tri in data['tris']:
            triv = verts[vert_indices[tri]]
            vertex.addData3f(triv[0][0], triv[0][1], triv[0][2])
            vertex.addData3f(triv[1][0], triv[1][1], triv[1][2])
            vertex.addData3f(triv[2][0], triv[2][1], triv[2][2])
            color.addData4f(curcolor[0], curcolor[1], curcolor[2], 1)
            color.addData4f(curcolor[0], curcolor[1], curcolor[2], 1)
            color.addData4f(curcolor[0], curcolor[1], curcolor[2], 1)
            numtris += 1

    tris = GeomTriangles(Geom.UHDynamic)
    tris.addConsecutiveVertices(0, 3 * numtris)
    tris.closePrimitive()

    linenodes = []
    if lineset:
        for lines in lineset:
            ls = LineSegs()
            ls.setThickness(4)
            curcolor = next(colors)
            ls.setColor(curcolor[0] / 256.0, curcolor[1] / 256.0,
                        curcolor[2] / 256.0, 1)

            tuples = False
            for blah in lines:
                if isinstance(blah, tuple):
                    tuples = True
                break
            if tuples:
                for i, j in lines:
                    frompt = verts[i]
                    topt = verts[j]
                    ls.moveTo(frompt[0], frompt[1], frompt[2])
                    ls.drawTo(topt[0], topt[1], topt[2])
            else:
                for i in range(len(lines) - 1):
                    frompt = verts[lines[i]]
                    topt = verts[lines[i + 1]]
                    ls.moveTo(frompt[0], frompt[1], frompt[2])
                    ls.drawTo(topt[0], topt[1], topt[2])

            linenodes.append(ls.create())

    pgeom = Geom(vdata)
    pgeom.addPrimitive(tris)

    node = GeomNode("primitive")
    node.addGeom(pgeom)

    p3dApp = ShowBase()
    #attachLights(render)
    geomPath = render.attachNewNode(node)

    for linenode in linenodes:
        geomPath.attachNewNode(linenode)

    #geomPath.setRenderModeWireframe()

    ensureCameraAt(geomPath, base.cam)

    boundingSphere = geomPath.getBounds()
    base.cam.setPos(boundingSphere.getCenter() + boundingSphere.getRadius())

    base.cam.lookAt(boundingSphere.getCenter())

    KeyboardMovement()
    ButtonUtils(geomPath)
    MouseDrag(geomPath)
    MouseScaleZoom(geomPath)
    #render.setShaderAuto()
    p3dApp.run()
Example #6
0
def main():

    parser = argparse.ArgumentParser(
        description='Tool for displaying a scene from open3dhub')

    parser.add_argument('--model-type',
                        choices=['progressive', 'optimized'],
                        default='progressive',
                        required=False,
                        help='Model type to use')
    parser.add_argument('--model-subtype',
                        choices=['base', 'full'],
                        default='base',
                        required=False,
                        help='Model subtype (currently only for progressive)')
    parser.add_argument('--force-model-download',
                        dest='force_model',
                        action='store_true',
                        help='Force re-downloading models')
    parser.add_argument(
        'scene_file',
        help='Scene file to use, generated with scene_generator',
        type=argparse.FileType('r'))
    parser.add_argument('--screenshots',
                        required=False,
                        help='Directory to save screenshots',
                        type=str)
    parser.add_argument('--exit-after-load',
                        required=False,
                        default=False,
                        action='store_true',
                        help='Exit the program after all models are loaded')

    args = parser.parse_args()

    global FORCE_MODEL_DOWNLOAD
    global SAVE_SS
    global START_TIME
    global LAST_SCREENSHOT
    global NUM_MODELS
    global EXIT_AFTER
    global MODEL_TYPE
    global MODEL_SUBTYPE
    global HASH_SIZES

    EXIT_AFTER = args.exit_after_load
    FORCE_MODEL_DOWNLOAD = args.force_model
    SAVE_SS = args.screenshots
    MODEL_TYPE = args.model_type
    MODEL_SUBTYPE = args.model_subtype

    if SAVE_SS is not None:
        if os.path.isdir(SAVE_SS):
            #yn = raw_input("Delete existing ss dir? ")
            yn = 'y'
            if yn == 'y':
                shutil.rmtree(SAVE_SS)
            else:
                print 'Exiting then'
                sys.exit(1)
        if not os.path.isdir(SAVE_SS):
            os.mkdir(SAVE_SS)
        if not os.path.isdir(SAVE_SS):
            print >> sys.stderr, 'Invalid screenshots directory'
            parser.print_usage()
            sys.exit(1)
    START_TIME = time.clock()
    LAST_SCREENSHOT = START_TIME

    scene_dict = pickle.load(args.scene_file)
    HASH_SIZES = scene_dict['sizes']
    scene_models = scene_dict['models']
    NUM_MODELS = len(scene_models)

    global base, render, taskMgr, loader
    base = MyBase()
    render = base.render
    taskMgr = base.taskMgr
    loader = base.loader

    #if FORCE_MODEL_DOWNLOAD:
    #    try:
    #        shutil.rmtree(TEMPDIR)
    #    except OSError:
    #        pass
    try:
        os.mkdir(TEMPDIR)
    except OSError:
        pass

    base.disableMouse()
    pandacore.attachLights(render)

    base.cam.setPos(0, 30000, 10000)
    base.cam.lookAt(0, 0, 2000)

    t = LoadingThread(scene_models)
    t.daemon = True
    t.start()

    taskMgr.add(checkForLoad, "checkForLoad")
    if SAVE_SS is not None:
        taskMgr.add(triggerScreenshot, "triggerScreenshot")

    KeyboardMovement(scale=10.0)
    MouseCamera()

    #base.win.setClearColor(VBase4(0.9,0.9,0.9,1))
    base.win.setClearColor(VBase4(0.529, 0.807, 0.98, 1))
    environ = loader.loadModel("grass.egg")
    environ.reparentTo(render)
    minPt, maxPt = environ.getTightBounds()
    xRange = math.fabs(minPt.getX() - maxPt.getX())
    yRange = math.fabs(minPt.getY() - maxPt.getY())
    zRange = math.fabs(minPt.getZ() - maxPt.getZ())
    environ.setScale(500, 2500, 100)
    environ.setPos(0, 1000, 0)  #-1 * zRange / 2.0)
    environ.setP(180)
    #environ.lookAt(200, 200, 0)
    #environ.lookAt(base.cam)

    #environ.setTransparency(TransparencyAttrib.MAlpha)
    #environ.setAlphaScale(0.3)

    render.setShaderAuto()
    render.setAntialias(AntialiasAttrib.MAuto)
    environ.setShaderOff()

    # effectively disable distance culling
    base.camLens.setFar(sys.maxint)
    base.camLens.setNear(8.0)

    base.setFrameRateMeter(True)
    base.run()