強火で進め

このブログではプログラム関連の記事を中心に書いてます。

Unity 4.0 の新機能「3D (volume) texture」を使ってみた


※ 3D (volume) texture は対応していない環境では使用出来ません。ご注意下さい。

こちらの Unity の中の人のサンプルを参考にしました(ほとんど同じですがw)。

Unity 4 - 3D Textures (Volumes)
http://forum.unity3d.com/threads/148605-Unity-4-3D-Textures-%28Volumes%29

試して気になった点が1つ有ります。このデモは Cube に 3D texture を使ったのですが Scale の X,Y,Z の値が等しい時(スタート時)には uv が丁度、 0〜1 の範囲で一つの面を覆って居るのです。

Cube の Scale の値としては X,Y,Z 全てが3なので Volume テクスチャとしては3回パターンが繰り返しそうなのにその様にはなっていません。

しかし、ちょっとでも X,Y,Z が同じ Scale の値という状態が崩れると(Y方向のスケールを拡大した瞬間)3回パターンが繰り返すテクスチャとして描画されました。

3D texture ってそういうモノなんですかね?それともバグ?自分は 3D texture に詳しく無いので謎。ご存知の方、コメント貰えると嬉しいです。

今回のデモで使ったコード

プロジェクト全部を見たい場合はこちらからダウンロードして下さい。ここではプログラムの部分のみ書いておきます。

C# のコード。

【Create3DTex.cs】

using UnityEngine;
     
public class Create3DTex : MonoBehaviour
{
       
	private 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 = 1f - (Mathf.Abs(x-size * .5f) * 2f * mul);
					c.g = 1f - (Mathf.Abs(y-size * .5f) * 2f * mul);
					c.b = 1f - (Mathf.Abs(z-size * .5f) * 2f * mul);
					cols [idx] = c;
				}
			}
		}
		tex.SetPixels (cols);
		tex.Apply ();
		renderer.material.SetTexture ("_Volume", tex);
	}   
}

シェーダのコード。

【Sample3DTexture.shader】

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;
		    return o;
		}
		 
		sampler3D _Volume;
		 
		float4 frag (ps_input i) : COLOR
		{
		    return tex3D (_Volume, i.uv);
		}
		 
		ENDCG
		 
		}
	}
	 
	Fallback "VertexLit"
}