uzor-urx-wgpu 1.5.0

URX WGPU backend — consumes urx-core DrawCommand, dispatches to instanced-WGPU primitive pipelines (Quad SDF + Line capsule + Triangle + Text atlas). Wraps uzor-render-wgpu-instanced (the existing well-tested primitive crate) with the URX scene-consumer API + URX metrics.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
//! `Scene` → `InstancedRenderContext` adapter.
//!
//! Walks `urx_core::Scene::commands` in painter's order, calls the
//! corresponding `uzor::render::RenderContext` methods on the
//! provided `InstancedRenderContext` so the underlying primitive
//! pipelines (Quad SDF, Line capsule, lyon triangles, glyph atlas)
//! see the same DrawCmd stream they always have.
//!
//! ## Stage 1a (2026-06-05) — degraded paths fixed
//!
//! The previous adapter silently turned gradient brushes, radii,
//! glyphs and rounded clips into counter-increments + no-ops. Stage 1a
//! routes them into the real `InstancedRenderContext` methods that
//! already exist:
//!
//! * `FillRect { radii: Some(r) }` → `fill_rounded_rect(x, y, w, h, r0)`
//!   (single radius — per-corner is a Stage 2 IR addition).
//! * `FillRect { brush: Linear gradient }` → `fill_linear_gradient(...)`
//!   with stop quad + the rect bounds as the gradient endpoints.
//! * `FillRect { brush: Radial gradient }` → degraded to solid for now
//!   (the underlying ctx has no `fill_radial_gradient` method;
//!   delivered in Stage 1b together with the native pipeline rewrite).
//! * `GlyphRun` → `fill_text(text, x, y)` per-glyph fallback. Note: we
//!   don't have the source text string at this layer (Scene carries
//!   pre-shaped glyph ids), so this still degrades; Stage 2 adds the
//!   `(text: String)` companion to `GlyphRun` or a `FontId`-driven
//!   atlas direct submit.
//! * `PushClipRect` / `PopClip` → real clip via path + `clip()`.

use std::time::Instant;

use uzor::render::{GradientPainter, Masking, Painter, ShapeHelpers, TextRenderer};
use uzor_render_wgpu_instanced::InstancedRenderContext;
use uzor_urx_core::math::{Affine, BezPath, Brush, Color, GradientKind};
use uzor_urx_core::scene::{DrawCommand, Scene};
use kurbo::PathEl;

