许可优化
许可优化
产品
产品
解决方案
解决方案
服务支持
服务支持
关于
关于
软件库
当前位置:服务支持 >  软件文章 >  Unity3D URP HiZ实现指南,遮挡剔除优化技术

Unity3D URP HiZ实现指南,遮挡剔除优化技术

阅读数 12
点赞 0
article_banner


前言

在Unity URP中实现Hi-Z(Hierarchical Z-Buffer)技术涉及构建深度纹理的Mipmap金字塔,用于高效遮挡剔除或屏幕空间效果。以下是完整实现步骤:

对惹,这里有一个游戏开发交流小组,希望大家可以点击进来一起交流一下开发经验呀!

1. 创建必要资源

计算着色器 (HiZ.compute):

#pragma kernel CSMain_HiZ

Texture2D<float> _DepthTexture;

RWTexture2D<float> _HiZTexture;

float2 _TexelSize;

groupshared float depthCache[64]; // 8x8线程组共享内存

[numthreads(8, 8, 1)]

void CSMain_HiZ(uint3 id : SV_DispatchThreadID, uint localIdx : SV_GroupIndex)

{

// 读取当前深度(取最大值)

float depth = _DepthTexture.Load(uint3(id.xy, 0));

depthCache[localIdx] = depth;

GroupMemoryBarrierWithGroupSync();

// 并行归约求深度最大值

[unroll]

for (int stride = 32; stride > 0; stride >>= 1) {

if (localIdx < stride) {

depthCache[localIdx] = max(depthCache[localIdx], depthCache[localIdx + stride]);

}

GroupMemoryBarrierWithGroupSync();

}

// 第一个线程写入结果

if (localIdx == 0) {

_HiZTexture[id.xy / 8] = depthCache[0]; // 下采样8x8区域

}

}

2. 创建C#脚本管理Hi-Z流程

