In This Article (14 sections)
Emil J’s Godot Water Shader, Mesh Setup and Gerstner Waves
Emil J’s Godot water shader connects ocean displacement with foam generated from horizontal compression. Gerstner waves shape the moving surface, while the Jacobian determinant identifies where neighboring surface points gather together, creating a signal that determines where foam appears. The public project also lists persistent Jacobian foam and persistent intersection foam, extending the effect beyond an instantaneous mask to include stored history and contact with surrounding objects.
The repository configuration checked on September 22, 2026 identifies Godot 4.7 with the Forward Plus renderer. That describes the published project rather than guaranteeing compatibility with every Godot 4 version or rendering method. The equations, example values, and implementation options discussed here illustrate the technique without claiming to reproduce Emil J’s exact variable names, shader structure, or defaults. Development is easiest to manage in stages: establish the geometry, check derivatives and lighting, tune instantaneous foam, and introduce persistence last. This prevents history or complex shading from hiding problems in the underlying calculations.
A straightforward setup uses a MeshInstance3D containing a PlaneMesh, which lies in the XZ plane with Y as the vertical axis. Its subdivide_width and subdivide_depth properties add geometry for deformation, while a ShaderMaterial containing a spatial shader provides exposed controls for amplitude, wavelength, direction, choppiness, phase, and foam. Vertex displacement only moves existing vertices, so a large plane with insufficient subdivision can evaluate the equations correctly while still producing an angular surface.
Mesh density should account for the shortest wavelength used to deform geometry. An eight unit wave sampled at half unit spacing, for example, has sixteen intervals across one wavelength. This is an illustrative starting point rather than a universal requirement, since sharper crests and closer cameras may need more detail. Smaller ripples can instead affect shading through normal detail without changing the silhouette. Displacement can also exceed the mesh’s original bounds, making extra_cull_margin and custom_aabb on GeometryInstance3D relevant if water disappears unexpectedly near the camera or viewing boundary. More subdivisions will not correct unsuitable culling bounds.
Gerstner Wave Equation, Verification, and Dispersion
For a single Gerstner style wave, let the undeformed surface coordinate be \(q=(x,z)\) and the normalized horizontal direction be \(d=(d_x,d_z)\). Define a positive wavelength \(L\), vertical amplitude \(A\), horizontal displacement amplitude \(B\), initial phase \(\phi\), angular frequency \(\omega\), and time \(t\). With the original water height at zero:\[ k=\frac{2\pi}{L} \]\[ \theta=k(d\cdot q)-\omega t+\phi \]\[ P(q,t)= \left( x+Bd_x\cos\theta,\; A\sin\theta,\; z+Bd_z\cos\theta \right) \]
This combines vertical oscillation with lateral movement, producing the sharper crests associated with Gerstner style waves. A common artistic parameterization is \(B=QA\), where \(Q\) controls horizontal choppiness. In a Godot spatial shader, displacement belongs in vertex(). By default, VERTEX is supplied in model space, while world_vertex_coords changes the coordinate convention. The phase and displacement calculations must use a consistent space.
Start with one wave before adding lighting, noise, or foam. Increasing amplitude should increase vertical movement, increasing wavelength should spread crests farther apart, and changing direction should rotate their travel. Normalize every nonzero direction vector so that changing its length does not also change the effective wavelength. Doubling \(L\) halves \(k\), while the vertical term \(A\sin\theta\) places the crest \(A\) above the rest level and the trough \(A\) below it, producing a total height of \(2A\). Initial phase shifts the pattern through its cycle without changing amplitude or wavelength, and Godot’s trigonometric shader functions use radians.
For a deep water gravity wave approximation, angular frequency and phase speed are related by:\[ \omega=\sqrt{gk} \]\[ c=\frac{\omega}{k}=\sqrt{\frac{g}{k}} \]
Here, \(g\) is the gravity parameter. The approximation assumes deep water and omits surface tension, so it is not a complete shallow water model. Phase speed \(c\), measured in distance per second, must not be confused with angular frequency \(\omega\), measured in radians per second. These phase expressions are equivalent:\[ k(d\cdot q-ct)+\phi \]\[ k(d\cdot q)-\omega t+\phi \]
Horizontal Compression and Multi-Wave Folding Limits
Vertical and horizontal displacement serve different purposes. Vertical amplitude controls how far the surface rises and falls, while horizontal displacement controls how neighboring points gather or spread apart. Setting \(B=0\) produces a vertically displaced sine surface. Increasing \(B\) changes crest and trough shape, but a high point is not automatically a compressed point. For one wave, the dimensionless quantity governing horizontal compression is:\[ s=kB \]
Consequently, \(Q\) alone does not determine choppiness when \(B=QA\). A moderate value can still produce strong compression if amplitude is large relative to wavelength. For the illustrative values \(L=12\), \(A=0.6\), and \(Q=0.7\), horizontal amplitude becomes \(B=0.42\), giving \(kB\approx0.220\). Keeping lateral movement conservative initially makes derivatives and foam easier to inspect. Gerstner displacement remains an artist controlled approximation, not a complete simulation of breaking waves, spray, or fluid interaction.
Several waves can reduce the repetition of a single component. For \(n\) waves, the combined position is:\[ P(q,t)= \left( x+\sum_{i=1}^{n}B_i d_{ix}\cos\theta_i,\; \sum_{i=1}^{n}A_i\sin\theta_i,\; z+\sum_{i=1}^{n}B_i d_{iz}\cos\theta_i \right) \]
Every phase should be evaluated from the same undeformed coordinate \(q\), with displacement accumulated from the original position. Feeding one wave’s displaced coordinates into the next creates a different, nested deformation whose derivatives require additional chain rule terms. A practical combination might use a long primary swell, a smaller wave traveling at an offset angle, and a shorter component for local variation. For this constant parameter model, a conservative sufficient condition against horizontal folding is:\[ \sum_{i=1}^{n}|k_iB_i|<1 \]
Exceeding that limit does not prove that every configuration will fold. It provides a useful conservative bound, while derivative contributions must still be combined before calculating the final normal or compression determinant.

