VolumeShader.js 13 KB

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