blackhole_renderer 0.1.1

Real-time GPU black hole renderer with gravitational lensing and accretion disk simulation
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
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
# Black Hole Renderer: A GPU-Accelerated Relativistic Ray Tracer

**Project Type:** Real-Time Graphics Simulation  
**Language:** Rust  
**Graphics API:** WebGPU (via wgpu)  
**Version:** 0.1.0  
**Date:** December 2025

---

## Abstract

This document presents the development and implementation of a GPU-accelerated black hole visualization system built using Rust and WebGPU. The project aims to simulate the gravitational lensing effects of a Schwarzschild black hole through real-time ray tracing in compute shaders. The system leverages modern GPU compute capabilities to perform relativistic ray tracing, providing an interactive visualization of spacetime distortion around a black hole. This implementation combines principles from general relativity, numerical integration methods, and high-performance GPU computing to create a physically-based rendering system.

---

## Table of Contents

1. [Introduction](#1-introduction)
2. [Theoretical Background](#2-theoretical-background)
3. [System Architecture](#3-system-architecture)
4. [Technical Implementation](#4-technical-implementation)
5. [Graphics Pipeline](#5-graphics-pipeline)
6. [Shader Implementation](#6-shader-implementation)
7. [Challenges and Solutions](#7-challenges-and-solutions)
8. [Current State and Future Work](#8-current-state-and-future-work)
9. [Appendices](#9-appendices)

---

## 1. Introduction

### 1.1 Motivation

Black holes represent one of the most fascinating phenomena in astrophysics. Their extreme gravitational fields bend spacetime itself, creating dramatic visual effects such as gravitational lensing, light bending, and the iconic accretion disk distortions. Visualizing these effects accurately requires solving the geodesic equations of general relativity, a computationally intensive task that becomes feasible only through GPU acceleration.

### 1.2 Project Objectives

The primary objectives of this project are:

1. **Physical Accuracy**: Implement the Schwarzschild metric to accurately model spacetime curvature around a non-rotating black hole
2. **Real-Time Performance**: Leverage GPU compute shaders to achieve interactive frame rates
3. **Modular Architecture**: Design a clean, maintainable codebase that separates physics, rendering, and GPU management concerns
4. **Educational Value**: Create a system that can be used to understand and visualize relativistic effects

### 1.3 Scope

This project focuses on:
- Schwarzschild (non-rotating) black hole simulation
- GPU-based ray tracing using WebGPU compute shaders
- Real-time interactive rendering
- Modular Rust architecture with clear separation of concerns

---

## 2. Theoretical Background

### 2.1 General Relativity and Black Holes

#### 2.1.1 The Schwarzschild Metric

The Schwarzschild metric describes the spacetime geometry around a spherically symmetric, non-rotating mass. In Schwarzschild coordinates $(t, r, \theta, \phi)$, the line element is:

$$
ds^2 = -\left(1 - \frac{r_s}{r}\right)c^2dt^2 + \left(1 - \frac{r_s}{r}\right)^{-1}dr^2 + r^2d\theta^2 + r^2\sin^2\theta d\phi^2
$$

where:
- $r_s = \frac{2GM}{c^2}$ is the Schwarzschild radius
- $G$ is the gravitational constant
- $M$ is the mass of the black hole
- $c$ is the speed of light

#### 2.1.2 Event Horizon

The event horizon occurs at $r = r_s$, where the metric becomes singular in these coordinates. Light rays inside this radius cannot escape, making the interior causally disconnected from the outside universe.

#### 2.1.3 Photon Sphere

At $r = 1.5 r_s$, photons can orbit the black hole in unstable circular orbits. This creates interesting visual effects in the rendered image.

### 2.2 Geodesic Equations

Light rays in curved spacetime follow null geodesics, which are solutions to the geodesic equation:

$$
\frac{d^2x^\mu}{d\lambda^2} + \Gamma^\mu_{\alpha\beta}\frac{dx^\alpha}{d\lambda}\frac{dx^\beta}{d\lambda} = 0
$$

where $\Gamma^\mu_{\alpha\beta}$ are the Christoffel symbols computed from the metric tensor.

### 2.3 Numerical Integration Methods

Due to the complexity of the geodesic equations, numerical integration is required. Common methods include:

- **Euler Method**: First-order, fast but inaccurate
- **Runge-Kutta 4 (RK4)**: Fourth-order, good balance of accuracy and performance
- **Adaptive Stepsize Methods**: Variable step size for efficiency

---

## 3. System Architecture

### 3.1 Project Structure

The project follows a modular architecture with clear separation of concerns:

```
blackhole_renderer/
├── Cargo.toml              # Project dependencies and metadata
├── LICENSE                 # Project license
├── README.md               # Quick start guide
├── docs/                   # Documentation directory
│   └── project_documentation.md
├── src/                    # Source code directory
│   ├── lib.rs             # Library root (exports public modules)
│   ├── main.rs            # GPU application entry point
│   ├── app.rs             # Application state management (planned)
│   ├── gpu/               # GPU-related modules
│   │   ├── compute.rs     # Compute pipeline management (planned)
│   │   └── state.rs       # GPU state management (planned)
│   ├── physics/           # Physics simulation modules
│   │   ├── mod.rs         # Module declaration
│   │   ├── geodesic.rs    # ✅ Geodesic integration (RK4)
│   │   ├── integration.rs # Numerical integration routines (planned)
│   │   └── schwarzschild.rs # Schwarzschild metric calculations (planned)
│   └── renderer/          # Rendering modules
│       ├── camera.rs      # Camera system (planned)
│       ├── cpu_reference.rs # CPU reference implementation (planned)
│       └── scene.rs       # Scene management (planned)
├── examples/              # Standalone example programs
│   ├── ray_tracing.rs     # ✅ Terminal-based ray trajectory demo
│   └── cpu_image.rs       # ✅ CPU-based PPM image generator
└── shaders/               # WGSL shader files
    ├── trace.wgsl         # Ray tracing compute shader
    └── fullscreen.wgsl    # Fullscreen quad rendering shader
```

### 3.2 Module Responsibilities

#### 3.2.1 Main Module (`main.rs`)
- GPU application initialization
- Window creation using winit
- WebGPU instance, adapter, device, and queue setup
- Event loop management
- Coordination between compute and render passes

#### 3.2.2 Library Module (`lib.rs`)
- Exports public physics modules
- Enables code reuse in examples
- Library API surface

#### 3.2.3 Physics Modules
- **geodesic.rs** ✅: RK4 integration of Schwarzschild geodesics
  - `RayState` struct: Position (r, phi) and momentum (pr)
  - `rk4_step()`: Fourth-order Runge-Kutta integrator
  - Schwarzschild metric derivative functions
  - Public API for library consumers
- **integration.rs** (Planned): General numerical methods
- **schwarzschild.rs** (Planned): Metric tensor calculations

#### 3.2.4 GPU Modules (Planned)
- **state.rs**: GPU resource management and state
- **compute.rs**: Compute pipeline setup and dispatch

#### 3.2.5 Renderer Modules (Planned)
- **camera.rs**: Camera positioning and ray generation
- **scene.rs**: Scene object management
- **cpu_reference.rs**: CPU-based reference implementation for validation

#### 3.2.6 Example Programs ✅
- **ray_tracing.rs**: Single photon trajectory simulation
  - Demonstrates geodesic physics in terminal
  - Validates RK4 integration accuracy
  - Shows event horizon capture dynamics
  
- **cpu_image.rs**: Black hole image generator
  - 800×800 PPM format output
  - Camera-based ray generation
  - Impact parameter calculation
  - Event horizon detection
  - Gradient coloring for escapes
  - Configurable parameters (see §3.3)

### 3.3 CPU Image Generator Architecture

The `cpu_image.rs` example provides a complete CPU-based black hole renderer:

#### 3.3.1 Camera System
- **Position**: r = 20.0 (20 Schwarzschild radii from singularity)
- **Orientation**: Looking at origin
- **Field of View**: 1.0 radian
- **Resolution**: 800×800 pixels

#### 3.3.2 Ray Generation
For each pixel (px, py):
1. Convert pixel coordinates to normalized device coordinates: `(-0.5 to 0.5)`
2. Apply field of view scaling
3. Calculate impact parameter: `l = r_cam × sin(angle)`
4. Initialize `RayState` with starting conditions:
   - r = 20.0 (camera distance)
   - phi = 0.0 (starting angle)
   - pr = -1.0 (inward momentum)

#### 3.3.3 Integration Loop
```rust
for _step in 0..max_steps {
    state = rk4_step(state, l, step_size);
    
    if state.r < 2.0 {  // Event horizon
        return (0, 0, 0);  // Black pixel
    }
    
    if state.r > 50.0 {  // Escape
        let intensity = (state.r - 50.0) / 50.0;
        return gradient_color(intensity);
    }
}
```

#### 3.3.4 Output Format
- **Format**: PPM P3 (ASCII)
- **Color Space**: RGB (0-255)
- **Filename**: `blackhole.ppm`
- **File Size**: ~1.5 MB for 800×800 resolution

#### 3.3.5 Performance Characteristics
- **Pixel Rate**: ~10-50 pixels/second (single-threaded)
- **Total Time**: ~2-15 minutes for full image
- **Accuracy**: Step size 0.01 provides good balance
- **Max Steps**: 5000 per ray (prevents infinite loops)

---

## 4. Technical Implementation

### 4.1 Technology Stack

#### 4.1.1 Core Dependencies

```toml
[dependencies]
winit = "0.29"      # Cross-platform window creation and event handling
wgpu = "0.19"       # Safe Rust bindings for WebGPU API
glam = "0.25"       # Fast linear algebra library
image = "0.24"      # Image encoding/decoding
anyhow = "1.0"      # Flexible error handling
pollster = "0.3"    # Block on async functions
```

#### 4.1.2 Why Rust?

Rust was chosen for this project due to:
- **Memory Safety**: Zero-cost abstractions without garbage collection
- **Performance**: Comparable to C/C++ with better ergonomics
- **Ecosystem**: Excellent WebGPU bindings and math libraries
- **Concurrency**: Fearless concurrent programming model

#### 4.1.3 Why WebGPU?

WebGPU (via wgpu) offers:
- **Modern API**: Designed for both graphics and compute workloads
- **Cross-platform**: Works on Windows, macOS, Linux, and browsers
- **Safety**: Type-safe API with clear ownership semantics
- **Future-proof**: Next-generation graphics standard

### 4.2 GPU Resource Management

#### 4.2.1 Device Initialization

The system initializes WebGPU resources in the following sequence:

1. **Instance Creation**: Creates a WebGPU instance that enumerates available adapters
2. **Adapter Selection**: Selects a GPU adapter with high-performance preference
3. **Device Request**: Requests a logical device and command queue
4. **Surface Configuration**: Sets up the window surface for presentation

```rust
let instance = wgpu::Instance::default();
let surface = instance.create_surface(&window).unwrap();

let adapter = instance
    .request_adapter(&wgpu::RequestAdapterOptions {
        power_preference: wgpu::PowerPreference::HighPerformance,
        compatible_surface: Some(&surface),
        force_fallback_adapter: false,
    })
    .await
    .unwrap();
```

#### 4.2.2 Output Texture

A storage texture is created to hold the compute shader output:

- **Format**: `Rgba16Float` - 16-bit floating point for high dynamic range
- **Usage**: Both storage binding (write) and texture binding (read)
- **Dimensions**: Matches window size for 1:1 pixel mapping

```rust
let texture = device.create_texture(&wgpu::TextureDescriptor {
    label: Some("Output Texture"),
    size: wgpu::Extent3d {
        width: size.width,
        height: size.height,
        depth_or_array_layers: 1,
    },
    format: wgpu::TextureFormat::Rgba16Float,
    usage: wgpu::TextureUsages::STORAGE_BINDING
        | wgpu::TextureUsages::TEXTURE_BINDING,
    // ... other fields
});
```

### 4.3 Surface Configuration

The surface is configured for optimal presentation:

```rust
let surface_config = wgpu::SurfaceConfiguration {
    usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
    format: surface_format,
    width: size.width,
    height: size.height,
    present_mode: wgpu::PresentMode::Fifo,  // V-Sync enabled
    alpha_mode: surface_caps.alpha_modes[0],
    view_formats: vec![],
    desired_maximum_frame_latency: 2,
};
```

**Key Configuration Choices:**
- **Present Mode**: Fifo (V-Sync) for smooth, tear-free rendering
- **Frame Latency**: Maximum 2 frames for reduced input lag
- **Format**: Surface-preferred format for optimal performance

---

## 5. Graphics Pipeline

### 5.1 Dual-Pipeline Architecture

The system uses a two-stage pipeline architecture:

1. **Compute Pipeline**: Generates the ray-traced image
2. **Render Pipeline**: Displays the computed image to screen

```
┌─────────────────┐
│  Compute Pass   │
│  (Ray Tracing)  │
│                 │
│  trace.wgsl     │
└────────┬────────┘
         │ Writes to
         ▼
    ┌────────────┐
    │  Storage   │
    │  Texture   │
    └────┬───────┘
         │ Read by
         ▼
┌─────────────────┐
│  Render Pass    │
│  (Fullscreen)   │
│                 │
│ fullscreen.wgsl │
└────────┬────────┘
         │
         ▼
   ┌──────────┐
   │  Screen  │
   └──────────┘
```

### 5.2 Compute Pipeline

#### 5.2.1 Pipeline Configuration

```rust
let compute_pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
    label: Some("Compute Pipeline"),
    layout: Some(&pipeline_layout),
    module: &shader,
    entry_point: "main",
});
```

#### 5.2.2 Bind Group Layout

The compute shader accesses a single storage texture:

```rust
let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
    entries: &[wgpu::BindGroupLayoutEntry {
        binding: 0,
        visibility: wgpu::ShaderStages::COMPUTE,
        ty: wgpu::BindingType::StorageTexture {
            access: wgpu::StorageTextureAccess::WriteOnly,
            format: wgpu::TextureFormat::Rgba16Float,
            view_dimension: wgpu::TextureViewDimension::D2,
        },
        count: None,
    }],
});
```

#### 5.2.3 Workgroup Dispatch

The compute shader is dispatched with 8×8 workgroups:

```rust
let gx = (size.width + 7) / 8;
let gy = (size.height + 7) / 8;
pass.dispatch_workgroups(gx, gy, 1);
```

This ensures full coverage of the output texture while maintaining efficient GPU occupancy.

### 5.3 Render Pipeline

#### 5.3.1 Fullscreen Quad Rendering

The render pipeline uses a clever technique to render a fullscreen quad without vertex buffers:

- **Vertex Count**: 3 vertices
- **Triangle Size**: Oversized to cover entire screen
- **UV Mapping**: Automatic from vertex index

#### 5.3.2 Bind Group Layout

The render shader reads the computed texture:

```rust
let render_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
    entries: &[
        wgpu::BindGroupLayoutEntry {
            binding: 0,
            visibility: wgpu::ShaderStages::FRAGMENT,
            ty: wgpu::BindingType::Texture {
                multisampled: false,
                view_dimension: wgpu::TextureViewDimension::D2,
                sample_type: wgpu::TextureSampleType::Float { filterable: true },
            },
            count: None,
        },
        wgpu::BindGroupLayoutEntry {
            binding: 1,
            visibility: wgpu::ShaderStages::FRAGMENT,
            ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
            count: None,
        },
    ],
});
```

#### 5.3.3 Pipeline Configuration

```rust
let render_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
    label: Some("Render Pipeline"),
    layout: Some(&render_pipeline_layout),
    vertex: wgpu::VertexState {
        module: &render_shader,
        entry_point: "vs_main",
        buffers: &[],  // No vertex buffer needed
    },
    fragment: Some(wgpu::FragmentState {
        module: &render_shader,
        entry_point: "fs_main",
        targets: &[Some(wgpu::ColorTargetState {
            format: surface_format,
            blend: Some(wgpu::BlendState::REPLACE),
            write_mask: wgpu::ColorWrites::ALL,
        })],
    }),
    primitive: wgpu::PrimitiveState::default(),
    depth_stencil: None,
    multisample: wgpu::MultisampleState::default(),
    multiview: None,
});
```

---

## 6. Shader Implementation

### 6.1 Compute Shader (trace.wgsl)

#### 6.1.1 Current Implementation

The current compute shader implements a simple UV-based gradient as a placeholder:

```wgsl
@group(0) @binding(0)
var output_tex: texture_storage_2d<rgba16float, write>;

@compute @workgroup_size(8, 8)
fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
    let size = textureDimensions(output_tex);

    // Bounds check
    if (gid.x >= size.x || gid.y >= size.y) {
        return;
    }

    // Generate UV coordinates
    let uv = vec2<f32>(
        f32(gid.x) / f32(size.x),
        f32(gid.y) / f32(size.y)
    );

    // Simple gradient output
    let color = vec4<f32>(uv.x, uv.y, 0.2, 1.0);
    textureStore(output_tex, vec2<i32>(gid.xy), color);
}
```

**Key Features:**
- **Workgroup Size**: 8×8 threads per workgroup (64 threads total)
- **Bounds Checking**: Prevents out-of-bounds writes
- **UV Mapping**: Converts pixel coordinates to normalized [0,1] space
- **Direct Storage**: Writes directly to storage texture

#### 6.1.2 Planned Ray Tracing Implementation

The future implementation will include:

1. **Camera Ray Generation**:
   ```wgsl
   fn generate_camera_ray(uv: vec2<f32>) -> Ray {
       // Transform UV to camera space
       // Apply camera transformation
       // Return ray origin and direction
   }
   ```

2. **Geodesic Integration**:
   ```wgsl
   fn trace_geodesic(ray: Ray, max_steps: i32) -> vec4<f32> {
       // Numerical integration of geodesic equations
       // Step along light path in curved spacetime
       // Return final color
   }
   ```

3. **Schwarzschild Metric Evaluation**:
   ```wgsl
   fn schwarzschild_metric(r: f32, theta: f32) -> mat4x4<f32> {
       // Compute metric tensor components
       // Return metric tensor
   }
   ```

4. **Collision Detection**:
   ```wgsl
   fn check_event_horizon(r: f32) -> bool {
       return r < schwarzschild_radius;
   }
   ```

### 6.2 Fragment Shader (fullscreen.wgsl)

#### 6.2.1 Vertex Shader

The vertex shader generates a fullscreen triangle using only the vertex index:

```wgsl
@vertex
fn vs_main(@builtin(vertex_index) i: u32) -> VSOut {
    // Three vertices forming an oversized triangle
    var positions = array<vec2<f32>, 3>(
        vec2<f32>(-1.0, -1.0),  // Bottom-left
        vec2<f32>( 3.0, -1.0),  // Far right
        vec2<f32>(-1.0,  3.0),  // Far top
    );

    // Corresponding UV coordinates
    var uvs = array<vec2<f32>, 3>(
        vec2<f32>(0.0, 0.0),
        vec2<f32>(2.0, 0.0),
        vec2<f32>(0.0, 2.0),
    );

    var out: VSOut;
    out.pos = vec4<f32>(positions[i], 0.0, 1.0);
    out.uv = uvs[i];
    return out;
}
```

**Technique Explanation:**
- Single oversized triangle covers entire screen
- No vertex buffer allocation required
- GPU clips triangle to viewport automatically
- Saves memory bandwidth and setup overhead

#### 6.2.2 Fragment Shader

Simple texture sampling shader:

```wgsl
@fragment
fn fs_main(in: VSOut) -> @location(0) vec4<f32> {
    return textureSample(img, samp, in.uv);
}
```

---

## 7. Challenges and Solutions

### 7.1 Frame Scope Management Issue

#### 7.1.1 Problem

Initial implementation had `frame` variable used outside its scope:

```rust
// INCORRECT: frame used before it's created
let view = frame.texture.create_view(...);
// ... later in event loop
let frame = surface.get_current_texture().unwrap();
```

This caused compilation errors:
- `cannot find value 'frame' in this scope`

#### 7.1.2 Root Cause

The render pass setup was placed before the event loop, attempting to use the frame surface texture before it was acquired. WebGPU requires acquiring a new frame texture each render cycle within the event loop.

#### 7.1.3 Solution

Restructured the event loop to:
1. Acquire frame first
2. Execute compute pass
3. Execute render pass
4. Present frame

```rust
Event::WindowEvent { event: WindowEvent::RedrawRequested, .. } => {
    // 1. Acquire frame
    let frame = surface.get_current_texture().unwrap();
    let view = frame.texture.create_view(...);
    
    // 2. Compute pass
    let mut compute_encoder = device.create_command_encoder(...);
    { /* compute pass */ }
    queue.submit(Some(compute_encoder.finish()));
    
    // 3. Render pass
    let mut render_encoder = device.create_command_encoder(...);
    { /* render pass */ }
    queue.submit(Some(render_encoder.finish()));
    
    // 4. Present
    frame.present();
}
```

### 7.2 WebGPU API Version Compatibility

#### 7.2.1 Problem

wgpu 0.19 introduced breaking changes requiring new mandatory fields:
- `SurfaceConfiguration::desired_maximum_frame_latency`
- `PipelineLayoutDescriptor::push_constant_ranges`
- `RenderPassDescriptor::timestamp_writes`
- `RenderPassDescriptor::occlusion_query_set`

#### 7.2.2 Solution

Updated all struct initializations to include new required fields:

```rust
// Surface configuration
let surface_config = wgpu::SurfaceConfiguration {
    // ... existing fields ...
    desired_maximum_frame_latency: 2,  // Added
};

// Pipeline layout
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
    // ... existing fields ...
    push_constant_ranges: &[],  // Added
});

// Render pass descriptor
let render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
    // ... existing fields ...
    timestamp_writes: None,      // Added
    occlusion_query_set: None,   // Added
});
```

### 7.3 Store Operation Type Change

#### 7.3.1 Problem

The `store` field in `Operations` changed from `bool` to `StoreOp` enum:

```rust
// OLD (incorrect)
ops: wgpu::Operations {
    load: wgpu::LoadOp::Clear(wgpu::Color::BLACK),
    store: true,  // Wrong type
}
```

#### 7.3.2 Solution

```rust
// NEW (correct)
ops: wgpu::Operations {
    load: wgpu::LoadOp::Clear(wgpu::Color::BLACK),
    store: wgpu::StoreOp::Store,  // Correct enum variant
}
```

### 7.4 View Formats Type Mismatch

#### 7.4.1 Problem

`view_formats` field changed from accepting a slice reference to requiring a `Vec`:

```rust
// OLD (incorrect)
view_formats: &[],  // Type mismatch
```

#### 7.4.2 Solution

```rust
// NEW (correct)
view_formats: vec![],  // Empty Vec
```

---

## 8. Current State and Future Work

### 8.1 Current Implementation Status

#### 8.1.1 Completed Components ✅

1. **Application Framework**
   - Window creation and management (winit)
   - Event loop handling
   - GPU initialization and configuration

2. **Compute Pipeline**
   - Compute shader loading and compilation
   - Bind group setup for storage textures
   - Workgroup dispatch logic

3. **Render Pipeline**
   - Fullscreen quad rendering
   - Texture sampling setup
   - Frame presentation

4. **Resource Management**
   - Storage texture creation
   - Surface configuration
   - Pipeline layouts

5. **Shader Infrastructure**
   - WGSL shader files
   - Placeholder compute shader (UV gradient)
   - Fullscreen rendering shader

6. **Physics Module (`src/physics/geodesic.rs`)** ✅
   - `RayState` struct for tracking ray position and momentum
   - RK4 (4th-order Runge-Kutta) numerical integrator
   - Schwarzschild geodesic equations implementation
   - Public API for library reuse

7. **CPU Reference Implementation** ✅
   - **Terminal Ray Tracer** (`examples/ray_tracing.rs`)
     - Single ray trajectory simulation
     - Terminal output showing r, phi evolution
     - Validates physics implementation
   
   - **PPM Image Generator** (`examples/cpu_image.rs`)
     - 800×800 pixel black hole rendering
     - Full camera system at r=20.0
     - Impact parameter calculation from pixel coordinates
     - Event horizon detection (black pixels)
     - Escape gradient coloring
     - PPM P3 format output
     - Up to 5000 integration steps per pixel
     - Configurable step size (0.01 default)

8. **Library Architecture** ✅
   - `src/lib.rs` exporting public modules
   - Physics module reusable in examples
   - Proper Rust module organization

#### 8.1.2 Module Stubs (Empty Files)

The following modules exist but are not yet implemented:
- `src/app.rs`
- `src/gpu/compute.rs`
- `src/gpu/state.rs`
- `src/physics/integration.rs`
- `src/physics/schwarzschild.rs`
- `src/renderer/camera.rs`
- `src/renderer/cpu_reference.rs`
- `src/renderer/scene.rs`

### 8.2 Planned Features

#### 8.2.1 Physics Implementation

1. **Schwarzschild Metric Module**
   - Metric tensor computation
   - Christoffel symbol calculation
   - Coordinate transformations
   - Conserved quantities (energy, angular momentum)

2. **Numerical Integration**
   - RK4 integrator for geodesic equations
   - Adaptive step size control
   - Accuracy vs. performance trade-offs
   - Stability analysis

3. **Ray Initialization**
   - Camera-to-world transformation
   - Initial conditions for light rays
   - Impact parameter calculation

#### 8.2.2 Rendering Enhancements

1. **Camera System**
   - Position and orientation controls
   - Field of view adjustment
   - Orbital camera movement
   - Keyboard/mouse input handling

2. **Scene Management**
   - Background star field
   - Accretion disk geometry
   - Environment mapping
   - Procedural textures

3. **Visual Effects**
   - Doppler shifting (relativistic beaming)
   - Gravitational redshift
   - Time dilation effects
   - Ray intensity attenuation

#### 8.2.3 Performance Optimization

1. **GPU Optimizations**
   - Warp occupancy analysis
   - Memory coalescing
   - Shared memory usage
   - Early ray termination

2. **Algorithmic Improvements**
   - Adaptive step sizing
   - Level-of-detail system
   - Frustum culling for rays
   - Temporal coherence exploitation

#### 8.2.4 User Interface

1. **Control Panel**
   - Black hole mass adjustment
   - Camera controls
   - Render quality settings
   - Performance metrics display

2. **Debug Visualization**
   - Ray path visualization
   - Geodesic plotting
   - Metric tensor heatmap
   - Integration step display

### 8.3 Development Roadmap

#### Phase 1: Core Physics (Weeks 1-2)
- [ ] Implement Schwarzschild metric calculations
- [ ] Create RK4 numerical integrator
- [ ] Write geodesic equation solver
- [ ] Add CPU reference implementation

#### Phase 2: GPU Ray Tracer (Weeks 3-4)
- [ ] Port physics to WGSL compute shader
- [ ] Implement ray initialization from camera
- [ ] Add background environment sampling
- [ ] Optimize compute shader performance

#### Phase 3: Visual Features (Weeks 5-6)
- [ ] Add accretion disk geometry
- [ ] Implement Doppler shifting
- [ ] Add gravitational lensing effects
- [ ] Create procedural star field

#### Phase 4: Interactivity (Weeks 7-8)
- [ ] Implement camera controls
- [ ] Add parameter adjustment UI
- [ ] Create real-time performance monitoring
- [ ] Add screenshot/recording capability

#### Phase 5: Polish and Optimization (Weeks 9-10)
- [ ] Profile and optimize hot paths
- [ ] Add adaptive quality settings
- [ ] Write comprehensive documentation
- [ ] Create example scenes

---

## 9. Appendices

### 9.1 Mathematical Formulations

#### 9.1.1 Schwarzschild Christoffel Symbols

The non-zero Christoffel symbols for the Schwarzschild metric are:

$$
\begin{align}
\Gamma^t_{tr} &= \frac{M}{r(r-2M)} \\
\Gamma^r_{tt} &= \frac{M(r-2M)}{r^3} \\
\Gamma^r_{rr} &= -\frac{M}{r(r-2M)} \\
\Gamma^r_{\theta\theta} &= -(r-2M) \\
\Gamma^r_{\phi\phi} &= -(r-2M)\sin^2\theta \\
\Gamma^\theta_{r\theta} &= \frac{1}{r} \\
\Gamma^\theta_{\phi\phi} &= -\sin\theta\cos\theta \\
\Gamma^\phi_{r\phi} &= \frac{1}{r} \\
\Gamma^\phi_{\theta\phi} &= \cot\theta
\end{align}
$$

#### 9.1.2 Geodesic Equations in Schwarzschild Spacetime

For a photon moving in the equatorial plane ($\theta = \pi/2$):

$$
\begin{align}
\frac{dt}{d\lambda} &= \frac{E}{1-\frac{r_s}{r}} \\
\frac{dr}{d\lambda} &= \pm\sqrt{E^2 - \left(1-\frac{r_s}{r}\right)\frac{L^2}{r^2}} \\
\frac{d\phi}{d\lambda} &= \frac{L}{r^2}
\end{align}
$$

where $E$ and $L$ are conserved energy and angular momentum per unit mass.

### 9.2 Code Snippets

#### 9.2.1 Main Event Loop Structure

```rust
event_loop.run(move |event, target| {
    match event {
        Event::WindowEvent {
            event: WindowEvent::CloseRequested,
            ..
        } => {
            target.exit();
        }

        Event::WindowEvent {
            event: WindowEvent::RedrawRequested,
            ..
        } => {
            // Get frame
            let frame = surface.get_current_texture().unwrap();
            let view = frame.texture.create_view(&wgpu::TextureViewDescriptor::default());

            // Compute pass
            let mut compute_encoder = device.create_command_encoder(...);
            {
                let mut pass = compute_encoder.begin_compute_pass(...);
                pass.set_pipeline(&compute_pipeline);
                pass.set_bind_group(0, &bind_group, &[]);
                pass.dispatch_workgroups(gx, gy, 1);
            }
            queue.submit(Some(compute_encoder.finish()));

            // Render pass
            let mut render_encoder = device.create_command_encoder(...);
            {
                let mut rpass = render_encoder.begin_render_pass(...);
                rpass.set_pipeline(&render_pipeline);
                rpass.set_bind_group(0, &render_bg, &[]);
                rpass.draw(0..3, 0..1);
            }
            queue.submit(Some(render_encoder.finish()));
            
            frame.present();
        }

        _ => {}
    }
});
```

### 9.3 Performance Considerations

#### 9.3.1 GPU Workgroup Size Selection

The chosen 8×8 workgroup size (64 threads) balances several factors:

| Factor | Consideration |
|--------|---------------|
| **Occupancy** | Most GPUs have 32-64 threads per warp/wavefront |
| **Memory** | Small workgroup reduces shared memory pressure |
| **Dispatch** | Even division for most common resolutions |
| **Flexibility** | Works well across different GPU architectures |

#### 9.3.2 Memory Layout

```
Storage Texture (Rgba16Float):
- 4 channels × 16 bits = 64 bits per pixel
- For 1920×1080: ~16.6 MB
- Write-only in compute, read-only in fragment
- No CPU-GPU transfer needed
```

### 9.4 References and Resources

#### 9.4.1 Academic Papers
1. **Schwarzschild, K.** (1916). "On the Gravitational Field of a Mass Point According to Einstein's Theory"
2. **Chandrasekhar, S.** (1983). "The Mathematical Theory of Black Holes"
3. **Marck, J.A.** (1996). "Short-cut method of solution of geodesic equations for Schwarzschild black hole"

#### 9.4.2 Online Resources
- [WebGPU Specification](https://www.w3.org/TR/webgpu/)
- [wgpu Documentation](https://docs.rs/wgpu/)
- [WGSL Specification](https://www.w3.org/TR/WGSL/)
- [Rust Graphics Programming](https://sotrh.github.io/learn-wgpu/)

#### 9.4.3 Tools and Libraries
- **winit**: Cross-platform window creation
- **wgpu**: Safe Rust WebGPU bindings
- **glam**: Fast 3D math library
- **pollster**: Synchronous async executor

### 9.5 Build and Run Instructions

#### 9.5.1 Prerequisites

```bash
# Install Rust (if not already installed)
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

# Ensure Rust is up to date
rustup update stable
```

#### 9.5.2 Building the Project

```bash
# Clone/navigate to project directory
cd blackhole_renderer

# Build in debug mode
cargo build

# Build in release mode (optimized)
cargo build --release
```

#### 9.5.3 Running the Application

```bash
# Run in debug mode
cargo run

# Run in release mode
cargo run --release
```

#### 9.5.4 Expected Output

Current implementation displays:
- Window titled "Black Hole Renderer"
- UV-based gradient (placeholder for ray tracing)
- Colors: Red channel = X coordinate, Green channel = Y coordinate

### 9.6 Troubleshooting

#### 9.6.1 Common Issues

**Problem**: Compilation errors about missing fields  
**Solution**: Ensure wgpu version 0.19 or later

**Problem**: Black screen on startup  
**Solution**: Check GPU driver support for Vulkan/DirectX 12/Metal

**Problem**: Performance issues  
**Solution**: Run with `--release` flag for optimizations

#### 9.6.2 Debug Tips

```bash
# Enable wgpu validation (slower but catches errors)
RUST_LOG=wgpu=info cargo run

# Enable full logging
RUST_LOG=trace cargo run

# Check GPU info
cargo run | grep "Using GPU"
```

### 9.7 License and Acknowledgments

This project is released under the MIT License (see LICENSE file).

**Acknowledgments:**
- The wgpu team for excellent WebGPU bindings
- The Rust community for tools and libraries
- Academic researchers in general relativity and black hole physics
- Graphics programming community for shader techniques

---

## Conclusion

This project represents a comprehensive implementation of a GPU-accelerated black hole renderer using modern graphics APIs and physically-based simulation techniques. The modular architecture provides a solid foundation for implementing the full relativistic ray tracing system, while the current implementation demonstrates the core rendering pipeline and GPU compute infrastructure.

The combination of Rust's safety guarantees, WebGPU's performance capabilities, and principles from general relativity creates an exciting platform for both scientific visualization and educational purposes. Future development will focus on implementing the complete physics simulation, adding interactive controls, and optimizing performance for real-time interaction.

The project serves as both a technical demonstration of GPU compute capabilities and an educational tool for understanding the visual effects of extreme gravitational fields. As development continues, it will provide increasingly accurate and visually stunning representations of one of nature's most fascinating phenomena.

---

**Document Version:** 1.0  
**Last Updated:** December 2025  
**Author:** Project Developer  
**Status:** Active Development