Noise, Surface Derivatives and Correct Water Normals
Noise can reduce repetition, but geometry variation, fine shading detail, and foam breakup are separate operations that need not share a texture or animation speed. Godot’s NoiseTexture2D generates texture data from a noise resource and supports options including seamless generation, mipmaps, and normal map output. Enabled mipmaps also require an appropriate sampling filter. For an initial shader, applying noise to foam appearance is simpler than altering displacement: the Jacobian can continue determining where foam is eligible, while noise breaks continuous bands into irregular patches.
Changing geometry with noise requires corresponding changes to its derivatives. If horizontal amplitude varies across the surface as \(B(q)\), differentiating its displacement term gives:\[ \frac{\partial}{\partial x} \left[B(q)\cos\theta(q)\right] = B_x\cos\theta-B\sin\theta\,\theta_x \]
Here, \(B_x\) and \(\theta_x\) are the derivatives of amplitude and phase with respect to \(x\). Treating amplitude as constant would omit the first term and make the calculated compression inconsistent with the displaced geometry. Spatially changing directions and phase warping introduce similar additional terms, which is why decorative noise and changes to the underlying wave model should be handled separately.
Noise applied only to vertical height changes the surface and its normal, but it does not automatically change the horizontal Jacobian if horizontal coordinates remain unchanged. A normal texture affects shading without changing mesh position or geometric compression, while foam noise changes appearance without altering the water’s shape. These effects should also remain spatially and temporally coherent. Independent random changes every frame can look unstable and make sampling artifacts difficult to distinguish from intended motion.
Computing Normals and Coordinate Conventions
Lighting requires normals that describe the displaced surface rather than the original flat plane. For \(P(x,z,t)\), define the tangent vectors and normal as:\[ T_x=\frac{\partial P}{\partial x}, \qquad T_z=\frac{\partial P}{\partial z} \]\[ N=\operatorname{normalize}(T_z\times T_x) \]
This cross product order matches the upward orientation of the original XZ plane: \(T_x=(1,0,0)\) and \(T_z=(0,0,1)\) produce \((0,1,0)\). For the stated multiwave model, the vertical derivatives are:\[ H_x=\sum_i k_iA_i d_{ix}\cos\theta_i \]\[ H_z=\sum_i k_iA_i d_{iz}\cos\theta_i \]
Horizontal derivatives complete the tangents. Accumulate all contributions before taking the cross product and normalizing, since adding already normalized individual wave normals does not reproduce the normal of the combined surface. A coarse mesh can also fail to represent the intended shape even when the analytical equations are correct, so geometry and lighting should be inspected together.
Coordinate conventions remain important throughout shading. Vertex stage normals normally use model space, fragment stage NORMAL is in view space, and NORMAL_MAP expects tangent space normal map data. Mixing these conventions can make highlights and reflections rotate incorrectly as the camera moves. Simple directional lighting provides a useful diagnostic before reflection, refraction, and foam complicate the result. Godot’s screen space reflections have separate limitations: they cannot recover information outside the screen or behind visible geometry, and transparent objects are not included as reflected objects. Those restrictions do not indicate that the Gerstner normal is mathematically wrong.