/// Translate a `Scene` into context calls. Caller has already cleared
/// `ctx.draw_commands` for this frame (the hub's `with_render_context`
/// path takes care of that).
pub fn adapt_scene_into(scene: &Scene, ctx: &mut InstancedRenderContext) {
    use uzor_urx_core::metrics_keys::{
        KEY_RENDER_PRIMITIVES, render_submit_count_key,
    };

    let t0 = Instant::now();
    let mut clip_depth: u32 = 0;

    for cmd in &scene.commands {
        match cmd {
            DrawCommand::FillRect { rect, radii, brush, transform } => {
                apply_transform(ctx, transform);
                let (x, y, w, h) = (rect.x0, rect.y0, rect.width(), rect.height());
                match brush {
                    Brush::Solid(c) => {
                        ctx.set_fill_color(&color_to_css(*c));
                        if let Some(r) = radii.filter(|r| r.iter().any(|v| *v > 0.0)) {
                            // Stage 1a — single radius. Stage 2: per-corner.
                            ctx.fill_rounded_rect(x, y, w, h, r[0] as f64);
                        } else {
                            ctx.fill_rect(x, y, w, h);
                        }
                    }
                    Brush::Gradient(grad) => match &grad.kind {
                        GradientKind::Linear(pos) => {
                            // Stage 1a — radii dropped under linear gradient
                            // (the underlying tessellator only knows the rect bounds).
                            let stops: Vec<(f32, String)> = grad.stops.iter().map(|s| {
                                let c = s.color.to_alpha_color::<peniko::color::Srgb>();
                                (s.offset, color_to_css(c))
                            }).collect();
                            let stop_refs: Vec<(f32, &str)> =
                                stops.iter().map(|(t, s)| (*t, s.as_str())).collect();
                            ctx.fill_linear_gradient(
                                &stop_refs,
                                pos.start.x, pos.start.y,
                                pos.end.x,   pos.end.y,
                            );
                            degrade_radii(radii, "wgpu_fill_rect_gradient_radii_dropped");
                        }
                        GradientKind::Radial(_) | GradientKind::Sweep(_) => {
                            // Stage 1b — InstancedRenderContext has no
                            // radial/sweep gradient API; degrade to solid
                            // using the first stop colour.
                            let c = grad.stops.first()
                                .map(|s| s.color.to_alpha_color::<peniko::color::Srgb>())
                                .unwrap_or(Color::from_rgba8(0,0,0,0));
                            ctx.set_fill_color(&color_to_css(c));
                            if let Some(r) = radii.filter(|r| r.iter().any(|v| *v > 0.0)) {
                                ctx.fill_rounded_rect(x, y, w, h, r[0] as f64);
                            } else {
                                ctx.fill_rect(x, y, w, h);
                            }
                            metrics::counter!(
                                KEY_RENDER_PRIMITIVES,
                                "kind" => "wgpu_fill_rect_radial_or_sweep_to_solid",
                            ).increment(1);
                        }
                    },
                    Brush::Image(_) => {
                        // Stage 1b — image brushes require atlas wire.
                        metrics::counter!(
                            KEY_RENDER_PRIMITIVES,
                            "kind" => "wgpu_fill_rect_image_dropped",
                        ).increment(1);
                    }
                }
                unapply_transform(ctx, transform);
            }
            DrawCommand::StrokeRect { rect, radii, stroke, brush, transform } => {
                apply_transform(ctx, transform);
                let color = brush_to_solid_color(brush);
                ctx.set_stroke_color(&color_to_css(color));
                ctx.set_stroke_width(stroke.width as f64);
                let (x, y, w, h) = (rect.x0, rect.y0, rect.width(), rect.height());
                if let Some(r) = radii.filter(|r| r.iter().any(|v| *v > 0.0)) {
                    ctx.stroke_rounded_rect(x, y, w, h, r[0] as f64);
                } else {
                    ctx.stroke_rect(x, y, w, h);
                }
                unapply_transform(ctx, transform);
            }
            DrawCommand::Line { from, to, stroke, brush, transform } => {
                let color = brush_to_solid_color(brush);
                ctx.set_stroke_color(&color_to_css(color));
                ctx.set_stroke_width(stroke.width as f64);
                apply_transform(ctx, transform);
                ctx.begin_path();
                ctx.move_to(from.x, from.y);
                ctx.line_to(to.x, to.y);
                ctx.stroke();
                unapply_transform(ctx, transform);
            }
            DrawCommand::LineBatch { segments, stroke, brush, transform } => {
                let color = brush_to_solid_color(brush);
                ctx.set_stroke_color(&color_to_css(color));
                ctx.set_stroke_width(stroke.width as f64);
                apply_transform(ctx, transform);
                ctx.begin_path();
                for segment in segments {
                    ctx.move_to(segment.from.x, segment.from.y);
                    ctx.line_to(segment.to.x, segment.to.y);
                }
                ctx.stroke();
                unapply_transform(ctx, transform);
            }
            DrawCommand::FillPath { path, rule: _rule, brush, transform } => {
                let color = brush_to_solid_color(brush);
                ctx.set_fill_color(&color_to_css(color));
                apply_transform(ctx, transform);
                ctx.begin_path();
                emit_path_into_ctx(path, ctx);
                ctx.fill();
                unapply_transform(ctx, transform);
            }
            DrawCommand::StrokePath { path, stroke, brush, transform } => {
                let color = brush_to_solid_color(brush);
                ctx.set_stroke_color(&color_to_css(color));
                ctx.set_stroke_width(stroke.width as f64);
                apply_transform(ctx, transform);
                ctx.begin_path();
                emit_path_into_ctx(path, ctx);
                ctx.stroke();
                unapply_transform(ctx, transform);
            }
            DrawCommand::GlyphRun { glyphs: _, font: _, font_size, brush, transform, text } => {
                match text {
                    // Stage 2 (Wave 0 of the URX family-parity plan,
                    // 2026-07-24): the `text` source-string companion the
                    // IR grew for exactly this round-trip now reaches the
                    // instanced backend's EXISTING GPU glyph atlas via
                    // `fill_text`. The run origin is the transform's own
                    // translation (same convention `uzor-urx-cpu`'s
                    // `draw_glyph_run` reads); `FontId` → family
                    // resolution is not wired at this layer yet (default
                    // family, size honored) — a documented approximation
                    // the Wave 2 native glyph-id atlas removes.
                    Some(s) if !s.is_empty() => {
                        let color = brush_to_solid_color(brush);
                        ctx.set_fill_color(&color_to_css(color));
                        ctx.set_font(&format!("{font_size}px sans-serif"));
                        apply_transform(ctx, transform);
                        ctx.fill_text(s, 0.0, 0.0);
                        unapply_transform(ctx, transform);
                    }
                    // A pre-shaped glyph-id-only run (no source string)
                    // still degrades, counted — closing it needs the
                    // native atlas keyed by (FontId, glyph_id) (Wave 2).
                    _ => {
                        metrics::counter!(
                            uzor_urx_core::metrics_keys::KEY_RENDER_PRIMITIVES,
                            "kind" => "wgpu_glyphrun_dropped",
                        ).increment(1);
                    }
                }
            }
            DrawCommand::Image { .. } => {
                // Stage 1b — image atlas wire.
                metrics::counter!(
                    uzor_urx_core::metrics_keys::KEY_RENDER_PRIMITIVES,
                    "kind" => "wgpu_image_dropped",
                ).increment(1);
            }
            DrawCommand::PushClipRect { rect, transform } => {
                apply_transform(ctx, transform);
                ctx.save();
                ctx.begin_path();
                ctx.move_to(rect.x0, rect.y0);
                ctx.line_to(rect.x1, rect.y0);
                ctx.line_to(rect.x1, rect.y1);
                ctx.line_to(rect.x0, rect.y1);
                ctx.close_path();
                ctx.clip();
                clip_depth += 1;
                unapply_transform(ctx, transform);
            }
            DrawCommand::PushClipRoundedRect { rect, transform } => {
                // Stage 1a — approximate rounded clip with the bounding rect.
                // True rounded clip needs stencil — Stage 1b.
                apply_transform(ctx, transform);
                ctx.save();
                ctx.begin_path();
                let r = rect.rect();
                ctx.move_to(r.x0, r.y0);
                ctx.line_to(r.x1, r.y0);
                ctx.line_to(r.x1, r.y1);
                ctx.line_to(r.x0, r.y1);
                ctx.close_path();
                ctx.clip();
                clip_depth += 1;
                metrics::counter!(
                    uzor_urx_core::metrics_keys::KEY_RENDER_PRIMITIVES,
                    "kind" => "wgpu_rounded_clip_to_rect_bbox",
                ).increment(1);
                unapply_transform(ctx, transform);
            }
            DrawCommand::PopClip => {
                if clip_depth > 0 {
                    ctx.restore();
                    clip_depth -= 1;
                }
            }
            DrawCommand::PushBlendLayer { .. } | DrawCommand::PopBlendLayer => {
                // Stage 2 IR additions — non-SrcOver blend modes on the
                // wgpu adapter require offscreen-target lift, which the
                // underlying InstancedRenderContext doesn't expose yet.
                // Drop silently; Stage 1b's native pipeline rewrite owns
                // the proper implementation.
                metrics::counter!(
                    uzor_urx_core::metrics_keys::KEY_RENDER_PRIMITIVES,
                    "kind" => "wgpu_blend_layer_dropped",
                ).increment(1);
            }
        }
    }
    while clip_depth > 0 {
        ctx.restore();
        clip_depth -= 1;
    }

    let elapsed_us = t0.elapsed().as_micros() as u64;
    metrics::histogram!(render_submit_count_key("urx_wgpu_adapt")).record(elapsed_us as f64);
    metrics::counter!(KEY_RENDER_PRIMITIVES).increment(scene.commands.len() as u64);
}

