PySSV Module Reference

Public API

The pySSV.ssv_canvas.SSVCanvas is one of the core components of pySSV, it’s what manages and provides and interface for the three major internal components: the renderer, the widget, and the shader preprocessor.

pySSV.canvas(size: Tuple[int, int] | None = (640, 480), backend: str = 'opengl', gl_version: Tuple[int, int] | None = None, standalone: bool = False, target_framerate: int = 60, use_renderdoc: bool = False, supports_line_directives: bool | None = None)[source]

Creates a new SSVCanvas which contains the render widget and manages the render context.

Parameters:
  • size (Tuple[int, int] | None) – the default resolution of the renderer as a tuple: (width: int, height: int).

  • backend (str) – the rendering backend to use; currently supports: "opengl".

  • gl_version (Tuple[int, int] | None) – optionally, the minimum version of OpenGL to support. Accepts a tuple of (major, minor), eg: gl_version=(4, 2) for OpenGL 4.2 Core.

  • standalone (bool) – whether the canvas should run standalone, or attempt to create a Jupyter Widget for rendering.

  • target_framerate (int) – the default framerate to target when running.

  • use_renderdoc (bool) – optionally, an instance of the Renderdoc in-app api to provide support for frame capturing and analysis in renderdoc.

  • supports_line_directives (bool | None) – whether the shader compiler supports #line directives (Nvidia GPUs only). Set to None for automatic detection. If you get ‘extension not supported: GL_ARB_shading_language_include’ errors, set this to False.

pySSV.ssv_canvas.OnMouseDelegate

A callable with parameters matching the signature:

on_mouse(mouse_down: tuple[bool, bool, bool], mouse_pos: tuple[int, int], mouse_wheel_delta: float) -> None:
    ...
mouse_down: a tuple of booleans representing the mouse button state (left, right, middle).
mouse_pos: a tuple of ints representing the mouse position relative to the canvas in pixels.
mouse_wheel_delta: how many pixels the mousewheel has scrolled since the last callback.

alias of Callable[[Tuple[bool, bool, bool], Tuple[int, int], float], None]

pySSV.ssv_canvas.OnKeyDelegate

A callable with parameters matching the signature:

on_key(key: str, down: bool) -> None:
    ...
key: the name of key in this event. Possible values can be found here: https://developer.mozilla.org/en-US/docs/Web/API/UI_Events/Keyboard_event_key_values
down: whether the key is being pressed.

alias of Callable[[str, bool], None]

pySSV.ssv_canvas.OnFrameRenderedDelegate

A callable with parameters matching the signature:

on_key(delta_time: float) -> None:
    ...
key: the time in seconds since the last frame was rendered.

alias of Callable[[float], None]

class pySSV.ssv_canvas.SSVCanvas(size: Tuple[int, int] | None, backend: str = 'opengl', gl_version: Tuple[int, int] | None = None, standalone: bool = False, target_framerate: int = 60, use_renderdoc: bool = False, supports_line_directives: bool | None = None)[source]

An SSV canvas manages the OpenGL rendering context, shaders, and the jupyter widget

Creates a new SSV Canvas object which manages the graphics context and render widget/window.

Parameters:
  • size (Tuple[int, int] | None) – the default resolution of the renderer as a tuple: (width: int, height: int).

  • backend (str) – the rendering backend to use; currently supports: "opengl".

  • gl_version (Tuple[int, int] | None) – optionally, the minimum version of OpenGL to support. Accepts a tuple of (major, minor), eg: gl_version=(4, 2) for OpenGL 4.2 Core.

  • standalone (bool) – whether the canvas should run standalone, or attempt to create a Jupyter Widget for rendering.

  • target_framerate (int) – the default framerate to target when running.

  • use_renderdoc (bool) – optionally, an instance of the Renderdoc in-app api to provide support for frame capturing and analysis in renderdoc.

  • supports_line_directives (bool | None) – whether the shader compiler supports #line directives (Nvidia GPUs only). Set to None for automatic detection. If you get ‘extension not supported: GL_ARB_shading_language_include’ errors, set this to False.

property main_render_buffer: SSVRenderBuffer

Gets the main render buffer associated with this SSVCanvas.

Returns:

the main render buffer.

property size: Tuple[int, int]

Gets the size of the canvas in pixels

property standalone: bool

Gets whether this canvas outputs to a standalone window as opposed to a jupyter widget.

property widget: SSVRenderWidget | None

Gets the render widget object. Only defined when standalone is False.

property main_camera: SSVCameraController

Gets the main camera controller.

property mouse_down: Tuple[bool, bool, bool]

Gets the current mouse button state as a tuple of bool. [left, right, middle]

property mouse_pos: Tuple[int, int]

Gets the current mouse position relative to the canvas in pixels.

property preprocessor

Gets this canvas’ preprocessor instance. Useful if you need to manually add compiler defines/macros.

property frame_number

Gets the number of frames that have been rendered since this canvas was run.

property canvas_time: float

Gets or sets the current canvas time (this is the value used by the shader’s uTime uniform). Note that due to renderer latency there will be some offset to time value get/set here.

on_start(callback: Callable[[], None], remove: bool = False)[source]

Registers/unregisters a callback which is invoked when this canvas’s run() method is called, before any frames are rendered.

Parameters:
  • callback (Callable[[], None]) – the callback to invoke.

  • remove (bool) – whether the given callback should be removed.

on_mouse_event(callback: Callable[[Tuple[bool, bool, bool], Tuple[int, int], float], None], remove: bool = False)[source]

Registers/unregisters a callback which is invoked when.

Parameters:
on_keyboard_event(callback: Callable[[str, bool], None], remove: bool = False)[source]

Registers/unregisters a callback which is invoked when.

Parameters:
  • callback (Callable[[str, bool], None]) – the callback to invoke.

  • remove (bool) – whether the given callback should be removed.

on_frame_rendered(callback: Callable[[float], None], remove: bool = False)[source]

Registers/unregisters a callback which is invoked when.

Parameters:
  • callback (Callable[[float], None]) – the callback to invoke.

  • remove (bool) – whether the given callback should be removed.

run(stream_mode: str | SSVStreamingMode = SSVStreamingMode.JPG, stream_quality: float | None = None, never_kill=False) None[source]

Starts the render loop and displays the Jupyter Widget (or render window if in standalone mode).

Parameters:
  • stream_mode (str | SSVStreamingMode) – the encoding format to use to transmit rendered frames from the render process to the Jupyter widget.

  • stream_quality (float | None) – the encoding quality to use for the given encoding format. Takes a float between 0-100 (some stream modes support values larger than 100, others clamp it internally), where 100 results in the highest quality. This value is scaled to give a bit rate target or quality factor for the chosen encoder. Pass in None to use the encoder’s default quality settings.

  • never_kill – disables the watchdog responsible for stopping the render process when the widget is no longer being displayed. Warning: The only way to stop a renderer started with this enabled is to restart the Jupyter kernel.

Return type:

None

stop(force=False) None[source]

Stops the current canvas from rendering continuously. The renderer is not released and can be restarted.

Parameters:

force – kills the render process and releases resources. SSVCanvases cannot be restarted if they have been force stopped.

Return type:

None

pause() None[source]

Pauses the current canvas, preventing new frames from being rendered and freezing time.

Return type:

None

unpause() None[source]

Unpauses the current canvas, and resumes playback at the time the canvas was paused at.

Return type:

None

shader(shader_source: str, additional_template_directory: str | None = None, additional_templates: List[str] | None = None, shader_defines: Dict[str, str] | None = None, compiler_extensions: List[str] | None = None)[source]

Registers, compiles and attaches a shader to the main render buffer.

Parameters:
  • shader_source (str) – the shader source code to preprocess. It should contain the necessary #pragma SSV <template_name> directive see Built In Shader Templates for more information.

  • additional_template_directory (str | None) – a path to a directory containing custom shader templates. See Writing Shader Templates for information about using custom shader templates.

  • additional_templates (List[str] | None) – a list of custom shader templates (source code, not paths).See Writing Shader Templates for information about using custom shader templates.

  • shader_defines (Dict[str, str] | None) – extra preprocessor defines to be enabled globally.

  • compiler_extensions (List[str] | None) – a list of GLSL extensions required by this shader (eg: GL_EXT_control_flow_attributes)

update_uniform(uniform_name: str, value: Any, share_with_render_buffer: bool = True, share_with_canvas: bool = True) None[source]

Sets the value of a uniform associated with the main full-screen shader.

Parameters:
  • uniform_name (str) – the name of the uniform to set.

  • value (Any) – the value to set. Must be compatible with the destination uniform.

  • share_with_render_buffer (bool) – update this uniform across all shaders in this render buffer.

  • share_with_canvas (bool) – update this uniform across all shaders in this canvas.

Return type:

None

render_buffer(size: Tuple[int, int], name: str | None = None, order: int = 0, dtype: str = 'f1', components: int = 4) SSVRenderBuffer[source]

Creates a new render buffer for this canvas. Useful for effects requiring multi pass rendering.

Parameters:
  • size (Tuple[int, int]) – the resolution of the new render buffer to create.

  • name (str | None) – the name of this render buffer. This is the name given to the automatically generated uniform declaration. If set to None a name is automatically generated.

  • order (int) – a number to hint the renderer as to the order to render the buffers in. Smaller values are rendered first; the main render buffer has an order of 999999.

  • dtype (str) – the data type for each pixel component (see: https://moderngl.readthedocs.io/en/5.8.2/topics/texture_formats.html).

  • components (int) – how many vector components should each pixel have (RGB=3, RGBA=4).

Returns:

a new render buffer object.

Return type:

SSVRenderBuffer

texture(data: ndarray[Any, dtype[_ScalarType_co]] | Image, uniform_name: str | None, force_2d: bool = False, force_3d: bool = False, override_dtype: str | None = None, treat_as_normalized_integer: bool = True, declare_uniform: bool = True) SSVTexture[source]

Creates or updates a texture from the NumPy array provided.

Parameters:
  • data (ndarray[Any, dtype[_ScalarType_co]] | Image) – a NumPy array or a PIL/Pillow Image containing the image data to copy to the texture.

  • uniform_name (str | None) – optionally, the name of the shader uniform to associate this texture with. If None is specified, a name is automatically generated in the form ‘uTexture{n}’

  • force_2d (bool) – when set, forces the texture to be treated as 2-dimensional, even if it could be represented by a 1D texture. This only applies in the ambiguous case where a 2D single component texture has a height <= 4 (eg: np.array([[0.0, 0.1, 0.2], [0.3, 0.4, 0.5], [0.6, 0.7, 0.8]])), with this parameter set to False, the array would be converted to a 1D texture with a width of 3 and 3 components; setting this to True ensures that it becomes a 3x3 texture with 1 component.

  • force_3d (bool) – when set, forces the texture to be treated as 3-dimensional, even if it could be represented by a 2D texture. See the description of the force_2d parameter for a full explanation.

  • override_dtype (str | None) – optionally, a moderngl datatype to force on the texture. See https://moderngl.readthedocs.io/en/latest/topics/texture_formats.html for the full list of available texture formats.

  • treat_as_normalized_integer (bool) – when enabled, integer types (singed/unsigned) are treated as normalized integers by OpenGL, such that when the texture is sampled values in the texture are mapped to floats in the range [0, 1] or [-1, 1]. See: https://www.khronos.org/opengl/wiki/Normalized_Integer for more details.

  • declare_uniform (bool) – when set, a shader uniform is automatically declared for this uniform in shaders.

Return type:

SSVTexture

get_texture(uniform_name: str) SSVTexture | None[source]

Gets a texture that’s already been defined on this canvas.

Parameters:

uniform_name (str) – the name of the uniform associated with this texture.

Returns:

the texture object or None if no texture was found with that name.

Return type:

SSVTexture | None

save_image(image_type: SSVStreamingMode = SSVStreamingMode.JPG, quality: float = 95, size: Tuple[int, int] | None = None, render_buffer: int = 0, suppress_ui: bool = False) bytes[source]

Saves the current frame as an image.

Parameters:
  • image_type (SSVStreamingMode) – the image compression algorithm to use.

  • quality (float) – the encoding quality to use for the given encoding format. Takes a float between 0-100 (some stream modes support values larger than 100, others clamp it internally), where 100 results in the highest quality. This value is scaled to give a bit rate target or quality factor for the chosen encoder.

  • size (Tuple[int, int] | None) – optionally, the width and height of the saved image. If set to None uses the current resolution of the render buffer.

  • render_buffer (int) – the uid of the render buffer to save.

  • suppress_ui (bool) – whether any active SSVGUI should be suppressed.

Returns:

the bytes representing the compressed image.

Return type:

bytes

dbg_query_shader_template(shader_template_name: str, additional_template_directory: str | None = None, additional_templates=None) str[source]

Gets the list of arguments a given shader template expects and returns a string containing their usage info.

Parameters:
  • shader_template_name (str) – the name of the template to look for.

  • additional_template_directory (str | None) – a path to a directory containing custom shader templates.

  • additional_templates – a list of custom shader templates (source code, not paths).

Returns:

the shader template’s auto generated help string.

Return type:

str

dbg_query_shader_templates(additional_template_directory: str | None = None) str[source]

Gets a list of all the shader templates available to the preprocessor.

Parameters:

additional_template_directory (str | None) – a path to a directory containing custom shader templates.

Returns:

A string of all the shader templates which were found.

Return type:

str

dbg_preprocess_shader(shader_source: str, additional_template_directory: str | None = None, additional_templates: List[str] | None = None, shader_defines: Dict[str, str] | None = None, compiler_extensions: List[str] | None = None, pretty_print: bool = True) str | Dict[str, str][source]

Runs the preprocessor on a shader and returns the results. Useful for debugging shaders.

Parameters:
  • shader_source (str) – the shader source code to preprocess. It should contain the necessary #pragma SSV <template_name> directive see Built In Shader Templates for more information.

  • additional_template_directory (str | None) – a path to a directory containing custom shader templates. See Writing Shader Templates for information about using custom shader templates.

  • additional_templates (List[str] | None) – a list of custom shader templates (source code, not paths).See Writing Shader Templates for information about using custom shader templates.

  • shader_defines (Dict[str, str] | None) – extra preprocessor defines to be enabled globally.

  • compiler_extensions (List[str] | None) – a list of GLSL extensions required by this shader (eg: GL_EXT_control_flow_attributes)

  • pretty_print (bool) – when enabled returns a single string containing all the preprocessed shaders

Return type:

str | Dict[str, str]

dbg_render_test()[source]

Sets up the render pipeline to render a demo shader.

dbg_log_context(full=False)[source]

Logs the OpenGL information to the console for debugging.

Parameters:

full – whether to log all of the OpenGL context information (including extensions).

dbg_log_frame_times(enabled=True)[source]

Enables or disables frame time logging.

Parameters:

enabled – whether to log frame times.

dbg_capture_frame()[source]

Triggers a frame capture with RenderDoc if this canvas has it enabled.

Due to the asynchronous nature of the renderer, the frame may be capture 1 frame late.

Canvas Objects

These classes must be constructed by an pySSV.ssv_canvas.SSVCanvas.

class pySSV.ssv_render_buffer.SSVRenderBuffer(canvas: SSVCanvas, render_process_client: SSVRenderProcessClient, preprocessor: SSVShaderPreprocessor, render_buffer_uid: int | None, render_buffer_name: str, order: int, size: tuple[int, int], dtype: str, components: int)[source]

A lightweight class representing a native render buffer.

Used Internally

Note that SSVRenderBuffer objects should be constructed using the factory method on an SSVCanvas.

Parameters:
  • canvas (SSVCanvas) – the canvas creating this render buffer.

  • render_process_client (SSVRenderProcessClient) – the render process connection belonging to the canvas.

  • preprocessor (SSVShaderPreprocessor) – the preprocessor belonging to the canvas.

  • render_buffer_uid (Optional[int]) – the UID to give this render buffer. Set to None to generate one automatically.

  • render_buffer_name (str) – the name of this render buffer. This is the name given to the automatically generated uniform declaration.

  • order (int) – the render order of the render buffer. Smaller numbers are rendered first.

  • size (tuple[int, int]) – the resolution of the render buffer.

  • dtype (str) – the moderngl datatype of the render buffer.

  • components (int) – how many vector components should each pixel have (RGB=3, RGBA=4).

property render_buffer_uid: int

Gets the internal UID of this render buffer.

property render_buffer_name: str

Gets the name of this render buffer.

property canvas: SSVCanvas

Gets the canvas associated with this render buffer.

property full_screen_vertex_buffer: SSVVertexBuffer

Gets the default full-screen vertex buffer for this render buffer.

property order: int

Gets or sets the render order of this render buffer. This number to hint the renderer as to the order to render the buffers in. Smaller values are rendered first; the main render buffer has an order of 999999.

property size: tuple[int, int]

Gets or sets the resolution of this render buffer.

property components: int

Gets or sets how many vector components each pixel should have (RGB=3, RGBA=4).

property dtype: str

Gets or sets the data type for each pixel component (see: https://moderngl.readthedocs.io/en/5.8.2/topics/texture_formats.html).

property vertex_buffers: Tuple[SSVVertexBuffer, ...]

Gets the tuple of vertex buffers registered to this render buffer.

shader(shader_source: str, additional_template_directory: str | None = None, additional_templates: list[str] | None = None, shader_defines: dict[str, str] | None = None, compiler_extensions: list[str] | None = None)[source]

Registers, compiles and attaches a full-screen shader to this render buffer.

Parameters:
  • shader_source (str) – the shader source code to preprocess. It should contain the necessary #pragma SSV <template_name> directive see Built In Shader Templates for more information.

  • additional_template_directory (str | None) – a path to a directory containing custom shader templates. See Writing Shader Templates for information about using custom shader templates.

  • additional_templates (list[str] | None) – a list of custom shader templates (source code, not paths).See Writing Shader Templates for information about using custom shader templates.

  • shader_defines (dict[str, str] | None) – extra preprocessor defines to be enabled globally.

  • compiler_extensions (list[str] | None) – a list of GLSL extensions required by this shader (eg: GL_EXT_control_flow_attributes)

update_uniform(uniform_name: str, value: Any, share_with_render_buffer: bool = True, share_with_canvas: bool = False) None[source]

Sets the value of a uniform associated with this buffer’s full-screen shader.

Parameters:
  • uniform_name (str) – the name of the uniform to set.

  • value (Any) – the value to set. Must be compatible with the destination uniform.

  • share_with_render_buffer (bool) – update this uniform across all shaders in this render buffer.

  • share_with_canvas (bool) – update this uniform across all shaders in this canvas.

Return type:

None

vertex_buffer() SSVVertexBuffer[source]

Creates a new draw call and associated vertex buffer on this render buffer.

Returns:

A new vertex buffer object.

Return type:

SSVVertexBuffer

delete_vertex_buffer(buffer: SSVVertexBuffer)[source]

Removes a vertex buffer from this render buffer, releasing its resources.

Parameters:

buffer (SSVVertexBuffer) – the vertex buffer to remove.

class pySSV.ssv_vertex_buffer.SSVVertexBuffer(draw_call_uid: int | None, render_buffer: SSVRenderBuffer, render_process_client: SSVRenderProcessClient, preprocessor: SSVShaderPreprocessor)[source]

A lightweight class representing a vertex buffer associated with a draw call.

Used internally

Note that SSVVertexBuffer objects should be constructed using the factory method on either an SSVCanvas or an SSVRenderBuffer.

Parameters:
property draw_call_uid: int

Gets the internal uid of this draw call.

property is_valid: bool
release()[source]

Destroys this vertex buffer.

update_vertex_buffer(vertex_array: ndarray[Any, dtype[_ScalarType_co]], vertex_attributes: tuple[str, ...] = ('in_vert', 'in_color'), index_array: ndarray[Any, dtype[_ScalarType_co]] | None = None)[source]

Updates the data inside a vertex buffer.

Parameters:
  • vertex_array (ndarray[Any, dtype[_ScalarType_co]]) – a numpy array containing the new vertex data.

  • index_array (ndarray[Any, dtype[_ScalarType_co]] | None) – optionally, a numpy array containing the indices of vertices ordered to make triangles.

  • vertex_attributes (tuple[str, ...]) – a tuple of the names of the vertex attributes to map to in the shader, in the order that they appear in the vertex array.

shader(shader_source: str, additional_template_directory: str | None = None, additional_templates: list[str] | None = None, shader_defines: dict[str, str] | None = None, compiler_extensions: list[str] | None = None)[source]

Registers, compiles and attaches a shader to the draw call associated with this vertex buffer.

Parameters:
  • shader_source (str) – the shader source code to preprocess. It should contain the necessary #pragma SSV <template_name> directive see Built In Shader Templates for more information.

  • additional_template_directory (str | None) – a path to a directory containing custom shader templates. See Writing Shader Templates for information about using custom shader templates.

  • additional_templates (list[str] | None) – a list of custom shader templates (source code, not paths).See Writing Shader Templates for information about using custom shader templates.

  • shader_defines (dict[str, str] | None) – extra preprocessor defines to be enabled globally.

  • compiler_extensions (list[str] | None) – a list of GLSL extensions required by this shader (eg: GL_EXT_control_flow_attributes)

update_uniform(uniform_name: str, value: Any, share_with_render_buffer: bool = False, share_with_canvas: bool = False) None[source]

Sets the value of a uniform associated with this draw call.

Parameters:
  • uniform_name (str) – the name of the uniform to set.

  • value (Any) – the value to set. Must be compatible with the destination uniform.

  • share_with_render_buffer (bool) – update this uniform across all shaders in this render buffer.

  • share_with_canvas (bool) – update this uniform across all shaders in this canvas.

Return type:

None

class pySSV.ssv_camera.MoveDir(value)[source]

Represents a cardinal direction to move in.

NONE = 0
FORWARD = 1
BACKWARD = 2
LEFT = 3
RIGHT = 4
UP = 5
DOWN = 6
class pySSV.ssv_camera.SSVCamera[source]

A simple class representing a camera.

position: ndarray[Any, dtype[float32]]

The camera’s position in 3D space.

direction: ndarray[Any, dtype[float32]]

A normalised vector pointing in the direction the camera is facing.

fov: float

The field of view of the camera in degrees.

clip_dist: Tuple[float, float]

The distances of the near and far clipping planes respectively.

aspect_ratio: float

The aspect ratio of the render buffer.

property rotation_matrix: ndarray[Any, dtype[float32]]

Gets the current view matrix of the camera, without the translation component.

property view_matrix: ndarray[Any, dtype[float32]]

Gets the current view matrix of the camera.

property projection_matrix

Gets the current projection matrix of the camera.

class pySSV.ssv_camera.SSVCameraController[source]

A simple class representing a camera controller.

inhibit: bool = False

Whether the camera controls should be inhibited

move_speed: float

The movement speed of the camera.

zoom_speed: float

The zooming speed of the camera.

pan_speed: float

The panning speed of the camera in radians per pixel of mouse movement.

abstract mouse_change(mouse_pos: Tuple[int, int], mouse_down: Tuple[bool, bool, bool])[source]
Parameters:
abstract move(direction: MoveDir, distance: float = 1.0)[source]
Parameters:
class pySSV.ssv_camera.SSVLookCameraController[source]

A camera controller which supports mouse look controls.

mouse_change(mouse_pos: Tuple[int, int], mouse_down: Tuple[bool, bool, bool])[source]

Updates the camera with a mouse event.

Parameters:
move(direction: MoveDir, distance: float = 1.0)[source]

Updates the camera position with a movement event.

Parameters:
  • direction (MoveDir) – the direction to move in.

  • distance (float) – the distance to move.

class pySSV.ssv_camera.SSVOrbitCameraController[source]

A camera controller which supports orbiting around a given target.

property target_pos

Gets or sets the point around which to orbit.

property orbit_dist

Gets or sets the distance from the target position to orbit at.

mouse_change(mouse_pos: Tuple[int, int], mouse_down: Tuple[bool, bool, bool])[source]

Updates the camera with a mouse event.

Parameters:
zoom(distance: float)[source]

Updates the orbit distance with a zoom event.

Parameters:

distance (float) – how far to zoom in.

move(direction: MoveDir, distance: float = 1.0)[source]

Updates the camera position with a movement event.

Parameters:
  • direction (MoveDir) – the direction to move in.

  • distance (float) – the distance to move.

pySSV.ssv_texture.determine_texture_shape(data: ndarray[Any, dtype[_ScalarType_co]], override_dtype: str | None, treat_as_normalized_integer: bool = True) tuple[int, int, int, int, str | None][source]

Attempts to determine suitable texture parameters given an ndarray. This method returns (0,0,0,0,None) if a suitable format cannot be found.

Parameters:
  • data (ndarray[Any, dtype[_ScalarType_co]]) – the ndarray to parse.

  • override_dtype (str | None) – optionally, a moderngl dtype string to use instead of the numpy dtype.

  • treat_as_normalized_integer (bool) – when enabled, integer types (singed/unsigned) are treated as normalized integers by OpenGL, such that when the texture is sampled values in the texture are mapped to floats in the range [0, 1] or [-1, 1]. See: https://www.khronos.org/opengl/wiki/Normalized_Integer for more details.

Returns:

(components, depth, height, width, dtype)

Return type:

tuple[int, int, int, int, str | None]

class pySSV.ssv_texture.SSVTexture(texture_uid: int | None, render_process_client: SSVRenderProcessClient, preprocessor: SSVShaderPreprocessor, data: npt.NDArray | Image.Image, uniform_name: str, force_2d: bool = False, force_3d: bool = False, override_dtype: str | None = None, treat_as_normalized_integer: bool = True, declare_uniform: bool = True)[source]

A lightweight class representing a Texture object.

Used Internally

Note that SSVTexture objects should be constructed using the factory method on either an SSVCanvas.

Parameters:
  • texture_uid (Optional[int]) – the UID to give this texture buffer. Set to None to generate one automatically.

  • render_process_client (SSVRenderProcessClient) – the render process connection belonging to the canvas.

  • preprocessor (SSVShaderPreprocessor) – the preprocessor belonging to the canvas.

  • data (Union[npt.NDArray, Image.Image]) – a NumPy array or a PIL/Pillow Image containing the image data to copy to the texture.

  • uniform_name (str) – the name of the shader uniform to associate this texture with.

  • force_2d (bool) – when set, forces the texture to be treated as 2-dimensional, even if it could be represented by a 1D texture. This only applies in the ambiguous case where a 2D single component texture has a height <= 4 (eg: np.array([[0.0, 0.1, 0.2], [0.3, 0.4, 0.5], [0.6, 0.7, 0.8]])), with this parameter set to False, the array would be converted to a 1D texture with a width of 3 and 3 components; setting this to True ensures that it becomes a 3x3 texture with 1 component.

  • force_3d (bool) – when set, forces the texture to be treated as 3-dimensional, even if it could be represented by a 2D texture. See the description of the force_2d parameter for a full explanation.

  • override_dtype (Optional[str]) – optionally, a moderngl datatype to force on the texture.

  • treat_as_normalized_integer (bool) – when enabled, integer types (singed/unsigned) are treated as normalized integers by OpenGL, such that when the texture is sampled values in the texture are mapped to floats in the range [0, 1] or [-1, 1]. See: https://www.khronos.org/opengl/wiki/Normalized_Integer for more details.

  • declare_uniform (bool) – when set, a shader uniform is automatically declared for this uniform in shaders.

property texture_uid: int

Gets the internal UID of this texture object.

property uniform_name: str

Gets the shader uniform name associated with this texture.

property components: int

Gets the number of components for a single pixel (RGB=3, RGBA=4). Always at least 1, never more than 4.

property depth: int

Gets the depth of the texture. Always returns 1 for 1D and 2D textures.

property height: int

Gets the height of the texture. Always returns 1 for 1D textures.

property width: int

Gets the width of the texture.

property dtype: str

Gets the data type of a single component in the texture.

See https://moderngl.readthedocs.io/en/latest/topics/texture_formats.html for a full list of available data types.

property repeat_x: None

Sets whether the texture should repeat or be clamped in the x-axis.

property repeat_y: None

Sets whether the texture should repeat or be clamped in the y-axis.

property linear_filtering: None

Sets whether the texture should use nearest neighbour (False) or linear (True) interpolation.

property linear_mipmap_filtering: None

Sets whether different mipmap levels should blend linearly (True) or not (False).

property anisotropy: None

Sets the number of anisotropy samples to use. (minimum of 1 = disabled, maximum of 16)

property is_valid: bool

Gets whether this texture object represents a valid texture that hasn’t been destroyed yet.

update_texture(data: ndarray[Any, dtype[_ScalarType_co]], rect: tuple[int, int, int, int] | tuple[int, int, int, int, int, int] | None = None)[source]

Updates the contents of this texture from the NumPy array provided.

Parameters:
  • data (ndarray[Any, dtype[_ScalarType_co]]) – a NumPy array containing the image data to copy to the texture.

  • rect (tuple[int, int, int, int] | tuple[int, int, int, int, int, int] | None) – optionally, a rectangle (left, top, right, bottom) specifying the area of the target texture to update.

build_mipmaps()[source]

Generates mipmaps for the texture.

release()[source]

Destroys this texture object and releases the associated GPU resources.

GUI Library

pySSV provides a simple to use immediate-mode GUI library to add interactivity to your shaders. A GUI can be created for a given canvas by calling the pySSV.ssv_gui.create_gui() method which returns a new pySSV.ssv_gui.SSVGUI.

class pySSV.ssv_gui.SSVGUIShaderMode(value)[source]

Represents the shader features needed to render a GUI element when using the built-in UI shader.

SOLID = 0
TRANSPARENT = 1
TEXT = 2
TEXTURE = 4
SHADOWED = 8
ROUNDING = 16
OUTLINE = 32
static get_vertex_attributes(shader_mode: int) Tuple[str, ...][source]

Gets the tuple of vertex attribute names required to support this shader mode.

Parameters:

shader_mode (int) –

Returns:

Return type:

Tuple[str, …]

class pySSV.ssv_gui.TextAlign(value)[source]

An enumeration.

LEFT = 0
CENTRE = 1
CENTER = 1
RIGHT = 2
class pySSV.ssv_gui.Rect(x: int = 0, y: int = 0, width: int = 20, height: int = 20)[source]

Represents a 2D rectangle in pixel space.

Parameters:
x: int
y: int
width: int
height: int
pySSV.ssv_gui.SSVGUIDrawDelegate

draw(gui: SSVGUI, rect: Rect) -> None

Type:

A delegate for a GUIElement draw function. It should follow the signature

alias of Callable[[SSVGUI, Rect], None]

pySSV.ssv_gui.SSVGUIPreLayoutDelegate

A delegate for a GUIElement pre layout function. It should follow the signature: draw(gui: SSVGUI) -> tuple[width: int, height: int]

alias of Callable[[SSVGUI], Tuple[int, int]]

class pySSV.ssv_gui.SSVGUIElement(draw_func: Callable[[SSVGUI, Rect], None], control_width: int, control_height: int, expand: bool, layout: bool, overlay_last: bool, pre_layout_func: Callable[[SSVGUI], Tuple[int, int]] | None)[source]

A class representing a single GUI element for use by the layout engine.

Parameters:
draw_func: Callable[[SSVGUI, Rect], None]
control_width: int
control_height: int
expand: bool
layout: bool
overlay_last: bool
pre_layout_func: Callable[[SSVGUI], Tuple[int, int]] | None
class pySSV.ssv_gui.SSVGUILayoutContainer(gui: SSVGUI, vertical: bool = True, enabled: bool | Reference[bool] = True, squeeze: bool = False, pad: bool = False)[source]

A GUILayoutContainer stores a list gui elements (represented by their draw functions). It automatically lays out all of its elements either vertically or horizontally when its draw() method is called. An SSVGUILayoutContainer can itself be put inside another layout container.

Parameters:
draw(gui: SSVGUI, max_bounds: Rect)[source]

Lays out and draws all the elements within this container in the order they were added.

Parameters:
  • gui (SSVGUI) – the parent SSVGUI instance.

  • max_bounds (Rect) – the rect representing the space to fit elements within.

property min_width: int

Measures the minimum width of a given layout group by recursively measuring all of its children.

property min_height: int

Measures the minimum height of a given layout group by recursively measuring all of its children.

add_element(draw_callback: Callable[[SSVGUI, Rect], None], control_width: int, control_height: int, expand: bool = False, layout: bool = True, overlay_last: bool = False, pre_layout_callback: Callable[[SSVGUI], Tuple[int, int]] | None = None)[source]

Adds a GUI element to this Layout Container.

Parameters:
  • draw_callback (Callable[[SSVGUI, Rect], None]) – the draw function of the GUI element

  • control_width (int) – the requested width of the control. The layout engine can give a larger width than this if the expand option is enabled; if the layout group has squeeze enabled, the actual width may be smaller than requested.

  • control_height (int) – the requested height of the control. The layout engine can give a larger height than this if the expand option is enabled; if the layout group has squeeze enabled, the actual height may be smaller than requested.

  • expand (bool) – whether the element should attempt to fill all remaining space in the container. If multiple elements have expand set, then the remaining space is shared. The element’s minimum size is still determined by the defined layout size.

  • layout (bool) – whether this element should participate in automatic layout. If disabled, the element doesn’t count towards layout calculations and is given the full Rect of the Layout Container. The element will still be drawn in the order specified.

  • overlay_last (bool) – whether this element should be overlaid on top of the last element drawn.

  • pre_layout_callback (Callable[[SSVGUI], Tuple[int, int]] | None) – the callback is invoked just before the element is laid out, it’s useful for Layout Group elements which might not know their minimum size until just before layout.

class pySSV.ssv_gui.SSVGUI(canvas: SSVCanvas, render_buffer: SSVRenderBuffer)[source]

An immediate mode GUI library for pySSV.

Creates a new GUI and binds its event listeners to the given canvas.

Parameters:
property layout_control_height: int

Gets or sets the default GUI element height.

property layout_control_width: int

Gets or sets the default GUI element width.

property padding: Tuple[int, int, int, int]

Gets or sets the amount of padding between GUI elements in pixels.

property rounding_radius: float

Gets or sets the default corner radius for GUI elements, in pixels.

on_gui(callback: Callable[[SSVGUI], None], remove: bool = False)[source]

Registers/unregisters a callback to this GUI’s on_gui event which is called any time the GUI is invalidated and needs to be redrawn.

All GUI drawing operations should occur within the callback registered here. Calling GUI drawing functions outside of this callback results in undefined behaviour.

Parameters:
  • callback (Callable[[SSVGUI], None]) – the callback function to register to the on_gui event.

  • remove (bool) – whether the function passed in should be removed from the callback list.

on_post_gui(callback: Callable[[SSVGUI], None], remove: bool = False)[source]

Registers/unregisters a callback to this GUI’s on_post_gui event which is called just after the GUI drawn.

GUI drawing operations are not permitted within this callback; but any Reference values returned by GUI elements will have been updated by the time this callback is invoked.

Parameters:
  • callback (Callable[[SSVGUI], None]) – the callback function to register to the on_post_gui event.

  • remove (bool) – whether the function passed in should be removed from the callback list.

begin_horizontal(width: int | None = None, height: int | None = None, pad: bool = False, squeeze: bool = True)[source]

Starts a new horizontal layout group. All GUI elements created after this call will flow horizontally, left to right until end_horizontal() is called.

Parameters:
  • width (int | None) – optionally override the width of this layout group. Defaults to the current layout_control_width.

  • height (int | None) – optionally override the height of this layout group. Defaults to the current layout_control_height.

  • pad (bool) – whether padding should be created between this layout group and the last GUI element.

  • squeeze (bool) – whether this layout group should attempt to squeeze the elements contained within if they would have otherwise overflowed.

end_horizontal()[source]

Ends a horizontal layout group.

begin_vertical(width: int | None = None, height: int | None = None, pad: bool = False, squeeze: bool = False)[source]

Starts a new vertical layout group. All GUI elements created after this call will flow vertically, top to bottom until end_vertical() is called.

Parameters:
  • width (int | None) – optionally override the width of this layout group. Defaults to the current layout_control_width.

  • height (int | None) – optionally override the height of this layout group. Defaults to the current layout_control_height.

  • pad (bool) – whether padding should be created between this layout group and the last GUI element.

  • squeeze (bool) – whether this layout group should attempt to squeeze the elements contained within if they would have otherwise overflowed.

end_vertical() SSVGUILayoutContainer[source]

Ends a vertical layout group.

Return type:

SSVGUILayoutContainer

begin_toggle(enabled: bool | Reference[bool], width: int | None = None, height: int | None = None, pad: bool = False, squeeze: bool = False)[source]

Starts a new toggle layout group. GUI elements contained within this group can be shown or hidden using the enabled field. All GUI elements created after this call will flow vertically, top to bottom until end_toggle() is called.

Parameters:
  • enabled (bool | Reference[bool]) – a boolean or a reference to a boolean for whether the contents of this group should be shown.

  • width (int | None) – optionally override the width of this layout group. Defaults to the current layout_control_width.

  • height (int | None) – optionally override the height of this layout group. Defaults to the current layout_control_height.

  • pad (bool) – whether padding should be created between this layout group and the last GUI element.

  • squeeze (bool) – whether this layout group should attempt to squeeze the elements contained within if they would have otherwise overflowed.

end_toggle()[source]

Ends a toggle layout group.

space(width: int | None = None, height: int | None = None)[source]

Creates a blank space element.

Parameters:
  • width (int | None) – optionally, the width of the element.

  • height (int | None) – optionally, the height of the element.

rect(colour: Colour, rect: Rect | None = None, overlay_last: bool = False)[source]

Creates a rectangle GUI element.

Parameters:
  • colour (Colour) – the colour of the rectangle.

  • rect (Rect | None) – optionally, the absolute coordinates of the rectangle to draw. These will be clipped to fit within the current layout group.

  • overlay_last (bool) – whether the layout engine should overlay this element onto the last drawn element.

rounded_rect(colour: Colour, outline: bool = False, radius: float | None = None, rect: Rect | None = None, overlay_last: bool = False)[source]

Creates a rounded rectangle GUI element.

Parameters:
  • colour (Colour) – the colour of the rectangle.

  • outline (bool) – whether the rectangle should be outlined.

  • radius (float | None) – the rounding radius in pixels. This can be set to an arbitrarily high number to create circles/pills. Set to None to use the GUI’s rounding_radius.

  • rect (Rect | None) – optionally, the absolute coordinates of the rectangle to draw. These will be clipped to fit within the current layout group.

  • overlay_last (bool) – whether the layout engine should overlay this element onto the last drawn element.

label(text: str, colour: ~pySSV.ssv_colour.Colour = <pySSV.ssv_colour.Colour object>, font_size: float | None = None, x_offset: int = 0, weight: float = 0.5, italic: bool = False, shadow: bool = False, align: ~pySSV.ssv_gui.TextAlign = TextAlign.LEFT, enforce_hinting: bool = True, rect: ~pySSV.ssv_gui.Rect | None = None, overlay_last: bool = False)[source]

Creates a label GUI element.

Parameters:
  • text (str) – the text to display.

  • colour (Colour) – the colour of the rectangle.

  • font_size (float | None) – the font size in pt.

  • x_offset (int) – how far to indent the text in pixels.

  • weight (float) – the font weight [0-1], where 0.5 is the native font weight. The font renderer uses SDF fonts which allows variable font weight rendering for free within certain limits (since this is only an effect, at the extremes type quality is degraded).

  • italic (bool) – whether the text should be rendered in faux italic. This effect simply applies a shear transformation to the rendered characters, so it will work on any font, but won’t look as good as a proper italic font.

  • shadow (bool) – whether the text should be rendered with a shadow. This incurs a very small extra rendering cost, and tends to have visual artifacts when the font weight is high.

  • align (TextAlign) – the horizontal alignment of the text.

  • enforce_hinting (bool) – this option applies rounding to the font size and position to force it to line up with the pixel grid to improve sharpness. This is only effective if the font texture was rendered with hinting enabled in the first place. This can result in aliasing when animating font size/text position.

  • rect (Rect | None) – optionally, the absolute coordinates of the rectangle to draw. These will be clipped to fit within the current layout group.

  • overlay_last (bool) – whether the layout engine should overlay this element onto the last drawn element.

label_3d(text: str, pos: ~typing.Tuple[float, float, float], colour: ~pySSV.ssv_colour.Colour = <pySSV.ssv_colour.Colour object>, font_size: float | None = None, weight: float = 0.5, italic: bool = False, shadow: bool = False, align: ~pySSV.ssv_gui.TextAlign = TextAlign.CENTRE, enforce_hinting: bool = True)[source]

Creates a label GUI element which is transformed in 3d space using the canvas’s camera.

Parameters:
  • text (str) – the text to display.

  • pos (Tuple[float, float, float]) – the 3d position of the label.

  • colour (Colour) – the colour of the rectangle.

  • font_size (float | None) – the font size in pt.

  • weight (float) – the font weight [0-1], where 0.5 is the native font weight. The font renderer uses SDF fonts which allows variable font weight rendering for free within certain limits (since this is only an effect, at the extremes type quality is degraded).

  • italic (bool) – whether the text should be rendered in faux italic. This effect simply applies a shear transformation to the rendered characters, so it will work on any font, but won’t look as good as a proper italic font.

  • shadow (bool) – whether the text should be rendered with a shadow. This incurs a very small extra rendering cost, and tends to have visual artifacts when the font weight is high.

  • align (TextAlign) – the horizontal alignment of the text.

  • enforce_hinting (bool) – this option applies rounding to the font size and position to force it to line up with the pixel grid to improve sharpness. This is only effective if the font texture was rendered with hinting enabled in the first place. This can result in aliasing when animating font size/text position.

button(text: str, colour: Colour | None = None, radius: float | None = None, rect: Rect | None = None) Reference[bool][source]

Creates a button GUI element.

Since the actual drawing of GUI elements is deferred till after layout has been updated (which occurs just after the on_gui event finishes), the result of whether the button has been clicked or not is not known when this method returns. Wait until the on_post_gui event (or the start of the next on_gui) event to get the value of the button.

Parameters:
  • text (str) – the button text.

  • colour (Colour | None) – the colour of the button rectangle.

  • radius (float | None) – optionally, the corner radius of the button rectangle.

  • rect (Rect | None) – optionally, the absolute coordinates of the rectangle to draw. These will be clipped to fit within the current layout group.

Returns:

a reference to a boolean which will be set to True if the button was clicked.

Return type:

Reference[bool]

slider(text: str, value: float, min_value: float = 0.0, max_value: float = 1.0, step_size: float = 0, power: float = 1.0, colour: Colour | None = None, track_thickness: float = 4, rect: Rect | None = None) Reference[float][source]

Creates a slider GUI element.

Since the actual drawing of GUI elements is deferred till after layout has been updated (which occurs just after the on_gui event finishes), the updated value of this slider is not known when this method returns. Wait until the on_post_gui event (or the start of the next on_gui) event to get the new value of this slider. Until then the value returned by the slider will be the value passed in to it.

Parameters:
  • text (str) – the label of the slider.

  • value (float) – the current value of the slider.

  • min_value (float) – the minimum value of the slider.

  • max_value (float) – the maximum value of the slider.

  • step_size (float) – the step size to round the slider value to.

  • power (float) – an exponent to raise the value of the slider to, useful for creating non-linear sliders.

  • colour (Colour | None) – the colour of the rectangle.

  • track_thickness (float) – the thickness of the slider track in pixels.

  • rect (Rect | None) – optionally, the absolute coordinates of the rectangle to draw. These will be clipped to fit within the current layout group.

Returns:

a reference to a float which will be set to the new value of the slider.

Return type:

Reference[float]

checkbox(text: str, value: bool | Reference[bool], colour: Colour | None = None, radius: float | None = None, rect: Rect | None = None) Reference[bool][source]

Creates a checkbox GUI element.

Since the actual drawing of GUI elements is deferred till after layout has been updated (which occurs just after the on_gui event finishes), the updated value of this checkbox is not known when this method returns. Wait until the on_post_gui event (or the start of the next on_gui) event to get the new value of this checkbox. Until then the value returned by the checkbox will be the value passed in to it.

Parameters:
  • text (str) – the label of the checkbox.

  • value (bool | Reference[bool]) – whether the checkbox is currently checked.

  • colour (Colour | None) – the colour of the checkbox.

  • radius (float | None) – optionally, the corner radius of the checkbox.

  • rect (Rect | None) – optionally, the absolute coordinates of the rectangle to draw. These will be clipped to fit within the current layout group.

Returns:

a reference to a float which will be set to the new value of the checkbox.

Return type:

Reference[bool]

pySSV.ssv_gui.create_gui(canvas: SSVCanvas) SSVGUI[source]

Creates a new full screen GUI and render buffer and binds it to the canvas (the render buffer’s order defaults to 100).

Parameters:

canvas (SSVCanvas) – the canvas to bind to.

Returns:

a new SSVGUI object

Return type:

SSVGUI

class pySSV.ssv_colour.Colour(r: float = 0, g: float = 0, b: float = 0, a: float = 1)[source]

Represents an RGBA colour.

Creates a new colour object

Parameters:
  • r (float) – red (0-1)

  • g (float) – green (0-1)

  • b (float) – blue (0-1)

  • a (float) – alpha (0-1)

r: float
g: float
b: float
a: float
property astuple: Tuple[float, float, float, float]

Gets the (r, g, b, a) tuple of this colour.

static from_hex(hex_colour: str) Colour[source]
Parameters:

hex_colour (str) –

Return type:

Colour

static from_int(r: int, g: int, b: int, a: int = 255) Colour[source]
Parameters:
Return type:

Colour

class pySSV.ssv_fonts.SSVCharacterDefinition(id: int, char: str, x: int, y: int, width: int, height: int, x_offset: int, y_offset: int, x_advance: int)[source]
Parameters:
  • id (int) –

  • char (str) –

  • x (int) –

  • y (int) –

  • width (int) –

  • height (int) –

  • x_offset (int) –

  • y_offset (int) –

  • x_advance (int) –

id: int

The id of the character. (Usually the ascii character code)

char: str

The character being represented.

x: int

The x coordinate of the character in the bitmap from the left in pixels.

y: int

The y coordinate of the character in the bitmap from the top in pixels.

width: int

The width of the character in the bitmap in pixels.

height: int

The height of the character in the bitmap in pixels.

x_offset: int

How much to offset the character by in the x axis when rendering in pixels.

y_offset: int

How much to offset the character by in the y axis when rendering in pixels.

x_advance: int

How far to advance before drawing the next character.

class pySSV.ssv_fonts.SSVFont(font_path: str)[source]

Constructs a new SSVFont instance from an existing .fnt file.

A .fnt file is a Bitmap Font file which is an xml file following the schema defined here: https://www.angelcode.com/products/bmfont/doc/file_format.html

Font files can be generated using: https://github.com/soimy/msdf-bmfont-xml

Parameters:

font_path (str) – the path to the font file to load.


Internal Modules

As a user you generally won’t need to interact with these modules, the documentation provided here is for developers wanting to extend pySSV and power users wanting to better understand how pySSV works internally.

Utilities

class pySSV.ssv_logging.SSVFormatter(fmt)[source]

Initialize the formatter with specified format strings.

Initialize the formatter either with the specified format string, or a default as described above. Allow for specialized date formatting with the optional datefmt argument. If datefmt is omitted, you get an ISO8601-like (or RFC 3339-like) format.

Use a style parameter of ‘%’, ‘{’ or ‘$’ to specify that you want to use one of %-formatting, str.format() ({}) formatting or string.Template formatting in your format string.

Changed in version 3.2: Added the style parameter.

format(record: LogRecord) str[source]

Format the specified record as text.

The record’s attribute dictionary is used as the operand to a string formatting operation which yields the returned string. Before formatting the dictionary, a couple of preparatory steps are carried out. The message attribute of the record is computed using LogRecord.getMessage(). If the formatting string uses the time (as determined by a call to usesTime(), formatTime() is called to format the event time. If there is exception information, it is formatted using formatException() and appended to the message.

Parameters:

record (LogRecord) –

Return type:

str

class pySSV.ssv_logging.SSVLogStream[source]

A StringIO pipe for sending log messages with a severity level.

abstract write(text: str, severity: int = 20) int[source]

Called to write a log message to the stream.

Parameters:
  • text (str) – the message to log.

  • severity (int) – the severity to log the message with.

Returns:

the number of characters written to the stream.

Return type:

int

class pySSV.ssv_logging.SSVStreamHandler(stream=None)[source]

Initialize the handler.

If stream is not specified, sys.stderr is used.

Parameters:

stream (SSVLogStream | TextIO) –

stream: SSVLogStream | TextIO
emit(record: LogRecord) None[source]

Emit a record.

If a formatter is specified, it is used to format the record. The record is then written to the stream with a trailing newline. If exception information is present, it is formatted using traceback.print_exception and appended to the stream. If the stream has an ‘encoding’ attribute, it is used to determine how to do the output to the stream.

Parameters:

record (LogRecord) –

Return type:

None

pySSV.ssv_logging.make_formatter(prefix='pySSV')[source]
pySSV.ssv_logging.set_output_stream(stream: TextIOBase, level=20, prefix='pySSV')[source]
Parameters:

stream (TextIOBase) –

pySSV.ssv_logging.set_severity(severity: int)[source]

Sets the minimum message severity to be logged.

Parameters:

severity (int) – the logging severity as an integer. Preset severity levels are defined in the logging module. Possible values include: logging.DEBUG, logging.INFO, logging.WARN, logging.ERROR, etc…

pySSV.ssv_logging.get_severity() int[source]

Gets the minimum severity level of the current logger.

Returns:

the minimum severity level of the logger.

Return type:

int

pySSV.ssv_logging.log(msg, *args, severity=10, raw=False)[source]

Logs a message to the console.

Parameters:
  • msg – message to log to the console

  • args – objects to log to the console

  • severity – the severity to log the message with, severity levels are defined in the logging module.

  • raw – logs the message without any formatting

class pySSV.environment.Env(value)[source]

An enumeration.

JUPYTER_NOTEBOOK = 'notebook'
JUPYTERLAB = 'lab'
JUPYTERLITE = 'lite'
SAGEMAKER = 'sagemaker'
HYPHA = 'hypha'
COLAB = 'colab'
pySSV.environment.find_env()[source]
class pySSV.ssv_callback_dispatcher.SSVCallbackDispatcher[source]

A simple event callback dispatcher class similar to the ipywidgets.widgets.widget.CallbackDispatcher.

register_callback(callback: T, remove: bool = False)[source]

Registers/unregisters a callback to this dispatcher.

Parameters:
  • callback (T) – the callback to add/remove.

  • remove (bool) – whether the callback should be removed.

class pySSV.ssv_future.Future[source]

Represents a lightweight, low-level Event-backed future.

For more complex async requirements, the asyncio library is probably a better idea.

property result: T
property is_available: bool
set_result(val: T)[source]

Sets the result of the Future object and notifies objects waiting for the result.

Parameters:

val (T) – the result to set.

wait_result(timeout: float | None = None) T | None[source]

Waits synchronously until the result is available and then returns it.

Parameters:

timeout (float | None) – the maximum amount of time in seconds to wait for the result. Set to None to wait indefinitely.

Returns:

the awaited result or None if the operation timed out.

Return type:

T | None

class pySSV.ssv_future.Reference(value: T)[source]

Represents an object/value which can be passed by reference.

Parameters:

value (T) –

property result: T

Renderer

class pySSV.ssv_render.ShaderStage(value)[source]

An enum representing an OpenGL shader stage.

VERTEX = 'vertex'
TESSELLATION = 'tessellation'
GEOMETRY = 'geometry'
PIXEL = 'pixel'
COMPUTE = 'compute'
class pySSV.ssv_render.SSVStreamingMode(value)[source]

Represents an image/video streaming mode for pySSV. Note that some of these streaming formats may not be supported on all platforms.

JPG = 'jpg'
PNG = 'png'
VP8 = 'vp8'
VP9 = 'vp9'
H264 = 'h264'
HEVC = 'hevc'

Not supported

MPEG4 = 'mpeg4'

Not supported

MJPEG = 'mjpeg'
class pySSV.ssv_render.SSVRender(gl_version: int | None = None, use_renderdoc_api: bool = False)[source]

An abstract rendering backend for SSV

Initialises a new renderer (and backing graphics context) with the given options.

Parameters:
  • gl_version (int | None) – optionally, the minimum version of OpenGL to support.

  • use_renderdoc_api (bool) – whether the renderer should attempt to load the RenderDoc API.

abstract render() bool[source]

Renders a complete frame.

Returns:

whether the frame rendered successfully.

Return type:

bool

abstract read_frame(components: int = 4, frame_buffer_uid: int = 0) bytes[source]

Gets the current contents of the frame buffer as a byte array.

Parameters:
  • components (int) – how many components to read from the frame (out of RGBA).

  • frame_buffer_uid (int) – the frame buffer to read from.

Returns:

the contents of the frame buffer as a bytearray in the RGBA format.

Return type:

bytes

abstract read_frame_into(buffer: bytearray, components: int = 4, frame_buffer_uid: int = 0) None[source]

Gets the current contents of the frame buffer as a byte array.

Parameters:
  • buffer (bytearray) – the buffer to copy the frame into.

  • components (int) – how many components to read from the frame (out of RGBA).

  • frame_buffer_uid (int) – the frame buffer to read from.

Return type:

None

abstract log_context_info(full=False) None[source]

Logs the OpenGL information to the console for debugging.

Parameters:

full – whether to log all of the OpenGL context information (including extensions).

Return type:

None

abstract get_context_info() Dict[str, str][source]

Returns the OpenGL context information.

Return type:

Dict[str, str]

abstract get_supported_extensions() Set[str][source]

Gets the set of supported OpenGL shader compiler extensions.

Return type:

Set[str]

abstract update_frame_buffer(frame_buffer_uid: int, order: int | None, size: Tuple[int, int] | None, uniform_name: str | None, components: int | None = 4, dtype: str | None = 'f1') None[source]

Updates the resolution/format of the given frame buffer. Note that framebuffer 0 is always used for output. If the given framebuffer id does not exist, it is created.

Setting a parameter to None preserves the current value for that frame buffer.

Parameters:
  • frame_buffer_uid (int) – the uid of the framebuffer to update/create. Buffer 0 is the output framebuffer.

  • order (int | None) – the sorting order to render the frame buffers in, smaller values are rendered first.

  • size (Tuple[int, int] | None) – the new resolution of the framebuffer.

  • uniform_name (str | None) – the name of the uniform to bind this frame buffer to.

  • components (int | None) – how many vector components should each pixel have (RGB=3, RGBA=4).

  • dtype (str | None) – the data type for each pixel component (see: https://moderngl.readthedocs.io/en/5.8.2/topics/texture_formats.html).

Return type:

None

abstract delete_frame_buffer(frame_buffer_uid: int) None[source]

Destroys the given framebuffer. Note that framebuffer 0 can’t be destroyed as it is the output framebuffer.

Parameters:

frame_buffer_uid (int) – the uid of the framebuffer to destroy.

Return type:

None

abstract update_uniform(frame_buffer_uid: int | None, draw_call_uid: int | None, uniform_name: str, value: Any) None[source]

Updates the value of a named shader uniform.

Parameters:
  • frame_buffer_uid (int | None) – the uid of the framebuffer of the uniform to update. Set to None to update across all buffers.

  • draw_call_uid (int | None) – the uid of the draw call of the uniform to update. Set to None to update across all buffers.

  • uniform_name (str) – the name of the shader uniform to update.

  • value (Any) – the new value of the shader uniform. (Must be convertible to a GLSL type)

Return type:

None

abstract update_vertex_buffer(frame_buffer_uid: int, draw_call_uid: int, vertex_array: ndarray[Any, dtype[_ScalarType_co]] | None, index_array: ndarray[Any, dtype[_ScalarType_co]] | None, vertex_attributes: Tuple[str] | None) None[source]

Updates the data inside a vertex buffer.

Parameters:
  • frame_buffer_uid (int) – the uid of the framebuffer of the vertex buffer to update.

  • draw_call_uid (int) – the uid of the draw call of the vertex buffer to update.

  • vertex_array (ndarray[Any, dtype[_ScalarType_co]] | None) – a numpy array containing the new vertex data.

  • index_array (ndarray[Any, dtype[_ScalarType_co]] | None) – optionally, a numpy array containing the indices of vertices ordered to make triangles.

  • vertex_attributes (Tuple[str] | None) – a tuple of the names of the vertex attributes to map to in the shader, in the order that they appear in the vertex array.

Return type:

None

abstract delete_vertex_buffer(frame_buffer_uid: int, draw_call_uid: int) None[source]

Deletes an existing vertex buffer.

Parameters:
  • frame_buffer_uid (int) – the uid of the framebuffer of the vertex buffer to delete.

  • draw_call_uid (int) – the uid of the draw call of the vertex buffer to delete.

Return type:

None

abstract register_shader(frame_buffer_uid: int, draw_call_uid: int, vertex_shader: str, fragment_shader: str | None, tess_control_shader: str | None, tess_evaluation_shader: str | None, geometry_shader: str | None, compute_shader: str | None, primitive_type: str | None = None) None[source]

Compiles and registers a shader to a given framebuffer.

Parameters:
  • frame_buffer_uid (int) – the uid of the framebuffer to register the shader to.

  • draw_call_uid (int) – the uid of the draw call to register the shader to.

  • vertex_shader (str) – the preprocessed vertex shader GLSL source.

  • fragment_shader (str | None) – the preprocessed fragment shader GLSL source.

  • tess_control_shader (str | None) – the preprocessed tessellation control shader GLSL source.

  • tess_evaluation_shader (str | None) – the preprocessed tessellation evaluation shader GLSL source.

  • geometry_shader (str | None) – the preprocessed geometry shader GLSL source.

  • compute_shader (str | None) – [Not implemented] the preprocessed compute shader GLSL source.

  • primitive_type (str | None) – what type of input primitive to treat the vertex data as. One of (“TRIANGLES”, “LINES”, “POINTS), defaults to “TRIANGLES” if None.

Return type:

None

abstract update_texture(texture_uid: int, data: ndarray[Any, dtype[_ScalarType_co]], uniform_name: str | None, override_dtype: str | None, rect: Tuple[int, int, int, int] | Tuple[int, int, int, int, int, int] | None, treat_as_normalized_integer: bool) None[source]

Creates or updates a texture from the NumPy array provided.

Parameters:
  • texture_uid (int) – the uid of the texture to create or update.

  • data (ndarray[Any, dtype[_ScalarType_co]]) – a NumPy array containing the image data to copy to the texture.

  • uniform_name (str | None) – the name of the shader uniform to associate this texture with.

  • override_dtype (str | None) – optionally, a moderngl override

  • rect (Tuple[int, int, int, int] | Tuple[int, int, int, int, int, int] | None) – optionally, a rectangle (left, top, right, bottom) specifying the area of the target texture to update.

  • treat_as_normalized_integer (bool) – when enabled, integer types (singed/unsigned) are treated as normalized integers by OpenGL, such that when the texture is sampled values in the texture are mapped to floats in the range [0, 1] or [-1, 1]. See: https://www.khronos.org/opengl/wiki/Normalized_Integer for more details.

Return type:

None

abstract update_texture_sampler(texture_uid: int, repeat_x: bool | None, repeat_y: bool | None, linear_filtering: bool | None, linear_mipmap_filtering: bool | None, anisotropy: int | None, build_mip_maps: bool) None[source]

Updates a texture’s sampling settings. Parameters set to None are not updated.

Parameters:
  • texture_uid (int) – the uid of the texture to update.

  • repeat_x (bool | None) – whether the texture should repeat or be clamped in the x-axis.

  • repeat_y (bool | None) – whether the texture should repeat or be clamped in the y-axis.

  • linear_filtering (bool | None) – whether the texture should use nearest neighbour (False) or linear (True) interpolation.

  • linear_mipmap_filtering (bool | None) – whether different mipmap levels should blend linearly (True) or not (False).

  • anisotropy (int | None) – the number of anisotropy samples to use. (minimum of 1 = disabled, maximum of 16)

  • build_mip_maps (bool) – when set to True, immediately builds mipmaps for the texture.

Return type:

None

abstract delete_texture(texture_uid: int) None[source]

Destroys the given texture object.

Parameters:

texture_uid (int) – the uid of the texture to destroy.

Return type:

None

abstract renderdoc_capture_frame(filename: str | None) None[source]

Triggers a frame capture with Renderdoc if it’s initialised.

Parameters:

filename (str | None) – optionally, the filename and path to save the capture with.

Return type:

None

abstract set_start_time(start_time: float) None[source]

Sets the renderer’s start time; this is used by the renderer to compute the canvas time which is injected into shaders.

Parameters:

start_time (float) – the start time of the renderer in seconds since the start of the epoch.

Return type:

None

pySSV.ssv_render_opengl.load_render_doc(renderdoc_path: str | None = None) RENDERDOC_API_1_6_0[source]
Parameters:

renderdoc_path (str | None) –

Return type:

RENDERDOC_API_1_6_0

class pySSV.ssv_render_opengl.RENDERDOC_API_1_6_0[source]
class pySSV.ssv_render_opengl.SSVDrawCall[source]

Stores a reference to all the objects needed to represent a single draw call belonging to a render buffer.

order: int
vertex_buffer: Buffer | None
index_buffer: Buffer | None
vertex_attributes: Tuple[str, ...]
gl_vertex_array: VertexArray | None
shader_program: Program | None
primitive_type: int
release(needs_gc: bool, release_vb: bool = True)[source]
Parameters:
  • needs_gc (bool) –

  • release_vb (bool) –

class pySSV.ssv_render_opengl.SSVRenderBufferOpenGL(order: int, needs_gc: bool, frame_buffer: Framebuffer, render_texture: Texture, draw_calls: Dict[int, SSVDrawCall], uniform_name: str)[source]

Stores a reference to all the OpenGL objects needed to render a single render buffer.

Parameters:
  • order (int) –

  • needs_gc (bool) –

  • frame_buffer (Framebuffer) –

  • render_texture (Texture) –

  • draw_calls (Dict[int, SSVDrawCall]) –

  • uniform_name (str) –

order: int
needs_gc: bool
frame_buffer: Framebuffer
render_texture: Texture
draw_calls: Dict[int, SSVDrawCall]
uniform_name: str
release()[source]

Releases the resources within this render buffer, clearing the draw call list.

class pySSV.ssv_render_opengl.SSVTextureOpenGL(texture: Texture | Texture3D, uniform_name: str)[source]

Stores a reference to an OpenGL texture object.

Parameters:
  • texture (Texture | Texture3D) –

  • uniform_name (str) –

texture: Texture | Texture3D
uniform_name: str
release(needs_gc: bool)[source]
Parameters:

needs_gc (bool) –

class pySSV.ssv_render_opengl.SSVRenderOpenGL(gl_version: int | None = None, use_renderdoc_api: bool = False)[source]

A rendering backend for SSV based on OpenGL

Initialises a new renderer (and backing graphics context) with the given options.

Parameters:
  • gl_version (int | None) – optionally, the minimum version of OpenGL to support.

  • use_renderdoc_api (bool) – whether the renderer should attempt to load the RenderDoc API.

log_context_info(full=False)[source]

Logs the OpenGL information to the console for debugging.

Parameters:

full – whether to log all of the OpenGL context information (including extensions)

get_context_info() Dict[str, str][source]

Returns the OpenGL context information.

Return type:

Dict[str, str]

get_supported_extensions() Set[str][source]

Gets the set of supported OpenGL shader compiler extensions.

Return type:

Set[str]

update_frame_buffer(frame_buffer_uid: int, order: int | None, size: Tuple[int, int] | None, uniform_name: str | None, components: int | None = 4, dtype: str | None = 'f1')[source]

Updates the resolution/format of the given frame buffer. Note that framebuffer 0 is always used for output. If the given framebuffer id does not exist, it is created.

Setting a parameter to None preserves the current value for that frame buffer.

Parameters:
  • frame_buffer_uid (int) – the uid of the framebuffer to update/create. Buffer 0 is the output framebuffer.

  • order (int | None) – the sorting order to render the frame buffers in, smaller values are rendered first.

  • size (Tuple[int, int] | None) – the new resolution of the framebuffer.

  • uniform_name (str | None) – the name of the uniform to bind this frame buffer to.

  • components (int | None) – how many vector components should each pixel have (RGB=3, RGBA=4).

  • dtype (str | None) – the data type for each pixel component (see: https://moderngl.readthedocs.io/en/5.8.2/topics/texture_formats.html).

delete_frame_buffer(frame_buffer_uid: int)[source]

Destroys the given framebuffer. Note that framebuffer 0 can’t be destroyed as it is the output framebuffer.

Parameters:

frame_buffer_uid (int) – the uid of the framebuffer to destroy.

update_uniform(frame_buffer_uid: int | None, draw_call_uid: int | None, uniform_name: str, value: Any)[source]

Updates the value of a named shader uniform.

Parameters:
  • frame_buffer_uid (int | None) – the uid of the framebuffer of the uniform to update. Set to None to update across all buffers.

  • draw_call_uid (int | None) – the uid of the draw call of the uniform to update. Set to None to update across all buffers.

  • uniform_name (str) – the name of the shader uniform to update.

  • value (Any) – the new value of the shader uniform. (Must be convertible to a GLSL type)

update_vertex_buffer(frame_buffer_uid: int, draw_call_uid: int, vertex_array: ndarray[Any, dtype[_ScalarType_co]] | None, index_array: ndarray[Any, dtype[_ScalarType_co]] | None, vertex_attributes: Tuple[str] | None)[source]

Updates the data inside a vertex buffer.

Parameters:
  • frame_buffer_uid (int) – the uid of the framebuffer of the vertex buffer to update.

  • draw_call_uid (int) – the uid of the draw call of the vertex buffer to update.

  • vertex_array (ndarray[Any, dtype[_ScalarType_co]] | None) – a numpy array containing the new vertex data.

  • index_array (ndarray[Any, dtype[_ScalarType_co]] | None) – optionally, a numpy array containing the indices of vertices ordered to make triangles.

  • vertex_attributes (Tuple[str] | None) – a tuple of the names of the vertex attributes to map to in the shader, in the order that they appear in the vertex array.

delete_vertex_buffer(frame_buffer_uid: int, draw_call_uid: int)[source]

Deletes an existing vertex buffer.

Parameters:
  • frame_buffer_uid (int) – the uid of the framebuffer of the vertex buffer to delete.

  • draw_call_uid (int) – the uid of the draw call of the vertex buffer to delete.

register_shader(frame_buffer_uid: int, draw_call_uid: int, vertex_shader: str, fragment_shader: str | None, tess_control_shader: str | None, tess_evaluation_shader: str | None, geometry_shader: str | None, compute_shader: str | None, primitive_type: str | None = None)[source]

Compiles and registers a shader to a given framebuffer.

Parameters:
  • frame_buffer_uid (int) – the uid of the framebuffer to register the shader to.

  • draw_call_uid (int) – the uid of the draw call to register the shader to.

  • vertex_shader (str) – the preprocessed vertex shader GLSL source.

  • fragment_shader (str | None) – the preprocessed fragment shader GLSL source.

  • tess_control_shader (str | None) – the preprocessed tessellation control shader GLSL source.

  • tess_evaluation_shader (str | None) – the preprocessed tessellation evaluation shader GLSL source.

  • geometry_shader (str | None) – the preprocessed geometry shader GLSL source.

  • compute_shader (str | None) – [Not implemented] the preprocessed compute shader GLSL source.

  • primitive_type (str | None) – what type of input primitive to treat the vertex data as. One of (“TRIANGLES”, “LINES”, “POINTS), defaults to “TRIANGLES” if None.

update_texture(texture_uid: int, data: ndarray[Any, dtype[_ScalarType_co]], uniform_name: str | None, override_dtype: str | None, rect: Tuple[int, int, int, int] | Tuple[int, int, int, int, int, int] | None, treat_as_normalized_integer: bool)[source]

Creates or updates a texture from the NumPy array provided.

Parameters:
  • texture_uid (int) – the uid of the texture to create or update.

  • data (ndarray[Any, dtype[_ScalarType_co]]) – a NumPy array containing the image data to copy to the texture.

  • uniform_name (str | None) – the name of the shader uniform to associate this texture with.

  • override_dtype (str | None) – optionally, a moderngl override

  • rect (Tuple[int, int, int, int] | Tuple[int, int, int, int, int, int] | None) – optionally, a rectangle (left, top, right, bottom) specifying the area of the target texture to update.

  • treat_as_normalized_integer (bool) – when enabled, integer types (singed/unsigned) are treated as normalized integers by OpenGL, such that when the texture is sampled values in the texture are mapped to floats in the range [0, 1] or [-1, 1]. See: https://www.khronos.org/opengl/wiki/Normalized_Integer for more details.

update_texture_sampler(texture_uid: int, repeat_x: bool | None, repeat_y: bool | None, linear_filtering: bool | None, linear_mipmap_filtering: bool | None, anisotropy: int | None, build_mip_maps: bool)[source]

Updates a texture’s sampling settings. Parameters set to None are not updated.

Parameters:
  • texture_uid (int) – the uid of the texture to update.

  • repeat_x (bool | None) – whether the texture should repeat or be clamped in the x-axis.

  • repeat_y (bool | None) – whether the texture should repeat or be clamped in the y-axis.

  • linear_filtering (bool | None) – whether the texture should use nearest neighbour (False) or linear (True) interpolation.

  • linear_mipmap_filtering (bool | None) – whether different mipmap levels should blend linearly (True) or not (False).

  • anisotropy (int | None) – the number of anisotropy samples to use. (minimum of 1 = disabled, maximum of 16)

  • build_mip_maps (bool) – when set to True, immediately builds mipmaps for the texture.

delete_texture(texture_uid: int)[source]

Destroys the given texture object.

Parameters:

texture_uid (int) – the uid of the texture to destroy.

render()[source]

Renders a complete frame.

Returns:

whether the frame rendered successfully.

read_frame(components: int = 4, frame_buffer_uid: int = 0)[source]

Gets the current contents of the frame buffer as a byte array.

Parameters:
  • components (int) – how many components to read from the frame (out of RGBA).

  • frame_buffer_uid (int) – the frame buffer to read from.

Returns:

the contents of the frame buffer as a bytearray in the RGBA format.

read_frame_into(buffer, components: int = 4, frame_buffer_uid: int = 0)[source]

Gets the current contents of the frame buffer as a byte array.

Parameters:
  • buffer – the buffer to copy the frame into.

  • components (int) – how many components to read from the frame (out of RGBA).

  • frame_buffer_uid (int) – the frame buffer to read from.

renderdoc_capture_frame(filename: str | None)[source]

Triggers a frame capture with Renderdoc if it’s initialised.

Parameters:

filename (str | None) – optionally, the filename and path to save the capture with.

set_start_time(start_time: float)[source]

Sets the renderer’s start time; this is used by the renderer to compute the canvas time which is injected into shaders.

Parameters:

start_time (float) – the start time of the renderer in seconds since the start of the epoch.

class pySSV.ssv_render_process_client.SSVRenderProcessClient(backend: str, gl_version: int | None = None, timeout: float | None = 1, use_renderdoc_api: bool = False)[source]

This class creates, manages, and provides a communication interface for the render process (an SSVRenderProcessServer).

Initialises a new Render Process Client and starts the render process.

Parameters:
  • backend (str) – the rendering backend to use.

  • gl_version (int | None) – optionally, the minimum version of OpenGL to support.

  • timeout (float | None) – the render process watchdog timeout, set to None to disable.

  • use_renderdoc_api (bool) – whether the renderdoc_api should be initialised.

property is_alive
subscribe_on_render(observer: Callable[[bytes], None])[source]

Subscribes an event handler to the on_render event, triggered after each frame is rendered.

Parameters:

observer (Callable[[bytes], None]) – a function to handle the event (must have the signature: callback(data: bytes) -> None).

unsubscribe_on_render(observer: Callable[[bytes], None])[source]

Unsubscribes an event handler from the on_render event.

Parameters:

observer (Callable[[bytes], None]) – a function currently registered to handle the event.

subscribe_on_log(observer: Callable[[str], None])[source]

Subscribes an event handler to the on_log event, triggered when the render process logs a message.

Parameters:

observer (Callable[[str], None]) – a function to handle the event (must have the signature: callback(data: bytes) -> None).

unsubscribe_on_log(observer: Callable[[str], None])[source]

Unsubscribes an event handler from the on_log event.

Parameters:

observer (Callable[[str], None]) – a function currently registered to handle the event.

update_frame_buffer(frame_buffer_uid: int, order: int | None, size: Tuple[int, int] | None, uniform_name: str | None, components: int | None = 4, dtype: str | None = 'f1')[source]

Updates the resolution/format of the given frame buffer. Note that framebuffer 0 is always used for output. If the given framebuffer id does not exist, it is created.

Setting a parameter to None preserves the current value for that frame buffer.

Parameters:
  • frame_buffer_uid (int) – the uid of the framebuffer to update/create. Buffer 0 is the output framebuffer.

  • order (int | None) – the sorting order to render the frame buffers in, smaller values are rendered first.

  • size (Tuple[int, int] | None) – the new resolution of the framebuffer.

  • uniform_name (str | None) – the name of the uniform to bind this frame buffer to.

  • components (int | None) – how many vector components should each pixel have (RGB=3, RGBA=4).

  • dtype (str | None) – the data type for each pixel component (see: https://moderngl.readthedocs.io/en/5.8.2/topics/texture_formats.html).

delete_frame_buffer(buffer_uid: int)[source]

Destroys the given framebuffer. Note that framebuffer 0 can’t be destroyed as it is the output framebuffer.

Parameters:

buffer_uid (int) – the id of the framebuffer to destroy.

render(target_framerate: float, stream_mode: str, encode_quality: float | None = None)[source]

Starts rendering frames at the given framerate.

Parameters:
  • target_framerate (float) – the framerate to render at. Set to -1 to render a single frame.

  • stream_mode (str) – the streaming format to use to send the frames to the widget.

  • encode_quality (float | None) – the encoding quality to use for the given encoding format. Takes a float between 0-100 (some stream modes support values larger than 100, others clamp it internally), where 100 results in the highest quality. This value is scaled to give a bit rate target or quality factor for the chosen encoder. Pass in None to use the encoder’s default quality settings.

stop()[source]

Kills the render process.

send_heartbeat()[source]

Sends a heartbeat to the render process to keep it alive.

set_timeout(time: float | None = 1)[source]

Sets the maximum time the render process will wait for a heartbeat before killing itself. Set to None to disable the watchdog.

Parameters:

time (float | None) – timeout in seconds.

update_uniform(frame_buffer_uid: int | None, draw_call_uid: int | None, uniform_name: str, value: Any)[source]

Updates the value of a named shader uniform.

Parameters:
  • frame_buffer_uid (int | None) – the uid of the framebuffer of the uniform to update. Set to None to update across all buffers.

  • draw_call_uid (int | None) – the uid of the draw call of the uniform to update. Set to None to update across all buffers.

  • uniform_name (str) – the name of the shader uniform to update.

  • value (Any) – the new value of the shader uniform. (Must be convertible to a GLSL type)

update_vertex_buffer(frame_buffer_uid: int, draw_call_uid: int, vertex_array: ndarray[Any, dtype[_ScalarType_co]] | None, index_array: ndarray[Any, dtype[_ScalarType_co]] | None, vertex_attributes: Tuple[str, ...] | None)[source]

Updates the data inside a vertex buffer.

Parameters:
  • frame_buffer_uid (int) – the uid of the framebuffer of the vertex buffer to update.

  • draw_call_uid (int) – the uid of the draw call of the vertex buffer to update.

  • vertex_array (ndarray[Any, dtype[_ScalarType_co]] | None) – a numpy array containing the new vertex data.

  • index_array (ndarray[Any, dtype[_ScalarType_co]] | None) – optionally, a numpy array containing the indices of vertices ordered to make triangles.

  • vertex_attributes (Tuple[str, ...] | None) – a tuple of the names of the vertex attributes to map to in the shader, in the order that they appear in the vertex array.

delete_vertex_buffer(frame_buffer_uid: int, draw_call_uid: int)[source]

Deletes an existing vertex buffer.

Parameters:
  • frame_buffer_uid (int) – the uid of the framebuffer of the vertex buffer to delete.

  • draw_call_uid (int) – the uid of the draw call of the vertex buffer to delete.

update_texture(texture_uid: int, data: ndarray[Any, dtype[_ScalarType_co]], uniform_name: str | None, override_dtype: str | None, rect: Tuple[int, int, int, int] | Tuple[int, int, int, int, int, int] | None, treat_as_normalized_integer: bool)[source]

Creates or updates a texture from the NumPy array provided.

Parameters:
  • texture_uid (int) – the uid of the texture to create or update.

  • data (ndarray[Any, dtype[_ScalarType_co]]) – a NumPy array containing the image data to copy to the texture.

  • uniform_name (str | None) – the name of the shader uniform to associate this texture with.

  • override_dtype (str | None) – Optionally, a moderngl override

  • rect (Tuple[int, int, int, int] | Tuple[int, int, int, int, int, int] | None) – optionally, a rectangle (left, top, right, bottom) specifying the area of the target texture to update.

  • treat_as_normalized_integer (bool) – when enabled, integer types (singed/unsigned) are treated as normalized integers by OpenGL, such that when the texture is sampled values in the texture are mapped to floats in the range [0, 1] or [-1, 1]. See: https://www.khronos.org/opengl/wiki/Normalized_Integer for more details.

update_texture_sampler(texture_uid: int, repeat_x: bool | None = None, repeat_y: bool | None = None, linear_filtering: bool | None = None, linear_mipmap_filtering: bool | None = None, anisotropy: int | None = None, build_mip_maps: bool = False)[source]

Updates a texture’s sampling settings. Parameters set to None are not updated.

Parameters:
  • texture_uid (int) – the uid of the texture to update.

  • repeat_x (bool | None) – whether the texture should repeat or be clamped in the x-axis.

  • repeat_y (bool | None) – whether the texture should repeat or be clamped in the y-axis.

  • linear_filtering (bool | None) – whether the texture should use nearest neighbour (False) or linear (True) interpolation.

  • linear_mipmap_filtering (bool | None) – whether different mipmap levels should blend linearly (True) or not (False).

  • anisotropy (int | None) – the number of anisotropy samples to use. (minimum of 1 = disabled, maximum of 16)

  • build_mip_maps (bool) – when set to True, immediately builds mipmaps for the texture.

delete_texture(texture_uid: int)[source]

Destroys the given texture object.

Parameters:

texture_uid (int) – the uid of the texture to destroy.

register_shader(frame_buffer_uid: int, draw_call_uid: int, vertex_shader: str, fragment_shader: str | None = None, tess_control_shader: str | None = None, tess_evaluation_shader: str | None = None, geometry_shader: str | None = None, compute_shader: str | None = None, primitive_type: str | None = None)[source]

Compiles and registers a shader to a given framebuffer.

Parameters:
  • frame_buffer_uid (int) – the uid of the framebuffer to register the shader to.

  • draw_call_uid (int) – the uid of the draw call to register the shader to.

  • vertex_shader (str) – the preprocessed vertex shader GLSL source.

  • fragment_shader (str | None) – the preprocessed fragment shader GLSL source.

  • tess_control_shader (str | None) – the preprocessed tessellation control shader GLSL source.

  • tess_evaluation_shader (str | None) – the preprocessed tessellation evaluation shader GLSL source.

  • geometry_shader (str | None) – the preprocessed geometry shader GLSL source.

  • compute_shader (str | None) – [Not implemented] the preprocessed compute shader GLSL source.

  • primitive_type (str | None) – what type of input primitive to treat the vertex data as. One of (“TRIANGLES”, “LINES”, “POINTS), defaults to “TRIANGLES” if None.

renderdoc_capture_frame(filename: str | None)[source]

Triggers a frame capture with Renderdoc if it’s initialised.

Parameters:

filename (str | None) – optionally, the filename and path to save the capture with.

set_start_time(start_time: float) None[source]

Sets the renderer’s start time; this is used by the renderer to compute the canvas time which is injected into shaders.

Parameters:

start_time (float) – the start time of the renderer in seconds since the start of the epoch.

Return type:

None

get_context_info(timeout: float | None = None) Dict[str, str] | None[source]

Returns the OpenGL context information.

Parameters:

timeout (float | None) – the maximum amount of time in seconds to wait for the result. Set to None to wait indefinitely.

Return type:

Dict[str, str] | None

get_frame_times(timeout: float | None = None) Tuple[float, float, float, float] | None[source]

Gets the frame time statistics from the renderer. This function is blocking and shouldn’t be called too often.

Returns the following statistics:
  • avg_frame_time: Average time taken to render a frame (calculated each frame using: last_avg_frame_time * 0.9 + frame_time * 0.1)

  • max_frame_time: The maximum frame time since this function was last called. (Using dbg_log_frame_times interferes with this value.)

  • avg_encode_time: Average time taken to encode a frame for streaming (calculated each frame using: last_avg_encode_time * 0.9 + encode_time * 0.1)

  • max_encode_time: The maximum time taken to encode a frame for streaming since this function was last called. (Using dbg_log_frame_times interferes with this value.)

Parameters:

timeout (float | None) – the maximum amount of time in seconds to wait for the result. Set to None to wait indefinitely.

Returns:

(avg_frame_time, max_frame_time, avg_encode_time, max_encode_time)

Return type:

Tuple[float, float, float, float] | None

get_supported_extensions(timeout: float | None = None) Set[str] | None[source]

Gets the set of supported OpenGL shader compiler extensions.

Parameters:

timeout (float | None) – the maximum amount of time in seconds to wait for the result. Set to None to wait indefinitely.

Return type:

Set[str] | None

save_image(image_type: SSVStreamingMode, quality: float, size: Tuple[int, int] | None, render_buffer: int, suppress_ui: bool) Future[bytes][source]

Saves the current frame as an image.

Parameters:
  • image_type (SSVStreamingMode) – the image compression algorithm to use.

  • quality (float) – the encoding quality to use for the given encoding format. Takes a float between 0-100 (some stream modes support values larger than 100, others clamp it internally), where 100 results in the highest quality. This value is scaled to give a bit rate target or quality factor for the chosen encoder.

  • size (Tuple[int, int] | None) – optionally, the width and height of the saved image. If set to None uses the current resolution of the render buffer.

  • render_buffer (int) – the uid of the render buffer to save.

  • suppress_ui (bool) – whether any active SSVGUIs should be suppressed.

Returns:

the bytes representing the compressed image.

Return type:

Future[bytes]

dbg_log_context_info(full=False)[source]

Logs the OpenGL information to the console for debugging.

Parameters:

full – whether to log all of the OpenGL context information (including extensions).

dbg_log_frame_times(enabled=True)[source]

Enables or disables frame time logging.

Parameters:

enabled – whether to log frame times.

dbg_render_test()[source]

DEPRECATED

[For debugging only] Sets up the pipeline to render with a demo shader.

dbg_render_command(command: str, *args)[source]

[For debugging only] Sends a custom command to the render process.

Parameters:
  • command (str) – the custom command to send

  • args – the arguments to send with the command

class pySSV.ssv_render_process_server.SSVRenderProcessLogger(tx_queue: Queue)[source]

A StringIO pipe for sending log messages to, this class pipes incoming messages to “LogM” commands.

Parameters:

tx_queue (Queue) –

write(text: str, severity: int = 21) int[source]

Called to write a log message to the stream.

Parameters:
  • text (str) – the message to log.

  • severity (int) – the severity to log the message with.

Returns:

the number of characters written to the stream.

Return type:

int

class pySSV.ssv_render_process_server.SSVRenderProcessServer(backend: str, gl_version: int | None, command_queue_tx: Queue, command_queue_rx: Queue, log_severity: int, timeout: float | None, use_renderdoc_api: bool = False)[source]

This class listens for render commands and dispatches them to the renderer. This class is intended to be constructed in a dedicated process by SSVRenderProcessClient.

Parameters:
  • backend (str) –

  • gl_version (int | None) –

  • command_queue_tx (Queue) –

  • command_queue_rx (Queue) –

  • log_severity (int) –

  • timeout (float | None) –

  • use_renderdoc_api (bool) –

Jupyter Widget

pySSV.ssv_render_widget.OnSaveImageDelegate

A callable with parameters matching the signature:

on_save_image(image_type: SSVStreamingMode, quality: float, size: Optional[Tuple[int, int]], render_buffer: int):
    ...
image_type: the image codec to save the image with.
quality: a value between 0-100, indicating the image quality (larger values are higher quality). For png this represents compression quality (higher values result in smaller files, but take longer to compress).
size: the resolution of the saved image. When set to None, uses the current resolution of the render buffer (this also prevents an additional frame from being rendered).
render_buffer: the uid of the render buffer to save.
suppress_ui: whether any active SSVGUIs should be supressed.

alias of Callable[[SSVStreamingMode, float, Optional[Tuple[int, int]], int, bool], None]

class pySSV.ssv_render_widget.SSVRenderWidget(**kwargs: Any)[source]

An SSV Render Widget manages the state and communication of the Jupyter Widget responsible for displaying rendered results embedded in a Jupyter notebook.

Public constructor

streaming_mode

An enum whose value must be in a given sequence.

stream_data_binary

A trait for byte strings.

stream_data_ascii

A trait for unicode strings.

use_websockets

A boolean (True, False) trait.

websocket_url

A trait for unicode strings.

canvas_width

An int trait.

canvas_height

An int trait.

status_connection

A boolean (True, False) trait.

status_logs

A trait for unicode strings.

mouse_pos_x

An int trait.

mouse_pos_y

An int trait.

enable_renderdoc

A boolean (True, False) trait.

frame_rate

A float trait.

frame_times

A trait for unicode strings.

on_heartbeat(callback: Callable[[], None], remove=False)[source]

Register a callback to execute when the widget receives a heartbeat from the client.

Parameters:
  • callback (Callable[[], None]) – the function to be called when a heartbeat is received.

  • remove – set to true to remove the callback from the list of callbacks.

on_play(callback: Callable[[], None], remove=False)[source]

Register a callback to execute when the widget’s play button is pressed.

Parameters:
  • callback (Callable[[], None]) – the function to be called when the play button is pressed.

  • remove – set to true to remove the callback from the list of callbacks.

on_stop(callback: Callable[[], None], remove=False)[source]

Register a callback to execute when the widget’s stop button is pressed.

Parameters:
  • callback (Callable[[], None]) – the function to be called when the stop button is pressed.

  • remove – set to true to remove the callback from the list of callbacks.

on_click(callback: Callable[[bool, int], None], remove=False)[source]

Register a callback to execute when the widget receives a mouseup or mousedown event.

Parameters:
  • callback (Callable[[bool, int], None]) – the function to be called when the event is raised.

  • remove – set to true to remove the callback from the list of callbacks.

on_key(callback: Callable[[str, bool], None], remove=False)[source]

Register a callback to execute when the widget receives a keyup or keydown event.

Parameters:
  • callback (Callable[[str, bool], None]) – the function to be called when the event is raised.

  • remove – set to true to remove the callback from the list of callbacks.

on_mouse_wheel(callback: Callable[[float], None], remove=False)[source]

Register a callback to execute when the widget receives a mouse wheel event.

Parameters:
  • callback (Callable[[float], None]) – the function to be called when the event is raised.

  • remove – set to true to remove the callback from the list of callbacks.

on_save_image(callback: Callable[[SSVStreamingMode, float, Tuple[int, int] | None, int, bool], None], remove=False)[source]

Register a callback to execute when the widget’s ‘save image’ button is pressed.

Parameters:
on_renderdoc_capture(callback: Callable[[], None], remove=False)[source]

Register a callback to execute when the widget’s renderdoc capture button is pressed.

Parameters:
  • callback (Callable[[], None]) – the function to be called when the event is raised.

  • remove – set to true to remove the callback from the list of callbacks.

download_file(filename: str, data: bytes)[source]

Triggers a file download in the client’s web browser.

Parameters:
  • filename (str) – the file name of the file to download.

  • data (bytes) – the data to be downloaded.

class pySSV.ssv_render_widget.SSVRenderWidgetLogIO(widget: SSVRenderWidget)[source]
Parameters:

widget (SSVRenderWidget) –

write(_SSVRenderWidgetLogIO__s: str) int[source]

Write string to stream. Returns the number of characters written (which is always equal to the length of the string).

Parameters:

_SSVRenderWidgetLogIO__s (str) –

Return type:

int

class pySSV.ssv_canvas_stream_server.SSVCanvasStreamServerHTTP(msg_queue: SimpleQueue, is_alive: Callable[[], bool], *args, **kwargs)[source]
Parameters:
  • msg_queue (SimpleQueue) –

  • is_alive (Callable[[], bool]) –

do_GET()[source]
class pySSV.ssv_canvas_stream_server.SSVCanvasStreamServer(http: bool = False, port: int | None = None, timeout: float = 10)[source]

A basic websocket/http server which serves frame data to the SSV canvas.

Parameters:
property url: str

Gets the URL of this websocket.

property is_alive
close()[source]

Shuts down the websocket server.

send(msg: bytes)[source]

Sends a bytes packet to the websocket.

Parameters:

msg (bytes) – the packet to send.

heartbeat()[source]

Sends a heartbeat to the server to keep it alive.

Shader Preprocessor

class pySSV.ssv_shader_preprocessor.SSVShaderPreprocessor(gl_version: str, supports_line_directives: bool)[source]

This class is responsible for preprocessing shader source code and shader templates into platform specific, ready to compile shaders for each pipeline stage.

Parameters:
  • gl_version (str) –

  • supports_line_directives (bool) –

property global_defines: Dict[str, str]

Gets the (mutable) dictionary of compiler macros which are defined globally in all shaders. This does not include any macros defined by the SSVShaderPreprocessor itself. The dict contains key-value pairs where the key is the macro name and the value is the macro definition (as a C preprocessor macro).

preprocess(source: str, filepath: str | None = None, additional_template_directory: str | None = None, additional_templates: List[str] | None = None, shader_defines: Dict[str, str] | None = None, compiler_extensions: List[str] | None = None) Dict[str, str][source]

Preprocesses an SSV shader into multiple processed shaders for each pipeline.

Parameters:
  • source (str) – the shader source code to preprocess. It should contain the necessary #pragma SSV <template_name> directive see Built In Shader Templates for more information.

  • filepath (str | None) – the filepath of the shader, used to help the preprocessor give more meaningful error messages.

  • additional_template_directory (str | None) – a path to a directory containing custom shader templates. See Writing Shader Templates for information about using custom shader templates.

  • additional_templates (List[str] | None) – a list of custom shader templates (source code, not paths). See Writing Shader Templates for information about using custom shader templates.

  • shader_defines (Dict[str, str] | None) – extra preprocessor defines to be enabled globally.

  • compiler_extensions (List[str] | None) – a list of GLSL extensions required by this shader (eg: GL_EXT_control_flow_attributes)

Returns:

a dict of compiled shaders for each of the required pipeline stages.

Return type:

Dict[str, str]

dbg_query_shader_templates(additional_template_directory: str | None = None) List[SSVTemplatePragmaData][source]

Gets a list of all the shader templates available to the preprocessor.

Parameters:

additional_template_directory (str | None) – a path to a directory containing custom shader templates.

Returns:

A list of shader template metadata definitions.

Return type:

List[SSVTemplatePragmaData]

dbg_query_shader_template(template_name: str, additional_template_directory: str | None = None, additional_templates: List[str] | None = None) str[source]

Gets the list of arguments a given shader template expects and returns a string containing their usage info.

Parameters:
  • template_name (str) – the name of the template to look for.

  • additional_template_directory (str | None) – a path to a directory containing custom shader templates.

  • additional_templates (List[str] | None) – a list of custom shader templates (source code, not paths).

Returns:

the shader template’s auto generated help string.

Return type:

str

add_dynamic_uniform(name: str, glsl_type: str)[source]

Adds a uniform declaration to _DYNAMIC_UNIFORMS macro.

Parameters:
  • name (str) – the name of the uniform to add. Must be a valid GLSL identifier.

  • glsl_type (str) – the glsl type of the uniform.

remove_dynamic_uniform(name: str)[source]

Removes a uniform declaration from the dynamic uniforms.

Parameters:

name (str) – the name of the uniform to remove.

class pySSV.ssv_shader_source_preprocessor.SSVShaderSourcePreprocessor(shader_source)[source]

This class is responsible for the actual preprocessing of the shader template. It extends the pcpp.Preprocessor to add functionality needed to support our custom #include and #pragma directives.

class pySSV.ssv_pragma_parser.SSVTemplatePragmaData(**kwargs)[source]
command: str
name: str
author: str | None = None
description: str | None = None
shader_stage: List[str] | None = None
non_positional: bool = False
action: str | None = None
default: str | None = None
choices: List[str] | None = None
const: str | None = None
primitive_type: str | None = None
class pySSV.ssv_pragma_parser.SSVShaderPragmaData(**kwargs)[source]
template: str
args: List[str] = []
class pySSV.ssv_pragma_parser.SSVTemplatePragmaParser[source]

This class is responsible for parsing #pragma definitions in SSV shader templates.

Refer to Writing Shader Templates for details on writing shader templates.

on_include_not_found(is_malformed, is_system_include, curdir, includepath)[source]

Used internally by the parser.

on_error(file, line, msg)[source]

Used internally by the parser.

on_directive_unknown(directive, toks, ifpassthru, precedingtoks)[source]

Used internally by the parser.

parse(input, source=None, ignore=None) Dict[str, List[SSVTemplatePragmaData]][source]

Parses the #pragma directives of a shader template.

Parameters:
  • input – the source of the shader template.

  • source – the path to the source file.

  • ignore

Returns:

a dictionary of parsed shader template commands.

Return type:

Dict[str, List[SSVTemplatePragmaData]]

write(oh=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]

The pragma parser only parses #pragma arguments, it should not be used to preprocess shader files.

Parameters:

oh – unused

class pySSV.ssv_pragma_parser.SSVShaderPragmaParser[source]

This class is responsible for parsing #pragma definitions in SSV shaders.

on_directive_unknown(directive, toks, ifpassthru, precedingtoks)[source]

Used internally by the parser.

parse(input, source=None, ignore=None) SSVShaderPragmaData[source]

Parses the #pragma directives of a shader.

Parameters:
  • input – the source of the shader.

  • source – the path to the source file.

  • ignore

Returns:

an object of parsed shader template info.

Return type:

SSVShaderPragmaData

write(oh=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]

The pragma parser only parses #pragma arguments, it should not be used to preprocess shader files.

Parameters:

oh – unused

class pySSV.ssv_shader_args_tokenizer.SSVShaderArgsTokenizer[source]
static correct_tokens(tokens: List[Any], preprocessor: Preprocessor)[source]

This method takes a list of PCPP LexTokens and converts them to a list of arguments for argparse.

This method handles string un-escaping and whitespace stripping.

Parameters:
  • tokens (List[Any]) – the list of PCPP tokens to parse.

  • preprocessor (Preprocessor) – the preprocessor used to generate the tokens.

Returns:

a list of arguments.