import { BITMAP_TEXT, SCALE_LINEAR, SCALE_NEAREST } from '../core/const.js'; import { Point } from '../geom/point.js'; import { DisplayObject } from './display_object.js'; import { Image } from './image.js'; import type { BitmapFontCacheEntry } from '../core/cache.js'; import type { Game } from '../core/game.js'; import type { BitmapFontData } from '../core/loader_parser.js'; /** One measured line of bitmap text: its width, its content and where each glyph starts. */ export type BitmapTextLine = { width: number; text: string; end: boolean; chars: number[]; y: number; }; export class BitmapText extends DisplayObject { declare public type: number; public pendingDestroy!: boolean; declare public renderOrderID: number; public textWidth!: number; public textHeight!: number; public _prevAnchor!: Point; public _glyphs!: Image[]; public _maxWidth!: number; public _text!: string; public _data!: BitmapFontCacheEntry | null; public _font!: string; public _fontSize!: number; public _align!: string; public _tint!: number; public dirty!: boolean; /** * Creates a new BitmapText instance. * @param {Game} game - The game instance this bitmap text belongs to. * @param {number} x - The x position of the bitmap text. * @param {number} y - The y position of the bitmap text. * @param {string} font - The key of the bitmap font to use. * @param {string} text - The text to display. * @param {number} size - The font size. * @param {string} align - The text alignment (left, center, right). */ public constructor(game: Game, x = 0, y = 0, font = '', text = '', size = 32, align = 'left') { super(game); this.type = BITMAP_TEXT; this.position.setTo(x, y); this.textWidth = 0; this.textHeight = 0; this._prevAnchor = new Point(); this._glyphs = []; this._maxWidth = 0; this._text = text || ''; this._data = game.cache.getBitmapFont(font); this._font = font; this._fontSize = size; this._align = align; this._tint = 0xffffff; this.updateText(); this.dirty = false; } /** * Destroys this bitmap text and cleans up resources. */ public override destroy(): void { this._prevAnchor = null!; this._glyphs = null!; this._text = null!; this._data = null; super.destroy(); } /** * Called before the update cycle for this bitmap text. */ public override preUpdate(): void { if (this.pendingDestroy) { this.destroy(); return; } if (!this.exists || this.parent?.exists !== true) { this.renderOrderID = -1; return; } if (this.visible) { this.game.stage.currentRenderOrderID += 1; this.renderOrderID = this.game.stage.currentRenderOrderID; } for (const child of this.children) { child.preUpdate(); } } /** * Sets the text to display. * @param {string} text - The new text to display. */ public setText(text: string): void { this.text = text; } /** * Scans a line of text to calculate its width and other properties. * @param {object} data - The font data for this bitmap text. * @param {number} scale - The scaling factor to apply to the font size. * @param {string} text - The text to scan. * @returns {{width: number, text: string, end: boolean, chars: number[]}} An object containing the width, processed text, end status, and character positions. */ public scanLine(data: BitmapFontData, scale: number, text: string): Omit { let x = 0; let w = 0; let lastSpace = -1; let wrappedWidth = 0; let prevCharCode = null; const maxWidth = this._maxWidth > 0 ? this._maxWidth : null; const chars: number[] = []; // Let's scan the text and work out if any of the lines are > maxWidth let end = true; for (let i = 0; i < text.length; i += 1) { end = i === text.length - 1; if (/(?:\r\n|\r|\n)/.test(text.charAt(i))) { return { width: w, text: text.slice(0, i), end, chars, }; } let charCode = text.codePointAt(i) ?? 32; let charData = data.chars[charCode]; let c = 0; // If the character data isn't found in the data array // then we replace it with a blank space if (charData === undefined) { charCode = 32; charData = data.chars[charCode]; } if (charData === undefined) { continue; } // Adjust for kerning from previous character to this one const kerning = (prevCharCode === null ? 0 : charData.kerning[prevCharCode]) ?? 0; // Record the last space in the string and the current width if (/(\s)/.test(text.charAt(i))) { lastSpace = i; wrappedWidth = w; } // What will the line width be if we add this character to it? c = (kerning + (charData.texture?.width ?? 0) + charData.xOffset) * scale; // Do we need to line-wrap? if (maxWidth !== null && w + c >= maxWidth && lastSpace > -1) { // The last space was at "lastSpace" which was "i - lastSpace" characters ago return { width: wrappedWidth || w, text: text.slice(0, lastSpace), end, chars, }; } w += (charData.xAdvance + kerning) * scale; chars.push(x + (charData.xOffset + kerning) * scale); x += (charData.xAdvance + kerning) * scale; prevCharCode = charCode; } return { width: w, text, end, chars, }; } /** * Cleans the provided text by removing invalid characters and replacing them with a specified character. * @param {string} text - The text to clean. * @param {string} replace - The character to use for replacement of invalid characters (default: ''). * @returns {string} The cleaned text. */ public cleanText(text: string, replace = ''): string { const data = this._data?.font; if (!data) { return ''; } const re = /\r\n|\n\r|\n|\r/g; const lines = text.replace(re, '\n').split('\n'); for (let i = 0; i < lines.length; i += 1) { const line = lines[i]!; let output = ''; for (let c = 0; c < line.length; c += 1) { output = output.concat(data.chars[line.codePointAt(c) ?? 32] ? line[c]! : replace); } lines[i] = output; } return lines.join('\n'); } /** * Updates the internal text rendering based on current properties and content. */ public updateText(): void { const data = this._data?.font; if (!data) { return; } let { text } = this; const scale = this._fontSize / data.size; const lines: BitmapTextLine[] = []; let y = 0; this.textWidth = 0; let end = false; do { const line: BitmapTextLine = { ...this.scanLine(data, scale, text), y }; lines.push(line); if (line.width > this.textWidth) { this.textWidth = line.width; } y += data.lineHeight * scale; text = text.slice(line.text.length + 1); ({ end } = line); } while (!end); this.textHeight = y; let t = 0; let align = 0; const ax = this.textWidth * this.anchor.x; const ay = this.textHeight * this.anchor.y; for (const currentLine of lines) { if (this._align === 'right') { align = this.textWidth - currentLine.width; } else if (this._align === 'center') { align = (this.textWidth - currentLine.width) / 2; } for (let c = 0; c < currentLine.text.length; c += 1) { let charCode = currentLine.text.codePointAt(c) ?? 32; let charData = data.chars[charCode]; if (charData === undefined) { charCode = 32; charData = data.chars[charCode]; } if (charData?.texture === undefined) { continue; } let g = this._glyphs[t]; if (g) { // Sprite already exists in the glyphs pool, so we'll reuse it for this letter g.texture = charData.texture; } else { // We need a new sprite as the pool is empty or exhausted g = new Image(this.game, 0, 0, charData.texture); g.name = currentLine.text[c] ?? ''; this._glyphs.push(g); } g.position.x = (currentLine.chars[c] ?? 0) + align - ax; g.position.y = currentLine.y + charData.yOffset * scale - ay; g.scale.setTo(scale, scale); g.tint = this.tint; g.texture.requiresReTint = true; if (!g.parent) { this.addChild(g); } t += 1; } } // Remove unnecessary children // This moves them from the display list (children array) but retains them in the _glyphs pool for (let i = t; i < this._glyphs.length; i += 1) { this.removeChild(this._glyphs[i]!); } } /** * Removes unused glyphs from the pool and returns the number removed. * @returns {number} The number of glyphs that were removed from the pool. */ public purgeGlyphs(): number { const len = this._glyphs.length; const kept = []; for (const glyph of this._glyphs) { if (glyph.parent !== this) { glyph.destroy(); } else { kept.push(glyph); } } this._glyphs = []; this._glyphs = kept; this.updateText(); return len - kept.length; } /** * Updates the transform of this bitmap text, updating its text if needed. */ public override updateTransform(): this { if (this.dirty || !this.anchor.equals(this._prevAnchor)) { this.updateText(); this.dirty = false; this._prevAnchor.copyFrom(this.anchor); } super.updateTransform(); return this; } /** * Adds a color to a specific position in the text. * @param {string} value - The color to apply (in hex format or CSS color name). * @param {number} _position - The character position to apply the color to. * @returns {BitmapText} This bitmap text instance for chaining. */ public addColor(value: string, _position: number): this { const color = typeof value === 'string' ? Number.parseInt(value.replace('#', ''), 16) : value; if (color !== this._tint) { this._tint = color; this.updateText(); } return this; } /** * Gets the text alignment property. * @returns {string} The current text alignment (left, center, right). */ public get align(): string { return this._align; } /** * Sets the text alignment property. * @param {string} value - The new text alignment (left, center, right). */ public set align(value: string) { if (value !== this._align && (value === 'left' || value === 'center' || value === 'right')) { this._align = value; this.updateText(); } } /** * Gets the tint color of this bitmap text. * @returns {number} The current tint color in RGB format. */ public get tint(): number { return this._tint; } /** * Sets the tint color of this bitmap text. * @param {number} value - The new tint color in RGB format. */ public set tint(value: number) { if (value !== this._tint) { this._tint = value; this.updateText(); } } /** * Gets the fill color of this bitmap text as a hex string. * @returns {string} The current fill color in hex format. */ public get fill(): string { if (typeof this.tint === 'number') { let colorStr = this.tint.toString(16); while (colorStr.length < 6) { colorStr = `0${colorStr}`; } return `#${colorStr.toUpperCase()}`; } return this.tint; } /** * Sets the fill color of this bitmap text. * @param {string} value - The new fill color in hex format or CSS color name. */ public set fill(value: string) { this.tint = typeof value === 'string' ? Number.parseInt(value.replace('#', ''), 16) : value; } /** * Gets the font key used by this bitmap text. * @returns {string} The current font key. */ public get font(): string { return this._font; } /** * Sets the font key used by this bitmap text. * @param {string} value - The new font key to use. */ public set font(value: string) { const trimmedValue = value.trim(); if (trimmedValue !== this._font) { this._font = trimmedValue; this._data = this.game.cache.getBitmapFont(this._font); this.updateText(); } } /** * Gets the font size of this bitmap text. * @returns {number} The current font size. */ public get fontSize(): number { return this._fontSize; } /** * Sets the font size of this bitmap text. * @param {number} value - The new font size to use. */ public set fontSize(value: number | string) { const size = Math.trunc(Number(value)); if (size !== this._fontSize && size > 0) { this._fontSize = size; this.updateText(); } } /** * Gets the text content of this bitmap text. * @returns {string} The current text content. */ public get text(): string { return this._text; } /** * Sets the text content of this bitmap text. * @param {string | number | boolean | Date} value - The new text content to set. */ public set text(value: string | number | boolean | Date) { const typedValue = value.toString(); if (typedValue !== this._text) { this._text = typedValue || ''; this.updateText(); } } /** * Gets the maximum width of this bitmap text. * @returns {number} The current maximum width. */ public get maxWidth(): number { return this._maxWidth; } /** * Sets the maximum width of this bitmap text. * @param {number} value - The new maximum width to set. */ public set maxWidth(value: number) { if (value !== this._maxWidth) { this._maxWidth = value; this.updateText(); } } /** * Gets whether smoothing is enabled for this bitmap text's font. * @returns {boolean} True if smoothing is enabled, false otherwise. */ public get smoothed(): boolean { return this._data?.base.scaleMode === 0; } /** * Sets whether smoothing is enabled for this bitmap text's font. * @param {boolean} value - Whether to enable smoothing (true) or not (false). */ public set smoothed(value: boolean) { if (this._data) { this._data.base.scaleMode = value ? SCALE_LINEAR : SCALE_NEAREST; } } }