예제 #1
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)
예제 #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.")
예제 #3
0
    def filmSetOutputChannel(self, type):
        # Stop the rendering
        self.session.Stop()
        self.session = None

        # Delete old channel outputs
        self.config.Delete("film.outputs")

        # Set the new channel outputs
        self.config.Parse(pyluxcore.Properties().Set(
            pyluxcore.Property(
                "film.outputs.1.type", ["RGB_IMAGEPIPELINE"])).Set(
                    pyluxcore.Property(
                        "film.outputs.1.filename",
                        ["luxball_RGB_IMAGEPIPELINE.png"])).Set(
                            pyluxcore.Property(
                                "film.outputs.2.type", [str(type)])).Set(
                                    pyluxcore.Property(
                                        "film.outputs.2.filename",
                                        ["luxball_SELECTED_OUTPUT.exr"])))
        self.selectedFilmChannel = type

        # Re-start the rendering
        self.session = pyluxcore.RenderSession(self.config)
        self.session.Start()
        print("Film channel selected: %s" % (str(type)))
예제 #4
0
    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)
예제 #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.")
예제 #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()
예제 #7
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()
예제 #8
0
def DoRenderSession(config):
	session = pyluxcore.RenderSession(config)

	session.Start()
	session.WaitForDone()
	session.Stop()

	return session
예제 #9
0
def Render(config):
	session = pyluxcore.RenderSession(config)

	session.Start()
	session.WaitForDone()
	session.Stop()

	return GetRendering(session)
예제 #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.")
예제 #11
0
    def setup(self):
        self.session = pyluxcore.RenderSession(self.config)
        self.selectedFilmChannel = pyluxcore.FilmOutputType.RGB_IMAGEPIPELINE
        self.filmWidth, self.filmHeight = self.config.GetFilmSize()[:2]
        self.allocateImageBuffers()
        self.resize(self.filmWidth + 60, self.filmHeight + 130)
        print("File loaded")
        self.update()

        if self.fromSu == True:
            if self.eximage != "":
                self.configProps.SetFromString("""
                film.outputs.0.filename = "{image}"
                """.format(image=self.eximage))
            self.render_image()
예제 #12
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")
예제 #13
0
	def resizeEvent(self, event):
		if (event.size().width() != self.filmWidth) or (event.size().height() != self.filmHeight):
			# Stop the rendering
			self.session.Stop()
			self.session = None

			# Set the new size
			self.filmWidth = int(event.size().width())
			self.filmHeight = int(event.size().height())
			self.config.Parse(pyluxcore.Properties().
				Set(pyluxcore.Property("film.width", [self.filmWidth])).
				Set(pyluxcore.Property("film.height", [self.filmHeight])))
			self.allocateImageBuffers()

			# Re-start the rendering
			self.session = pyluxcore.RenderSession(self.config)
			self.session.Start()
		
		super(RenderView, self).resizeEvent(event)
예제 #14
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])
예제 #15
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)
예제 #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)
예제 #17
0
def BatchRendering(config, startState=None, startFilm=None):
    session = pyluxcore.RenderSession(config, startState, startFilm)

    haltTime = config.GetProperty("batch.halttime").GetInt()
    haltSpp = config.GetProperty("batch.haltspp").GetInt()

    session.Start()

    try:
        while not session.HasDone():
            time.sleep(1.0)

            # Print some information about the rendering progress

            # Update statistics
            session.UpdateStats()

            stats = session.GetStats()
            elapsedTime = stats.Get("stats.renderengine.time").GetFloat()
            currentPass = stats.Get("stats.renderengine.pass").GetInt()
            # Convergence test is update inside UpdateFilm()
            convergence = stats.Get(
                "stats.renderengine.convergence").GetFloat()

            logger.info(
                "[Elapsed time: %3d/%dsec][Samples %4d/%d][Convergence %f%%][Avg. samples/sec % 3.2fM on %.1fK tris]"
                %
                (elapsedTime, haltTime, currentPass, haltSpp,
                 100.0 * convergence,
                 stats.Get("stats.renderengine.total.samplesec").GetFloat() /
                 1000000.0,
                 stats.Get("stats.dataset.trianglecount").GetFloat() / 1000.0))
    except KeyboardInterrupt:
        pass

    session.Stop()

    return session
예제 #18
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()
예제 #19
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.")
예제 #20
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.")
예제 #21
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.")
예제 #22
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.")
예제 #23
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
예제 #24
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))