VolumeShader.js 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. /**
  2. * @author Almar Klein / http://almarklein.org
  3. *
  4. * Shaders to render 3D volumes using raycasting.
  5. * The applied techniques are based on similar implementations in the Visvis and Vispy projects.
  6. * This is not the only approach, therefore it's marked 1.
  7. */
  8. import {
  9. Vector2,
  10. Vector3
  11. } from "../../../build/three.module.js";
  12. var VolumeRenderShader1 = {
  13. uniforms: {
  14. "u_size": { value: new Vector3( 1, 1, 1 ) },
  15. "u_renderstyle": { value: 0 },
  16. "u_renderthreshold": { value: 0.5 },
  17. "u_clim": { value: new Vector2( 1, 1 ) },
  18. "u_data": { value: null },
  19. "u_cmdata": { value: null }
  20. },
  21. vertexShader: [
  22. " varying vec4 v_nearpos;",
  23. " varying vec4 v_farpos;",
  24. " varying vec3 v_position;",
  25. " void main() {",
  26. // Prepare transforms to map to "camera view". See also:
  27. // https://threejs.org/docs/#api/renderers/webgl/WebGLProgram
  28. " mat4 viewtransformf = modelViewMatrix;",
  29. " mat4 viewtransformi = inverse(modelViewMatrix);",
  30. // Project local vertex coordinate to camera position. Then do a step
  31. // backward (in cam coords) to the near clipping plane, and project back. Do
  32. // the same for the far clipping plane. This gives us all the information we
  33. // need to calculate the ray and truncate it to the viewing cone.
  34. " vec4 position4 = vec4(position, 1.0);",
  35. " vec4 pos_in_cam = viewtransformf * position4;",
  36. // Intersection of ray and near clipping plane (z = -1 in clip coords)
  37. " pos_in_cam.z = -pos_in_cam.w;",
  38. " v_nearpos = viewtransformi * pos_in_cam;",
  39. // Intersection of ray and far clipping plane (z = +1 in clip coords)
  40. " pos_in_cam.z = pos_in_cam.w;",
  41. " v_farpos = viewtransformi * pos_in_cam;",
  42. // Set varyings and output pos
  43. " v_position = position;",
  44. " gl_Position = projectionMatrix * viewMatrix * modelMatrix * position4;",
  45. " }",
  46. ].join( "\n" ),
  47. fragmentShader: [
  48. " precision highp float;",
  49. " precision mediump sampler3D;",
  50. " uniform vec3 u_size;",
  51. " uniform int u_renderstyle;",
  52. " uniform float u_renderthreshold;",
  53. " uniform vec2 u_clim;",
  54. " uniform sampler3D u_data;",
  55. " uniform sampler2D u_cmdata;",
  56. " varying vec3 v_position;",
  57. " varying vec4 v_nearpos;",
  58. " varying vec4 v_farpos;",
  59. // The maximum distance through our rendering volume is sqrt(3).
  60. " const int MAX_STEPS = 887; // 887 for 512^3, 1774 for 1024^3",
  61. " const int REFINEMENT_STEPS = 4;",
  62. " const float relative_step_size = 1.0;",
  63. " const vec4 ambient_color = vec4(0.2, 0.4, 0.2, 1.0);",
  64. " const vec4 diffuse_color = vec4(0.8, 0.2, 0.2, 1.0);",
  65. " const vec4 specular_color = vec4(1.0, 1.0, 1.0, 1.0);",
  66. " const float shininess = 40.0;",
  67. " void cast_mip(vec3 start_loc, vec3 step, int nsteps, vec3 view_ray);",
  68. " void cast_iso(vec3 start_loc, vec3 step, int nsteps, vec3 view_ray);",
  69. " float sample1(vec3 texcoords);",
  70. " vec4 apply_colormap(float val);",
  71. " vec4 add_lighting(float val, vec3 loc, vec3 step, vec3 view_ray);",
  72. " void main() {",
  73. // Normalize clipping plane info
  74. " vec3 farpos = v_farpos.xyz / v_farpos.w;",
  75. " vec3 nearpos = v_nearpos.xyz / v_nearpos.w;",
  76. // Calculate unit vector pointing in the view direction through this fragment.
  77. " vec3 view_ray = normalize(nearpos.xyz - farpos.xyz);",
  78. // Compute the (negative) distance to the front surface or near clipping plane.
  79. // v_position is the back face of the cuboid, so the initial distance calculated in the dot
  80. // product below is the distance from near clip plane to the back of the cuboid
  81. " float distance = dot(nearpos - v_position, view_ray);",
  82. " distance = max(distance, min((-0.5 - v_position.x) / view_ray.x,",
  83. " (u_size.x - 0.5 - v_position.x) / view_ray.x));",
  84. " distance = max(distance, min((-0.5 - v_position.y) / view_ray.y,",
  85. " (u_size.y - 0.5 - v_position.y) / view_ray.y));",
  86. " distance = max(distance, min((-0.5 - v_position.z) / view_ray.z,",
  87. " (u_size.z - 0.5 - v_position.z) / view_ray.z));",
  88. // Now we have the starting position on the front surface
  89. " vec3 front = v_position + view_ray * distance;",
  90. // Decide how many steps to take
  91. " int nsteps = int(-distance / relative_step_size + 0.5);",
  92. " if ( nsteps < 1 )",
  93. " discard;",
  94. // Get starting location and step vector in texture coordinates
  95. " vec3 step = ((v_position - front) / u_size) / float(nsteps);",
  96. " vec3 start_loc = front / u_size;",
  97. // For testing: show the number of steps. This helps to establish
  98. // whether the rays are correctly oriented
  99. //'gl_FragColor = vec4(0.0, float(nsteps) / 1.0 / u_size.x, 1.0, 1.0);',
  100. //'return;',
  101. " if (u_renderstyle == 0)",
  102. " cast_mip(start_loc, step, nsteps, view_ray);",
  103. " else if (u_renderstyle == 1)",
  104. " cast_iso(start_loc, step, nsteps, view_ray);",
  105. " if (gl_FragColor.a < 0.05)",
  106. " discard;",
  107. " }",
  108. " float sample1(vec3 texcoords) {",
  109. " /* Sample float value from a 3D texture. Assumes intensity data. */",
  110. " return texture(u_data, texcoords.xyz).r;",
  111. " }",
  112. " vec4 apply_colormap(float val) {",
  113. " val = (val - u_clim[0]) / (u_clim[1] - u_clim[0]);",
  114. " return texture2D(u_cmdata, vec2(val, 0.5));",
  115. " }",
  116. " void cast_mip(vec3 start_loc, vec3 step, int nsteps, vec3 view_ray) {",
  117. " float max_val = -1e6;",
  118. " int max_i = 100;",
  119. " vec3 loc = start_loc;",
  120. // Enter the raycasting loop. In WebGL 1 the loop index cannot be compared with
  121. // non-constant expression. So we use a hard-coded max, and an additional condition
  122. // inside the loop.
  123. " for (int iter=0; iter<MAX_STEPS; iter++) {",
  124. " if (iter >= nsteps)",
  125. " break;",
  126. // Sample from the 3D texture
  127. " float val = sample1(loc);",
  128. // Apply MIP operation
  129. " if (val > max_val) {",
  130. " max_val = val;",
  131. " max_i = iter;",
  132. " }",
  133. // Advance location deeper into the volume
  134. " loc += step;",
  135. " }",
  136. // Refine location, gives crispier images
  137. " vec3 iloc = start_loc + step * (float(max_i) - 0.5);",
  138. " vec3 istep = step / float(REFINEMENT_STEPS);",
  139. " for (int i=0; i<REFINEMENT_STEPS; i++) {",
  140. " max_val = max(max_val, sample1(iloc));",
  141. " iloc += istep;",
  142. " }",
  143. // Resolve final color
  144. " gl_FragColor = apply_colormap(max_val);",
  145. " }",
  146. " void cast_iso(vec3 start_loc, vec3 step, int nsteps, vec3 view_ray) {",
  147. " gl_FragColor = vec4(0.0); // init transparent",
  148. " vec4 color3 = vec4(0.0); // final color",
  149. " vec3 dstep = 1.5 / u_size; // step to sample derivative",
  150. " vec3 loc = start_loc;",
  151. " float low_threshold = u_renderthreshold - 0.02 * (u_clim[1] - u_clim[0]);",
  152. // Enter the raycasting loop. In WebGL 1 the loop index cannot be compared with
  153. // non-constant expression. So we use a hard-coded max, and an additional condition
  154. // inside the loop.
  155. " for (int iter=0; iter<MAX_STEPS; iter++) {",
  156. " if (iter >= nsteps)",
  157. " break;",
  158. // Sample from the 3D texture
  159. " float val = sample1(loc);",
  160. " if (val > low_threshold) {",
  161. // Take the last interval in smaller steps
  162. " vec3 iloc = loc - 0.5 * step;",
  163. " vec3 istep = step / float(REFINEMENT_STEPS);",
  164. " for (int i=0; i<REFINEMENT_STEPS; i++) {",
  165. " val = sample1(iloc);",
  166. " if (val > u_renderthreshold) {",
  167. " gl_FragColor = add_lighting(val, iloc, dstep, view_ray);",
  168. " return;",
  169. " }",
  170. " iloc += istep;",
  171. " }",
  172. " }",
  173. // Advance location deeper into the volume
  174. " loc += step;",
  175. " }",
  176. " }",
  177. " vec4 add_lighting(float val, vec3 loc, vec3 step, vec3 view_ray)",
  178. " {",
  179. // Calculate color by incorporating lighting
  180. // View direction
  181. " vec3 V = normalize(view_ray);",
  182. // calculate normal vector from gradient
  183. " vec3 N;",
  184. " float val1, val2;",
  185. " val1 = sample1(loc + vec3(-step[0], 0.0, 0.0));",
  186. " val2 = sample1(loc + vec3(+step[0], 0.0, 0.0));",
  187. " N[0] = val1 - val2;",
  188. " val = max(max(val1, val2), val);",
  189. " val1 = sample1(loc + vec3(0.0, -step[1], 0.0));",
  190. " val2 = sample1(loc + vec3(0.0, +step[1], 0.0));",
  191. " N[1] = val1 - val2;",
  192. " val = max(max(val1, val2), val);",
  193. " val1 = sample1(loc + vec3(0.0, 0.0, -step[2]));",
  194. " val2 = sample1(loc + vec3(0.0, 0.0, +step[2]));",
  195. " N[2] = val1 - val2;",
  196. " val = max(max(val1, val2), val);",
  197. " float gm = length(N); // gradient magnitude",
  198. " N = normalize(N);",
  199. // Flip normal so it points towards viewer
  200. " float Nselect = float(dot(N, V) > 0.0);",
  201. " N = (2.0 * Nselect - 1.0) * N; // == Nselect * N - (1.0-Nselect)*N;",
  202. // Init colors
  203. " vec4 ambient_color = vec4(0.0, 0.0, 0.0, 0.0);",
  204. " vec4 diffuse_color = vec4(0.0, 0.0, 0.0, 0.0);",
  205. " vec4 specular_color = vec4(0.0, 0.0, 0.0, 0.0);",
  206. // note: could allow multiple lights
  207. " for (int i=0; i<1; i++)",
  208. " {",
  209. // Get light direction (make sure to prevent zero devision)
  210. " vec3 L = normalize(view_ray); //lightDirs[i];",
  211. " float lightEnabled = float( length(L) > 0.0 );",
  212. " L = normalize(L + (1.0 - lightEnabled));",
  213. // Calculate lighting properties
  214. " float lambertTerm = clamp(dot(N, L), 0.0, 1.0);",
  215. " vec3 H = normalize(L+V); // Halfway vector",
  216. " float specularTerm = pow(max(dot(H, N), 0.0), shininess);",
  217. // Calculate mask
  218. " float mask1 = lightEnabled;",
  219. // Calculate colors
  220. " ambient_color += mask1 * ambient_color; // * gl_LightSource[i].ambient;",
  221. " diffuse_color += mask1 * lambertTerm;",
  222. " specular_color += mask1 * specularTerm * specular_color;",
  223. " }",
  224. // Calculate final color by componing different components
  225. " vec4 final_color;",
  226. " vec4 color = apply_colormap(val);",
  227. " final_color = color * (ambient_color + diffuse_color) + specular_color;",
  228. " final_color.a = color.a;",
  229. " return final_color;",
  230. " }",
  231. ].join( "\n" )
  232. };
  233. export { VolumeRenderShader1 };