Last active
October 5, 2019 12:09
-
-
Save tar-bin/891ce1735d98809da6bc9bd1b9b2cb30 to your computer and use it in GitHub Desktop.
Unityシェーダー学習:ライフゲーム(CustomRenderTexture用)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Shader "Tarbin/Lifegame" | |
{ | |
Properties | |
{ | |
_InputTex("InputTex", 2D) = "white" {} | |
} | |
SubShader | |
{ | |
Cull Off ZWrite Off ZTest Always | |
Pass | |
{ | |
Name "Update" | |
CGPROGRAM | |
#include "UnityCustomRenderTexture.cginc" | |
// 頂点シェーダは決まったものを使う | |
#pragma vertex CustomRenderTextureVertexShader | |
#pragma fragment frag | |
sampler2D _InputTex; | |
float4 frag(v2f_customrendertexture i) : SV_Target | |
{ | |
// 1Pixelあたりのオフセット | |
float dx = 1 / _CustomRenderTextureWidth; | |
float dy = 1 / _CustomRenderTextureHeight; | |
// 描画位置 | |
float2 uv = i.globalTexcoord; | |
// 前回状態 | |
float4 selfTex = tex2D(_SelfTexture2D, uv); | |
// 更新タイミングでなければ前回のまま | |
if ((sin(_Time.w * 30) + 1.0)*.5 * 30 > 1) { | |
return selfTex; | |
} | |
float3x3 lifeMat = step(0.5, float3x3( | |
tex2D(_SelfTexture2D, float2(uv.x - dx, uv.y - dy)).r, tex2D(_SelfTexture2D, float2(uv.x, uv.y - dy)).r, tex2D(_SelfTexture2D, float2(uv.x + dx, uv.y - dy)).r, | |
tex2D(_SelfTexture2D, float2(uv.x - dx, uv.y )).r, 0.0, tex2D(_SelfTexture2D, float2(uv.x + dx, uv.y )).r, | |
tex2D(_SelfTexture2D, float2(uv.x - dx, uv.y + dy)).r, tex2D(_SelfTexture2D, float2(uv.x, uv.y + dy)).r, tex2D(_SelfTexture2D, float2(uv.x + dx, uv.y + dy)).r)); | |
float lifeRes = lifeMat[0][0] + lifeMat[0][1] + lifeMat[0][2] | |
+ lifeMat[1][0] + lifeMat[1][1] + lifeMat[1][2] | |
+ lifeMat[2][0] + lifeMat[2][1] + lifeMat[2][2]; | |
if (selfTex.r < 0.5) { | |
// 誕生:現在が死亡 + 隣接セルが3つ | |
if (lifeRes > 2.5 && lifeRes < 3.5) { | |
selfTex.r = 1; | |
} | |
} else if (lifeRes > 1.5 && lifeRes < 3.5) { | |
// 生存:現在が生存 + 隣接セルが2or3つ | |
selfTex.r = 1; | |
// 世代カウンタ+1 | |
selfTex.g += dx; | |
} else { | |
// 過疎:現在が生存 + 隣接セルが1以下 | |
// 過密:現在が生存 + 隣接セルが4以上 | |
selfTex.r = 0; | |
// 世代カウンタリセット | |
selfTex.g = 0; | |
} | |
// カメラからの入力を上書き | |
float biasTex = tex2D(_InputTex, uv).r; | |
if (biasTex > 0.5) { | |
selfTex.r = 1; | |
} | |
return selfTex; | |
} | |
ENDCG | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment