babylon.digitalRainPostProcess.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  2. module BABYLON {
  3. /**
  4. * DigitalRainFontTexture is the helper class used to easily create your digital rain font texture.
  5. *
  6. * It basically takes care rendering the font front the given font size to a texture.
  7. * This is used later on in the postprocess.
  8. */
  9. export class DigitalRainFontTexture extends BaseTexture {
  10. @serialize("font")
  11. private _font: string;
  12. @serialize("text")
  13. private _text: string;
  14. private _charSize: number;
  15. /**
  16. * Gets the size of one char in the texture (each char fits in size * size space in the texture).
  17. */
  18. public get charSize(): number {
  19. return this._charSize;
  20. }
  21. /**
  22. * Create a new instance of the Digital Rain FontTexture class
  23. * @param name the name of the texture
  24. * @param font the font to use, use the W3C CSS notation
  25. * @param text the caracter set to use in the rendering.
  26. * @param scene the scene that owns the texture
  27. */
  28. constructor(name: string, font: string, text: string, scene: Nullable<Scene> = null) {
  29. super(scene);
  30. scene = this.getScene();
  31. if (!scene) {
  32. return;
  33. }
  34. this.name = name;
  35. this._text == text;
  36. this._font == font;
  37. this.wrapU = Texture.CLAMP_ADDRESSMODE;
  38. this.wrapV = Texture.CLAMP_ADDRESSMODE;
  39. //this.anisotropicFilteringLevel = 1;
  40. // Get the font specific info.
  41. var maxCharHeight = this.getFontHeight(font);
  42. var maxCharWidth = this.getFontWidth(font);
  43. this._charSize = Math.max(maxCharHeight.height, maxCharWidth);
  44. // This is an approximate size, but should always be able to fit at least the maxCharCount.
  45. var textureWidth = this._charSize;
  46. var textureHeight = Math.ceil(this._charSize * text.length);
  47. // Create the texture that will store the font characters.
  48. this._texture = scene.getEngine().createDynamicTexture(textureWidth, textureHeight, false, Texture.NEAREST_SAMPLINGMODE);
  49. //scene.getEngine().setclamp
  50. var textureSize = this.getSize();
  51. // Create a canvas with the final size: the one matching the texture.
  52. var canvas = document.createElement("canvas");
  53. canvas.width = textureSize.width;
  54. canvas.height = textureSize.height;
  55. var context = <CanvasRenderingContext2D>canvas.getContext("2d");
  56. context.textBaseline = "top";
  57. context.font = font;
  58. context.fillStyle = "white";
  59. context.imageSmoothingEnabled = false;
  60. // Sets the text in the texture.
  61. for (var i = 0; i < text.length; i++) {
  62. context.fillText(text[i], 0, i * this._charSize - maxCharHeight.offset);
  63. }
  64. // Flush the text in the dynamic texture.
  65. scene.getEngine().updateDynamicTexture(this._texture, canvas, false, true);
  66. }
  67. /**
  68. * Gets the max char width of a font.
  69. * @param font the font to use, use the W3C CSS notation
  70. * @return the max char width
  71. */
  72. private getFontWidth(font: string): number {
  73. var fontDraw = document.createElement("canvas");
  74. var ctx = <CanvasRenderingContext2D>fontDraw.getContext('2d');
  75. ctx.fillStyle = 'white';
  76. ctx.font = font;
  77. return ctx.measureText("W").width;
  78. }
  79. // More info here: https://videlais.com/2014/03/16/the-many-and-varied-problems-with-measuring-font-height-for-html5-canvas/
  80. /**
  81. * Gets the max char height of a font.
  82. * @param font the font to use, use the W3C CSS notation
  83. * @return the max char height
  84. */
  85. private getFontHeight(font: string): {height: number, offset: number} {
  86. var fontDraw = document.createElement("canvas");
  87. var ctx = <CanvasRenderingContext2D>fontDraw.getContext('2d');
  88. ctx.fillRect(0, 0, fontDraw.width, fontDraw.height);
  89. ctx.textBaseline = 'top';
  90. ctx.fillStyle = 'white';
  91. ctx.font = font;
  92. ctx.fillText('jH|', 0, 0);
  93. var pixels = ctx.getImageData(0, 0, fontDraw.width, fontDraw.height).data;
  94. var start = -1;
  95. var end = -1;
  96. for (var row = 0; row < fontDraw.height; row++) {
  97. for (var column = 0; column < fontDraw.width; column++) {
  98. var index = (row * fontDraw.width + column) * 4;
  99. if (pixels[index] === 0) {
  100. if (column === fontDraw.width - 1 && start !== -1) {
  101. end = row;
  102. row = fontDraw.height;
  103. break;
  104. }
  105. continue;
  106. }
  107. else {
  108. if (start === -1) {
  109. start = row;
  110. }
  111. break;
  112. }
  113. }
  114. }
  115. return { height: (end - start) + 1, offset: start - 1};
  116. }
  117. /**
  118. * Clones the current DigitalRainFontTexture.
  119. * @return the clone of the texture.
  120. */
  121. public clone(): DigitalRainFontTexture {
  122. return new DigitalRainFontTexture(this.name, this._font, this._text, this.getScene());
  123. }
  124. /**
  125. * Parses a json object representing the texture and returns an instance of it.
  126. * @param source the source JSON representation
  127. * @param scene the scene to create the texture for
  128. * @return the parsed texture
  129. */
  130. public static Parse(source: any, scene: Scene): DigitalRainFontTexture {
  131. var texture = SerializationHelper.Parse(() => new DigitalRainFontTexture(source.name, source.font, source.text, scene),
  132. source, scene, null);
  133. return texture;
  134. }
  135. }
  136. /**
  137. * Option available in the Digital Rain Post Process.
  138. */
  139. export interface IDigitalRainPostProcessOptions {
  140. /**
  141. * The font to use following the w3c font definition.
  142. */
  143. font?: string;
  144. /**
  145. * This defines the amount you want to mix the "tile" or caracter space colored in the digital rain.
  146. * This number is defined between 0 and 1;
  147. */
  148. mixToTile?: number;
  149. /**
  150. * This defines the amount you want to mix the normal rendering pass in the digital rain.
  151. * This number is defined between 0 and 1;
  152. */
  153. mixToNormal?: number;
  154. }
  155. /**
  156. * DigitalRainPostProcess helps rendering everithing in digital rain.
  157. *
  158. * Simmply add it to your scene and let the nerd that lives in you have fun.
  159. * Example usage: var pp = new DigitalRainPostProcess("digitalRain", "20px Monospace", camera);
  160. */
  161. export class DigitalRainPostProcess extends PostProcess {
  162. /**
  163. * The font texture used to render the char in the post process.
  164. */
  165. private _digitalRainFontTexture: DigitalRainFontTexture;
  166. /**
  167. * This defines the amount you want to mix the "tile" or caracter space colored in the digital rain.
  168. * This number is defined between 0 and 1;
  169. */
  170. public mixToTile: number = 0;
  171. /**
  172. * This defines the amount you want to mix the normal rendering pass in the digital rain.
  173. * This number is defined between 0 and 1;
  174. */
  175. public mixToNormal: number = 0;
  176. /**
  177. * Instantiates a new Digital Rain Post Process.
  178. * @param name the name to give to the postprocess
  179. * @camera the camera to apply the post process to.
  180. * @param options can either be the font name or an option object following the IDigitalRainPostProcessOptions format
  181. */
  182. constructor(name: string, camera: Camera, options?: string | IDigitalRainPostProcessOptions) {
  183. super(name,
  184. 'digitalrain',
  185. ['digitalRainFontInfos', 'digitalRainOptions', 'cosTimeZeroOne', 'matrixSpeed'],
  186. ['digitalRainFont'],
  187. {
  188. width: camera.getEngine().getRenderWidth(),
  189. height: camera.getEngine().getRenderHeight()
  190. },
  191. camera,
  192. Texture.TRILINEAR_SAMPLINGMODE,
  193. camera.getEngine(),
  194. true);
  195. // Default values.
  196. var font = "15px Monospace";
  197. var characterSet = "古池や蛙飛び込む水の音ふるいけやかわずとびこむみずのおと初しぐれ猿も小蓑をほしげ也はつしぐれさるもこみのをほしげなり江戸の雨何石呑んだ時鳥えどのあめなんごくのんだほととぎす";
  198. // Use options.
  199. if (options) {
  200. if (typeof(options) === "string") {
  201. font = <string>options;
  202. }
  203. else {
  204. font = (<IDigitalRainPostProcessOptions>options).font || font;
  205. this.mixToTile = (<IDigitalRainPostProcessOptions>options).mixToTile || this.mixToTile;
  206. this.mixToNormal = (<IDigitalRainPostProcessOptions>options).mixToNormal || this.mixToNormal;
  207. }
  208. }
  209. this._digitalRainFontTexture = new DigitalRainFontTexture(name, font, characterSet, camera.getScene());
  210. var textureSize = this._digitalRainFontTexture.getSize();
  211. var alpha = 0.0;
  212. var cosTimeZeroOne = 0.0;
  213. var matrix = Matrix.FromValues(
  214. Math.random(), Math.random(), Math.random(), Math.random(),
  215. Math.random(), Math.random(), Math.random(), Math.random(),
  216. Math.random(), Math.random(), Math.random(), Math.random(),
  217. Math.random(), Math.random(), Math.random(), Math.random()
  218. );
  219. this.onApply = (effect: Effect) => {
  220. effect.setTexture("digitalRainFont", this._digitalRainFontTexture);
  221. effect.setFloat4("digitalRainFontInfos",
  222. this._digitalRainFontTexture.charSize,
  223. characterSet.length,
  224. textureSize.width,
  225. textureSize.height);
  226. effect.setFloat4("digitalRainOptions",
  227. this.width,
  228. this.height,
  229. this.mixToNormal,
  230. this.mixToTile);
  231. effect.setMatrix("matrixSpeed",
  232. matrix);
  233. alpha += 0.003;
  234. cosTimeZeroOne = alpha;
  235. effect.setFloat('cosTimeZeroOne', cosTimeZeroOne);
  236. };
  237. }
  238. }
  239. }