shader-code.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. /**
  2. * Copyright (c) 2018-2021 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * @author Alexander Rose <alexander.rose@weirdbyte.de>
  5. */
  6. import { ValueCell } from '../mol-util';
  7. import { idFactory } from '../mol-util/id-factory';
  8. import { WebGLExtensions } from './webgl/extensions';
  9. import { isWebGL2, GLRenderingContext } from './webgl/compat';
  10. export type DefineKind = 'boolean' | 'string' | 'number'
  11. export type DefineType = boolean | string
  12. export type DefineValues = { [k: string]: ValueCell<DefineType> }
  13. const shaderCodeId = idFactory();
  14. type ShaderExtensionsValue = 'required' | 'optional'
  15. export interface ShaderExtensions {
  16. readonly standardDerivatives?: ShaderExtensionsValue
  17. readonly fragDepth?: ShaderExtensionsValue
  18. readonly drawBuffers?: ShaderExtensionsValue
  19. readonly shaderTextureLod?: ShaderExtensionsValue
  20. }
  21. type FragOutTypes = { [k in number]: 'vec4' | 'ivec4' }
  22. export interface ShaderCode {
  23. readonly id: number
  24. readonly name: string
  25. readonly vert: string
  26. readonly frag: string
  27. readonly extensions: ShaderExtensions
  28. /** Fragment shader output type only applicable for webgl2 */
  29. readonly outTypes: FragOutTypes
  30. }
  31. import { apply_fog } from './shader/chunks/apply-fog.glsl';
  32. import { apply_interior_color } from './shader/chunks/apply-interior-color.glsl';
  33. import { apply_light_color } from './shader/chunks/apply-light-color.glsl';
  34. import { apply_marker_color } from './shader/chunks/apply-marker-color.glsl';
  35. import { assign_clipping_varying } from './shader/chunks/assign-clipping-varying.glsl';
  36. import { assign_color_varying } from './shader/chunks/assign-color-varying.glsl';
  37. import { assign_group } from './shader/chunks/assign-group.glsl';
  38. import { assign_marker_varying } from './shader/chunks/assign-marker-varying.glsl';
  39. import { assign_material_color } from './shader/chunks/assign-material-color.glsl';
  40. import { assign_position } from './shader/chunks/assign-position.glsl';
  41. import { assign_size } from './shader/chunks/assign-size.glsl';
  42. import { check_picking_alpha } from './shader/chunks/check-picking-alpha.glsl';
  43. import { clip_instance } from './shader/chunks/clip-instance.glsl';
  44. import { clip_pixel } from './shader/chunks/clip-pixel.glsl';
  45. import { color_frag_params } from './shader/chunks/color-frag-params.glsl';
  46. import { color_vert_params } from './shader/chunks/color-vert-params.glsl';
  47. import { common_clip } from './shader/chunks/common-clip.glsl';
  48. import { common_frag_params } from './shader/chunks/common-frag-params.glsl';
  49. import { common_vert_params } from './shader/chunks/common-vert-params.glsl';
  50. import { common } from './shader/chunks/common.glsl';
  51. import { float_to_rgba } from './shader/chunks/float-to-rgba.glsl';
  52. import { light_frag_params } from './shader/chunks/light-frag-params.glsl';
  53. import { matrix_scale } from './shader/chunks/matrix-scale.glsl';
  54. import { normal_frag_params } from './shader/chunks/normal-frag-params.glsl';
  55. import { read_from_texture } from './shader/chunks/read-from-texture.glsl';
  56. import { rgba_to_float } from './shader/chunks/rgba-to-float.glsl';
  57. import { size_vert_params } from './shader/chunks/size-vert-params.glsl';
  58. import { texture3d_from_1d_trilinear } from './shader/chunks/texture3d-from-1d-trilinear.glsl';
  59. import { texture3d_from_2d_linear } from './shader/chunks/texture3d-from-2d-linear.glsl';
  60. import { texture3d_from_2d_nearest } from './shader/chunks/texture3d-from-2d-nearest.glsl';
  61. import { wboit_params } from './shader/chunks/wboit-params.glsl';
  62. import { wboit_write } from './shader/chunks/wboit-write.glsl';
  63. const ShaderChunks: { [k: string]: string } = {
  64. apply_fog,
  65. apply_interior_color,
  66. apply_light_color,
  67. apply_marker_color,
  68. assign_clipping_varying,
  69. assign_color_varying,
  70. assign_group,
  71. assign_marker_varying,
  72. assign_material_color,
  73. assign_position,
  74. assign_size,
  75. check_picking_alpha,
  76. clip_instance,
  77. clip_pixel,
  78. color_frag_params,
  79. color_vert_params,
  80. common_clip,
  81. common_frag_params,
  82. common_vert_params,
  83. common,
  84. float_to_rgba,
  85. light_frag_params,
  86. matrix_scale,
  87. normal_frag_params,
  88. read_from_texture,
  89. rgba_to_float,
  90. size_vert_params,
  91. texture3d_from_1d_trilinear,
  92. texture3d_from_2d_linear,
  93. texture3d_from_2d_nearest,
  94. wboit_params,
  95. wboit_write
  96. };
  97. const reInclude = /^(?!\/\/)\s*#include\s+(\S+)/gmi;
  98. const reSingleLineComment = /[ \t]*\/\/.*\n/g;
  99. const reMultiLineComment = /[ \t]*\/\*[\s\S]*?\*\//g;
  100. const reMultipleLinebreaks = /\n{2,}/g;
  101. function addIncludes(text: string) {
  102. return text
  103. .replace(reInclude, (_, p1) => {
  104. const chunk = ShaderChunks[p1];
  105. if (!chunk) throw new Error(`empty chunk, '${p1}'`);
  106. return chunk;
  107. })
  108. .trim()
  109. .replace(reSingleLineComment, '\n')
  110. .replace(reMultiLineComment, '\n')
  111. .replace(reMultipleLinebreaks, '\n');
  112. }
  113. export function ShaderCode(name: string, vert: string, frag: string, extensions: ShaderExtensions = {}, outTypes: FragOutTypes = {}): ShaderCode {
  114. return { id: shaderCodeId(), name, vert: addIncludes(vert), frag: addIncludes(frag), extensions, outTypes };
  115. }
  116. // Note: `drawBuffers` need to be 'optional' for wboit
  117. import { points_vert } from './shader/points.vert';
  118. import { points_frag } from './shader/points.frag';
  119. export const PointsShaderCode = ShaderCode('points', points_vert, points_frag, { drawBuffers: 'optional' });
  120. import { spheres_vert } from './shader/spheres.vert';
  121. import { spheres_frag } from './shader/spheres.frag';
  122. export const SpheresShaderCode = ShaderCode('spheres', spheres_vert, spheres_frag, { fragDepth: 'required', drawBuffers: 'optional' });
  123. import { cylinders_vert } from './shader/cylinders.vert';
  124. import { cylinders_frag } from './shader/cylinders.frag';
  125. export const CylindersShaderCode = ShaderCode('cylinders', cylinders_vert, cylinders_frag, { fragDepth: 'required', drawBuffers: 'optional' });
  126. import { text_vert }from './shader/text.vert';
  127. import { text_frag } from './shader/text.frag';
  128. export const TextShaderCode = ShaderCode('text', text_vert, text_frag, { standardDerivatives: 'required', drawBuffers: 'optional' });
  129. import { lines_vert } from './shader/lines.vert';
  130. import { lines_frag } from './shader/lines.frag';
  131. export const LinesShaderCode = ShaderCode('lines', lines_vert, lines_frag, { drawBuffers: 'optional' });
  132. import { mesh_vert } from './shader/mesh.vert';
  133. import { mesh_frag } from './shader/mesh.frag';
  134. export const MeshShaderCode = ShaderCode('mesh', mesh_vert, mesh_frag, { standardDerivatives: 'optional', drawBuffers: 'optional' });
  135. import { directVolume_vert } from './shader/direct-volume.vert';
  136. import { directVolume_frag } from './shader/direct-volume.frag';
  137. export const DirectVolumeShaderCode = ShaderCode('direct-volume', directVolume_vert, directVolume_frag, { fragDepth: 'optional', drawBuffers: 'optional' });
  138. import { image_vert } from './shader/image.vert';
  139. import { image_frag } from './shader/image.frag';
  140. export const ImageShaderCode = ShaderCode('image', image_vert, image_frag, { drawBuffers: 'optional' });
  141. //
  142. export type ShaderDefines = {
  143. [k: string]: ValueCell<DefineType>
  144. }
  145. function getDefinesCode(defines: ShaderDefines) {
  146. if (defines === undefined) return '';
  147. const lines = [];
  148. for (const name in defines) {
  149. const define = defines[name];
  150. const v = define.ref.value;
  151. if (v !== undefined) {
  152. if (typeof v === 'string') {
  153. lines.push(`#define ${name}_${v}`);
  154. } else if (typeof v === 'number') {
  155. lines.push(`#define ${name} ${v}`);
  156. } else if (typeof v === 'boolean') {
  157. if (v) lines.push(`#define ${name}`);
  158. } else {
  159. throw new Error('unknown define type');
  160. }
  161. }
  162. }
  163. return lines.join('\n') + '\n';
  164. }
  165. function getGlsl100FragPrefix(extensions: WebGLExtensions, shaderExtensions: ShaderExtensions) {
  166. const prefix: string[] = [];
  167. if (shaderExtensions.standardDerivatives) {
  168. prefix.push('#extension GL_OES_standard_derivatives : enable');
  169. prefix.push('#define enabledStandardDerivatives');
  170. }
  171. if (shaderExtensions.fragDepth) {
  172. if (extensions.fragDepth) {
  173. prefix.push('#extension GL_EXT_frag_depth : enable');
  174. prefix.push('#define enabledFragDepth');
  175. } else if (shaderExtensions.fragDepth === 'required') {
  176. throw new Error(`required 'GL_EXT_frag_depth' extension not available`);
  177. }
  178. }
  179. if (shaderExtensions.drawBuffers) {
  180. if (extensions.drawBuffers) {
  181. prefix.push('#extension GL_EXT_draw_buffers : require');
  182. prefix.push('#define requiredDrawBuffers');
  183. prefix.push('#define gl_FragColor gl_FragData[0]');
  184. } else if (shaderExtensions.drawBuffers === 'required') {
  185. throw new Error(`required 'GL_EXT_draw_buffers' extension not available`);
  186. }
  187. }
  188. if (shaderExtensions.shaderTextureLod) {
  189. if (extensions.shaderTextureLod) {
  190. prefix.push('#extension GL_EXT_shader_texture_lod : enable');
  191. prefix.push('#define enabledShaderTextureLod');
  192. } else if (shaderExtensions.shaderTextureLod === 'required') {
  193. throw new Error(`required 'GL_EXT_shader_texture_lod' extension not available`);
  194. }
  195. }
  196. if (extensions.depthTexture) {
  197. prefix.push('#define depthTextureSupport');
  198. }
  199. return prefix.join('\n') + '\n';
  200. }
  201. const glsl300VertPrefix = `#version 300 es
  202. #define attribute in
  203. #define varying out
  204. #define texture2D texture
  205. `;
  206. const glsl300FragPrefixCommon = `
  207. #define varying in
  208. #define texture2D texture
  209. #define texture2DLodEXT textureLod
  210. #define gl_FragColor out_FragData0
  211. #define gl_FragDepthEXT gl_FragDepth
  212. #define depthTextureSupport
  213. `;
  214. function getGlsl300FragPrefix(gl: WebGL2RenderingContext, extensions: WebGLExtensions, shaderExtensions: ShaderExtensions, outTypes: FragOutTypes) {
  215. const prefix = [
  216. '#version 300 es',
  217. `layout(location = 0) out highp ${outTypes[0] || 'vec4'} out_FragData0;`
  218. ];
  219. if (shaderExtensions.standardDerivatives) {
  220. prefix.push('#define enabledStandardDerivatives');
  221. }
  222. if (shaderExtensions.fragDepth) {
  223. prefix.push('#define enabledFragDepth');
  224. }
  225. if (shaderExtensions.drawBuffers) {
  226. prefix.push('#define requiredDrawBuffers');
  227. const maxDrawBuffers = gl.getParameter(gl.MAX_DRAW_BUFFERS) as number;
  228. for (let i = 1, il = maxDrawBuffers; i < il; ++i) {
  229. prefix.push(`layout(location = ${i}) out highp ${outTypes[i] || 'vec4'} out_FragData${i};`);
  230. }
  231. }
  232. if (shaderExtensions.shaderTextureLod) {
  233. prefix.push('#define enabledShaderTextureLod');
  234. }
  235. prefix.push(glsl300FragPrefixCommon);
  236. return prefix.join('\n') + '\n';
  237. }
  238. function transformGlsl300Frag(frag: string) {
  239. return frag.replace(/gl_FragData\[([0-9]+)\]/g, 'out_FragData$1');
  240. }
  241. export function addShaderDefines(gl: GLRenderingContext, extensions: WebGLExtensions, defines: ShaderDefines, shaders: ShaderCode): ShaderCode {
  242. const header = getDefinesCode(defines);
  243. const vertPrefix = isWebGL2(gl) ? glsl300VertPrefix : '';
  244. const fragPrefix = isWebGL2(gl)
  245. ? getGlsl300FragPrefix(gl, extensions, shaders.extensions, shaders.outTypes)
  246. : getGlsl100FragPrefix(extensions, shaders.extensions);
  247. const frag = isWebGL2(gl) ? transformGlsl300Frag(shaders.frag) : shaders.frag;
  248. return {
  249. id: shaderCodeId(),
  250. name: shaders.name,
  251. vert: `${vertPrefix}${header}${shaders.vert}`,
  252. frag: `${fragPrefix}${header}${frag}`,
  253. extensions: shaders.extensions,
  254. outTypes: shaders.outTypes
  255. };
  256. }