//------------------------------------------------------------------------------
// Constructor scope
//------------------------------------------------------------------------------
/**
* Creates a new Tilemap object.
*
* @constructor
*
* @class
* @classdesc
*
* The rune.tilemap.Tilemap class, represents an orthogonal grid (Tilemap) of
* textured rectangles (Tiles). A Tilemap contains two layers (buffers) of
* tiles; back and front, where each layer is represented by a TilemapLayer
* object. Rune's Scene objects automatically instantiate their own Tilemap.
* Tile sizes and map width/height are in pixels; widthInTiles and heightInTiles
* are cell counts. Layer methods document whether they take pixel positions,
* local cell coordinates or linear tile indices.
*
* @see rune.scene.Scene
* @see rune.tilemap.TilemapLayer
*/
rune.tilemap.Tilemap = function() {
//--------------------------------------------------------------------------
// Private properties
//--------------------------------------------------------------------------
/**
* Reference to the current map's source JSON data.
*
* @type {Object}
* @private
*/
this.m_data = null;
/**
* The back buffer.
*
* @type {rune.tilemap.TilemapLayer}
* @private
*/
this.m_bufferA = null;
/**
* The front buffer.
*
* @type {rune.tilemap.TilemapLayer}
* @private
*/
this.m_bufferB = null;
/**
* The height of the tile map, given in number of tiles.
*
* @type {number}
* @private
*/
this.m_heightInTiles = 0;
/**
* The name of the current map.
*
* @type {string}
* @private
*/
this.m_name = "";
/**
* The name of the texture that the map uses.
*
* @type {string}
* @private
*/
this.m_texture = "";
/**
* Map-owned tile definitions indexed by tile value. Grouped values share
* one definition within this map, but never with other map instances.
*
* @type {Object}
* @private
*/
this.m_tiles = {};
/**
* An Array object used for various tasks. The primary purpose is to
* stabilize memory consumption.
*
* @type {Array}
* @private
*/
this.m_tmpArray = [];
/**
* A Rectangle object used for various tasks in order to reduce
* and stabilize memory usage.
*
* @type {rune.geom.Rectangle}
* @private
*/
this.m_tmpRect = new rune.geom.Rectangle();
/**
* The height of a Tile, given in pixels.
*
* @type {number}
* @private
*/
this.m_tileHeight = 0;
/**
* The width of a Tile, given in pixels.
*
* @type {number}
* @private
*/
this.m_tileWidth = 0;
/**
* The width of the tile map, given in number of tiles.
*
* @type {number}
* @private
*/
this.m_widthInTiles = 0;
//--------------------------------------------------------------------------
// Constructor call
//--------------------------------------------------------------------------
/**
* Invokes secondary class constructor.
*/
this.m_construct();
};
//------------------------------------------------------------------------------
// Public static constants (ENGINE)
//------------------------------------------------------------------------------
/**
* Constant to identify the map back buffer. This is used internally by Rune
* and is not intended for public use.
*
* @const
* @default 0
* @ignore
*/
rune.tilemap.Tilemap.BACK_BUFFER = 0;
/**
* Constant to identify the map front buffer. This is used internally by Rune
* and is not intended for public use.
*
* @const
* @default 1
* @ignore
*/
rune.tilemap.Tilemap.FRONT_BUFFER = 1;
//------------------------------------------------------------------------------
// PUBLIC STATIC METHODS (ENGINE)
//------------------------------------------------------------------------------
/**
* Clamps a zero-based frame index to the complete cells of a regular atlas.
* Partial cells at the texture edges are ignored. Returns zero if there are
* no complete frames. The texture may be an image, canvas or Rune Texture.
*
* @param {Object} texture Texture with pixel width and height, or null.
* @param {number} index Zero-based integer frame index.
* @param {number} frameWidth Frame width in pixels.
* @param {number} frameHeight Frame height in pixels.
*
* @return {number} The clamped index, or zero for an empty atlas.
* @ignore
*/
rune.tilemap.Tilemap.clampFrameIndex = function(texture, index, frameWidth, frameHeight) {
var columns = texture != null && frameWidth > 0 ? Math.floor(texture['width'] / frameWidth) : 0;
var rows = texture != null && frameHeight > 0 ? Math.floor(texture['height'] / frameHeight) : 0;
if (!isFinite(columns) || !isFinite(rows) || columns <= 0 || rows <= 0) {
return 0;
}
return rune.util.Math.clamp(parseInt(index, 10) || 0, 0, columns * rows - 1);
};
/**
* Gets a frame rectangle from a regular, tightly packed atlas in row-major order.
* Uses a zero-based index clamped to complete frames. Partial edge cells are
* ignored. Returns an empty rectangle if no complete frame is available.
*
* @param {Object} texture Image, canvas or Rune Texture with pixel dimensions.
* @param {number} index Zero-based integer frame index.
* @param {number} frameWidth Frame width in pixels.
* @param {number} frameHeight Frame height in pixels.
* @param {rune.geom.Rectangle} [output] Rectangle to overwrite instead of allocating.
*
* @return {rune.geom.Rectangle} The frame rectangle, or the supplied output.
* @ignore
*/
rune.tilemap.Tilemap.getFrameRect = function(texture, index, frameWidth, frameHeight, output) {
output = output || new rune.geom.Rectangle();
output['x'] = 0;
output['y'] = 0;
output['width'] = 0;
output['height'] = 0;
if (texture == null || frameWidth <= 0 || frameHeight <= 0 ||
!isFinite(frameWidth) || !isFinite(frameHeight) ||
!isFinite(texture['width']) || !isFinite(texture['height']) ||
texture['width'] < frameWidth || texture['height'] < frameHeight) {
return output;
}
var columns = Math.floor(texture['width'] / frameWidth);
var frame = rune.tilemap.Tilemap.clampFrameIndex(texture, index, frameWidth, frameHeight);
output['x'] = (frame % columns) * frameWidth;
output['y'] = Math.floor(frame / columns) * frameHeight;
output['width'] = frameWidth;
output['height'] = frameHeight;
return output;
};
/**
* Validates and copies tile definitions into a lookup shared by Tilemap and
* TileGraphic. Accepts legacy value entries and grouped values entries.
* Each definition is copied once, including nested custom properties.
*
* @param {Object} tiles Source tile definitions, or null for an empty lookup.
* @param {string} name Resource name used in error messages.
*
* @returns {Object} Tile properties indexed by value.
* @throws {Error} If definitions are invalid, duplicated or not JSON-compatible.
* @ignore
*/
rune.tilemap.Tilemap.parseTileProperties = function(tiles, name) {
var properties = {};
if (tiles == null) {
return properties;
}
if (typeof tiles !== "object") {
throw new TypeError('Tilemap: Resource "' + name + '" requires a tile definition array or object.');
}
for (var key in tiles) {
if (!Object.prototype.hasOwnProperty.call(tiles, key)) {
continue;
}
var definition = tiles[key];
var message = 'Tilemap: Invalid tile definition "' + key + '" in resource "' + name + '". ';
if (definition == null || typeof definition !== "object" || Array.isArray(definition)) {
throw new TypeError(message + 'Expected an object.');
}
var hasValue = Object.prototype.hasOwnProperty.call(definition, 'value');
var hasValues = Object.prototype.hasOwnProperty.call(definition, 'values');
if (hasValue === hasValues) {
throw new Error(message + 'Use either value or values.');
}
var values = hasValues ? definition['values'] : [definition['value']];
if (!Array.isArray(values) || values.length === 0) {
throw new TypeError(message + 'Expected a non-empty values array.');
}
var copy = JSON.parse(JSON.stringify(definition));
for (var i = 0; i < values.length; i++) {
var value = values[i];
if (!hasValues && typeof value === "string" && value.trim().length > 0) {
value = Number(value);
}
if (typeof value !== "number" || !isFinite(value) || value < 0 ||
Math.floor(value) !== value || value > 9007199254740991) {
throw new RangeError(message + 'Tile values must be non-negative safe integers.');
}
if (Object.prototype.hasOwnProperty.call(properties, value)) {
throw new Error(message + 'Duplicate tile value ' + value + '.');
}
properties[value] = copy;
}
}
return properties;
};
//------------------------------------------------------------------------------
// Public getter and setter methods
//------------------------------------------------------------------------------
/**
* Reference to the Tilemap's rear buffer, i.e. the bottom layer in the layer
* hierarchy. Note that DisplayObjects placed on the stage are rendered on top
* of this buffer.
*
* @member {rune.tilemap.TilemapLayer} back
* @memberof rune.tilemap.Tilemap
* @instance
* @readonly
*/
Object.defineProperty(rune.tilemap.Tilemap.prototype, "back", {
/**
* @this rune.tilemap.Tilemap
* @ignore
*/
get : function() {
return this.m_bufferA;
}
});
/**
* Reference to the Tilemap's front buffer, i.e. the top layer in the layer
* hierarchy. Note that this layer is rendered on top of both the
* DisplayObjects placed on the stage, as well as the Tiles included in the
* back buffer.
*
* @member {rune.tilemap.TilemapLayer} front
* @memberof rune.tilemap.Tilemap
* @instance
* @readonly
*/
Object.defineProperty(rune.tilemap.Tilemap.prototype, "front", {
/**
* @this rune.tilemap.Tilemap
* @ignore
*/
get : function() {
return this.m_bufferB;
}
});
/**
* The current height of the map, specified in pixels.
*
* @member {number} height
* @memberof rune.tilemap.Tilemap
* @instance
* @readonly
*/
Object.defineProperty(rune.tilemap.Tilemap.prototype, "height", {
/**
* @this rune.tilemap.Tilemap
* @ignore
*/
get : function() {
return this.m_heightInTiles * this.m_tileHeight;
}
});
/**
* The height of the tile map, given in number of tiles.
*
* @member {number} heightInTiles
* @memberof rune.tilemap.Tilemap
* @instance
* @readonly
*/
Object.defineProperty(rune.tilemap.Tilemap.prototype, "heightInTiles", {
/**
* @this rune.tilemap.Tilemap
* @ignore
*/
get : function() {
return this.m_heightInTiles;
}
});
/**
* The name of the current map. The name is retrieved from the map data
* (JSON) when the map is loaded. If no name is declared in the map data,
* the name of the map data file is used as the name.
*
* @member {string} name
* @memberof rune.tilemap.Tilemap
* @instance
* @readonly
*/
Object.defineProperty(rune.tilemap.Tilemap.prototype, "name", {
/**
* @this rune.tilemap.Tilemap
* @ignore
*/
get : function() {
return this.m_name;
}
});
/**
* The total number of Tiles included in the current map.
*
* @member {number} numTiles
* @memberof rune.tilemap.Tilemap
* @instance
* @readonly
*/
Object.defineProperty(rune.tilemap.Tilemap.prototype, "numTiles", {
/**
* @this rune.tilemap.Tilemap
* @ignore
*/
get : function() {
return (this.m_widthInTiles * this.m_heightInTiles) || 0;
}
});
/**
* Reference to the texture the map uses for its Tiles.
*
* @member {HTMLImage} texture
* @memberof rune.tilemap.Tilemap
* @instance
* @readonly
*/
Object.defineProperty(rune.tilemap.Tilemap.prototype, "texture", {
/**
* @this rune.tilemap.Tilemap
* @ignore
*/
get : function() {
var resource = this['application']['resources'].get(this.m_texture);
return resource ? resource['data'] : null;
}
});
/**
* The height of a Tile, given in pixels.
*
* @member {number} tileHeight
* @memberof rune.tilemap.Tilemap
* @instance
* @readonly
*/
Object.defineProperty(rune.tilemap.Tilemap.prototype, "tileHeight", {
/**
* @this rune.tilemap.Tilemap
* @ignore
*/
get : function() {
return this.m_tileHeight;
}
});
/**
* The width of a Tile, given in pixels.
*
* @member {number} tileWidth
* @memberof rune.tilemap.Tilemap
* @instance
* @readonly
*/
Object.defineProperty(rune.tilemap.Tilemap.prototype, "tileWidth", {
/**
* @this rune.tilemap.Tilemap
* @ignore
*/
get : function() {
return this.m_tileWidth;
}
});
/**
* The current width of the map, specified in pixels.
*
* @member {number} width
* @memberof rune.tilemap.Tilemap
* @instance
* @readonly
*/
Object.defineProperty(rune.tilemap.Tilemap.prototype, "width", {
/**
* @this rune.tilemap.Tilemap
* @ignore
*/
get : function() {
return this.m_widthInTiles * this.m_tileWidth;
}
});
/**
* The width of the tile map, given in number of tiles.
*
* @member {number} widthInTiles
* @memberof rune.tilemap.Tilemap
* @instance
* @readonly
*/
Object.defineProperty(rune.tilemap.Tilemap.prototype, "widthInTiles", {
/**
* @this rune.tilemap.Tilemap
* @ignore
*/
get : function() {
return this.m_widthInTiles;
}
});
//------------------------------------------------------------------------------
// Protected getter and setter methods
//------------------------------------------------------------------------------
/**
* Reference to Rune's base class.
*
* @member {rune.system.Application} application
* @memberof rune.tilemap.Tilemap
* @instance
* @readonly
* @protected
* @ignore
*/
Object.defineProperty(rune.tilemap.Tilemap.prototype, "application", {
/**
* @this rune.tilemap.Tilemap
* @ignore
*/
get : function() {
return rune.system.Application['instance'];
}
});
//------------------------------------------------------------------------------
// Public prototype methods (API)
//------------------------------------------------------------------------------
/**
* Resets the map.
*
* @returns {undefined}
*/
rune.tilemap.Tilemap.prototype.clear = function() {
this.m_data = null;
this.m_name = "";
this.m_texture = "";
this.m_heightInTiles = 0;
this.m_widthInTiles = 0;
this.m_tileHeight = 0;
this.m_tileWidth = 0;
this.m_tiles = {};
if (this.m_bufferA) {
this.m_bufferA.clear();
}
if (this.m_bufferB) {
this.m_bufferB.clear();
}
};
/**
* Creates and returns a new Block object based on a tile value. The method
* can be used to generate tiles represented by Sprite objects.
*
* @param {number} v Tile value.
*
* @returns {rune.tilemap.Block}
*/
rune.tilemap.Tilemap.prototype.getBlock = function(v) {
return new rune.tilemap.Block(
this,
v
);
};
/**
* Reads an own, top-level property from the loaded map's source JSON data.
* Nested properties are accessed through the returned object, not through
* path syntax. Objects and arrays are returned as independent deep copies.
* Changes to the running tilemap are not reflected in the source data.
*
* The default value is returned unchanged only if the property is missing,
* including before loading a map and after clear(). Values such as false,
* zero, an empty string and null are preserved. Without a default value,
* a missing property returns undefined.
*
* @param {string} name Property name.
* @param {*} [defaultValue] Value to return if the property is missing.
*
* @returns {*} Property value, a deep copy, or the supplied default value.
*/
rune.tilemap.Tilemap.prototype.getProperty = function(name, defaultValue) {
if (this.m_data != null && Object.prototype.hasOwnProperty.call(this.m_data, name)) {
var value = this.m_data[name];
if (value != null && typeof value === "object") {
return JSON.parse(JSON.stringify(value));
}
return value;
}
return defaultValue;
};
/**
* Returns a rectangle object that describes a value's location in the
* texture atlas. The method is mainly intended for internal use,
* but can be useful if you want to copy a "piece" of the texture atlas.
* The same map-owned Rectangle is reused and overwritten on every call,
* including calls made internally during rendering. Do not modify or retain
* it as a snapshot. Use Rectangle.clone() for an independent copy, or
* Rectangle.copy() to copy its values into a caller-owned rectangle.
*
* @example
* var saved = rune.geom.Rectangle.clone(map.getTileTextureRectOf(3));
*
* @param {number} v Tile value.
*
* @returns {rune.geom.Rectangle} Map-owned reusable rectangle.
* @see rune.geom.Rectangle.clone
* @see rune.geom.Rectangle.copy
*/
rune.tilemap.Tilemap.prototype.getTileTextureRectOf = function(v) {
if (v > 0) {
v -= 1;
}
return rune.tilemap.Tilemap.getFrameRect(
this['texture'],
v,
this['tileWidth'],
this['tileHeight'],
this.m_tmpRect
);
};
/**
* Returns the map-owned properties for a tile value, or null if undefined.
* Values in the same values group return the same object, so property edits
* affect the whole group. Definitions and nested properties are independent
* of the source resource and other map instances. Editing value or values
* does not change the lookup established when the map was loaded.
*
* @param {number|string} v Tile value.
*
* @returns {?Object} The shared group definition within this map, or null.
*/
rune.tilemap.Tilemap.prototype.getTilePropertiesOf = function(v) {
if (typeof v === "string" && v.trim().length > 0) {
v = Number(v);
}
return Object.prototype.hasOwnProperty.call(this.m_tiles, v) ? this.m_tiles[v] : null;
};
/**
* Loads a map from resource data. Each layer owns a copy of its tile values,
* so edits do not affect the resource or other map instances. Loading the
* same resource again restores its original tile values. If loading fails,
* the current layers, live tile edits and map properties are preserved.
* Width, height, tileWidth and tileHeight must be positive safe integers.
* The cell count must fit a JavaScript array, and pixel dimensions must remain
* safe integers.
* Tile definitions accept either value or a non-empty values array. Each tile
* value must be a unique non-negative safe integer. Legacy value entries also
* accept numeric strings. Definitions are copied
* per map, while grouped values share one definition within the map.
*
* @param {string} name The name of the resource that represents the map data.
*
* @throws {Error} In case of missing or corrupt map data.
* @throws {RangeError} If dimensions are invalid or exceed supported ranges.
*
* @returns {undefined}
*/
rune.tilemap.Tilemap.prototype.load = function(name) {
var resource = this['application']['resources'].get(name);
if (!resource) {
throw new Error('Tilemap: Map resource "' + name + '" was not found.');
}
if (!resource['data']) {
throw new Error('Tilemap: Map resource "' + name + '" has no data.');
}
var map = resource['data'];
var dimensions = ['width', 'height', 'tileWidth', 'tileHeight'];
for (var i = 0; i < dimensions.length; i++) {
var dimension = dimensions[i];
var value = map[dimension];
if (typeof value !== "number" || !isFinite(value) || value <= 0 ||
Math.floor(value) !== value || value > 9007199254740991) {
throw new RangeError('Tilemap: Map resource "' + name + '" requires a positive safe integer for ' + dimension + '.');
}
}
if (map['width'] * map['height'] > 4294967295 ||
map['width'] * map['tileWidth'] > 9007199254740991 ||
map['height'] * map['tileHeight'] > 9007199254740991) {
throw new RangeError('Tilemap: Map resource "' + name + '" exceeds supported cell or pixel dimensions.');
}
var tiles = rune.tilemap.Tilemap.parseTileProperties(map['tiles'], name);
var previous = {
data: this.m_data,
name: this.m_name,
texture: this.m_texture,
height: this.m_heightInTiles,
width: this.m_widthInTiles,
tileHeight: this.m_tileHeight,
tileWidth: this.m_tileWidth,
tiles: this.m_tiles
};
var back = null;
var front = null;
try {
// LAYER CONSTRUCTION READS DIMENSIONS FROM THIS MAP. KEEP THE OLD
// LAYERS ALIVE WHILE PREPARING REPLACEMENTS WITH THE NEW DIMENSIONS.
this.m_data = map;
this.m_name = map['name'] || name;
this.m_texture = map['texture'] || "";
this.m_heightInTiles = map['height'];
this.m_widthInTiles = map['width'];
this.m_tileHeight = map['tileHeight'];
this.m_tileWidth = map['tileWidth'];
this.m_tiles = tiles;
back = new rune.tilemap.TilemapLayer(this, map['back']);
front = new rune.tilemap.TilemapLayer(this, map['front']);
} catch (error) {
this.m_data = previous.data;
this.m_name = previous.name;
this.m_texture = previous.texture;
this.m_heightInTiles = previous.height;
this.m_widthInTiles = previous.width;
this.m_tileHeight = previous.tileHeight;
this.m_tileWidth = previous.tileWidth;
this.m_tiles = previous.tiles;
if (back) back.dispose();
if (front) front.dispose();
throw error;
}
this.m_disposeBuffers();
this.m_bufferA = back;
this.m_bufferB = front;
};
//------------------------------------------------------------------------------
// Public prototype methods (ENGINE)
//------------------------------------------------------------------------------
/**
* Preparing the Tilemap for removal.
*
* @returns {undefined}
* @ignore
*/
rune.tilemap.Tilemap.prototype.dispose = function() {
this.m_disposeBuffers();
this.clear();
this.m_tmpArray = null;
this.m_tmpRect = null;
};
/**
* Returns back-layer tile indices within a pixel rectangle. Front-layer
* contents do not filter this result: transparent or hidden front tiles must
* leave the underlying back tiles visible. Primarily intended for internal use.
*
* @param {number} x The x-coordinate of the rectangle.
* @param {number} y The y-coordinate of the rectangle.
* @param {number} w The width of the rectangle, given in pixels.
* @param {number} h The height of the rectangle, given in pixels.
*
* @returns {Array.<number>}
* @ignore
*/
rune.tilemap.Tilemap.prototype.getBackBufferIn = function(x, y, w, h) {
if (!this.m_bufferA) return this.m_tmpArray;
return this.m_bufferA.getTileIndexesIn(x, y, w, h);
};
/**
* Provides an alternative to getBackBufferIn.
*
* @param {rune.geom.Rectangle} r Clipping area.
*
* @returns {Array.<number>}
* @ignore
*/
rune.tilemap.Tilemap.prototype.getBackBufferInRect = function(r) {
return this.getBackBufferIn(
r['x'],
r['y'],
r['width'],
r['height']
);
};
/**
* Returns a chunk of the front buffer, based on specified coordinates (in the
* form of a rectangle). Note that this method is primarily intended for
* internal use.
*
* @param {number} x The x-coordinate of the rectangle.
* @param {number} y The y-coordinate of the rectangle.
* @param {number} w The width of the rectangle, given in pixels.
* @param {number} h The height of the rectangle, given in pixels.
*
* @returns {Array.<number>}
* @ignore
*/
rune.tilemap.Tilemap.prototype.getFrontBufferIn = function(x, y, w, h) {
if (!this.m_bufferB) return this.m_tmpArray;
return this.m_bufferB.getTileIndexesIn(x, y, w, h);
};
/**
* Provides an alternative to getBackBufferIn.
*
* @param {rune.geom.Rectangle} r Clipping area.
*
* @returns {Array.<number>}
* @ignore
*/
rune.tilemap.Tilemap.prototype.getFrontBufferInRect = function(r) {
return this.getFrontBufferIn(
r['x'],
r['y'],
r['width'],
r['height']
);
};
//------------------------------------------------------------------------------
// Protected prototype methods
//------------------------------------------------------------------------------
/**
* The class constructor.
*
* @returns {undefined}
* @protected
* @ignore
*/
rune.tilemap.Tilemap.prototype.m_construct = function() {
//@note: Nothing ATM.
};
/**
* Removes the tilemap's layer buffers.
*
* @returns {undefined}
* @private
*/
rune.tilemap.Tilemap.prototype.m_disposeBuffers = function() {
if (this.m_bufferA) {
this.m_bufferA.dispose();
this.m_bufferA = null;
}
if (this.m_bufferB) {
this.m_bufferB.dispose();
this.m_bufferB = null;
}
};