This commit is contained in:
Akko
2025-08-04 18:57:35 +02:00
parent 8cf6e78a79
commit 9495868c2e
5030 changed files with 518594 additions and 17609 deletions

View File

@@ -0,0 +1,49 @@
import type { ICanvas, ICanvasRenderingContext2DSettings } from '../../../../environment/canvas/ICanvas';
import type { ICanvasRenderingContext2D } from '../../../../environment/canvas/ICanvasRenderingContext2D';
export interface CanvasAndContext {
canvas: ICanvas;
context: ICanvasRenderingContext2D;
}
/**
* Texture pool, used by FilterSystem and plugins.
*
* Stores collection of temporary pow2 or screen-sized renderTextures
*
* If you use custom RenderTexturePool for your filters, you can use methods
* `getFilterTexture` and `returnFilterTexture` same as in
* @name CanvasPool
* @memberof rendering
*/
export declare class CanvasPoolClass {
canvasOptions: ICanvasRenderingContext2DSettings;
/**
* Allow renderTextures of the same size as screen, not just pow2
*
* Automatically sets to true after `setScreenSize`
* @default false
*/
enableFullScreen: boolean;
private _canvasPool;
constructor(canvasOptions?: ICanvasRenderingContext2DSettings);
/**
* Creates texture with params that were specified in pool constructor.
* @param pixelWidth - Width of texture in pixels.
* @param pixelHeight - Height of texture in pixels.
*/
private _createCanvasAndContext;
/**
* Gets a Power-of-Two render texture or fullScreen texture
* @param minWidth - The minimum width of the render texture.
* @param minHeight - The minimum height of the render texture.
* @param resolution - The resolution of the render texture.
* @returns The new render texture.
*/
getOptimalCanvasAndContext(minWidth: number, minHeight: number, resolution?: number): CanvasAndContext;
/**
* Place a render texture back into the pool.
* @param canvasAndContext
*/
returnCanvasAndContext(canvasAndContext: CanvasAndContext): void;
clear(): void;
}
export declare const CanvasPool: CanvasPoolClass;

View File

@@ -0,0 +1,65 @@
'use strict';
var adapter = require('../../../../environment/adapter.js');
var pow2 = require('../../../../maths/misc/pow2.js');
"use strict";
class CanvasPoolClass {
constructor(canvasOptions) {
this._canvasPool = /* @__PURE__ */ Object.create(null);
this.canvasOptions = canvasOptions || {};
this.enableFullScreen = false;
}
/**
* Creates texture with params that were specified in pool constructor.
* @param pixelWidth - Width of texture in pixels.
* @param pixelHeight - Height of texture in pixels.
*/
_createCanvasAndContext(pixelWidth, pixelHeight) {
const canvas = adapter.DOMAdapter.get().createCanvas();
canvas.width = pixelWidth;
canvas.height = pixelHeight;
const context = canvas.getContext("2d");
return { canvas, context };
}
/**
* Gets a Power-of-Two render texture or fullScreen texture
* @param minWidth - The minimum width of the render texture.
* @param minHeight - The minimum height of the render texture.
* @param resolution - The resolution of the render texture.
* @returns The new render texture.
*/
getOptimalCanvasAndContext(minWidth, minHeight, resolution = 1) {
minWidth = Math.ceil(minWidth * resolution - 1e-6);
minHeight = Math.ceil(minHeight * resolution - 1e-6);
minWidth = pow2.nextPow2(minWidth);
minHeight = pow2.nextPow2(minHeight);
const key = (minWidth << 17) + (minHeight << 1);
if (!this._canvasPool[key]) {
this._canvasPool[key] = [];
}
let canvasAndContext = this._canvasPool[key].pop();
if (!canvasAndContext) {
canvasAndContext = this._createCanvasAndContext(minWidth, minHeight);
}
return canvasAndContext;
}
/**
* Place a render texture back into the pool.
* @param canvasAndContext
*/
returnCanvasAndContext(canvasAndContext) {
const canvas = canvasAndContext.canvas;
const { width, height } = canvas;
const key = (width << 17) + (height << 1);
this._canvasPool[key].push(canvasAndContext);
}
clear() {
this._canvasPool = {};
}
}
const CanvasPool = new CanvasPoolClass();
exports.CanvasPool = CanvasPool;
exports.CanvasPoolClass = CanvasPoolClass;
//# sourceMappingURL=CanvasPool.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,62 @@
import { DOMAdapter } from '../../../../environment/adapter.mjs';
import { nextPow2 } from '../../../../maths/misc/pow2.mjs';
"use strict";
class CanvasPoolClass {
constructor(canvasOptions) {
this._canvasPool = /* @__PURE__ */ Object.create(null);
this.canvasOptions = canvasOptions || {};
this.enableFullScreen = false;
}
/**
* Creates texture with params that were specified in pool constructor.
* @param pixelWidth - Width of texture in pixels.
* @param pixelHeight - Height of texture in pixels.
*/
_createCanvasAndContext(pixelWidth, pixelHeight) {
const canvas = DOMAdapter.get().createCanvas();
canvas.width = pixelWidth;
canvas.height = pixelHeight;
const context = canvas.getContext("2d");
return { canvas, context };
}
/**
* Gets a Power-of-Two render texture or fullScreen texture
* @param minWidth - The minimum width of the render texture.
* @param minHeight - The minimum height of the render texture.
* @param resolution - The resolution of the render texture.
* @returns The new render texture.
*/
getOptimalCanvasAndContext(minWidth, minHeight, resolution = 1) {
minWidth = Math.ceil(minWidth * resolution - 1e-6);
minHeight = Math.ceil(minHeight * resolution - 1e-6);
minWidth = nextPow2(minWidth);
minHeight = nextPow2(minHeight);
const key = (minWidth << 17) + (minHeight << 1);
if (!this._canvasPool[key]) {
this._canvasPool[key] = [];
}
let canvasAndContext = this._canvasPool[key].pop();
if (!canvasAndContext) {
canvasAndContext = this._createCanvasAndContext(minWidth, minHeight);
}
return canvasAndContext;
}
/**
* Place a render texture back into the pool.
* @param canvasAndContext
*/
returnCanvasAndContext(canvasAndContext) {
const canvas = canvasAndContext.canvas;
const { width, height } = canvas;
const key = (width << 17) + (height << 1);
this._canvasPool[key].push(canvasAndContext);
}
clear() {
this._canvasPool = {};
}
}
const CanvasPool = new CanvasPoolClass();
export { CanvasPool, CanvasPoolClass };
//# sourceMappingURL=CanvasPool.mjs.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,11 @@
import type { ICanvas } from '../../../../environment/canvas/ICanvas';
import type { Texture } from './Texture';
export type GetPixelsOutput = {
pixels: Uint8ClampedArray;
width: number;
height: number;
};
export interface CanvasGenerator {
generateCanvas(texture: Texture): ICanvas;
getPixels(texture: Texture): GetPixelsOutput;
}

View File

@@ -0,0 +1,4 @@
'use strict';
"use strict";
//# sourceMappingURL=GenerateCanvas.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"GenerateCanvas.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;"}

View File

@@ -0,0 +1,2 @@
"use strict";
//# sourceMappingURL=GenerateCanvas.mjs.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"GenerateCanvas.mjs","sources":[],"sourcesContent":[],"names":[],"mappings":""}

View File

@@ -0,0 +1,18 @@
import { Texture } from './Texture';
import type { TextureSourceOptions } from './sources/TextureSource';
/**
* A render texture, extends `Texture`.
* @see {@link rendering.Texture}
* @memberof rendering
*/
export declare class RenderTexture extends Texture {
static create(options: TextureSourceOptions): RenderTexture;
/**
* Resizes the render texture.
* @param width - The new width of the render texture.
* @param height - The new height of the render texture.
* @param resolution - The new resolution of the render texture.
* @returns This texture.
*/
resize(width: number, height: number, resolution?: number): this;
}

View File

@@ -0,0 +1,27 @@
'use strict';
var TextureSource = require('./sources/TextureSource.js');
var Texture = require('./Texture.js');
"use strict";
class RenderTexture extends Texture.Texture {
static create(options) {
return new RenderTexture({
source: new TextureSource.TextureSource(options)
});
}
/**
* Resizes the render texture.
* @param width - The new width of the render texture.
* @param height - The new height of the render texture.
* @param resolution - The new resolution of the render texture.
* @returns This texture.
*/
resize(width, height, resolution) {
this.source.resize(width, height, resolution);
return this;
}
}
exports.RenderTexture = RenderTexture;
//# sourceMappingURL=RenderTexture.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"RenderTexture.js","sources":["../../../../../src/rendering/renderers/shared/texture/RenderTexture.ts"],"sourcesContent":["import { TextureSource } from './sources/TextureSource';\nimport { Texture } from './Texture';\n\nimport type { TextureSourceOptions } from './sources/TextureSource';\n\n/**\n * A render texture, extends `Texture`.\n * @see {@link rendering.Texture}\n * @memberof rendering\n */\nexport class RenderTexture extends Texture\n{\n public static create(options: TextureSourceOptions): RenderTexture\n {\n return new RenderTexture({\n source: new TextureSource(options)\n });\n }\n\n /**\n * Resizes the render texture.\n * @param width - The new width of the render texture.\n * @param height - The new height of the render texture.\n * @param resolution - The new resolution of the render texture.\n * @returns This texture.\n */\n public resize(width: number, height: number, resolution?: number): this\n {\n this.source.resize(width, height, resolution);\n\n return this;\n }\n}\n"],"names":["Texture","TextureSource"],"mappings":";;;;;;AAUO,MAAM,sBAAsBA,eACnC,CAAA;AAAA,EACI,OAAc,OAAO,OACrB,EAAA;AACI,IAAA,OAAO,IAAI,aAAc,CAAA;AAAA,MACrB,MAAA,EAAQ,IAAIC,2BAAA,CAAc,OAAO,CAAA;AAAA,KACpC,CAAA,CAAA;AAAA,GACL;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASO,MAAA,CAAO,KAAe,EAAA,MAAA,EAAgB,UAC7C,EAAA;AACI,IAAA,IAAA,CAAK,MAAO,CAAA,MAAA,CAAO,KAAO,EAAA,MAAA,EAAQ,UAAU,CAAA,CAAA;AAE5C,IAAO,OAAA,IAAA,CAAA;AAAA,GACX;AACJ;;;;"}

View File

@@ -0,0 +1,25 @@
import { TextureSource } from './sources/TextureSource.mjs';
import { Texture } from './Texture.mjs';
"use strict";
class RenderTexture extends Texture {
static create(options) {
return new RenderTexture({
source: new TextureSource(options)
});
}
/**
* Resizes the render texture.
* @param width - The new width of the render texture.
* @param height - The new height of the render texture.
* @param resolution - The new resolution of the render texture.
* @returns This texture.
*/
resize(width, height, resolution) {
this.source.resize(width, height, resolution);
return this;
}
}
export { RenderTexture };
//# sourceMappingURL=RenderTexture.mjs.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"RenderTexture.mjs","sources":["../../../../../src/rendering/renderers/shared/texture/RenderTexture.ts"],"sourcesContent":["import { TextureSource } from './sources/TextureSource';\nimport { Texture } from './Texture';\n\nimport type { TextureSourceOptions } from './sources/TextureSource';\n\n/**\n * A render texture, extends `Texture`.\n * @see {@link rendering.Texture}\n * @memberof rendering\n */\nexport class RenderTexture extends Texture\n{\n public static create(options: TextureSourceOptions): RenderTexture\n {\n return new RenderTexture({\n source: new TextureSource(options)\n });\n }\n\n /**\n * Resizes the render texture.\n * @param width - The new width of the render texture.\n * @param height - The new height of the render texture.\n * @param resolution - The new resolution of the render texture.\n * @returns This texture.\n */\n public resize(width: number, height: number, resolution?: number): this\n {\n this.source.resize(width, height, resolution);\n\n return this;\n }\n}\n"],"names":[],"mappings":";;;;AAUO,MAAM,sBAAsB,OACnC,CAAA;AAAA,EACI,OAAc,OAAO,OACrB,EAAA;AACI,IAAA,OAAO,IAAI,aAAc,CAAA;AAAA,MACrB,MAAA,EAAQ,IAAI,aAAA,CAAc,OAAO,CAAA;AAAA,KACpC,CAAA,CAAA;AAAA,GACL;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASO,MAAA,CAAO,KAAe,EAAA,MAAA,EAAgB,UAC7C,EAAA;AACI,IAAA,IAAA,CAAK,MAAO,CAAA,MAAA,CAAO,KAAO,EAAA,MAAA,EAAQ,UAAU,CAAA,CAAA;AAE5C,IAAO,OAAA,IAAA,CAAA;AAAA,GACX;AACJ;;;;"}

View File

@@ -0,0 +1,70 @@
import { ExtensionType } from '../../../../extensions/Extensions';
import type { Renderer } from '../../types';
import type { InstructionSet } from '../instructions/InstructionSet';
import type { Renderable } from '../Renderable';
import type { System } from '../system/System';
/**
* Options for the {@link RenderableGCSystem}.
* @memberof rendering
* @property {boolean} [renderableGCActive=true] - If set to true, this will enable the garbage collector on the renderables.
* @property {number} [renderableGCAMaxIdle=60000] -
* The maximum idle frames before a texture is destroyed by garbage collection.
* @property {number} [renderableGCCheckCountMax=60000] - time between two garbage collections.
*/
export interface RenderableGCSystemOptions {
/**
* If set to true, this will enable the garbage collector on the GPU.
* @default true
* @memberof rendering.SharedRendererOptions
*/
renderableGCActive: boolean;
/**
* The maximum idle frames before a texture is destroyed by garbage collection.
* @default 60 * 60
* @memberof rendering.SharedRendererOptions
*/
renderableGCMaxUnusedTime: number;
/**
* Frames between two garbage collections.
* @default 600
* @memberof rendering.SharedRendererOptions
*/
renderableGCFrequency: number;
}
/**
* System plugin to the renderer to manage renderable garbage collection. When rendering
* stuff with the renderer will assign resources to each renderable. This could be for example
* a batchable Sprite, or a text texture. If the renderable is not used for a certain amount of time
* its resources will be tided up by its render pipe.
* @memberof rendering
*/
export declare class RenderableGCSystem implements System<RenderableGCSystemOptions> {
/** @ignore */
static extension: {
readonly type: readonly [ExtensionType.WebGLSystem, ExtensionType.WebGPUSystem];
readonly name: "renderableGC";
};
/** default options for the renderableGCSystem */
static defaultOptions: RenderableGCSystemOptions;
/**
* Maximum idle frames before a texture is destroyed by garbage collection.
* @see renderableGCSystem.defaultMaxIdle
*/
maxUnusedTime: number;
private _renderer;
private readonly _managedRenderables;
private _handler;
private _frequency;
private _now;
/** @param renderer - The renderer this System works for. */
constructor(renderer: Renderer);
init(options: RenderableGCSystemOptions): void;
get enabled(): boolean;
set enabled(value: boolean);
prerender(): void;
addRenderable(renderable: Renderable, instructionSet: InstructionSet): void;
/** Runs the scheduled garbage collection */
run(): void;
destroy(): void;
private _removeRenderable;
}

View File

@@ -0,0 +1,116 @@
'use strict';
var Extensions = require('../../../../extensions/Extensions.js');
"use strict";
const _RenderableGCSystem = class _RenderableGCSystem {
/** @param renderer - The renderer this System works for. */
constructor(renderer) {
this._managedRenderables = [];
this._renderer = renderer;
}
init(options) {
options = { ..._RenderableGCSystem.defaultOptions, ...options };
this.maxUnusedTime = options.renderableGCMaxUnusedTime;
this._frequency = options.renderableGCFrequency;
this.enabled = options.renderableGCActive;
}
get enabled() {
return !!this._handler;
}
set enabled(value) {
if (this.enabled === value)
return;
if (value) {
this._handler = this._renderer.scheduler.repeat(
() => this.run(),
this._frequency
);
} else {
this._renderer.scheduler.cancel(this._handler);
}
}
prerender() {
this._now = performance.now();
}
addRenderable(renderable, instructionSet) {
if (!this.enabled)
return;
renderable._lastUsed = this._now;
if (renderable._lastInstructionTick === -1) {
this._managedRenderables.push(renderable);
renderable.once("destroyed", this._removeRenderable, this);
}
renderable._lastInstructionTick = instructionSet.tick;
}
/** Runs the scheduled garbage collection */
run() {
const now = performance.now();
const managedRenderables = this._managedRenderables;
const renderPipes = this._renderer.renderPipes;
let offset = 0;
for (let i = 0; i < managedRenderables.length; i++) {
const renderable = managedRenderables[i];
if (renderable === null) {
offset++;
continue;
}
const renderGroup = renderable.renderGroup ?? renderable.parentRenderGroup;
const currentIndex = renderGroup?.instructionSet?.tick ?? -1;
if (renderable._lastInstructionTick !== currentIndex && now - renderable._lastUsed > this.maxUnusedTime) {
if (!renderable.destroyed) {
const rp = renderPipes;
rp[renderable.renderPipeId].destroyRenderable(renderable);
}
renderable._lastInstructionTick = -1;
offset++;
renderable.off("destroyed", this._removeRenderable, this);
} else {
managedRenderables[i - offset] = renderable;
}
}
managedRenderables.length = managedRenderables.length - offset;
}
destroy() {
this.enabled = false;
this._renderer = null;
this._managedRenderables.length = 0;
}
_removeRenderable(renderable) {
const index = this._managedRenderables.indexOf(renderable);
if (index >= 0) {
renderable.off("destroyed", this._removeRenderable, this);
this._managedRenderables[index] = null;
}
}
};
/** @ignore */
_RenderableGCSystem.extension = {
type: [
Extensions.ExtensionType.WebGLSystem,
Extensions.ExtensionType.WebGPUSystem
],
name: "renderableGC"
};
/** default options for the renderableGCSystem */
_RenderableGCSystem.defaultOptions = {
/**
* If set to true, this will enable the garbage collector on the GPU.
* @default true
*/
renderableGCActive: true,
/**
* The maximum idle frames before a texture is destroyed by garbage collection.
* @default 60 * 60
*/
renderableGCMaxUnusedTime: 6e4,
/**
* Frames between two garbage collections.
* @default 600
*/
renderableGCFrequency: 3e4
};
let RenderableGCSystem = _RenderableGCSystem;
exports.RenderableGCSystem = RenderableGCSystem;
//# sourceMappingURL=RenderableGCSystem.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,114 @@
import { ExtensionType } from '../../../../extensions/Extensions.mjs';
"use strict";
const _RenderableGCSystem = class _RenderableGCSystem {
/** @param renderer - The renderer this System works for. */
constructor(renderer) {
this._managedRenderables = [];
this._renderer = renderer;
}
init(options) {
options = { ..._RenderableGCSystem.defaultOptions, ...options };
this.maxUnusedTime = options.renderableGCMaxUnusedTime;
this._frequency = options.renderableGCFrequency;
this.enabled = options.renderableGCActive;
}
get enabled() {
return !!this._handler;
}
set enabled(value) {
if (this.enabled === value)
return;
if (value) {
this._handler = this._renderer.scheduler.repeat(
() => this.run(),
this._frequency
);
} else {
this._renderer.scheduler.cancel(this._handler);
}
}
prerender() {
this._now = performance.now();
}
addRenderable(renderable, instructionSet) {
if (!this.enabled)
return;
renderable._lastUsed = this._now;
if (renderable._lastInstructionTick === -1) {
this._managedRenderables.push(renderable);
renderable.once("destroyed", this._removeRenderable, this);
}
renderable._lastInstructionTick = instructionSet.tick;
}
/** Runs the scheduled garbage collection */
run() {
const now = performance.now();
const managedRenderables = this._managedRenderables;
const renderPipes = this._renderer.renderPipes;
let offset = 0;
for (let i = 0; i < managedRenderables.length; i++) {
const renderable = managedRenderables[i];
if (renderable === null) {
offset++;
continue;
}
const renderGroup = renderable.renderGroup ?? renderable.parentRenderGroup;
const currentIndex = renderGroup?.instructionSet?.tick ?? -1;
if (renderable._lastInstructionTick !== currentIndex && now - renderable._lastUsed > this.maxUnusedTime) {
if (!renderable.destroyed) {
const rp = renderPipes;
rp[renderable.renderPipeId].destroyRenderable(renderable);
}
renderable._lastInstructionTick = -1;
offset++;
renderable.off("destroyed", this._removeRenderable, this);
} else {
managedRenderables[i - offset] = renderable;
}
}
managedRenderables.length = managedRenderables.length - offset;
}
destroy() {
this.enabled = false;
this._renderer = null;
this._managedRenderables.length = 0;
}
_removeRenderable(renderable) {
const index = this._managedRenderables.indexOf(renderable);
if (index >= 0) {
renderable.off("destroyed", this._removeRenderable, this);
this._managedRenderables[index] = null;
}
}
};
/** @ignore */
_RenderableGCSystem.extension = {
type: [
ExtensionType.WebGLSystem,
ExtensionType.WebGPUSystem
],
name: "renderableGC"
};
/** default options for the renderableGCSystem */
_RenderableGCSystem.defaultOptions = {
/**
* If set to true, this will enable the garbage collector on the GPU.
* @default true
*/
renderableGCActive: true,
/**
* The maximum idle frames before a texture is destroyed by garbage collection.
* @default 60 * 60
*/
renderableGCMaxUnusedTime: 6e4,
/**
* Frames between two garbage collections.
* @default 600
*/
renderableGCFrequency: 3e4
};
let RenderableGCSystem = _RenderableGCSystem;
export { RenderableGCSystem };
//# sourceMappingURL=RenderableGCSystem.mjs.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,215 @@
import EventEmitter from 'eventemitter3';
import { Rectangle } from '../../../../maths/shapes/Rectangle';
import { BufferImageSource } from './sources/BufferImageSource';
import { TextureSource } from './sources/TextureSource';
import { TextureMatrix } from './TextureMatrix';
import type { TextureResourceOrOptions } from './utils/textureFrom';
/**
* Stores the width of the non-scalable borders, for example when used with {@link scene.NineSlicePlane} texture.
* @memberof rendering
*/
export interface TextureBorders {
/** left border in pixels */
left: number;
/** top border in pixels */
top: number;
/** right border in pixels */
right: number;
/** bottom border in pixels */
bottom: number;
}
/**
* The UVs data structure for a texture.
* @memberof rendering
*/
export type UVs = {
x0: number;
y0: number;
x1: number;
y1: number;
x2: number;
y2: number;
x3: number;
y3: number;
};
/**
* The options that can be passed to a new Texture
* @memberof rendering
*/
export interface TextureOptions<TextureSourceType extends TextureSource = TextureSource> {
/** the underlying texture data that this texture will use */
source?: TextureSourceType;
/** optional label, for debugging */
label?: string;
/** The rectangle frame of the texture to show */
frame?: Rectangle;
/** The area of original texture */
orig?: Rectangle;
/** Trimmed rectangle of original texture */
trim?: Rectangle;
/** Default anchor point used for sprite placement / rotation */
defaultAnchor?: {
x: number;
y: number;
};
/** Default borders used for 9-slice scaling {@link NineSlicePlane}*/
defaultBorders?: TextureBorders;
/** indicates how the texture was rotated by texture packer. See {@link groupD8} */
rotate?: number;
/** set to true if you plan on modifying the uvs of this texture - can affect performance with high numbers of sprites*/
dynamic?: boolean;
}
export interface BindableTexture {
source: TextureSource;
}
export type TextureSourceLike = TextureSource | TextureResourceOrOptions | string;
/**
* A texture stores the information that represents an image or part of an image.
*
* A texture must have a loaded resource passed to it to work. It does not contain any
* loading mechanisms.
*
* The Assets class can be used to load an texture from a file. This is the recommended
* way as it will handle the loading and caching for you.
*
* ```js
*
* const texture = await Assets.load('assets/image.png');
*
* // once Assets has loaded the image it will be available via the from method
* const sameTexture = Texture.from('assets/image.png');
* // another way to access the texture once loaded
* const sameAgainTexture = Asset.get('assets/image.png');
*
* const sprite1 = new Sprite(texture);
*
* ```
*
* It cannot be added to the display list directly; instead use it as the texture for a Sprite.
* If no frame is provided for a texture, then the whole image is used.
*
* You can directly create a texture from an image and then reuse it multiple times like this :
*
* ```js
* import { Sprite, Texture } from 'pixi.js';
*
* const texture = await Assets.load('assets/image.png');
* const sprite1 = new Sprite(texture);
* const sprite2 = new Sprite(texture);
* ```
*
* If you didn't pass the texture frame to constructor, it enables `noFrame` mode:
* it subscribes on baseTexture events, it automatically resizes at the same time as baseTexture.
* @memberof rendering
* @class
*/
export declare class Texture<TextureSourceType extends TextureSource = TextureSource> extends EventEmitter<{
update: Texture;
destroy: Texture;
}> implements BindableTexture {
/**
* Helper function that creates a returns Texture based on the source you provide.
* The source should be loaded and ready to go. If not its best to grab the asset using Assets.
* @param id - String or Source to create texture from
* @param skipCache - Skip adding the texture to the cache
* @returns The texture based on the Id provided
*/
static from: (id: TextureSourceLike, skipCache?: boolean) => Texture;
/** label used for debugging */
label?: string;
/** unique id for this texture */
readonly uid: number;
/**
* Has the texture been destroyed?
* @readonly
*/
destroyed: boolean;
_source: TextureSourceType;
/**
* Indicates whether the texture is rotated inside the atlas
* set to 2 to compensate for texture packer rotation
* set to 6 to compensate for spine packer rotation
* can be used to rotate or mirror sprites
* See {@link maths.groupD8} for explanation
*/
readonly rotate: number;
/** A uvs object based on the given frame and the texture source */
readonly uvs: UVs;
/**
* Anchor point that is used as default if sprite is created with this texture.
* Changing the `defaultAnchor` at a later point of time will not update Sprite's anchor point.
* @default {0,0}
*/
readonly defaultAnchor?: {
x: number;
y: number;
};
/**
* Default width of the non-scalable border that is used if 9-slice plane is created with this texture.
* @since 7.2.0
* @see scene.NineSliceSprite
*/
readonly defaultBorders?: TextureBorders;
/**
* This is the area of the BaseTexture image to actually copy to the Canvas / WebGL when rendering,
* irrespective of the actual frame size or placement (which can be influenced by trimmed texture atlases)
*/
readonly frame: Rectangle;
/** This is the area of original texture, before it was put in atlas. */
readonly orig: Rectangle;
/**
* This is the trimmed area of original texture, before it was put in atlas
* Please call `updateUvs()` after you change coordinates of `trim` manually.
*/
readonly trim: Rectangle;
/**
* Does this Texture have any frame data assigned to it?
*
* This mode is enabled automatically if no frame was passed inside constructor.
*
* In this mode texture is subscribed to baseTexture events, and fires `update` on any change.
*
* Beware, after loading or resize of baseTexture event can fired two times!
* If you want more control, subscribe on baseTexture itself.
* @example
* texture.on('update', () => {});
*/
noFrame: boolean;
/**
* Set to true if you plan on modifying the uvs of this texture.
* When this is the case, sprites and other objects using the texture will
* make sure to listen for changes to the uvs and update their vertices accordingly.
*/
dynamic: boolean;
private _textureMatrix;
/** is it a texture? yes! used for type checking */
readonly isTexture = true;
/**
* @param {rendering.TextureOptions} options - Options for the texture
*/
constructor({ source, label, frame, orig, trim, defaultAnchor, defaultBorders, rotate, dynamic }?: TextureOptions<TextureSourceType>);
set source(value: TextureSourceType);
/** the underlying source of the texture (equivalent of baseTexture in v7) */
get source(): TextureSourceType;
/** returns a TextureMatrix instance for this texture. By default, that object is not created because its heavy. */
get textureMatrix(): TextureMatrix;
/** The width of the Texture in pixels. */
get width(): number;
/** The height of the Texture in pixels. */
get height(): number;
/** Call this function when you have modified the frame of this texture. */
updateUvs(): void;
/**
* Destroys this texture
* @param destroySource - Destroy the source when the texture is destroyed.
*/
destroy(destroySource?: boolean): void;
/** call this if you have modified the `texture outside` of the constructor */
update(): void;
/** @deprecated since 8.0.0 */
get baseTexture(): TextureSource;
/** an Empty Texture used internally by the engine */
static EMPTY: Texture;
/** a White texture used internally by the engine */
static WHITE: Texture<BufferImageSource>;
}

