1#![no_std]
33#![forbid(unsafe_code)]
34
35extern crate alloc;
36
37use alloc::sync::Arc;
38
39use gpu::*;
40
41mod atlas;
42mod block;
43pub mod curve;
44pub mod dxf;
45mod dxftext;
46pub mod fill;
47mod geo;
48mod index;
49pub mod math;
50pub mod msdf;
51mod scene;
52pub mod text;
53
54pub use scene::{Block, BlockId, Camera, Cap, EntityId, FrameStats, HatchLine, Insert, InstanceInfo, Join, Layer, LayerId, Scene, Shape, Style, StyleId, Transparency, Unit, UploadInfo, ARC_STEP,
55 BLOCK_DEPTH, BY_BLOCK_COLOR, BY_BLOCK_DASH, BY_BLOCK_WIDTH, DASH_MAX, HATCH_DASH_MAX, HATCH_MAX, TRANSPARENCY_MAX};
56pub use scene::{box_is_window, Grip, HighlightInfo, Hit, IndexInfo, Overlay, OverlayInfo, Region, SelectMode, Snap, SnapKind, SnapOptions, Space, Target, CROSSING_EDGE, CROSSING_FILL, GRIP_COLD, GRIP_EDGE,
58 GRIP_HOT, GRIP_HOVER, GRIP_PX, HL_ALPHA, HL_HOVER, HL_HOVER_RGB, HL_SELECTED, HL_SELECTED_RGB, MARKER_COLOR, MARKER_PX, MARKER_WIDTH, SNAP_ALL, SNAP_CEN, SNAP_END, SNAP_INS, SNAP_INT,
59 SNAP_MID, SNAP_NEA, SNAP_PER, SNAP_QUA, SNAP_TAN, WINDOW_EDGE, WINDOW_FILL};
60pub use scene::{TextInfo, TEXT_BAR_BELOW, TEXT_FILL_FROM, TEXT_LARGE_FROM};
61pub use scene::CpuInfo;
63pub use text::{layout_mtext, layout_text, Attach, Bar as TextBar, FontId, FontMetrics, Fonts, GlyphShape, HAlign, Layout as TextLayout, Line as TextLine, MText, Placed as PlacedGlyph, Text, TextStyle, TextStyleId,
64 VAlign, FALLBACK_MAX, LINE_SPACING};
65
66pub const FRAMES_MAX: usize = 3;
68pub const PAGE: u32 = 256;
70pub const BATCH: u32 = 16384;
72pub const LAYERS_MAX: u32 = 65535;
74
75pub(crate) const RECORD_WORDS: usize = 16;
76pub(crate) const RECORD_BYTES: u64 = 64;
77pub(crate) const STYLE_WORDS: usize = 32;
78pub(crate) const STYLE_BYTES: u64 = 128;
79pub(crate) const CHANGE_WORDS: usize = 20;
81pub(crate) const VIEW_BYTES: u64 = 80;
82pub(crate) const INST_WORDS: usize = 40;
84pub(crate) const INST_BYTES: u64 = 160;
85pub(crate) const SPACE_BYTES: u64 = 80;
86pub(crate) const ENTRY_BYTES: u64 = 16;
88pub(crate) const WG_INST: u32 = 64;
89pub(crate) const HATCH_WORDS: usize = 128;
91pub(crate) const HATCH_BYTES: u64 = 512;
92pub(crate) const DRAW_BYTES: u64 = 20;
93pub(crate) const STAMPS: u32 = 4;
95pub(crate) const WG_SCATTER: u32 = 64;
96
97fn scatter_chunk(l: &Limits) -> u32 {
100 let bytes = CHANGE_WORDS as u64 * 4;
101 let align = (l.min_storage_offset_alignment as u64).max(1);
102 let mut n = (l.max_compute_workgroups[0] as u64 * WG_SCATTER as u64).min(l.max_storage_binding as u64 / bytes).min(u32::MAX as u64 / 2).max(1);
103 while n > 1 && (n * bytes) % align != 0 {
104 n -= 1;
105 }
106 n as u32
107}
108
109#[cfg(not(target_arch = "wasm32"))]
112mod spv {
113 include!("shaders_spv.rs");
114}
115
116pub const COMMON_WGSL: &str = include_str!("common.wgsl");
119pub const BLOCK_WGSL: &str = include_str!("block.wgsl");
120pub const CULL_WGSL: &str = concat!(include_str!("common.wgsl"), include_str!("block.wgsl"), include_str!("textc.wgsl"), include_str!("cull.wgsl"));
121pub const SCATTER_WGSL: &str = concat!(include_str!("common.wgsl"), include_str!("scatter.wgsl"));
122pub const STROKE_WGSL: &str = concat!(include_str!("common.wgsl"), include_str!("block.wgsl"), include_str!("stroke.wgsl"), "\n@fragment\nfn fs_full(i: VsOut) -> @location(0) vec4f {\n",
123 include_str!("full_body.wgsl"), "}\n\nfn full_body(i: VsOut) -> vec4f {\n", include_str!("full_body.wgsl"), "}\n", include_str!("fill.wgsl"));
124pub const TEXT_WGSL: &str = concat!(include_str!("common.wgsl"), include_str!("block.wgsl"), include_str!("stroke.wgsl"), "\n@fragment\nfn fs_full(i: VsOut) -> @location(0) vec4f {\n",
127 include_str!("full_body.wgsl"), "}\n\nfn full_body(i: VsOut) -> vec4f {\n", include_str!("full_body.wgsl"), "}\n", include_str!("fill.wgsl"), include_str!("textc.wgsl"),
128 include_str!("text.wgsl"));
129pub const TEXTC_WGSL: &str = include_str!("textc.wgsl");
130pub const HL_WGSL: &str = include_str!("hl.wgsl");
133pub const HL_WRITE_WGSL: &str = include_str!("hl_write.wgsl");
134
135pub fn hl_wgsl(base: &str) -> alloc::string::String {
139 let mut s = base.replace("item_of(visible[l.x + j], l.x + j)", "item_of(hl_take(visible[l.x + j]), l.x + j)");
140 s = s.replace("fn ink(color: u32, t: u32, layer_t: u32) -> u32 {",
141 "fn ink(color: u32, t: u32, layer_t: u32) -> u32 {\n return hl_ink(ink_own(color, t, layer_t));\n}\n\nfn ink_own(color: u32, t: u32, layer_t: u32) -> u32 {");
142 s = s.replace("fn half_width(st: Style, view: View) -> f32 {",
143 "fn half_width(st: Style, view: View) -> f32 {\n return half_width_own(st, view) + hl_wider();\n}\n\nfn half_width_own(st: Style, view: View) -> f32 {");
144 s.push_str(HL_WGSL);
145 s
146}
147
148pub fn write_hl_wgsl() -> alloc::string::String {
150 let mut s = alloc::string::String::from(CULL_WGSL);
151 s.push_str(HL_WRITE_WGSL);
152 s
153}
154#[cfg(not(target_arch = "wasm32"))]
155pub const COUNT_SPV: &[u32] = spv::COUNT;
156#[cfg(not(target_arch = "wasm32"))]
157pub const SCAN_SPV: &[u32] = spv::SCAN;
158#[cfg(not(target_arch = "wasm32"))]
159pub const WRITE_SPV: &[u32] = spv::WRITE;
160#[cfg(not(target_arch = "wasm32"))]
161pub const INSTANCES_SPV: &[u32] = spv::INSTANCES;
162#[cfg(not(target_arch = "wasm32"))]
163pub const SCATTER_SPV: &[u32] = spv::SCATTER;
164#[cfg(not(target_arch = "wasm32"))]
165pub const VS_SPV: &[u32] = spv::VS;
166#[cfg(not(target_arch = "wasm32"))]
167pub const VS_FULL_SPV: &[u32] = spv::VS_FULL;
168#[cfg(not(target_arch = "wasm32"))]
169pub const FS_SPV: &[u32] = spv::FS;
170#[cfg(not(target_arch = "wasm32"))]
171pub const FS_FULL_SPV: &[u32] = spv::FS_FULL;
172#[cfg(not(target_arch = "wasm32"))]
173pub const VS_FILL_SPV: &[u32] = spv::VS_FILL;
174#[cfg(not(target_arch = "wasm32"))]
175pub const FS_FILL_SPV: &[u32] = spv::FS_FILL;
176#[cfg(not(target_arch = "wasm32"))]
177pub const VS_TEXT_SPV: &[u32] = spv::VS_TEXT;
178#[cfg(not(target_arch = "wasm32"))]
179pub const FS_TEXT_SPV: &[u32] = spv::FS_TEXT;
180#[cfg(not(target_arch = "wasm32"))]
181pub const VS_TEXT_ALL_SPV: &[u32] = spv::VS_TEXT_ALL;
182#[cfg(not(target_arch = "wasm32"))]
183pub const FS_TEXT_ALL_SPV: &[u32] = spv::FS_TEXT_ALL;
184#[cfg(not(target_arch = "wasm32"))]
186pub const VS_HL_SPV: &[u32] = spv::VS_HL;
187#[cfg(not(target_arch = "wasm32"))]
188pub const VS_FULL_HL_SPV: &[u32] = spv::VS_FULL_HL;
189#[cfg(not(target_arch = "wasm32"))]
190pub const VS_FILL_HL_SPV: &[u32] = spv::VS_FILL_HL;
191#[cfg(not(target_arch = "wasm32"))]
192pub const VS_TEXT_HL_SPV: &[u32] = spv::VS_TEXT_HL;
193#[cfg(not(target_arch = "wasm32"))]
194pub const VS_TEXT_ALL_HL_SPV: &[u32] = spv::VS_TEXT_ALL_HL;
195#[cfg(not(target_arch = "wasm32"))]
196pub const WRITE_HL_SPV: &[u32] = spv::WRITE_HL;
197
198#[derive(Clone, Copy, Debug)]
200#[non_exhaustive]
201pub struct RendererDesc {
202 pub color: Format,
204 pub frames_in_flight: usize,
206 pub separate_scratch: Option<bool>,
213}
214
215impl RendererDesc {
216 pub const fn new(color: Format) -> RendererDesc {
217 RendererDesc { color, frames_in_flight: 2, separate_scratch: None }
218 }
219}
220
221pub(crate) struct Tag;
223
224pub struct Renderer {
226 pub(crate) dev: Device,
227 pub(crate) desc: RendererDesc,
228 pub(crate) multi: bool,
230 pub(crate) separate: bool,
232 pub(crate) max_records: u32,
233 pub(crate) max_entries: u32,
234 pub(crate) scatter_chunk: u32,
237 pub(crate) tag: Arc<Tag>,
238 count: ComputePipeline,
239 scan: ComputePipeline,
240 write: ComputePipeline,
241 scatter: ComputePipeline,
242 instances: ComputePipeline,
244 stroke: RenderPipeline,
247 stroke_full: RenderPipeline,
248 stroke_fill: RenderPipeline,
250 text: RenderPipeline,
252 text_all: RenderPipeline,
253 pub(crate) text_layout: BindGroupLayout,
254 pub(crate) count_layout: BindGroupLayout,
255 pub(crate) scan_layout: BindGroupLayout,
256 pub(crate) write_layout: BindGroupLayout,
257 pub(crate) scatter_layout: BindGroupLayout,
258 pub(crate) inst_layout: BindGroupLayout,
259 pub(crate) draw_layout: BindGroupLayout,
260 quads: Buffer,
262 hl: Option<HlPipes>,
264}
265
266struct HlPipes {
268 write: ComputePipeline,
269 pub(crate) write_layout: BindGroupLayout,
270 stroke: RenderPipeline,
271 stroke_full: RenderPipeline,
272 stroke_fill: RenderPipeline,
273 text: RenderPipeline,
274 text_all: RenderPipeline,
275}
276
277struct HlModules {
279 write: ShaderModule,
280 vs: ShaderModule,
281 vs_full: ShaderModule,
282 vs_fill: ShaderModule,
283 vs_text: ShaderModule,
284 vs_text_all: ShaderModule,
285 fs: ShaderModule,
286 fs_full: ShaderModule,
287 fs_fill: ShaderModule,
288 fs_text: ShaderModule,
289 fs_text_all: ShaderModule,
290}
291
292#[cfg(not(target_arch = "wasm32"))]
293fn hl_modules(dev: &Device) -> Result<HlModules> {
294 let m = |w: &[u32]| ShaderModule::from_spirv(dev, w);
295 Ok(HlModules { write: m(WRITE_HL_SPV)?, vs: m(VS_HL_SPV)?, vs_full: m(VS_FULL_HL_SPV)?, vs_fill: m(VS_FILL_HL_SPV)?, vs_text: m(VS_TEXT_HL_SPV)?, vs_text_all: m(VS_TEXT_ALL_HL_SPV)?, fs: m(FS_SPV)?,
296 fs_full: m(FS_FULL_SPV)?, fs_fill: m(FS_FILL_SPV)?, fs_text: m(FS_TEXT_SPV)?, fs_text_all: m(FS_TEXT_ALL_SPV)? })
297}
298
299#[cfg(target_arch = "wasm32")]
300fn hl_modules(dev: &Device) -> Result<HlModules> {
301 let w = ShaderModule::from_wgsl(dev, &write_hl_wgsl())?;
302 let s = ShaderModule::from_wgsl(dev, &hl_wgsl(STROKE_WGSL))?;
303 let t = ShaderModule::from_wgsl(dev, &hl_wgsl(TEXT_WGSL))?;
304 let fs = ShaderModule::from_wgsl(dev, STROKE_WGSL)?;
305 let ft = ShaderModule::from_wgsl(dev, TEXT_WGSL)?;
306 Ok(HlModules { write: w, vs: s.clone(), vs_full: s.clone(), vs_fill: s, vs_text: t.clone(), vs_text_all: t, fs: fs.clone(), fs_full: fs.clone(), fs_fill: fs, fs_text: ft.clone(), fs_text_all: ft })
307}
308
309struct Modules {
310 count: ShaderModule,
311 scan: ShaderModule,
312 write: ShaderModule,
313 instances: ShaderModule,
314 scatter: ShaderModule,
315 vs: ShaderModule,
316 vs_full: ShaderModule,
317 fs: ShaderModule,
318 fs_full: ShaderModule,
319 vs_fill: ShaderModule,
320 fs_fill: ShaderModule,
321 vs_text: ShaderModule,
322 fs_text: ShaderModule,
323 vs_text_all: ShaderModule,
324 fs_text_all: ShaderModule,
325}
326
327#[cfg(not(target_arch = "wasm32"))]
328fn modules(dev: &Device) -> Result<Modules> {
329 let m = |w: &[u32]| ShaderModule::from_spirv(dev, w);
330 Ok(Modules { count: m(COUNT_SPV)?, scan: m(SCAN_SPV)?, write: m(WRITE_SPV)?, instances: m(INSTANCES_SPV)?, scatter: m(SCATTER_SPV)?, vs: m(VS_SPV)?, vs_full: m(VS_FULL_SPV)?, fs: m(FS_SPV)?,
331 fs_full: m(FS_FULL_SPV)?, vs_fill: m(VS_FILL_SPV)?, fs_fill: m(FS_FILL_SPV)?, vs_text: m(VS_TEXT_SPV)?, fs_text: m(FS_TEXT_SPV)?, vs_text_all: m(VS_TEXT_ALL_SPV)?,
332 fs_text_all: m(FS_TEXT_ALL_SPV)? })
333}
334
335#[cfg(target_arch = "wasm32")]
336fn modules(dev: &Device) -> Result<Modules> {
337 let c = ShaderModule::from_wgsl(dev, CULL_WGSL)?;
338 let s = ShaderModule::from_wgsl(dev, STROKE_WGSL)?;
339 let t = ShaderModule::from_wgsl(dev, TEXT_WGSL)?;
340 Ok(Modules { count: c.clone(), scan: c.clone(), write: c.clone(), instances: c, scatter: ShaderModule::from_wgsl(dev, SCATTER_WGSL)?, vs: s.clone(), vs_full: s.clone(), fs: s.clone(),
341 fs_full: s.clone(), vs_fill: s.clone(), fs_fill: s, vs_text: t.clone(), fs_text: t.clone(), vs_text_all: t.clone(), fs_text_all: t })
342}
343
344impl Renderer {
345 pub fn new(dev: &Device, desc: &RendererDesc) -> Result<Renderer> {
346 if !(1..=FRAMES_MAX).contains(&desc.frames_in_flight) {
347 return Err(GpuError::Invalid("frames_in_flight: 1 ..= 3"));
348 }
349 if desc.color.is_srgb() || desc.color.is_depth() || desc.color.is_compressed() {
350 return Err(GpuError::Invalid("RendererDesc: a colour format without sRGB (render2d blends sRGB codes as they are)"));
351 }
352 let md = modules(dev)?;
353 let b = |binding, kind, stages| Binding { binding, kind, stages };
354 let (cs, vs) = (Stages::COMPUTE, Stages::VERTEX);
355 let vfs = Stages::VERTEX | Stages::FRAGMENT;
357 let (read, rw) = (BindingKind::StorageBufferRead, BindingKind::StorageBuffer);
358 let count_layout = dev.create_bind_group_layout(&[b(0, BindingKind::UniformBuffer, cs), b(1, read, cs), b(2, read, cs), b(3, read, cs), b(4, rw, cs), b(5, rw, cs), b(11, rw, cs),
362 b(12, rw, cs)])?;
363 let scan_layout = dev.create_bind_group_layout(&[b(5, rw, cs), b(6, read, cs), b(7, rw, cs), b(8, rw, cs), b(9, rw, cs)])?;
364 let write_layout = dev.create_bind_group_layout(&[b(3, read, cs), b(4, rw, cs), b(7, rw, cs), b(10, rw, cs), b(14, rw, cs)])?;
365 let inst_layout = dev.create_bind_group_layout(&[b(0, BindingKind::UniformBuffer, cs), b(12, rw, cs), b(13, read, cs)])?;
366 let scatter_layout = dev.create_bind_group_layout(&[b(0, read, cs), b(1, rw, cs)])?;
367 let draw_layout = dev.create_bind_group_layout(&[b(0, BindingKind::UniformBuffer, vfs), b(1, read, vfs), b(2, read, vfs), b(3, read, vs), b(4, read, vs), b(5, read, Stages::FRAGMENT),
370 b(6, read, vfs), b(7, read, vs), b(8, read, vs)])?;
371 let text_layout = dev.create_bind_group_layout(&[b(0, BindingKind::UniformBuffer, vfs), b(1, read, vfs), b(2, read, vfs), b(3, read, vs), b(4, read, vs), b(5, read, Stages::FRAGMENT),
373 b(6, read, vfs), b(7, read, vs), b(8, read, vs), b(9, BindingKind::Texture, Stages::FRAGMENT), b(10, read, vfs)])?;
374 let pl = |g: &BindGroupLayout, push: u32| dev.create_pipeline_layout(&PipelineLayoutDesc { groups: &[g], push_constants: push });
375 let (count_pl, scan_pl, write_pl, scatter_pl, draw_pl) = (pl(&count_layout, 0)?, pl(&scan_layout, 16)?, pl(&write_layout, 0)?, pl(&scatter_layout, 4)?, pl(&draw_layout, 4)?);
378 let inst_pl = pl(&inst_layout, 16)?;
379 let text_pl = pl(&text_layout, 4)?;
380 let compute = |layout: &PipelineLayout, m: &ShaderModule, entry: &str| dev.create_compute_pipeline(&ComputePipelineDesc { layout, shader: ShaderStage::new(m, entry) });
381 let count = compute(&count_pl, &md.count, "count")?;
382 let scan = compute(&scan_pl, &md.scan, "scan")?;
383 let write = compute(&write_pl, &md.write, "write")?;
384 let scatter = compute(&scatter_pl, &md.scatter, "main")?;
385 let instances = compute(&inst_pl, &md.instances, "instances")?;
386 let stroke_with = |vs: &ShaderModule, ventry: &str, fs: &ShaderModule, fentry: &str, layout: &PipelineLayout| {
388 dev.create_render_pipeline(&RenderPipelineDesc {
389 layout,
390 vertex: ShaderStage::new(vs, ventry),
391 fragment: Some(ShaderStage::new(fs, fentry)),
392 buffers: &[],
393 topology: Topology::Triangles,
394 cull: Cull::None,
395 front_cw: false,
396 targets: &[ColorTarget { format: desc.color, blend: Some(Blend::PREMULTIPLIED), write_mask: 0xF }],
397 depth: None,
398 })
399 };
400 let stroke = stroke_with(&md.vs, "vs", &md.fs, "fs", &draw_pl)?;
401 let stroke_full = stroke_with(&md.vs_full, "vs_full", &md.fs_full, "fs_full", &draw_pl)?;
402 let stroke_fill = stroke_with(&md.vs_fill, "vs_fill", &md.fs_fill, "fs_fill", &draw_pl)?;
403 let text = stroke_with(&md.vs_text, "vs_text", &md.fs_text, "fs_text", &text_pl)?;
404 let text_all = stroke_with(&md.vs_text_all, "vs_text_all", &md.fs_text_all, "fs_text_all", &text_pl)?;
405 let mut idx = alloc::vec::Vec::with_capacity(BATCH as usize * 6);
406 for q in 0..BATCH {
407 let v = (q * 4) as u16;
408 idx.extend_from_slice(&[v, v + 1, v + 2, v + 2, v + 1, v + 3]);
409 }
410 let quads = dev.create_buffer(&BufferDesc { size: idx.len() as u64 * 2, usage: BufferUsage::INDEX, memory: MemoryKind::Device })?;
411 dev.queue().write_buffer(&quads, 0, &idx)?;
412 let (f, l) = (dev.features(), dev.limits());
413 let multi = dev.level() == Level::Voll && f.multi_draw_indirect && f.draw_indirect_first_instance;
414 let by_binding = l.max_storage_binding as u64 / RECORD_BYTES;
416 let max_entries = l.max_compute_workgroups[0].min(1 << 24);
417 let by_dispatch = max_entries as u64 * PAGE as u64;
418 let max_records = (by_binding / PAGE as u64 * PAGE as u64).min(by_dispatch).min(1 << 29) as u32;
420 let scatter_chunk = scatter_chunk(&l);
421 let info = dev.info();
422 let separate = desc.separate_scratch.unwrap_or(info.vendor_id == 0x8086 && info.backend == "Vulkan");
423 Ok(Renderer {
424 dev: dev.clone(),
425 desc: *desc,
426 multi,
427 separate,
428 max_records,
429 max_entries,
430 scatter_chunk,
431 tag: Arc::new(Tag),
432 count,
433 scan,
434 write,
435 scatter,
436 instances,
437 stroke,
438 stroke_full,
439 stroke_fill,
440 text,
441 text_all,
442 text_layout,
443 count_layout,
444 scan_layout,
445 write_layout,
446 scatter_layout,
447 inst_layout,
448 draw_layout,
449 quads,
450 hl: None,
451 })
452 }
453
454 pub(crate) fn ensure_hl(&mut self) -> Result<()> {
456 if self.hl.is_some() {
457 return Ok(());
458 }
459 let dev = self.dev.clone();
460 let md = hl_modules(&dev)?;
461 let b = |binding, kind, stages| Binding { binding, kind, stages };
462 let (cs, rw, read) = (Stages::COMPUTE, BindingKind::StorageBuffer, BindingKind::StorageBufferRead);
463 let write_layout = dev.create_bind_group_layout(&[b(3, read, cs), b(4, rw, cs), b(7, rw, cs), b(10, rw, cs), b(14, rw, cs), b(15, read, cs)])?;
464 let write_pl = dev.create_pipeline_layout(&PipelineLayoutDesc { groups: &[&write_layout], push_constants: 0 })?;
465 let write = dev.create_compute_pipeline(&ComputePipelineDesc { layout: &write_pl, shader: ShaderStage::new(&md.write, "write_hl") })?;
466 let draw_pl = dev.create_pipeline_layout(&PipelineLayoutDesc { groups: &[&self.draw_layout], push_constants: 4 })?;
467 let text_pl = dev.create_pipeline_layout(&PipelineLayoutDesc { groups: &[&self.text_layout], push_constants: 4 })?;
468 let color = self.desc.color;
469 let pipe = |vs: &ShaderModule, ventry: &str, fs: &ShaderModule, fentry: &str, layout: &PipelineLayout| {
470 dev.create_render_pipeline(&RenderPipelineDesc {
471 layout,
472 vertex: ShaderStage::new(vs, ventry),
473 fragment: Some(ShaderStage::new(fs, fentry)),
474 buffers: &[],
475 topology: Topology::Triangles,
476 cull: Cull::None,
477 front_cw: false,
478 targets: &[ColorTarget { format: color, blend: Some(Blend::PREMULTIPLIED), write_mask: 0xF }],
479 depth: None,
480 })
481 };
482 self.hl = Some(HlPipes {
483 write,
484 write_layout,
485 stroke: pipe(&md.vs, "vs", &md.fs, "fs", &draw_pl)?,
486 stroke_full: pipe(&md.vs_full, "vs_full", &md.fs_full, "fs_full", &draw_pl)?,
487 stroke_fill: pipe(&md.vs_fill, "vs_fill", &md.fs_fill, "fs_fill", &draw_pl)?,
488 text: pipe(&md.vs_text, "vs_text", &md.fs_text, "fs_text", &text_pl)?,
489 text_all: pipe(&md.vs_text_all, "vs_text_all", &md.fs_text_all, "fs_text_all", &text_pl)?,
490 });
491 Ok(())
492 }
493
494 pub(crate) fn hl_write_layout(&self) -> Option<&BindGroupLayout> {
496 self.hl.as_ref().map(|h| &h.write_layout)
497 }
498
499 pub fn device(&self) -> &Device {
500 &self.dev
501 }
502
503 pub fn desc(&self) -> &RendererDesc {
504 &self.desc
505 }
506
507 pub fn multi_draw(&self) -> bool {
509 self.multi
510 }
511
512 pub fn max_records(&self) -> u32 {
514 self.max_records
515 }
516
517 pub fn record<'a>(&'a self, e: &mut CommandEncoder<'a>, s: &'a Scene, color: ColorAttachment<'a>) -> Result<()> {
520 if !s.tag.as_ref().is_some_and(|t| Arc::ptr_eq(t, &self.tag)) {
521 return Err(GpuError::Invalid("record: a scene of another Renderer, or one without a device"));
522 }
523 if !s.prepared {
524 return Err(GpuError::Invalid("record: Scene::prepare comes first"));
525 }
526 if s.stale {
527 return Err(GpuError::Invalid("record: the scene changed after Scene::prepare"));
528 }
529 if color.view.format() != self.desc.color {
530 return Err(GpuError::Invalid("record: the colour target is not in the renderer's format"));
531 }
532 if color.view.size() != s.size {
533 return Err(GpuError::Invalid("record: the colour target is not of the size Scene::prepare was given"));
534 }
535 let g = s.groups.as_ref().ok_or(GpuError::Invalid("record: Scene::prepare comes first"))?;
536 let f = &s.frames[s.slot];
537 let ts = match &s.ts {
538 Some(ts) if s.stats_on => Some(ts),
539 _ => None,
540 };
541 let base = s.slot as u32 * STAMPS;
542 if let Some(ts) = ts {
543 e.reset_timestamps(ts, base, STAMPS);
544 e.timestamp(ts, base);
545 }
546 e.barrier(Access::COPY_READ | Access::COPY_WRITE | Access::COMPUTE_READ | Access::COMPUTE_WRITE | Access::INDIRECT | Access::INDEX_VERTEX | Access::GRAPHICS_READ,
549 Access::COPY_READ | Access::COPY_WRITE | Access::COMPUTE_READ | Access::COMPUTE_WRITE);
550 if let Some((old, moves)) = &s.up.rebuild {
552 e.fill_buffer(&s.pool, 0, s.pool.size(), 0);
553 if !moves.is_empty() {
554 e.barrier(Access::COPY_WRITE, Access::COPY_WRITE);
555 for &(src, dst, size) in moves {
556 e.copy_buffer(old, src, &s.pool, dst, size);
557 }
558 }
559 e.barrier(Access::COPY_WRITE, Access::COPY_WRITE | Access::COMPUTE_WRITE);
561 }
562 e.copy_buffer(&f.stage, 0, &s.view_ubo, 0, VIEW_BYTES);
563 if let Some((up, size)) = &s.up.styles {
564 e.copy_buffer(up, 0, &s.styles_buf, 0, *size);
565 }
566 if let Some((up, size)) = &s.up.hatch {
569 e.copy_buffer(up, 0, &s.hatch_buf, 0, *size);
570 }
571 if let Some((up, dst, size)) = &s.up.gtab {
574 e.copy_buffer(up, 0, &s.gtab_buf, *dst, *size);
575 }
576 if let (Some(at), Some(tex)) = (&s.up.atlas, &s.atlas_tex) {
580 e.texture_barrier(tex, if at.fresh { Layout::Undefined } else { Layout::Sampled }, Layout::CopyDst);
581 for c in &at.copies {
582 e.copy_buffer_to_texture(&at.buf, DataLayout { offset: c.offset, bytes_per_row: c.row, rows_per_image: 0 },
583 TextureRegion { texture: tex, mip: 0, origin: [c.x, c.y, 0], size: [c.w, c.h, 1], base_layer: c.page, layers: 1 });
584 }
585 e.texture_barrier(tex, Layout::CopyDst, Layout::Sampled);
586 }
587 if let Some((up, order, layers)) = &s.up.tables {
588 if *order > 0 {
589 e.copy_buffer(up, 0, &s.einfo_buf, 0, *order);
590 }
591 if *layers > 0 {
592 e.copy_buffer(up, *order, &s.layers_buf, 0, *layers);
593 }
594 }
595 if let Some((up, runs)) = &s.up.runs {
596 for &(src, dst, size) in runs {
597 e.copy_buffer(up, src, &s.pool, dst, size);
598 }
599 }
600 if let Some((up, runs)) = &s.up.insts {
603 for &(src, dst, size) in runs {
604 e.copy_buffer(up, src, &s.inst_buf, dst, size);
605 }
606 }
607 if let (Some((up, runs)), Some(hb)) = (&s.up.hl, &s.hl.buf) {
611 for &(src, dst, size) in runs {
612 e.copy_buffer(up, src, hb, dst, size);
613 }
614 }
615 if let (Some(ov), Some(g)) = (&s.up.ov, &s.ov_gpu) {
616 for &(src, dst, size) in &ov.copies {
617 let to = match dst {
618 0 => &g.view,
619 1 => &g.pool,
620 2 => &g.styles,
621 3 => &g.visible,
622 4 => &g.lists,
623 _ => &g.epx,
624 };
625 e.copy_buffer(&ov.buf, src, to, 0, size);
626 }
627 }
628 if s.up.scatter > 0 {
629 if f.scatter_groups.len() < s.up.scatter.div_ceil(self.scatter_chunk) as usize {
632 return Err(GpuError::Invalid("record: Scene::prepare comes first"));
633 }
634 e.set_compute_pipeline(&self.scatter);
635 let mut left = s.up.scatter;
636 for (k, group) in f.scatter_groups.iter().enumerate() {
637 if left == 0 {
638 break;
639 }
640 let n = left.min(self.scatter_chunk);
641 if k > 0 {
642 e.barrier(Access::COMPUTE_WRITE, Access::COMPUTE_WRITE);
645 }
646 e.set_bind_group(0, group);
647 e.push_constants(0, &[n]);
648 e.dispatch(n.div_ceil(WG_SCATTER), 1, 1);
649 left -= n;
650 }
651 }
652 e.barrier(Access::COPY_WRITE | Access::COMPUTE_WRITE, Access::COMPUTE_READ | Access::GRAPHICS_READ);
654 if let Some(ts) = ts {
655 e.timestamp(ts, base + 1);
656 }
657 let layers = s.vis_layers;
658 if layers > 0 {
659 if s.inst_count > 0 {
660 e.set_compute_pipeline(&self.instances);
663 e.set_bind_group(0, &g.inst);
664 e.push_constants(0, &[s.inst_count, 0, 0, 0]);
665 e.dispatch(s.inst_count.div_ceil(WG_INST), 1, 1);
666 e.barrier(Access::COMPUTE_WRITE, Access::COMPUTE_READ);
667 }
668 if s.entries > 0 {
669 e.set_compute_pipeline(&self.count);
670 e.set_bind_group(0, &g.count);
671 e.dispatch(s.entries, 1, 1);
672 e.barrier(Access::COMPUTE_WRITE, Access::COMPUTE_READ);
674 }
675 e.set_compute_pipeline(&self.scan);
676 e.set_bind_group(0, &g.scan);
677 e.push_constants(0, &[s.entries, layers, self.multi as u32, 0]);
678 e.dispatch(1, 1, 1);
679 if s.entries > 0 {
680 e.barrier(Access::COMPUTE_WRITE, Access::COMPUTE_READ);
682 match (&self.hl, &s.hl_group, s.hl_on) {
684 (Some(h), Some(hg), true) => {
685 e.set_compute_pipeline(&h.write);
686 e.set_bind_group(0, hg);
687 }
688 _ => {
689 e.set_compute_pipeline(&self.write);
690 e.set_bind_group(0, &g.write);
691 }
692 }
693 e.dispatch(s.entries, 1, 1);
694 }
695 e.barrier(Access::COMPUTE_WRITE, Access::INDIRECT | Access::GRAPHICS_READ | Access::COPY_READ);
697 if let (true, Some(rb)) = (s.stats_on, &f.readback) {
698 e.copy_buffer(&s.lists_buf, 0, rb, 0, layers as u64 * 16);
699 }
700 }
701 if let Some(ts) = ts {
702 e.timestamp(ts, base + 2);
703 }
704 let mut runs: alloc::vec::Vec<(Option<(u32, u32)>, &RenderPipeline, &BindGroup, bool)> = alloc::vec::Vec::new();
707 if layers > 0 {
708 let hl = |k: u32| s.hl_on && self.hl.is_some() && s.hl_drawn.get(k as usize).copied().unwrap_or(false);
712 let class = |k: u32| (s.full.get(k as usize).copied().unwrap_or(scene::CLASS_PLAIN), hl(k));
713 let mut k = 0;
714 while k < layers {
715 let mut n = 1;
716 while k + n < layers && class(k + n) == class(k) {
717 n += 1;
718 }
719 let (cls, lit) = class(k);
720 let (pipe, group) = match (self.hl.as_ref().filter(|_| lit), cls) {
721 (Some(h), scene::CLASS_TEXT) => (&h.text, g.text.as_ref()),
722 (Some(h), scene::CLASS_TEXT_ALL) => (&h.text_all, g.text.as_ref()),
723 (Some(h), scene::CLASS_FILL) => (&h.stroke_fill, Some(&g.draw)),
724 (Some(h), scene::CLASS_FULL) => (&h.stroke_full, Some(&g.draw)),
725 (Some(h), _) => (&h.stroke, Some(&g.draw)),
726 (None, scene::CLASS_TEXT) => (&self.text, g.text.as_ref()),
727 (None, scene::CLASS_TEXT_ALL) => (&self.text_all, g.text.as_ref()),
728 (None, scene::CLASS_FILL) => (&self.stroke_fill, Some(&g.draw)),
729 (None, scene::CLASS_FULL) => (&self.stroke_full, Some(&g.draw)),
730 (None, _) => (&self.stroke, Some(&g.draw)),
731 };
732 if let Some(group) = group {
733 runs.push((Some((k, n)), pipe, group, matches!(cls, scene::CLASS_FULL | scene::CLASS_FILL | scene::CLASS_TEXT_ALL)));
734 }
735 k += n;
736 }
737 }
738 if let (Some(ov), Some(gg)) = (&s.up.ov, &s.ov_gpu) {
740 if let (true, Some(group)) = (ov.quads > 0, &gg.group) {
741 runs.push((None, &self.stroke_fill, group, true));
742 }
743 }
744 let mut cut = alloc::vec![false; runs.len()];
749 if self.separate {
750 let mut last: Option<&RenderPipeline> = None;
751 for (c, r) in cut.iter_mut().zip(&runs) {
752 if r.3 {
753 *c = last.is_some_and(|q| !core::ptr::eq(q, r.1));
754 last = Some(r.1);
755 }
756 }
757 }
758 let cuts = cut.iter().filter(|&&c| c).count();
759 let first = if cuts > 0 { ColorAttachment { store: true, after: Layout::ColorTarget, ..color } } else { color };
760 e.begin_render(&RenderPassDesc { color: &[first], depth: None });
761 let mut passes = 0;
762 for (r, &c) in runs.iter().zip(&cut) {
763 if c {
764 e.end_render();
765 e.barrier(Access::COLOR_TARGET, Access::COLOR_TARGET);
767 passes += 1;
768 let next = ColorAttachment { load: Load::Keep, before: Layout::ColorTarget, ..color };
769 let next = if passes < cuts { ColorAttachment { store: true, after: Layout::ColorTarget, ..next } } else { next };
770 e.begin_render(&RenderPassDesc { color: &[next], depth: None });
771 }
772 e.set_render_pipeline(r.1);
773 e.set_bind_group(0, r.2);
774 e.set_index_buffer(&self.quads, 0, IndexFormat::U16);
775 match r.0 {
776 Some((k, n)) if self.multi => {
777 e.push_constants(0, &[0u32]);
778 e.draw_indexed_indirect_multi(&s.draws_buf, k as u64 * DRAW_BYTES, n, DRAW_BYTES as u32);
779 }
780 Some((k, n)) => {
781 for j in k..k + n {
783 e.push_constants(0, &[j]);
784 e.draw_indexed_indirect(&s.draws_buf, j as u64 * DRAW_BYTES);
785 }
786 }
787 None => {
788 if let Some(ov) = &s.up.ov {
789 e.push_constants(0, &[0u32]);
790 e.draw_indexed(6 * ov.quads.min(BATCH), ov.quads.div_ceil(BATCH), 0, 0, 0);
791 }
792 }
793 }
794 }
795 e.end_render();
796 if let Some(ts) = ts {
797 e.timestamp(ts, base + 3);
798 }
799 if s.stats_on && layers > 0 {
800 e.barrier(Access::COPY_WRITE, Access::HOST_READ);
801 }
802 Ok(())
803 }
804}