def initializeMitsuba(self):
        # Start up the scheduling system with one worker per local core
        self.scheduler = Scheduler.getInstance()
        for i in range(0, multiprocessing.cpu_count()):
            self.scheduler.registerWorker(LocalWorker(i, 'wrk%i' % i))

        self.scheduler.start()
        # Create a queue for tracking render jobs
        self.queue = RenderQueue()
        # Get a reference to the plugin manager
        self.pmgr = PluginManager.getInstance()
        # Process Mitsuba log and progress messages within Python

        class CustomAppender(Appender):
            def append(self2, logLevel, message):
                print(message)

            def logProgress(self2, progress, name, formatted, eta):
                # Asynchronously notify the main thread
                self.renderProgress.emit(progress)

        logger = Thread.getThread().getLogger()
        logger.setLogLevel(EWarn) # Display warning & error messages
        logger.clearAppenders()
        logger.addAppender(CustomAppender())

        def closeEvent(self, e):
            self.job.cancel()
            self.queue.join()
            self.scheduler.stop()
def create_spheres(pointcloud: np.ndarray,
                   spectrum: Spectrum,
                   sphere_radius: float = 1.) -> List:
    """
    Create little spheres at the pointcloud's points' locations.
    :param pointcloud: 3D pointcloud, as Nx3 ndarray
    :param spectrum: The color spectrum to use with the spheres' diffuse bsdf
    :param sphere_radius: The radius to use for each sphere
    :return: A list of mitsuba shapes, to be added to a Scene
    """
    spheres = []
    for row in pointcloud:
        sphere = PluginManager.getInstance().create({
            'type':
            'sphere',
            'center':
            Point3(float(row[0]), float(row[1]), float(row[2])),
            'radius':
            sphere_radius,
            'bsdf': {
                'type': 'diffuse',
                'diffuseReflectance': spectrum
            },
        })
        spheres.append(sphere)

    return spheres
Example #3
0
 def __init__(self, path, split_files=False):
     from mitsuba import variant
     if not variant():
         mitsuba.set_variant('scalar_rgb')
     from mitsuba.core import PluginManager
     self.pmgr = PluginManager.instance()
     self.split_files = split_files
     self.scene_data = [
         {
             'type': 'scene'
         },  #MAIN
         {},  #MATS
         {},  #GEOM
         {},  #EMIT
         {}
     ]  #CAMS
     self.com_count = 0  # Counter for comment ids
     self.exported_ids = set()
     self.copy_count = {
         'tex': 0,
         'mesh': 0,
         'spectrum': 0
     }  # Counters for giving unique names to copied files
     self.copied_paths = {}
     self.files = []
     self.file_names = []  # Relative paths to the fragment files
     self.file_tabs = []
     self.file_stack = []
     self.current_file = Files.MAIN
     self.directory = ''  # scene foler
     self.set_filename(path)
Example #4
0
def create_sensor_from_transform(transform,
                                 width=1920,
                                 height=1440,
                                 fov=45.,
                                 num_samples=256) -> Sensor:
    """
    Create a Mitsuba sensor from a camera transform
    :param transform: The transform (camera to world) that this sensor uses
    :param width: The width of the resulting image
    :param height: The height of the resulting image
    :param fov: The field of view in degrees (default 45, meshlab uses 60)
    :param num_samples: Number of samples per pixel
    :return: A Mitsuba sensor
    """
    sensor = PluginManager.getInstance().create({
        'type': 'perspective',
        'film': {
            'type': 'ldrfilm',
            'width': width,
            'height': height,
            'pixelFormat': 'rgba',
            'exposure': 1.0,
            'banner': False
        },
        'sampler': {
            'type': 'ldsampler',
            'sampleCount': num_samples
        },
        'toWorld': transform,
        'fov': fov,
    })

    return sensor
Example #5
0
            def __init__(self):
                super().__init__()

                self.thread = Thread.registerUnmanagedThread('exporter')
                self.thread.setFileResolver(main_fresolver)
                self.thread.setLogger(main_logger)

                self.pmgr = PluginManager.getInstance()
                self.scene = Scene()
