embedded-3dgfx 0.2.3

3D graphics rendering for embedded systems (fork of embedded-gfx by Kezii)
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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
# Embedded-3dgfx
<a href="https://crates.io/crates/embedded-3dgfx"><img alt="crates.io" src="https://img.shields.io/crates/v/embedded-3dgfx"></a>
<a href="https://github.com/leftger/embedded-3dgfx/actions"><img alt="actions" src="https://github.com/leftger/embedded-3dgfx/actions/workflows/rust.yml/badge.svg"></a>

A complete `no_std` 3D graphics and physics engine for embedded systems. Features real-time rendering, rigid body dynamics, soft body physics, skeletal animation, and advanced visual effects optimized for resource-constrained devices.

> **Note**: This is a fork of [embedded-gfx]https://github.com/Kezii/embedded-gfx by [Kezii]https://github.com/Kezii. This fork adds texture mapping, fog/dithering effects, DMA rendering, Z-buffer improvements, and a complete physics engine.

## ๐ŸŒŸ Key Features

### ๐ŸŽจ 3D Graphics Rendering
- **Complete MVP Pipeline** - Model-View-Projection with perspective projection
- **Z-buffering** - Hardware-style depth testing with tunable epsilon
- **Advanced Shading** - Flat, Gouraud, directional lighting, Blinn-Phong specular
- **Texture Mapping** - Affine UV mapping with multi-texture support
- **Visual Effects** - Fog, dithering, billboards, vertex animation
- **LOD System** - Distance-based mesh detail switching
- **Performance** - Frustum culling, backface culling, DMA rendering

### โš›๏ธ Physics Engine
- **Rigid Body Dynamics** - Linear/angular motion, forces, torques
- **Collision Detection** - Sphere, AABB, and Capsule colliders
- **Collision Response** - Impulse-based with friction and restitution
- **Constraints** - Distance, ball-socket, and fixed joints
- **Ray Casting** - Line-of-sight, shooting, object selection
- **Body Management** - Activation/deactivation, lifecycle control

### ๐Ÿฆด Skeletal Animation
- **Bone Hierarchy** - Parent-child skeletal structures
- **Linear Blend Skinning** - Smooth vertex deformation (SSD)
- **Multi-Bone Influence** - Up to 4 bones per vertex
- **Real-time Animation** - Interactive character animation

### ๐ŸงŠ Soft Body Physics
- **Mass-Spring Systems** - Deformable objects (cloth, jelly, soft bodies)
- **Pressure Preservation** - Volume maintenance for enclosed bodies
- **Collision Response** - Ground collision with friction
- **Pre-built Shapes** - Cloth grids, jelly cubes, soft spheres

## ๐Ÿš€ Quick Start

### Installation

```toml
[dependencies]
# For embedded (no_std)
embedded-3dgfx = { version = "0.1", default-features = false }

# For desktop/simulator with all features
embedded-3dgfx = { version = "0.1", features = ["std"] }
```

### Basic Example

```rust
use embedded_3dgfx::{K3dengine, mesh::{Geometry, K3dMesh, RenderMode}};
use nalgebra::Vector3;

// Create engine
let mut engine = K3dengine::new(320, 240);
engine.camera.set_position(Vector3::new(0.0, 0.0, 5.0).into());

// Create a cube mesh
let geometry = Geometry { vertices: &CUBE_VERTS, faces: &CUBE_FACES, /* ... */ };
let mut mesh = K3dMesh::new(geometry);
mesh.set_render_mode(RenderMode::Lines);

// Render
engine.render(std::iter::once(&mesh), |primitive| {
    draw(primitive, &mut display);
});
```

### Physics Example

