def TestSceneEditRendering(cls, params):
    engineType = params[0]
    samplerType = params[1]
    renderConfigAdditionalProps = params[2]
    isDeterministic = params[3]

    # Create the rendering configuration
    cfgProps = pyluxcore.Properties()
    cfgProps.SetFromFile("resources/scenes/simple/simple.cfg")

    # Set the rendering engine
    cfgProps.Set(pyluxcore.Property("renderengine.type", engineType))
    # Set the sampler
    cfgProps.Set(pyluxcore.Property("sampler.type", samplerType))

    cfgProps.Set(renderConfigAdditionalProps)
    cfgProps.Set(LuxCoreTest.customConfigProps)

    config = pyluxcore.RenderConfig(cfgProps)

    # Run the rendering
    StandardAnimTest(
        cls, "SceneEditRendering_" + engineType + ("" if not samplerType else
                                                   ("_" + samplerType)),
        config, 5, isDeterministic)
Esempio n. 2
0
    def render(self, blScene):
        print("LuxCore render call")

        scale = blScene.render.resolution_percentage / 100.0
        self.filmWidth = int(blScene.render.resolution_x * scale)
        self.filmHeight = int(blScene.render.resolution_y * scale)

        ########################################################################
        # Do the rendering
        ########################################################################

        imageBufferFloat = array('f', [0.0] *
                                 (self.filmWidth * self.filmHeight * 3))

        scene = self.ConvertBlenderScene(blScene)
        config = pyluxcore.RenderConfig(self.CreateRenderConfigProps(), scene)
        session = pyluxcore.RenderSession(config)

        session.Start()

        startTime = time.time()
        while True:
            time.sleep(0.5)

            elapsedTime = time.time() - startTime

            # Print some information about the rendering progress

            # Update statistics
            session.UpdateStats()

            stats = session.GetStats()
            print(
                "[Elapsed time: %3d/5sec][Samples %4d][Avg. samples/sec % 3.2fM on %.1fK tris]"
                %
                (stats.Get("stats.renderengine.time").GetFloat(),
                 stats.Get("stats.renderengine.pass").GetInt(),
                 (stats.Get("stats.renderengine.total.samplesec").GetFloat() /
                  1000000.0),
                 (stats.Get("stats.dataset.trianglecount").GetFloat() /
                  1000.0)))

            # Update the image
            session.GetFilm().GetOutputFloat(
                pyluxcore.FilmOutputType.RGB_TONEMAPPED, imageBufferFloat)

            # Here we write the pixel values to the RenderResult
            result = self.begin_result(0, 0, self.filmWidth, self.filmHeight)
            layer = result.layers[0]
            layer.rect = pyluxcore.ConvertFilmChannelOutput_3xFloat_To_3xFloatList(
                self.filmWidth, self.filmHeight, imageBufferFloat)
            self.end_result(result)

            if self.test_break():
                # Time to stop the rendering
                break

        session.Stop()

        print("Done.")
    def render_image(self):
        self.ui.renderView.clear()
        self.scaleFactor = 1.0
        if not self.ui.fitToWindowAct.isChecked():
            self.ui.renderView.adjustSize()
        self.update()
        try:
            self.halt = self.configProps.Get("batch.halttime").GetInt()
            print(self.halt)

        except:
            print("no halttime set")
        try:
            self.shalt = self.configProps.Get("batch.haltspp").GetInt()
            print(self.shalt)

        except:
            print("no samples set")
        self.config = pyluxcore.RenderConfig(self.configProps, self.scene)
        self.session = pyluxcore.RenderSession(self.config)
        self.session.Start()
        self.timer.start(500, self)
        self.ui.renBtn.setEnabled(False)
        self.ui.stopBtn.setEnabled(True)
        self.ui.pauBtn.setEnabled(True)
Esempio n. 4
0
def SimpleRender():
    # Load the configuration from file
    props = pyluxcore.Properties("scenes/luxball/luxball-hdr.cfg")

    # Change the render engine
    props.Set(pyluxcore.Property("renderengine.type", ["PATHOCL"]))
    props.Set(pyluxcore.Property("opencl.devices.select", ["01000"]))
    props.Set(pyluxcore.Property("film.hw.enable", ["0"]))
    props.Set(pyluxcore.Property("opencl.native.threads.count", [0]))

    config = pyluxcore.RenderConfig(props)
    session = pyluxcore.RenderSession(config)

    session.Start()

    startTime = time.time()
    while True:
        time.sleep(1)

        elapsedTime = time.time() - startTime

        if elapsedTime > 1.0:
            # Time to stop the rendering
            break

    session.Stop()
Esempio n. 5
0
def ExtractConfiguration():
    print(
        "Extracting Film configuration example (requires scenes directory)...")

    # Load the configuration from file
    props = pyluxcore.Properties("scenes/luxball/luxball-hdr-comp.cfg")

    # Change the render engine to PATHCPU
    props.Set(pyluxcore.Property("renderengine.type", ["PATHCPU"]))

    config = pyluxcore.RenderConfig(props)
    session = pyluxcore.RenderSession(config)

    # Extract the RenderConfig properties (redundant here)
    props = session.GetRenderConfig().GetProperties()

    ids = set()
    for i in props.GetAllUniqueSubNames("film.outputs"):
        if props.Get(i + ".type").GetString() == "MATERIAL_ID_MASK":
            ids.add(props.Get(i + ".id").GetInt())

    for i in ids:
        print("MATERIAL_ID_MASK ID => %d" % i)

    print("Done.")
Esempio n. 6
0
def SimpleRender():
    # Load the configuration from file
    props = pyluxcore.Properties("scenes/luxball/luxball-hdr.cfg")

    # Change the render engine to PATHCPU
    props.Set(pyluxcore.Property("renderengine.type", ["PATHCPU"]))
    #props.Set(pyluxcore.Property("opencl.devices.select", ["0100"]))

    config = pyluxcore.RenderConfig(props)
    session = pyluxcore.RenderSession(config)

    session.Start()

    startTime = time.time()
    while True:
        time.sleep(1)

        elapsedTime = time.time() - startTime

        if elapsedTime > 1.0:
            # Time to stop the rendering
            break

    session.Stop()

    # Save the rendered image
    session.GetFilm().Save()