View File

@@ -0,0 +1,194 @@
'use strict';
var EventEmitter = require('eventemitter3');
var groupD8 = require('../../../../maths/matrix/groupD8.js');
var Rectangle = require('../../../../maths/shapes/Rectangle.js');
var uid = require('../../../../utils/data/uid.js');
var deprecation = require('../../../../utils/logging/deprecation.js');
var NOOP = require('../../../../utils/misc/NOOP.js');
var BufferImageSource = require('./sources/BufferImageSource.js');
var TextureSource = require('./sources/TextureSource.js');
var TextureMatrix = require('./TextureMatrix.js');
"use strict";
class Texture extends EventEmitter {
/**
* @param {rendering.TextureOptions} options - Options for the texture
*/
constructor({
source,
label,
frame,
orig,
trim,
defaultAnchor,
defaultBorders,
rotate,
dynamic
} = {}) {
super();
/** unique id for this texture */
this.uid = uid.uid("texture");
/** A uvs object based on the given frame and the texture source */
this.uvs = { x0: 0, y0: 0, x1: 0, y1: 0, x2: 0, y2: 0, x3: 0, y3: 0 };
/**
* This is the area of the BaseTexture image to actually copy to the Canvas / WebGL when rendering,
* irrespective of the actual frame size or placement (which can be influenced by trimmed texture atlases)
*/
this.frame = new Rectangle.Rectangle();
/**
* Does this Texture have any frame data assigned to it?
*
* This mode is enabled automatically if no frame was passed inside constructor.
*
* In this mode texture is subscribed to baseTexture events, and fires `update` on any change.
*
* Beware, after loading or resize of baseTexture event can fired two times!
* If you want more control, subscribe on baseTexture itself.
* @example
* texture.on('update', () => {});
*/
this.noFrame = false;
/**
* Set to true if you plan on modifying the uvs of this texture.
* When this is the case, sprites and other objects using the texture will
* make sure to listen for changes to the uvs and update their vertices accordingly.
*/
this.dynamic = false;
/** is it a texture? yes! used for type checking */
this.isTexture = true;
this.label = label;
this.source = source?.source ?? new TextureSource.TextureSource();
this.noFrame = !frame;
if (frame) {
this.frame.copyFrom(frame);
} else {
const { width, height } = this._source;
this.frame.width = width;
this.frame.height = height;
}
this.orig = orig || this.frame;
this.trim = trim;
this.rotate = rotate ?? 0;
this.defaultAnchor = defaultAnchor;
this.defaultBorders = defaultBorders;
this.destroyed = false;
this.dynamic = dynamic || false;
this.updateUvs();
}
set source(value) {
if (this._source) {
this._source.off("resize", this.update, this);
}
this._source = value;
value.on("resize", this.update, this);
this.emit("update", this);
}
/** the underlying source of the texture (equivalent of baseTexture in v7) */
get source() {
return this._source;
}
/** returns a TextureMatrix instance for this texture. By default, that object is not created because its heavy. */
get textureMatrix() {
if (!this._textureMatrix) {
this._textureMatrix = new TextureMatrix.TextureMatrix(this);
}
return this._textureMatrix;
}
/** The width of the Texture in pixels. */
get width() {
return this.orig.width;
}
/** The height of the Texture in pixels. */
get height() {
return this.orig.height;
}
/** Call this function when you have modified the frame of this texture. */
updateUvs() {
const { uvs, frame } = this;
const { width, height } = this._source;
const nX = frame.x / width;
const nY = frame.y / height;
const nW = frame.width / width;
const nH = frame.height / height;
let rotate = this.rotate;
if (rotate) {
const w2 = nW / 2;
const h2 = nH / 2;
const cX = nX + w2;
const cY = nY + h2;
rotate = groupD8.groupD8.add(rotate, groupD8.groupD8.NW);
uvs.x0 = cX + w2 * groupD8.groupD8.uX(rotate);
uvs.y0 = cY + h2 * groupD8.groupD8.uY(rotate);
rotate = groupD8.groupD8.add(rotate, 2);
uvs.x1 = cX + w2 * groupD8.groupD8.uX(rotate);
uvs.y1 = cY + h2 * groupD8.groupD8.uY(rotate);
rotate = groupD8.groupD8.add(rotate, 2);
uvs.x2 = cX + w2 * groupD8.groupD8.uX(rotate);
uvs.y2 = cY + h2 * groupD8.groupD8.uY(rotate);
rotate = groupD8.groupD8.add(rotate, 2);
uvs.x3 = cX + w2 * groupD8.groupD8.uX(rotate);
uvs.y3 = cY + h2 * groupD8.groupD8.uY(rotate);
} else {
uvs.x0 = nX;
uvs.y0 = nY;
uvs.x1 = nX + nW;
uvs.y1 = nY;
uvs.x2 = nX + nW;
uvs.y2 = nY + nH;
uvs.x3 = nX;
uvs.y3 = nY + nH;
}
}
/**
* Destroys this texture
* @param destroySource - Destroy the source when the texture is destroyed.
*/
destroy(destroySource = false) {
if (this._source) {
if (destroySource) {
this._source.destroy();
this._source = null;
}
}
this._textureMatrix = null;
this.destroyed = true;
this.emit("destroy", this);
this.removeAllListeners();
}
/** call this if you have modified the `texture outside` of the constructor */
update() {
if (this.noFrame) {
this.frame.width = this._source.width;
this.frame.height = this._source.height;
}
this.updateUvs();
this.emit("update", this);
}
/** @deprecated since 8.0.0 */
get baseTexture() {
deprecation.deprecation(deprecation.v8_0_0, "Texture.baseTexture is now Texture.source");
return this._source;
}
}
Texture.EMPTY = new Texture({
label: "EMPTY",
source: new TextureSource.TextureSource({
label: "EMPTY"
})
});
Texture.EMPTY.destroy = NOOP.NOOP;
Texture.WHITE = new Texture({
source: new BufferImageSource.BufferImageSource({
resource: new Uint8Array([255, 255, 255, 255]),
width: 1,
height: 1,
alphaMode: "premultiply-alpha-on-upload",
label: "WHITE"
}),
label: "WHITE"
});
Texture.WHITE.destroy = NOOP.NOOP;
exports.Texture = Texture;
//# sourceMappingURL=Texture.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,192 @@
import EventEmitter from 'eventemitter3';
import { groupD8 } from '../../../../maths/matrix/groupD8.mjs';
import { Rectangle } from '../../../../maths/shapes/Rectangle.mjs';
import { uid } from '../../../../utils/data/uid.mjs';
import { deprecation, v8_0_0 } from '../../../../utils/logging/deprecation.mjs';
import { NOOP } from '../../../../utils/misc/NOOP.mjs';
import { BufferImageSource } from './sources/BufferImageSource.mjs';
import { TextureSource } from './sources/TextureSource.mjs';
import { TextureMatrix } from './TextureMatrix.mjs';
"use strict";
class Texture extends EventEmitter {
/**
* @param {rendering.TextureOptions} options - Options for the texture
*/
constructor({
source,
label,
frame,
orig,
trim,
defaultAnchor,
defaultBorders,
rotate,
dynamic
} = {}) {
super();
/** unique id for this texture */
this.uid = uid("texture");
/** A uvs object based on the given frame and the texture source */
this.uvs = { x0: 0, y0: 0, x1: 0, y1: 0, x2: 0, y2: 0, x3: 0, y3: 0 };
/**
* This is the area of the BaseTexture image to actually copy to the Canvas / WebGL when rendering,
* irrespective of the actual frame size or placement (which can be influenced by trimmed texture atlases)
*/
this.frame = new Rectangle();
/**
* Does this Texture have any frame data assigned to it?
*
* This mode is enabled automatically if no frame was passed inside constructor.
*
* In this mode texture is subscribed to baseTexture events, and fires `update` on any change.
*
* Beware, after loading or resize of baseTexture event can fired two times!
* If you want more control, subscribe on baseTexture itself.
* @example
* texture.on('update', () => {});
*/
this.noFrame = false;
/**
* Set to true if you plan on modifying the uvs of this texture.
* When this is the case, sprites and other objects using the texture will
* make sure to listen for changes to the uvs and update their vertices accordingly.
*/
this.dynamic = false;
/** is it a texture? yes! used for type checking */
this.isTexture = true;
this.label = label;
this.source = source?.source ?? new TextureSource();
this.noFrame = !frame;
if (frame) {
this.frame.copyFrom(frame);
} else {
const { width, height } = this._source;
this.frame.width = width;
this.frame.height = height;
}
this.orig = orig || this.frame;
this.trim = trim;
this.rotate = rotate ?? 0;
this.defaultAnchor = defaultAnchor;
this.defaultBorders = defaultBorders;
this.destroyed = false;
this.dynamic = dynamic || false;
this.updateUvs();
}
set source(value) {
if (this._source) {
this._source.off("resize", this.update, this);
}
this._source = value;
value.on("resize", this.update, this);
this.emit("update", this);
}
/** the underlying source of the texture (equivalent of baseTexture in v7) */
get source() {
return this._source;
}
/** returns a TextureMatrix instance for this texture. By default, that object is not created because its heavy. */
get textureMatrix() {
if (!this._textureMatrix) {
this._textureMatrix = new TextureMatrix(this);
}
return this._textureMatrix;
}
/** The width of the Texture in pixels. */
get width() {
return this.orig.width;
}
/** The height of the Texture in pixels. */
get height() {
return this.orig.height;
}
/** Call this function when you have modified the frame of this texture. */
updateUvs() {
const { uvs, frame } = this;
const { width, height } = this._source;
const nX = frame.x / width;
const nY = frame.y / height;
const nW = frame.width / width;
const nH = frame.height / height;
let rotate = this.rotate;
if (rotate) {
const w2 = nW / 2;
const h2 = nH / 2;
const cX = nX + w2;
const cY = nY + h2;
rotate = groupD8.add(rotate, groupD8.NW);
uvs.x0 = cX + w2 * groupD8.uX(rotate);
uvs.y0 = cY + h2 * groupD8.uY(rotate);
rotate = groupD8.add(rotate, 2);
uvs.x1 = cX + w2 * groupD8.uX(rotate);
uvs.y1 = cY + h2 * groupD8.uY(rotate);
rotate = groupD8.add(rotate, 2);
uvs.x2 = cX + w2 * groupD8.uX(rotate);
uvs.y2 = cY + h2 * groupD8.uY(rotate);
rotate = groupD8.add(rotate, 2);
uvs.x3 = cX + w2 * groupD8.uX(rotate);
uvs.y3 = cY + h2 * groupD8.uY(rotate);
} else {
uvs.x0 = nX;
uvs.y0 = nY;
uvs.x1 = nX + nW;
uvs.y1 = nY;
uvs.x2 = nX + nW;
uvs.y2 = nY + nH;
uvs.x3 = nX;
uvs.y3 = nY + nH;
}
}
/**
* Destroys this texture
* @param destroySource - Destroy the source when the texture is destroyed.
*/
destroy(destroySource = false) {
if (this._source) {
if (destroySource) {
this._source.destroy();
this._source = null;
}
}
this._textureMatrix = null;
this.destroyed = true;
this.emit("destroy", this);
this.removeAllListeners();
}
/** call this if you have modified the `texture outside` of the constructor */
update() {
if (this.noFrame) {
this.frame.width = this._source.width;
this.frame.height = this._source.height;
}
this.updateUvs();
this.emit("update", this);
}
/** @deprecated since 8.0.0 */
get baseTexture() {
deprecation(v8_0_0, "Texture.baseTexture is now Texture.source");
return this._source;
}
}
Texture.EMPTY = new Texture({
label: "EMPTY",
source: new TextureSource({
label: "EMPTY"
})
});
Texture.EMPTY.destroy = NOOP;
Texture.WHITE = new Texture({
source: new BufferImageSource({
resource: new Uint8Array([255, 255, 255, 255]),
width: 1,
height: 1,
alphaMode: "premultiply-alpha-on-upload",
label: "WHITE"
}),
label: "WHITE"
});
Texture.WHITE.destroy = NOOP;
export { Texture };
//# sourceMappingURL=Texture.mjs.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,91 @@
import { ExtensionType } from '../../../../extensions/Extensions';
import type { Renderer } from '../../types';
import type { System } from '../system/System';
/**
* Options for the {@link TextureGCSystem}.
* @memberof rendering
* @property {boolean} [textureGCActive=true] - If set to true, this will enable the garbage collector on the GPU.
* @property {number} [textureGCAMaxIdle=60 * 60] -
* The maximum idle frames before a texture is destroyed by garbage collection.
* @property {number} [textureGCCheckCountMax=600] - Frames between two garbage collections.
*/
export interface TextureGCSystemOptions {
/**
* If set to true, this will enable the garbage collector on the GPU.
* @default true
* @memberof rendering.SharedRendererOptions
*/
textureGCActive: boolean;
/**
* @deprecated since 8.3.0
* @see {@link TextureGCSystem.textureGCMaxIdle}
* @memberof rendering.SharedRendererOptions
*/
textureGCAMaxIdle: number;
/**
* The maximum idle frames before a texture is destroyed by garbage collection.
* @default 60 * 60
* @memberof rendering.SharedRendererOptions
*/
textureGCMaxIdle: number;
/**
* Frames between two garbage collections.
* @default 600
* @memberof rendering.SharedRendererOptions
*/
textureGCCheckCountMax: number;
}
/**
* System plugin to the renderer to manage texture garbage collection on the GPU,
* ensuring that it does not get clogged up with textures that are no longer being used.
* @memberof rendering
*/
export declare class TextureGCSystem implements System<TextureGCSystemOptions> {
/** @ignore */
static extension: {
readonly type: readonly [ExtensionType.WebGLSystem, ExtensionType.WebGPUSystem];
readonly name: "textureGC";
};
/** default options for the TextureGCSystem */
static defaultOptions: TextureGCSystemOptions;
/**
* Frame count since started.
* @readonly
*/
count: number;
/**
* Frame count since last garbage collection.
* @readonly
*/
checkCount: number;
/**
* Maximum idle frames before a texture is destroyed by garbage collection.
* @see TextureGCSystem.defaultMaxIdle
*/
maxIdle: number;
/**
* Frames between two garbage collections.
* @see TextureGCSystem.defaultCheckCountMax
*/
checkCountMax: number;
/**
* Current garbage collection mode.
* @see TextureGCSystem.defaultMode
*/
active: boolean;
private _renderer;
/** @param renderer - The renderer this System works for. */
constructor(renderer: Renderer);
init(options: TextureGCSystemOptions): void;
/**
* Checks to see when the last time a texture was used.
* If the texture has not been used for a specified amount of time, it will be removed from the GPU.
*/
protected postrender(): void;
/**
* Checks to see when the last time a texture was used.
* If the texture has not been used for a specified amount of time, it will be removed from the GPU.
*/
run(): void;
destroy(): void;
}

View File

@@ -0,0 +1,88 @@
'use strict';
var Extensions = require('../../../../extensions/Extensions.js');
"use strict";
const _TextureGCSystem = class _TextureGCSystem {
/** @param renderer - The renderer this System works for. */
constructor(renderer) {
this._renderer = renderer;
this.count = 0;
this.checkCount = 0;
}
init(options) {
options = { ..._TextureGCSystem.defaultOptions, ...options };
this.checkCountMax = options.textureGCCheckCountMax;
this.maxIdle = options.textureGCAMaxIdle ?? options.textureGCMaxIdle;
this.active = options.textureGCActive;
}
/**
* Checks to see when the last time a texture was used.
* If the texture has not been used for a specified amount of time, it will be removed from the GPU.
*/
postrender() {
if (!this._renderer.renderingToScreen) {
return;
}
this.count++;
if (!this.active)
return;
this.checkCount++;
if (this.checkCount > this.checkCountMax) {
this.checkCount = 0;
this.run();
}
}
/**
* Checks to see when the last time a texture was used.
* If the texture has not been used for a specified amount of time, it will be removed from the GPU.
*/
run() {
const managedTextures = this._renderer.texture.managedTextures;
for (let i = 0; i < managedTextures.length; i++) {
const texture = managedTextures[i];
if (texture.autoGarbageCollect && texture.resource && texture._touched > -1 && this.count - texture._touched > this.maxIdle) {
texture._touched = -1;
texture.unload();
}
}
}
destroy() {
this._renderer = null;
}
};
/** @ignore */
_TextureGCSystem.extension = {
type: [
Extensions.ExtensionType.WebGLSystem,
Extensions.ExtensionType.WebGPUSystem
],
name: "textureGC"
};
/** default options for the TextureGCSystem */
_TextureGCSystem.defaultOptions = {
/**
* If set to true, this will enable the garbage collector on the GPU.
* @default true
*/
textureGCActive: true,
/**
* @deprecated since 8.3.0
* @see {@link TextureGCSystem.textureGCMaxIdle}
*/
textureGCAMaxIdle: null,
/**
* The maximum idle frames before a texture is destroyed by garbage collection.
* @default 60 * 60
*/
textureGCMaxIdle: 60 * 60,
/**
* Frames between two garbage collections.
* @default 600
*/
textureGCCheckCountMax: 600
};
let TextureGCSystem = _TextureGCSystem;
exports.TextureGCSystem = TextureGCSystem;
//# sourceMappingURL=TextureGCSystem.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,86 @@
import { ExtensionType } from '../../../../extensions/Extensions.mjs';
"use strict";
const _TextureGCSystem = class _TextureGCSystem {
/** @param renderer - The renderer this System works for. */
constructor(renderer) {
this._renderer = renderer;
this.count = 0;
this.checkCount = 0;
}
init(options) {
options = { ..._TextureGCSystem.defaultOptions, ...options };
this.checkCountMax = options.textureGCCheckCountMax;
this.maxIdle = options.textureGCAMaxIdle ?? options.textureGCMaxIdle;
this.active = options.textureGCActive;
}
/**
* Checks to see when the last time a texture was used.
* If the texture has not been used for a specified amount of time, it will be removed from the GPU.
*/
postrender() {
if (!this._renderer.renderingToScreen) {
return;
}
this.count++;
if (!this.active)
return;
this.checkCount++;
if (this.checkCount > this.checkCountMax) {
this.checkCount = 0;
this.run();
}
}
/**
* Checks to see when the last time a texture was used.
* If the texture has not been used for a specified amount of time, it will be removed from the GPU.
*/
run() {
const managedTextures = this._renderer.texture.managedTextures;
for (let i = 0; i < managedTextures.length; i++) {
const texture = managedTextures[i];
if (texture.autoGarbageCollect && texture.resource && texture._touched > -1 && this.count - texture._touched > this.maxIdle) {
texture._touched = -1;
texture.unload();
}
}
}
destroy() {
this._renderer = null;
}
};
/** @ignore */
_TextureGCSystem.extension = {
type: [
ExtensionType.WebGLSystem,
ExtensionType.WebGPUSystem
],
name: "textureGC"
};
/** default options for the TextureGCSystem */
_TextureGCSystem.defaultOptions = {
/**
* If set to true, this will enable the garbage collector on the GPU.
* @default true
*/
textureGCActive: true,
/**
* @deprecated since 8.3.0
* @see {@link TextureGCSystem.textureGCMaxIdle}
*/
textureGCAMaxIdle: null,
/**
* The maximum idle frames before a texture is destroyed by garbage collection.
* @default 60 * 60
*/
textureGCMaxIdle: 60 * 60,
/**
* Frames between two garbage collections.
* @default 600
*/
textureGCCheckCountMax: 600
};
let TextureGCSystem = _TextureGCSystem;
export { TextureGCSystem };
//# sourceMappingURL=TextureGCSystem.mjs.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,82 @@
import { Matrix } from '../../../../maths/matrix/Matrix';
import type { Texture } from './Texture';
/**
* Class controls uv mapping from Texture normal space to BaseTexture normal space.
*
* Takes `trim` and `rotate` into account. May contain clamp settings for Meshes and TilingSprite.
*
* Can be used in Texture `uvMatrix` field, or separately, you can use different clamp settings on the same texture.
* If you want to add support for texture region of certain feature or filter, that's what you're looking for.
*
* Takes track of Texture changes through `_lastTextureID` private field.
* Use `update()` method call to track it from outside.
* @see Texture
* @see Mesh
* @see TilingSprite
* @memberof rendering
*/
export declare class TextureMatrix {
/**
* Matrix operation that converts texture region coords to texture coords
* @readonly
*/
mapCoord: Matrix;
/**
* Changes frame clamping
* Works with TilingSprite and Mesh
* Change to 1.5 if you texture has repeated right and bottom lines, that leads to smoother borders
* @default 0
*/
clampOffset: number;
/**
* Changes frame clamping
* Works with TilingSprite and Mesh
* Change to -0.5 to add a pixel to the edge, recommended for transparent trimmed textures in atlas
* @default 0.5
*/
clampMargin: number;
/**
* Clamp region for normalized coords, left-top pixel center in xy , bottom-right in zw.
* Calculated based on clampOffset.
*/
readonly uClampFrame: Float32Array;
/** Normalized clamp offset. Calculated based on clampOffset. */
readonly uClampOffset: Float32Array;
/**
* Tracks Texture frame changes.
* @ignore
*/
_updateID: number;
/**
* Tracks Texture frame changes.
* @protected
*/
protected _textureID: number;
protected _texture: Texture;
/**
* If texture size is the same as baseTexture.
* @default false
* @readonly
*/
isSimple: boolean;
/**
* @param texture - observed texture
* @param clampMargin - Changes frame clamping, 0.5 by default. Use -0.5 for extra border.
*/
constructor(texture: Texture, clampMargin?: number);
/** Texture property. */
get texture(): Texture;
set texture(value: Texture);
/**
* Multiplies uvs array to transform
* @param uvs - mesh uvs
* @param [out=uvs] - output
* @returns - output
*/
multiplyUvs(uvs: Float32Array, out?: Float32Array): Float32Array;
/**
* Updates matrices if texture was changed
* @returns - whether or not it was updated
*/
update(): boolean;
}

View File

