Unity-NorthStar / data /Assets /Tutorial /pages /Ocean and Environment.asset
introvoyz041's picture
Migrated from GitHub
d883ffe verified
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!114 &11400000
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 0}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 4510294d23d964fe59443526f1ca7c4b, type: 3}
m_Name: Ocean and Environment
m_EditorClassIdentifier:
m_displayName: Ocean and Environment
m_hierarchyName: Ocean and Environment
m_context: {fileID: 11400000, guid: 621dae04c7b446848b2db1c19788c9f3, type: 2}
m_markdownFile: {fileID: 0}
m_priority: 1002
m_overrideMarkdownText: "# Ocean Design and Implementation\n\nThe ocean system
uses an inverse Fast Fourier Transform (iFFT) to simulate realistic wave motion
across many waves (128\xB2 = 16,384 waves at default resolution). This method
provides detailed, dynamic ocean visuals while maintaining performance.\n\n![](./Images/OceanSystem/Fig0.png)\n\n##
Choosing iFFT Over Gerstner Waves\n\nEarly tests with Gerstner waves in the vertex
shader were inefficient for realistic ocean simulation. While suitable for stylized
games, Gerstner waves require individual control over direction, amplitude, and
wavelength, making them hard to manage and computationally expensive at high
wave counts. In contrast, iFFT generates a frequency spectrum of waves, offering
greater realism and easier control.\n\nAlthough iFFT can be computationally expensive,
optimizations ensured it remained viable. A key decision was whether to run the
simulation on the CPU or GPU. The GPU is well-suited for parallel processing,
but the project required high frame rates and high-resolution rendering, making
additional GPU load undesirable. Moreover, ocean height queries for floating
objects and ship physics would require costly GPU-to-CPU data transfers. To address
these concerns, the simulation runs on the CPU, leveraging Unity's job system
and Burst compiler for parallelized, optimized calculations. Certain iFFT components
update only when parameters change, further reducing CPU load.\n\n## Environment
Profile & Ocean Settings\n\n![](./Images/OceanSystem/Fig1.png)\n\n1. **Wind Yaw/Pitch**\n\n
Controls the wind direction and, consequently, the ocean waves. Instead of a
full XYZ rotation, pitch and yaw suffice to control wind direction, converted
to a vector via spherical coordinate transform. The ocean does not react to up/down
wind, but other effects, like sails, do. The total projected length of the wind
vector along the ocean plane is used as the final wind speed/direction for the
ocean simulation. Wind speed is set specifically for the ocean, independent of
other systems, for more control.\n\n2. **Wind Speed**\n\n Controls the strength,
speed, and height of the waves. Higher speeds cause larger, choppier waves, while
lower speeds produce gentle waves.\n\n3. **Directionality**\n\n Controls wave
alignment with the wind direction. A value of 0 gives a random, choppy look,
while 1 aligns most waves with the wind. Very low or high values are most useful
for random or windy scenarios; in-between values give a non-specific look.\n\n4.
**Choppiness**\n\n Controls horizontal wave displacement. Simple up/down movement
is insufficient for a convincing ocean, so extra horizontal displacement is calculated/applied
to the vertices. This value generally looks best at 1 but is included for flexibility.\n\n5.
**Patch Size**\n\n Defines the world-space size the ocean simulation covers.
Simulating an infinite ocean is not feasible, so a small patch is simulated and
repeated over the ocean surface. Smaller values concentrate detail in a smaller
area, but tiling may be more noticeable. Larger values reduce repetition and
allow for larger, varied waves, especially with higher wind speeds, but lose
fine detail. A detail normal map can restore some fine detail. A scrolling noise
texture modulates displacement to break up tiling.\n\n6. **MinWaveSize**\n\n
A fine control filter to fade out very small waves generated by the simulation.
At lower resolutions and patch sizes, small wavelengths can alias, causing a
faceted or flickering look. It can also be used for a stylized look, removing
finer waves and leaving larger rolling waves.\n\n7. **(Advanced) Gravity**\n\n
Earth's gravity in meters per second controls the relation between wave size
and speed. Generally, this should not be adjusted as it can make waves look oddly
fast or slow, but it is included for special cases.\n\n8. **(Advanced) SequenceLength**\n\n
The sequence repeats after a certain time to avoid accumulating floating-point
errors. It can be shortened to produce a looping sequence, e.g., a 10-second
loop baked into displacement/normal maps to avoid runtime computation. Larger
waves will not progress correctly at short sequences. For most cases, set this
to a high value, like 200 seconds, to reduce errors without noticeable repetition.\n\n9.
**(Advanced) TimeScale**\n\n Scales the simulation speed. Usually left at 1,
it can slow down or speed up the simulation or achieve certain ocean states/looks
not possible with regular controls. However, other controls should be used instead,
as this parameter often produces unrealistic results.\n\n## Ocean Simulation
& Material\n\nThe material used for rendering the ocean can vary per environment
profile. The system smoothly transitions between different materials/parameters
when profiles change. Care is needed as texture properties can't be interpolated,
and certain parameters, like changing time scales or texture scaling/offsets,
can cause large changes during transitions. More details are in the Ocean Shader
section.\n\n## Ocean Simulation\n\nThis component updates the ocean simulation,
setting up data for burst jobs, dispatching them, and updating the final texture
contents. It dispatches a job to fill the ocean spectrum data when ocean properties
change, like wind speed or direction. This fills an n*n resolution array with
float4's containing two complex numbers, representing initial wave properties
like amplitude and frequency. It also fills a dispersion table buffer with initial
time-related properties.\n\nEach frame starts with a dispersion job update, initializing
a complex number array for the height component and two additional arrays for
X and Z displacement components. These are inputs into the iFFT jobs, processed
in groups targeting an entire row and then an entire column of the texture.\n\nThe
final result is written to the displacement texture using GetRawTextureData to
write directly to the pixel data without requiring copies/conversions. This is
an RGBA 16-bit float texture; the alpha channel is unused since there is no signed
float texture format with only RGB channels. An unsigned texture could be used
with a bias, but precision close to zero is essential.\n\nA second pass generates
a normal/foam/smoothness map based on the displacement data. Normals are computed
via the central difference of four neighboring displacement samples. Foam at
wave peaks is calculated using the Jacobian of the displacement. The final value
is processed in the shader according to foam threshold and strength parameters.\n\nThe
alpha channel stores a filtered smoothness value, helping with consistent highlights
and environment reflections in the distance. It's calculated by averaging normal
length and mapping it to a roughness value via analytical importance sampling
of a GGX distribution.\n\n**Normal Map Baker**\n\nA function, accessible via
a context menu option (right-clicking on the OceanSimulation component), bakes
the current ocean's normal map into a texture. This can be used as a detail normal
map in the ocean material or for other purposes. Increasing simulation resolution
and adjusting properties can capture smaller-scale details in the normal map
while leaving the ocean simulation to calculate larger-scale details and displacement.\n\n![](./Images/OceanSystem/Fig2.png)\n\n##
Quadtree Renderer\n\nThe ocean uses a Quadtree system for rendering instead of
a single mesh like a plane. This approach balances vertex density and draw distance.
The system moves with the camera, ensuring the ocean is always visible.\n\n![](./Images/OceanSystem/Fig3.png)\n\nEach
frame, the quadtree aligns with the camera position based on a grid size, set
to the vertex spacing of the largest subdivision level. This prevents mesh sliding,
which can cause artifacts as the camera moves. The highest quadtree level is
checked against the camera view frustum. If visible, it is evaluated for subdivision
based on its distance to the camera, multiplied by the current quadtree level's
radius. If below a threshold, it subdivides, and each child patch is checked
against the view frustum and tested for further subdivision if visible.\n\nVisible
patches that are not close enough for further subdivision, or have reached the
max subdivision level, are added to a rendering list.\n\nPatches are grouped
into draw calls based on subdivision levels. If all neighbors share the same
level, a simple tessellated quad is used. Otherwise, an index buffer with edge-stitching
prevents seams between meshes. All patches use the same vertex buffer for performance
but different index buffers.\n\nThe final draw calls are rendered using Graphics.DrawMeshInstanced.\n\nEfforts
to use displacement map LODs for smoother transitions between LODs were explored,
but time constraints prevented full implementation. Issues with cracks between
patches and performance concerns due to extra data processing remain.\n\nThe
system is controlled by several parameters:\n\n- **Size:** Total patch size,
ideally large enough to reach the far plane in all directions. Balances processing
needs and detail up close. Avoid excessive size. Techniques like fog can hide
the ocean disappearing at a distance.\n- **Vertex Count:** Number of vertices
along one side of a patch. For example, a value of 8 creates a patch with 8*8=64
vertices. (Actual count is N+1 to form a quad with N*N patches.)\n- **LOD levels:**
Maximum grid subdivisions. Subdivision level depends on camera distance, with
higher levels offering more detail up close but requiring more processing.\n-
**Max Height:** Corresponds to wave height in world space, used for culling patches
below the camera.\n- **Culling Bounds Scale:** Patches are culled based on a
bounding box. High wind speeds can cause patches to disappear while still visible
due to horizontal and vertical displacement.\n- **LOD threshold:** A patch subdivides
into smaller patches when closer to the camera than its radius multiplied by
this threshold. Increasing this value reduces flickering/popping as the camera
moves but increases GPU vertex processing.\n- **Skirting Size:** Beyond the ocean
distance, a simple \"skirting mesh\" renders more of the mesh with simplified
geometry. No LOD-stitching means minor cracks may appear. Best used if rendering
the ocean to the far plane is too demanding.\n\n## Conclusion\n\nBy using iFFT,
CPU-side processing, and a dynamic quadtree renderer, the ocean system achieves
high visual fidelity while maintaining performance. Future improvements could
include smoother LOD transitions and optimizations for GPU-based displacement
rendering.\n\n### Relevant Files\n- [OceanSimulation.cs](https://github.com/meta-quest/Unity-UtilityPackages/blob/main/com.meta.utilities.environment/Runtime/Scripts/Water/OceanSimulation.cs)\n-
[OceanSpectrumJob.cs](https://github.com/meta-quest/Unity-UtilityPackages/blob/main/com.meta.utilities.environment/Runtime/Scripts/Water/OceanSpectrumJob.cs)\n-
[OceanDispersionJob.cs](https://github.com/meta-quest/Unity-UtilityPackages/blob/main/com.meta.utilities.environment/Runtime/Scripts/Water/OceanDispersionJob.cs)\n-
[OceanFFTRowJob.cs](https://github.com/meta-quest/Unity-UtilityPackages/blob/main/com.meta.utilities.environment/Runtime/Scripts/Water/OceanFFTRowJob.cs)\n-
[OceanFFTColumnJob.cs](https://github.com/meta-quest/Unity-UtilityPackages/blob/main/com.meta.utilities.environment/Runtime/Scripts/Water/OceanFFTColumnJob.cs)\n-
[OceanFFTFinalJob.cs](https://github.com/meta-quest/Unity-UtilityPackages/blob/main/com.meta.utilities.environment/Runtime/Scripts/Water/OceanFFTFinalJob.cs)\n-
[QuadtreeRenderer.cs](https://github.com/meta-quest/Unity-UtilityPackages/blob/main/com.meta.utilities.environment/Runtime/Scripts/Water/QuadtreeRenderer.cs)\n"
m_overrideMarkdownRoot: .\Documentation/