Esempio n. 7
0
    def test_Film_ConvTest(self):
        # Load the configuration from file
        props = pyluxcore.Properties("resources/scenes/simple/simple.cfg")

        # Change the render engine to PATHCPU
        props.Set(pyluxcore.Property("renderengine.type", ["PATHCPU"]))
        props.Set(pyluxcore.Property("sampler.type", ["RANDOM"]))
        props.Set(GetDefaultEngineProperties("PATHCPU"))

        # Replace halt condition
        props.Delete("batch.haltdebug")
        # Run at full speed
        props.Delete("native.threads.count")
        props.Set(pyluxcore.Property("batch.haltthreshold", 0.075))
        props.Set(pyluxcore.Property("batch.haltthreshold.step", 16))

        config = pyluxcore.RenderConfig(props)
        session = pyluxcore.RenderSession(config)

        session.Start()
        while True:
            time.sleep(0.5)

            # Update statistics (and run the convergence test)
            session.UpdateStats()

            if session.HasDone():
                # Time to stop the rendering
                break
        session.Stop()

        image = GetImagePipelineImage(session.GetFilm())

        CheckResult(self, image, "Film_ConvTest", False)
Esempio n. 8
0
def TestGeneratedScene(cls, params):
    engineType = params[0]
    samplerType = params[1]
    renderConfigAdditionalProps = params[2]
    isDeterministic = params[3]

    # Create the rendering configuration
    cfgProps = pyluxcore.Properties()
    cfgProps.SetFromString("""
		film.width = 512
		film.height = 384
		""")

    # Set the rendering engine
    cfgProps.Set(pyluxcore.Property("renderengine.type", engineType))
    # Set the sampler
    cfgProps.Set(pyluxcore.Property("sampler.type", samplerType))

    cfgProps.Set(renderConfigAdditionalProps)
    cfgProps.Set(LuxCoreTest.customConfigProps)

    # Create the scene properties
    scnProps = pyluxcore.Properties()

    # Set the camera position
    scnProps.SetFromString("""
		scene.camera.lookat.orig = 0.0 5.0 2.0
		scene.camera.lookat.target = 0.0 0.0 0.0
		""")

    # Define a white matte material
    scnProps.SetFromString("""
		scene.materials.whitematte.type = matte
		scene.materials.whitematte.kd = 0.75 0.75 0.75
		""")

    # Add a plane
    scnProps.Set(BuildPlane("plane1", "whitematte"))

    # Add a distant light source
    scnProps.SetFromString("""
		scene.lights.distl.type = sharpdistant
		scene.lights.distl.color = 1.0 1.0 1.0
		scene.lights.distl.gain = 2.0 2.0 2.0
		scene.lights.distl.direction = 1.0 1.0 -1.0
		""")

    # Create the scene
    scene = pyluxcore.Scene()
    scene.Parse(scnProps)

    # Create the render config
    config = pyluxcore.RenderConfig(cfgProps, scene)

    # Run the rendering
    StandardImageTest(
        cls, "GeneratedScene_" + engineType + ("" if not samplerType else
                                               ("_" + samplerType)), config,
        isDeterministic)
    def load_stuff(self):
        self.session = None
        self.config = None
        self.scene = None
        self.ui.renBtn.setEnabled(True)
        self.ui.stopBtn.setEnabled(False)
        self.ui.pauBtn.setEnabled(False)
        self.ui.renderView.clear()
        cmdLineProp = pyluxcore.Properties()
        self.configProps = pyluxcore.Properties()
        self.sceneProps = pyluxcore.Properties()
        print(self.ext)
        print(self.cfgFileName)
        if (self.ext == "lxs"):
            os.chdir(self.lastpath)
            pyluxcore.ParseLXS(self.cfgFileName, self.configProps,
                               self.sceneProps)
            self.configProps.Set(cmdLineProp)
            self.scene = pyluxcore.Scene(
                self.configProps.Get("images.scale", [1.0]).GetFloat())
            self.scene.Parse(self.sceneProps)
            self.config = pyluxcore.RenderConfig(self.configProps, self.scene)

            self.setup()
            return
        elif (self.ext == "cfg"):
            os.chdir(self.lastpath)
            print(self.cfgFileName)
            self.configProps = pyluxcore.Properties(self.cfgFileName)
            self.scene = pyluxcore.Scene(
                self.configProps.Get("scene.file").GetString())
            self.sceneProps = self.scene.ToProperties()
            self.cameraPos = self.sceneProps.Get(
                "scene.camera.lookat.orig").GetFloats()
            self.config = pyluxcore.RenderConfig(self.configProps, self.scene)
            self.setup()

        elif (self.ext == "bcf"):
            os.chdir(self.lastpath)
            self.config = pyluxcore.RenderConfig(self.cfgFileName)
            self.configProps.Parse(cmdLineProp)
            self.setup()
