summaryrefslogtreecommitdiff
path: root/assets/final/shaders
AgeCommit message (Collapse)Author
18 hoursfeat(gpu): Add WGSL noise and hash function library (Task #59)skal
Implements comprehensive RNG and noise functions for procedural shader effects: Hash Functions: - hash_1f, hash_2f, hash_3f (float-based, fast) - hash_2f_2f, hash_3f_3f (vector output) - hash_1u, hash_1u_2f, hash_1u_3f (integer-based, high quality) Noise Functions: - noise_2d, noise_3d (value noise with smoothstep) - fbm_2d, fbm_3d (fractional Brownian motion) - gyroid (periodic minimal surface) Integration: - Added to ShaderComposer as "math/noise" snippet - Available via #include "math/noise" in WGSL shaders - Test suite validates all 11 functions compile Testing: - test_noise_functions.cc validates shader loading - All 33 tests pass (100%) Size Impact: ~200-400 bytes per function used (dead-code eliminated) Files: - assets/final/shaders/math/noise.wgsl (new, 4.2KB, 150 lines) - assets/final/demo_assets.txt (added SHADER_MATH_NOISE) - assets/final/test_assets_list.txt (added SHADER_MATH_NOISE) - src/gpu/effects/shaders.cc (registered snippet) - src/tests/test_noise_functions.cc (new test) - CMakeLists.txt (added test target) Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
20 hoursfeat(gpu): Add parameter-driven GaussianBlurEffectskal
Extends shader parametrization system to GaussianBlurEffect with strength parameter (Task #73 continued). Changes: - Added GaussianBlurParams struct (strength, default: 2.0f) - Added GaussianBlurUniforms with proper WGSL alignment (32 bytes) - Updated shader to use parameterized strength instead of hardcoded 2.0 - Extended seq_compiler to parse strength parameter - Updated demo.seq with 2 parameterized instances: * Line 38: strength=3.0 (stronger blur for particles) * Line 48: strength=1.5 (subtle blur) Technical details: - Backward-compatible default constructor maintained - Migrated from raw buffer to UniformBuffer<GaussianBlurUniforms> - Shader replaces 'let base_size = 2.0' with 'uniforms.strength' - Generated code creates GaussianBlurParams initialization Testing: - All 32/32 tests pass - Demo runs without errors - Generated code verified correct Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
20 hoursfeat(gpu): Add parameter-driven ChromaAberrationEffectskal
Implements Task #73 - Extends shader parametrization system to ChromaAberrationEffect following the FlashEffect pattern. Changes: - Added ChromaAberrationParams struct (offset_scale, angle) - Added ChromaUniforms with proper WGSL alignment (32 bytes) - Updated shader to compute offset direction from angle parameter - Extended seq_compiler to parse offset/angle parameters - Updated demo.seq with 2 parameterized instances: * Line 50: offset=0.03 angle=0.785 (45° diagonal, stronger) * Line 76: offset=0.01 angle=1.57 (90° vertical, subtle) Technical details: - Backward-compatible default constructor maintained - Migrated from raw buffer to UniformBuffer<ChromaUniforms> - Shader computes direction: vec2(cos(angle), sin(angle)) - Generated code creates ChromaAberrationParams initialization Testing: - All 32/32 tests pass - Demo runs without errors - Binary size: 5.6M stripped (~200-300 bytes impact) Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
20 hoursrefactor(shaders): Use bump mapping utility function in renderer_3dskal
- Added #include "math/sdf_utils" to renderer_3d.wgsl - Replaced 35 lines of inline bump mapping code with call to get_normal_bump() - Improves code reusability and maintainability - Same functionality with cleaner implementation
20 hoursfeat(shaders): Add bump-mapped normal calculation variantsskal
Adds two new functions for displacement-mapped normal calculation: Functions added: - get_normal_bump(): High-quality 6-sample central differences - get_normal_bump_fast(): Optimized 4-sample tetrahedron pattern Performance comparison: - get_normal_bump: 6 SDF + 6 texture + 6 UV = 18 operations - get_normal_bump_fast: 4 SDF + 4 texture + 4 UV = 12 operations - Speed improvement: 33% faster with tetrahedron method Parameters: - p: Sample position (vec3) - obj_params: Object parameters (vec4) - noise_tex: Displacement texture (texture_2d) - noise_sampler: Texture sampler - disp_strength: Displacement strength multiplier Requirements: - spherical_uv() function must be available in calling context - get_dist() function must be available in calling context Use cases: - get_normal_bump: Static scenes, high-quality renders - get_normal_bump_fast: Real-time rendering, performance-critical paths Location: assets/final/shaders/math/sdf_utils.wgsl
20 hoursfeat(shaders): Add optimized 4-sample SDF normal estimationskal
Adds get_normal_fast() variant using tetrahedral gradient approximation. Performance improvement: - 4 SDF evaluations (vs 6 in get_normal_basic) - ~33% fewer distance field samples - Tetrahedron pattern: k.xyy, k.yyx, k.yxy, k.xxx where k=(1,-1) Trade-off: - Slightly less accurate than central differences method - Good for real-time rendering where performance matters - Same sphere optimization (analytical normal for obj_type == 1.0) Parameters: - epsilon: 0.0001 (vs 0.001 in basic method) - Same interface: takes position and object params Use case: Fast lighting calculations, performance-critical shaders
21 hoursfeat(shaders): Add Möller-Trumbore ray-triangle intersectionskal
Implements ray-triangle intersection algorithm for future mesh raytracing support. Changes: - Add ray_triangle.wgsl with TriangleHit struct and intersection function - Register shader snippet in asset system (SHADER_RAY_TRIANGLE) - Add shader composer registration for #include "ray_triangle" support Returns: - hit.uv: Barycentric coordinates (for texture mapping) - hit.z: Parametric distance along ray - hit.N: Triangle face normal - hit.hit: Boolean indicating intersection Task: Progress on SDF for mesh (related to Task #18) Algorithm: Fast, Minimum Storage Ray-Triangle Intersection (Möller-Trumbore) Size: ~30 lines WGSL, negligible binary impact
22 hoursrefactor(shaders): Apply common utilities to renderer shadersskal
Updated renderer_3d.wgsl, mesh_render.wgsl, skybox.wgsl to use common_utils functions. Registered snippet in ShaderComposer. Updated demo_assets.txt with SHADER_MATH_COMMON_UTILS entry. Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
22 hoursfeat(shaders): Extract common WGSL utilities for better composabilityskal
Created math/common_utils.wgsl with reusable shader functions: - transform_normal() - Normal matrix transform (2 call sites) - spherical_uv() - Spherical UV mapping (7 call sites) - spherical_uv_from_dir() - For direction vectors (1 call site) - grid_pattern() - Procedural checkerboard (2 call sites) - Constants: PI, TAU Refactored shaders: - renderer_3d.wgsl: 7 spherical_uv + 1 normal + 2 grid (~12 lines removed) - mesh_render.wgsl: 1 normal transform (~3 lines removed) - skybox.wgsl: 1 spherical UV (~2 lines removed) Impact: ~200 bytes saved, 12 call sites deduplicated Tests: 31/31 passing Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
30 hoursfeat(3d): Fix ObjectType::PLANE scaling and consolidate ObjectType mappingskal
- Implemented correct scaling for planes in both CPU (physics) and GPU (shaders) using the normal-axis scale factor. - Consolidated ObjectType to type_id mapping in Renderer3D to ensure consistency and support for CUBE. - Fixed overestimation of distance for non-uniformly scaled ground planes, which caused missing shadows. - Updated documentation and marked Task A.2 as completed.
3 daysfeat(particles): Implement transparent circular particles with alpha ↵skal
blending (Task #53) ## Visual Improvements - Particles now render as smooth fading circles instead of squares - Added UV coordinates to vertex shader output - Fragment shader applies circular falloff (smoothstep 1.0 to 0.5) - Lifetime-based fade: alpha multiplied by particle.pos.w (1.0 → 0.0) ## Pipeline Changes - Enabled alpha blending for particle shaders (auto-detected via strstr) - Blend mode: SrcAlpha + OneMinusSrcAlpha (standard alpha blending) - Alpha channel: One + OneMinusSrcAlpha for proper compositing ## Demo Integration - Added 5 ParticleSprayEffect instances at key moments (6b, 12b, 17b, 24b, 56b) - Increased particle presence throughout demo - Particles now more visually impactful with transparency ## Files Modified - assets/final/shaders/particle_render.wgsl: Circular fade logic - src/gpu/gpu.cc: Auto-enable blending for particle shaders - assets/demo.seq: Added ParticleSprayEffect at multiple sequences ## Testing - All 23 tests pass (100%) - Verified with demo64k visual inspection
3 daysfix(shaders): Resolve WGSL validation errors and add shader compilation testsskal
Fixed three critical WGSL shader issues causing demo64k and test_3d_render to crash: 1. **renderer_3d.wgsl**: Removed dead code using non-existent `inverse()` function - WGSL doesn't have `inverse()` for matrices - Dead code was unreachable but still validated by shader compiler - Also removed reference to undefined `in.normal` vertex input 2. **sdf_utils.wgsl & lighting.wgsl**: Fixed `get_normal_basic()` signature mismatch - Changed parameter from `obj_type: f32` to `obj_params: vec4<f32>` - Now correctly matches `get_dist()` function signature 3. **scene_query_linear.wgsl**: Fixed incorrect BVH binding declaration - Linear mode was incorrectly declaring binding 2 (BVH buffer) - Replaced BVH traversal with simple linear object loop - Root cause: Both BVH and Linear shaders were identical (copy-paste error) Added comprehensive shader compilation test (test_shader_compilation.cc): - Tests all production shaders compile successfully through WebGPU - Validates both BVH and Linear composition modes - Catches WGSL syntax errors, binding mismatches, and type errors - Would have caught all three bugs fixed in this commit Why tests didn't catch this: - Existing test_shader_assets only checked for keywords, not compilation - No test actually created WebGPU shader modules from composed code - New test fills this gap with real GPU validation Results: - demo64k runs without WebGPU errors - test_3d_render no longer crashes - All 22/23 tests pass (FftTest unrelated issue from FFT Phase 1) Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
3 daysRevert "fix(shaders): Correct plane distance scaling for non-uniform transforms"skal
This reverts commit a5229022b0e500ac86560e585081f45293e587d2.
3 daysfix(shaders): Correct plane distance scaling for non-uniform transformsskal
When a plane has non-uniform scaling (e.g., floor with scale 20,0.01,20), transforming points to local space distorts SDF distances. For a horizontal plane with Y-scale of 0.01, distances become 100x too large in local space. Fix: Multiply plane distances by the scale factor along the normal direction (Y component for horizontal planes). This corrects shadow calculations while maintaining the large floor area needed for visualization. Reverted incorrect uniform scale fix (c23f3b9) that made floor too small.
3 daysfix(shaders): Exclude meshes from SDF scaling factor in shadow calculationsskal
Fixed incorrect mesh shadow rendering caused by applying scale factor to mesh AABBs which already have correct local-space extents. ROOT CAUSE: The 's' scale factor (line 44) is meant for UNIT primitives (sphere, box, torus) that are scaled by the model matrix. Meshes (type 5.0) already store their correct AABB extents in obj_params.yzw, so applying 's' caused incorrect shadow sizes. ISSUE: let s = min(length(obj.model[0].xyz), ...); if (obj.params.x != 4.0) { // Excluded planes only d = min(d, get_dist(q, obj.params) * s); // ❌ WRONG for meshes! } FIX: if (obj.params.x != 4.0 && obj.params.x != 5.0) { // Exclude planes AND meshes d = min(d, get_dist(q, obj.params) * s); } else { d = min(d, get_dist(q, obj.params)); // No scaling } EXPLANATION: - Type 1.0 (Sphere): Unit sphere, scaled by 's' ✓ - Type 2.0 (Box): Unit box, scaled by 's' ✓ - Type 3.0 (Torus): Unit torus, scaled by 's' ✓ - Type 4.0 (Plane): Special case, no scaling ✓ - Type 5.0 (Mesh): AABB already has correct size, no scaling needed ✓ FILES FIXED: - assets/final/shaders/render/scene_query_linear.wgsl - assets/final/shaders/render/scene_query_bvh.wgsl PARTIAL FIX: This fixes mesh shadow sizing issues. Shadow rotation limitation remains (AABBs are axis-aligned, don't rotate with mesh - this is a fundamental AABB limitation, not a bug). handoff(Claude): Mesh shadows now correctly sized. Investigating floor shadow stretching issue next (likely related to plane scaling).
3 daysfix(shaders): Correct mesh normal transformation - remove double transposeskal
Fixed critical bug in normal matrix transformation causing mesh stretching and incorrect scaling during rotation. ROOT CAUSE: In WGSL, mat3x3(v0, v1, v2) creates a matrix where v0, v1, v2 are COLUMNS. When extracting rows from inv_model, the constructor already produces the transpose. Applying transpose() again cancels out, giving incorrect normals. ISSUE: let normal_matrix = mat3x3(inv_model[0].xyz, inv_model[1].xyz, inv_model[2].xyz); // This gives transpose(inv_model) already! out.normal = normalize(transpose(normal_matrix) * in.normal); // Double transpose = identity, wrong result FIX: let normal_matrix = mat3x3(inv_model[0].xyz, inv_model[1].xyz, inv_model[2].xyz); // Already transpose(inv_model), which is the correct normal matrix out.normal = normalize(normal_matrix * in.normal); // Correct transformation FILES FIXED: - assets/final/shaders/mesh_render.wgsl:38 (mesh vertex normals) - assets/final/shaders/renderer_3d.wgsl:185 (SDF bump-mapped normals) RESULT: Mesh normals now transform correctly under rotation and non-uniform scaling. Fixes Task A (test_mesh visualization stretching bug). handoff(Claude): Normal transformation bug fixed. Mesh should now render correctly without stretching. Shadow bug on floor plane still remains (separate WGSL shader issue for later investigation).
3 daysfix: Correct mesh normal transformation and floor shadow renderingskal
3 daysfeat(3d): Implement basic OBJ mesh asset pipelineskal
Added support for loading and rendering OBJ meshes. - Updated asset_packer to parse .obj files into a binary format. - Added MeshAsset and GetMeshAsset helper to asset_manager. - Extended Object3D with mesh_asset_id and ObjectType::MESH. - Implemented mesh rasterization pipeline in Renderer3D. - Added a sample cube mesh and verified in test_3d_render.
3 dayschore: Update documentation, generated assets, and cleanupskal
Removed obsolete scene_query.wgsl (replaced by variants). Updated TODO.md. Committed generated asset files reflecting new shader snippets.
3 daysrefactor(gpu): Implement compile-time BVH toggle via shader compositionskal
Completed Task #18-B optimization and refactoring. - Replaced runtime branching in shader with compile-time snippet substitution in ShaderComposer. - Added 'scene_query_bvh.wgsl' and 'scene_query_linear.wgsl' as distinct snippets. - Refactored Renderer3D to manage two separate pipelines (with and without BVH). - Updated ShaderComposer to support snippet substitution during composition. - Verified both paths with test_3d_render (default and --no-bvh). - Removed temporary shader hacks and cleaned up renderer_3d.wgsl.
3 daysfeat(perf): Add toggle for GPU BVH and fix fallbackskal
Completed Task #18-B. - Implemented GPU-side BVH traversal for scene queries, improving performance. - Added a --no-bvh command-line flag to disable the feature for debugging and performance comparison. - Fixed a shader compilation issue where the non-BVH fallback path failed to render objects.
5 daysfeat: Optional sequence end times and comprehensive effect documentationskal
This milestone implements several key enhancements to the sequencing system and developer documentation: ## Optional Sequence End Times (New Feature) - Added support for explicit sequence termination via [time] syntax - Example: SEQUENCE 0 0 [30.0] forcefully ends all effects at 30 seconds - Updated seq_compiler.cc to parse optional [time] parameter with brackets - Added end_time_ field to Sequence class (default -1.0 = no explicit end) - Modified update_active_list() to check sequence end time and deactivate all effects when reached - Fully backward compatible - existing sequences work unchanged ## Comprehensive Effect Documentation (demo.seq) - Documented all effect constructor parameters (standard: device, queue, format) - Added runtime parameter documentation (time, beat, intensity, aspect_ratio) - Created detailed effect catalog with specific behaviors: * Scene effects: HeptagonEffect, ParticlesEffect, Hybrid3DEffect, FlashCubeEffect * Post-process effects: GaussianBlurEffect, SolarizeEffect, ChromaAberrationEffect, ThemeModulationEffect, FadeEffect, FlashEffect - Added examples section showing common usage patterns - Documented exact parameter behaviors (e.g., blur pulsates 0.5x-2.5x, flash triggers at intensity > 0.7, theme cycles every 8 seconds) ## Code Quality & Verification - Audited all hardcoded 1280x720 dimensions throughout codebase - Verified all shaders use uniforms.resolution and uniforms.aspect_ratio - Confirmed Effect::resize() properly updates width_/height_ members - No issues found - dimension handling is fully dynamic and robust ## Files Changed - tools/seq_compiler.cc: Parse [end_time], generate set_end_time() calls - src/gpu/effect.h: Added end_time_, set_end_time(), get_end_time() - src/gpu/effect.cc: Check sequence end time in update_active_list() - assets/demo.seq: Comprehensive syntax and effect documentation - Generated files updated (timeline.cc, assets_data.cc, music_data.cc) This work establishes a more flexible sequencing system and provides developers with clear documentation for authoring demo timelines. handoff(Claude): Optional sequence end times implemented, effect documentation complete, dimension handling verified. Ready for next phase of development.
5 daysfeat(gpu): Implement recursive WGSL composition and modularize shaders (Task ↵skal
#50) - Updated ShaderComposer to support recursive #include "snippet_name" with cycle detection. - Extracted granular WGSL snippets: math/sdf_shapes, math/sdf_utils, render/shadows, render/scene_query, render/lighting_utils. - Refactored Renderer3D to use #include in shaders, simplifying C++ dependency lists. - Fixed WGPUShaderSourceWGSL usage on macOS to correctly handle composed shader strings. - Added comprehensive unit tests for recursive composition in test_shader_composer. - Verified system stability with test_3d_render and full test suite. - Marked Task #50 as recurrent for future code hygiene.
5 dayshandoff(Claude): Stabilize 3D renderer with rotating skybox and two-pass ↵skal
architecture - Fixed black screen by ensuring clear operations in Pass 2 when Skybox pass is skipped. - Resolved WebGPU validation errors by synchronizing depth-stencil state. - Implemented rotating skybox using world-space ray unprojection (inv_view_proj). - Improved procedural noise generation (multi-octave Value Noise). - Restored scene integrity by correcting object indexing and removing artifacts. - Updated documentation (TODO.md, PROJECT_CONTEXT.md).
6 daysfix: Implement proper skybox rendering with Perlin noiseskal
- Added ObjectType::SKYBOX for dedicated skybox rendering. - Created assets/final/shaders/skybox.wgsl for background rendering. - Implemented a two-pass rendering strategy in Renderer3D::render: - First pass renders the skybox without depth writes. - Second pass renders scene objects with depth testing. - Corrected GlobalUniforms struct in common_uniforms.wgsl and src/3d/renderer.h to include and explicit padding for 112-byte alignment. - Updated Renderer3D::update_uniforms to set the new and zero-initialize padding. - Reverted sky sampling logic in renderer_3d.wgsl to for SDF misses, preventing background bleed-through. - Updated test_3d_render.cc to include a SKYBOX object with Perlin noise. handoff(Gemini): The skybox is now correctly rendered with Perlin noise as a dedicated background pass. Objects render correctly without transparency to the sky. All necessary C++ and WGSL shader changes are implemented and verified.
6 daysfeat: side-quest - Perlin noise sky and ProcGenFunc error handlingskal
- Updated ProcGenFunc signature to return bool for error reporting. - Implemented gen_perlin (Fractional Brownian Motion) in procedural/generator.cc. - Added support for sky texture in Renderer3D and its shader. - Integrated Perlin noise sky texture in test_3d_render.cc. - Caught and handled memory/generation errors in AssetManager and TextureManager. - Assigned reference numbers to all remaining tasks in documentation. handoff(Gemini): Side-quest complete. ProcGenFunc now returns bool. Perlin noise added and used for sky in 3D test. Windows build remains stable. All tasks numbered.
6 daystest(shader): Add ShaderComposer and WGSL asset validation tests (Task #26)skal
Implemented comprehensive unit tests for ShaderComposer and a validation test for production WGSL shader assets. This ensures the shader asset pipeline is robust and that all shaders contain required entry points and snippets. Also improved InitShaderComposer to be more robust during testing.
6 daysrefactor: Shader Asset Integration (Task #24)skal
Extracted all hardcoded WGSL shaders into external assets. Updated AssetManager to handle shader snippets. Refactored Renderer3D, VisualDebug, and Effects to load shaders via the AssetManager, enabling better shader management and composition.