dr2d 0.0.1-alpha.1

GPU-accelerated 2D data renderer built on wgpu
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
# dr2d - 2d Data Renderer

GPU-accelerated 2D data renderer built in Rust on wgpu.

dr2d is a rendering primitive. It handles vertices, viewports, data, and GPU.
Meaning belongs to the layer above — dr2d renders triangles, it does not
interpret them.

## Architecture

```
┌─────────────────────────────────────────────────────┐
│                      dr2d                           │
│                                                     │
│  ┌───────────┐   ┌───────────┐   ┌──────────────┐  │
│  │  Renderer  │   │  Viewport  │   │  InputQueue  │  │
│  │  ├ SDF     │   │  pan/zoom  │   │  events      │  │
│  │  ├ Tess    │   │  transform │   │  drain()     │  │
│  │  └ Frame   │   └───────────┘   └──────────────┘  │
│  └───────────┘                                      │
│                                                     │
│  ┌───────────┐   ┌───────────────────────────────┐  │
│  │   Scene    │   │           Data                │  │
│  │  shapes    │   │  ParquetLoader  CoordMapper   │  │
│  │  viewpoints│   └───────────────────────────────┘  │
│  └───────────┘                                      │
│                                                     │
│  ┌─────────────────┐   ┌──────────────────────┐    │
│  │  Text (feature)  │   │  Headless (feature)  │    │
│  │  GlyphAtlas      │   │  HeadlessRenderer    │    │
│  └─────────────────┘   └──────────────────────┘    │
└─────────────────────────────────────────────────────┘
```

### Rendering Pipeline

```
begin_frame(viewport)
    ├── draw_sdf(shape, instances)      ← SDF pipeline (resolution-independent)
    ├── draw_instanced(mesh, instances) ← shared mesh + per-instance transforms
    ├── draw_triangles(vertices)        ← flat triangle list
    └── finish()                        ← submit + present
```

The renderer maintains two GPU pipelines:

- SDF pipeline — expands a unit quad per instance, evaluates signed distance
  functions in the fragment shader for anti-aliased, resolution-independent shapes
- Tessellation pipeline — renders pre-tessellated triangle meshes with optional
  instancing, used for polygons, rectangles, and text glyphs

Both pipelines share a single uniform bind group containing the viewport
transform matrix.

## Features

- SDF rendering — resolution-independent shapes (circle, rounded rect, ring, diamond, line cap) with anti-aliased edges
- Instanced rendering — `draw_sdf`, `draw_instanced`, `draw_triangles`
- GPU rendering via wgpu (Vulkan, Metal, DX12, WebGPU)
- Parquet/Arrow data loading with streaming row-group reads
- Viewport with pan, zoom, fit-to-data, window-to-scene coordinate conversion
- Mouse and keyboard input with scene coordinate mapping
- Lyon-based polygon tessellation with caching
- Text rendering (feature: `text`) — embedded glyph atlas, ASCII
- Headless rendering (feature: `headless`) — render to RGBA pixel buffer

## Quick Start

```rust
use dr2d::{Renderer, Viewport, SdfShape, SdfInstance};

let renderer = Renderer::new(window).await?;
let viewport = Viewport::new();

let mut frame = renderer.begin_frame(&viewport)?;
frame.draw_sdf(SdfShape::Circle, &[SdfInstance {
    position: [100.0, 100.0],
    size: [20.0, 20.0],
    color: [1.0, 0.0, 0.0, 1.0],
    shape_type: SdfShape::Circle as u32,
    param: 0.0,
    _pad: [0.0; 2],
}]);
frame.finish();
```

## API Reference

### Renderer

Creates and manages the GPU context, pipelines, and frame lifecycle.

```rust
// Create renderer attached to a winit window
let renderer = Renderer::new(window).await?;

// Resize the rendering surface
renderer.resize(width, height);

// Frame lifecycle
let mut frame = renderer.begin_frame(&viewport)?;
// ... draw calls ...
frame.finish();
// or: renderer.end_frame(frame)?;

// Convenience: render all scene shapes in one call
renderer.render(&mut scene, &viewport)?;

// Query window dimensions
let (w, h) = renderer.window_size();
```

### FrameEncoder

Returned by `begin_frame()`. Records draw calls into a GPU command encoder.

| Method | Description |
|--------|-------------|
| `draw_sdf(shape, &[SdfInstance])` | Draw SDF shapes (resolution-independent, anti-aliased) |
| `draw_instanced(&[Vertex], &[InstanceData])` | Draw shared mesh with per-instance transforms |
| `draw_triangles(&[Vertex])` | Draw a flat triangle list |
| `finish()` | Submit commands and present the frame |