Esempio n. 10
0
def SaveFilm():
    print("Film save example (requires scenes directory)...")

    # Load the configuration from file
    props = pyluxcore.Properties("scenes/simple/simple.cfg")
    #props = pyluxcore.Properties("scenes/luxball/luxball-hdr.cfg")
    # To test large films
    #props.Set(pyluxcore.Property("film.width", 2048))
    #props.Set(pyluxcore.Property("film.height", 2048))

    # Change the render engine to PATHCPU
    props.Set(pyluxcore.Property("renderengine.type", ["PATHCPU"]))

    config = pyluxcore.RenderConfig(props)
    session = pyluxcore.RenderSession(config)

    session.Start()

    startTime = time.time()
    while True:
        time.sleep(.5)

        elapsedTime = time.time() - startTime

        # Print some information about the rendering progress

        # Update statistics
        session.UpdateStats()

        stats = session.GetStats()
        print(
            "[Elapsed time: %3d/5sec][Samples %4d][Avg. samples/sec % 3.2fM on %.1fK tris]"
            % (stats.Get("stats.renderengine.time").GetFloat(),
               stats.Get("stats.renderengine.pass").GetInt(),
               (stats.Get("stats.renderengine.total.samplesec").GetFloat() /
                1000000.0),
               (stats.Get("stats.dataset.trianglecount").GetFloat() / 1000.0)))

        if elapsedTime > 5.0:
            # Time to stop the rendering
            break

    session.Stop()

    # Save the rendered image
    t1 = Clock()
    session.GetFilm().SaveFilm("simple.flm")
    t2 = Clock()
    print("Film save time: %s secs" % (t2 - t1))

    print("Done.")
Esempio n. 11
0
	def renderEnginePathCPU(self):
		# Stop the rendering
		self.session.Stop()
		self.session = None
		
		# Change the render engine to PATHCPU
		props = self.config.GetProperties()
		props.Set(pyluxcore.Property("renderengine.type", ["PATHCPU"]))
		
		# Create the new RenderConfig
		self.config = pyluxcore.RenderConfig(props, self.scene)
		
		# Re-start the rendering
		self.session = pyluxcore.RenderSession(self.config)
		self.session.Start()
		print("PathCPU selected")
Esempio n. 12
0
	def renderEnginePathOCL(self, index):
		# Stop the rendering
		self.session.Stop()
		self.session = None
		
		# Change the render engine to PATHCPU
		props = self.config.GetProperties()
		selectString = list("0" * len(self.deviceList))
		selectString[index] = "1"
		props.Set(pyluxcore.Property("renderengine.type", ["PATHOCL"])). \
			Set(pyluxcore.Property("opencl.devices.select", ["".join(selectString)]))
		
		# Create the new RenderConfig
		self.config = pyluxcore.RenderConfig(props, self.scene)
		
		# Re-start the rendering
		self.session = pyluxcore.RenderSession(self.config)
		self.session.Start()
		print("PathOCL selected: %s" % self.deviceList[index][0])
    def CreateConfig(self, type):
        # Load the configuration from file
        props = pyluxcore.Properties("resources/scenes/simple/simple.cfg")

        # Change the render engine to PATHCPU
        props.Set(pyluxcore.Property("renderengine.type", ["PATHCPU"]))
        props.Set(pyluxcore.Property("sampler.type", ["RANDOM"]))
        props.Set(GetDefaultEngineProperties("PATHCPU"))

        config = pyluxcore.RenderConfig(props)
        scene = config.GetScene()

        # Delete the red and green boxes
        scene.DeleteObject("box1")
        scene.DeleteObject("box2")

        # Create the base object
        props = pyluxcore.Properties()
        if (type == "Normal"):
            props.SetFromString("""
				scene.objects.box1.ply = resources/scenes/simple/simple-mat-cube1.ply
				scene.objects.box1.material = redmatte
				""")
        elif (type == "Instance"):
            props.SetFromString("""
				scene.objects.box1.ply = resources/scenes/simple/simple-mat-cube1.ply
				scene.objects.box1.material = redmatte
				scene.objects.box1.transformation = 1.0 0.0 0.0 0.0  0.0 1.0 0.0 0.0  0.0 0.0 1.0 0.0  -0.5 0.0 0.0 1.0
				""")
        elif (type == "Motion"):
            props.SetFromString("""
				scene.objects.box1.ply = resources/scenes/simple/simple-mat-cube1.ply
				scene.objects.box1.material = redmatte
				scene.objects.box1.motion.0.time = 0.0
				scene.objects.box1.motion.0.transformation = 1.0 0.0 0.0 0.0  0.0 1.0 0.0 0.0  0.0 0.0 1.0 0.0  -0.25 0.0 0.0 1.0
				scene.objects.box1.motion.1.time = 1.0
				scene.objects.box1.motion.1.transformation = 1.0 0.0 0.0 0.0  0.0 1.0 0.0 0.0  0.0 0.0 1.0 0.0  0.25 0.0 0.0 1.0
				""")
        else:
            self.assertFalse()
        scene.Parse(props)

        return config
Esempio n. 14
0
	def __init__(self, cfgFileName):
		super(RenderView, self).__init__()
		
		self.dofEnabled = True
		self.luxBallShapeIsCube = False
		self.selectedFilmChannel = pyluxcore.FilmOutputType.RGB_TONEMAPPED
		
		self.createActions()
		self.createMenus()
		
		# Load the configuration from file
		props = pyluxcore.Properties(cfgFileName)
		
		# Change the render engine to PATHCPU
		props.Set(pyluxcore.Property("renderengine.type", ["PATHCPU"]))

		# Read the configuration and start the rendering
		self.scene = pyluxcore.Scene(props.Get("scene.file").GetString(),
			props.Get("images.scale", [1.0]).GetFloat())
		sceneProps = self.scene.GetProperties()
		# Save Camera position
		self.cameraPos = sceneProps.Get("scene.camera.lookat.orig").GetFloats()
		self.luxBallPos = [0.0, 0.0, 0.0]
		
		# Create the rendering configuration
		self.config = pyluxcore.RenderConfig(props, self.scene)
		self.filmWidth, self.filmHeight = self.config.GetFilmSize()[:2]
	
		# Allocate the image for the rendering
		self.allocateImageBuffers()

		self.setGeometry(0, 0, self.filmWidth, self.filmHeight)
		self.setWindowTitle('LuxCore RenderView')
		self.center()
		
		# Create the rendering session
		self.session = pyluxcore.RenderSession(self.config)
		# Start the rendering
		self.session.Start()
		
		self.timer = QBasicTimer()
		self.timer.start(500, self)
