| 1 | //! Browser entry point: evaluates a Fusion `.comp` with the native engine on WebGPU and presents |
| 2 | //! the chosen node to a `<canvas>`. All UI lives in `index.html`. |
| 3 | #![cfg(target_arch = "wasm32")] |
| 4 | |
| 5 | use engine::media::MediaCache; |
| 6 | use engine::{DisplaySettings, Engine}; |
| 7 | use model::{Comp, NodeId}; |
| 8 | use serde_json::json; |
| 9 | use std::collections::HashSet; |
| 10 | use std::sync::{Arc, Mutex}; |
| 11 | use wasm_bindgen::prelude::*; |
| 12 | |
| 13 | const DEMO_COMP: &str = include_str!("../demo.comp"); |
| 14 | |
| 15 | struct Viewer { |
| 16 | texture: wgpu::Texture, |
| 17 | bind_group: wgpu::BindGroup, |
| 18 | } |
| 19 | |
| 20 | #[wasm_bindgen] |
| 21 | pub struct Fission { |
| 22 | engine: Engine, |
| 23 | surface: wgpu::Surface<'static>, |
| 24 | config: wgpu::SurfaceConfiguration, |
| 25 | /// The latest GPU error the device raised outside any error scope, until [`Self::gpu_error`] reads it. |
| 26 | gpu_error: Arc<Mutex<Option<String>>>, |
| 27 | present: wgpu::RenderPipeline, |
| 28 | sampler: wgpu::Sampler, |
| 29 | viewer: Option<Viewer>, |
| 30 | comp: Option<Comp>, |
| 31 | target: Option<NodeId>, |
| 32 | unsupported: Vec<String>, |
| 33 | } |
| 34 | |
| 35 | fn js_err(e: impl std::fmt::Display) -> JsError { |
| 36 | JsError::new(&e.to_string()) |
| 37 | } |
| 38 | |
| 39 | #[wasm_bindgen] |
| 40 | impl Fission { |
| 41 | /// Fails with a readable message when the browser has no WebGPU adapter. |
| 42 | pub async fn create(canvas: web_sys::HtmlCanvasElement) -> Result<Fission, JsError> { |
| 43 | console_error_panic_hook::set_once(); |
| 44 | let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle()); |
| 45 | let surface = instance.create_surface(wgpu::SurfaceTarget::Canvas(canvas)).map_err(js_err)?; |
| 46 | let adapter = instance |
| 47 | .request_adapter(&wgpu::RequestAdapterOptions { |
| 48 | compatible_surface: Some(&surface), |
| 49 | ..Default::default() |
| 50 | }) |
| 51 | .await |
| 52 | .map_err(|e| JsError::new(&format!("No WebGPU adapter: {e}")))?; |
| 53 | let mut features = wgpu::Features::empty(); |
| 54 | if adapter.features().contains(wgpu::Features::FLOAT32_FILTERABLE) { |
| 55 | features |= wgpu::Features::FLOAT32_FILTERABLE; |
| 56 | } |
| 57 | let (device, queue) = adapter |
| 58 | .request_device(&wgpu::DeviceDescriptor { |
| 59 | required_features: features, |
| 60 | required_limits: adapter.limits(), |
| 61 | ..Default::default() |
| 62 | }) |
| 63 | .await |
| 64 | .map_err(js_err)?; |
| 65 | |
| 66 | let gpu_error = Arc::new(Mutex::new(None)); |
| 67 | let slot = Arc::clone(&gpu_error); |
| 68 | device.on_uncaptured_error(Arc::new(move |e: wgpu::Error| { |
| 69 | console_error(&format!("GPU error: {e}")); |
| 70 | let mut guard = slot.lock().unwrap(); |
| 71 | if guard.is_none() { |
| 72 | *guard = Some(e.to_string()); |
| 73 | } |
| 74 | })); |
| 75 | let slot = Arc::clone(&gpu_error); |
| 76 | device.set_device_lost_callback(move |reason, message| { |
| 77 | console_error(&format!("GPU device lost ({reason:?}): {message}")); |
| 78 | *slot.lock().unwrap() = Some(format!("The GPU device was lost ({reason:?}): {message}")); |
| 79 | }); |
| 80 | |
| 81 | let caps = surface.get_capabilities(&adapter); |
| 82 | let surface_format = caps.formats.iter().copied().find(|f| !f.is_srgb()).unwrap_or(wgpu::TextureFormat::Bgra8Unorm); |
| 83 | let config = wgpu::SurfaceConfiguration { |
| 84 | usage: wgpu::TextureUsages::RENDER_ATTACHMENT, |
| 85 | format: surface_format, |
| 86 | color_space: wgpu::SurfaceColorSpace::Auto, |
| 87 | width: 1, |
| 88 | height: 1, |
| 89 | present_mode: wgpu::PresentMode::AutoVsync, |
| 90 | desired_maximum_frame_latency: 2, |
| 91 | alpha_mode: caps.alpha_modes.first().copied().unwrap_or(wgpu::CompositeAlphaMode::Auto), |
| 92 | view_formats: vec![], |
| 93 | }; |
| 94 | let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { |
| 95 | label: Some("present"), |
| 96 | source: wgpu::ShaderSource::Wgsl(include_str!("present.wgsl").into()), |
| 97 | }); |
| 98 | let present = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { |
| 99 | label: Some("present"), |
| 100 | layout: None, |
| 101 | vertex: wgpu::VertexState { |
| 102 | module: &shader, |
| 103 | entry_point: Some("vertex"), |
| 104 | compilation_options: Default::default(), |
| 105 | buffers: &[], |
| 106 | }, |
| 107 | fragment: Some(wgpu::FragmentState { |
| 108 | module: &shader, |
| 109 | entry_point: Some("fragment"), |
| 110 | compilation_options: Default::default(), |
| 111 | targets: &[Some(config.format.into())], |
| 112 | }), |
| 113 | primitive: Default::default(), |
| 114 | depth_stencil: None, |
| 115 | multisample: Default::default(), |
| 116 | multiview_mask: None, |
| 117 | cache: None, |
| 118 | }); |
| 119 | let sampler = device.create_sampler(&wgpu::SamplerDescriptor { |
| 120 | mag_filter: wgpu::FilterMode::Linear, |
| 121 | min_filter: wgpu::FilterMode::Linear, |
| 122 | ..Default::default() |
| 123 | }); |
| 124 | |
| 125 | Ok(Fission { |
| 126 | engine: Engine::new(device, queue), |
| 127 | surface, |
| 128 | config, |
| 129 | gpu_error, |
| 130 | present, |
| 131 | sampler, |
| 132 | viewer: None, |
| 133 | comp: None, |
| 134 | target: None, |
| 135 | unsupported: Vec::new(), |
| 136 | }) |
| 137 | } |
| 138 | |
| 139 | pub fn demo_comp() -> String { |
| 140 | DEMO_COMP.to_owned() |
| 141 | } |
| 142 | |
| 143 | /// Registers a project file (a dropped folder's relative path) that `Loader` clips resolve against. |
| 144 | /// `false` when the files held would pass the memory cap. |
| 145 | pub fn add_file(&mut self, path: &str, bytes: &[u8]) -> bool { |
| 146 | let added = MediaCache::insert_virtual_bytes(path, bytes); |
| 147 | self.engine.bust_all_caches(); |
| 148 | added |
| 149 | } |
| 150 | |
| 151 | /// Registers a dropped `.ttf`/`.otf`/`.ttc` font for `TextPlus` / `Text3D` rendering on wasm32. |
| 152 | pub fn add_font(&mut self, bytes: &[u8]) { |
| 153 | engine::text_engine::register_font_bytes(bytes.to_vec()); |
| 154 | self.engine.bust_all_caches(); |
| 155 | } |
| 156 | |
| 157 | pub fn clear_files(&mut self) { |
| 158 | MediaCache::clear_virtual_bytes(); |
| 159 | self.engine.bust_all_caches(); |
| 160 | } |
| 161 | |
| 162 | /// Parses `text`, selects its default output and returns [`Self::describe`]. |
| 163 | pub fn load_comp(&mut self, text: &str, name: &str) -> Result<String, JsError> { |
| 164 | let mut comp = Comp::from_fusion_str(text).map_err(js_err)?; |
| 165 | comp.name = name.to_owned(); |
| 166 | self.target = comp.default_output_node(); |
| 167 | self.comp = Some(comp); |
| 168 | self.engine.bust_all_caches(); |
| 169 | self.describe() |
| 170 | } |
| 171 | |
| 172 | /// JSON: comp format, frame range, node graph and whether each `Loader` clip resolves. |
| 173 | pub fn describe(&self) -> Result<String, JsError> { |
| 174 | let comp = self.comp.as_ref().ok_or_else(|| JsError::new("no comp loaded"))?; |
| 175 | let names: HashSet<String> = comp.node_by_name.keys().cloned().collect(); |
| 176 | let nodes: Vec<_> = comp |
| 177 | .nodes |
| 178 | .iter() |
| 179 | .filter(|n| !n.internal) |
| 180 | .map(|n| { |
| 181 | let from: Vec<_> = n.image_connections(&names).into_iter().map(|(port, src, _)| json!([port, src])).collect(); |
| 182 | let clips: Vec<_> = n |
| 183 | .clips |
| 184 | .iter() |
| 185 | .map(|c| json!({ "file": c.filename, "found": engine::media::resolve_clip_path(c, c.global_start).is_some() })) |
| 186 | .collect(); |
| 187 | json!({ "id": n.id.0, "name": n.name, "kind": n.kind, "pos": n.pos, "bypassed": n.bypassed, "from": from, "clips": clips }) |
| 188 | }) |
| 189 | .collect(); |
| 190 | Ok(json!({ |
| 191 | "name": comp.name, |
| 192 | "width": comp.width, |
| 193 | "height": comp.height, |
| 194 | "fps": comp.fps, |
| 195 | "range": comp.render_range, |
| 196 | "target": self.target.map(|t| t.0), |
| 197 | "nodes": nodes, |
| 198 | }) |
| 199 | .to_string()) |
| 200 | } |
| 201 | |
| 202 | pub fn set_node(&mut self, id: usize) -> Result<(), JsError> { |
| 203 | let comp = self.comp.as_ref().ok_or_else(|| JsError::new("no comp loaded"))?; |
| 204 | if id >= comp.nodes.len() { |
| 205 | return Err(JsError::new("no such node")); |
| 206 | } |
| 207 | self.target = Some(NodeId(id)); |
| 208 | Ok(()) |
| 209 | } |
| 210 | |
| 211 | /// Evaluates the selected node at `frame` into the canvas and returns the CPU-side milliseconds, |
| 212 | /// or `undefined` when the surface could not take the frame and the caller should retry. |
| 213 | pub fn render(&mut self, frame: f64) -> Result<Option<f64>, JsError> { |
| 214 | let (comp, target) = self.comp.as_ref().zip(self.target).ok_or_else(|| JsError::new("no comp loaded"))?; |
| 215 | // Cached by the engine, so `render_into_viewer` below reuses it; the size can change with media or time. |
| 216 | let (tex, _) = self.engine.evaluate(comp, target, frame); |
| 217 | let size = fit_texture(tex.canvas_size, self.engine.device().limits().max_texture_dimension_2d); |
| 218 | if self.viewer.as_ref().is_none_or(|v| [v.texture.width(), v.texture.height()] != size) { |
| 219 | [self.config.width, self.config.height] = size; |
| 220 | self.surface.configure(self.engine.device(), &self.config); |
| 221 | self.viewer = Some(make_viewer(self.engine.device(), &self.present, &self.sampler, size)); |
| 222 | } |
| 223 | let viewer = self.viewer.as_ref().expect("viewer sized above"); |
| 224 | let stats = self.engine.render_into_viewer(comp, target, frame, &viewer.texture, DisplaySettings::default()); |
| 225 | self.unsupported = stats.unsupported_nodes; |
| 226 | |
| 227 | let (frame_tex, suboptimal) = match self.surface.get_current_texture() { |
| 228 | wgpu::CurrentSurfaceTexture::Success(t) => (t, false), |
| 229 | wgpu::CurrentSurfaceTexture::Suboptimal(t) => (t, true), |
| 230 | wgpu::CurrentSurfaceTexture::Outdated | wgpu::CurrentSurfaceTexture::Lost => { |
| 231 | self.surface.configure(self.engine.device(), &self.config); |
| 232 | return Ok(None); |
| 233 | } |
| 234 | wgpu::CurrentSurfaceTexture::Timeout | wgpu::CurrentSurfaceTexture::Occluded | wgpu::CurrentSurfaceTexture::Validation => { |
| 235 | return Ok(None); |
| 236 | } |
| 237 | }; |
| 238 | let device = self.engine.device(); |
| 239 | let mut encoder = device.create_command_encoder(&Default::default()); |
| 240 | let view = frame_tex.texture.create_view(&Default::default()); |
| 241 | { |
| 242 | let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { |
| 243 | color_attachments: &[Some(wgpu::RenderPassColorAttachment { |
| 244 | view: &view, |
| 245 | depth_slice: None, |
| 246 | resolve_target: None, |
| 247 | ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::BLACK), store: wgpu::StoreOp::Store }, |
| 248 | })], |
| 249 | ..Default::default() |
| 250 | }); |
| 251 | pass.set_pipeline(&self.present); |
| 252 | pass.set_bind_group(0, &viewer.bind_group, &[]); |
| 253 | pass.draw(0..3, 0..1); |
| 254 | } |
| 255 | self.engine.queue().submit(Some(encoder.finish())); |
| 256 | self.engine.queue().present(frame_tex); |
| 257 | if suboptimal { |
| 258 | self.surface.configure(self.engine.device(), &self.config); |
| 259 | } |
| 260 | Ok(Some(stats.eval_ms)) |
| 261 | } |
| 262 | |
| 263 | /// Takes the latest GPU error or device loss, which would otherwise only show as a black canvas. |
| 264 | pub fn gpu_error(&self) -> Option<String> { |
| 265 | self.gpu_error.lock().unwrap().take() |
| 266 | } |
| 267 | |
| 268 | /// Kinds the last rendered frame could not evaluate. |
| 269 | pub fn unsupported(&self) -> Vec<String> { |
| 270 | self.unsupported.clone() |
| 271 | } |
| 272 | } |
| 273 | |
| 274 | #[wasm_bindgen] |
| 275 | extern "C" { |
| 276 | #[wasm_bindgen(js_namespace = console, js_name = error)] |
| 277 | fn console_error(message: &str); |
| 278 | } |
| 279 | |
| 280 | /// `size` shrunk, keeping its aspect, until both sides fit `max`; never below one pixel. |
| 281 | fn fit_texture([width, height]: [u32; 2], max: u32) -> [u32; 2] { |
| 282 | let scale = (f64::from(max) / f64::from(width.max(height).max(1))).min(1.0); |
| 283 | [width, height].map(|side| ((f64::from(side) * scale).round() as u32).clamp(1, max.max(1))) |
| 284 | } |
| 285 | |
| 286 | /// The intermediate viewer texture, sized to the (already fitted) output. |
| 287 | fn make_viewer( |
| 288 | device: &wgpu::Device, |
| 289 | present: &wgpu::RenderPipeline, |
| 290 | sampler: &wgpu::Sampler, |
| 291 | [width, height]: [u32; 2], |
| 292 | ) -> Viewer { |
| 293 | let texture = device.create_texture(&wgpu::TextureDescriptor { |
| 294 | label: Some("viewer"), |
| 295 | size: wgpu::Extent3d { width, height, depth_or_array_layers: 1 }, |
| 296 | mip_level_count: 1, |
| 297 | sample_count: 1, |
| 298 | dimension: wgpu::TextureDimension::D2, |
| 299 | format: wgpu::TextureFormat::Rgba8Unorm, |
| 300 | usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::STORAGE_BINDING, |
| 301 | view_formats: &[], |
| 302 | }); |
| 303 | let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { |
| 304 | label: Some("present"), |
| 305 | layout: &present.get_bind_group_layout(0), |
| 306 | entries: &[ |
| 307 | wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(&texture.create_view(&Default::default())) }, |
| 308 | wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::Sampler(sampler) }, |
| 309 | ], |
| 310 | }); |
| 311 | Viewer { texture, bind_group } |
| 312 | } |