代码来自Aras
Texture3D必须要在脚本中创建
c#:
<span style="font-size:14px;"> using UnityEngine; public class Create3DTex : MonoBehaviour { public Texture3D tex; public int size = 16; void Start () { tex = new Texture3D (size, size, size, TextureFormat.ARGB32, true); var cols = new Color[size*size*size]; float mul = 1.0f / (size-1); int idx = 0; Color c = Color.white; for (int z = 0; z < size; ++z) { for (int y = 0; y < size; ++y) { for (int x = 0; x < size; ++x, ++idx) { c.r = ((x1)!=0) ? x*mul : 1-x*mul; c.g = ((y1)!=0) ? y*mul : 1-y*mul; c.b = ((z1)!=0) ? z*mul : 1-z*mul; cols[idx] = c; } } } tex.SetPixels (cols); tex.Apply (); renderer.material.SetTexture ("_Volume", tex); } } </span>JS:
<span style="font-size:14px;">function CreateIdentityLut (dim : int, tex3D : Texture3D) { var newC : Color[] = new Color[dim * dim * dim]; var oneOverDim : float = 1.0f / (1.0f * dim - 1.0f); for(var i : int = 0; i < dim; i++) { for(var j : int = 0; j < dim; j++) { for(var k : int = 0; k < dim; k++) { newC[i + (j*dim) + (k*dim*dim)] = new Color((i*1.0f)*oneOverDim, (j*1.0f)*oneOverDim, (k*1.0f)*oneOverDim, 1.0f); } } } tex3D.SetPixels (newC); tex3D.Apply (); } </span>
shader:
<span style="font-size:14px;"> Shader "DX11/Sample 3D Texture" { Properties { _Volume ("Texture", 3D) = "" {} } SubShader { Pass { CGPROGRAM #pragma vertex vert #pragma fragment frag #pragma exclude_renderers flash gles #include "UnityCG.cginc" struct vs_input { float4 vertex : POSITION; }; struct ps_input { float4 pos : SV_POSITION; float3 uv : TEXCOORD0; }; ps_input vert (vs_input v) { ps_input o; o.pos = mul (UNITY_MATRIX_MVP, v.vertex); o.uv = v.vertex.xyz*0.5+0.5; return o; } sampler3D _Volume; float4 frag (ps_input i) : COLOR { return tex3D (_Volume, i.uv); } ENDCG } } Fallback "VertexLit" } </span>