Skip to main content

webizen_studio/render/
studio_preview.rs

1//! Native studio render pipeline — wires graph/mesh/qualia/scene/tensor types into
2//! the headless GPU contract used by `update_render_preview`.
3
4use super::graph::{Node, Scene, Style};
5use super::mesh::{Mesh, Transform};
6use super::motion::{Spring, Timeline};
7use super::qualia::{build_scene, item_color, ItemState, SceneItem, SceneSource, SemanticScene};
8use super::scene::{Camera, ScreenPoint, Vec3};
9use super::tensor_buffer::TensorBufferView;
10use super::Renderer;
11use crate::canvas_model::PanePlacement;
12use crate::theme_engine::{ResolvedTheme, ThemeBinding};
13use webizen_render::scene_contract::RenderScene;
14
15/// Semantic scene derived from the current workspace pane grid (native host path).
16pub fn semantic_scene_from_panes(panes: &[PanePlacement]) -> SemanticScene {
17    let items = panes
18        .iter()
19        .enumerate()
20        .map(|(idx, pane)| SceneItem {
21            id: pane.component_id.clone(),
22            state: if idx == 0 {
23                ItemState::Highlighted
24            } else {
25                ItemState::Active
26            },
27            intensity: (0.35 + (idx as f64 * 0.08)).min(1.0),
28            provenance: Some(format!("pane:{idx}")),
29            reasons: vec![format!(
30                "{} @ ({:.0}, {:.0})",
31                pane.component_id, pane.x, pane.y
32            )],
33        })
34        .collect();
35
36    SemanticScene {
37        items,
38        explanations: vec!["Workspace pane grid mapped to semantic manifold nodes".to_string()],
39    }
40}
41
42/// Layout function: map pane ids to world positions on a shallow grid.
43fn pane_layout(panes: &[PanePlacement]) -> impl Fn(&str) -> Option<(Vec3, Mesh)> + '_ {
44    move |id| {
45        let idx = panes.iter().position(|p| p.component_id == id)?;
46        let pane = &panes[idx];
47        let x = (pane.x as f64 / 12.0) - 4.0;
48        let z = (pane.y as f64 / 12.0) - 3.0;
49        let size = (pane.w.max(pane.h) as f64 / 18.0).clamp(0.35, 1.4);
50        Some((Vec3::new(x, 0.0, z), Mesh::cube(size)))
51    }
52}
53
54/// Build a scene from any [`SceneSource`] (SPARQL payload, mock, or pane grid).
55pub fn workspace_scene_from_source(source: &impl SceneSource, panes: &[PanePlacement]) -> Scene {
56    let sem = source.semantic_scene();
57    if sem.items.is_empty() {
58        return empty_workspace_fallback_scene();
59    }
60    build_scene(&sem, Camera::default(), |id| pane_layout(panes)(id))
61}
62
63/// Build the internal scene graph from workspace panes.
64pub fn workspace_scene_from_panes(panes: &[PanePlacement]) -> Scene {
65    let sem = semantic_scene_from_panes(panes);
66    build_scene(&sem, Camera::default(), |id| pane_layout(panes)(id))
67}
68
69/// Convert workspace panes to the neutral GPU [`RenderScene`] contract.
70pub fn render_contract_from_panes(panes: &[PanePlacement]) -> RenderScene {
71    RenderScene::from(workspace_scene_from_panes(panes))
72}
73
74/// Read tensor buffer telemetry without converting the canonical EMF spectrum
75/// into display colour. Colour is a later observer-specific projection.
76pub fn tensor_buffer_digest(buffer: &[u8]) -> (usize, f64) {
77    let view = TensorBufferView::new(buffer);
78    if view.is_empty() {
79        return (0, 0.0);
80    }
81    let count = view.len();
82    let opacity = view
83        .get(0)
84        .map(|t| {
85            let _emf_spectrum = t.emf_spectrum();
86            let _energy = t.manifold_energy();
87            t.opacity()
88        })
89        .unwrap_or(0.0);
90    (count, opacity)
91}
92
93/// Theme-scoped motion tick for native studio shell (sanctuary disables springs).
94pub fn theme_motion_timeline(theme: &ResolvedTheme, dt: f64) -> Timeline {
95    let class = theme.class_name.as_deref();
96    super::motion::timeline_from_theme(0.0, dt, class)
97}
98
99/// One UI motion step for native builds when the selection changes.
100pub fn step_native_selection_pulse(
101    spring: &mut Spring,
102    selected: bool,
103    theme: &ResolvedTheme,
104) -> f64 {
105    super::motion_loop::step_selection_spring(spring, selected, theme.class_name.as_deref(), 0.016)
106}
107
108/// Sample color for inspector chips from a semantic item state.
109pub fn preview_item_swatch(state: ItemState, intensity: f64) -> String {
110    item_color(state, intensity)
111}
112
113/// Orbit camera for spatial preview controls (native).
114pub fn orbit_preview_camera(camera: &mut Camera, yaw: f64, pitch: f64) {
115    camera.orbit(yaw, pitch);
116}
117
118/// Build a minimal wireframe grid scene for empty workspaces.
119pub fn empty_workspace_fallback_scene() -> Scene {
120    Scene::new(Camera::default())
121        .with_background("var(--qualia-bg)")
122        .add(
123            Node::new("grid")
124                .with_mesh(Mesh::grid(12.0, 12))
125                .with_style(Style::wire("#475569"))
126                .with_transform(Transform::at(Vec3::new(0.0, -0.5, 0.0))),
127        )
128}
129
130/// Count draw primitives when rasterizing a workspace scene (native diagnostics).
131pub fn rasterize_scene_draw_count(panes: &[PanePlacement]) -> usize {
132    let scene = if panes.is_empty() {
133        empty_workspace_fallback_scene()
134    } else {
135        workspace_scene_from_panes(panes)
136    };
137    let mut r = DrawCountRenderer::new((960.0, 540.0));
138    scene.render(&mut r);
139    r.finish()
140}
141
142/// Headless native renderer byte length for the current pane layout.
143pub async fn native_headless_png_byte_len(
144    panes: &[PanePlacement],
145    width: u32,
146    height: u32,
147) -> Option<usize> {
148    use super::native::NativeRenderer;
149    let scene = if panes.is_empty() {
150        empty_workspace_fallback_scene()
151    } else {
152        workspace_scene_from_panes(panes)
153    };
154    let mut renderer = NativeRenderer::new(width, height).await.ok()?;
155    renderer.resize(width, height);
156    scene.render(&mut renderer);
157    let _preview_rgba = renderer.read_pixels();
158    renderer.read_png().map(|bytes| bytes.len())
159}
160
161struct DrawCountRenderer {
162    camera: Camera,
163    viewport: (f64, f64),
164    count: std::cell::Cell<usize>,
165}
166
167impl DrawCountRenderer {
168    fn new(viewport: (f64, f64)) -> Self {
169        Self {
170            camera: Camera::default(),
171            viewport,
172            count: std::cell::Cell::new(0),
173        }
174    }
175
176    fn finish(self) -> usize {
177        self.count.get()
178    }
179}
180
181impl Renderer for DrawCountRenderer {
182    fn viewport(&self) -> (f64, f64) {
183        self.viewport
184    }
185
186    fn set_camera(&mut self, camera: Camera) {
187        self.camera = camera;
188    }
189
190    fn clear(&self, _color: &str) {
191        self.count.set(self.count.get() + 1);
192    }
193
194    fn project(&self, world: Vec3) -> Option<ScreenPoint> {
195        self.camera.project(world, self.viewport)
196    }
197
198    fn line(&self, _a: ScreenPoint, _b: ScreenPoint, _color: &str, _alpha: f64, _width: f64) {
199        self.count.set(self.count.get() + 1);
200    }
201
202    fn point(&self, _p: ScreenPoint, _radius: f64, _color: &str, _alpha: f64) {
203        self.count.set(self.count.get() + 1);
204    }
205
206    fn fill_polygon(&self, _points: &[ScreenPoint], _color: &str, _alpha: f64) {
207        self.count.set(self.count.get() + 1);
208    }
209}
210
211/// Resolve theme binding into a motion-friendly class for spring drivers.
212pub fn motion_class_from_binding(
213    binding: &ThemeBinding,
214    catalog: &[crate::theme_engine::ThemeDefinition],
215) -> String {
216    let resolved = crate::theme_engine::resolve_theme(Some(binding), catalog);
217    resolved
218        .class_name
219        .unwrap_or_else(|| "theme-fiduciary-dark".to_string())
220}
221
222#[cfg(test)]
223mod tests {
224    use super::*;
225    use crate::canvas_model::{LayerBehavior, PanePlacement};
226    use crate::theme_engine::builtin_theme_catalog;
227
228    #[test]
229    fn workspace_panes_produce_render_contract() {
230        let panes = vec![PanePlacement {
231            component_id: "dashboard".to_string(),
232            x: 12,
233            y: 8,
234            w: 24,
235            h: 18,
236            data_bindings: vec![],
237            binds_rpc: None,
238            requires_capability: vec![],
239            ui_mode: None,
240            layer: LayerBehavior::Docked,
241            anchor: Some("top-left".to_string()),
242            min_w_points: 8,
243            min_h_points: 6,
244            supported_presentations: vec![],
245            theme: ThemeBinding::default(),
246        }];
247        let contract = render_contract_from_panes(&panes);
248        assert!(!contract.is_empty());
249    }
250
251    #[test]
252    fn tensor_digest_handles_empty_buffer() {
253        assert_eq!(tensor_buffer_digest(&[]), (0, 0.0));
254    }
255
256    #[test]
257    fn tensor_digest_reads_engine_abi_and_keeps_emf_sigma_unclamped() {
258        use super::super::tensor_buffer::{
259            Q42_TENSOR_HEADER_BYTES, Q42_TENSOR_MAGIC, Q42_TENSOR_STRIDE, Q42_TENSOR_VERSION,
260        };
261
262        let mut buffer = vec![0u8; Q42_TENSOR_HEADER_BYTES + Q42_TENSOR_STRIDE];
263        buffer[0..4].copy_from_slice(&Q42_TENSOR_MAGIC.to_le_bytes());
264        buffer[4..6].copy_from_slice(&Q42_TENSOR_VERSION.to_le_bytes());
265        buffer[8..12].copy_from_slice(&1_u32.to_le_bytes());
266        buffer[12..16].copy_from_slice(&(Q42_TENSOR_STRIDE as u32).to_le_bytes());
267        buffer[Q42_TENSOR_HEADER_BYTES + 7 * 4..Q42_TENSOR_HEADER_BYTES + 8 * 4]
268            .copy_from_slice(&0.7_f32.to_le_bytes());
269        buffer[Q42_TENSOR_HEADER_BYTES + 9 * 4..Q42_TENSOR_HEADER_BYTES + 10 * 4]
270            .copy_from_slice(&2.5_f32.to_le_bytes());
271
272        let (count, opacity) = tensor_buffer_digest(&buffer);
273        assert_eq!(count, 1);
274        assert!((opacity - 0.7).abs() < 1e-6);
275        let tensor = TensorBufferView::new(&buffer).get(0).unwrap();
276        let emf = tensor.emf_spectrum();
277        assert!((emf[0] - 0.7).abs() < 1e-6);
278        assert_eq!(emf[1], 0.0);
279        assert_eq!(emf[2], 2.5);
280    }
281
282    #[test]
283    fn motion_class_defaults_to_fiduciary() {
284        let class = motion_class_from_binding(&ThemeBinding::default(), &builtin_theme_catalog());
285        assert!(class.contains("fiduciary") || class.contains("theme-"));
286    }
287}