@@ -0,0 +1,96 @@
'use strict';
var Matrix = require('../../../../maths/matrix/Matrix.js');
"use strict";
const tempMat = new Matrix.Matrix();
class TextureMatrix {
/**
* @param texture - observed texture
* @param clampMargin - Changes frame clamping, 0.5 by default. Use -0.5 for extra border.
*/
constructor(texture, clampMargin) {
this.mapCoord = new Matrix.Matrix();
this.uClampFrame = new Float32Array(4);
this.uClampOffset = new Float32Array(2);
this._textureID = -1;
this._updateID = 0;
this.clampOffset = 0;
if (typeof clampMargin === "undefined") {
this.clampMargin = texture.width < 10 ? 0 : 0.5;
} else {
this.clampMargin = clampMargin;
}
this.isSimple = false;
this.texture = texture;
}
/** Texture property. */
get texture() {
return this._texture;
}
set texture(value) {
if (this.texture === value)
return;
this._texture?.removeListener("update", this.update, this);
this._texture = value;
this._texture.addListener("update", this.update, this);
this.update();
}
/**
* Multiplies uvs array to transform
* @param uvs - mesh uvs
* @param [out=uvs] - output
* @returns - output
*/
multiplyUvs(uvs, out) {
if (out === void 0) {
out = uvs;
}
const mat = this.mapCoord;
for (let i = 0; i < uvs.length; i += 2) {
const x = uvs[i];
const y = uvs[i + 1];
out[i] = x * mat.a + y * mat.c + mat.tx;
out[i + 1] = x * mat.b + y * mat.d + mat.ty;
}
return out;
}
/**
* Updates matrices if texture was changed
* @returns - whether or not it was updated
*/
update() {
const tex = this._texture;
this._updateID++;
const uvs = tex.uvs;
this.mapCoord.set(uvs.x1 - uvs.x0, uvs.y1 - uvs.y0, uvs.x3 - uvs.x0, uvs.y3 - uvs.y0, uvs.x0, uvs.y0);
const orig = tex.orig;
const trim = tex.trim;
if (trim) {
tempMat.set(
orig.width / trim.width,
0,
0,
orig.height / trim.height,
-trim.x / trim.width,
-trim.y / trim.height
);
this.mapCoord.append(tempMat);
}
const texBase = tex.source;
const frame = this.uClampFrame;
const margin = this.clampMargin / texBase._resolution;
const offset = this.clampOffset / texBase._resolution;
frame[0] = (tex.frame.x + margin + offset) / texBase.width;
frame[1] = (tex.frame.y + margin + offset) / texBase.height;
frame[2] = (tex.frame.x + tex.frame.width - margin + offset) / texBase.width;
frame[3] = (tex.frame.y + tex.frame.height - margin + offset) / texBase.height;
this.uClampOffset[0] = this.clampOffset / texBase.pixelWidth;
this.uClampOffset[1] = this.clampOffset / texBase.pixelHeight;
this.isSimple = tex.frame.width === texBase.width && tex.frame.height === texBase.height && tex.rotate === 0;
return true;
}
}
exports.TextureMatrix = TextureMatrix;
//# sourceMappingURL=TextureMatrix.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,94 @@
import { Matrix } from '../../../../maths/matrix/Matrix.mjs';
"use strict";
const tempMat = new Matrix();
class TextureMatrix {
/**
* @param texture - observed texture
* @param clampMargin - Changes frame clamping, 0.5 by default. Use -0.5 for extra border.
*/
constructor(texture, clampMargin) {
this.mapCoord = new Matrix();
this.uClampFrame = new Float32Array(4);
this.uClampOffset = new Float32Array(2);
this._textureID = -1;
this._updateID = 0;
this.clampOffset = 0;
if (typeof clampMargin === "undefined") {
this.clampMargin = texture.width < 10 ? 0 : 0.5;
} else {
this.clampMargin = clampMargin;
}
this.isSimple = false;
this.texture = texture;
}
/** Texture property. */
get texture() {
return this._texture;
}
set texture(value) {
if (this.texture === value)
return;
this._texture?.removeListener("update", this.update, this);
this._texture = value;
this._texture.addListener("update", this.update, this);
this.update();
}
/**
* Multiplies uvs array to transform
* @param uvs - mesh uvs
* @param [out=uvs] - output
* @returns - output
*/
multiplyUvs(uvs, out) {
if (out === void 0) {
out = uvs;
}
const mat = this.mapCoord;
for (let i = 0; i < uvs.length; i += 2) {
const x = uvs[i];
const y = uvs[i + 1];
out[i] = x * mat.a + y * mat.c + mat.tx;
out[i + 1] = x * mat.b + y * mat.d + mat.ty;
}
return out;
}
/**
* Updates matrices if texture was changed
* @returns - whether or not it was updated
*/
update() {
const tex = this._texture;
this._updateID++;
const uvs = tex.uvs;
this.mapCoord.set(uvs.x1 - uvs.x0, uvs.y1 - uvs.y0, uvs.x3 - uvs.x0, uvs.y3 - uvs.y0, uvs.x0, uvs.y0);
const orig = tex.orig;
const trim = tex.trim;
if (trim) {
tempMat.set(
orig.width / trim.width,
0,
0,
orig.height / trim.height,
-trim.x / trim.width,
-trim.y / trim.height
);
this.mapCoord.append(tempMat);
}
const texBase = tex.source;
const frame = this.uClampFrame;
const margin = this.clampMargin / texBase._resolution;
const offset = this.clampOffset / texBase._resolution;
frame[0] = (tex.frame.x + margin + offset) / texBase.width;
frame[1] = (tex.frame.y + margin + offset) / texBase.height;
frame[2] = (tex.frame.x + tex.frame.width - margin + offset) / texBase.width;
frame[3] = (tex.frame.y + tex.frame.height - margin + offset) / texBase.height;
this.uClampOffset[0] = this.clampOffset / texBase.pixelWidth;
this.uClampOffset[1] = this.clampOffset / texBase.pixelHeight;
this.isSimple = tex.frame.width === texBase.width && tex.frame.height === texBase.height && tex.rotate === 0;
return true;
}
}
export { TextureMatrix };
//# sourceMappingURL=TextureMatrix.mjs.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,65 @@
import { TextureSource } from './sources/TextureSource';
import { Texture } from './Texture';
import type { TextureSourceOptions } from './sources/TextureSource';
/**
* Texture pool, used by FilterSystem and plugins.
*
* Stores collection of temporary pow2 or screen-sized renderTextures
*
* If you use custom RenderTexturePool for your filters, you can use methods
* `getFilterTexture` and `returnFilterTexture` same as in default pool
* @memberof rendering
* @name TexturePool
*/
export declare class TexturePoolClass {
/** The default options for texture pool */
textureOptions: TextureSourceOptions;
/**
* Allow renderTextures of the same size as screen, not just pow2
*
* Automatically sets to true after `setScreenSize`
* @default false
*/
enableFullScreen: boolean;
private _texturePool;
private _poolKeyHash;
/**
* @param textureOptions - options that will be passed to BaseRenderTexture constructor
* @param {SCALE_MODE} [textureOptions.scaleMode] - See {@link SCALE_MODE} for possible values.
*/
constructor(textureOptions?: TextureSourceOptions);
/**
* Creates texture with params that were specified in pool constructor.
* @param pixelWidth - Width of texture in pixels.
* @param pixelHeight - Height of texture in pixels.
* @param antialias
*/
createTexture(pixelWidth: number, pixelHeight: number, antialias: boolean): Texture;
/**
* Gets a Power-of-Two render texture or fullScreen texture
* @param frameWidth - The minimum width of the render texture.
* @param frameHeight - The minimum height of the render texture.
* @param resolution - The resolution of the render texture.
* @param antialias
* @returns The new render texture.
*/
getOptimalTexture(frameWidth: number, frameHeight: number, resolution: number, antialias: boolean): Texture;
/**
* Gets extra texture of the same size as input renderTexture
* @param texture - The texture to check what size it is.
* @param antialias - Whether to use antialias.
* @returns A texture that is a power of two
*/
getSameSizeTexture(texture: Texture, antialias?: boolean): Texture<TextureSource<any>>;
/**
* Place a render texture back into the pool.
* @param renderTexture - The renderTexture to free
*/
returnTexture(renderTexture: Texture): void;
/**
* Clears the pool.
* @param destroyTextures - Destroy all stored textures.
*/
clear(destroyTextures?: boolean): void;
}
export declare const TexturePool: TexturePoolClass;

View File

@@ -0,0 +1,115 @@
'use strict';
var pow2 = require('../../../../maths/misc/pow2.js');
var TextureSource = require('./sources/TextureSource.js');
var Texture = require('./Texture.js');
"use strict";
let count = 0;
class TexturePoolClass {
/**
* @param textureOptions - options that will be passed to BaseRenderTexture constructor
* @param {SCALE_MODE} [textureOptions.scaleMode] - See {@link SCALE_MODE} for possible values.
*/
constructor(textureOptions) {
this._poolKeyHash = /* @__PURE__ */ Object.create(null);
this._texturePool = {};
this.textureOptions = textureOptions || {};
this.enableFullScreen = false;
}
/**
* Creates texture with params that were specified in pool constructor.
* @param pixelWidth - Width of texture in pixels.
* @param pixelHeight - Height of texture in pixels.
* @param antialias
*/
createTexture(pixelWidth, pixelHeight, antialias) {
const textureSource = new TextureSource.TextureSource({
...this.textureOptions,
width: pixelWidth,
height: pixelHeight,
resolution: 1,
antialias,
autoGarbageCollect: true
});
return new Texture.Texture({
source: textureSource,
label: `texturePool_${count++}`
});
}
/**
* Gets a Power-of-Two render texture or fullScreen texture
* @param frameWidth - The minimum width of the render texture.
* @param frameHeight - The minimum height of the render texture.
* @param resolution - The resolution of the render texture.
* @param antialias
* @returns The new render texture.
*/
getOptimalTexture(frameWidth, frameHeight, resolution = 1, antialias) {
let po2Width = Math.ceil(frameWidth * resolution - 1e-6);
let po2Height = Math.ceil(frameHeight * resolution - 1e-6);
po2Width = pow2.nextPow2(po2Width);
po2Height = pow2.nextPow2(po2Height);
const key = (po2Width << 17) + (po2Height << 1) + (antialias ? 1 : 0);
if (!this._texturePool[key]) {
this._texturePool[key] = [];
}
let texture = this._texturePool[key].pop();
if (!texture) {
texture = this.createTexture(po2Width, po2Height, antialias);
}
texture.source._resolution = resolution;
texture.source.width = po2Width / resolution;
texture.source.height = po2Height / resolution;
texture.source.pixelWidth = po2Width;
texture.source.pixelHeight = po2Height;
texture.frame.x = 0;
texture.frame.y = 0;
texture.frame.width = frameWidth;
texture.frame.height = frameHeight;
texture.updateUvs();
this._poolKeyHash[texture.uid] = key;
return texture;
}
/**
* Gets extra texture of the same size as input renderTexture
* @param texture - The texture to check what size it is.
* @param antialias - Whether to use antialias.
* @returns A texture that is a power of two
*/
getSameSizeTexture(texture, antialias = false) {
const source = texture.source;
return this.getOptimalTexture(texture.width, texture.height, source._resolution, antialias);
}
/**
* Place a render texture back into the pool.
* @param renderTexture - The renderTexture to free
*/
returnTexture(renderTexture) {
const key = this._poolKeyHash[renderTexture.uid];
this._texturePool[key].push(renderTexture);
}
/**
* Clears the pool.
* @param destroyTextures - Destroy all stored textures.
*/
clear(destroyTextures) {
destroyTextures = destroyTextures !== false;
if (destroyTextures) {
for (const i in this._texturePool) {
const textures = this._texturePool[i];
if (textures) {
for (let j = 0; j < textures.length; j++) {
textures[j].destroy(true);
}
}
}
}
this._texturePool = {};
}
}
const TexturePool = new TexturePoolClass();
exports.TexturePool = TexturePool;
exports.TexturePoolClass = TexturePoolClass;
//# sourceMappingURL=TexturePool.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,112 @@
import { nextPow2 } from '../../../../maths/misc/pow2.mjs';
import { TextureSource } from './sources/TextureSource.mjs';
import { Texture } from './Texture.mjs';
"use strict";
let count = 0;
class TexturePoolClass {
/**
* @param textureOptions - options that will be passed to BaseRenderTexture constructor
* @param {SCALE_MODE} [textureOptions.scaleMode] - See {@link SCALE_MODE} for possible values.
*/
constructor(textureOptions) {
this._poolKeyHash = /* @__PURE__ */ Object.create(null);
this._texturePool = {};
this.textureOptions = textureOptions || {};
this.enableFullScreen = false;
}
/**
* Creates texture with params that were specified in pool constructor.
* @param pixelWidth - Width of texture in pixels.
* @param pixelHeight - Height of texture in pixels.
* @param antialias
*/
createTexture(pixelWidth, pixelHeight, antialias) {
const textureSource = new TextureSource({
...this.textureOptions,
width: pixelWidth,
height: pixelHeight,
resolution: 1,
antialias,
autoGarbageCollect: true
});
return new Texture({
source: textureSource,
label: `texturePool_${count++}`
});
}
/**
* Gets a Power-of-Two render texture or fullScreen texture
* @param frameWidth - The minimum width of the render texture.
* @param frameHeight - The minimum height of the render texture.
* @param resolution - The resolution of the render texture.
* @param antialias
* @returns The new render texture.
*/
getOptimalTexture(frameWidth, frameHeight, resolution = 1, antialias) {
let po2Width = Math.ceil(frameWidth * resolution - 1e-6);
let po2Height = Math.ceil(frameHeight * resolution - 1e-6);
po2Width = nextPow2(po2Width);
po2Height = nextPow2(po2Height);
const key = (po2Width << 17) + (po2Height << 1) + (antialias ? 1 : 0);
if (!this._texturePool[key]) {
this._texturePool[key] = [];
}
let texture = this._texturePool[key].pop();
if (!texture) {
texture = this.createTexture(po2Width, po2Height, antialias);
}
texture.source._resolution = resolution;
texture.source.width = po2Width / resolution;
texture.source.height = po2Height / resolution;
texture.source.pixelWidth = po2Width;
texture.source.pixelHeight = po2Height;
texture.frame.x = 0;
texture.frame.y = 0;
texture.frame.width = frameWidth;
texture.frame.height = frameHeight;
texture.updateUvs();
this._poolKeyHash[texture.uid] = key;
return texture;
}
/**
* Gets extra texture of the same size as input renderTexture
* @param texture - The texture to check what size it is.
* @param antialias - Whether to use antialias.
* @returns A texture that is a power of two
*/
getSameSizeTexture(texture, antialias = false) {
const source = texture.source;
return this.getOptimalTexture(texture.width, texture.height, source._resolution, antialias);
}
/**
* Place a render texture back into the pool.
* @param renderTexture - The renderTexture to free
*/
returnTexture(renderTexture) {
const key = this._poolKeyHash[renderTexture.uid];
this._texturePool[key].push(renderTexture);
}
/**
* Clears the pool.
* @param destroyTextures - Destroy all stored textures.
*/
clear(destroyTextures) {
destroyTextures = destroyTextures !== false;
if (destroyTextures) {
for (const i in this._texturePool) {
const textures = this._texturePool[i];
if (textures) {
for (let j = 0; j < textures.length; j++) {
textures[j].destroy(true);
}
}
}
}
this._texturePool = {};
}
}
const TexturePool = new TexturePoolClass();
export { TexturePool, TexturePoolClass };
//# sourceMappingURL=TexturePool.mjs.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,112 @@
import EventEmitter from 'eventemitter3';
import type { BindResource } from '../../gpu/shader/BindResource';
import type { COMPARE_FUNCTION, SCALE_MODE, WRAP_MODE } from './const';
export interface TextureStyleOptions extends Partial<TextureStyle> {
/** setting this will set wrapModeU,wrapModeV and wrapModeW all at once! */
addressMode?: WRAP_MODE;
/** specifies the {{GPUAddressMode|address modes}} for the texture width, height, and depth coordinates, respectively. */
addressModeU?: WRAP_MODE;
/** specifies the {{GPUAddressMode|address modes}} for the texture width, height, and depth coordinates, respectively. */
addressModeV?: WRAP_MODE;
/** Specifies the {{GPUAddressMode|address modes}} for the texture width, height, and depth coordinates, respectively. */
addressModeW?: WRAP_MODE;
/** setting this will set magFilter,minFilter and mipmapFilter all at once! */
scaleMode?: SCALE_MODE;
/** specifies the sampling behavior when the sample footprint is smaller than or equal to one texel. */
magFilter?: SCALE_MODE;
/** specifies the sampling behavior when the sample footprint is larger than one texel. */
minFilter?: SCALE_MODE;
/** specifies behavior for sampling between mipmap levels. */
mipmapFilter?: SCALE_MODE;
/** specifies the minimum and maximum levels of detail, respectively, used internally when sampling a texture. */
lodMinClamp?: number;
/** Specifies the minimum and maximum levels of detail, respectively, used internally when sampling a texture. */
lodMaxClamp?: number;
/**
* When provided the sampler will be a comparison sampler with the specified
* {@link GPUCompareFunction}.
* Note: Comparison samplers may use filtering, but the sampling results will be
* implementation-dependent and may differ from the normal filtering rules.
*/
compare?: COMPARE_FUNCTION;
/**
* Specifies the maximum anisotropy value clamp used by the sampler.
* Note: Most implementations support {@link GPUSamplerDescriptor#maxAnisotropy} values in range
* between 1 and 16, inclusive. The used value of {@link GPUSamplerDescriptor#maxAnisotropy} will
* be clamped to the maximum value that the platform supports.
*
* setting this to anything higher than 1 will set scale modes to 'linear'
*/
maxAnisotropy?: number;
}
/**
* A texture style describes how a texture should be sampled by a shader.
* @memberof rendering
*/
export declare class TextureStyle extends EventEmitter<{
change: TextureStyle;
destroy: TextureStyle;
}> implements BindResource {
_resourceType: string;
_touched: number;
private _sharedResourceId;
/** default options for the style */
static readonly defaultOptions: TextureStyleOptions;
/** */
addressModeU?: WRAP_MODE;
/** */
addressModeV?: WRAP_MODE;
/** Specifies the {{GPUAddressMode|address modes}} for the texture width, height, and depth coordinates, respectively. */
addressModeW?: WRAP_MODE;
/** Specifies the sampling behavior when the sample footprint is smaller than or equal to one texel. */
magFilter?: SCALE_MODE;
/** Specifies the sampling behavior when the sample footprint is larger than one texel. */
minFilter?: SCALE_MODE;
/** Specifies behavior for sampling between mipmap levels. */
mipmapFilter?: SCALE_MODE;
/** */
lodMinClamp?: number;
/** Specifies the minimum and maximum levels of detail, respectively, used internally when sampling a texture. */
lodMaxClamp?: number;
/**
* When provided the sampler will be a comparison sampler with the specified
* {@link GPUCompareFunction}.
* Note: Comparison samplers may use filtering, but the sampling results will be
* implementation-dependent and may differ from the normal filtering rules.
*/
compare?: COMPARE_FUNCTION;
/**
* Specifies the maximum anisotropy value clamp used by the sampler.
* Note: Most implementations support {@link GPUSamplerDescriptor#maxAnisotropy} values in range
* between 1 and 16, inclusive. The used value of {@link GPUSamplerDescriptor#maxAnisotropy} will
* be clamped to the maximum value that the platform supports.
* @internal
* @ignore
*/
_maxAnisotropy?: number;
/**
* Has the style been destroyed?
* @readonly
*/
destroyed: boolean;
/**
* @param options - options for the style
*/
constructor(options?: TextureStyleOptions);
set addressMode(value: WRAP_MODE);
/** setting this will set wrapModeU,wrapModeV and wrapModeW all at once! */
get addressMode(): WRAP_MODE;
set wrapMode(value: WRAP_MODE);
get wrapMode(): WRAP_MODE;
set scaleMode(value: SCALE_MODE);
/** setting this will set magFilter,minFilter and mipmapFilter all at once! */
get scaleMode(): SCALE_MODE;
/** Specifies the maximum anisotropy value clamp used by the sampler. */
set maxAnisotropy(value: number);
get maxAnisotropy(): number;
get _resourceId(): number;
update(): void;
private _generateResourceId;
/** Destroys the style */
destroy(): void;
}

View File

@@ -0,0 +1,116 @@
'use strict';
var EventEmitter = require('eventemitter3');
var uid = require('../../../../utils/data/uid.js');
var deprecation = require('../../../../utils/logging/deprecation.js');
"use strict";
const idHash = /* @__PURE__ */ Object.create(null);
function createResourceIdFromString(value) {
const id = idHash[value];
if (id === void 0) {
idHash[value] = uid.uid("resource");
}
return id;
}
const _TextureStyle = class _TextureStyle extends EventEmitter {
/**
* @param options - options for the style
*/
constructor(options = {}) {
super();
this._resourceType = "textureSampler";
this._touched = 0;
/**
* Specifies the maximum anisotropy value clamp used by the sampler.
* Note: Most implementations support {@link GPUSamplerDescriptor#maxAnisotropy} values in range
* between 1 and 16, inclusive. The used value of {@link GPUSamplerDescriptor#maxAnisotropy} will
* be clamped to the maximum value that the platform supports.
* @internal
* @ignore
*/
this._maxAnisotropy = 1;
/**
* Has the style been destroyed?
* @readonly
*/
this.destroyed = false;
options = { ..._TextureStyle.defaultOptions, ...options };
this.addressMode = options.addressMode;
this.addressModeU = options.addressModeU ?? this.addressModeU;
this.addressModeV = options.addressModeV ?? this.addressModeV;
this.addressModeW = options.addressModeW ?? this.addressModeW;
this.scaleMode = options.scaleMode;
this.magFilter = options.magFilter ?? this.magFilter;
this.minFilter = options.minFilter ?? this.minFilter;
this.mipmapFilter = options.mipmapFilter ?? this.mipmapFilter;
this.lodMinClamp = options.lodMinClamp;
this.lodMaxClamp = options.lodMaxClamp;
this.compare = options.compare;
this.maxAnisotropy = options.maxAnisotropy ?? 1;
}
set addressMode(value) {
this.addressModeU = value;
this.addressModeV = value;
this.addressModeW = value;
}
/** setting this will set wrapModeU,wrapModeV and wrapModeW all at once! */
get addressMode() {
return this.addressModeU;
}
set wrapMode(value) {
deprecation.deprecation(deprecation.v8_0_0, "TextureStyle.wrapMode is now TextureStyle.addressMode");
this.addressMode = value;
}
get wrapMode() {
return this.addressMode;
}
set scaleMode(value) {
this.magFilter = value;
this.minFilter = value;
this.mipmapFilter = value;
}
/** setting this will set magFilter,minFilter and mipmapFilter all at once! */
get scaleMode() {
return this.magFilter;
}
/** Specifies the maximum anisotropy value clamp used by the sampler. */
set maxAnisotropy(value) {
this._maxAnisotropy = Math.min(value, 16);
if (this._maxAnisotropy > 1) {
this.scaleMode = "linear";
}
}
get maxAnisotropy() {
return this._maxAnisotropy;
}
// TODO - move this to WebGL?
get _resourceId() {
return this._sharedResourceId || this._generateResourceId();
}
update() {
this.emit("change", this);
this._sharedResourceId = null;
}
_generateResourceId() {
const bigKey = `${this.addressModeU}-${this.addressModeV}-${this.addressModeW}-${this.magFilter}-${this.minFilter}-${this.mipmapFilter}-${this.lodMinClamp}-${this.lodMaxClamp}-${this.compare}-${this._maxAnisotropy}`;
this._sharedResourceId = createResourceIdFromString(bigKey);
return this._resourceId;
}
/** Destroys the style */
destroy() {
this.destroyed = true;
this.emit("destroy", this);
this.emit("change", this);
this.removeAllListeners();
}
};
/** default options for the style */
_TextureStyle.defaultOptions = {
addressMode: "clamp-to-edge",
scaleMode: "linear"
};
let TextureStyle = _TextureStyle;
exports.TextureStyle = TextureStyle;
//# sourceMappingURL=TextureStyle.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,114 @@
import EventEmitter from 'eventemitter3';
import { uid } from '../../../../utils/data/uid.mjs';
import { deprecation, v8_0_0 } from '../../../../utils/logging/deprecation.mjs';
"use strict";
const idHash = /* @__PURE__ */ Object.create(null);
function createResourceIdFromString(value) {
const id = idHash[value];
if (id === void 0) {
idHash[value] = uid("resource");
}
return id;
}
const _TextureStyle = class _TextureStyle extends EventEmitter {
/**
* @param options - options for the style
*/
constructor(options = {}) {
super();
this._resourceType = "textureSampler";
this._touched = 0;
/**
* Specifies the maximum anisotropy value clamp used by the sampler.
* Note: Most implementations support {@link GPUSamplerDescriptor#maxAnisotropy} values in range
* between 1 and 16, inclusive. The used value of {@link GPUSamplerDescriptor#maxAnisotropy} will
* be clamped to the maximum value that the platform supports.
* @internal
* @ignore
*/
this._maxAnisotropy = 1;
/**
* Has the style been destroyed?
* @readonly
*/
this.destroyed = false;
options = { ..._TextureStyle.defaultOptions, ...options };
this.addressMode = options.addressMode;
this.addressModeU = options.addressModeU ?? this.addressModeU;
this.addressModeV = options.addressModeV ?? this.addressModeV;
this.addressModeW = options.addressModeW ?? this.addressModeW;
this.scaleMode = options.scaleMode;
this.magFilter = options.magFilter ?? this.magFilter;
this.minFilter = options.minFilter ?? this.minFilter;
this.mipmapFilter = options.mipmapFilter ?? this.mipmapFilter;
this.lodMinClamp = options.lodMinClamp;
this.lodMaxClamp = options.lodMaxClamp;
this.compare = options.compare;
this.maxAnisotropy = options.maxAnisotropy ?? 1;
}
set addressMode(value) {
this.addressModeU = value;
this.addressModeV = value;
this.addressModeW = value;
}
/** setting this will set wrapModeU,wrapModeV and wrapModeW all at once! */
get addressMode() {
return this.addressModeU;
}
set wrapMode(value) {
deprecation(v8_0_0, "TextureStyle.wrapMode is now TextureStyle.addressMode");
this.addressMode = value;
}
get wrapMode() {
return this.addressMode;
}
set scaleMode(value) {
this.magFilter = value;
this.minFilter = value;
this.mipmapFilter = value;
}
/** setting this will set magFilter,minFilter and mipmapFilter all at once! */
get scaleMode() {
return this.magFilter;
}
/** Specifies the maximum anisotropy value clamp used by the sampler. */
set maxAnisotropy(value) {
this._maxAnisotropy = Math.min(value, 16);
if (this._maxAnisotropy > 1) {
this.scaleMode = "linear";
}
}
get maxAnisotropy() {
return this._maxAnisotropy;
}
// TODO - move this to WebGL?
get _resourceId() {
return this._sharedResourceId || this._generateResourceId();
}
update() {
this.emit("change", this);
this._sharedResourceId = null;
}
_generateResourceId() {
const bigKey = `${this.addressModeU}-${this.addressModeV}-${this.addressModeW}-${this.magFilter}-${this.minFilter}-${this.mipmapFilter}-${this.lodMinClamp}-${this.lodMaxClamp}-${this.compare}-${this._maxAnisotropy}`;
this._sharedResourceId = createResourceIdFromString(bigKey);
return this._resourceId;
}
/** Destroys the style */
destroy() {
this.destroyed = true;
this.emit("destroy", this);
this.emit("change", this);
this.removeAllListeners();
}
};
/** default options for the style */
_TextureStyle.defaultOptions = {
addressMode: "clamp-to-edge",
scaleMode: "linear"
};
let TextureStyle = _TextureStyle;
export { TextureStyle };
//# sourceMappingURL=TextureStyle.mjs.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,45 @@
import type { Size } from '../../../../maths/misc/Size';
import type { Rectangle } from '../../../../maths/shapes/Rectangle';
/**
* Stores a texture's frame in UV coordinates, in
* which everything lies in the rectangle `[(0,0), (1,0),
* (1,1), (0,1)]`.
*
* | Corner | Coordinates |
* |--------------|-------------|
* | Top-Left | `(x0,y0)` |
* | Top-Right | `(x1,y1)` |
* | Bottom-Right | `(x2,y2)` |
* | Bottom-Left | `(x3,y3)` |
* @protected
* @memberof rendering
*/
export declare class TextureUvs {
/** X-component of top-left corner `(x0,y0)`. */
x0: number;
/** Y-component of top-left corner `(x0,y0)`. */
y0: number;
/** X-component of top-right corner `(x1,y1)`. */
x1: number;
/** Y-component of top-right corner `(x1,y1)`. */
y1: number;
/** X-component of bottom-right corner `(x2,y2)`. */
x2: number;
/** Y-component of bottom-right corner `(x2,y2)`. */
y2: number;
/** X-component of bottom-left corner `(x3,y3)`. */
x3: number;
/** Y-component of bottom-right corner `(x3,y3)`. */
y3: number;
uvsFloat32: Float32Array;
constructor();
/**
* Sets the texture Uvs based on the given frame information.
* @protected
* @param frame - The frame of the texture
* @param baseFrame - The base frame of the texture
* @param rotate - Rotation of frame, see {@link groupD8}
*/
set(frame: Rectangle, baseFrame: Size, rotate: number): void;
toString(): string;
}

