babylon.text2d.ts 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  1. module BABYLON {
  2. export class Text2DRenderCache extends ModelRenderCache {
  3. effectsReady: boolean = false;
  4. vb: WebGLBuffer = null;
  5. ib: WebGLBuffer = null;
  6. instancingAttributes: InstancingAttributeInfo[] = null;
  7. fontTexture: BaseFontTexture = null;
  8. effect: Effect = null;
  9. effectInstanced: Effect = null;
  10. render(instanceInfo: GroupInstanceInfo, context: Render2DContext): boolean {
  11. // Do nothing if the shader is still loading/preparing
  12. if (!this.effectsReady) {
  13. if ((this.effect && (!this.effect.isReady() || (this.effectInstanced && !this.effectInstanced.isReady())))) {
  14. return false;
  15. }
  16. this.effectsReady = true;
  17. }
  18. let canvas = instanceInfo.owner.owner;
  19. var engine = canvas.engine;
  20. this.fontTexture.update();
  21. let effect = context.useInstancing ? this.effectInstanced : this.effect;
  22. engine.enableEffect(effect);
  23. effect.setTexture("diffuseSampler", this.fontTexture);
  24. engine.bindBuffersDirectly(this.vb, this.ib, [1], 4, effect);
  25. let sdf = this.fontTexture.isSignedDistanceField;
  26. // Enable alpha mode only if the texture is not using SDF, SDF is rendered in AlphaTest mode, which mean no alpha blend
  27. var curAlphaMode: number;
  28. if (!sdf) {
  29. curAlphaMode = engine.getAlphaMode();
  30. engine.setAlphaMode(Engine.ALPHA_COMBINE, true);
  31. }
  32. let pid = context.groupInfoPartData[0];
  33. if (context.useInstancing) {
  34. if (!this.instancingAttributes) {
  35. this.instancingAttributes = this.loadInstancingAttributes(Text2D.TEXT2D_MAINPARTID, effect);
  36. }
  37. let glBuffer = context.instancedBuffers ? context.instancedBuffers[0] : pid._partBuffer;
  38. let count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  39. canvas._addDrawCallCount(1, context.renderMode);
  40. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingAttributes);
  41. engine.draw(true, 0, 6, count);
  42. engine.unbindInstanceAttributes();
  43. } else {
  44. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  45. for (let i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  46. this.setupUniforms(effect, 0, pid._partData, i);
  47. engine.draw(true, 0, 6);
  48. }
  49. }
  50. if (!sdf) {
  51. engine.setAlphaMode(curAlphaMode, true);
  52. }
  53. return true;
  54. }
  55. public dispose(): boolean {
  56. if (!super.dispose()) {
  57. return false;
  58. }
  59. if (this.vb) {
  60. this._engine._releaseBuffer(this.vb);
  61. this.vb = null;
  62. }
  63. if (this.ib) {
  64. this._engine._releaseBuffer(this.ib);
  65. this.ib = null;
  66. }
  67. if (this.fontTexture) {
  68. this.fontTexture.decCachedFontTextureCounter();
  69. this.fontTexture = null;
  70. }
  71. this.effect = null;
  72. this.effectInstanced = null;
  73. return true;
  74. }
  75. }
  76. export class Text2DInstanceData extends InstanceDataBase {
  77. constructor(partId: number, dataElementCount: number) {
  78. super(partId, dataElementCount);
  79. }
  80. @instanceData()
  81. get topLeftUV(): Vector2 {
  82. return null;
  83. }
  84. set topLeftUV(value: Vector2) {
  85. }
  86. @instanceData()
  87. get sizeUV(): Vector2 {
  88. return null;
  89. }
  90. set sizeUV(value: Vector2) {
  91. }
  92. @instanceData()
  93. get textureSize(): Vector2 {
  94. return null;
  95. }
  96. set textureSize(value: Vector2) {
  97. }
  98. @instanceData()
  99. get color(): Color4 {
  100. return null;
  101. }
  102. set color(value: Color4) {
  103. }
  104. @instanceData()
  105. get superSampleFactor(): number {
  106. return null;
  107. }
  108. set superSampleFactor(value: number) {
  109. }
  110. }
  111. @className("Text2D", "BABYLON")
  112. /**
  113. * Primitive that render text using a specific font
  114. */
  115. export class Text2D extends RenderablePrim2D {
  116. static TEXT2D_MAINPARTID = 1;
  117. static TEXT2D_CATEGORY_SDF = "SignedDistanceField";
  118. public static fontProperty: Prim2DPropInfo;
  119. public static defaultFontColorProperty: Prim2DPropInfo;
  120. public static textProperty: Prim2DPropInfo;
  121. public static sizeProperty: Prim2DPropInfo;
  122. public static fontSuperSampleProperty: Prim2DPropInfo;
  123. public static fontSignedDistanceFieldProperty: Prim2DPropInfo;
  124. @modelLevelProperty(RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, pi => Text2D.fontProperty = pi, false, true)
  125. /**
  126. * Get/set the font name to use, using HTML CSS notation.
  127. * Set is not supported right now.
  128. */
  129. public get fontName(): string {
  130. return this._fontName;
  131. }
  132. public set fontName(value: string) {
  133. if (this._fontName) {
  134. throw new Error("Font Name change is not supported right now.");
  135. }
  136. this._fontName = value;
  137. }
  138. @dynamicLevelProperty(RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, pi => Text2D.defaultFontColorProperty = pi)
  139. /**
  140. * Get/set the font default color
  141. */
  142. public get defaultFontColor(): Color4 {
  143. return this._defaultFontColor;
  144. }
  145. public set defaultFontColor(value: Color4) {
  146. this._defaultFontColor = value;
  147. }
  148. @instanceLevelProperty(RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, pi => Text2D.textProperty = pi, false, true)
  149. /**
  150. * Get/set the text to render.
  151. * \n \t character are supported.
  152. */
  153. public get text(): string {
  154. return this._text;
  155. }
  156. public set text(value: string) {
  157. if (!value) {
  158. value = "";
  159. }
  160. this._text = value;
  161. this._textSize = null; // A change of text will reset the TextSize which will be recomputed next time it's used
  162. this._size = null;
  163. this._updateCharCount();
  164. // Trigger a textSize to for a sizeChange if necessary, which is needed for layout to recompute
  165. let s = this.textSize;
  166. }
  167. @instanceLevelProperty(RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 4, pi => Text2D.sizeProperty = pi)
  168. /**
  169. * Get/set the size of the area where the text is drawn.
  170. * You should not set this size, the default behavior compute the size based on the actual text.
  171. */
  172. public get size(): Size {
  173. if (this._size != null) {
  174. return this._size;
  175. }
  176. return this.textSize;
  177. }
  178. public set size(value: Size) {
  179. this._size = value;
  180. }
  181. @modelLevelProperty(RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 5, pi => Text2D.fontSuperSampleProperty = pi, false, false)
  182. /**
  183. * Get/set the font name to use, using HTML CSS notation.
  184. * Set is not supported right now.
  185. */
  186. public get fontSuperSample(): boolean {
  187. return this._fontTexture && this._fontTexture.isSuperSampled;
  188. }
  189. @modelLevelProperty(RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 6, pi => Text2D.fontSuperSampleProperty = pi, false, false)
  190. /**
  191. * Get/set the font name to use, using HTML CSS notation.
  192. * Set is not supported right now.
  193. */
  194. public get fontSignedDistanceField(): boolean {
  195. return this._fontTexture && this._fontTexture.isSignedDistanceField;
  196. }
  197. public get isSizeAuto(): boolean {
  198. return false;
  199. }
  200. /**
  201. * Get the actual size of the Text2D primitive
  202. */
  203. public get actualSize(): Size {
  204. if (this._actualSize) {
  205. return this._actualSize;
  206. }
  207. return this.size;
  208. }
  209. /**
  210. * Get the area that bounds the text associated to the primitive
  211. */
  212. public get textSize(): Size {
  213. if (!this._textSize) {
  214. if (this.owner && this._text) {
  215. let newSize = this.fontTexture.measureText(this._text, this._tabulationSize);
  216. if (!newSize.equals(this._textSize)) {
  217. this.onPrimitivePropertyDirty(Prim2DBase.sizeProperty.flagId);
  218. this._positioningDirty();
  219. }
  220. this._textSize = newSize;
  221. } else {
  222. return Text2D.nullSize;
  223. }
  224. }
  225. return this._textSize;
  226. }
  227. protected get fontTexture(): BaseFontTexture {
  228. if (this._fontTexture) {
  229. return this._fontTexture;
  230. }
  231. if (this.fontName == null || this.owner == null || this.owner.scene == null) {
  232. return null;
  233. }
  234. this._fontTexture = FontTexture.GetCachedFontTexture(this.owner.scene, this.fontName, this._fontSuperSample, this._fontSDF);
  235. return this._fontTexture;
  236. }
  237. /**
  238. * Dispose the primitive, remove it from its parent
  239. */
  240. public dispose(): boolean {
  241. if (!super.dispose()) {
  242. return false;
  243. }
  244. if (this._fontTexture) {
  245. FontTexture.ReleaseCachedFontTexture(this.owner.scene, this.fontName, this._fontSuperSample, this._fontSDF);
  246. this._fontTexture = null;
  247. }
  248. return true;
  249. }
  250. protected updateLevelBoundingInfo() {
  251. BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo);
  252. }
  253. /**
  254. * Create a Text primitive
  255. * @param text the text to display
  256. * @param settings a combination of settings, possible ones are
  257. * - parent: the parent primitive/canvas, must be specified if the primitive is not constructed as a child of another one (i.e. as part of the children array setting)
  258. * - children: an array of direct children
  259. * - id a text identifier, for information purpose
  260. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  261. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  262. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  263. * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
  264. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  265. * - zOrder: override the zOrder with the specified value
  266. * - origin: define the normalized origin point location, default [0.5;0.5]
  267. * - fontName: the name/size/style of the font to use, following the CSS notation. Default is "12pt Arial".
  268. * - fontSuperSample: if true the text will be rendered with a superSampled font (the font is twice the given size). Use this settings if the text lies in world space or if it's scaled in.
  269. * - signedDistanceField: if true the text will be rendered using the SignedDistanceField technique. This technique has the advantage to be rendered order independent (then much less drawing calls), but only works on font that are a little more than one pixel wide on the screen but the rendering quality is excellent whatever the font size is on the screen (which is the purpose of this technique). Outlining/Shadow is not supported right now. If you can, you should use this mode, the quality and the performances are the best. Note that fontSuperSample has no effect when this mode is on.
  270. * - defaultFontColor: the color by default to apply on each letter of the text to display, default is plain white.
  271. * - areaSize: the size of the area in which to display the text, default is auto-fit from text content.
  272. * - tabulationSize: number of space character to insert when a tabulation is encountered, default is 4
  273. * - isVisible: true if the text must be visible, false for hidden. Default is true.
  274. * - isPickable: if true the Primitive can be used with interaction mode and will issue Pointer Event. If false it will be ignored for interaction/intersection test. Default value is true.
  275. * - isContainer: if true the Primitive acts as a container for interaction, if the primitive is not pickable or doesn't intersection, no further test will be perform on its children. If set to false, children will always be considered for intersection/interaction. Default value is true.
  276. * - childrenFlatZOrder: if true all the children (direct and indirect) will share the same Z-Order. Use this when there's a lot of children which don't overlap. The drawing order IS NOT GUARANTED!
  277. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  278. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  279. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  280. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  281. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  282. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  283. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  284. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  285. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  286. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  287. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  288. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  289. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  290. */
  291. constructor(text: string, settings?: {
  292. parent ?: Prim2DBase,
  293. children ?: Array<Prim2DBase>,
  294. id ?: string,
  295. position ?: Vector2,
  296. x ?: number,
  297. y ?: number,
  298. rotation ?: number,
  299. scale ?: number,
  300. scaleX ?: number,
  301. scaleY ?: number,
  302. dontInheritParentScale ?: boolean,
  303. opacity ?: number,
  304. zOrder ?: number,
  305. origin ?: Vector2,
  306. fontName ?: string,
  307. fontSuperSample ?: boolean,
  308. fontSignedDistanceField ?: boolean,
  309. bitmapFontTexture ?: BitmapFontTexture,
  310. defaultFontColor ?: Color4,
  311. size ?: Size,
  312. tabulationSize ?: number,
  313. isVisible ?: boolean,
  314. isPickable ?: boolean,
  315. isContainer ?: boolean,
  316. childrenFlatZOrder ?: boolean,
  317. marginTop ?: number | string,
  318. marginLeft ?: number | string,
  319. marginRight ?: number | string,
  320. marginBottom ?: number | string,
  321. margin ?: number | string,
  322. marginHAlignment ?: number,
  323. marginVAlignment ?: number,
  324. marginAlignment ?: string,
  325. paddingTop ?: number | string,
  326. paddingLeft ?: number | string,
  327. paddingRight ?: number | string,
  328. paddingBottom ?: number | string,
  329. padding ?: string,
  330. }) {
  331. if (!settings) {
  332. settings = {};
  333. }
  334. super(settings);
  335. if (settings.bitmapFontTexture != null) {
  336. this._fontTexture = settings.bitmapFontTexture;
  337. this._fontName = null;
  338. this._fontSuperSample = false;
  339. this._fontSDF = false;
  340. } else {
  341. this._fontName = (settings.fontName==null) ? "12pt Arial" : settings.fontName;
  342. this._fontSuperSample= (settings.fontSuperSample!=null && settings.fontSuperSample);
  343. this._fontSDF = (settings.fontSignedDistanceField!=null && settings.fontSignedDistanceField);
  344. }
  345. this.defaultFontColor = (settings.defaultFontColor==null) ? new Color4(1,1,1,1) : settings.defaultFontColor;
  346. this._tabulationSize = (settings.tabulationSize == null) ? 4 : settings.tabulationSize;
  347. this._textSize = null;
  348. this.text = text;
  349. this.size = (settings.size==null) ? null : settings.size;
  350. this._updateRenderMode();
  351. }
  352. protected levelIntersect(intersectInfo: IntersectInfo2D): boolean {
  353. // For now I can't do something better that boundingInfo is a hit, detecting an intersection on a particular letter would be possible, but do we really need it? Not for now...
  354. return true;
  355. }
  356. protected createModelRenderCache(modelKey: string): ModelRenderCache {
  357. let renderCache = new Text2DRenderCache(this.owner.engine, modelKey);
  358. return renderCache;
  359. }
  360. protected setupModelRenderCache(modelRenderCache: ModelRenderCache) {
  361. let renderCache = <Text2DRenderCache>modelRenderCache;
  362. let engine = this.owner.engine;
  363. renderCache.fontTexture = this.fontTexture;
  364. renderCache.fontTexture.incCachedFontTextureCounter();
  365. let vb = new Float32Array(4);
  366. for (let i = 0; i < 4; i++) {
  367. vb[i] = i;
  368. }
  369. renderCache.vb = engine.createVertexBuffer(vb);
  370. let ib = new Float32Array(6);
  371. ib[0] = 0;
  372. ib[1] = 2;
  373. ib[2] = 1;
  374. ib[3] = 0;
  375. ib[4] = 3;
  376. ib[5] = 2;
  377. renderCache.ib = engine.createIndexBuffer(ib);
  378. // Get the instanced version of the effect, if the engine does not support it, null is return and we'll only draw on by one
  379. let ei = this.getDataPartEffectInfo(Text2D.TEXT2D_MAINPARTID, ["index"], null, true);
  380. if (ei) {
  381. renderCache.effectInstanced = engine.createEffect("text2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  382. }
  383. ei = this.getDataPartEffectInfo(Text2D.TEXT2D_MAINPARTID, ["index"], null, false);
  384. renderCache.effect = engine.createEffect("text2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  385. return renderCache;
  386. }
  387. protected createInstanceDataParts(): InstanceDataBase[] {
  388. return [new Text2DInstanceData(Text2D.TEXT2D_MAINPARTID, this._charCount)];
  389. }
  390. // Looks like a hack!? Yes! Because that's what it is!
  391. // For the InstanceData layer to compute correctly we need to set all the properties involved, which won't be the case if there's no text
  392. // This method is called before the layout construction for us to detect this case, set some text and return the initial one to restore it after (there can be some text without char to display, say "\t\n" for instance)
  393. protected beforeRefreshForLayoutConstruction(part: InstanceDataBase): any {
  394. if (!this._charCount) {
  395. let curText = this._text;
  396. this.text = "A";
  397. return curText;
  398. }
  399. }
  400. // if obj contains something, we restore the _text property
  401. protected afterRefreshForLayoutConstruction(part: InstanceDataBase, obj: any) {
  402. if (obj !== undefined) {
  403. this.text = obj;
  404. }
  405. }
  406. protected getUsedShaderCategories(dataPart: InstanceDataBase): string[] {
  407. var cat = super.getUsedShaderCategories(dataPart);
  408. if (this._fontSDF) {
  409. cat.push(Text2D.TEXT2D_CATEGORY_SDF);
  410. }
  411. return cat;
  412. }
  413. protected refreshInstanceDataPart(part: InstanceDataBase): boolean {
  414. if (!super.refreshInstanceDataPart(part)) {
  415. return false;
  416. }
  417. if (part.id === Text2D.TEXT2D_MAINPARTID) {
  418. let d = <Text2DInstanceData>part;
  419. let texture = this.fontTexture;
  420. let superSampleFactor = texture.isSuperSampled ? 0.5 : 1;
  421. let ts = texture.getSize();
  422. let offset = Vector2.Zero();
  423. let lh = this.fontTexture.lineHeight;
  424. offset.y = ((this.textSize.height/lh)-1) * lh; // Origin is bottom, not top, so the offset is starting with a y that is the top location of the text
  425. let charxpos = 0;
  426. d.dataElementCount = this._charCount;
  427. d.curElement = 0;
  428. for (let char of this.text) {
  429. // Line feed
  430. if (char === "\n") {
  431. offset.x = 0;
  432. offset.y -= texture.lineHeight;
  433. }
  434. // Tabulation ?
  435. if (char === "\t") {
  436. let nextPos = charxpos + this._tabulationSize;
  437. nextPos = nextPos - (nextPos % this._tabulationSize);
  438. offset.x += (nextPos - charxpos) * texture.spaceWidth;
  439. charxpos = nextPos;
  440. continue;
  441. }
  442. if (char < " ") {
  443. continue;
  444. }
  445. this.updateInstanceDataPart(d, offset);
  446. let ci = texture.getChar(char);
  447. offset.x += ci.charWidth;
  448. d.topLeftUV = ci.topLeftUV;
  449. let suv = ci.bottomRightUV.subtract(ci.topLeftUV);
  450. d.sizeUV = suv;
  451. d.textureSize = new Vector2(ts.width, ts.height);
  452. d.color = this.defaultFontColor;
  453. d.superSampleFactor = superSampleFactor;
  454. ++d.curElement;
  455. }
  456. }
  457. return true;
  458. }
  459. private _updateCharCount() {
  460. let count = 0;
  461. for (let char of this._text) {
  462. if (char === "\r" || char === "\n" || char === "\t" || char < " ") {
  463. continue;
  464. }
  465. ++count;
  466. }
  467. this._charCount = count;
  468. }
  469. protected _useTextureAlpha(): boolean {
  470. return this._fontSDF;
  471. }
  472. protected _shouldUseAlphaFromTexture(): boolean {
  473. return !this._fontSDF;
  474. }
  475. private _fontTexture: BaseFontTexture;
  476. private _tabulationSize: number;
  477. private _charCount: number;
  478. private _fontName: string;
  479. private _fontSuperSample: boolean;
  480. private _fontSDF: boolean;
  481. private _defaultFontColor: Color4;
  482. private _text: string;
  483. private _textSize: Size;
  484. }
  485. }