Example #6
0
            def __init__(self):
                super().__init__()

                self.thread = Thread.registerUnmanagedThread('exporter')
                self.thread.setFileResolver(main_fresolver)
                self.thread.setLogger(main_logger)

                self.pmgr = PluginManager.getInstance()
                self.scene = Scene()
Example #7
0
    def __initialize_mitsuba_setting(self):
        self.plgr = PluginManager.getInstance()
        self.output_dir = self.scene.output_dir

        mitsuba_module_path = os.path.dirname(inspect.getfile(MitsubaRenderer))
        self.file_resolver = Thread.getThread().getFileResolver()
        self.file_resolver.appendPath(
            os.path.join(mitsuba_module_path, "xml_files/"))
        self.file_resolver.appendPath(
            os.path.join(mitsuba_module_path, "textures/"))
        self.file_resolver.appendPath(
            os.path.join(mitsuba_module_path, "shapes/"))

        self.mitsuba_scene = Scene()
Example #8
0
def makeScene():

    scene = Scene()

    pmgr = PluginManager.getInstance()

    # make shapes
    for i in range(100):
        shapeProps = Properties("sphere")
        shapeProps["center"] = Point(i, i, i)
        shapeProps["radius"] = 0.1
        shape = pmgr.createObject(shapeProps)
        shape.configure()

        scene.addChild(shape)

    # make perspective sensor
    sensorProps = Properties("perspective")
    sensorProps["toWorld"] = Transform.lookAt(Point(0, 0, 10), Point(0, 0, 0),
                                              Vector(0, 1, 0))
    sensorProps["fov"] = 45.0

    sensor = pmgr.createObject(sensorProps)

    # make film
    filmProps = Properties("ldrfilm")
    filmProps["width"] = 640
    filmProps["height"] = 480

    film = pmgr.createObject(filmProps)
    film.configure()

    sensor.addChild("film", film)
    sensor.configure()

    scene.addChild(sensor)
    scene.configure()

    return scene
Example #9
0
def makeScene():

    scene = Scene()

    pmgr = PluginManager.getInstance()

    # make shapes
    for i in range(100):
        shapeProps = Properties("sphere")
        shapeProps["center"] = Point(i, i, i)
        shapeProps["radius"] = 0.1
        shape = pmgr.createObject(shapeProps)
        shape.configure()

        scene.addChild(shape)

    # make perspective sensor
    sensorProps = Properties("perspective")
    sensorProps["toWorld"] = Transform.lookAt(Point(0, 0, 10), Point(0, 0, 0), Vector(0, 1, 0))
    sensorProps["fov"] = 45.0

    sensor = pmgr.createObject(sensorProps)

    # make film
    filmProps = Properties("ldrfilm")
    filmProps["width"]  = 640
    filmProps["height"] = 480

    film = pmgr.createObject(filmProps)
    film.configure()

    sensor.addChild("film", film)
    sensor.configure()

    scene.addChild(sensor)
    scene.configure()

    return scene
Example #10
0
def construct_simple_scene(scene_objects, sensor) -> Scene:
    """
    Construct a simple scene containing given objects and using the given sensor. Uses the path integrator and constant
    emitter
    :param scene_objects: All scene child objects to add
    :param sensor: The mitsuba sensor definition to use for this scene
    :return: The scene created, already configured and initialized
    """
    pmgr = PluginManager.getInstance()
    integrator = pmgr.create({'type': 'path'})
    emitter = pmgr.create({'type': 'constant'})

    scene = Scene()
    scene.addChild(integrator)
    scene.addChild(emitter)
    scene.addChild(sensor)
    for obj in scene_objects:
        scene.addChild(obj)

    scene.configure()
    scene.initialize()

    return scene