View File

@@ -0,0 +1,70 @@
'use strict';
var groupD8 = require('../../../../maths/matrix/groupD8.js');
"use strict";
class TextureUvs {
constructor() {
this.x0 = 0;
this.y0 = 0;
this.x1 = 1;
this.y1 = 0;
this.x2 = 1;
this.y2 = 1;
this.x3 = 0;
this.y3 = 1;
this.uvsFloat32 = new Float32Array(8);
}
/**
* Sets the texture Uvs based on the given frame information.
* @protected
* @param frame - The frame of the texture
* @param baseFrame - The base frame of the texture
* @param rotate - Rotation of frame, see {@link groupD8}
*/
set(frame, baseFrame, rotate) {
const tw = baseFrame.width;
const th = baseFrame.height;
if (rotate) {
const w2 = frame.width / 2 / tw;
const h2 = frame.height / 2 / th;
const cX = frame.x / tw + w2;
const cY = frame.y / th + h2;
rotate = groupD8.groupD8.add(rotate, groupD8.groupD8.NW);
this.x0 = cX + w2 * groupD8.groupD8.uX(rotate);
this.y0 = cY + h2 * groupD8.groupD8.uY(rotate);
rotate = groupD8.groupD8.add(rotate, 2);
this.x1 = cX + w2 * groupD8.groupD8.uX(rotate);
this.y1 = cY + h2 * groupD8.groupD8.uY(rotate);
rotate = groupD8.groupD8.add(rotate, 2);
this.x2 = cX + w2 * groupD8.groupD8.uX(rotate);
this.y2 = cY + h2 * groupD8.groupD8.uY(rotate);
rotate = groupD8.groupD8.add(rotate, 2);
this.x3 = cX + w2 * groupD8.groupD8.uX(rotate);
this.y3 = cY + h2 * groupD8.groupD8.uY(rotate);
} else {
this.x0 = frame.x / tw;
this.y0 = frame.y / th;
this.x1 = (frame.x + frame.width) / tw;
this.y1 = frame.y / th;
this.x2 = (frame.x + frame.width) / tw;
this.y2 = (frame.y + frame.height) / th;
this.x3 = frame.x / tw;
this.y3 = (frame.y + frame.height) / th;
}
this.uvsFloat32[0] = this.x0;
this.uvsFloat32[1] = this.y0;
this.uvsFloat32[2] = this.x1;
this.uvsFloat32[3] = this.y1;
this.uvsFloat32[4] = this.x2;
this.uvsFloat32[5] = this.y2;
this.uvsFloat32[6] = this.x3;
this.uvsFloat32[7] = this.y3;
}
toString() {
return `[pixi.js/core:TextureUvs x0=${this.x0} y0=${this.y0} x1=${this.x1} y1=${this.y1} x2=${this.x2} y2=${this.y2} x3=${this.x3} y3=${this.y3}]`;
}
}
exports.TextureUvs = TextureUvs;
//# sourceMappingURL=TextureUvs.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,68 @@
import { groupD8 } from '../../../../maths/matrix/groupD8.mjs';
"use strict";
class TextureUvs {
constructor() {
this.x0 = 0;
this.y0 = 0;
this.x1 = 1;
this.y1 = 0;
this.x2 = 1;
this.y2 = 1;
this.x3 = 0;
this.y3 = 1;
this.uvsFloat32 = new Float32Array(8);
}
/**
* Sets the texture Uvs based on the given frame information.
* @protected
* @param frame - The frame of the texture
* @param baseFrame - The base frame of the texture
* @param rotate - Rotation of frame, see {@link groupD8}
*/
set(frame, baseFrame, rotate) {
const tw = baseFrame.width;
const th = baseFrame.height;
if (rotate) {
const w2 = frame.width / 2 / tw;
const h2 = frame.height / 2 / th;
const cX = frame.x / tw + w2;
const cY = frame.y / th + h2;
rotate = groupD8.add(rotate, groupD8.NW);
this.x0 = cX + w2 * groupD8.uX(rotate);
this.y0 = cY + h2 * groupD8.uY(rotate);
rotate = groupD8.add(rotate, 2);
this.x1 = cX + w2 * groupD8.uX(rotate);
this.y1 = cY + h2 * groupD8.uY(rotate);
rotate = groupD8.add(rotate, 2);
this.x2 = cX + w2 * groupD8.uX(rotate);
this.y2 = cY + h2 * groupD8.uY(rotate);
rotate = groupD8.add(rotate, 2);
this.x3 = cX + w2 * groupD8.uX(rotate);
this.y3 = cY + h2 * groupD8.uY(rotate);
} else {
this.x0 = frame.x / tw;
this.y0 = frame.y / th;
this.x1 = (frame.x + frame.width) / tw;
this.y1 = frame.y / th;
this.x2 = (frame.x + frame.width) / tw;
this.y2 = (frame.y + frame.height) / th;
this.x3 = frame.x / tw;
this.y3 = (frame.y + frame.height) / th;
}
this.uvsFloat32[0] = this.x0;
this.uvsFloat32[1] = this.y0;
this.uvsFloat32[2] = this.x1;
this.uvsFloat32[3] = this.y1;
this.uvsFloat32[4] = this.x2;
this.uvsFloat32[5] = this.y2;
this.uvsFloat32[6] = this.x3;
this.uvsFloat32[7] = this.y3;
}
toString() {
return `[pixi.js/core:TextureUvs x0=${this.x0} y0=${this.y0} x1=${this.x1} y1=${this.y1} x2=${this.x2} y2=${this.y2} x3=${this.x3} y3=${this.y3}]`;
}
}
export { TextureUvs };
//# sourceMappingURL=TextureUvs.mjs.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,73 @@
/**
* Specifies the alpha composition mode for textures.
*
* - `no-premultiply-alpha`: Does not premultiply alpha.
* - `premultiply-alpha-on-upload`: Premultiplies alpha on texture upload.
* - `premultiplied-alpha`: Assumes the texture is already in premultiplied alpha format.
* @typedef {'no-premultiply-alpha' | 'premultiply-alpha-on-upload' | 'premultiplied-alpha'} ALPHA_MODES
*/
export type ALPHA_MODES = 'no-premultiply-alpha' | 'premultiply-alpha-on-upload' | 'premultiplied-alpha';
/**
* Constants for multi-sampling antialiasing.
* @see Framebuffer#multisample
* @name MSAA_QUALITY
* @static
* @enum {number}
* @property {number} NONE - No multisampling for this renderTexture
* @property {number} LOW - Try 2 samples
* @property {number} MEDIUM - Try 4 samples
* @property {number} HIGH - Try 8 samples
*/
export declare enum MSAA_QUALITY {
NONE = 0,
LOW = 2,
MEDIUM = 4,
HIGH = 8
}
export type TEXTURE_FORMATS = 'r8unorm' | 'r8snorm' | 'r8uint' | 'r8sint' | 'r16uint' | 'r16sint' | 'r16float' | 'rg8unorm' | 'rg8snorm' | 'rg8uint' | 'rg8sint' | 'r32uint' | 'r32sint' | 'r32float' | 'rg16uint' | 'rg16sint' | 'rg16float' | 'rgba8unorm' | 'rgba8unorm-srgb' | 'rgba8snorm' | 'rgba8uint' | 'rgba8sint' | 'bgra8unorm' | 'bgra8unorm-srgb' | 'rgb9e5ufloat' | 'rgb10a2unorm' | 'rg11b10ufloat' | 'rg32uint' | 'rg32sint' | 'rg32float' | 'rgba16uint' | 'rgba16sint' | 'rgba16float' | 'rgba32uint' | 'rgba32sint' | 'rgba32float' | 'stencil8' | 'depth16unorm' | 'depth24plus' | 'depth24plus-stencil8' | 'depth32float' | 'depth32float-stencil8' | 'bc1-rgba-unorm' | 'bc1-rgba-unorm-srgb' | 'bc2-rgba-unorm' | 'bc2-rgba-unorm-srgb' | 'bc3-rgba-unorm' | 'bc3-rgba-unorm-srgb' | 'bc4-r-unorm' | 'bc4-r-snorm' | 'bc5-rg-unorm' | 'bc5-rg-snorm' | 'bc6h-rgb-ufloat' | 'bc6h-rgb-float' | 'bc7-rgba-unorm' | 'bc7-rgba-unorm-srgb' | 'etc2-rgb8unorm' | 'etc2-rgb8unorm-srgb' | 'etc2-rgb8a1unorm' | 'etc2-rgb8a1unorm-srgb' | 'etc2-rgba8unorm' | 'etc2-rgba8unorm-srgb' | 'eac-r11unorm' | 'eac-r11snorm' | 'eac-rg11unorm' | 'eac-rg11snorm' | 'astc-4x4-unorm' | 'astc-4x4-unorm-srgb' | 'astc-5x4-unorm' | 'astc-5x4-unorm-srgb' | 'astc-5x5-unorm' | 'astc-5x5-unorm-srgb' | 'astc-6x5-unorm' | 'astc-6x5-unorm-srgb' | 'astc-6x6-unorm' | 'astc-6x6-unorm-srgb' | 'astc-8x5-unorm' | 'astc-8x5-unorm-srgb' | 'astc-8x6-unorm' | 'astc-8x6-unorm-srgb' | 'astc-8x8-unorm' | 'astc-8x8-unorm-srgb' | 'astc-10x5-unorm' | 'astc-10x5-unorm-srgb' | 'astc-10x6-unorm' | 'astc-10x6-unorm-srgb' | 'astc-10x8-unorm' | 'astc-10x8-unorm-srgb' | 'astc-10x10-unorm' | 'astc-10x10-unorm-srgb' | 'astc-12x10-unorm' | 'astc-12x10-unorm-srgb' | 'astc-12x12-unorm' | 'astc-12x12-unorm-srgb';
export type TEXTURE_VIEW_DIMENSIONS = '1d' | '2d' | '2d-array' | 'cube' | 'cube-array' | '3d';
export type TEXTURE_DIMENSIONS = '1d' | '2d' | '3d';
export type WRAP_MODE =
/**
* The texture uvs are clamped
* @default 33071
*/
'clamp-to-edge'
/**
* The texture uvs tile and repeat
* @default 10497
*/
| 'repeat'
/**
* The texture uvs tile and repeat with mirroring
* @default 33648
*/
| 'mirror-repeat';
export declare enum DEPRECATED_WRAP_MODES {
CLAMP = "clamp-to-edge",
REPEAT = "repeat",
MIRRORED_REPEAT = "mirror-repeat"
}
/** @deprecated since 8.0.0 */
export declare const WRAP_MODES: typeof DEPRECATED_WRAP_MODES;
/**
* The scale modes that are supported by pixi.
*
* The {@link settings.SCALE_MODE} scale mode affects the default scaling mode of future operations.
* It can be re-assigned to either LINEAR or NEAREST, depending upon suitability.
* @static
*/
export type SCALE_MODE =
/** Pixelating scaling */
'nearest'
/** Smooth scaling */
| 'linear';
export declare enum DEPRECATED_SCALE_MODES {
NEAREST = "nearest",
LINEAR = "linear"
}
/**
* @deprecated since 8.0.0
*/
export declare const SCALE_MODES: typeof DEPRECATED_SCALE_MODES;
export type COMPARE_FUNCTION = 'never' | 'less' | 'equal' | 'less-equal' | 'greater' | 'not-equal' | 'greater-equal' | 'always';

View File

@@ -0,0 +1,42 @@
'use strict';
var deprecation = require('../../../../utils/logging/deprecation.js');
"use strict";
var MSAA_QUALITY = /* @__PURE__ */ ((MSAA_QUALITY2) => {
MSAA_QUALITY2[MSAA_QUALITY2["NONE"] = 0] = "NONE";
MSAA_QUALITY2[MSAA_QUALITY2["LOW"] = 2] = "LOW";
MSAA_QUALITY2[MSAA_QUALITY2["MEDIUM"] = 4] = "MEDIUM";
MSAA_QUALITY2[MSAA_QUALITY2["HIGH"] = 8] = "HIGH";
return MSAA_QUALITY2;
})(MSAA_QUALITY || {});
var DEPRECATED_WRAP_MODES = /* @__PURE__ */ ((DEPRECATED_WRAP_MODES2) => {
DEPRECATED_WRAP_MODES2["CLAMP"] = "clamp-to-edge";
DEPRECATED_WRAP_MODES2["REPEAT"] = "repeat";
DEPRECATED_WRAP_MODES2["MIRRORED_REPEAT"] = "mirror-repeat";
return DEPRECATED_WRAP_MODES2;
})(DEPRECATED_WRAP_MODES || {});
const WRAP_MODES = new Proxy(DEPRECATED_WRAP_MODES, {
get(target, prop) {
deprecation.deprecation(deprecation.v8_0_0, `DRAW_MODES.${prop} is deprecated, use '${DEPRECATED_WRAP_MODES[prop]}' instead`);
return target[prop];
}
});
var DEPRECATED_SCALE_MODES = /* @__PURE__ */ ((DEPRECATED_SCALE_MODES2) => {
DEPRECATED_SCALE_MODES2["NEAREST"] = "nearest";
DEPRECATED_SCALE_MODES2["LINEAR"] = "linear";
return DEPRECATED_SCALE_MODES2;
})(DEPRECATED_SCALE_MODES || {});
const SCALE_MODES = new Proxy(DEPRECATED_SCALE_MODES, {
get(target, prop) {
deprecation.deprecation(deprecation.v8_0_0, `DRAW_MODES.${prop} is deprecated, use '${DEPRECATED_SCALE_MODES[prop]}' instead`);
return target[prop];
}
});
exports.DEPRECATED_SCALE_MODES = DEPRECATED_SCALE_MODES;
exports.DEPRECATED_WRAP_MODES = DEPRECATED_WRAP_MODES;
exports.MSAA_QUALITY = MSAA_QUALITY;
exports.SCALE_MODES = SCALE_MODES;
exports.WRAP_MODES = WRAP_MODES;
//# sourceMappingURL=const.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,36 @@
import { deprecation, v8_0_0 } from '../../../../utils/logging/deprecation.mjs';
"use strict";
var MSAA_QUALITY = /* @__PURE__ */ ((MSAA_QUALITY2) => {
MSAA_QUALITY2[MSAA_QUALITY2["NONE"] = 0] = "NONE";
MSAA_QUALITY2[MSAA_QUALITY2["LOW"] = 2] = "LOW";
MSAA_QUALITY2[MSAA_QUALITY2["MEDIUM"] = 4] = "MEDIUM";
MSAA_QUALITY2[MSAA_QUALITY2["HIGH"] = 8] = "HIGH";
return MSAA_QUALITY2;
})(MSAA_QUALITY || {});
var DEPRECATED_WRAP_MODES = /* @__PURE__ */ ((DEPRECATED_WRAP_MODES2) => {
DEPRECATED_WRAP_MODES2["CLAMP"] = "clamp-to-edge";
DEPRECATED_WRAP_MODES2["REPEAT"] = "repeat";
DEPRECATED_WRAP_MODES2["MIRRORED_REPEAT"] = "mirror-repeat";
return DEPRECATED_WRAP_MODES2;
})(DEPRECATED_WRAP_MODES || {});
const WRAP_MODES = new Proxy(DEPRECATED_WRAP_MODES, {
get(target, prop) {
deprecation(v8_0_0, `DRAW_MODES.${prop} is deprecated, use '${DEPRECATED_WRAP_MODES[prop]}' instead`);
return target[prop];
}
});
var DEPRECATED_SCALE_MODES = /* @__PURE__ */ ((DEPRECATED_SCALE_MODES2) => {
DEPRECATED_SCALE_MODES2["NEAREST"] = "nearest";
DEPRECATED_SCALE_MODES2["LINEAR"] = "linear";
return DEPRECATED_SCALE_MODES2;
})(DEPRECATED_SCALE_MODES || {});
const SCALE_MODES = new Proxy(DEPRECATED_SCALE_MODES, {
get(target, prop) {
deprecation(v8_0_0, `DRAW_MODES.${prop} is deprecated, use '${DEPRECATED_SCALE_MODES[prop]}' instead`);
return target[prop];
}
});
export { DEPRECATED_SCALE_MODES, DEPRECATED_WRAP_MODES, MSAA_QUALITY, SCALE_MODES, WRAP_MODES };
//# sourceMappingURL=const.mjs.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,14 @@
import { TextureSource } from './TextureSource';
import type { ExtensionMetadata } from '../../../../../extensions/Extensions';
import type { TypedArray } from '../../buffer/Buffer';
import type { TextureSourceOptions } from './TextureSource';
export interface BufferSourceOptions extends TextureSourceOptions<TypedArray | ArrayBuffer> {
width: number;
height: number;
}
export declare class BufferImageSource extends TextureSource<TypedArray | ArrayBuffer> {
static extension: ExtensionMetadata;
uploadMethodId: string;
constructor(options: BufferSourceOptions);
static test(resource: any): resource is TypedArray | ArrayBuffer;
}

View File

@@ -0,0 +1,42 @@
'use strict';
var Extensions = require('../../../../../extensions/Extensions.js');
var TextureSource = require('./TextureSource.js');
"use strict";
class BufferImageSource extends TextureSource.TextureSource {
constructor(options) {
const buffer = options.resource || new Float32Array(options.width * options.height * 4);
let format = options.format;
if (!format) {
if (buffer instanceof Float32Array) {
format = "rgba32float";
} else if (buffer instanceof Int32Array) {
format = "rgba32uint";
} else if (buffer instanceof Uint32Array) {
format = "rgba32uint";
} else if (buffer instanceof Int16Array) {
format = "rgba16uint";
} else if (buffer instanceof Uint16Array) {
format = "rgba16uint";
} else if (buffer instanceof Int8Array) {
format = "bgra8unorm";
} else {
format = "bgra8unorm";
}
}
super({
...options,
resource: buffer,
format
});
this.uploadMethodId = "buffer";
}
static test(resource) {
return resource instanceof Int8Array || resource instanceof Uint8Array || resource instanceof Uint8ClampedArray || resource instanceof Int16Array || resource instanceof Uint16Array || resource instanceof Int32Array || resource instanceof Uint32Array || resource instanceof Float32Array;
}
}
BufferImageSource.extension = Extensions.ExtensionType.TextureSource;
exports.BufferImageSource = BufferImageSource;
//# sourceMappingURL=BufferImageSource.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"BufferImageSource.js","sources":["../../../../../../src/rendering/renderers/shared/texture/sources/BufferImageSource.ts"],"sourcesContent":["import { ExtensionType } from '../../../../../extensions/Extensions';\nimport { TextureSource } from './TextureSource';\n\nimport type { ExtensionMetadata } from '../../../../../extensions/Extensions';\nimport type { TypedArray } from '../../buffer/Buffer';\nimport type { TextureSourceOptions } from './TextureSource';\n\nexport interface BufferSourceOptions extends TextureSourceOptions<TypedArray | ArrayBuffer>\n{\n width: number;\n height: number;\n}\n\nexport class BufferImageSource extends TextureSource<TypedArray | ArrayBuffer>\n{\n public static extension: ExtensionMetadata = ExtensionType.TextureSource;\n\n public uploadMethodId = 'buffer';\n\n constructor(options: BufferSourceOptions)\n {\n const buffer = options.resource || new Float32Array(options.width * options.height * 4);\n let format = options.format;\n\n if (!format)\n {\n if (buffer instanceof Float32Array)\n {\n format = 'rgba32float';\n }\n else if (buffer instanceof Int32Array)\n {\n format = 'rgba32uint';\n }\n else if (buffer instanceof Uint32Array)\n {\n format = 'rgba32uint';\n }\n else if (buffer instanceof Int16Array)\n {\n format = 'rgba16uint';\n }\n else if (buffer instanceof Uint16Array)\n {\n format = 'rgba16uint';\n }\n else if (buffer instanceof Int8Array)\n {\n format = 'bgra8unorm';\n }\n else\n {\n format = 'bgra8unorm';\n }\n }\n\n super({\n ...options,\n resource: buffer,\n format,\n });\n }\n\n public static test(resource: any): resource is TypedArray | ArrayBuffer\n {\n return resource instanceof Int8Array\n || resource instanceof Uint8Array\n || resource instanceof Uint8ClampedArray\n || resource instanceof Int16Array\n || resource instanceof Uint16Array\n || resource instanceof Int32Array\n || resource instanceof Uint32Array\n || resource instanceof Float32Array;\n }\n}\n"],"names":["TextureSource","ExtensionType"],"mappings":";;;;;;AAaO,MAAM,0BAA0BA,2BACvC,CAAA;AAAA,EAKI,YAAY,OACZ,EAAA;AACI,IAAM,MAAA,MAAA,GAAS,QAAQ,QAAY,IAAA,IAAI,aAAa,OAAQ,CAAA,KAAA,GAAQ,OAAQ,CAAA,MAAA,GAAS,CAAC,CAAA,CAAA;AACtF,IAAA,IAAI,SAAS,OAAQ,CAAA,MAAA,CAAA;AAErB,IAAA,IAAI,CAAC,MACL,EAAA;AACI,MAAA,IAAI,kBAAkB,YACtB,EAAA;AACI,QAAS,MAAA,GAAA,aAAA,CAAA;AAAA,OACb,MAAA,IACS,kBAAkB,UAC3B,EAAA;AACI,QAAS,MAAA,GAAA,YAAA,CAAA;AAAA,OACb,MAAA,IACS,kBAAkB,WAC3B,EAAA;AACI,QAAS,MAAA,GAAA,YAAA,CAAA;AAAA,OACb,MAAA,IACS,kBAAkB,UAC3B,EAAA;AACI,QAAS,MAAA,GAAA,YAAA,CAAA;AAAA,OACb,MAAA,IACS,kBAAkB,WAC3B,EAAA;AACI,QAAS,MAAA,GAAA,YAAA,CAAA;AAAA,OACb,MAAA,IACS,kBAAkB,SAC3B,EAAA;AACI,QAAS,MAAA,GAAA,YAAA,CAAA;AAAA,OAGb,MAAA;AACI,QAAS,MAAA,GAAA,YAAA,CAAA;AAAA,OACb;AAAA,KACJ;AAEA,IAAM,KAAA,CAAA;AAAA,MACF,GAAG,OAAA;AAAA,MACH,QAAU,EAAA,MAAA;AAAA,MACV,MAAA;AAAA,KACH,CAAA,CAAA;AA3CL,IAAA,IAAA,CAAO,cAAiB,GAAA,QAAA,CAAA;AAAA,GA4CxB;AAAA,EAEA,OAAc,KAAK,QACnB,EAAA;AACI,IAAA,OAAO,QAAoB,YAAA,SAAA,IACxB,QAAoB,YAAA,UAAA,IACpB,oBAAoB,iBACpB,IAAA,QAAA,YAAoB,UACpB,IAAA,QAAA,YAAoB,WACpB,IAAA,QAAA,YAAoB,UACpB,IAAA,QAAA,YAAoB,eACpB,QAAoB,YAAA,YAAA,CAAA;AAAA,GAC3B;AACJ,CAAA;AA7Da,iBAAA,CAEK,YAA+BC,wBAAc,CAAA,aAAA;;;;"}

