Start, configure, get output

NpOptiX.start() → None[source]

Start the raytracing, compute, and UI threads.

Actions provided with on_initialization parameter of NpOptiX constructor are executed by this method on the main thread, before starting the ratracing thread.

NpOptiX.close() → None[source]

Stop the raytracing thread, release resources.

Raytracing cannot be restarted after this method is called.

Override in UI class, call this base implementation (or raise a close event for your UI and call this base implementation there).

NpOptiX.get_scene() → dict[source]

Get dictionary with the scene description.

Returns a dictionary with the scene description. Geometry objects, materials, lights, texture data or file names, cameras, postprocessing and scene parameters are included. Callback functions and vieport dimensions are not saved. Existing files are overwritten.

Returns

out – Dictionary with the scene description.

Return type

dict, optional

NpOptiX.set_scene(scene: dict) → None[source]

Setup scene using description in provided dictionary.

Set new scene using provided description (and destroy current scene). Geometry objects, materials, lights, texture data or file names, cameras, postprocessing and scene parameters are replaced. Callback functions and vieport dimensions are preserved.

Note: locations of external resources loaded from files (e.g. textures) are saved as relative paths, ensure your working directory matches these locations.

Parameters

scene (dict) – Dictionary with the scene description.

NpOptiX.load_scene(file_name: str) → None[source]

Load scene description from JSON file.

Load new scene from JSON file (and destroy current scene). Geometry objects, materials, lights, texture data or file names, cameras, postprocessing and scene parameters are replaced. Callback functions and vieport dimensions are preserved.

Parameters

file_name (str) – Input file name.

NpOptiX.save_scene(file_name: str) → None[source]

Save scene description to JSON file.

Save description of the scene to file. Geometry objects, materials, lights, texture data or file names, cameras, postprocessing and scene parameters are included. Callback functions and vieport dimensions are not saved. Existing files are overwritten.

Parameters

file_name (str) – Output file name.

NpOptiX.save_image(file_name: str, bps: Union[plotoptix.enums.ChannelDepth, str] = <ChannelDepth.Bps8: 1>) → None[source]

Save current image to file.

Save current content of the image buffer to a file. Accepted formats, recognized by the extension used in the file_name, are:

  • bmp, gif, png, jpg, and tif for 8bps color depth,

  • png (Windows only), and tif for 16bps color depth,

  • tif for 32bps hdr images.

Existing files are overwritten.

Parameters
  • file_name (str) – Output file name.

  • bps (ChannelDepth enum or string, optional) – Color depth.

NpOptiX.get_rt_output(bps: Union[plotoptix.enums.ChannelDepth, str] = <ChannelDepth.Bps8: 1>, channels: Union[plotoptix.enums.ChannelOrder, str] = <ChannelOrder.RGBA: 3>) → Optional[numpy.ndarray][source]

Return a copy of the output image.

The image data type is specified with the bps argument. 8 bit per channel data, numpy.uint8, is returned by default. Use Bps16 value to read the image in 16 bit per channel depth, numpy.uint16. Use Bps32 value to read the HDR image in 32 bit per channel format, numpy.float32.

If channels ordering includes alpha channel then it is a constant, 100% opaque value, to be used in the future releases.

Safe to call at any time, from any thread.

Parameters
  • bps (ChannelDepth enum or string, optional) – Color depth.

  • channels (ChannelOrder enum or string, optional) – Color channels ordering.

Returns

out – RGB(A) array of shape (height, width, 3) or (height, width, 4) and type corresponding to bps argument. None in case of errors.

Return type

ndarray

NpOptiX._img_rgba = None

Ray-tracing output, 8bps color.

Shape: (height, width, 4), dtype = np.uint8, contains RGBA data (alpha channel is now constant, 255).

A ndarray wrapped aroud the gpu bufffer. It enables reading the image with no additional memory copy. Access the buffer in the on_launch_finished callback or in/after the on_rt_accum_done callback to avoid reading while the buffer content is being updated.

NpOptiX._raw_rgba = None

Ray-tracing output, raw floating point data.

