Skip to main content

velox_engine/
vector_canvas.rs

1//! 原生 2D 矢量画布原语(`VectorCanvas` / `Polyline` / `Polygon` / `Circle` / `Sector`)。
2//!
3//! 面向实时波形图、折线图、仪表盘、雷达/海图矢量轨迹等高频动态矢量绘制场景:
4//! - 100% 无堆兼容,数据全部驻留当前帧 `ScratchArena`,通过 8B 引用挂入 `DrawPayload::Vector`;
5//! - 彻底规避每帧拼接 SVG 字符串的开销,软件端与 GPU 端均提供原生抗锯齿绘制。
6
7use crate::display::PixelFormat;
8use crate::element::{Element, IntoElement};
9use crate::pod::FrameScope;
10use crate::solver::Region;
11use crate::style::Color;
12use crate::svg::math::{atan2_f32, floor_f32, sqrt_f32};
13
14/// 二维局部浮点坐标点(相对于 `VectorCanvas` 盒子左上角,单位逻辑像素)。
15#[derive(Copy, Clone, Debug, Default)]
16pub struct VecPoint {
17    pub x: f32,
18    pub y: f32,
19}
20
21impl VecPoint {
22    #[inline(always)]
23    pub const fn new(x: f32, y: f32) -> Self {
24        Self { x, y }
25    }
26}
27
28#[inline(always)]
29fn canon_f32(v: f32) -> u32 {
30    if v == 0.0 { 0 } else { v.to_bits() }
31}
32
33impl PartialEq for VecPoint {
34    #[inline(always)]
35    fn eq(&self, other: &Self) -> bool {
36        canon_f32(self.x) == canon_f32(other.x) && canon_f32(self.y) == canon_f32(other.y)
37    }
38}
39
40impl Eq for VecPoint {}
41
42/// 单个矢量画布绘制图元。
43#[derive(Copy, Clone, Debug)]
44pub enum VectorPrimitive<'a> {
45    /// 抗锯齿折线 / 虚线 / 闭合折线环(支持自定义线宽、圆头与虚线样式)。
46    Polyline {
47        points: &'a [VecPoint],
48        color: Color,
49        width: f32,
50        dash_len: f32,
51        gap_len: f32,
52        closed: bool,
53    },
54    /// 任意多边形填充与可选描边(扫描线奇偶规则抗锯齿填充)。
55    Polygon {
56        points: &'a [VecPoint],
57        fill: Color,
58        stroke: Color,
59        stroke_width: f32,
60    },
61    /// 解析 SDF 抗锯齿实心圆 / 圆环。
62    Circle {
63        cx: f32,
64        cy: f32,
65        radius: f32,
66        fill: Color,
67        stroke: Color,
68        stroke_width: f32,
69    },
70    /// 解析 SDF 扇形 / 环扇(角度单位度,0° 为 12 点钟方向顺时针递增)。
71    Sector {
72        cx: f32,
73        cy: f32,
74        inner_r: f32,
75        outer_r: f32,
76        start_deg: f32,
77        sweep_deg: f32,
78        fill: Color,
79    },
80}
81
82impl<'a> PartialEq for VectorPrimitive<'a> {
83    fn eq(&self, other: &Self) -> bool {
84        match (*self, *other) {
85            (
86                Self::Polyline {
87                    points: p1,
88                    color: c1,
89                    width: w1,
90                    dash_len: d1,
91                    gap_len: g1,
92                    closed: cl1,
93                },
94                Self::Polyline {
95                    points: p2,
96                    color: c2,
97                    width: w2,
98                    dash_len: d2,
99                    gap_len: g2,
100                    closed: cl2,
101                },
102            ) => {
103                p1 == p2
104                    && c1 == c2
105                    && canon_f32(w1) == canon_f32(w2)
106                    && canon_f32(d1) == canon_f32(d2)
107                    && canon_f32(g1) == canon_f32(g2)
108                    && cl1 == cl2
109            }
110            (
111                Self::Polygon {
112                    points: p1,
113                    fill: f1,
114                    stroke: s1,
115                    stroke_width: sw1,
116                },
117                Self::Polygon {
118                    points: p2,
119                    fill: f2,
120                    stroke: s2,
121                    stroke_width: sw2,
122                },
123            ) => p1 == p2 && f1 == f2 && s1 == s2 && canon_f32(sw1) == canon_f32(sw2),
124            (
125                Self::Circle {
126                    cx: x1,
127                    cy: y1,
128                    radius: r1,
129                    fill: f1,
130                    stroke: s1,
131                    stroke_width: sw1,
132                },
133                Self::Circle {
134                    cx: x2,
135                    cy: y2,
136                    radius: r2,
137                    fill: f2,
138                    stroke: s2,
139                    stroke_width: sw2,
140                },
141            ) => {
142                canon_f32(x1) == canon_f32(x2)
143                    && canon_f32(y1) == canon_f32(y2)
144                    && canon_f32(r1) == canon_f32(r2)
145                    && f1 == f2
146                    && s1 == s2
147                    && canon_f32(sw1) == canon_f32(sw2)
148            }
149            (
150                Self::Sector {
151                    cx: x1,
152                    cy: y1,
153                    inner_r: ir1,
154                    outer_r: or1,
155                    start_deg: sd1,
156                    sweep_deg: sw1,
157                    fill: f1,
158                },
159                Self::Sector {
160                    cx: x2,
161                    cy: y2,
162                    inner_r: ir2,
163                    outer_r: or2,
164                    start_deg: sd2,
165                    sweep_deg: sw2,
166                    fill: f2,
167                },
168            ) => {
169                canon_f32(x1) == canon_f32(x2)
170                    && canon_f32(y1) == canon_f32(y2)
171                    && canon_f32(ir1) == canon_f32(ir2)
172                    && canon_f32(or1) == canon_f32(or2)
173                    && canon_f32(sd1) == canon_f32(sd2)
174                    && canon_f32(sw1) == canon_f32(sw2)
175                    && f1 == f2
176            }
177            _ => false,
178        }
179    }
180}
181
182impl<'a> Eq for VectorPrimitive<'a> {}
183
184/// 矢量画布绘制载荷(分配于 `ScratchArena`,通过 8B 引用挂入 `DrawPayload::Vector`)。
185#[derive(Copy, Clone, PartialEq, Eq, Debug)]
186pub struct VectorDrawSpec<'a> {
187    pub primitives: &'a [VectorPrimitive<'a>],
188    pub width: i16,
189    pub height: i16,
190    pub opacity: u8,
191}
192
193impl<'a> VectorDrawSpec<'a> {
194    pub fn mix_hash(&self, h: &mut u32) {
195        #[inline(always)]
196        fn mix_u8(h: &mut u32, b: u8) {
197            *h ^= b as u32;
198            *h = h.wrapping_mul(0x0100_0193);
199        }
200        #[inline(always)]
201        fn mix_u32(h: &mut u32, v: u32) {
202            for b in v.to_le_bytes() {
203                mix_u8(h, b);
204            }
205        }
206        mix_u32(
207            h,
208            ((self.width as u16 as u32) << 16) | (self.height as u16 as u32),
209        );
210        mix_u8(h, self.opacity);
211        for p in self.primitives {
212            match *p {
213                VectorPrimitive::Polyline {
214                    points,
215                    color,
216                    width,
217                    dash_len,
218                    gap_len,
219                    closed,
220                } => {
221                    mix_u8(h, 1);
222                    mix_u32(h, color.0);
223                    mix_u32(h, canon_f32(width));
224                    mix_u32(h, canon_f32(dash_len));
225                    mix_u32(h, canon_f32(gap_len));
226                    mix_u8(h, if closed { 1 } else { 0 });
227                    for pt in points {
228                        mix_u32(h, canon_f32(pt.x));
229                        mix_u32(h, canon_f32(pt.y));
230                    }
231                }
232                VectorPrimitive::Polygon {
233                    points,
234                    fill,
235                    stroke,
236                    stroke_width,
237                } => {
238                    mix_u8(h, 2);
239                    mix_u32(h, fill.0);
240                    mix_u32(h, stroke.0);
241                    mix_u32(h, canon_f32(stroke_width));
242                    for pt in points {
243                        mix_u32(h, canon_f32(pt.x));
244                        mix_u32(h, canon_f32(pt.y));
245                    }
246                }
247                VectorPrimitive::Circle {
248                    cx,
249                    cy,
250                    radius,
251                    fill,
252                    stroke,
253                    stroke_width,
254                } => {
255                    mix_u8(h, 3);
256                    mix_u32(h, canon_f32(cx));
257                    mix_u32(h, canon_f32(cy));
258                    mix_u32(h, canon_f32(radius));
259                    mix_u32(h, fill.0);
260                    mix_u32(h, stroke.0);
261                    mix_u32(h, canon_f32(stroke_width));
262                }
263                VectorPrimitive::Sector {
264                    cx,
265                    cy,
266                    inner_r,
267                    outer_r,
268                    start_deg,
269                    sweep_deg,
270                    fill,
271                } => {
272                    mix_u8(h, 4);
273                    mix_u32(h, canon_f32(cx));
274                    mix_u32(h, canon_f32(cy));
275                    mix_u32(h, canon_f32(inner_r));
276                    mix_u32(h, canon_f32(outer_r));
277                    mix_u32(h, canon_f32(start_deg));
278                    mix_u32(h, canon_f32(sweep_deg));
279                    mix_u32(h, fill.0);
280                }
281            }
282        }
283    }
284}
285
286/// 声明式原生 2D 矢量画布元素。
287#[derive(Copy, Clone, Debug)]
288pub struct VectorCanvas<'a> {
289    pub spec: VectorDrawSpec<'a>,
290}
291
292/// 构造一个 2D 矢量画布元素(图元切片自动分配于当前帧 `ScratchArena`)。
293#[inline]
294pub fn vector_canvas<'a>(
295    cx: &'a FrameScope,
296    width: i16,
297    height: i16,
298    primitives: &[VectorPrimitive<'a>],
299) -> VectorCanvas<'a> {
300    let alloc = cx.arena().alloc_iter(primitives.iter().copied());
301    VectorCanvas {
302        spec: VectorDrawSpec {
303            primitives: alloc,
304            width,
305            height,
306            opacity: 255,
307        },
308    }
309}
310
311impl<'a> VectorCanvas<'a> {
312    #[inline(always)]
313    pub const fn opacity(mut self, opacity: u8) -> Self {
314        self.spec.opacity = opacity;
315        self
316    }
317}
318
319impl<'a> IntoElement<'a> for VectorCanvas<'a> {
320    #[inline]
321    fn into_element(self, cx: &'a FrameScope) -> Element<'a> {
322        let spec_ref = cx.arena().alloc_temp(self.spec);
323        Element::Vector(spec_ref)
324    }
325}
326
327// ============================================================================
328// 跨平台抗锯齿软件光栅器(纯数学 SDF + 奇偶填充,100% 无堆)
329// ============================================================================
330
331#[inline]
332fn blend_cov_pixel<P: PixelFormat>(target: &mut [P], idx: usize, color: Color, cov: f32) {
333    let a = ((color.a() as f32) * cov.clamp(0.0, 1.0) + 0.5) as u8;
334    if a == 0 {
335        return;
336    }
337    if let Some(dst) = target.get_mut(idx) {
338        let blended = crate::sdf::blend_color(dst.to_color(), color, a);
339        *dst = P::from_color(blended);
340    }
341}
342
343#[inline]
344fn dist_point_to_segment(px: f32, py: f32, ax: f32, ay: f32, bx: f32, by: f32) -> (f32, f32) {
345    let vx = bx - ax;
346    let vy = by - ay;
347    let len2 = vx * vx + vy * vy;
348    if len2 <= 1e-6 {
349        let dx = px - ax;
350        let dy = py - ay;
351        return (sqrt_f32(dx * dx + dy * dy), 0.0);
352    }
353    let t = (((px - ax) * vx + (py - ay) * vy) / len2).clamp(0.0, 1.0);
354    let dx = px - (ax + vx * t);
355    let dy = py - (ay + vy * t);
356    (sqrt_f32(dx * dx + dy * dy), t * sqrt_f32(len2))
357}
358
359#[allow(clippy::too_many_arguments)]
360fn rasterize_polyline<P: PixelFormat>(
361    points: &[VecPoint],
362    color: Color,
363    width: f32,
364    dash_len: f32,
365    gap_len: f32,
366    closed: bool,
367    bounds: Region,
368    vis: Region,
369    sf: f32,
370    origin_x: i16,
371    origin_y: i16,
372    stride: usize,
373    target: &mut [P],
374) {
375    if points.len() < 2 || color.a() == 0 || width <= 0.0 {
376        return;
377    }
378    let half_w = (width * sf * 0.5).max(0.5);
379    let bx0 = bounds.x as f32;
380    let by0 = bounds.y as f32;
381    let seg_count = if closed { points.len() } else { points.len() - 1 };
382    let dash_period = if dash_len > 0.0 && gap_len > 0.0 {
383        (dash_len + gap_len) * sf
384    } else {
385        0.0
386    };
387    let dash_on = dash_len * sf;
388    let mut accum_len = 0.0f32;
389
390    for s in 0..seg_count {
391        let p0 = points[s];
392        let p1 = points[(s + 1) % points.len()];
393        let ax = bx0 + p0.x * sf;
394        let ay = by0 + p0.y * sf;
395        let bx = bx0 + p1.x * sf;
396        let by = by0 + p1.y * sf;
397        let seg_len = sqrt_f32((bx - ax) * (bx - ax) + (by - ay) * (by - ay));
398
399        let pad = half_w + 1.5;
400        let min_x = (floor_f32(ax.min(bx) - pad) as i16).max(vis.x);
401        let max_x = ((ax.max(bx) + pad) as i16 + 1).min(vis.right());
402        let min_y = (floor_f32(ay.min(by) - pad) as i16).max(vis.y);
403        let max_y = ((ay.max(by) + pad) as i16 + 1).min(vis.bottom());
404
405        for py in min_y..max_y {
406            let row_off = ((py - origin_y) as usize) * stride;
407            let cy = py as f32 + 0.5;
408            for px in min_x..max_x {
409                let cx = px as f32 + 0.5;
410                let (d, along) = dist_point_to_segment(cx, cy, ax, ay, bx, by);
411                let cov = (half_w + 0.5 - d).clamp(0.0, 1.0);
412                if cov <= 0.0 {
413                    continue;
414                }
415                if dash_period > 0.0 {
416                    let phase = (accum_len + along) % dash_period;
417                    if phase > dash_on {
418                        continue;
419                    }
420                }
421                blend_cov_pixel(target, row_off + ((px - origin_x) as usize), color, cov);
422            }
423        }
424        accum_len += seg_len;
425    }
426}
427
428#[allow(clippy::too_many_arguments)]
429fn rasterize_polygon<P: PixelFormat>(
430    points: &[VecPoint],
431    fill: Color,
432    stroke: Color,
433    stroke_width: f32,
434    bounds: Region,
435    vis: Region,
436    sf: f32,
437    origin_x: i16,
438    origin_y: i16,
439    stride: usize,
440    target: &mut [P],
441) {
442    if points.len() < 3 {
443        return;
444    }
445    let bx0 = bounds.x as f32;
446    let by0 = bounds.y as f32;
447    if fill.a() > 0 {
448        let mut min_x = f32::INFINITY;
449        let mut max_x = f32::NEG_INFINITY;
450        let mut min_y = f32::INFINITY;
451        let mut max_y = f32::NEG_INFINITY;
452        for pt in points {
453            let x = bx0 + pt.x * sf;
454            let y = by0 + pt.y * sf;
455            min_x = min_x.min(x);
456            max_x = max_x.max(x);
457            min_y = min_y.min(y);
458            max_y = max_y.max(y);
459        }
460        let x0 = (floor_f32(min_x) as i16).max(vis.x);
461        let x1 = (max_x as i16 + 1).min(vis.right());
462        let y0 = (floor_f32(min_y) as i16).max(vis.y);
463        let y1 = (max_y as i16 + 1).min(vis.bottom());
464
465        for py in y0..y1 {
466            let row_off = ((py - origin_y) as usize) * stride;
467            let cy = py as f32 + 0.5;
468            for px in x0..x1 {
469                let cx = px as f32 + 0.5;
470                // 奇偶射线法
471                let mut inside = false;
472                let mut j = points.len() - 1;
473                for i in 0..points.len() {
474                    let xi = bx0 + points[i].x * sf;
475                    let yi = by0 + points[i].y * sf;
476                    let xj = bx0 + points[j].x * sf;
477                    let yj = by0 + points[j].y * sf;
478                    let cond = ((yi > cy) != (yj > cy))
479                        && (cx < (xj - xi) * (cy - yi) / ((yj - yi) + 1e-7) + xi);
480                    if cond {
481                        inside = !inside;
482                    }
483                    j = i;
484                }
485                if inside {
486                    blend_cov_pixel(target, row_off + ((px - origin_x) as usize), fill, 1.0);
487                }
488            }
489        }
490    }
491    if stroke.a() > 0 && stroke_width > 0.0 {
492        rasterize_polyline(
493            points,
494            stroke,
495            stroke_width,
496            0.0,
497            0.0,
498            true,
499            bounds,
500            vis,
501            sf,
502            origin_x,
503            origin_y,
504            stride,
505            target,
506        );
507    }
508}
509
510/// 将 [`VectorDrawSpec`] 光栅化至目标像素缓冲(支持任意 HiDPI 缩放与裁剪框)。
511#[allow(clippy::too_many_arguments)]
512pub fn rasterize_vector_spec<P: PixelFormat>(
513    spec: &VectorDrawSpec<'_>,
514    bounds: Region,
515    clip: Region,
516    sf: f32,
517    origin_x: i16,
518    origin_y: i16,
519    stride: usize,
520    target: &mut [P],
521) {
522    let vis = bounds.intersect(clip);
523    if vis.is_empty() || spec.opacity == 0 {
524        return;
525    }
526    let scale_c = |c: Color| c.scale_alpha(spec.opacity);
527    let bx0 = bounds.x as f32;
528    let by0 = bounds.y as f32;
529
530    for prim in spec.primitives {
531        match *prim {
532            VectorPrimitive::Polyline {
533                points,
534                color,
535                width,
536                dash_len,
537                gap_len,
538                closed,
539            } => rasterize_polyline(
540                points,
541                scale_c(color),
542                width,
543                dash_len,
544                gap_len,
545                closed,
546                bounds,
547                vis,
548                sf,
549                origin_x,
550                origin_y,
551                stride,
552                target,
553            ),
554            VectorPrimitive::Polygon {
555                points,
556                fill,
557                stroke,
558                stroke_width,
559            } => rasterize_polygon(
560                points,
561                scale_c(fill),
562                scale_c(stroke),
563                stroke_width,
564                bounds,
565                vis,
566                sf,
567                origin_x,
568                origin_y,
569                stride,
570                target,
571            ),
572            VectorPrimitive::Circle {
573                cx,
574                cy,
575                radius,
576                fill,
577                stroke,
578                stroke_width,
579            } => {
580                let ccx = bx0 + cx * sf;
581                let ccy = by0 + cy * sf;
582                let r = radius * sf;
583                let sw = stroke_width * sf;
584                let outer = r + sw * 0.5 + 1.5;
585                let x0 = (floor_f32(ccx - outer) as i16).max(vis.x);
586                let x1 = ((ccx + outer) as i16 + 1).min(vis.right());
587                let y0 = (floor_f32(ccy - outer) as i16).max(vis.y);
588                let y1 = ((ccy + outer) as i16 + 1).min(vis.bottom());
589                let fcol = scale_c(fill);
590                let scol = scale_c(stroke);
591
592                for py in y0..y1 {
593                    let row_off = ((py - origin_y) as usize) * stride;
594                    let dy = py as f32 + 0.5 - ccy;
595                    for px in x0..x1 {
596                        let dx = px as f32 + 0.5 - ccx;
597                        let dist = sqrt_f32(dx * dx + dy * dy);
598                        let idx = row_off + ((px - origin_x) as usize);
599                        if fcol.a() > 0 {
600                            let cov = (r + 0.5 - dist).clamp(0.0, 1.0);
601                            if cov > 0.0 {
602                                blend_cov_pixel(target, idx, fcol, cov);
603                            }
604                        }
605                        if scol.a() > 0 && sw > 0.0 {
606                            let sd = crate::svg::math::abs_f32(dist - r);
607                            let cov = (sw * 0.5 + 0.5 - sd).clamp(0.0, 1.0);
608                            if cov > 0.0 {
609                                blend_cov_pixel(target, idx, scol, cov);
610                            }
611                        }
612                    }
613                }
614            }
615            VectorPrimitive::Sector {
616                cx,
617                cy,
618                inner_r,
619                outer_r,
620                start_deg,
621                sweep_deg,
622                fill,
623            } => {
624                let fcol = scale_c(fill);
625                if fcol.a() == 0 || outer_r <= inner_r || sweep_deg <= 0.0 {
626                    continue;
627                }
628                let ccx = bx0 + cx * sf;
629                let ccy = by0 + cy * sf;
630                let ir = inner_r.max(0.0) * sf;
631                let or = outer_r * sf;
632                let pad = or + 1.5;
633                let x0 = (floor_f32(ccx - pad) as i16).max(vis.x);
634                let x1 = ((ccx + pad) as i16 + 1).min(vis.right());
635                let y0 = (floor_f32(ccy - pad) as i16).max(vis.y);
636                let y1 = ((ccy + pad) as i16 + 1).min(vis.bottom());
637                let start_n = ((start_deg % 360.0) + 360.0) % 360.0;
638                let sweep_c = sweep_deg.clamp(0.0, 360.0);
639
640                for py in y0..y1 {
641                    let row_off = ((py - origin_y) as usize) * stride;
642                    let dy = py as f32 + 0.5 - ccy;
643                    for px in x0..x1 {
644                        let dx = px as f32 + 0.5 - ccx;
645                        let dist = sqrt_f32(dx * dx + dy * dy);
646                        let cov_r = (or + 0.5 - dist).min(dist - ir + 0.5).clamp(0.0, 1.0);
647                        if cov_r <= 0.0 {
648                            continue;
649                        }
650                        if sweep_c < 359.9 {
651                            // 0° 为 12 点钟方向顺时针
652                            let mut ang = atan2_f32(dx, -dy) * (180.0 / core::f32::consts::PI);
653                            if ang < 0.0 {
654                                ang += 360.0;
655                            }
656                            let rel = ((ang - start_n) + 360.0) % 360.0;
657                            if rel > sweep_c {
658                                continue;
659                            }
660                        }
661                        blend_cov_pixel(
662                            target,
663                            row_off + ((px - origin_x) as usize),
664                            fcol,
665                            cov_r,
666                        );
667                    }
668                }
669            }
670        }
671    }
672}