View File

@@ -0,0 +1,40 @@
import { ExtensionType } from '../../../../../extensions/Extensions.mjs';
import { TextureSource } from './TextureSource.mjs';
"use strict";
class BufferImageSource extends TextureSource {
constructor(options) {
const buffer = options.resource || new Float32Array(options.width * options.height * 4);
let format = options.format;
if (!format) {
if (buffer instanceof Float32Array) {
format = "rgba32float";
} else if (buffer instanceof Int32Array) {
format = "rgba32uint";
} else if (buffer instanceof Uint32Array) {
format = "rgba32uint";
} else if (buffer instanceof Int16Array) {
format = "rgba16uint";
} else if (buffer instanceof Uint16Array) {
format = "rgba16uint";
} else if (buffer instanceof Int8Array) {
format = "bgra8unorm";
} else {
format = "bgra8unorm";
}
}
super({
...options,
resource: buffer,
format
});
this.uploadMethodId = "buffer";
}
static test(resource) {
return resource instanceof Int8Array || resource instanceof Uint8Array || resource instanceof Uint8ClampedArray || resource instanceof Int16Array || resource instanceof Uint16Array || resource instanceof Int32Array || resource instanceof Uint32Array || resource instanceof Float32Array;
}
}
BufferImageSource.extension = ExtensionType.TextureSource;
export { BufferImageSource };
//# sourceMappingURL=BufferImageSource.mjs.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"BufferImageSource.mjs","sources":["../../../../../../src/rendering/renderers/shared/texture/sources/BufferImageSource.ts"],"sourcesContent":["import { ExtensionType } from '../../../../../extensions/Extensions';\nimport { TextureSource } from './TextureSource';\n\nimport type { ExtensionMetadata } from '../../../../../extensions/Extensions';\nimport type { TypedArray } from '../../buffer/Buffer';\nimport type { TextureSourceOptions } from './TextureSource';\n\nexport interface BufferSourceOptions extends TextureSourceOptions<TypedArray | ArrayBuffer>\n{\n width: number;\n height: number;\n}\n\nexport class BufferImageSource extends TextureSource<TypedArray | ArrayBuffer>\n{\n public static extension: ExtensionMetadata = ExtensionType.TextureSource;\n\n public uploadMethodId = 'buffer';\n\n constructor(options: BufferSourceOptions)\n {\n const buffer = options.resource || new Float32Array(options.width * options.height * 4);\n let format = options.format;\n\n if (!format)\n {\n if (buffer instanceof Float32Array)\n {\n format = 'rgba32float';\n }\n else if (buffer instanceof Int32Array)\n {\n format = 'rgba32uint';\n }\n else if (buffer instanceof Uint32Array)\n {\n format = 'rgba32uint';\n }\n else if (buffer instanceof Int16Array)\n {\n format = 'rgba16uint';\n }\n else if (buffer instanceof Uint16Array)\n {\n format = 'rgba16uint';\n }\n else if (buffer instanceof Int8Array)\n {\n format = 'bgra8unorm';\n }\n else\n {\n format = 'bgra8unorm';\n }\n }\n\n super({\n ...options,\n resource: buffer,\n format,\n });\n }\n\n public static test(resource: any): resource is TypedArray | ArrayBuffer\n {\n return resource instanceof Int8Array\n || resource instanceof Uint8Array\n || resource instanceof Uint8ClampedArray\n || resource instanceof Int16Array\n || resource instanceof Uint16Array\n || resource instanceof Int32Array\n || resource instanceof Uint32Array\n || resource instanceof Float32Array;\n }\n}\n"],"names":[],"mappings":";;;;AAaO,MAAM,0BAA0B,aACvC,CAAA;AAAA,EAKI,YAAY,OACZ,EAAA;AACI,IAAM,MAAA,MAAA,GAAS,QAAQ,QAAY,IAAA,IAAI,aAAa,OAAQ,CAAA,KAAA,GAAQ,OAAQ,CAAA,MAAA,GAAS,CAAC,CAAA,CAAA;AACtF,IAAA,IAAI,SAAS,OAAQ,CAAA,MAAA,CAAA;AAErB,IAAA,IAAI,CAAC,MACL,EAAA;AACI,MAAA,IAAI,kBAAkB,YACtB,EAAA;AACI,QAAS,MAAA,GAAA,aAAA,CAAA;AAAA,OACb,MAAA,IACS,kBAAkB,UAC3B,EAAA;AACI,QAAS,MAAA,GAAA,YAAA,CAAA;AAAA,OACb,MAAA,IACS,kBAAkB,WAC3B,EAAA;AACI,QAAS,MAAA,GAAA,YAAA,CAAA;AAAA,OACb,MAAA,IACS,kBAAkB,UAC3B,EAAA;AACI,QAAS,MAAA,GAAA,YAAA,CAAA;AAAA,OACb,MAAA,IACS,kBAAkB,WAC3B,EAAA;AACI,QAAS,MAAA,GAAA,YAAA,CAAA;AAAA,OACb,MAAA,IACS,kBAAkB,SAC3B,EAAA;AACI,QAAS,MAAA,GAAA,YAAA,CAAA;AAAA,OAGb,MAAA;AACI,QAAS,MAAA,GAAA,YAAA,CAAA;AAAA,OACb;AAAA,KACJ;AAEA,IAAM,KAAA,CAAA;AAAA,MACF,GAAG,OAAA;AAAA,MACH,QAAU,EAAA,MAAA;AAAA,MACV,MAAA;AAAA,KACH,CAAA,CAAA;AA3CL,IAAA,IAAA,CAAO,cAAiB,GAAA,QAAA,CAAA;AAAA,GA4CxB;AAAA,EAEA,OAAc,KAAK,QACnB,EAAA;AACI,IAAA,OAAO,QAAoB,YAAA,SAAA,IACxB,QAAoB,YAAA,UAAA,IACpB,oBAAoB,iBACpB,IAAA,QAAA,YAAoB,UACpB,IAAA,QAAA,YAAoB,WACpB,IAAA,QAAA,YAAoB,UACpB,IAAA,QAAA,YAAoB,eACpB,QAAoB,YAAA,YAAA,CAAA;AAAA,GAC3B;AACJ,CAAA;AA7Da,iBAAA,CAEK,YAA+B,aAAc,CAAA,aAAA;;;;"}

View File

@@ -0,0 +1,27 @@
import { TextureSource } from './TextureSource';
import type { ICanvas } from '../../../../../environment/canvas/ICanvas';
import type { ExtensionMetadata } from '../../../../../extensions/Extensions';
import type { TextureSourceOptions } from './TextureSource';
export interface CanvasSourceOptions extends TextureSourceOptions<ICanvas> {
/** should the canvas be resized to preserve its screen width and height regardless of the resolution of the renderer */
autoDensity?: boolean;
/** if true, this canvas will be set up to be transparent where possible */
transparent?: boolean;
}
export declare class CanvasSource extends TextureSource<ICanvas> {
static extension: ExtensionMetadata;
uploadMethodId: string;
autoDensity: boolean;
transparent: boolean;
private _context2D;
constructor(options: CanvasSourceOptions);
resizeCanvas(): void;
resize(width?: number, height?: number, resolution?: number): boolean;
static test(resource: any): resource is ICanvas;
/**
* Returns the 2D rendering context for the canvas.
* Caches the context after creating it.
* @returns The 2D rendering context of the canvas.
*/
get context2D(): CanvasRenderingContext2D;
}

View File

@@ -0,0 +1,66 @@
'use strict';
var adapter = require('../../../../../environment/adapter.js');
var Extensions = require('../../../../../extensions/Extensions.js');
var TextureSource = require('./TextureSource.js');
"use strict";
class CanvasSource extends TextureSource.TextureSource {
constructor(options) {
if (!options.resource) {
options.resource = adapter.DOMAdapter.get().createCanvas();
}
if (!options.width) {
options.width = options.resource.width;
if (!options.autoDensity) {
options.width /= options.resolution;
}
}
if (!options.height) {
options.height = options.resource.height;
if (!options.autoDensity) {
options.height /= options.resolution;
}
}
super(options);
this.uploadMethodId = "image";
this.autoDensity = options.autoDensity;
const canvas = options.resource;
if (this.pixelWidth !== canvas.width || this.pixelWidth !== canvas.height) {
this.resizeCanvas();
}
this.transparent = !!options.transparent;
}
resizeCanvas() {
if (this.autoDensity) {
this.resource.style.width = `${this.width}px`;
this.resource.style.height = `${this.height}px`;
}
if (this.resource.width !== this.pixelWidth || this.resource.height !== this.pixelHeight) {
this.resource.width = this.pixelWidth;
this.resource.height = this.pixelHeight;
}
}
resize(width = this.width, height = this.height, resolution = this._resolution) {
const didResize = super.resize(width, height, resolution);
if (didResize) {
this.resizeCanvas();
}
return didResize;
}
static test(resource) {
return globalThis.HTMLCanvasElement && resource instanceof HTMLCanvasElement || globalThis.OffscreenCanvas && resource instanceof OffscreenCanvas;
}
/**
* Returns the 2D rendering context for the canvas.
* Caches the context after creating it.
* @returns The 2D rendering context of the canvas.
*/
get context2D() {
return this._context2D || (this._context2D = this.resource.getContext("2d"));
}
}
CanvasSource.extension = Extensions.ExtensionType.TextureSource;
exports.CanvasSource = CanvasSource;
//# sourceMappingURL=CanvasSource.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,64 @@
import { DOMAdapter } from '../../../../../environment/adapter.mjs';
import { ExtensionType } from '../../../../../extensions/Extensions.mjs';
import { TextureSource } from './TextureSource.mjs';
"use strict";
class CanvasSource extends TextureSource {
constructor(options) {
if (!options.resource) {
options.resource = DOMAdapter.get().createCanvas();
}
if (!options.width) {
options.width = options.resource.width;
if (!options.autoDensity) {
options.width /= options.resolution;
}
}
if (!options.height) {
options.height = options.resource.height;
if (!options.autoDensity) {
options.height /= options.resolution;
}
}
super(options);
this.uploadMethodId = "image";
this.autoDensity = options.autoDensity;
const canvas = options.resource;
if (this.pixelWidth !== canvas.width || this.pixelWidth !== canvas.height) {
this.resizeCanvas();
}
this.transparent = !!options.transparent;
}
resizeCanvas() {
if (this.autoDensity) {
this.resource.style.width = `${this.width}px`;
this.resource.style.height = `${this.height}px`;
}
if (this.resource.width !== this.pixelWidth || this.resource.height !== this.pixelHeight) {
this.resource.width = this.pixelWidth;
this.resource.height = this.pixelHeight;
}
}
resize(width = this.width, height = this.height, resolution = this._resolution) {
const didResize = super.resize(width, height, resolution);
if (didResize) {
this.resizeCanvas();
}
return didResize;
}
static test(resource) {
return globalThis.HTMLCanvasElement && resource instanceof HTMLCanvasElement || globalThis.OffscreenCanvas && resource instanceof OffscreenCanvas;
}
/**
* Returns the 2D rendering context for the canvas.
* Caches the context after creating it.
* @returns The 2D rendering context of the canvas.
*/
get context2D() {
return this._context2D || (this._context2D = this.resource.getContext("2d"));
}
}
CanvasSource.extension = ExtensionType.TextureSource;
export { CanvasSource };
//# sourceMappingURL=CanvasSource.mjs.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,6 @@
import { TextureSource } from './TextureSource';
import type { TextureSourceOptions } from './TextureSource';
export declare class CompressedSource extends TextureSource<Uint8Array[]> {
readonly uploadMethodId = "compressed";
constructor(options: TextureSourceOptions);
}

View File

@@ -0,0 +1,16 @@
'use strict';
var TextureSource = require('./TextureSource.js');
"use strict";
class CompressedSource extends TextureSource.TextureSource {
constructor(options) {
super(options);
this.uploadMethodId = "compressed";
this.resource = options.resource;
this.mipLevelCount = this.resource.length;
}
}
exports.CompressedSource = CompressedSource;
//# sourceMappingURL=CompressedSource.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"CompressedSource.js","sources":["../../../../../../src/rendering/renderers/shared/texture/sources/CompressedSource.ts"],"sourcesContent":["import { TextureSource } from './TextureSource';\n\nimport type { TextureSourceOptions } from './TextureSource';\n\nexport class CompressedSource extends TextureSource<Uint8Array[]>\n{\n public readonly uploadMethodId = 'compressed';\n\n constructor(options: TextureSourceOptions)\n {\n super(options);\n\n this.resource = options.resource;\n this.mipLevelCount = this.resource.length;\n }\n}\n"],"names":["TextureSource"],"mappings":";;;;;AAIO,MAAM,yBAAyBA,2BACtC,CAAA;AAAA,EAGI,YAAY,OACZ,EAAA;AACI,IAAA,KAAA,CAAM,OAAO,CAAA,CAAA;AAJjB,IAAA,IAAA,CAAgB,cAAiB,GAAA,YAAA,CAAA;AAM7B,IAAA,IAAA,CAAK,WAAW,OAAQ,CAAA,QAAA,CAAA;AACxB,IAAK,IAAA,CAAA,aAAA,GAAgB,KAAK,QAAS,CAAA,MAAA,CAAA;AAAA,GACvC;AACJ;;;;"}

View File

@@ -0,0 +1,14 @@
import { TextureSource } from './TextureSource.mjs';
"use strict";
class CompressedSource extends TextureSource {
constructor(options) {
super(options);
this.uploadMethodId = "compressed";
this.resource = options.resource;
this.mipLevelCount = this.resource.length;
}
}
export { CompressedSource };
//# sourceMappingURL=CompressedSource.mjs.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"CompressedSource.mjs","sources":["../../../../../../src/rendering/renderers/shared/texture/sources/CompressedSource.ts"],"sourcesContent":["import { TextureSource } from './TextureSource';\n\nimport type { TextureSourceOptions } from './TextureSource';\n\nexport class CompressedSource extends TextureSource<Uint8Array[]>\n{\n public readonly uploadMethodId = 'compressed';\n\n constructor(options: TextureSourceOptions)\n {\n super(options);\n\n this.resource = options.resource;\n this.mipLevelCount = this.resource.length;\n }\n}\n"],"names":[],"mappings":";;;AAIO,MAAM,yBAAyB,aACtC,CAAA;AAAA,EAGI,YAAY,OACZ,EAAA;AACI,IAAA,KAAA,CAAM,OAAO,CAAA,CAAA;AAJjB,IAAA,IAAA,CAAgB,cAAiB,GAAA,YAAA,CAAA;AAM7B,IAAA,IAAA,CAAK,WAAW,OAAQ,CAAA,QAAA,CAAA;AACxB,IAAK,IAAA,CAAA,aAAA,GAAgB,KAAK,QAAS,CAAA,MAAA,CAAA;AAAA,GACvC;AACJ;;;;"}

View File

@@ -0,0 +1,11 @@
import { TextureSource } from './TextureSource';
import type { ICanvas } from '../../../../../environment/canvas/ICanvas';
import type { ExtensionMetadata } from '../../../../../extensions/Extensions';
import type { TextureSourceOptions } from './TextureSource';
export type ImageResource = ImageBitmap | HTMLCanvasElement | OffscreenCanvas | ICanvas | VideoFrame | HTMLImageElement | HTMLVideoElement;
export declare class ImageSource extends TextureSource<ImageResource> {
static extension: ExtensionMetadata;
uploadMethodId: string;
constructor(options: TextureSourceOptions<ImageResource>);
static test(resource: any): resource is ImageResource;
}

View File

@@ -0,0 +1,29 @@
'use strict';
var adapter = require('../../../../../environment/adapter.js');
var Extensions = require('../../../../../extensions/Extensions.js');
var warn = require('../../../../../utils/logging/warn.js');
var TextureSource = require('./TextureSource.js');
"use strict";
class ImageSource extends TextureSource.TextureSource {
constructor(options) {
if (options.resource && (globalThis.HTMLImageElement && options.resource instanceof HTMLImageElement)) {
const canvas = adapter.DOMAdapter.get().createCanvas(options.resource.width, options.resource.height);
const context = canvas.getContext("2d");
context.drawImage(options.resource, 0, 0, options.resource.width, options.resource.height);
options.resource = canvas;
warn.warn("ImageSource: Image element passed, converting to canvas. Use CanvasSource instead.");
}
super(options);
this.uploadMethodId = "image";
this.autoGarbageCollect = true;
}
static test(resource) {
return globalThis.HTMLImageElement && resource instanceof HTMLImageElement || typeof ImageBitmap !== "undefined" && resource instanceof ImageBitmap || globalThis.VideoFrame && resource instanceof VideoFrame;
}
}
ImageSource.extension = Extensions.ExtensionType.TextureSource;
exports.ImageSource = ImageSource;
//# sourceMappingURL=ImageSource.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"ImageSource.js","sources":["../../../../../../src/rendering/renderers/shared/texture/sources/ImageSource.ts"],"sourcesContent":["import { DOMAdapter } from '../../../../../environment/adapter';\nimport { ExtensionType } from '../../../../../extensions/Extensions';\nimport { warn } from '../../../../../utils/logging/warn';\nimport { TextureSource } from './TextureSource';\n\nimport type { ICanvas } from '../../../../../environment/canvas/ICanvas';\nimport type { ExtensionMetadata } from '../../../../../extensions/Extensions';\nimport type { TextureSourceOptions } from './TextureSource';\n\nexport type ImageResource =\nImageBitmap\n| HTMLCanvasElement\n| OffscreenCanvas\n| ICanvas\n| VideoFrame\n| HTMLImageElement\n| HTMLVideoElement;\n\nexport class ImageSource extends TextureSource<ImageResource>\n{\n public static extension: ExtensionMetadata = ExtensionType.TextureSource;\n public uploadMethodId = 'image';\n\n constructor(options: TextureSourceOptions<ImageResource>)\n {\n if (options.resource && (globalThis.HTMLImageElement && options.resource instanceof HTMLImageElement))\n {\n const canvas = DOMAdapter.get().createCanvas(options.resource.width, options.resource.height);\n const context = canvas.getContext('2d');\n\n context.drawImage(options.resource, 0, 0, options.resource.width, options.resource.height);\n options.resource = canvas;\n\n // #if _DEBUG\n warn('ImageSource: Image element passed, converting to canvas. Use CanvasSource instead.');\n // #endif\n }\n\n super(options);\n\n this.autoGarbageCollect = true;\n }\n\n public static test(resource: any): resource is ImageResource\n {\n return (globalThis.HTMLImageElement && resource instanceof HTMLImageElement)\n || (typeof ImageBitmap !== 'undefined' && resource instanceof ImageBitmap)\n || (globalThis.VideoFrame && resource instanceof VideoFrame);\n }\n}\n"],"names":["TextureSource","DOMAdapter","warn","ExtensionType"],"mappings":";;;;;;;;AAkBO,MAAM,oBAAoBA,2BACjC,CAAA;AAAA,EAII,YAAY,OACZ,EAAA;AACI,IAAA,IAAI,QAAQ,QAAa,KAAA,UAAA,CAAW,gBAAoB,IAAA,OAAA,CAAQ,oBAAoB,gBACpF,CAAA,EAAA;AACI,MAAM,MAAA,MAAA,GAASC,kBAAW,CAAA,GAAA,EAAM,CAAA,YAAA,CAAa,QAAQ,QAAS,CAAA,KAAA,EAAO,OAAQ,CAAA,QAAA,CAAS,MAAM,CAAA,CAAA;AAC5F,MAAM,MAAA,OAAA,GAAU,MAAO,CAAA,UAAA,CAAW,IAAI,CAAA,CAAA;AAEtC,MAAQ,OAAA,CAAA,SAAA,CAAU,OAAQ,CAAA,QAAA,EAAU,CAAG,EAAA,CAAA,EAAG,QAAQ,QAAS,CAAA,KAAA,EAAO,OAAQ,CAAA,QAAA,CAAS,MAAM,CAAA,CAAA;AACzF,MAAA,OAAA,CAAQ,QAAW,GAAA,MAAA,CAAA;AAGnB,MAAAC,SAAA,CAAK,oFAAoF,CAAA,CAAA;AAAA,KAE7F;AAEA,IAAA,KAAA,CAAM,OAAO,CAAA,CAAA;AAjBjB,IAAA,IAAA,CAAO,cAAiB,GAAA,OAAA,CAAA;AAmBpB,IAAA,IAAA,CAAK,kBAAqB,GAAA,IAAA,CAAA;AAAA,GAC9B;AAAA,EAEA,OAAc,KAAK,QACnB,EAAA;AACI,IAAQ,OAAA,UAAA,CAAW,gBAAoB,IAAA,QAAA,YAAoB,gBACvD,IAAA,OAAO,WAAgB,KAAA,WAAA,IAAe,QAAoB,YAAA,WAAA,IAC1D,UAAW,CAAA,UAAA,IAAc,QAAoB,YAAA,UAAA,CAAA;AAAA,GACrD;AACJ,CAAA;AA/Ba,WAAA,CAEK,YAA+BC,wBAAc,CAAA,aAAA;;;;"}

View File

@@ -0,0 +1,27 @@
import { DOMAdapter } from '../../../../../environment/adapter.mjs';
import { ExtensionType } from '../../../../../extensions/Extensions.mjs';
import { warn } from '../../../../../utils/logging/warn.mjs';
import { TextureSource } from './TextureSource.mjs';
"use strict";
class ImageSource extends TextureSource {
constructor(options) {
if (options.resource && (globalThis.HTMLImageElement && options.resource instanceof HTMLImageElement)) {
const canvas = DOMAdapter.get().createCanvas(options.resource.width, options.resource.height);
const context = canvas.getContext("2d");
context.drawImage(options.resource, 0, 0, options.resource.width, options.resource.height);
options.resource = canvas;
warn("ImageSource: Image element passed, converting to canvas. Use CanvasSource instead.");
}
super(options);
this.uploadMethodId = "image";
this.autoGarbageCollect = true;
}
static test(resource) {
return globalThis.HTMLImageElement && resource instanceof HTMLImageElement || typeof ImageBitmap !== "undefined" && resource instanceof ImageBitmap || globalThis.VideoFrame && resource instanceof VideoFrame;
}
}
ImageSource.extension = ExtensionType.TextureSource;
export { ImageSource };
//# sourceMappingURL=ImageSource.mjs.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"ImageSource.mjs","sources":["../../../../../../src/rendering/renderers/shared/texture/sources/ImageSource.ts"],"sourcesContent":["import { DOMAdapter } from '../../../../../environment/adapter';\nimport { ExtensionType } from '../../../../../extensions/Extensions';\nimport { warn } from '../../../../../utils/logging/warn';\nimport { TextureSource } from './TextureSource';\n\nimport type { ICanvas } from '../../../../../environment/canvas/ICanvas';\nimport type { ExtensionMetadata } from '../../../../../extensions/Extensions';\nimport type { TextureSourceOptions } from './TextureSource';\n\nexport type ImageResource =\nImageBitmap\n| HTMLCanvasElement\n| OffscreenCanvas\n| ICanvas\n| VideoFrame\n| HTMLImageElement\n| HTMLVideoElement;\n\nexport class ImageSource extends TextureSource<ImageResource>\n{\n public static extension: ExtensionMetadata = ExtensionType.TextureSource;\n public uploadMethodId = 'image';\n\n constructor(options: TextureSourceOptions<ImageResource>)\n {\n if (options.resource && (globalThis.HTMLImageElement && options.resource instanceof HTMLImageElement))\n {\n const canvas = DOMAdapter.get().createCanvas(options.resource.width, options.resource.height);\n const context = canvas.getContext('2d');\n\n context.drawImage(options.resource, 0, 0, options.resource.width, options.resource.height);\n options.resource = canvas;\n\n // #if _DEBUG\n warn('ImageSource: Image element passed, converting to canvas. Use CanvasSource instead.');\n // #endif\n }\n\n super(options);\n\n this.autoGarbageCollect = true;\n }\n\n public static test(resource: any): resource is ImageResource\n {\n return (globalThis.HTMLImageElement && resource instanceof HTMLImageElement)\n || (typeof ImageBitmap !== 'undefined' && resource instanceof ImageBitmap)\n || (globalThis.VideoFrame && resource instanceof VideoFrame);\n }\n}\n"],"names":[],"mappings":";;;;;;AAkBO,MAAM,oBAAoB,aACjC,CAAA;AAAA,EAII,YAAY,OACZ,EAAA;AACI,IAAA,IAAI,QAAQ,QAAa,KAAA,UAAA,CAAW,gBAAoB,IAAA,OAAA,CAAQ,oBAAoB,gBACpF,CAAA,EAAA;AACI,MAAM,MAAA,MAAA,GAAS,UAAW,CAAA,GAAA,EAAM,CAAA,YAAA,CAAa,QAAQ,QAAS,CAAA,KAAA,EAAO,OAAQ,CAAA,QAAA,CAAS,MAAM,CAAA,CAAA;AAC5F,MAAM,MAAA,OAAA,GAAU,MAAO,CAAA,UAAA,CAAW,IAAI,CAAA,CAAA;AAEtC,MAAQ,OAAA,CAAA,SAAA,CAAU,OAAQ,CAAA,QAAA,EAAU,CAAG,EAAA,CAAA,EAAG,QAAQ,QAAS,CAAA,KAAA,EAAO,OAAQ,CAAA,QAAA,CAAS,MAAM,CAAA,CAAA;AACzF,MAAA,OAAA,CAAQ,QAAW,GAAA,MAAA,CAAA;AAGnB,MAAA,IAAA,CAAK,oFAAoF,CAAA,CAAA;AAAA,KAE7F;AAEA,IAAA,KAAA,CAAM,OAAO,CAAA,CAAA;AAjBjB,IAAA,IAAA,CAAO,cAAiB,GAAA,OAAA,CAAA;AAmBpB,IAAA,IAAA,CAAK,kBAAqB,GAAA,IAAA,CAAA;AAAA,GAC9B;AAAA,EAEA,OAAc,KAAK,QACnB,EAAA;AACI,IAAQ,OAAA,UAAA,CAAW,gBAAoB,IAAA,QAAA,YAAoB,gBACvD,IAAA,OAAO,WAAgB,KAAA,WAAA,IAAe,QAAoB,YAAA,WAAA,IAC1D,UAAW,CAAA,UAAA,IAAc,QAAoB,YAAA,UAAA,CAAA;AAAA,GACrD;AACJ,CAAA;AA/Ba,WAAA,CAEK,YAA+B,aAAc,CAAA,aAAA;;;;"}