Shape: (height, width, 4), dtype = np.float32, contains RGBA data (alpha channel is now constant, 1.0).

A ndarray wrapped aroud the gpu bufffer. It enables reading the image with no additional memory copy. Access the buffer in the on_launch_finished callback or in/after the on_rt_accum_done callback to avoid reading while the buffer content is being updated.

NpOptiX._hit_pos = None

Hit position.

Shape: (height, width, 4), dtype = np.float32, contains [X, Y, Z, D] data, where XYZ is the hit 3D position and D is the hit distance to the camera plane.

NpOptiX._geo_id = None

Object info.

Encodes the object handle and primitive index (or vertex/face index for meshes) for each pixel in the output image.

Shape: (height, width, 2), dtype = np.int32, contains:
  • _geo_id[h, w, 0] = handle | (vtx_id << 30), where handle is the object handle, vtx_id is the vertex index for the triangular face that was hit (values are 0, 1, 2);

  • _geo_id[h, w, 1] = prim_idx, where prim_idx is the primitive index in a data set, or face index of a mesh.

NpOptiX._albedo = None

Surface albedo.

Shape: (height, width, 4), dtype = np.float32, contains RGBA data (alpha channel is now constant, 0.0).

Available when denoiser is enabled (plotoptix.enums.Postprocessing.Denoiser), and set to plotoptix.enums.DenoiserKind.RgbAlbedo or plotoptix.enums.DenoiserKind.RgbAlbedoNormal mode, or when save_albedo parameter is set to True (see plotoptix.NpOptiX.set_param()).

NpOptiX._normal = None

Surface normal.

Shape: (height, width, 4), dtype = np.float32, contains XYZ0 data (4’th channel is constant, 0.0).

Surface normal vector in camera space. Available only when the denoiser is enabled (plotoptix.enums.Postprocessing.Denoiser), and set to plotoptix.enums.DenoiserKind.RgbAlbedoNormal mode, or when save_normals parameter is set to True (see plotoptix.NpOptiX.set_param()).

NpOptiX._run_event_loop()[source]

Internal method for running the UI event loop.

This method should be overriden in derived UI class (but do not call this base implementation).

Remember to set self._started_event after all your UI initialization.

NpOptiX.run()[source]

Starts UI event loop.

Derived from threading.Thread.

Use plotoptix.NpOptiX.start() to perform complete initialization.

Do not override, use plotoptix.NpOptiX._run_event_loop() instead.

NpOptiX.get_gpu_architecture(ordinal: int) → Optional[plotoptix.enums.GpuArchitecture][source]

Get SM architecture of selected GPU.

Returns architecture of selected GPU.

Parameters

ordinal (int) – CUDA ordinal of the GPU.

Returns

out – SM architecture or None if not recognized.

Return type

GpuArchitecture or None

Scene configuration

NpOptiX.set_ambient(color: Any, refresh: bool = False) → None[source]

Set ambient light color.

Set ambient light color of the scene (shader variable ambient_color, default value is [0.86, 0.89, 0.94]). Raytrace the whole scene if refresh is set to True. Note, color components range is <0; 1>.

Parameters
  • color (Any) – New ambient light color value; single value is a grayscale level, RGB color components can be provided as array-like values.

  • refresh (bool, optional) – Set to True if the image should be re-computed.

Examples

>>> optix = TkOptiX()
>>> optix.set_ambient(0.5) # set dim gray light
>>> optix.set_ambient([0.1, 0.2, 0.3]) # set dim bluish light
NpOptiX.get_ambient() -> (<class 'float'>, <class 'float'>, <class 'float'>)[source]

Get ambient color.

Returns

out – Color values (r, g, b) of the ambient light color.

Return type

tuple (float, float, float)

NpOptiX.set_background(bg: Any, rt_format: Union[plotoptix.enums.RtFormat, str] = <RtFormat.Float4: 260>, prescale: float = 1.0, baseline: float = 0.0, exposure: float = 1.0, gamma: float = 1.0, keep_on_host: bool = False, refresh: bool = False) → None[source]

Set background color.

