A sophisticated real-time raytracing simulation featuring first-person exploration through procedurally lit 3D mazes
Experience immersive 3D raytracing with FPS-style controls โข Real-time lighting โข Dynamic shadows
๐ Quick Start โข ๐ฎ Controls โข ๐ง Technical Details โข ๐น Demo
|
|
| ๐ฎ FPS Mode | ๐ 3D Overview |
|---|---|
| Interactive first-person exploration | Animated bird's-eye visualization |
| Navigate mazes with WASD controls | Watch dynamic lighting in 3D space |
| Real-time raytracing rendering | Cinematic camera movements |
The engine renders complex 3D environments in real-time by casting rays from the player's viewpoint. Each pixel represents a ray shot into the virtual world, calculating intersections with maze walls to create realistic lighting, shadows, and depth effects.
- Pure Python Implementation: No external graphics libraries required
- Educational Raytracing: Perfect for learning ray-based rendering concepts
- Performance Optimized: Vectorized operations for smooth frame rates
- Customizable Everything: Easily modify maze layouts, lighting, and visual effects
|
Required:
|
Optional:
|
๐ฆ Method 1: Quick Setup (Recommended)
# Clone the repository
git clone https://github.com/mehmetkahya0/raytrace.git
cd raytrace
# Create and activate virtual environment
python -m venv .venv
source .venv/bin/activate # On Windows: .venv\Scripts\activate
# Install dependencies
pip install -r requirements.txt
# Run the FPS raytracer
python main.py๐ง Method 2: Manual Setup
# Create project directory
mkdir raytrace && cd raytrace
# Set up virtual environment
python -m venv .venv
source .venv/bin/activate
# Install dependencies manually
pip install numpy>=1.21.0 matplotlib>=3.5.0
# Download the source files
# Then run: python main.py๐ฑ macOS
# Using Homebrew
brew install ffmpeg
# Using MacPorts
sudo port install ffmpeg๐ง Linux (Ubuntu/Debian)
sudo apt update
sudo apt install ffmpeg๐ช Windows
- Download from ffmpeg.org
- Extract to
C:\ffmpeg - Add
C:\ffmpeg\binto your PATH
python main.py| Key | Action | Key | Action |
|---|---|---|---|
W |
๐ผ Move Forward | Q |
โฌ ๏ธ Strafe Left |
S |
๐ฝ Move Backward | E |
โก๏ธ Strafe Right |
A |
๐ Turn Left | D |
โฉ๏ธ Turn Right |
๐ก Tip: Click on the window to give it focus before using controls
Features in FPS Mode:
- ๐ฏ Real-time first-person perspective
- ๐ Live position and angle display
- ๐ซ๏ธ Dynamic fog and lighting effects
- ๐ฌ Automatic video recording to
fps_raytracing.mp4
python graph_view.pyFeatures in Overview Mode:
- ๐ฅ Cinematic 3D visualization
- ๐ก Animated moving light source
- ๐ 360ยฐ rotating camera view
- ๐น Export to
raytracing_simulation.mp4
Both modes automatically generate high-quality MP4 videos:
# Files created after running:
fps_raytracing.mp4 # First-person exploration recording
raytracing_simulation.mp4 # 3D overview animationraytrace/
โโโ ๐ฎ main.py # Interactive FPS raytracing engine
โโโ ๐ graph_view.py # 3D overview visualization with animated lighting
โโโ ๐ requirements.txt # Python dependencies (numpy, matplotlib)
โโโ ๐ซ .gitignore # Git ignore rules for Python projects
โโโ ๐ README.md # Comprehensive project documentation
โโโ ๐ .venv/ # Virtual environment (auto-generated)
โโโ ๐ฌ *.mp4 # Generated video files (auto-created)
๐ฎ main.py - Interactive FPS Engine
Core Components:
cast_ray()- Ray intersection calculationsrender_frame()- Real-time frame renderingget_wall_color()- Lighting and fog calculationsupdate()- Animation loop with player movement- Keyboard event handlers for smooth controls
Key Features:
- 320x240 screen resolution (configurable)
- 60ยฐ field of view with perspective projection
- Dynamic player position tracking
- Real-time collision detection
๐ graph_view.py - 3D Visualization
Core Components:
create_wall_cubes()- 3D maze geometry generationlight_intensity()- Distance-based lighting calculationscolor_at_point()- Volumetric color mapping- Vectorized operations for performance optimization
Key Features:
- Poly3D wall rendering with transparency
- Animated light source movement
- Scatter plot visualization of lit spaces
- Cinematic camera positioning
๐ฌ Core Rendering Pipeline
# Simplified algorithm flow:
for each_pixel_column in screen_width:
ray_angle = calculate_ray_direction(pixel, player_angle, fov)
ray_direction = [cos(ray_angle), sin(ray_angle), 0]
distance, hit_point = cast_ray(player_position, ray_direction)
wall_height = screen_height / (distance + 0.1)
wall_color = calculate_lighting(hit_point, light_source)
render_wall_column(pixel_column, wall_height, wall_color)- Ray Generation: Cast rays from player position through each screen column
- Intersection Testing: Step along ray until hitting a wall or boundary
- Distance Calculation: Measure ray travel distance for perspective
- Lighting Computation: Apply inverse square law and fog effects
- Screen Projection: Convert 3D coordinates to 2D screen pixels
|
Mathematical Foundation: # Light intensity calculation
distance = ||hit_point - light_source||
intensity = 1.0 / (1.0 + distance * 0.1)
# Fog effect
fog_factor = max(0.0, 1.0 - distance / 20.0)
# Final color
color = base_color * intensity * fog_factor |
Visual Effects:
|
| Technique | Implementation | Benefit |
|---|---|---|
| ๐ Vectorization | NumPy array operations | 10x faster calculations |
| ๐พ Pre-computation | Cache empty space positions | Reduced runtime overhead |
| ๐ฏ Efficient Ray Stepping | Fixed step size iteration | Consistent performance |
| ๐ Optimized Animation | Minimal object recreation | Smooth frame rates |
๐๏ธ Rendering Settings
# Maze and world settings
maze_size = (20, 20, 10) # World dimensions (x, y, z)
screen_width = 320 # Render resolution width
screen_height = 240 # Render resolution height
# Camera and movement
fov = np.pi / 3 # Field of view (60 degrees)
move_speed = 0.1 # Player movement speed
rotation_speed = 0.05 # Turning sensitivity
# Lighting and atmosphere
light_pos = [15.0, 15.0, 8.0] # Light source position
max_render_distance = 30 # Ray casting limit
fog_distance = 20.0 # Fog effect range๐๏ธ Maze Construction
# Create custom maze layouts
maze = np.zeros(maze_size)
# Add wall blocks (1 = wall, 0 = empty space)
maze[1:3, 1:8, 1:3] = 1 # Rectangular wall section
maze[5:7, 5:12, 1:4] = 1 # Another wall group
maze[8:10, 2:6, 1:3] = 1 # Individual wall cluster
# Walls can be any shape or size within the grid| Effect | Description | Implementation |
|---|---|---|
| ๐ Realistic Lighting | Distance-based light falloff with smooth gradients | Inverse square law calculations |
| ๐ซ๏ธ Atmospheric Fog | Objects fade with distance for depth perception | Linear fog factor interpolation |
| ๐ Wall Shading | Surfaces closer to light sources appear brighter | Dynamic color intensity mapping |
| ๐ Environment Rendering | Complete floor, ceiling, and wall visualization | Full 3D space ray intersection |
| ๐ฌ Perspective Projection | Realistic first-person view with proper FOV | Mathematical perspective transformation |
| ๐จ Color Interpolation | Smooth transitions between light and shadow | RGB gradient calculations |
๐ฏ Wall Rendering Process
# For each screen column:
1. Calculate ray direction based on FOV and player angle
2. Cast ray into 3D world until wall intersection
3. Compute wall height using perspective projection
4. Apply lighting based on distance to light source
5. Render wall column with proper color intensity
6. Fill remaining pixels with floor/ceiling colors๐ Color System
- Base Colors: Configurable wall, floor, and ceiling tones
- Light Intensity: Real-time calculations based on distance
- Fog Blending: Linear interpolation for atmospheric effects
- Dynamic Range: Full 0-1 color range with proper clamping
Both modes automatically save animations:
fps_raytracing.mp4- First-person explorationraytracing_simulation.mp4- 3D overview animation
|
๐ข NumPy (โฅ1.21.0)
|
๐ Matplotlib (โฅ3.5.0)
|
| Component | Minimum | Recommended |
|---|---|---|
| ๐ Python | 3.8+ | 3.9+ |
| ๐พ RAM | 2GB | 4GB+ |
| ๐ฅ๏ธ OS | Windows/macOS/Linux | Any modern OS |
| ๐ฌ FFmpeg | Optional | For video export |
๐ฏ Using requirements.txt (Recommended)
pip install -r requirements.txtContents of requirements.txt:
numpy>=1.21.0
matplotlib>=3.5.0๐ง Manual Installation
pip install numpy matplotlib- CPU Usage: Intensive during rendering (normal for raytracing)
- Memory: ~100-500MB depending on maze size
- Frame Rate: 20-60 FPS on modern hardware
- Optimization: Vectorized NumPy operations for maximum speed
|
|
Looking to contribute? Here are some great starting points:
๐ฐ Beginner-Friendly Tasks
- ๐จ Add new maze layouts and patterns
- ๐ Implement different color schemes
- ๐ Create performance benchmarking tools
- ๐ Improve documentation and comments
- ๐ Fix minor bugs and edge cases
๐ฅ Advanced Challenges
- โก GPU-accelerated rendering pipeline
- ๐ต 3D positional audio system
- ๐ค AI pathfinding for NPCs
- ๐ Network multiplayer support
- ๐ฎ VR/AR compatibility layer
๐ Quick Contribution Guide
-
๐ด Fork the Repository
# Click the Fork button on GitHub, then: git clone https://github.com/yourusername/raytrace.git cd raytrace
-
๐ฟ Create Feature Branch
git checkout -b feature/amazing-new-feature
-
๐ป Make Your Changes
- Add new features or fix bugs
- Follow existing code style
- Add comments for complex logic
- Test your changes thoroughly
-
โ Commit and Push
git add . git commit -m "Add amazing new feature" git push origin feature/amazing-new-feature
-
๐ Create Pull Request
- Open a PR on GitHub
- Describe your changes clearly
- Link any related issues
|
๐ฏ What We're Looking For:
|
๐ Code Standards:
|
| Type | Description | Examples |
|---|---|---|
| ๐ Bug Fix | Fix existing issues | Collision detection, memory leaks |
| โจ Feature | Add new functionality | New lighting effects, controls |
| ๐ Documentation | Improve docs | README updates, code comments |
| ๐จ Enhancement | Improve existing features | Performance, visual quality |
| ๐งช Testing | Add or improve tests | Unit tests, integration tests |
- ๐ญ Questions? Open a Discussion
- ๐ Found a Bug? Create an Issue
- ๐ก Feature Ideas? Start a Feature Request
- ๐ฅ Community: Join our development discussions
๐ ImportError: No module named 'numpy' or 'matplotlib'
Problem: Missing dependencies
Solution:
# Make sure virtual environment is activated
source .venv/bin/activate # macOS/Linux
# .venv\Scripts\activate # Windows
# Install dependencies
pip install -r requirements.txt
# Or install manually
pip install numpy>=1.21.0 matplotlib>=3.5.0๐ฌ FFmpeg not found error when saving videos
Problem: FFmpeg not installed or not in PATH
Solutions:
macOS:
# Using Homebrew (recommended)
brew install ffmpeg
# Using MacPorts
sudo port install ffmpegLinux (Ubuntu/Debian):
sudo apt update
sudo apt install ffmpegWindows:
- Download from ffmpeg.org
- Extract to
C:\ffmpeg - Add
C:\ffmpeg\binto your system PATH
Alternative: Comment out the video saving lines if you don't need video export:
# ani.save('fps_raytracing.mp4', writer='ffmpeg', fps=20)โจ๏ธ Keyboard controls not working
Problem: Window doesn't have focus
Solution:
- Click on the matplotlib window to give it focus
- Make sure the window is active (not minimized)
- Try clicking in the plot area specifically
macOS users: You may need to click multiple times or use Cmd+Tab to ensure focus.
๐ Poor performance / Low frame rate
Problem: Performance issues
Solutions:
-
Reduce screen resolution:
screen_width = 160 # Default: 320 screen_height = 120 # Default: 240
-
Decrease maze size:
maze_size = (10, 10, 5) # Default: (20, 20, 10)
-
Increase ray step size:
step_size = 0.2 # Default: 0.1 (less accurate but faster)
-
Close other applications to free up system resources
๐ฅ๏ธ Display issues on high-DPI screens
Problem: Blurry or incorrectly sized display
Solution:
# Add at the beginning of your script
import matplotlib
matplotlib.rcParams['figure.dpi'] = 100 # Adjust as needed| Tip | Description | Impact |
|---|---|---|
| ๐ง Optimize Settings | Reduce resolution/maze size | 2-5x speedup |
| ๐พ Use SSD | Run from SSD instead of HDD | Faster loading |
| ๐ฅ๏ธ Close Apps | Free up system resources | Smoother experience |
| ๐ Update Python | Use Python 3.9+ for better performance | 10-20% improvement |
| โก Virtual Environment | Use clean venv to avoid conflicts | More stable |
|
๐ macOS
|
๐ง Linux
|
๐ช Windows
|
If you're still having issues:
- ๐ Search existing Issues - Your problem might already be solved
- ๐ Create a new Issue - Include your OS, Python version, and error messages
- ๐ฌ Join Discussions - Get help from the community
- ๐ง Contact maintainers - For urgent or security-related issues
This project is licensed under the MIT License - see the LICENSE file for details.
What this means:
- โ Commercial use - Use in commercial projects
- โ Modification - Change and adapt the code
- โ Distribution - Share with others
- โ Private use - Use for personal projects
โ ๏ธ Limitation - No warranty or liability
|
๐ฎ Inspiration
|
๐ฌ Science Stack
|
๐ฅ Community
|
- ๐ NumPy Community - For blazing-fast numerical operations
- ๐จ Matplotlib Team - For powerful visualization capabilities
- ๐ฎ Game Dev Community - For inspiration and techniques
- ๐ Computer Graphics Pioneers - For foundational algorithms
Made with โค๏ธ and Python
๐งโ๐ป Created by Mehmet Kahya โข ๐ 2025
Bringing raytracing to everyone, one ray at a time โจ