Esempio n. 15
0
def TestSceneEditRendering(cls, params):
    engineType = params[0]
    samplerType = params[1]

    # Create the rendering configuration
    props = pyluxcore.Properties(LuxCoreTest.customConfigProps)
    props.SetFromFile("resources/scenes/simple/simple.cfg")

    # Set the rendering engine
    props.Set(GetEngineProperties(engineType))
    # Set the sampler (if required)
    if samplerType:
        props.Set(pyluxcore.Property("sampler.type", samplerType))

    config = pyluxcore.RenderConfig(props)

    # Run the rendering
    StandardAnimTest(
        cls, "SceneEditRendering_" + engineType + ("" if not samplerType else
                                                   ("_" + samplerType)),
        config, 5)
Esempio n. 16
0
    def RunRemoveUnusedTest(self, name, removeImageMaps, removeUnusedTexs,
                            removeUnusedMats, removeUnusedMeshes, editProps):
        # Load the configuration from file
        props = pyluxcore.Properties(
            "resources/scenes/simple/texture-imagemap.cfg")

        # Change the render engine to PATHCPU
        props.Set(pyluxcore.Property("renderengine.type", ["PATHCPU"]))
        props.Set(pyluxcore.Property("sampler.type", ["RANDOM"]))
        props.Set(GetDefaultEngineProperties("PATHCPU"))
        # Delete halt condition
        props.Delete("batch.haltthreshold")

        config = pyluxcore.RenderConfig(props)
        session = pyluxcore.RenderSession(config)

        session.Start()
        time.sleep(2.0)
        session.BeginSceneEdit()

        scene = config.GetScene()
        scene.Parse(editProps)

        if (removeImageMaps):
            scene.RemoveUnusedImageMaps()
        if (removeUnusedTexs):
            scene.RemoveUnusedTextures()
        if (removeUnusedMats):
            scene.RemoveUnusedMaterials()
        if (removeUnusedMeshes):
            scene.RemoveUnusedMeshes()

        session.EndSceneEdit()
        time.sleep(5.0)
        session.Stop()

        image = GetImagePipelineImage(session.GetFilm())

        CheckResult(self, image, name, False)
Esempio n. 17
0
    def view_update(self, context):
        print("LuxCore view_update call")

        if (self.session != None):
            self.session.Stop()

        if (self.filmWidth != context.region.width) or (self.filmHeight !=
                                                        context.region.height):
            self.filmWidth = context.region.width
            self.filmHeight = context.region.height
            self.imageBufferFloat = array(
                'f', [0.0] * (self.filmWidth * self.filmHeight * 3))
            print("Film size: %dx%d" % (self.filmWidth, self.filmHeight))

        ########################################################################
        # Setup the rendering
        ########################################################################

        scene = self.ConvertBlenderScene(bpy.context.scene)
        config = pyluxcore.RenderConfig(self.CreateRenderConfigProps(), scene)
        self.session = pyluxcore.RenderSession(config)

        self.session.Start()
Esempio n. 18
0
    def test_Film_SaveLoad(self):
        # Load the configuration from file
        props = pyluxcore.Properties("resources/scenes/simple/simple.cfg")

        # Change the render engine to PATHCPU
        props.Set(pyluxcore.Property("renderengine.type", ["PATHCPU"]))
        props.Set(pyluxcore.Property("sampler.type", ["RANDOM"]))
        props.Set(GetDefaultEngineProperties("PATHCPU"))

        config = pyluxcore.RenderConfig(props)
        session = DoRenderSession(config)

        # Get the imagepipeline result
        filmA = session.GetFilm()
        imageA = GetImagePipelineImage(filmA)

        # Save the film
        filmA.SaveFilm("simple.flm")

        # Load the film
        filmB = pyluxcore.Film("simple.flm")
        self.assertEqual(filmB.GetWidth(), filmA.GetWidth())
        self.assertEqual(filmB.GetHeight(), filmA.GetHeight())

        # Get the imagepipeline result
        imageB = GetImagePipelineImage(filmB)

        # To debug
        #imageA.save("imageA.png")
        #imageB.save("imageB.png")

        # Check if there is a difference
        (sameImage, diffCount, diffImage) = CompareImage(imageA, imageB)

        self.assertTrue(sameImage)

        os.unlink("simple.flm")
