1
+ //In Unity3D editor, add 3D Object/Quad to Main Camera, then bind material with shader to the quad. Set quad position at (x=0 ; y=0; z=0.4;).
2
+ // Apply fly script to the camera and cubemap to material. Play.
3
+ Shader "Raymarching Cubemap"
4
+ {
5
+ Properties
6
+ {
7
+ _Cube( "Environment Map" , Cube ) = "" {}
8
+ }
9
+ Subshader
10
+ {
11
+ Pass
12
+ {
13
+ CGPROGRAM
14
+ #pragma vertex vertex_shader
15
+ #pragma fragment pixel_shader
16
+ #pragma target 3.0
17
+
18
+ uniform samplerCUBE _Cube;
19
+
20
+ struct custom_type
21
+ {
22
+ float4 screen_vertex : SV_POSITION ;
23
+ float3 world_vertex : TEXCOORD1 ;
24
+ };
25
+
26
+ float sphere (float3 p,float3 c,float r)
27
+ {
28
+ return distance (p,c)-r;
29
+ }
30
+
31
+ float map (float3 p)
32
+ {
33
+ return sphere (p,float3 (0 ,0 ,0 ),2.0 );
34
+ }
35
+
36
+ float3 set_normal (float3 p)
37
+ {
38
+ float3 x = float3 (0.001 ,0.000 ,0.000 );
39
+ float3 y = float3 (0.000 ,0.001 ,0.000 );
40
+ float3 z = float3 (0.000 ,0.000 ,0.001 );
41
+ return normalize (float3 (map (p+x)-map (p-x),map (p+y)-map (p-y),map (p+z)-map (p-z)));
42
+ }
43
+
44
+ float4 raymarch (float3 ro, float3 rd)
45
+ {
46
+ for (int i=0 ; i<64 ; i++)
47
+ {
48
+ float t = map (ro);
49
+ if (t < 0.001 )
50
+ {
51
+ rd=reflect (rd,set_normal (ro));
52
+ return texCUBElod (_Cube,float4 (rd,0.0 ));
53
+ }
54
+ else ro+=t*rd;
55
+ }
56
+ return texCUBE (_Cube,rd);
57
+ }
58
+
59
+ custom_type vertex_shader (float4 vertex:POSITION )
60
+ {
61
+ custom_type vs;
62
+ vs.screen_vertex = UnityObjectToClipPos (vertex);
63
+ vs.world_vertex = mul (unity_ObjectToWorld ,vertex);
64
+ return vs;
65
+ }
66
+
67
+ float4 pixel_shader (custom_type ps ):SV_TARGET
68
+ {
69
+ float3 worldPosition = ps.world_vertex;
70
+ float3 viewDirection = normalize (ps.world_vertex-_WorldSpaceCameraPos .xyz);
71
+ return raymarch (worldPosition,viewDirection);
72
+ }
73
+
74
+ ENDCG
75
+
76
+ }
77
+ }
78
+ }
0 commit comments