import type { Texture } from '../webgl/texture.js'; import { ENGINE_ERROR_CREATING_CANVAS_2D_CONTEXT, ENGINE_ERROR_GETTING_DOCUMENT } from '../../core/error_code.js'; import { hex2rgb } from '../../util/math.js'; import { create, removeByCanvas } from './pool.js'; import { getRegistry } from '../../core/registry.js'; import type { Game } from '../../core/game.js'; import type { Image } from '../image.js'; /** * Tints a sprite with the given color. * @param {object} sprite - The sprite to tint. * @param {object} color - The color to tint with. * @returns {object} The tinted sprite. */ export const getTintedTexture = (sprite: Image, color: number): HTMLCanvasElement => { const canvas = sprite.tintedTexture ?? create('CanvasTinter', 1, 1); const tint = globalThis.PhaserRegistry.CANVAS_TINT_METHOD; tint(sprite.texture, color, canvas); return canvas; }; /** * Tints a texture with the given color. * @param {object} texture - The texture to tint. * @param {object} color - The color to tint with. * @param {HTMLCanvasElement} canvas - The canvas to render to. * @throws {Error} If the operation fails. */ export const tintWithMultiply = (texture: Texture, color: number, canvas: HTMLCanvasElement): void => { const context = canvas.getContext('2d', { willReadFrequently: false }); if (!context) { throw new Error(ENGINE_ERROR_CREATING_CANVAS_2D_CONTEXT); } const { crop } = texture; if (canvas.width !== crop.width || canvas.height !== crop.height) { canvas.width = crop.width; canvas.height = crop.height; } context.clearRect(0, 0, crop.width, crop.height); context.fillStyle = `#${`00000${Math.trunc(color).toString(16)}`.slice(-6)}`; context.fillRect(0, 0, crop.width, crop.height); context.globalCompositeOperation = 'multiply'; context.drawImage( texture.baseTexture.source!, crop.x, crop.y, crop.width, crop.height, 0, 0, crop.width, crop.height ); context.globalCompositeOperation = 'destination-atop'; context.drawImage( texture.baseTexture.source!, crop.x, crop.y, crop.width, crop.height, 0, 0, crop.width, crop.height ); }; /** * Tints a texture with the given color. * @param {object} texture - The texture to tint. * @param {object} color - The color to tint with. * @param {HTMLCanvasElement} canvas - The canvas to render to. * @throws {Error} If the operation fails. */ export const tintWithPerPixel = (texture: Texture, color: number, canvas: HTMLCanvasElement): void => { const context = canvas.getContext('2d', { willReadFrequently: false }); if (!context) { throw new Error(ENGINE_ERROR_CREATING_CANVAS_2D_CONTEXT); } const { crop } = texture; canvas.width = crop.width; canvas.height = crop.height; context.globalCompositeOperation = 'copy'; context.drawImage( texture.baseTexture.source!, crop.x, crop.y, crop.width, crop.height, 0, 0, crop.width, crop.height ); const [r, g, b] = hex2rgb(color); const pixelData = context.getImageData(0, 0, crop.width, crop.height); const pixels = pixelData.data; for (let i = 0; i < pixels.length; i += 4) { pixels[i + 0]! *= r; pixels[i + 1]! *= g; pixels[i + 2]! *= b; const canHandleAlpha = globalThis.PhaserRegistry.CAN_CANVAS_HANDLE_ALPHA; if (!canHandleAlpha) { const alpha = pixels[i + 3]!; pixels[i + 0]! /= 255 / alpha; pixels[i + 1]! /= 255 / alpha; pixels[i + 2]! /= 255 / alpha; } } context.putImageData(pixelData, 0, 0); }; /** * Checks if the tinter can handle the given texture. * @returns {boolean} True if the tinter can handle the texture, false otherwise. * @throws {Error} If the operation fails. */ export const checkInverseAlpha = (): boolean => { // Check for DOM if (document === undefined) { throw new Error(ENGINE_ERROR_GETTING_DOCUMENT); } // Create canvas and context const canvas = create('CanvasAlpha', 2, 1, true); const context = canvas.getContext('2d', { willReadFrequently: false }); if (!context) { throw new Error(ENGINE_ERROR_CREATING_CANVAS_2D_CONTEXT); } // Set canvas fill style context.fillStyle = 'rgba(10, 20, 30, 0.5)'; // Draw a single pixel context.fillRect(0, 0, 1, 1); // Get the color values const s1 = context.getImageData(0, 0, 1, 1); if (s1 === null) { return false; } // Plot them to x2 context.putImageData(s1, 1, 0); // Get those values const s2 = context.getImageData(1, 0, 1, 1); // Dispose canvas try { context.reset(); } catch { // pass } removeByCanvas(canvas); // Compare and return return ( s2.data[0] === s1.data[0] && s2.data[1] === s1.data[1] && s2.data[2] === s1.data[2] && s2.data[3] === s1.data[3] ); }; /** * Checks if the tinter can handle the given texture. * @returns {boolean} True if the tinter can handle the texture, false otherwise. * @throws {Error} If the operation fails. */ export const canUseNewCanvasBlendModes = (): boolean => { // Check for DOM if (document === undefined) { throw new Error(ENGINE_ERROR_GETTING_DOCUMENT); } // Create test images const pngHead = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAABAQMAAADD8p2OAAAAA1BMVEX/'; const pngEnd = 'AAAACklEQVQI12NgAAAAAgAB4iG8MwAAAABJRU5ErkJggg=='; const magenta = new globalThis.Image(); magenta.src = `${pngHead}AP804Oa6${pngEnd}`; const yellow = new globalThis.Image(); yellow.src = `${pngHead}/wCKxvRF${pngEnd}`; // Create canvas and context const canvas = create('CanvasTinter', 6, 1, true); const context = canvas.getContext('2d', { willReadFrequently: false }); if (!context) { throw new Error(ENGINE_ERROR_CREATING_CANVAS_2D_CONTEXT); } // Draw test images to canvas context.globalCompositeOperation = 'multiply'; context.drawImage(magenta, 0, 0); context.drawImage(yellow, 2, 0); if (context.getImageData(2, 0, 1, 1) === null) { return false; } const { data } = context.getImageData(2, 0, 1, 1); // Dispose canvas try { context.reset(); } catch { // pass } removeByCanvas(canvas); // Compare and return return data[0] === 255 && data[1] === 0 && data[2] === 0; }; /** * Creates a new Tinter instance. * @param {Game} game - The game instance. */ export const detectCapabilities = (game: Game): void => { getRegistry(); try { globalThis.PhaserRegistry.CAN_CANVAS_USE_MULTIPLY = canUseNewCanvasBlendModes(); } catch (error) { const typedError = error instanceof Error ? error : new Error(String(error)); game.logger.fatal('Tinter', { error: typedError }); globalThis.PhaserRegistry.CAN_CANVAS_USE_MULTIPLY = false; } if (!globalThis.PhaserRegistry.CAN_CANVAS_USE_MULTIPLY) { // only detect canvas alpha support if tintWithPerPixel will be used try { globalThis.PhaserRegistry.CAN_CANVAS_HANDLE_ALPHA = checkInverseAlpha(); } catch (error) { const typedError = error instanceof Error ? error : new Error(String(error)); game.logger.fatal('Tinter', { error: typedError }); globalThis.PhaserRegistry.CAN_CANVAS_HANDLE_ALPHA = false; } } globalThis.PhaserRegistry.CANVAS_TINT_METHOD = globalThis.PhaserRegistry.CAN_CANVAS_USE_MULTIPLY ? tintWithMultiply : tintWithPerPixel; };