```rust
use embedded_3dgfx::physics::{PhysicsWorld, RigidBody, Collider, Ray};
use nalgebra::Vector3;

// Create physics world
let mut world = PhysicsWorld::<16, 4>::new();
world.set_gravity(Vector3::new(0.0, -9.81, 0.0));

// Add a falling sphere
let sphere = RigidBody::new(1.0)
    .with_collider(Collider::Sphere { radius: 0.5 })
    .with_position(Vector3::new(0.0, 10.0, 0.0));
world.add_body(sphere);

// Add static ground
let ground = RigidBody::new_static()
    .with_collider(Collider::Aabb { half_extents: Vector3::new(10.0, 0.5, 10.0) });
world.add_body(ground);

// Simulate
world.step::<8>(0.016);

// Ray cast
let ray = Ray::new(Vector3::zeros(), Vector3::new(0.0, -1.0, 0.0));
if let Some(hit) = world.ray_cast(&ray, 100.0) {
    println!("Hit at distance: {}", hit.distance);
}
```

## ๐ŸŽฎ Examples

The project includes 23+ interactive examples. Run with:

```bash
cargo run --example <name> --features std
```

### 3D Rendering Examples

**Core Rendering:**
- `basic_rendering` - Render mode cycling (Points, Lines, Solid)
- `rotating_cube` - Animated 3D transformations
- `scene_viewer` - Interactive multi-mesh scene

**Lighting & Effects:**
- `lighting_demo` - Directional lighting with ambient
- `gouraud_demo` - Smooth color interpolation
- `blinn_phong_demo` - Specular highlights
- `fog_dithering_demo` - Atmospheric effects

**Advanced Features:**
- `texture_mapping_demo` - UV-mapped textures
- `dma_rendering_demo` - Double-buffer performance
- `billboard_demo` - Camera-facing quads
- `lod_demo` - Level of detail switching
- `vertex_animation_demo` - Keyframe animation
- `stl_viewer` - Load and view STL models

### Physics Examples

**Rigid Body Dynamics:** (See [PHYSICS_EXAMPLES.md](PHYSICS_EXAMPLES.md))
- `physics_rolling_ball` โญ **START HERE** - Beginner-friendly intro
- `physics_bouncing_balls` - Multiple colliding spheres
- `physics_pendulum` - Swinging pendulum with constraints
- `physics_newtons_cradle` - Newton's cradle with chain constraints
- `physics_stack_tower` - Stacking boxes with friction
- `physics_domino_chain` - Domino effect simulation
- `physics_wrecking_ball` - Wrecking ball demolition
- `physics_demo` - Comprehensive physics showcase
- `capsule_physics_demo` - Capsule collider interactions

**Advanced Physics:** (See [SKELETAL_AND_SOFTBODY.md](SKELETAL_AND_SOFTBODY.md))
- `skeletal_animation_demo` - Bone hierarchy and skinning
- `cloth_simulation` - Hanging cloth with wind
- `jelly_cube_demo` - Soft deformable cube
- `raycast_demo` - Ray casting and hit detection

## ๐Ÿ“š Feature Flags

### `std` (includes `perfcounter`)
- Enables Painter's Algorithm (uses `std::vec::Vec`)
- Performance counter with std timing
- Required for desktop simulator examples

### `perfcounter` (optional)
- Enables FPS/timing measurements
- Requires timing source: `std` or `embassy-time`
- Automatically included with `std`

### `embassy-time` (optional)
- Timing for embedded targets using Embassy framework
- Use with `perfcounter` for embedded performance monitoring

### `row_width_*` (mutually exclusive)
- `row_width_160` - Optimize for 160px wide displays
- `row_width_240` - Optimize for 240px wide displays (default)
- `row_width_320` - Optimize for 320px wide displays

## ๐ŸŽฏ Core Rendering Features

### Rendering Pipeline
- **Full MVP Transforms** - Model-View-Projection with perspective
- **Z-buffering** - 16.16 fixed-point depth testing
- **Backface Culling** - ~50% face elimination
- **Frustum Culling** - 50-200% speedup for off-screen objects
- **Optimized Rasterization** - Integer-only triangle filling

