materialHelper.ts 38 KB

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