| %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: Optimization |
| m_EditorClassIdentifier: |
| m_displayName: Optimization |
| m_hierarchyName: Optimization |
| m_context: {fileID: 11400000, guid: 4e52cc0593e52cf48a31fabc7fbf34b0, type: 2} |
| m_markdownFile: {fileID: 0} |
| m_priority: 1017 |
| m_overrideMarkdownText: "## Optimizing Framerate\n\nDuring development, we balanced |
| framerate targets with visual fidelity, making tradeoffs to meet performance |
| and aesthetic goals. Static environments with baked lighting are usually preferred |
| for performance. However, the boat's movement and dynamic weather required us |
| to optimize real-time lighting and shadows.\n\n## Target Framerate Tradeoffs\n\nAchieving |
| a native 90Hz framerate was challenging. A 90Hz target allows only 11 milliseconds |
| per frame for processing logic, animation, physics, sound, and rendering. This |
| was difficult due to our extensive use of dynamic ocean, sky, time of day, lighting, |
| and shadows. Instead, we aimed for:\n- 72Hz natively (13.88ms per frame).\n- |
| 90Hz with Application Space Warp (ASW), which improved visual quality, including |
| higher resolution textures, post-processing, and increased MSAA levels.\n\n## |
| Measuring Framerate\n\n### OVR Metrics Tool\n\nGathering performance data is |
| crucial for diagnosing and improving framerate issues. We used Meta\u2019s OVR |
| Metrics Tool (available on the Meta Quest store) to overlay detailed real-time |
| statistics about the game\u2019s performance. This helped us diagnose framerate |
| issues.\n\n\n\nWe created a daily |
| build from the development branch, tested by QA the next morning. The recorded |
| playthrough was posted on a dedicated Slack channel. With the metrics overlay, |
| we could see framerate fluctuations, detect performance regressions, and track |
| frame spikes.\n\n**RenderDoc Meta Fork**\n\nFor diagnosing specific issues related |
| to individual draw calls, we used the Meta fork of RenderDoc to get frame timings |
| directly.\n\n\n\n**Unity Profiler**\n\nThe |
| Unity profiler was invaluable for diagnosing CPU performance, although some calls |
| can be opaque, making it difficult to identify the actual problem.\n\n\n\n**Frame |
| Budget**\n\nAiming for a 72Hz refresh rate gave us a frame budget of 13.88ms. |
| It's crucial to keep the game within this budget to prevent noticeable slowdowns, |
| which are problematic in VR due to potential comfort issues like simulator sickness.\n\n**Fixed |
| Costs**\n\nSome fixed costs per frame cannot be optimized or removed as they |
| are critical to the game\u2019s functionality. These include the Meta SDK for |
| device management, input, tracking, and PhaseSync.\n\n**Meta SDK**\n\nCertain |
| Meta SDK features are expensive, such as Inside Out Full Body Tracking and using |
| many grab points on an object. For instance, a large trigger volume intersecting |
| with an object containing multiple grab points (like the ship\u2019s steering |
| wheel) caused unexpected framerate drops. We removed the large trigger volume |
| to prevent intersection with grab points.\n\n**PhaseSync**\n\nPhaseSync, an automated |
| frame pacing solution by Meta, synchronizes frame delivery to reduce latency. |
| It works well when frames are delivered steadily. However, if framerate is unstable, |
| it overestimates wait time, causing delays before frames can begin processing |
| in Unity, worsening framerate issues. Consistently reaching the target refresh |
| rate improves game feel and responsiveness by reducing latency between user input |
| and frame rendering.\n\n## Low Framerate Causes and Solutions\n\nWe identified |
| several sources of frame spikes and implemented solutions:\n\n**Asset Loading |
| & Deserialization**\n- Preloaded required assets to avoid unexpected asset loading.\n- |
| Used object pooling instead of instantiating prefabs at runtime.\n\n**Expensive |
| Calls**\n- Avoided `FindObjectsOfType()` and `GetComponentsInChildren()`, replacing |
| them with Meta\u2019s [AutoSet](https://github.com/meta-quest/Unity-UtilityPackages/blob/main/com.meta.utilities/README.md) |
| attribute for asynchronous component gathering.\n\n**GameObject Activation and |
| Start/Awake Callbacks**\nThese callbacks can be expensive when objects are activated. |
| Disabled objects wait until first activation, causing in-game slowdowns. This |
| was problematic during asynchronous scene loading. We pre-loaded scenes for transitions |
| but scene activation was costly due to many objects/scripts. We used short fade-to-black |
| transitions during screen blackouts to conform to VRC requirements.\n\n**Expensive |
| Calls**\n\nSome Unity calls are expensive and should be avoided. They sometimes |
| appear in production code, including Meta SDKs.\n\n**Examples:**\n- `FindObjectsOfType()`\n- |
| `GetComponentsInChildren()`\n\nWe used the [Meta Utilities Package attribute](https://github.com/meta-quest/Unity-UtilityPackages/blob/main/com.meta.utilities/README.md) |
| `AutoSet` to gather components at build time for asynchronous deserialization, |
| making activation cheaper. For `FindObjectsOfType`, we used `Singleton` and `Multiton` |
| from the package.\n\n**GC Collection**\n\nAllocations are expensive and should |
| be avoided. GC Allocations appeared in various places. We avoided them by rewriting |
| code or ignoring small allocation amounts. Common patterns include using Unity\u2019s |
| NonAlloc versions of physics query functions, like `Physics.SphereCastNonAlloc()`.\n\n**Reflection |
| Probes and DynamicGI.UpdateEnvironment()**\n\nTo support dynamic environment |
| profiles, reflection probes and environment lighting (IBL) need updates. Calls |
| to `DynamicGI.UpdateEnvironment()` are expensive, as they are calculated on the |
| GPU and read back synchronously by the CPU, stalling both. We created an offline |
| editor tool to generate precomputed lighting data for all environment profiles. |
| This data is fed to `DynamicGI.SetEnvironmentData()` as needed, allowing seamless |
| environmental lighting interpolation.\n\nOriginally, we updated reflection probes |
| dynamically when lighting changed significantly, but this was costly. We created |
| a probe blending system to blend pre-baked start and end environment conditions |
| smoothly.\n\n## Shader Compilation\n\nNear the project\u2019s end, we noticed |
| frame spikes from shader compilation. Avoiding shader compilation required tracking |
| all shader variants used during gameplay and pre-loading them during load time. |
| Unity allows tracking shader variants in the editor and saving them to a ShaderVariantCollection |
| asset. However, differences between editor and build and between platforms make |
| it difficult to gather a trusted list of shader variants.\n\n\n\nAnother |
| build option logs all shader variants loaded in a build.\n\n\n\nCombining |
| this with LogCat after a full playthrough, we obtained an accurate list of shader |
| variants used by the game.\n\n\n\nThe |
| raw output looks like this:\n\n\n\nWe |
| wrote an editor script to process this file and create a ShaderVariantCollection |
| for loading during game initialization. However, this did not fix the frame spikes.\n\n**PSO |
| Creation**\n\nModern graphics APIs, like Vulkan, render many draw calls with |
| little overhead. However, each unique shader and graphics state combination requires |
| device-specific preprocessing and optimizations at the driver level. Complex |
| shaders can take significant time, up to 500ms. Worse, it\u2019s not just each |
| shader variant but the combination of shader variant and pipeline state. Vertex |
| attribute layout and render target can trigger new PSOs, causing frame spikes.\n\nUnity |
| 6 can record and cache all PSOs during gameplay, distributing them with a build |
| and pre-loading at startup. We used Unity 2022.3, so we created our own solution. |
| We wrote a pre-warmer to force Unity to generate all required PSOs by combining |
| the shader variant list with known mesh attributes, lighting, light-probe, and |
| render target combinations, rendering them as a 1-pixel triangle outside the |
| player\u2019s view during the loading screen.\n\nThis process was slow initially, |
| taking about a minute, but became almost instant due to Unity\u2019s internal |
| PSO cache. We later bundled this cache with builds, though it may become invalid |
| after firmware updates.\n\n## Sustained Low Framerate\n\nSustained low framerate |
| occurs when the frame budget is exceeded each frame, due to CPU or GPU timings. |
| If excessive CPU time causes this, it's called CPU bound. If the GPU is the cause, |
| it's GPU bound. In our project, both CPU and GPU have been bottlenecks at different |
| times, depending on the resources needed to render a frame.\n\n**Script Callbacks |
| \u2013 CPU**\n\nScript callbacks are executed at predefined points during the |
| frame, sequentially on the main thread. This means the frame processing speed |
| is limited by the main thread's completion time. While some rendering tasks can |
| run in parallel on separate threads, they eventually must wait for the main thread. |
| Therefore, we must manage our single-threaded code budget carefully.\n\n_Examples:_\n\n- |
| Update / LateUpdate\n- FixedUpdate / OnTriggerStay / OnCollisionEnter\n\n**Physics |
| \u2013 CPU**\n\nManaging physics was straightforward by avoiding too many complex |
| dynamic objects or dense mesh colliders. More simulated objects and colliders |
| increase physics costs. Collision and trigger script callbacks also add overhead |
| and should be minimized.\n\nSimulation and collision detection are multi-threaded |
| via PhysX, but queries like Physics.SphereCastNonAlloc() still block the main |
| thread. For the rope system, we used OverlapSphereCommand in Burst jobs.\n\n**Burst |
| Jobs - CPU**\n\nWe used Unity Burst Jobs to enhance performance in key areas |
| like rope physics and ocean simulation. These jobs run on worker threads, freeing |
| the main thread for parallel tasks.\n\nTo maximize the Job System, we start jobs |
| at the beginning of Update() and complete them at the end of LateUpdate(). This |
| allows jobs to run on worker threads without blocking the main thread.\n\n**Render |
| Thread - CPU**\n\nReducing active game objects by merging meshes and materials |
| kept the render thread efficient.\n\n**Rendering \u2013 GPU**\n\n\n\n\n*Comparison |
| of the same shader before and after optimization. Green is faster.*\n\n## Rendering |
| Optimizations\n\nRendering optimizations could fill an entire article, but here |
| are some key actions we took:\n\n**Shader Instructions**\n\nA central shader |
| node (WavesDefaultShader) handles texture data unpacking, weather features, object |
| highlights, and more. This centralization allows for feature optimization and |
| scene rendering tweaks. However, not all shaders need these features. We created |
| several optimized master shaders for common feature sets, and a Material Editor |
| facilitates easy shader switching to include only necessary features.\n\n**Reducing |
| Quad Overdraw**\n\nVertex processing is a minor part of GPU time in this game. |
| However, small triangles from highly tessellated meshes, MSAA use, and rendering |
| each triangle twice (once per eye) cause significant quad overdraw. We reduced |
| triangle counts and ensured efficient triangulation. Mesh LODs also help reduce |
| quad overdraw by lowering triangle counts for distant meshes.\n\n**[URP Modifications](URPModifications.md)**\n\nTo |
| optimize the device, we made minor URP code modifications. We replaced the Unity |
| BRDF with a more accurate approximation, improving lighting on shiny surfaces. |
| Shadowing improvements reduce shadow reception overhead and improve shadow texel |
| density. Some MSAA targets were switched to non-MSAA for efficiency. Rotating |
| reflection probes enhance reflection realism as the ship moves.\n\n**[Ocean LODs](OceanSystemDesignAndImplementation.md)**\n\nA |
| quadtree is generated around the camera, with deeper subdivisions nearby. An |
| 8x8 vertex ocean tile is drawn across each leaf node. To stitch tiles with neighbors, |
| many tiles with varying edge tessellations are generated and selected to match |
| edge vertices. Ocean displacement scales to 0 at the quadtree edge, with an ocean |
| skirting mesh extending to the horizon.\n\n\n\n### |
| Relevant Files\n- [QuadtreeRenderer.cs](https://github.com/meta-quest/Unity-UtilityPackages/blob/main/com.meta.utilities.environment/Runtime/Scripts/Water/QuadtreeRenderer.cs)\n\n**[Shadow |
| Importance Volumes](ShadowImportanceVolumes.md)**\n\nBy default, shadow maps |
| cover the camera frustum, extending the far plane to the maximum shadow distance. |
| The wide FOV (90 degrees or more) in VR means this range is large, often containing |
| only ocean or sky. Shadow Importance Volumes let designers specify surfaces needing |
| shadow coverage, clamping the shadow map projection to this space.\n\n**URP Configuration**\n\nSeemingly |
| minor URP configuration options can greatly impact scene rendering performance.\n\nTile-based |
| GPU architectures benefit from keeping resources in tile memory. Configuring |
| Depth Texture Mode as After Opaques ends the render pass to copy the depth buffer |
| to main memory. Setting depth as After Transparents defers depth resolve until |
| scene rendering finishes.\n\nSetting Post-processing Grading Mode to High Dynamic |
| Range allows Unity to bake tonemapping into the Color Grading LUT, removing the |
| tonemapper from the post-process pass.\n\nTo improve performance and control |
| reflection probe sampling, probe blending is disabled, and probes are manually |
| assigned to meshes. Each deck has its own Reflection Probe, and props on that |
| deck sample the same probe.\n\nUnity supports Light Layers for light filtering |
| within shaders. This feature's cost is minor, but since it's unnecessary and |
| increases shader variant counts, it was disabled.\n" |
| m_overrideMarkdownRoot: .\Documentation/ |
|
|