materialHelper.ts 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833
  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, variableName = "vEyePosition"): void {
  33. if (scene._forcedViewPosition) {
  34. effect.setVector3(variableName, 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(variableName, 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["SHADOWCSMNOBLEND" + lightIndex] = false;
  309. defines["SHADOWCSM_RIGHTHANDED" + lightIndex] = false;
  310. defines["SHADOWPCF" + lightIndex] = false;
  311. defines["SHADOWPCSS" + lightIndex] = false;
  312. defines["SHADOWPOISSON" + lightIndex] = false;
  313. defines["SHADOWESM" + lightIndex] = false;
  314. defines["SHADOWCUBE" + lightIndex] = false;
  315. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  316. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  317. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  318. var shadowGenerator = light.getShadowGenerator();
  319. if (shadowGenerator) {
  320. const shadowMap = shadowGenerator.getShadowMap();
  321. if (shadowMap) {
  322. if (shadowMap.renderList && shadowMap.renderList.length > 0) {
  323. state.shadowEnabled = true;
  324. shadowGenerator.prepareDefines(defines, lightIndex);
  325. }
  326. }
  327. }
  328. }
  329. if (light.lightmapMode != Light.LIGHTMAP_DEFAULT) {
  330. state.lightmapMode = true;
  331. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  332. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == Light.LIGHTMAP_SHADOWSONLY);
  333. } else {
  334. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  335. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  336. }
  337. }
  338. /**
  339. * Prepares the defines related to the light information passed in parameter
  340. * @param scene The scene we are intending to draw
  341. * @param mesh The mesh the effect is compiling for
  342. * @param defines The defines to update
  343. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  344. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  345. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  346. * @returns true if normals will be required for the rest of the effect
  347. */
  348. public static PrepareDefinesForLights(scene: Scene, mesh: AbstractMesh, defines: any, specularSupported: boolean, maxSimultaneousLights = 4, disableLighting = false): boolean {
  349. if (!defines._areLightsDirty) {
  350. return defines._needNormals;
  351. }
  352. var lightIndex = 0;
  353. let state = {
  354. needNormals: false,
  355. needRebuild: false,
  356. lightmapMode: false,
  357. shadowEnabled: false,
  358. specularEnabled: false
  359. };
  360. if (scene.lightsEnabled && !disableLighting) {
  361. for (var light of mesh.lightSources) {
  362. this.PrepareDefinesForLight(scene, mesh, light, lightIndex, defines, specularSupported, state);
  363. lightIndex++;
  364. if (lightIndex === maxSimultaneousLights) {
  365. break;
  366. }
  367. }
  368. }
  369. defines["SPECULARTERM"] = state.specularEnabled;
  370. defines["SHADOWS"] = state.shadowEnabled;
  371. // Resetting all other lights if any
  372. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  373. if (defines["LIGHT" + index] !== undefined) {
  374. defines["LIGHT" + index] = false;
  375. defines["HEMILIGHT" + index] = false;
  376. defines["POINTLIGHT" + index] = false;
  377. defines["DIRLIGHT" + index] = false;
  378. defines["SPOTLIGHT" + index] = false;
  379. defines["SHADOW" + index] = false;
  380. defines["SHADOWCSM" + index] = false;
  381. defines["SHADOWCSMDEBUG" + index] = false;
  382. defines["SHADOWCSMNUM_CASCADES" + index] = false;
  383. defines["SHADOWCSMUSESHADOWMAXZ" + index] = false;
  384. defines["SHADOWCSMNOBLEND" + index] = false;
  385. defines["SHADOWCSM_RIGHTHANDED" + index] = false;
  386. defines["SHADOWPCF" + index] = false;
  387. defines["SHADOWPCSS" + index] = false;
  388. defines["SHADOWPOISSON" + index] = false;
  389. defines["SHADOWESM" + index] = false;
  390. defines["SHADOWCUBE" + index] = false;
  391. defines["SHADOWLOWQUALITY" + index] = false;
  392. defines["SHADOWMEDIUMQUALITY" + index] = false;
  393. }
  394. }
  395. let caps = scene.getEngine().getCaps();
  396. if (defines["SHADOWFLOAT"] === undefined) {
  397. state.needRebuild = true;
  398. }
  399. defines["SHADOWFLOAT"] = state.shadowEnabled &&
  400. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  401. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  402. defines["LIGHTMAPEXCLUDED"] = state.lightmapMode;
  403. if (state.needRebuild) {
  404. defines.rebuild();
  405. }
  406. return state.needNormals;
  407. }
  408. /**
  409. * Prepares the uniforms and samplers list to be used in the effect (for a specific light)
  410. * @param lightIndex defines the light index
  411. * @param uniformsList The uniform list
  412. * @param samplersList The sampler list
  413. * @param projectedLightTexture defines if projected texture must be used
  414. * @param uniformBuffersList defines an optional list of uniform buffers
  415. */
  416. public static PrepareUniformsAndSamplersForLight(lightIndex: number, uniformsList: string[], samplersList: string[], projectedLightTexture?: any, uniformBuffersList: Nullable<string[]> = null) {
  417. uniformsList.push(
  418. "vLightData" + lightIndex,
  419. "vLightDiffuse" + lightIndex,
  420. "vLightSpecular" + lightIndex,
  421. "vLightDirection" + lightIndex,
  422. "vLightFalloff" + lightIndex,
  423. "vLightGround" + lightIndex,
  424. "lightMatrix" + lightIndex,
  425. "shadowsInfo" + lightIndex,
  426. "depthValues" + lightIndex,
  427. );
  428. if (uniformBuffersList) {
  429. uniformBuffersList.push("Light" + lightIndex);
  430. }
  431. samplersList.push("shadowSampler" + lightIndex);
  432. samplersList.push("depthSampler" + lightIndex);
  433. uniformsList.push(
  434. "viewFrustumZ" + lightIndex,
  435. "cascadeBlendFactor" + lightIndex,
  436. "lightSizeUVCorrection" + lightIndex,
  437. "depthCorrection" + lightIndex,
  438. "penumbraDarkness" + lightIndex,
  439. "frustumLengths" + lightIndex,
  440. );
  441. if (projectedLightTexture) {
  442. samplersList.push("projectionLightSampler" + lightIndex);
  443. uniformsList.push(
  444. "textureProjectionMatrix" + lightIndex,
  445. );
  446. }
  447. }
  448. /**
  449. * Prepares the uniforms and samplers list to be used in the effect
  450. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  451. * @param samplersList The sampler list
  452. * @param defines The defines helping in the list generation
  453. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  454. */
  455. public static PrepareUniformsAndSamplersList(uniformsListOrOptions: string[] | IEffectCreationOptions, samplersList?: string[], defines?: any, maxSimultaneousLights = 4): void {
  456. let uniformsList: string[];
  457. let uniformBuffersList: Nullable<string[]> = null;
  458. if ((<IEffectCreationOptions>uniformsListOrOptions).uniformsNames) {
  459. var options = <IEffectCreationOptions>uniformsListOrOptions;
  460. uniformsList = options.uniformsNames;
  461. uniformBuffersList = options.uniformBuffersNames;
  462. samplersList = options.samplers;
  463. defines = options.defines;
  464. maxSimultaneousLights = options.maxSimultaneousLights || 0;
  465. } else {
  466. uniformsList = <string[]>uniformsListOrOptions;
  467. if (!samplersList) {
  468. samplersList = [];
  469. }
  470. }
  471. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  472. if (!defines["LIGHT" + lightIndex]) {
  473. break;
  474. }
  475. this.PrepareUniformsAndSamplersForLight(lightIndex, uniformsList, samplersList, defines["PROJECTEDLIGHTTEXTURE" + lightIndex], uniformBuffersList);
  476. }
  477. if (defines["NUM_MORPH_INFLUENCERS"]) {
  478. uniformsList.push("morphTargetInfluences");
  479. }
  480. }
  481. /**
  482. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  483. * @param defines The defines to update while falling back
  484. * @param fallbacks The authorized effect fallbacks
  485. * @param maxSimultaneousLights The maximum number of lights allowed
  486. * @param rank the current rank of the Effect
  487. * @returns The newly affected rank
  488. */
  489. public static HandleFallbacksForShadows(defines: any, fallbacks: EffectFallbacks, maxSimultaneousLights = 4, rank = 0): number {
  490. let lightFallbackRank = 0;
  491. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  492. if (!defines["LIGHT" + lightIndex]) {
  493. break;
  494. }
  495. if (lightIndex > 0) {
  496. lightFallbackRank = rank + lightIndex;
  497. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  498. }
  499. if (!defines["SHADOWS"]) {
  500. if (defines["SHADOW" + lightIndex]) {
  501. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  502. }
  503. if (defines["SHADOWPCF" + lightIndex]) {
  504. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  505. }
  506. if (defines["SHADOWPCSS" + lightIndex]) {
  507. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  508. }
  509. if (defines["SHADOWPOISSON" + lightIndex]) {
  510. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  511. }
  512. if (defines["SHADOWESM" + lightIndex]) {
  513. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  514. }
  515. }
  516. }
  517. return lightFallbackRank++;
  518. }
  519. private static _TmpMorphInfluencers = { "NUM_MORPH_INFLUENCERS": 0 };
  520. /**
  521. * Prepares the list of attributes required for morph targets according to the effect defines.
  522. * @param attribs The current list of supported attribs
  523. * @param mesh The mesh to prepare the morph targets attributes for
  524. * @param influencers The number of influencers
  525. */
  526. public static PrepareAttributesForMorphTargetsInfluencers(attribs: string[], mesh: AbstractMesh, influencers: number): void {
  527. this._TmpMorphInfluencers.NUM_MORPH_INFLUENCERS = influencers;
  528. this.PrepareAttributesForMorphTargets(attribs, mesh, this._TmpMorphInfluencers);
  529. }
  530. /**
  531. * Prepares the list of attributes required for morph targets according to the effect defines.
  532. * @param attribs The current list of supported attribs
  533. * @param mesh The mesh to prepare the morph targets attributes for
  534. * @param defines The current Defines of the effect
  535. */
  536. public static PrepareAttributesForMorphTargets(attribs: string[], mesh: AbstractMesh, defines: any): void {
  537. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  538. if (influencers > 0 && EngineStore.LastCreatedEngine) {
  539. var maxAttributesCount = EngineStore.LastCreatedEngine.getCaps().maxVertexAttribs;
  540. var manager = (<Mesh>mesh).morphTargetManager;
  541. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  542. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  543. var uv = manager && manager.supportsUVs && defines["UV1"];
  544. for (var index = 0; index < influencers; index++) {
  545. attribs.push(VertexBuffer.PositionKind + index);
  546. if (normal) {
  547. attribs.push(VertexBuffer.NormalKind + index);
  548. }
  549. if (tangent) {
  550. attribs.push(VertexBuffer.TangentKind + index);
  551. }
  552. if (uv) {
  553. attribs.push(VertexBuffer.UVKind + "_" + index);
  554. }
  555. if (attribs.length > maxAttributesCount) {
  556. Logger.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  557. }
  558. }
  559. }
  560. }
  561. /**
  562. * Prepares the list of attributes required for bones according to the effect defines.
  563. * @param attribs The current list of supported attribs
  564. * @param mesh The mesh to prepare the bones attributes for
  565. * @param defines The current Defines of the effect
  566. * @param fallbacks The current efffect fallback strategy
  567. */
  568. public static PrepareAttributesForBones(attribs: string[], mesh: AbstractMesh, defines: any, fallbacks: EffectFallbacks): void {
  569. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  570. fallbacks.addCPUSkinningFallback(0, mesh);
  571. attribs.push(VertexBuffer.MatricesIndicesKind);
  572. attribs.push(VertexBuffer.MatricesWeightsKind);
  573. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  574. attribs.push(VertexBuffer.MatricesIndicesExtraKind);
  575. attribs.push(VertexBuffer.MatricesWeightsExtraKind);
  576. }
  577. }
  578. }
  579. /**
  580. * Check and prepare the list of attributes required for instances according to the effect defines.
  581. * @param attribs The current list of supported attribs
  582. * @param defines The current MaterialDefines of the effect
  583. */
  584. public static PrepareAttributesForInstances(attribs: string[], defines: MaterialDefines): void {
  585. if (defines["INSTANCES"]) {
  586. this.PushAttributesForInstances(attribs);
  587. }
  588. }
  589. /**
  590. * Add the list of attributes required for instances to the attribs array.
  591. * @param attribs The current list of supported attribs
  592. */
  593. public static PushAttributesForInstances(attribs: string[]): void {
  594. attribs.push("world0");
  595. attribs.push("world1");
  596. attribs.push("world2");
  597. attribs.push("world3");
  598. }
  599. /**
  600. * Binds the light information to the effect.
  601. * @param light The light containing the generator
  602. * @param effect The effect we are binding the data to
  603. * @param lightIndex The light index in the effect used to render
  604. */
  605. public static BindLightProperties(light: Light, effect: Effect, lightIndex: number): void {
  606. light.transferToEffect(effect, lightIndex + "");
  607. }
  608. /**
  609. * Binds the lights information from the scene to the effect for the given mesh.
  610. * @param light Light to bind
  611. * @param lightIndex Light index
  612. * @param scene The scene where the light belongs to
  613. * @param effect The effect we are binding the data to
  614. * @param useSpecular Defines if specular is supported
  615. * @param rebuildInParallel Specifies whether the shader is rebuilding in parallel
  616. */
  617. public static BindLight(light: Light, lightIndex: number, scene: Scene, effect: Effect, useSpecular: boolean, rebuildInParallel = false): void {
  618. light._bindLight(lightIndex, scene, effect, useSpecular, rebuildInParallel);
  619. }
  620. /**
  621. * Binds the lights information from the scene to the effect for the given mesh.
  622. * @param scene The scene the lights belongs to
  623. * @param mesh The mesh we are binding the information to render
  624. * @param effect The effect we are binding the data to
  625. * @param defines The generated defines for the effect
  626. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  627. * @param rebuildInParallel Specifies whether the shader is rebuilding in parallel
  628. */
  629. public static BindLights(scene: Scene, mesh: AbstractMesh, effect: Effect, defines: any, maxSimultaneousLights = 4, rebuildInParallel = false): void {
  630. let len = Math.min(mesh.lightSources.length, maxSimultaneousLights);
  631. for (var i = 0; i < len; i++) {
  632. let light = mesh.lightSources[i];
  633. this.BindLight(light, i, scene, effect, typeof defines === "boolean" ? defines : defines["SPECULARTERM"], rebuildInParallel);
  634. }
  635. }
  636. private static _tempFogColor = Color3.Black();
  637. /**
  638. * Binds the fog information from the scene to the effect for the given mesh.
  639. * @param scene The scene the lights belongs to
  640. * @param mesh The mesh we are binding the information to render
  641. * @param effect The effect we are binding the data to
  642. * @param linearSpace Defines if the fog effect is applied in linear space
  643. */
  644. public static BindFogParameters(scene: Scene, mesh: AbstractMesh, effect: Effect, linearSpace = false): void {
  645. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== Scene.FOGMODE_NONE) {
  646. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  647. // Convert fog color to linear space if used in a linear space computed shader.
  648. if (linearSpace) {
  649. scene.fogColor.toLinearSpaceToRef(this._tempFogColor);
  650. effect.setColor3("vFogColor", this._tempFogColor);
  651. }
  652. else {
  653. effect.setColor3("vFogColor", scene.fogColor);
  654. }
  655. }
  656. }
  657. /**
  658. * Binds the bones information from the mesh to the effect.
  659. * @param mesh The mesh we are binding the information to render
  660. * @param effect The effect we are binding the data to
  661. */
  662. public static BindBonesParameters(mesh?: AbstractMesh, effect?: Effect): void {
  663. if (!effect || !mesh) {
  664. return;
  665. }
  666. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  667. mesh.computeBonesUsingShaders = false;
  668. }
  669. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  670. const skeleton = mesh.skeleton;
  671. if (skeleton.isUsingTextureForMatrices && effect.getUniformIndex("boneTextureWidth") > -1) {
  672. const boneTexture = skeleton.getTransformMatrixTexture(mesh);
  673. effect.setTexture("boneSampler", boneTexture);
  674. effect.setFloat("boneTextureWidth", 4.0 * (skeleton.bones.length + 1));
  675. } else {
  676. const matrices = skeleton.getTransformMatrices(mesh);
  677. if (matrices) {
  678. effect.setMatrices("mBones", matrices);
  679. }
  680. }
  681. }
  682. }
  683. /**
  684. * Binds the morph targets information from the mesh to the effect.
  685. * @param abstractMesh The mesh we are binding the information to render
  686. * @param effect The effect we are binding the data to
  687. */
  688. public static BindMorphTargetParameters(abstractMesh: AbstractMesh, effect: Effect): void {
  689. let manager = (<Mesh>abstractMesh).morphTargetManager;
  690. if (!abstractMesh || !manager) {
  691. return;
  692. }
  693. effect.setFloatArray("morphTargetInfluences", manager.influences);
  694. }
  695. /**
  696. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  697. * @param defines The generated defines used in the effect
  698. * @param effect The effect we are binding the data to
  699. * @param scene The scene we are willing to render with logarithmic scale for
  700. */
  701. public static BindLogDepth(defines: any, effect: Effect, scene: Scene): void {
  702. if (defines["LOGARITHMICDEPTH"]) {
  703. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log((<Camera>scene.activeCamera).maxZ + 1.0) / Math.LN2));
  704. }
  705. }
  706. /**
  707. * Binds the clip plane information from the scene to the effect.
  708. * @param scene The scene the clip plane information are extracted from
  709. * @param effect The effect we are binding the data to
  710. */
  711. public static BindClipPlane(effect: Effect, scene: Scene): void {
  712. if (scene.clipPlane) {
  713. let clipPlane = scene.clipPlane;
  714. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  715. }
  716. if (scene.clipPlane2) {
  717. let clipPlane = scene.clipPlane2;
  718. effect.setFloat4("vClipPlane2", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  719. }
  720. if (scene.clipPlane3) {
  721. let clipPlane = scene.clipPlane3;
  722. effect.setFloat4("vClipPlane3", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  723. }
  724. if (scene.clipPlane4) {
  725. let clipPlane = scene.clipPlane4;
  726. effect.setFloat4("vClipPlane4", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  727. }
  728. if (scene.clipPlane5) {
  729. let clipPlane = scene.clipPlane5;
  730. effect.setFloat4("vClipPlane5", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  731. }
  732. if (scene.clipPlane6) {
  733. let clipPlane = scene.clipPlane6;
  734. effect.setFloat4("vClipPlane6", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  735. }
  736. }
  737. }