### Shading & Lighting
- **Flat Shading** - Per-face solid colors
- **Gouraud Shading** - Smooth vertex color interpolation
- **Directional Lighting** - Diffuse with ambient term
- **Blinn-Phong** - Specular highlights with half-vector
- **Pre-computed Constants** - Per-mesh optimization

### Visual Effects
- **Fog** - Depth-based atmospheric effects
- **Dithering** - 4ร—4 Bayer matrix ordered dithering
- **Billboards** - Camera-facing sprites
- **Vertex Animation** - Keyframe interpolation

### Texturing
- **Affine Mapping** - UV-based texture coordinates
- **Multi-texture** - Multiple textures per scene
- **Power-of-2 Optimization** - Fast wrapping with bit masks
- **RGB565 Format** - Memory-efficient 16-bit color

### Performance Systems
- **DMA Rendering** - ~30% FPS boost with double buffering
- **LOD** - 3-10ร— triangle reduction at distance
- **Swap Chain** - Asynchronous buffer transfers
- **Inline Optimization** - Aggressive hot-path inlining

## โš›๏ธ Physics System

### Rigid Body Dynamics
```rust
let body = RigidBody::new(1.0)
    .with_collider(Collider::Capsule { height: 2.0, radius: 0.5 })
    .with_position(Vector3::new(0.0, 5.0, 0.0))
    .with_restitution(0.6)  // Bounciness
    .with_friction(0.5);     // Surface friction
```

### Collision Detection
- **Sphere Collider** - Cheapest, perfect for balls and particles
- **AABB Collider** - Boxes, platforms, walls (axis-aligned)
- **Capsule Collider** - Best for characters (efficient + smooth)
- **Broad Phase** - O(nยฒ) narrow-phase only (spatial partitioning planned)

### Constraints & Joints
```rust
// Distance constraint (rope, rod)
world.add_constraint(Constraint::Distance {
    body_a: ball_id,
    body_b: anchor_id,
    rest_length: 2.0,
    compliance: 0.0,  // Stiffness
});

// Ball-socket joint (ragdoll)
world.add_constraint(Constraint::BallSocket { /* ... */ });

// Fixed joint (welding)
world.add_constraint(Constraint::Fixed { /* ... */ });
```

### Ray Casting
```rust
let ray = Ray::new(origin, direction);
if let Some(hit) = world.ray_cast(&ray, 100.0) {
    println!("Hit body {:?} at {}", hit.body_id, hit.distance);
    println!("Point: {:?}, Normal: {:?}", hit.point, hit.normal);
}
```

## ๐Ÿฆด Skeletal Animation

```rust
let mut skeleton = Skeleton::<8>::new();
let root = skeleton.add_bone(Bone::new("root"), None).unwrap();
let arm = skeleton.add_bone(
    Bone::new("arm").with_position(Vector3::new(0.0, 1.0, 0.0)),
    Some(root)
).unwrap();

skeleton.update_transforms();
skeleton.compute_inverse_bind_poses();

// Animate
skeleton.get_bone_mut(arm).unwrap().set_rotation(rotation);
skeleton.update_transforms();

// Apply to mesh
apply_skinning(&skeleton, &skinning_data, &bind_vertices, &mut deformed);
```

## ๐ŸงŠ Soft Body Physics

```rust
// Create cloth (8ร—8 grid)
let mut cloth = SoftBody::<64, 256>::create_cloth(8, 8, 0.4, 200.0, 1.0).unwrap();
cloth.set_gravity(Vector3::new(0.0, -9.81, 0.0));

// Create jelly cube (3ร—3ร—3 particles)
let mut jelly = SoftBody::<64, 256>::create_jelly_cube(3, 0.5, 150.0, 0.5).unwrap();
jelly.pressure_config.enabled = true;  // Volume preservation

// Simulate
cloth.step(0.016);
jelly.step(0.016);

// Get deformed vertices for rendering
cloth.get_vertex_positions(&mut vertex_buffer);
```

## ๐Ÿ“‹ System Requirements

