babylon.furMaterial.ts 19 KB

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