Esempio n. 19
0
    def __HandleConnection(self, clientSocket, addr):
        id = str(uuid.uuid4())
        renderConfigFile = "renderfarmnode-" + id + ".bcf"
        filmFile = "renderfarmnode-" + id + ".flm"
        try:
            logger.info("Received connection from: " + str(addr))

            #-----------------------------------------------------------
            # Check pyluxcore version
            #-----------------------------------------------------------

            remoteVersion = socketutils.RecvLine(clientSocket)
            logger.info("Remote pyluxcore version: " + remoteVersion)
            logger.info("Local pyluxcore version: " + pyluxcore.Version())
            if (remoteVersion != pyluxcore.Version()):
                logger.info("No matching pyluxcore versions !")
                socketutils.SendLine(
                    clientSocket,
                    "ERROR: wrong pyluxcore version" + pyluxcore.Version())
                return
            socketutils.SendLine(clientSocket, "OK")

            #-----------------------------------------------------------
            # Receive the RenderConfig serialized file
            #-----------------------------------------------------------

            logger.info("Receiving RenderConfig serialized file: " +
                        renderConfigFile)
            socketutils.RecvFile(clientSocket, renderConfigFile)
            logger.info("Receiving RenderConfig serialized MD5: " +
                        md5utils.md5sum(renderConfigFile))

            #-----------------------------------------------------------
            # Receive the seed
            #-----------------------------------------------------------

            seed = socketutils.RecvLine(clientSocket)
            logger.info("Received seed: " + seed)
            seed = int(seed)

            #-----------------------------------------------------------
            # Read the RenderConfig serialized file
            #-----------------------------------------------------------

            logger.info("Reading RenderConfig serialized file: " +
                        renderConfigFile)
            config = pyluxcore.RenderConfig(renderConfigFile)
            # Sanitize the RenderConfig
            self.__SanitizeRenderConfig(config)
            config.Parse(self.customProperties)

            #-----------------------------------------------------------
            # Start the rendering
            #-----------------------------------------------------------

            session = pyluxcore.RenderSession(config)
            session.Start()

            try:
                socketutils.SendLine(clientSocket, "RENDERING_STARTED")

                statsLine = "Not yet avilable"
                while not self.threadStop:
                    result = socketutils.RecvLineWithTimeOut(clientSocket, 0.2)
                    # Check if there was the timeout
                    if result == None:
                        continue
                    logger.info("Received command: " + result)

                    #-------------------------------------------------------
                    # Update statistics
                    #-------------------------------------------------------

                    session.UpdateStats()

                    stats = session.GetStats()
                    elapsedTime = stats.Get(
                        "stats.renderengine.time").GetFloat()
                    currentPass = stats.Get(
                        "stats.renderengine.pass").GetInt()

                    statsLine = "[Elapsed time: %3dsec][Samples %4d][Avg. samples/sec % 3.2fM on %.1fK tris]" % (
                        elapsedTime, currentPass,
                        stats.Get("stats.renderengine.total.samplesec"
                                  ).GetFloat() / 1000000.0,
                        stats.Get("stats.dataset.trianglecount").GetFloat() /
                        1000.0)

                    #-------------------------------------------------------
                    # Execute the command
                    #-------------------------------------------------------

                    if (result.startswith("ERROR")):
                        logger.info(result)
                        return
                    elif (result == "GET_STATS"):
                        socketutils.SendLine(clientSocket, statsLine)
                    elif (result == "GET_FILM"):
                        # Save the film to a file
                        session.GetFilm().SaveFilm(filmFile)

                        # Transmit the film file
                        socketutils.SendFile(clientSocket, filmFile)
                    elif (result == "DONE"):
                        socketutils.SendOk(clientSocket)
                        break
                    else:
                        raise SyntaxError("Unknow command: " + result)

                    #-------------------------------------------------------
                    # Print some information about the rendering progress
                    #-------------------------------------------------------

                    logger.info(statsLine)
            finally:
                session.Stop()
        except KeyboardInterrupt:
            raise
        except Exception as e:
            logger.exception(e)
        finally:
            try:
                os.remove(filmFile)
            except OSError:
                pass
            try:
                os.remove(filmFile + ".bak")
            except OSError:
                pass
            try:
                os.remove(renderConfigFile)
            except OSError:
                pass

            try:
                clientSocket.shutdown(socket.SHUT_RDWR)
            except:
                pass

            try:
                clientSocket.close()
            except:
                pass

            logger.info("Connection done: " + str(addr))
Esempio n. 20
0
def SaveResumeRenderingS():
	print("Save and Resume example (requires scenes directory)...")

	# Load the configuration from file
	props = pyluxcore.Properties("scenes/luxball/luxball-hdr.cfg")

	# Change the render engine to PATHCPU
	props.Set(pyluxcore.Property("renderengine.type", ["PATHCPU"]))

	config = pyluxcore.RenderConfig(props)
	session = pyluxcore.RenderSession(config)

	session.Start()

	startTime = time.time()
	for i in range(0, 3):
		time.sleep(1)

		elapsedTime = time.time() - startTime

		# Print some information about the rendering progress

		# Update statistics
		session.UpdateStats()

		stats = session.GetStats();
		print("[Elapsed time: %3d/3sec][Samples %4d][Avg. samples/sec % 3.2fM on %.1fK tris]" % (
				stats.Get("stats.renderengine.time").GetFloat(),
				stats.Get("stats.renderengine.pass").GetInt(),
				(stats.Get("stats.renderengine.total.samplesec").GetFloat()  / 1000000.0),
				(stats.Get("stats.dataset.trianglecount").GetFloat() / 1000.0)))
	
	session.Pause()
	
	session.GetFilm().SaveOutput("test-save.png", pyluxcore.FilmOutputType.RGB_IMAGEPIPELINE, pyluxcore.Properties())

	# Save the session resume file
	session.SaveResumeFile("test.rsm")

	# Save the rendered image
	session.GetFilm().Save()
	
	# Stop the rendering
	session.Stop()
	
	# Resume rendering
	print("Resume rendering")

	(config, startState, startFilm) = pyluxcore.RenderConfig.LoadResumeFile("test.rsm")
	session = pyluxcore.RenderSession(config, startState, startFilm)
	
	session.Start()

	startTime = time.time()
	for i in range(0, 3):
		time.sleep(1)

		elapsedTime = time.time() - startTime

		# Print some information about the rendering progress

		# Update statistics
		session.UpdateStats()

		stats = session.GetStats();
		print("[Elapsed time: %3d/3sec][Samples %4d][Avg. samples/sec % 3.2fM on %.1fK tris]" % (
				stats.Get("stats.renderengine.time").GetFloat(),
				stats.Get("stats.renderengine.pass").GetInt(),
				(stats.Get("stats.renderengine.total.samplesec").GetFloat()  / 1000000.0),
				(stats.Get("stats.dataset.trianglecount").GetFloat() / 1000.0)))
	
	session.GetFilm().SaveOutput("test-resume.png", pyluxcore.FilmOutputType.RGB_IMAGEPIPELINE, pyluxcore.Properties())
	session.Stop()
	
	print("Done.")