View File

@@ -0,0 +1,270 @@
import EventEmitter from 'eventemitter3';
import { TextureStyle } from '../TextureStyle';
import type { BindResource } from '../../../gpu/shader/BindResource';
import type { ALPHA_MODES, SCALE_MODE, TEXTURE_DIMENSIONS, TEXTURE_FORMATS, WRAP_MODE } from '../const';
import type { TextureStyleOptions } from '../TextureStyle';
import type { TextureResourceOrOptions } from '../utils/textureFrom';
/**
* options for creating a new TextureSource
* @memberof rendering
*/
export interface TextureSourceOptions<T extends Record<string, any> = any> extends TextureStyleOptions {
/**
* the resource that will be uploaded to the GPU. This is where we get our pixels from
* eg an ImageBimt / Canvas / Video etc
*/
resource?: T;
/** the pixel width of this texture source. This is the REAL pure number, not accounting resolution */
width?: number;
/** the pixel height of this texture source. This is the REAL pure number, not accounting resolution */
height?: number;
/** the resolution of the texture. */
resolution?: number;
/** the format that the texture data has */
format?: TEXTURE_FORMATS;
/**
* Used by internal textures
* @ignore
*/
sampleCount?: number;
/**
* Only really affects RenderTextures.
* Should we use antialiasing for this texture. It will look better, but may impact performance as a
* Blit operation will be required to resolve the texture.
*/
antialias?: boolean;
/** how many dimensions does this texture have? currently v8 only supports 2d */
dimensions?: TEXTURE_DIMENSIONS;
/** The number of mip levels to generate for this texture. this is overridden if autoGenerateMipmaps is true */
mipLevelCount?: number;
/**
* Should we auto generate mipmaps for this texture? This will automatically generate mipmaps
* for this texture when uploading to the GPU. Mipmapped textures take up more memory, but
* can look better when scaled down.
*
* For performance reasons, it is recommended to NOT use this with RenderTextures, as they are often updated every frame.
* If you do, make sure to call `updateMipmaps` after you update the texture.
*/
autoGenerateMipmaps?: boolean;
/** the alpha mode of the texture */
alphaMode?: ALPHA_MODES;
/** optional label, can be used for debugging */
label?: string;
/** If true, the Garbage Collector will unload this texture if it is not used after a period of time */
autoGarbageCollect?: boolean;
}
/**
* A TextureSource stores the information that represents an image.
* All textures have require TextureSource, which contains information about the source.
* Therefore you can have many textures all using a single TextureSource (eg a sprite sheet)
*
* This is an class is extended depending on the source of the texture.
* Eg if you are using an an image as your resource, then an ImageSource is used.
* @memberof rendering
* @typeParam T - The TextureSource's Resource type.
*/
export declare class TextureSource<T extends Record<string, any> = any> extends EventEmitter<{
change: BindResource;
update: TextureSource;
unload: TextureSource;
destroy: TextureSource;
resize: TextureSource;
styleChange: TextureSource;
updateMipmaps: TextureSource;
error: Error;
}> implements BindResource {
protected readonly options: TextureSourceOptions<T>;
/** The default options used when creating a new TextureSource. override these to add your own defaults */
static defaultOptions: TextureSourceOptions;
/** unique id for this Texture source */
readonly uid: number;
/** optional label, can be used for debugging */
label: string;
/**
* The resource type used by this TextureSource. This is used by the bind groups to determine
* how to handle this resource.
* @ignore
* @internal
*/
readonly _resourceType = "textureSource";
/**
* i unique resource id, used by the bind group systems.
* This can change if the texture is resized or its resource changes
*/
_resourceId: number;
/**
* this is how the backends know how to upload this texture to the GPU
* It changes depending on the resource type. Classes that extend TextureSource
* should override this property.
* @ignore
* @internal
*/
uploadMethodId: string;
_resolution: number;
/** the pixel width of this texture source. This is the REAL pure number, not accounting resolution */
pixelWidth: number;
/** the pixel height of this texture source. This is the REAL pure number, not accounting resolution */
pixelHeight: number;
/**
* the width of this texture source, accounting for resolution
* eg pixelWidth 200, resolution 2, then width will be 100
*/
width: number;
/**
* the height of this texture source, accounting for resolution
* eg pixelHeight 200, resolution 2, then height will be 100
*/
height: number;
/**
* the resource that will be uploaded to the GPU. This is where we get our pixels from
* eg an ImageBimt / Canvas / Video etc
*/
resource: T;
/**
* The number of samples of a multisample texture. This is always 1 for non-multisample textures.
* To enable multisample for a texture, set antialias to true
* @internal
* @ignore
*/
sampleCount: number;
/** The number of mip levels to generate for this texture. this is overridden if autoGenerateMipmaps is true */
mipLevelCount: number;
/**
* Should we auto generate mipmaps for this texture? This will automatically generate mipmaps
* for this texture when uploading to the GPU. Mipmapped textures take up more memory, but
* can look better when scaled down.
*
* For performance reasons, it is recommended to NOT use this with RenderTextures, as they are often updated every frame.
* If you do, make sure to call `updateMipmaps` after you update the texture.
*/
autoGenerateMipmaps: boolean;
/** the format that the texture data has */
format: TEXTURE_FORMATS;
/** how many dimensions does this texture have? currently v8 only supports 2d */
dimension: TEXTURE_DIMENSIONS;
/** the alpha mode of the texture */
alphaMode: ALPHA_MODES;
private _style;
/**
* Only really affects RenderTextures.
* Should we use antialiasing for this texture. It will look better, but may impact performance as a
* Blit operation will be required to resolve the texture.
*/
antialias: boolean;
/**
* Has the source been destroyed?
* @readonly
*/
destroyed: boolean;
/**
* Used by automatic texture Garbage Collection, stores last GC tick when it was bound
* @protected
*/
_touched: number;
/**
* Used by the batcher to build texture batches. faster to have the variable here!
* @protected
*/
_batchTick: number;
/**
* A temporary batch location for the texture batching. Here for performance reasons only!
* @protected
*/
_textureBindLocation: number;
isPowerOfTwo: boolean;
/** If true, the Garbage Collector will unload this texture if it is not used after a period of time */
autoGarbageCollect: boolean;
/**
* used internally to know where a texture came from. Usually assigned by the asset loader!
* @ignore
*/
_sourceOrigin: string;
/**
* @param options - options for creating a new TextureSource
*/
constructor(options?: TextureSourceOptions<T>);
/** returns itself */
get source(): TextureSource;
/** the style of the texture */
get style(): TextureStyle;
set style(value: TextureStyle);
/** setting this will set wrapModeU,wrapModeV and wrapModeW all at once! */
get addressMode(): WRAP_MODE;
set addressMode(value: WRAP_MODE);
/** setting this will set wrapModeU,wrapModeV and wrapModeW all at once! */
get repeatMode(): WRAP_MODE;
set repeatMode(value: WRAP_MODE);
/** Specifies the sampling behavior when the sample footprint is smaller than or equal to one texel. */
get magFilter(): SCALE_MODE;
set magFilter(value: SCALE_MODE);
/** Specifies the sampling behavior when the sample footprint is larger than one texel. */
get minFilter(): SCALE_MODE;
set minFilter(value: SCALE_MODE);
/** Specifies behavior for sampling between mipmap levels. */
get mipmapFilter(): SCALE_MODE;
set mipmapFilter(value: SCALE_MODE);
/** Specifies the minimum and maximum levels of detail, respectively, used internally when sampling a texture. */
get lodMinClamp(): number;
set lodMinClamp(value: number);
/** Specifies the minimum and maximum levels of detail, respectively, used internally when sampling a texture. */
get lodMaxClamp(): number;
set lodMaxClamp(value: number);
private _onStyleChange;
/** call this if you have modified the texture outside of the constructor */
update(): void;
/** Destroys this texture source */
destroy(): void;
/**
* This will unload the Texture source from the GPU. This will free up the GPU memory
* As soon as it is required fore rendering, it will be re-uploaded.
*/
unload(): void;
/** the width of the resource. This is the REAL pure number, not accounting resolution */
get resourceWidth(): number;
/** the height of the resource. This is the REAL pure number, not accounting resolution */
get resourceHeight(): number;
/**
* the resolution of the texture. Changing this number, will not change the number of pixels in the actual texture
* but will the size of the texture when rendered.
*
* changing the resolution of this texture to 2 for example will make it appear twice as small when rendered (as pixel
* density will have increased)
*/
get resolution(): number;
set resolution(resolution: number);
/**
* Resize the texture, this is handy if you want to use the texture as a render texture
* @param width - the new width of the texture
* @param height - the new height of the texture
* @param resolution - the new resolution of the texture
* @returns - if the texture was resized
*/
resize(width?: number, height?: number, resolution?: number): boolean;
/**
* Lets the renderer know that this texture has been updated and its mipmaps should be re-generated.
* This is only important for RenderTexture instances, as standard Texture instances will have their
* mipmaps generated on upload. You should call this method after you make any change to the texture
*
* The reason for this is is can be quite expensive to update mipmaps for a texture. So by default,
* We want you, the developer to specify when this action should happen.
*
* Generally you don't want to have mipmaps generated on Render targets that are changed every frame,
*/
updateMipmaps(): void;
set wrapMode(value: WRAP_MODE);
get wrapMode(): WRAP_MODE;
set scaleMode(value: SCALE_MODE);
/** setting this will set magFilter,minFilter and mipmapFilter all at once! */
get scaleMode(): SCALE_MODE;
/**
* Refresh check for isPowerOfTwo texture based on size
* @private
*/
protected _refreshPOT(): void;
static test(_resource: any): any;
/**
* A helper function that creates a new TextureSource based on the resource you provide.
* @param resource - The resource to create the texture source from.
*/
static from: (resource: TextureResourceOrOptions) => TextureSource;
}

View File

@@ -0,0 +1,334 @@
'use strict';
var EventEmitter = require('eventemitter3');
var pow2 = require('../../../../../maths/misc/pow2.js');
var definedProps = require('../../../../../scene/container/utils/definedProps.js');
var uid = require('../../../../../utils/data/uid.js');
var TextureStyle = require('../TextureStyle.js');
"use strict";
const _TextureSource = class _TextureSource extends EventEmitter {
/**
* @param options - options for creating a new TextureSource
*/
constructor(options = {}) {
super();
this.options = options;
/** unique id for this Texture source */
this.uid = uid.uid("textureSource");
/**
* The resource type used by this TextureSource. This is used by the bind groups to determine
* how to handle this resource.
* @ignore
* @internal
*/
this._resourceType = "textureSource";
/**
* i unique resource id, used by the bind group systems.
* This can change if the texture is resized or its resource changes
*/
this._resourceId = uid.uid("resource");
/**
* this is how the backends know how to upload this texture to the GPU
* It changes depending on the resource type. Classes that extend TextureSource
* should override this property.
* @ignore
* @internal
*/
this.uploadMethodId = "unknown";
// dimensions
this._resolution = 1;
/** the pixel width of this texture source. This is the REAL pure number, not accounting resolution */
this.pixelWidth = 1;
/** the pixel height of this texture source. This is the REAL pure number, not accounting resolution */
this.pixelHeight = 1;
/**
* the width of this texture source, accounting for resolution
* eg pixelWidth 200, resolution 2, then width will be 100
*/
this.width = 1;
/**
* the height of this texture source, accounting for resolution
* eg pixelHeight 200, resolution 2, then height will be 100
*/
this.height = 1;
/**
* The number of samples of a multisample texture. This is always 1 for non-multisample textures.
* To enable multisample for a texture, set antialias to true
* @internal
* @ignore
*/
this.sampleCount = 1;
/** The number of mip levels to generate for this texture. this is overridden if autoGenerateMipmaps is true */
this.mipLevelCount = 1;
/**
* Should we auto generate mipmaps for this texture? This will automatically generate mipmaps
* for this texture when uploading to the GPU. Mipmapped textures take up more memory, but
* can look better when scaled down.
*
* For performance reasons, it is recommended to NOT use this with RenderTextures, as they are often updated every frame.
* If you do, make sure to call `updateMipmaps` after you update the texture.
*/
this.autoGenerateMipmaps = false;
/** the format that the texture data has */
this.format = "rgba8unorm";
/** how many dimensions does this texture have? currently v8 only supports 2d */
this.dimension = "2d";
/**
* Only really affects RenderTextures.
* Should we use antialiasing for this texture. It will look better, but may impact performance as a
* Blit operation will be required to resolve the texture.
*/
this.antialias = false;
/**
* Used by automatic texture Garbage Collection, stores last GC tick when it was bound
* @protected
*/
this._touched = 0;
/**
* Used by the batcher to build texture batches. faster to have the variable here!
* @protected
*/
this._batchTick = -1;
/**
* A temporary batch location for the texture batching. Here for performance reasons only!
* @protected
*/
this._textureBindLocation = -1;
options = { ..._TextureSource.defaultOptions, ...options };
this.label = options.label ?? "";
this.resource = options.resource;
this.autoGarbageCollect = options.autoGarbageCollect;
this._resolution = options.resolution;
if (options.width) {
this.pixelWidth = options.width * this._resolution;
} else {
this.pixelWidth = this.resource ? this.resourceWidth ?? 1 : 1;
}
if (options.height) {
this.pixelHeight = options.height * this._resolution;
} else {
this.pixelHeight = this.resource ? this.resourceHeight ?? 1 : 1;
}
this.width = this.pixelWidth / this._resolution;
this.height = this.pixelHeight / this._resolution;
this.format = options.format;
this.dimension = options.dimensions;
this.mipLevelCount = options.mipLevelCount;
this.autoGenerateMipmaps = options.autoGenerateMipmaps;
this.sampleCount = options.sampleCount;
this.antialias = options.antialias;
this.alphaMode = options.alphaMode;
this.style = new TextureStyle.TextureStyle(definedProps.definedProps(options));
this.destroyed = false;
this._refreshPOT();
}
/** returns itself */
get source() {
return this;
}
/** the style of the texture */
get style() {
return this._style;
}
set style(value) {
if (this.style === value)
return;
this._style?.off("change", this._onStyleChange, this);
this._style = value;
this._style?.on("change", this._onStyleChange, this);
this._onStyleChange();
}
/** setting this will set wrapModeU,wrapModeV and wrapModeW all at once! */
get addressMode() {
return this._style.addressMode;
}
set addressMode(value) {
this._style.addressMode = value;
}
/** setting this will set wrapModeU,wrapModeV and wrapModeW all at once! */
get repeatMode() {
return this._style.addressMode;
}
set repeatMode(value) {
this._style.addressMode = value;
}
/** Specifies the sampling behavior when the sample footprint is smaller than or equal to one texel. */
get magFilter() {
return this._style.magFilter;
}
set magFilter(value) {
this._style.magFilter = value;
}
/** Specifies the sampling behavior when the sample footprint is larger than one texel. */
get minFilter() {
return this._style.minFilter;
}
set minFilter(value) {
this._style.minFilter = value;
}
/** Specifies behavior for sampling between mipmap levels. */
get mipmapFilter() {
return this._style.mipmapFilter;
}
set mipmapFilter(value) {
this._style.mipmapFilter = value;
}
/** Specifies the minimum and maximum levels of detail, respectively, used internally when sampling a texture. */
get lodMinClamp() {
return this._style.lodMinClamp;
}
set lodMinClamp(value) {
this._style.lodMinClamp = value;
}
/** Specifies the minimum and maximum levels of detail, respectively, used internally when sampling a texture. */
get lodMaxClamp() {
return this._style.lodMaxClamp;
}
set lodMaxClamp(value) {
this._style.lodMaxClamp = value;
}
_onStyleChange() {
this.emit("styleChange", this);
}
/** call this if you have modified the texture outside of the constructor */
update() {
if (this.resource) {
const resolution = this._resolution;
const didResize = this.resize(this.resourceWidth / resolution, this.resourceHeight / resolution);
if (didResize)
return;
}
this.emit("update", this);
}
/** Destroys this texture source */
destroy() {
this.destroyed = true;
this.emit("destroy", this);
this.emit("change", this);
if (this._style) {
this._style.destroy();
this._style = null;
}
this.uploadMethodId = null;
this.resource = null;
this.removeAllListeners();
}
/**
* This will unload the Texture source from the GPU. This will free up the GPU memory
* As soon as it is required fore rendering, it will be re-uploaded.
*/
unload() {
this._resourceId = uid.uid("resource");
this.emit("change", this);
this.emit("unload", this);
}
/** the width of the resource. This is the REAL pure number, not accounting resolution */
get resourceWidth() {
const { resource } = this;
return resource.naturalWidth || resource.videoWidth || resource.displayWidth || resource.width;
}
/** the height of the resource. This is the REAL pure number, not accounting resolution */
get resourceHeight() {
const { resource } = this;
return resource.naturalHeight || resource.videoHeight || resource.displayHeight || resource.height;
}
/**
* the resolution of the texture. Changing this number, will not change the number of pixels in the actual texture
* but will the size of the texture when rendered.
*
* changing the resolution of this texture to 2 for example will make it appear twice as small when rendered (as pixel
* density will have increased)
*/
get resolution() {
return this._resolution;
}
set resolution(resolution) {
if (this._resolution === resolution)
return;
this._resolution = resolution;
this.width = this.pixelWidth / resolution;
this.height = this.pixelHeight / resolution;
}
/**
* Resize the texture, this is handy if you want to use the texture as a render texture
* @param width - the new width of the texture
* @param height - the new height of the texture
* @param resolution - the new resolution of the texture
* @returns - if the texture was resized
*/
resize(width, height, resolution) {
resolution = resolution || this._resolution;
width = width || this.width;
height = height || this.height;
const newPixelWidth = Math.round(width * resolution);
const newPixelHeight = Math.round(height * resolution);
this.width = newPixelWidth / resolution;
this.height = newPixelHeight / resolution;
this._resolution = resolution;
if (this.pixelWidth === newPixelWidth && this.pixelHeight === newPixelHeight) {
return false;
}
this._refreshPOT();
this.pixelWidth = newPixelWidth;
this.pixelHeight = newPixelHeight;
this.emit("resize", this);
this._resourceId = uid.uid("resource");
this.emit("change", this);
return true;
}
/**
* Lets the renderer know that this texture has been updated and its mipmaps should be re-generated.
* This is only important for RenderTexture instances, as standard Texture instances will have their
* mipmaps generated on upload. You should call this method after you make any change to the texture
*
* The reason for this is is can be quite expensive to update mipmaps for a texture. So by default,
* We want you, the developer to specify when this action should happen.
*
* Generally you don't want to have mipmaps generated on Render targets that are changed every frame,
*/
updateMipmaps() {
if (this.autoGenerateMipmaps && this.mipLevelCount > 1) {
this.emit("updateMipmaps", this);
}
}
set wrapMode(value) {
this._style.wrapMode = value;
}
get wrapMode() {
return this._style.wrapMode;
}
set scaleMode(value) {
this._style.scaleMode = value;
}
/** setting this will set magFilter,minFilter and mipmapFilter all at once! */
get scaleMode() {
return this._style.scaleMode;
}
/**
* Refresh check for isPowerOfTwo texture based on size
* @private
*/
_refreshPOT() {
this.isPowerOfTwo = pow2.isPow2(this.pixelWidth) && pow2.isPow2(this.pixelHeight);
}
static test(_resource) {
throw new Error("Unimplemented");
}
};
/** The default options used when creating a new TextureSource. override these to add your own defaults */
_TextureSource.defaultOptions = {
resolution: 1,
format: "bgra8unorm",
alphaMode: "premultiply-alpha-on-upload",
dimensions: "2d",
mipLevelCount: 1,
autoGenerateMipmaps: false,
sampleCount: 1,
antialias: false,
autoGarbageCollect: false
};
let TextureSource = _TextureSource;
exports.TextureSource = TextureSource;
//# sourceMappingURL=TextureSource.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,332 @@
import EventEmitter from 'eventemitter3';
import { isPow2 } from '../../../../../maths/misc/pow2.mjs';
import { definedProps } from '../../../../../scene/container/utils/definedProps.mjs';
import { uid } from '../../../../../utils/data/uid.mjs';
import { TextureStyle } from '../TextureStyle.mjs';
"use strict";
const _TextureSource = class _TextureSource extends EventEmitter {
/**
* @param options - options for creating a new TextureSource
*/
constructor(options = {}) {
super();
this.options = options;
/** unique id for this Texture source */
this.uid = uid("textureSource");
/**
* The resource type used by this TextureSource. This is used by the bind groups to determine
* how to handle this resource.
* @ignore
* @internal
*/
this._resourceType = "textureSource";
/**
* i unique resource id, used by the bind group systems.
* This can change if the texture is resized or its resource changes
*/
this._resourceId = uid("resource");
/**
* this is how the backends know how to upload this texture to the GPU
* It changes depending on the resource type. Classes that extend TextureSource
* should override this property.
* @ignore
* @internal
*/
this.uploadMethodId = "unknown";
// dimensions
this._resolution = 1;
/** the pixel width of this texture source. This is the REAL pure number, not accounting resolution */
this.pixelWidth = 1;
/** the pixel height of this texture source. This is the REAL pure number, not accounting resolution */
this.pixelHeight = 1;
/**
* the width of this texture source, accounting for resolution
* eg pixelWidth 200, resolution 2, then width will be 100
*/
this.width = 1;
/**
* the height of this texture source, accounting for resolution
* eg pixelHeight 200, resolution 2, then height will be 100
*/
this.height = 1;
/**
* The number of samples of a multisample texture. This is always 1 for non-multisample textures.
* To enable multisample for a texture, set antialias to true
* @internal
* @ignore
*/
this.sampleCount = 1;
/** The number of mip levels to generate for this texture. this is overridden if autoGenerateMipmaps is true */
this.mipLevelCount = 1;
/**
* Should we auto generate mipmaps for this texture? This will automatically generate mipmaps
* for this texture when uploading to the GPU. Mipmapped textures take up more memory, but
* can look better when scaled down.
*
* For performance reasons, it is recommended to NOT use this with RenderTextures, as they are often updated every frame.
* If you do, make sure to call `updateMipmaps` after you update the texture.
*/
this.autoGenerateMipmaps = false;
/** the format that the texture data has */
this.format = "rgba8unorm";
/** how many dimensions does this texture have? currently v8 only supports 2d */
this.dimension = "2d";
/**
* Only really affects RenderTextures.
* Should we use antialiasing for this texture. It will look better, but may impact performance as a
* Blit operation will be required to resolve the texture.
*/
this.antialias = false;
/**
* Used by automatic texture Garbage Collection, stores last GC tick when it was bound
* @protected
*/
this._touched = 0;
/**
* Used by the batcher to build texture batches. faster to have the variable here!
* @protected
*/
this._batchTick = -1;
/**
* A temporary batch location for the texture batching. Here for performance reasons only!
* @protected
*/
this._textureBindLocation = -1;
options = { ..._TextureSource.defaultOptions, ...options };
this.label = options.label ?? "";
this.resource = options.resource;
this.autoGarbageCollect = options.autoGarbageCollect;
this._resolution = options.resolution;
if (options.width) {
this.pixelWidth = options.width * this._resolution;
} else {
this.pixelWidth = this.resource ? this.resourceWidth ?? 1 : 1;
}
if (options.height) {
this.pixelHeight = options.height * this._resolution;
} else {
this.pixelHeight = this.resource ? this.resourceHeight ?? 1 : 1;
}
this.width = this.pixelWidth / this._resolution;
this.height = this.pixelHeight / this._resolution;
this.format = options.format;
this.dimension = options.dimensions;
this.mipLevelCount = options.mipLevelCount;
this.autoGenerateMipmaps = options.autoGenerateMipmaps;
this.sampleCount = options.sampleCount;
this.antialias = options.antialias;
this.alphaMode = options.alphaMode;
this.style = new TextureStyle(definedProps(options));
this.destroyed = false;
this._refreshPOT();
}
/** returns itself */
get source() {
return this;
}
/** the style of the texture */
get style() {
return this._style;
}
set style(value) {
if (this.style === value)
return;
this._style?.off("change", this._onStyleChange, this);
this._style = value;
this._style?.on("change", this._onStyleChange, this);
this._onStyleChange();
}
/** setting this will set wrapModeU,wrapModeV and wrapModeW all at once! */
get addressMode() {
return this._style.addressMode;
}
set addressMode(value) {
this._style.addressMode = value;
}
/** setting this will set wrapModeU,wrapModeV and wrapModeW all at once! */
get repeatMode() {
return this._style.addressMode;
}
set repeatMode(value) {
this._style.addressMode = value;
}
/** Specifies the sampling behavior when the sample footprint is smaller than or equal to one texel. */
get magFilter() {
return this._style.magFilter;
}
set magFilter(value) {
this._style.magFilter = value;
}
/** Specifies the sampling behavior when the sample footprint is larger than one texel. */
get minFilter() {
return this._style.minFilter;
}
set minFilter(value) {
this._style.minFilter = value;
}
/** Specifies behavior for sampling between mipmap levels. */
get mipmapFilter() {
return this._style.mipmapFilter;
}
set mipmapFilter(value) {
this._style.mipmapFilter = value;
}
/** Specifies the minimum and maximum levels of detail, respectively, used internally when sampling a texture. */
get lodMinClamp() {
return this._style.lodMinClamp;
}
set lodMinClamp(value) {
this._style.lodMinClamp = value;
}
/** Specifies the minimum and maximum levels of detail, respectively, used internally when sampling a texture. */
get lodMaxClamp() {
return this._style.lodMaxClamp;
}
set lodMaxClamp(value) {
this._style.lodMaxClamp = value;
}
_onStyleChange() {
this.emit("styleChange", this);
}
/** call this if you have modified the texture outside of the constructor */
update() {
if (this.resource) {
const resolution = this._resolution;
const didResize = this.resize(this.resourceWidth / resolution, this.resourceHeight / resolution);
if (didResize)
return;
}
this.emit("update", this);
}
/** Destroys this texture source */
destroy() {
this.destroyed = true;
this.emit("destroy", this);
this.emit("change", this);
if (this._style) {
this._style.destroy();
this._style = null;
}
this.uploadMethodId = null;
this.resource = null;
this.removeAllListeners();
}
/**
* This will unload the Texture source from the GPU. This will free up the GPU memory
* As soon as it is required fore rendering, it will be re-uploaded.
*/
unload() {
this._resourceId = uid("resource");
this.emit("change", this);
this.emit("unload", this);
}
/** the width of the resource. This is the REAL pure number, not accounting resolution */
get resourceWidth() {
const { resource } = this;
return resource.naturalWidth || resource.videoWidth || resource.displayWidth || resource.width;
}
/** the height of the resource. This is the REAL pure number, not accounting resolution */
get resourceHeight() {
const { resource } = this;
return resource.naturalHeight || resource.videoHeight || resource.displayHeight || resource.height;
}
/**
* the resolution of the texture. Changing this number, will not change the number of pixels in the actual texture
* but will the size of the texture when rendered.
*
* changing the resolution of this texture to 2 for example will make it appear twice as small when rendered (as pixel
* density will have increased)
*/
get resolution() {
return this._resolution;
}
set resolution(resolution) {
if (this._resolution === resolution)
return;
this._resolution = resolution;
this.width = this.pixelWidth / resolution;
this.height = this.pixelHeight / resolution;
}
/**
* Resize the texture, this is handy if you want to use the texture as a render texture
* @param width - the new width of the texture
* @param height - the new height of the texture
* @param resolution - the new resolution of the texture
* @returns - if the texture was resized
*/
resize(width, height, resolution) {
resolution = resolution || this._resolution;
width = width || this.width;
height = height || this.height;
const newPixelWidth = Math.round(width * resolution);
const newPixelHeight = Math.round(height * resolution);
this.width = newPixelWidth / resolution;
this.height = newPixelHeight / resolution;
this._resolution = resolution;
if (this.pixelWidth === newPixelWidth && this.pixelHeight === newPixelHeight) {
return false;
}
this._refreshPOT();
this.pixelWidth = newPixelWidth;
this.pixelHeight = newPixelHeight;
this.emit("resize", this);
this._resourceId = uid("resource");
this.emit("change", this);
return true;
}
/**
* Lets the renderer know that this texture has been updated and its mipmaps should be re-generated.
* This is only important for RenderTexture instances, as standard Texture instances will have their
* mipmaps generated on upload. You should call this method after you make any change to the texture
*
* The reason for this is is can be quite expensive to update mipmaps for a texture. So by default,
* We want you, the developer to specify when this action should happen.
*
* Generally you don't want to have mipmaps generated on Render targets that are changed every frame,
*/
updateMipmaps() {
if (this.autoGenerateMipmaps && this.mipLevelCount > 1) {
this.emit("updateMipmaps", this);
}
}
set wrapMode(value) {
this._style.wrapMode = value;
}
get wrapMode() {
return this._style.wrapMode;
}
set scaleMode(value) {
this._style.scaleMode = value;
}
/** setting this will set magFilter,minFilter and mipmapFilter all at once! */
get scaleMode() {
return this._style.scaleMode;
}
/**
* Refresh check for isPowerOfTwo texture based on size
* @private
*/
_refreshPOT() {
this.isPowerOfTwo = isPow2(this.pixelWidth) && isPow2(this.pixelHeight);
}
static test(_resource) {
throw new Error("Unimplemented");
}
};
/** The default options used when creating a new TextureSource. override these to add your own defaults */
_TextureSource.defaultOptions = {
resolution: 1,
format: "bgra8unorm",
alphaMode: "premultiply-alpha-on-upload",
dimensions: "2d",
mipLevelCount: 1,
autoGenerateMipmaps: false,
sampleCount: 1,
antialias: false,
autoGarbageCollect: false
};
let TextureSource = _TextureSource;
export { TextureSource };
//# sourceMappingURL=TextureSource.mjs.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,149 @@
import { TextureSource } from './TextureSource';
import type { ExtensionMetadata } from '../../../../../extensions/Extensions';
import type { Dict } from '../../../../../utils/types';
import type { ALPHA_MODES } from '../const';
import type { TextureSourceOptions } from './TextureSource';
type VideoResource = HTMLVideoElement;
/**
* Options for video sources.
* @memberof rendering
*/
export interface VideoSourceOptions extends TextureSourceOptions<VideoResource> {
/** If true, the video will start loading immediately. */
autoLoad?: boolean;
/** If true, the video will start playing as soon as it is loaded. */
autoPlay?: boolean;
/** The number of times a second to update the texture from the video. Leave at 0 to update at every render. */
updateFPS?: number;
/** If true, the video will be loaded with the `crossorigin` attribute. */
crossorigin?: boolean | string;
/** If true, the video will loop when it ends. */
loop?: boolean;
/** If true, the video will be muted. */
muted?: boolean;
/** If true, the video will play inline. */
playsinline?: boolean;
/** If true, the video will be preloaded. */
preload?: boolean;
/** The time in milliseconds to wait for the video to preload before timing out. */
preloadTimeoutMs?: number;
/** The alpha mode of the video. */
alphaMode?: ALPHA_MODES;
}
export interface VideoResourceOptionsElement {
src: string;
mime: string;
}
/**
* A source for video-based textures.
* @memberof rendering
*/
export declare class VideoSource extends TextureSource<VideoResource> {
static extension: ExtensionMetadata;
/** The default options for video sources. */
static defaultOptions: VideoSourceOptions;
/** Whether or not the video is ready to play. */
isReady: boolean;
/** The upload method for this texture. */
uploadMethodId: string;
/**
* When set to true will automatically play videos used by this texture once
* they are loaded. If false, it will not modify the playing state.
* @default true
*/
protected autoPlay: boolean;
/**
* `true` to use Ticker.shared to auto update the base texture.
* @default true
*/
private _autoUpdate;
/**
* `true` if the instance is currently connected to Ticker.shared to auto update the base texture.
* @default false
*/
private _isConnectedToTicker;
/**
* Promise when loading.
* @default null
*/
private _load;
private _msToNextUpdate;
private _preloadTimeout;
/** Callback when completed with load. */
private _resolve;
private _reject;
private _updateFPS;
private _videoFrameRequestCallbackHandle;
constructor(options: VideoSourceOptions);
/** Update the video frame if the source is not destroyed and meets certain conditions. */
protected updateFrame(): void;
/** Callback to update the video frame and potentially request the next frame update. */
private _videoFrameRequestCallback;
/**
* Checks if the resource has valid dimensions.
* @returns {boolean} True if width and height are set, otherwise false.
*/
get isValid(): boolean;
/**
* Start preloading the video resource.
* @returns {Promise<this>} Handle the validate event
*/
load(): Promise<this>;
/**
* Handle video error events.
* @param event - The error event
*/
private _onError;
/**
* Checks if the underlying source is playing.
* @returns True if playing.
*/
private _isSourcePlaying;
/**
* Checks if the underlying source is ready for playing.
* @returns True if ready.
*/
private _isSourceReady;
/** Runs the update loop when the video is ready to play. */
private _onPlayStart;
/** Stops the update loop when a pause event is triggered. */
private _onPlayStop;
/** Handles behavior when the video completes seeking to the current playback position. */
private _onSeeked;
private _onCanPlay;
private _onCanPlayThrough;
/** Fired when the video is loaded and ready to play. */
private _mediaReady;
/** Cleans up resources and event listeners associated with this texture. */
destroy(): void;
/** Should the base texture automatically update itself, set to true by default. */
get autoUpdate(): boolean;
set autoUpdate(value: boolean);
/**
* How many times a second to update the texture from the video.
* Leave at 0 to update at every render.
* A lower fps can help performance, as updating the texture at 60fps on a 30ps video may not be efficient.
*/
get updateFPS(): number;
set updateFPS(value: number);
/**
* Configures the updating mechanism based on the current state and settings.
*
* This method decides between using the browser's native video frame callback or a custom ticker
* for updating the video frame. It ensures optimal performance and responsiveness
* based on the video's state, playback status, and the desired frames-per-second setting.
*
* - If `_autoUpdate` is enabled and the video source is playing:
* - It will prefer the native video frame callback if available and no specific FPS is set.
* - Otherwise, it will use a custom ticker for manual updates.
* - If `_autoUpdate` is disabled or the video isn't playing, any active update mechanisms are halted.
*/
private _configureAutoUpdate;
/**
* Map of video MIME types that can't be directly derived from file extensions.
* @readonly
*/
static MIME_TYPES: Dict<string>;
static test(resource: any): resource is VideoResource;
}
export {};