Set background color or texture (shader variable bg_color, texture bg_texture or bg_texture8 depending on the rt_format). Raytrace the whole scene if refresh is set to True. Texture should be provided as an array of shape (height, width, n), where n is 3 or 4. 3-component RGB arrays are extended to 4-component RGBA shape (alpha channel is reserved for future implementations).

Function attempts to load texture from file if bg is a string.

Color values are corrected to account for the postprocessing tone mapping if exposure and gamma values are provided.

Use keep_on_host=True to make a copy of data in the host memory (in addition to GPU memory), this option is required when (small) textures are going to be saved to JSON description of the scene.

Note, color components range is <0; 1>.

Parameters
  • bg (Any) – New backgroud color or texture data; single value is a grayscale level, RGB color components can be provided as an array-like values, texture is provided as an array of shape (height, width, n) or string with the source image file path.

  • rt_format (RtFormat, optional) – Target format of the texture.

  • prescale (float, optional) – Scaling factor for color values.

  • baseline (float, optional) – Baseline added to color values.

  • exposure (float, optional) – Exposure value used in the postprocessing.

  • gamma (float, optional) – Gamma value used in the postprocessing.

  • keep_on_host (bool, optional) – Store texture data copy in the host memory.

  • refresh (bool, optional) – Set to True if the image should be re-computed.

Examples

>>> optix = TkOptiX()
>>> optix.set_background(0.5) # set gray background
>>> optix.set_background([0.5, 0.7, 0.9]) # set light bluish background
NpOptiX.get_background() -> (<class 'float'>, <class 'float'>, <class 'float'>)[source]

Get background color.

Note, currently returns constant background color also in texture based background modes.

Returns

out – Color values (r, g, b) of the background color.

Return type

tuple (float, float, float)

NpOptiX.get_background_mode() → Optional[plotoptix.enums.MissProgram][source]

Get currently configured miss program.

Returns

out – Miss program, see plotoptix.enums.MissProgram, or None if reading the mode failed.

Return type

MissProgram or None

NpOptiX.set_background_mode(mode: Union[plotoptix.enums.MissProgram, str], refresh: bool = False) → None[source]

Set miss program.

Parameters
  • mode (MissProgram enum or string) – Miss program, see plotoptix.enums.MissProgram.

  • refresh (bool, optional) – Set to True if the image should be re-computed.

NpOptiX.refresh_scene() → None[source]

Refresh scene

Starts raytracing accumulation from scratch.

NpOptiX.resize(width: Optional[int] = None, height: Optional[int] = None) → None[source]

Change dimensions of the raytracing output.

Both or one of the dimensions may be provided. No effect if width and height is same as of the current output.

Parameters
  • width (int, optional) – New width of the raytracing output.

  • height (int, optional) – New height of the raytracing output.

Raytracer configuration

Ray tracing algorithms are controlled via variables allocated in the host memory and on the GPU. Host variables can be modified with plotoptix.NpOptiX.set_param() method and are described there. Values of host variables are available through the plotoptix.NpOptiX.get_param() method. Most of GPU variables controll postprocessing algorithms (see description in plotoptix.enums.Postprocessing). These variables are accessed via plotoptix.NpOptiX.set_int() / plotoptix.NpOptiX.get_int() and similar methods.

GPU variables related to the raytracer general configuraton are documented below:

  • Number of the ray segments

    Name: path_seg_range

    Type: uint2

    Default value: [2, 6]

    Description: [min, max] range of the ray segments; if the ray is scattered, reflected or refracted more than min times it may be terminated with the Russian Roulette algorithm but the number of segments never exceeds max. Use higher values in scenes with multiple transparent and/or reflective objects and if you need the high quality of diffuse lights. Use lower values to increase performance.

    Example:

    rt = TkOptiX()
    rt.set_uint("path_seg_range", 4, 16)
    
  • Ray tracing precision

    Name: scene_epsilon

    Type: float

    Default value: 0.002

    Description: epsilon value used whenever a geometrical computation threshold is needed, e.g. as a minimum distance between hits or displacement of the ray next segment in the normal direction. You may need to set a lower value if your scene dimensions are tiny, or increase the value to avoid artifacts (e.g. in scenes with huge amounts of very small primitives).

    Example:

    rt = TkOptiX()
    rt.set_float("scene_epsilon", 1.0e-04)
    
