materialHelper.ts 32 KB

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