View File

@@ -0,0 +1,327 @@
'use strict';
var Extensions = require('../../../../../extensions/Extensions.js');
var Ticker = require('../../../../../ticker/Ticker.js');
var detectVideoAlphaMode = require('../../../../../utils/browser/detectVideoAlphaMode.js');
var TextureSource = require('./TextureSource.js');
"use strict";
const _VideoSource = class _VideoSource extends TextureSource.TextureSource {
constructor(options) {
super(options);
// Public
/** Whether or not the video is ready to play. */
this.isReady = false;
/** The upload method for this texture. */
this.uploadMethodId = "video";
options = {
..._VideoSource.defaultOptions,
...options
};
this._autoUpdate = true;
this._isConnectedToTicker = false;
this._updateFPS = options.updateFPS || 0;
this._msToNextUpdate = 0;
this.autoPlay = options.autoPlay !== false;
this.alphaMode = options.alphaMode ?? "premultiply-alpha-on-upload";
this._videoFrameRequestCallback = this._videoFrameRequestCallback.bind(this);
this._videoFrameRequestCallbackHandle = null;
this._load = null;
this._resolve = null;
this._reject = null;
this._onCanPlay = this._onCanPlay.bind(this);
this._onCanPlayThrough = this._onCanPlayThrough.bind(this);
this._onError = this._onError.bind(this);
this._onPlayStart = this._onPlayStart.bind(this);
this._onPlayStop = this._onPlayStop.bind(this);
this._onSeeked = this._onSeeked.bind(this);
if (options.autoLoad !== false) {
void this.load();
}
}
/** Update the video frame if the source is not destroyed and meets certain conditions. */
updateFrame() {
if (this.destroyed) {
return;
}
if (this._updateFPS) {
const elapsedMS = Ticker.Ticker.shared.elapsedMS * this.resource.playbackRate;
this._msToNextUpdate = Math.floor(this._msToNextUpdate - elapsedMS);
}
if (!this._updateFPS || this._msToNextUpdate <= 0) {
this._msToNextUpdate = this._updateFPS ? Math.floor(1e3 / this._updateFPS) : 0;
}
if (this.isValid) {
this.update();
}
}
/** Callback to update the video frame and potentially request the next frame update. */
_videoFrameRequestCallback() {
this.updateFrame();
if (this.destroyed) {
this._videoFrameRequestCallbackHandle = null;
} else {
this._videoFrameRequestCallbackHandle = this.resource.requestVideoFrameCallback(
this._videoFrameRequestCallback
);
}
}
/**
* Checks if the resource has valid dimensions.
* @returns {boolean} True if width and height are set, otherwise false.
*/
get isValid() {
return !!this.resource.videoWidth && !!this.resource.videoHeight;
}
/**
* Start preloading the video resource.
* @returns {Promise<this>} Handle the validate event
*/
async load() {
if (this._load) {
return this._load;
}
const source = this.resource;
const options = this.options;
if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) {
source.complete = true;
}
source.addEventListener("play", this._onPlayStart);
source.addEventListener("pause", this._onPlayStop);
source.addEventListener("seeked", this._onSeeked);
if (!this._isSourceReady()) {
if (!options.preload) {
source.addEventListener("canplay", this._onCanPlay);
}
source.addEventListener("canplaythrough", this._onCanPlayThrough);
source.addEventListener("error", this._onError, true);
} else {
this._mediaReady();
}
this.alphaMode = await detectVideoAlphaMode.detectVideoAlphaMode();
this._load = new Promise((resolve, reject) => {
if (this.isValid) {
resolve(this);
} else {
this._resolve = resolve;
this._reject = reject;
if (options.preloadTimeoutMs !== void 0) {
this._preloadTimeout = setTimeout(() => {
this._onError(new ErrorEvent(`Preload exceeded timeout of ${options.preloadTimeoutMs}ms`));
});
}
source.load();
}
});
return this._load;
}
/**
* Handle video error events.
* @param event - The error event
*/
_onError(event) {
this.resource.removeEventListener("error", this._onError, true);
this.emit("error", event);
if (this._reject) {
this._reject(event);
this._reject = null;
this._resolve = null;
}
}
/**
* Checks if the underlying source is playing.
* @returns True if playing.
*/
_isSourcePlaying() {
const source = this.resource;
return !source.paused && !source.ended;
}
/**
* Checks if the underlying source is ready for playing.
* @returns True if ready.
*/
_isSourceReady() {
const source = this.resource;
return source.readyState > 2;
}
/** Runs the update loop when the video is ready to play. */
_onPlayStart() {
if (!this.isValid) {
this._mediaReady();
}
this._configureAutoUpdate();
}
/** Stops the update loop when a pause event is triggered. */
_onPlayStop() {
this._configureAutoUpdate();
}
/** Handles behavior when the video completes seeking to the current playback position. */
_onSeeked() {
if (this._autoUpdate && !this._isSourcePlaying()) {
this._msToNextUpdate = 0;
this.updateFrame();
this._msToNextUpdate = 0;
}
}
_onCanPlay() {
const source = this.resource;
source.removeEventListener("canplay", this._onCanPlay);
this._mediaReady();
}
_onCanPlayThrough() {
const source = this.resource;
source.removeEventListener("canplaythrough", this._onCanPlay);
if (this._preloadTimeout) {
clearTimeout(this._preloadTimeout);
this._preloadTimeout = void 0;
}
this._mediaReady();
}
/** Fired when the video is loaded and ready to play. */
_mediaReady() {
const source = this.resource;
if (this.isValid) {
this.isReady = true;
this.resize(source.videoWidth, source.videoHeight);
}
this._msToNextUpdate = 0;
this.updateFrame();
this._msToNextUpdate = 0;
if (this._resolve) {
this._resolve(this);
this._resolve = null;
this._reject = null;
}
if (this._isSourcePlaying()) {
this._onPlayStart();
} else if (this.autoPlay) {
void this.resource.play();
}
}
/** Cleans up resources and event listeners associated with this texture. */
destroy() {
this._configureAutoUpdate();
const source = this.resource;
if (source) {
source.removeEventListener("play", this._onPlayStart);
source.removeEventListener("pause", this._onPlayStop);
source.removeEventListener("seeked", this._onSeeked);
source.removeEventListener("canplay", this._onCanPlay);
source.removeEventListener("canplaythrough", this._onCanPlayThrough);
source.removeEventListener("error", this._onError, true);
source.pause();
source.src = "";
source.load();
}
super.destroy();
}
/** Should the base texture automatically update itself, set to true by default. */
get autoUpdate() {
return this._autoUpdate;
}
set autoUpdate(value) {
if (value !== this._autoUpdate) {
this._autoUpdate = value;
this._configureAutoUpdate();
}
}
/**
* How many times a second to update the texture from the video.
* Leave at 0 to update at every render.
* A lower fps can help performance, as updating the texture at 60fps on a 30ps video may not be efficient.
*/
get updateFPS() {
return this._updateFPS;
}
set updateFPS(value) {
if (value !== this._updateFPS) {
this._updateFPS = value;
this._configureAutoUpdate();
}
}
/**
* Configures the updating mechanism based on the current state and settings.
*
* This method decides between using the browser's native video frame callback or a custom ticker
* for updating the video frame. It ensures optimal performance and responsiveness
* based on the video's state, playback status, and the desired frames-per-second setting.
*
* - If `_autoUpdate` is enabled and the video source is playing:
* - It will prefer the native video frame callback if available and no specific FPS is set.
* - Otherwise, it will use a custom ticker for manual updates.
* - If `_autoUpdate` is disabled or the video isn't playing, any active update mechanisms are halted.
*/
_configureAutoUpdate() {
if (this._autoUpdate && this._isSourcePlaying()) {
if (!this._updateFPS && this.resource.requestVideoFrameCallback) {
if (this._isConnectedToTicker) {
Ticker.Ticker.shared.remove(this.updateFrame, this);
this._isConnectedToTicker = false;
this._msToNextUpdate = 0;
}
if (this._videoFrameRequestCallbackHandle === null) {
this._videoFrameRequestCallbackHandle = this.resource.requestVideoFrameCallback(
this._videoFrameRequestCallback
);
}
} else {
if (this._videoFrameRequestCallbackHandle !== null) {
this.resource.cancelVideoFrameCallback(this._videoFrameRequestCallbackHandle);
this._videoFrameRequestCallbackHandle = null;
}
if (!this._isConnectedToTicker) {
Ticker.Ticker.shared.add(this.updateFrame, this);
this._isConnectedToTicker = true;
this._msToNextUpdate = 0;
}
}
} else {
if (this._videoFrameRequestCallbackHandle !== null) {
this.resource.cancelVideoFrameCallback(this._videoFrameRequestCallbackHandle);
this._videoFrameRequestCallbackHandle = null;
}
if (this._isConnectedToTicker) {
Ticker.Ticker.shared.remove(this.updateFrame, this);
this._isConnectedToTicker = false;
this._msToNextUpdate = 0;
}
}
}
static test(resource) {
return globalThis.HTMLVideoElement && resource instanceof HTMLVideoElement;
}
};
_VideoSource.extension = Extensions.ExtensionType.TextureSource;
/** The default options for video sources. */
_VideoSource.defaultOptions = {
...TextureSource.TextureSource.defaultOptions,
/** If true, the video will start loading immediately. */
autoLoad: true,
/** If true, the video will start playing as soon as it is loaded. */
autoPlay: true,
/** The number of times a second to update the texture from the video. Leave at 0 to update at every render. */
updateFPS: 0,
/** If true, the video will be loaded with the `crossorigin` attribute. */
crossorigin: true,
/** If true, the video will loop when it ends. */
loop: false,
/** If true, the video will be muted. */
muted: true,
/** If true, the video will play inline. */
playsinline: true,
/** If true, the video will be preloaded. */
preload: false
};
/**
* Map of video MIME types that can't be directly derived from file extensions.
* @readonly
*/
_VideoSource.MIME_TYPES = {
ogv: "video/ogg",
mov: "video/quicktime",
m4v: "video/mp4"
};
let VideoSource = _VideoSource;
exports.VideoSource = VideoSource;
//# sourceMappingURL=VideoSource.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,325 @@
import { ExtensionType } from '../../../../../extensions/Extensions.mjs';
import { Ticker } from '../../../../../ticker/Ticker.mjs';
import { detectVideoAlphaMode } from '../../../../../utils/browser/detectVideoAlphaMode.mjs';
import { TextureSource } from './TextureSource.mjs';
"use strict";
const _VideoSource = class _VideoSource extends TextureSource {
constructor(options) {
super(options);
// Public
/** Whether or not the video is ready to play. */
this.isReady = false;
/** The upload method for this texture. */
this.uploadMethodId = "video";
options = {
..._VideoSource.defaultOptions,
...options
};
this._autoUpdate = true;
this._isConnectedToTicker = false;
this._updateFPS = options.updateFPS || 0;
this._msToNextUpdate = 0;
this.autoPlay = options.autoPlay !== false;
this.alphaMode = options.alphaMode ?? "premultiply-alpha-on-upload";
this._videoFrameRequestCallback = this._videoFrameRequestCallback.bind(this);
this._videoFrameRequestCallbackHandle = null;
this._load = null;
this._resolve = null;
this._reject = null;
this._onCanPlay = this._onCanPlay.bind(this);
this._onCanPlayThrough = this._onCanPlayThrough.bind(this);
this._onError = this._onError.bind(this);
this._onPlayStart = this._onPlayStart.bind(this);
this._onPlayStop = this._onPlayStop.bind(this);
this._onSeeked = this._onSeeked.bind(this);
if (options.autoLoad !== false) {
void this.load();
}
}
/** Update the video frame if the source is not destroyed and meets certain conditions. */
updateFrame() {
if (this.destroyed) {
return;
}
if (this._updateFPS) {
const elapsedMS = Ticker.shared.elapsedMS * this.resource.playbackRate;
this._msToNextUpdate = Math.floor(this._msToNextUpdate - elapsedMS);
}
if (!this._updateFPS || this._msToNextUpdate <= 0) {
this._msToNextUpdate = this._updateFPS ? Math.floor(1e3 / this._updateFPS) : 0;
}
if (this.isValid) {
this.update();
}
}
/** Callback to update the video frame and potentially request the next frame update. */
_videoFrameRequestCallback() {
this.updateFrame();
if (this.destroyed) {
this._videoFrameRequestCallbackHandle = null;
} else {
this._videoFrameRequestCallbackHandle = this.resource.requestVideoFrameCallback(
this._videoFrameRequestCallback
);
}
}
/**
* Checks if the resource has valid dimensions.
* @returns {boolean} True if width and height are set, otherwise false.
*/
get isValid() {
return !!this.resource.videoWidth && !!this.resource.videoHeight;
}
/**
* Start preloading the video resource.
* @returns {Promise<this>} Handle the validate event
*/
async load() {
if (this._load) {
return this._load;
}
const source = this.resource;
const options = this.options;
if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) {
source.complete = true;
}
source.addEventListener("play", this._onPlayStart);
source.addEventListener("pause", this._onPlayStop);
source.addEventListener("seeked", this._onSeeked);
if (!this._isSourceReady()) {
if (!options.preload) {
source.addEventListener("canplay", this._onCanPlay);
}
source.addEventListener("canplaythrough", this._onCanPlayThrough);
source.addEventListener("error", this._onError, true);
} else {
this._mediaReady();
}
this.alphaMode = await detectVideoAlphaMode();
this._load = new Promise((resolve, reject) => {
if (this.isValid) {
resolve(this);
} else {
this._resolve = resolve;
this._reject = reject;
if (options.preloadTimeoutMs !== void 0) {
this._preloadTimeout = setTimeout(() => {
this._onError(new ErrorEvent(`Preload exceeded timeout of ${options.preloadTimeoutMs}ms`));
});
}
source.load();
}
});
return this._load;
}
/**
* Handle video error events.
* @param event - The error event
*/
_onError(event) {
this.resource.removeEventListener("error", this._onError, true);
this.emit("error", event);
if (this._reject) {
this._reject(event);
this._reject = null;
this._resolve = null;
}
}
/**
* Checks if the underlying source is playing.
* @returns True if playing.
*/
_isSourcePlaying() {
const source = this.resource;
return !source.paused && !source.ended;
}
/**
* Checks if the underlying source is ready for playing.
* @returns True if ready.
*/
_isSourceReady() {
const source = this.resource;
return source.readyState > 2;
}
/** Runs the update loop when the video is ready to play. */
_onPlayStart() {
if (!this.isValid) {
this._mediaReady();
}
this._configureAutoUpdate();
}
/** Stops the update loop when a pause event is triggered. */
_onPlayStop() {
this._configureAutoUpdate();
}
/** Handles behavior when the video completes seeking to the current playback position. */
_onSeeked() {
if (this._autoUpdate && !this._isSourcePlaying()) {
this._msToNextUpdate = 0;
this.updateFrame();
this._msToNextUpdate = 0;
}
}
_onCanPlay() {
const source = this.resource;
source.removeEventListener("canplay", this._onCanPlay);
this._mediaReady();
}
_onCanPlayThrough() {
const source = this.resource;
source.removeEventListener("canplaythrough", this._onCanPlay);
if (this._preloadTimeout) {
clearTimeout(this._preloadTimeout);
this._preloadTimeout = void 0;
}
this._mediaReady();
}
/** Fired when the video is loaded and ready to play. */
_mediaReady() {
const source = this.resource;
if (this.isValid) {
this.isReady = true;
this.resize(source.videoWidth, source.videoHeight);
}
this._msToNextUpdate = 0;
this.updateFrame();
this._msToNextUpdate = 0;
if (this._resolve) {
this._resolve(this);
this._resolve = null;
this._reject = null;
}
if (this._isSourcePlaying()) {
this._onPlayStart();
} else if (this.autoPlay) {
void this.resource.play();
}
}
/** Cleans up resources and event listeners associated with this texture. */
destroy() {
this._configureAutoUpdate();
const source = this.resource;
if (source) {
source.removeEventListener("play", this._onPlayStart);
source.removeEventListener("pause", this._onPlayStop);
source.removeEventListener("seeked", this._onSeeked);
source.removeEventListener("canplay", this._onCanPlay);
source.removeEventListener("canplaythrough", this._onCanPlayThrough);
source.removeEventListener("error", this._onError, true);
source.pause();
source.src = "";
source.load();
}
super.destroy();
}
/** Should the base texture automatically update itself, set to true by default. */
get autoUpdate() {
return this._autoUpdate;
}
set autoUpdate(value) {
if (value !== this._autoUpdate) {
this._autoUpdate = value;
this._configureAutoUpdate();
}
}
/**
* How many times a second to update the texture from the video.
* Leave at 0 to update at every render.
* A lower fps can help performance, as updating the texture at 60fps on a 30ps video may not be efficient.
*/
get updateFPS() {
return this._updateFPS;
}
set updateFPS(value) {
if (value !== this._updateFPS) {
this._updateFPS = value;
this._configureAutoUpdate();
}
}
/**
* Configures the updating mechanism based on the current state and settings.
*
* This method decides between using the browser's native video frame callback or a custom ticker
* for updating the video frame. It ensures optimal performance and responsiveness
* based on the video's state, playback status, and the desired frames-per-second setting.
*
* - If `_autoUpdate` is enabled and the video source is playing:
* - It will prefer the native video frame callback if available and no specific FPS is set.
* - Otherwise, it will use a custom ticker for manual updates.
* - If `_autoUpdate` is disabled or the video isn't playing, any active update mechanisms are halted.
*/
_configureAutoUpdate() {
if (this._autoUpdate && this._isSourcePlaying()) {
if (!this._updateFPS && this.resource.requestVideoFrameCallback) {
if (this._isConnectedToTicker) {
Ticker.shared.remove(this.updateFrame, this);
this._isConnectedToTicker = false;
this._msToNextUpdate = 0;
}
if (this._videoFrameRequestCallbackHandle === null) {
this._videoFrameRequestCallbackHandle = this.resource.requestVideoFrameCallback(
this._videoFrameRequestCallback
);
}
} else {
if (this._videoFrameRequestCallbackHandle !== null) {
this.resource.cancelVideoFrameCallback(this._videoFrameRequestCallbackHandle);
this._videoFrameRequestCallbackHandle = null;
}
if (!this._isConnectedToTicker) {
Ticker.shared.add(this.updateFrame, this);
this._isConnectedToTicker = true;
this._msToNextUpdate = 0;
}
}
} else {
if (this._videoFrameRequestCallbackHandle !== null) {
this.resource.cancelVideoFrameCallback(this._videoFrameRequestCallbackHandle);
this._videoFrameRequestCallbackHandle = null;
}
if (this._isConnectedToTicker) {
Ticker.shared.remove(this.updateFrame, this);
this._isConnectedToTicker = false;
this._msToNextUpdate = 0;
}
}
}
static test(resource) {
return globalThis.HTMLVideoElement && resource instanceof HTMLVideoElement;
}
};
_VideoSource.extension = ExtensionType.TextureSource;
/** The default options for video sources. */
_VideoSource.defaultOptions = {
...TextureSource.defaultOptions,
/** If true, the video will start loading immediately. */
autoLoad: true,
/** If true, the video will start playing as soon as it is loaded. */
autoPlay: true,
/** The number of times a second to update the texture from the video. Leave at 0 to update at every render. */
updateFPS: 0,
/** If true, the video will be loaded with the `crossorigin` attribute. */
crossorigin: true,
/** If true, the video will loop when it ends. */
loop: false,
/** If true, the video will be muted. */
muted: true,
/** If true, the video will play inline. */
playsinline: true,
/** If true, the video will be preloaded. */
preload: false
};
/**
* Map of video MIME types that can't be directly derived from file extensions.
* @readonly
*/
_VideoSource.MIME_TYPES = {
ogv: "video/ogg",
mov: "video/quicktime",
m4v: "video/mp4"
};
let VideoSource = _VideoSource;
export { VideoSource };
//# sourceMappingURL=VideoSource.mjs.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1 @@
export declare function generateUID(): number;

