materialHelper.ts 32 KB

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