Crate wrend

Source
Expand description

Wrend is a WebGL2 Rendering library for making Rust/JavaScript + WebGL development easier and safer.

Wrend provides an organized system for building custom rendering pipelines: you tell Wrend how all of your graphical resources relate to one another through user-specified ids and callbacks, and it does all the work of actually putting things together. It also comes with some out-of-the-box nice-to-have abstractions like recording canvas output and animation frame scheduling, as well as automatic clean-up.

Though most of the demo app examples are built using Yew, wrend itself is framework agnostic and is designed to be used in a variety of settings with diverse rendering pipelines, including contexts like React and raw HTML & JavaScript.

§Overview

The fundamental organizing components of Wrend are links, such as ProgramLink, AttributeLink, and UniformLink, which get appended to a RendererDataBuilder. These links tell wrend how your data should be created and how each resource relates to all the other resources in your pipeline.

§Callbacks

Many links accept some sort of callback, which is used to create a particular resource in your build pipeline.

For example, BufferLink accepts a BufferCreateCallback, which is called during the build process to acquire a web_sys::WebGlBuffer. In this callback, you are free to initialize your web_sys::WebGlBuffer however you like.

§Ids

Most resources such as shaders, Uniforms and Attributes retrieve resources using unique Ids, which can be any data type that implements the Id trait. These Ids help Wrend understand how your data fits together.

For example, you can load shaders into the build pipeline using RendererDataBuilder::add_vertex_shader_src. Then, when creating a ProgramLink, you can refer to that shader using its VertexShaderId to link that shader to any number of programs you create.

§Build

Once all resources and links have been added to the RendererDataBuilder, the pipeline can be built on using RendererDataBuilder::build_renderer.

§Panics

There are very few locations in which Rust code can panic in wrend, and those that exist are being slimmed down.

The primary locations that can are where JavaScript types such as arrays are passed into Rust–because these types must be converted to WebAssembly, there is currently the chance for panic if the wrong type is supplied. If using TypeScript, you should see TypeScript errors for any incorrect types supplied, as the library as a whole is strongly typed.

A long term goal of wrend is to provide matchable errors (or catchable errors in JavaScript) for all fallible operations.

§Example

The following is a “Hello, triangle!” example (the equivalent of “Hello, world!” for WebGL)

use js_sys::Float32Array;
use wasm_bindgen::{prelude::*, JsCast};
use web_sys::{window, HtmlCanvasElement, WebGl2RenderingContext};
use wrend::{
    AttributeCreateContext, AttributeLink, BufferCreateContext, BufferLink, Id, IdDefault, IdName,
    ProgramLink, Renderer, RendererData,
};

#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Default)]
pub struct ProgramId;

impl Id for ProgramId {}

#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Default)]
pub struct VaoId;

impl Id for VaoId {}

#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub enum BufferId {
    VertexBuffer,
}

impl Id for BufferId {}

impl Default for BufferId {
    fn default() -> Self {
        Self::VertexBuffer
    }
}

impl IdName for BufferId {
    fn name(&self) -> String {
        match self {
            BufferId::VertexBuffer => "a_position".to_string(),
        }
    }
}

#[derive(Clone, Default, Copy, PartialEq, Eq, Hash, Debug)]
pub struct VertexShaderId;

impl Id for VertexShaderId {}

#[derive(Clone, Default, Copy, PartialEq, Eq, Hash, Debug)]
pub struct FragmentShaderId;

impl Id for FragmentShaderId {}

#[derive(Clone, Default, Copy, PartialEq, Eq, Hash, Debug)]
pub struct PositionAttributeId;

impl Id for PositionAttributeId {}

impl IdName for PositionAttributeId {
    fn name(&self) -> String {
        String::from("a_position")
    }
}

#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default)]
struct AppState {
    count: u32,
}

const VERTEX_SHADER: &str = r#"#version 300 es
in vec2 a_position;
out vec2 v_position;

void main() {
    gl_Position = vec4(a_position, 0, 1);
    vec2 zero_to_two = a_position + 1.0;
    vec2 zero_to_one = zero_to_two * 0.5;
    v_position = zero_to_one;
}"#;


const FRAGMENT_SHADER: &str = r#"#version 300 es
precision mediump float;
in vec2 v_position;
out vec4 out_color;

