-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
272 lines (220 loc) · 7.32 KB
/
app.py
File metadata and controls
272 lines (220 loc) · 7.32 KB
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
"""
Singularity - Interactive Schwarzschild Black Hole Visualizer
Real-time gravitational lensing simulation using general relativity.
Supports both local (Pygame) and Google Colab (ipywidgets) environments.
Controls:
WASD / Arrow Keys : Orbit camera around black hole
Q / E : Zoom in / out
ESC : Quit (local mode only)
"""
import math
import sys
import time
import numpy as np
import taichi as ti
try:
import pygame
except ImportError:
pygame = None
from singularity.config import (
init_taichi,
rs,
WIDTH,
HEIGHT,
D_LAMBDA,
MAX_STEPS,
is_colab,
IN_COLAB,
)
from singularity.renderer.raytracer import RayTracer
from singularity.renderer.camera import Camera
from singularity.visualization.display import get_display_manager
def print_controls():
"""Print control instructions to console"""
print("\n" + "=" * 50)
print(" SINGULARITY - Black Hole Visualizer")
print("=" * 50)
print("\nControls:")
print(" W / ↑ : Orbit up")
print(" S / ↓ : Orbit down")
print(" A / ← : Orbit left")
print(" D / → : Orbit right")
print(" Q : Zoom in")
print(" E : Zoom out")
print(" ESC : Quit (local mode)")
print("\nPhysics:")
print(f" Black Hole : Sagittarius A*")
print(f" Mass : {8.54e36:.2e} kg (~4.3 million solar masses)")
print(f" r_s : {rs:.3e} m ({rs / 1e9:.2f} billion km)")
print(f" Resolution : {WIDTH} x {HEIGHT}")
print("=" * 50 + "\n")
def run_colab_mode():
"""Run in Google Colab with ipywidgets controls"""
print("Running in Colab mode...")
# Initialize Taichi
init_taichi()
# Create renderer
tracer = RayTracer(HEIGHT, WIDTH, rs)
# Initialize camera
cam_dist = 6.0 * rs
camera = Camera(pos=[cam_dist, 0, 0.5 * rs], target=[0, 0, 0])
# Get display manager (Colab)
window = get_display_manager(WIDTH, HEIGHT)
# Frame timing
frame_count = 0
start_time = time.time()
print("Rendering started. Use the control buttons to navigate.")
print("Close the notebook cell to stop.\n")
# Main render loop
while window.running:
# Handle input from ipywidgets
keys = window.handle_events()
# Camera controls
move_speed = 0.05
moved = False
# Check for key states
if keys[pygame.K_a] or keys[pygame.K_LEFT]:
camera.orbit(-move_speed, 0)
moved = True
if keys[pygame.K_d] or keys[pygame.K_RIGHT]:
camera.orbit(move_speed, 0)
moved = True
if keys[pygame.K_w] or keys[pygame.K_UP]:
camera.orbit(0, -move_speed)
moved = True
if keys[pygame.K_s] or keys[pygame.K_DOWN]:
camera.orbit(0, move_speed)
moved = True
if keys[pygame.K_q]:
camera.zoom(0.95)
moved = True
if keys[pygame.K_e]:
camera.zoom(1.05)
moved = True
if moved:
tracer.reset_accumulation()
# Get camera vectors for Taichi
c_pos, c_fwd, c_up, c_rt = camera.get_taichi_vectors()
# Calculate aspect and tan_fov in Python scope
aspect = WIDTH / HEIGHT
tan_fov = math.tan(camera.fov / 2.0)
# Render frame
tracer.render(
cam_pos=c_pos,
cam_fwd=c_fwd,
cam_up=c_up,
cam_right=c_rt,
fov=camera.fov,
dl=D_LAMBDA,
max_steps=MAX_STEPS,
aspect=aspect,
tan_fov=tan_fov
)
# Update display
window.update(tracer.get_image())
# Frame rate tracking
frame_count += 1
if frame_count % 30 == 0:
elapsed = time.time() - start_time
fps = frame_count / elapsed if elapsed > 0 else 0
print(f"FPS: {fps:.1f} | Distance: {camera.dist / rs:.2f} r_s")
start_time = time.time()
frame_count = 0
window.clock.tick(30) # Target 30 FPS for Colab
print("Visualization stopped.")
def run_local_mode():
"""Run locally with Pygame window"""
print("Running in local mode...")
try:
import pygame
except ImportError:
print("Error: pygame not installed. Install with: pip install pygame")
sys.exit(1)
# Initialize Taichi
init_taichi()
# Create renderer
tracer = RayTracer(HEIGHT, WIDTH, rs)
# Initialize camera
cam_dist = 6.0 * rs
camera = Camera(pos=[cam_dist, 0, 0.5 * rs], target=[0, 0, 0])
# Get display manager (Pygame)
window = get_display_manager(WIDTH, HEIGHT)
# Frame timing
frame_count = 0
start_time = time.time()
# Main render loop
while window.running:
# Handle Pygame events
keys = window.handle_events()
# Camera controls
move_speed = 0.05
moved = False
if keys[pygame.K_a] or keys[pygame.K_LEFT]:
camera.orbit(-move_speed, 0)
moved = True
if keys[pygame.K_d] or keys[pygame.K_RIGHT]:
camera.orbit(move_speed, 0)
moved = True
if keys[pygame.K_w] or keys[pygame.K_UP]:
camera.orbit(0, -move_speed)
moved = True
if keys[pygame.K_s] or keys[pygame.K_DOWN]:
camera.orbit(0, move_speed)
moved = True
if keys[pygame.K_q]:
camera.zoom(0.95)
moved = True
if keys[pygame.K_e]:
camera.zoom(1.05)
moved = True
if moved:
tracer.reset_accumulation()
# Get camera vectors for Taichi
c_pos, c_fwd, c_up, c_rt = camera.get_taichi_vectors()
# Calculate aspect and tan_fov in Python scope
aspect = WIDTH / HEIGHT
tan_fov = math.tan(camera.fov / 2.0)
# Render frame
tracer.render(
cam_pos=c_pos,
cam_fwd=c_fwd,
cam_up=c_up,
cam_right=c_rt,
fov=camera.fov,
dl=D_LAMBDA,
max_steps=MAX_STEPS,
aspect=aspect,
tan_fov=tan_fov
)
# Update display
window.update(tracer.get_image())
# Frame rate tracking
frame_count += 1
if frame_count % 60 == 0:
elapsed = time.time() - start_time
fps = frame_count / elapsed if elapsed > 0 else 0
print(f"FPS: {fps:.1f} | Distance: {camera.dist / rs:.2f} r_s")
start_time = time.time()
frame_count = 0
window.clock.tick(60) # Target 60 FPS
pygame.quit()
print("Visualization stopped.")
def main():
"""Main entry point"""
try:
print_controls()
# Detect environment and run appropriate mode
if is_colab() or IN_COLAB:
run_colab_mode()
else:
run_local_mode()
except KeyboardInterrupt:
print("\nInterrupted by user.")
sys.exit(0)
except Exception as e:
print(f"\nError: {e}")
import traceback
traceback.print_exc()
sys.exit(1)
if __name__ == "__main__":
main()