Esempio n. 21
0
def ImagePipelineEdit():
	print("Image pipeline editing examples (requires scenes directory)...")

	# Load the configuration from file
	props = pyluxcore.Properties("scenes/luxball/luxball-hdr.cfg")

	# Change the render engine to PATHCPU
	props.Set(pyluxcore.Property("renderengine.type", ["PATHCPU"]))

	config = pyluxcore.RenderConfig(props)
	session = pyluxcore.RenderSession(config)

	session.Start()

	startTime = time.time()
	imageSaved = False
	while True:
		time.sleep(1)

		elapsedTime = time.time() - startTime

		# Print some information about the rendering progress

		# Update statistics
		session.UpdateStats()

		stats = session.GetStats();
		print("[Elapsed time: %3d/10sec][Samples %4d][Avg. samples/sec % 3.2fM on %.1fK tris]" % (
				stats.Get("stats.renderengine.time").GetFloat(),
				stats.Get("stats.renderengine.pass").GetInt(),
				(stats.Get("stats.renderengine.total.samplesec").GetFloat()  / 1000000.0),
				(stats.Get("stats.dataset.trianglecount").GetFloat() / 1000.0)))

		if elapsedTime > 5.0 and not imageSaved:
			session.GetFilm().Save()
			os.rename("normal.png", "normal-edit1.png")
			
			# Define the new image pipeline
			props = pyluxcore.Properties()
			props.SetFromString("""
				film.imagepipeline.0.type = TONEMAP_REINHARD02
				film.imagepipeline.1.type = CAMERA_RESPONSE_FUNC
				film.imagepipeline.1.name = Ektachrome_320TCD
				film.imagepipeline.2.type = GAMMA_CORRECTION
				film.imagepipeline.2.value = 2.2
				""")
			session.Parse(props)

			# Change radiance group scale
#			props = pyluxcore.Properties()
#			props.SetFromString("""
#				film.radiancescales.0.rgbscale = 1.0 0.0 0.0
#				""")
#			session.Parse(props)

			imageSaved = True

		if elapsedTime > 10.0:
			# Time to stop the rendering
			break

	session.Stop()

	# Save the rendered image
	session.GetFilm().Save()
	os.rename("normal.png", "normal-edit2.png")

	print("Done.")
Esempio n. 22
0
def StrandsRender():
	print("Strands example...")

	# Create the rendering configuration
	cfgProps = pyluxcore.Properties()
	cfgProps.SetFromString("""
		film.width = 640
		film.height = 480
		""")

	# Set the rendering engine
	cfgProps.Set(pyluxcore.Property("renderengine.type", ["PATHCPU"]))

	# Create the scene properties
	scnProps = pyluxcore.Properties()
	
	# Set the camera position
	scnProps.SetFromString("""
		scene.camera.lookat.orig = 0.0 5.0 2.0
		scene.camera.lookat.target = 0.0 0.0 0.0
		""")
	
	# Define a white matte material
	scnProps.SetFromString("""
		scene.materials.whitematte.type = matte
		scene.materials.whitematte.kd = 0.75 0.75 0.75
		""")

	# Add a plane
	scnProps.Set(BuildPlane("plane1", "whitematte"))
	
	# Add a distant light source
	scnProps.SetFromString("""
		scene.lights.distl.type = sharpdistant
		scene.lights.distl.color = 1.0 1.0 1.0
		scene.lights.distl.gain = 2.0 2.0 2.0
		scene.lights.distl.direction = 1.0 1.0 -1.0
		""")
	
	# Create the scene
	#resizePolicyProps = pyluxcore.Properties()
	#resizePolicyProps.SetFromString("""
	#	scene.images.resizepolicy.type = "MIPMAPMEM"
	#	scene.images.resizepolicy.scale = 1.0
	#	scene.images.resizepolicy.minsize = 64
	#	""")
	#scene = pyluxcore.Scene(scnProps, resizePolicyProps)

	scene = pyluxcore.Scene()
	scene.Parse(scnProps)

	# Add strands
	points = []
	segments = []
	strandsCount = 30
	for i in range(strandsCount):
		x = random.random() * 2.0 - 1.0
		y = random.random() * 2.0 - 1.0
		points.append((x , y, 0.0))
		points.append((x , y, 1.0))
		segments.append(1)

	scene.DefineStrands("strands_shape", strandsCount, 2 * strandsCount, points, segments,
		0.025, 0.0, (1.0, 1.0, 1.0), None, "ribbon",
		0, 0, 0, False, False, True)
		
	strandsProps = pyluxcore.Properties()
	strandsProps.SetFromString("""
		scene.objects.strands_obj.material = whitematte
		scene.objects.strands_obj.shape = strands_shape
		""")
	scene.Parse(strandsProps)

	# Save the strand mesh (just for testing)
	scene.SaveMesh("strands_shape", "strands_shape.ply")

	# Create the render config
	config = pyluxcore.RenderConfig(cfgProps, scene)
	session = pyluxcore.RenderSession(config)

	session.Start()

	startTime = time.time()
	while True:
		time.sleep(1)

		elapsedTime = time.time() - startTime

		# Print some information about the rendering progress

		# Update statistics
		session.UpdateStats()

		stats = session.GetStats();
		print("[Elapsed time: %3d/5sec][Samples %4d][Avg. samples/sec % 3.2fM on %.1fK tris]" % (
				stats.Get("stats.renderengine.time").GetFloat(),
				stats.Get("stats.renderengine.pass").GetInt(),
				(stats.Get("stats.renderengine.total.samplesec").GetFloat()  / 1000000.0),
				(stats.Get("stats.dataset.trianglecount").GetFloat() / 1000.0)))

		if elapsedTime > 5.0:
			# Time to stop the rendering
			break

	session.Stop()

	# Save the rendered image
	session.GetFilm().Save()

	print("Done.")