void main() {
  out_color = vec4(v_position.x, v_position.y, v_position.x * 0.5 + v_position.y * 0.5, 1);
}"#;

pub fn main() -> Result<(), JsValue> {
    let canvas: HtmlCanvasElement = window()
        .unwrap()
        .document()
        .unwrap()
        .query_selector("canvas")
        .unwrap()
        .unwrap()
        .dyn_into()
        .unwrap();

    let app_state = AppState::default();

    let program_link = ProgramLink::new(ProgramId, VertexShaderId, FragmentShaderId);

    let vertex_buffer_link =
        BufferLink::new(BufferId::VertexBuffer, |ctx: &BufferCreateContext| {
            let gl = ctx.gl();
            let buffer = gl.create_buffer().unwrap();
            gl.bind_buffer(WebGl2RenderingContext::ARRAY_BUFFER, Some(&buffer));
            let vertex_array = unsafe { Float32Array::view(&[-0.0, 1.0, 1.0, -1.0, -1.0, -1.0]) };
            gl.buffer_data_with_array_buffer_view(
                WebGl2RenderingContext::ARRAY_BUFFER,
                &vertex_array,
                WebGl2RenderingContext::STATIC_DRAW,
            );

            buffer
        });

    let a_position_link = AttributeLink::new(
        VaoId,
        BufferId::VertexBuffer,
        PositionAttributeId,
        |ctx: &AttributeCreateContext| {
            let gl = ctx.gl();
            let attribute_location = ctx.attribute_location();
            let webgl_buffer = ctx.webgl_buffer();
            gl.bind_buffer(WebGl2RenderingContext::ARRAY_BUFFER, Some(webgl_buffer));
            gl.vertex_attrib_pointer_with_i32(
                attribute_location.into(),
                2,
                WebGl2RenderingContext::FLOAT,
                false,
                0,
                0,
            );
        },
    );

    let render_callback = |renderer_data: &RendererData<
        VertexShaderId,
        FragmentShaderId,
        ProgramId,
        IdDefault,
        BufferId,
        PositionAttributeId,
        IdDefault,
        IdDefault,
        IdDefault,
        VaoId,
        AppState,
    >| {
        let gl = renderer_data.gl();
        let canvas: HtmlCanvasElement = gl.canvas().unwrap().dyn_into().unwrap();

        renderer_data.use_program(&ProgramId);
        renderer_data.use_vao(&VaoId);

        gl.viewport(0, 0, canvas.width() as i32, canvas.height() as i32);
        gl.clear_color(0.0, 0.0, 0.0, 0.0);
        gl.clear(WebGl2RenderingContext::COLOR_BUFFER_BIT);
        gl.draw_arrays(WebGl2RenderingContext::TRIANGLES, 0, 3);
    };

    let mut render_builder = Renderer::builder();

    render_builder
        .set_canvas(canvas)
        .set_user_ctx(app_state)
        .add_vertex_shader_src(VertexShaderId, VERTEX_SHADER.to_string())
        .add_fragment_shader_src(FragmentShaderId, FRAGMENT_SHADER.to_string())
        .add_program_link(program_link)
        .add_buffer_link(vertex_buffer_link)
        .add_attribute_link(a_position_link)
        .add_vao_link(VaoId)
        .set_render_callback(render_callback);

    let renderer = render_builder
        .build_renderer()
        .expect("Renderer should successfully build");

    renderer.render();

    Ok(())
}

§Demos

todo

§Future Work

Currently, wrend only supports build pipelines where all resources are initialized up front. That is, no new textures, buffers, uniforms can be added after the pipeline has been initialized.

Structs§