#[inline]
fn degrade_radii(radii: &Option<[f32; 4]>, label: &'static str) {
    if let Some(r) = radii {
        if r.iter().any(|v| *v > 0.0) {
            metrics::counter!(
                uzor_urx_core::metrics_keys::KEY_RENDER_PRIMITIVES,
                "kind" => label,
            ).increment(1);
        }
    }
}

/// Emit a kurbo `BezPath` into an `InstancedRenderContext` via the
/// Painter trait. Quadratic/cubic curves flattened on our side
/// (the underlying ctx only exposes move_to/line_to). Tolerance
/// matches urx-cpu (0.25 px).
fn emit_path_into_ctx(path: &BezPath, ctx: &mut InstancedRenderContext) {
    kurbo::flatten(path.elements().iter().copied(), 0.25, |el| {
        match el {
            PathEl::MoveTo(p) => { ctx.move_to(p.x, p.y); }
            PathEl::LineTo(p) => { ctx.line_to(p.x, p.y); }
            PathEl::ClosePath => { ctx.close_path(); }
            _ => {}
        }
    });
}

#[inline]
fn brush_to_solid_color(brush: &Brush) -> Color {
    match brush {
        Brush::Solid(c)    => *c,
        Brush::Gradient(g) => g.stops.first()
            .map(|s| s.color.to_alpha_color::<peniko::color::Srgb>())
            .unwrap_or(Color::from_rgba8(0, 0, 0, 0)),
        Brush::Image(_)    => Color::from_rgba8(0, 0, 0, 0),
    }
}