All draw calls skip silently when given empty slices.

### SDF Shapes

Built-in signed distance function shapes evaluated per-fragment on the GPU:

| Variant | Description | `param` usage |
|---------|-------------|---------------|
| `Circle` | Unit circle | unused |
| `RoundedRect` | Rounded rectangle | corner radius |
| `Ring` | Donut / annulus | ring thickness |
| `Diamond` | Rotated square | unused |
| `LineCap` | Capsule / line segment with round ends | unused |

### SdfInstance

Per-instance data for SDF rendering (48 bytes, GPU-aligned):

| Field | Type | Description |
|-------|------|-------------|
| `position` | `[f32; 2]` | Center in scene coordinates |
| `size` | `[f32; 2]` | Half-extents of bounding quad |
| `color` | `[f32; 4]` | RGBA color |
| `shape_type` | `u32` | Cast from `SdfShape` enum |
| `param` | `f32` | Shape-specific parameter |

### Vertex / InstanceData

| Type | Fields | Description |
|------|--------|-------------|
| `Vertex` | `position: [f32; 2]`, `color: [f32; 4]` | GPU vertex for triangle rendering |
| `InstanceData` | `position: [f32; 2]`, `size: [f32; 2]`, `color: [f32; 4]` | Per-instance offset, scale, color |

### Viewport

2D translation (pan) and uniform scale (zoom). Transforms scene coordinates to
NDC for GPU rendering.

```rust
let mut vp = Viewport::new(); // pan=(0,0), zoom=1.0

vp.set_pan(100.0, -50.0);
vp.set_zoom(2.0)?; // returns Err if zoom <= 0

// Build 3×vec4 transform matrix for GPU uniform buffer
let matrix: [f32; 12] = vp.transform_matrix(window_width, window_height);

// Convert window pixel coordinates to scene coordinates
let (scene_x, scene_y) = vp.window_to_scene(px_x, px_y, win_w, win_h);
```

Fields: `pan_x: f32`, `pan_y: f32`, `zoom: f32` (all public).

### InputQueue / InputEvent

Buffers input events between frames. Events carry both screen and scene
coordinates.

```rust
let mut queue = InputQueue::new();
queue.push(event);
let events: Vec<InputEvent> = queue.drain();
```

`InputEvent` variants:

| Variant | Key fields |
|---------|------------|
| `MouseButton` | `button`, `state`, `screen_x/y`, `scene_x/y` |
| `MouseMove` | `screen_x/y`, `scene_x/y` |
| `KeyboardKey` | `key: KeyCode`, `state: ElementState` |
| `Scroll` | `delta_x`, `delta_y` |
| `ModifiersChanged` | `alt`, `ctrl`, `shift`, `super_key` |

Use `convert_window_event()` to translate winit `WindowEvent` into `InputEvent`.

### Scene

Container for shapes and named viewpoints. Shapes are sorted by layer for
draw ordering.

```rust
let mut scene = Scene::new();

let id = scene.add_shape(shape)?;
scene.update_shape(id, new_shape)?;
scene.remove_shape(id)?;
let shape_ref = scene.get_shape(id);
let sorted: &[ShapeId] = scene.shapes_sorted();
```

Shape geometry types:

| Geometry | Fields |
|----------|--------|
| `Rectangle` | `x`, `y`, `width`, `height` |
| `Polygon` | `vertices: Vec<[f32; 2]>` (3–1024 vertices) |
| `Triangle` | `vertices: [[f32; 2]; 3]` |

Shape properties: `color: [f32; 3]`, `opacity: f32`, `layer: i32`,
`border_color: Option<[f32; 3]>`, `border_width: f32`.

Viewpoints:

```rust
scene.register_viewpoint("overview".into(), viewpoint);
let vp = scene.activate_viewpoint("overview")?;
scene.remove_viewpoint("overview");
```

### Data Module

#### ParquetLoader

Reads Parquet files into Arrow RecordBatch or extracts typed column pairs.
Supports streaming row-group reads. Numeric columns (f32, f64, i32, i64) are
cast to f32 automatically.

```rust
// Stream columns directly from file
let pair = ParquetLoader::load_columns(path, "x", "y")?;

// Load full RecordBatch, then extract
let batch = ParquetLoader::load(path)?;
let pair = ParquetLoader::extract_columns(&batch, "x", "y")?;
```

`ColumnPair` contains `x: Vec<f32>` and `y: Vec<f32>`.

#### CoordinateMapper

Linear mapping from data value ranges to scene coordinate ranges.

