Last active
November 16, 2019 03:58
-
-
Save syuji-higa/b5e3c70ad049b2b0563150f900484fc4 to your computer and use it in GitHub Desktop.
Unity - Shader Raymarching
This file contains hidden or 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 "Unlit/Raymarching" | |
{ | |
Properties | |
{ | |
_MainTex ("Texture", 2D) = "white" {} | |
} | |
SubShader | |
{ | |
Tags { "Queue" = "Transparent" "RenderType" = "Transparent"} | |
Blend SrcAlpha OneMinusSrcAlpha | |
LOD 100 | |
Pass | |
{ | |
CGPROGRAM | |
#pragma vertex vert | |
#pragma fragment frag alpha:fade | |
// make fog work | |
#pragma multi_compile_fog | |
#include "UnityCG.cginc" | |
struct appdata | |
{ | |
float4 vertex : POSITION; | |
float2 uv : TEXCOORD0; | |
}; | |
struct v2f | |
{ | |
float2 uv : TEXCOORD0; | |
UNITY_FOG_COORDS(1) | |
float4 vertex : SV_POSITION; | |
}; | |
sampler2D _MainTex; | |
float4 _MainTex_ST; | |
v2f vert (appdata v) | |
{ | |
v2f o; | |
o.vertex = UnityObjectToClipPos(v.vertex); | |
o.uv = TRANSFORM_TEX(v.uv, _MainTex); | |
UNITY_TRANSFER_FOG(o,o.vertex); | |
return o; | |
} | |
float2x2 rot(float a){ | |
float s = sin(a), c = cos(a); | |
return float2x2(s,c,-c,s); | |
} | |
float df(float3 p){ | |
p.xy = mul(p.xy,rot(_Time.y)); | |
p.yz = mul(p.yz,rot(_Time.y)); | |
p.z += sin(_Time.y*5+p.x*20)/20; | |
p.x += sin(_Time.y*5+p.y*20)/20; | |
p.y += sin(_Time.y*5+p.x*20)/20; | |
float2 q = float2(length(p.xz)-.3,p.y*.3); | |
return length(q)-.1; | |
} | |
float3 norm(float3 p){ | |
float2 e = float2(.001,0); | |
float d = df(p); | |
return normalize(float3(d-df(p-e.xyy),d-df(p-e.yxy),d-df(p-e.yyx))); | |
} | |
float4 frag (v2f i) : SV_Target | |
{ | |
float2 R = _ScreenParams; | |
float2 p = (i.uv*R-R*.5)*2/R.xy; | |
float3 cp = float3(0,0,-1), | |
cu = float3(0,1,0), cf = float3(0,0,1), cl = cross(cu,cf), | |
ray = normalize(p.x*cl+p.y*cu+cf); | |
float4 c = float4(0,0,0,0); | |
float d, t = 0; | |
for(int i = 0; i < 128; i++){ | |
float3 rp = cp + t * ray; | |
t += d = df(rp); | |
if(d < .001){ | |
float3 no = norm(rp), lp = float3(-1,1,-1), ld = normalize(lp-rp); | |
float dif = dot(no,ld); | |
float spe = pow(max(dot(-ray,reflect(-ld,no)),0),16)*.8; | |
c = float4(float3(1,1,1) * dif + spe, 1); | |
break; | |
} | |
} | |
return c; | |
} | |
ENDCG | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment