furMaterial.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556
  1. import { Nullable } from "babylonjs/types";
  2. import { serializeAsVector3, serializeAsTexture, serialize, expandToProperty, serializeAsColor3, SerializationHelper } from "babylonjs/Misc/decorators";
  3. import { Matrix, Vector3 } from "babylonjs/Maths/math.vector";
  4. import { Color3 } from "babylonjs/Maths/math.color";
  5. import { IAnimatable } from 'babylonjs/Animations/animatable.interface';
  6. import { Tags } from "babylonjs/Misc/tags";
  7. import { BaseTexture } from "babylonjs/Materials/Textures/baseTexture";
  8. import { Texture } from "babylonjs/Materials/Textures/texture";
  9. import { DynamicTexture } from "babylonjs/Materials/Textures/dynamicTexture";
  10. import { IEffectCreationOptions } from "babylonjs/Materials/effect";
  11. import { MaterialDefines } from "babylonjs/Materials/materialDefines";
  12. import { MaterialHelper } from "babylonjs/Materials/materialHelper";
  13. import { PushMaterial } from "babylonjs/Materials/pushMaterial";
  14. import { MaterialFlags } from "babylonjs/Materials/materialFlags";
  15. import { VertexBuffer } from "babylonjs/Meshes/buffer";
  16. import { AbstractMesh } from "babylonjs/Meshes/abstractMesh";
  17. import { SubMesh } from "babylonjs/Meshes/subMesh";
  18. import { Mesh } from "babylonjs/Meshes/mesh";
  19. import { Scene } from "babylonjs/scene";
  20. import { _TypeStore } from 'babylonjs/Misc/typeStore';
  21. import { EffectFallbacks } from 'babylonjs/Materials/effectFallbacks';
  22. import "./fur.fragment";
  23. import "./fur.vertex";
  24. class FurMaterialDefines extends MaterialDefines {
  25. public DIFFUSE = false;
  26. public HEIGHTMAP = false;
  27. public CLIPPLANE = false;
  28. public CLIPPLANE2 = false;
  29. public CLIPPLANE3 = false;
  30. public CLIPPLANE4 = false;
  31. public CLIPPLANE5 = false;
  32. public CLIPPLANE6 = false;
  33. public ALPHATEST = false;
  34. public DEPTHPREPASS = false;
  35. public POINTSIZE = false;
  36. public FOG = false;
  37. public NORMAL = false;
  38. public UV1 = false;
  39. public UV2 = false;
  40. public VERTEXCOLOR = false;
  41. public VERTEXALPHA = false;
  42. public NUM_BONE_INFLUENCERS = 0;
  43. public BonesPerMesh = 0;
  44. public INSTANCES = false;
  45. public HIGHLEVEL = false;
  46. public IMAGEPROCESSINGPOSTPROCESS = false;
  47. constructor() {
  48. super();
  49. this.rebuild();
  50. }
  51. }
  52. export class FurMaterial extends PushMaterial {
  53. @serializeAsTexture("diffuseTexture")
  54. private _diffuseTexture: BaseTexture;
  55. @expandToProperty("_markAllSubMeshesAsTexturesDirty")
  56. public diffuseTexture: BaseTexture;
  57. @serializeAsTexture("heightTexture")
  58. private _heightTexture: BaseTexture;
  59. @expandToProperty("_markAllSubMeshesAsTexturesDirty")
  60. public heightTexture: BaseTexture;
  61. @serializeAsColor3()
  62. public diffuseColor = new Color3(1, 1, 1);
  63. @serialize()
  64. public furLength: number = 1;
  65. @serialize()
  66. public furAngle: number = 0;
  67. @serializeAsColor3()
  68. public furColor = new Color3(0.44, 0.21, 0.02);
  69. @serialize()
  70. public furOffset: number = 0.0;
  71. @serialize()
  72. public furSpacing: number = 12;
  73. @serializeAsVector3()
  74. public furGravity = new Vector3(0, 0, 0);
  75. @serialize()
  76. public furSpeed: number = 100;
  77. @serialize()
  78. public furDensity: number = 20;
  79. @serialize()
  80. public furOcclusion: number = 0.0;
  81. public furTexture: DynamicTexture;
  82. @serialize("disableLighting")
  83. private _disableLighting = false;
  84. @expandToProperty("_markAllSubMeshesAsLightsDirty")
  85. public disableLighting: boolean;
  86. @serialize("maxSimultaneousLights")
  87. private _maxSimultaneousLights = 4;
  88. @expandToProperty("_markAllSubMeshesAsLightsDirty")
  89. public maxSimultaneousLights: number;
  90. @serialize()
  91. public highLevelFur: boolean = true;
  92. public _meshes: AbstractMesh[];
  93. private _furTime: number = 0;
  94. constructor(name: string, scene: Scene) {
  95. super(name, scene);
  96. }
  97. @serialize()
  98. public get furTime() {
  99. return this._furTime;
  100. }
  101. public set furTime(furTime: number) {
  102. this._furTime = furTime;
  103. }
  104. public needAlphaBlending(): boolean {
  105. return (this.alpha < 1.0);
  106. }
  107. public needAlphaTesting(): boolean {
  108. return false;
  109. }
  110. public getAlphaTestTexture(): Nullable<BaseTexture> {
  111. return null;
  112. }
  113. public updateFur(): void {
  114. for (var i = 1; i < this._meshes.length; i++) {
  115. var offsetFur = <FurMaterial>this._meshes[i].material;
  116. offsetFur.furLength = this.furLength;
  117. offsetFur.furAngle = this.furAngle;
  118. offsetFur.furGravity = this.furGravity;
  119. offsetFur.furSpacing = this.furSpacing;
  120. offsetFur.furSpeed = this.furSpeed;
  121. offsetFur.furColor = this.furColor;
  122. offsetFur.diffuseTexture = this.diffuseTexture;
  123. offsetFur.furTexture = this.furTexture;
  124. offsetFur.highLevelFur = this.highLevelFur;
  125. offsetFur.furTime = this.furTime;
  126. offsetFur.furDensity = this.furDensity;
  127. }
  128. }
  129. // Methods
  130. public isReadyForSubMesh(mesh: AbstractMesh, subMesh: SubMesh, useInstances?: boolean): boolean {
  131. if (this.isFrozen) {
  132. if (subMesh.effect && subMesh.effect._wasPreviouslyReady) {
  133. return true;
  134. }
  135. }
  136. if (!subMesh._materialDefines) {
  137. subMesh._materialDefines = new FurMaterialDefines();
  138. }
  139. var defines = <FurMaterialDefines>subMesh._materialDefines;
  140. var scene = this.getScene();
  141. if (this._isReadyForSubMesh(subMesh)) {
  142. return true;
  143. }
  144. var engine = scene.getEngine();
  145. // Textures
  146. if (defines._areTexturesDirty) {
  147. if (scene.texturesEnabled) {
  148. if (this.diffuseTexture && MaterialFlags.DiffuseTextureEnabled) {
  149. if (!this.diffuseTexture.isReady()) {
  150. return false;
  151. } else {
  152. defines._needUVs = true;
  153. defines.DIFFUSE = true;
  154. }
  155. }
  156. if (this.heightTexture && engine.getCaps().maxVertexTextureImageUnits) {
  157. if (!this.heightTexture.isReady()) {
  158. return false;
  159. } else {
  160. defines._needUVs = true;
  161. defines.HEIGHTMAP = true;
  162. }
  163. }
  164. }
  165. }
  166. // High level
  167. if (this.highLevelFur !== defines.HIGHLEVEL) {
  168. defines.HIGHLEVEL = true;
  169. defines.markAsUnprocessed();
  170. }
  171. // Misc.
  172. MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  173. // Lights
  174. defines._needNormals = MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights, this._disableLighting);
  175. // Values that need to be evaluated on every frame
  176. MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false);
  177. // Attribs
  178. MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true);
  179. // Get correct effect
  180. if (defines.isDirty) {
  181. defines.markAsProcessed();
  182. scene.resetCachedMaterial();
  183. // Fallbacks
  184. var fallbacks = new EffectFallbacks();
  185. if (defines.FOG) {
  186. fallbacks.addFallback(1, "FOG");
  187. }
  188. MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this.maxSimultaneousLights);
  189. if (defines.NUM_BONE_INFLUENCERS > 0) {
  190. fallbacks.addCPUSkinningFallback(0, mesh);
  191. }
  192. defines.IMAGEPROCESSINGPOSTPROCESS = scene.imageProcessingConfiguration.applyByPostProcess;
  193. //Attributes
  194. var attribs = [VertexBuffer.PositionKind];
  195. if (defines.NORMAL) {
  196. attribs.push(VertexBuffer.NormalKind);
  197. }
  198. if (defines.UV1) {
  199. attribs.push(VertexBuffer.UVKind);
  200. }
  201. if (defines.UV2) {
  202. attribs.push(VertexBuffer.UV2Kind);
  203. }
  204. if (defines.VERTEXCOLOR) {
  205. attribs.push(VertexBuffer.ColorKind);
  206. }
  207. MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  208. MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  209. // Legacy browser patch
  210. var shaderName = "fur";
  211. var join = defines.toString();
  212. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vDiffuseColor",
  213. "vFogInfos", "vFogColor", "pointSize",
  214. "vDiffuseInfos",
  215. "mBones",
  216. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "vClipPlane5", "vClipPlane6", "diffuseMatrix",
  217. "furLength", "furAngle", "furColor", "furOffset", "furGravity", "furTime", "furSpacing", "furDensity", "furOcclusion"
  218. ];
  219. var samplers = ["diffuseSampler",
  220. "heightTexture", "furTexture"
  221. ];
  222. var uniformBuffers = new Array<string>();
  223. MaterialHelper.PrepareUniformsAndSamplersList(<IEffectCreationOptions>{
  224. uniformsNames: uniforms,
  225. uniformBuffersNames: uniformBuffers,
  226. samplers: samplers,
  227. defines: defines,
  228. maxSimultaneousLights: this.maxSimultaneousLights
  229. });
  230. subMesh.setEffect(scene.getEngine().createEffect(shaderName,
  231. <IEffectCreationOptions>{
  232. attributes: attribs,
  233. uniformsNames: uniforms,
  234. uniformBuffersNames: uniformBuffers,
  235. samplers: samplers,
  236. defines: join,
  237. fallbacks: fallbacks,
  238. onCompiled: this.onCompiled,
  239. onError: this.onError,
  240. indexParameters: { maxSimultaneousLights: this.maxSimultaneousLights }
  241. }, engine), defines);
  242. }
  243. if (!subMesh.effect || !subMesh.effect.isReady()) {
  244. return false;
  245. }
  246. defines._renderId = scene.getRenderId();
  247. subMesh.effect._wasPreviouslyReady = true;
  248. return true;
  249. }
  250. public bindForSubMesh(world: Matrix, mesh: Mesh, subMesh: SubMesh): void {
  251. var scene = this.getScene();
  252. var defines = <FurMaterialDefines>subMesh._materialDefines;
  253. if (!defines) {
  254. return;
  255. }
  256. var effect = subMesh.effect;
  257. if (!effect) {
  258. return;
  259. }
  260. this._activeEffect = effect;
  261. // Matrices
  262. this.bindOnlyWorldMatrix(world);
  263. this._activeEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  264. // Bones
  265. MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  266. if (scene.getCachedMaterial() !== this) {
  267. // Textures
  268. if (this._diffuseTexture && MaterialFlags.DiffuseTextureEnabled) {
  269. this._activeEffect.setTexture("diffuseSampler", this._diffuseTexture);
  270. this._activeEffect.setFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  271. this._activeEffect.setMatrix("diffuseMatrix", this._diffuseTexture.getTextureMatrix());
  272. }
  273. if (this._heightTexture) {
  274. this._activeEffect.setTexture("heightTexture", this._heightTexture);
  275. }
  276. // Clip plane
  277. MaterialHelper.BindClipPlane(this._activeEffect, scene);
  278. // Point size
  279. if (this.pointsCloud) {
  280. this._activeEffect.setFloat("pointSize", this.pointSize);
  281. }
  282. MaterialHelper.BindEyePosition(effect, scene);
  283. }
  284. this._activeEffect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  285. if (scene.lightsEnabled && !this.disableLighting) {
  286. MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this.maxSimultaneousLights);
  287. }
  288. // View
  289. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== Scene.FOGMODE_NONE) {
  290. this._activeEffect.setMatrix("view", scene.getViewMatrix());
  291. }
  292. // Fog
  293. MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  294. this._activeEffect.setFloat("furLength", this.furLength);
  295. this._activeEffect.setFloat("furAngle", this.furAngle);
  296. this._activeEffect.setColor4("furColor", this.furColor, 1.0);
  297. if (this.highLevelFur) {
  298. this._activeEffect.setVector3("furGravity", this.furGravity);
  299. this._activeEffect.setFloat("furOffset", this.furOffset);
  300. this._activeEffect.setFloat("furSpacing", this.furSpacing);
  301. this._activeEffect.setFloat("furDensity", this.furDensity);
  302. this._activeEffect.setFloat("furOcclusion", this.furOcclusion);
  303. this._furTime += this.getScene().getEngine().getDeltaTime() / this.furSpeed;
  304. this._activeEffect.setFloat("furTime", this._furTime);
  305. this._activeEffect.setTexture("furTexture", this.furTexture);
  306. }
  307. this._afterBind(mesh, this._activeEffect);
  308. }
  309. public getAnimatables(): IAnimatable[] {
  310. var results = [];
  311. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  312. results.push(this.diffuseTexture);
  313. }
  314. if (this.heightTexture && this.heightTexture.animations && this.heightTexture.animations.length > 0) {
  315. results.push(this.heightTexture);
  316. }
  317. return results;
  318. }
  319. public getActiveTextures(): BaseTexture[] {
  320. var activeTextures = super.getActiveTextures();
  321. if (this._diffuseTexture) {
  322. activeTextures.push(this._diffuseTexture);
  323. }
  324. if (this._heightTexture) {
  325. activeTextures.push(this._heightTexture);
  326. }
  327. return activeTextures;
  328. }
  329. public hasTexture(texture: BaseTexture): boolean {
  330. if (super.hasTexture(texture)) {
  331. return true;
  332. }
  333. if (this.diffuseTexture === texture) {
  334. return true;
  335. }
  336. if (this._heightTexture === texture) {
  337. return true;
  338. }
  339. return false;
  340. }
  341. public dispose(forceDisposeEffect?: boolean): void {
  342. if (this.diffuseTexture) {
  343. this.diffuseTexture.dispose();
  344. }
  345. if (this._meshes) {
  346. for (var i = 1; i < this._meshes.length; i++) {
  347. let mat = this._meshes[i].material;
  348. if (mat) {
  349. mat.dispose(forceDisposeEffect);
  350. }
  351. this._meshes[i].dispose();
  352. }
  353. }
  354. super.dispose(forceDisposeEffect);
  355. }
  356. public clone(name: string): FurMaterial {
  357. return SerializationHelper.Clone(() => new FurMaterial(name, this.getScene()), this);
  358. }
  359. public serialize(): any {
  360. var serializationObject = SerializationHelper.Serialize(this);
  361. serializationObject.customType = "BABYLON.FurMaterial";
  362. if (this._meshes) {
  363. serializationObject.sourceMeshName = this._meshes[0].name;
  364. serializationObject.quality = this._meshes.length;
  365. }
  366. return serializationObject;
  367. }
  368. public getClassName(): string {
  369. return "FurMaterial";
  370. }
  371. // Statics
  372. public static Parse(source: any, scene: Scene, rootUrl: string): FurMaterial {
  373. var material = SerializationHelper.Parse(() => new FurMaterial(source.name, scene), source, scene, rootUrl);
  374. if (source.sourceMeshName && material.highLevelFur) {
  375. scene.executeWhenReady(() => {
  376. var sourceMesh = <Mesh>scene.getMeshByName(source.sourceMeshName);
  377. if (sourceMesh) {
  378. var furTexture = FurMaterial.GenerateTexture("Fur Texture", scene);
  379. material.furTexture = furTexture;
  380. FurMaterial.FurifyMesh(sourceMesh, source.quality);
  381. }
  382. });
  383. }
  384. return material;
  385. }
  386. public static GenerateTexture(name: string, scene: Scene): DynamicTexture {
  387. // Generate fur textures
  388. var texture = new DynamicTexture("FurTexture " + name, 256, scene, true);
  389. var context = texture.getContext();
  390. for (var i = 0; i < 20000; ++i) {
  391. context.fillStyle = "rgba(255, " + Math.floor(Math.random() * 255) + ", " + Math.floor(Math.random() * 255) + ", 1)";
  392. context.fillRect((Math.random() * texture.getSize().width), (Math.random() * texture.getSize().height), 2, 2);
  393. }
  394. texture.update(false);
  395. texture.wrapU = Texture.WRAP_ADDRESSMODE;
  396. texture.wrapV = Texture.WRAP_ADDRESSMODE;
  397. return texture;
  398. }
  399. // Creates and returns an array of meshes used as shells for the Fur Material
  400. // that can be disposed later in your code
  401. // The quality is in interval [0, 100]
  402. public static FurifyMesh(sourceMesh: Mesh, quality: number): Mesh[] {
  403. var meshes = [sourceMesh];
  404. var mat: FurMaterial = <FurMaterial>sourceMesh.material;
  405. var i;
  406. if (!(mat instanceof FurMaterial)) {
  407. throw "The material of the source mesh must be a Fur Material";
  408. }
  409. for (i = 1; i < quality; i++) {
  410. var offsetFur = new FurMaterial(mat.name + i, sourceMesh.getScene());
  411. sourceMesh.getScene().materials.pop();
  412. Tags.EnableFor(offsetFur);
  413. Tags.AddTagsTo(offsetFur, "furShellMaterial");
  414. offsetFur.furLength = mat.furLength;
  415. offsetFur.furAngle = mat.furAngle;
  416. offsetFur.furGravity = mat.furGravity;
  417. offsetFur.furSpacing = mat.furSpacing;
  418. offsetFur.furSpeed = mat.furSpeed;
  419. offsetFur.furColor = mat.furColor;
  420. offsetFur.diffuseTexture = mat.diffuseTexture;
  421. offsetFur.furOffset = i / quality;
  422. offsetFur.furTexture = mat.furTexture;
  423. offsetFur.highLevelFur = mat.highLevelFur;
  424. offsetFur.furTime = mat.furTime;
  425. offsetFur.furDensity = mat.furDensity;
  426. var offsetMesh = sourceMesh.clone(sourceMesh.name + i) as Mesh;
  427. offsetMesh.material = offsetFur;
  428. offsetMesh.skeleton = sourceMesh.skeleton;
  429. offsetMesh.position = Vector3.Zero();
  430. meshes.push(offsetMesh);
  431. }
  432. for (i = 1; i < meshes.length; i++) {
  433. meshes[i].parent = sourceMesh;
  434. }
  435. (<FurMaterial>sourceMesh.material)._meshes = meshes;
  436. return meshes;
  437. }
  438. }
  439. _TypeStore.RegisteredTypes["BABYLON.FurMaterial"] = FurMaterial;