[27] render3d: Punkt-Pipeline für Punktwolken (WebGPU + nativ), Cap-Shader für Chrome

Instanz-Quads mit fester Pixelgrösse, tiefengetestet gegen das Modell, vom Live-Schnitt
gekappt; Farbmodi rgb/Intensität/Klasse/Höhe auf der CPU, Versatz in f64 (LV95-fest).
Bindungen set_point_cloud/_style/remove/clear ohne Panic; render_png --points.
CAP_WGSL: fwidth vor die Verzweigungen (Tint verwarf sonst jeden 3D-Frame in Chrome).

Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67
This commit is contained in:
Claude committed 2026-10-28 15:11:17 +00:00
1 parent f18b4e22ad
commit 5907bce3a6
7 files changed
+1197 -21

No files matched your search

+58
View File
@@ -3,12 +3,18 @@
// Dient Referenzbildern und der Prüfung des 3D ohne Nutzer-App.
//
// cargo run --release --features png --bin render_png -- modell.json aus.png [--view iso] [--style shaded] [--size 1200x800] [--target x,y,z] [--dist 12]
// [--points wolke.txt] [--point-size 3] [--point-color rgb|intensity|class|height]
//
// `--points` ([27]): Textdatei mit einem Punkt je Zeile `x y z [r g b [intensitaet [klasse]]]` in
// Modell-Metern (x = Ost, y = Nord, z = Hoehe) — dieselbe Punkt-Pipeline wie im Browser-Viewport.
//
// `modell.json` ist das Modell wie `set_model` es bekommt (`dossier-cli … model3d`).
use std::io::Write;
use render3d::gpu::{RenderStyle, Renderer};
use render3d::gpu_points::PointStyle;
use render3d::points::{PointCloudCpu, PointColorMode};
use render3d::math::preset_camera;
use render3d::types::{CameraPreset, MeshInput, SlabInput, WallInput};
use serde::Deserialize;
@@ -56,6 +62,46 @@ fn bounds(m: &ModelInput) -> Option<([f32; 3], [f32; 3])> {
any.then_some((min, max))
}
/// Liest `x y z [r g b [i [k]]]` je Zeile (Leerzeichen/Komma/Semikolon); unlesbare Zeilen fallen weg.
/// Attribute nur, wenn JEDE Zeile sie hat.
fn read_points_txt(path: &str) -> Option<PointCloudCpu> {
let text = std::fs::read_to_string(path).ok()?;
let (mut xyz, mut rgb, mut int, mut cls) = (Vec::new(), Vec::new(), Vec::new(), Vec::new());
let (mut all_rgb, mut all_int, mut all_cls) = (true, true, true);
for line in text.lines() {
let v: Vec<f64> = line
.split(|c: char| c.is_whitespace() || c == ',' || c == ';')
.filter(|s| !s.is_empty())
.map_while(|s| s.parse::<f64>().ok())
.collect();
if v.len() < 3 {
continue;
}
xyz.extend_from_slice(&[v[0] as f32, v[1] as f32, v[2] as f32]);
all_rgb &= v.len() >= 6;
all_int &= v.len() >= 7;
all_cls &= v.len() >= 8;
if v.len() >= 6 {
rgb.extend(v[3..6].iter().map(|c| c.clamp(0.0, 255.0) as u8));
}
if v.len() >= 7 {
int.push(v[6].clamp(0.0, 65535.0) as u16);
}
if v.len() >= 8 {
cls.push(v[7].clamp(0.0, 255.0) as u8);
}
}
let pick = |ok: bool, len: usize, want: usize| ok && len == want;
let n = xyz.len() / 3;
PointCloudCpu::from_raw(
&xyz,
if pick(all_rgb, rgb.len(), n * 3) { &rgb } else { &[] },
if pick(all_int, int.len(), n) { &int } else { &[] },
if pick(all_cls, cls.len(), n) { &cls } else { &[] },
[0.0; 3],
)
}
fn preset(name: &str) -> CameraPreset {
match name {
"front" => CameraPreset::Front,
@@ -175,6 +221,18 @@ fn main() {
let mut renderer = Renderer::new(&device, format);
renderer.set_render_style(RenderStyle::from_str_or_shaded(&flag("--style", "shaded")));
renderer.upload_model(&device, &model.walls, &model.slabs, &model.meshes);
let points_path = flag("--points", "");
if !points_path.is_empty() {
let cloud = read_points_txt(&points_path);
let n = cloud.as_ref().map_or(0, |c| c.len());
let style = PointStyle {
mode: PointColorMode::from_str_or_rgb(&flag("--point-color", "rgb")),
size_px: flag("--point-size", "3").parse().unwrap_or(3.0),
visible: true,
};
renderer.set_point_cloud(&device, 1, cloud, style);
eprintln!("Punktwolke: {n} Punkte aus {points_path}");
}
let (target, dist) = match bounds(&model) {
Some((min, max)) => {
+53
View File
@@ -16,6 +16,8 @@ use crate::edges::{
build_edge_adjacency, build_mesh_edges, build_silhouette_edges, EdgeAdj, EDGE_FLOATS_PER_VERTEX,
};
use crate::grid::{build_ground_grid, GRID_FLOATS_PER_VERTEX};
use crate::gpu_points::{PointRenderer, PointStyle};
use crate::points::PointCloudCpu;
use crate::math::{view_projection, Mat4};
use crate::mesh::{
build_free_wall_end_caps, build_scene_mesh, build_scene_mesh_textured, build_terrain_mesh,
@@ -388,6 +390,9 @@ pub struct Renderer {
/// Farbformat des Render-Ziels (Surface), fuer die MSAA-Zwischentextur.
color_format: wgpu::TextureFormat,
globals: Globals,
/// Punktwolken ([27], `gpu_points.rs`): eigene Instanz-Quad-Pipeline, tiefengetestet im
/// selben Pass wie das Modell.
points: PointRenderer,
/// Loeschfarbe (Hintergrund). Default heller Grauton wie die three.js-Sicht.
pub clear_color: wgpu::Color,
}
@@ -973,7 +978,11 @@ impl Renderer {
}],
});
let points =
PointRenderer::new(device, &bind_group_layout, color_format, DEPTH_FORMAT, SAMPLE_COUNT);
Self {
points,
pipeline,
hidden_face_pipeline,
grid_pipeline,
@@ -1022,6 +1031,43 @@ impl Renderer {
}
}
/// Setzt/ersetzt die Punktwolke `id` ([27]); `None` (unbrauchbare Eingabe) entfernt sie.
pub fn set_point_cloud(
&mut self,
device: &wgpu::Device,
id: u32,
cloud: Option<PointCloudCpu>,
style: PointStyle,
) {
self.points.set_cloud(device, id, cloud, style);
}
/// Nur die Darstellung einer Punktwolke aendern (Farbmodus/Groesse/Sichtbarkeit).
/// `false`, wenn die Wolke unbekannt ist.
pub fn set_point_cloud_style(&mut self, queue: &wgpu::Queue, id: u32, style: PointStyle) -> bool {
self.points.set_style(queue, id, style)
}
/// Entfernt die Punktwolke `id` (unbekannt = nichts).
pub fn remove_point_cloud(&mut self, id: u32) {
self.points.remove(id);
}
/// Entfernt alle Punktwolken.
pub fn clear_point_clouds(&mut self) {
self.points.clear();
}
/// Punktzahl der Wolke `id` (0 = unbekannt).
pub fn point_cloud_len(&self, id: u32) -> usize {
self.points.point_count(id)
}
/// World-Bounding-Box aller sichtbaren Punktwolken.
pub fn point_cloud_bounds(&self) -> Option<([f32; 3], [f32; 3])> {
self.points.bounds()
}
/// Erzeugt das Mesh aus geflachten Waenden und laedt die Puffer hoch.
pub fn upload_walls(&mut self, device: &wgpu::Device, walls: &[WallInput]) {
self.upload_mesh(device, build_walls_mesh(walls), build_walls_mesh_textured(walls));
@@ -1713,6 +1759,9 @@ impl Renderer {
}
}
// Punktwolken: Viewport/Punktgroesse in die Uniforms (feste Pixelgroesse).
self.points.prepare(queue, (w, h));
let depth_view = &self.depth.as_ref().unwrap().view;
let msaa_view = &self.msaa.as_ref().unwrap().view;
@@ -1890,6 +1939,10 @@ impl Renderer {
pass.draw(0..dl.vertex_count, 0..1);
}
// 2d) Punktwolken ([27]): Instanz-Quads, tiefengetestet gegen Modell/Unterlage —
// stilunabhaengig (gemessene Bestandsdaten gehoeren in jede Darstellung).
self.points.draw(&mut pass, &self.bind_group);
// 3) Bodengitter NACH dem Modell zeichnen (gemeinsamer Tiefenpuffer ->
// das Modell verdeckt das Gitter korrekt). Unabhaengig vom Stil, nur
// wenn sichtbar + vorhanden.
+458
View File
@@ -0,0 +1,458 @@
// GPU-Teil der Punktwolken ([27]): eigene Pipeline neben Mesh/Grid im selben Render-Pass,
// dasselbe Tiefen-/MSAA-/Farbziel (sonst inkompatibler Pass) und dieselbe `Globals`-Bind-Group.
// Läuft unverändert auf WebGPU (Browser) und nativ (Metal/Vulkan) — `Renderer` ruft nur
// `prepare` vor und `draw` im Pass auf.
//
// Je Punkt ein Instanz-Eintrag (Position 12 B + RGBA8 4 B); das Quad entsteht im Vertex-Shader
// aus `vertex_index` (6 Vertices je Instanz, kein Index-/Geometriepuffer je Punkt). Grosse Wolken
// liegen in Puffern zu höchstens `MAX_POINTS_PER_CHUNK` Punkten (je ein Draw-Call).
use std::collections::BTreeMap;
use bytemuck::{Pod, Zeroable};
use wgpu::util::DeviceExt;
use crate::points::{chunk_ranges, clamp_point_size, PointCloudCpu, PointColorMode, POINT_WGSL};
/// Uniform je Wolke, 1:1 zu `PointParams` im WGSL.
#[repr(C)]
#[derive(Clone, Copy, Pod, Zeroable)]
struct PointParams {
/// x = Grösse px, y/z = Viewport px, w = runde Punkte (1/0).
params: [f32; 4],
}
struct PointChunk {
positions: wgpu::Buffer,
colors: wgpu::Buffer,
start: usize,
count: u32,
}
struct PointCloudGpu {
cpu: PointCloudCpu,
chunks: Vec<PointChunk>,
uniform: wgpu::Buffer,
bind_group: wgpu::BindGroup,
mode: PointColorMode,
size_px: f32,
visible: bool,
}
/// Darstellungs-Einstellungen einer Wolke.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct PointStyle {
pub mode: PointColorMode,
pub size_px: f32,
pub visible: bool,
}
/// Alle Punktwolken des Renderers + ihre Pipeline.
pub struct PointRenderer {
pipeline: wgpu::RenderPipeline,
params_layout: wgpu::BindGroupLayout,
clouds: BTreeMap<u32, PointCloudGpu>,
}
impl PointRenderer {
/// `globals_layout` = group(0) der übrigen Pipelines; Ziel-Format, Tiefenformat und Samples
/// müssen mit dem Haupt-Pass übereinstimmen.
pub fn new(
device: &wgpu::Device,
globals_layout: &wgpu::BindGroupLayout,
color_format: wgpu::TextureFormat,
depth_format: wgpu::TextureFormat,
sample_count: u32,
) -> Self {
let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("points.wgsl"),
source: wgpu::ShaderSource::Wgsl(POINT_WGSL.into()),
});
let params_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("points.params.layout"),
entries: &[wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: wgpu::BufferSize::new(std::mem::size_of::<PointParams>() as u64),
},
count: None,
}],
});
let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("points.layout"),
bind_group_layouts: &[Some(globals_layout), Some(&params_layout)],
immediate_size: 0,
});
let pos_layout = wgpu::VertexBufferLayout {
array_stride: 12,
step_mode: wgpu::VertexStepMode::Instance,
attributes: &wgpu::vertex_attr_array![0 => Float32x3],
};
let col_layout = wgpu::VertexBufferLayout {
array_stride: 4,
step_mode: wgpu::VertexStepMode::Instance,
attributes: &wgpu::vertex_attr_array![1 => Unorm8x4],
};
let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("points.pipeline"),
layout: Some(&layout),
vertex: wgpu::VertexState {
module: &module,
entry_point: Some("vs_main"),
buffers: &[pos_layout, col_layout],
compilation_options: Default::default(),
},
fragment: Some(wgpu::FragmentState {
module: &module,
entry_point: Some("fs_main"),
targets: &[Some(wgpu::ColorTargetState {
format: color_format,
blend: Some(wgpu::BlendState::REPLACE),
write_mask: wgpu::ColorWrites::ALL,
})],
compilation_options: Default::default(),
}),
primitive: wgpu::PrimitiveState {
topology: wgpu::PrimitiveTopology::TriangleList,
// Bildschirm-Quads, immer zur Kamera gewandt — kein Culling nötig.
cull_mode: None,
..Default::default()
},
// Tiefentest gegen das Modell (Wände verdecken Punkte dahinter) und Tiefe schreiben
// (Punkte verdecken Gitter/Kanten dahinter).
depth_stencil: Some(wgpu::DepthStencilState {
format: depth_format,
depth_write_enabled: Some(true),
depth_compare: Some(wgpu::CompareFunction::Less),
stencil: wgpu::StencilState::default(),
bias: wgpu::DepthBiasState::default(),
}),
multisample: wgpu::MultisampleState {
count: sample_count,
mask: !0,
alpha_to_coverage_enabled: false,
},
multiview_mask: None,
cache: None,
});
Self {
pipeline,
params_layout,
clouds: BTreeMap::new(),
}
}
/// Setzt/ersetzt die Wolke `id`. `None`-Daten (unbrauchbare Eingabe) entfernen sie.
pub fn set_cloud(
&mut self,
device: &wgpu::Device,
id: u32,
cpu: Option<PointCloudCpu>,
style: PointStyle,
) {
let Some(cpu) = cpu else {
self.clouds.remove(&id);
return;
};
let size_px = clamp_point_size(style.size_px);
let colors = cpu.colors(style.mode);
let chunks = chunk_ranges(cpu.len())
.into_iter()
.map(|(start, count)| PointChunk {
positions: device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("points.positions"),
contents: bytemuck::cast_slice(&cpu.positions[start * 3..(start + count) * 3]),
usage: wgpu::BufferUsages::VERTEX,
}),
colors: device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("points.colors"),
contents: bytemuck::cast_slice(&colors[start..start + count]),
usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
}),
start,
count: count as u32,
})
.collect();
let uniform = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("points.params"),
size: std::mem::size_of::<PointParams>() as u64,
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("points.params.bind"),
layout: &self.params_layout,
entries: &[wgpu::BindGroupEntry {
binding: 0,
resource: uniform.as_entire_binding(),
}],
});
self.clouds.insert(
id,
PointCloudGpu {
cpu,
chunks,
uniform,
bind_group,
mode: style.mode,
size_px,
visible: style.visible,
},
);
}
/// Ändert nur die Darstellung (Farbmodus, Grösse, Sichtbarkeit). Bei neuem Farbmodus wird nur
/// der Farbpuffer überschrieben (Positionen bleiben). `false`, wenn `id` unbekannt ist.
pub fn set_style(&mut self, queue: &wgpu::Queue, id: u32, style: PointStyle) -> bool {
let Some(c) = self.clouds.get_mut(&id) else {
return false;
};
c.size_px = clamp_point_size(style.size_px);
c.visible = style.visible;
if c.cpu.effective_mode(style.mode) != c.cpu.effective_mode(c.mode) {
let colors = c.cpu.colors(style.mode);
for ch in &c.chunks {
let end = ch.start + ch.count as usize;
queue.write_buffer(&ch.colors, 0, bytemuck::cast_slice(&colors[ch.start..end]));
}
}
c.mode = style.mode;
true
}
pub fn remove(&mut self, id: u32) {
self.clouds.remove(&id);
}
pub fn clear(&mut self) {
self.clouds.clear();
}
/// Anzahl Punkte der Wolke `id` (0 = unbekannt), für Bindungen/Tests.
pub fn point_count(&self, id: u32) -> usize {
self.clouds.get(&id).map_or(0, |c| c.cpu.len())
}
/// World-Bounding-Box aller sichtbaren Wolken (für das Einpassen der Kamera).
pub fn bounds(&self) -> Option<([f32; 3], [f32; 3])> {
let mut min = [f32::INFINITY; 3];
let mut max = [f32::NEG_INFINITY; 3];
for c in self.clouds.values().filter(|c| c.visible) {
for p in c.cpu.positions.chunks_exact(3) {
for i in 0..3 {
min[i] = min[i].min(p[i]);
max[i] = max[i].max(p[i]);
}
}
}
min[0].is_finite().then_some((min, max))
}
/// Je Frame vor dem Pass: Viewport/Grösse in die Uniforms schreiben.
pub fn prepare(&self, queue: &wgpu::Queue, viewport: (u32, u32)) {
for c in self.clouds.values().filter(|c| c.visible) {
let round = if c.size_px >= 3.0 { 1.0 } else { 0.0 };
let p = PointParams {
params: [c.size_px, viewport.0.max(1) as f32, viewport.1.max(1) as f32, round],
};
queue.write_buffer(&c.uniform, 0, bytemuck::bytes_of(&p));
}
}
/// Im Haupt-Pass: alle sichtbaren Wolken zeichnen (ein Draw-Call je Puffer).
pub fn draw<'a>(&'a self, pass: &mut wgpu::RenderPass<'a>, globals: &'a wgpu::BindGroup) {
let mut bound = false;
for c in self.clouds.values().filter(|c| c.visible) {
if !bound {
pass.set_pipeline(&self.pipeline);
pass.set_bind_group(0, globals, &[]);
bound = true;
}
pass.set_bind_group(1, &c.bind_group, &[]);
for ch in &c.chunks {
pass.set_vertex_buffer(0, ch.positions.slice(..));
pass.set_vertex_buffer(1, ch.colors.slice(..));
pass.draw(0..6, 0..ch.count);
}
}
}
}
// Headless-Render in eine Textur (Vulkan/lavapipe im Linux-Container, Metal auf macOS). Ohne
// GPU-Adapter wird der Test übersprungen (Meldung auf stderr) statt rot.
#[cfg(test)]
mod gpu_tests {
use super::PointStyle;
use crate::gpu::Renderer;
use crate::points::{PointCloudCpu, PointColorMode};
use crate::types::{Camera, WallInput};
const W: u32 = 64;
const H: u32 = 64;
const FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8Unorm;
fn device() -> Option<(wgpu::Device, wgpu::Queue)> {
let instance = wgpu::Instance::default();
let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions {
power_preference: wgpu::PowerPreference::default(),
force_fallback_adapter: false,
compatible_surface: None,
}))
.ok()?;
pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor {
label: Some("points.test"),
required_features: wgpu::Features::empty(),
required_limits: wgpu::Limits::default(),
experimental_features: wgpu::ExperimentalFeatures::disabled(),
memory_hints: wgpu::MemoryHints::Performance,
trace: wgpu::Trace::Off,
}))
.ok()
}
/// Rendert und liefert RGBA8 aller Pixel.
fn render(device: &wgpu::Device, queue: &wgpu::Queue, r: &mut Renderer, cam: &Camera) -> Vec<u8> {
let tex = device.create_texture(&wgpu::TextureDescriptor {
label: None,
size: wgpu::Extent3d { width: W, height: H, depth_or_array_layers: 1 },
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: FORMAT,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
view_formats: &[],
});
let view = tex.create_view(&wgpu::TextureViewDescriptor::default());
r.render(device, queue, &view, cam, (W, H));
let padded = (W * 4).div_ceil(256) * 256;
let buf = device.create_buffer(&wgpu::BufferDescriptor {
label: None,
size: (padded * H) as u64,
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
mapped_at_creation: false,
});
let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None });
enc.copy_texture_to_buffer(
wgpu::TexelCopyTextureInfo {
texture: &tex,
mip_level: 0,
origin: wgpu::Origin3d::ZERO,
aspect: wgpu::TextureAspect::All,
},
wgpu::TexelCopyBufferInfo {
buffer: &buf,
layout: wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(padded),
rows_per_image: Some(H),
},
},
wgpu::Extent3d { width: W, height: H, depth_or_array_layers: 1 },
);
queue.submit([enc.finish()]);
let slice = buf.slice(..);
slice.map_async(wgpu::MapMode::Read, |r| r.expect("Readback"));
let _ = device.poll(wgpu::PollType::wait_indefinitely());
let data = slice.get_mapped_range();
let mut out = Vec::with_capacity((W * H * 4) as usize);
for y in 0..H as usize {
out.extend_from_slice(&data[y * padded as usize..y * padded as usize + W as usize * 4]);
}
out
}
fn pixel(img: &[u8], x: u32, y: u32) -> [u8; 3] {
let i = ((y * W + x) * 4) as usize;
[img[i], img[i + 1], img[i + 2]]
}
fn is_red(c: [u8; 3]) -> bool {
c[0] > 200 && c[1] < 40 && c[2] < 40
}
/// Senkrechte Punkt-Fläche 2 × 2 m (Modell x −1..1, Höhe 0..2) auf Modell-y = `y`, rot.
fn red_sheet(y: f64) -> PointCloudCpu {
let mut xyz = Vec::new();
let mut rgb = Vec::new();
for i in 0..=40 {
for k in 0..=40 {
xyz.extend_from_slice(&[-1.0 + i as f32 * 0.05, 0.0, k as f32 * 0.05]);
rgb.extend_from_slice(&[255, 0, 0]);
}
}
PointCloudCpu::from_raw(&xyz, &rgb, &[], &[], [0.0, y, 0.0]).unwrap()
}
fn camera() -> Camera {
// Blick von world +z (Modell-Süd, Nord-Achse negiert) auf den Nullpunkt, 1 m hoch.
Camera { eye: [0.0, 1.0, 10.0], target: [0.0, 1.0, 0.0], ..Camera::default() }
}
const STYLE: PointStyle = PointStyle { mode: PointColorMode::Rgb, size_px: 4.0, visible: true };
#[test]
fn points_render_visible_and_respect_depth_of_model() {
let Some((device, queue)) = device() else {
eprintln!("kein GPU-Adapter — Punkt-Render-Test übersprungen");
return;
};
let mut r = Renderer::new(&device, FORMAT);
let wall: WallInput =
serde_json::from_str(r#"{"start":[-3,0],"end":[3,0],"thickness":0.2,"height":3}"#).unwrap();
r.upload_model(&device, &[wall], &[], &[]);
let cam = camera();
// Wolke VOR der Wand (Modell-y = −3 → world z = +3): rot in der Bildmitte.
r.set_point_cloud(&device, 1, Some(red_sheet(-3.0)), STYLE);
assert_eq!(r.point_cloud_len(1), 41 * 41);
let img = render(&device, &queue, &mut r, &cam);
let c = pixel(&img, W / 2, H / 2);
assert!(is_red(c), "Mitte sollte rot sein: {c:?}");
// Wolke HINTER der Wand (Modell-y = +5 → world z = −5): Wand verdeckt sie.
r.set_point_cloud(&device, 1, Some(red_sheet(5.0)), STYLE);
let img = render(&device, &queue, &mut r, &cam);
let c = pixel(&img, W / 2, H / 2);
assert!(!is_red(c), "Wand muss Punkte verdecken: {c:?}");
// Unsichtbar geschaltet: auch vor der Wand nichts Rotes.
r.set_point_cloud(&device, 1, Some(red_sheet(-3.0)), STYLE);
assert!(r.set_point_cloud_style(&queue, 1, PointStyle { visible: false, ..STYLE }));
let img = render(&device, &queue, &mut r, &cam);
assert!(!is_red(pixel(&img, W / 2, H / 2)), "unsichtbare Wolke gezeichnet");
// Farbmodus Höhe: nur der Farbpuffer wird ersetzt → Mitte nicht mehr Rot, nicht Hintergrund.
let height = PointStyle { mode: PointColorMode::Height, ..STYLE };
assert!(r.set_point_cloud_style(&queue, 1, height));
let img = render(&device, &queue, &mut r, &cam);
let c = pixel(&img, W / 2, H / 2);
assert!(!is_red(c) && c != pixel(&img, 0, 0), "Höhenfarbe erwartet: {c:?}");
// Entfernen + unbekannte id.
r.remove_point_cloud(1);
assert_eq!(r.point_cloud_len(1), 0);
assert!(!r.set_point_cloud_style(&queue, 1, STYLE));
}
#[test]
fn fixed_pixel_size_independent_of_distance() {
let Some((device, queue)) = device() else {
eprintln!("kein GPU-Adapter — Punkt-Render-Test übersprungen");
return;
};
let mut r = Renderer::new(&device, FORMAT);
let one = PointCloudCpu::from_raw(&[0.0, 0.0, 1.0], &[0, 0, 255], &[], &[], [0.0; 3]).unwrap();
let count_blue =
|img: &[u8]| img.chunks_exact(4).filter(|p| p[2] > 200 && p[0] < 60 && p[1] < 60).count();
r.set_point_cloud(&device, 7, Some(one), PointStyle { size_px: 8.0, ..STYLE });
let near = render(&device, &queue, &mut r, &Camera { eye: [0.0, 1.0, 5.0], ..camera() });
let far = render(&device, &queue, &mut r, &Camera { eye: [0.0, 1.0, 50.0], ..camera() });
let (a, b) = (count_blue(&near), count_blue(&far));
// Runder Punkt Ø 8 px ≈ 50 px Fläche, unabhängig vom Abstand.
assert!(a > 25 && a < 80, "nah: {a}");
assert!((a as i32 - b as i32).abs() <= 6, "nah {a} vs fern {b}");
}
}
+3
View File
@@ -18,6 +18,7 @@ pub mod edges;
pub mod grid;
pub mod math;
pub mod mesh;
pub mod points;
pub(crate) mod openings;
pub mod roof_cut;
pub mod section;
@@ -28,6 +29,8 @@ pub mod types;
#[cfg(feature = "render")]
pub mod gpu;
#[cfg(feature = "render")]
pub mod gpu_points;
// Browser-Bindings (wasm32 + WebGPU), nur mit Feature "web". Setzt "render" voraus
// (dieselbe GPU-Schicht wie das native Fenster), fuegt aber KEINE winit-Abhaengigkeit
+528
View File
@@ -0,0 +1,528 @@
// Punktwolken für den 3D-Viewport ([27], Stufe 1): GPU-freie Schicht (Puffer-Aufbau, Farbabbildung,
// WGSL-Quelle). Die Pipeline selbst liegt in `gpu_points.rs` (Feature "render") und läuft so
// unverändert im Browser (WebGPU, `web.rs`) wie nativ (Metal/Vulkan: `render_png`, `native.rs`).
//
// Eingabe: wie der Leser sie liefert (`src/io/pointCloud.ts`, `fileio/pointcloud*.rs`) — `xyz` als
// f32 RELATIV zu einem Ursprung, dazu der Modellversatz dieses Ursprungs als f64 (Modell-Meter,
// x = Ost, y = Nord, z = Höhe). Die Summe wird hier in f64 gebildet und erst danach auf f32
// gerundet: LV95-Koordinaten (2,6 Mio. m) kippen so nie in f32 (dort nur ~0,25 m Auflösung).
//
// Achsen: wie die übrigen ECHTEN Geo-Rohdaten (Gelände/Import, `mesh::append_context_mesh`,
// `MeshKind::Terrain`): Modell (x, y, z) → world (x, z, −y). So liegt eine Punktwolke deckungsgleich
// auf einem swissALTI3D-Gelände desselben Standort-Bezugs.
//
// Darstellung: ein Instanz-Quad je Punkt (6 Vertices aus `vertex_index`, keine Geometrie je Punkt
// im Puffer), feste Grösse in Bildschirm-Pixeln, tiefengetestet gegen das Modell. Farben werden auf
// der CPU berechnet (eine Quelle der Wahrheit, testbar) und als eigener RGBA8-Puffer neben den
// Positionen gehalten — ein Wechsel des Farbmodus lädt nur diesen kleinen Puffer neu.
/// Farbmodus einer Punktwolke.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PointColorMode {
/// Gemessene Farbe (RGB aus der Datei); ohne Farbe → Höhe.
Rgb,
/// Intensität als Grauwert (robuster Bereich 1.–99. Perzentil); ohne Intensität → Höhe.
Intensity,
/// ASPRS-Klassifikation (Boden, Vegetation, Gebäude …); ohne Klassen → Höhe.
Class,
/// Höhe als Farbverlauf (blau → grün → gelb → rot).
Height,
}
impl PointColorMode {
/// Parst den API-String ("rgb" | "intensity" | "class" | "height"); Unbekanntes → `Rgb`.
pub fn from_str_or_rgb(s: &str) -> Self {
match s {
"intensity" => PointColorMode::Intensity,
"class" => PointColorMode::Class,
"height" => PointColorMode::Height,
_ => PointColorMode::Rgb,
}
}
}
/// Höchstzahl Punkte je GPU-Puffer. 4 Mio. × 12 Byte = 48 MB — sicher unter dem WebGPU-Standard-
/// limit `maxBufferSize` (256 MB) und `maxStorageBufferBindingSize`; grössere Wolken werden auf
/// mehrere Puffer (je ein Draw-Call) verteilt, nie ein Draw je Punkt.
pub const MAX_POINTS_PER_CHUNK: usize = 4_000_000;
/// Grenzen der Punktgrösse in Bildschirm-Pixeln (Klemmung aller Eingaben).
pub const MIN_POINT_SIZE_PX: f32 = 1.0;
pub const MAX_POINT_SIZE_PX: f32 = 32.0;
/// Klemmt eine Punktgrösse (NaN → 2 px).
pub fn clamp_point_size(px: f32) -> f32 {
if px.is_finite() {
px.clamp(MIN_POINT_SIZE_PX, MAX_POINT_SIZE_PX)
} else {
2.0
}
}
/// CPU-Seite einer Punktwolke: world-Positionen (f32, bereits mit Versatz) und die optionalen
/// Attribute, gefiltert auf gültige Punkte (NaN/∞ fliegen raus, Attribute bleiben ausgerichtet).
#[derive(Clone, Debug, Default)]
pub struct PointCloudCpu {
/// world x, y (= Höhe), z (= −Nord) je Punkt.
pub positions: Vec<f32>,
pub rgb: Option<Vec<u8>>,
pub intensity: Option<Vec<u16>>,
pub classification: Option<Vec<u8>>,
/// Höhenbereich (world y) aller Punkte, für den Höhen-Farbverlauf.
pub height_range: [f32; 2],
}
impl PointCloudCpu {
/// Baut die world-Positionen aus `xyz` (relativ, f32) + `offset` (Modell-Meter des Ursprungs, f64).
/// Attribute mit falscher Länge werden ignoriert (nicht abgeschnitten — lieber keine Farbe als
/// verrutschte). `None` bei unbrauchbarer Eingabe (kein vollständiger Punkt, Versatz nicht endlich).
pub fn from_raw(
xyz: &[f32],
rgb: &[u8],
intensity: &[u16],
classification: &[u8],
offset: [f64; 3],
) -> Option<Self> {
if !offset.iter().all(|v| v.is_finite()) {
return None;
}
let n = xyz.len() / 3;
if n == 0 {
return None;
}
let rgb = (rgb.len() == n * 3).then_some(rgb);
let intensity = (intensity.len() == n).then_some(intensity);
let classification = (classification.len() == n).then_some(classification);
let mut positions = Vec::with_capacity(n * 3);
let mut out_rgb = rgb.map(|_| Vec::with_capacity(n * 3));
let mut out_int = intensity.map(|_| Vec::with_capacity(n));
let mut out_cls = classification.map(|_| Vec::with_capacity(n));
let mut hmin = f32::INFINITY;
let mut hmax = f32::NEG_INFINITY;
for i in 0..n {
let (x, y, z) = (xyz[i * 3], xyz[i * 3 + 1], xyz[i * 3 + 2]);
if !(x.is_finite() && y.is_finite() && z.is_finite()) {
continue;
}
// In f64 addieren, erst dann runden (LV95-fest).
let wx = (offset[0] + x as f64) as f32;
let wy = (offset[2] + z as f64) as f32;
let wz = -((offset[1] + y as f64) as f32);
if !(wx.is_finite() && wy.is_finite() && wz.is_finite()) {
continue;
}
positions.extend_from_slice(&[wx, wy, wz]);
hmin = hmin.min(wy);
hmax = hmax.max(wy);
if let (Some(o), Some(src)) = (out_rgb.as_mut(), rgb) {
o.extend_from_slice(&src[i * 3..i * 3 + 3]);
}
if let (Some(o), Some(src)) = (out_int.as_mut(), intensity) {
o.push(src[i]);
}
if let (Some(o), Some(src)) = (out_cls.as_mut(), classification) {
o.push(src[i]);
}
}
if positions.is_empty() {
return None;
}
Some(Self {
positions,
rgb: out_rgb,
intensity: out_int,
classification: out_cls,
height_range: [hmin, hmax],
})
}
/// Anzahl Punkte.
pub fn len(&self) -> usize {
self.positions.len() / 3
}
pub fn is_empty(&self) -> bool {
self.positions.is_empty()
}
/// Welcher Modus tatsächlich gezeichnet wird (fehlt das Attribut, fällt er auf Höhe zurück).
pub fn effective_mode(&self, mode: PointColorMode) -> PointColorMode {
let has = match mode {
PointColorMode::Rgb => self.rgb.is_some(),
PointColorMode::Intensity => self.intensity.is_some(),
PointColorMode::Class => self.classification.is_some(),
PointColorMode::Height => true,
};
if has {
mode
} else {
PointColorMode::Height
}
}
/// RGBA8 je Punkt (Alpha 255) für den Farbmodus — der Inhalt des Farb-Vertex-Puffers.
pub fn colors(&self, mode: PointColorMode) -> Vec<[u8; 4]> {
let n = self.len();
match self.effective_mode(mode) {
PointColorMode::Rgb => {
let rgb = self.rgb.as_deref().unwrap_or(&[]);
(0..n).map(|i| [rgb[i * 3], rgb[i * 3 + 1], rgb[i * 3 + 2], 255]).collect()
}
PointColorMode::Intensity => {
let it = self.intensity.as_deref().unwrap_or(&[]);
let [lo, hi] = intensity_window(it);
let span = (hi as f32 - lo as f32).max(1.0);
it.iter()
.map(|&v| {
let t = ((v as f32 - lo as f32) / span).clamp(0.0, 1.0);
// Leicht angehoben (nie ganz schwarz) — dunkle Punkte bleiben auf dem
// dunklen Hintergrund/Modell sichtbar.
let g = (30.0 + t * 225.0).round() as u8;
[g, g, g, 255]
})
.collect()
}
PointColorMode::Class => {
let cls = self.classification.as_deref().unwrap_or(&[]);
cls.iter()
.map(|&c| {
let [r, g, b] = class_color(c);
[r, g, b, 255]
})
.collect()
}
PointColorMode::Height => {
let [lo, hi] = self.height_range;
let span = (hi - lo).max(1e-6);
(0..n)
.map(|i| {
let t = (self.positions[i * 3 + 1] - lo) / span;
let [r, g, b] = height_ramp(t);
[r, g, b, 255]
})
.collect()
}
}
}
}
/// Robuster Intensitätsbereich: 1.–99. Perzentil (Histogramm über u16), damit einzelne Ausreisser
/// (Reflektoren) nicht die ganze Wolke grau in grau machen. Leer → [0, 65535].
pub fn intensity_window(values: &[u16]) -> [u16; 2] {
if values.is_empty() {
return [0, u16::MAX];
}
let mut hist = vec![0u32; 65_536];
for &v in values {
hist[v as usize] += 1;
}
let n = values.len() as u64;
let lo_rank = n / 100;
let hi_rank = n - 1 - n / 100;
let mut acc: u64 = 0;
let mut lo = None;
let mut hi = u16::MAX;
for (v, &c) in hist.iter().enumerate() {
if c == 0 {
continue;
}
let next = acc + c as u64;
if lo.is_none() && next > lo_rank {
lo = Some(v as u16);
}
if next > hi_rank {
hi = v as u16;
break;
}
acc = next;
}
let lo = lo.unwrap_or(0);
[lo, hi.max(lo)]
}
/// Farben der ASPRS-Standardklassen (LAS 1.4, Tabelle 17). Unbekannte/benutzerdefinierte Klassen →
/// neutrales Grau.
pub fn class_color(c: u8) -> [u8; 3] {
match c {
0 | 1 => [170, 170, 170], // nie klassifiziert / nicht zugeordnet
2 => [166, 120, 72], // Boden
3 => [170, 210, 120], // niedrige Vegetation
4 => [96, 170, 72], // mittlere Vegetation
5 => [40, 120, 50], // hohe Vegetation
6 => [214, 90, 70], // Gebäude
7 => [255, 0, 255], // Rauschen (tief)
8 => [240, 220, 60], // Modell-Schlüsselpunkt (LAS 1.0–1.3)
9 => [70, 130, 220], // Wasser
10 => [120, 80, 160], // Schiene
11 => [90, 90, 90], // Strassenoberfläche
13 => [250, 160, 40], // Leitungsschutz
14 => [250, 200, 40], // Leitung
15 => [200, 60, 160], // Mast
17 => [130, 110, 100], // Brücke
18 => [255, 80, 255], // Rauschen (hoch)
_ => [140, 140, 140],
}
}
/// Höhen-Farbverlauf (t ∈ [0,1], ausserhalb geklemmt): blau → cyan → grün → gelb → rot.
pub fn height_ramp(t: f32) -> [u8; 3] {
const STOPS: [[f32; 3]; 5] = [
[40.0, 70.0, 200.0],
[40.0, 180.0, 220.0],
[80.0, 190.0, 80.0],
[240.0, 220.0, 60.0],
[220.0, 60.0, 40.0],
];
let t = if t.is_finite() { t.clamp(0.0, 1.0) } else { 0.0 };
let f = t * (STOPS.len() - 1) as f32;
let i = (f.floor() as usize).min(STOPS.len() - 2);
let u = f - i as f32;
let a = STOPS[i];
let b = STOPS[i + 1];
[
(a[0] + (b[0] - a[0]) * u).round() as u8,
(a[1] + (b[1] - a[1]) * u).round() as u8,
(a[2] + (b[2] - a[2]) * u).round() as u8,
]
}
/// Teilt `n` Punkte in Puffer-Bereiche von höchstens `MAX_POINTS_PER_CHUNK` (Start, Anzahl).
pub fn chunk_ranges(n: usize) -> Vec<(usize, usize)> {
let mut out = Vec::new();
let mut s = 0;
while s < n {
let c = (n - s).min(MAX_POINTS_PER_CHUNK);
out.push((s, c));
s += c;
}
out
}
/// Vertex-Shader-Ecken des Instanz-Quads (zwei Dreiecke, CCW), in Einheiten der halben Punktgrösse.
pub const QUAD_CORNERS: [[f32; 2]; 6] = [
[-1.0, -1.0],
[1.0, -1.0],
[1.0, 1.0],
[-1.0, -1.0],
[1.0, 1.0],
[-1.0, 1.0],
];
/// WGSL der Punkt-Pipeline. group(0) = dasselbe `Globals` wie Mesh/Grid (View-Projektion,
/// Live-Schnitt); group(1) = Punkt-Parameter (`params.x` = Grösse px, `yz` = Viewport px,
/// `w` > 0.5 = runde Punkte). Instanz-Attribute: Position (world) + RGBA8-Farbe.
pub const POINT_WGSL: &str = r#"
struct Globals {
view_proj : mat4x4<f32>,
light_dir : vec4<f32>,
sky_color : vec4<f32>,
ground_color : vec4<f32>,
sun_color : vec4<f32>,
mode : vec4<f32>,
section_plane : vec4<f32>,
};
@group(0) @binding(0) var<uniform> globals : Globals;
struct PointParams {
params : vec4<f32>,
};
@group(1) @binding(0) var<uniform> point : PointParams;
struct VsIn {
@builtin(vertex_index) vi : u32,
@location(0) position : vec3<f32>,
@location(1) color : vec4<f32>,
};
struct VsOut {
@builtin(position) clip_pos : vec4<f32>,
@location(0) color : vec3<f32>,
@location(1) world_pos : vec3<f32>,
@location(2) corner : vec2<f32>,
};
@vertex
fn vs_main(in : VsIn) -> VsOut {
var corners = array<vec2<f32>, 6>(
vec2<f32>(-1.0, -1.0), vec2<f32>(1.0, -1.0), vec2<f32>(1.0, 1.0),
vec2<f32>(-1.0, -1.0), vec2<f32>(1.0, 1.0), vec2<f32>(-1.0, 1.0),
);
let c = corners[in.vi % 6u];
var clip = globals.view_proj * vec4<f32>(in.position, 1.0);
// Feste Bildschirmgrösse: Versatz in NDC (2 / Viewport je Pixel), mit w multipliziert, damit
// die Perspektiv-Division ihn nicht wieder verkleinert.
let vp = max(point.params.yz, vec2<f32>(1.0, 1.0));
let half_px = 0.5 * point.params.x;
clip = vec4<f32>(clip.xy + c * half_px * 2.0 / vp * clip.w, clip.zw);
var out : VsOut;
out.clip_pos = clip;
out.color = in.color.rgb;
out.world_pos = in.position;
out.corner = c;
return out;
}
@fragment
fn fs_main(in : VsOut) -> @location(0) vec4<f32> {
// Live-Schnitt wie Mesh/Grid: was hinter der Ebene liegt, fällt weg.
if (globals.mode.y > 0.5) {
if (dot(in.world_pos, globals.section_plane.xyz) + globals.section_plane.w > 0.0) {
discard;
}
}
if (point.params.w > 0.5 && dot(in.corner, in.corner) > 1.0) {
discard;
}
return vec4<f32>(in.color, 1.0);
}
"#;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn color_mode_parses_api_strings() {
assert_eq!(PointColorMode::from_str_or_rgb("rgb"), PointColorMode::Rgb);
assert_eq!(PointColorMode::from_str_or_rgb("intensity"), PointColorMode::Intensity);
assert_eq!(PointColorMode::from_str_or_rgb("class"), PointColorMode::Class);
assert_eq!(PointColorMode::from_str_or_rgb("height"), PointColorMode::Height);
assert_eq!(PointColorMode::from_str_or_rgb("quatsch"), PointColorMode::Rgb);
}
#[test]
fn positions_map_model_to_world_like_terrain() {
// Modell (x, y, z) → world (x, z, −y), Versatz addiert.
let c = PointCloudCpu::from_raw(&[1.0, 2.0, 3.0], &[], &[], &[], [10.0, 20.0, 30.0]).unwrap();
assert_eq!(c.positions, vec![11.0, 33.0, -22.0]);
assert_eq!(c.height_range, [33.0, 33.0]);
}
#[test]
fn lv95_offset_is_added_in_f64() {
// Ursprung in LV95 (2,6 Mio. m), Projekt-Nullpunkt 2 600 000 / 1 200 000: Versatz klein,
// aber die Summe Ursprung + Punkt darf nicht über f32 laufen. Hier: Versatz −0,5 (aus
// f64-Differenz), Punkt 0,123 → 0,623 mm-genau.
let off = [2_600_123.0_f64 - 2_600_123.5, 1_200_000.0 - 1_200_000.25, 0.0];
let c = PointCloudCpu::from_raw(&[0.123, 0.001, 0.0], &[], &[], &[], off).unwrap();
assert!((c.positions[0] - (-0.377)).abs() < 1e-6);
assert!((c.positions[2] - 0.249).abs() < 1e-6);
}
#[test]
fn invalid_points_are_dropped_and_attributes_stay_aligned() {
let xyz = [0.0, 0.0, 0.0, f32::NAN, 0.0, 0.0, 1.0, 1.0, 1.0];
let rgb = [1, 2, 3, 4, 5, 6, 7, 8, 9];
let it = [10u16, 20, 30];
let cls = [2u8, 6, 9];
let c = PointCloudCpu::from_raw(&xyz, &rgb, &it, &cls, [0.0; 3]).unwrap();
assert_eq!(c.len(), 2);
assert_eq!(c.rgb.as_deref(), Some(&[1, 2, 3, 7, 8, 9][..]));
assert_eq!(c.intensity.as_deref(), Some(&[10, 30][..]));
assert_eq!(c.classification.as_deref(), Some(&[2, 9][..]));
}
#[test]
fn broken_input_yields_none_not_panic() {
assert!(PointCloudCpu::from_raw(&[], &[], &[], &[], [0.0; 3]).is_none());
assert!(PointCloudCpu::from_raw(&[1.0, 2.0], &[], &[], &[], [0.0; 3]).is_none());
assert!(PointCloudCpu::from_raw(&[1.0, 2.0, 3.0], &[], &[], &[], [f64::NAN, 0.0, 0.0]).is_none());
assert!(PointCloudCpu::from_raw(&[f32::INFINITY, 0.0, 0.0], &[], &[], &[], [0.0; 3]).is_none());
// Überzählige xyz-Werte (kein ganzer Punkt) werden ignoriert.
let c = PointCloudCpu::from_raw(&[1.0, 2.0, 3.0, 4.0], &[], &[], &[], [0.0; 3]).unwrap();
assert_eq!(c.len(), 1);
}
#[test]
fn attributes_with_wrong_length_are_ignored() {
let c = PointCloudCpu::from_raw(&[0.0; 6], &[1, 2, 3], &[5], &[1, 2, 3], [0.0; 3]).unwrap();
assert!(c.rgb.is_none() && c.intensity.is_none() && c.classification.is_none());
// Ohne Attribut fällt jeder Modus auf Höhe zurück.
assert_eq!(c.effective_mode(PointColorMode::Rgb), PointColorMode::Height);
assert_eq!(c.effective_mode(PointColorMode::Class), PointColorMode::Height);
assert_eq!(c.colors(PointColorMode::Intensity).len(), 2);
}
#[test]
fn rgb_colors_pass_through() {
let c = PointCloudCpu::from_raw(&[0.0; 6], &[255, 0, 0, 0, 128, 255], &[], &[], [0.0; 3]).unwrap();
assert_eq!(c.colors(PointColorMode::Rgb), vec![[255, 0, 0, 255], [0, 128, 255, 255]]);
}
#[test]
fn class_colors_follow_asprs() {
let c = PointCloudCpu::from_raw(&[0.0; 9], &[], &[], &[2, 6, 200], [0.0; 3]).unwrap();
let col = c.colors(PointColorMode::Class);
assert_eq!(col[0], [166, 120, 72, 255]); // Boden
assert_eq!(col[1], [214, 90, 70, 255]); // Gebäude
assert_eq!(col[2], [140, 140, 140, 255]); // unbekannt
}
#[test]
fn height_ramp_runs_from_blue_to_red_by_world_height() {
// Modell-z 0 / 5 / 10 → world y; tiefster Punkt blau, höchster rot.
let xyz = [0.0, 0.0, 0.0, 0.0, 0.0, 5.0, 0.0, 0.0, 10.0];
let c = PointCloudCpu::from_raw(&xyz, &[], &[], &[], [0.0; 3]).unwrap();
let col = c.colors(PointColorMode::Height);
assert_eq!(&col[0][..3], &height_ramp(0.0)[..]);
assert_eq!(&col[2][..3], &height_ramp(1.0)[..]);
assert_eq!(height_ramp(0.0), [40, 70, 200]);
assert_eq!(height_ramp(1.0), [220, 60, 40]);
assert_eq!(height_ramp(f32::NAN), [40, 70, 200]);
assert_eq!(height_ramp(7.0), [220, 60, 40]);
}
#[test]
fn intensity_uses_robust_window() {
// 1000 Punkte 100..1099 plus ein Ausreisser 65535: der Ausreisser setzt den Bereich NICHT.
let mut it: Vec<u16> = (100..1100).collect();
it.push(65_535);
let w = intensity_window(&it);
assert!(w[0] >= 100 && w[0] < 120, "{w:?}");
assert!(w[1] > 1000 && w[1] < 1100, "{w:?}");
let xyz = vec![0.0f32; it.len() * 3];
let c = PointCloudCpu::from_raw(&xyz, &[], &it, &[], [0.0; 3]).unwrap();
let col = c.colors(PointColorMode::Intensity);
assert_eq!(col[0], [30, 30, 30, 255]); // dunkelstes Ende (nie schwarz)
assert_eq!(col[col.len() - 1], [255, 255, 255, 255]); // Ausreisser geklemmt
assert_eq!(intensity_window(&[]), [0, 65_535]);
assert_eq!(intensity_window(&[7, 7, 7]), [7, 7]);
}
#[test]
fn chunking_splits_large_clouds() {
assert!(chunk_ranges(0).is_empty());
assert_eq!(chunk_ranges(10), vec![(0, 10)]);
let r = chunk_ranges(MAX_POINTS_PER_CHUNK * 2 + 5);
assert_eq!(r.len(), 3);
assert_eq!(r[2], (MAX_POINTS_PER_CHUNK * 2, 5));
}
#[test]
fn point_size_is_clamped() {
assert_eq!(clamp_point_size(0.0), MIN_POINT_SIZE_PX);
assert_eq!(clamp_point_size(100.0), MAX_POINT_SIZE_PX);
assert_eq!(clamp_point_size(f32::NAN), 2.0);
assert_eq!(clamp_point_size(3.5), 3.5);
}
#[test]
fn point_wgsl_validates() {
use naga::valid::{Capabilities, ValidationFlags, Validator};
let module = naga::front::wgsl::parse_str(POINT_WGSL)
.unwrap_or_else(|e| panic!("points: WGSL-Parse-Fehler: {e:?}"));
Validator::new(ValidationFlags::all(), Capabilities::all())
.validate(&module)
.unwrap_or_else(|e| panic!("points: WGSL-Validierung fehlgeschlagen: {e:?}"));
}
#[test]
fn quad_corners_match_shader() {
// Die Ecken im WGSL müssen dieselben sein wie die Rust-Konstante (zwei CCW-Dreiecke).
for c in QUAD_CORNERS {
let s = format!("vec2<f32>({:.1}, {:.1})", c[0], c[1]);
assert!(POINT_WGSL.contains(&s), "fehlt im Shader: {s}");
}
}
}
+45 -21
View File
@@ -414,11 +414,13 @@ fn vs_main(in : VsIn) -> VsOut {
}
// Ein AA-gekantetes Linienband entlang der Koordinate `s` (in Einheiten von
// `spacing`): 1 auf der Linie, 0 dazwischen. `fwidth` glaettet blickwinkelrichtig.
fn line_band(s : f32, half_s : f32) -> f32 {
// `spacing`): 1 auf der Linie, 0 dazwischen. `fw` = fwidth von `s` glaettet blickwinkelrichtig;
// vom Aufrufer VOR jeder Verzweigung berechnet (Ableitungen nur in uniformem Kontrollfluss —
// Chrome/Tint verwirft den Shader sonst, und mit ihm den ganzen 3D-Pass).
fn line_band(s : f32, half_s : f32, fw : f32) -> f32 {
let frac = fract(s);
let dist = min(frac, 1.0 - frac);
let aa = max(fwidth(s), 1e-5);
let aa = max(fw, 1e-5);
return 1.0 - smoothstep(half_s, half_s + aa, dist);
}
@@ -431,15 +433,6 @@ fn fs_main(in : VsOut) -> @location(0) vec4<f32> {
let angle = in.hatch.y;
let scale = max(in.hatch.z, 0.05);
// none (0): leere (weisse) Schnittflaeche — wie „keine Schraffur" im 2D.
if (pattern == 0) {
return vec4<f32>(paper, 1.0);
}
// solid (1): Vollton (Poché) — z. B. Beton.
if (pattern == 1) {
return vec4<f32>(ink, 1.0);
}
// Muster-Koordinaten: (u,v) in Modell-Metern, um `angle` gedreht. Konvention
// wie die 2D-Schraffur (`hatchPreview.parallelLines`): `angle == 0` ergibt
// HORIZONTALE Linien (Phasen-Achse = dv), `+angle` dreht die Schar gegen den
@@ -461,28 +454,42 @@ fn fs_main(in : VsOut) -> @location(0) vec4<f32> {
let half = max(in.hatch.w * 0.005, 0.0001);
let half_s = half / spacing;
// Alle Ableitungen hier, vor jeder Verzweigung nach `pattern` (uniformer Kontrollfluss).
let su = du / spacing;
let sv = dv / spacing;
let fw_u = fwidth(su);
let fw_v = fwidth(sv);
let cell = spacing * 2.0;
let tri = abs(fract(du / cell) - 0.5) * 2.0; // 0..1 Dreieckswelle (Daemmung)
let fb = fract(dv / cell);
let fw_zig = fwidth(fb) + fwidth(tri);
// none (0): leere (weisse) Schnittflaeche — wie „keine Schraffur" im 2D.
if (pattern == 0) {
return vec4<f32>(paper, 1.0);
}
// solid (1): Vollton (Poché) — z. B. Beton.
if (pattern == 1) {
return vec4<f32>(ink, 1.0);
}
var line = 0.0;
if (pattern == 2) {
// diagonal: EINE Linienschar quer zur Phasen-Achse (dv). angle==0 →
// horizontal; `hatch.angle` (z. B. 45° bei Backstein) dreht sie wie im 2D.
line = line_band(dv / spacing, half_s);
line = line_band(sv, half_s, fw_v);
} else if (pattern == 3) {
// crosshatch: zwei Scharen ueber Kreuz (Phase dv + Phase du = +90°). Bei
// angle==0 horizontal+vertikal, bei 45° (Beton) das gekippte Kreuz — wie 2D.
line = max(
line_band(dv / spacing, half_s),
line_band(du / spacing, half_s)
line_band(sv, half_s, fw_v),
line_band(su, half_s, fw_u)
);
} else {
// insulation (4, Daemmung): Zickzack. Die Quer-Position (dv) folgt einer
// Dreieckswelle entlang der Lauf-Achse (du) — ein durchgehender Zickzack.
let cell = spacing * 2.0;
let a = du / cell;
let b = dv / cell;
let tri = abs(fract(a) - 0.5) * 2.0; // 0..1 Dreieckswelle
let fb = fract(b);
let d = min(abs(fb - tri), min(abs(fb - tri + 1.0), abs(fb - tri - 1.0)));
let aa = max(fwidth(fb) + fwidth(tri), 1e-5);
let aa = max(fw_zig, 1e-5);
let hw = half / cell;
line = 1.0 - smoothstep(hw, hw + aa, d);
}
@@ -491,3 +498,20 @@ fn fs_main(in : VsOut) -> @location(0) vec4<f32> {
return vec4<f32>(color, 1.0);
}
"#;
#[cfg(test)]
mod uniformity_tests {
/// Chrome/Tint verwirft Ableitungen (`fwidth`) in nicht-uniformem Kontrollfluss — und mit dem
/// Cap-Shader die ganze Cap-Pipeline, deren Fehler den GESAMTEN 3D-Pass ungültig macht (28.10.
/// im Browser-Build gesehen). naga prüft das nicht; darum hier: jedes `fwidth` im Cap-Shader
/// steht vor der ersten Verzweigung nach `pattern` und nicht in einer Hilfsfunktion.
#[test]
fn cap_shader_derivatives_before_pattern_branches() {
let src = super::CAP_WGSL;
let fs = src.find("fn fs_main").expect("fs_main");
let first_branch = src[fs..].find("if (pattern").expect("Verzweigung") + fs;
for (i, _) in src.match_indices("fwidth(") {
assert!(i > fs && i < first_branch, "fwidth an Stelle {i} ausserhalb des uniformen Teils");
}
}
}
+52
View File
@@ -584,6 +584,58 @@ impl WebModelRenderer {
self.renderer.clear_aerial();
}
/// Setzt/ersetzt die Punktwolke `id` ([27], `points.rs`/`gpu_points.rs`). `xyz` = f32 je Punkt
/// RELATIV zum Ursprung, `ox/oy/oz` = Modell-Meter dieses Ursprungs (f64; x = Ost, y = Nord,
/// z = Hoehe) — die Summe bildet Rust in f64. `rgb`/`intensity`/`classification` leer = fehlt
/// (falsche Laenge = ignoriert). `color_mode` ∈ rgb|intensity|class|height, `point_size` in
/// Bildschirm-Pixeln. Gibt die Anzahl gezeichneter Punkte zurueck; 0 = Eingabe unbrauchbar
/// (die Wolke `id` ist dann entfernt) — nie ein Panic.
#[allow(clippy::too_many_arguments)]
pub fn set_point_cloud(
&mut self,
id: u32,
xyz: &[f32],
rgb: &[u8],
intensity: &[u16],
classification: &[u8],
ox: f64,
oy: f64,
oz: f64,
color_mode: &str,
point_size: f32,
visible: bool,
) -> u32 {
let cpu = crate::points::PointCloudCpu::from_raw(xyz, rgb, intensity, classification, [ox, oy, oz]);
let style = crate::gpu_points::PointStyle {
mode: crate::points::PointColorMode::from_str_or_rgb(color_mode),
size_px: point_size,
visible,
};
self.renderer.set_point_cloud(&self.device, id, cpu, style);
self.renderer.point_cloud_len(id) as u32
}
/// Nur Darstellung der Punktwolke `id` aendern (ohne Neu-Hochladen der Positionen).
/// `false`, wenn die Wolke unbekannt ist (dann `set_point_cloud` aufrufen).
pub fn set_point_cloud_style(&mut self, id: u32, color_mode: &str, point_size: f32, visible: bool) -> bool {
let style = crate::gpu_points::PointStyle {
mode: crate::points::PointColorMode::from_str_or_rgb(color_mode),
size_px: point_size,
visible,
};
self.renderer.set_point_cloud_style(&self.queue, id, style)
}
/// Entfernt die Punktwolke `id` (unbekannt = nichts).
pub fn remove_point_cloud(&mut self, id: u32) {
self.renderer.remove_point_cloud(id);
}
/// Entfernt alle Punktwolken.
pub fn clear_point_clouds(&mut self) {
self.renderer.clear_point_clouds();
}
/// Surface an eine neue Pixelgroesse anpassen (DPR beachtet der Aufrufer).
pub fn resize(&mut self, width: u32, height: u32) {
let (w, h) = (width.max(1), height.max(1));