Jacobian Compression and Dynamic Foam Generation
The Jacobian used for foam describes the mapping from the original horizontal coordinates \((x,z)\) to the displaced horizontal coordinates \((P_x,P_z)\):\[ J= \begin{pmatrix} \frac{\partial P_x}{\partial x} & \frac{\partial P_x}{\partial z}\\[4pt] \frac{\partial P_z}{\partial x} & \frac{\partial P_z}{\partial z} \end{pmatrix} \]
For the constant parameter multiwave model, its components are:\[ J_{xx}=1-\sum_i k_iB_i d_{ix}^{2}\sin\theta_i \]\[ J_{xz}=J_{zx} =-\sum_i k_iB_i d_{ix}d_{iz}\sin\theta_i \]\[ J_{zz}=1-\sum_i k_iB_i d_{iz}^{2}\sin\theta_i \]
The determinant is then calculated from the complete matrix:\[ j=J_{xx}J_{zz}-J_{xz}J_{zx} \]
This scalar measures the signed local change in projected horizontal area. It is not water density or a determinant describing the full three dimensional surface. Its interpretation is:
- \(j=1\) means no net local horizontal area change, even if the surface moves vertically.
- \(0<j<1\) indicates horizontal compression.
- \(j>1\) indicates horizontal expansion.
- \(j=0\) means the horizontal projection is singular.
- \(j<0\) indicates reversed horizontal orientation.
These derivatives also complete the tangent vectors used for lighting:\[ T_x=(J_{xx},H_x,J_{zx}) \]\[ T_z=(J_{xz},H_z,J_{zz}) \]
The determinant \(j\) equals the Y component of the unnormalized vector \(T_z\times T_x\). Normalizing that vector removes its area scale, so the determinant needs to be retained separately to drive foam. This connects the normal and compression calculations without making them interchangeable.
For a single normalized wave, the determinant simplifies to:\[ j=1-kB\sin\theta \]
With positive horizontal amplitude, the crest gives \(1-kB\), while the trough gives \(1+kB\), explaining the compression near crests and expansion near troughs. If \(B=0\), the surface can rise and fall while its horizontal mapping remains unchanged and \(j=1\). With multiple waves, directions and phases interact to create more varied compression patterns. Calculating the determinant after assembling the full Jacobian preserves those interactions; adding individual wave determinants does not.
From Compression to Foam Thresholds
To turn compression into foam, two thresholds provide a gradual transition. Let foam_start identify where foam begins and foam_full the lower determinant value where it reaches full strength, with foam_full < foam_start. An illustrative expression is:
float foam_mask = 1.0 - smoothstep(
foam_full,
foam_start,
jacobian
);Here, jacobian contains the scalar determinant. Example values of foam_full = 0.45 and foam_start = 0.85 create a smooth transition between no foam and full coverage. The earlier single wave example reaches a minimum determinant of approximately \(0.780\), so it enters that transition without reaching full foam. That is the expected mathematical result, not evidence of a broken shader, and the example thresholds are not verified defaults from Emil J’s project.
Negative determinants are not required for attractive whitecaps. Foam can begin before the horizontal surface folds, so increasing choppiness simply to force visible foam confuses an appearance setting with a deformation limit. Once generation behaves correctly, appearance can be adjusted through a pale foam color, increased roughness, and noise applied to coverage or edges. Godot provides outputs such as ALBEDO and ROUGHNESS, while using ALPHA moves a spatial material into the transparent pipeline. Introduce transparency deliberately and retain a debug view of the instantaneous mask so that lighting and persistence do not conceal threshold errors.