Example #11
0
def do_simulation_multiangle_seq(seqname):
    currdir = os.path.split(os.path.realpath(__file__))[0]
    sys.path.append(currdir + '/bin/rt/' + current_rt_program + '/python/2.7/')
    os.environ['PATH'] = currdir + '/bin/rt/' + current_rt_program + os.pathsep + os.environ['PATH']
    import mitsuba
    from mitsuba.core import Vector, Point, Ray, Thread, Scheduler, LocalWorker, PluginManager, Transform
    from mitsuba.render import SceneHandler
    from mitsuba.render import RenderQueue, RenderJob
    from mitsuba.render import Scene
    import multiprocessing

    scheduler = Scheduler.getInstance()
    for i in range(0, multiprocessing.cpu_count()):
        scheduler.registerWorker(LocalWorker(i, 'wrk%i' % i))
    scheduler.start()


    scene_path = session.get_scenefile_path()
    fileResolver = Thread.getThread().getFileResolver()
    fileResolver.appendPath(str(scene_path))
    scene = SceneHandler.loadScene(fileResolver.resolve(
        str(os.path.join(session.get_scenefile_path(), main_scene_xml_file))))
    scene.configure()
    scene.initialize()
    queue = RenderQueue()
    sceneResID = scheduler.registerResource(scene)
    bsphere = scene.getKDTree().getAABB().getBSphere()
    radius = bsphere.radius
    targetx, targety, targetz = bsphere.center[0], bsphere.center[1], bsphere.center[2]
    f = open(seqname + ".conf", 'r')
    params = json.load(f)
    obs_azimuth = params['seq1']['obs_azimuth']
    obs_zenith = params['seq2']['obs_zenith']
    cfgfile = session.get_config_file()
    f = open(cfgfile, 'r')
    cfg = json.load(f)
    viewR = cfg["sensor"]["obs_R"]
    mode = cfg["sensor"]["film_type"]
    azi_arr = map(lambda x: float(x), obs_azimuth.strip().split(":")[1].split(","))
    zeni_arr = map(lambda x: float(x), obs_zenith.strip().split(":")[1].split(","))
    seq_header = multi_file_prefix + "_" + seqname
    index = 0
    for azi in azi_arr:
        for zeni in zeni_arr:
            distFile = os.path.join(session.get_output_dir(),
                                    seq_header + ("_VA_%.2f" % azi).replace(".", "_") + ("_VZ_%.2f" % zeni).replace(".", "_"))
            newScene = Scene(scene)
            pmgr = PluginManager.getInstance()
            newSensor = pmgr.createObject(scene.getSensor().getProperties())
            theta = zeni / 180.0 * math.pi
            phi = (azi - 90) / 180.0 * math.pi
            scale_x = radius
            scale_z = radius
            toWorld = Transform.lookAt(
                Point(targetx - viewR * math.sin(theta) * math.cos(phi), targety + viewR * math.cos(theta),
                      targetz - viewR * math.sin(theta) * math.sin(phi)),  # original
                Point(targetx, targety, targetz),  # target
                Vector(0, 0, 1)  # up
            ) * Transform.scale(
                Vector(scale_x, scale_z, 1)  # 视场大小
            )
            newSensor.setWorldTransform(toWorld)
            newFilm = pmgr.createObject(scene.getFilm().getProperties())
            newFilm.configure()
            newSensor.addChild(newFilm)
            newSensor.configure()
            newScene.addSensor(newSensor)
            newScene.setSensor(newSensor)
            newScene.setSampler(scene.getSampler())
            newScene.setDestinationFile(str(distFile))
            job = RenderJob('Simulation Job' + "VA_"+str(azi)+"_VZ_"+str(zeni), newScene, queue, sceneResID)
            job.start()
        queue.waitLeft(0)
        queue.join()
    # handle npy
    if mode == "spectrum" and (output_format not in ("npy", "NPY")):
        for azi in azi_arr:
            for zeni in zeni_arr:
                distFile = os.path.join(session.get_output_dir(),
                                        seq_header + ("_VA_%.2f" % azi).replace(".", "_") + ("_VZ_%.2f" % zeni).replace(
                                            ".", "_"))
                data = np.load(distFile + ".npy")
                bandlist = cfg["sensor"]["bands"].split(",")
                RasterHelper.saveToHdr_no_transform(data, distFile, bandlist, output_format)
                os.remove(distFile + ".npy")