babylon.asciiArtPostProcess.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  2. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  3. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") return Reflect.decorate(decorators, target, key, desc);
  4. switch (arguments.length) {
  5. case 2: return decorators.reduceRight(function(o, d) { return (d && d(o)) || o; }, target);
  6. case 3: return decorators.reduceRight(function(o, d) { return (d && d(target, key)), void 0; }, void 0);
  7. case 4: return decorators.reduceRight(function(o, d) { return (d && d(target, key, o)) || o; }, desc);
  8. }
  9. };
  10. var BABYLON;
  11. (function (BABYLON) {
  12. /**
  13. * AsciiArtFontTexture is the helper class used to easily create your ascii art font texture.
  14. *
  15. * It basically takes care rendering the font front the given font size to a texture.
  16. * This is used later on in the postprocess.
  17. */
  18. var AsciiArtFontTexture = (function (_super) {
  19. __extends(AsciiArtFontTexture, _super);
  20. /**
  21. * Create a new instance of the Ascii Art FontTexture class
  22. * @param name the name of the texture
  23. * @param font the font to use, use the W3C CSS notation
  24. * @param text the caracter set to use in the rendering.
  25. * @param scene the scene that owns the texture
  26. */
  27. function AsciiArtFontTexture(name, font, text, scene) {
  28. _super.call(this, scene);
  29. this.name = name;
  30. this._text == text;
  31. this._font == font;
  32. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34. //this.anisotropicFilteringLevel = 1;
  35. // Get the font specific info.
  36. var maxCharHeight = this.getFontHeight(font);
  37. var maxCharWidth = this.getFontWidth(font);
  38. this._charSize = Math.max(maxCharHeight.height, maxCharWidth);
  39. // This is an approximate size, but should always be able to fit at least the maxCharCount.
  40. var textureWidth = Math.ceil(this._charSize * text.length);
  41. var textureHeight = this._charSize;
  42. // Create the texture that will store the font characters.
  43. this._texture = scene.getEngine().createDynamicTexture(textureWidth, textureHeight, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  44. //scene.getEngine().setclamp
  45. var textureSize = this.getSize();
  46. // Create a canvas with the final size: the one matching the texture.
  47. var canvas = document.createElement("canvas");
  48. canvas.width = textureSize.width;
  49. canvas.height = textureSize.height;
  50. var context = canvas.getContext("2d");
  51. context.textBaseline = "top";
  52. context.font = font;
  53. context.fillStyle = "white";
  54. context.imageSmoothingEnabled = false;
  55. // Sets the text in the texture.
  56. for (var i = 0; i < text.length; i++) {
  57. context.fillText(text[i], i * this._charSize, -maxCharHeight.offset);
  58. }
  59. // Flush the text in the dynamic texture.
  60. this.getScene().getEngine().updateDynamicTexture(this._texture, canvas, false, true);
  61. }
  62. Object.defineProperty(AsciiArtFontTexture.prototype, "charSize", {
  63. /**
  64. * Gets the size of one char in the texture (each char fits in size * size space in the texture).
  65. */
  66. get: function () {
  67. return this._charSize;
  68. },
  69. enumerable: true,
  70. configurable: true
  71. });
  72. /**
  73. * Gets the max char width of a font.
  74. * @param font the font to use, use the W3C CSS notation
  75. * @return the max char width
  76. */
  77. AsciiArtFontTexture.prototype.getFontWidth = function (font) {
  78. var fontDraw = document.createElement("canvas");
  79. var ctx = fontDraw.getContext('2d');
  80. ctx.fillStyle = 'white';
  81. ctx.font = font;
  82. return ctx.measureText("W").width;
  83. };
  84. // More info here: https://videlais.com/2014/03/16/the-many-and-varied-problems-with-measuring-font-height-for-html5-canvas/
  85. /**
  86. * Gets the max char height of a font.
  87. * @param font the font to use, use the W3C CSS notation
  88. * @return the max char height
  89. */
  90. AsciiArtFontTexture.prototype.getFontHeight = function (font) {
  91. var fontDraw = document.createElement("canvas");
  92. var ctx = fontDraw.getContext('2d');
  93. ctx.fillRect(0, 0, fontDraw.width, fontDraw.height);
  94. ctx.textBaseline = 'top';
  95. ctx.fillStyle = 'white';
  96. ctx.font = font;
  97. ctx.fillText('jH|', 0, 0);
  98. var pixels = ctx.getImageData(0, 0, fontDraw.width, fontDraw.height).data;
  99. var start = -1;
  100. var end = -1;
  101. for (var row = 0; row < fontDraw.height; row++) {
  102. for (var column = 0; column < fontDraw.width; column++) {
  103. var index = (row * fontDraw.width + column) * 4;
  104. if (pixels[index] === 0) {
  105. if (column === fontDraw.width - 1 && start !== -1) {
  106. end = row;
  107. row = fontDraw.height;
  108. break;
  109. }
  110. continue;
  111. }
  112. else {
  113. if (start === -1) {
  114. start = row;
  115. }
  116. break;
  117. }
  118. }
  119. }
  120. return { height: (end - start) + 1, offset: start - 1 };
  121. };
  122. /**
  123. * Clones the current AsciiArtTexture.
  124. * @return the clone of the texture.
  125. */
  126. AsciiArtFontTexture.prototype.clone = function () {
  127. return new AsciiArtFontTexture(this.name, this._font, this._text, this.getScene());
  128. };
  129. /**
  130. * Parses a json object representing the texture and returns an instance of it.
  131. * @param source the source JSON representation
  132. * @param scene the scene to create the texture for
  133. * @return the parsed texture
  134. */
  135. AsciiArtFontTexture.Parse = function (source, scene) {
  136. var texture = BABYLON.SerializationHelper.Parse(function () { return new AsciiArtFontTexture(source.name, source.font, source.text, scene); }, source, scene, null);
  137. return texture;
  138. };
  139. __decorate([
  140. BABYLON.serialize("font")
  141. ], AsciiArtFontTexture.prototype, "_font");
  142. __decorate([
  143. BABYLON.serialize("text")
  144. ], AsciiArtFontTexture.prototype, "_text");
  145. return AsciiArtFontTexture;
  146. })(BABYLON.BaseTexture);
  147. BABYLON.AsciiArtFontTexture = AsciiArtFontTexture;
  148. /**
  149. * AsciiArtPostProcess helps rendering everithing in Ascii Art.
  150. *
  151. * Simmply add it to your scene and let the nerd that lives in you have fun.
  152. * Example usage: var pp = new AsciiArtPostProcess("myAscii", "20px Monospace", camera);
  153. */
  154. var AsciiArtPostProcess = (function (_super) {
  155. __extends(AsciiArtPostProcess, _super);
  156. /**
  157. * Instantiates a new Ascii Art Post Process.
  158. * @param name the name to give to the postprocess
  159. * @camera the camera to apply the post process to.
  160. * @param options can either be the font name or an option object following the IAsciiArtPostProcessOptions format
  161. */
  162. function AsciiArtPostProcess(name, camera, options) {
  163. var _this = this;
  164. _super.call(this, name, 'asciiart', ['asciiArtFontInfos', 'asciiArtOptions'], ['asciiArtFont'], {
  165. width: camera.getEngine().getRenderWidth(),
  166. height: camera.getEngine().getRenderHeight()
  167. }, camera, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, camera.getEngine(), true);
  168. /**
  169. * This defines the amount you want to mix the "tile" or caracter space colored in the ascii art.
  170. * This number is defined between 0 and 1;
  171. */
  172. this.mixToTile = 0;
  173. /**
  174. * This defines the amount you want to mix the normal rendering pass in the ascii art.
  175. * This number is defined between 0 and 1;
  176. */
  177. this.mixToNormal = 0;
  178. // Default values.
  179. var font = "40px Monospace";
  180. var characterSet = " `-.'_:,\"=^;<+!*?/cL\\zrs7TivJtC{3F)Il(xZfY5S2eajo14[nuyE]P6V9kXpKwGhqAUbOd8#HRDB0$mgMW&Q%N@";
  181. // Use options.
  182. if (options) {
  183. if (typeof (options) === "string") {
  184. font = options;
  185. }
  186. else {
  187. font = options.font || font;
  188. characterSet = options.characterSet || characterSet;
  189. this.mixToTile = options.mixToTile || this.mixToTile;
  190. this.mixToNormal = options.mixToNormal || this.mixToNormal;
  191. }
  192. }
  193. this._asciiArtFontTexture = new AsciiArtFontTexture(name, font, characterSet, camera.getScene());
  194. var textureSize = this._asciiArtFontTexture.getSize();
  195. this.onApply = function (effect) {
  196. effect.setTexture("asciiArtFont", _this._asciiArtFontTexture);
  197. effect.setFloat4("asciiArtFontInfos", _this._asciiArtFontTexture.charSize, characterSet.length, textureSize.width, textureSize.height);
  198. effect.setFloat4("asciiArtOptions", _this.width, _this.height, _this.mixToNormal, _this.mixToTile);
  199. };
  200. }
  201. return AsciiArtPostProcess;
  202. })(BABYLON.PostProcess);
  203. BABYLON.AsciiArtPostProcess = AsciiArtPostProcess;
  204. })(BABYLON || (BABYLON = {}));
  205. BABYLON.Effect.ShadersStore['asciiartPixelShader'] = "// Samplers.\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D asciiArtFont;\n\n// Infos.\nuniform vec4 asciiArtFontInfos;\nuniform vec4 asciiArtOptions;\n\n// Transform color to luminance.\nfloat getLuminance(vec3 color)\n{\n return clamp(dot(color, vec3(0.2126, 0.7152, 0.0722)), 0., 1.);\n}\n\n// Main functions.\nvoid main(void) \n{\n float caracterSize = asciiArtFontInfos.x;\n float numChar = asciiArtFontInfos.y - 1.0;\n float fontx = asciiArtFontInfos.z;\n float fonty = asciiArtFontInfos.w;\n\n float screenx = asciiArtOptions.x;\n float screeny = asciiArtOptions.y;\n\n float tileX = float(floor((gl_FragCoord.x) / caracterSize)) * caracterSize / screenx;\n float tileY = float(floor((gl_FragCoord.y) / caracterSize)) * caracterSize / screeny;\n\n vec2 tileUV = vec2(tileX, tileY);\n vec4 tileColor = texture2D(textureSampler, tileUV);\n vec4 baseColor = texture2D(textureSampler, vUV);\n\n float tileLuminance = getLuminance(tileColor.rgb);\n\n float offsetx = (float(floor(tileLuminance * numChar))) * caracterSize / fontx;\n float offsety = 0.0;\n\n float x = float(mod(gl_FragCoord.x, caracterSize)) / fontx;\n float y = float(mod(gl_FragCoord.y, caracterSize)) / fonty;\n\n vec4 finalColor = texture2D(asciiArtFont, vec2(offsetx + x, offsety + (caracterSize / fonty - y)));\n finalColor.rgb *= tileColor.rgb;\n finalColor.a = 1.0;\n\n finalColor = mix(finalColor, tileColor, asciiArtOptions.w);\n finalColor = mix(finalColor, baseColor, asciiArtOptions.z);\n\n gl_FragColor = finalColor;\n}";