Persistent Foam, History Buffers and Intersection Effects
An instantaneous mask describes where compression occurs now, while persistent foam records earlier generation. Without history, a patch disappears as soon as the determinant rises above its threshold. One illustrative update for a stored foam field combines transport, exponential decay, and new deposition:\[ F_{n+1}(u)= \operatorname{clamp} \left[ F_n(u-v_{uv}\Delta t)e^{-\Delta t/\tau} +\sigma S(u,t)\Delta t,\; 0,\; 1 \right] \]
Here, \(F_n\) is the previous foam value, \(S\) is the current generation signal, \(\tau>0\) is the decay time constant, and \(\sigma\) controls deposition. The coordinate \(u\) belongs to the foam texture, so velocity \(v_{uv}\) must use texture coordinate units per second, with \(\Delta t\) representing the time step. This remains a discrete approximation, particularly when the source or velocity changes rapidly. Setting transport velocity to zero initially isolates persistence and makes it easier to verify generation, retention, and fading before adding advection.
Ping Pong Buffering and SubViewport Rendering
A robust GPU implementation keeps the previous foam texture separate from the texture being written, alternating between them through ping pong buffering. Godot’s screen reading documentation explains the general read and write hazard behind this separation, and hint_screen_texture should not be treated as an automatic previous frame foam buffer. One possible architecture renders updates into a SubViewport and samples its ViewportTexture from the water material. This is an implementation option, not a reconstruction of Emil J’s exact project.
History should be initialized to zero, with the active update target controlled explicitly. Disabling SubViewport clearing alone does not establish safe feedback, decay, or transport. The history coordinate system also affects behavior: foam stored in undeformed surface coordinates follows that parameterization as waves move, while world mapped storage requires a consistent conversion from world positions to texture coordinates. Moving a camera centered texture region without shifting or reprojecting its history can make foam appear attached to the camera.
Jacobian foam and intersection foam should retain separate generation and history because they represent different events. Jacobian foam comes from compression within the wave field, while intersection foam comes from contact or proximity between water and surrounding geometry. Emil J’s intersection foam material uses depth information and stores different foam types in separate color channels. The creator also describes persistent contact foam that can trail behind moving objects.
Separate channels preserve useful controls even when both effects eventually appear white. Compression foam may need a shorter lifetime and irregular patch distribution, while contact foam may require a different width, fade rate, or trailing behavior. Their generation signals should therefore remain distinct until the final shading stage, where they can be combined through a maximum or another controlled blend.
Depth Reconstruction and Coordinate Spaces
For depth based intersection foam, reconstruct the sampled scene position before comparing it with the water. Raw depth values are not ordinary linear distances. Godot’s documentation uses the inverse projection matrix for reconstruction and distinguishes the normalized device coordinate conventions of Compatibility from those of Forward Plus and Mobile. Both compared positions must also use the same coordinate space. Comparing scene geometry with an undeformed flat plane will produce a contact band that fails to follow the actual waves.
A screen depth difference is not the shortest physical distance between an object and the water. It varies with camera angle and cannot account for geometry absent from the sampled depth information, making this form of intersection foam a screen space approximation. Keeping that limitation separate from the compression calculation helps diagnose each effect correctly while preserving independent control over wave foam, object contact, and their persistence.

