├── .gitignore ├── Cargo.toml ├── LICENSE ├── README.md ├── index.html └── src └── lib.rs /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "hello_triangle_wasm_rust" 3 | version = "0.1.0" 4 | authors = ["Ian Kettlewell "] 5 | edition = "2018" 6 | license = "CC0" 7 | 8 | [dependencies] 9 | 10 | [lib] 11 | crate-type = ["cdylib"] -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Creative Commons Legal Code 2 | 3 | CC0 1.0 Universal 4 | 5 | CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE 6 | LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN 7 | ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS 8 | INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES 9 | REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS 10 | PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM 11 | THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED 12 | HEREUNDER. 13 | 14 | Statement of Purpose 15 | 16 | The laws of most jurisdictions throughout the world automatically confer 17 | exclusive Copyright and Related Rights (defined below) upon the creator 18 | and subsequent owner(s) (each and all, an "owner") of an original work of 19 | authorship and/or a database (each, a "Work"). 20 | 21 | Certain owners wish to permanently relinquish those rights to a Work for 22 | the purpose of contributing to a commons of creative, cultural and 23 | scientific works ("Commons") that the public can reliably and without fear 24 | of later claims of infringement build upon, modify, incorporate in other 25 | works, reuse and redistribute as freely as possible in any form whatsoever 26 | and for any purposes, including without limitation commercial purposes. 27 | These owners may contribute to the Commons to promote the ideal of a free 28 | culture and the further production of creative, cultural and scientific 29 | works, or to gain reputation or greater distribution for their Work in 30 | part through the use and efforts of others. 31 | 32 | For these and/or other purposes and motivations, and without any 33 | expectation of additional consideration or compensation, the person 34 | associating CC0 with a Work (the "Affirmer"), to the extent that he or she 35 | is an owner of Copyright and Related Rights in the Work, voluntarily 36 | elects to apply CC0 to the Work and publicly distribute the Work under its 37 | terms, with knowledge of his or her Copyright and Related Rights in the 38 | Work and the meaning and intended legal effect of CC0 on those rights. 39 | 40 | 1. Copyright and Related Rights. A Work made available under CC0 may be 41 | protected by copyright and related or neighboring rights ("Copyright and 42 | Related Rights"). Copyright and Related Rights include, but are not 43 | limited to, the following: 44 | 45 | i. the right to reproduce, adapt, distribute, perform, display, 46 | communicate, and translate a Work; 47 | ii. moral rights retained by the original author(s) and/or performer(s); 48 | iii. publicity and privacy rights pertaining to a person's image or 49 | likeness depicted in a Work; 50 | iv. rights protecting against unfair competition in regards to a Work, 51 | subject to the limitations in paragraph 4(a), below; 52 | v. rights protecting the extraction, dissemination, use and reuse of data 53 | in a Work; 54 | vi. database rights (such as those arising under Directive 96/9/EC of the 55 | European Parliament and of the Council of 11 March 1996 on the legal 56 | protection of databases, and under any national implementation 57 | thereof, including any amended or successor version of such 58 | directive); and 59 | vii. other similar, equivalent or corresponding rights throughout the 60 | world based on applicable law or treaty, and any national 61 | implementations thereof. 62 | 63 | 2. Waiver. To the greatest extent permitted by, but not in contravention 64 | of, applicable law, Affirmer hereby overtly, fully, permanently, 65 | irrevocably and unconditionally waives, abandons, and surrenders all of 66 | Affirmer's Copyright and Related Rights and associated claims and causes 67 | of action, whether now known or unknown (including existing as well as 68 | future claims and causes of action), in the Work (i) in all territories 69 | worldwide, (ii) for the maximum duration provided by applicable law or 70 | treaty (including future time extensions), (iii) in any current or future 71 | medium and for any number of copies, and (iv) for any purpose whatsoever, 72 | including without limitation commercial, advertising or promotional 73 | purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each 74 | member of the public at large and to the detriment of Affirmer's heirs and 75 | successors, fully intending that such Waiver shall not be subject to 76 | revocation, rescission, cancellation, termination, or any other legal or 77 | equitable action to disrupt the quiet enjoyment of the Work by the public 78 | as contemplated by Affirmer's express Statement of Purpose. 79 | 80 | 3. Public License Fallback. Should any part of the Waiver for any reason 81 | be judged legally invalid or ineffective under applicable law, then the 82 | Waiver shall be preserved to the maximum extent permitted taking into 83 | account Affirmer's express Statement of Purpose. In addition, to the 84 | extent the Waiver is so judged Affirmer hereby grants to each affected 85 | person a royalty-free, non transferable, non sublicensable, non exclusive, 86 | irrevocable and unconditional license to exercise Affirmer's Copyright and 87 | Related Rights in the Work (i) in all territories worldwide, (ii) for the 88 | maximum duration provided by applicable law or treaty (including future 89 | time extensions), (iii) in any current or future medium and for any number 90 | of copies, and (iv) for any purpose whatsoever, including without 91 | limitation commercial, advertising or promotional purposes (the 92 | "License"). The License shall be deemed effective as of the date CC0 was 93 | applied by Affirmer to the Work. Should any part of the License for any 94 | reason be judged legally invalid or ineffective under applicable law, such 95 | partial invalidity or ineffectiveness shall not invalidate the remainder 96 | of the License, and in such case Affirmer hereby affirms that he or she 97 | will not (i) exercise any of his or her remaining Copyright and Related 98 | Rights in the Work or (ii) assert any associated claims and causes of 99 | action with respect to the Work, in either case contrary to Affirmer's 100 | express Statement of Purpose. 101 | 102 | 4. Limitations and Disclaimers. 103 | 104 | a. No trademark or patent rights held by Affirmer are waived, abandoned, 105 | surrendered, licensed or otherwise affected by this document. 106 | b. Affirmer offers the Work as-is and makes no representations or 107 | warranties of any kind concerning the Work, express, implied, 108 | statutory or otherwise, including without limitation warranties of 109 | title, merchantability, fitness for a particular purpose, non 110 | infringement, or the absence of latent or other defects, accuracy, or 111 | the present or absence of errors, whether or not discoverable, all to 112 | the greatest extent permissible under applicable law. 113 | c. Affirmer disclaims responsibility for clearing rights of other persons 114 | that may apply to the Work or any use thereof, including without 115 | limitation any person's Copyright and Related Rights in the Work. 116 | Further, Affirmer disclaims responsibility for obtaining any necessary 117 | consents, permissions or other rights required for any use of the 118 | Work. 119 | d. Affirmer understands and acknowledges that Creative Commons is not a 120 | party to this document and has no duty or obligation with respect to 121 | this CC0 or use of the Work. 122 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Hello Triangle with WebGL and Rust 2 | 3 | This is a minimal example that demonstrates how to render a triangle with WebAssembly, WebGL, Rust, and zero dependencies. 4 | 5 | To build the project perform the following steps: 6 | 7 | 1. Install Rust. 8 | 2. Install the `wasm32-unknown-unknown` target: `rustup target add wasm32-unknown-unknown` 9 | 3. Build the directory: `cargo build --target wasm32-unknown-unknown` 10 | 4. Run a local server to host the project directory. `devserver` is the easiest to setup: 11 | * First run `cargo install devserver` 12 | * Then simply run `devserver`. 13 | 5. Navigate to `localhost:8080` and view the triangle! 14 | 15 | The `.wasm` file produced is around 1.5mb. Which is kinda big! 16 | 17 | 18 | ## How to create a smaller .wasm file 19 | 20 | If you'd like to make a smaller .wasm file you need to instruct the compiler to remove all the extra debugging information it adds. Unfortunately you can't do this with stable Rust right now, but nightly Rust has a flag we can use. 21 | 22 | To install nightly Rust with WebAssembly support follow the following steps: 23 | 24 | 1. Install nightly Rust: `rustup install nightly` 25 | 2. Make it your default with `rustup default nightly` 26 | 3. Install WebAssembly support for nightly `rustup target add wasm32-unknown-unknown` 27 | 28 | Now you can run a build a *release* build with all compiler information stripped out: 29 | 30 | `cargo rustc --target wasm32-unknown-unknown --release -- -Z strip=symbols` 31 | 32 | You must change this line in `index.html` to `fetch('target/wasm32-unknown-unknown/release/hello_triangle_wasm_rust.wasm')` to make sure it points to the release folder. 33 | 34 | This new stripped .wasm file is 16kb instead of 1.6mb. 1/100th the size! 35 | -------------------------------------------------------------------------------- /index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 111 | 112 | 113 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | use std::ffi::c_void; 2 | 3 | // This is called when the Javascript initializes 4 | 5 | #[no_mangle] 6 | pub extern "C" fn start() { 7 | unsafe { 8 | imported::setup_canvas(); 9 | 10 | // Create the vertex buffer 11 | let vertex_buffer = imported::create_buffer(); 12 | imported::bind_buffer(GLEnum::ArrayBuffer, vertex_buffer); 13 | buffer_data_f32( 14 | GLEnum::ArrayBuffer, 15 | &[-0.5, 0.5, 0.0, -0.5, -0.5, 0.0, 0.5, -0.5, 0.0], 16 | GLEnum::StaticDraw, 17 | ); 18 | 19 | // Crate the index buffer 20 | let index_buffer = imported::create_buffer(); 21 | imported::bind_buffer(GLEnum::ElementArrayBuffer, index_buffer); 22 | 23 | // There is a WebGL extension to use u32 indices, but here we'll just use u16. 24 | buffer_data_u16(GLEnum::ElementArrayBuffer, &[0, 1, 2], GLEnum::StaticDraw); 25 | 26 | // Create the vertex shader 27 | let vertex_shader = imported::create_shader(GLEnum::VertexShader); 28 | shader_source( 29 | vertex_shader, 30 | r#" 31 | attribute vec3 vertex_position; 32 | 33 | void main(void) { 34 | gl_Position = vec4(vertex_position, 1.0); 35 | } 36 | "#, 37 | ); 38 | imported::compile_shader(vertex_shader); 39 | 40 | // Create the fragment shader 41 | let fragment_shader = imported::create_shader(GLEnum::FragmentShader); 42 | shader_source( 43 | fragment_shader, 44 | r#"void main() { 45 | gl_FragColor = vec4(1.0, 0.5, 0.313, 1.0); 46 | } 47 | "#, 48 | ); 49 | imported::compile_shader(fragment_shader); 50 | 51 | // Create the shader program 52 | let shader_program = imported::create_program(); 53 | imported::attach_shader(shader_program, vertex_shader); 54 | imported::attach_shader(shader_program, fragment_shader); 55 | imported::link_program(shader_program); 56 | imported::use_program(shader_program); 57 | 58 | // Get the location of the vertex_position attribute. 59 | // This is needed to later bind the data to it. 60 | let attrib_location = get_attrib_location(shader_program, "vertex_position").unwrap(); 61 | 62 | // Enable the attribute location. 63 | // This only needs to be done once per program, it's really just boilerplate. 64 | imported::enable_vertex_attrib_array(attrib_location); 65 | 66 | // Bind the vertex buffer. It's already bound, but in a more regular draw loop 67 | // it would not be. 68 | imported::bind_buffer(GLEnum::ArrayBuffer, vertex_buffer); 69 | 70 | // Now bind the vertex attributed to the correct buffer. 71 | imported::vertex_attrib_pointer(attrib_location as u32, 3, GLEnum::Float, false, 0, 0); 72 | 73 | // Bind the index buffer as well. 74 | imported::bind_buffer(GLEnum::ElementArrayBuffer, index_buffer); 75 | 76 | imported::clear_color(0.3765, 0.3137, 0.8627, 1.0); 77 | imported::clear(GLEnum::ColorBufferBit); 78 | imported::draw_elements(GLEnum::Triangles, 3, GLEnum::UnsignedShort, 0); 79 | } 80 | } 81 | 82 | // A few of the external functions we'll wrap so that we can use them in a more Rusty way. 83 | 84 | pub fn shader_source(shader: JSObject, source: &str) { 85 | unsafe { imported::shader_source(shader, source as *const str as *const c_void, source.len()) } 86 | } 87 | 88 | pub fn get_attrib_location(program: JSObject, name: &str) -> Option { 89 | unsafe { 90 | // Returns -1 if attribute does not exist, to be more Rusty we'll return None instead. 91 | // A GLUint is returned instead because all APIs that consume this value expect a GLUint. 92 | // getAttribLocation only returns a signed value to use the -1 to indicate if the location 93 | // does not exist. 94 | let result = 95 | imported::get_attrib_location(program, name as *const str as *const c_void, name.len()); 96 | if result == -1 { 97 | None 98 | } else { 99 | Some(result as u32) 100 | } 101 | } 102 | } 103 | 104 | pub fn bind_buffer(target: GLEnum, gl_object: Option) { 105 | unsafe { imported::bind_buffer(target, gl_object.unwrap_or(JSObject::null())) } 106 | } 107 | 108 | pub fn buffer_data_f32(target: GLEnum, data: &[f32], usage: GLEnum) { 109 | unsafe { 110 | imported::buffer_data_f32( 111 | target, 112 | data as *const [f32] as *const c_void, 113 | data.len(), 114 | usage, 115 | ) 116 | } 117 | } 118 | 119 | pub fn buffer_data_u16(target: GLEnum, data: &[u16], usage: GLEnum) { 120 | unsafe { 121 | imported::buffer_data_u16( 122 | target, 123 | data as *const [u16] as *const c_void, 124 | data.len(), 125 | usage, 126 | ) 127 | } 128 | } 129 | 130 | // The raw external bindings to Javascript 131 | mod imported { 132 | use super::*; 133 | 134 | extern "C" { 135 | pub fn setup_canvas(); 136 | // pub fn create_shader(source: *const c_void, source_length: usize); 137 | pub fn create_buffer() -> JSObject; 138 | pub fn bind_buffer(target: GLEnum, gl_object: JSObject); 139 | pub fn buffer_data_f32( 140 | target: GLEnum, 141 | data: *const c_void, 142 | data_length: usize, 143 | usage: GLEnum, 144 | ); 145 | 146 | pub fn buffer_data_u16( 147 | target: GLEnum, 148 | data: *const c_void, 149 | data_length: usize, 150 | usage: GLEnum, 151 | ); 152 | 153 | pub fn create_shader(shader_type: GLEnum) -> JSObject; 154 | pub fn shader_source(shader: JSObject, source: *const c_void, source_length: usize); 155 | pub fn compile_shader(shader: JSObject); 156 | pub fn create_program() -> JSObject; 157 | pub fn attach_shader(program: JSObject, shader: JSObject); 158 | pub fn link_program(program: JSObject); 159 | pub fn use_program(program: JSObject); 160 | pub fn get_attrib_location( 161 | program: JSObject, 162 | name: *const c_void, 163 | name_length: usize, 164 | ) -> GLint; 165 | pub fn vertex_attrib_pointer( 166 | index: GLUint, 167 | size: GLint, 168 | _type: GLEnum, 169 | normalized: bool, 170 | stride: GLsizei, 171 | pointer: GLintptr, 172 | ); 173 | pub fn enable_vertex_attrib_array(index: GLUint); 174 | pub fn clear_color(r: f32, g: f32, b: f32, a: f32); 175 | pub fn clear(mask: GLEnum); 176 | pub fn draw_elements(mode: GLEnum, count: GLsizei, _type: GLEnum, offset: GLintptr); 177 | } 178 | } 179 | 180 | // What follows are types defined to help communicate with Javascript code. 181 | 182 | #[derive(Clone, Copy)] 183 | #[repr(C)] 184 | pub struct JSObject(u32); 185 | 186 | impl JSObject { 187 | pub const fn null() -> Self { 188 | JSObject(0) 189 | } 190 | } 191 | 192 | // Sourced from here: https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API/Constants 193 | #[repr(u32)] 194 | pub enum GLEnum { 195 | Triangles = 0x0004, 196 | ArrayBuffer = 0x8892, 197 | ElementArrayBuffer = 0x8893, 198 | VertexShader = 0x8B31, 199 | FragmentShader = 0x8B30, 200 | Byte = 0x1400, 201 | UnsignedByte = 0x1401, 202 | Short = 0x1402, 203 | UnsignedShort = 0x1403, 204 | Int = 0x1404, 205 | UnsignedInt = 0x1405, 206 | Float = 0x1406, 207 | StaticDraw = 0x88E4, 208 | DynamicDraw = 0x88E8, 209 | ColorBufferBit = 0x00004000, 210 | } 211 | 212 | // Define some types to make it easier to port directly from the spec. 213 | pub type GLUint = u32; 214 | pub type GLint = i32; 215 | pub type GLsizei = i32; 216 | 217 | // GLintptr should be an i64, but Wasm can't pass those so for now just use an i32. 218 | pub type GLintptr = i32; 219 | --------------------------------------------------------------------------------