Esempio n. 23
0
def GetOutputTest():
	print("Film getOutput() example (requires scenes directory)...")

	# Load the configuration from file
	props = pyluxcore.Properties("scenes/luxball/luxball-hdr.cfg")

	# Change the render engine to PATHCPU
	props.Set(pyluxcore.Property("renderengine.type", ["PATHCPU"]))

	config = pyluxcore.RenderConfig(props)
	session = pyluxcore.RenderSession(config)

	# NOTICE THE DIFFERENT BEHAVIOR REQUIRED BY PYTHON 3.3, 2.7 and 2.6
	filmWidth, filmHeight = config.GetFilmSize()[:2]
	if sys.version_info < (2,7,0):
		imageBufferFloat = bytearray(filmWidth * filmHeight * 3 * 4)
		imageBufferUChar = bytearray(filmWidth * filmHeight * 4)
	elif sys.version_info < (3,0,0):
		imageBufferFloat = buffer(array('f', [0.0] * (filmWidth * filmHeight * 3)))
		imageBufferUChar = buffer(array('B', [0] * (filmWidth * filmHeight * 4)))
	else:
		imageBufferFloat = array('f', [0.0] * (filmWidth * filmHeight * 3))
		imageBufferUChar = array('B', [0] * (filmWidth * filmHeight * 4))

	session.Start()

	startTime = time.time()
	imageIndex = 0
	while True:
		time.sleep(1)

		elapsedTime = time.time() - startTime

		# Print some information about the rendering progress

		# Update statistics
		session.UpdateStats()

		stats = session.GetStats();
		print("[Elapsed time: %3d/5sec][Samples %4d][Avg. samples/sec % 3.2fM on %.1fK tris]" % (
				stats.Get("stats.renderengine.time").GetFloat(),
				stats.Get("stats.renderengine.pass").GetInt(),
				(stats.Get("stats.renderengine.total.samplesec").GetFloat()  / 1000000.0),
				(stats.Get("stats.dataset.trianglecount").GetFloat() / 1000.0)))

		# This is mostly for testing the PyLuxCore functionality, save an image every second

		# Update the image
		session.GetFilm().GetOutputFloat(pyluxcore.FilmOutputType.RGB_IMAGEPIPELINE, imageBufferFloat)
		pyluxcore.ConvertFilmChannelOutput_3xFloat_To_4xUChar(filmWidth, filmHeight,
			imageBufferFloat, imageBufferUChar, False)

		# Save the imageBufferUChar buffer to a PPM file
		imageFileName = "image" + str(imageIndex) + ".ppm"
		print("Saving image file: " + imageFileName)
		f = open(imageFileName, "w")
		f.write("P3\n")
		f.write(str(filmWidth) + " " + str(filmHeight) + "\n")
		f.write("255\n")
		for i in range(0, len(imageBufferUChar), 4):
			f.write(str(imageBufferUChar[i + 2]) + " " + str(imageBufferUChar[i + 1]) + " " + str(imageBufferUChar[i]) + "\n")
		f.close()
		imageIndex += 1

		if elapsedTime > 5.0:
			# Time to stop the rendering
			break

	session.Stop()

	print("Done.")
Esempio n. 24
0
def LuxCoreConsole(argv):
    parser = argparse.ArgumentParser(description="PyLuxCoreConsole")
    parser.add_argument("fileToRender",
                        help=".cfg, .lxs, .bcf or .rsm file to render")
    parser.add_argument("-f",
                        "--scene",
                        metavar="FILE_NAME",
                        nargs=1,
                        help="scene file name")
    parser.add_argument("-w",
                        "--film-width",
                        metavar="WIDTH",
                        nargs=1,
                        type=int,
                        help="film width")
    parser.add_argument("-e",
                        "--film-height",
                        metavar="HEIGHT",
                        nargs=1,
                        type=int,
                        help="film height")
    parser.add_argument("-D",
                        "--define",
                        metavar=("PROP_NAME", "VALUE"),
                        nargs=2,
                        action="append",
                        help="assign a value to a property")
    parser.add_argument("-d",
                        "--current-dir",
                        metavar="DIR_NAME",
                        nargs=1,
                        help="current directory path")
    parser.add_argument(
        "-c",
        "--remove-unused",
        action="store_true",
        help="remove all unused meshes, materials, textures and image maps")
    parser.add_argument("-t",
                        "--camera-shutter",
                        metavar="CAMERA_SHUTTER",
                        nargs=2,
                        type=float,
                        help="camera shutter open/close")

    # Parse command line arguments
    args = parser.parse_args(argv)
    cmdLineProp = pyluxcore.Properties()
    if (args.scene):
        cmdLineProp.Set(pyluxcore.Property("scene.file", args.scene))
    if (args.film_width):
        cmdLineProp.Set(pyluxcore.Property("film.width", args.film_width))
    if (args.film_height):
        cmdLineProp.Set(pyluxcore.Property("film.height", args.film_height))
    if (args.define):
        for (name, value) in args.define:
            cmdLineProp.Set(pyluxcore.Property(name, value))
    if (args.current_dir):
        os.chdir(args.current_dir[0])
    removeUnused = args.remove_unused

    if (not args.fileToRender):
        raise TypeError("File to render must be specified")

    # Load the file to render
    config = None
    startState = None
    startFilm = None
    configFileNameExt = os.path.splitext(args.fileToRender)[1]
    if (configFileNameExt == ".lxs"):
        # It is a LuxRender SDL file
        logger.info("Parsing LuxRender SDL file...")

        # Parse the LXS file
        configProps = pyluxcore.Properties()
        sceneProps = pyluxcore.Properties()
        pyluxcore.ParseLXS(args.fileToRender, configProps, sceneProps)
        configProps.Set(cmdLineProp)

        scene = pyluxcore.Scene(
            configProps.Get("images.scale", [1.0]).GetFloat())
        scene.Parse(sceneProps)

        config = pyluxcore.RenderConfig(configProps, scene)
    elif (configFileNameExt == ".cfg"):
        # It is a LuxCore SDL file
        configProps = pyluxcore.Properties(args.fileToRender)
        configProps.Set(cmdLineProp)
        config = pyluxcore.RenderConfig(configProps)
    elif (configFileNameExt == ".bcf"):
        # It is a LuxCore RenderConfig binary archive
        config = pyluxcore.RenderConfig(args.fileToRender)
        config.Parse(cmdLineProp)
    elif (configFileNameExt == ".rsm"):
        # It is a rendering resume file
        (config, startState,
         startFilm) = pyluxcore.RenderConfig.LoadResumeFile(args.fileToRender)
        config.Parse(cmdLineProp)
    else:
        raise TypeError("Unknown file extension: " + args.fileToRender)

    if (removeUnused):
        config.GetScene().RemoveUnusedMeshes()
        config.GetScene().RemoveUnusedImageMaps()
        config.GetScene().RemoveUnusedMaterials()
        config.GetScene().RemoveUnusedTextures()

    # Overwrite camera shutter open/close
    if (args.camera_shutter):
        cameraProps = config.GetScene().ToProperties().GetAllProperties(
            "scene.camera")
        cameraProps.Set(
            pyluxcore.Property("scene.camera.shutteropen",
                               [args.camera_shutter[0]]))
        cameraProps.Set(
            pyluxcore.Property("scene.camera.shutterclose",
                               [args.camera_shutter[1]]))
        config.GetScene().Parse(cameraProps)

    # Force the film update at 2.5secs (mostly used by PathOCL)
    # Skip in case of a FILESAVER
    isFileSaver = (
        config.GetProperty("renderengine.type").GetString() == "FILESAVER")
    if (not isFileSaver):
        config.Parse(pyluxcore.Properties().Set(
            pyluxcore.Property("screen.refresh.interval", 2500)))

    session = BatchRendering(config, startState, startFilm)

    if (not isFileSaver):
        # Save the rendered image
        session.GetFilm().Save()

    logger.info("Done.")