Frequently Asked Questions[FAQs]
- What makes Emil J’s Godot water shader tutorial different from a basic animated water material?
Its documented approach connects the water’s geometry directly to foam generation instead of simply moving a texture across the surface. Gerstner waves shape the water, while the Jacobian determinant measures local horizontal compression and helps determine where foam should appear. The published project also includes persistent foam, allowing generated foam to remain visible after the original compression has passed rather than disappearing immediately with the current wave state. - Which Godot version does the published water shader project use?
The repository configuration checked on September 22, 2026 identifies Godot 4.7 using the Forward Plus renderer. This describes the configuration of the published project and is useful when trying to reproduce its rendering environment. It should not be treated as proof that the Gerstner wave mathematics require Godot 4.7 specifically or that every part of the shader will behave identically in Mobile or Compatibility rendering modes.
- Does a Gerstner water shader need a subdivided mesh?
Yes, if the water surface itself is being displaced geometrically. The shader can only move vertices that already exist, so a large plane with too little subdivision will produce angular or poorly defined waves even if the equations are correct. Godot’s PlaneMesh subdivision controls provide the extra geometry needed for larger waves, while very small ripples can often be handled through normal detail instead of requiring equally dense geometry.
- Why does height-based foam look different from Jacobian foam?
Height based foam responds to how high the water surface rises, while Jacobian foam responds to how much the horizontal surface is being compressed. Those are different measurements. A wave can rise significantly in the vertical direction without producing much horizontal compression, so a height threshold may place foam on every high crest while a Jacobian based system only generates it where the Gerstner displacement actually causes the surface to bunch together.
- Must the Jacobian determinant become negative before foam appears?
No. A determinant between zero and one already represents horizontal compression, which is enough to drive a foam mask. The artist can choose a positive threshold at which foam begins to appear and another lower value where it reaches full strength. Negative values indicate that the horizontal mapping has reversed orientation, so deliberately pushing the waves into that state is unnecessary and can create undesirable folding simply to obtain stronger foam.
- Can animated shader time create persistent foam without a history texture?
Not by itself. Shader time can animate a procedural pattern and make foam move or change from frame to frame, but it does not remember what the foam looked like previously. Persistent foam requires stored state, such as a history texture or another stateful simulation mechanism, so previously generated foam can decay gradually over time. Godot’s screen texture should therefore not be treated as an automatic previous frame foam buffer.
- Can Godot noise textures be used to make foam less uniform?
Yes. NoiseTexture2D can be used to break up a smooth compression mask into more irregular foam patches and can provide features such as seamless generation and mipmaps. Using noise only for foam appearance is relatively straightforward because the Jacobian still determines where foam is allowed to form. Applying spatial noise directly to wave displacement is more complex because the surface normals and Jacobian calculations then need to account for the additional derivatives introduced by that noise.
- Is intersection foam the same as wave-compression foam?
No. The two effects are generated by different events. Jacobian foam comes from compression within the moving water surface, while intersection foam appears where another object meets or approaches the water. Emil J describes keeping different foam types in separate color channels, which allows their width, persistence, intensity, and fade behavior to be controlled independently before they are combined in the final material.
- Why is no foam visible even though the water is moving correctly?
The most common reason is that the Jacobian determinant never becomes low enough to cross the selected foam threshold. Horizontal displacement may be too small, the threshold values may be too restrictive, or the foam generation may be working but getting lost during the persistence update. A useful debugging approach is to display the raw determinant and instantaneous foam mask separately before adding color, lighting, or history. Simply increasing wave height does not necessarily increase horizontal compression.
- Will the complete shader look identical in every Godot rendering method?
Not necessarily. The Gerstner wave mathematics can remain the same while rendering features around them behave differently. Godot documents differences between Forward Plus, Mobile, and Compatibility in areas such as depth reconstruction, screen space reflections, and other screen dependent effects. Each rendering method should therefore be tested independently for both appearance and performance rather than assuming that a shader tuned for one mode will produce identical results everywhere.

