ShaderUtils.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666
  1. /**
  2. * @author alteredq / http://alteredqualia.com/
  3. * @author mr.doob / http://mrdoob.com/
  4. */
  5. if ( THREE.WebGLRenderer ) {
  6. THREE.ShaderUtils = {
  7. lib: {
  8. /* -------------------------------------------------------------------------
  9. // Fresnel shader
  10. // - based on Nvidia Cg tutorial
  11. ------------------------------------------------------------------------- */
  12. 'fresnel': {
  13. uniforms: {
  14. "mRefractionRatio": { type: "f", value: 1.02 },
  15. "mFresnelBias": { type: "f", value: 0.1 },
  16. "mFresnelPower": { type: "f", value: 2.0 },
  17. "mFresnelScale": { type: "f", value: 1.0 },
  18. "tCube": { type: "t", value: 1, texture: null }
  19. },
  20. fragmentShader: [
  21. "uniform samplerCube tCube;",
  22. "varying vec3 vReflect;",
  23. "varying vec3 vRefract[3];",
  24. "varying float vReflectionFactor;",
  25. "void main() {",
  26. "vec4 reflectedColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  27. "vec4 refractedColor = vec4( 1.0, 1.0, 1.0, 1.0 );",
  28. "refractedColor.r = textureCube( tCube, vec3( -vRefract[0].x, vRefract[0].yz ) ).r;",
  29. "refractedColor.g = textureCube( tCube, vec3( -vRefract[1].x, vRefract[1].yz ) ).g;",
  30. "refractedColor.b = textureCube( tCube, vec3( -vRefract[2].x, vRefract[2].yz ) ).b;",
  31. "refractedColor.a = 1.0;",
  32. "gl_FragColor = mix( refractedColor, reflectedColor, clamp( vReflectionFactor, 0.0, 1.0 ) );",
  33. "}"
  34. ].join("\n"),
  35. vertexShader: [
  36. "uniform float mRefractionRatio;",
  37. "uniform float mFresnelBias;",
  38. "uniform float mFresnelScale;",
  39. "uniform float mFresnelPower;",
  40. "varying vec3 vReflect;",
  41. "varying vec3 vRefract[3];",
  42. "varying float vReflectionFactor;",
  43. "void main() {",
  44. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  45. "vec4 mPosition = objectMatrix * vec4( position, 1.0 );",
  46. "vec3 nWorld = normalize ( mat3( objectMatrix[0].xyz, objectMatrix[1].xyz, objectMatrix[2].xyz ) * normal );",
  47. "vec3 I = mPosition.xyz - cameraPosition;",
  48. "vReflect = reflect( I, nWorld );",
  49. "vRefract[0] = refract( normalize( I ), nWorld, mRefractionRatio );",
  50. "vRefract[1] = refract( normalize( I ), nWorld, mRefractionRatio * 0.99 );",
  51. "vRefract[2] = refract( normalize( I ), nWorld, mRefractionRatio * 0.98 );",
  52. "vReflectionFactor = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( I ), nWorld ), mFresnelPower );",
  53. "gl_Position = projectionMatrix * mvPosition;",
  54. "}"
  55. ].join("\n")
  56. },
  57. /* -------------------------------------------------------------------------
  58. // Normal map shader
  59. // - Blinn-Phong
  60. // - normal + diffuse + specular + AO + displacement maps
  61. // - point and directional lights (use with "lights: true" material option)
  62. ------------------------------------------------------------------------- */
  63. 'normal' : {
  64. uniforms: THREE.UniformsUtils.merge( [
  65. THREE.UniformsLib[ "fog" ],
  66. THREE.UniformsLib[ "lights" ],
  67. {
  68. "enableAO" : { type: "i", value: 0 },
  69. "enableDiffuse" : { type: "i", value: 0 },
  70. "enableSpecular": { type: "i", value: 0 },
  71. "tDiffuse" : { type: "t", value: 0, texture: null },
  72. "tNormal" : { type: "t", value: 2, texture: null },
  73. "tSpecular" : { type: "t", value: 3, texture: null },
  74. "tAO" : { type: "t", value: 4, texture: null },
  75. "uNormalScale": { type: "f", value: 1.0 },
  76. "tDisplacement": { type: "t", value: 5, texture: null },
  77. "uDisplacementBias": { type: "f", value: 0.0 },
  78. "uDisplacementScale": { type: "f", value: 1.0 },
  79. "uDiffuseColor": { type: "c", value: new THREE.Color( 0xeeeeee ) },
  80. "uSpecularColor": { type: "c", value: new THREE.Color( 0x111111 ) },
  81. "uAmbientColor": { type: "c", value: new THREE.Color( 0x050505 ) },
  82. "uShininess": { type: "f", value: 30 },
  83. "uOpacity": { type: "f", value: 1 }
  84. }
  85. ] ),
  86. fragmentShader: [
  87. "uniform vec3 uAmbientColor;",
  88. "uniform vec3 uDiffuseColor;",
  89. "uniform vec3 uSpecularColor;",
  90. "uniform float uShininess;",
  91. "uniform float uOpacity;",
  92. "uniform bool enableDiffuse;",
  93. "uniform bool enableSpecular;",
  94. "uniform bool enableAO;",
  95. "uniform sampler2D tDiffuse;",
  96. "uniform sampler2D tNormal;",
  97. "uniform sampler2D tSpecular;",
  98. "uniform sampler2D tAO;",
  99. "uniform float uNormalScale;",
  100. "varying vec3 vTangent;",
  101. "varying vec3 vBinormal;",
  102. "varying vec3 vNormal;",
  103. "varying vec2 vUv;",
  104. "uniform vec3 ambientLightColor;",
  105. "#if MAX_DIR_LIGHTS > 0",
  106. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  107. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  108. "#endif",
  109. "#if MAX_POINT_LIGHTS > 0",
  110. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  111. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  112. "#endif",
  113. "varying vec3 vViewPosition;",
  114. THREE.ShaderChunk[ "fog_pars_fragment" ],
  115. "void main() {",
  116. "gl_FragColor = vec4( 1.0 );",
  117. "vec4 mColor = vec4( uDiffuseColor, uOpacity );",
  118. "vec4 mSpecular = vec4( uSpecularColor, uOpacity );",
  119. "vec3 specularTex = vec3( 1.0 );",
  120. "vec3 normalTex = texture2D( tNormal, vUv ).xyz * 2.0 - 1.0;",
  121. "normalTex.xy *= uNormalScale;",
  122. "normalTex = normalize( normalTex );",
  123. "if( enableDiffuse )",
  124. "gl_FragColor = gl_FragColor * texture2D( tDiffuse, vUv );",
  125. "if( enableAO )",
  126. "gl_FragColor = gl_FragColor * texture2D( tAO, vUv );",
  127. "if( enableSpecular )",
  128. "specularTex = texture2D( tSpecular, vUv ).xyz;",
  129. "mat3 tsb = mat3( vTangent, vBinormal, vNormal );",
  130. "vec3 finalNormal = tsb * normalTex;",
  131. "vec3 normal = normalize( finalNormal );",
  132. "vec3 viewPosition = normalize( vViewPosition );",
  133. // point lights
  134. "#if MAX_POINT_LIGHTS > 0",
  135. "vec4 pointTotal = vec4( 0.0 );",
  136. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  137. "vec3 pointVector = normalize( vPointLight[ i ].xyz );",
  138. "vec3 pointHalfVector = normalize( vPointLight[ i ].xyz + vViewPosition );",
  139. "float pointDistance = vPointLight[ i ].w;",
  140. "float pointDotNormalHalf = dot( normal, pointHalfVector );",
  141. "float pointDiffuseWeight = max( dot( normal, pointVector ), 0.0 );",
  142. "float pointSpecularWeight = 0.0;",
  143. "if ( pointDotNormalHalf >= 0.0 )",
  144. "pointSpecularWeight = specularTex.r * pow( pointDotNormalHalf, uShininess );",
  145. "pointTotal += pointDistance * vec4( pointLightColor[ i ], 1.0 ) * ( mColor * pointDiffuseWeight + mSpecular * pointSpecularWeight * pointDiffuseWeight );",
  146. "}",
  147. "#endif",
  148. // directional lights
  149. "#if MAX_DIR_LIGHTS > 0",
  150. "vec4 dirTotal = vec4( 0.0 );",
  151. "for( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {",
  152. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  153. "vec3 dirVector = normalize( lDirection.xyz );",
  154. "vec3 dirHalfVector = normalize( lDirection.xyz + vViewPosition );",
  155. "float dirDotNormalHalf = dot( normal, dirHalfVector );",
  156. "float dirDiffuseWeight = max( dot( normal, dirVector ), 0.0 );",
  157. "float dirSpecularWeight = 0.0;",
  158. "if ( dirDotNormalHalf >= 0.0 )",
  159. "dirSpecularWeight = specularTex.r * pow( dirDotNormalHalf, uShininess );",
  160. "dirTotal += vec4( directionalLightColor[ i ], 1.0 ) * ( mColor * dirDiffuseWeight + mSpecular * dirSpecularWeight * dirDiffuseWeight );",
  161. "}",
  162. "#endif",
  163. // all lights contribution summation
  164. "vec4 totalLight = vec4( ambientLightColor * uAmbientColor, uOpacity );",
  165. "#if MAX_DIR_LIGHTS > 0",
  166. "totalLight += dirTotal;",
  167. "#endif",
  168. "#if MAX_POINT_LIGHTS > 0",
  169. "totalLight += pointTotal;",
  170. "#endif",
  171. "gl_FragColor = gl_FragColor * totalLight;",
  172. THREE.ShaderChunk[ "fog_fragment" ],
  173. "}"
  174. ].join("\n"),
  175. vertexShader: [
  176. "attribute vec4 tangent;",
  177. "#ifdef VERTEX_TEXTURES",
  178. "uniform sampler2D tDisplacement;",
  179. "uniform float uDisplacementScale;",
  180. "uniform float uDisplacementBias;",
  181. "#endif",
  182. "varying vec3 vTangent;",
  183. "varying vec3 vBinormal;",
  184. "varying vec3 vNormal;",
  185. "varying vec2 vUv;",
  186. "#if MAX_POINT_LIGHTS > 0",
  187. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  188. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  189. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  190. "#endif",
  191. "varying vec3 vViewPosition;",
  192. "void main() {",
  193. "vec4 mPosition = objectMatrix * vec4( position, 1.0 );",
  194. "vViewPosition = cameraPosition - mPosition.xyz;",
  195. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  196. "vNormal = normalize( normalMatrix * normal );",
  197. // tangent and binormal vectors
  198. "vTangent = normalize( normalMatrix * tangent.xyz );",
  199. "vBinormal = cross( vNormal, vTangent ) * tangent.w;",
  200. "vBinormal = normalize( vBinormal );",
  201. "vUv = uv;",
  202. // point lights
  203. "#if MAX_POINT_LIGHTS > 0",
  204. "for( int i = 0; i < MAX_POINT_LIGHTS; i++ ) {",
  205. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  206. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  207. "float lDistance = 1.0;",
  208. "if ( pointLightDistance[ i ] > 0.0 )",
  209. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  210. "lVector = normalize( lVector );",
  211. "vPointLight[ i ] = vec4( lVector, lDistance );",
  212. "}",
  213. "#endif",
  214. // displacement mapping
  215. "#ifdef VERTEX_TEXTURES",
  216. "vec3 dv = texture2D( tDisplacement, uv ).xyz;",
  217. "float df = uDisplacementScale * dv.x + uDisplacementBias;",
  218. "vec4 displacedPosition = vec4( vNormal.xyz * df, 0.0 ) + mvPosition;",
  219. "gl_Position = projectionMatrix * displacedPosition;",
  220. "#else",
  221. "gl_Position = projectionMatrix * mvPosition;",
  222. "#endif",
  223. "}"
  224. ].join("\n")
  225. },
  226. /* -------------------------------------------------------------------------
  227. // Cube map shader
  228. ------------------------------------------------------------------------- */
  229. 'cube': {
  230. uniforms: { "tCube": { type: "t", value: 1, texture: null } },
  231. vertexShader: [
  232. "varying vec3 vViewPosition;",
  233. "void main() {",
  234. "vec4 mPosition = objectMatrix * vec4( position, 1.0 );",
  235. "vViewPosition = cameraPosition - mPosition.xyz;",
  236. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  237. "}"
  238. ].join("\n"),
  239. fragmentShader: [
  240. "uniform samplerCube tCube;",
  241. "varying vec3 vViewPosition;",
  242. "void main() {",
  243. "vec3 wPos = cameraPosition - vViewPosition;",
  244. "gl_FragColor = textureCube( tCube, vec3( - wPos.x, wPos.yz ) );",
  245. "}"
  246. ].join("\n")
  247. },
  248. /* ------------------------------------------------------------------------
  249. // Convolution shader
  250. // - ported from o3d sample to WebGL / GLSL
  251. // http://o3d.googlecode.com/svn/trunk/samples/convolution.html
  252. ------------------------------------------------------------------------ */
  253. 'convolution': {
  254. uniforms: {
  255. "tDiffuse" : { type: "t", value: 0, texture: null },
  256. "uImageIncrement" : { type: "v2", value: new THREE.Vector2( 0.001953125, 0.0 ) },
  257. "cKernel" : { type: "fv1", value: [] }
  258. },
  259. vertexShader: [
  260. "varying vec2 vUv;",
  261. "uniform vec2 uImageIncrement;",
  262. //"#define KERNEL_SIZE 25.0",
  263. "void main(void) {",
  264. "vUv = uv - ((KERNEL_SIZE - 1.0) / 2.0) * uImageIncrement;",
  265. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  266. "}"
  267. ].join("\n"),
  268. fragmentShader: [
  269. "varying vec2 vUv;",
  270. "uniform sampler2D tDiffuse;",
  271. "uniform vec2 uImageIncrement;",
  272. //"#define KERNEL_SIZE 25",
  273. "uniform float cKernel[KERNEL_SIZE];",
  274. "void main(void) {",
  275. "vec2 imageCoord = vUv;",
  276. "vec4 sum = vec4( 0.0, 0.0, 0.0, 0.0 );",
  277. "for( int i=0; i<KERNEL_SIZE; ++i ) {",
  278. "sum += texture2D( tDiffuse, imageCoord ) * cKernel[i];",
  279. "imageCoord += uImageIncrement;",
  280. "}",
  281. "gl_FragColor = sum;",
  282. "}"
  283. ].join("\n")
  284. },
  285. /* -------------------------------------------------------------------------
  286. // Film grain & scanlines shader
  287. // - ported from HLSL to WebGL / GLSL
  288. // http://www.truevision3d.com/forums/showcase/staticnoise_colorblackwhite_scanline_shaders-t18698.0.html
  289. // Screen Space Static Postprocessor
  290. //
  291. // Produces an analogue noise overlay similar to a film grain / TV static
  292. //
  293. // Original implementation and noise algorithm
  294. // Pat 'Hawthorne' Shearon
  295. //
  296. // Optimized scanlines + noise version with intensity scaling
  297. // Georg 'Leviathan' Steinrohder
  298. // This version is provided under a Creative Commons Attribution 3.0 License
  299. // http://creativecommons.org/licenses/by/3.0/
  300. ------------------------------------------------------------------------- */
  301. 'film': {
  302. uniforms: {
  303. tDiffuse: { type: "t", value: 0, texture: null },
  304. time: { type: "f", value: 0.0 },
  305. nIntensity: { type: "f", value: 0.5 },
  306. sIntensity: { type: "f", value: 0.05 },
  307. sCount: { type: "f", value: 4096 },
  308. grayscale: { type: "i", value: 1 }
  309. },
  310. vertexShader: [
  311. "varying vec2 vUv;",
  312. "void main() {",
  313. "vUv = vec2( uv.x, 1.0 - uv.y );",
  314. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  315. "}"
  316. ].join("\n"),
  317. fragmentShader: [
  318. "varying vec2 vUv;",
  319. "uniform sampler2D tDiffuse;",
  320. // control parameter
  321. "uniform float time;",
  322. "uniform bool grayscale;",
  323. // noise effect intensity value (0 = no effect, 1 = full effect)
  324. "uniform float nIntensity;",
  325. // scanlines effect intensity value (0 = no effect, 1 = full effect)
  326. "uniform float sIntensity;",
  327. // scanlines effect count value (0 = no effect, 4096 = full effect)
  328. "uniform float sCount;",
  329. "void main() {",
  330. // sample the source
  331. "vec4 cTextureScreen = texture2D( tDiffuse, vUv );",
  332. // make some noise
  333. "float x = vUv.x * vUv.y * time * 1000.0;",
  334. "x = mod( x, 13.0 ) * mod( x, 123.0 );",
  335. "float dx = mod( x, 0.01 );",
  336. // add noise
  337. "vec3 cResult = cTextureScreen.rgb + cTextureScreen.rgb * clamp( 0.1 + dx * 100.0, 0.0, 1.0 );",
  338. // get us a sine and cosine
  339. "vec2 sc = vec2( sin( vUv.y * sCount ), cos( vUv.y * sCount ) );",
  340. // add scanlines
  341. "cResult += cTextureScreen.rgb * vec3( sc.x, sc.y, sc.x ) * sIntensity;",
  342. // interpolate between source and result by intensity
  343. "cResult = cTextureScreen.rgb + clamp( nIntensity, 0.0,1.0 ) * ( cResult - cTextureScreen.rgb );",
  344. // convert to grayscale if desired
  345. "if( grayscale ) {",
  346. "cResult = vec3( cResult.r * 0.3 + cResult.g * 0.59 + cResult.b * 0.11 );",
  347. "}",
  348. "gl_FragColor = vec4( cResult, cTextureScreen.a );",
  349. "}"
  350. ].join("\n")
  351. },
  352. /* -------------------------------------------------------------------------
  353. // Full-screen textured quad shader
  354. ------------------------------------------------------------------------- */
  355. 'screen': {
  356. uniforms: {
  357. tDiffuse: { type: "t", value: 0, texture: null },
  358. opacity: { type: "f", value: 1.0 }
  359. },
  360. vertexShader: [
  361. "varying vec2 vUv;",
  362. "void main() {",
  363. "vUv = vec2( uv.x, 1.0 - uv.y );",
  364. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  365. "}"
  366. ].join("\n"),
  367. fragmentShader: [
  368. "varying vec2 vUv;",
  369. "uniform sampler2D tDiffuse;",
  370. "uniform float opacity;",
  371. "void main() {",
  372. "vec4 texel = texture2D( tDiffuse, vUv );",
  373. "gl_FragColor = opacity * texel;",
  374. "}"
  375. ].join("\n")
  376. },
  377. /* -------------------------------------------------------------------------
  378. // Simple test shader
  379. ------------------------------------------------------------------------- */
  380. 'basic': {
  381. uniforms: {},
  382. vertexShader: [
  383. "void main() {",
  384. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  385. "}"
  386. ].join("\n"),
  387. fragmentShader: [
  388. "void main() {",
  389. "gl_FragColor = vec4( 1.0, 0.0, 0.0, 0.5 );",
  390. "}"
  391. ].join("\n")
  392. }
  393. },
  394. buildKernel: function( sigma ) {
  395. // We lop off the sqrt(2 * pi) * sigma term, since we're going to normalize anyway.
  396. function gauss( x, sigma ) {
  397. return Math.exp( - ( x * x ) / ( 2.0 * sigma * sigma ) );
  398. }
  399. var i, values, sum, halfWidth, kMaxKernelSize = 25, kernelSize = 2 * Math.ceil( sigma * 3.0 ) + 1;
  400. if ( kernelSize > kMaxKernelSize ) kernelSize = kMaxKernelSize;
  401. halfWidth = ( kernelSize - 1 ) * 0.5
  402. values = new Array( kernelSize );
  403. sum = 0.0;
  404. for ( i = 0; i < kernelSize; ++i ) {
  405. values[ i ] = gauss( i - halfWidth, sigma );
  406. sum += values[ i ];
  407. }
  408. // normalize the kernel
  409. for ( i = 0; i < kernelSize; ++i ) values[ i ] /= sum;
  410. return values;
  411. }
  412. };
  413. };