Building a WebGL Rainy-Night Convenience Store Scene with an AI Coding Assistant
This article explains why a rainy-night convenience store is an ideal first WebGL practice scene and how to build it effectively with an AI coding assistant. It covers turning vague visual intent into measurable constraints, structuring the work into iterative rounds, and implementing the core rendering techniques: GPU-driven rain, low-cost wet-ground reflections, emissive signage with bloom, and fog for atmospheric depth. It also includes a performance-engineering checklist, a troubleshooting order for common failures, and the final steps to move from a local demo to a shareable deliverable.
Building a WebGL Rainy-Night Convenience Store Scene with an AI Coding Assistant
1. Why a “Rainy-Night Convenience Store” Is an Ideal 3D Practice Scene
When you build an interactive WebGL scene in the browser, the hardest part isn’t “can’t draw it”—it’s “drew it, but it’s wrong.” A rainy-night convenience store works well as a first assignment for three reasons:
- The element set is bounded. It really only contains three categories of objects: a single building (with display window, door, and signage), a patch of street with a few pieces of street furniture, and a layer of barely-volumetric “rain.” The object count is manageable, yet it covers five core areas: modeling, materials, lighting, particles, and post-processing.
- The challenges are concentrated and measurable. Reflections on a wet road, the halo around a glowing sign, the depth layering of the rain streaks, silhouettes dissolving into distant fog—each maps to a concrete rendering metric (reflection resolution, bloom threshold, particle count, fog density). That makes it ideal for a closed loop of “set a target → generate an implementation → measure and verify.”
- The performance risks are explicit. Large-area transparency overdraw, multiple light sources, and full-screen post-processing are all direct killers of frame time. Whether a rainy-night scene runs smoothly can be attributed almost linearly to a few specific switches, which makes it great for building performance awareness.
Put another way, the value of this kind of scene isn’t how dazzling it looks—it’s that it compresses “artistic intent” and “engineering constraints” into one small project.
2. First, Translate “Feel” into Verifiable Technical Metrics
When working with AI coding tools, the most common source of inefficiency is too many adjectives and too few metrics. Descriptions like “make the mood a bit colder” or “make the rain denser” force the model to guess along multiple dimensions at once, so even when it gets it right, it’s luck. A more effective approach is to build a constraint table first:
| Dimension | What to define | Example constraint |
|---|---|---|
| Units & scale | Mapping between scene units and real dimensions | 1 scene unit = 1 meter; sign bottom edge 2.6 m above ground; rolling shutter 3.4 m wide |
| Camera | FOV, position, whether it can roam | ~35mm-equivalent FOV, 6 m across the street, allows small lateral panning |
| Composition | Subject’s share of the frame | Building silhouette occupies 60%~70% of frame width; sky no more than 15% |
| Light ratio | Brightness difference between subject and environment | Store-window interior ~4~6x brighter than the environment; sign is the brightest source |
| Performance budget | Target devices and frame time | Desktop within 16 ms; mobile within 32 ms, with particle count reduced to 40% |
The table does more than “explain things clearly”—it gives every subsequent conversation an acceptance criterion. After this, whether you’re changing the rain, the lights, or the fog, you can answer the same question: is it still within budget, and does it still respect the composition constraints?
Illustrative renderer setup (stylized pseudo-code, showing the dependencies between config options):
// Note: the snippet below is illustrative; exact API names depend on the rendering library you useconst renderer = createRenderer({ canvas, antialias: !isMobile });// 1) Output and color: avoid a "washed-out gray" or "blown-out white" lookrenderer.outputColorSpace = SRGB; // convert output to sRGBrenderer.toneMapping = ACESFilmic; // tone mapping to compress highlightsrenderer.toneMappingExposure = 1.1;// 2) Clamp the pixel ratio: values above 2 on mobile almost always drop framesrenderer.setPixelRatio(Math.min(devicePixelRatio, isMobile ? 1.5 : 2));// 3) Depth precision: night scenes span a wide near/far range, so avoid z-fightingcamera.near = 0.1;camera.far = 120;
Here’s a common beginner trap: light intensity has different units under different lighting models (whether “physically correct lighting” is enabled changes the order of magnitude of intensities). If a generated scene “won’t get bright no matter what you do,” first confirm the lighting mode and intensity units, rather than blindly multiplying intensity by 10.
3. Treat the AI Coding Assistant as a High-Frequency Pair Programmer, Not a One-Shot Generator
Expecting a finished result in one pass is unrealistic, especially for visual detail. A more reliable rhythm is to split the work into five rounds, each solving only one class of problem, and to confirm after each round that it runs and can be rolled back:
- Skeleton round: produce a runnable project structure (HTML entry + ES Module split + a local static server), with just an empty scene and camera orbit controls. Acceptance: it opens, it rotates, and the console is error-free.
- Geometry round: block out the building mass, the street surface, the curb, and a few props. Acceptance: proportions match the table above, aligned against a reference dimension (for example, repeatedly comparing against door height).
- Materials & lighting round: distinguish dry concrete, wet asphalt, glass, and a metal rolling shutter; add emissive signage. Acceptance: the night-time light ratio matches expectations, with no large areas of dead black.
- Atmosphere round: rain curtain, ground reflections, bloom, fog. Acceptance: frame time is within budget, and the layers of rain and fog are distinguishable.
- Optimization & fallback round: merge draw calls, downsample, and tier by device capability. Acceptance: mobile reaches 30 fps with no obvious quality collapse.
Four prompt techniques that pay off in practice:
- Demand minimal changes. Give an explicit instruction: “only modify the specified files, output diff snippets, and explain the reason for each change,” so unrelated logic doesn’t get overwritten by a full-file rewrite.
- Make the tool justify itself. Ask it to list the coordinates, parameters, and assumptions involved in the change, and to flag anything it’s unsure about. This significantly reduces made-up-API errors.
- Shard the context. When a file exceeds a few hundred lines, provide interface signatures per module (for example, the inputs and outputs of
createRainField(options)) instead of pasting whole blocks. - Keep rollback points. Commit a version at the end of each round, so a regression only needs one round of rollback instead of re-explaining from scratch.
4. Implementing Rain: Take the CPU Out of the Per-Frame Loop
Rain is the part most easily written badly. The naive approach updates the positions of thousands of particles each frame and writes them into a buffer, straining both the CPU and bandwidth. The right direction is to hand the motion entirely to the vertex shader: the CPU writes static attributes only at initialization (base position, random phase, fall speed, length).
For “instanced thin-quad rain streaks,” the vertex shader logic looks like this (GLSL, directly referenceable):
// attributes: iOffset (seed position), iSpeed (fall speed), iLen (rain streak length)uniform float uTime;uniform vec3 uVolume; // rain volume bounding box, e.g. (24, 14, 24)uniform vec3 uWind; // wind direction and slantvoid main() {float fall = mod(iOffset.y - uTime * iSpeed, uVolume.y);vec3 base = vec3(iOffset.x, fall, iOffset.z) + uWind * (uVolume.y - fall) * 0.02;// orient each streak along the velocity direction to keep it visually consistentvec3 dir = normalize(vec3(uWind.x * 0.02, -1.0, uWind.z * 0.02));vec3 pos = base + dir * position.y * iLen;gl_Position = projectionMatrix * modelViewMatrix * vec4(pos, 1.0);vFade = smoothstep(0.0, 2.0, fall) * smoothstep(0.0, 3.0, uVolume.y - fall);}
Three key points:
- Use modulo for an infinite loop. Particles wrap around automatically once they leave the volume, with no CPU involvement.
- Layer by distance. Use thin streaks in the foreground (with a clear direction), short line segments in the mid-ground, and a slowly scrolling noise plane in the background to express the “rain curtain.” The distant layer usually saves more particles than you’d think.
- Transparency and depth. The rain material should disable depth write, enable depth test, and tolerate some sorting error; keep the rain opacity low (typically 0.15~0.35) so it reads through “density” rather than “opacity.”
5. Wet Ground: Trading Controllable Cost for the Look of Reflections
The key to realism isn’t actually the rain—it’s the ground the rain has soaked. Screen-space reflections (SSR) have a high ceiling but come at a high cost and are prone to edge artifacts; a more pragmatic combination is:
- Planar mirror reflection. Render the scene a second time at low resolution for the ground (0.5x horizontal, 0.25x vertical is enough), and apply slight blur and vertical stretch when sampling. Night scenes are extremely forgiving of blur, and viewers perceive the result as “crinkled by rainwater.”
- Rough material + environment map. Wet asphalt isn’t a mirror—it’s a dark, low-roughness material. Use a simple night environment map (procedurally generated gradient blocks work) to provide a base reflection tint.
- Puddle mask. Procedurally generate a noise mask to control “where it’s wetter.” Within the mask, reflectivity and roughness vary together, with smooth transitions at the edges to avoid hard seams.
- Streak highlights. Sample the reflection with a slight vertical stretch along the view direction. This is one of the most recognizable details of wet ground, at almost zero cost.
Pseudo-code illustration:
// Reflection pass: half resolution + cull expensive objectsreflectRT = createRenderTarget(w * 0.5, h * 0.25);renderScene(cameraReflected, { target: reflectRT, hide: [rainField, glassPane] });// Ground material: one mask drives both reflectivity and roughnessgroundMat.roughnessMap = puddleMask;groundMat.reflectStrength = 0.55; // approaches 0 in dry areas, 1 in wet areas
6. Glowing Signs and Bloom: The Visual Anchor of a Night Scene
A night scene must have a clear “brightest point,” or the eye has nowhere to land. The recommended approach is two steps:
- Self-illumination, not added lights. Use emissive materials for the sign, light box, and refrigerator case, paired with a texture drawn dynamically on a Canvas to carry text and graphics. Compared to modeling the strokes, a texture saves polygons and lets you change the wording anytime.
- Threshold bloom. In the post-processing chain, use the classic combination of “luminance threshold + multi-level blur + composite,” with the threshold set to a level that only bright regions trigger (for example, 0.75~0.85) and kept restrained in intensity. Too much bloom makes the whole image look washed-out gray, which is the most common source of the “plastic feel” in rainy-night scenes.
Keep the post-processing chain to 3~4 passes (bloom, tone mapping/output conversion, and optional vignette and slight chromatic aberration). Every added full-screen pass requires re-measuring frame time.
7. Fog and Aerial Perspective: A Technique That Improves Both Quality and Performance
Exponential-squared fog (exp2) is almost mandatory in night scenes: it lets distant objects gradually blend into the background color, which visually “permits” distant areas to lack detail. That means you can safely keep distant geometry coarse and cut distant particles, and the image still looks complete. Don’t pick pure black for the fog color—it should sit near the mid-tone between sky and environment (slightly blue-teal); otherwise distant areas become a dead-black mass and all sense of depth is lost.
8. Performance-Engineering Checklist
The frame time of a rainy-night scene can be attributed item by item. Troubleshoot and optimize in roughly this order:
- Draw batches. Merge static geometry by material, and convert repeated objects (raindrops, bollards, shelving, floor tiles) to instancing. Aim to get draw calls down to double digits.
- Overdraw. Large-area semi-transparency (rain, fog planes, glass, halos) is an invisible killer. Reducing the number of layers matters more than lowering resolution.
- Adaptive resolution. Dynamically adjusting render resolution based on actual frame time is the single highest-payoff optimization.
// Adaptive resolution: use frame time as the feedback signallet scale = basePixelRatio;function onFrame(ms) {if (ms > 22) scale = Math.max(0.6, scale - 0.05);else if (ms < 13) scale = Math.min(basePixelRatio, scale + 0.02);renderer.setPixelRatio(scale);}
- Shadows. For night scenes, have only one light cast shadows, keep the shadow map resolution at 1024 or below, and express the rest with “fake decal shadows.”
- Device tiering. On mobile, disable planar reflection, halve the particle count, reduce bloom to a single blur level, and keep fog (it costs very little).
- Measurement. Use frame time and draw-call count as the primary metrics, not just fps; fps averages away stutter intervals.
9. Common Failures and a Troubleshooting Order
Troubleshooting in the order “confirm the pipeline first, then the data, then tune parameters” is the most efficient:
- Black screen: first check whether the output color space and tone mapping are being applied twice (a missing or duplicated linear→sRGB conversion both cause an all-black/all-white screen).
- Blown-out highlights: lower the emissive and bloom intensity, increase the tone-mapping compression, then check the light intensity units.
- Surface flicker (z-fighting): widen the near/far plane gap, reduce far, or enable logarithmic depth.
- A light isn’t lit: confirm the material type actually receives light (basic materials don’t respond to lighting), and confirm the normal direction is correct.
- Rain isn’t moving: usually the time uniform isn’t being updated each frame, or the modulo range doesn’t match the bounding box, causing particles to vanish instantly.
- Getting slower with each change: look back at whether you added full-screen passes, reflections, or shadows; these changes cost far more than intuition suggests.
10. From Demo to Deliverable
There’s still a bit of engineering work between a scene that runs locally and one you can share with others: deploy assets and build outputs to object storage and put a CDN in front to reduce first-load time; compress and crop models and textures, and enable progressive loading where needed; integrate common observability such as front-end logging and monitoring alerts, and use real-device frame-time distributions to guide the next round of optimization; and finally keep a fallback path so low-end devices automatically enter a simplified rendering branch.
Looking back, the greatest value the AI coding assistant brought to this project wasn’t replacing an understanding of rendering fundamentals—it was compressing the “try → observe → fix” loop from hours down to minutes. Constraints like proportions, light ratio, and performance budget still need to be defined and verified by a person; but once the constraints are clear, turning that rainy-night shop in your head into something runnable and playable is just a patient string of conversations.
