[K3c] Strichmuster im Chunk-Pfad (nativer macOS-Renderer): Instanzen im render2d-Format, gleicher Strich-Shader

Der Chunk-Pfad (gpu_compile → GpuChunkCache → render2d/chunks.rs) hat Linien-Strichmuster nie
gezeichnet (keine Regression von 0516253). Jetzt trägt die GPU-Sicht des Plan-Puffers dash, gpu_compile
gibt gestrichelte Züge als DashSegment-Instanzen aus (Phase über Ketten, Länge wie Szenen-Pfad), der
Chunk-Renderer zeichnet sie mit DASH_LINE_WGSL in Maler-Reihenfolge (lineAt). render_png: --chunks/--bounds.
This commit is contained in:
Claude committed 2026-10-29 12:26:19 +00:00
1 parent 9395ddc5de
commit 7ba007f40c
12 files changed
+827 -53

No files matched your search

+43 -8
View File
@@ -4,9 +4,12 @@
// Session funktioniert.
//
// Start: cargo run --features headless --bin render_png -- [--out PFAD] [--width N] [--height N]
// [--scene szene.bin] [--crop x0,y0,x1,y1] [--scale N]
// [--scene szene.bin | --chunks a.bin,b.bin…] [--bounds minX,minY,maxX,maxY] [--crop x0,y0,x1,y1] [--scale N]
// `--scene`: Szene-Bytes wie für `set_scene_bin` (statt der Demo); Ausschnitt = Ausmass der Szene,
// `--crop` wählt daraus einen Teil (Anteile 0..1, y von oben), `--scale` den Papier-Massstab 1:N.
// `--chunks`: GPU-Chunks (je Datei die u32-Ausgabe von `gpu_compile_flat`, gepackt) über den
// Chunk-Renderer des nativen macOS-Pfads (`chunks.rs`); Ausschnitt = Vereinigung der Chunk-Ausmasse.
// `--bounds` (Modell-Meter) ersetzt das Ausmass — für deckungsgleiche Vergleiche Szene ↔ Chunks.
#![cfg(feature = "headless")]
use render2d::headless::HeadlessRenderer;
@@ -21,6 +24,8 @@ fn main() {
let mut scene_file: Option<String> = None;
let mut crop = [0.0f32, 0.0, 1.0, 1.0];
let mut paper_n = 100.0f32;
let mut chunk_files: Vec<String> = Vec::new();
let mut bounds_arg: Option<[f32; 4]> = None;
let mut args = std::env::args().skip(1);
while let Some(arg) = args.next() {
@@ -39,6 +44,13 @@ fn main() {
}
"--out" => out = args.next().unwrap_or(out),
"--scene" => scene_file = args.next(),
"--chunks" => chunk_files = args.next().unwrap_or_default().split(',').filter(|f| !f.is_empty()).map(String::from).collect(),
"--bounds" => {
let v: Vec<f32> = args.next().unwrap_or_default().split(',').filter_map(|x| x.parse().ok()).collect();
if v.len() == 4 {
bounds_arg = Some([v[0], v[1], v[2], v[3]]);
}
}
"--scale" => paper_n = args.next().and_then(|v| v.parse().ok()).unwrap_or(paper_n),
"--crop" => {
let v: Vec<f32> = args.next().unwrap_or_default().split(',').filter_map(|x| x.parse().ok()).collect();
@@ -51,18 +63,41 @@ fn main() {
}
let mut renderer = HeadlessRenderer::new().expect("Headless-Renderer initialisieren");
// Ausmass (Modell-Meter) → Bildschirm-Raum (x·90, −y·90), dann der Ausschnitt.
let view_of = |b: [f32; 4]| {
let (x0, x1) = (b[0] * 90.0, b[2] * 90.0);
let (y0, y1) = (-b[3] * 90.0, -b[1] * 90.0);
let (w, h) = (x1 - x0, y1 - y0);
ViewBox::new(x0 + crop[0] * w, y0 + crop[1] * h, (crop[2] - crop[0]) * w, (crop[3] - crop[1]) * h)
};
if !chunk_files.is_empty() {
let chunks: Vec<Vec<u32>> = chunk_files
.iter()
.map(|f| std::fs::read(f).expect("Chunk lesen").chunks_exact(4).map(|c| u32::from_le_bytes([c[0], c[1], c[2], c[3]])).collect())
.collect();
let b = bounds_arg.unwrap_or_else(|| {
let mut b = [f32::INFINITY, f32::INFINITY, f32::NEG_INFINITY, f32::NEG_INFINITY];
for c in &chunks {
if let Some(cb) = render2d::headless::chunk_flat_bounds(c) {
b = [b[0].min(cb[0] as f32), b[1].min(cb[1] as f32), b[2].max(cb[2] as f32), b[3].max(cb[3] as f32)];
}
}
b
});
let vb = view_of(b);
let view = render2d::chunks::View { x: vb.x as f64, y: vb.y as f64, w: vb.w as f64, h: vb.h as f64 };
let image = renderer.render_chunks_to_image(&chunks, width, height, view, paper_n as f64).expect("Chunks rendern");
std::fs::write(&out, image.encode_png()).expect("PNG schreiben");
println!("render_png: Chunks geschrieben nach {out} ({width}x{height})");
return;
}
let (scene, view_box) = match &scene_file {
None => (demo_scene(), initial_view_box()),
Some(f) => {
let bytes = std::fs::read(f).expect("Szene lesen");
let scene = render2d::scene_bin::decode_scene(&bytes).expect("Szene dekodieren");
// Ausmass (Modell-Meter) → Bildschirm-Raum (x·90, −y·90), dann der Ausschnitt.
let b = render2d::compile_scene(&scene).bounds;
let (x0, x1) = (b[0] * 90.0, b[2] * 90.0);
let (y0, y1) = (-b[3] * 90.0, -b[1] * 90.0);
let (w, h) = (x1 - x0, y1 - y0);
let vb = ViewBox::new(x0 + crop[0] * w, y0 + crop[1] * h, (crop[2] - crop[0]) * w, (crop[3] - crop[1]) * h);
(scene, vb)
let b = bounds_arg.unwrap_or_else(|| render2d::compile_scene(&scene).bounds);
(scene, view_of(b))
}
};
let image = renderer.render_to_image(&scene, width, height, view_box, paper_n);
+151 -25
View File
@@ -7,6 +7,12 @@
//
// Linien-Vertices kommen KOMPAKT (12 Byte, s. LINE_PACKED_WGSL).
//
// Gestrichelte Striche kommen als Instanzen (je Segment 16 x f32, Format wie
// `DashSegment`/`gpu::DashInstance`) und laufen durch DIESELBE Strich-Pipeline wie
// der Szenen-Pfad (`DASH_LINE_WGSL`: Striche, Luecken, runde Enden im Fragment-
// Shader). Innerhalb eines Chunks in Maler-Reihenfolge mit den Linien verzahnt
// (`DashBatch::line_at`), damit spaetere Striche fruehere gestrichelte decken.
//
// Die Webview kompiliert weiterhin (Cache/Chunk-Logik bleibt in TypeScript) und
// schickt nur noch die Puffer-BYTES je Chunk einmalig; pro Frame geht nur der
// Ausschnitt (viewBox) hierher. Rust haelt die Puffer — kein JSON, kein
@@ -17,7 +23,7 @@ use std::collections::HashMap;
use bytemuck::{Pod, Zeroable};
use wgpu::util::DeviceExt;
use crate::shaders::FILL_WGSL;
use crate::shaders::{DASH_LINE_WGSL, FILL_WGSL};
/// Graustufe fuer gedimmte Linien (== GREY_RGB in glPlanCompile.ts).
const GREY: f32 = 0.549;
@@ -175,6 +181,40 @@ pub struct LineBatch {
pub device_px: bool,
}
/// Instanz-Bereich gestrichelter Segmente (Strich-Pipeline) mit Farbe + Papier-mm.
#[derive(Clone, Debug, serde::Deserialize)]
pub struct DashBatch {
pub start: u32,
pub count: u32,
pub color: [f32; 4],
pub stroke_mm: f32,
/// Maler-Reihenfolge: gezeichnet vor dem ersten Linien-Batch mit `start >= line_at`
/// (Linien-Index-Position beim Erzeugen; kein Linien-Batch ueberspannt sie).
#[serde(default)]
pub line_at: u32,
}
/// Zeichenfolge der Striche eines Chunks: (gestrichelt?, Batch-Index), Linien und
/// gestrichelte Batches nach `line_at` verzahnt. Fehlen die Puffer einer Art, entfaellt sie.
fn stroke_order(g: &ChunkGeom) -> Vec<(bool, usize)> {
let lines = if g.line_vtx.is_some() && g.line_idx.is_some() { g.line_batches.len() } else { 0 };
let dashes = if g.dash_inst.is_some() { g.dash_batches.len() } else { 0 };
let mut out = Vec::with_capacity(lines + dashes);
let mut j = 0;
for i in 0..lines {
while j < dashes && g.dash_batches[j].line_at <= g.line_batches[i].start {
out.push((true, j));
j += 1;
}
out.push((false, i));
}
out.extend((j..dashes).map(|k| (true, k)));
out
}
/// Bytes je Strich-Instanz (16 x f32: ab, run, dash[8]; wie `gpu::DashInstance`).
pub const DASH_INSTANCE_BYTES: u64 = 16 * 4;
/// Ein Chunk (== `GpuGeometry` der Webview): Puffer-IDs statt GL-Puffer.
#[derive(Clone, Debug, serde::Deserialize)]
pub struct ChunkGeom {
@@ -184,6 +224,11 @@ pub struct ChunkGeom {
pub line_vtx: Option<u32>,
pub line_idx: Option<u32>,
pub line_batches: Vec<LineBatch>,
/// Puffer der Strich-Instanzen (gestrichelte Segmente); fehlt ohne Strichmuster.
#[serde(default)]
pub dash_inst: Option<u32>,
#[serde(default)]
pub dash_batches: Vec<DashBatch>,
pub origin: [f64; 2],
#[serde(default)]
pub greyed: bool,
@@ -201,6 +246,7 @@ pub struct View {
pub struct ChunkRenderer {
fill_pipeline: wgpu::RenderPipeline,
line_pipeline: wgpu::RenderPipeline,
dash_pipeline: wgpu::RenderPipeline,
bind_group_layout: wgpu::BindGroupLayout,
uniform: Option<(wgpu::Buffer, wgpu::BindGroup, u64)>,
buffers: HashMap<u32, wgpu::Buffer>,
@@ -338,6 +384,20 @@ impl ChunkRenderer {
},
"chunks.line.pipeline",
);
// Gestrichelte Segmente: Instanz-Puffer, Quad aus `vertex_index` (wie gpu.rs).
let dash_module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("chunks.dash"),
source: wgpu::ShaderSource::Wgsl(DASH_LINE_WGSL.into()),
});
let dash_pipeline = make(
&dash_module,
wgpu::VertexBufferLayout {
array_stride: DASH_INSTANCE_BYTES,
step_mode: wgpu::VertexStepMode::Instance,
attributes: &wgpu::vertex_attr_array![0 => Float32x4, 1 => Float32x4, 2 => Float32x4, 3 => Float32x4],
},
"chunks.dash.pipeline",
);
let text_module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("chunks.text"),
source: wgpu::ShaderSource::Wgsl(TEXT_WGSL.into()),
@@ -387,6 +447,7 @@ impl ChunkRenderer {
inst_buf: None,
fill_pipeline,
line_pipeline,
dash_pipeline,
bind_group_layout,
uniform: None,
buffers: HashMap::new(),
@@ -567,20 +628,20 @@ impl ChunkRenderer {
blocks.push(Globals { view_proj: proj, color: c, viewport_px: vp, stroke_px: 0.0, stroke_scale: 1.0 });
}
}
for g in self.layout.iter().chain(self.highlight.iter()) {
if g.line_vtx.is_none() || g.line_idx.is_none() {
continue;
}
// Striche (Linien + gestrichelte) je Chunk in Maler-Reihenfolge (`stroke_order`).
let orders: Vec<Vec<(bool, usize)>> = self.layout.iter().chain(self.highlight.iter()).map(stroke_order).collect();
for (g, order) in self.layout.iter().chain(self.highlight.iter()).zip(&orders) {
let proj = projection(bounds, g.origin);
for b in &g.line_batches {
let c = if g.greyed { [GREY, GREY, GREY, b.color[3]] } else { b.color };
blocks.push(Globals {
view_proj: proj,
color: c,
viewport_px: vp,
stroke_px: b.stroke_mm,
stroke_scale: if b.device_px { 1.0 } else if b.screen_px { meet as f32 } else { mm_px as f32 },
});
for &(dashed, k) in order {
let (color, stroke_mm, scale) = if dashed {
let b = &g.dash_batches[k];
(b.color, b.stroke_mm, mm_px as f32)
} else {
let b = &g.line_batches[k];
(b.color, b.stroke_mm, if b.device_px { 1.0 } else if b.screen_px { meet as f32 } else { mm_px as f32 })
};
let c = if g.greyed { [GREY, GREY, GREY, color[3]] } else { color };
blocks.push(Globals { view_proj: proj, color: c, viewport_px: vp, stroke_px: stroke_mm, stroke_scale: scale });
}
}
@@ -719,19 +780,55 @@ impl ChunkRenderer {
block += 1;
}
}
pass.set_pipeline(&self.line_pipeline);
for g in self.layout.iter().chain(self.highlight.iter()) {
let (Some(p), Some(i)) = (g.line_vtx, g.line_idx) else { continue };
let (Some(pb), Some(ib)) = (self.buffers.get(&p), self.buffers.get(&i)) else {
block += g.line_batches.len() as u32;
continue;
// Striche je Chunk: Linien-Batches (indiziert) und gestrichelte Segmente (je
// Instanz ein Quad aus 6 Vertices) in Maler-Reihenfolge, Pipeline nur bei Wechsel.
let mut current: Option<bool> = None;
for (g, order) in self.layout.iter().chain(self.highlight.iter()).zip(&orders) {
let lines = match (g.line_vtx.and_then(|p| self.buffers.get(&p)), g.line_idx.and_then(|i| self.buffers.get(&i))) {
(Some(pb), Some(ib)) => Some((pb, ib)),
_ => None,
};
pass.set_vertex_buffer(0, pb.slice(..));
pass.set_index_buffer(ib.slice(..), wgpu::IndexFormat::Uint32);
for b in &g.line_batches {
pass.set_bind_group(0, ubind, &[block * stride as u32]);
pass.draw_indexed(b.start..b.start + b.count, 0, 0..1);
let dash = g.dash_inst.and_then(|d| self.buffers.get(&d));
let mut bound_lines = false;
let mut bound_dash = false;
for &(dashed, k) in order {
let this_block = block;
block += 1;
if dashed {
let Some(db) = dash else { continue };
if current != Some(true) {
pass.set_pipeline(&self.dash_pipeline);
current = Some(true);
bound_lines = false;
}
if !bound_dash {
pass.set_vertex_buffer(0, db.slice(..));
bound_dash = true;
}
let b = &g.dash_batches[k];
// Bereich gegen die Puffergroesse klemmen (fremde Angaben → nie ausserhalb lesen).
let n_inst = (db.size() / DASH_INSTANCE_BYTES) as u32;
let end = b.start.saturating_add(b.count).min(n_inst);
if b.start < end {
pass.set_bind_group(0, ubind, &[this_block * stride as u32]);
pass.draw(0..6, b.start..end);
}
} else {
let Some((pb, ib)) = lines else { continue };
if current != Some(false) {
pass.set_pipeline(&self.line_pipeline);
current = Some(false);
bound_dash = false;
}
if !bound_lines {
pass.set_vertex_buffer(0, pb.slice(..));
pass.set_index_buffer(ib.slice(..), wgpu::IndexFormat::Uint32);
bound_lines = true;
}
let b = &g.line_batches[k];
pass.set_bind_group(0, ubind, &[this_block * stride as u32]);
pass.draw_indexed(b.start..b.start + b.count, 0, 0..1);
}
}
}
// Text zuoberst.
@@ -762,6 +859,35 @@ impl ChunkRenderer {
mod tests {
use super::*;
fn lb(start: u32) -> LineBatch {
LineBatch { start, count: 6, color: [0.0; 4], stroke_mm: 0.1, screen_px: false, device_px: false }
}
fn db(line_at: u32) -> DashBatch {
DashBatch { start: 0, count: 1, color: [0.0; 4], stroke_mm: 0.1, line_at }
}
#[test]
fn striche_in_maler_reihenfolge() {
let g = ChunkGeom {
fill_pos: None,
fill_idx: None,
fill_batches: vec![],
line_vtx: Some(1),
line_idx: Some(2),
line_batches: vec![lb(0), lb(6), lb(12)],
dash_inst: Some(3),
dash_batches: vec![db(0), db(6), db(6), db(18)],
origin: [0.0, 0.0],
greyed: false,
};
assert_eq!(stroke_order(&g), vec![(true, 0), (false, 0), (true, 1), (true, 2), (false, 1), (false, 2), (true, 3)]);
// Ohne Strich-Puffer: nur Linien; ohne Linien-Puffer: nur gestrichelte.
let only_lines = ChunkGeom { dash_inst: None, ..g.clone() };
assert_eq!(stroke_order(&only_lines), vec![(false, 0), (false, 1), (false, 2)]);
let only_dash = ChunkGeom { line_idx: None, ..g };
assert_eq!(stroke_order(&only_dash), vec![(true, 0), (true, 1), (true, 2), (true, 3)]);
}
#[test]
fn projection_matches_ts_reference() {
// viewBox 0,0,100,50 auf 200x100 px: keine Aspekt-Korrektur noetig.
+173
View File
@@ -17,6 +17,7 @@
use image::ImageEncoder;
use crate::chunks::{ChunkGeom, ChunkRenderer, DashBatch, FillBatch, LineBatch, View};
use crate::gpu::Renderer;
use crate::types::{Scene, ViewBox};
@@ -156,6 +157,39 @@ impl HeadlessRenderer {
}
}
/// Rendert GPU-Chunks (je Eintrag die flache Ausgabe der Kern-Kompilierung
/// `gpu_compile_flat`, gepackte Linien-Vertices) ueber den Chunk-Renderer, den der
/// native macOS-Pfad benutzt (`chunks.rs`: dieselben Shader und dieselbe
/// Zeichenreihenfolge, nur ohne Metal-Flaeche). `view` in Bildschirm-Einheiten.
/// Fuer Headless-Vergleiche Chunk-Pfad gegen Szenen-Pfad.
pub fn render_chunks_to_image(&self, chunks: &[Vec<u32>], width: u32, height: u32, view: View, paper_scale_n: f64) -> Result<RgbaImage, String> {
let (width, height) = (width.max(1), height.max(1));
let mut cr = ChunkRenderer::new(&self.device, COLOR_FORMAT, 4);
let mut layout = Vec::new();
let mut next_id = 1u32;
for words in chunks {
let (geom, bufs) = chunk_from_flat(words, &mut next_id).ok_or("Chunk-Ausgabe unlesbar")?;
for (id, bytes) in bufs {
cr.upload(&self.device, id, &bytes);
}
layout.push(geom);
}
cr.set_layout(layout);
let texture = self.device.create_texture(&wgpu::TextureDescriptor {
label: Some("headless.chunks.target"),
size: wgpu::Extent3d { width, height, depth_or_array_layers: 1 },
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: COLOR_FORMAT,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
view_formats: &[],
});
let tv = texture.create_view(&wgpu::TextureViewDescriptor::default());
cr.render(&self.device, &self.queue, &tv, view, (width, height), paper_scale_n);
Ok(RgbaImage { width, height, pixels: self.read_pixels(&texture, width, height) })
}
/// Texture -> gepolsterter Buffer -> straff gepacktes Pixel-Array (Row-
/// Alignment-Falle, siehe Modul-Kopf).
fn read_pixels(&self, texture: &wgpu::Texture, width: u32, height: u32) -> Vec<u8> {
@@ -235,3 +269,142 @@ fn align_up(value: u32, align: u32) -> u32 {
}
((value + align - 1) / align) * align
}
/// Modell-Ausmass (minX, minY, maxX, maxY, Meter) einer flachen Chunk-Ausgabe (`gpu_compile_flat`).
pub fn chunk_flat_bounds(words: &[u32]) -> Option<[f64; 4]> {
let meta = flat_meta(words)?;
(meta.len() >= 6).then(|| [meta[2], meta[3], meta[4], meta[5]])
}
fn flat_meta(words: &[u32]) -> Option<Vec<f64>> {
let m = *words.first()? as usize;
if words.len() < 2 + 2 * m {
return None;
}
Some((0..m).map(|i| f64::from_bits(words[2 + 2 * i] as u64 | ((words[3 + 2 * i] as u64) << 32))).collect())
}
/// Flache Kern-Ausgabe (Layout s. `core/src/gpu_compile.rs`, gepackt) → Layout-Eintrag + Puffer
/// (ID, Bytes) wie sie die Webview an den nativen Renderer schickt (`nativeGl.ts`).
pub fn chunk_from_flat(words: &[u32], next_id: &mut u32) -> Option<(ChunkGeom, Vec<(u32, Vec<u8>)>)> {
let meta = flat_meta(words)?;
if meta.len() < 12 {
return None;
}
let n = |v: f64| -> Option<usize> { (v >= 0.0 && v.fract() == 0.0).then_some(v as usize) };
let (nfp, nfi, nlv, nli, nf, nl) = (n(meta[6])?, n(meta[7])?, n(meta[8])?, n(meta[9])?, n(meta[10])?, n(meta[11])?);
let mut k = 12;
let rgba = |m: &[f64]| [m[0] as f32, m[1] as f32, m[2] as f32, m[3] as f32];
let mut fill_batches = Vec::new();
for _ in 0..nf {
let b = meta.get(k..k + 6)?;
fill_batches.push(FillBatch { start: b[0] as u32, count: b[1] as u32, color: rgba(&b[2..6]) });
k += 6;
}
let mut line_batches = Vec::new();
for _ in 0..nl {
let b = meta.get(k..k + 8)?;
line_batches.push(LineBatch { start: b[0] as u32, count: b[1] as u32, color: rgba(&b[2..6]), stroke_mm: b[6] as f32, screen_px: b[7] == 1.0, device_px: false });
k += 8;
}
let (nd, ndb) = (meta.get(k).copied().map(n).unwrap_or(Some(0))?, meta.get(k + 1).copied().map(n).unwrap_or(Some(0))?);
k += 2;
let mut dash_batches = Vec::new();
for _ in 0..ndb {
let b = meta.get(k..k + 8)?;
dash_batches.push(DashBatch { start: b[0] as u32, count: b[1] as u32, color: rgba(&b[2..6]), stroke_mm: b[6] as f32, line_at: b[7] as u32 });
k += 8;
}
let mut off = 2 + 2 * meta.len();
let mut bufs = Vec::new();
let mut take = |len: usize, off: &mut usize| -> Option<Option<u32>> {
let w = words.get(*off..*off + len)?;
*off += len;
if len == 0 {
return Some(None);
}
let id = *next_id;
*next_id += 1;
bufs.push((id, w.iter().flat_map(|v| v.to_le_bytes()).collect::<Vec<u8>>()));
Some(Some(id))
};
let fill_pos = take(nfp, &mut off)?;
let fill_idx = take(nfi, &mut off)?;
let line_vtx = take(nlv, &mut off)?;
let line_idx = take(nli, &mut off)?;
let dash_inst = take(nd * 16, &mut off)?;
let geom = ChunkGeom {
fill_pos,
fill_idx,
fill_batches,
line_vtx,
line_idx,
line_batches,
dash_inst,
dash_batches,
origin: [meta[0], meta[1]],
greyed: false,
};
Some((geom, bufs))
}
#[cfg(test)]
mod tests {
use super::*;
/// Flache Ausgabe wie `gpu_compile_flat` mit EINER gestrichelten Linie (Instanz) von
/// (0,0) nach (L,0) Bildschirm-Einheiten, Muster an/aus = `on`/`off`.
fn dashed_chunk(len: f32, on: f32, off: f32, stroke_mm: f64) -> Vec<u32> {
let mut meta: Vec<f64> = vec![0.0, 0.0, 0.0, 0.0, len as f64 / 90.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0];
meta.extend_from_slice(&[1.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, stroke_mm, 0.0]);
let mut out = vec![meta.len() as u32, 0];
for m in &meta {
let b = m.to_bits();
out.push(b as u32);
out.push((b >> 32) as u32);
}
let inst = [0.0, 0.0, len, 0.0, 0.0, len, on + off, 2.0, on, off, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0f32];
out.extend(inst.iter().map(|v| v.to_bits()));
out
}
/// Der Chunk-Renderer (nativer macOS-Pfad, hier ueber Vulkan/lavapipe) zeichnet Striche
/// und Luecken: entlang der Achse wechseln gedeckte und freie Pixel im Muster-Takt.
#[test]
fn chunk_renderer_zeichnet_striche_und_luecken() {
let r = match HeadlessRenderer::new() {
Ok(r) => r,
Err(e) => {
eprintln!("uebersprungen, kein Headless-Adapter: {e}");
return;
}
};
// 200 Einheiten lang, Muster 20 an / 20 aus; Ansicht 1:1 auf 200x40 px.
let chunk = dashed_chunk(200.0, 20.0, 20.0, 0.05);
let img = r
.render_chunks_to_image(&[chunk], 200, 40, View { x: 0.0, y: -20.0, w: 200.0, h: 40.0 }, 1000.0)
.expect("rendern");
let px = |x: u32| {
let i = ((20 * img.width + x) * 4) as usize;
img.pixels[i] // Rot-Kanal: Linie schwarz -> 0, Hintergrund weiss -> 255
};
// Strich-Mitten (10, 50, 90 …) dunkel, Luecken-Mitten (30, 70, 110 …) hell.
for c in [10u32, 50, 90, 130, 170] {
assert!(px(c) < 80, "Strich bei x={c}: {}", px(c));
}
for c in [30u32, 70, 110, 150] {
assert!(px(c) > 200, "Luecke bei x={c}: {}", px(c));
}
}
#[test]
fn flache_ausgabe_wird_gelesen() {
let mut id = 1;
let (g, bufs) = chunk_from_flat(&dashed_chunk(100.0, 5.0, 5.0, 0.35), &mut id).unwrap();
assert_eq!(g.dash_inst, Some(1));
assert_eq!(g.dash_batches.len(), 1);
assert_eq!(bufs[0].1.len(), 64);
assert!(g.line_vtx.is_none() && g.fill_pos.is_none());
assert!(chunk_from_flat(&[5, 0, 1], &mut id).is_none());
}
}