NpOptiX.set_param(**kwargs) → None[source]

Set raytracer parameter(s).

Available parameters:

  • compute_timeout: timeout for the computation thread

    Set this parameter if the computations performed in the scene_compute callback are longer than the frame ray tracing. See also plotoptix.NpOptiX.set_scene_compute_cb().

  • light_shading: light shading mode.

    Use plotoptix.enums.LightShading.Hard for best caustics or plotoptix.enums.LightShading.Soft for fast convergence. String names "Hard" and "Soft" are accepted.

    Set mode before adding lights.

  • max_accumulation_frames

    Number of accumulation frames computed for the scene.

  • min_accumulation_step

    Number of accumulation frames computed in a single step (before each image refresh).

  • rt_timeout

    Ray tracing timeout. Default value is 30000 (30s).

  • save_albedo

    Allocate buffer and collect albedo information if set to True. If set to False then buffer is allocated only if denoiser requires it.

  • save_normals

    Allocate buffer and collect normals if set to True. If set to False then buffer is allocated only if denoiser requires it.

Parameters

kwargs (Any) – Values of parameters corresponding to provided names.

Examples

>>> optix = TkOptiX()
>>> optix.set_param(min_accumulation_step=4, max_accumulation_frames=200)
NpOptiX.get_param(name: str) → Optional[Any][source]

Get raytracer parameter.

Available parameters:

  • compute_timeout

  • light_shading

  • max_accumulation_frames

  • min_accumulation_step

  • rt_timeout

  • save_albedo

  • save_normals

Parameters

name (string) – Parameter name.

Returns

out – Value of the parameter or None if parameter not found.

Return type

Any, optional

Examples

>>> optix = TkOptiX()
>>> print(optix.get_param("max_accumulation_frames"))
NpOptiX.set_int(name: str, x: int, refresh: bool = False) → None[source]

Set shader variable.

Set shader variable with given name and of the type int. Raytrace the whole scene if refresh is set to True. Note, shader variables distinguish int and uint while the type provided by Python methods is int in both cases.

Parameters
  • name (string) – Variable name.

  • x (int) – Variable value.

  • refresh (bool, optional) – Set to True if the image should be re-computed.

NpOptiX.get_int(name: str) → Optional[int][source]

Get shader int variable with given name.

Parameters

name (string) – Variable name.

Returns

out – Value of the variable or None if variable not found.

Return type

int

NpOptiX.set_uint(name: str, x: int, y: Optional[int] = None, refresh: bool = False) → None[source]

Set shader variable.

Set shader variable with given name and of the type uint or uint2 (if y provided). Raytrace the whole scene if refresh is set to True. Note, shader variables distinguish int and uint while the type provided by Python methods is int in both cases.

Parameters
  • name (string) – Variable name.

  • x (int) – Variable value (x component in case of uint2).

  • y (int, optional) – Y component value for uint2 variable.

  • refresh (bool, optional) – Set to True if the image should be re-computed.

Examples

>>> optix = TkOptiX()
>>> optix.set_uint("path_seg_range", 4, 16) # set longer range of traced path segments
NpOptiX.get_uint(name: str) → Optional[int][source]

Get shader uint variable with given name.

Parameters

name (string) – Variable name.

Returns

out – Value of the variable or None if variable not found.

Return type

int

NpOptiX.get_uint2(name: str) -> (typing.Union[int, NoneType], typing.Union[int, NoneType])[source]

Get shader uint2 variable with given name.

Parameters

name (string) – Variable name.

Returns

out – Value (x, y) of the variable or (None, None) if variable not found.

Return type

tuple (int, int)

NpOptiX.set_float(name: str, x: float, y: Optional[float] = None, z: Optional[float] = None, refresh: bool = False) → None[source]

Set shader variable.

Set shader variable with given name and of the type float, float2 (if y provided), or float3 (if y and z provided). Raytrace the whole scene if refresh is set to True.

