= Rendering Water as Post-Process Effect
:author:
:revnumber:
:revdate: 2016/03/17 20:48
:relfileprefix: ../../
:imagesdir: ../..
:uri-jmonkeyengine: https://github.com/jMonkeyEngine/jmonkeyengine/tree/master/
:uri-forum: https://hub.jmonkeyengine.org/
ifdef::env-github,env-browser[:outfilesuffix: .adoc]


The awesome SeaMonkey WaterFilter is highly configurable. It can render any type of water and also simulates the underwater part of the effect, including light effects called caustics. The effect is based on link:https://www.gamedev.net/articles/programming/graphics/rendering-water-as-a-post-process-effect-r2642/[Wojciech Toman’s Rendering Water as a Post-process Effect] 
published on gamedev.net. Here's a video:


image::jme3/advanced/water-post.png[water-post.png,width="",height="",align="center",link=https://youtu.be/AWlUzgRN3Pc]


[NOTE]
====
The SeaMonkey WaterFilter is ideal for oceans and lakes, and especially for under-water scenes. If you only need a small simple water surface, such as a water trough or a shallow fountain, the <<jme3/advanced/water#,SimpleWaterProcessor>> may already be all you need.
====



== The Theory

The effect is part of a deferred rendering process, taking advantage of the pre-computed position buffer and back buffer (a texture representing the screen’s pixels position in view space, and a texture of the rendered scene).

After some calculation, this allows to reconstruct the position in world space for each pixel on the screen. “If a pixel is under a given water height, let’s render it as a blue pixel! Blue pixel? Not exactly, we want waves, we want ripples, we want foam, we want reflection and refraction.

The GameDev.net article describes how those effects are achieved, but the main idea is to generate waves from a height map, create ripples from a normal map, blend in the foam texture when the water depth is below a certain height, compute the refraction color with a clever color extinction algorithm, and then, display the reflection and specular effect by computing a Fresnel term (like in the simple water effect). In addition, this effect allows to blend the water shore with the ground to avoid the hard edges of classic water effects based on grids or quads.


== How Did We Implement it in jME3?

jME3 default behavior is to use a forward rendering process, so there is no position buffer rendered that we can take advantage of. But while rendering the main scene to a frame buffer in the FilterPostPorcessor, we can write the hardware depth buffer to a texture, with nearly no additional cost.

There are several ways of reconstructing the world space position of a pixel from the depth buffer. The computational cost is higher than just fetching the position from a position buffer, but the bandwidth and the memory required is a lot lower.

Now we have the rendered scene in a texture, and we can reconstruct the position in world space of each pixel. We’re good to go!

– Nehon


== Sample Code

These are test cases in the jME3 repository:

*  link:{uri-jmonkeyengine}jme3-examples/src/main/java/jme3test/water/TestPostWater.java[TestPostWater.java] (ocean island)
*  link:{uri-jmonkeyengine}jme3-examples/src/main/java/jme3test/water/TestPostWaterLake.java[TestPostWaterLake.java] (calm and muddy water pond)
*  link:{uri-jmonkeyengine}jme3-examples/src/main/java/jme3test/water/TestMultiPostWater.java[TestMultiPostWater.java] (several ponds of different sizes at different heights etc)


=== Using the Water Filter

In the `simpleInitApp()` method, you attach your scene to the rootNode, typically a terrain with a sky. Remember to add a directional light, since the water relies on the light direction vector. The WaterFilter constructor expects a node with the scene attached that should be reflected in the water, and vector information from the light source's direction.

This is how you use the water filter post-processor code in your code:

[source,java]
----

private FilterPostProcessor fpp;
private WaterFilter water;
private Vector3f lightDir = new Vector3f(-4.9f, -1.3f, 5.9f); // same as light source
private float initialWaterHeight = 0.8f; // choose a value for your scene
...

public void simpleInitApp() {
  ...
  fpp = new FilterPostProcessor(assetManager);
  water = new WaterFilter(rootNode, lightDir);
  water.setWaterHeight(initialWaterHeight);
  fpp.addFilter(water);
  viewPort.addProcessor(fpp);
  ...
}

----

Usually you make the water reflect everything attached to the rootNode. But you can also give a custom node (a subnode of the rootNode) to the WaterFilter constructor that has only a subset of scene nodes attached. This would be a relevant optimization if you have lots of nodes that are far away from the water, or covered, and will never be reflected.


=== Optional: Waves

If you want waves, set the water height in the update loop. We reuse the initialWaterHeight variable, and repeatedly reset the waterHeight value according to time. This causes the waves.

[source,java]
----

private float time = 0.0f;
private float waterHeight = 0.0f;

@Override
public void simpleUpdate(float tpf) {
  super.simpleUpdate(tpf);
  time += tpf;
  waterHeight = (float) Math.cos(((time * 0.6f) % FastMath.TWO_PI)) * 1.5f;
  water.setWaterHeight(initialWaterHeight + waterHeight);
}

----


=== Optional: Water Wave and Color Effects


image::jme3/advanced/water-post-muddy.png[water-post-muddy.png,width="220",height="172",align="center"]


All these effects are optional. Every setter also has a getter.

[cols="3", options="header"]
|===

a| Water method example
a|Effects: Waves
a|Default

a|water.setWaterHeight(-6);
a|Use this waterheight method for causing waves.
a|0.0f

a|water.setMaxAmplitude(0.3f);
a|How high the highest waves are.
a|1.0f

a|water.setWaveScale(0.008f);
a|Sets the scale factor of the waves height map. The smaller the value, the bigger the waves!
a| 0.005f

a|water.setWindDirection(new Vector2f(0,1))
a|Sets the wind direction, which is the direction where the waves move
a|Vector2f(0.0f, -1.0f)

a|water.setSpeed(0.7f);
a|How fast the waves move. Set it to 0.0f for still water.
a|1.0f

a|water.setHeightTexture( (Texture2D) +
manager.loadTexture(“Textures/waveheight.png) )
a|This height map describes the shape of the waves
a|“Common/MatDefs/Water/Textures/heightmap.jpg

a|water.setNormalTexture( (Texture2D) +
manager.loadTexture(“Textures/wavenormals.png) )
a|This normal map describes the shape of the waves
a|“Common/MatDefs/Water/Textures/gradient_map.jpg

a|water.setUseRipples(false);
a|Switches the ripples effect on or off.
a|true

a|water.setNormalScale(0.5f)
a|Sets the normal scaling factors to apply to the normal map. The higher the value, the more small ripples will be visible on the waves.
a|1.0f

|===

[cols="3", options="header"]
|===

a| Water method example
a| Effects: Color
a|Default

a|water.setLightDirection(new Vector3f(-0.37f,-0.50f,-0.78f))
a|Usually you set this to the same as the light source's direction. Use this to set the light direction if the sun is moving.
a|Value given to WaterFilter() constructor.

a|water.setLightColor(ColorRGBA.White)
a|Usually you set this to the same as the light source's color.
a|RGBA.White

a|water.setWaterColor(ColorRGBA.Brown.mult(2.0f));
a|Sets the main water color.
a|greenish blue +
ColorRGBA(0.0f,0.5f,0.5f,1.0f)

a|water.setDeepWaterColor(ColorRGBA.Brown);
a|Sets the deep water color.
a|dark blue +
ColorRGBA(0.0f, 0.0f,0.2f,1.0f)

a|water.setWaterTransparency(0.2f);
a|Sets how fast colors fade out. use this to control how clear (e.g. 0.05f) or muddy (0.2f) water is.
a| 0.1f

a|water.setColorExtinction(new Vector3f(10f,20f,30f));
a|Sets At what depth the refraction color extincts. The three values are RGB (red, green, blue) in this order. Play with these parameters to “muddy the water.
a|Vector3f(5f,20f,30f)

|===

[cols="3", options="header"]
|===

a| Water method example
a| Effects: Shore
a|Default

a|water.setCenter(Vector3f.ZERO); +
water.setRadius(260);
a|Limit the water filter to a semisphere with the given center and radius. Use this for lakes and smaller bodies of water. Skip this for oceans.
a|unused

a|water.setShoreHardness(1.0f);
a|Sets how soft the transition between shore and water should be. High values mean a harder transition between shore and water.
a|0.1f

a|water.setUseHQShoreline(false);
a|Renders shoreline with better quality ?
a|true

|===

[cols="3", options="header"]
|===

a| Water method example
a| Effects: Foam
a|Default

a|water.setUseFoam(false);
a|Switches the white foam on or off
a|true

a|water.setFoamHardness(0.5f)
a|Sets how much the foam will blend with the shore to avoid a hard edged water plane.
a|1.0f

a|water.setFoamExistence(new Vector3f(0.5f,5f,1.0f))
a|The three values describe what depth foam starts to fade out, at what depth it is completely invisible, at what height foam for waves appears (+ waterHeight).
a|Vector3f(0.45f,4.35f,1.0f)

a|water.setFoamTexture( (Texture2D) +
manager.loadTexture(“Textures/foam.png) )
a|This foam texture will be used with WrapMode.Repeat
a|“Common/MatDefs/Water/Textures/foam.jpg

|===

[cols="3", options="header"]
|===

a| Water method example
a| Effects: Light
a|Default

a|water.setSunScale(1f);
a|Sets how big the sun should appear in the light's specular effect on the water.
a|3.0f

a|water.setUseSpecular(false)
a|Switches specular effect on or off
a|true

a|water.setShininess(0.8f)
a|Sets the shininess of the water reflections
a|0.7f

a|water.setUseRefraction(true)
a|Switches the refraction effect on or off.
a|true

a|water.setRefractionConstant(0.2f);
a|The lower the value, the less reflection can be seen on water. This is a constant related to the index of refraction (IOR) used to compute the fresnel term.
a|0.3f

a|water.setRefractionStrength(-0.1)
a|This value modifies the current Fresnel term. If you want to weaken reflections use bigger value. If you want to empasize them, use a value smaller than 0.
a|0.0f

a|water.setReflectionMapSize(256)
a|Sets the size of the reflection map. The higher, the better the quality, but the slower the effect.
a|512

|===


=== Sound Effects

You should also add audio nodes with water sounds to complete the effect.

[source,java]
----

AudioNode waves = new AudioNode(assetManager, "Sounds/Environment/Ocean Waves.ogg", false);
waves.setLooping(true);
audioRenderer.playSource(waves);

----

See also: <<jme3/advanced/audio#,audio>>.

'''

See also:

*  link:{uri-forum}t/monkeys-at-the-beach/15000[JME3's Water Post-Process Effect] by Nehon
*  <<jme3/advanced/water#,Simple water>>
