sim-engine 0.4.2

A validated high-performance visualization engine for simulations
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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
# Sim;Engine

Sim;Engine is a validated visualization library built for simulation products.
It provides a high-performance 2D renderer, scientific visualization paths,
and a focused retained 3D stereometry pipeline.

Sim;X is the primary consumer and design driver, but the crate is reusable.
Applications provide ready visual state. Sim;Engine owns cameras, drawing,
clipping, interpolation, GPU resources, composition, recovery, and rendering
diagnostics. Physics, simulation stepping, domain entities, UI navigation, and
plugins remain in the host application.

This is **Sim;Engine 0.4.2**, focused on dense 2D mathematical visualization.
See the [0.4.2 changelog](CHANGELOG.md#042---2026-09-25).
The crate remains pre-1.0, and its
supported release target is Linux with Vulkan. A concrete adapter/driver is
supported when the mandatory semantic fixture passes on it;
untested drivers are not inferred from Mesa evidence. The minimum supported
Rust version is 1.90.

The software-Vulkan CI fixture uses Mesa 25.3+ lavapipe. Mesa 25.2.8 llvmpipe
has a reproduced MSAA scissor leak and does not pass the rendering contract;
its upstream fix is included in [Mesa 25.3](https://docs.mesa3d.org/relnotes/25.3.0.html).
This does not impose an Ubuntu-version requirement on host applications.

The 0.4 API includes Opaque/Mask/Blend 3D materials, sidedness, vertex colors,
optional Lambert lighting and distance fog, capacity-reusing mesh updates,
mipmapped and repeating textures, atomic region edits, and complete material
recovery. CPU-only fonts and reusable pre-shaped text reduce repeated text work;
optional GPU timestamps and changing-scene fixtures make costs observable.
See the [0.4 integration guide](DOCUMENTATION.md#04-integration-guide) and
[0.4.0 changelog](CHANGELOG.md#040---2026-09-12) for contracts and migration
notes from 0.3.0.

Version **0.4.2** adds compact retained circles, independent round lines and
axis-aligned rectangles, plus ordered same-atlas batches of prepared labels.
They reuse capacity, support explicit clipping/DPI and device recovery, and
keep numeric checks and resource budgets. Preparation substages and selected
adapter metadata make remaining CPU/GPU costs visible. These paths are opt-in:
an application must retain and submit batches; upgrading alone does not convert
its existing streaming geometry. See the
[dense 2D guide](DOCUMENTATION.md#042-dense-2d-rendering).

The [0.4.1 performance guide](DOCUMENTATION.md#041-performance-guide) covers
earlier partial mip uploads, retained-3D validation, instancing, changed-uniform
uploads and optional culling. Existing 0.4 integrations need no source migration.
No universal frame rate or replacement for consumer testing is promised.

## Documentation

- [Library documentation]DOCUMENTATION.md - installation, concepts, every
  rendering path, recovery, performance, architecture, and examples.
- [Changelog]CHANGELOG.md - release history and migration notes.
- [Archived 0.3 documentation]https://github.com/lexawhatt/Sim-Engine/blob/v0.3.0/DOCUMENTATION.md - the guide for integrations that have not upgraded.
- Generated API reference:

  ```bash
  cargo doc --all-features --no-deps --open
  ```

## Capabilities

- validated circles, rectangles, rounded rectangles, lines, and polylines,
  including sub-ULP radii, rounded corners, and world-width strokes preserved
  as camera-relative local offsets;
- solid, linear-gradient, and radial-gradient fills;
- logical/world-width strokes with bounded caps, joins, dashes, markers,
  clipping, and stable layer ordering;
- 2D camera pan, rotation, zoom, fit, and picking;
- fallible tweening and easing;
- streaming, prepared, and dynamic triangle geometry;
- compact retained screen circles, independent round lines and rectangles;
- retained sRGB RGBA images, atlas sprite batches, and world-space image quads;
- host-shaped, bounded glyph atlas runs with deterministic logical bounds;
- many-placement glyph batches with independent translations, tints and clips;
- optional CPU-only `fonts` feature for TTF/OTF loading, shaping and rasterization;
  `text` adds GPU atlases, retained runs and preparation from pre-shaped lines;
- budgeted instanced particle rendering;
- scalar-field textures, color maps, partial updates, and heatmaps;
- offscreen targets, composition, and bounded trails;
- device recovery with explicit retained-resource restoration;
- typed logical-pixel, 2D/3D world-length, and target-scale boundaries;
- retained 3D meshes, independent transforms, hardware depth, and visible or
  dashed hidden mathematical edges;
- explicit StrictPortable/Native surface policies and source-triangle diagnostics;
- capacity-reusing, alias-isolated mesh edits and material-only rebinding;
- Opaque/Mask/Blend surfaces, sidedness, vertex colors, optional normals,
  ambient/directional Lambert lighting and distance fog;
- complete mip chains, isolated repeating tiles and bounded texture-region edits;
- atomic retained-3D scene recovery that preserves stable object IDs and visual
  state across logical-device replacement;
- optional bounded GPU pass timestamps with correlation IDs and loss counters;
- primitive/source-grouped diagnostics and repeatable release-mode workloads
  for static UI, prepared/streaming UI, viewports, atlases, glyphs, mixed
  layers, budget rejection, DPI reconfiguration, real compositor scale
  transitions, and recovery.

Ordinary scenes support explicit construction, tessellation, and upload
budgets, fixed logical-screen geometry, and independent positioned viewport or
offscreen-target rendering. `FrameComposer` orders streaming and prepared
scenes, compact primitives, dynamic meshes, particles, scalar fields, images,
glyph runs/batches, and 2D/3D
color targets under one frame budget and one surface presentation.
`DynamicMeshBudget` limits caller-provided filled triangles and makes full
updates allocation-fallible and atomic.

GPU transform validation enforces bounded arithmetic for 2D scenes, dynamic
triangles, particles, and retained 3D. Nonzero subnormal
coordinate/transform operands, coordinate magnitudes above `2^120`, ambiguous
geometry-branch thresholds, and arithmetic ranges that cannot be proven
portable are rejected with a structured transform error before submission.
Normalized linear color channels are not geometric operands and may include
subnormal values; their contribution is below the precision of current
normalized render targets. This intentionally prefers a clear rejection over
backend-dependent geometry disappearance or topology. Retained 3D defaults to
`StrictPortable`, which also proves clipping topology and rejects ambiguous
surface classifications. Opt-in `Native` uses hardware surface clipping while
retaining arithmetic checks; mathematical-edge validation stays strict.

Blend sorts objects, not triangles within a mesh; intersecting transparent
surfaces can still overlap incorrectly. General section materials, hatching,
projected 3D anchors, 3D picking, point lights, shadows and PBR remain outside
0.4.2. Unlit remains available and is the default.

An additional Intel UHD (CML GT2) / Mesa 26.1.6 Vulkan qualification run did
not complete the material readback fixture; the same wait reproduced on the
unchanged dev.4 baseline. This configuration is not qualified by the successful
NVIDIA or software-Vulkan runs. See [known boundaries](DOCUMENTATION.md#28-known-boundaries).

## Installation

The default feature set includes the `wgpu` renderer:

```bash
cargo add sim-engine@0.4.2
```

or add it directly to `Cargo.toml`:

```toml
[dependencies]
sim-engine = "0.4.2"
```

Use core visual-state APIs without GPU dependencies:

```toml
[dependencies]
sim-engine = { version = "0.4.2", default-features = false }
```

Run the examples from a repository checkout matching the library version:

```bash
cargo run --release --features text --example text_ui_updates
cargo run --release --features text --example text_ui_updates -- --page fonts
cargo run --release --features text --example text_ui_updates -- --font /path/to/MyFont.ttf
cargo run --release --features text --example text_ui_updates -- --acceptance
cargo run --release --example frame_cache_benchmark
cargo run --release --example frame_cache_benchmark -- --case mixed --labels 1000 --trials 3 --frames 120
cargo run --release --example stroke_gallery -- --page 5
cargo run --release --example editable_textured_3d
cargo run --release --example editable_textured_3d -- --acceptance
cargo run --release --example dense_scene_benchmark -- --constructions 500 --mode analytic --labels batch
```

The text lab has three pages: `1` compares DejaVu Sans/Serif/Mono, Inter and
DejaVu Math; `2` (default) shows `𝓣𝔂𝓹𝓮 𝓼𝓸𝓶𝓮𝓽𝓱𝓲𝓷𝓰 𝓽𝓸 𝓼𝓽𝓪𝓻𝓽`, math
symbols, Japanese, combining accents and one Arabic RTL run; `3` exercises
retained updates, clipping and motion at 16/24/48 logical pixels. Use the wheel
to scroll shorter gallery windows, and `--page fonts|unicode|motion` to select
the initial page. Licensed font fixtures are embedded, including an 89 KiB
Japanese **example subset**, not a full CJK font. `--font` replaces the selected
font comparison and motion samples with your TTF/OTF file. Font support
is opt-in; the default renderer and core-only builds retain their dependency
boundary. UI navigation, audio, and domain logic stay in the host. `--acceptance`
exercises public update, composition and recovery routes and requires 40 actual
presented frames on each page. Automatic font fallback and mixed-script paragraph layout
are not implied by these independently shaped, explicitly font-selected rows.
For changing-text diagnostics, use `frame_cache_benchmark --case recolored
--labels 1000 --cache on`; compare with `--upload-staging 0` to isolate bounded
uniform-upload packing without disabling the other caches. Transfer memory and
GPU copy work are reported separately from host-upload bytes.

### Loading a font

Enable the optional `text` feature:

```toml
sim-engine = { version = "0.4.2", features = ["text"] }
```

```rust,no_run
# #[cfg(feature = "text")]
# fn main() -> Result<(), Box<dyn std::error::Error>> {
use sim_engine::{FontBudget, FontFace};

let font = FontFace::from_bytes(
    std::fs::read("assets/MyFont.ttf")?,
    FontBudget::default(),
)?;
# let _ = font;
# Ok(())
# }
# #[cfg(not(feature = "text"))]
# fn main() {}
```

Then create a `TextAtlas2d`, prepare a `TextRun2d`, and draw it through the
frame composer. The [font guide](DOCUMENTATION.md#loading-ttfotf-fonts-optional-text-feature)
covers the complete render/update/DPI/recovery workflow. Supply trusted,
appropriately licensed font assets. Automatic font fallback, paragraph bidi,
wrapping, color emoji, and font-file I/O are not built into the engine.

For CPU-only font work, use `default-features = false, features = ["fonts"]`.
`TextShapingSession` reuses shaping state; `TextAtlas2d::prepare_from_shaped`
and `update_from_shaped` consume its results without shaping again.

## Quick Start

```rust
use sim_engine::{Camera2d, Color, Rect, Scene, ShapeStyle, Vec2};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let camera = Camera2d::new(Vec2::ZERO, 2.0)?;
    let mut scene = Scene::new(Color::rgb8(12, 14, 18))?;

    scene.try_circle(
        Vec2::new(10.0, 20.0),
        8.0,
        ShapeStyle::filled(Color::rgb8(86, 195, 255)),
    )?;
    scene.try_rect(
        Rect::from_center_size(Vec2::ZERO, Vec2::new(120.0, 64.0)),
        8.0,
        ShapeStyle::fill_stroke(
            Color::rgb8(24, 31, 44),
            2.0,
            Color::rgb8(86, 195, 255),
        ),
    )?;

    let _ = camera;
    Ok(())
}
```

Window creation stays in the host. Renderer initialization is asynchronous;
steady-state updates and rendering are synchronous submissions. Standalone
retained-resource mutations submit their transfer immediately (without waiting
for GPU completion), while a skipped surface frame enqueues no uploads:

```rust,ignore
let options = WgpuRendererOptions::new(
    RendererPresentMode::Vsync,
    window.scale_factor(),
)?;
let mut renderer = WgpuRenderer::new_with_options(
    window.clone(),
    width,
    height,
    options,
).await?;
let notify_window = window.clone();
renderer.set_pre_present_notify(move || notify_window.pre_present_notify());

let mut frame = renderer.begin_frame(scene.background(), FrameBudget::default())?;
frame.draw_scene(&scene, camera, FramePassOptions::default())?;
let report = frame.present()?;
```

## Choose A Rendering Path

| Workload | Preferred API |
| --- | --- |
| Small changing scene | `Scene` |
| Static geometry with a moving camera | `PreparedScene` |
| Frequently changing triangles | `DynamicMesh2d` |
| Images and atlas sprites | `Image2d` plus `ImageBatch2d` |
| TTF/OTF labels and counters (`text` feature) | `FontFace`, `TextAtlas2d` and `TextRun2d` |
| Host-shaped scientific text | `GlyphAtlas2d` plus `GlyphRun2d` |
| Large point or circle population | `ParticleField2d` |
| Dense scalar grid | `ScalarFieldTexture` |
| Mixed UI, viewports, fields, and targets | `FrameComposer` |
| Bounded gas plus particle overlay | `render_layered_visualization` |
| Stereometry solids and hidden edges | `Mesh3d` plus `Scene3d` |
| Changing 3D geometry with immutable aliases | `update_scene3d_mesh` with `DynamicMesh3dBudget` |
| Material or background changes without geometry upload | `Scene3d::set_texture_material` / `set_background` |
| Partial 3D texture edits | `update_scene3d_texture_region` |

## Examples

```bash
cargo run --release --example demo
cargo run --release --example ui_demo -- --uncapped
cargo run --release --example star_remnant_stress -- --benchmark
cargo run --release --no-default-features --example particle_cpu_benchmark
cargo run --release --no-default-features --example scene_construction_benchmark
cargo run --release --example rendering_benchmark_suite -- --fixture ui_90_10
cargo run --release --example stroke_gallery -- --uncapped
cargo run --release --example stereometry_3d -- --uncapped
cargo run --release --example cylinder_derivation_3d -- --uncapped --benchmark
cargo run --release --example materials_3d
cargo run --release --example lighting_3d
cargo run --release --example texture_lifecycle_3d
cargo run --release --example texture_lifecycle_3d -- --acceptance
cargo run --release --all-features --example mesh3d_scene_benchmark -- --case repeated
```

From a Sim;Engine repository checkout, run the complete named
performance/contract matrix on a Vulkan-capable Linux machine with
`./scripts/rendering_benchmark_matrix.sh`. Release scripts are repository
tooling and are intentionally not shipped in the crates.io source archive.
Gated surface workloads
require a `1280x720` physical surface at scale `1.0`; both values are printed
in every result. Absolute timings are comparable only when surface extent,
scale, adapter, driver, backend, present mode, and workload are recorded
together; deterministic command/vertex/upload counters are portable.
The matrix first probes the real production surface. It pins the selected
high-performance Vulkan adapter by PCI bus address as well as backend, name,
vendor, and model, then requires the offscreen semantic oracle and every
surface/HiDPI process to use that same physical GPU. The oracle uses the
production surface format and its selected MSAA count. A nested compositor may
advertise a different surface format; its HiDPI evidence remains pinned by the
physical PCI identity rather than pretending two surfaces have identical
capabilities. Every warmup and
measured report must be `Drawn`; a timeout, occlusion, or outdated surface
fails the fixture instead of inflating throughput with skipped attempts.
Gated workloads use three independent 120-frame trials. Every trial must meet
the wall-throughput floor; the reported median is diagnostic only.
Renderer-work percentiles cover all 360 drawn frames, so one failed trial
cannot be hidden by two faster trials.

The matrix always enforces fixture-specific p95 ceilings for renderer work
excluding surface acquisition. Immediate additionally requires 60 presented
FPS. Mailbox/FIFO wall throughput must reach 95% of the confirmed current
monitor refresh, bounded to a 30-60 Hz release floor. The window is mapped by
an unmeasured drawn frame before any output metadata is used. Immediate does
not require refresh metadata; Mailbox/FIFO require a positive refresh rate
from the window's confirmed current monitor. Zero/unknown refresh and
primary/first-monitor fallbacks are never accepted for synchronized evidence.
Warmup and measured frames advance one `RedrawRequested` at a time, allowing
compositor events between every sample. A resize, scale transition, or changed
current-output identity invalidates the confirmation and discards partial
timing samples; a surface outside the fixed release extent/scale fails rather
than being measured as a cheaper workload. The benchmark registers
`Window::pre_present_notify` with the renderer. The callback runs after queue
submission and immediately before present only for the concrete FIFO, FIFO-
relaxed, or Mailbox modes; Immediate remains unpaced. The final measured
present then yields through a compositor-aware redraw boundary and repeats the
generation/output check before evidence is published.
Acquire percentiles remain reported but do not independently flip the verdict
from one scheduler-sensitive sample.
The mandatory workloads include the fused bounded particle/scalar path and a
retained-3D target-composition path with 4,096 budgeted dynamic triangles, so
per-particle portability/culling/upload, dynamic-triangle proofs, and per-object
surface/hidden-edge validation cannot regress outside the release performance
evidence.
The matrix also drives a nested KWin compositor through a real scale
1.00-to-1.25 transition and records the paired event and successful redraw for
the exact revision on that same physical adapter.
The automatic transition requires `dbus-run-session`, `kwin_wayland`, and
`kscreen-doctor`; a missing executable fails the matrix instead of silently
skipping HiDPI evidence.
The wrapper, standalone matrix, and standalone HiDPI gate reject a dirty
worktree, then build and execute from a read-only detached worktree of the
captured commit with a separate Cargo target directory. They recheck the
calling checkout before accepting results. Replacement refs and legacy grafts
are rejected, and all Git operations run with replacement objects disabled.
Evidence therefore remains bound to Git object data for the exact recorded SHA
even if the mutable calling worktree changes while a long gate is running.
Child gates write only to hidden staging. The launcher atomically publishes a
completed bundle after the entire requested gate succeeds; failed, killed, or
crashed runs cannot leave a bundle that claims success. A nonblocking process
lock rejects concurrent release gates before either invocation can invalidate
or publish evidence.

`stroke_gallery` is the visual oracle for the stroke contract. Pages 1-4
show every cap/join, half-alpha overlap probes, bounded animated dashes,
outward endpoint arrow markers, miter fallback, camera rotation, and the
accepted 0.005-world-unit line at zoom 10,000. Press `Space`, arrows, `+`/`-`, or `R`
to pause, scrub, zoom, and reset. Page 5 adds the exact-tip scientific arrows
introduced in 0.3.

`ui_demo` includes a retained host-rasterized scientific glyph probe above all
four independently changing scene workloads. It demonstrates one-time atlas
and run creation without requiring the optional font loader or shaping path.

## Verification

From a clean Sim;Engine repository checkout, the Linux release gate
checks the declared Rust 1.90 MSRV, all targets with and without the renderer
and CPU fonts, strict clippy, rustdoc, Vulkan semantic GPU
readback with a backend assertion, the Vulkan performance matrix on a real
surface, real text/standalone-mesh recovery, a transactional nested-compositor
HiDPI transition, and the publishable package boundary:

```bash
./scripts/linux_release_gate.sh
```

After all 11 steps pass, the launcher atomically publishes
`target/linux-release-evidence/`. Its `completion.txt` binds the successful
gate and exact SHA; the same directory contains `linux-vulkan-surface.txt`,
`linux-vulkan-adapter.txt`, `linux-vulkan-performance.txt`, and
`linux-hidpi-transition.txt`. The performance manifest preserves the complete
fixture counters, timings, thresholds, and passed verdicts for all nine
surface runs instead of leaving them only in terminal output.

Maintainers should follow the complete
[official release procedure](DOCUMENTATION.md#30-official-release-procedure).
Publishing is complete only when crates.io exposes the immutable package, the
annotated Git tag points at the evidenced commit, and the matching GitHub
Release is public.

## License

Licensed under either
[MIT](https://github.com/lexawhatt/Sim-Engine/blob/main/LICENSE) or
[Apache-2.0](https://github.com/lexawhatt/Sim-Engine/blob/main/LICENSE-APACHE),
at your option.