Skip to main content

webizen_studio/render/
q_viewport.rs

1//! Declarative `<q-viewport>` lifecycle — types and pure logic (plan §7.3 W5).
2//!
3//! The viewport lifecycle is:
4//! 1. **Detect backend** — call `Render.gpu_backend_info` to probe WebGPU/WebGL2.
5//! 2. **Init GPU** — call `Render.gpu_init` with width/height/particle_cap.
6//! 3. **Frame loop** — repeatedly call `Render.gpu_render_frame` with sim-time.
7//! 4. **Resize** — call `Render.gpu_resize` when the canvas dimensions change.
8//! 5. **Camera** — call `Render.gpu_set_camera` on mouse/wheel input.
9//! 6. **Destroy** — call `Render.gpu_destroy` on unmount.
10//! 7. **After resize** — `Render.gpu_sync_bloom` then `Render.gpu_surface_size`.
11//! 8. **Pick** — `Render.gpu_pick` + `Render.gpu_poll_pick` on click.
12//! 9. **Camera readback** — `Render.gpu_camera_state` after orbit.
13//!
14//! This module contains only the types and pure logic (no UI dependencies).
15//! The async invoke functions live in the component module, which has access
16//! to the `qapp_engine::invoke_json` helper.
17
18use serde::{Deserialize, Serialize};
19use serde_json::Value;
20
21/// Backend type detected by `Render.gpu_backend_info`.
22#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
23#[serde(rename_all = "lowercase")]
24pub enum ViewportBackend {
25    /// Native wgpu (DirectML/Vulkan/Metal) or browser WebGPU.
26    Webgpu,
27    /// Browser WebGL2 fallback (naga-translated GLSL ES 300).
28    Webgl2,
29    /// Canvas 2D fallback (no GPU acceleration).
30    Canvas2d,
31    /// No backend available.
32    None,
33}
34
35impl Default for ViewportBackend {
36    fn default() -> Self {
37        Self::None
38    }
39}
40
41impl ViewportBackend {
42    /// Constructs from str.
43    pub fn from_str(s: &str) -> Self {
44        match s.to_lowercase().as_str() {
45            "webgpu" => Self::Webgpu,
46            "webgl2" => Self::Webgl2,
47            "canvas2d" => Self::Canvas2d,
48            _ => Self::None,
49        }
50    }
51
52    /// `true` when gpu.
53    pub fn is_gpu(&self) -> bool {
54        matches!(self, Self::Webgpu | Self::Webgl2)
55    }
56}
57
58/// Viewport configuration — declarative props for `<q-viewport>`.
59#[derive(Debug, Clone, Serialize, Deserialize)]
60pub struct ViewportConfig {
61    /// Canvas width in physical pixels.
62    pub width: u32,
63    /// Canvas height in physical pixels.
64    pub height: u32,
65    /// Particle capacity for the ambient field.
66    #[serde(default = "default_particle_cap")]
67    pub particle_cap: u32,
68    /// Target frame rate (frames per second). 0 = uncapped (requestAnimationFrame).
69    #[serde(default = "default_target_fps")]
70    pub target_fps: u32,
71    /// Initial camera yaw (radians).
72    #[serde(default)]
73    pub camera_yaw: f32,
74    /// Initial camera pitch (radians).
75    #[serde(default = "default_camera_pitch")]
76    pub camera_pitch: f32,
77    /// Initial camera zoom.
78    #[serde(default = "default_camera_zoom")]
79    pub camera_zoom: f32,
80    /// Whether to auto-mount on creation.
81    #[serde(default = "default_auto_mount")]
82    pub auto_mount: bool,
83}
84
85fn default_particle_cap() -> u32 {
86    4096
87}
88fn default_target_fps() -> u32 {
89    60
90}
91fn default_camera_pitch() -> f32 {
92    -0.3
93}
94fn default_camera_zoom() -> f32 {
95    1.0
96}
97fn default_auto_mount() -> bool {
98    true
99}
100
101impl Default for ViewportConfig {
102    fn default() -> Self {
103        Self {
104            width: 800,
105            height: 600,
106            particle_cap: default_particle_cap(),
107            target_fps: default_target_fps(),
108            camera_yaw: 0.0,
109            camera_pitch: default_camera_pitch(),
110            camera_zoom: default_camera_zoom(),
111            auto_mount: true,
112        }
113    }
114}
115
116/// Viewport runtime state — tracks the GPU handle, backend, and frame count.
117#[derive(Debug, Clone, Default)]
118pub struct ViewportState {
119    /// GPU portal handle (from `Render.gpu_init`). None = not mounted.
120    pub handle: Option<u64>,
121    /// Detected backend.
122    pub backend: ViewportBackend,
123    /// Frame count since mount.
124    pub frame_count: u64,
125    /// Last sim-time passed to `Render.gpu_render_frame`.
126    pub last_time: f32,
127    /// Whether the viewport is currently running a frame loop.
128    pub running: bool,
129    /// Last error message (if any).
130    pub last_error: Option<String>,
131    /// Last `Render.gpu_surface_size` width.
132    pub surface_width: u32,
133    /// Last `Render.gpu_surface_size` height.
134    pub surface_height: u32,
135    /// Last pick node id, if any.
136    pub last_pick: Option<u32>,
137}
138
139impl ViewportState {
140    /// Whether the viewport is mounted and has a valid GPU handle.
141    pub fn is_mounted(&self) -> bool {
142        self.handle.is_some()
143    }
144
145    /// Whether the viewport has a GPU-accelerated backend.
146    pub fn is_gpu(&self) -> bool {
147        self.backend.is_gpu()
148    }
149}
150
151/// Workshop-dialect Vibe body for GPU invokes (`using Render;`).
152pub fn vibe_gpu_script(body: &str) -> String {
153    format!("using Render;\neffect fn go() {{\n    {body}\n}}")
154}
155
156/// Extract the GPU handle from a `poet_eval` result JSON.
157pub fn extract_handle(result: &Value) -> Result<u64, String> {
158    // The result may have the handle in `value` (as a JSON string) or directly.
159    if let Some(value_str) = result.get("value").and_then(|v| v.as_str()) {
160        if let Ok(value) = serde_json::from_str::<Value>(value_str) {
161            if let Some(handle) = value.get("handle").and_then(|h| h.as_u64()) {
162                return Ok(handle);
163            }
164        }
165    }
166    if let Some(handle) = result.get("handle").and_then(|h| h.as_u64()) {
167        return Ok(handle);
168    }
169    Err("no handle in gpu_init result".into())
170}
171
172fn nested_record(result: &Value) -> Option<Value> {
173    if let Some(value_str) = result.get("value").and_then(|v| v.as_str()) {
174        serde_json::from_str::<Value>(value_str).ok()
175    } else {
176        Some(result.clone())
177    }
178}
179
180/// Extract `{width, height}` from `Render.gpu_surface_size`.
181pub fn extract_surface_size(result: &Value) -> Option<(u32, u32)> {
182    let rec = nested_record(result)?;
183    let w = rec.get("width").and_then(|v| v.as_u64())? as u32;
184    let h = rec.get("height").and_then(|v| v.as_u64())? as u32;
185    Some((w, h))
186}
187
188/// Extract pick result from `Render.gpu_poll_pick`.
189pub fn extract_pick(result: &Value) -> Option<u32> {
190    let rec = nested_record(result)?;
191    if rec.get("found").and_then(|v| v.as_bool()) != Some(true) {
192        return None;
193    }
194    rec.get("node_id")
195        .and_then(|v| v.as_u64())
196        .map(|n| n as u32)
197}
198
199/// Extract the backend string from a `poet_eval` result JSON.
200pub fn extract_backend(result: &Value) -> ViewportBackend {
201    if let Some(value_str) = result.get("value").and_then(|v| v.as_str()) {
202        if let Ok(value) = serde_json::from_str::<Value>(value_str) {
203            if let Some(backend_str) = value.get("backend").and_then(|b| b.as_str()) {
204                return ViewportBackend::from_str(backend_str);
205            }
206        }
207    }
208    if let Some(backend_str) = result.get("backend").and_then(|b| b.as_str()) {
209        return ViewportBackend::from_str(backend_str);
210    }
211    ViewportBackend::None
212}
213
214#[cfg(test)]
215mod tests {
216    use super::*;
217    use serde_json::json;
218
219    #[test]
220    fn viewport_backend_from_str() {
221        assert_eq!(ViewportBackend::from_str("webgpu"), ViewportBackend::Webgpu);
222        assert_eq!(ViewportBackend::from_str("WebGL2"), ViewportBackend::Webgl2);
223        assert_eq!(
224            ViewportBackend::from_str("canvas2d"),
225            ViewportBackend::Canvas2d
226        );
227        assert_eq!(ViewportBackend::from_str("unknown"), ViewportBackend::None);
228    }
229
230    #[test]
231    fn viewport_backend_is_gpu() {
232        assert!(ViewportBackend::Webgpu.is_gpu());
233        assert!(ViewportBackend::Webgl2.is_gpu());
234        assert!(!ViewportBackend::Canvas2d.is_gpu());
235        assert!(!ViewportBackend::None.is_gpu());
236    }
237
238    #[test]
239    fn viewport_config_default() {
240        let config = ViewportConfig::default();
241        assert_eq!(config.width, 800);
242        assert_eq!(config.height, 600);
243        assert_eq!(config.particle_cap, 4096);
244        assert_eq!(config.target_fps, 60);
245        assert!(config.auto_mount);
246    }
247
248    #[test]
249    fn viewport_state_default() {
250        let state = ViewportState::default();
251        assert!(!state.is_mounted());
252        assert!(!state.is_gpu());
253        assert_eq!(state.frame_count, 0);
254    }
255
256    #[test]
257    fn viewport_state_mounted() {
258        let state = ViewportState {
259            handle: Some(42),
260            backend: ViewportBackend::Webgpu,
261            ..Default::default()
262        };
263        assert!(state.is_mounted());
264        assert!(state.is_gpu());
265    }
266
267    #[test]
268    fn extract_handle_from_value() {
269        let result = json!({
270            "value": "{\"handle\": 123, \"width\": 800, \"height\": 600}"
271        });
272        assert_eq!(extract_handle(&result).unwrap(), 123);
273    }
274
275    #[test]
276    fn extract_handle_direct() {
277        let result = json!({ "handle": 456 });
278        assert_eq!(extract_handle(&result).unwrap(), 456);
279    }
280
281    #[test]
282    fn extract_handle_missing() {
283        let result = json!({ "error": "something went wrong" });
284        assert!(extract_handle(&result).is_err());
285    }
286
287    #[test]
288    fn viewport_config_serialize_deserialize() {
289        let config = ViewportConfig {
290            width: 1024,
291            height: 768,
292            particle_cap: 8192,
293            target_fps: 30,
294            camera_yaw: 0.5,
295            camera_pitch: -0.2,
296            camera_zoom: 2.0,
297            auto_mount: false,
298        };
299        let json_str = serde_json::to_string(&config).unwrap();
300        let decoded: ViewportConfig = serde_json::from_str(&json_str).unwrap();
301        assert_eq!(decoded.width, 1024);
302        assert_eq!(decoded.height, 768);
303        assert_eq!(decoded.particle_cap, 8192);
304        assert_eq!(decoded.target_fps, 30);
305        assert!(!decoded.auto_mount);
306    }
307
308    #[test]
309    fn vibe_gpu_script_uses_render_family() {
310        let src = vibe_gpu_script("return Render.gpu_adapter_info();");
311        assert!(src.contains("using Render;"));
312        assert!(src.contains("Render.gpu_adapter_info"));
313        assert!(!src.contains("capability.invoke"));
314    }
315
316    #[test]
317    fn extract_surface_size_direct() {
318        let result = json!({ "width": 128, "height": 64 });
319        assert_eq!(extract_surface_size(&result), Some((128, 64)));
320    }
321
322    #[test]
323    fn extract_pick_found() {
324        let result = json!({ "found": true, "node_id": 7 });
325        assert_eq!(extract_pick(&result), Some(7));
326        let miss = json!({ "found": false });
327        assert_eq!(extract_pick(&miss), None);
328    }
329}