```rust
let mapper = CoordinateMapper::from_column_pairs(&[&pair1, &pair2]);

let (scene_x, scene_y) = mapper.map_point(data_x, data_y);
let points: Vec<[f32; 2]> = mapper.map_all(&pair);
```

Default scene range: `0.0..1000.0` on both axes.

### Text (feature: `text`)

Embedded glyph atlas with geometric outlines for ASCII characters (A-Z, a-z,
0-9, common punctuation). Tessellated into triangle vertices via lyon.

```rust
let atlas = GlyphAtlas::new();
let vertices: Vec<Vertex> = atlas.tessellate_string("Hello", x, y, font_size);
```

Unknown characters are skipped but the cursor still advances.

### Headless (feature: `headless`)

Render to an in-memory RGBA pixel buffer without a window. Creates a wgpu
device without a surface.

```rust
let mut hr = HeadlessRenderer::new().await?;
let pixels: Vec<u8> = hr.render_to_image(800, 600).await?;
// pixels.len() == 800 * 600 * 4
```

Returns `HeadlessError::InvalidDimensions` if width or height is zero.
PNG encoding is left to downstream consumers.

## Keyboard Shortcuts

Built-in interaction processor translates input events into viewport mutations.

| Key | Action |
|-----|--------|
| Arrow keys | Pan viewport |
| Scroll wheel | Zoom in/out |
| `+` / `-` | Zoom in / zoom out |
| Left click + drag | Pan viewport |
| `F` | Fit viewport to data |
| `Ctrl+Shift+H` | Fit viewport to data |
| `Home` | Reset to origin (pan=0, zoom=1.0) |
| `0` | Reset to initial viewport state |
| `1``9` | Activate named viewpoints (sorted alphabetically) |
| `F11` | Toggle fullscreen |
| `Alt+Enter` | Toggle fullscreen |
| `Ctrl+Super+F` | Toggle fullscreen |
| `Escape` | Exit fullscreen |
| `Ctrl+S` | Save request (polled via `take_save_request()`) |

## Using dr2d Downstream

Add dr2d as a dependency in your `Cargo.toml`:

```toml
[dependencies]
dr2d = "0.0.1-alpha.1"

# Optional features
# dr2d = { version = "0.0.1-alpha.1", features = ["text", "headless"] }
```

Minimal windowed application:

```rust
use std::sync::Arc;
use dr2d::{Renderer, Viewport, Scene, SdfShape, SdfInstance};

async fn run(window: Arc<winit::window::Window>) {
    let mut renderer = Renderer::new(window).await.unwrap();
    let viewport = Viewport::new();

    // Draw a red circle
    let mut frame = renderer.begin_frame(&viewport).unwrap();
    frame.draw_sdf(SdfShape::Circle, &[SdfInstance {
        position: [0.0, 0.0],
        size: [50.0, 50.0],
        color: [1.0, 0.0, 0.0, 1.0],
        shape_type: SdfShape::Circle as u32,
        param: 0.0,
        _pad: [0.0; 2],
    }]);
    frame.finish();
}
```

For scene-based rendering with shapes and tessellation:

```rust
use dr2d::{Renderer, Viewport, Scene};
use dr2d::scene::shape::{Shape, ShapeGeometry};

let mut scene = Scene::new();
scene.add_shape(Shape {
    geometry: ShapeGeometry::Rectangle { x: 10.0, y: 10.0, width: 200.0, height: 100.0 },
    color: [0.2, 0.4, 0.8],
    opacity: 1.0,
    layer: 0,
    border_color: None,
    border_width: 0.0,
}).unwrap();

renderer.render(&mut scene, &viewport).unwrap();
```

## Feature Flags

| Feature | Default | Description |
|---------|---------|-------------|
| `text` | no | GlyphAtlas with embedded ASCII glyph outlines and lyon tessellation |
| `headless` | no | HeadlessRenderer for offscreen rendering to RGBA pixel buffers |

## Examples

```bash
cargo run --example scatter_sdf -p dr2d
cargo run --example custom_shapes -p dr2d
cargo run --example headless_export -p dr2d --features headless
```

## CLI

The `dr2d-cli` crate loads TOML scene files and renders them in a window.

```bash
cargo run -p dr2d-cli -- scene.toml
cargo run -p dr2d-cli -- scene.toml --watch   # hot-reload on file change
```

## Philosophy

See [PHILOSOPHY.md](PHILOSOPHY.md).

## License

Apache 2.0 — Copyright 2026 Krishnamoorthy Sankaran. See [LICENSE](LICENSE).

All source files carry the following header convention:

```
// SPDX-License-Identifier: Apache-2.0
```