Parameters
  • name (string) – Vairable name.

  • x (float) – Variable value (x component in case of float2 and float3).

  • y (float, optional) – Y component value for float2 and float3 variables.

  • z (float, optional) – Z component value for float3 variables.

  • refresh (bool, optional) – Set to True if the image should be re-computed.

Examples

>>> optix = TkOptiX()
>>> optix.set_float("tonemap_exposure", 0.8)
>>> optix.set_float("tonemap_gamma", 2.2)
NpOptiX.get_float(name: str) → Optional[float][source]

Get shader float variable with given name.

Parameters

name (string) – Variable name.

Returns

out – Value of the variable or None if variable not found.

Return type

float

NpOptiX.get_float2(name: str) -> (typing.Union[float, NoneType], typing.Union[float, NoneType])[source]

Get shader float2 variable with given name.

Parameters

name (string) – Variable name.

Returns

out – Value (x, y) of the variable or (None, None) if variable not found.

Return type

tuple (float, float)

NpOptiX.get_float3(name: str) -> (typing.Union[float, NoneType], typing.Union[float, NoneType], typing.Union[float, NoneType])[source]

Get shader float3 variable with given name.

Parameters

name (string) – Variable name.

Returns

out – Value (x, y, z) of the variable or (None, None, None) if variable not found.

Return type

tuple (float, float, float)

NpOptiX.set_texture_1d(name: str, data: Any, addr_mode: Union[plotoptix.enums.TextureAddressMode, str] = <TextureAddressMode.Clamp: 1>, keep_on_host: bool = False, refresh: bool = False) → None[source]

Set texture data.

Set texture name data. Texture format (float, float2, float4 or byte, byte2, byte4) and length are deduced from the data array shape and dtype. Use keep_on_host=True to make a copy of data in the host memory (in addition to GPU memory), this option is required when (small) textures are going to be saved to JSON description of the scene.

Parameters
  • name (string) – Texture name.

  • data (array_like) – Texture data.

  • addr_mode (TextureAddressMode or string, optional) – Texture addressing mode on edge crossing.

  • keep_on_host (bool, optional) – Store texture data copy in the host memory.

  • refresh (bool, optional) – Set to True if the image should be re-computed.

NpOptiX.set_texture_2d(name: str, data: Any, addr_mode: Union[plotoptix.enums.TextureAddressMode, str] = <TextureAddressMode.Wrap: 0>, keep_on_host: bool = False, refresh: bool = False) → None[source]

Set texture data.

Set texture name data. Texture format (float, float2, float4 or byte, byte2, byte4) and width/height are deduced from the data array shape and dtype. Use keep_on_host=True to make a copy of data in the host memory (in addition to GPU memory), this option is required when (small) textures are going to be saved to JSON description of the scene.

Parameters
  • name (string) – Texture name.

  • data (array_like) – Texture data.

  • addr_mode (TextureAddressMode or string, optional) – Texture addressing mode on edge crossing.

  • keep_on_host (bool, optional) – Store texture data copy in the host memory.

  • refresh (bool, optional) – Set to True if the image should be re-computed.

NpOptiX.load_texture(tex_name: str, file_name: str, rt_format: plotoptix.enums.RtFormat = <RtFormat.Float4: 260>, prescale: float = 1.0, baseline: float = 0.0, exposure: float = 1.0, gamma: float = 1.0, addr_mode: Union[plotoptix.enums.TextureAddressMode, str] = <TextureAddressMode.Wrap: 0>, keep_on_host: bool = False, refresh: bool = False) → None[source]

Load texture from file.

Parameters
  • tex_name (string) – Texture name.

  • file_name (string) – Source image file.

  • rt_format (RtFormat, optional) – Target format of the texture.

  • prescale (float, optional) – Scaling factor for color values.

  • baseline (float, optional) – Baseline added to color values.

  • exposure (float, optional) – Exposure value used in the postprocessing.

  • gamma (float, optional) – Gamma value used in the postprocessing.

  • addr_mode (TextureAddressMode or string, optional) – Texture addressing mode on edge crossing.

  • keep_on_host (bool, optional) – Store texture data copy in the host memory.

  • refresh (bool, optional) – Set to True if the image should be re-computed.

