Skip to content

AnthonyNystrom/NuGenPSurface-Python

Repository files navigation

NuGenPSurface

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 Application

Overview

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

Features

Three Visualization Modes

1. Parametric Surfaces

  • 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

2. 4D Fractals

  • 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

3. Advanced Materials (PBR)

  • 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

Core Features

  • 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

Installation

Prerequisites

  • Python 3.8 or higher
  • pip package manager
  • Modern web browser with WebGL support

Setup

  1. Install dependencies:
cd NuGenPSurface
pip install -r requirements.txt
  1. Run the application:
python app.py
  1. Open browser to:
http://localhost:5002

Usage

Parametric Surfaces Tab

Predefined Surfaces:

  1. Select a surface from the dropdown (organized by category)
  2. Choose quality level (Lowest to Highest)
  3. Surface renders automatically in 3D viewport
  4. View expressions and parameters in the floating info panel

Custom Surfaces:

  1. Select "Custom Surface" from dropdown
  2. 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
  3. Click "Generate Custom Surface"

Example - Sphere:

X: cos(u) * sin(v)
Y: sin(u) * sin(v)
Z: cos(v)
u: [0, 2π]
v: [0, π]

4D Fractals Tab

Predefined Fractals:

  1. Select a fractal from the dropdown
  2. 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)
  3. Fractal renders automatically
  4. View iteration formulas in the info panel

Custom Fractals:

  1. Select "Custom Fractal" from dropdown
  2. Enter quaternion iteration formulas (zr', zi', zj', zk')
  3. Set constant values (cr, ci, cj, ck)
  4. 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]

Advanced Materials Tab

Using Presets:

  1. Select source type (Surface or Fractal)
  2. Choose a specific source from the dropdown
  3. Select a material preset (Chrome, Gold, Glass, etc.)
  4. Select a lighting preset (Studio, Outdoor, etc.)
  5. Choose render quality
  6. 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:

  1. Enable clipping checkbox
  2. Choose axis (X, Y, or Z)
  3. Adjust position slider
  4. Toggle "Keep Positive Side" to choose which half to keep

Mirroring:

  1. Select mirror type:
    • Planar: Mirror across a plane (X=0, Y=0, or Z=0)
    • Radial: Circular repetition around an axis (2-12 segments)
  2. Choose axis and position

Deformation:

  1. Select deformation type (Twist, Bend, Taper, Wave)
  2. Adjust strength slider
  3. Choose axis for deformation

Subdivision:

  1. Select subdivision level (1-3)
  2. Higher levels create smoother meshes

Custom Materials:

  1. Generate a surface/fractal with any material
  2. Adjust sliders in real-time:
    • Metalness (0.0 = dielectric, 1.0 = metal)
    • Roughness (0.0 = mirror, 1.0 = matte)
  3. Toggle post-processing:
    • Bloom (glow effect)
    • Shadows (soft shadows)
    • Ambient Occlusion (contact shadows)
  4. Click "Apply Material Only" to update without regenerating geometry

Controls

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 view
  • W: Toggle wireframe mode
  • G: Toggle grid
  • I: Toggle info panel
  • F: Toggle fullscreen
  • Space: Play/pause animation
  • 1-3: Switch between tabs
  • Q: Cycle through quality presets
  • M: Cycle through material presets (Advanced tab)

Export

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

Mathematical Functions

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)

Architecture

Backend (Python Flask)

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

Frontend (JavaScript/Three.js)

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

Key Design Patterns

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

API Endpoints

GET /api/surfaces

Get list of all available surfaces with categories

GET /api/surface/

Get detailed information about a specific surface

POST /api/generate

Generate mesh from predefined surface

{
  "surface": "torus",
  "quality": "medium"
}

POST /api/generate/custom

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 /api/fractals

Get list of all available fractals

GET /api/fractal/

Get detailed information about a specific fractal

POST /api/generate/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"
}

POST /api/generate/custom_fractal

Generate mesh from custom fractal formulas

GET /api/materials

Get list of all available PBR materials

GET /api/lighting_presets

Get list of all lighting presets

POST /api/mesh/advanced

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"
    }
  ]
}

POST /api/export/obj

Export current mesh as OBJ file

POST /api/validate

Validate mathematical expression for safety

Quality Levels

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

Surface Categories

Basic Shapes

Sphere, Torus, Cylinder, Cone, Plane, Cube, Ellipsoid

Minimal Surfaces

Enneper, Catenoid, Helicoid, Costa, Breather, Henneberg, Catalan, Scherk, Schwarz P, Schwarz D, Gyroid

Topology

Moebius Strip, Klein Bottle, Boy's Surface, Cross Cap, Roman Surface, Steiner Surface

Knots

Trefoil Knot, Figure-Eight Knot, Cinquefoil Knot, Torus Knot (various)

Natural Forms

Heart, Drop, Egg, Apple, Shell, Nautilus Shell, Snail Shell, Seashell

Exotic Surfaces

Dini's Surface, Kuen Surface, Whitney Umbrella, Bohemian Dome, Astroidal Ellipsoid, Dupin Cyclide

And 50+ more surfaces!

4D Fractal Types

Classic Fractals

  • Quaternion Julia - Julia sets in 4D quaternion space
  • Burning Ship - 4D extension of the Burning Ship fractal
  • Custom Fractals - User-defined quaternion iteration formulas

Visualization Methods

  • 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

PBR Materials

Metallic Materials

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

Glass/Crystal Materials

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

Special Materials

Neon - Emissive glow materials (various colors) Holographic - Multi-color iridescent effect Pearl - Subsurface scattering pearlescence Carbon Fiber - Anisotropic composite material

Lighting Presets

Studio - Three-point lighting (key, fill, rim) Outdoor - Natural daylight simulation Dramatic - High-contrast directional lighting Soft - Diffuse ambient illumination

Performance

  • 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

Security

  • 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

Conversion from Original

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)

Development

Project Structure

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)

Adding New Surfaces

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"
)

Adding New Materials

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
}

Adding New Fractals

Edit modules/fractal_definitions.py to add new iteration formulas and fractal types.

Troubleshooting

Application won't start

  • Check Python version: python --version (needs 3.8+)
  • Install dependencies: pip install -r requirements.txt
  • Check port 5002 is available: lsof -i :5002

Mesh not rendering

  • Check browser console for errors (F12)
  • Verify WebGL support: Visit https://get.webgl.org/
  • Try reducing quality level
  • Check expression syntax

Slow performance

  • 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

Custom expressions fail

  • 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.)

License

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.

Credits

  • 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

Contributing

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

Support

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.

About

Python/Flask based Mathematical Surface Visualization

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published