materialHelper.functions.js 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823
  1. import { Logger } from "../Misc/logger.js";
  2. import { Color3 } from "../Maths/math.color.js";
  3. import { EngineStore } from "../Engines/engineStore.js";
  4. import { LightConstants } from "../Lights/lightConstants.js";
  5. import { prepareDefinesForClipPlanes } from "./clipPlaneMaterialHelper.js";
  6. // Temps
  7. const _TempFogColor = Color3.Black();
  8. const _TmpMorphInfluencers = { NUM_MORPH_INFLUENCERS: 0 };
  9. /**
  10. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  11. * @param defines The generated defines used in the effect
  12. * @param effect The effect we are binding the data to
  13. * @param scene The scene we are willing to render with logarithmic scale for
  14. */
  15. export function BindLogDepth(defines, effect, scene) {
  16. if (!defines || defines["LOGARITHMICDEPTH"] || (defines.indexOf && defines.indexOf("LOGARITHMICDEPTH") >= 0)) {
  17. const camera = scene.activeCamera;
  18. if (camera.mode === 1) {
  19. Logger.Error("Logarithmic depth is not compatible with orthographic cameras!", 20);
  20. }
  21. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(camera.maxZ + 1.0) / Math.LN2));
  22. }
  23. }
  24. /**
  25. * Binds the fog information from the scene to the effect for the given mesh.
  26. * @param scene The scene the lights belongs to
  27. * @param mesh The mesh we are binding the information to render
  28. * @param effect The effect we are binding the data to
  29. * @param linearSpace Defines if the fog effect is applied in linear space
  30. */
  31. export function BindFogParameters(scene, mesh, effect, linearSpace = false) {
  32. if (effect && scene.fogEnabled && (!mesh || mesh.applyFog) && scene.fogMode !== 0) {
  33. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  34. // Convert fog color to linear space if used in a linear space computed shader.
  35. if (linearSpace) {
  36. scene.fogColor.toLinearSpaceToRef(_TempFogColor, scene.getEngine().useExactSrgbConversions);
  37. effect.setColor3("vFogColor", _TempFogColor);
  38. }
  39. else {
  40. effect.setColor3("vFogColor", scene.fogColor);
  41. }
  42. }
  43. }
  44. /**
  45. * Prepares the list of attributes required for morph targets according to the effect defines.
  46. * @param attribs The current list of supported attribs
  47. * @param mesh The mesh to prepare the morph targets attributes for
  48. * @param influencers The number of influencers
  49. */
  50. export function PrepareAttributesForMorphTargetsInfluencers(attribs, mesh, influencers) {
  51. _TmpMorphInfluencers.NUM_MORPH_INFLUENCERS = influencers;
  52. PrepareAttributesForMorphTargets(attribs, mesh, _TmpMorphInfluencers);
  53. }
  54. /**
  55. * Prepares the list of attributes required for morph targets according to the effect defines.
  56. * @param attribs The current list of supported attribs
  57. * @param mesh The mesh to prepare the morph targets attributes for
  58. * @param defines The current Defines of the effect
  59. */
  60. export function PrepareAttributesForMorphTargets(attribs, mesh, defines) {
  61. const influencers = defines["NUM_MORPH_INFLUENCERS"];
  62. if (influencers > 0 && EngineStore.LastCreatedEngine) {
  63. const maxAttributesCount = EngineStore.LastCreatedEngine.getCaps().maxVertexAttribs;
  64. const manager = mesh.morphTargetManager;
  65. if (manager?.isUsingTextureForTargets) {
  66. return;
  67. }
  68. const normal = manager && manager.supportsNormals && defines["NORMAL"];
  69. const tangent = manager && manager.supportsTangents && defines["TANGENT"];
  70. const uv = manager && manager.supportsUVs && defines["UV1"];
  71. for (let index = 0; index < influencers; index++) {
  72. attribs.push(`position` + index);
  73. if (normal) {
  74. attribs.push(`normal` + index);
  75. }
  76. if (tangent) {
  77. attribs.push(`tangent` + index);
  78. }
  79. if (uv) {
  80. attribs.push(`uv` + "_" + index);
  81. }
  82. if (attribs.length > maxAttributesCount) {
  83. Logger.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  84. }
  85. }
  86. }
  87. }
  88. /**
  89. * Add the list of attributes required for instances to the attribs array.
  90. * @param attribs The current list of supported attribs
  91. * @param needsPreviousMatrices If the shader needs previous matrices
  92. */
  93. export function PushAttributesForInstances(attribs, needsPreviousMatrices = false) {
  94. attribs.push("world0");
  95. attribs.push("world1");
  96. attribs.push("world2");
  97. attribs.push("world3");
  98. if (needsPreviousMatrices) {
  99. attribs.push("previousWorld0");
  100. attribs.push("previousWorld1");
  101. attribs.push("previousWorld2");
  102. attribs.push("previousWorld3");
  103. }
  104. }
  105. /**
  106. * Binds the morph targets information from the mesh to the effect.
  107. * @param abstractMesh The mesh we are binding the information to render
  108. * @param effect The effect we are binding the data to
  109. */
  110. export function BindMorphTargetParameters(abstractMesh, effect) {
  111. const manager = abstractMesh.morphTargetManager;
  112. if (!abstractMesh || !manager) {
  113. return;
  114. }
  115. effect.setFloatArray("morphTargetInfluences", manager.influences);
  116. }
  117. /**
  118. * Binds the scene's uniform buffer to the effect.
  119. * @param effect defines the effect to bind to the scene uniform buffer
  120. * @param sceneUbo defines the uniform buffer storing scene data
  121. */
  122. export function BindSceneUniformBuffer(effect, sceneUbo) {
  123. sceneUbo.bindToEffect(effect, "Scene");
  124. }
  125. /**
  126. * Helps preparing the defines values about the UVs in used in the effect.
  127. * UVs are shared as much as we can across channels in the shaders.
  128. * @param texture The texture we are preparing the UVs for
  129. * @param defines The defines to update
  130. * @param key The channel key "diffuse", "specular"... used in the shader
  131. */
  132. export function PrepareDefinesForMergedUV(texture, defines, key) {
  133. defines._needUVs = true;
  134. defines[key] = true;
  135. if (texture.optimizeUVAllocation && texture.getTextureMatrix().isIdentityAs3x2()) {
  136. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  137. defines["MAINUV" + (texture.coordinatesIndex + 1)] = true;
  138. }
  139. else {
  140. defines[key + "DIRECTUV"] = 0;
  141. }
  142. }
  143. /**
  144. * Binds a texture matrix value to its corresponding uniform
  145. * @param texture The texture to bind the matrix for
  146. * @param uniformBuffer The uniform buffer receiving the data
  147. * @param key The channel key "diffuse", "specular"... used in the shader
  148. */
  149. export function BindTextureMatrix(texture, uniformBuffer, key) {
  150. const matrix = texture.getTextureMatrix();
  151. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  152. }
  153. /**
  154. * Prepares the list of attributes required for baked vertex animations according to the effect defines.
  155. * @param attribs The current list of supported attribs
  156. * @param mesh The mesh to prepare for baked vertex animations
  157. * @param defines The current Defines of the effect
  158. */
  159. export function PrepareAttributesForBakedVertexAnimation(attribs, mesh, defines) {
  160. const enabled = defines["BAKED_VERTEX_ANIMATION_TEXTURE"] && defines["INSTANCES"];
  161. if (enabled) {
  162. attribs.push("bakedVertexAnimationSettingsInstanced");
  163. }
  164. }
  165. // Copies the bones transformation matrices into the target array and returns the target's reference
  166. function _CopyBonesTransformationMatrices(source, target) {
  167. target.set(source);
  168. return target;
  169. }
  170. /**
  171. * Binds the bones information from the mesh to the effect.
  172. * @param mesh The mesh we are binding the information to render
  173. * @param effect The effect we are binding the data to
  174. * @param prePassConfiguration Configuration for the prepass, in case prepass is activated
  175. */
  176. export function BindBonesParameters(mesh, effect, prePassConfiguration) {
  177. if (!effect || !mesh) {
  178. return;
  179. }
  180. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  181. mesh.computeBonesUsingShaders = false;
  182. }
  183. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  184. const skeleton = mesh.skeleton;
  185. if (skeleton.isUsingTextureForMatrices && effect.getUniformIndex("boneTextureWidth") > -1) {
  186. const boneTexture = skeleton.getTransformMatrixTexture(mesh);
  187. effect.setTexture("boneSampler", boneTexture);
  188. effect.setFloat("boneTextureWidth", 4.0 * (skeleton.bones.length + 1));
  189. }
  190. else {
  191. const matrices = skeleton.getTransformMatrices(mesh);
  192. if (matrices) {
  193. effect.setMatrices("mBones", matrices);
  194. if (prePassConfiguration && mesh.getScene().prePassRenderer && mesh.getScene().prePassRenderer.getIndex(2)) {
  195. if (!prePassConfiguration.previousBones[mesh.uniqueId]) {
  196. prePassConfiguration.previousBones[mesh.uniqueId] = matrices.slice();
  197. }
  198. effect.setMatrices("mPreviousBones", prePassConfiguration.previousBones[mesh.uniqueId]);
  199. _CopyBonesTransformationMatrices(matrices, prePassConfiguration.previousBones[mesh.uniqueId]);
  200. }
  201. }
  202. }
  203. }
  204. }
  205. /**
  206. * Binds the light information to the effect.
  207. * @param light The light containing the generator
  208. * @param effect The effect we are binding the data to
  209. * @param lightIndex The light index in the effect used to render
  210. */
  211. export function BindLightProperties(light, effect, lightIndex) {
  212. light.transferToEffect(effect, lightIndex + "");
  213. }
  214. /**
  215. * Binds the lights information from the scene to the effect for the given mesh.
  216. * @param light Light to bind
  217. * @param lightIndex Light index
  218. * @param scene The scene where the light belongs to
  219. * @param effect The effect we are binding the data to
  220. * @param useSpecular Defines if specular is supported
  221. * @param receiveShadows Defines if the effect (mesh) we bind the light for receives shadows
  222. */
  223. export function BindLight(light, lightIndex, scene, effect, useSpecular, receiveShadows = true) {
  224. light._bindLight(lightIndex, scene, effect, useSpecular, receiveShadows);
  225. }
  226. /**
  227. * Binds the lights information from the scene to the effect for the given mesh.
  228. * @param scene The scene the lights belongs to
  229. * @param mesh The mesh we are binding the information to render
  230. * @param effect The effect we are binding the data to
  231. * @param defines The generated defines for the effect
  232. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  233. */
  234. export function BindLights(scene, mesh, effect, defines, maxSimultaneousLights = 4) {
  235. const len = Math.min(mesh.lightSources.length, maxSimultaneousLights);
  236. for (let i = 0; i < len; i++) {
  237. const light = mesh.lightSources[i];
  238. BindLight(light, i, scene, effect, typeof defines === "boolean" ? defines : defines["SPECULARTERM"], mesh.receiveShadows);
  239. }
  240. }
  241. /**
  242. * Prepares the list of attributes required for bones according to the effect defines.
  243. * @param attribs The current list of supported attribs
  244. * @param mesh The mesh to prepare the bones attributes for
  245. * @param defines The current Defines of the effect
  246. * @param fallbacks The current effect fallback strategy
  247. */
  248. export function PrepareAttributesForBones(attribs, mesh, defines, fallbacks) {
  249. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  250. fallbacks.addCPUSkinningFallback(0, mesh);
  251. attribs.push(`matricesIndices`);
  252. attribs.push(`matricesWeights`);
  253. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  254. attribs.push(`matricesIndicesExtra`);
  255. attribs.push(`matricesWeightsExtra`);
  256. }
  257. }
  258. }
  259. /**
  260. * Check and prepare the list of attributes required for instances according to the effect defines.
  261. * @param attribs The current list of supported attribs
  262. * @param defines The current MaterialDefines of the effect
  263. */
  264. export function PrepareAttributesForInstances(attribs, defines) {
  265. if (defines["INSTANCES"] || defines["THIN_INSTANCES"]) {
  266. PushAttributesForInstances(attribs, !!defines["PREPASS_VELOCITY"]);
  267. }
  268. if (defines.INSTANCESCOLOR) {
  269. attribs.push(`instanceColor`);
  270. }
  271. }
  272. /**
  273. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  274. * @param defines The defines to update while falling back
  275. * @param fallbacks The authorized effect fallbacks
  276. * @param maxSimultaneousLights The maximum number of lights allowed
  277. * @param rank the current rank of the Effect
  278. * @returns The newly affected rank
  279. */
  280. export function HandleFallbacksForShadows(defines, fallbacks, maxSimultaneousLights = 4, rank = 0) {
  281. let lightFallbackRank = 0;
  282. for (let lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  283. if (!defines["LIGHT" + lightIndex]) {
  284. break;
  285. }
  286. if (lightIndex > 0) {
  287. lightFallbackRank = rank + lightIndex;
  288. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  289. }
  290. if (!defines["SHADOWS"]) {
  291. if (defines["SHADOW" + lightIndex]) {
  292. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  293. }
  294. if (defines["SHADOWPCF" + lightIndex]) {
  295. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  296. }
  297. if (defines["SHADOWPCSS" + lightIndex]) {
  298. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  299. }
  300. if (defines["SHADOWPOISSON" + lightIndex]) {
  301. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  302. }
  303. if (defines["SHADOWESM" + lightIndex]) {
  304. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  305. }
  306. if (defines["SHADOWCLOSEESM" + lightIndex]) {
  307. fallbacks.addFallback(rank, "SHADOWCLOSEESM" + lightIndex);
  308. }
  309. }
  310. }
  311. return lightFallbackRank++;
  312. }
  313. /**
  314. * Gets the current status of the fog (should it be enabled?)
  315. * @param mesh defines the mesh to evaluate for fog support
  316. * @param scene defines the hosting scene
  317. * @returns true if fog must be enabled
  318. */
  319. export function GetFogState(mesh, scene) {
  320. return scene.fogEnabled && mesh.applyFog && scene.fogMode !== 0;
  321. }
  322. /**
  323. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  324. * @param mesh defines the current mesh
  325. * @param scene defines the current scene
  326. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  327. * @param pointsCloud defines if point cloud rendering has to be turned on
  328. * @param fogEnabled defines if fog has to be turned on
  329. * @param alphaTest defines if alpha testing has to be turned on
  330. * @param defines defines the current list of defines
  331. * @param applyDecalAfterDetail Defines if the decal is applied after or before the detail
  332. */
  333. export function PrepareDefinesForMisc(mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines, applyDecalAfterDetail = false) {
  334. if (defines._areMiscDirty) {
  335. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  336. defines["POINTSIZE"] = pointsCloud;
  337. defines["FOG"] = fogEnabled && GetFogState(mesh, scene);
  338. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  339. defines["ALPHATEST"] = alphaTest;
  340. defines["DECAL_AFTER_DETAIL"] = applyDecalAfterDetail;
  341. }
  342. }
  343. /**
  344. * Prepares the defines related to the light information passed in parameter
  345. * @param scene The scene we are intending to draw
  346. * @param mesh The mesh the effect is compiling for
  347. * @param defines The defines to update
  348. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  349. * @param maxSimultaneousLights Specifies how manuy lights can be added to the effect at max
  350. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  351. * @returns true if normals will be required for the rest of the effect
  352. */
  353. export function PrepareDefinesForLights(scene, mesh, defines, specularSupported, maxSimultaneousLights = 4, disableLighting = false) {
  354. if (!defines._areLightsDirty) {
  355. return defines._needNormals;
  356. }
  357. let lightIndex = 0;
  358. const state = {
  359. needNormals: defines._needNormals,
  360. needRebuild: false,
  361. lightmapMode: false,
  362. shadowEnabled: false,
  363. specularEnabled: false,
  364. };
  365. if (scene.lightsEnabled && !disableLighting) {
  366. for (const light of mesh.lightSources) {
  367. PrepareDefinesForLight(scene, mesh, light, lightIndex, defines, specularSupported, state);
  368. lightIndex++;
  369. if (lightIndex === maxSimultaneousLights) {
  370. break;
  371. }
  372. }
  373. }
  374. defines["SPECULARTERM"] = state.specularEnabled;
  375. defines["SHADOWS"] = state.shadowEnabled;
  376. // Resetting all other lights if any
  377. for (let index = lightIndex; index < maxSimultaneousLights; index++) {
  378. if (defines["LIGHT" + index] !== undefined) {
  379. defines["LIGHT" + index] = false;
  380. defines["HEMILIGHT" + index] = false;
  381. defines["POINTLIGHT" + index] = false;
  382. defines["DIRLIGHT" + index] = false;
  383. defines["SPOTLIGHT" + index] = false;
  384. defines["SHADOW" + index] = false;
  385. defines["SHADOWCSM" + index] = false;
  386. defines["SHADOWCSMDEBUG" + index] = false;
  387. defines["SHADOWCSMNUM_CASCADES" + index] = false;
  388. defines["SHADOWCSMUSESHADOWMAXZ" + index] = false;
  389. defines["SHADOWCSMNOBLEND" + index] = false;
  390. defines["SHADOWCSM_RIGHTHANDED" + index] = false;
  391. defines["SHADOWPCF" + index] = false;
  392. defines["SHADOWPCSS" + index] = false;
  393. defines["SHADOWPOISSON" + index] = false;
  394. defines["SHADOWESM" + index] = false;
  395. defines["SHADOWCLOSEESM" + index] = false;
  396. defines["SHADOWCUBE" + index] = false;
  397. defines["SHADOWLOWQUALITY" + index] = false;
  398. defines["SHADOWMEDIUMQUALITY" + index] = false;
  399. }
  400. }
  401. const caps = scene.getEngine().getCaps();
  402. if (defines["SHADOWFLOAT"] === undefined) {
  403. state.needRebuild = true;
  404. }
  405. defines["SHADOWFLOAT"] =
  406. state.shadowEnabled && ((caps.textureFloatRender && caps.textureFloatLinearFiltering) || (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  407. defines["LIGHTMAPEXCLUDED"] = state.lightmapMode;
  408. if (state.needRebuild) {
  409. defines.rebuild();
  410. }
  411. return state.needNormals;
  412. }
  413. /**
  414. * Prepares the defines related to the light information passed in parameter
  415. * @param scene The scene we are intending to draw
  416. * @param mesh The mesh the effect is compiling for
  417. * @param light The light the effect is compiling for
  418. * @param lightIndex The index of the light
  419. * @param defines The defines to update
  420. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  421. * @param state Defines the current state regarding what is needed (normals, etc...)
  422. * @param state.needNormals
  423. * @param state.needRebuild
  424. * @param state.shadowEnabled
  425. * @param state.specularEnabled
  426. * @param state.lightmapMode
  427. */
  428. export function PrepareDefinesForLight(scene, mesh, light, lightIndex, defines, specularSupported, state) {
  429. state.needNormals = true;
  430. if (defines["LIGHT" + lightIndex] === undefined) {
  431. state.needRebuild = true;
  432. }
  433. defines["LIGHT" + lightIndex] = true;
  434. defines["SPOTLIGHT" + lightIndex] = false;
  435. defines["HEMILIGHT" + lightIndex] = false;
  436. defines["POINTLIGHT" + lightIndex] = false;
  437. defines["DIRLIGHT" + lightIndex] = false;
  438. light.prepareLightSpecificDefines(defines, lightIndex);
  439. // FallOff.
  440. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = false;
  441. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = false;
  442. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = false;
  443. switch (light.falloffType) {
  444. case LightConstants.FALLOFF_GLTF:
  445. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = true;
  446. break;
  447. case LightConstants.FALLOFF_PHYSICAL:
  448. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = true;
  449. break;
  450. case LightConstants.FALLOFF_STANDARD:
  451. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = true;
  452. break;
  453. }
  454. // Specular
  455. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  456. state.specularEnabled = true;
  457. }
  458. // Shadows
  459. defines["SHADOW" + lightIndex] = false;
  460. defines["SHADOWCSM" + lightIndex] = false;
  461. defines["SHADOWCSMDEBUG" + lightIndex] = false;
  462. defines["SHADOWCSMNUM_CASCADES" + lightIndex] = false;
  463. defines["SHADOWCSMUSESHADOWMAXZ" + lightIndex] = false;
  464. defines["SHADOWCSMNOBLEND" + lightIndex] = false;
  465. defines["SHADOWCSM_RIGHTHANDED" + lightIndex] = false;
  466. defines["SHADOWPCF" + lightIndex] = false;
  467. defines["SHADOWPCSS" + lightIndex] = false;
  468. defines["SHADOWPOISSON" + lightIndex] = false;
  469. defines["SHADOWESM" + lightIndex] = false;
  470. defines["SHADOWCLOSEESM" + lightIndex] = false;
  471. defines["SHADOWCUBE" + lightIndex] = false;
  472. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  473. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  474. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  475. const shadowGenerator = light.getShadowGenerator(scene.activeCamera) ?? light.getShadowGenerator();
  476. if (shadowGenerator) {
  477. const shadowMap = shadowGenerator.getShadowMap();
  478. if (shadowMap) {
  479. if (shadowMap.renderList && shadowMap.renderList.length > 0) {
  480. state.shadowEnabled = true;
  481. shadowGenerator.prepareDefines(defines, lightIndex);
  482. }
  483. }
  484. }
  485. }
  486. if (light.lightmapMode != LightConstants.LIGHTMAP_DEFAULT) {
  487. state.lightmapMode = true;
  488. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  489. defines["LIGHTMAPNOSPECULAR" + lightIndex] = light.lightmapMode == LightConstants.LIGHTMAP_SHADOWSONLY;
  490. }
  491. else {
  492. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  493. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  494. }
  495. }
  496. /**
  497. * Helper used to prepare the list of defines associated with frame values for shader compilation
  498. * @param scene defines the current scene
  499. * @param engine defines the current engine
  500. * @param material defines the material we are compiling the shader for
  501. * @param defines specifies the list of active defines
  502. * @param useInstances defines if instances have to be turned on
  503. * @param useClipPlane defines if clip plane have to be turned on
  504. * @param useThinInstances defines if thin instances have to be turned on
  505. */
  506. export function PrepareDefinesForFrameBoundValues(scene, engine, material, defines, useInstances, useClipPlane = null, useThinInstances = false) {
  507. let changed = PrepareDefinesForCamera(scene, defines);
  508. if (useClipPlane !== false) {
  509. changed = prepareDefinesForClipPlanes(material, scene, defines);
  510. }
  511. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  512. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  513. changed = true;
  514. }
  515. if (defines["INSTANCES"] !== useInstances) {
  516. defines["INSTANCES"] = useInstances;
  517. changed = true;
  518. }
  519. if (defines["THIN_INSTANCES"] !== useThinInstances) {
  520. defines["THIN_INSTANCES"] = useThinInstances;
  521. changed = true;
  522. }
  523. if (changed) {
  524. defines.markAsUnprocessed();
  525. }
  526. }
  527. /**
  528. * Prepares the defines for bones
  529. * @param mesh The mesh containing the geometry data we will draw
  530. * @param defines The defines to update
  531. */
  532. export function PrepareDefinesForBones(mesh, defines) {
  533. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  534. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  535. const materialSupportsBoneTexture = defines["BONETEXTURE"] !== undefined;
  536. if (mesh.skeleton.isUsingTextureForMatrices && materialSupportsBoneTexture) {
  537. defines["BONETEXTURE"] = true;
  538. }
  539. else {
  540. defines["BonesPerMesh"] = mesh.skeleton.bones.length + 1;
  541. defines["BONETEXTURE"] = materialSupportsBoneTexture ? false : undefined;
  542. const prePassRenderer = mesh.getScene().prePassRenderer;
  543. if (prePassRenderer && prePassRenderer.enabled) {
  544. const nonExcluded = prePassRenderer.excludedSkinnedMesh.indexOf(mesh) === -1;
  545. defines["BONES_VELOCITY_ENABLED"] = nonExcluded;
  546. }
  547. }
  548. }
  549. else {
  550. defines["NUM_BONE_INFLUENCERS"] = 0;
  551. defines["BonesPerMesh"] = 0;
  552. if (defines["BONETEXTURE"] !== undefined) {
  553. defines["BONETEXTURE"] = false;
  554. }
  555. }
  556. }
  557. /**
  558. * Prepares the defines for morph targets
  559. * @param mesh The mesh containing the geometry data we will draw
  560. * @param defines The defines to update
  561. */
  562. export function PrepareDefinesForMorphTargets(mesh, defines) {
  563. const manager = mesh.morphTargetManager;
  564. if (manager) {
  565. defines["MORPHTARGETS_UV"] = manager.supportsUVs && defines["UV1"];
  566. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  567. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  568. defines["NUM_MORPH_INFLUENCERS"] = manager.numMaxInfluencers || manager.numInfluencers;
  569. defines["MORPHTARGETS"] = defines["NUM_MORPH_INFLUENCERS"] > 0;
  570. defines["MORPHTARGETS_TEXTURE"] = manager.isUsingTextureForTargets;
  571. }
  572. else {
  573. defines["MORPHTARGETS_UV"] = false;
  574. defines["MORPHTARGETS_TANGENT"] = false;
  575. defines["MORPHTARGETS_NORMAL"] = false;
  576. defines["MORPHTARGETS"] = false;
  577. defines["NUM_MORPH_INFLUENCERS"] = 0;
  578. }
  579. }
  580. /**
  581. * Prepares the defines for baked vertex animation
  582. * @param mesh The mesh containing the geometry data we will draw
  583. * @param defines The defines to update
  584. */
  585. export function PrepareDefinesForBakedVertexAnimation(mesh, defines) {
  586. const manager = mesh.bakedVertexAnimationManager;
  587. defines["BAKED_VERTEX_ANIMATION_TEXTURE"] = manager && manager.isEnabled ? true : false;
  588. }
  589. /**
  590. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  591. * @param mesh The mesh containing the geometry data we will draw
  592. * @param defines The defines to update
  593. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  594. * @param useBones Precise whether bones should be used or not (override mesh info)
  595. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  596. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  597. * @param useBakedVertexAnimation Precise whether baked vertex animation should be used or not (override mesh info)
  598. * @returns false if defines are considered not dirty and have not been checked
  599. */
  600. export function PrepareDefinesForAttributes(mesh, defines, useVertexColor, useBones, useMorphTargets = false, useVertexAlpha = true, useBakedVertexAnimation = true) {
  601. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  602. return false;
  603. }
  604. defines._normals = defines._needNormals;
  605. defines._uvs = defines._needUVs;
  606. defines["NORMAL"] = defines._needNormals && mesh.isVerticesDataPresent(`normal`);
  607. if (defines._needNormals && mesh.isVerticesDataPresent(`tangent`)) {
  608. defines["TANGENT"] = true;
  609. }
  610. for (let i = 1; i <= 6; ++i) {
  611. defines["UV" + i] = defines._needUVs ? mesh.isVerticesDataPresent(`uv${i === 1 ? "" : i}`) : false;
  612. }
  613. if (useVertexColor) {
  614. const hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(`color`);
  615. defines["VERTEXCOLOR"] = hasVertexColors;
  616. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  617. }
  618. if (mesh.isVerticesDataPresent(`instanceColor`) && (mesh.hasInstances || mesh.hasThinInstances)) {
  619. defines["INSTANCESCOLOR"] = true;
  620. }
  621. if (useBones) {
  622. PrepareDefinesForBones(mesh, defines);
  623. }
  624. if (useMorphTargets) {
  625. PrepareDefinesForMorphTargets(mesh, defines);
  626. }
  627. if (useBakedVertexAnimation) {
  628. PrepareDefinesForBakedVertexAnimation(mesh, defines);
  629. }
  630. return true;
  631. }
  632. /**
  633. * Prepares the defines related to multiview
  634. * @param scene The scene we are intending to draw
  635. * @param defines The defines to update
  636. */
  637. export function PrepareDefinesForMultiview(scene, defines) {
  638. if (scene.activeCamera) {
  639. const previousMultiview = defines.MULTIVIEW;
  640. defines.MULTIVIEW = scene.activeCamera.outputRenderTarget !== null && scene.activeCamera.outputRenderTarget.getViewCount() > 1;
  641. if (defines.MULTIVIEW != previousMultiview) {
  642. defines.markAsUnprocessed();
  643. }
  644. }
  645. }
  646. /**
  647. * Prepares the defines related to order independant transparency
  648. * @param scene The scene we are intending to draw
  649. * @param defines The defines to update
  650. * @param needAlphaBlending Determines if the material needs alpha blending
  651. */
  652. export function PrepareDefinesForOIT(scene, defines, needAlphaBlending) {
  653. const previousDefine = defines.ORDER_INDEPENDENT_TRANSPARENCY;
  654. const previousDefine16Bits = defines.ORDER_INDEPENDENT_TRANSPARENCY_16BITS;
  655. defines.ORDER_INDEPENDENT_TRANSPARENCY = scene.useOrderIndependentTransparency && needAlphaBlending;
  656. defines.ORDER_INDEPENDENT_TRANSPARENCY_16BITS = !scene.getEngine().getCaps().textureFloatLinearFiltering;
  657. if (previousDefine !== defines.ORDER_INDEPENDENT_TRANSPARENCY || previousDefine16Bits !== defines.ORDER_INDEPENDENT_TRANSPARENCY_16BITS) {
  658. defines.markAsUnprocessed();
  659. }
  660. }
  661. /**
  662. * Prepares the defines related to the prepass
  663. * @param scene The scene we are intending to draw
  664. * @param defines The defines to update
  665. * @param canRenderToMRT Indicates if this material renders to several textures in the prepass
  666. */
  667. export function PrepareDefinesForPrePass(scene, defines, canRenderToMRT) {
  668. const previousPrePass = defines.PREPASS;
  669. if (!defines._arePrePassDirty) {
  670. return;
  671. }
  672. const texturesList = [
  673. {
  674. type: 1,
  675. define: "PREPASS_POSITION",
  676. index: "PREPASS_POSITION_INDEX",
  677. },
  678. {
  679. type: 2,
  680. define: "PREPASS_VELOCITY",
  681. index: "PREPASS_VELOCITY_INDEX",
  682. },
  683. {
  684. type: 3,
  685. define: "PREPASS_REFLECTIVITY",
  686. index: "PREPASS_REFLECTIVITY_INDEX",
  687. },
  688. {
  689. type: 0,
  690. define: "PREPASS_IRRADIANCE",
  691. index: "PREPASS_IRRADIANCE_INDEX",
  692. },
  693. {
  694. type: 7,
  695. define: "PREPASS_ALBEDO_SQRT",
  696. index: "PREPASS_ALBEDO_SQRT_INDEX",
  697. },
  698. {
  699. type: 5,
  700. define: "PREPASS_DEPTH",
  701. index: "PREPASS_DEPTH_INDEX",
  702. },
  703. {
  704. type: 6,
  705. define: "PREPASS_NORMAL",
  706. index: "PREPASS_NORMAL_INDEX",
  707. },
  708. ];
  709. if (scene.prePassRenderer && scene.prePassRenderer.enabled && canRenderToMRT) {
  710. defines.PREPASS = true;
  711. defines.SCENE_MRT_COUNT = scene.prePassRenderer.mrtCount;
  712. defines.PREPASS_NORMAL_WORLDSPACE = scene.prePassRenderer.generateNormalsInWorldSpace;
  713. for (let i = 0; i < texturesList.length; i++) {
  714. const index = scene.prePassRenderer.getIndex(texturesList[i].type);
  715. if (index !== -1) {
  716. defines[texturesList[i].define] = true;
  717. defines[texturesList[i].index] = index;
  718. }
  719. else {
  720. defines[texturesList[i].define] = false;
  721. }
  722. }
  723. }
  724. else {
  725. defines.PREPASS = false;
  726. for (let i = 0; i < texturesList.length; i++) {
  727. defines[texturesList[i].define] = false;
  728. }
  729. }
  730. if (defines.PREPASS != previousPrePass) {
  731. defines.markAsUnprocessed();
  732. defines.markAsImageProcessingDirty();
  733. }
  734. }
  735. /**
  736. * Helper used to prepare the defines relative to the active camera
  737. * @param scene defines the current scene
  738. * @param defines specifies the list of active defines
  739. * @returns true if the defines have been updated, else false
  740. */
  741. export function PrepareDefinesForCamera(scene, defines) {
  742. let changed = false;
  743. if (scene.activeCamera) {
  744. const wasOrtho = defines["CAMERA_ORTHOGRAPHIC"] ? 1 : 0;
  745. const wasPersp = defines["CAMERA_PERSPECTIVE"] ? 1 : 0;
  746. const isOrtho = scene.activeCamera.mode === 1 ? 1 : 0;
  747. const isPersp = scene.activeCamera.mode === 0 ? 1 : 0;
  748. if (wasOrtho ^ isOrtho || wasPersp ^ isPersp) {
  749. defines["CAMERA_ORTHOGRAPHIC"] = isOrtho === 1;
  750. defines["CAMERA_PERSPECTIVE"] = isPersp === 1;
  751. changed = true;
  752. }
  753. }
  754. return changed;
  755. }
  756. /**
  757. * Prepares the uniforms and samplers list to be used in the effect (for a specific light)
  758. * @param lightIndex defines the light index
  759. * @param uniformsList The uniform list
  760. * @param samplersList The sampler list
  761. * @param projectedLightTexture defines if projected texture must be used
  762. * @param uniformBuffersList defines an optional list of uniform buffers
  763. * @param updateOnlyBuffersList True to only update the uniformBuffersList array
  764. */
  765. export function PrepareUniformsAndSamplersForLight(lightIndex, uniformsList, samplersList, projectedLightTexture, uniformBuffersList = null, updateOnlyBuffersList = false) {
  766. if (uniformBuffersList) {
  767. uniformBuffersList.push("Light" + lightIndex);
  768. }
  769. if (updateOnlyBuffersList) {
  770. return;
  771. }
  772. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightFalloff" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  773. samplersList.push("shadowSampler" + lightIndex);
  774. samplersList.push("depthSampler" + lightIndex);
  775. uniformsList.push("viewFrustumZ" + lightIndex, "cascadeBlendFactor" + lightIndex, "lightSizeUVCorrection" + lightIndex, "depthCorrection" + lightIndex, "penumbraDarkness" + lightIndex, "frustumLengths" + lightIndex);
  776. if (projectedLightTexture) {
  777. samplersList.push("projectionLightSampler" + lightIndex);
  778. uniformsList.push("textureProjectionMatrix" + lightIndex);
  779. }
  780. }
  781. /**
  782. * Prepares the uniforms and samplers list to be used in the effect
  783. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the list and extra information
  784. * @param samplersList The sampler list
  785. * @param defines The defines helping in the list generation
  786. * @param maxSimultaneousLights The maximum number of simultaneous light allowed in the effect
  787. */
  788. export function PrepareUniformsAndSamplersList(uniformsListOrOptions, samplersList, defines, maxSimultaneousLights = 4) {
  789. let uniformsList;
  790. let uniformBuffersList = null;
  791. if (uniformsListOrOptions.uniformsNames) {
  792. const options = uniformsListOrOptions;
  793. uniformsList = options.uniformsNames;
  794. uniformBuffersList = options.uniformBuffersNames;
  795. samplersList = options.samplers;
  796. defines = options.defines;
  797. maxSimultaneousLights = options.maxSimultaneousLights || 0;
  798. }
  799. else {
  800. uniformsList = uniformsListOrOptions;
  801. if (!samplersList) {
  802. samplersList = [];
  803. }
  804. }
  805. for (let lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  806. if (!defines["LIGHT" + lightIndex]) {
  807. break;
  808. }
  809. PrepareUniformsAndSamplersForLight(lightIndex, uniformsList, samplersList, defines["PROJECTEDLIGHTTEXTURE" + lightIndex], uniformBuffersList);
  810. }
  811. if (defines["NUM_MORPH_INFLUENCERS"]) {
  812. uniformsList.push("morphTargetInfluences");
  813. uniformsList.push("morphTargetCount");
  814. }
  815. if (defines["BAKED_VERTEX_ANIMATION_TEXTURE"]) {
  816. uniformsList.push("bakedVertexAnimationSettings");
  817. uniformsList.push("bakedVertexAnimationTextureSizeInverted");
  818. uniformsList.push("bakedVertexAnimationTime");
  819. samplersList.push("bakedVertexAnimationTexture");
  820. }
  821. }
  822. //# sourceMappingURL=materialHelper.functions.js.map