Examples

>>> optix = TkOptiX()
>>> optix.load_texture("rainbow", "data/rainbow.jpg") # set gray background

Postprocessing 2D

NpOptiX.add_postproc(stage: Union[plotoptix.enums.Postprocessing, str], refresh: bool = False) → None[source]

Add 2D postprocessing stage.

Stages are applied to image in the order they are added with this method. Each stage algorithm has its own variables that should be configured before adding the postprocessing stage. Configuration can be updated at any time, but stages cannot be disabled after adding. See plotoptix.enums.Postprocessing for algorithms configuration examples.

Parameters
  • stage (Postprocessing or string) – Postprocessing algorithm to add.

  • refresh (bool, optional) – Set to True if the image should be re-computed.

NpOptiX.set_correction_curve(ctrl_points: Any, channel: Union[plotoptix.enums.Channel, str] = <Channel.Gray: 0>, n_points: int = 256, range: float = 255, refresh: bool = False) → None[source]

Set correction curve.

Calculate and setup a color correction curve using control points provided with ctrl_points. Curve is applied in 2D postprocessing stage to the selected channel. Control points should be an array_like set of input-output values (array shape is (m,2)). Control point input and output maximum value can be provided with the range parameter. Control points are scaled to the range <0;1>, extreme values (0,0) and (1,1) are added if not present in ctrl_points (use plotoptix.NpOptiX.set_texture_1d() if custom correction curve should e.g. start above 0 or saturate at a level lower than 1). Smooth bezier curve is calculated from the control points and stored in 1D texture with n_points length.

Parameters
  • ctrl_points (array_like) – Control points to construct curve.

  • channel (Channel or string, optional) – Destination color for the correction curve.

  • n_points (int, optional) – Number of curve points to be stored in texture.

  • range (float, optional) – Maximum input / output value corresponding to provided ctrl_points.

  • refresh (bool, optional) – Set to True if the image should be re-computed.

Encoder configuration

NpOptiX.encoder_create(fps: int, bitrate: float = 2, idrrate: Optional[int] = None, profile: Union[plotoptix.enums.NvEncProfile, str] = <NvEncProfile.Default: 0>, preset: Union[plotoptix.enums.NvEncPreset, str] = <NvEncPreset.Default: 0>) → None[source]

Create video encoder.

Create and configure video encoder for this raytracer instance. Only one encoder per raytracer instance is supported now. Specifying preset overrides bitrate settings. Beware that some combinations are not supported by all players (e.g. lossless encoding is not playable in Windows Media Player).

Parameters
  • fps (int) – Frames per second assumed in the output file.

  • bitrate (float, optional) – Constant bitrate of the encoded stream, in Mbits to save you typing 0’s.

  • idrrate (int, optional) – Instantaneous Decode Refresh frame interval. 2 seconds interval is used if idrrate is not provided.

  • profile (NvEncProfile enum or string, optional) – H.264 encoding profile.

  • preset (NvEncPreset enum or string, optional) – H.264 encoding preset, overrides bitrate settings.

NpOptiX.encoder_start(out_name: str, n_frames: int = 0) → None[source]

Start video encoding.

Start encoding to MP4 file with provided name. Total number of frames can be optionally limited. Output file is overwritten if it already exists. New file is created and encoding is restarted if method is launched during previously started encoding.

Parameters
  • out_name (str) – Output file name.

  • n_frames (int, optional) – Maximum number of frames to encode if n_frames or unlimited encoding when default value is used.

NpOptiX.encoder_stop() → None[source]

Stop video encoding.

Stop encoding and close the output file (can happen before configured total number of frames to encode).

NpOptiX.encoder_is_open() → bool[source]

Encoder is encoding.

Returns

outTrue if encoder is encoding.

Return type

bool

NpOptiX.encoded_frames() → int[source]

Number of encoded video frames.

Returns

out – Number of frames.

Return type

int

NpOptiX.encoding_frames() → int[source]

Number of frames to encode.

Returns

out – Number of frames.

Return type

int