import type { Game } from '../core/game.js'; import type { Matrix } from '../geom/matrix.js'; import { BLEND_NORMAL, GRAPHICS } from '../core/const.js'; import { Circle } from '../geom/circle.js'; import { Ellipse } from '../geom/ellipse.js'; import { Point } from '../geom/point.js'; import { Polygon } from '../geom/polygon.js'; import { Rectangle } from '../geom/rectangle.js'; import { RoundedRectangle } from '../geom/rounded_rectangle.js'; import { getIdentityMatrix } from '../geom/util/matrix.js'; import { getEmptyRectangle } from '../geom/util/rectangle.js'; import { CanvasBuffer } from './canvas/buffer.js'; import { renderGraphics as renderCanvasGraphics } from './canvas/graphics.js'; import { DisplayObject } from './display_object.js'; import type { GraphicsShape } from './graphics_data.js'; import { GraphicsData } from './graphics_data.js'; import { Image } from './image.js'; import { renderCanvas as renderSpriteCanvas, renderWebGL as renderSpriteWebGL } from './sprite_util.js'; import { renderGraphics as renderWebGLGraphics } from './webgl/graphics.js'; import { textureFromCanvas } from './webgl/texture_util.js'; import type { RenderSession } from './render_session.js'; import type { GraphicsData as WebGLGraphicsData } from './webgl/graphics_data.js'; import type { IdentifiedWebGLRenderingContext } from './webgl/util.js'; /** Graphics attaches the buffer it draws into onto its cached sprite. */ export type CachedSprite = Image & { buffer: CanvasBuffer }; /** A polygon whose vertices have been flattened to a bare x, y number list. */ export type FlatPolygon = Omit & { points: number[] }; /** drawShape only records a current path for polygon data, and it flattens what it records. */ export type PolygonPath = Omit & { shape: FlatPolygon }; /** Per-context WebGL state cached on a graphics object, keyed by gl context id. */ export type GraphicsWebGLBucket = { lastIndex: number; data: WebGLGraphicsData[]; gl: IdentifiedWebGLRenderingContext; }; /** * Reports whether a triangle winds towards the viewer. In two dimensions the cross product is a * scalar, so its sign alone says which way the face points. * @param {Point[]} points - The three corners of the triangle, in order. * @returns {boolean} True when the triangle faces the viewer. */ const isFrontFacing = (points: Point[]): boolean => { const [a, b, c] = points; if (!a || !b || !c) { return true; } const ab = new Point(b.x - a.x, b.y - a.y); const cb = new Point(b.x - c.x, b.y - c.y); return cb.cross(ab) > 0; }; export class Graphics extends DisplayObject { declare public type: number; declare public renderable: boolean; public fillAlpha!: number; public lineWidth!: number; public lineColor!: number; public lineAlpha!: number; public graphicsData!: GraphicsData[]; declare public tint: number; public blendMode!: number; public currentPath!: PolygonPath | null; public _webGL!: Record; public isMask!: boolean; public boundsPadding!: number; public _localBounds!: Rectangle; public dirty!: boolean; public clearDirty!: boolean; public _boundsDirty!: boolean; public _cacheAsBitmap!: boolean; public webGLDirty!: boolean; public cachedSpriteDirty!: boolean; declare public _cachedSprite: CachedSprite | null; public filling!: boolean; public fillColor!: number | null; public _prevTint!: number; /** * Creates a new Graphics object. * @param {Game} game - The game instance. * @param {number} x - The x coordinate of the graphics object. * @param {number} y - The y coordinate of the graphics object. */ public constructor(game: Game, x = 0, y = 0) { super(game); /** @type {number} */ this.type = GRAPHICS; this.position.setTo(x, y); /** @type {boolean} */ this.renderable = true; /** @type {number} */ this.fillAlpha = 1; /** @type {number} */ this.lineWidth = 0; /** @type {number} */ this.lineColor = 0; this.graphicsData = []; /** @type {number} */ this.tint = 0xffffff; /** @type {number} */ this.blendMode = BLEND_NORMAL; /** @type {GraphicsData} */ this.currentPath = null; /** @type {object[]} */ this._webGL = []; /** @type {boolean} */ this.isMask = false; /** @type {number} */ this.boundsPadding = 0; /** @type {Rectangle} */ this._localBounds = new Rectangle(0, 0, 1, 1); /** @type {boolean} */ this.dirty = true; /** @type {boolean} */ this._boundsDirty = false; /** @type {boolean} */ this._cacheAsBitmap = false; /** @type {boolean} */ this.webGLDirty = false; /** @type {boolean} */ this.cachedSpriteDirty = false; } /** * Destroys the graphics object and clears all data. */ public override destroy(): void { this.clear(); super.destroy(); } /** * Sets the line style for subsequent drawing operations. * @param {number} lineWidth - The width of the line to draw. * @param {number} color - The color of the line to draw. * @param {number} alpha - The alpha (transparency) of the line to draw. * @returns {Graphics} This Graphics object for chaining. */ public lineStyle(lineWidth = 0, color = 0, alpha = 1): this { this.lineWidth = lineWidth || 0; this.lineColor = color || 0; this.lineAlpha = alpha ?? 1; if (this.currentPath) { if (this.currentPath.shape.points.length > 0) { // halfway through a line? start a new one! this.drawShape(new Polygon(this.currentPath.shape.points.slice(-2))); } else { // otherwise its empty so lets just set the line properties this.currentPath.lineWidth = this.lineWidth; this.currentPath.lineColor = this.lineColor; this.currentPath.lineAlpha = this.lineAlpha; } } return this; } /** * Moves the drawing cursor to the specified point. * @param {number} x - The x coordinate to move to. * @param {number} y - The y coordinate to move to. * @returns {Graphics} This Graphics object for chaining. */ public moveTo(x: number, y: number): this { this.drawShape(new Polygon([x, y])); return this; } /** * Draws a line from the current drawing position to the specified point. * @param {number} x - The x coordinate to draw to. * @param {number} y - The y coordinate to draw to. * @returns {Graphics} This Graphics object for chaining. */ public lineTo(x: number, y: number): this { if (!this.currentPath) { this.moveTo(0, 0); } this.currentPath!.shape.points.push(x, y); this.dirty = true; this._boundsDirty = true; return this; } /** * Draws a quadratic curve from the current position to the specified point. * @param {number} cpX - The x coordinate of the control point. * @param {number} cpY - The y coordinate of the control point. * @param {number} toX - The x coordinate to draw to. * @param {number} toY - The y coordinate to draw to. * @returns {Graphics} This Graphics object for chaining. */ public quadraticCurveTo(cpX: number, cpY: number, toX: number, toY: number): this { if (this.currentPath) { if (this.currentPath.shape.points.length === 0) { this.currentPath.shape.points = [0, 0]; } } else { this.moveTo(0, 0); } let xa; let ya; const n = 20; const { points } = this.currentPath!.shape; if (points.length === 0) { this.moveTo(0, 0); } const fromX = points.at(-2)!; const fromY = points.at(-1)!; let j = 0; for (let i = 1; i <= n; i += 1) { j = i / n; xa = fromX + (cpX - fromX) * j; ya = fromY + (cpY - fromY) * j; points.push(xa + (cpX + (toX - cpX) * j - xa) * j, ya + (cpY + (toY - cpY) * j - ya) * j); } this.dirty = true; this._boundsDirty = true; return this; } /** * Draws a cubic Bezier curve from the current position to the specified point. * @param {number} cpX - The x coordinate of the first control point. * @param {number} cpY - The y coordinate of the first control point. * @param {number} cpX2 - The x coordinate of the second control point. * @param {number} cpY2 - The y coordinate of the second control point. * @param {number} toX - The x coordinate to draw to. * @param {number} toY - The y coordinate to draw to. * @returns {Graphics} This Graphics object for chaining. */ public bezierCurveTo(cpX: number, cpY: number, cpX2: number, cpY2: number, toX: number, toY: number): this { if (this.currentPath) { if (this.currentPath.shape.points.length === 0) { this.currentPath.shape.points = [0, 0]; } } else { this.moveTo(0, 0); } const n = 20; let dt; let dt2; let dt3; let t2; let t3; const { points } = this.currentPath!.shape; const fromX = points.at(-2)!; const fromY = points.at(-1)!; let j = 0; for (let i = 1; i <= n; i += 1) { j = i / n; dt = 1 - j; dt2 = dt * dt; dt3 = dt2 * dt; t2 = j * j; t3 = t2 * j; points.push( dt3 * fromX + 3 * dt2 * j * cpX + 3 * dt * t2 * cpX2 + t3 * toX, dt3 * fromY + 3 * dt2 * j * cpY + 3 * dt * t2 * cpY2 + t3 * toY ); } this.dirty = true; this._boundsDirty = true; return this; } /** * Draws an arc from the current position to the specified point. * @param {number} x1 - The x coordinate of the starting point. * @param {number} y1 - The y coordinate of the starting point. * @param {number} x2 - The x coordinate of the end point. * @param {number} y2 - The y coordinate of the end point. * @param {number} radius - The radius of the arc. * @returns {Graphics} This Graphics object for chaining. */ public arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): this { if (this.currentPath) { if (this.currentPath.shape.points.length === 0) { this.currentPath.shape.points.push(x1, y1); } } else { this.moveTo(x1, y1); } const { points } = this.currentPath!.shape; const fromX = points.at(-2)!; const fromY = points.at(-1)!; const a1 = fromY - y1; const b1 = fromX - x1; const a2 = y2 - y1; const b2 = x2 - x1; const mm = Math.abs(a1 * b2 - b1 * a2); if (mm < 1e-8 || radius === 0) { if (points.at(-2) !== x1 || points.at(-1) !== y1) { points.push(x1, y1); } } else { const dd = a1 * a1 + b1 * b1; const cc = a2 * a2 + b2 * b2; const tt = a1 * a2 + b1 * b2; const k1 = (radius * Math.sqrt(dd)) / mm; const k2 = (radius * Math.sqrt(cc)) / mm; const j1 = (k1 * tt) / dd; const j2 = (k2 * tt) / cc; const cx = k1 * b2 + k2 * b1; const cy = k1 * a2 + k2 * a1; const px = b1 * (k2 + j1); const py = a1 * (k2 + j1); const qx = b2 * (k1 + j2); const qy = a2 * (k1 + j2); const startAngle = Math.atan2(py - cy, px - cx); const endAngle = Math.atan2(qy - cy, qx - cx); this.arc(cx + x1, cy + y1, radius, startAngle, endAngle, b1 * a2 > b2 * a1); } this.dirty = true; this._boundsDirty = true; return this; } /** * Draws an arc with the specified center, radius, and angles. * @param {number} cx - The x coordinate of the center point. * @param {number} cy - The y coordinate of the center point. * @param {number} radius - The radius of the arc. * @param {number} startAngle - The starting angle in radians. * @param {number} endAngle - The ending angle in radians. * @param {boolean} anticlockwise - Whether to draw the arc anticlockwise. * @param {number} segments - The number of segments to use for drawing the arc. * @returns {Graphics} This Graphics object for chaining. */ public arc( cx: number, cy: number, radius: number, startAngle: number, endAngle: number, anticlockwise = false, segments = 40 ): this { // If we do this we can never draw a full circle if (startAngle === endAngle) { return this; } const fullTurn = Math.PI * 2; const from = anticlockwise && startAngle <= endAngle ? startAngle + fullTurn : startAngle; const to = !anticlockwise && endAngle <= startAngle ? endAngle + fullTurn : endAngle; const sweep = anticlockwise ? (from - to) * -1 : to - from; const segs = Math.ceil(Math.abs(sweep) / (Math.PI * 2)) * segments; // Sweep check - moved here because we don't want to do the moveTo below if the arc fails if (sweep === 0) { return this; } const startX = cx + Math.cos(from) * radius; const startY = cy + Math.sin(from) * radius; if (anticlockwise && this.filling) { this.moveTo(cx, cy); } else { this.moveTo(startX, startY); } // currentPath will always exist after calling a moveTo const { points } = this.currentPath!.shape; const theta = sweep / (segs * 2); const theta2 = theta * 2; const cTheta = Math.cos(theta); const sTheta = Math.sin(theta); const segMinus = segs - 1; const remainder = (segMinus % 1) / segMinus; for (let i = 0; i <= segMinus; i += 1) { const real = i + remainder * i; const angle = theta + from + theta2 * real; const c = Math.cos(angle); const s = -Math.sin(angle); points.push((cTheta * c + sTheta * s) * radius + cx, (cTheta * -s + sTheta * c) * radius + cy); } this.dirty = true; this._boundsDirty = true; return this; } /** * Begins filling with the specified color and alpha. * @param {number} color - The fill color to use. * @param {number} alpha - The fill alpha (transparency) to use. * @returns {Graphics} This Graphics object for chaining. */ public beginFill(color = 0, alpha = 1): this { this.filling = true; this.fillColor = color || 0; this.fillAlpha = alpha ?? 1; if (this.currentPath && this.currentPath.shape.points.length <= 2) { this.currentPath.fill = this.filling; this.currentPath.fillColor = this.fillColor; this.currentPath.fillAlpha = this.fillAlpha; } return this; } /** * Ends the current fill operation. * @returns {Graphics} This Graphics object for chaining. */ public endFill(): this { this.filling = false; this.fillColor = null; this.fillAlpha = 1; return this; } /** * Draws a rectangle with the specified properties. * @param {number} x - The x coordinate of the rectangle. * @param {number} y - The y coordinate of the rectangle. * @param {number} width - The width of the rectangle. * @param {number} height - The height of the rectangle. * @returns {Graphics} This Graphics object for chaining. */ public drawRect(x: number, y: number, width: number, height: number): this { this.drawShape(new Rectangle(x, y, width, height)); return this; } /** * Draws a rounded rectangle with the specified properties. * @param {number} x - The x coordinate of the rectangle. * @param {number} y - The y coordinate of the rectangle. * @param {number} width - The width of the rectangle. * @param {number} height - The height of the rectangle. * @param {number} radius - The radius of the rounded corners. * @returns {Graphics} This Graphics object for chaining. */ public drawRoundedRect(x: number, y: number, width: number, height: number, radius: number): this { this.drawShape(new RoundedRectangle(x, y, width, height, radius)); return this; } /** * Draws a circle with the specified properties. * @param {number} x - The x coordinate of the center point. * @param {number} y - The y coordinate of the center point. * @param {number} diameter - The diameter of the circle. * @returns {Graphics} This Graphics object for chaining. */ public drawCircle(x: number, y: number, diameter: number): this { this.drawShape(new Circle(x, y, diameter)); return this; } /** * Draws an ellipse with the specified properties. * @param {number} x - The x coordinate of the center point. * @param {number} y - The y coordinate of the center point. * @param {number} width - The width of the ellipse. * @param {number} height - The height of the ellipse. * @returns {Graphics} This Graphics object for chaining. */ public drawEllipse(x: number, y: number, width: number, height: number): this { this.drawShape(new Ellipse(x, y, width, height)); return this; } /** * Draws a polygon with the specified path. * @param {Polygon} path - The polygon to draw. * @returns {Graphics} This Graphics object for chaining. */ public drawPolygon(path: Polygon): this { const points = path instanceof Polygon ? path.points : path; /* if (!Array.isArray(points)) { points = new Array(arguments.length); for (let i = 0; i < points.length; i += 1) { points[i] = arguments[i]; } } */ this.drawShape(new Polygon(points)); return this; } /** * Clears all graphics data. * @returns {Graphics} This Graphics object for chaining. */ public clear(): this { this.lineWidth = 0; this.filling = false; this.dirty = true; this._boundsDirty = true; this.clearDirty = true; this.graphicsData = []; this.updateLocalBounds(); return this; } /** * Generates a texture from the graphics object (not implemented). */ public override generateTexture(): void { this.game.logger.warn('graphics.generateTexture() is not implemented'); } /** * Renders the graphics object using WebGL. * @param {object} renderSession - The render session to use. */ public override renderWebGL(renderSession: RenderSession): void { // if the sprite is not visible or the alpha is 0 then no need to render this element if (!this.visible || this.alpha === 0 || this.isMask) { return; } if (this._cacheAsBitmap) { if (this.dirty || this.cachedSpriteDirty) { this.generateCachedSprite(); // we will also need to update the texture on the gpu too! this.updateCachedSpriteTexture(); this.cachedSpriteDirty = false; this.dirty = false; } this._cachedSprite!.worldAlpha = this.worldAlpha; renderSpriteWebGL(this._cachedSprite!, renderSession); } else { renderSession.spriteBatch.stop(); renderSession.blendModeManager.setBlendMode(this.blendMode); if (this._mask) { renderSession.maskManager.pushMask(this._mask, renderSession); } if (this._filters) { renderSession.filterManager.pushFilter(this._filterBlock); } // check blend mode if (this.blendMode !== renderSession.spriteBatch.currentBlendMode) { renderSession.spriteBatch.currentBlendMode = this.blendMode; const blendModeWebGL = globalThis.PhaserRegistry.blendModesWebGL[renderSession.spriteBatch.currentBlendMode]!; renderSession.spriteBatch.gl.blendFunc(blendModeWebGL[0]!, blendModeWebGL[1]!); } // check if the webgl graphic needs to be updated if (this.webGLDirty) { this.dirty = true; this.webGLDirty = false; } renderWebGLGraphics(this, renderSession); // only render if it has children! if (this.children.length > 0) { renderSession.spriteBatch.start(); // simple render children! for (const child of this.children) { child.renderWebGL(renderSession); } renderSession.spriteBatch.stop(); } if (this._filters) { renderSession.filterManager.popFilter(); } if (this._mask) { renderSession.maskManager.popMask(this.mask, renderSession); } renderSession.drawCount += 1; renderSession.spriteBatch.start(); } } /** * Renders the graphics object using Canvas. * @param {object} renderSession - The render session to use. */ public override renderCanvas(renderSession: RenderSession): void { // if the sprite is not visible or the alpha is 0 then no need to render this element if (!this.visible || this.alpha === 0 || this.isMask) { return; } // if the tint has changed, set the graphics object to dirty. if (this._prevTint !== this.tint) { this.dirty = true; this._prevTint = this.tint; } if (this._cacheAsBitmap) { if (this.dirty || this.cachedSpriteDirty) { this.generateCachedSprite(); // we will also need to update the texture this.updateCachedSpriteTexture(); this.cachedSpriteDirty = false; this.dirty = false; } this._cachedSprite!.alpha = this.alpha; renderSpriteCanvas(this._cachedSprite!, renderSession); } else { const { context } = renderSession; const transform = this.worldTransform; if (this.blendMode !== renderSession.currentBlendMode) { renderSession.currentBlendMode = this.blendMode; context.globalCompositeOperation = globalThis.PhaserRegistry.blendModesCanvas[renderSession.currentBlendMode] ?? 'source-over'; } if (this._mask) { renderSession.maskManager.pushMask(this._mask, renderSession); } const { resolution } = renderSession; const tx = transform.tx * renderSession.resolution + renderSession.shakeX; const ty = transform.ty * renderSession.resolution + renderSession.shakeY; context.setTransform( transform.a * resolution, transform.b * resolution, transform.c * resolution, transform.d * resolution, tx, ty ); renderCanvasGraphics(this, context); // simple render children! for (const child of this.children) { child.renderCanvas(renderSession); } if (this._mask) { renderSession.maskManager.popMask(this._mask, renderSession); } } } /** * Gets the bounds of the graphics object. * @param {Matrix} matrix - The transformation matrix to use. * @returns {Rectangle} The bounds rectangle of the graphics object. */ public override getBounds(matrix: Matrix | null = null): Rectangle { if (!this.renderable) { return getEmptyRectangle(); } if (this.dirty) { this.updateLocalBounds(); this.webGLDirty = true; this.cachedSpriteDirty = true; this.dirty = false; } else if (this.currentBounds) { return this.currentBounds; } const bounds = this._localBounds; const w0 = bounds.x; const w1 = bounds.width + bounds.x; const h0 = bounds.y; const h1 = bounds.height + bounds.y; const worldTransform = matrix ?? this.worldTransform; const { a } = worldTransform; const { b } = worldTransform; const { c } = worldTransform; const { d } = worldTransform; const { tx } = worldTransform; const { ty } = worldTransform; const x1 = a * w1 + c * h1 + tx; const y1 = d * h1 + b * w1 + ty; const x2 = a * w0 + c * h1 + tx; const y2 = d * h1 + b * w0 + ty; const x3 = a * w0 + c * h0 + tx; const y3 = d * h0 + b * w0 + ty; const x4 = a * w1 + c * h0 + tx; const y4 = d * h0 + b * w1 + ty; let maxX = x1; let maxY = y1; let minX = x1; let minY = y1; minX = x2 < minX ? x2 : minX; minX = x3 < minX ? x3 : minX; minX = x4 < minX ? x4 : minX; minY = y2 < minY ? y2 : minY; minY = y3 < minY ? y3 : minY; minY = y4 < minY ? y4 : minY; maxX = x2 > maxX ? x2 : maxX; maxX = x3 > maxX ? x3 : maxX; maxX = x4 > maxX ? x4 : maxX; maxY = y2 > maxY ? y2 : maxY; maxY = y3 > maxY ? y3 : maxY; maxY = y4 > maxY ? y4 : maxY; this.cachedBounds.x = minX; this.cachedBounds.width = maxX - minX; this.cachedBounds.y = minY; this.cachedBounds.height = maxY - minY; this.currentBounds = this.cachedBounds; return this.currentBounds; } /** * Gets the local bounds of the graphics object. * @returns {Rectangle} The local bounds rectangle of the graphics object. */ public override getLocalBounds(): Rectangle { const matrixCache = this.worldTransform; this.worldTransform = getIdentityMatrix(); for (const child of this.children) { child.updateTransform(); } const bounds = this.getBounds(); this.worldTransform = matrixCache; for (const child of this.children) { child.updateTransform(); } return bounds; } /** * Checks if the graphics object contains a point. * @param {Point} point - The point to check. * @param {Point} tempPoint - A temporary point object to use. * @returns {boolean} True if the graphics object contains the point, otherwise false. */ public containsPoint(point: Point, tempPoint: Point): boolean { this.worldTransform.applyInverse(point, tempPoint); const { graphicsData } = this; for (const data of graphicsData) { if (data.fill && data.shape?.contains(tempPoint.x, tempPoint.y)) { return true; } } return false; } /** * Updates the local bounds of the graphics object. */ public updateLocalBounds(): void { let minX = Infinity; let maxX = -Infinity; let minY = Infinity; let maxY = -Infinity; if (this.graphicsData.length > 0) { let points; let x; let y; let w; let h; for (const data of this.graphicsData) { const { lineWidth, shape } = data; if (shape instanceof Rectangle || shape instanceof RoundedRectangle) { x = shape.x - lineWidth / 2; y = shape.y - lineWidth / 2; w = shape.width + lineWidth; h = shape.height + lineWidth; minX = x < minX ? x : minX; maxX = x + w > maxX ? x + w : maxX; minY = y < minY ? y : minY; maxY = y + h > maxY ? y + h : maxY; } else if (shape instanceof Circle) { ({ x, y } = shape); w = shape.radius + lineWidth / 2; h = shape.radius + lineWidth / 2; minX = x - w < minX ? x - w : minX; maxX = x + w > maxX ? x + w : maxX; minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } else if (shape instanceof Ellipse) { ({ x, y } = shape); w = shape.width + lineWidth / 2; h = shape.height + lineWidth / 2; minX = x - w < minX ? x - w : minX; maxX = x + w > maxX ? x + w : maxX; minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } else { // POLY - assumes points are sequential, not Point objects ({ points } = shape); for (let j = 0; j < points.length; j += 1) { const vertex = points[j]; if (vertex instanceof Point) { ({ x, y } = vertex); } else { x = vertex!; y = points[j + 1] as number; if (j < points.length - 1) { j += 1; } } minX = x - lineWidth < minX ? x - lineWidth : minX; maxX = x + lineWidth > maxX ? x + lineWidth : maxX; minY = y - lineWidth < minY ? y - lineWidth : minY; maxY = y + lineWidth > maxY ? y + lineWidth : maxY; } } } } else { minX = 0; maxX = 0; minY = 0; maxY = 0; } const padding = this.boundsPadding; this._localBounds.x = minX - padding; this._localBounds.width = maxX - minX + padding * 2; this._localBounds.y = minY - padding; this._localBounds.height = maxY - minY + padding * 2; } /** * Generates a cached sprite representation of the graphics object. */ public override generateCachedSprite(): void { const bounds = this.getLocalBounds(); if (!this._cachedSprite) { const canvasBuffer = new CanvasBuffer(bounds.width, bounds.height); const texture = textureFromCanvas(canvasBuffer.canvas); this._cachedSprite = new Image(this.game, 0, 0, texture) as CachedSprite; this._cachedSprite.buffer = canvasBuffer; this._cachedSprite.worldTransform = this.worldTransform; } else { this._cachedSprite.buffer.resize(bounds.width, bounds.height); } // leverage the anchor to account for the offset of the element this._cachedSprite.anchor.x = -(bounds.x / bounds.width); this._cachedSprite.anchor.y = -(bounds.y / bounds.height); // this._cachedSprite.buffer.context.save(); this._cachedSprite.buffer.context.translate(-bounds.x, -bounds.y); // make sure we set the alpha of the graphics to 1 for the render.. this.worldAlpha = 1; // now render the graphic.. renderCanvasGraphics(this, this._cachedSprite.buffer.context); this._cachedSprite.alpha = this.alpha; } /** * Updates the cached sprite texture. */ public updateCachedSpriteTexture(): void { const cachedSprite = this._cachedSprite!; const { texture } = cachedSprite; const { canvas } = cachedSprite.buffer; texture.baseTexture.width = canvas.width; texture.baseTexture.height = canvas.height; texture.crop.width = canvas.width; texture.crop.height = canvas.height; texture.frame.width = canvas.width; texture.frame.height = canvas.height; cachedSprite._width = canvas.width; cachedSprite._height = canvas.height; // update the dirty base textures texture.baseTexture.dirty(); } /** * Destroys the cached sprite. */ public override destroyCachedSprite(): void { if (!this._cachedSprite) { return; } this._cachedSprite.texture.destroy(true); this._cachedSprite = null; } /** * Draws a shape with the specified properties. * @param {object} shape - The shape to draw. * @returns {GraphicsData} The graphics data for the drawn shape. */ public drawShape(shape: GraphicsShape): GraphicsData { // check current path! if (this.currentPath && this.currentPath.shape.points.length <= 2) { this.graphicsData.pop(); } this.currentPath = null; // Handle mixed-type polygons let target = shape; if (target instanceof Polygon) { target = target.clone(); target.flatten(); } const data = new GraphicsData( this.lineWidth, this.lineColor, this.lineAlpha, this.fillColor, this.fillAlpha, this.filling, target ); this.graphicsData.push(data); if (data.shape instanceof Polygon) { data.shape.closed = this.filling; this.currentPath = data as PolygonPath; } this.dirty = true; this._boundsDirty = true; return data; } /** * Performs post-update operations for the graphics object. */ public override postUpdate(): void { if (this._boundsDirty) { this.updateLocalBounds(); this._boundsDirty = false; } for (const child of this.children) { child.postUpdate(); } } /** * Draws a triangle with the specified points and culling options. * @param {Point[]} points - The points of the triangle. * @param {boolean} cull - Whether to perform backface culling. */ public drawTriangle(points: Point[], cull = false): void { const triangle = new Polygon(points); if (cull && !isFrontFacing(points)) { return; } this.drawPolygon(triangle); } /** * Draws triangles with the specified vertices and indices. * @param {number[]|Point[]} vertices - The vertices of the triangles. * @param {number[]} indices - The indices of the vertices to use. * @param {boolean} cull - Whether to perform backface culling. */ public drawTriangles(vertices: Point[] | number[], indices: number[] | null, cull = false): void { let points: Point[] = []; let i; if (indices === null) { if (vertices[0] instanceof Point) { const corners = vertices as Point[]; for (i = 0; i < corners.length / 3; i += 1) { this.drawTriangle([corners[i * 3]!, corners[i * 3 + 1]!, corners[i * 3 + 2]!], cull); } } else { const coordinates = vertices as number[]; for (i = 0; i < coordinates.length / 6; i += 1) { this.drawTriangle( [ new Point(coordinates[i * 6 + 0], coordinates[i * 6 + 1]), new Point(coordinates[i * 6 + 2], coordinates[i * 6 + 3]), new Point(coordinates[i * 6 + 4], coordinates[i * 6 + 5]), ], cull ); } } } else if (vertices[0] instanceof Point) { const corners = vertices as Point[]; for (i = 0; i < indices.length / 3; i += 1) { points.push(corners[indices[i * 3]!]!, corners[indices[i * 3 + 1]!]!, corners[indices[i * 3 + 2]!]!); if (points.length === 3) { this.drawTriangle(points, cull); points = []; } } } else { const coordinates = vertices as number[]; for (i = 0; i < indices.length; i += 1) { points.push(new Point(coordinates[indices[i]! * 2], coordinates[indices[i]! * 2 + 1])); if (points.length === 3) { this.drawTriangle(points, cull); points = []; } } } } }