# gargantua_hyper_realistic.py
import pygame
import random
import math
import numpy as np
# --- Constants ---
SCREEN_WIDTH = 1200
SCREEN_HEIGHT = 900
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
YELLOW = (255, 255, 0)
ORANGE = (255, 165, 0)
DARK_ORANGE = (200, 100, 0)
NEAR_WHITE_YELLOW = (255, 255, 200)
GLOW_COLOR = (255, 200, 100, 50) # Semi-transparent for glow
# Simulation Parameters
BH_RADIUS_BASE = 60 # Base radius of the black hole event horizon
DISK_OUTER_RADIUS_BASE = 400 # Base outer radius of the accretion disk
DISK_THICKNESS_BASE = 40 # Base visual thickness of the disk edge
LENSING_RADIUS_FACTOR = 3.0 # How far out the noticeable lensing distortion goes
STAR_COUNT = 1000
PARTICLE_COUNT = 200
DISK_ROTATION_SPEED = 0.0005 # Radians per frame
FOV = 60 # Field of view in degrees for perspective projection
# --- Initialization ---
pygame.init()
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Gargantua Hyper-Realistic Simulator")
clock = pygame.time.Clock()
random.seed()
# --- Simulation State Variables ---
zoom_level = 1.0
min_zoom = 0.2
max_zoom = 5.0
pan_offset_x = 0.0
pan_offset_y = 0.0
view_yaw = 0.0 # Rotation around Y-axis (left-right)
view_pitch = 0.0 # Rotation around X-axis (up-down)
disk_angle = 0.0 # For disk rotation animation
# --- Helper Functions ---
def rotation_matrix(yaw, pitch):
"""Returns a 3x3 rotation matrix for yaw (Y) and pitch (X) in radians."""
cos_y, sin_y = math.cos(yaw), math.sin(yaw)
cos_p, sin_p = math.cos(pitch), math.sin(pitch)
rot_yaw = np.array([
[cos_y, 0, sin_y],
[0, 1, 0],
[-sin_y, 0, cos_y]
])
rot_pitch = np.array([
[1, 0, 0],
[0, cos_p, -sin_p],
[0, sin_p, cos_p]
])
return rot_yaw @ rot_pitch
def project_3d_to_2d(x, y, z, center_x, center_y, zoom, rot_matrix, fov=FOV):
"""Projects a 3D point to 2D screen coordinates with perspective."""
# Apply rotation
point = np.array([x, y, z])
rotated = rot_matrix @ point
# Perspective projection
z_depth = rotated[2] + 1000 # Offset to ensure positive z (camera distance)
if z_depth <= 0: # Behind camera, don't draw
return None, None, None
fov_rad = math.radians(fov)
scale = (SCREEN_HEIGHT / 2) / (z_depth * math.tan(fov_rad / 2))
screen_x = center_x + (rotated[0] + pan_offset_x) * scale * zoom
screen_y = center_y - (rotated[1] + pan_offset_y) * scale * zoom # Invert Y for screen coords
depth = z_depth # For depth sorting or scaling effects
return screen_x, screen_y, depth
def generate_stars(count):
"""Generates random star positions in 3D space."""
stars = []
area_scale = 5
for _ in range(count):
# Spherical distribution for 3D effect
dist = random.uniform(500, 2000) # Distance from origin
theta = random.uniform(0, 2 * math.pi) # Azimuthal angle
phi = random.uniform(0, math.pi) # Polar angle
x = dist * math.sin(phi) * math.cos(theta)
y = dist * math.sin(phi) * math.sin(theta)
z = dist * math.cos(phi)
brightness = random.uniform(50, 200) * (2000 - dist) / 1500 # Dimmer further away
size = random.randint(1, 3)
stars.append({
'x': x, 'y': y, 'z': z,
'brightness': int(brightness),
'size': size
})
return stars
def generate_particles(count):
"""Generates particles in the accretion disk plane with motion."""
particles = []
for _ in range(count):
# Particles are in the disk plane (y=0) with some thickness
r = random.uniform(BH_RADIUS_BASE * 1.2, DISK_OUTER_RADIUS_BASE)
theta = random.uniform(0, 2 * math.pi)
x = r * math.cos(theta)
z = r * math.sin(theta)
y = random.uniform(-DISK_THICKNESS_BASE / 4, DISK_THICKNESS_BASE / 4) # Small vertical spread
# Orbital velocity (simplified, faster closer to BH)
v = math.sqrt(1 / max(r, BH_RADIUS_BASE * 1.1)) * 0.05
particles.append({
'x': x, 'y': y, 'z': z,
'theta': theta, 'r': r, 'v': v,
'brightness': random.uniform(100, 255),
'size': random.uniform(1, 3)
})
return particles
def apply_lensing_distortion(x, y, z, bh_center_x, bh_center_y, bh_center_z, bh_radius, lensing_radius):
"""Applies a simplified 3D gravitational lensing effect."""
dx, dy, dz = x - bh_center_x, y - bh_center_y, z - bh_center_z
dist_sq = dx*dx + dy*dy + dz*dz
if dist_sq < 1e-6 or dist_sq > lensing_radius**2:
return x, y, z # No distortion if too far or at center
dist = math.sqrt(dist_sq)
effective_dist = max(dist, bh_radius * 0.8) # Avoid extreme distortion inside horizon
push_factor = 1.0 + (bh_radius**2 / effective_dist**2) * 2.0 # Stronger lensing closer to BH
push_factor = min(push_factor, 4.0) # Cap distortion
new_x = bh_center_x + dx / dist * effective_dist * push_factor
new_y = bh_center_y + dy / dist * effective_dist * push_factor
new_z = bh_center_z + dz / dist * effective_dist * push_factor
return new_x, new_y, new_z
# --- Generate Stars and Particles ---
stars = generate_stars(STAR_COUNT)
particles = generate_particles(PARTICLE_COUNT)
# --- Main Loop ---
running = True
while running:
# --- Event Handling ---
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
running = False
elif event.key == pygame.K_EQUALS or event.key == pygame.K_PLUS or event.key == pygame.K_PAGEUP:
zoom_level = min(max_zoom, zoom_level * 1.2)
elif event.key == pygame.K_MINUS or event.key == pygame.K_UNDERSCORE or event.key == pygame.K_PAGEDOWN:
zoom_level = max(min_zoom, zoom_level / 1.2)
elif event.key == pygame.K_LEFT:
pan_offset_x += 50 / zoom_level
elif event.key == pygame.K_RIGHT:
pan_offset_x -= 50 / zoom_level
elif event.key == pygame.K_UP:
pan_offset_y += 50 / zoom_level
elif event.key == pygame.K_DOWN:
pan_offset_y -= 50 / zoom_level
elif event.key == pygame.K_a:
view_yaw += 0.05
elif event.key == pygame.K_d:
view_yaw -= 0.05
elif event.key == pygame.K_w:
view_pitch += 0.05
elif event.key == pygame.K_s:
view_pitch -= 0.05
elif event.key == pygame.K_r: # Reset view
zoom_level = 1.0
pan_offset_x = 0.0
pan_offset_y = 0.0
view_yaw = 0.0
view_pitch = 0.0
disk_angle = 0.0
# --- Update State ---
disk_angle += DISK_ROTATION_SPEED
center_x = SCREEN_WIDTH // 2
center_y = SCREEN_HEIGHT // 2
rot_matrix = rotation_matrix(view_yaw, view_pitch)
# Calculate screen-space dimensions based on zoom
bh_radius_screen = BH_RADIUS_BASE * zoom_level
disk_outer_radius_screen = DISK_OUTER_RADIUS_BASE * zoom_level
disk_thickness_screen = DISK_THICKNESS_BASE * zoom_level
lensing_radius_screen = bh_radius_screen * LENSING_RADIUS_FACTOR
# --- Drawing ---
screen.fill(BLACK)
# Create a surface for glow effects
glow_surface = pygame.Surface((SCREEN_WIDTH, SCREEN_HEIGHT), pygame.SRCALPHA)
# 1. Draw Stars (with 3D projection and lensing)
star_draw_list = [] # For depth sorting
for star in stars:
# Apply lensing in 3D space
x, y, z = apply_lensing_distortion(
star['x'], star['y'], star['z'],
0, 0, 0, # Black hole at origin
BH_RADIUS_BASE, DISK_OUTER_RADIUS_BASE * LENSING_RADIUS_FACTOR
)
# Project to 2D
sx, sy, depth = project_3d_to_2d(x, y, z, center_x, center_y, zoom_level, rot_matrix)
if sx is None: continue # Behind camera
if not (-50 < sx < SCREEN_WIDTH + 50 and -50 < sy < SCREEN_HEIGHT + 50): continue # Off-screen
star_draw_list.append({
'sx': sx, 'sy': sy, 'depth': depth,
'brightness': star['brightness'],
'size': star['size'] * (1000 / depth) * zoom_level # Size scales with depth
})
# Sort stars by depth (furthest first)
star_draw_list.sort(key=lambda s: s['depth'], reverse=True)
for star in star_draw_list:
brightness = int(star['brightness'] * (1000 / star['depth'])) # Dimmer further away
color = (min(255, brightness), min(255, brightness), min(255, brightness * 0.8))
size = max(1, int(star['size']))
pygame.draw.circle(screen, color, (int(star['sx']), int(star['sy'])), size)
# 2. Update and Draw Particles (in disk plane, with motion)
particle_draw_list = []
for particle in particles:
# Update particle position (orbital motion)
particle['theta'] += particle['v']
particle['x'] = particle['r'] * math.cos(particle['theta'])
particle['z'] = particle['r'] * math.sin(particle['theta'])
# Apply lensing
x, y, z = apply_lensing_distortion(
particle['x'], particle['y'], particle['z'],
0, 0, 0, BH_RADIUS_BASE, DISK_OUTER_RADIUS_BASE * LENSING_RADIUS_FACTOR
)
# Project to 2D
sx, sy, depth = project_3d_to_2d(x, y, z, center_x, center_y, zoom_level, rot_matrix)
if sx is None: continue
if not (-50 < sx < SCREEN_WIDTH + 50 and -50 < sy < SCREEN_HEIGHT + 50): continue
particle_draw_list.append({
'sx': sx, 'sy': sy, 'depth': depth,
'brightness': particle['brightness'],
'size': particle['size'] * (1000 / depth) * zoom_level
})
particle_draw_list.sort(key=lambda p: p['depth'], reverse=True)
for particle in particle_draw_list:
brightness = int(particle['brightness'] * (1000 / particle['depth']))
color = (min(255, brightness), min(255, brightness * 0.9), min(255, brightness * 0.7))
size = max(1, int(particle['size']))
pygame.draw.circle(screen, color, (int(particle['sx']), int(particle['sy'])), size)
# Add glow to glow_surface
glow_size = size * 3
pygame.draw.circle(glow_surface, GLOW_COLOR, (int(particle['sx']), int(particle['sy'])), int(glow_size))
# 3. Draw Accretion Disk (Main Plane - 3D Elliptical Ring)
disk_segments = 100
disk_draw_list = []
for i in range(disk_segments):
theta = (i / disk_segments) * 2 * math.pi
# Outer edge of disk
x_outer = DISK_OUTER_RADIUS_BASE * math.cos(theta)
z_outer = DISK_OUTER_RADIUS_BASE * math.sin(theta)
y_outer = 0 # Disk lies in XZ plane
# Inner edge (just outside BH)
x_inner = BH_RADIUS_BASE * 1.2 * math.cos(theta)
z_inner = BH_RADIUS_BASE * 1.2 * math.sin(theta)
y_inner = 0
# Apply lensing to both points
x_outer, y_outer, z_outer = apply_lensing_distortion(
x_outer, y_outer, z_outer, 0, 0, 0, BH_RADIUS_BASE, DISK_OUTER_RADIUS_BASE * LENSING_RADIUS_FACTOR
)
x_inner, y_inner, z_inner = apply_lensing_distortion(
x_inner, y_inner, z_inner, 0, 0, 0, BH_RADIUS_BASE, DISK_OUTER_RADIUS_BASE * LENSING_RADIUS_FACTOR
)
# Project to 2D
sx_outer, sy_outer, depth_outer = project_3d_to_2d(x_outer, y_outer, z_outer, center_x, center_y, zoom_level, rot_matrix)
sx_inner, sy_inner, depth_inner = project_3d_to_2d(x_inner, y_inner, z_inner, center_x, center_y, zoom_level, rot_matrix)
if sx_outer is None or sx_inner is None: continue
disk_draw_list.append({
'sx_outer': sx_outer, 'sy_outer': sy_outer, 'depth_outer': depth_outer,
'sx_inner': sx_inner, 'sy_inner': sy_inner, 'depth_inner': depth_inner,
'theta': theta
})
disk_draw_list.sort(key=lambda d: min(d['depth_outer'], d['depth_inner']), reverse=True)
for i, seg in enumerate(disk_draw_list):
next_seg = disk_draw_list[(i + 1) % len(disk_draw_list)]
# Calculate brightness based on distance from BH and angle (brighter inside, facing camera)
r = (seg['depth_outer'] + seg['depth_inner']) / 2
brightness = 255 * (DISK_OUTER_RADIUS_BASE / r)**0.5
# Color gradient
lerp = (DISK_OUTER_RADIUS_BASE - r) / (DISK_OUTER_RADIUS_BASE - BH_RADIUS_BASE)
r_col = int(NEAR_WHITE_YELLOW[0] * (1 - lerp) + ORANGE[0] * lerp)
g_col = int(NEAR_WHITE_YELLOW[1] * (1 - lerp) + ORANGE[1] * lerp)
b_col = int(NEAR_WHITE_YELLOW[2] * (1 - lerp) + ORANGE[2] * lerp)
color = (min(255, r_col), min(255, g_col), min(255, b_col))
# Draw quad for disk segment
points = [
(int(seg['sx_outer']), int(seg['sy_outer'])),
(int(seg['sx_inner']), int(seg['sy_inner'])),
(int(next_seg['sx_inner']), int(next_seg['sy_inner'])),
(int(next_seg['sx_outer']), int(next_seg['sy_outer']))
]
pygame.draw.polygon(screen, color, points)
# Add glow
glow_points = points
glow_size = 10 * zoom_level
for px, py in glow_points:
pygame.draw.circle(glow_surface, GLOW_COLOR, (int(px), int(py)), int(glow_size))
# 4. Draw Lensed Disk Arcs (Above and Below) - Simplified 3D
arc_segments = 50
arc_draw_list = []
for arc_type in ['upper', 'lower']:
for i in range(arc_segments):
theta = (i / arc_segments) * math.pi + math.pi / 2 # Half circle for arcs
# Simulate lensed arc by placing points just outside BH, distorted upwards/downwards
r_base = BH_RADIUS_BASE * 1.5
x = r_base * math.cos(theta)
z = r_base * math.sin(theta)
y = (BH_RADIUS_BASE * 1.5 if arc_type == 'upper' else -BH_RADIUS_BASE * 1.5) # Vertical offset
x, y, z = apply_lensing_distortion(x, y, z, 0, 0, 0, BH_RADIUS_BASE, DISK_OUTER_RADIUS_BASE * LENSING_RADIUS_FACTOR)
sx, sy, depth = project_3d_to_2d(x, y, z, center_x, center_y, zoom_level, rot_matrix)
if sx is None: continue
arc_draw_list.append({
'sx': sx, 'sy': sy, 'depth': depth,
'theta': theta, 'arc_type': arc_type
})
arc_draw_list.sort(key=lambda a: a['depth'], reverse=True)
for i, arc in enumerate(arc_draw_list):
if i == 0: continue
prev_arc = arc_draw_list[i - 1]
if arc['arc_type'] != prev_arc['arc_type']: continue
# Brightness and color similar to disk
r = arc['depth']
brightness = 255 * (DISK_OUTER_RADIUS_BASE / r)**0.5
lerp = (DISK_OUTER_RADIUS_BASE - r) / (DISK_OUTER_RADIUS_BASE - BH_RADIUS_BASE)
r_col = int(NEAR_WHITE_YELLOW[0] * (1 - lerp) + DARK_ORANGE[0] * lerp)
g_col = int(NEAR_WHITE_YELLOW[1] * (1 - lerp) + DARK_ORANGE[1] * lerp)
b_col = int(NEAR_WHITE_YELLOW[2] * (1 - lerp) + DARK_ORANGE[2] * lerp)
color = (min(255, r_col), min(255, g_col), min(255, b_col))
pygame.draw.line(screen, color, (int(prev_arc['sx']), int(prev_arc['sy'])), (int(arc['sx']), int(arc['sy'])), int(5 * zoom_level))
# Add glow
pygame.draw.circle(glow_surface, GLOW_COLOR, (int(arc['sx']), int(arc['sy'])), int(15 * zoom_level))
# 5. Draw Black Hole Event Horizon (as a 3D sphere)
bh_points = []
for theta in range(0, 360, 10):
for phi in range(0, 180, 10):
theta_rad = math.radians(theta)
phi_rad = math.radians(phi)
x = BH_RADIUS_BASE * math.sin(phi_rad) * math.cos(theta_rad)
y = BH_RADIUS_BASE * math.sin(phi_rad) * math.sin(theta_rad)
z = BH_RADIUS_BASE * math.cos(phi_rad)
sx, sy, depth = project_3d_to_2d(x, y, z, center_x, center_y, zoom_level, rot_matrix)
if sx is not None:
bh_points.append((sx, sy, depth))
bh_points.sort(key=lambda p: p[2], reverse=True)
for i, (sx, sy, depth) in enumerate(bh_points):
if depth > 1000: # Front side of sphere
pygame.draw.circle(screen, BLACK, (int(sx), int(sy)), int(BH_RADIUS_BASE * zoom_level * (1000 / depth)))
# 6. Apply Glow Effects
screen.blit(glow_surface, (0, 0), special_flags=pygame.BLEND_ADD)
# --- Display Update ---
pygame.display.flip()
# --- Frame Limiting ---
clock.tick(30) # Limit to 30 FPS for performance
# --- Cleanup ---
pygame.quit()