furMaterial.ts 18 KB

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