materialHelper.ts 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829
  1. import { Logger } from "../Misc/logger";
  2. import { Nullable } from "../types";
  3. import { Camera } from "../Cameras/camera";
  4. import { Scene } from "../scene";
  5. import { Engine } from "../Engines/engine";
  6. import { EngineStore } from "../Engines/engineStore";
  7. import { AbstractMesh } from "../Meshes/abstractMesh";
  8. import { Mesh } from "../Meshes/mesh";
  9. import { VertexBuffer } from "../Meshes/buffer";
  10. import { Light } from "../Lights/light";
  11. import { UniformBuffer } from "./uniformBuffer";
  12. import { Effect, IEffectCreationOptions } from "./effect";
  13. import { BaseTexture } from "../Materials/Textures/baseTexture";
  14. import { WebVRFreeCamera } from '../Cameras/VR/webVRCamera';
  15. import { MaterialDefines } from "./materialDefines";
  16. import { Color3 } from '../Maths/math.color';
  17. import { EffectFallbacks } from './effectFallbacks';
  18. /**
  19. * "Static Class" containing the most commonly used helper while dealing with material for
  20. * rendering purpose.
  21. *
  22. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  23. *
  24. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  25. */
  26. export class MaterialHelper {
  27. /**
  28. * Bind the current view position to an effect.
  29. * @param effect The effect to be bound
  30. * @param scene The scene the eyes position is used from
  31. */
  32. public static BindEyePosition(effect: Effect, scene: Scene): void {
  33. if (scene._forcedViewPosition) {
  34. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  35. return;
  36. }
  37. var globalPosition = scene.activeCamera!.globalPosition;
  38. if (!globalPosition) {
  39. // Use WebVRFreecamera's device position as global position is not it's actual position in babylon space
  40. globalPosition = (scene.activeCamera! as WebVRFreeCamera).devicePosition;
  41. }
  42. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : globalPosition);
  43. }
  44. /**
  45. * Helps preparing the defines values about the UVs in used in the effect.
  46. * UVs are shared as much as we can accross channels in the shaders.
  47. * @param texture The texture we are preparing the UVs for
  48. * @param defines The defines to update
  49. * @param key The channel key "diffuse", "specular"... used in the shader
  50. */
  51. public static PrepareDefinesForMergedUV(texture: BaseTexture, defines: any, key: string): void {
  52. defines._needUVs = true;
  53. defines[key] = true;
  54. if (texture.getTextureMatrix().isIdentityAs3x2()) {
  55. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  56. if (texture.coordinatesIndex === 0) {
  57. defines["MAINUV1"] = true;
  58. } else {
  59. defines["MAINUV2"] = true;
  60. }
  61. } else {
  62. defines[key + "DIRECTUV"] = 0;
  63. }
  64. }
  65. /**
  66. * Binds a texture matrix value to its corrsponding uniform
  67. * @param texture The texture to bind the matrix for
  68. * @param uniformBuffer The uniform buffer receivin the data
  69. * @param key The channel key "diffuse", "specular"... used in the shader
  70. */
  71. public static BindTextureMatrix(texture: BaseTexture, uniformBuffer: UniformBuffer, key: string): void {
  72. var matrix = texture.getTextureMatrix();
  73. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  74. }
  75. /**
  76. * Gets the current status of the fog (should it be enabled?)
  77. * @param mesh defines the mesh to evaluate for fog support
  78. * @param scene defines the hosting scene
  79. * @returns true if fog must be enabled
  80. */
  81. public static GetFogState(mesh: AbstractMesh, scene: Scene) {
  82. return (scene.fogEnabled && mesh.applyFog && scene.fogMode !== Scene.FOGMODE_NONE);
  83. }
  84. /**
  85. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  86. * @param mesh defines the current mesh
  87. * @param scene defines the current scene
  88. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  89. * @param pointsCloud defines if point cloud rendering has to be turned on
  90. * @param fogEnabled defines if fog has to be turned on
  91. * @param alphaTest defines if alpha testing has to be turned on
  92. * @param defines defines the current list of defines
  93. */
  94. public static PrepareDefinesForMisc(mesh: AbstractMesh, scene: Scene, useLogarithmicDepth: boolean, pointsCloud: boolean, fogEnabled: boolean, alphaTest: boolean, defines: any): void {
  95. if (defines._areMiscDirty) {
  96. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  97. defines["POINTSIZE"] = pointsCloud;
  98. defines["FOG"] = fogEnabled && this.GetFogState(mesh, scene);
  99. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  100. defines["ALPHATEST"] = alphaTest;
  101. }
  102. }
  103. /**
  104. * Helper used to prepare the list of defines associated with frame values for shader compilation
  105. * @param scene defines the current scene
  106. * @param engine defines the current engine
  107. * @param defines specifies the list of active defines
  108. * @param useInstances defines if instances have to be turned on
  109. * @param useClipPlane defines if clip plane have to be turned on
  110. */
  111. public static PrepareDefinesForFrameBoundValues(scene: Scene, engine: Engine, defines: any, useInstances: boolean, useClipPlane: Nullable<boolean> = null): void {
  112. var changed = false;
  113. let useClipPlane1 = false;
  114. let useClipPlane2 = false;
  115. let useClipPlane3 = false;
  116. let useClipPlane4 = false;
  117. let useClipPlane5 = false;
  118. let useClipPlane6 = false;
  119. useClipPlane1 = useClipPlane == null ? (scene.clipPlane !== undefined && scene.clipPlane !== null) : useClipPlane;
  120. useClipPlane2 = useClipPlane == null ? (scene.clipPlane2 !== undefined && scene.clipPlane2 !== null) : useClipPlane;
  121. useClipPlane3 = useClipPlane == null ? (scene.clipPlane3 !== undefined && scene.clipPlane3 !== null) : useClipPlane;
  122. useClipPlane4 = useClipPlane == null ? (scene.clipPlane4 !== undefined && scene.clipPlane4 !== null) : useClipPlane;
  123. useClipPlane5 = useClipPlane == null ? (scene.clipPlane5 !== undefined && scene.clipPlane5 !== null) : useClipPlane;
  124. useClipPlane6 = useClipPlane == null ? (scene.clipPlane6 !== undefined && scene.clipPlane6 !== null) : useClipPlane;
  125. if (defines["CLIPPLANE"] !== useClipPlane1) {
  126. defines["CLIPPLANE"] = useClipPlane1;
  127. changed = true;
  128. }
  129. if (defines["CLIPPLANE2"] !== useClipPlane2) {
  130. defines["CLIPPLANE2"] = useClipPlane2;
  131. changed = true;
  132. }
  133. if (defines["CLIPPLANE3"] !== useClipPlane3) {
  134. defines["CLIPPLANE3"] = useClipPlane3;
  135. changed = true;
  136. }
  137. if (defines["CLIPPLANE4"] !== useClipPlane4) {
  138. defines["CLIPPLANE4"] = useClipPlane4;
  139. changed = true;
  140. }
  141. if (defines["CLIPPLANE5"] !== useClipPlane5) {
  142. defines["CLIPPLANE5"] = useClipPlane5;
  143. changed = true;
  144. }
  145. if (defines["CLIPPLANE6"] !== useClipPlane6) {
  146. defines["CLIPPLANE6"] = useClipPlane6;
  147. changed = true;
  148. }
  149. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  150. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  151. changed = true;
  152. }
  153. if (defines["INSTANCES"] !== useInstances) {
  154. defines["INSTANCES"] = useInstances;
  155. changed = true;
  156. }
  157. if (changed) {
  158. defines.markAsUnprocessed();
  159. }
  160. }
  161. /**
  162. * Prepares the defines for bones
  163. * @param mesh The mesh containing the geometry data we will draw
  164. * @param defines The defines to update
  165. */
  166. public static PrepareDefinesForBones(mesh: AbstractMesh, defines: any) {
  167. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  168. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  169. const materialSupportsBoneTexture = defines["BONETEXTURE"] !== undefined;
  170. if (mesh.skeleton.isUsingTextureForMatrices && materialSupportsBoneTexture) {
  171. defines["BONETEXTURE"] = true;
  172. } else {
  173. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  174. defines["BONETEXTURE"] = materialSupportsBoneTexture ? false : undefined;
  175. }
  176. } else {
  177. defines["NUM_BONE_INFLUENCERS"] = 0;
  178. defines["BonesPerMesh"] = 0;
  179. }
  180. }
  181. /**
  182. * Prepares the defines for morph targets
  183. * @param mesh The mesh containing the geometry data we will draw
  184. * @param defines The defines to update
  185. */
  186. public static PrepareDefinesForMorphTargets(mesh: AbstractMesh, defines: any) {
  187. var manager = (<Mesh>mesh).morphTargetManager;
  188. if (manager) {
  189. defines["MORPHTARGETS_UV"] = manager.supportsUVs && defines["UV1"];
  190. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  191. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  192. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  193. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  194. } else {
  195. defines["MORPHTARGETS_UV"] = false;
  196. defines["MORPHTARGETS_TANGENT"] = false;
  197. defines["MORPHTARGETS_NORMAL"] = false;
  198. defines["MORPHTARGETS"] = false;
  199. defines["NUM_MORPH_INFLUENCERS"] = 0;
  200. }
  201. }
  202. /**
  203. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  204. * @param mesh The mesh containing the geometry data we will draw
  205. * @param defines The defines to update
  206. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  207. * @param useBones Precise whether bones should be used or not (override mesh info)
  208. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  209. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  210. * @returns false if defines are considered not dirty and have not been checked
  211. */
  212. public static PrepareDefinesForAttributes(mesh: AbstractMesh, defines: any, useVertexColor: boolean, useBones: boolean, useMorphTargets = false, useVertexAlpha = true): boolean {
  213. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  214. return false;
  215. }
  216. defines._normals = defines._needNormals;
  217. defines._uvs = defines._needUVs;
  218. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(VertexBuffer.NormalKind));
  219. if (defines._needNormals && mesh.isVerticesDataPresent(VertexBuffer.TangentKind)) {
  220. defines["TANGENT"] = true;
  221. }
  222. if (defines._needUVs) {
  223. defines["UV1"] = mesh.isVerticesDataPresent(VertexBuffer.UVKind);
  224. defines["UV2"] = mesh.isVerticesDataPresent(VertexBuffer.UV2Kind);
  225. } else {
  226. defines["UV1"] = false;
  227. defines["UV2"] = false;
  228. }
  229. if (useVertexColor) {
  230. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(VertexBuffer.ColorKind);
  231. defines["VERTEXCOLOR"] = hasVertexColors;
  232. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  233. }
  234. if (useBones) {
  235. this.PrepareDefinesForBones(mesh, defines);
  236. }
  237. if (useMorphTargets) {
  238. this.PrepareDefinesForMorphTargets(mesh, defines);
  239. }
  240. return true;
  241. }
  242. /**
  243. * Prepares the defines related to multiview
  244. * @param scene The scene we are intending to draw
  245. * @param defines The defines to update
  246. */
  247. public static PrepareDefinesForMultiview(scene: Scene, defines: any) {
  248. if (scene.activeCamera) {
  249. var previousMultiview = defines.MULTIVIEW;
  250. defines.MULTIVIEW = (scene.activeCamera.outputRenderTarget !== null && scene.activeCamera.outputRenderTarget.getViewCount() > 1);
  251. if (defines.MULTIVIEW != previousMultiview) {
  252. defines.markAsUnprocessed();
  253. }
  254. }
  255. }
  256. /**
  257. * Prepares the defines related to the light information passed in parameter
  258. * @param scene The scene we are intending to draw
  259. * @param mesh The mesh the effect is compiling for
  260. * @param light The light the effect is compiling for
  261. * @param lightIndex The index of the light
  262. * @param defines The defines to update
  263. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  264. * @param state Defines the current state regarding what is needed (normals, etc...)
  265. */
  266. public static PrepareDefinesForLight(scene: Scene, mesh: AbstractMesh, light: Light, lightIndex: number, defines: any, specularSupported: boolean, state: {
  267. needNormals: boolean,
  268. needRebuild: boolean,
  269. shadowEnabled: boolean,
  270. specularEnabled: boolean,
  271. lightmapMode: boolean
  272. }) {
  273. state.needNormals = true;
  274. if (defines["LIGHT" + lightIndex] === undefined) {
  275. state.needRebuild = true;
  276. }
  277. defines["LIGHT" + lightIndex] = true;
  278. defines["SPOTLIGHT" + lightIndex] = false;
  279. defines["HEMILIGHT" + lightIndex] = false;
  280. defines["POINTLIGHT" + lightIndex] = false;
  281. defines["DIRLIGHT" + lightIndex] = false;
  282. light.prepareLightSpecificDefines(defines, lightIndex);
  283. // FallOff.
  284. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = false;
  285. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = false;
  286. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = false;
  287. switch (light.falloffType) {
  288. case Light.FALLOFF_GLTF:
  289. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = true;
  290. break;
  291. case Light.FALLOFF_PHYSICAL:
  292. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = true;
  293. break;
  294. case Light.FALLOFF_STANDARD:
  295. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = true;
  296. break;
  297. }
  298. // Specular
  299. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  300. state.specularEnabled = true;
  301. }
  302. // Shadows
  303. defines["SHADOW" + lightIndex] = false;
  304. defines["SHADOWCSM" + lightIndex] = false;
  305. defines["SHADOWCSMDEBUG" + lightIndex] = false;
  306. defines["SHADOWCSMNUM_CASCADES" + lightIndex] = false;
  307. defines["SHADOWCSMUSESHADOWMAXZ" + lightIndex] = false;
  308. defines["SHADOWPCF" + lightIndex] = false;
  309. defines["SHADOWPCSS" + lightIndex] = false;
  310. defines["SHADOWPOISSON" + lightIndex] = false;
  311. defines["SHADOWESM" + lightIndex] = false;
  312. defines["SHADOWCUBE" + lightIndex] = false;
  313. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  314. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  315. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  316. var shadowGenerator = light.getShadowGenerator();
  317. if (shadowGenerator) {
  318. const shadowMap = shadowGenerator.getShadowMap();
  319. if (shadowMap) {
  320. if (shadowMap.renderList && shadowMap.renderList.length > 0) {
  321. state.shadowEnabled = true;
  322. shadowGenerator.prepareDefines(defines, lightIndex);
  323. }
  324. }
  325. }
  326. }
  327. if (light.lightmapMode != Light.LIGHTMAP_DEFAULT) {
  328. state.lightmapMode = true;
  329. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  330. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == Light.LIGHTMAP_SHADOWSONLY);
  331. } else {
  332. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  333. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  334. }
  335. }
  336. /**
  337. * Prepares the defines related to the light information passed in parameter
  338. * @param scene The scene we are intending to draw
  339. * @param mesh The mesh the effect is compiling for
  340. * @param defines The defines to update
  341. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  342. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  343. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  344. * @returns true if normals will be required for the rest of the effect
  345. */
  346. public static PrepareDefinesForLights(scene: Scene, mesh: AbstractMesh, defines: any, specularSupported: boolean, maxSimultaneousLights = 4, disableLighting = false): boolean {
  347. if (!defines._areLightsDirty) {
  348. return defines._needNormals;
  349. }
  350. var lightIndex = 0;
  351. let state = {
  352. needNormals: false,
  353. needRebuild: false,
  354. lightmapMode: false,
  355. shadowEnabled: false,
  356. specularEnabled: false
  357. };
  358. if (scene.lightsEnabled && !disableLighting) {
  359. for (var light of mesh.lightSources) {
  360. this.PrepareDefinesForLight(scene, mesh, light, lightIndex, defines, specularSupported, state);
  361. lightIndex++;
  362. if (lightIndex === maxSimultaneousLights) {
  363. break;
  364. }
  365. }
  366. }
  367. defines["SPECULARTERM"] = state.specularEnabled;
  368. defines["SHADOWS"] = state.shadowEnabled;
  369. // Resetting all other lights if any
  370. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  371. if (defines["LIGHT" + index] !== undefined) {
  372. defines["LIGHT" + index] = false;
  373. defines["HEMILIGHT" + index] = false;
  374. defines["POINTLIGHT" + index] = false;
  375. defines["DIRLIGHT" + index] = false;
  376. defines["SPOTLIGHT" + index] = false;
  377. defines["SHADOW" + index] = false;
  378. defines["SHADOWCSM" + index] = false;
  379. defines["SHADOWCSMDEBUG" + index] = false;
  380. defines["SHADOWCSMNUM_CASCADES" + index] = false;
  381. defines["SHADOWCSMUSESHADOWMAXZ" + index] = false;
  382. defines["SHADOWPCF" + index] = false;
  383. defines["SHADOWPCSS" + index] = false;
  384. defines["SHADOWPOISSON" + index] = false;
  385. defines["SHADOWESM" + index] = false;
  386. defines["SHADOWCUBE" + index] = false;
  387. defines["SHADOWLOWQUALITY" + index] = false;
  388. defines["SHADOWMEDIUMQUALITY" + index] = false;
  389. }
  390. }
  391. let caps = scene.getEngine().getCaps();
  392. if (defines["SHADOWFLOAT"] === undefined) {
  393. state.needRebuild = true;
  394. }
  395. defines["SHADOWFLOAT"] = state.shadowEnabled &&
  396. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  397. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  398. defines["LIGHTMAPEXCLUDED"] = state.lightmapMode;
  399. if (state.needRebuild) {
  400. defines.rebuild();
  401. }
  402. return state.needNormals;
  403. }
  404. /**
  405. * Prepares the uniforms and samplers list to be used in the effect (for a specific light)
  406. * @param lightIndex defines the light index
  407. * @param uniformsList The uniform list
  408. * @param samplersList The sampler list
  409. * @param projectedLightTexture defines if projected texture must be used
  410. * @param uniformBuffersList defines an optional list of uniform buffers
  411. */
  412. public static PrepareUniformsAndSamplersForLight(lightIndex: number, uniformsList: string[], samplersList: string[], projectedLightTexture?: any, uniformBuffersList: Nullable<string[]> = null) {
  413. uniformsList.push(
  414. "vLightData" + lightIndex,
  415. "vLightDiffuse" + lightIndex,
  416. "vLightSpecular" + lightIndex,
  417. "vLightDirection" + lightIndex,
  418. "vLightFalloff" + lightIndex,
  419. "vLightGround" + lightIndex,
  420. "lightMatrix" + lightIndex,
  421. "shadowsInfo" + lightIndex,
  422. "depthValues" + lightIndex,
  423. );
  424. if (uniformBuffersList) {
  425. uniformBuffersList.push("Light" + lightIndex);
  426. }
  427. samplersList.push("shadowSampler" + lightIndex);
  428. samplersList.push("depthSampler" + lightIndex);
  429. uniformsList.push(
  430. "viewFrustumZ" + lightIndex,
  431. "cascadeBlendFactor" + lightIndex,
  432. "lightSizeUVCorrection" + lightIndex,
  433. "depthCorrection" + lightIndex,
  434. "penumbraDarkness" + lightIndex,
  435. "frustumLengths" + lightIndex,
  436. );
  437. if (projectedLightTexture) {
  438. samplersList.push("projectionLightSampler" + lightIndex);
  439. uniformsList.push(
  440. "textureProjectionMatrix" + lightIndex,
  441. );
  442. }
  443. }
  444. /**
  445. * Prepares the uniforms and samplers list to be used in the effect
  446. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  447. * @param samplersList The sampler list
  448. * @param defines The defines helping in the list generation
  449. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  450. */
  451. public static PrepareUniformsAndSamplersList(uniformsListOrOptions: string[] | IEffectCreationOptions, samplersList?: string[], defines?: any, maxSimultaneousLights = 4): void {
  452. let uniformsList: string[];
  453. let uniformBuffersList: Nullable<string[]> = null;
  454. if ((<IEffectCreationOptions>uniformsListOrOptions).uniformsNames) {
  455. var options = <IEffectCreationOptions>uniformsListOrOptions;
  456. uniformsList = options.uniformsNames;
  457. uniformBuffersList = options.uniformBuffersNames;
  458. samplersList = options.samplers;
  459. defines = options.defines;
  460. maxSimultaneousLights = options.maxSimultaneousLights || 0;
  461. } else {
  462. uniformsList = <string[]>uniformsListOrOptions;
  463. if (!samplersList) {
  464. samplersList = [];
  465. }
  466. }
  467. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  468. if (!defines["LIGHT" + lightIndex]) {
  469. break;
  470. }
  471. this.PrepareUniformsAndSamplersForLight(lightIndex, uniformsList, samplersList, defines["PROJECTEDLIGHTTEXTURE" + lightIndex], uniformBuffersList);
  472. }
  473. if (defines["NUM_MORPH_INFLUENCERS"]) {
  474. uniformsList.push("morphTargetInfluences");
  475. }
  476. }
  477. /**
  478. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  479. * @param defines The defines to update while falling back
  480. * @param fallbacks The authorized effect fallbacks
  481. * @param maxSimultaneousLights The maximum number of lights allowed
  482. * @param rank the current rank of the Effect
  483. * @returns The newly affected rank
  484. */
  485. public static HandleFallbacksForShadows(defines: any, fallbacks: EffectFallbacks, maxSimultaneousLights = 4, rank = 0): number {
  486. let lightFallbackRank = 0;
  487. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  488. if (!defines["LIGHT" + lightIndex]) {
  489. break;
  490. }
  491. if (lightIndex > 0) {
  492. lightFallbackRank = rank + lightIndex;
  493. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  494. }
  495. if (!defines["SHADOWS"]) {
  496. if (defines["SHADOW" + lightIndex]) {
  497. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  498. }
  499. if (defines["SHADOWPCF" + lightIndex]) {
  500. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  501. }
  502. if (defines["SHADOWPCSS" + lightIndex]) {
  503. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  504. }
  505. if (defines["SHADOWPOISSON" + lightIndex]) {
  506. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  507. }
  508. if (defines["SHADOWESM" + lightIndex]) {
  509. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  510. }
  511. }
  512. }
  513. return lightFallbackRank++;
  514. }
  515. private static _TmpMorphInfluencers = { "NUM_MORPH_INFLUENCERS": 0 };
  516. /**
  517. * Prepares the list of attributes required for morph targets according to the effect defines.
  518. * @param attribs The current list of supported attribs
  519. * @param mesh The mesh to prepare the morph targets attributes for
  520. * @param influencers The number of influencers
  521. */
  522. public static PrepareAttributesForMorphTargetsInfluencers(attribs: string[], mesh: AbstractMesh, influencers: number): void {
  523. this._TmpMorphInfluencers.NUM_MORPH_INFLUENCERS = influencers;
  524. this.PrepareAttributesForMorphTargets(attribs, mesh, this._TmpMorphInfluencers);
  525. }
  526. /**
  527. * Prepares the list of attributes required for morph targets according to the effect defines.
  528. * @param attribs The current list of supported attribs
  529. * @param mesh The mesh to prepare the morph targets attributes for
  530. * @param defines The current Defines of the effect
  531. */
  532. public static PrepareAttributesForMorphTargets(attribs: string[], mesh: AbstractMesh, defines: any): void {
  533. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  534. if (influencers > 0 && EngineStore.LastCreatedEngine) {
  535. var maxAttributesCount = EngineStore.LastCreatedEngine.getCaps().maxVertexAttribs;
  536. var manager = (<Mesh>mesh).morphTargetManager;
  537. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  538. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  539. var uv = manager && manager.supportsUVs && defines["UV1"];
  540. for (var index = 0; index < influencers; index++) {
  541. attribs.push(VertexBuffer.PositionKind + index);
  542. if (normal) {
  543. attribs.push(VertexBuffer.NormalKind + index);
  544. }
  545. if (tangent) {
  546. attribs.push(VertexBuffer.TangentKind + index);
  547. }
  548. if (uv) {
  549. attribs.push(VertexBuffer.UVKind + "_" + index);
  550. }
  551. if (attribs.length > maxAttributesCount) {
  552. Logger.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  553. }
  554. }
  555. }
  556. }
  557. /**
  558. * Prepares the list of attributes required for bones according to the effect defines.
  559. * @param attribs The current list of supported attribs
  560. * @param mesh The mesh to prepare the bones attributes for
  561. * @param defines The current Defines of the effect
  562. * @param fallbacks The current efffect fallback strategy
  563. */
  564. public static PrepareAttributesForBones(attribs: string[], mesh: AbstractMesh, defines: any, fallbacks: EffectFallbacks): void {
  565. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  566. fallbacks.addCPUSkinningFallback(0, mesh);
  567. attribs.push(VertexBuffer.MatricesIndicesKind);
  568. attribs.push(VertexBuffer.MatricesWeightsKind);
  569. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  570. attribs.push(VertexBuffer.MatricesIndicesExtraKind);
  571. attribs.push(VertexBuffer.MatricesWeightsExtraKind);
  572. }
  573. }
  574. }
  575. /**
  576. * Check and prepare the list of attributes required for instances according to the effect defines.
  577. * @param attribs The current list of supported attribs
  578. * @param defines The current MaterialDefines of the effect
  579. */
  580. public static PrepareAttributesForInstances(attribs: string[], defines: MaterialDefines): void {
  581. if (defines["INSTANCES"]) {
  582. this.PushAttributesForInstances(attribs);
  583. }
  584. }
  585. /**
  586. * Add the list of attributes required for instances to the attribs array.
  587. * @param attribs The current list of supported attribs
  588. */
  589. public static PushAttributesForInstances(attribs: string[]): void {
  590. attribs.push("world0");
  591. attribs.push("world1");
  592. attribs.push("world2");
  593. attribs.push("world3");
  594. }
  595. /**
  596. * Binds the light information to the effect.
  597. * @param light The light containing the generator
  598. * @param effect The effect we are binding the data to
  599. * @param lightIndex The light index in the effect used to render
  600. */
  601. public static BindLightProperties(light: Light, effect: Effect, lightIndex: number): void {
  602. light.transferToEffect(effect, lightIndex + "");
  603. }
  604. /**
  605. * Binds the lights information from the scene to the effect for the given mesh.
  606. * @param light Light to bind
  607. * @param lightIndex Light index
  608. * @param scene The scene where the light belongs to
  609. * @param effect The effect we are binding the data to
  610. * @param useSpecular Defines if specular is supported
  611. * @param rebuildInParallel Specifies whether the shader is rebuilding in parallel
  612. */
  613. public static BindLight(light: Light, lightIndex: number, scene: Scene, effect: Effect, useSpecular: boolean, rebuildInParallel = false): void {
  614. light._bindLight(lightIndex, scene, effect, useSpecular, rebuildInParallel);
  615. }
  616. /**
  617. * Binds the lights information from the scene to the effect for the given mesh.
  618. * @param scene The scene the lights belongs to
  619. * @param mesh The mesh we are binding the information to render
  620. * @param effect The effect we are binding the data to
  621. * @param defines The generated defines for the effect
  622. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  623. * @param rebuildInParallel Specifies whether the shader is rebuilding in parallel
  624. */
  625. public static BindLights(scene: Scene, mesh: AbstractMesh, effect: Effect, defines: any, maxSimultaneousLights = 4, rebuildInParallel = false): void {
  626. let len = Math.min(mesh.lightSources.length, maxSimultaneousLights);
  627. for (var i = 0; i < len; i++) {
  628. let light = mesh.lightSources[i];
  629. this.BindLight(light, i, scene, effect, typeof defines === "boolean" ? defines : defines["SPECULARTERM"], rebuildInParallel);
  630. }
  631. }
  632. private static _tempFogColor = Color3.Black();
  633. /**
  634. * Binds the fog information from the scene to the effect for the given mesh.
  635. * @param scene The scene the lights belongs to
  636. * @param mesh The mesh we are binding the information to render
  637. * @param effect The effect we are binding the data to
  638. * @param linearSpace Defines if the fog effect is applied in linear space
  639. */
  640. public static BindFogParameters(scene: Scene, mesh: AbstractMesh, effect: Effect, linearSpace = false): void {
  641. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== Scene.FOGMODE_NONE) {
  642. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  643. // Convert fog color to linear space if used in a linear space computed shader.
  644. if (linearSpace) {
  645. scene.fogColor.toLinearSpaceToRef(this._tempFogColor);
  646. effect.setColor3("vFogColor", this._tempFogColor);
  647. }
  648. else {
  649. effect.setColor3("vFogColor", scene.fogColor);
  650. }
  651. }
  652. }
  653. /**
  654. * Binds the bones information from the mesh to the effect.
  655. * @param mesh The mesh we are binding the information to render
  656. * @param effect The effect we are binding the data to
  657. */
  658. public static BindBonesParameters(mesh?: AbstractMesh, effect?: Effect): void {
  659. if (!effect || !mesh) {
  660. return;
  661. }
  662. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  663. mesh.computeBonesUsingShaders = false;
  664. }
  665. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  666. const skeleton = mesh.skeleton;
  667. if (skeleton.isUsingTextureForMatrices && effect.getUniformIndex("boneTextureWidth") > -1) {
  668. const boneTexture = skeleton.getTransformMatrixTexture(mesh);
  669. effect.setTexture("boneSampler", boneTexture);
  670. effect.setFloat("boneTextureWidth", 4.0 * (skeleton.bones.length + 1));
  671. } else {
  672. const matrices = skeleton.getTransformMatrices(mesh);
  673. if (matrices) {
  674. effect.setMatrices("mBones", matrices);
  675. }
  676. }
  677. }
  678. }
  679. /**
  680. * Binds the morph targets information from the mesh to the effect.
  681. * @param abstractMesh The mesh we are binding the information to render
  682. * @param effect The effect we are binding the data to
  683. */
  684. public static BindMorphTargetParameters(abstractMesh: AbstractMesh, effect: Effect): void {
  685. let manager = (<Mesh>abstractMesh).morphTargetManager;
  686. if (!abstractMesh || !manager) {
  687. return;
  688. }
  689. effect.setFloatArray("morphTargetInfluences", manager.influences);
  690. }
  691. /**
  692. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  693. * @param defines The generated defines used in the effect
  694. * @param effect The effect we are binding the data to
  695. * @param scene The scene we are willing to render with logarithmic scale for
  696. */
  697. public static BindLogDepth(defines: any, effect: Effect, scene: Scene): void {
  698. if (defines["LOGARITHMICDEPTH"]) {
  699. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log((<Camera>scene.activeCamera).maxZ + 1.0) / Math.LN2));
  700. }
  701. }
  702. /**
  703. * Binds the clip plane information from the scene to the effect.
  704. * @param scene The scene the clip plane information are extracted from
  705. * @param effect The effect we are binding the data to
  706. */
  707. public static BindClipPlane(effect: Effect, scene: Scene): void {
  708. if (scene.clipPlane) {
  709. let clipPlane = scene.clipPlane;
  710. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  711. }
  712. if (scene.clipPlane2) {
  713. let clipPlane = scene.clipPlane2;
  714. effect.setFloat4("vClipPlane2", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  715. }
  716. if (scene.clipPlane3) {
  717. let clipPlane = scene.clipPlane3;
  718. effect.setFloat4("vClipPlane3", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  719. }
  720. if (scene.clipPlane4) {
  721. let clipPlane = scene.clipPlane4;
  722. effect.setFloat4("vClipPlane4", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  723. }
  724. if (scene.clipPlane5) {
  725. let clipPlane = scene.clipPlane5;
  726. effect.setFloat4("vClipPlane5", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  727. }
  728. if (scene.clipPlane6) {
  729. let clipPlane = scene.clipPlane6;
  730. effect.setFloat4("vClipPlane6", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  731. }
  732. }
  733. }