AnimationCallback
AnimationCallbackJs
Attribute
AttributeCreateCallback
AttributeCreateCallbackJs
AttributeCreateContext
Context that is used when a new attribute is created
AttributeCreateContextJs
AttributeJs
AttributeLink
AttributeLinkJs
AttributeLocation
Wrapper around the raw number returned from WebGL to represent an attribute location
AttributeMap
Bridge
Enables accepting either a single item or many items when taking function arguments
Buffer
BufferCreateCallback
BufferCreateCallbackJs
BufferCreateContext
Context used when creating a buffer–passed as an argument to the callback
BufferCreateContextJs
BufferJs
BufferLink
BufferLinkJs
BufferMap
CallbackWithContext
This is a reusable callback type, useful in contexts where a callback must be received from the user which will later be invoked with specific arguments.
Color
Color and position values are stored as floats Colors are actually written to memory as bytes (0->255)
Framebuffer
FramebufferCreateCallback
FramebufferCreateCallbackJs
FramebufferCreateContext
Context used when creating a Framebuffer object–passed into the callback as the first argument
FramebufferCreateContextJs
FramebufferJs
FramebufferLink
FramebufferLinkJs
GetContextCallback
Wrapper around CallbackWithContext to provide a default implementation
GetContextCallbackJs
IdDefault
Default ID that can be used when no id has been specified by the consuming application
Listener
Safe wrapper around eventListener callbacks that cleans them up once the Listener struct is dropped For more information, see https://github.com/rustwasm/wasm-bindgen/issues/993.
Matrix4x4
Point
Color and position values are stored as floats Colors are actually written to memory as bytes (0->255)
ProgramLink
This contains an id for a pair of shaders: one vertex shader and one fragment shader. These can be combined to link together a program.
ProgramLinkBuilder
ProgramLinkJs
ProgramLinkJsBuilder
RenderCallback
RenderCallbackJs
Renderer
The Renderer struct takes ownership of the RendererData, enabling it to perform more complex operations than would otherwise be possible, such as animating renders over time or recording canvas output.
RendererData
RendererDataBuilder
RendererDataBuilderJs
See RendererDataBuilder
RendererDataJs
RendererJs
StringArray
Texture
TextureCreateCallback
TextureCreateCallbackJs
TextureCreateContext
This is the context object that is passed to the create_texture callback function
TextureCreateContextJs
TextureJs
TextureJsArray
TextureLink
TextureLinkJs
TextureMap
TransformFeedbackLink
TransformFeedbackLinkJs
Uniform
Contains the build information for a WebGL uniform.
UniformContext
This is the context object that is passed to each uniform’s update callback
UniformContextJs
UniformCreateUpdateCallback
UniformCreateUpdateCallbackJs
UniformJs
UniformLink
This link is used to associated a one or more ProgramIds with a conceptual uniform. This allows sharing uniforms across programs, even when each uniform’s location differs between programs.
UniformLinkJs
UniformLocationsMap
UniformMap
UniformShouldUpdateCallback
This callback is used to determine whether a crate::Uniform should be updated or not. Can be created by converting from either a Rust or a JavaScript callback.
UniformShouldUpdateCallbackJs
Vec3
Color and position values are stored as floats Colors are actually written to memory as bytes (0->255)
WebGlProgramMap
WebGlShaderMap

Enums§

BuildRendererError
Callback
Wrapper type for a callback that can be either a JavaScript callback or a Rust callback
CompileShaderError
CreateAttributeError
CreateBufferError
CreateFramebufferError
CreateTextureError
CreateTransformFeedbackError
CreateUniformError
CreateVAOError
LinkProgramError
ProgramLinkBuildError
RendererBuilderError
SaveContextError
ShaderType
Safe wrapper around WebGL’s fragment shader i32s
WebGlContextError

Constants§

QUAD

Traits§

Id
Collection of traits that make something useful as an id for programs, shaders, uniforms, etc.
IdName
Useful for Ids that need a literal String representation (such as uniforms)
IntoJsWrapper
For structs that were originally implemented in Rust but also have a dedicated JavaScript-compatible wrapper.

Functions§

degrees_to_radians
init_once
This optional function can be called once to show more more helpful errors on panic as well as to provide standard logging output to the console in general.
random_with_range

Type Aliases§

AttributeCreateCallbackInner
AttributeCreateContextJsInner
AttributeJsInner
AttributeLinkJsInner
BufferJsInner
BufferLinkJsInner
CallbackWithContextDefaultReturnType
Type alias for the default return type of the callback type
FramebufferJsInner
FramebufferLinkJsInner
GetContextCallbackInner
ProgramLinkBuilderJsInner
ProgramLinkJsInner
RendererDataJsInner
Wrapper around RendererData to make it callable from JavaScript.
RendererJsInner
TextureCreateContextJsInner
TextureJsInner
TextureLinkJsInner
TransformFeedbackLinkJsInner
UniformContextJsInner
UniformJsInner
UniformLinkJsInner
UniformShouldUpdateCallbackInner
This is the inner type that UniformShouldUpdateCallback stores