### Embedded Targets
**Minimum:**
- ARM Cortex-M4F (with FPU)
- 128KB RAM (single-buffer + small scenes)
- 256KB+ Flash

**Recommended:**
- ARM Cortex-M33 with FPU (e.g., STM32WBA)
- 512KB+ RAM (double-buffer + Z-buffer + physics)
- 512KB+ Flash

### Performance Budget (240ร—135 @ 60 FPS)
- Rendering: ~10-13ms per frame
- Physics (16 bodies): ~2-3ms per frame
- Display transfer (DMA): ~3ms (parallel)
- **Total: 60+ FPS achievable**

### Memory Usage
| Feature | Memory Cost |
|---------|-------------|
| Single framebuffer (240ร—135) | 65 KB |
| Double framebuffer (240ร—135) | 130 KB |
| Z-buffer (240ร—135) | 130 KB |
| Physics (16 bodies) | ~4 KB |
| Soft body (64 particles) | ~2 KB |
| Skeleton (8 bones) | ~1 KB |

**Total typical usage:** 200-300 KB RAM

## ๐Ÿงช Testing

```bash
# Run all 182 tests
cargo test

# Run library tests only
cargo test --lib

# Test with all features
cargo test --lib --all-features
```

**Test Coverage:**
- โœ… 182 passing tests
- โœ… Rendering pipeline (transformations, clipping, rasterization)
- โœ… Physics (collisions, constraints, integration)
- โœ… Skeletal animation (skinning, bone hierarchy)
- โœ… Soft body (springs, particles, pressure)
- โœ… Ray casting (all collider types)

## ๐Ÿ“ฆ no_std Compatibility

Fully `no_std` compatible by default. All core features work without the standard library.

### Feature Flag Combinations

**Pure Embedded (no_std):**
```toml
embedded-3dgfx = { version = "0.1", default-features = false }
```

**Embedded with Embassy Timing:**
```toml
embedded-3dgfx = { version = "0.1", default-features = false, features = ["perfcounter", "embassy-time"] }
```

**Desktop/Simulator:**
```toml
embedded-3dgfx = { version = "0.1", features = ["std"] }
```

**Custom Row Width:**
```toml
embedded-3dgfx = { version = "0.1", default-features = false, features = ["row_width_320"] }
```

## ๐ŸŽฏ Use Cases

### Game Development
- โœ… Character controllers (capsule colliders + ray casting)
- โœ… Projectile physics (rigid bodies + continuous motion)
- โœ… Skeletal animation (characters, creatures)
- โœ… Particle systems (billboards + soft bodies)
- โœ… Level geometry (static AABB colliders)

