@awayjs/stage
Version:
Stage for AwayJS
1,107 lines (1,104 loc) • 64.2 kB
JavaScript
import { __extends } from "tslib";
import { Rectangle, Point, ColorUtils, AssetEvent } from '@awayjs/core';
import { UnloadService } from './../managers/UnloadManager';
import { Image2D } from './Image2D';
import { BitmapImageChannel } from './BitmapImageChannel';
import { LehmerRng } from '../utils/LehmerRng';
import { Turbulence } from '../utils/Turbulence';
import { Settings } from './../Settings';
/**
* The BitmapImage2D export class lets you work with the data(pixels) of a Bitmap
* object. You can use the methods of the BitmapImage2D export class to create
* arbitrarily sized transparent or opaque bitmap images and manipulate them
* in various ways at runtime. You can also access the BitmapImage2D for a bitmap
* image that you load with the <code>flash.Assets</code> or
* <code>flash.display.Loader</code> classes.
*
* <p>This export class lets you separate bitmap rendering operations from the
* internal display updating routines of flash. By manipulating a
* BitmapImage2D object directly, you can create complex images without incurring
* the per-frame overhead of constantly redrawing the content from vector
* data.</p>
*
* <p>The methods of the BitmapImage2D export class support effects that are not
* available through the filters available to non-bitmap display objects.</p>
*
* <p>A BitmapImage2D object contains an array of pixel data. This data can
* represent either a fully opaque bitmap or a transparent bitmap that
* contains alpha channel data. Either type of BitmapImage2D object is stored as
* a buffer of 32-bit integers. Each 32-bit integer determines the properties
* of a single pixel in the bitmap.</p>
*
* <p>Each 32-bit integer is a combination of four 8-bit channel values(from
* 0 to 255) that describe the alpha transparency and the red, green, and blue
* (ARGB) values of the pixel.(For ARGB values, the most significant byte
* represents the alpha channel value, followed by red, green, and blue.)</p>
*
* <p>The four channels(alpha, red, green, and blue) are represented as
* numbers when you use them with the <code>BitmapImage2D.copyChannel()</code>
* method or the <code>DisplacementMapFilter.componentX</code> and
* <code>DisplacementMapFilter.componentY</code> properties, and these numbers
* are represented by the following constants in the BitmapImage2DChannel
* class:</p>
*
* <ul>
* <li><code>BitmapImage2DChannel.ALPHA</code></li>
* <li><code>BitmapImage2DChannel.RED</code></li>
* <li><code>BitmapImage2DChannel.GREEN</code></li>
* <li><code>BitmapImage2DChannel.BLUE</code></li>
* </ul>
*
* <p>You can attach BitmapImage2D objects to a Bitmap object by using the
* <code>bitmapData</code> property of the Bitmap object.</p>
*
* <p>You can use a BitmapImage2D object to fill a Graphics object by using the
* <code>Graphics.beginBitmapFill()</code> method.</p>
*
* <p>You can also use a BitmapImage2D object to perform batch tile rendering
* using the <code>flash.display.Tilesheet</code> class.</p>
*
* <p>In Flash Player 10, the maximum size for a BitmapImage2D object
* is 8,191 pixels in width or height, and the total number of pixels cannot
* exceed 16,777,215 pixels.(So, if a BitmapImage2D object is 8,191 pixels wide,
* it can only be 2,048 pixels high.) In Flash Player 9 and earlier, the limitation
* is 2,880 pixels in height and 2,880 in width.</p>
*/
var HAS_REF = ('WeakRef' in window);
var alerted = false;
function REF_ENABLED() {
if (alerted)
return HAS_REF;
alerted = true;
HAS_REF = HAS_REF && Settings.ENABLE_WEAK_REF;
if (HAS_REF) {
console.debug('[ImageBitmap2D Experemental] Use WeakRef for ImageBitmap2D');
}
return HAS_REF;
}
function fastARGB_to_ABGR(val, hasAlpha) {
if (hasAlpha === void 0) { hasAlpha = true; }
var a = hasAlpha ? (val & 0xff000000) : 0xff000000;
return (a
| ((val & 0xff) << 16)
| (val & 0xff00)
| ((val & 0xff0000) >> 16) & 0xff) >>> 0;
}
var BitmapImage2D = /** @class */ (function (_super) {
__extends(BitmapImage2D, _super);
/**
* Creates a BitmapImage2D object with a specified width and height. If you
* specify a value for the <code>fillColor</code> parameter, every pixel in
* the bitmap is set to that color.
*
* <p>By default, the bitmap is created as transparent, unless you pass
* the value <code>false</code> for the transparent parameter. After you
* create an opaque bitmap, you cannot change it to a transparent bitmap.
* Every pixel in an opaque bitmap uses only 24 bits of color channel
* information. If you define the bitmap as transparent, every pixel uses 32
* bits of color channel information, including an alpha transparency
* channel.</p>
*
* @param width The width of the bitmap image in pixels.
* @param height The height of the bitmap image in pixels.
* @param transparent Specifies whether the bitmap image supports per-pixel
* transparency. The default value is <code>true</code>
* (transparent). To create a fully transparent bitmap,
* set the value of the <code>transparent</code>
* parameter to <code>true</code> and the value of the
* <code>fillColor</code> parameter to 0x00000000(or to
* 0). Setting the <code>transparent</code> property to
* <code>false</code> can result in minor improvements
* in rendering performance.
* @param fillColor A 32-bit ARGB color value that you use to fill the
* bitmap image area. The default value is
* 0xFFFFFFFF(solid white).
*/
function BitmapImage2D(width, height, transparent, fillColor, powerOfTwo, stage) {
if (transparent === void 0) { transparent = true; }
if (fillColor === void 0) { fillColor = null; }
if (powerOfTwo === void 0) { powerOfTwo = true; }
if (stage === void 0) { stage = null; }
var _this = _super.call(this, width, height, powerOfTwo) || this;
_this._isSymbolSource = false;
_this._isWeakRef = false;
_this._unpackPMA = true;
_this._locked = false;
_this._floodStack = [];
_this._nestedBitmap = [];
_this._initalFillColor = null;
_this._lastUsedFill = null;
_this.needUpload = false;
/**
* @description Upload flag, marking a image that it was uploaded on GPU
* and can use GPU operations
* fillRect can be implemented on GPU or CPU
*/
_this.wasUpload = false;
_this.isUnloaded = false;
_this.lastUsedTime = 0;
if (stage) {
// init
BitmapImage2D.getManager(stage);
}
//this._data = new Uint8ClampedArray(4 * this._rect.width * this._rect.height);
_this._transparent = transparent;
_this._stage = stage;
_this._initalFillColor = fillColor;
_this._lastUsedFill = fillColor;
return _this;
}
BitmapImage2D.getManager = function (stage) {
if (!Settings.ENABLE_UNLOAD_BITMAP || !stage) {
return null;
}
if (this._unloadManager) {
return this._unloadManager;
}
var hasFence = stage.context.hasFence;
this._unloadManager = UnloadService.createManager({
name: 'BitmapImage2D' + (hasFence ? 'async' : ''),
priority: 0,
maxUnloadTasks: (hasFence
? Settings.MAX_BITMAP_UNLOAD_TASKS_ASYNC
: Settings.MAX_BITMAP_UNLOAD_TASKS),
exectionPeriod: 100, // every 100 ms GC will runs to unload bitmap
});
return this._unloadManager;
};
BitmapImage2D.prototype.syncData = function (async) {
var _this = this;
if (async === void 0) { async = false; }
if (async && this._asyncRead) {
return this._asyncRead;
}
if (!async && this._asyncRead) {
throw '[SceneImage2D] Synced read not allowed while async read is requested!';
}
this.applySymbol();
// update data from pixels from GPU
if (!this._imageDataDirty) {
return async ? Promise.resolve(false) : false;
}
var context = this._stage.context;
this._stage.setRenderTarget(this, true, 0, 0, true);
this._stage.context.disableStencil();
// when we call syncData, we already loose other data
// not require apply symbol etc, because it already should be applied
if (!this._data) {
this._data = new Uint8ClampedArray(this.width * this.height * 4);
}
// mark that this internal call, avoid reqursion loop
this._asyncRead = context.drawToBitmapImage2D(this, false, async);
this._stage.setRenderTarget(null);
if (!async) {
this._imageDataDirty = false;
// we store pixel buffer already as PMA.
// we should prevent unpack what already is PMA
this._unpackPMA = false;
return true;
}
return this._asyncRead.then(function (_status) {
_this._imageDataDirty = false;
_this._unpackPMA = false;
_this._asyncRead = null;
return true;
});
};
BitmapImage2D.prototype.getDataInternal = function (constructEmpty, skipSync) {
if (constructEmpty === void 0) { constructEmpty = true; }
if (skipSync === void 0) { skipSync = false; }
// if it empty, fill with initlal value
if (this._initalFillColor !== null) {
//use CPU fill to avoid a readback when syncing
this.fillRect(this.rect, this._initalFillColor, !skipSync);
}
if (!skipSync && this._imageDataDirty) {
// sync data already should fill _data
this.syncData(false);
return this._data;
}
this.applySymbol();
if (!this._data && (constructEmpty || this._alphaChannel)) {
this._data = new Uint8ClampedArray(this.width * this.height * 4);
}
if (this._alphaChannel) {
var alpha = this._alphaChannel;
var data = this._data;
for (var i = 0; i < alpha.length; i++) {
// fix JPEG compresiion bug
// it shown when color transform is disabled
if (alpha[i] <= 1) {
data[i * 4 + 0]
= data[i * 4 + 1]
= data[i * 4 + 2] = 0;
}
data[i * 4 + 3] = alpha[i];
}
//remove alpha data once applied
this._alphaChannel = null;
this._transparent = true;
this._unpackPMA = false;
}
return this._data;
};
Object.defineProperty(BitmapImage2D.prototype, "sourceBitmap", {
get: function () {
return this._sourceBitmap;
},
enumerable: false,
configurable: true
});
BitmapImage2D.prototype.invalidateGPU = function () {
if (this.needUpload)
return;
this.needUpload = true;
this.invalidate();
};
BitmapImage2D.prototype.invalidate = function () {
if (this._locked)
return;
_super.prototype.invalidate.call(this);
};
Object.defineProperty(BitmapImage2D.prototype, "canUnload", {
get: function () {
return !this._sourceBitmap
&& !this._nestedBitmap.length
&& !this._locked
&& !this._isSymbolSource;
},
enumerable: false,
configurable: true
});
BitmapImage2D.prototype.unmarkToUnload = function () {
var _a;
(_a = BitmapImage2D.getManager(this._stage)) === null || _a === void 0 ? void 0 : _a.removeTask(this);
};
BitmapImage2D.prototype.markToUnload = function () {
if (!BitmapImage2D.getManager(this._stage))
return;
if (this._isSymbolSource)
return;
this.lastUsedTime = BitmapImage2D._unloadManager.correctedTime;
// add before, because task can be already exist
// and if we a run GC before - it kill texture
BitmapImage2D._unloadManager.addTask(this);
// run execution when is marked that used
// const count = BitmapImage2D.unloadManager.execute();
// count && console.debug('[BitmapImage2D Experemental] Texture was unloaded from GPU by timer:', count);
};
BitmapImage2D.prototype.unload = function () {
// copy buffer back to _data
// this.syncData();
// dispose texture
this.lastUsedTime = -1;
this.dispatchEvent(new AssetEvent(BitmapImage2D.UNLOAD_EVENT, this));
this.invalidateGPU();
};
BitmapImage2D.prototype.addMipLevel = function (newLevel) {
if (!this._customMipLevels)
this._customMipLevels = [];
this._customMipLevels.push(newLevel);
};
Object.defineProperty(BitmapImage2D.prototype, "mipLevels", {
get: function () {
return this._customMipLevels;
},
enumerable: false,
configurable: true
});
Object.defineProperty(BitmapImage2D.prototype, "assetType", {
/**
*
* @returns {string}
*/
get: function () {
return BitmapImage2D.assetType;
},
enumerable: false,
configurable: true
});
Object.defineProperty(BitmapImage2D.prototype, "transparent", {
/**
* Defines whether the bitmap image supports per-pixel transparency. You can
* set this value only when you construct a BitmapImage2D object by passing in
* <code>true</code> for the <code>transparent</code> parameter of the
* constructor. Then, after you create a BitmapImage2D object, you can check
* whether it supports per-pixel transparency by determining if the value of
* the <code>transparent</code> property is <code>true</code>.
*/
get: function () {
return this._transparent;
},
set: function (value) {
this._transparent = value;
},
enumerable: false,
configurable: true
});
Object.defineProperty(BitmapImage2D.prototype, "unpackPMA", {
/**
* Store a mode, witch should be uploaded to GPU
* not all case PMA is should be enabled
*/
get: function () {
return this._unpackPMA && this._transparent;
},
enumerable: false,
configurable: true
});
BitmapImage2D.prototype.addLazySymbol = function (tag) {
this._lazySymbol = tag;
this._isSymbolSource = true;
// we should reset initial color, because a bitmap symbol has data of its own
this._initalFillColor = null;
this.invalidateGPU();
};
BitmapImage2D.prototype.applySymbol = function () {
if (!this._lazySymbol /*|| !this._lazySymbol.needParse*/) {
return false;
}
if (this._lazySymbol.needParse) {
this._lazySymbol.lazyParser();
}
this._data = this._lazySymbol.definition.data;
// disable UNPACK_PREMULTIPLE_ALPHA because already is PMA
this._unpackPMA = !this._lazySymbol.definition.isPMA;
this._lazySymbol = null;
return true;
};
/**
* @description transfer adapter to weak mode
* Reference will dropped, and adapter destroyed after collecting a adapter
*/
BitmapImage2D.prototype.useWeakRef = function () {
if (!REF_ENABLED() || this._isWeakRef) {
return;
}
this._isWeakRef = true;
if (!this._finalizer) {
this._finalizer = new FinalizationRegistry(this.onAdapterDropped.bind(this));
}
this.adapter = this._adapter;
};
BitmapImage2D.prototype.unuseWeakRef = function () {
if (!this._isWeakRef) {
return;
}
this._isWeakRef = false;
this._finalizer.unregister(this);
this._weakRefAdapter = null;
this.adapter = this._adapter;
};
Object.defineProperty(BitmapImage2D.prototype, "isWeakRef", {
get: function () {
return this._isWeakRef;
},
enumerable: false,
configurable: true
});
Object.defineProperty(BitmapImage2D.prototype, "adapter", {
get: function () {
return (this._weakRefAdapter ? this._weakRefAdapter.deref() : this._adapter) || this;
},
set: function (v) {
if (this._isWeakRef) {
this._finalizer.unregister(this);
if (v) {
this._weakRefAdapter = new WeakRef(v);
this._finalizer.register(v, this.id, this);
}
else {
this._weakRefAdapter = null;
}
// drop hard ref
this._adapter = null;
}
else {
this._adapter = v;
}
},
enumerable: false,
configurable: true
});
BitmapImage2D.prototype.onAdapterDropped = function (id) {
console.debug('[ImageBitmap2D Experemental] Disposing adaptee, GC runs for:', id);
this.dispose();
};
BitmapImage2D.prototype.addNestedReference = function (child) {
if (this._sourceBitmap) {
this._sourceBitmap.addNestedReference(child);
return;
}
this._nestedBitmap.push(child);
child._sourceBitmap = this;
//console.debug(`[BitmapImage] Add nested ${child.id} -> ${this.id}`);
};
BitmapImage2D.prototype.dropNestedReference = function (child) {
var index = this._nestedBitmap.indexOf(child);
return index > -1 && !!this._nestedBitmap.splice(index, 1);
};
/**
* @description Detach clone from source, and apply texture directly
*/
BitmapImage2D.prototype.dropAllReferences = function (fireDroping) {
if (fireDroping === void 0) { fireDroping = true; }
if (this._nestedBitmap.length) {
for (var _i = 0, _a = this._nestedBitmap; _i < _a.length; _i++) {
var nest = _a[_i];
nest.dropAllReferences(false);
}
this._nestedBitmap.length = 0;
}
if (!this._sourceBitmap) {
return;
}
var source = this._sourceBitmap;
this._sourceBitmap = null;
fireDroping && source.dropNestedReference(this);
this.deepClone(source);
//console.debug("[BitmapImage] drop nested references:", source.id);
};
BitmapImage2D.prototype.deepClone = function (from) {
this.setPixels(this._rect, from.data);
this.invalidateGPU();
};
BitmapImage2D.prototype.copyTo = function (target) {
if (Settings.ENABLE_TEXTURE_REF_CLONE) {
this.addNestedReference(target);
}
else {
target.deepClone(this);
}
return target;
};
/**
* Returns a new BitmapImage2D object that is a clone of the original instance
* with an exact copy of the contained bitmap.
*
* @return A new BitmapImage2D object that is identical to the original.
*/
BitmapImage2D.prototype.clone = function () {
var clone = new BitmapImage2D(this._rect.width, this._rect.height, this._transparent, null, this._powerOfTwo);
if (Settings.ENABLE_TEXTURE_REF_CLONE) {
this.addNestedReference(clone);
}
else {
clone.deepClone(this);
}
return clone;
};
/**
* Adjusts the color values in a specified area of a bitmap image by using a
* <code>ColorTransform</code> object. If the rectangle matches the
* boundaries of the bitmap image, this method transforms the color values of
* the entire image.
*
* @param rect A Rectangle object that defines the area of the
* image in which the ColorTransform object is applied.
* @param colorTransform A ColorTransform object that describes the color
* transformation values to apply.
*/
BitmapImage2D.prototype.colorTransform = function (rect, colorTransform) {
this.dropAllReferences();
var i, j, index;
var data = this.data;
for (i = 0; i < rect.width; ++i) {
for (j = 0; j < rect.height; ++j) {
index = (i + rect.x + (j + rect.y) * this._rect.width) * 4;
data[index] = data[index] * colorTransform.redMultiplier + colorTransform.redOffset;
data[index + 1] = data[index + 1] * colorTransform.greenMultiplier + colorTransform.greenOffset;
data[index + 2] = data[index + 2] * colorTransform.blueMultiplier + colorTransform.blueOffset;
data[index + 3] = data[index + 3] * colorTransform.alphaMultiplier + colorTransform.alphaOffset;
}
}
this.invalidateGPU();
};
/**
* Transfers data from one channel of another BitmapImage2D object or the
* current BitmapImage2D object into a channel of the current BitmapImage2D object.
* All of the data in the other channels in the destination BitmapImage2D object
* are preserved.
*
* <p>The source channel value and destination channel value can be one of
* following values: </p>
*
* <ul>
* <li><code>BitmapImage2DChannel.RED</code></li>
* <li><code>BitmapImage2DChannel.GREEN</code></li>
* <li><code>BitmapImage2DChannel.BLUE</code></li>
* <li><code>BitmapImage2DChannel.ALPHA</code></li>
* </ul>
*
* @param sourceBitmapImage2D The input bitmap image to use. The source image
* can be a different BitmapImage2D object or it can
* refer to the current BitmapImage2D object.
* @param sourceRect The source Rectangle object. To copy only channel
* data from a smaller area within the bitmap,
* specify a source rectangle that is smaller than
* the overall size of the BitmapImage2D object.
* @param destPoint The destination Point object that represents the
* upper-left corner of the rectangular area where
* the new channel data is placed. To copy only
* channel data from one area to a different area in
* the destination image, specify a point other than
* (0,0).
* @param sourceChannel The source channel. Use a value from the
* BitmapImage2DChannel class
* (<code>BitmapImage2DChannel.RED</code>,
* <code>BitmapImage2DChannel.BLUE</code>,
* <code>BitmapImage2DChannel.GREEN</code>,
* <code>BitmapImage2DChannel.ALPHA</code>).
* @param destChannel The destination channel. Use a value from the
* BitmapImage2DChannel class
* (<code>BitmapImage2DChannel.RED</code>,
* <code>BitmapImage2DChannel.BLUE</code>,
* <code>BitmapImage2DChannel.GREEN</code>,
* <code>BitmapImage2DChannel.ALPHA</code>).
* @throws TypeError The sourceBitmapImage2D, sourceRect or destPoint are null.
*/
/* eslint-disable-next-line */
BitmapImage2D.prototype.copyChannel = function (sourceBitmap, sourceRect, destPoint, sourceChannel, destChannel) {
this._lastUsedFill = null;
this.dropAllReferences();
this.unmarkToUnload();
if (destChannel != 8 || !this._imageDataDirty && !sourceBitmap._imageDataDirty) {
var sourceData = sourceBitmap.data;
var destData = this.data;
var sourceOffset = Math.round(Math.log(sourceChannel) / Math.log(2));
var destOffset = Math.round(Math.log(destChannel) / Math.log(2));
var sourceX = Math.round(sourceRect.x);
var sourceY = Math.round(sourceRect.y);
var destX = Math.round(destPoint.x);
var destY = Math.round(destPoint.y);
var value = void 0;
var i = void 0, j = void 0, sourceIndex = void 0, destIndex = void 0;
for (i = 0; i < sourceRect.width; ++i) {
for (j = 0; j < sourceRect.height; ++j) {
sourceIndex = (i + sourceX + (j + sourceY) * sourceBitmap.width) * 4;
destIndex = (i + destX + (j + destY) * this._rect.width) * 4;
value = (sourceOffset == 3) ? sourceData[sourceIndex + 3] : sourceData[sourceIndex + 3] ? sourceData[sourceIndex + sourceOffset] * 255 / sourceData[sourceIndex + 3] : 0;
if (destOffset == 3) {
destData[destIndex + 0] = destData[sourceIndex + 3] ? destData[destIndex + 0] * value / destData[sourceIndex + 3] : 0;
destData[destIndex + 1] = destData[sourceIndex + 3] ? destData[destIndex + 1] * value / destData[sourceIndex + 3] : 0;
destData[destIndex + 2] = destData[sourceIndex + 3] ? destData[destIndex + 2] * value / destData[sourceIndex + 3] : 0;
destData[destIndex + 3] = value;
}
else {
destData[destIndex + destOffset] = value;
}
}
}
this.invalidateGPU();
return;
}
if (this._initalFillColor !== null)
this.fillRect(this._rect, this._initalFillColor);
this._stage.filterManager.copyChannel(sourceBitmap, this, sourceRect, destPoint, sourceChannel, destChannel);
this._imageDataDirty = true;
};
/* eslint-disable-next-line */
BitmapImage2D.prototype.merge = function (source, sourceRect, destPoint, redMultiplier, greenMultiplier, blueMultiplier, alphaMultiplier) {
this.dropAllReferences();
var dest = this.getDataInternal(true);
var src = source.data;
redMultiplier = ~~redMultiplier;
greenMultiplier = ~~greenMultiplier;
blueMultiplier = ~~blueMultiplier;
alphaMultiplier = ~~alphaMultiplier;
var i, j, index;
for (i = 0; i < sourceRect.width; ++i) {
for (j = 0; j < sourceRect.height; ++j) {
index = (i + sourceRect.x + (j + sourceRect.y) * this.width) * 4;
/* eslint-disable */
dest[index] = ~~((src[index] * redMultiplier + dest[index] * (0x100 - redMultiplier)) / 0x100);
dest[index + 1] = ~~((src[index + 1] * greenMultiplier + dest[index + 1] * (0x100 - greenMultiplier)) / 0x100);
dest[index + 2] = ~~((src[index + 2] * blueMultiplier + dest[index + 2] * (0x100 - blueMultiplier)) / 0x100);
dest[index + 3] = ~~((src[index + 3] * alphaMultiplier + dest[index + 3] * (0x100 - alphaMultiplier)) / 0x100);
/* eslint-enable */
}
}
this.invalidateGPU();
};
/**
* Frees memory that is used to store the BitmapImage2D object.
*
* <p>When the <code>dispose()</code> method is called on an image, the width
* and height of the image are set to 0. All subsequent calls to methods or
* properties of this BitmapImage2D instance fail, and an exception is thrown.
* </p>
*
* <p><code>BitmapImage2D.dispose()</code> releases the memory occupied by the
* actual bitmap data, immediately(a bitmap can consume up to 64 MB of
* memory). After using <code>BitmapImage2D.dispose()</code>, the BitmapImage2D
* object is no longer usable and an exception may be thrown if
* you call functions on the BitmapImage2D object. However,
* <code>BitmapImage2D.dispose()</code> does not garbage collect the BitmapImage2D
* object(approximately 128 bytes); the memory occupied by the actual
* BitmapImage2D object is released at the time the BitmapImage2D object is
* collected by the garbage collector.</p>
*
*/
BitmapImage2D.prototype.dispose = function () {
var _a;
(_a = BitmapImage2D.getManager(this._stage)) === null || _a === void 0 ? void 0 : _a.removeTask(this);
if (this._isWeakRef) {
this._finalizer.unregister(this);
}
this.dropAllReferences();
this._data = null;
this._rect = null;
this._transparent = null;
this._locked = null;
this._isDisposed = true;
this.clear();
};
BitmapImage2D.prototype.getColorBoundsRect = function (mask, color, findColor) {
if (findColor === void 0) { findColor = true; }
var buffer = new Uint32Array(this.getDataInternal(true).buffer);
var size = this.rect;
color = fastARGB_to_ABGR(color, this._transparent);
mask = fastARGB_to_ABGR(mask, this._transparent);
var minX = size.width, minY = size.height, maxX = 0, maxY = 0;
var has = false;
// const start = performance.now();
for (var j = 0; j < size.height; j++) {
for (var i = 0; i < size.width; i++) {
var c = buffer[j * size.width + i];
c = (c & mask) >>> 0;
if ((c === color && findColor) || (c !== color && !findColor)) {
has = true;
minX = i < minX ? i : minX; // Math.min(minX, i);
maxX = i > maxX ? i : maxX; // Math.max(maxX, i);
minY = j < minY ? j : minY; //Math.min(minY, j);
maxY = j > maxY ? j : maxY; // Math.max(maxY, j);
}
}
}
//console.log("getColorBoundsRect not implemented yet in flash/BitmapData");
var d = has
? new Rectangle(minX, minY, maxX - minX + 1, maxY - minY + 1)
: new Rectangle(0, 0, 0, 0);
/*
const delta = performance.now() - start;
console.debug(
'ColoreRect (mask, color, rect, time):',
mask.toString(16),
color.toString(16),
d._rawData,
delta);
*/
return d;
};
BitmapImage2D.prototype.hitTest = function (firstPoint, firstAlphaThreshold, secondObject, secondBitmapDataPoint, secondAlphaThreshold) {
if (secondBitmapDataPoint === void 0) { secondBitmapDataPoint = null; }
if (secondAlphaThreshold === void 0) { secondAlphaThreshold = 1; }
if (secondObject instanceof Point) {
var color = this.getPixel32(secondObject.x - firstPoint.x, secondObject.y - firstPoint.y);
var alpha = (color >> 24 & 0xff);
return alpha >= firstAlphaThreshold;
}
else if (secondObject instanceof Rectangle) {
secondObject = secondObject.clone();
secondObject.x -= firstPoint.x;
secondObject.y -= firstPoint.y;
if (!this._rect.intersects(secondObject)) {
return false;
}
// slow, not require check a rect from left-right,
// more effective - scan from left and right to center and from to and bottom to center
// BUT for CPU this is good, because data can be cached easy
for (var j = secondObject.y; j < secondObject.bottom; j++) {
for (var i = secondObject.x; i < secondObject.right; i++) {
// slow, to many calls, we can validate outside
var color = this.getPixel32(i, j);
var alpha = (color >> 24 & 0xff);
if (alpha >= firstAlphaThreshold)
return true;
}
}
}
else if (secondObject !== null) {
console.warn('[BitmapImage2D] HitTest not implemented for:', secondObject.assetType);
}
return false;
};
// https://lodev.org/cgtutor/floodfill.html
// scanline method implementation
BitmapImage2D.prototype.floodFill = function (x, y, color) {
this.dropAllReferences();
var startX = x, startY = y;
x = x | 0;
y = y | 0;
//const start = performance.now();
// needs update data when it use GL rendering mode
var data = new Uint32Array(this.getDataInternal(true).buffer);
var width = this._rect.width;
var height = this._rect.height;
var stack = this._floodStack;
// avoid reloaction. it costly
stack.length = width * height * 2;
var oldc32 = data[(x + y * width)];
//const rect = [100000,100000,0,0];
var _a = ColorUtils.float32ColorToARGB(color), newA = _a[0], newR = _a[1], newG = _a[2], newB = _a[3];
newA = this._transparent ? newA : 0xff;
// premultiply
newR = newR * newA / 0xff | 0;
newG = newG * newA / 0xff | 0;
newB = newB * newA / 0xff | 0;
var newc32 = ((newA << 24) | (newB << 16) | (newG << 8) | (newR)) >>> 0;
if (newc32 === oldc32) {
// same, return to avoid infinity loop
return;
}
var x1 = 0;
var spanAbove, spanBelow;
var stackIndex = 0;
stack[stackIndex++] = x;
stack[stackIndex++] = y;
while (stackIndex > 0) {
if (stackIndex / 2 > data.length) {
throw "[BitmapImage2D] FloodFill bug, to many interation: ".concat(startX, ":").concat(startY);
}
y = stack[--stackIndex];
x1 = x = stack[--stackIndex];
while (x1 >= 0 && data[y * width + x1] === oldc32) {
x1--;
}
x1++;
spanAbove = spanBelow = false;
while (x1 < width && data[y * width + x1] === oldc32) {
data[y * width + x1] = newc32;
/*
rect[0] = rect[0] > x1 ? x1 : rect[0];
rect[1] = rect[1] > y ? y : rect[1];
rect[2] = rect[2] < x1 ? x1 : rect[2];
rect[3] = rect[3] < y ? y : rect[3];
*/
if (!spanAbove && y > 0 && data[(y - 1) * width + x1] === oldc32) {
stack[stackIndex++] = x1;
stack[stackIndex++] = y - 1;
spanAbove = true;
}
else if (spanAbove && y > 0 && data[(y - 1) * width + x1] !== oldc32) {
spanAbove = false;
}
if (!spanBelow && y < height - 1 && data[(y + 1) * width + x1] === oldc32) {
stack[stackIndex++] = x1;
stack[stackIndex++] = y + 1;
spanBelow = true;
}
else if (spanBelow && y < height - 1 && data[(y + 1) * width + x1] !== oldc32) {
spanBelow = false;
}
x1++;
}
}
/*
rect[2] -= rect[0];
rect[3] -= rect[1];
if(rect[2] * rect[3]) {
rect[2] += 1;
rect[3] += 1;
}
const delta = performance.now() - start;
console.debug(
"FloodFill (sourceColor, targetColor, source rect, result, time):",
oldc32.toString(16), newc32.toString(16), this._rect._rawData, rect, delta,)
*/
this.invalidateGPU();
};
/**
* Ruffle port of noise
* @see https://github.com/ruffle-rs/ruffle/blob/d43b033caa98ed201f37558c25f9ce5f2da189d0/core/src/avm1/object/bitmap_data.rs#L326
*/
BitmapImage2D.prototype.noise = function (randomSeed, low, high, channelOptions, grayScale) {
if (low === void 0) { low = 0; }
if (high === void 0) { high = 255; }
if (channelOptions === void 0) { channelOptions = 7; }
if (grayScale === void 0) { grayScale = false; }
var rng = new LehmerRng(randomSeed);
var w = this.width;
var h = this.height;
var data = this.getDataInternal(true, true);
for (var y = 0; y < h; y++) {
for (var x = 0; x < w; x++) {
var index = (x + y * w) * 4;
if (grayScale) {
var gray = rng.genRange(low, high);
data[index] = gray | 0;
data[index + 1] = gray | 0;
data[index + 2] = gray | 0;
}
else {
var r = (channelOptions & BitmapImageChannel.RED) ? rng.genRange(low, high) : 0;
var g = (channelOptions & BitmapImageChannel.GREEN) ? rng.genRange(low, high) : 0;
var b = (channelOptions & BitmapImageChannel.BLUE) ? rng.genRange(low, high) : 0;
data[index] = r | 0;
data[index + 1] = g | 0;
data[index + 2] = b | 0;
}
data[index + 3] = (channelOptions & BitmapImageChannel.ALPHA) ? rng.genRange(low, high) : 255;
}
}
this.invalidateGPU();
};
/**
* Ruffle port of perlinNoise
* There are not guarantees that it valid =)
* RESULT IS NOT EQUAL A FLASH RESULT, SEED IS WRONG!!
* @see https://github.com/ruffle-rs/ruffle/blob/d43b033caa98ed201f37558c25f9ce5f2da189d0/core/src/avm1/object/bitmap_data.rs#L713
*/
BitmapImage2D.prototype.perlinNoise = function (baseX, baseY, numOctaves, randomSeed, stitch, fractalNoise, channelOptions, grayScale, offsets) {
if (channelOptions === void 0) { channelOptions = 7; }
if (grayScale === void 0) { grayScale = false; }
if (offsets === void 0) { offsets = null; }
var w = this.width;
var h = this.height;
var data = this.getDataInternal(true, true);
var turb = Turbulence.fromSeed(randomSeed);
// translate [x, y, x, y] to [[x, y], [x, y] ...]
var octave_offsets = null;
if (offsets) {
octave_offsets = [];
if (typeof offsets[0] === 'number') {
for (var i = 0; i < offsets.length; i += 2) {
octave_offsets[i / 2] = [offsets[i + 0], offsets[i + 1]];
}
}
else if (offsets[0] instanceof Point) {
for (var i = 0; i < offsets.length; i += 2) {
octave_offsets[i / 2] = [offsets[i].x, offsets[i].y];
}
}
}
for (var y = 0; y < h; y++) {
for (var x = 0; x < w; x++) {
var noise = [0, 0, 0, 0];
var index = (x + y * w) * 4;
if (grayScale) {
noise[0] = turb.turbulence(0, [x, y], [1. / baseX, 1 / baseY], numOctaves, fractalNoise, stitch, [0, 0], [w, h], octave_offsets);
noise[1] = noise[2] = noise[0];
noise[3] = 1;
if ((channelOptions & 8) !== 0) {
noise[3] = turb.turbulence(1, [x, y], [1. / baseX, 1 / baseY], numOctaves, fractalNoise, stitch, [0, 0], [w, h], octave_offsets);
}
// end grayscale
}
else {
for (var channel = 0; channel < 4; channel++) {
noise[channel] = (channel === 3) ? 1 : -1;
if ((channelOptions & (1 << channel)) === 0) {
continue;
}
noise[channel] = turb.turbulence(channel, [x, y], [1. / baseX, 1 / baseY], numOctaves, fractalNoise, stitch, [0, 0], [w, h], octave_offsets);
}
}
for (var i = 0; i < 4; i++) {
var mapped = 0;
// This is precisely how Adobe Flash converts the -1..1 or 0..1 floats to u8.
// Please don't touch, it was difficult to figure out the exact method. :)
if (fractalNoise) {
// Yes, the + 0.5 for correct (nearest) rounding is done before the division by 2.0,
// making it technically less correct (I think), but this is how it is!
mapped = ((noise[i] * 0xff + 0xff) + 0.5) / 2.0;
}
else {
mapped = noise[i] * 0xff + 0.5;
}
data[index + i] = mapped | 0;
if (!this._transparent) {
data[index + 3] = 0xff;
}
}
}
}
this.invalidateGPU();
};
BitmapImage2D.prototype.drawBitmap = function (source, offsetX, offsetY, width, height, matrix) {
if (matrix === void 0) { matrix = null; }
this.dropAllReferences();
BitmapImageUtils.drawBitmap(source, offsetX, offsetY, width, height, this.data, 0, 0, this._rect.width, this._rect.height, matrix);
this.invalidateGPU();
};
/**
* Fills a rectangular area of pixels with a specified ARGB color.
*
* @param rect The rectangular area to fill.
* @param color The ARGB color value that fills the area. ARGB colors are
* often specified in hexadecimal format; for example,
* 0xFF336699.
* @throws TypeError The rect is null.
*/
BitmapImage2D.prototype.fillRect = function (rect, color, useCPU) {
if (useCPU === void 0) { useCPU = false; }
this.dropAllReferences();
//ensure we reset initial color to stop recursive texture writes
this._initalFillColor = null;
if (useCPU) {
if (!this._data) {
try {
this._data = new Uint8ClampedArray(this.width * this.height * 4);
}
catch (e) {
console.error(this.width, this.height);
}
}
var x = ~~rect.x, y = ~~rect.y, width = ~~rect.width, height = ~~rect.height, data = new Uint32Array(this._data.buffer);
var rgba = 0;
if (this._transparent) {
var _a = ColorUtils.float32ColorToARGB(color), a = _a[0], r = _a[1], g = _a[2], b = _a[3];
// PMA
// we should FLIP bytes because a use UINT32
rgba = ColorUtils.ARGBtoFloat32(a, b * a / 0xff | 0, g * a / 0xff | 0, r * a / 0xff | 0) >>> 0;
/**
* TW2 has bug with transition over timeline when used a PMA
* I think that caused by invalid blend mode
*/
this._unpackPMA = false;
}
else {
rgba = fastARGB_to_ABGR(color & 0xffffff, false);
}
//fast path for complete fill
if (x == 0 && y == 0 && width == this._rect.width && height == this._rect.height) {
data.fill(rgba);
}
else {
var j = void 0;
var index = void 0;
for (j = 0; j < height; ++j) {
index = x + (j + y) * this._rect.width;
data.fill(rgba, index, index + width);
}
}
this.invalidateGPU();
}
else {
var argb = ColorUtils.float32ColorToARGB(color);
var alpha = this._transparent ? argb[0] / 255 : 1;
var isCrop = rect !== this._rect && !this._rect.equals(rect);
this._stage.setRenderTarget(this, true, 0, 0, true);
this._stage.setScissor(rect);
// we shure that color is fully filled when there are not any crops
this._lastUsedFill = isCrop ? null : color;
this._stage.clear((argb[1] / 0xff) * alpha, (argb[2] / 0xff) * alpha, (argb[3] / 0xff) * alpha, alpha);
this._stage.setScissor(null);
this._imageDataDirty = true;
}
};
/**
* Returns an integer that represents an RGB pixel value from a BitmapImage2D
* object at a specific point(<i>x</i>, <i>y</i>). The
* <code>getPixel()</code> method returns an unmultiplied pixel value. No
* alpha information is returned.
*
* <p>All pixels in a BitmapImage2D object are stored as premultiplied color
* values. A premultiplied image pixel has the red, green, and blue color
* channel values already multiplied by the alpha data. For example, if the
* alpha value is 0, the values for the RGB channels are also 0, independent
* of their unmultiplied values. This loss of data can cause some problems
* when you perform operations. All BitmapImage2D methods take and return
* unmultiplied values. The internal pixel representation is converted from
* premultiplied to unmultiplied before it is returned as a value. During a
* set operation, the pixel value is premultiplied before the raw image pixel
* is set.</p>
*
* @param x The <i>x</i> position of the pixel.
* @param y The <i>y</i> position of the pixel.
* @return A number that represents an RGB pixel value. If the(<i>x</i>,
* <i>y</i>) coordinates are outside the bounds of the image, the
* method returns 0.
*/
BitmapImage2D.prototype.getPixel = function (x, y) {
if (!this._rect.contains(x, y))
return 0x0;
var index = (~~x + ~~y * this._rect.width) * 4, data = this._data;
var r = data[index + 0], g = data[index + 1], b = data[index + 2], a = data[index + 3];
//returns black if fully transparent
if (!a)
return 0x0;
return (r * 0xFF / a << 16) | (g * 0xFF / a << 8) | b * 0xFF / a;
};
/**
* Returns an ARGB color value that contains alpha channel data and RGB data.
* This method is similar to the <code>getPixel()</code> method, which
* returns an RGB color without alpha channel data.
*
* <p>All pixels in a BitmapImage2D object are stored as premultiplied color
* values. A premultiplied image pixel has the red, green, and blue color
* channel values already multiplied by the alpha data. For example, if the
* alpha value is 0, the values for the RGB channels are also 0, independent
* of their unmultiplied values. This loss of data can cause some problems
* when you perform operations. All BitmapImage2D methods take and return
* unmultiplied values. The internal pixel representation is converted from
* premultiplied to unmultiplied before it is returned as a value. During a
* set operation, the pixel value is premultiplied before the raw image pixel
* is set.</p>
*
* @param x The <i>x</i> position of the pixel.
* @param y The <i>y</i> position of the pixel.
* @return A number representing an ARGB pixel value. If the(<i>x</i>,
* <i>y</i>) coordinates are outside the bounds of the image, 0 is
* returned.
*/
BitmapImage2D.prototype.getPixel32 = function (x, y) {
if (!this._rect.contains(x, y))
return 0x0;
var index = (~~x + ~~y * this._rect.width) * 4;
var data = this.getDataInternal(true);
var r = data[index++], g = data[index++], b = data[index++], a = data[index];
if (!a)
return 0x0;
return ((a << 24) | (r * 0xFF / a << 16) | (g * 0xFF / a << 8) | b * 0xFF / a) >>> 0;
};
BitmapImage2D.prototype.getPixels = function (rect) {
if (rect.equals(this._rect)) {
return this.getDataInternal(true, false);
}
var data = this.getDataInternal(true, false);
var target = new Uint8ClampedArray(rect.width * rect.height * 4);
var x = rect.x | 0;
var y = rect.y | 0;
var width = rect.width | 0;
var height = rect.height | 0;
var index;
for (var j = 0; j < height; ++j) {
index = x + (j + y) * this._rect.width;
target.set(data.subarray(index * 4, (index + width) * 4), j * width * 4);
}
return target;
};
BitmapImage2D.prototype.getPixelData = function (x, y, imagePixel) {
var index = (x + y * this._rect.width) * 4;
var data = this.getDataInternal(true);
imagePixel[0] = data[index++];
imagePixel[1] = data[index++];
imagePixel[2] = data[index++];
imagePixel[3] = data[index];
};
BitmapImage2D.prototype.setPixelData = function (x, y, imagePixel) {
this.dropAllReferences();
var index = (x + y * this._rect.width) * 4;
var data = this.getDataInternal(true);
data[index + 0] = imagePixel[0];
data[index + 1] = imagePixel[1];
data[index + 2] = imagePixel[2];
data[index + 3] = this._transparent ? imagePixel[3] : 0xFF;
this.invalidateGPU();
};
/**
* Locks an image so that any objects that reference the BitmapImage2D object,
* such as Bitmap objects, are not updated when this BitmapImage2D object
* changes. To improve performance, use this method along with the
* <code>unlock()</code> method before and after numerous calls to the
* <code>setPixel()</code> or <code>setPixel32()</code> method.
*
*/
BitmapImage2D.prototype.lock = function () {
if (this._locked)
return;
this._locked = true;
};
/**
* Converts an Array into a rectangular region of pixel data. For each pixel,
* an Array element is read and written i