Esempio n. 25
0
def build_session(scene, output_name):
    props = pyluxcore.Properties()
    props.SetFromString("""
        opencl.cpu.use = 0
        # Use all GPU devices we can find
        opencl.gpu.use = 1
        # You can use this setting to specify exactly which OpenCL devices to use
        #opencl.devices.select = "1"

        renderengine.type = "PATHCPU"
        sampler.type = "SOBOL"
        #renderengine.type = "TILEPATHOCL"
        #sampler.type = "TILEPATHSAMPLER"
        #pathocl.pixelatomics.enable = 1
        renderengine.seed = 1
        path.pathdepth.total = 17
        path.pathdepth.diffuse = 10
        path.pathdepth.glossy = 17
        path.pathdepth.specular = 16

        path.photongi.sampler.type = METROPOLIS
        path.photongi.photon.maxcount = 10000000
        path.photongi.photon.maxdepth = 16
        path.photongi.photon.time.start = 0.0
        path.photongi.photon.time.end = 1.0
        #path.photongi.indirect.enabled = 1
        #path.photongi.indirect.maxsize = 100000
        #path.photongi.indirect.haltthreshold = 0.05
        #path.photongi.indirect.lookup.radius = 0.15
        #path.photongi.indirect.glossinessusagethreshold = 0.0
        #path.photongi.indirect.usagethresholdscale = 0.0
        #path.photongi.indirect.filter.radiusscale = 4.0
        #path.photongi.caustic.enabled = 0
        #path.photongi.caustic.maxsize = 10000
        #path.photongi.caustic.lookup.radius = 0.15
        #path.photongi.debug.type = showindirect
        #path.photongi.debug.type = showcaustic
        #path.photongi.debug.type = showindirectpathmix
        path.photongi.persistent.file = cornell.pgi
                
        film.width = 768
        film.height = 768
        
        film.imagepipelines.0.0.type = "NOP"
        film.imagepipelines.0.1.type = "TONEMAP_LUXLINEAR"
        film.imagepipelines.0.1.fstop = 4
        film.imagepipelines.0.1.exposure = 100
        film.imagepipelines.0.1.sensitivity = 150
        film.imagepipelines.0.2.type = "GAMMA_CORRECTION"
        film.imagepipelines.0.2.value = 2.2000000000000002
        
        film.imagepipelines.1.0.type = INTEL_OIDN
        film.imagepipelines.1.1.type = "TONEMAP_LUXLINEAR"
        film.imagepipelines.1.1.fstop = 4
        film.imagepipelines.1.1.exposure = 100
        film.imagepipelines.1.1.sensitivity = 150
        film.imagepipelines.1.2.type = "GAMMA_CORRECTION"
        film.imagepipelines.1.2.value = 2.2000000000000002
        
        #film.imagepipelines.0.1.type = GAMMA_CORRECTION
        #film.imagepipelines.0.1.value = 7.0
        #film.imagepipelines.0.0.type = BCD_DENOISER
        #film.imagepipelines.0.1.type = GAMMA_CORRECTION
        #film.imagepipelines.0.1.value = 2.2
        
        film.filter.type = "BLACKMANHARRIS"
        film.filter.width = 1.5
        film.outputs.0.type = "RGB_IMAGEPIPELINE"
        film.outputs.0.index = 0
        film.outputs.0.filename = """ + output_name + "_noisy.png" + """
        film.outputs.1.type = RGB_IMAGEPIPELINE
        film.outputs.1.index = 1
        film.outputs.1.filename = """ + output_name + ".png" + """
        film.outputs.2.type = ALBEDO
        film.outputs.2.filename = """ + output_name + "_" + "ALBEDO.png" + """
        film.outputs.3.type = AVG_SHADING_NORMAL
        film.outputs.3.filename = """ + output_name + "_" + "AVG_SHADING_NORMAL.png" + """
        scene.file = "freefall.scn"
        """)

    renderconfig = pyluxcore.RenderConfig(props, scene)
    session = pyluxcore.RenderSession(renderconfig)
    return session
Esempio n. 26
0
def RenderConfigOps():
    props = pyluxcore.Properties("scenes/luxball/luxball-hdr.cfg")
    config = pyluxcore.RenderConfig(props)