A modern web-based mathematical visualization application for parametric surfaces, 4D fractals, and advanced PBR materials. Converted from my original C++/.NET DirectX application to Python Flask with Three.js WebGL rendering.
NuGenPSurface provides real-time 3D visualization of mathematical objects across three main categories:
- Parametric Surfaces - 80+ predefined mathematical surfaces with custom equation support
- 4D Fractals - Quaternion-based fractals with 3D slice visualization
- Advanced Materials - PBR (Physically Based Rendering) materials with realistic lighting and mesh operations
- 80+ predefined surfaces including minimal surfaces, topological shapes, knots, and more
- Custom parametric equations X(u,v), Y(u,v), Z(u,v) with full mathematical expression support
- Real-time parameter adjustment
- Multi-dimensional support (4D, 5D, 6D projections to 3D)
- Quality levels from 2,500 to 30,000 vertices
- Quaternion-based fractal iteration: z_n+1 = f(z_n) + c
- Classic fractals: Julia sets, Quaternion Julia, Burning Ship
- Custom fractal formulas with real-time editing
- 3D slice visualization through 4D space (XY, XZ, YZ, XW, YW, ZW planes)
- Multiple coloring methods: Escape time, orbit trap, distance estimation
- Configurable iteration counts (10-500), escape radius (1.0-10.0), and slice parameters
- Source Types: Apply effects to any parametric surface or 4D fractal
- 20+ Realistic Materials: Chrome, Gold, Copper, Glass, Crystal, Neon, Holographic, Pearl
- Physically Based Rendering: Metalness/roughness workflow with ACESFilmic tone mapping
- Multiple Lighting Presets: Studio, Outdoor, Dramatic, Soft
- Mesh Operations:
- Clipping: Cut meshes along X/Y/Z planes with adjustable position
- Mirroring: Planar (reflect across axis) or Radial (circular segments 2-12x)
- Deformation: Twist, bend, taper, wave effects
- Subdivision: Smooth mesh refinement
- Post-Processing Effects: Bloom, shadows, ambient occlusion
- Real-Time Material Adjustment: Modify metalness, roughness, and effects without regenerating geometry
- Unified Custom Formula Editor: Single adaptive interface for surfaces and fractals
- Interactive 3D Rendering - WebGL-accelerated with Three.js
- Export Functionality - OBJ mesh export and PNG screenshots
- Live Preview - Real-time updates as you adjust parameters
- Keyboard Shortcuts - Efficient navigation and control (press ? for help)
- Responsive UI - Modern interface with floating info panels
- Input Validation - Secure expression parsing with safety checks
- Memory Management - Efficient resource cleanup and lazy initialization
- Python 3.8 or higher
- pip package manager
- Modern web browser with WebGL support
- Install dependencies:
cd NuGenPSurface
pip install -r requirements.txt- Run the application:
python app.py- Open browser to:
http://localhost:5002
Predefined Surfaces:
- Select a surface from the dropdown (organized by category)
- Choose quality level (Lowest to Highest)
- Surface renders automatically in 3D viewport
- View expressions and parameters in the floating info panel
Custom Surfaces:
- Select "Custom Surface" from dropdown
- Enter parametric equations in the fields that appear:
- X(u,v) = expression
- Y(u,v) = expression
- Z(u,v) = expression
- Parameter ranges for u and v
- Click "Generate Custom Surface"
Example - Sphere:
X: cos(u) * sin(v)
Y: sin(u) * sin(v)
Z: cos(v)
u: [0, 2π]
v: [0, π]
Predefined Fractals:
- Select a fractal from the dropdown
- Adjust parameters:
- Max Iterations (10-500)
- Escape Radius (1.0-10.0)
- Slice Plane (XY, XZ, YZ, XW, YW, ZW)
- Slice Value (-2.0 to 2.0)
- Color Method (Escape Time, Orbit Trap, Distance)
- Fractal renders automatically
- View iteration formulas in the info panel
Custom Fractals:
- Select "Custom Fractal" from dropdown
- Enter quaternion iteration formulas (zr', zi', zj', zk')
- Set constant values (cr, ci, cj, ck)
- Click "Generate Custom Fractal"
Example - Quaternion Julia:
Formula: z_n+1 = f(z_n) + c
Real (zr'): zr*zr - zi*zi - zj*zj - zk*zk + cr
i (zi'): 2*zr*zi + ci
j (zj'): 2*zr*zj + cj
k (zk'): 2*zr*zk + ck
Constant (c): [-0.8, 0.156, 0.0, 0.0]
Using Presets:
- Select source type (Surface or Fractal)
- Choose a specific source from the dropdown
- Select a material preset (Chrome, Gold, Glass, etc.)
- Select a lighting preset (Studio, Outdoor, etc.)
- Choose render quality
- Click "Generate"
Custom Formulas with Advanced Effects: The Advanced tab features a unified custom formula section that adapts based on source type:
- For Surfaces: Shows X(u,v), Y(u,v), Z(u,v) parametric fields
- For Fractals: Shows Real, i, j, k quaternion iteration fields + constant values
- Formula fields automatically populate when you select a preset, and remain editable
- Single "Generate Custom with Advanced Effects" button applies all operations
Mesh Operations:
Clipping:
- Enable clipping checkbox
- Choose axis (X, Y, or Z)
- Adjust position slider
- Toggle "Keep Positive Side" to choose which half to keep
Mirroring:
- Select mirror type:
- Planar: Mirror across a plane (X=0, Y=0, or Z=0)
- Radial: Circular repetition around an axis (2-12 segments)
- Choose axis and position
Deformation:
- Select deformation type (Twist, Bend, Taper, Wave)
- Adjust strength slider
- Choose axis for deformation
Subdivision:
- Select subdivision level (1-3)
- Higher levels create smoother meshes
Custom Materials:
- Generate a surface/fractal with any material
- Adjust sliders in real-time:
- Metalness (0.0 = dielectric, 1.0 = metal)
- Roughness (0.0 = mirror, 1.0 = matte)
- Toggle post-processing:
- Bloom (glow effect)
- Shadows (soft shadows)
- Ambient Occlusion (contact shadows)
- Click "Apply Material Only" to update without regenerating geometry
Mouse:
- Left drag: Rotate camera around the object
- Right drag: Pan camera left/right/up/down
- Scroll wheel: Zoom in/out
Keyboard Shortcuts:
Press ? in the application to see all shortcuts, including:
R: Reset camera viewW: Toggle wireframe modeG: Toggle gridI: Toggle info panelF: Toggle fullscreenSpace: Play/pause animation1-3: Switch between tabsQ: Cycle through quality presetsM: Cycle through material presets (Advanced tab)
OBJ Export:
- Click "Export as OBJ" to download mesh file
- Compatible with Blender, Maya, 3ds Max, etc.
- Includes vertex positions, normals, and colors
Screenshot:
- Click "Take Screenshot" to save current view as PNG
- High-resolution capture of the viewport
All tabs support these mathematical functions:
Trigonometric:
sin, cos, tan, asin, acos, atan, atan2
Hyperbolic:
sinh, cosh, tanh, asinh, acosh, atanh
Exponential/Logarithmic:
exp, log, log10, log2
Power/Root:
sqrt, cbrt, pow
Rounding:
floor, ceil, round, trunc
Other:
abs, sign, min, max, mod
Constants:
pi, e, tau
Operators:
+, -, *, /, ^ (power), % (modulo)
app.py - Main Flask application
- REST API endpoints
- Request handling and validation
- Mesh generation coordination
modules/function_parser.py - Mathematical expression parser
- Evaluates parametric equations
- Vectorized NumPy evaluation for performance
- Safe expression parsing with security checks
- Automatic scalar broadcasting for constant expressions
modules/matrix_transforms.py - Transformation matrices
- 3D, 4D, 5D, 6D homogeneous transformations
- Rotation, scaling, translation operations
- Perspective projection from higher dimensions to 3D
modules/surfaces.py - Surface library
- 80+ predefined mathematical surfaces
- Organized by category
- Surface definitions with expressions and parameter ranges
modules/fractal_definitions.py - Fractal library
- Quaternion-based 4D fractals
- Multiple iteration methods (Julia, Burning Ship)
- Custom formula support
modules/mesh_generator.py - Mesh generation
- Converts parametric surfaces to triangle meshes
- Quality level management
- Computes vertex normals and colors
- OBJ export functionality
- Mesh operations: clipping, mirroring, deformation, subdivision
modules/advanced_materials.py - PBR material definitions
- 20+ physically accurate material presets
- Metalness/roughness values based on real-world measurements
- Lighting preset configurations
static/js/app.js - Main application logic
- Three.js scene management
- Tab coordination (Parametric, 4D Fractals, Advanced)
- Event handling and UI updates
- Camera controls and rendering loop
- Dynamic renderer settings per tab (tone mapping, exposure)
- Lazy initialization for performance
- Unified custom formula interface with adaptive fields
static/js/advanced_renderer.js - Advanced rendering module
- PBR material management
- Lighting setup and control
- Post-processing effects (bloom, shadows, AO)
- Material property updates
- Resource cleanup and disposal
static/js/orbit_controls.js - Camera controls
- Mouse and touch interaction
- Smooth camera movement
- Zoom and pan functionality
Lazy Initialization:
- Advanced renderer only created when Advanced tab first accessed
- Saves memory (~60%) for users who don't use Advanced features
- Zero performance impact on Parametric and 4D Fractals tabs
Dynamic Renderer Settings:
- Renderer properties set per frame based on active tab
- Parametric/4D: THREE.NoToneMapping, exposure 1.0
- Advanced: ACESFilmicToneMapping, exposure 1.8, physically correct lights
- Ensures each tab maintains its intended appearance
Resource Management:
- AbortController for canceling pending requests (prevents race conditions)
- Dispose methods for cleanup of Three.js objects
- Event listener cleanup on tab switches
- Memory-efficient mesh handling
Input Validation:
- Expression sanitization prevents code injection
- Length limits and keyword blacklists
- Safe evaluation in sandboxed environment
Adaptive UI:
- Single unified custom formula section in Advanced tab
- Dynamic field visibility based on source type (surface vs fractal)
- Context-sensitive hints and button labels
- Automatic formula population from presets
Get list of all available surfaces with categories
Get detailed information about a specific surface
Generate mesh from predefined surface
{
"surface": "torus",
"quality": "medium"
}Generate mesh from custom parametric equations
{
"expressions": {
"x": "cos(u) * sin(v)",
"y": "sin(u) * sin(v)",
"z": "cos(v)"
},
"parameters": {
"u": {"min": 0, "max": 6.28},
"v": {"min": 0, "max": 3.14}
},
"quality": "medium"
}Get list of all available fractals
Get detailed information about a specific fractal
Generate mesh from fractal with parameters
{
"fractal": "quaternion_julia",
"parameters": {
"constant": [-0.8, 0.156, 0.0, 0.0],
"max_iterations": 100,
"escape_radius": 2.0,
"slice_plane": "xy",
"slice_value": 0.0
},
"quality": "medium"
}Generate mesh from custom fractal formulas
Get list of all available PBR materials
Get list of all lighting presets
Generate mesh with advanced materials, lighting, and mesh operations
{
"source_type": "surface",
"source_name": "torus",
"quality": "medium",
"material": "chrome",
"lighting": "studio",
"operations": [
{
"type": "mirror",
"mirror_type": "radial",
"axis": "y",
"segments": 6
},
{
"type": "deform",
"deform_type": "twist",
"strength": 0.5,
"axis": "y"
}
]
}Export current mesh as OBJ file
Validate mathematical expression for safety
| Level | Resolution | Vertices | Triangles | Use Case |
|---|---|---|---|---|
| Lowest | 50×50 | 2,500 | 4,802 | Quick preview |
| Low | 100×50 | 5,000 | 9,702 | Fast interaction |
| Medium | 150×75 | 11,250 | 22,052 | Balanced quality |
| High | 200×100 | 20,000 | 39,602 | Detailed visualization |
| Highest | 300×100 | 30,000 | 59,702 | Export/presentation |
Sphere, Torus, Cylinder, Cone, Plane, Cube, Ellipsoid
Enneper, Catenoid, Helicoid, Costa, Breather, Henneberg, Catalan, Scherk, Schwarz P, Schwarz D, Gyroid
Moebius Strip, Klein Bottle, Boy's Surface, Cross Cap, Roman Surface, Steiner Surface
Trefoil Knot, Figure-Eight Knot, Cinquefoil Knot, Torus Knot (various)
Heart, Drop, Egg, Apple, Shell, Nautilus Shell, Snail Shell, Seashell
Dini's Surface, Kuen Surface, Whitney Umbrella, Bohemian Dome, Astroidal Ellipsoid, Dupin Cyclide
And 50+ more surfaces!
- Quaternion Julia - Julia sets in 4D quaternion space
- Burning Ship - 4D extension of the Burning Ship fractal
- Custom Fractals - User-defined quaternion iteration formulas
- 3D Slicing - Extract 3D cross-sections through 4D space
- Slice Planes - XY, XZ, YZ, XW, YW, ZW
- Color Mapping - Escape time, orbit trap, distance estimation
Chrome - Mirror-polished chromium (metalness: 1.0, roughness: 0.05) Gold - 24k gold (color: [1.0, 0.766, 0.336]) Copper - Pure copper (color: [0.95, 0.64, 0.54]) Brushed Metal - Anisotropic aluminum Rainbow Metal - Iridescent thin-film effect
Clear Glass - Transparent with refraction (IOR: 1.5) Frosted Glass - Semi-transparent with high roughness Crystal - Diamond-like with clearcoat Colored Glass - Tinted transparent materials
Neon - Emissive glow materials (various colors) Holographic - Multi-color iridescent effect Pearl - Subsurface scattering pearlescence Carbon Fiber - Anisotropic composite material
Studio - Three-point lighting (key, fill, rim) Outdoor - Natural daylight simulation Dramatic - High-contrast directional lighting Soft - Diffuse ambient illumination
- Frontend: 60 FPS WebGL rendering with hardware acceleration
- Backend: NumPy vectorized calculations for efficient mesh generation
- Network: Compressed JSON mesh data for fast transmission
- Memory: Lazy initialization saves 60% memory for unused features
- Optimization: AbortController prevents race conditions in live preview
- Input Validation: All mathematical expressions sanitized before evaluation
- Expression Length Limits: Maximum 500 characters
- Keyword Blacklist: Prevents dangerous Python operations
- Sandboxed Evaluation: Safe mathematical expression execution
- CORS: Configured for secure cross-origin requests
This application is a complete rewrite of the C++/.NET DirectX NuGenPSurface application:
Original (C++/CLI):
- Windows Forms desktop application
- DirectX 9 hardware acceleration
- ~40,000 lines of C++ code
- Windows-only
New (Python/JavaScript):
- Web-based Flask application
- Three.js WebGL rendering
- Modern modular architecture
- Cross-platform (any OS with browser)
- Enhanced features (4D fractals, PBR materials, mesh operations)
NuGenPSurface/
├── app.py # Flask application
├── requirements.txt # Python dependencies
├── modules/
│ ├── __init__.py
│ ├── function_parser.py # Expression evaluator
│ ├── matrix_transforms.py # Transformation matrices
│ ├── surfaces.py # Surface library (80+ surfaces)
│ ├── fractal_definitions.py # 4D fractal definitions
│ ├── advanced_materials.py # PBR material definitions
│ └── mesh_generator.py # Mesh generation and export
├── templates/
│ └── index.html # Main HTML page
└── static/
├── js/
│ ├── app.js # Main Three.js application
│ ├── advanced_renderer.js # PBR rendering module
│ └── orbit_controls.js # Camera controls
├── css/
│ └── styles.css # Application styles
└── models/
└── (exported OBJ files)
Edit modules/surfaces.py:
"my_surface": SurfaceDefinition(
name="My Surface",
x_expr="cos(u) * (2 + cos(v))",
y_expr="sin(u) * (2 + cos(v))",
z_expr="sin(v)",
u_min=0, u_max=2*np.pi,
v_min=0, v_max=2*np.pi,
description="Description of my surface",
category="Custom"
)Edit modules/advanced_materials.py:
"my_material": {
"base_color": [r, g, b],
"metalness": 1.0,
"roughness": 0.1,
"emissive": [0, 0, 0],
"emissive_intensity": 0.0,
"clearcoat": 0.0,
"clearcoat_roughness": 0.0
}Edit modules/fractal_definitions.py to add new iteration formulas and fractal types.
- Check Python version:
python --version(needs 3.8+) - Install dependencies:
pip install -r requirements.txt - Check port 5002 is available:
lsof -i :5002
- Check browser console for errors (F12)
- Verify WebGL support: Visit https://get.webgl.org/
- Try reducing quality level
- Check expression syntax
- Reduce quality level (use Lowest or Low)
- Close other browser tabs
- Disable post-processing effects in Advanced tab
- Check GPU drivers are up to date
- Verify syntax (use supported functions only)
- Check parameter ranges (avoid division by zero)
- Ensure expression length < 500 characters
- No forbidden keywords (import, eval, exec, etc.)
MIT License
Copyright © 2025 Anthony Nystrom
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
See LICENSE file for full details.
- Author: Anthony Nystrom
- Original NuGenPSurface: C++/.NET DirectX application (2000s)
- Web Conversion: Python Flask + Three.js (2025)
- Mathematical Surfaces: Various mathematicians and geometers
- PBR Material Values: Based on industry standards (Marmoset, Substance, Disney BRDF)
- Open Source: MIT License - Free to use, modify, and distribute
Contributions are welcome! Areas for enhancement:
- Additional parametric surfaces
- New fractal types and iteration formulas
- More PBR material presets
- Additional mesh operations
- Performance optimizations
- UI/UX improvements
- Documentation and examples
For issues, questions, or feature requests, please open an issue on the project repository.
NuGenPSurface - Exploring the beauty of mathematical visualization in 3D and beyond.
