babylon.materialHelper.ts 31 KB

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