use bloom_shared::engine::EngineState; use bloom_shared::renderer::Renderer; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::OnceLock; use wasm_bindgen::prelude::*; static mut ENGINE: OnceLock = OnceLock::new(); static mut LAST_PROJECT: (f64, f64) = (0.0, 0.0); static mut LAST_PICK: Option = None; // Guards against double wgpu init when bloom_init_window is called twice // (once by the JS orchestrator before Perry boots, and once by Perry's main). static INIT_STARTED: AtomicBool = AtomicBool::new(false); fn engine() -> &'static mut EngineState { unsafe { ENGINE.get_mut().expect("Engine not initialized") } } /// Log to the browser console. #[wasm_bindgen] extern "C" { #[wasm_bindgen(js_namespace = console, js_name = log)] pub(crate) fn console_log(s: &str); #[wasm_bindgen(js_namespace = console, js_name = warn)] pub(crate) fn console_warn(s: &str); } /// Display handle for the wgpu-core (WebGL2) path. /// /// When wgpu falls back to WebGL2 it goes through wgpu-core, whose /// `create_surface` passes `raw_display_handle: None` for a canvas target and /// then errors with `MissingDisplayHandle` unless the *instance* carries one /// (wgpu-core 29 instance.rs:254). The WebGPU backend never looks at it. On the /// web a display handle holds nothing, so this is pure ceremony — but without it /// the WebGL2 fallback can't create a surface at all. #[derive(Debug)] struct WebDisplay; impl wgpu::rwh::HasDisplayHandle for WebDisplay { fn display_handle(&self) -> Result, wgpu::rwh::HandleError> { let raw = wgpu::rwh::RawDisplayHandle::Web(wgpu::rwh::WebDisplayHandle::new()); // SAFETY: a web display handle carries no pointer and cannot dangle. Ok(unsafe { wgpu::rwh::DisplayHandle::borrow_raw(raw) }) } } // ============================================================ // Window // ============================================================ /// Returns 1.0 once `ENGINE` has been populated by the async wgpu setup, 0.0 /// before then. Non-panicking — safe to call at any time. Used by the JS /// orchestrator to gate Perry boot until the engine is actually usable. #[wasm_bindgen] pub fn bloom_is_initialized() -> f64 { unsafe { if ENGINE.get().is_some() { 1.0 } else { 0.0 } } } /// Host-surface attach (PerryTS/perry#5519). Not applicable on web: the /// engine builds its surface from the `bloom-canvas` DOM element in /// `bloom_init_window`, and a wasm module can't be handed a native view /// pointer. Present for FFI-surface uniformity; always returns 0.0 so web /// hosts use the canvas-based `bloom_init_window` path instead. #[wasm_bindgen] pub fn bloom_attach_native(_handle: f64, _width: f64, _height: f64) -> f64 { 0.0 } #[wasm_bindgen] pub fn bloom_init_window(width: f64, height: f64, _title: f64, fullscreen: f64) { // Set up panic hook for better error messages in the browser console console_error_panic_hook::set_once(); // Idempotent: once an init is in flight (or done), later calls are no-ops. // Perry's main() typically calls initWindow after the JS orchestrator has // already kicked off wgpu setup — the second call must not start a new one. if INIT_STARTED.swap(true, Ordering::SeqCst) { return; } let log_w = width as u32; let log_h = height as u32; let _fullscreen = fullscreen != 0.0; wasm_bindgen_futures::spawn_local(async move { let window = web_sys::window().expect("no global window"); let document = window.document().expect("no document"); let canvas = document .get_element_by_id("bloom-canvas") .expect("no element with id 'bloom-canvas'") .dyn_into::() .expect("element is not a canvas"); // HiDPI: size the canvas *backing store* (set_width/set_height, // i.e. the WebGPU surface) to logical × devicePixelRatio so a // 4K Retina display actually renders at 4K. CSS layout dimensions // stay in logical pixels — index.html keeps `width: 100%` on // the canvas — so the document layout is unchanged. Clamp to // [1, 3] because higher dprs (some phones report 4) are wasted // shading work and can crash low-end mobile GPUs. let dpr = window.device_pixel_ratio().max(1.0).min(3.0); let phys_w = ((log_w as f64) * dpr).round() as u32; let phys_h = ((log_h as f64) * dpr).round() as u32; canvas.set_width(phys_w); canvas.set_height(phys_h); let instance = wgpu::Instance::new(wgpu::InstanceDescriptor { backends: wgpu::Backends::BROWSER_WEBGPU | wgpu::Backends::GL, ..wgpu::InstanceDescriptor::new_with_display_handle(Box::new(WebDisplay)) }); let surface = instance .create_surface(wgpu::SurfaceTarget::Canvas(canvas)) .expect("Failed to create surface from canvas"); let adapter = instance .request_adapter(&wgpu::RequestAdapterOptions { compatible_surface: Some(&surface), power_preference: wgpu::PowerPreference::HighPerformance, ..Default::default() }) .await .expect("No WebGPU/WebGL adapter found"); // BC feature -> cooked BC7 textures upload compressed (else CPU-decode). let required_features = adapter.features() & wgpu::Features::TEXTURE_COMPRESSION_BC; // On GL, `Limits::default()` is unsatisfiable: WebGL2 has no compute, so // `max_compute_workgroups_per_dimension` is 0 against a default request of // 65535 and device creation fails outright. Ask that backend for exactly what // it reports instead. // // On WebGPU, raise the per-stage resource limits to whatever the adapter // offers (EN-063): the material ABI's fragment stage samples 19 textures // once the wasm scene-inputs fold-in lands in group 0, and the WebGPU // DEFAULT of 16 rejects the pipeline layout — while desktop adapters // advertise 48+. requiredLimits is the sanctioned way to claim them // (unlike maxBindGroups, which is a hard cap). Everything else keeps the // defaults so we notice, rather than silently depend on, exotic limits. let required_limits = if adapter.get_info().backend == wgpu::Backend::Gl { adapter.limits() } else { let a = adapter.limits(); let mut l = wgpu::Limits::default(); l.max_sampled_textures_per_shader_stage = a .max_sampled_textures_per_shader_stage .max(l.max_sampled_textures_per_shader_stage); l.max_samplers_per_shader_stage = a .max_samplers_per_shader_stage .max(l.max_samplers_per_shader_stage); l.max_texture_array_layers = a.max_texture_array_layers.max(l.max_texture_array_layers); l }; let (device, queue) = adapter .request_device(&wgpu::DeviceDescriptor { label: Some("bloom_device"), required_features, required_limits, ..Default::default() }) .await .expect("Failed to create device"); let surface_caps = surface.get_capabilities(&adapter); let format = surface_caps .formats .iter() .find(|f| f.is_srgb()) .copied() .unwrap_or(surface_caps.formats[0]); // COPY_SRC (readback of the swapchain image) is unsupported on a WebGL2 // surface — asking for it there fails Surface::configure validation — so keep // it only where the surface advertises it. let usage = (wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC) & surface_caps.usages; let surface_config = wgpu::SurfaceConfiguration { usage, format, width: phys_w, height: phys_h, present_mode: wgpu::PresentMode::Fifo, alpha_mode: surface_caps.alpha_modes[0], view_formats: vec![], desired_maximum_frame_latency: 2, }; surface.configure(&device, &surface_config); let renderer = Renderer::new(device, queue, surface, surface_config, log_w, log_h); let engine_state = EngineState::new(renderer); unsafe { let _ = ENGINE.set(engine_state); } let info = adapter.get_info(); console_log(&format!( "Bloom engine initialized ({:?} on {})", info.backend, info.name )); }); } #[wasm_bindgen] pub fn bloom_close_window() { // TODO: Phase 3 — clean up resources if needed } /// Web-only resize hook. Called from index.html when a ResizeObserver /// or matchMedia(`(resolution: ...)`) signals the canvas's CSS box /// changed or devicePixelRatio shifted (e.g. browser zoom). The JS /// glue does the dpr math; we just receive both sizes and forward to /// the renderer. #[wasm_bindgen] pub fn bloom_resize(physical_w: f64, physical_h: f64, logical_w: f64, logical_h: f64) { let pw = (physical_w as u32).max(1); let ph = (physical_h as u32).max(1); let lw = (logical_w as u32).max(1); let lh = (logical_h as u32).max(1); unsafe { if let Some(eng) = ENGINE.get_mut() { eng.renderer.window_resized(pw, ph, lw, lh); } } } #[wasm_bindgen] pub fn bloom_window_should_close() -> f64 { // Web windows don't close the same way; always return false 0.0 } #[wasm_bindgen] pub fn bloom_toggle_fullscreen() { // Handled by JS glue — uses Fullscreen API on the canvas element } #[wasm_bindgen] pub fn bloom_set_window_title(_title: f64) { // TODO: Phase 3 — set document.title (need string conversion) } #[wasm_bindgen] pub fn bloom_set_window_icon(_path: f64) { // TODO: Phase 3 — set favicon (need string conversion + fetch) } // ============================================================ // Drawing // ============================================================ #[wasm_bindgen] pub fn bloom_begin_drawing() { // No event polling needed on web — events are injected from JS via bloom_inject_* engine().begin_frame(); } #[wasm_bindgen] pub fn bloom_end_drawing() { engine().end_frame(); } #[wasm_bindgen] pub fn bloom_clear_background(r: f64, g: f64, b: f64, a: f64) { engine().renderer.set_clear_color(r, g, b, a); } // ============================================================ // Timing // ============================================================ #[wasm_bindgen] pub fn bloom_set_target_fps(fps: f64) { engine().target_fps = fps; } #[wasm_bindgen] pub fn bloom_set_direct_2d_mode(on: f64) { engine().direct_2d_mode = on > 0.5; } #[wasm_bindgen] pub fn bloom_get_delta_time() -> f64 { engine().delta_time } #[wasm_bindgen] pub fn bloom_get_fps() -> f64 { engine().get_fps() } /// tvOS's Menu-leaves-the-app switch: nothing to do in a browser. #[wasm_bindgen] pub fn bloom_set_menu_button_exits(on: f64) -> f64 { bloom_shared::display::set_menu_exits(on != 0.0); 1.0 } /// Physical pixels per point: the page's devicePixelRatio is the browser's business here. #[wasm_bindgen] pub fn bloom_get_display_scale() -> f64 { bloom_shared::display::display_scale() } /// Safe-area insets: none reported on the web (CSS env(safe-area-inset-*) covers pages). #[wasm_bindgen] pub fn bloom_get_safe_area_inset(edge: f64) -> f64 { if edge >= 0.0 { bloom_shared::display::safe_area_inset(edge as usize) } else { 0.0 } } #[wasm_bindgen] pub fn bloom_get_screen_width() -> f64 { engine().screen_width() } #[wasm_bindgen] pub fn bloom_get_screen_height() -> f64 { engine().screen_height() } #[wasm_bindgen] pub fn bloom_get_time() -> f64 { engine().get_time() } // Input FFI (keyboard/mouse/gamepad/touch + JS-event injection) lives // in input_ffi.rs (2000-line file policy). mod audio_ffi; mod input_ffi; mod material_ffi; pub use input_ffi::*; // EN-063 — web FFI parity for full-3D games: mesh/instance/texture-array // scratch builders, staged-model bytes, env-HDR bytes, profiler text, // splat impulses, host stubs (parity_ffi) and ragdolls via the Jolt JS // bridge (ragdoll_ffi). #[cfg(feature = "models3d")] mod parity_ffi; #[cfg(feature = "models3d")] pub use parity_ffi::*; #[cfg(all(feature = "jolt", feature = "models3d"))] mod ragdoll_ffi; #[cfg(all(feature = "jolt", feature = "models3d"))] pub use ragdoll_ffi::*; // ============================================================ // 2D Drawing - Shapes // ============================================================ #[wasm_bindgen] pub fn bloom_draw_line( x1: f64, y1: f64, x2: f64, y2: f64, thickness: f64, r: f64, g: f64, b: f64, a: f64, ) { engine() .renderer .draw_line(x1, y1, x2, y2, thickness, r, g, b, a); } #[wasm_bindgen] pub fn bloom_draw_rect(x: f64, y: f64, w: f64, h: f64, r: f64, g: f64, b: f64, a: f64) { engine().renderer.draw_rect(x, y, w, h, r, g, b, a); } #[wasm_bindgen] pub fn bloom_draw_rect_lines( x: f64, y: f64, w: f64, h: f64, thickness: f64, r: f64, g: f64, b: f64, a: f64, ) { engine() .renderer .draw_rect_lines(x, y, w, h, thickness, r, g, b, a); } #[wasm_bindgen] pub fn bloom_draw_circle(cx: f64, cy: f64, radius: f64, r: f64, g: f64, b: f64, a: f64) { engine().renderer.draw_circle(cx, cy, radius, r, g, b, a); } #[wasm_bindgen] pub fn bloom_draw_circle_lines(cx: f64, cy: f64, radius: f64, r: f64, g: f64, b: f64, a: f64) { engine() .renderer .draw_circle_lines(cx, cy, radius, r, g, b, a); } #[wasm_bindgen] pub fn bloom_draw_triangle( x1: f64, y1: f64, x2: f64, y2: f64, x3: f64, y3: f64, r: f64, g: f64, b: f64, a: f64, ) { engine() .renderer .draw_triangle(x1, y1, x2, y2, x3, y3, r, g, b, a); } #[wasm_bindgen] pub fn bloom_draw_poly( cx: f64, cy: f64, sides: f64, radius: f64, rotation: f64, r: f64, g: f64, b: f64, a: f64, ) { engine() .renderer .draw_poly(cx, cy, sides, radius, rotation, r, g, b, a); } // ============================================================ // Camera 2D // ============================================================ #[wasm_bindgen] pub fn bloom_begin_mode_2d( offset_x: f64, offset_y: f64, target_x: f64, target_y: f64, rotation: f64, zoom: f64, ) { engine().renderer.begin_mode_2d( offset_x as f32, offset_y as f32, target_x as f32, target_y as f32, rotation as f32, zoom as f32, ); } #[wasm_bindgen] pub fn bloom_end_mode_2d() { engine().renderer.end_mode_2d(); } // ============================================================ // Camera 3D and 3D Drawing // ============================================================ #[wasm_bindgen] pub fn bloom_begin_mode_3d( pos_x: f64, pos_y: f64, pos_z: f64, target_x: f64, target_y: f64, target_z: f64, up_x: f64, up_y: f64, up_z: f64, fovy: f64, projection: f64, ) { engine().renderer.begin_mode_3d( pos_x as f32, pos_y as f32, pos_z as f32, target_x as f32, target_y as f32, target_z as f32, up_x as f32, up_y as f32, up_z as f32, fovy as f32, projection as f32, ); } #[wasm_bindgen] pub fn bloom_end_mode_3d() { engine().renderer.end_mode_3d(); } #[wasm_bindgen] pub fn bloom_draw_cube( x: f64, y: f64, z: f64, w: f64, h: f64, d: f64, r: f64, g: f64, b: f64, a: f64, ) { engine().renderer.draw_cube(x, y, z, w, h, d, r, g, b, a); } #[wasm_bindgen] pub fn bloom_draw_cube_wires( x: f64, y: f64, z: f64, w: f64, h: f64, d: f64, r: f64, g: f64, b: f64, a: f64, ) { engine() .renderer .draw_cube_wires(x, y, z, w, h, d, r, g, b, a); } #[wasm_bindgen] pub fn bloom_draw_sphere(cx: f64, cy: f64, cz: f64, radius: f64, r: f64, g: f64, b: f64, a: f64) { engine() .renderer .draw_sphere(cx, cy, cz, radius, r, g, b, a); } #[wasm_bindgen] pub fn bloom_draw_sphere_wires( cx: f64, cy: f64, cz: f64, radius: f64, r: f64, g: f64, b: f64, a: f64, ) { engine() .renderer .draw_sphere_wires(cx, cy, cz, radius, r, g, b, a); } #[wasm_bindgen] pub fn bloom_draw_cylinder( x: f64, y: f64, z: f64, radius_top: f64, radius_bottom: f64, height: f64, r: f64, g: f64, b: f64, a: f64, ) { engine() .renderer .draw_cylinder(x, y, z, radius_top, radius_bottom, height, r, g, b, a); } #[wasm_bindgen] pub fn bloom_draw_plane(cx: f64, cy: f64, cz: f64, w: f64, d: f64, r: f64, g: f64, b: f64, a: f64) { engine().renderer.draw_plane(cx, cy, cz, w, d, r, g, b, a); } #[wasm_bindgen] pub fn bloom_draw_grid(slices: f64, spacing: f64) { engine().renderer.draw_grid(slices as i32, spacing); } #[wasm_bindgen] pub fn bloom_draw_ray( origin_x: f64, origin_y: f64, origin_z: f64, dir_x: f64, dir_y: f64, dir_z: f64, r: f64, g: f64, b: f64, a: f64, ) { engine().renderer.draw_ray( origin_x, origin_y, origin_z, dir_x, dir_y, dir_z, r, g, b, a, ); } // ============================================================ // Text // ============================================================ // The original FFI functions accept f64 (NaN-boxed string handles from Perry WASM). // The JS glue intercepts these and calls the _str variants below with actual strings. #[wasm_bindgen] pub fn bloom_draw_text( _text: f64, _x: f64, _y: f64, _size: f64, _r: f64, _g: f64, _b: f64, _a: f64, ) { // No-op: JS glue calls bloom_draw_text_str instead } #[wasm_bindgen] pub fn bloom_draw_text_str(text: &str, x: f64, y: f64, size: f64, r: f64, g: f64, b: f64, a: f64) { let eng = engine(); let mut text_renderer = std::mem::replace( &mut eng.text, bloom_shared::text_renderer::TextRenderer::empty(), ); text_renderer.draw_text(&mut eng.renderer, text, x, y, size as u32, r, g, b, a); eng.text = text_renderer; } #[wasm_bindgen] pub fn bloom_measure_text(_text: f64, _size: f64) -> f64 { 0.0 } #[wasm_bindgen] pub fn bloom_measure_text_str(text: &str, size: f64) -> f64 { engine().text.measure_text(text, size as u32) } /// No system emoji renderer in the browser build: the page falls back. #[wasm_bindgen] pub fn bloom_render_emoji(_text: f64, _size: f64, _path: f64) -> f64 { 0.0 } #[wasm_bindgen] pub fn bloom_load_font(_path: f64, _size: f64) -> f64 { 0.0 } /// Load a font from raw bytes (fetched by JS glue via fetch()). #[wasm_bindgen] pub fn bloom_load_font_bytes(data: &[u8]) -> f64 { engine().text.load_font(data) as f64 } #[wasm_bindgen] pub fn bloom_unload_font(font_handle: f64) { engine().text.unload_font(font_handle as usize); } #[wasm_bindgen] pub fn bloom_draw_text_ex( _font_handle: f64, _text: f64, _x: f64, _y: f64, _size: f64, _spacing: f64, _r: f64, _g: f64, _b: f64, _a: f64, ) { // No-op: JS glue calls bloom_draw_text_ex_str instead } #[wasm_bindgen] pub fn bloom_draw_text_ex_str( font_handle: f64, text: &str, x: f64, y: f64, size: f64, spacing: f64, r: f64, g: f64, b: f64, a: f64, ) { let eng = engine(); let mut text_renderer = std::mem::replace( &mut eng.text, bloom_shared::text_renderer::TextRenderer::empty(), ); text_renderer.draw_text_ex( &mut eng.renderer, font_handle as usize, text, x, y, size as u32, spacing as f32, r, g, b, a, ); eng.text = text_renderer; } #[wasm_bindgen] pub fn bloom_measure_text_ex(_font_handle: f64, _text: f64, _size: f64, _spacing: f64) -> f64 { 0.0 } #[wasm_bindgen] pub fn bloom_measure_text_ex_str(font_handle: f64, text: &str, size: f64, spacing: f64) -> f64 { engine() .text .measure_text_ex(font_handle as usize, text, size as u32, spacing as f32) } // --- Texture loading from bytes (fetched by JS glue) --- /// Load a texture from raw image bytes (PNG/JPEG/etc.), fetched by JS glue via fetch(). #[wasm_bindgen] pub fn bloom_load_texture_bytes(data: &[u8]) -> f64 { let eng = engine(); let renderer_ptr = &mut eng.renderer as *mut bloom_shared::renderer::Renderer; eng.textures .load_texture(unsafe { &mut *renderer_ptr }, data) } // ============================================================ // Textures // ============================================================ #[wasm_bindgen] pub fn bloom_load_texture(_path: f64) -> f64 { // TODO: Phase 3 — need fetch() for texture file + string conversion 0.0 } #[wasm_bindgen] pub fn bloom_unload_texture(handle: f64) { let eng = engine(); let renderer_ptr = &mut eng.renderer as *mut Renderer; eng.textures .unload_texture(handle, unsafe { &mut *renderer_ptr }); } #[wasm_bindgen] pub fn bloom_draw_texture( handle: f64, x: f64, y: f64, tint_r: f64, tint_g: f64, tint_b: f64, tint_a: f64, ) { let eng = engine(); if let Some(tex) = eng.textures.get(handle) { let bind_group_idx = tex.bind_group_idx; eng.renderer .draw_texture(bind_group_idx, x, y, tint_r, tint_g, tint_b, tint_a); } } #[wasm_bindgen] pub fn bloom_draw_texture_pro( handle: f64, src_x: f64, src_y: f64, src_w: f64, src_h: f64, dst_x: f64, dst_y: f64, dst_w: f64, dst_h: f64, origin_x: f64, origin_y: f64, rotation: f64, tint_r: f64, tint_g: f64, tint_b: f64, tint_a: f64, ) { let eng = engine(); if let Some(tex) = eng.textures.get(handle) { let bind_group_idx = tex.bind_group_idx; eng.renderer.draw_texture_pro( bind_group_idx, src_x, src_y, src_w, src_h, dst_x, dst_y, dst_w, dst_h, origin_x, origin_y, rotation, tint_r, tint_g, tint_b, tint_a, ); } } #[wasm_bindgen] pub fn bloom_draw_texture_rec( handle: f64, src_x: f64, src_y: f64, src_w: f64, src_h: f64, dst_x: f64, dst_y: f64, tint_r: f64, tint_g: f64, tint_b: f64, tint_a: f64, ) { let eng = engine(); if let Some(tex) = eng.textures.get(handle) { let bind_group_idx = tex.bind_group_idx; eng.renderer.draw_texture_rec( bind_group_idx, src_x, src_y, src_w, src_h, dst_x, dst_y, tint_r, tint_g, tint_b, tint_a, ); } } #[wasm_bindgen] pub fn bloom_get_texture_width(handle: f64) -> f64 { engine() .textures .get(handle) .map(|t| t.width as f64) .unwrap_or(0.0) } #[wasm_bindgen] pub fn bloom_get_texture_height(handle: f64) -> f64 { engine() .textures .get(handle) .map(|t| t.height as f64) .unwrap_or(0.0) } #[wasm_bindgen] pub fn bloom_load_image(_path: f64) -> f64 { 0.0 } #[wasm_bindgen] pub fn bloom_load_image_bytes(data: &[u8]) -> f64 { engine().textures.load_image(data) } #[wasm_bindgen] pub fn bloom_image_resize(handle: f64, w: f64, h: f64) { engine().textures.image_resize(handle, w as u32, h as u32); } #[wasm_bindgen] pub fn bloom_image_crop(handle: f64, x: f64, y: f64, w: f64, h: f64) { engine() .textures .image_crop(handle, x as u32, y as u32, w as u32, h as u32); } #[wasm_bindgen] pub fn bloom_image_flip_h(handle: f64) { engine().textures.image_flip_h(handle); } #[wasm_bindgen] pub fn bloom_image_flip_v(handle: f64) { engine().textures.image_flip_v(handle); } #[wasm_bindgen] pub fn bloom_load_texture_from_image(handle: f64) -> f64 { let eng = engine(); let renderer_ptr = &mut eng.renderer as *mut Renderer; eng.textures .load_texture_from_image(handle, unsafe { &mut *renderer_ptr }) } #[wasm_bindgen] pub fn bloom_gen_texture_mipmaps(_handle: f64) { // Mipmap generation is handled by the GPU texture creation pipeline } #[wasm_bindgen] pub fn bloom_set_texture_filter(handle: f64, mode: f64) { let eng = engine(); if let Some(tex) = eng.textures.get(handle) { let bind_group_idx = tex.bind_group_idx; eng.renderer.set_texture_filter(bind_group_idx, mode > 0.5); } } // ============================================================ // Models // ============================================================ #[wasm_bindgen] pub fn bloom_load_model(_path: f64) -> f64 { 0.0 } // Virtual geometry needs the visibility-shading path, which the web // renderer does not start: every call reports that nothing was done. #[wasm_bindgen] pub fn bloom_request_virtual_geometry() -> f64 { 0.0 } #[wasm_bindgen] pub fn bloom_enable_virtual_geometry(_p0: f64) -> f64 { 0.0 } #[wasm_bindgen] pub fn bloom_model_attach_virtual_geometry(_p0: f64, _p1: f64) -> f64 { 0.0 } #[wasm_bindgen] #[allow(clippy::too_many_arguments)] pub fn bloom_draw_model_virtual_transform16( _p0: f64, _p1: f64, _p2: f64, _p3: f64, _p4: f64, _p5: f64, _p6: f64, _p7: f64, _p8: f64, _p9: f64, _p10: f64, _p11: f64, _p12: f64, _p13: f64, _p14: f64, _p15: f64, _p16: f64, _p17: f64, ) -> f64 { 0.0 } #[wasm_bindgen] pub fn bloom_set_virtual_geometry_error_pixels(_p0: f64) -> f64 { 0.0 } #[wasm_bindgen] pub fn bloom_virtual_geometry_stat(_p0: f64) -> f64 { 0.0 } #[wasm_bindgen] pub fn bloom_scene_attach_virtual_model(_p0: f64, _p1: f64, _p2: f64) -> f64 { 0.0 } #[wasm_bindgen] pub fn bloom_set_virtual_geometry_proxy_error(_p0: f64) -> f64 { 0.0 } #[wasm_bindgen] pub fn bloom_load_model_bytes(data: &[u8]) -> f64 { let eng = engine(); eng.models.load_model_with_textures(data, &mut eng.renderer) } #[wasm_bindgen] pub fn bloom_draw_model( handle: f64, x: f64, y: f64, z: f64, scale: f64, r: f64, g: f64, b: f64, a: f64, ) { let eng = engine(); if let Some(model) = eng.models.get(handle) { let position = [x as f32, y as f32, z as f32]; let scale = scale as f32; let tint = [ (r / 255.0) as f32, (g / 255.0) as f32, (b / 255.0) as f32, (a / 255.0) as f32, ]; let handle_bits = handle.to_bits(); if eng .renderer .cache_model_if_static(handle_bits, &model.meshes) { // Skinned models cache too (bind-pose VB with raw joint indices, // skinned in the scene VS) — they MUST take the skinned cached // draw, which pops the staged pose ONCE for the whole model and // shares the joint offset across every primitive. Routing them // through the unskinned draw (as this did) leaves each primitive // reading joint offset 0 — another model's matrices — so every // character animated wrongly on web while native was correct. // Mirrors the shared macro in ffi_core/models.rs. if eng.renderer.is_model_skinned(handle_bits) { eng.renderer .draw_model_cached_skinned(handle_bits, position, scale, tint); } else { eng.renderer .draw_model_cached(handle_bits, position, scale, tint); } } } } /// EN-039 — immediate draws that can pitch and roll, not just yaw. /// /// The web crate was the only platform without it, which failed ffi-parity: /// every manifest function must be reachable from every platform, and this one /// is NOT a legitimate gap. The documented WEB_GAP_ALLOWLIST entries are all /// pointer-taking calls blocked on the Perry-WASM linear-memory bridge — this /// takes the matrix as 16 loose f64 scalars precisely so it can cross any FFI, /// so allowlisting it would have been recording a TODO for work that is four /// lines of typing. /// /// Mirrors the shared macro (ffi_core/models.rs) exactly, including the skinned /// early-out: a skinned model's pose is driven by the anim palette, so drawing /// it through the static cache would fight the skinning. #[wasm_bindgen] #[allow(clippy::too_many_arguments)] pub fn bloom_draw_model_transform16( handle: f64, m0: f64, m1: f64, m2: f64, m3: f64, m4: f64, m5: f64, m6: f64, m7: f64, m8: f64, m9: f64, m10: f64, m11: f64, m12: f64, m13: f64, m14: f64, m15: f64, color_packed_argb: f64, ) { let bits = color_packed_argb as u32; let a = ((bits >> 24) & 0xff) as f32 / 255.0; let r = ((bits >> 16) & 0xff) as f32 / 255.0; let g = ((bits >> 8) & 0xff) as f32 / 255.0; let b = (bits & 0xff) as f32 / 255.0; let s = [ m0, m1, m2, m3, m4, m5, m6, m7, m8, m9, m10, m11, m12, m13, m14, m15, ]; // Column-major, same unpacking as the shared macro. let mut mat = [[0.0f32; 4]; 4]; for col in 0..4 { for row in 0..4 { mat[col][row] = s[col * 4 + row] as f32; } } let eng = engine(); if let Some(model) = eng.models.get(handle) { let handle_bits = handle.to_bits(); if eng .renderer .cache_model_if_static(handle_bits, &model.meshes) { if eng.renderer.is_model_skinned(handle_bits) { return; } eng.renderer .draw_model_cached_transform(handle_bits, mat, [r, g, b, a]); } } } #[wasm_bindgen] pub fn bloom_draw_model_rotated( handle: f64, x: f64, y: f64, z: f64, scale: f64, rot_y: f64, color_packed_argb: f64, ) { let bits = color_packed_argb as u32; let a = ((bits >> 24) & 0xff) as f32 / 255.0; let r = ((bits >> 16) & 0xff) as f32 / 255.0; let g = ((bits >> 8) & 0xff) as f32 / 255.0; let b = (bits & 0xff) as f32 / 255.0; let eng = engine(); if let Some(model) = eng.models.get(handle) { let position = [x as f32, y as f32, z as f32]; let scale = scale as f32; let tint = [r, g, b, a]; let handle_bits = handle.to_bits(); // Static models go through the cached scene pipeline (alpha cutout, // normal/MR maps, foliage wind + transmission, cutout shadows, // planar reflections) — the old immediate path had none of that and // rendered cutout foliage as opaque cards. Skinned models take the // skinned cached draw and IGNORE the rotation — their joint matrices // bake orientation, exactly as the old immediate fallback behaved. // // This mirrors the shared macro (ffi_core/models.rs). It was still on // the immediate path here: round 5 fixed native and the web copy was // never updated, so every tree in a browser rendered as torn opaque // sheets — the very artifact that fix was written for. if eng .renderer .cache_model_if_static(handle_bits, &model.meshes) { if eng.renderer.is_model_skinned(handle_bits) { eng.renderer .draw_model_cached_skinned(handle_bits, position, scale, tint); } else { eng.renderer.draw_model_cached_rotated( handle_bits, position, scale, rot_y as f32, tint, ); } } } } #[wasm_bindgen] pub fn bloom_unload_model(handle: f64) { let eng = engine(); // Evict cached GPU meshes (keyed by handle bits) before the handle dies // — without this the buffers leak and a slot-reusing future model would // render the stale geometry. Mirrors the shared macro. eng.renderer.evict_model_cache(handle.to_bits()); eng.models.unload_model(handle); } #[wasm_bindgen] pub fn bloom_gen_mesh_cube(w: f64, h: f64, d: f64) -> f64 { engine().models.gen_mesh_cube(w as f32, h as f32, d as f32) } #[wasm_bindgen] pub fn bloom_gen_mesh_heightmap(image_handle: f64, size_x: f64, size_y: f64, size_z: f64) -> f64 { let eng = engine(); if let Some(img) = eng.textures.images.get(image_handle) { let data = img.data.clone(); let w = img.width; let h = img.height; eng.models .gen_mesh_heightmap(&data, w, h, size_x as f32, size_y as f32, size_z as f32) } else { 0.0 } } #[wasm_bindgen] pub fn bloom_load_shader(_source: f64) -> f64 { // TODO: Phase 4 — need string conversion from NaN-boxed f64 handle 0.0 } #[wasm_bindgen] pub fn bloom_create_mesh( _vertex_ptr: f64, _vertex_count: f64, _index_ptr: f64, _index_count: f64, ) -> f64 { // TODO: Phase 4 — need to handle pointer passing from WASM linear memory 0.0 } // ============================================================ // Lighting // ============================================================ #[wasm_bindgen] pub fn bloom_set_ambient_light(r: f64, g: f64, b: f64, intensity: f64) -> f64 { engine().renderer.set_ambient_light(r, g, b, intensity); 1.0 } #[wasm_bindgen] pub fn bloom_set_directional_light( dx: f64, dy: f64, dz: f64, r: f64, g: f64, b: f64, intensity: f64, ) -> f64 { engine() .renderer .set_directional_light(dx, dy, dz, r, g, b, intensity); 1.0 } #[wasm_bindgen] pub fn bloom_set_procedural_sky( enabled: f64, rayleigh_density: f64, mie_density: f64, ground_albedo: f64, ) -> f64 { engine().renderer.set_procedural_sky( enabled != 0.0, rayleigh_density as f32, mie_density as f32, ground_albedo as f32, ); 1.0 } #[wasm_bindgen] pub fn bloom_set_sun_direction(dx: f64, dy: f64, dz: f64, intensity: f64) -> f64 { engine() .renderer .set_sun_direction(dx as f32, dy as f32, dz as f32, intensity as f32); 1.0 } #[wasm_bindgen] pub fn bloom_set_joint_test(joint_index: f64, angle: f64) -> f64 { engine() .renderer .set_joint_test(joint_index as usize, angle as f32); 1.0 } #[wasm_bindgen] pub fn bloom_add_directional_light( dx: f64, dy: f64, dz: f64, r: f64, g: f64, b: f64, intensity: f64, ) { engine().renderer.add_directional_light( dx as f32, dy as f32, dz as f32, r as f32, g as f32, b as f32, intensity as f32, ); } #[wasm_bindgen] pub fn bloom_add_point_light( x: f64, y: f64, z: f64, range: f64, r: f64, g: f64, b: f64, intensity: f64, ) { engine().renderer.add_point_light( x as f32, y as f32, z as f32, range as f32, r as f32, g as f32, b as f32, intensity as f32, ); } #[wasm_bindgen] pub fn bloom_add_shadowed_point_light( _x: f64, _y: f64, _z: f64, _range: f64, _r: f64, _g: f64, _b: f64, _intensity: f64, ) -> f64 { // Web's conventional lighting path has no local VSM address space. A // status-bearing rejection prevents a requested shadow from becoming an // unshadowed light without the caller noticing. 0.0 } #[wasm_bindgen] pub fn bloom_add_shadowed_spot_light( _x: f64, _y: f64, _z: f64, _direction_x: f64, _direction_y: f64, _direction_z: f64, _range: f64, _inner_cone_degrees: f64, _outer_cone_degrees: f64, _r: f64, _g: f64, _b: f64, _intensity: f64, ) -> f64 { 0.0 } // ============================================================ // Scene graph (retained mode) // ============================================================ #[wasm_bindgen] pub fn bloom_scene_create_node() -> f64 { engine().scene.create_node() } #[wasm_bindgen] pub fn bloom_scene_destroy_node(handle: f64) { engine().scene.destroy_node(handle); } #[wasm_bindgen] pub fn bloom_scene_set_visible(handle: f64, visible: f64) -> f64 { engine().scene.set_visible(handle, visible != 0.0); 1.0 } #[wasm_bindgen] pub fn bloom_scene_set_cast_shadow(handle: f64, cast: f64) -> f64 { engine().scene.set_cast_shadow(handle, cast != 0.0); 1.0 } #[wasm_bindgen] pub fn bloom_scene_set_receive_shadow(handle: f64, receive: f64) -> f64 { engine().scene.set_receive_shadow(handle, receive != 0.0); 1.0 } #[wasm_bindgen] pub fn bloom_scene_set_parent(handle: f64, parent: f64) -> f64 { engine().scene.set_parent(handle, parent); 1.0 } #[wasm_bindgen] pub fn bloom_scene_set_transform(_handle: f64, _matrix_ptr: f64) -> f64 { // Pointer-taking form — unreachable from Perry on wasm (a `number[]` // cannot cross an i64 param), like the other pointer stubs here. The // 16-scalar `_transform16` below is the live path; it used to carry // THIS name, which meant setSceneNodeTransform resolved to nothing and // was auto-stubbed by Perry's FFI proxy — a silent no-op on web while // the working implementation sat one rename away. 0.0 } #[wasm_bindgen] pub fn bloom_scene_set_trs(handle: f64, px: f64, py: f64, pz: f64, yaw: f64, scale: f64) -> f64 { engine().scene.set_trs( handle, px as f32, py as f32, pz as f32, yaw as f32, scale as f32, ); 1.0 } #[wasm_bindgen] #[allow(clippy::too_many_arguments)] pub fn bloom_scene_set_transform16( handle: f64, m00: f64, m01: f64, m02: f64, m03: f64, m10: f64, m11: f64, m12: f64, m13: f64, m20: f64, m21: f64, m22: f64, m23: f64, m30: f64, m31: f64, m32: f64, m33: f64, ) -> f64 { // On web we pass the 16 matrix elements as individual f64 args // (no raw pointer passing from WASM) let mat = [ [m00 as f32, m01 as f32, m02 as f32, m03 as f32], [m10 as f32, m11 as f32, m12 as f32, m13 as f32], [m20 as f32, m21 as f32, m22 as f32, m23 as f32], [m30 as f32, m31 as f32, m32 as f32, m33 as f32], ]; engine().scene.set_transform(handle, mat); 1.0 } #[wasm_bindgen] pub fn bloom_scene_update_geometry( _handle: f64, _vert_ptr: f64, _vert_count: f64, _idx_ptr: f64, _idx_count: f64, ) { // TODO: Phase 4 — need to handle pointer/buffer passing from WASM linear memory. // On web, vertex and index data will need to be passed via a different mechanism // (e.g., typed arrays through JS interop). } #[wasm_bindgen] pub fn bloom_scene_set_material_color(handle: f64, r: f64, g: f64, b: f64, a: f64) -> f64 { engine() .scene .set_material_color(handle, r as f32, g as f32, b as f32, a as f32); 1.0 } #[wasm_bindgen] pub fn bloom_scene_set_material_pbr(handle: f64, roughness: f64, metalness: f64) -> f64 { engine() .scene .set_material_pbr(handle, roughness as f32, metalness as f32); 1.0 } #[wasm_bindgen] pub fn bloom_scene_set_material_texture(handle: f64, texture_idx: f64) -> f64 { engine() .scene .set_material_texture(handle, texture_idx as u32); 1.0 } #[wasm_bindgen] pub fn bloom_scene_node_count() -> f64 { engine().scene.node_count() as f64 } #[wasm_bindgen] pub fn bloom_scene_node_vertex_count(handle: f64) -> f64 { match engine().scene.nodes.get(handle) { Some(node) => node.vertices.len() as f64, None => -1.0, } } #[wasm_bindgen] pub fn bloom_scene_node_index_count(handle: f64) -> f64 { match engine().scene.nodes.get(handle) { Some(node) => node.indices.len() as f64, None => -1.0, } } #[wasm_bindgen] pub fn bloom_scene_attach_model(node_handle: f64, model_handle: f64, mesh_index: f64) { let eng = engine(); let mi = mesh_index as usize; let model_data = match eng.models.models.get(model_handle) { Some(md) => md, None => return, }; if mi >= model_data.meshes.len() { return; } let mesh = &model_data.meshes[mi]; let vertices = mesh.vertices.clone(); let indices = mesh.indices.clone(); let base_color_tex = mesh.texture_idx; let normal_tex = mesh.normal_texture_idx; let mr_tex = mesh.metallic_roughness_texture_idx; let emissive_tex = mesh.emissive_texture_idx; let emissive_factor = mesh.emissive_factor; let roughness_factor = mesh.roughness_factor; let metallic_factor = mesh.metallic_factor; let alpha_cutoff = mesh.alpha_cutoff; eng.scene.update_geometry(node_handle, vertices, indices); if let Some(tex_idx) = base_color_tex { eng.scene.set_material_texture(node_handle, tex_idx); } if let Some(tex_idx) = normal_tex { eng.scene.set_material_normal_texture(node_handle, tex_idx); } if let Some(tex_idx) = mr_tex { eng.scene .set_material_metallic_roughness_texture(node_handle, tex_idx); } if let Some(tex_idx) = emissive_tex { eng.scene .set_material_emissive_texture(node_handle, tex_idx); } eng.scene.set_material_emissive_factor( node_handle, emissive_factor[0], emissive_factor[1], emissive_factor[2], ); // Carry the glTF material factors + MASK cutoff too (mirrors the shared // macro) — dropping them left attached foliage opaque (solid cards) and // every attached mesh at the default roughness 0.8 regardless of its // authored material. eng.scene .set_material_pbr(node_handle, roughness_factor, metallic_factor); eng.scene .set_material_alpha_cutoff(node_handle, alpha_cutoff); } // ============================================================ // Geometry generation // ============================================================ #[wasm_bindgen] pub fn bloom_scene_extrude_polygon( _handle: f64, _polygon_ptr: f64, _polygon_count: f64, _depth: f64, ) { // TODO: Phase 4 — need to handle pointer/buffer passing from WASM linear memory } #[wasm_bindgen] pub fn bloom_scene_subtract_box( handle: f64, min_x: f64, min_y: f64, min_z: f64, max_x: f64, max_y: f64, max_z: f64, ) { let eng = engine(); if let Some(node) = eng.scene.nodes.get(handle) { let current = bloom_shared::geometry::GeometryData { vertices: node.vertices.clone(), indices: node.indices.clone(), }; let result = bloom_shared::geometry::subtract_box( ¤t, [min_x as f32, min_y as f32, min_z as f32], [max_x as f32, max_y as f32, max_z as f32], ); eng.scene .update_geometry(handle, result.vertices, result.indices); } } // ============================================================ // Shadow mapping // ============================================================ #[wasm_bindgen] pub fn bloom_enable_shadows() -> f64 { engine().renderer.shadow_map.enable(); 1.0 } #[wasm_bindgen] pub fn bloom_disable_shadows() -> f64 { engine().renderer.shadow_map.disable(); 1.0 } // ============================================================ // Post-processing // ============================================================ #[wasm_bindgen] pub fn bloom_enable_postfx() { let eng = engine(); let w = eng.renderer.width(); let h = eng.renderer.height(); let fmt = eng.renderer.surface_format(); eng.postfx = Some(bloom_shared::postfx::PostFxPipeline::new( &eng.renderer.device, w, h, fmt, )); } #[wasm_bindgen] pub fn bloom_disable_postfx() { engine().postfx = None; } #[wasm_bindgen] pub fn bloom_postfx_set_selected(handle: f64) -> f64 { if let Some(pfx) = &mut engine().postfx { if handle == 0.0 { pfx.set_selected(Vec::new()); } else { pfx.set_selected(vec![handle]); } 1.0 } else { 0.0 } } #[wasm_bindgen] pub fn bloom_postfx_set_hovered(handle: f64) -> f64 { if let Some(pfx) = &mut engine().postfx { pfx.set_hovered(handle); 1.0 } else { 0.0 } } #[wasm_bindgen] pub fn bloom_postfx_set_outline_color(r: f64, g: f64, b: f64, a: f64) -> f64 { if let Some(pfx) = &mut engine().postfx { pfx.outline_params.color_selected = [r as f32, g as f32, b as f32, a as f32]; 1.0 } else { 0.0 } } #[wasm_bindgen] pub fn bloom_postfx_set_outline_thickness(thickness: f64) -> f64 { if let Some(pfx) = &mut engine().postfx { pfx.outline_params.thickness[0] = thickness as f32; 1.0 } else { 0.0 } } // ============================================================ // Picking // ============================================================ #[wasm_bindgen] pub fn bloom_scene_pick(screen_x: f64, screen_y: f64) -> f64 { let eng = engine(); let inv_vp = eng.renderer.inverse_vp_matrix(); let cam_pos = eng.renderer.camera_pos(); let w = eng.renderer.width() as f32; let h = eng.renderer.height() as f32; let (origin, direction) = bloom_shared::picking::screen_to_ray( screen_x as f32, screen_y as f32, w, h, &inv_vp, &cam_pos, ); let result = bloom_shared::picking::raycast_scene(&eng.scene, &origin, &direction); let hit = result.hit; unsafe { LAST_PICK = Some(result); } if hit { 1.0 } else { 0.0 } } #[wasm_bindgen] pub fn bloom_pick_hit_handle() -> f64 { unsafe { LAST_PICK.as_ref().map(|r| r.handle).unwrap_or(0.0) } } #[wasm_bindgen] pub fn bloom_pick_hit_distance() -> f64 { unsafe { LAST_PICK.as_ref().map(|r| r.distance as f64).unwrap_or(0.0) } } #[wasm_bindgen] pub fn bloom_pick_hit_x() -> f64 { unsafe { LAST_PICK.as_ref().map(|r| r.point[0] as f64).unwrap_or(0.0) } } #[wasm_bindgen] pub fn bloom_pick_hit_y() -> f64 { unsafe { LAST_PICK.as_ref().map(|r| r.point[1] as f64).unwrap_or(0.0) } } #[wasm_bindgen] pub fn bloom_pick_hit_z() -> f64 { unsafe { LAST_PICK.as_ref().map(|r| r.point[2] as f64).unwrap_or(0.0) } } #[wasm_bindgen] pub fn bloom_pick_hit_normal_x() -> f64 { unsafe { LAST_PICK .as_ref() .map(|r| r.normal[0] as f64) .unwrap_or(0.0) } } #[wasm_bindgen] pub fn bloom_pick_hit_normal_y() -> f64 { unsafe { LAST_PICK .as_ref() .map(|r| r.normal[1] as f64) .unwrap_or(0.0) } } #[wasm_bindgen] pub fn bloom_pick_hit_normal_z() -> f64 { unsafe { LAST_PICK .as_ref() .map(|r| r.normal[2] as f64) .unwrap_or(0.0) } } // ============================================================ // 3D -> 2D Projection // ============================================================ #[wasm_bindgen] pub fn bloom_project_to_screen(wx: f64, wy: f64, wz: f64) -> f64 { let eng = engine(); let vp = eng.renderer.vp_matrix(); let w = eng.renderer.width() as f32; let h = eng.renderer.height() as f32; let x = wx as f32; let y = wy as f32; let z = wz as f32; let clip_x = vp[0][0] * x + vp[1][0] * y + vp[2][0] * z + vp[3][0]; let clip_y = vp[0][1] * x + vp[1][1] * y + vp[2][1] * z + vp[3][1]; let clip_w = vp[0][3] * x + vp[1][3] * y + vp[2][3] * z + vp[3][3]; if clip_w <= 0.0 { unsafe { LAST_PROJECT = (-9999.0, -9999.0); } return -9999.0; } let ndc_x = clip_x / clip_w; let ndc_y = clip_y / clip_w; let screen_x = ((ndc_x + 1.0) * 0.5 * w) as f64; let screen_y = ((1.0 - ndc_y) * 0.5 * h) as f64; unsafe { LAST_PROJECT = (screen_x, screen_y); } screen_x } #[wasm_bindgen] pub fn bloom_project_screen_y() -> f64 { unsafe { LAST_PROJECT.1 } } // ============================================================ // File I/O // ============================================================ #[wasm_bindgen] pub fn bloom_write_file(_path: f64, _data: f64) -> f64 { // Handled by JS glue — uses localStorage 0.0 } #[wasm_bindgen] pub fn bloom_set_crash_report_path(_path: f64) { // No file on the web; a panic is already in the browser console. } #[wasm_bindgen] pub fn bloom_file_exists(_path: f64) -> f64 { // Handled by JS glue — checks localStorage 0.0 } #[wasm_bindgen] pub fn bloom_read_file(_path: f64) -> f64 { // Handled by JS glue — reads from localStorage 0.0 } // ============================================================ // Cursor // ============================================================ #[wasm_bindgen] pub fn bloom_disable_cursor() { let input = &mut engine().input; input.cursor_disabled = true; input.clear_mouse_delta(); // JS glue also calls canvas.requestPointerLock() } #[wasm_bindgen] pub fn bloom_enable_cursor() { engine().input.cursor_disabled = false; // JS glue also calls document.exitPointerLock() } // ============================================================ // Frame callbacks & game loop // ============================================================ #[wasm_bindgen] pub fn bloom_register_frame_callback(_priority: f64, _callback: f64) -> f64 { // On web, frame callbacks are managed by the JS glue layer (bloom_glue.js) // since the callback is a Perry WASM closure that can only be invoked // through Perry's runtime. The JS glue intercepts this call. 0.0 } #[wasm_bindgen] pub fn bloom_unregister_frame_callback(_id: f64) { // Managed by JS glue layer } /// Emscripten-style game loop entry point. /// On native: blocks in a while loop calling begin_drawing/callback/end_drawing. /// On web: returns immediately. The JS glue layer (bloom_glue.js) intercepts /// this call and drives the game loop via requestAnimationFrame. #[wasm_bindgen] pub fn bloom_run_game(_callback: f64) { // On web, this is a no-op — the JS glue intercepts the FFI call // before it reaches here and sets up the rAF loop with the callback. // The game's while(!windowShouldClose()) loop should exit after this // (bloom_glue.js makes windowShouldClose return 1.0 once runGame is called). } // ============================================================ // Staging (async asset loading) // ============================================================ #[wasm_bindgen] pub fn bloom_stage_texture(_path: f64) -> f64 { // TODO: Phase 4 — fetch() texture then decode_and_stage_texture 0.0 } #[wasm_bindgen] pub fn bloom_stage_model(_path: f64) -> f64 { // TODO: Phase 4 — fetch() model then stage 0.0 } #[wasm_bindgen] pub fn bloom_stage_sound(_path: f64) -> f64 { // TODO: Phase 4 — fetch() sound then stage 0.0 } #[wasm_bindgen] pub fn bloom_commit_texture(staging_handle: f64) -> f64 { let staged = match bloom_shared::staging::take_texture(staging_handle) { Some(s) => s, None => return 0.0, }; let eng = engine(); let bind_group_idx = eng .renderer .register_texture(staged.width, staged.height, &staged.data); eng.textures .textures .alloc(bloom_shared::textures::TextureData { bind_group_idx, width: staged.width, height: staged.height, }) } #[wasm_bindgen] pub fn bloom_commit_model(staging_handle: f64) -> f64 { let staged = match bloom_shared::staging::take_model(staging_handle) { Some(s) => s, None => return 0.0, }; let eng = engine(); // Normal maps must go through the kind-aware registration (linear space // + LEADR mips) or the committed model shades visibly flatter than the // same GLB through loadModel. Kept in lockstep with the native // bloom_commit_model in ffi_core/models.rs. let mut tex_map: Vec = Vec::with_capacity(staged.textures.len()); for tex in &staged.textures { tex_map.push(eng.renderer.register_texture_kind_with_alpha_coverage( tex.width, tex.height, &tex.data, tex.is_normal, tex.alpha_coverage_reference, )); } let mut model = staged.model; // Remap EVERY texture slot, not just the base colour — dropping the // normal/MR/emissive/occlusion references silently strips the character // maps on any model loaded through the staged path (the round-5 "stale // aux-texture remap" bug, which this web copy used to reproduce). let remap = |idx: &mut Option| { if let Some(i) = *idx { let s = i as usize; *idx = if s > 0 && s <= tex_map.len() { Some(tex_map[s - 1]) } else { None }; } }; for mesh in &mut model.meshes { let mesh = std::sync::Arc::make_mut(mesh); remap(&mut mesh.texture_idx); remap(&mut mesh.normal_texture_idx); remap(&mut mesh.metallic_roughness_texture_idx); remap(&mut mesh.emissive_texture_idx); remap(&mut mesh.occlusion_texture_idx); if let Some(binding) = &mut mesh.transmission.texture { remap(&mut binding.runtime_texture_idx); } if let Some(binding) = &mut mesh.transmission.thickness_texture { remap(&mut binding.runtime_texture_idx); } } eng.models.models.alloc(model) } #[wasm_bindgen] pub fn bloom_commit_sound(staging_handle: f64) -> f64 { match bloom_shared::staging::take_sound(staging_handle) { Some(sd) => engine().audio.load_sound(sd), None => 0.0, } } #[wasm_bindgen] pub fn bloom_commit_music(staging_handle: f64) -> f64 { match bloom_shared::staging::take_sound(staging_handle) { Some(sd) => engine().audio.load_music(sd), None => 0.0, } } // ============================================================ // Platform detection // ============================================================ #[wasm_bindgen] pub fn bloom_get_platform() -> f64 { 7.0 // Web platform ID } /// Relaunch the running program with the arguments it was started with. /// Returns 0 when this platform cannot (the caller should tell the player to /// reopen the app); where it can, it does not return. See `restartApp()`. #[wasm_bindgen] pub fn bloom_restart_app() -> f64 { // A page reload is the web's relaunch. The reload is queued; this frame // still finishes, so report success and let the caller stop drawing. match web_sys::window() { Some(w) => { if w.location().reload().is_ok() { 1.0 } else { 0.0 } } None => 0.0, } } #[wasm_bindgen] pub fn bloom_get_language() -> f64 { // navigator.language (e.g. "en-US" / "zh-Hans") -> packed 2-letter code. let lang = web_sys::window() .and_then(|w| w.navigator().language()) .unwrap_or_default(); let b = lang.to_ascii_lowercase().into_bytes(); if b.len() >= 2 { (b[0] as f64) * 256.0 + (b[1] as f64) } else { 25966.0 } } #[wasm_bindgen] pub fn bloom_is_any_input_pressed() -> f64 { if engine().input.is_any_input_pressed() { 1.0 } else { 0.0 } } #[wasm_bindgen] pub fn bloom_get_crown_rotation() -> f64 { engine().input.consume_crown_rotation() } // Scene graph QoL — Q4/Q5/Q6/Q7 #[wasm_bindgen] pub fn bloom_scene_get_transform(handle: f64, index: f64) -> f64 { let mat = engine().scene.get_transform(handle); let i = index as usize; let col = i / 4; let row = i % 4; if col < 4 && row < 4 { mat[col][row] as f64 } else { 0.0 } } #[wasm_bindgen] pub fn bloom_scene_get_bounds_min_x(handle: f64) -> f64 { engine().scene.get_bounds(handle).0[0] as f64 } #[wasm_bindgen] pub fn bloom_scene_get_bounds_min_y(handle: f64) -> f64 { engine().scene.get_bounds(handle).0[1] as f64 } #[wasm_bindgen] pub fn bloom_scene_get_bounds_min_z(handle: f64) -> f64 { engine().scene.get_bounds(handle).0[2] as f64 } #[wasm_bindgen] pub fn bloom_scene_get_bounds_max_x(handle: f64) -> f64 { engine().scene.get_bounds(handle).1[0] as f64 } #[wasm_bindgen] pub fn bloom_scene_get_bounds_max_y(handle: f64) -> f64 { engine().scene.get_bounds(handle).1[1] as f64 } #[wasm_bindgen] pub fn bloom_scene_get_bounds_max_z(handle: f64) -> f64 { engine().scene.get_bounds(handle).1[2] as f64 } #[wasm_bindgen] pub fn bloom_scene_set_user_data(handle: f64, data: f64) -> f64 { engine().scene.set_user_data(handle, data as i64); 1.0 } #[wasm_bindgen] pub fn bloom_scene_get_user_data(handle: f64) -> f64 { engine().scene.get_user_data(handle) as f64 } // Q1: Render texture FFI (stub) #[wasm_bindgen] pub fn bloom_load_render_texture(width: f64, height: f64) -> f64 { engine() .textures .load_render_texture(width as u32, height as u32) } #[wasm_bindgen] pub fn bloom_unload_render_texture(handle: f64) { engine().textures.unload_render_texture(handle); } #[wasm_bindgen] pub fn bloom_begin_texture_mode(_handle: f64) { /* stub */ } #[wasm_bindgen] pub fn bloom_end_texture_mode() { /* stub */ } #[wasm_bindgen] pub fn bloom_get_render_texture_texture(handle: f64) -> f64 { engine().textures.get_render_texture_texture(handle) } // Q8: Water material #[wasm_bindgen] pub fn bloom_scene_set_material_water( handle: f64, wave_amp: f64, wave_speed: f64, r: f64, g: f64, b: f64, a: f64, ) -> f64 { engine().scene.set_material_water( handle, wave_amp as f32, wave_speed as f32, r as f32, g as f32, b as f32, a as f32, ); 1.0 } // Q9: Spline ribbon mesh #[wasm_bindgen] pub fn bloom_gen_mesh_spline_ribbon( points_ptr: *const u8, point_count: f64, widths_ptr: *const u8, width_count: f64, ) -> f64 { let n = point_count as usize; let wn = width_count as usize; let points = unsafe { std::slice::from_raw_parts(points_ptr as *const f32, n * 3) }; let widths = unsafe { std::slice::from_raw_parts(widths_ptr as *const f32, wn) }; engine().models.gen_mesh_spline_ribbon(points, widths) } // Q6: Multi-hit picking static mut LAST_PICK_ALL: Vec = Vec::new(); #[wasm_bindgen] pub fn bloom_scene_pick_all(screen_x: f64, screen_y: f64, max_results: f64) -> f64 { let eng = engine(); let inv_vp = eng.renderer.inverse_vp_matrix(); let cam_pos = eng.renderer.camera_pos(); let w = eng.renderer.width() as f32; let h = eng.renderer.height() as f32; let (origin, direction) = bloom_shared::picking::screen_to_ray( screen_x as f32, screen_y as f32, w, h, &inv_vp, &cam_pos, ); let results = bloom_shared::picking::raycast_scene_all( &eng.scene, &origin, &direction, max_results as usize, ); let count = results.len(); unsafe { LAST_PICK_ALL = results; } count as f64 } #[wasm_bindgen] pub fn bloom_pick_all_handle(index: f64) -> f64 { let i = index as usize; unsafe { LAST_PICK_ALL.get(i).map(|r| r.handle).unwrap_or(0.0) } } #[wasm_bindgen] pub fn bloom_pick_all_distance(index: f64) -> f64 { let i = index as usize; unsafe { LAST_PICK_ALL .get(i) .map(|r| r.distance as f64) .unwrap_or(0.0) } } // Q2: Cursor shape #[wasm_bindgen] pub fn bloom_set_cursor_shape(shape: f64) { engine().input.cursor_shape = shape as u32; } // E4: Clipboard (stub) #[wasm_bindgen] pub fn bloom_set_clipboard_text(_text_ptr: *const u8) {} #[wasm_bindgen] pub fn bloom_get_clipboard_text() -> f64 { 0.0 } // E5b: File dialogs (stub) #[wasm_bindgen] pub fn bloom_open_file_dialog(_filter_ptr: *const u8, _title_ptr: *const u8) -> f64 { 0.0 } #[wasm_bindgen] pub fn bloom_save_file_dialog(_default_name_ptr: *const u8, _title_ptr: *const u8) -> f64 { 0.0 } #[wasm_bindgen] pub fn bloom_launch_process(_cmd: f64, _args: f64, _cwd: f64) -> f64 { // A web page does not get to launch processes. 0.0 } #[no_mangle] pub fn bloom_command_line_arg_count() -> f64 { 0.0 } #[no_mangle] pub fn bloom_preferred_language_count() -> f64 { // A web build runs in a real browser, whose navigator.languages is the answer. 0.0 } #[no_mangle] pub fn bloom_preferred_language(_index: f64) -> f64 { // Unreachable: the count is zero (see bloom_command_line_arg). 0.0 } #[no_mangle] pub fn bloom_command_line_arg(_index: f64) -> f64 { // `count()` is always zero on web, so this ABI-compatible sentinel is // unreachable through the public helper. Web has no Perry string // allocator and must not pretend a native pointer exists. 0.0 } // ============================================================ // Profiler — CPU phase timings (always available). TIMESTAMP_QUERY // is not part of the WebGPU spec as of wgpu 29, so the GPU path // returns 0 on web regardless of adapter — the profiler stays // CPU-only, which is still useful for frame-phase profiling. // ============================================================ #[wasm_bindgen] pub fn bloom_set_profiler_enabled(on: f64) { engine().profiler.set_enabled(on != 0.0); } #[wasm_bindgen] pub fn bloom_get_profiler_frame_cpu_us() -> f64 { engine().profiler.avg_frame_cpu_us() } #[wasm_bindgen] pub fn bloom_get_profiler_frame_gpu_us() -> f64 { engine().profiler.avg_frame_gpu_us() } /// SH-069: a browser is never the low tier unless BLOOM_LOW_TIER=1 forced it (it cannot here). #[wasm_bindgen] pub fn bloom_is_low_tier_gpu() -> f64 { 0.0 } #[wasm_bindgen] pub fn bloom_print_profiler_summary() { // No stdout in the browser — route through the existing // console_log binding so the summary lands in devtools. console_log(&engine().profiler.summary()); } // ============================================================ // Physics (Jolt via JoltPhysics.js) — the whole bloom_physics_* surface // lives in physics_ffi.rs, kept in lockstep with jolt_bridge.js and the // package.json manifest (tools/validate-ffi.js checks the name coverage). mod physics_ffi; pub use physics_ffi::*; // Renderer settings + LOD surface live in render_settings.rs (2000-line // file policy); same shared engine methods the native macro wraps. mod render_settings; pub use render_settings::*;