mod atlas;
mod clear;
mod collision;
mod columns;
mod density;
pub mod geo;
pub mod geojson;
pub mod gpu;
#[cfg(metal_backend)]
mod gpu_metal;
mod hooks;
mod images;
#[cfg(feature = "captions")]
mod labels;
mod lines;
mod map_view;
#[cfg(feature = "captions")]
mod msdf;
mod picking;
mod points;
mod polygon_mesh;
mod polygons;
pub use crate::math::precision;
mod segments;
pub(crate) mod shader;
mod shapes;
mod sprites;
pub use atlas::{AtlasError, AtlasRect, SharedAtlas, TextureAtlas};
pub use collision::{CollisionIndex, SharedCollision, SharedVisibility};
pub use columns::{Column, ColumnFormat};
pub use density::DensityMarks;
pub use hooks::{transition_offsets, ShaderHooks};
pub use images::{ImageMarks, ImageQuad};
#[cfg(feature = "captions")]
pub mod binning;
#[cfg(feature = "captions")]
pub use binning::{BinRequest, ScreenBinner, ScreenBins};
#[cfg(feature = "captions")]
pub use labels::{GlyphField, LabelAnchor, LabelBackground, LabelIcon, TextLabel, TextLabels};
pub use lines::LineMarks;
pub use map_view::{MapFrame, MapView};
pub use picking::{PickHit, PickRectRequest, PickRequest};
pub use points::PointMarks;
pub use polygon_mesh::PolygonMesh;
pub use polygons::{
PatternFrame, PolygonFeature, PolygonMarks, PolygonPattern, ProceduralFrame, ProceduralShape,
};
pub use precision::{split_f64, split_f64x3, Origin};
pub use segments::{ArcProfile, DashMode, LineCap, LineJoin, PathMesh, SegmentMarks};
pub use shader::{CustomShader, MarkKind, PREAMBLE, SWIFTSHADER_SAMPLING};
pub use shapes::ShapeMarks;
pub use sprites::{SpriteBox, SpriteMarks, SpriteMode, SpriteSdf};
use std::collections::HashMap;
pub const DEPTH_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Depth32Float;
#[derive(Debug, Clone, Copy)]
pub struct MarkView {
pub view_proj: [f32; 16],
pub projection_scale: f32,
pub viewport: (u32, u32),
pub origin: Origin,
pub light_direction: [f32; 3],
pub eye: [f32; 4],
pub tone_mapping: (crate::ToneMapping, f32),
pub reversed_z: bool,
pub focal_distance: f32,
pub clip_epsilon: f32,
pub subpixel_snap: Option<(f32, [f32; 2])>,
pub flip_y: bool,
pub swiftshader_sampling: bool,
pub swiftshader_depth: bool,
pub scene_lights: Option<SceneLights>,
}
pub type PointLight = ([f64; 3], [f32; 3], [f32; 3]);
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub struct SceneLights {
pub ambient: [f32; 3],
pub points: [Option<PointLight>; 4],
pub directional: [Option<([f32; 3], [f32; 3])>; 4],
pub shadow: Option<SceneShadow>,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct SceneShadow {
pub matrix: [f64; 16],
pub color: [f32; 4],
}
impl MarkView {
pub fn new(camera: &dyn crate::Camera, origin: Origin, viewport: (u32, u32)) -> Self {
let proj = camera.projection_matrix();
let view = camera.view_matrix();
let vp = proj.multiply(&view);
let world = view.invert().elements;
let eye = if proj.elements[15].abs() > 0.5 {
[world[8], world[9], world[10], 0.0]
} else {
[world[12], world[13], world[14], 1.0]
};
Self {
view_proj: vp.elements,
projection_scale: proj.elements[5],
viewport: (viewport.0.max(1), viewport.1.max(1)),
origin,
light_direction: [0.4, 0.8, 0.45],
eye,
tone_mapping: (crate::ToneMapping::None, 1.0),
reversed_z: false,
focal_distance: 0.0,
clip_epsilon: 0.001,
subpixel_snap: None,
flip_y: false,
swiftshader_sampling: false,
swiftshader_depth: false,
scene_lights: None,
}
}
pub fn with_scene_lights(mut self, lights: Option<SceneLights>) -> Self {
self.scene_lights = lights;
self
}
pub fn with_focal_distance(mut self, w: f32) -> Self {
self.focal_distance = w.max(0.0);
self
}
pub fn with_flip_y(mut self, flip: bool) -> Self {
self.flip_y = flip;
self
}
pub fn with_swiftshader_depth(mut self, on: bool) -> Self {
self.swiftshader_depth = on;
self
}
pub fn with_swiftshader_sampling(mut self, on: bool) -> Self {
self.swiftshader_sampling = on;
self
}
pub fn with_subpixel_snap(mut self, steps: f32, bias: [f32; 2]) -> Self {
self.subpixel_snap = Some((steps, bias));
self
}
pub fn with_clip_epsilon(mut self, w: f32) -> Self {
self.clip_epsilon = w;
self
}
pub fn from_renderer(
camera: &dyn crate::Camera,
origin: Origin,
renderer: &crate::Renderer,
) -> Self {
Self::for_surface(camera, origin, &MarkSurface::of(renderer))
}
pub fn for_surface(camera: &dyn crate::Camera, origin: Origin, surface: &MarkSurface) -> Self {
let mut v = Self::new(camera, origin, surface.size);
v.tone_mapping = surface.tone_mapping;
if surface.reversed_z {
v = v.with_reversed_z();
}
v
}
pub fn with_reversed_z(mut self) -> Self {
if !self.reversed_z {
for c in 0..4 {
self.view_proj[c * 4 + 2] = self.view_proj[c * 4 + 3] - self.view_proj[c * 4 + 2];
}
self.reversed_z = true;
}
self
}
pub fn with_tone_mapping(mut self, mode: crate::ToneMapping, exposure: f32) -> Self {
self.tone_mapping = (mode, exposure);
self
}
pub fn units_per_pixel(&self, p: [f64; 3]) -> Option<f64> {
let w = self.project(p)?[2] as f64;
let px_per_unit = self.projection_scale.abs() as f64 * self.viewport.1 as f64 * 0.5;
Some(w / px_per_unit.max(1e-12))
}
pub fn project(&self, p: [f64; 3]) -> Option<[f32; 3]> {
let l = self.origin.to_local(p);
let m = &self.view_proj;
let x = m[0] * l.x + m[4] * l.y + m[8] * l.z + m[12];
let y = m[1] * l.x + m[5] * l.y + m[9] * l.z + m[13];
let w = m[3] * l.x + m[7] * l.y + m[11] * l.z + m[15];
if w <= 1e-9 {
return None;
}
let (vw, vh) = (self.viewport.0 as f32, self.viewport.1 as f32);
Some([(x / w * 0.5 + 0.5) * vw, (0.5 - y / w * 0.5) * vh, w])
}
fn scene_uniforms(&self) -> SceneUniforms {
let mut u: SceneUniforms = bytemuck::Zeroable::zeroed();
let Some(l) = &self.scene_lights else {
return u;
};
let points = l.points.iter().flatten().count();
let dirs = l.directional.iter().flatten().count();
u.counts = [points as f32, dirs as f32, 1.0, 0.0];
u.ambient = [l.ambient[0], l.ambient[1], l.ambient[2], 0.0];
for (i, (p, c, a)) in l.points.iter().flatten().enumerate() {
let r = self.origin.to_local(*p);
u.point_pos[i] = [r.x, r.y, r.z, 1.0];
u.point_color[i] = [c[0], c[1], c[2], 0.0];
u.point_att[i] = [a[0], a[1], a[2], 0.0];
}
for (i, (d, c)) in l.directional.iter().flatten().enumerate() {
let n = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt().max(1e-12);
u.dir_dir[i] = [d[0] / n, d[1] / n, d[2] / n, 0.0];
u.dir_color[i] = [c[0], c[1], c[2], 0.0];
}
if let Some(sh) = &l.shadow {
let m = &sh.matrix;
let o = self.origin.position;
let mut r = [0f32; 16];
for c in 0..4 {
for row in 0..4 {
let v = if c == 3 {
m[12 + row] + m[row] * o[0] + m[4 + row] * o[1] + m[8 + row] * o[2]
} else {
m[c * 4 + row]
};
r[c * 4 + row] = v as f32;
}
}
u.shadow_matrix = bytemuck::cast(r);
u.shadow_color = sh.color;
u.shadow_on = [1.0, 0.0, 0.0, 0.0];
}
u
}
fn uniforms(&self, encode_srgb: bool, samples: u32, offset: [f32; 2]) -> FrameUniforms {
let (w, h) = (self.viewport.0 as f32, self.viewport.1 as f32);
let (ohi, olo) = self.origin.split();
let l = self.light_direction;
let len = (l[0] * l[0] + l[1] * l[1] + l[2] * l[2]).sqrt().max(1e-9);
FrameUniforms {
view_proj: self.view_proj,
origin_hi: ohi,
origin_lo: olo,
viewport: [w, h, 1.0 / w, 1.0 / h],
misc: [
self.projection_scale.abs() * h * 0.5,
if encode_srgb { 1.0 } else { 0.0 },
self.tone_mapping.0.shader_mode(),
self.tone_mapping.1,
],
light: [
l[0] / len,
l[1] / len,
l[2] / len,
if self.reversed_z { 1.0 } else { 0.0 },
],
eye: self.eye,
aa: [
if samples > 1 { 1.0 } else { 0.5 },
self.focal_distance,
offset[0],
offset[1],
],
clip: match self.subpixel_snap {
Some((steps, bias)) => [self.clip_epsilon, steps, bias[0], bias[1]],
None => [self.clip_epsilon, 0.0, 0.0, 0.0],
},
raster: [
if self.flip_y { 1.0 } else { 0.0 },
if self.swiftshader_sampling { 1.0 } else { 0.0 },
if self.swiftshader_depth { 1.0 } else { 0.0 },
0.0,
],
scene: self.scene_uniforms(),
}
}
}
#[derive(Debug, Clone, Copy)]
pub struct MarkSurface {
pub size: (u32, u32),
pub tone_mapping: (crate::ToneMapping, f32),
pub reversed_z: bool,
}
impl MarkSurface {
pub fn of(renderer: &crate::Renderer) -> Self {
Self {
size: renderer.drawing_buffer_size(),
tone_mapping: renderer.tone_mapping(),
reversed_z: renderer.reversed_z(),
}
}
}
pub struct MarkTarget<'a> {
pub color: gpu::TextureView,
pub resolve: Option<gpu::TextureView>,
pub depth: Option<gpu::TextureView>,
pub format: wgpu::TextureFormat,
pub samples: u32,
pub rect: Option<[u32; 4]>,
pub _borrow: std::marker::PhantomData<&'a ()>,
}
impl<'a> MarkTarget<'a> {
pub fn new(color: &'a wgpu::TextureView, format: wgpu::TextureFormat) -> Self {
Self::from_view(color.into(), format)
}
pub fn from_view(color: gpu::TextureView, format: wgpu::TextureFormat) -> Self {
Self {
color,
resolve: None,
depth: None,
format,
samples: 1,
rect: None,
_borrow: std::marker::PhantomData,
}
}
pub fn with_rect(mut self, rect: [u32; 4]) -> Self {
self.rect = Some(rect);
self
}
pub fn with_depth(mut self, depth: &'a wgpu::TextureView) -> Self {
self.depth = Some(depth.into());
self
}
pub fn with_depth_view(mut self, depth: gpu::TextureView) -> Self {
self.depth = Some(depth);
self
}
pub fn render_target(rt: &'a crate::RenderTarget) -> Self {
Self::new(&rt.color_view, rt.format).with_depth(&rt.depth_view)
}
pub fn over_frame(renderer: &'a crate::Renderer, frame: &'a wgpu::TextureView) -> Self {
let (msaa_color, depth, samples) = renderer.overlay_attachments();
match msaa_color {
Some(color) => Self {
color: color.into(),
resolve: Some(frame.into()),
depth: Some(depth.into()),
format: renderer.color_format(),
samples,
rect: None,
_borrow: std::marker::PhantomData,
},
None => Self::new(frame, renderer.color_format()).with_depth(depth),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum SizeUnits {
#[default]
Pixels,
World,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum MarkBlend {
#[default]
Alpha,
Additive,
Replace,
}
#[derive(Debug, Clone, PartialEq)]
pub struct MarkStyle {
pub size_scale: f32,
pub units: SizeUnits,
pub min_pixels: f32,
pub max_pixels: f32,
pub opacity: f32,
pub params: [[f32; 4]; 4],
pub depth_test: bool,
pub depth_write: bool,
pub depth_lift: f32,
pub depth_bias_units: f32,
pub depth_order: i32,
pub ground_bias: bool,
pub clip: Option<[f64; 4]>,
pub highlight: Option<u32>,
pub highlight_len: u32,
pub highlight_color: [u8; 4],
pub horizon: Option<([f64; 3], f64)>,
pub cull_back: bool,
pub tone_mapped: bool,
pub receive_shadows: bool,
pub cast_shadows: Option<bool>,
pub blend: MarkBlend,
pub antialias: bool,
pub mix_srgb: bool,
pub focal_pixels: bool,
pub visible: bool,
pub pickable: bool,
}
impl MarkStyle {
pub fn casts_shadows(&self) -> bool {
self.cast_shadows.unwrap_or(self.receive_shadows)
}
}
impl Default for MarkStyle {
fn default() -> Self {
Self {
size_scale: 1.0,
units: SizeUnits::Pixels,
min_pixels: 0.0,
max_pixels: f32::MAX,
opacity: 1.0,
params: [[0.0; 4]; 4],
depth_test: true,
depth_write: false,
depth_lift: 2.0,
depth_bias_units: 0.0,
depth_order: 0,
ground_bias: true,
clip: None,
highlight: None,
highlight_len: 1,
highlight_color: [255, 220, 0, 255],
horizon: None,
cull_back: false,
tone_mapped: false,
receive_shadows: false,
cast_shadows: None,
blend: MarkBlend::Alpha,
antialias: true,
mix_srgb: false,
focal_pixels: false,
visible: true,
pickable: true,
}
}
}
#[derive(Debug, Default)]
pub struct MarkCommon {
pub style: MarkStyle,
pub hooks: ShaderHooks,
pub local_origin: Option<[f64; 3]>,
pub feature_ids: Option<std::sync::Arc<[u64]>>,
custom: [Option<Column>; 2],
pick_id: u32,
layer_offset: u32,
}
impl MarkCommon {
pub fn set_custom(&mut self, slot: usize, components: u32, values: &[f32]) {
assert!(slot < 2, "custom slot {slot} is not 0 or 1");
assert!((1..=4).contains(&components), "1..=4 floats a row");
let col = self.custom[slot].get_or_insert_with(|| Column::float(components));
if col.format() != ColumnFormat::Float(components) {
*col = Column::float(components);
}
col.set_f32(values);
}
pub fn has_custom(&self, slot: usize) -> bool {
self.custom.get(slot).is_some_and(|c| c.is_some())
}
pub fn update_custom(&mut self, slot: usize, start: usize, values: &[f32]) {
self.custom[slot]
.as_mut()
.expect("set_custom first")
.update_f32(start, values);
}
pub fn set_feature_ids(&mut self, ids: Vec<u64>) {
self.feature_ids = Some(ids.into());
}
pub fn clear_custom(&mut self, slot: usize) {
self.custom[slot] = None;
}
pub fn release_gpu(&mut self) {
for c in self.custom.iter_mut().flatten() {
c.release();
}
}
pub fn gpu_bytes(&self) -> u64 {
self.custom.iter().flatten().map(Column::gpu_bytes).sum()
}
pub fn custom(&self, slot: usize) -> Option<&Column> {
self.custom[slot].as_ref()
}
fn custom_widths(&self) -> [u32; 2] {
let w = |c: &Option<Column>| match c.as_ref().map(|c| c.format()) {
Some(ColumnFormat::Float(n)) => n,
_ => 0,
};
[w(&self.custom[0]), w(&self.custom[1])]
}
}
pub type InstancedGeometry<'a> = (&'a gpu::Buffer, u32, Option<(&'a gpu::Buffer, u32)>);
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Lighting {
pub ambient: f32,
pub diffuse: f32,
pub specular: f32,
pub shininess: f32,
pub lights: [([f32; 3], f32); 2],
pub srgb: bool,
pub pbr: Option<[f32; 2]>,
pub scene: bool,
pub specular_color: [f32; 3],
}
impl Lighting {
pub fn deck_gl() -> Self {
let toward = |[x, y, z]: [f32; 3]| [-x, -z, y];
Self {
ambient: 0.35,
diffuse: 0.6,
specular: 30.0 / 255.0,
shininess: 32.0,
lights: [
(toward([-1.0, 3.0, -1.0]), 1.0),
(toward([1.0, -8.0, -2.5]), 0.9),
],
srgb: true,
pbr: None,
scene: false,
specular_color: [30.0 / 255.0; 3],
}
}
pub fn deck_gl_scene(specular_color: [f32; 3]) -> Self {
Self {
scene: true,
specular_color,
..Self::deck_gl()
}
}
pub fn deck_gl_pbr(metallic: f32, roughness: f32) -> Self {
let toward = |[x, y, z]: [f32; 3]| [x, z, -y];
Self {
ambient: 1.0,
srgb: false,
pbr: Some([metallic, roughness]),
lights: [
(toward([-1.0, 3.0, -1.0]), 1.0),
(toward([1.0, -8.0, -2.5]), 0.9),
],
..Self::deck_gl()
}
}
pub(crate) fn material(lighting: Option<&Lighting>) -> [f32; 4] {
lighting.map_or([0.0; 4], |l| match l.pbr {
None if l.scene => [l.specular, l.shininess.max(1.0), 0.0, 2.0],
Some([metallic, roughness]) => [
metallic.clamp(0.0, 1.0),
roughness.clamp(0.04, 1.0),
0.0,
1.0,
],
None => [l.specular, l.shininess.max(1.0), 0.0, 0.0],
})
}
pub(crate) fn uniforms(lighting: Option<&Lighting>) -> ([f32; 2], [f32; 4], [f32; 4]) {
let Some(l) = lighting else {
return ([0.0; 2], [0.0; 4], [0.0; 4]);
};
let light = |(d, i): ([f32; 3], f32)| {
let n = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt().max(1e-12);
[d[0] / n, d[1] / n, d[2] / n, i]
};
if l.scene {
let c = l.specular_color;
return (
[l.diffuse.max(1e-6), 1.0],
[c[0], c[1], c[2], 0.0],
[0.0; 4],
);
}
(
[l.diffuse.max(1e-6), if l.srgb { 1.0 } else { 0.0 }],
light(l.lights[0]),
light(l.lights[1]),
)
}
}
pub type KindUniforms = ([f32; 4], [f32; 4], [f32; 4]);
pub struct PrepareContext<'a> {
pub device: &'a gpu::Device,
pub queue: &'a gpu::Queue,
pub view: &'a MarkView,
pub(crate) resources: &'a SharedResources,
}
impl PrepareContext<'_> {
pub fn linear_sampler(&self) -> &gpu::Sampler {
&self.resources.linear_sampler
}
}
pub trait Mark {
fn kind(&self) -> MarkKind;
fn common(&self) -> &MarkCommon;
fn common_mut(&mut self) -> &mut MarkCommon;
fn instance_count(&self) -> usize;
fn rows(&self) -> usize {
self.instance_count()
}
fn per_vertex(&self) -> bool {
false
}
fn index_buffer(&self) -> Option<(&gpu::Buffer, u32)> {
None
}
fn style_mut(&mut self) -> &mut MarkStyle {
&mut self.common_mut().style
}
fn vertices_per_instance(&self) -> u32 {
6
}
fn line_list(&self) -> bool {
false
}
fn kind_uniforms(&self) -> KindUniforms {
([0.0; 4], [0.0; 4], [0.0; 4])
}
fn kind_extra(&self) -> [f32; 4] {
[0.0; 4]
}
fn kind_extra2(&self) -> [f32; 4] {
[0.0; 4]
}
fn kind_extra3(&self) -> [[f32; 4]; 3] {
[[0.0; 4]; 3]
}
fn kind_material(&self) -> [f32; 4] {
[0.0; 4]
}
fn prepare(&mut self, _ctx: &PrepareContext) {}
fn prepare_late(&self) -> bool {
false
}
fn columns(&mut self) -> Vec<&mut Column>;
fn geometry(&self) -> Option<InstancedGeometry<'_>> {
None
}
fn custom_shader(&self) -> Option<&CustomShader> {
None
}
fn extra_layout(&self) -> Option<&gpu::BindGroupLayout> {
None
}
fn extra_bind_group(&self) -> Option<&gpu::BindGroup> {
None
}
fn kind_flags(&self) -> u32 {
0
}
fn patterned(&self) -> bool {
false
}
fn release_gpu(&mut self) {
release_columns(self);
}
fn gpu_bytes(&mut self) -> u64 {
column_bytes(self)
}
#[doc(hidden)]
fn density(&self) -> Option<(&gpu::TextureView, &gpu::BindGroup)> {
None
}
#[doc(hidden)]
fn density_reduction(&self) -> Option<&[density::ReduceLevel]> {
None
}
}
pub fn release_columns<M: Mark + ?Sized>(m: &mut M) {
for c in m.columns() {
c.release();
}
m.common_mut().release_gpu();
}
pub fn column_bytes<M: Mark + ?Sized>(m: &mut M) -> u64 {
let own: u64 = m.columns().iter().map(|c| c.gpu_bytes()).sum();
own + m.common().gpu_bytes()
}
#[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
struct FrameUniforms {
view_proj: [f32; 16],
origin_hi: [f32; 4],
origin_lo: [f32; 4],
viewport: [f32; 4],
misc: [f32; 4],
light: [f32; 4],
eye: [f32; 4],
aa: [f32; 4],
clip: [f32; 4],
raster: [f32; 4],
scene: SceneUniforms,
}
#[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
struct SceneUniforms {
counts: [f32; 4],
ambient: [f32; 4],
point_pos: [[f32; 4]; 4],
point_color: [[f32; 4]; 4],
point_att: [[f32; 4]; 4],
dir_dir: [[f32; 4]; 4],
dir_color: [[f32; 4]; 4],
shadow_matrix: [[f32; 4]; 4],
shadow_color: [f32; 4],
shadow_on: [f32; 4],
}
const LAYER_SIZE: u64 = std::mem::size_of::<LayerUniforms>() as u64;
#[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
struct LayerUniforms {
params: [[f32; 4]; 4],
style: [f32; 4],
style2: [f32; 4],
style3: [f32; 4],
stroke: [f32; 4],
ids: [u32; 4],
depth: [f32; 4],
shadow: [f32; 4],
origin_hi: [f32; 4],
origin_lo: [f32; 4],
clip: [f32; 4],
extra: [f32; 4],
highlight: [f32; 4],
horizon: [f32; 4],
material: [f32; 4],
extra2: [f32; 4],
extra3: [f32; 4],
extra4: [f32; 4],
extra5: [f32; 4],
}
#[doc(hidden)]
pub struct SharedResources {
pub(crate) frame_layout: gpu::BindGroupLayout,
pub(crate) layer_layout: gpu::BindGroupLayout,
pub(crate) texture_layout: gpu::BindGroupLayout,
pub(crate) density_layout: gpu::BindGroupLayout,
pub(crate) reduce_layout: gpu::BindGroupLayout,
pub(crate) nearest_sampler: gpu::Sampler,
pub(crate) linear_sampler: gpu::Sampler,
pub(crate) mip_sampler: gpu::Sampler,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
enum DepthKey {
None,
Ignore,
Test {
test: bool,
write: bool,
reversed: bool,
},
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct PipelineKey {
kind: MarkKind,
hooks: u64,
custom: [u32; 2],
local: bool,
format: wgpu::TextureFormat,
samples: u32,
depth: DepthKey,
blend: MarkBlend,
pick: bool,
patterned: bool,
bias: bool,
bias_units: i32,
shadow: bool,
lines: bool,
cull: u8,
}
struct LayerArena {
buffer: gpu::Buffer,
bind_group: gpu::BindGroup,
capacity: usize,
}
pub struct MarkRenderer {
resources: SharedResources,
frame_uniform: gpu::Buffer,
frame_bind_group: gpu::BindGroup,
no_shadow: std::sync::Arc<gpu::TextureView>,
shadow_map: std::sync::Arc<gpu::TextureView>,
shadow_map_dirty: bool,
shadow_pass: bool,
layers: Option<LayerArena>,
layer_stride: u64,
layer_bytes: Vec<u8>,
modules: HashMap<(MarkKind, u64, [u32; 2], bool), gpu::ShaderModule>,
pipelines: HashMap<PipelineKey, gpu::RenderPipeline>,
composites: HashMap<(wgpu::TextureFormat, u32, DepthKey), gpu::RenderPipeline>,
composite_module: Option<gpu::ShaderModule>,
reduce_pipeline: Option<gpu::RenderPipeline>,
pick: picking::PickTargets,
clearer: Option<clear::Clearer>,
}
fn uniform_entry(binding: u32) -> wgpu::BindGroupLayoutEntry {
wgpu::BindGroupLayoutEntry {
binding,
visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
}
}
fn texture_entry(binding: u32, filterable: bool) -> wgpu::BindGroupLayoutEntry {
wgpu::BindGroupLayoutEntry {
binding,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable },
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
count: None,
}
}
fn sampler_entry(binding: u32) -> wgpu::BindGroupLayoutEntry {
wgpu::BindGroupLayoutEntry {
binding,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
count: None,
}
}
fn blend_state(blend: MarkBlend) -> wgpu::BlendState {
match blend {
MarkBlend::Replace => wgpu::BlendState::REPLACE,
MarkBlend::Alpha => wgpu::BlendState {
color: wgpu::BlendComponent {
src_factor: wgpu::BlendFactor::SrcAlpha,
dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha,
operation: wgpu::BlendOperation::Add,
},
alpha: wgpu::BlendComponent {
src_factor: wgpu::BlendFactor::One,
dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha,
operation: wgpu::BlendOperation::Add,
},
},
MarkBlend::Additive => wgpu::BlendState {
color: wgpu::BlendComponent {
src_factor: wgpu::BlendFactor::SrcAlpha,
dst_factor: wgpu::BlendFactor::One,
operation: wgpu::BlendOperation::Add,
},
alpha: wgpu::BlendComponent {
src_factor: wgpu::BlendFactor::Zero,
dst_factor: wgpu::BlendFactor::One,
operation: wgpu::BlendOperation::Add,
},
},
}
}
fn dump_wgsl(kind: &str, source: &str) {
#[cfg(not(target_arch = "wasm32"))]
if let Some(dir) = std::env::var_os("THREERS_DUMP_WGSL") {
use std::hash::{Hash, Hasher};
let mut h = std::collections::hash_map::DefaultHasher::new();
source.hash(&mut h);
let path = std::path::Path::new(&dir).join(format!("{kind}-{:016x}.wgsl", h.finish()));
if let Err(e) = std::fs::create_dir_all(&dir).and_then(|_| std::fs::write(&path, source)) {
log::warn!("THREERS_DUMP_WGSL {}: {e}", path.display());
}
}
#[cfg(target_arch = "wasm32")]
let _ = (kind, source);
}
fn depth_state(depth: DepthKey) -> Option<wgpu::DepthStencilState> {
let (write, compare) = match depth {
DepthKey::None => return None,
DepthKey::Ignore => (false, wgpu::CompareFunction::Always),
DepthKey::Test {
test: false, write, ..
} => (write, wgpu::CompareFunction::Always),
DepthKey::Test {
write, reversed, ..
} => (
write,
if reversed {
wgpu::CompareFunction::GreaterEqual
} else {
wgpu::CompareFunction::LessEqual
},
),
};
Some(wgpu::DepthStencilState {
format: DEPTH_FORMAT,
depth_write_enabled: Some(write),
depth_compare: Some(compare),
stencil: wgpu::StencilState::default(),
bias: wgpu::DepthBiasState::default(),
})
}
impl MarkRenderer {
fn frame_group(
device: &gpu::Device,
layout: &gpu::BindGroupLayout,
uniform: &gpu::Buffer,
shadow: &gpu::TextureView,
sampler: &gpu::Sampler,
) -> gpu::BindGroup {
device.create_bind_group(&gpu::BindGroupDescriptor {
label: Some("threers marks frame bind group"),
layout,
entries: &[
gpu::BindGroupEntry {
binding: 0,
resource: uniform.as_entire_binding(),
},
gpu::BindGroupEntry {
binding: 1,
resource: gpu::BindingResource::TextureView(shadow),
},
gpu::BindGroupEntry {
binding: 2,
resource: gpu::BindingResource::Sampler(sampler),
},
],
})
}
pub fn set_shadow_map(&mut self, map: Option<std::sync::Arc<wgpu::TextureView>>) {
self.set_shadow_map_view(map.map(|m| std::sync::Arc::new(gpu::TextureView::from(&*m))));
}
pub fn set_shadow_map_view(&mut self, map: Option<std::sync::Arc<gpu::TextureView>>) {
let map = map.unwrap_or_else(|| self.no_shadow.clone());
if !std::sync::Arc::ptr_eq(&map, &self.shadow_map) {
self.shadow_map = map;
self.shadow_map_dirty = true;
}
}
pub fn set_shadow_pass(&mut self, on: bool) {
self.shadow_pass = on;
}
fn drawn(&self, m: &dyn Mark) -> bool {
m.common().style.visible
&& m.instance_count() > 0
&& (!self.shadow_pass
|| (m.common().style.casts_shadows()
&& matches!(m.kind(), MarkKind::Shape | MarkKind::Polygon)))
}
pub fn new(device: &wgpu::Device) -> Self {
Self::new_on(&gpu::Gpu::from(device))
}
pub fn new_on(device: &gpu::Gpu) -> Self {
let frame_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("threers marks frame bgl"),
entries: &[uniform_entry(0), texture_entry(1, true), sampler_entry(2)],
});
let layer_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("threers marks layer bgl"),
entries: &[wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: true,
min_binding_size: wgpu::BufferSize::new(LAYER_SIZE),
},
count: None,
}],
});
let align = u64::from(device.limits().min_uniform_buffer_offset_alignment);
let layer_stride = LAYER_SIZE.div_ceil(align) * align;
let texture_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("threers marks texture bgl"),
entries: &[texture_entry(0, true), sampler_entry(1)],
});
let density_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("threers marks density bgl"),
entries: &[
texture_entry(0, true),
texture_entry(1, true),
sampler_entry(2),
texture_entry(3, true),
],
});
let reduce_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("threers marks density reduce bgl"),
entries: &[texture_entry(0, true), sampler_entry(1)],
});
let linear_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
label: Some("threers marks sampler"),
address_mode_u: wgpu::AddressMode::ClampToEdge,
address_mode_v: wgpu::AddressMode::ClampToEdge,
address_mode_w: wgpu::AddressMode::ClampToEdge,
mag_filter: wgpu::FilterMode::Linear,
min_filter: wgpu::FilterMode::Linear,
mipmap_filter: wgpu::MipmapFilterMode::Nearest,
..Default::default()
});
let frame_uniform = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("threers marks frame uniforms"),
size: std::mem::size_of::<FrameUniforms>() as u64,
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let no_shadow = device.create_texture(&wgpu::TextureDescriptor {
label: Some("threers marks no shadow map"),
size: wgpu::Extent3d {
width: 1,
height: 1,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba8Unorm,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
view_formats: &[],
});
let no_shadow = std::sync::Arc::new(no_shadow.create_view(&Default::default()));
let frame_bind_group = Self::frame_group(
device,
&frame_layout,
&frame_uniform,
&no_shadow,
&linear_sampler,
);
Self {
resources: SharedResources {
frame_layout,
layer_layout,
texture_layout,
density_layout,
reduce_layout,
nearest_sampler: device.create_sampler(&wgpu::SamplerDescriptor {
label: Some("threers marks nearest sampler"),
..Default::default()
}),
linear_sampler,
mip_sampler: device.create_sampler(&wgpu::SamplerDescriptor {
label: Some("threers marks mip sampler"),
address_mode_u: wgpu::AddressMode::ClampToEdge,
address_mode_v: wgpu::AddressMode::ClampToEdge,
mag_filter: wgpu::FilterMode::Linear,
min_filter: wgpu::FilterMode::Linear,
mipmap_filter: wgpu::MipmapFilterMode::Linear,
..Default::default()
}),
},
frame_uniform,
frame_bind_group,
no_shadow: no_shadow.clone(),
shadow_map: no_shadow,
shadow_map_dirty: false,
shadow_pass: false,
layers: None,
layer_stride,
layer_bytes: Vec::new(),
modules: HashMap::new(),
pipelines: HashMap::new(),
composites: HashMap::new(),
composite_module: None,
reduce_pipeline: None,
pick: picking::PickTargets::default(),
clearer: None,
}
}
pub fn pipeline_count(&self) -> usize {
self.pipelines.len() + self.composites.len()
}
fn prepare_all(
&mut self,
device: &gpu::Device,
queue: &gpu::Queue,
view: &MarkView,
marks: &mut [&mut dyn Mark],
) {
let stride = self.layer_stride as usize;
let mut bytes = std::mem::take(&mut self.layer_bytes);
bytes.clear();
bytes.resize(marks.len().max(1) * stride, 0);
let mut order: Vec<usize> = (0..marks.len())
.filter(|&i| !marks[i].prepare_late())
.collect();
order.extend((0..marks.len()).filter(|&i| marks[i].prepare_late()));
for i in order {
let m = &mut marks[i];
m.common_mut().pick_id = i as u32 + 1;
m.common_mut().layer_offset = (i * stride) as u32;
let ctx = PrepareContext {
device,
queue,
view,
resources: &self.resources,
};
m.prepare(&ctx);
let rows = m.rows();
for c in m.columns() {
c.upload(device, queue, rows);
}
for c in m.common_mut().custom.iter_mut().flatten() {
c.upload(device, queue, rows);
}
let (mut style2, style3, stroke) = m.kind_uniforms();
let extra = m.kind_extra();
let extra2 = m.kind_extra2();
let [extra3, extra4, extra5] = m.kind_extra3();
let material = m.kind_material();
let kind_flags = m.kind_flags();
let common = m.common_mut();
let s = &common.style;
style2[3] = s.opacity;
let layer_origin = match common.local_origin {
Some(o) => {
let v = view.origin.position;
let (hi, lo) = split_f64x3([-(o[0] - v[0]), -(o[1] - v[1]), -(o[2] - v[2])]);
([hi[0], hi[1], hi[2], 0.0], [lo[0], lo[1], lo[2], 0.0])
}
None => view.origin.split(),
};
let u = LayerUniforms {
params: s.params,
style: [
s.size_scale,
s.min_pixels,
s.max_pixels,
if s.units == SizeUnits::World {
1.0
} else {
0.0
},
],
style2,
style3,
stroke,
ids: [
common.pick_id,
s.highlight.map_or(0, |r| r + 1),
u32::from(!s.antialias)
| (u32::from(s.mix_srgb) << 1)
| (u32::from(s.focal_pixels) << 2)
| ((kind_flags & 0x1f) << 3)
| (s.highlight_len.clamp(1, (1 << 24) - 1) << 8),
0,
],
highlight: points::srgb_u8_to_linear(s.highlight_color),
horizon: match s.horizon {
Some((c, r)) => {
let o = view.origin.position;
[
(c[0] - o[0]) as f32,
(c[1] - o[1]) as f32,
(c[2] - o[2]) as f32,
r as f32,
]
}
None => [0.0; 4],
},
material,
depth: [
s.depth_lift.max(0.0),
s.depth_order as f32 * 1e-6,
if s.clip.is_some() { 1.0 } else { 0.0 },
if s.tone_mapped { 1.0 } else { 0.0 },
],
clip: match s.clip {
Some([x0, y0, x1, y1]) => {
let o = view.origin.position;
[
(x0 - o[0]) as f32,
(-y1 - o[2]) as f32,
(x1 - o[0]) as f32,
(-y0 - o[2]) as f32,
]
}
None => [0.0; 4],
},
origin_hi: layer_origin.0,
origin_lo: layer_origin.1,
extra,
extra2,
extra3,
extra4,
extra5,
shadow: [
if s.receive_shadows { 1.0 } else { 0.0 },
s.depth_bias_units,
0.0,
0.0,
],
};
bytes[i * stride..i * stride + LAYER_SIZE as usize]
.copy_from_slice(bytemuck::bytes_of(&u));
}
let needed = marks.len().max(1);
if self.layers.as_ref().is_none_or(|a| a.capacity < needed) {
let capacity = needed.max(16) + needed / 2;
let buffer = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("threers mark layer uniforms"),
size: capacity as u64 * self.layer_stride,
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let bind_group = device.create_bind_group(&gpu::BindGroupDescriptor {
label: Some("threers mark layer bind group"),
layout: &self.resources.layer_layout,
entries: &[gpu::BindGroupEntry {
binding: 0,
resource: gpu::BindingResource::Buffer(gpu::BufferBinding {
buffer: &buffer,
offset: 0,
size: wgpu::BufferSize::new(LAYER_SIZE),
}),
}],
});
self.layers = Some(LayerArena {
buffer,
bind_group,
capacity,
});
}
let arena = self.layers.as_ref().unwrap();
queue.write_buffer(&arena.buffer, 0, &bytes);
self.layer_bytes = bytes;
}
fn layer_bind_group(&self) -> &gpu::BindGroup {
&self.layers.as_ref().expect("prepared").bind_group
}
pub fn gpu_bytes(&self) -> u64 {
self.layers.as_ref().map_or(0, |a| a.buffer.size())
}
fn module(
&mut self,
device: &gpu::Device,
kind: MarkKind,
hooks: &ShaderHooks,
custom: [u32; 2],
local: bool,
custom_shader: Option<&CustomShader>,
) -> &gpu::ShaderModule {
self.modules
.entry((kind, hooks.key(), custom, local))
.or_insert_with(|| {
let source = match (custom_shader, local) {
(Some(cs), false) => cs.module_source(hooks, custom),
(Some(cs), true) => cs.module_source_local(hooks, custom),
(None, _) => shader::module_source_with(kind, hooks, custom, local),
};
dump_wgsl(&format!("{kind:?}"), &source);
device.create_shader_module(gpu::ShaderModuleDescriptor {
label: Some("threers mark shader"),
source: gpu::ShaderSource::Wgsl(source.into()),
})
})
}
fn ensure_pipeline(&mut self, device: &gpu::Device, key: &PipelineKey, mark: &mut dyn Mark) {
if self.pipelines.contains_key(key) {
return;
}
let hooks = mark.common().hooks.clone();
let custom_widths = key.custom;
let mut layouts: Vec<(u64, wgpu::VertexStepMode, Vec<wgpu::VertexAttribute>)> = Vec::new();
let mut loc = 0;
if key.kind == MarkKind::Shape {
let attr = |format, offset, shader_location| wgpu::VertexAttribute {
format,
offset,
shader_location,
};
layouts.push((
84,
wgpu::VertexStepMode::Vertex,
vec![
attr(wgpu::VertexFormat::Float32x3, 0, 0),
attr(wgpu::VertexFormat::Float32x3, 12, 1),
attr(wgpu::VertexFormat::Float32x2, 24, 2),
attr(wgpu::VertexFormat::Float32x4, 32, 3),
attr(wgpu::VertexFormat::Float32x3, 48, 4),
attr(wgpu::VertexFormat::Float32x3, 60, 5),
attr(wgpu::VertexFormat::Float32x3, 72, 6),
],
));
loc = 7;
} else if mark.geometry().is_some() {
layouts.push((
24,
wgpu::VertexStepMode::Vertex,
vec![
wgpu::VertexAttribute {
format: wgpu::VertexFormat::Float32x3,
offset: 0,
shader_location: 0,
},
wgpu::VertexAttribute {
format: wgpu::VertexFormat::Float32x3,
offset: 12,
shader_location: 1,
},
],
));
loc = 2;
}
let step = if mark.per_vertex() {
wgpu::VertexStepMode::Vertex
} else {
wgpu::VertexStepMode::Instance
};
{
let cols = mark.columns();
let refs: Vec<&Column> = cols.iter().map(|c| &**c).collect();
for (stride, attrs) in columns::instance_layouts(&refs, loc) {
layouts.push((stride, step, attrs));
}
}
if key.kind != MarkKind::Glyph {
let first = match mark.custom_shader() {
Some(cs) => cs.custom_location,
None => shader::custom_location(key.kind),
};
for (cloc, c) in (first..).zip(mark.common().custom.iter().flatten()) {
let (stride, attrs) = c.layout(cloc);
layouts.push((stride, step, attrs));
}
}
let buffers: Vec<Option<wgpu::VertexBufferLayout>> = layouts
.iter()
.map(|(stride, step, attrs)| {
Some(wgpu::VertexBufferLayout {
array_stride: *stride,
step_mode: *step,
attributes: attrs,
})
})
.collect();
let mut groups: Vec<Option<&gpu::BindGroupLayout>> = vec![
Some(&self.resources.frame_layout),
Some(&self.resources.layer_layout),
];
if key.patterned
|| matches!(
key.kind,
MarkKind::Glyph | MarkKind::Sprite | MarkKind::Image
)
{
groups.push(Some(&self.resources.texture_layout));
} else if let Some(l) = mark.extra_layout() {
groups.push(Some(l));
}
let layout = device.create_pipeline_layout(&gpu::PipelineLayoutDescriptor {
label: Some("threers mark pipeline layout"),
bind_group_layouts: &groups,
immediate_size: 0,
});
let cs = mark.custom_shader().cloned();
let module = self
.module(
device,
key.kind,
&hooks,
custom_widths,
key.local,
cs.as_ref(),
)
.clone();
let target = if key.pick || key.shadow {
wgpu::ColorTargetState {
format: key.format,
blend: None,
write_mask: wgpu::ColorWrites::ALL,
}
} else if key.kind == MarkKind::Splat {
wgpu::ColorTargetState {
format: key.format,
blend: Some(wgpu::BlendState {
color: wgpu::BlendComponent {
src_factor: wgpu::BlendFactor::One,
dst_factor: wgpu::BlendFactor::One,
operation: wgpu::BlendOperation::Add,
},
alpha: wgpu::BlendComponent {
src_factor: wgpu::BlendFactor::One,
dst_factor: wgpu::BlendFactor::One,
operation: wgpu::BlendOperation::Add,
},
}),
write_mask: wgpu::ColorWrites::ALL,
}
} else {
wgpu::ColorTargetState {
format: key.format,
blend: (key.blend != MarkBlend::Replace).then(|| blend_state(key.blend)),
write_mask: wgpu::ColorWrites::ALL,
}
};
let pipeline = device.create_render_pipeline(&gpu::RenderPipelineDescriptor {
label: Some("threers mark pipeline"),
layout: Some(&layout),
vertex: gpu::VertexState {
module: &module,
entry_point: Some("vs_main"),
buffers: &buffers,
compilation_options: Default::default(),
},
fragment: Some(gpu::FragmentState {
module: &module,
entry_point: Some(if key.pick {
"fs_pick"
} else if key.shadow {
"fs_shadow"
} else if key.patterned {
"fs_pattern"
} else {
"fs_main"
}),
targets: &[Some(target)],
compilation_options: Default::default(),
}),
primitive: wgpu::PrimitiveState {
topology: if key.lines {
wgpu::PrimitiveTopology::LineList
} else {
wgpu::PrimitiveTopology::TriangleList
},
front_face: if key.cull == 2 {
wgpu::FrontFace::Cw
} else {
wgpu::FrontFace::Ccw
},
cull_mode: (key.cull != 0).then_some(wgpu::Face::Back),
..Default::default()
},
depth_stencil: depth_state(key.depth).map(|mut d| {
let reversed = matches!(key.depth, DepthKey::Test { reversed: true, .. });
d.bias.constant = if reversed {
-key.bias_units
} else {
key.bias_units
};
if key.bias {
let toward = if matches!(key.depth, DepthKey::Test { reversed: true, .. }) {
-1
} else {
1
};
d.bias = wgpu::DepthBiasState {
constant: d.bias.constant - 2 * toward,
slope_scale: -(toward as f32),
clamp: 0.0,
};
}
d
}),
multisample: wgpu::MultisampleState {
count: key.samples,
..Default::default()
},
multiview_mask: None,
cache: None,
});
self.pipelines.insert(key.clone(), pipeline);
}
fn ensure_composite(
&mut self,
device: &gpu::Device,
format: wgpu::TextureFormat,
samples: u32,
depth: DepthKey,
) {
if self.composites.contains_key(&(format, samples, depth)) {
return;
}
let module = self
.composite_module
.get_or_insert_with(|| {
device.create_shader_module(gpu::ShaderModuleDescriptor {
label: Some("threers density composite"),
source: gpu::ShaderSource::Wgsl(shader::composite_source().into()),
})
})
.clone();
let layout = device.create_pipeline_layout(&gpu::PipelineLayoutDescriptor {
label: Some("threers density composite layout"),
bind_group_layouts: &[
Some(&self.resources.frame_layout),
Some(&self.resources.layer_layout),
Some(&self.resources.density_layout),
],
immediate_size: 0,
});
let pipeline = device.create_render_pipeline(&gpu::RenderPipelineDescriptor {
label: Some("threers density composite pipeline"),
layout: Some(&layout),
vertex: gpu::VertexState {
module: &module,
entry_point: Some("vs_main"),
buffers: &[],
compilation_options: Default::default(),
},
fragment: Some(gpu::FragmentState {
module: &module,
entry_point: Some("fs_main"),
targets: &[Some(wgpu::ColorTargetState {
format,
blend: Some(blend_state(MarkBlend::Alpha)),
write_mask: wgpu::ColorWrites::ALL,
})],
compilation_options: Default::default(),
}),
primitive: wgpu::PrimitiveState::default(),
depth_stencil: depth_state(depth),
multisample: wgpu::MultisampleState {
count: samples,
..Default::default()
},
multiview_mask: None,
cache: None,
});
self.composites.insert((format, samples, depth), pipeline);
}
fn ensure_reduce(&mut self, device: &gpu::Device) {
if self.reduce_pipeline.is_some() {
return;
}
let module = device.create_shader_module(gpu::ShaderModuleDescriptor {
label: Some("threers density reduce"),
source: gpu::ShaderSource::Wgsl(shader::reduce_source().into()),
});
let layout = device.create_pipeline_layout(&gpu::PipelineLayoutDescriptor {
label: Some("threers density reduce layout"),
bind_group_layouts: &[Some(&self.resources.reduce_layout)],
immediate_size: 0,
});
self.reduce_pipeline = Some(device.create_render_pipeline(
&gpu::RenderPipelineDescriptor {
label: Some("threers density reduce pipeline"),
layout: Some(&layout),
vertex: gpu::VertexState {
module: &module,
entry_point: Some("vs_main"),
buffers: &[],
compilation_options: Default::default(),
},
fragment: Some(gpu::FragmentState {
module: &module,
entry_point: Some("fs_main"),
targets: &[Some(wgpu::ColorTargetState {
format: density::FIELD_FORMAT,
blend: None,
write_mask: wgpu::ColorWrites::ALL,
})],
compilation_options: Default::default(),
}),
primitive: wgpu::PrimitiveState::default(),
depth_stencil: None,
multisample: wgpu::MultisampleState::default(),
multiview_mask: None,
cache: None,
},
));
}
fn key_for(
mark: &dyn Mark,
format: wgpu::TextureFormat,
samples: u32,
has_depth: bool,
pick: bool,
reversed: bool,
flipped: bool,
) -> PipelineKey {
let s = &mark.common().style;
let depth = if !has_depth {
DepthKey::None
} else if s.depth_test || s.depth_write {
DepthKey::Test {
test: s.depth_test,
write: s.depth_write,
reversed,
}
} else {
DepthKey::Ignore
};
PipelineKey {
kind: mark.kind(),
hooks: mark.common().hooks.key(),
local: mark.common().local_origin.is_some(),
custom: if mark.kind() == MarkKind::Glyph {
[0, 0]
} else {
mark.common().custom_widths()
},
format,
samples,
depth,
blend: s.blend,
pick,
patterned: !pick && mark.patterned(),
bias: s.ground_bias && matches!(mark.kind(), MarkKind::Polygon | MarkKind::Image),
bias_units: if matches!(mark.kind(), MarkKind::Custom(_)) {
0
} else {
s.depth_bias_units.round() as i32
},
shadow: false,
lines: mark.line_list(),
cull: match (s.cull_back && !mark.line_list(), flipped) {
(false, _) => 0,
(true, false) => 1,
(true, true) => 2,
},
}
}
fn record(
pass: &mut gpu::RenderPass<'_>,
pipeline: &gpu::RenderPipeline,
layers: &gpu::BindGroup,
mark: &mut dyn Mark,
) {
let count = mark.instance_count() as u32;
let verts = mark.vertices_per_instance();
pass.set_pipeline(pipeline);
pass.set_bind_group(1, layers, &[mark.common().layer_offset]);
if let Some(bg) = mark.extra_bind_group() {
pass.set_bind_group(2, bg, &[]);
}
let mut slot = 0;
let geometry = mark
.geometry()
.map(|(vb, n, ib)| (vb.clone(), n, ib.map(|(b, c)| (b.clone(), c))));
if let Some((vb, _, _)) = &geometry {
pass.set_vertex_buffer(0, vb.slice(..));
slot = 1;
}
let kind = mark.kind();
let mut buffers: Vec<gpu::Buffer> = mark
.columns()
.iter()
.map(|c| c.buffer.clone().expect("uploaded"))
.collect();
if kind != MarkKind::Glyph {
buffers.extend(
mark.common()
.custom
.iter()
.flatten()
.map(|c| c.buffer.clone().expect("uploaded")),
);
}
for b in &buffers {
pass.set_vertex_buffer(slot, b.slice(..));
slot += 1;
}
let index = mark.index_buffer().map(|(b, n)| (b.clone(), n));
match (geometry, index) {
(Some((_, _, Some((ib, n)))), _) | (None, Some((ib, n))) => {
pass.set_index_buffer(ib.slice(..), wgpu::IndexFormat::Uint32);
pass.draw_indexed(0..n, 0, 0..count);
}
(Some((_, n, None)), _) => pass.draw(0..n, 0..count),
(None, None) => pass.draw(0..verts, 0..count),
}
}
pub fn draw(
&mut self,
device: &wgpu::Device,
queue: &wgpu::Queue,
target: &MarkTarget,
view: &MarkView,
marks: &mut [&mut dyn Mark],
) {
self.draw_on(&gpu::Gpu::from((device, queue)), target, view, marks);
}
pub fn draw_on(
&mut self,
gpu: &gpu::Gpu,
target: &MarkTarget,
view: &MarkView,
marks: &mut [&mut dyn Mark],
) {
let (device, queue) = (gpu, gpu);
let encode = crate::renderer::shader_applies_transfer(target.format);
queue.write_buffer(
&self.frame_uniform,
0,
bytemuck::bytes_of(&view.uniforms(
encode,
target.samples,
target.rect.map_or([0.0; 2], |r| [r[0] as f32, r[1] as f32]),
)),
);
self.prepare_all(device, queue, view, marks);
if std::mem::take(&mut self.shadow_map_dirty) {
self.frame_bind_group = Self::frame_group(
device,
&self.resources.frame_layout,
&self.frame_uniform,
&self.shadow_map,
&self.resources.linear_sampler,
);
}
let has_depth = target.depth.is_some();
for m in marks.iter_mut() {
if !self.drawn(&**m) {
continue;
}
if m.kind() == MarkKind::Splat {
let key = Self::key_for(
&**m,
density::FIELD_FORMAT,
1,
false,
false,
view.reversed_z,
view.flip_y,
);
self.ensure_pipeline(device, &key, &mut **m);
let depth = if has_depth {
DepthKey::Ignore
} else {
DepthKey::None
};
self.ensure_composite(device, target.format, target.samples, depth);
if m.density_reduction().is_some() {
self.ensure_reduce(device);
}
} else {
let mut key = Self::key_for(
&**m,
target.format,
target.samples,
has_depth,
false,
view.reversed_z,
view.flip_y,
);
key.shadow = self.shadow_pass;
self.ensure_pipeline(device, &key, &mut **m);
}
}
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("threers marks"),
});
let mut i = 0;
while i < marks.len() {
let start = i;
while i < marks.len() && marks[i].kind() != MarkKind::Splat {
i += 1;
}
if i > start {
let mut pass = Self::begin_target_pass(&mut encoder, target);
pass.set_bind_group(0, &self.frame_bind_group, &[]);
for m in marks[start..i].iter_mut() {
if !self.drawn(&**m) {
continue;
}
let mut key = Self::key_for(
&**m,
target.format,
target.samples,
has_depth,
false,
view.reversed_z,
view.flip_y,
);
key.shadow = self.shadow_pass;
let pipeline = &self.pipelines[&key];
Self::record(&mut pass, pipeline, self.layer_bind_group(), &mut **m);
}
}
if i < marks.len() {
let m = &mut marks[i];
i += 1;
if !self.drawn(&**m) {
continue;
}
let key = Self::key_for(
&**m,
density::FIELD_FORMAT,
1,
false,
false,
view.reversed_z,
view.flip_y,
);
{
let (field, _) = m.density().unwrap();
let mut pass = encoder.begin_render_pass(&gpu::RenderPassDescriptor {
label: Some("threers density field"),
color_attachments: &[Some(gpu::RenderPassColorAttachment {
view: field,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
store: wgpu::StoreOp::Store,
},
})],
depth_stencil_attachment: None,
timestamp_writes: None,
occlusion_query_set: None,
multiview_mask: None,
});
pass.set_bind_group(0, &self.frame_bind_group, &[]);
Self::record(
&mut pass,
&self.pipelines[&key],
self.layer_bind_group(),
&mut **m,
);
}
if let Some(levels) = m.density_reduction() {
let reduce = self
.reduce_pipeline
.as_ref()
.expect("built with the pipelines");
for level in levels {
let mut pass = encoder.begin_render_pass(&gpu::RenderPassDescriptor {
label: Some("threers density reduce"),
color_attachments: &[Some(gpu::RenderPassColorAttachment {
view: &level.target,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
store: wgpu::StoreOp::Store,
},
})],
depth_stencil_attachment: None,
timestamp_writes: None,
occlusion_query_set: None,
multiview_mask: None,
});
pass.set_pipeline(reduce);
pass.set_bind_group(0, &level.bind_group, &[]);
pass.draw(0..3, 0..1);
}
}
let depth = if has_depth {
DepthKey::Ignore
} else {
DepthKey::None
};
let composite = &self.composites[&(target.format, target.samples, depth)];
let mut pass = Self::begin_target_pass(&mut encoder, target);
pass.set_pipeline(composite);
pass.set_bind_group(0, &self.frame_bind_group, &[]);
pass.set_bind_group(1, self.layer_bind_group(), &[m.common().layer_offset]);
pass.set_bind_group(2, m.density().unwrap().1, &[]);
pass.draw(0..3, 0..1);
}
}
queue.submit(Some(encoder.finish()));
}
fn begin_target_pass<'e>(
encoder: &'e mut gpu::CommandEncoder,
target: &MarkTarget<'_>,
) -> gpu::RenderPass<'e> {
let mut pass = encoder.begin_render_pass(&gpu::RenderPassDescriptor {
label: Some("threers marks pass"),
color_attachments: &[Some(gpu::RenderPassColorAttachment {
view: &target.color,
depth_slice: None,
resolve_target: target.resolve.as_ref(),
ops: wgpu::Operations {
load: wgpu::LoadOp::Load,
store: wgpu::StoreOp::Store,
},
})],
depth_stencil_attachment: target.depth.as_ref().map(|d| {
gpu::RenderPassDepthStencilAttachment {
view: d,
depth_ops: Some(wgpu::Operations {
load: wgpu::LoadOp::Load,
store: wgpu::StoreOp::Store,
}),
stencil_ops: None,
}
}),
timestamp_writes: None,
occlusion_query_set: None,
multiview_mask: None,
});
if let Some([x, y, w, h]) = target.rect {
pass.set_viewport(
x as f32,
y as f32,
w.max(1) as f32,
h.max(1) as f32,
0.0,
1.0,
);
pass.set_scissor_rect(x, y, w.max(1), h.max(1));
}
pass
}
pub fn clear(
&mut self,
device: &wgpu::Device,
queue: &wgpu::Queue,
target: &MarkTarget,
color: Option<wgpu::Color>,
depth: Option<f32>,
) {
self.clear_on(&gpu::Gpu::from((device, queue)), target, color, depth);
}
pub fn clear_on(
&mut self,
gpu: &gpu::Gpu,
target: &MarkTarget,
color: Option<wgpu::Color>,
depth: Option<f32>,
) {
let (device, queue) = (gpu, gpu);
self.clearer
.get_or_insert_with(|| clear::Clearer::new(device))
.clear(device, queue, target, color, depth);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn every_kind_fits_in_eight_vertex_buffers_with_both_custom_columns() {
let geometry = crate::BoxGeometry::new(1.0, 1.0, 1.0);
let mut marks: Vec<Box<dyn Mark>> = vec![
Box::new(PointMarks::new()),
Box::new(SegmentMarks::new()),
Box::new(ShapeMarks::new(&geometry)),
Box::new(DensityMarks::new()),
Box::new(PolygonMarks::new()),
Box::new(SpriteMarks::new(TextureAtlas::new(64).shared())),
Box::new(ImageMarks::new(TextureAtlas::new(64).shared())),
];
for m in &mut marks {
let kind = m.kind();
let own = m.columns().len();
let mesh = usize::from(kind == MarkKind::Shape);
let custom = if kind == MarkKind::Glyph { 0 } else { 2 };
assert!(
own + mesh + custom <= 8,
"{kind:?}: {own} columns + {mesh} mesh + {custom} custom"
);
}
}
}