Conclusion
Emil J’s Godot water shader work demonstrates a useful connection between procedural geometry and surface appearance: wave deformation can provide the signal that drives foam. The creator’s documented use of compression-based generation, persistent foam, and independently controlled intersection foam establishes the central ideas of the project.
The most important implementation principle is consistency. Evaluate waves from stable original coordinates, derive normals and compression from the same displacement function, and keep instantaneous foam generation distinct from stored foam history.
A convincing result does not depend on maximizing every parameter. Excessive choppiness can fold the surface, excessive deposition can cover the ocean permanently, and additional noise can conceal rather than fix a coordinate error. A dependable workflow builds from one understandable wave to a combined surface, verifies its derivatives, introduces a controlled foam mask, and only then adds persistence and contact effects.
Sources and Citations
- Emil J, public project repository : Source repository for the water shader project. The repository URL was identified, but its configuration file could not be retrieved for verification.
Citation: Godot Water Shader. (GitHub) - Emil J, dynamic ocean foam explanation : The creator explains that foam is generated from wave compression using the Jacobian determinant and links to the accompanying tutorial. reddit.com
Citation: Been working on dynamic ocean foam in Godot; Create Dynamic Ocean Foam in Godot | Jacobian Foam. (Emil J on Reddit) - Emil J, persistent intersection foam explanation : The creator describes using depth maps and separate color channels to control foam types independently and produce trails behind moving objects. reddit.com
Citation: Been working on trailing intersection foam in Godot. (Emil J on Reddit) - Godot documentation, mesh and material setup : Official references for PlaneMesh dimensions, subdivisions and orientation, alongside ShaderMaterial configuration and shader parameters. Godot Engine (stable) documentation in English
Citation: PlaneMesh; ShaderMaterial. (Godot Engine) - Godot documentation, shaders and noise textures : Engine references for spatial shader conventions, built-in functions and procedural noise textures. These support adapting the mathematical explanation to Godot shader syntax. Godot Engine (stable) documentation in English
Citation: Spatial shaders; Built-in shader functions; NoiseTexture2D. (Godot Engine) - Godot documentation, viewports and depth reconstruction : Official guidance on viewport rendering, reconstructing positions from depth textures and differences between rendering methods. Godot Engine (stable) documentation in English
Citation: Using Viewports; Advanced post-processing; Overview of renderers. (Godot Engine) - Mark Finch, Effective Water Simulation from Physical Models : This GPU Gems chapter explains mathematical wave models, Gerstner waves, surface orientation and combining geometric displacement with normal maps for real time water rendering. NVIDIA Developer
Citation: Chapter 1: Effective Water Simulation from Physical Models. (NVIDIA Developer) - Catlike Coding, Waves tutorial : Provides explanations of sine waves, Gerstner waves, normals and combining multiple waves. Its implementation uses Unity, so its shader syntax is not directly interchangeable with Godot’s. catlikecoding.com
Citation: Waves. (Catlike Coding) - Crest, water appearance and foam documentation : Explains foam generation at compressed wave crests and shorelines, appearance controls, and gradual decay through foam fade settings. Crest Ocean System
Citation: Water Appearance; Foam. (Crest Documentation) - Godot documentation, GPU optimization : Supports the discussion of rendering bottlenecks, pixel coverage, fragment shader costs, texture reads and overdraw. Godot Engine (stable) documentation in English
Citation: GPU optimization. (Godot Engine)
Recommended
- Blender Camera Add-ons for Studios and Production Teams: Best Tools for Animation, VFX, Film, VR, and Digital Agencies
- High On Life 2 Hits Game Pass: Release Date, Platforms, and Everything You Need to Know
- Acer Companion Handheld for Gaming PCs: What It Is, How It Works, and Why It Could Change PC Gaming
- Top 10 Blender Add-ons for Camera Animation (Cinematic Shots & Workflow Boosters)
- Hellblade 2 and Unreal Engine 5: What Makes the Sequel a Visual Breakthrough
- Google Open-Sources GNM Head: Everything You Need to Know About the New 3D Parametric Human Head Model
- PlayStation Allegedly Confirms You’ll Have to Verify Your Game Licenses Every Month: PS5/PS4 30-Day Online Check-In Explained
- 40 Brilliant Details in LEGO Batman: Legacy of the Dark Knight, Joaquin Phoenix Minifig, Deep DC Comics Easter Eggs, and Hidden Movie References Explained
- Gothic 1 Remake: How to Join the New Camp and Complete Every Required Quest
- Palworld Horror-Themed Dating Sim Spinoff Is Real: What We Know About More Than Just Pals
- Cronos: the New Dawn Helped Bloober Team Hit the Highest Annual Revenues in Company History (2025 Financial Results)
- Best New FREE Blender Addons in 2026: Must-Have Blender Extensions for Blender 4.2 LTS+
- KINGDOM HEARTS Collection I–III File Size Reportedly Reaches 131 GB
- NoPixel V GTA V Roleplay Closed Beta Starts September 8
- No Case Should Remain Unsolved PS5 Port Launches August 19, 2026












































































