View File

@@ -0,0 +1,10 @@
'use strict';
"use strict";
let uidCount = 0;
function generateUID() {
return uidCount++;
}
exports.generateUID = generateUID;
//# sourceMappingURL=generateUID.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"generateUID.js","sources":["../../../../../../src/rendering/renderers/shared/texture/utils/generateUID.ts"],"sourcesContent":["let uidCount = 0;\n\nexport function generateUID(): number\n{\n return uidCount++;\n}\n"],"names":[],"mappings":";;;AAAA,IAAI,QAAW,GAAA,CAAA,CAAA;AAER,SAAS,WAChB,GAAA;AACI,EAAO,OAAA,QAAA,EAAA,CAAA;AACX;;;;"}

View File

@@ -0,0 +1,8 @@
"use strict";
let uidCount = 0;
function generateUID() {
return uidCount++;
}
export { generateUID };
//# sourceMappingURL=generateUID.mjs.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"generateUID.mjs","sources":["../../../../../../src/rendering/renderers/shared/texture/utils/generateUID.ts"],"sourcesContent":["let uidCount = 0;\n\nexport function generateUID(): number\n{\n return uidCount++;\n}\n"],"names":[],"mappings":";AAAA,IAAI,QAAW,GAAA,CAAA,CAAA;AAER,SAAS,WAChB,GAAA;AACI,EAAO,OAAA,QAAA,EAAA,CAAA;AACX;;;;"}

View File

@@ -0,0 +1,6 @@
import { CanvasSource } from '../sources/CanvasSource';
import { Texture } from '../Texture';
import type { ICanvas } from '../../../../../environment/canvas/ICanvas';
import type { CanvasSourceOptions } from '../sources/CanvasSource';
export declare function getCanvasTexture(canvas: ICanvas, options?: CanvasSourceOptions): Texture<CanvasSource>;
export declare function hasCachedCanvasTexture(canvas: ICanvas): boolean;

View File

@@ -0,0 +1,33 @@
'use strict';
var CanvasSource = require('../sources/CanvasSource.js');
var Texture = require('../Texture.js');
"use strict";
const canvasCache = /* @__PURE__ */ new Map();
function getCanvasTexture(canvas, options) {
if (!canvasCache.has(canvas)) {
const texture = new Texture.Texture({
source: new CanvasSource.CanvasSource({
resource: canvas,
...options
})
});
const onDestroy = () => {
if (canvasCache.get(canvas) === texture) {
canvasCache.delete(canvas);
}
};
texture.once("destroy", onDestroy);
texture.source.once("destroy", onDestroy);
canvasCache.set(canvas, texture);
}
return canvasCache.get(canvas);
}
function hasCachedCanvasTexture(canvas) {
return canvasCache.has(canvas);
}
exports.getCanvasTexture = getCanvasTexture;
exports.hasCachedCanvasTexture = hasCachedCanvasTexture;
//# sourceMappingURL=getCanvasTexture.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"getCanvasTexture.js","sources":["../../../../../../src/rendering/renderers/shared/texture/utils/getCanvasTexture.ts"],"sourcesContent":["import { CanvasSource } from '../sources/CanvasSource';\nimport { Texture } from '../Texture';\n\nimport type { ICanvas } from '../../../../../environment/canvas/ICanvas';\nimport type { CanvasSourceOptions } from '../sources/CanvasSource';\n\nconst canvasCache: Map<ICanvas, Texture<CanvasSource>> = new Map();\n\nexport function getCanvasTexture(canvas: ICanvas, options?: CanvasSourceOptions): Texture<CanvasSource>\n{\n if (!canvasCache.has(canvas))\n {\n const texture = new Texture({\n source: new CanvasSource({\n resource: canvas,\n ...options,\n })\n });\n\n const onDestroy = () =>\n {\n if (canvasCache.get(canvas) === texture)\n {\n canvasCache.delete(canvas);\n }\n };\n\n texture.once('destroy', onDestroy);\n texture.source.once('destroy', onDestroy);\n\n canvasCache.set(canvas, texture);\n }\n\n return canvasCache.get(canvas);\n}\n\nexport function hasCachedCanvasTexture(canvas: ICanvas): boolean\n{\n return canvasCache.has(canvas);\n}\n"],"names":["Texture","CanvasSource"],"mappings":";;;;;;AAMA,MAAM,WAAA,uBAAuD,GAAI,EAAA,CAAA;AAEjD,SAAA,gBAAA,CAAiB,QAAiB,OAClD,EAAA;AACI,EAAA,IAAI,CAAC,WAAA,CAAY,GAAI,CAAA,MAAM,CAC3B,EAAA;AACI,IAAM,MAAA,OAAA,GAAU,IAAIA,eAAQ,CAAA;AAAA,MACxB,MAAA,EAAQ,IAAIC,yBAAa,CAAA;AAAA,QACrB,QAAU,EAAA,MAAA;AAAA,QACV,GAAG,OAAA;AAAA,OACN,CAAA;AAAA,KACJ,CAAA,CAAA;AAED,IAAA,MAAM,YAAY,MAClB;AACI,MAAA,IAAI,WAAY,CAAA,GAAA,CAAI,MAAM,CAAA,KAAM,OAChC,EAAA;AACI,QAAA,WAAA,CAAY,OAAO,MAAM,CAAA,CAAA;AAAA,OAC7B;AAAA,KACJ,CAAA;AAEA,IAAQ,OAAA,CAAA,IAAA,CAAK,WAAW,SAAS,CAAA,CAAA;AACjC,IAAQ,OAAA,CAAA,MAAA,CAAO,IAAK,CAAA,SAAA,EAAW,SAAS,CAAA,CAAA;AAExC,IAAY,WAAA,CAAA,GAAA,CAAI,QAAQ,OAAO,CAAA,CAAA;AAAA,GACnC;AAEA,EAAO,OAAA,WAAA,CAAY,IAAI,MAAM,CAAA,CAAA;AACjC,CAAA;AAEO,SAAS,uBAAuB,MACvC,EAAA;AACI,EAAO,OAAA,WAAA,CAAY,IAAI,MAAM,CAAA,CAAA;AACjC;;;;;"}

View File

@@ -0,0 +1,30 @@
import { CanvasSource } from '../sources/CanvasSource.mjs';
import { Texture } from '../Texture.mjs';
"use strict";
const canvasCache = /* @__PURE__ */ new Map();
function getCanvasTexture(canvas, options) {
if (!canvasCache.has(canvas)) {
const texture = new Texture({
source: new CanvasSource({
resource: canvas,
...options
})
});
const onDestroy = () => {
if (canvasCache.get(canvas) === texture) {
canvasCache.delete(canvas);
}
};
texture.once("destroy", onDestroy);
texture.source.once("destroy", onDestroy);
canvasCache.set(canvas, texture);
}
return canvasCache.get(canvas);
}
function hasCachedCanvasTexture(canvas) {
return canvasCache.has(canvas);
}
export { getCanvasTexture, hasCachedCanvasTexture };
//# sourceMappingURL=getCanvasTexture.mjs.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"getCanvasTexture.mjs","sources":["../../../../../../src/rendering/renderers/shared/texture/utils/getCanvasTexture.ts"],"sourcesContent":["import { CanvasSource } from '../sources/CanvasSource';\nimport { Texture } from '../Texture';\n\nimport type { ICanvas } from '../../../../../environment/canvas/ICanvas';\nimport type { CanvasSourceOptions } from '../sources/CanvasSource';\n\nconst canvasCache: Map<ICanvas, Texture<CanvasSource>> = new Map();\n\nexport function getCanvasTexture(canvas: ICanvas, options?: CanvasSourceOptions): Texture<CanvasSource>\n{\n if (!canvasCache.has(canvas))\n {\n const texture = new Texture({\n source: new CanvasSource({\n resource: canvas,\n ...options,\n })\n });\n\n const onDestroy = () =>\n {\n if (canvasCache.get(canvas) === texture)\n {\n canvasCache.delete(canvas);\n }\n };\n\n texture.once('destroy', onDestroy);\n texture.source.once('destroy', onDestroy);\n\n canvasCache.set(canvas, texture);\n }\n\n return canvasCache.get(canvas);\n}\n\nexport function hasCachedCanvasTexture(canvas: ICanvas): boolean\n{\n return canvasCache.has(canvas);\n}\n"],"names":[],"mappings":";;;;AAMA,MAAM,WAAA,uBAAuD,GAAI,EAAA,CAAA;AAEjD,SAAA,gBAAA,CAAiB,QAAiB,OAClD,EAAA;AACI,EAAA,IAAI,CAAC,WAAA,CAAY,GAAI,CAAA,MAAM,CAC3B,EAAA;AACI,IAAM,MAAA,OAAA,GAAU,IAAI,OAAQ,CAAA;AAAA,MACxB,MAAA,EAAQ,IAAI,YAAa,CAAA;AAAA,QACrB,QAAU,EAAA,MAAA;AAAA,QACV,GAAG,OAAA;AAAA,OACN,CAAA;AAAA,KACJ,CAAA,CAAA;AAED,IAAA,MAAM,YAAY,MAClB;AACI,MAAA,IAAI,WAAY,CAAA,GAAA,CAAI,MAAM,CAAA,KAAM,OAChC,EAAA;AACI,QAAA,WAAA,CAAY,OAAO,MAAM,CAAA,CAAA;AAAA,OAC7B;AAAA,KACJ,CAAA;AAEA,IAAQ,OAAA,CAAA,IAAA,CAAK,WAAW,SAAS,CAAA,CAAA;AACjC,IAAQ,OAAA,CAAA,MAAA,CAAO,IAAK,CAAA,SAAA,EAAW,SAAS,CAAA,CAAA;AAExC,IAAY,WAAA,CAAA,GAAA,CAAI,QAAQ,OAAO,CAAA,CAAA;AAAA,GACnC;AAEA,EAAO,OAAA,WAAA,CAAY,IAAI,MAAM,CAAA,CAAA;AACjC,CAAA;AAEO,SAAS,uBAAuB,MACvC,EAAA;AACI,EAAO,OAAA,WAAA,CAAY,IAAI,MAAM,CAAA,CAAA;AACjC;;;;"}

View File

@@ -0,0 +1,2 @@
import type { TEXTURE_FORMATS } from '../const';
export declare function getSupportedCompressedTextureFormats(): Promise<TEXTURE_FORMATS[]>;

View File

@@ -0,0 +1,31 @@
'use strict';
var isWebGLSupported = require('../../../../../utils/browser/isWebGLSupported.js');
var isWebGPUSupported = require('../../../../../utils/browser/isWebGPUSupported.js');
var getSupportedGlCompressedTextureFormats = require('../../../gl/texture/utils/getSupportedGlCompressedTextureFormats.js');
var getSupportedGPUCompressedTextureFormats = require('../../../gpu/texture/utils/getSupportedGPUCompressedTextureFormats.js');
"use strict";
let supportedCompressedTextureFormats;
async function getSupportedCompressedTextureFormats() {
if (supportedCompressedTextureFormats !== void 0)
return supportedCompressedTextureFormats;
supportedCompressedTextureFormats = await (async () => {
const _isWebGPUSupported = await isWebGPUSupported.isWebGPUSupported();
const _isWebGLSupported = isWebGLSupported.isWebGLSupported();
if (_isWebGPUSupported && _isWebGLSupported) {
const gpuTextureFormats = await getSupportedGPUCompressedTextureFormats.getSupportedGPUCompressedTextureFormats();
const glTextureFormats = getSupportedGlCompressedTextureFormats.getSupportedGlCompressedTextureFormats();
return gpuTextureFormats.filter((format) => glTextureFormats.includes(format));
} else if (_isWebGPUSupported) {
return await getSupportedGPUCompressedTextureFormats.getSupportedGPUCompressedTextureFormats();
} else if (_isWebGLSupported) {
return getSupportedGlCompressedTextureFormats.getSupportedGlCompressedTextureFormats();
}
return [];
})();
return supportedCompressedTextureFormats;
}
exports.getSupportedCompressedTextureFormats = getSupportedCompressedTextureFormats;
//# sourceMappingURL=getSupportedCompressedTextureFormats.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"getSupportedCompressedTextureFormats.js","sources":["../../../../../../src/rendering/renderers/shared/texture/utils/getSupportedCompressedTextureFormats.ts"],"sourcesContent":["import { isWebGLSupported } from '../../../../../utils/browser/isWebGLSupported';\nimport { isWebGPUSupported } from '../../../../../utils/browser/isWebGPUSupported';\nimport { getSupportedGlCompressedTextureFormats } from '../../../gl/texture/utils/getSupportedGlCompressedTextureFormats';\nimport { getSupportedGPUCompressedTextureFormats } from '../../../gpu/texture/utils/getSupportedGPUCompressedTextureFormats';\n\nimport type { TEXTURE_FORMATS } from '../const';\n\nlet supportedCompressedTextureFormats: TEXTURE_FORMATS[];\n\nexport async function getSupportedCompressedTextureFormats(): Promise<TEXTURE_FORMATS[]>\n{\n if (supportedCompressedTextureFormats !== undefined) return supportedCompressedTextureFormats;\n\n supportedCompressedTextureFormats = await (async (): Promise<TEXTURE_FORMATS[]> =>\n {\n // find only overlapping ones..\n const _isWebGPUSupported = await isWebGPUSupported();\n const _isWebGLSupported = isWebGLSupported();\n\n if (_isWebGPUSupported && _isWebGLSupported)\n {\n const gpuTextureFormats = await getSupportedGPUCompressedTextureFormats();\n const glTextureFormats = getSupportedGlCompressedTextureFormats();\n\n return gpuTextureFormats.filter((format) => glTextureFormats.includes(format));\n }\n else if (_isWebGPUSupported)\n {\n return await getSupportedGPUCompressedTextureFormats();\n }\n else if (_isWebGLSupported)\n {\n return getSupportedGlCompressedTextureFormats();\n }\n\n return [];\n })();\n\n return supportedCompressedTextureFormats;\n}\n"],"names":["isWebGPUSupported","isWebGLSupported","getSupportedGPUCompressedTextureFormats","getSupportedGlCompressedTextureFormats"],"mappings":";;;;;;;;AAOA,IAAI,iCAAA,CAAA;AAEJ,eAAsB,oCACtB,GAAA;AACI,EAAA,IAAI,iCAAsC,KAAA,KAAA,CAAA;AAAW,IAAO,OAAA,iCAAA,CAAA;AAE5D,EAAA,iCAAA,GAAoC,OAAO,YAC3C;AAEI,IAAM,MAAA,kBAAA,GAAqB,MAAMA,mCAAkB,EAAA,CAAA;AACnD,IAAA,MAAM,oBAAoBC,iCAAiB,EAAA,CAAA;AAE3C,IAAA,IAAI,sBAAsB,iBAC1B,EAAA;AACI,MAAM,MAAA,iBAAA,GAAoB,MAAMC,+EAAwC,EAAA,CAAA;AACxE,MAAA,MAAM,mBAAmBC,6EAAuC,EAAA,CAAA;AAEhE,MAAA,OAAO,kBAAkB,MAAO,CAAA,CAAC,WAAW,gBAAiB,CAAA,QAAA,CAAS,MAAM,CAAC,CAAA,CAAA;AAAA,eAExE,kBACT,EAAA;AACI,MAAA,OAAO,MAAMD,+EAAwC,EAAA,CAAA;AAAA,eAEhD,iBACT,EAAA;AACI,MAAA,OAAOC,6EAAuC,EAAA,CAAA;AAAA,KAClD;AAEA,IAAA,OAAO,EAAC,CAAA;AAAA,GACT,GAAA,CAAA;AAEH,EAAO,OAAA,iCAAA,CAAA;AACX;;;;"}

View File

@@ -0,0 +1,29 @@
import { isWebGLSupported } from '../../../../../utils/browser/isWebGLSupported.mjs';
import { isWebGPUSupported } from '../../../../../utils/browser/isWebGPUSupported.mjs';
import { getSupportedGlCompressedTextureFormats } from '../../../gl/texture/utils/getSupportedGlCompressedTextureFormats.mjs';
import { getSupportedGPUCompressedTextureFormats } from '../../../gpu/texture/utils/getSupportedGPUCompressedTextureFormats.mjs';
"use strict";
let supportedCompressedTextureFormats;
async function getSupportedCompressedTextureFormats() {
if (supportedCompressedTextureFormats !== void 0)
return supportedCompressedTextureFormats;
supportedCompressedTextureFormats = await (async () => {
const _isWebGPUSupported = await isWebGPUSupported();
const _isWebGLSupported = isWebGLSupported();
if (_isWebGPUSupported && _isWebGLSupported) {
const gpuTextureFormats = await getSupportedGPUCompressedTextureFormats();
const glTextureFormats = getSupportedGlCompressedTextureFormats();
return gpuTextureFormats.filter((format) => glTextureFormats.includes(format));
} else if (_isWebGPUSupported) {
return await getSupportedGPUCompressedTextureFormats();
} else if (_isWebGLSupported) {
return getSupportedGlCompressedTextureFormats();
}
return [];
})();
return supportedCompressedTextureFormats;
}
export { getSupportedCompressedTextureFormats };
//# sourceMappingURL=getSupportedCompressedTextureFormats.mjs.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"getSupportedCompressedTextureFormats.mjs","sources":["../../../../../../src/rendering/renderers/shared/texture/utils/getSupportedCompressedTextureFormats.ts"],"sourcesContent":["import { isWebGLSupported } from '../../../../../utils/browser/isWebGLSupported';\nimport { isWebGPUSupported } from '../../../../../utils/browser/isWebGPUSupported';\nimport { getSupportedGlCompressedTextureFormats } from '../../../gl/texture/utils/getSupportedGlCompressedTextureFormats';\nimport { getSupportedGPUCompressedTextureFormats } from '../../../gpu/texture/utils/getSupportedGPUCompressedTextureFormats';\n\nimport type { TEXTURE_FORMATS } from '../const';\n\nlet supportedCompressedTextureFormats: TEXTURE_FORMATS[];\n\nexport async function getSupportedCompressedTextureFormats(): Promise<TEXTURE_FORMATS[]>\n{\n if (supportedCompressedTextureFormats !== undefined) return supportedCompressedTextureFormats;\n\n supportedCompressedTextureFormats = await (async (): Promise<TEXTURE_FORMATS[]> =>\n {\n // find only overlapping ones..\n const _isWebGPUSupported = await isWebGPUSupported();\n const _isWebGLSupported = isWebGLSupported();\n\n if (_isWebGPUSupported && _isWebGLSupported)\n {\n const gpuTextureFormats = await getSupportedGPUCompressedTextureFormats();\n const glTextureFormats = getSupportedGlCompressedTextureFormats();\n\n return gpuTextureFormats.filter((format) => glTextureFormats.includes(format));\n }\n else if (_isWebGPUSupported)\n {\n return await getSupportedGPUCompressedTextureFormats();\n }\n else if (_isWebGLSupported)\n {\n return getSupportedGlCompressedTextureFormats();\n }\n\n return [];\n })();\n\n return supportedCompressedTextureFormats;\n}\n"],"names":[],"mappings":";;;;;;AAOA,IAAI,iCAAA,CAAA;AAEJ,eAAsB,oCACtB,GAAA;AACI,EAAA,IAAI,iCAAsC,KAAA,KAAA,CAAA;AAAW,IAAO,OAAA,iCAAA,CAAA;AAE5D,EAAA,iCAAA,GAAoC,OAAO,YAC3C;AAEI,IAAM,MAAA,kBAAA,GAAqB,MAAM,iBAAkB,EAAA,CAAA;AACnD,IAAA,MAAM,oBAAoB,gBAAiB,EAAA,CAAA;AAE3C,IAAA,IAAI,sBAAsB,iBAC1B,EAAA;AACI,MAAM,MAAA,iBAAA,GAAoB,MAAM,uCAAwC,EAAA,CAAA;AACxE,MAAA,MAAM,mBAAmB,sCAAuC,EAAA,CAAA;AAEhE,MAAA,OAAO,kBAAkB,MAAO,CAAA,CAAC,WAAW,gBAAiB,CAAA,QAAA,CAAS,MAAM,CAAC,CAAA,CAAA;AAAA,eAExE,kBACT,EAAA;AACI,MAAA,OAAO,MAAM,uCAAwC,EAAA,CAAA;AAAA,eAEhD,iBACT,EAAA;AACI,MAAA,OAAO,sCAAuC,EAAA,CAAA;AAAA,KAClD;AAEA,IAAA,OAAO,EAAC,CAAA;AAAA,GACT,GAAA,CAAA;AAEH,EAAO,OAAA,iCAAA,CAAA;AACX;;;;"}

Some files were not shown because too many files have changed in this diff Show More