#[inline]
fn color_to_css(c: Color) -> String {
    let p = c.to_rgba8();
    format!("rgba({},{},{},{})", p.r, p.g, p.b, (p.a as f64) / 255.0)
}

/// Apply a kurbo `Affine` to the context's transform via the small set
/// of methods exposed by `Painter` (translate/rotate/scale/save+restore).
/// We decompose to translate+scale only — full affine support would
/// require the underlying context to grow a `set_transform([f32;6])`
/// method (deferred to Stage 1b).
fn apply_transform(ctx: &mut InstancedRenderContext, t: &Affine) {
    if *t == Affine::IDENTITY { return; }
    ctx.save();
    let c = t.as_coeffs();
    let (sx, sy, tx, ty) = (c[0], c[3], c[4], c[5]);
    if tx != 0.0 || ty != 0.0 { ctx.translate(tx, ty); }
    if sx != 1.0 || sy != 1.0 { ctx.scale(sx, sy); }
}

fn unapply_transform(ctx: &mut InstancedRenderContext, t: &Affine) {
    if *t == Affine::IDENTITY { return; }
    ctx.restore();
}

/// Round-trip self-test: feed a 2-command Scene through adapt_scene_into
/// and verify the underlying context recorded the right number of
/// draw_commands.
#[cfg(test)]
mod tests {
    use super::*;
    use uzor_urx_core::math::{Rect, Vec2};
    use uzor_urx_core::scene::Stroke;

    #[test]
    fn adapt_emits_quad_for_fill_rect() {
        let mut ctx = InstancedRenderContext::new(100.0, 100.0, 0.0, 0.0);
        let mut scene = Scene::new();
        scene.push(DrawCommand::FillRect {
            rect: Rect::new(10.0, 10.0, 50.0, 50.0),
            radii: None,
            brush: Brush::Solid(Color::from_rgba8(255, 0, 0, 255)),
            transform: Affine::IDENTITY,
        });
        adapt_scene_into(&scene, &mut ctx);
        assert!(!ctx.draw_commands.is_empty());
    }

    #[test]
    fn adapt_emits_rounded_rect_for_radii() {
        let mut ctx = InstancedRenderContext::new(100.0, 100.0, 0.0, 0.0);
        let mut scene = Scene::new();
        scene.push(DrawCommand::FillRect {
            rect: Rect::new(10.0, 10.0, 50.0, 50.0),
            radii: Some([8.0, 8.0, 8.0, 8.0]),
            brush: Brush::Solid(Color::from_rgba8(255, 0, 0, 255)),
            transform: Affine::IDENTITY,
        });
        adapt_scene_into(&scene, &mut ctx);
        // Verifies the rounded-radius path doesn't degrade now.
        assert!(!ctx.draw_commands.is_empty());
    }