### Simulations
- โœ… Robotics visualization (skeletal arms, kinematics)
- โœ… Physics demonstrations (pendulum, Newton's cradle)
- โœ… Cloth/soft body (flags, deformable objects)
- โœ… Mechanical systems (constraints, joints)

### Embedded Displays
- โœ… STM32 with LCD displays
- โœ… ESP32 with TFT screens
- โœ… RP2040 with displays
- โœ… M5Stack devices

## ๐Ÿ“š Documentation

- **[PHYSICS_EXAMPLES.md]PHYSICS_EXAMPLES.md** - Complete physics demo guide
- **[SKELETAL_AND_SOFTBODY.md]SKELETAL_AND_SOFTBODY.md** - Animation & soft body documentation
- **[examples/README.md]examples/README.md** - All examples with screenshots
- **API Docs** - `cargo doc --open`

## ๐Ÿ—๏ธ Architecture

```
embedded-3dgfx/
โ”œโ”€โ”€ src/
โ”‚   โ”œโ”€โ”€ lib.rs              # Main engine & rendering
โ”‚   โ”œโ”€โ”€ camera.rs           # View/projection matrices
โ”‚   โ”œโ”€โ”€ mesh.rs             # Geometry & LOD
โ”‚   โ”œโ”€โ”€ draw.rs             # Rasterization & effects
โ”‚   โ”œโ”€โ”€ physics.rs          # Rigid body dynamics (3048 lines)
โ”‚   โ”œโ”€โ”€ skeleton.rs         # Skeletal animation (470 lines)
โ”‚   โ”œโ”€โ”€ softbody.rs         # Soft body physics (749 lines)
โ”‚   โ”œโ”€โ”€ texture.rs          # Texture management
โ”‚   โ”œโ”€โ”€ billboard.rs        # Camera-facing quads
โ”‚   โ”œโ”€โ”€ animation.rs        # Keyframe animation
โ”‚   โ”œโ”€โ”€ swapchain.rs        # DMA double-buffering
โ”‚   โ”œโ”€โ”€ perfcounter.rs      # Performance monitoring
โ”‚   โ””โ”€โ”€ painters.rs         # Painter's algorithm
โ”‚
โ”œโ”€โ”€ examples/               # 23 interactive demos
โ”‚   โ”œโ”€โ”€ basic_rendering.rs
โ”‚   โ”œโ”€โ”€ rotating_cube.rs
โ”‚   โ”œโ”€โ”€ physics_*.rs        # 8 physics demos
โ”‚   โ”œโ”€โ”€ cloth_simulation.rs
โ”‚   โ”œโ”€โ”€ skeletal_animation_demo.rs
โ”‚   โ”œโ”€โ”€ raycast_demo.rs
โ”‚   โ””โ”€โ”€ ...
โ”‚
โ””โ”€โ”€ load_stl/              # STL file embedding macro
```

## ๐Ÿ”ง Performance Optimizations

Recent performance improvements (2026):
- โœ… **Interpolator-based rasterization** - Faster triangle filling
- โœ… **FnvIndexSet edge deduplication** - Faster mesh processing
- โœ… **Configurable row buffers** - Memory/speed trade-off
- โœ… **Inline hot paths** - Better compiler optimization
- โœ… **mem::swap optimizations** - Reduced allocations

**Measured improvements:**
- Triangle rasterization: ~20% faster
- Edge generation: ~30% faster
- Memory usage: Configurable (160-320px row buffers)

## ๐ŸŽ“ Learning Resources

Start with these examples in order:

1. **`rotating_cube`** - Learn basic 3D rendering
2. **`physics_rolling_ball`** โญ - Understand physics basics
3. **`lighting_demo`** - Explore shading
4. **`skeletal_animation_demo`** - See advanced animation
5. **`cloth_simulation`** - Experience soft body physics

## ๐Ÿค Contributing

Contributions welcome! Priority areas:
- Hardware-specific display backends (ESP32, STM32, RP2040)
- Spatial partitioning (octree/grid for broad-phase)
- More joint types (hinge, slider, prismatic)
- Perspective-correct texture mapping
- Character controller system
- Mesh colliders (convex hulls)

## ๐ŸŒŸ Production Use

Working embedded example: [Rust on M5Stack Cardputer](https://github.com/Kezii/Rust-M5Stack-Cardputer)

## ๐Ÿ“– References

**Graphics:**
- [Tricks of the 3D Game Programming Gurus]https://www.amazon.com/Tricks-Game-Programming-Gurus-Advanced/dp/0672318350
- [Michael Abrash's Graphics Programming Black Book]https://github.com/jagregory/abrash-black-book
- [PSX Graphics Programming]https://psx-spx.consoledev.net/graphicsprocessingunitgpu/

**Physics:**
- [Game Physics Engine Development]https://www.routledge.com/Game-Physics-Engine-Development/Millington/p/book/9780123819765
- [Real-Time Collision Detection]https://www.amazon.com/Real-Time-Collision-Detection-Interactive-Technology/dp/1558607323
- [Game Programming Gems]https://www.amazon.com/Game-Programming-Gems/dp/1584500492 (Physics sections)

## ๐Ÿ“œ License

MIT OR Apache-2.0 - See LICENSE file for details.

---

**Built with โค๏ธ for the embedded Rust community**