Procedural Generation in Practice: A Real-Time Underwater Scene in a 96KB Web Page
This article examines a case study of a real-time underwater scene rendered entirely in the browser within roughly 96KB, with no downloaded 3D models or textures. It explains how procedural techniques replace asset files with mathematical rules, covering noise functions and fBm, mesh generation versus ray marching with signed distance functions, underwater light absorption and caustics approximation, browser and GPU compatibility concerns, performance and frame-budget interpretation, quality tiers and optimization strategies, size management and delivery, and practical limits with a pre-launch checklist.
Background: Why Compress an Entire Scene into 96KB
According to public reports, a front-end developer built a web-based underwater demo roughly 96KB in size. Every frame is computed in real time in the browser, with no 3D models or images downloaded. The author used AI-assisted code generation, with a prompt of only about 40 lines.
The value of this case lies not in the size number itself, but in the different way of organizing resources it demonstrates compared with traditional web 3D development. Traditional approaches depend on art assets: model files record vertices and faces, textures record the color of every pixel, and together they easily reach tens or hundreds of megabytes. Procedural approaches replace assets with computation rules. The shape and appearance of the scene are described by formulas, so only the formulas themselves need to be stored, and the data volume drops to an extremely low level.
This approach suits content with strong regularity that can be described mathematically, such as seabed terrain, water waves, light attenuation, bubbles, and floating particles. It does not suit scenes that require precise reproduction of real objects, such as a product model with brand markings. When choosing an approach, first judge whether the content can be expressed stably by formulas.
Core Principle: Replacing Asset Files with Functions
Procedural generation relies on a basic fact: the same set of inputs through a deterministic function always produces the same set of outputs. As long as coordinates, time, and random seeds are fixed, results are reproducible.
The most commonly used tool is the noise function. It takes a coordinate as input and outputs a value that varies continuously within a controllable range. Outputs at adjacent coordinates are similar, so the resulting terrain and textures look natural without obvious jumps. Stacking multiple layers of noise produces fractal Brownian motion (fBm), where each layer doubles in frequency and halves in amplitude, preserving both large-scale undulation and small-scale detail.
Below is a minimal implementation based on value noise, used only to illustrate the idea:
// Pseudorandom hash: the same coordinate always yields the same resultfunction hash(x, y) {const s = Math.sin(x * 127.1 + y * 311.7) * 43758.5453;return s - Math.floor(s);}// Smooth interpolation between integer grid pointsfunction valueNoise(x, y) {const xi = Math.floor(x), yi = Math.floor(y);const xf = x - xi, yf = y - yi;const u = xf * xf * (3 - 2 * xf);const v = yf * yf * (3 - 2 * yf);const a = hash(xi, yi), b = hash(xi + 1, yi);const c = hash(xi, yi + 1), d = hash(xi + 1, yi + 1);return a + (b - a) * u + (c - a) * v + (a - b - c + d) * u * v;}// Fractal stacking: returns a value roughly in [0, 1]function fbm(x, y, octaves = 5) {let sum = 0, amp = 0.5, freq = 1, norm = 0;for (let i = 0; i < octaves; i++) {sum += amp * valueNoise(x * freq, y * freq);norm += amp;amp *= 0.5;freq *= 2;}return sum / norm;}
The octaves parameter directly affects computational cost and the level of detail. Adding one layer roughly doubles the computation, making it the most direct knob between image quality and performance.
Building the 3D Space
Procedural 3D scenes generally follow one of two routes.
The first is mesh generation. The CPU or GPU generates vertices from a height function and hands them to the graphics pipeline. This approach has good compatibility and intuitive debugging, but vertex counts expand rapidly as detail increases.
The second is ray marching. The GPU casts a ray per pixel, advances it step by step, and uses a signed distance function (SDF) to determine whether the current position has entered an object. Scene data exists only in shader code and requires no vertex buffers. It is small in size and flexible in geometric expression, at the cost of multiple distance computations per pixel, which places high demands on GPU compute.
For the goal of size compression, ray marching has the advantage. The schematic code below describes an undulating seabed and a slowly swaying water surface:
// Seabed height: determined by fractal noisefloat seabed(vec2 p) {return fbm(p * 0.05) * 12.0 - 8.0;}// Signed distance: approximate distance from point p to the nearest surfacefloat sceneSDF(vec3 p, float t) {float floorDist = p.y - seabed(p.xz);float waveDist = p.y - (sin(p.x * 0.8 + t) * 0.3);return min(floorDist, -waveDist);}
The distance function here is not exact, but as long as it never overestimates the distance, ray marching converges stably. This is the fundamental constraint of distance field methods, and code should preserve this premise.
Lighting and Water Color
The visual credibility of an underwater scene comes mainly from the attenuation of light in water. Water absorbs red light most strongly and blue light most weakly, so deeper areas appear bluer. Physically, this phenomenon is described by the Beer-Lambert law: transmittance falls exponentially with depth, and different color channels have different attenuation coefficients.
// Schematic parameters; actual values need tuning for visual effectconst ABSORPTION = { r: 0.45, g: 0.12, b: 0.06 };function waterTint(depth) {return {r: Math.exp(-ABSORPTION.r * depth),g: Math.exp(-ABSORPTION.g * depth),b: Math.exp(-ABSORPTION.b * depth),};}
Caustic light patterns are another key visual element of underwater imagery. They can be approximated by the gradient of the water surface height or by superimposing multiple sine waves, without real ray tracing. The approximation sacrifices physical accuracy but preserves visual credibility at low cost.
Runtime Environment and Compatibility
Procedural approaches have requirements for browser graphics capability. To run shaders on the GPU, the browser needs to support modern web graphics interfaces. Support currently varies among mainstream browsers, and behavior may also differ across devices, driver versions, and operating systems.
Engineering practice should cover three things:
- Detect interface availability at startup, and give a clear message or switch to a static image when unavailable.
- Catch shader compilation failures to avoid a blank page caused by a single syntax error.
- Test on different graphics card types, especially integrated GPUs. Heavy fragment shader computation easily becomes a bottleneck on integrated graphics.
Floating-point precision also needs attention. Some mobile GPUs use lower-precision floating-point formats, and long-distance coordinate computations may show jitter or banding. A common practice is to translate coordinates relative to the camera, keeping only relative positions.
Interpreting Performance Numbers
According to reports, one tester reached 60 frames per second on an integrated GPU at 720p resolution with the lowest quality settings, while the author’s figures reach 180 frames per second at higher settings. These numbers are self-reported or from individual tests, with no unified test environment, and should be cited cautiously.
A frame budget helps explain the gap between the two numbers. At 720p there are 1280×720, or 921,600 pixels. 60 frames per second means about 16.7 ms per frame, while 180 frames per second leaves only about 5.6 ms. The more complex the per-pixel shader, the longer the execution time. Quality settings often change resolution, iteration counts, shadows, and post-processing together, so frame rate differences come mainly from combinations of these parameters rather than a single factor.
Quality Tiers and Optimization Strategies
Real projects should design quality settings as explicit tiers and record what each tier changes. Below is a common tiering approach:
| Tier | Render resolution | Ray march limit | Noise layers | Caustics |
|---|---|---|---|---|
| Low | Render at 0.5× screen, then upscale | Fewer | 3 layers | Off |
| Medium | 0.75× native screen | Medium | 4 layers | Simplified |
| High | Native screen resolution | More | 5 to 6 layers | Full |
Several general optimization principles also apply:
- Control detail with distance field step size. Distant objects can use larger steps to reduce iteration counts.
- Move pixel-independent computation to the CPU and pass only a few uniforms per frame.
- Compute noise hash constants and frequencies at initialization instead of recomputing every frame.
- Monitor frame time, automatically drop one tier when the budget is exceeded for several consecutive seconds, and keep a manual selection entry.
Size Management and Delivery
A 96KB target requires strict control over delivered content. HTML, CSS, and JavaScript are all inlined into a single file to avoid extra network requests. Shader source is stored as strings, and comments and excess whitespace can be removed during compression. With compression enabled on the server, the actual transfer size is usually reduced significantly further.
Size budget also needs to balance with maintainability. Over-compressed code is hard to modify, and later tuning becomes difficult. It is advisable to keep a readable source and generate the compressed artifact at build time.
Applicable Boundaries and Checklist
Procedural generation suits the following scenarios: demos and artistic creation, lightweight interactive displays, bandwidth-sensitive pages, and content that needs to load quickly on many devices. It does not suit projects that require precise reproduction of real assets, large numbers of dynamic interactive objects, or strict physical simulation.
Before launch, confirm each item:
- Is there a fallback when the interface is unavailable.
- Has every quality tier been tested for frame rate on target devices.
- Do shaders compile in different browsers.
- Is there precision jitter at long-distance coordinates.
- Do scenes with large motion provide an option to reduce motion effects.
- Is the delivered size within budget, with pre- and post-compression sizes recorded.
AI-generated code requires human review. Automatically generated shaders may contain unhandled edge cases, such as division by zero, square roots of negative numbers, or unbounded iteration counts. Incorporating these risks into the test process is what allows procedural approaches to be used reliably in real projects.