    #[test]
    fn adapt_emits_for_line() {
        let mut ctx = InstancedRenderContext::new(100.0, 100.0, 0.0, 0.0);
        let mut scene = Scene::new();
        scene.push(DrawCommand::Line {
            from: Vec2 { x: 5.0, y: 5.0 },
            to:   Vec2 { x: 50.0, y: 50.0 },
            stroke: Stroke { width: 2.0, ..Stroke::default() },
            brush: Brush::Solid(Color::from_rgba8(0, 255, 0, 255)),
            transform: Affine::IDENTITY,
        });
        adapt_scene_into(&scene, &mut ctx);
        assert!(!ctx.draw_commands.is_empty());
    }

    /// Wave 0 gate (URX family-parity plan 2026-07-24): a `GlyphRun`
    /// carrying its `text` source-string companion must reach the
    /// instanced backend's atlas text path as a real `DrawCmd::Text`
    /// (correct string, size, run-origin position from the transform) —
    /// not the counted `wgpu_glyphrun_dropped` degrade.
    #[test]
    fn adapt_routes_glyph_run_with_text_companion_to_the_atlas_text_path() {
        let mut ctx = InstancedRenderContext::new(200.0, 100.0, 0.0, 0.0);
        let mut scene = Scene::new();
        scene.push(DrawCommand::GlyphRun {
            glyphs: vec![],
            font: uzor_urx_core::scene::FontId(0),
            font_size: 24.0,
            brush: Brush::Solid(Color::from_rgba8(255, 255, 255, 255)),
            transform: Affine::translate((15.0, 60.0)),
            text: Some("hello".to_owned()),
        });
        adapt_scene_into(&scene, &mut ctx);
        let text_cmds: Vec<_> = ctx
            .draw_commands
            .iter()
            .filter_map(|c| match c {
                uzor_render_wgpu_instanced::DrawCmd::Text(t) => Some(t),
                _ => None,
            })
            .collect();
        assert_eq!(text_cmds.len(), 1, "exactly one Text draw command must be emitted");
        assert_eq!(text_cmds[0].text, "hello");
        assert_eq!(text_cmds[0].font_size, 24.0);
        assert!(
            (text_cmds[0].x - 15.0).abs() < 0.01 && (text_cmds[0].y - 60.0).abs() < 0.01,
            "run origin must come from the transform translation, got ({}, {})",
            text_cmds[0].x,
            text_cmds[0].y
        );
    }

    /// A pre-shaped glyph-id-only run (no `text` companion) still
    /// degrades (counted) — the Wave 2 native atlas closes that half.
    #[test]
    fn adapt_still_degrades_a_glyph_id_only_run_without_text() {
        let mut ctx = InstancedRenderContext::new(200.0, 100.0, 0.0, 0.0);
        let mut scene = Scene::new();
        scene.push(DrawCommand::GlyphRun {
            glyphs: vec![uzor_urx_core::scene::Glyph { glyph_id: 36, x: 0.0, y: 0.0 }],
            font: uzor_urx_core::scene::FontId(0),
            font_size: 24.0,
            brush: Brush::Solid(Color::from_rgba8(255, 255, 255, 255)),
            transform: Affine::IDENTITY,
            text: None,
        });
        adapt_scene_into(&scene, &mut ctx);
        assert!(
            !ctx.draw_commands.iter().any(|c| matches!(c, uzor_render_wgpu_instanced::DrawCmd::Text(_))),
            "a glyph-id-only run must not fabricate a Text command"
        );
    }

    #[test]
    fn adapt_balances_clip_stack() {
        let mut ctx = InstancedRenderContext::new(100.0, 100.0, 0.0, 0.0);
        let mut scene = Scene::new();
        scene.push(DrawCommand::PushClipRect {
            rect: Rect::new(0.0, 0.0, 50.0, 50.0),
            transform: Affine::IDENTITY,
        });
        // Missing PopClip — adapter must balance defensively.
        adapt_scene_into(&scene, &mut ctx);
    }
}