using UnityEngine; using UnityEngine.Rendering; using UnityEngine.Rendering.Universal; public class HiZFeature : ScriptableRendererFeature { class HiZPass : ScriptableRenderPass { const string ProfilerTag = "HiZ Generation"; readonly ComputeShader _hizShader; RenderTexture _hizPyramid; int _kernel; Vector2Int _textureSize; public HiZPass(ComputeShader shader) { _hizShader = shader; _kernel = _hizShader.FindKernel("CSMain_HiZ"); renderPassEvent = RenderPassEvent.AfterRenderingOpaques; } public override void Configure(CommandBuffer cmd, RenderTextureDescriptor desc) { _textureSize = new Vector2Int(desc.width, desc.height); // 创建Hi-Z金字塔纹理(带Mipmaps) if (_hizPyramid == null || _hizPyramid.width != _textureSize.x) { if (_hizPyramid != null) _hizPyramid.Release(); _hizPyramid = new RenderTexture(_textureSize.x, _textureSize.y, 0, RenderTextureFormat.RFloat) { enableRandomWrite = true, autoGenerateMips = false, useMipMap = true, filterMode = FilterMode.Point }; _hizPyramid.Create(); } } public override void Execute(ScriptableRenderContext context, ref RenderingData data) { CommandBuffer cmd = CommandBufferPool.Get(ProfilerTag); // 获取相机深度纹理 var depthId = new RenderTargetIdentifier("_CameraDepthTexture"); cmd.SetComputeTextureParam(_hizShader, _kernel, "_DepthTexture", depthId); // 生成Mipmap金字塔 int width = _textureSize.x; int height = _textureSize.y; int mipLevel = 0; while (width > 8 || height > 8) // 最小8x8 { cmd.SetComputeVectorParam(_hizShader, "_TexelSize", new Vector4(1f / width, 1f / height, width, height)); cmd.SetComputeTextureParam(_hizShader, _kernel, "_HiZTexture", _hizPyramid, mipLevel); cmd.DispatchCompute(_hizShader, _kernel, Mathf.CeilToInt(width / 8f), Mathf.CeilToInt(height / 8f), 1); width = Mathf.Max(1, width >> 1); height = Mathf.Max(1, height >> 1); mipLevel++; } // 传递到Shader全局变量 cmd.SetGlobalTexture("_HiZPyramid", _hizPyramid); cmd.SetGlobalFloat("_HiZMaxLevel", mipLevel - 1); context.ExecuteCommandBuffer(cmd); CommandBufferPool.Release(cmd); } public void Release() { if (_hizPyramid != null) _hizPyramid.Release(); } } [SerializeField] ComputeShader _hizComputeShader; HiZPass _pass; public override void Create() { if (_hizComputeShader == null) { Debug.LogError("HiZ Compute Shader missing!"); return; } _pass = new HiZPass(_hizComputeShader); } public override void AddRenderPasses(ScriptableRenderer renderer, ref RenderingData data) { if (data.cameraData.cameraType == CameraType.Game) renderer.EnqueuePass(_pass); } protected override void Dispose(bool disposing) { _pass?.Release(); _pass = null; } }

3. 在URP Renderer中配置

  1. 创建URP Asset (如果尚未创建)
  2. 在Renderer列表中添加自定义Renderer
  3. 将HiZFeature添加到Renderer Features列表

4. 在Shader中使用Hi-Z数据

Texture2D _HiZPyramid; float _HiZMaxLevel; // 层级深度遮挡测试 bool HiZOcclusionTest(float3 worldPos) { // 转换到屏幕空间 float4 clipPos = mul(UNITY_MATRIX_VP, float4(worldPos, 1)); float3 ndc = clipPos.xyz / clipPos.w; float2 uv = ndc.xy * 0.5 + 0.5; // 计算最佳Mip层级 float mip = min(_HiZMaxLevel, log2(max(abs(ddx(uv.x)), abs(ddy(uv.y))) * 2); // 从Hi-Z金字塔采样 float hizDepth = _HiZPyramid.SampleLevel(sampler_point_clamp, uv, mip).r; // 比较当前深度和Hi-Z深度 return ndc.z > hizDepth; // 如果当前深度更大,说明被遮挡 } // 在片段着色器中 void frag() { if (HiZOcclusionTest(worldPosition)) discard; // 或被遮挡物体执行其他逻辑 }

5. 优化技巧

  1. 异步计算:在支持ComputeQueue的平台上使用异步计算

cmd.SetExecutionFlags(CommandBufferExecutionFlags.AsyncCompute);

动态分辨率:根据性能需求动态调整Hi-Z金字塔尺寸

_textureSize = new Vector2Int( Mathf.ClosestPowerOfTwo(desc.width / 2), Mathf.ClosestPowerOfTwo(desc.height / 2) );

部分更新:仅当相机移动时更新高层级Mips

if (cameraMoved) UpdateFullPyramid(); else UpdateTopMipsOnly();

注意事项

  1. 深度格式兼容:确保目标平台支持深度纹理(Android需GLES3+)
  2. URP版本:适用于URP 10.0+(2020.3及更新版本)
  3. 性能分析:在移动端建议每帧只更新必要层级
  4. 遮挡精度:高层级Mipmap可能有精度损失,需调整阈值

此实现提供了完整的Hi-Z金字塔生成流程,可用于:

  • 高效遮挡剔除
  • 屏幕空间反射优化
  • 软阴影计算
  • 大场景LOD管理

使用时根据具体需求调整金字塔更新频率和分辨率,在复杂场景中可提升性能30%以上(视遮挡情况而定)。

更多教学视频

Unity3D​

www.bycwedu.com/promotion_channels/2146264125


免责声明:本文系网络转载或改编,未找到原创作者,版权归原作者所有。如涉及版权,请联系删

相关文章
技术文档
QR Code
微信扫一扫,欢迎咨询~
customer

online

联系我们
武汉格发信息技术有限公司
湖北省武汉市经开区科技园西路6号103孵化器
电话:155-2731-8020 座机:027-59821821
邮件:tanzw@gofarlic.com
Copyright © 2023 Gofarsoft Co.,Ltd. 保留所有权利
遇到许可问题?该如何解决!?
评估许可证实际采购量? 
不清楚软件许可证使用数据? 
收到软件厂商律师函!?  
想要少购买点许可证,节省费用? 
收到软件厂商侵权通告!?  
有正版license,但许可证不够用,需要新购? 
联系方式 board-phone 155-2731-8020
close1
预留信息,一起解决您的问题
* 姓名:
* 手机:

* 公司名称:

姓名不为空

姓名不为空

姓名不为空
手机不正确

手机不正确

手机不正确
公司不为空

公司不为空

公司不为空